Skip to content

Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.

feat(tests): port malleus, the load tester, from jitsi-meet-torture (#17846)

Jonathan Lennoxa19f89487f90
diff --git a/package.json b/package.json
index b50c05387e..943b1ef995 100644
--- a/package.json
+++ b/package.json
@@ -212,6 +212,7 @@
"lint-fix": "eslint --ext .js,.ts,.tsx --max-warnings 0 --fix .",
"postinstall": "patch-package --error-on-fail && jetify && npm run android-clean-cmake-cache && npm run android-autolinking",
"start": "make dev",
+ "build:load-test": "BUILD_LOAD_TEST=true webpack --config-name load-test",
"tsc:web": "tsc --noEmit --project tsconfig.web.json",
"tsc:native": "tsc --noEmit --project tsconfig.native.json",
"tsc:ci": "npm run tsc:web && npm run tsc:native",
diff --git a/react/features/load-test/LoadTestClient.ts b/react/features/load-test/LoadTestClient.ts
new file mode 100644
index 0000000000..bffde9b10c
--- /dev/null
+++ b/react/features/load-test/LoadTestClient.ts
@@ -0,0 +1,676 @@
+// @ts-expect-error
+import { getLogger } from '@jitsi/logger';
+// @ts-expect-error
+import jwtDecode from 'jwt-decode';
+
+import { IConfig } from '../base/config/configType';
+
+import {
+ DEFAULT_MAX_FULL_RESOLUTION_PARTICIPANTS,
+ DEFAULT_NUMBER_OF_VISIBLE_TILES,
+ VIDEO_QUALITY_LEVELS,
+ largeVideoHeight,
+ qualityForHeight,
+ tileViewTileHeight,
+ verticalFilmstripVisibleCount
+} from './layout';
+
+const logger = getLogger('load-test-client');
+
+/**
+ * The parameters shared by all the clients of a page.
+ */
+export interface ILoadTestParams {
+ /** Whether to attach the incoming media to media elements (only the first client ever does). */
+ autoPlayVideo: boolean;
+
+ /** The JWT to connect with, if any. */
+ jwt?: string;
+
+ /** Whether to send audio (do GUM for audio and add the track). */
+ localAudio: boolean;
+
+ /** Whether to send video. */
+ localVideo: boolean;
+
+ /** Whether to receive audio. */
+ remoteAudio: boolean;
+
+ /** Whether to receive video. */
+ remoteVideo: boolean;
+
+ /** The name of the room to join. */
+ roomName: string;
+
+ /** Whether to emulate stage view (the dominant speaker in high resolution) rather than tile view. */
+ stageView: boolean;
+
+ /** The height of the window the emulated client is assumed to have, which decides the video sizes it asks for. */
+ windowHeight: number;
+
+ /** The width of the window the emulated client is assumed to have. */
+ windowWidth: number;
+}
+
+interface IReceiverConstraints {
+ constraints: Record<string, { maxHeight: number; }>;
+ defaultConstraints: { maxHeight: number; };
+ lastN: number;
+ onStageSources: string[];
+}
+
+interface IRemoteVideoSource {
+ participantId: string;
+ sourceName: string;
+}
+
+function appendURLParam(url: string, name: string, value: string): string {
+ const newUrl = new URL(url);
+
+ newUrl.searchParams.append(name, value);
+
+ return newUrl.toString();
+}
+
+/**
+ * A lib-jitsi-meet only conference participant, used to generate load.
+ */
+export class LoadTestClient {
+ readonly id: number;
+ readonly config: IConfig;
+ readonly params: ILoadTestParams;
+
+ connection: any = null;
+ room: any = null;
+ numParticipants = 1;
+ localTracks: any[] = [];
+ remoteTracks: Record<string, any[]> = {};
+ visitor = false;
+
+ private dataChannelOpen = false;
+ private leaving = false;
+ private onStageParticipant: string | null = null;
+ private localAudio: boolean;
+ private receiverConstraints?: IReceiverConstraints;
+
+ /** The remote video sources, in the order they showed up: the order the filmstrip would list them in. */
+ private remoteVideoSources: IRemoteVideoSource[] = [];
+
+ private readonly onConnectionSuccessBound = this.onConnectionSuccess.bind(this);
+ private readonly onConnectionFailedBound = this.onConnectionFailed.bind(this);
+ private readonly onConnectionRedirectedBound = this.onConnectionRedirected.bind(this);
+ private readonly disconnectBound = this.disconnect.bind(this);
+
+ /**
+ * Creates a client; call connect() to start it.
+ *
+ * @param {number} id - The index of the client within the page.
+ * @param {IConfig} config - The client's own copy of the config, which it modifies.
+ * @param {ILoadTestParams} params - The page parameters.
+ */
+ constructor(id: number, config: IConfig, params: ILoadTestParams) {
+ this.id = id;
+ this.config = config;
+ this.params = params;
+ this.localAudio = params.localAudio;
+
+ this.updateConfig();
+ }
+
+ /**
+ * Points the XMPP connection URLs and the HTTP conference request URL at the room, as jitsi-meet does
+ * (react/features/base/connection/actions.any.ts): deployments that route by room name rely on it.
+ *
+ * @returns {void}
+ */
+ private updateConfig(): void {
+ const room = this.params.roomName.toLowerCase();
+ const conf = this.config as any;
+
+ conf.serviceUrl = conf.bosh = appendURLParam(conf.websocket || conf.bosh, 'room', room);
+ if (conf.websocketKeepAliveUrl) {
+ conf.websocketKeepAliveUrl = appendURLParam(conf.websocketKeepAliveUrl, 'room', room);
+ }
+ if (conf.conferenceRequestUrl) {
+ conf.conferenceRequestUrl = appendURLParam(conf.conferenceRequestUrl, 'room', room);
+ }
+ }
+
+ /**
+ * Whether the emulated client is in stage view: when asked to, or with fewer than 3 participants, when
+ * jitsi-meet does not use tile view either.
+ *
+ * @returns {boolean}
+ */
+ private isStageView(): boolean {
+ return this.params.stageView || this.numParticipants < 3;
+ }
+
+ /**
+ * Emulation of jitsi-meet's receiver constraints (react/features/video-quality/subscriber.ts) for a client
+ * with a window of the configured size, in the common case: no pinning, no screen sharing, default filmstrip.
+ *
+ * Only the sources that would be visible get a non-zero constraint. In tile view those are the first page of
+ * tiles, at the quality the tile height allows (capped at 360 beyond maxFullResolutionParticipants). In stage
+ * view the on-stage source gets the large video quality and the first filmstrip page gets the thumbnail quality.
+ * The lastN value is what the config says, -1 by default, as in jitsi-meet.
+ *
+ * @param {boolean} force - Whether to send the constraints even if they did not change.
+ * @returns {void}
+ */
+ private updateReceiverConstraints(force = false): void {
+ if (!this.dataChannelOpen || !this.room || this.leaving) {
+ return;
+ }
+
+ const { windowHeight, windowWidth } = this.params;
+ const conf = this.config as any;
+ const constraints: IReceiverConstraints = {
+ constraints: {},
+ defaultConstraints: { maxHeight: VIDEO_QUALITY_LEVELS.NONE },
+ lastN: conf.startLastN ?? conf.channelLastN ?? -1,
+ onStageSources: []
+ };
+ const maxFullResolutionParticipants
+ = conf.maxFullResolutionParticipants ?? DEFAULT_MAX_FULL_RESOLUTION_PARTICIPANTS;
+
+ if (this.isStageView()) {
+ const onStageSource = this.onStageParticipant
+ ? this.remoteVideoSources.find(s => s.participantId === this.onStageParticipant)?.sourceName
+ : undefined;
+ const thumbnailQuality = VIDEO_QUALITY_LEVELS.LOW;
+
+ this.remoteVideoSources.slice(0, verticalFilmstripVisibleCount(windowHeight)).forEach(s => {
+ constraints.constraints[s.sourceName] = { maxHeight: thumbnailQuality };
+ });
+
+ if (onStageSource) {
+ constraints.constraints[onStageSource] = { maxHeight: qualityForHeight(largeVideoHeight(windowHeight)) };
+ constraints.onStageSources = [ onStageSource ];
+ }
+ } else {
+ const visible = this.remoteVideoSources.slice(
+ 0, conf.tileView?.numberOfVisibleTiles ?? DEFAULT_NUMBER_OF_VISIBLE_TILES);
+ let quality = qualityForHeight(tileViewTileHeight(this.numParticipants, windowWidth, windowHeight));
+
+ if (maxFullResolutionParticipants !== -1 && visible.length > maxFullResolutionParticipants
+ && quality > VIDEO_QUALITY_LEVELS.STANDARD) {
+ quality = VIDEO_QUALITY_LEVELS.STANDARD;
+ }
+
+ visible.forEach(s => {
+ constraints.constraints[s.sourceName] = { maxHeight: quality };
+ });
+ }
+
+ if (force || JSON.stringify(constraints) !== JSON.stringify(this.receiverConstraints)) {
+ this.receiverConstraints = constraints;
+ logger.log(`Participant ${this.id}: receiver constraints ${JSON.stringify(constraints)}`);
+ this.room.setReceiverConstraints(constraints);
+ }
+ }
+
+ /**
+ * Records a remote video source, in filmstrip order.
+ *
+ * @param {Object} track - The remote video track.
+ * @returns {void}
+ */
+ private addRemoteVideoSource(track: any): void {
+ const sourceName = track.getSourceName();
+
+ if (sourceName && !this.remoteVideoSources.some(s => s.sourceName === sourceName)) {
+ this.remoteVideoSources.push({ participantId: track.getParticipantId(), sourceName });
+ }
+ }
+
+ /**
+ * Picks who is on stage when nobody is or when the on-stage participant left: like jitsi-meet's
+ * _electLastVisibleRemoteParticipant, the most recent remote participant with video.
+ *
+ * @returns {boolean} Whether the on stage participant changed.
+ */
+ private electOnStageParticipant(): boolean {
+ if (this.onStageParticipant && this.room.getParticipantById(this.onStageParticipant)) {
+ return false;
+ }
+
+ const last = this.remoteVideoSources[this.remoteVideoSources.length - 1];
+ const newOnStageParticipant = last?.participantId ?? null;
+
+ if (newOnStageParticipant !== this.onStageParticipant) {
+ this.onStageParticipant = newOnStageParticipant;
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Whether a participant ID is a valid ID for stage view.
+ *
+ * @param {string} id - The participant ID.
+ * @returns {boolean}
+ */
+ private isValidStageViewParticipant(id: string): boolean {
+ return id !== this.room.myUserId() && Boolean(this.room.getParticipantById(id));
+ }
+
+ /**
+ * Simple emulation of jitsi-meet's stage view participant selection behavior. Doesn't take into account
+ * pinning or screen sharing, and the initial behavior is slightly different.
+ *
+ * @param {string} selected - The new dominant speaker.
+ * @param {Array<string>} previous - The previous dominant speakers, most recent first.
+ * @returns {boolean} Whether the on stage participant changed.
+ */
+ private selectStageViewParticipant(selected: string, previous: string[]): boolean {
+ let newOnStageParticipant: string | undefined;
+
+ if (this.isValidStageViewParticipant(selected)) {
+ newOnStageParticipant = selected;
+ } else {
+ newOnStageParticipant = previous.find(id => this.isValidStageViewParticipant(id));
+ }
+ if (newOnStageParticipant && newOnStageParticipant !== this.onStageParticipant) {
+ this.onStageParticipant = newOnStageParticipant;
+
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Mutes or unmutes the local audio, creating the track on first unmute if it does not exist yet.
+ *
+ * @param {boolean} mute - Whether to mute.
+ * @returns {void}
+ */
+ muteAudio(mute: boolean): void {
+ this.localAudio = !mute;
+
+ let localAudioTrack = this.room.getLocalAudioTrack();
+
+ if (mute) {
+ localAudioTrack?.mute();
+
+ return;
+ }
+
+ if (this.visitor) {
+ logger.warn(`Participant ${this.id}: In visitor mode, not unmuting audio.`);
+
+ return;
+ }
+ if (localAudioTrack) {
+ localAudioTrack.unmute();
+
+ return;
+ }
+
+ // See if we created it but haven't added it.
+ localAudioTrack = this.localTracks.find(track => track.getType() === 'audio');
+ if (localAudioTrack) {
+ localAudioTrack.unmute();
+ this.room.replaceTrack(null, localAudioTrack);
+ } else {
+ JitsiMeetJS.createLocalTracks({ devices: [ 'audio' ] })
+ .then(([ audioTrack ]: any[]) => this.room.addTrack(audioTrack))
+ .catch((e: unknown) => logger.error(e));
+ }
+ }
+
+ /**
+ * Called when the number of participants changes.
+ *
+ * @returns {void}
+ */
+ private setNumberOfParticipants(): void {
+ if (this.id === 0) {
+ const el = document.getElementById('participants');
+
+ if (el) {
+ el.textContent = String(this.numParticipants);
+ }
+ }
+ this.updateReceiverConstraints();
+ }
+
+ private onDataChannelOpened(): void {
+ this.dataChannelOpen = true;
+ this.updateReceiverConstraints();
+ }
+
+ private onDominantSpeakerChanged(selected: string, previous: string[]): void {
+ if (this.selectStageViewParticipant(selected, previous) && this.isStageView()) {
+ this.updateReceiverConstraints();
+ }
+ }
+
+ private onTrackRemoved(track: any): void {
+ if (track.isLocal() || track.getType() !== 'video') {
+ return;
+ }
+
+ const sourceName = track.getSourceName();
+
+ this.remoteVideoSources = this.remoteVideoSources.filter(s => s.sourceName !== sourceName);
+ this.electOnStageParticipant();
+ this.updateReceiverConstraints();
+ }
+
+ /**
+ * Attaches a media element for a track to the page. Only the first client renders anything.
+ *
+ * @param {Object} track - The JitsiTrack.
+ * @param {string} id - The element ID.
+ * @param {boolean} autoplay - Whether the element autoplays.
+ * @param {boolean} muted - Whether the element is muted.
+ * @returns {void}
+ */
+ private attachTrack(track: any, id: string, autoplay: boolean, muted = false): void {
+ const element = document.createElement(track.getType() === 'video' ? 'video' : 'audio');
+
+ element.id = id;
+ element.autoplay = autoplay;
+ element.muted = muted;
+ document.body.appendChild(element);
+ track.attach(element);
+ }
+
+ private onLocalTracks(tracks: any[] = []): void {
+ this.localTracks = tracks;
+ for (let i = 0; i < this.localTracks.length; i++) {
+ const track = this.localTracks[i];
+
+ if (track.getType() === 'video') {
+ if (this.id === 0) {
+ this.attachTrack(track, `localVideo${i}`, this.params.autoPlayVideo);
+ }
+ this.room.addTrack(track);
+ } else {
+ if (this.localAudio) {
+ this.room.addTrack(track);
+ } else {
+ track.mute();
+ }
+ if (this.id === 0) {
+ this.attachTrack(track, `localAudio${i}`, true, true);
+ }
+ }
+ }
+ }
+
+ private onRemoteTrack(track: any): void {
+ if (!track.isLocal() && track.getType() === 'video') {
+ this.addRemoteVideoSource(track);
+ this.electOnStageParticipant();
+ this.updateReceiverConstraints();
+ }
+
+ if (track.isLocal()
+ || (track.getType() === 'video' && !this.params.remoteVideo)
+ || (track.getType() === 'audio' && !this.params.remoteAudio)) {
+ return;
+ }
+ const participant = track.getParticipantId();
+
+ if (!this.remoteTracks[participant]) {
+ this.remoteTracks[participant] = [];
+ }
+
+ if (this.id !== 0) {
+ return;
+ }
+
+ const idx = this.remoteTracks[participant].push(track);
+
+ this.attachTrack(track, `${participant}${track.getType()}${idx}`, true);
+ }
+
+ private onConferenceJoined(): void {
+ logger.log(`Participant ${this.id} Conference joined`);
+
+ // Delay processing USER_JOINED events until the MUC is fully joined,
+ // otherwise the apparent conference size will be wrong.
+ this.numParticipants = this.room.getParticipantCount();
+ this.setNumberOfParticipants();
+ this.room.on(JitsiMeetJS.events.conference.USER_JOINED, this.onUserJoined.bind(this));
+ this.room.on(JitsiMeetJS.events.conference._MEDIA_SESSION_STARTED, this.onMediaSessionStarted.bind(this));
+ }
+
+ /**
+ * Handles start muted events, when audio and/or video are muted due to startAudioMuted or startVideoMuted
+ * policy.
+ *
+ * @returns {void}
+ */
+ private onStartMuted(): void {
+ // Give it some time, as it may be currently in the process of muting
+ setTimeout(() => {
+ const localAudioTrack = this.room.getLocalAudioTrack();
+
+ if (this.localAudio && localAudioTrack?.isMuted()) {
+ localAudioTrack.unmute();
+ }
+
+ const localVideoTrack = this.room.getLocalVideoTrack();
+
+ if (this.params.localVideo && localVideoTrack?.isMuted()) {
+ localVideoTrack.unmute();
+ }
+ }, 2000);
+ }
+
+ private onUserJoined(id: string): void {
+ this.numParticipants++;
+ this.setNumberOfParticipants();
+ this.remoteTracks[id] = [];
+ }
+
+ private onMediaSessionStarted(): void {
+ this.updateReceiverConstraints(true);
+ }
+
+ private onUserLeft(id: string): void {
+ this.numParticipants--;
+ this.remoteVideoSources = this.remoteVideoSources.filter(s => s.participantId !== id);
+ if (this.onStageParticipant === id) {
+ this.onStageParticipant = null;
+ this.electOnStageParticipant();
+ }
+ this.setNumberOfParticipants();
+
+ const tracks = this.remoteTracks[id];
+
+ if (!tracks || this.id !== 0) {
+ return;
+ }
+
+ for (let i = 0; i < tracks.length; i++) {
+ const container = document.getElementById(`${id}${tracks[i].getType()}${i + 1}`);
+
+ if (container) {
+ tracks[i].detach(container);
+ container.parentElement?.removeChild(container);
+ }
+ }
+ }
+
+ private onPrivateMessage(_id: string, text: string): void {
+ switch (text) {
+ case 'video on':
+ this.onVideoOnMessage();
+ break;
+ }
+ }
+
+ /**
+ * Handles 'video on' private messages.
+ *
+ * @returns {void}
+ */
+ private onVideoOnMessage(): void {
+ if (this.visitor) {
+ logger.warn(`Participant ${this.id}: In visitor mode, not turning video on.`);
+
+ return;
+ }
+
+ logger.debug(`Participant ${this.id}: Turning my video on!`);
+
+ const localVideoTrack = this.room.getLocalVideoTrack();
+
+ if (localVideoTrack?.isMuted()) {
+ logger.debug(`Participant ${this.id}: Unmuting existing video track.`);
+ localVideoTrack.unmute();
+ } else if (!localVideoTrack) {
+ JitsiMeetJS.createLocalTracks({ devices: [ 'video' ] })
+ .then(([ videoTrack ]: any[]) => this.room.replaceTrack(null, videoTrack))
+ .then(() => {
+ logger.debug(`Participant ${this.id}: Successfully added a new video track for unmute.`);
+ })
+ .catch((e: unknown) => logger.error(e));
+ } else {
+ logger.log(`Participant ${this.id}: No-op! We are already video unmuted!`);
+ }
+ }
+
+ private onConferenceFailed(error: unknown): void {
+ if (error !== JitsiMeetJS.errors.conference.REDIRECTED) {
+ logger.error(error);
+ }
+ }
+
+ private onConnectionRedirected(vnode: string, focusJid: string): void {
+ logger.log(`Participant ${this.id}: redirecting to visitor node ${vnode} with focusJid=${focusJid}`);
+ this.connection.disconnect().then(() => {
+ this.visitor = true;
+
+ const conf = this.config as any;
+ const oldDomain = conf.hosts.domain;
+
+ conf.hosts.domain = `${vnode}.meet.jitsi`;
+ conf.hosts.muc = conf.hosts.muc.replace(oldDomain, conf.hosts.domain);
+ conf.focusUserJid = focusJid;
+ conf.disableFocus = true;
+
+ // Not every deployment configures all three (BOSH only, or no keep-alive URL).
+ for (const key of [ 'bosh', 'websocket', 'websocketKeepAliveUrl' ]) {
+ if (conf[key]) {
+ conf[key] = appendURLParam(conf[key], 'vnode', vnode);
+ }
+ }
+
+ this.localTracks.forEach(track => track.mute());
+
+ this.updateConfig();
+ this.connect();
+ });
+ }
+
+ /**
+ * Connects to the XMPP server; joins the room once connected.
+ *
+ * @returns {void}
+ */
+ connect(): void {
+ const { jwt } = this.params;
+
+ if (jwt) {
+ try {
+ const { context } = jwtDecode<any>(jwt);
+
+ if (context?.user?.role === 'visitor') {
+ (this.config as any).preferVisitor = true;
+ }
+ } catch (e) {
+ logger.error(e);
+ }
+ }
+
+ this.connection = new JitsiMeetJS.JitsiConnection(null, jwt, this.config);
+ this.connection.addEventListener(
+ JitsiMeetJS.events.connection.CONNECTION_ESTABLISHED, this.onConnectionSuccessBound);
+ this.connection.addEventListener(
+ JitsiMeetJS.events.connection.CONNECTION_FAILED, this.onConnectionFailedBound);
+ this.connection.addEventListener(
+ JitsiMeetJS.events.connection.CONNECTION_DISCONNECTED, this.disconnectBound);
+ this.connection.addEventListener(
+ JitsiMeetJS.events.connection.CONNECTION_REDIRECTED, this.onConnectionRedirectedBound);
+ this.connection.connect({ name: this.params.roomName });
+ }
+
+ private onConnectionSuccess(): void {
+ const { roomName, localVideo } = this.params;
+ const events = JitsiMeetJS.events.conference;
+
+ this.room = this.connection.initJitsiConference(roomName.toLowerCase(), this.config);
+ this.room.on(events.STARTED_MUTED, this.onStartMuted.bind(this));
+ this.room.on(events.TRACK_ADDED, this.onRemoteTrack.bind(this));
+ this.room.on(events.TRACK_REMOVED, this.onTrackRemoved.bind(this));
+ this.room.on(events.CONFERENCE_JOINED, this.onConferenceJoined.bind(this));
+ this.room.on(events.DATA_CHANNEL_OPENED, this.onDataChannelOpened.bind(this));
+ this.room.on(events.USER_LEFT, this.onUserLeft.bind(this));
+ this.room.on(events.PRIVATE_MESSAGE_RECEIVED, this.onPrivateMessage.bind(this));
+ this.room.on(events.CONFERENCE_FAILED, this.onConferenceFailed.bind(this));
+ // Stage view is also what jitsi-meet uses below 3 participants, so always follow the dominant speaker.
+ this.room.on(events.DOMINANT_SPEAKER_CHANGED, this.onDominantSpeakerChanged.bind(this));
+
+ const devices: string[] = [];
+
+ if (!this.visitor) {
+ if (localVideo) {
+ devices.push('video');
+ }
+ if (!this.config.disableInitialGUM) {
+ devices.push('audio');
+ }
+ }
+
+ if (devices.length > 0) {
+ JitsiMeetJS.createLocalTracks({ devices })
+ .then(this.onLocalTracks.bind(this))
+ .then(() => this.room.join())
+ .catch((error: unknown) => {
+ logger.error(`Participant ${this.id}: failed to create local tracks`, error);
+ });
+ } else {
+ this.room.join();
+ }
+ }
+
+ private onConnectionFailed(): void {
+ logger.error(`Participant ${this.id}: Connection Failed!`);
+ }
+
+ /**
+ * Called when the connection is disconnected: stops listening on it.
+ *
+ * @returns {void}
+ */
+ disconnect(): void {
+ logger.log('disconnect!');
+ this.connection.removeEventListener(
+ JitsiMeetJS.events.connection.CONNECTION_ESTABLISHED, this.onConnectionSuccessBound);
+ this.connection.removeEventListener(
+ JitsiMeetJS.events.connection.CONNECTION_FAILED, this.onConnectionFailedBound);
+ this.connection.removeEventListener(
+ JitsiMeetJS.events.connection.CONNECTION_DISCONNECTED, this.disconnectBound);
+ }
+
+ /**
+ * Leaves the conference and disconnects, releasing the local tracks.
+ *
+ * @returns {void}
+ */
+ unload(): void {
+ // Leaving removes every remote track, which would otherwise trigger a flurry of constraint updates.
+ this.leaving = true;
+ this.localTracks.forEach(track => track.dispose());
+ this.room?.leave();
+ this.connection?.disconnect();
+ }
+}
diff --git a/react/features/load-test/layout.ts b/react/features/load-test/layout.ts
new file mode 100644
index 0000000000..e0ae805386
--- /dev/null
+++ b/react/features/load-test/layout.ts
@@ -0,0 +1,217 @@
+/**
+ * A stripped-down model of the jitsi-meet web layout, enough to compute the receiver video constraints a real
+ * client with a window of the given size would send. Follows react/features/filmstrip/functions.web.ts
+ * (calculateResponsiveTileViewDimensions, calculateThumbnailSizeForTileView) and the constants those use; those
+ * functions take the redux state, which the load-test client does not have, so they cannot be used directly.
+ */
+
+/* Constants from react/features/filmstrip/constants.ts. */
+const TILE_ASPECT_RATIO = 16 / 9;
+const TILE_PORTRAIT_ASPECT_RATIO = 1 / 1.3;
+const TILE_MIN_HEIGHT_SMALL = 150;
+const TILE_MIN_HEIGHT_LARGE = 200;
+const ASPECT_RATIO_BREAKPOINT = 500;
+const TILE_VERTICAL_MARGIN = 4;
+const TILE_HORIZONTAL_MARGIN = 4;
+const TILE_VIEW_GRID_VERTICAL_MARGIN = 14;
+const TILE_VIEW_GRID_HORIZONTAL_MARGIN = 14;
+const TOOLBAR_HEIGHT = 72;
+const VERTICAL_FILMSTRIP_VERTICAL_MARGIN = 26;
+const DEFAULT_FILMSTRIP_WIDTH = 120;
+
+/** The default of interfaceConfig.TILE_VIEW_MAX_COLUMNS. */
+export const DEFAULT_MAX_COLUMNS = 5;
+
+/** The default of config.tileView.numberOfVisibleTiles. */
+export const DEFAULT_NUMBER_OF_VISIBLE_TILES = 25;
+
+/** The default of config.maxFullResolutionParticipants. */
+export const DEFAULT_MAX_FULL_RESOLUTION_PARTICIPANTS = 2;
+
+/** The window size assumed when the page does not say otherwise: what the test suite runs Chrome with. */
+export const DEFAULT_WINDOW_WIDTH = 1280;
+export const DEFAULT_WINDOW_HEIGHT = 1024;
+
+/* react/features/video-quality/constants.ts */
+export const VIDEO_QUALITY_LEVELS = {
+ ULTRA: 2160,
+ HIGH: 720,
+ STANDARD: 360,
+ LOW: 180,
+ NONE: 0
+};
+
+/**
+ * The receive quality level for a video element of the given height: the highest level whose value fits, and at
+ * least LOW. This is jitsi-meet's getReceiverVideoQualityLevel with the default (identity) height-to-level map;
+ * config.videoQuality.minHeightForQualityLvl is not emulated.
+ *
+ * @param {number} height - The height of the element in pixels.
+ * @returns {number} The quality level.
+ */
+export function qualityForHeight(height: number): number {
+ let selected = VIDEO_QUALITY_LEVELS.LOW;
+
+ for (const level of [ VIDEO_QUALITY_LEVELS.LOW, VIDEO_QUALITY_LEVELS.STANDARD, VIDEO_QUALITY_LEVELS.HIGH,
+ VIDEO_QUALITY_LEVELS.ULTRA ]) {
+ if (height >= level) {
+ selected = level;
+ }
+ }
+
+ return selected;
+}
+
+interface ITileSize {
+ height: number;
+ maxVisibleRows: number;
+ minHeightEnforced: boolean;
+ width: number;
+}
+
+/**
+ * The size of a tile for a grid of the given columns and rows; calculateThumbnailSizeForTileView with responsive
+ * tiles and tile enlargement enabled (the defaults).
+ *
+ * @param {number} columns - The number of columns.
+ * @param {number} minVisibleRows - The number of rows that have to be visible.
+ * @param {number} clientWidth - The width of the video area.
+ * @param {number} clientHeight - The height of the video area.
+ * @returns {ITileSize|undefined} The size, or undefined if that many columns cannot fit.
+ */
+function tileSize(
+ columns: number, minVisibleRows: number, clientWidth: number, clientHeight: number): ITileSize | undefined {
+ const aspectRatio = TILE_ASPECT_RATIO;
+ const minHeight = clientWidth < ASPECT_RATIO_BREAKPOINT ? TILE_MIN_HEIGHT_SMALL : TILE_MIN_HEIGHT_LARGE;
+ const viewWidth = clientWidth - (columns * TILE_HORIZONTAL_MARGIN) - TILE_VIEW_GRID_HORIZONTAL_MARGIN;
+ const availableHeight = clientHeight - TILE_VIEW_GRID_VERTICAL_MARGIN;
+ const viewHeight = availableHeight - (minVisibleRows * TILE_VERTICAL_MARGIN);
+ const initialWidth = viewWidth / columns;
+ let initialHeight = viewHeight / minVisibleRows;
+ let minHeightEnforced = false;
+
+ if (initialHeight < minHeight) {
+ minHeightEnforced = true;
+ initialHeight = minHeight;
+ }
+
+ const initialRatio = initialWidth / initialHeight;
+ let height = initialHeight;
+ let width;
+
+ if (initialRatio > aspectRatio) {
+ width = initialHeight * aspectRatio;
+ } else if (initialRatio >= TILE_PORTRAIT_ASPECT_RATIO) {
+ width = initialWidth;
+ } else if (!minHeightEnforced) {
+ height = initialWidth / TILE_PORTRAIT_ASPECT_RATIO;
+
+ if (height >= minHeight) {
+ width = initialWidth;
+ } else {
+ return undefined;
+ }
+ } else {
+ return undefined;
+ }
+
+ return {
+ height,
+ width,
+ minHeightEnforced,
+ maxVisibleRows: Math.floor(availableHeight / (height + TILE_VERTICAL_MARGIN))
+ };
+}
+
+/**
+ * The height of the tiles in tile view for the given number of participants (local included), following
+ * calculateResponsiveTileViewDimensions: the grid with the biggest total visible area wins.
+ *
+ * @param {number} numberOfParticipants - The number of participants, local included.
+ * @param {number} clientWidth - The width of the window.
+ * @param {number} clientHeight - The height of the window.
+ * @param {number} maxColumns - The maximum number of columns.
+ * @param {number} desiredNumberOfVisibleTiles - How many tiles should be visible without scrolling.
+ * @returns {number} The tile height in pixels.
+ */
+export function tileViewTileHeight( // eslint-disable-line max-params
+ numberOfParticipants: number,
+ clientWidth: number,
+ clientHeight: number,
+ maxColumns = DEFAULT_MAX_COLUMNS,
+ desiredNumberOfVisibleTiles = DEFAULT_NUMBER_OF_VISIBLE_TILES): number {
+ interface IDimensions {
+ height?: number;
+ maxArea: number;
+ numberOfVisibleParticipants?: number;
+ }
+
+ let dimensions: IDimensions = { maxArea: 0 };
+ let minHeightEnforcedDimensions: IDimensions = { maxArea: 0 };
+ let zeroVisibleRowsDimensions: IDimensions = { maxArea: 0 };
+
+ for (let c = 1; c <= Math.min(maxColumns, numberOfParticipants, desiredNumberOfVisibleTiles); c++) {
+ const r = Math.ceil(numberOfParticipants / c);
+ const visibleRows
+ = numberOfParticipants <= desiredNumberOfVisibleTiles ? r : Math.floor(desiredNumberOfVisibleTiles / c);
+ const size = tileSize(c, visibleRows, clientWidth, clientHeight);
+
+ if (!size) {
+ continue;
+ }
+
+ const { height, width, minHeightEnforced, maxVisibleRows } = size;
+ const numberOfVisibleParticipants = Math.min(c * maxVisibleRows, numberOfParticipants);
+ let area = Math.round((height + TILE_VERTICAL_MARGIN) * (width + TILE_HORIZONTAL_MARGIN)
+ * numberOfVisibleParticipants);
+ const current: IDimensions = { maxArea: area, height, numberOfVisibleParticipants };
+ const { numberOfVisibleParticipants: oldNumberOfVisibleParticipants = 0 } = dimensions;
+
+ if (!minHeightEnforced) {
+ if (area > dimensions.maxArea) {
+ dimensions = current;
+ } else if (area === dimensions.maxArea
+ && ((oldNumberOfVisibleParticipants > desiredNumberOfVisibleTiles
+ && oldNumberOfVisibleParticipants >= numberOfParticipants)
+ || (oldNumberOfVisibleParticipants < numberOfParticipants
+ && numberOfVisibleParticipants <= desiredNumberOfVisibleTiles))) {
+ dimensions = current;
+ }
+ } else if (area >= minHeightEnforcedDimensions.maxArea) {
+ minHeightEnforcedDimensions = current;
+ } else if (maxVisibleRows === 0) {
+ area = height * width * Math.min(c, numberOfParticipants);
+ if (area > zeroVisibleRowsDimensions.maxArea) {
+ zeroVisibleRowsDimensions = { ...current, maxArea: area };
+ }
+ }
+ }
+
+ const chosen = [ dimensions, minHeightEnforcedDimensions, zeroVisibleRowsDimensions ].find(d => d.maxArea > 0);
+
+ return chosen?.height ?? (clientWidth < ASPECT_RATIO_BREAKPOINT ? TILE_MIN_HEIGHT_SMALL : TILE_MIN_HEIGHT_LARGE);
+}
+
+/**
+ * How many remote thumbnails fit in the vertical filmstrip of stage view without scrolling, at the default
+ * filmstrip width, leaving room for the local thumbnail.
+ *
+ * @param {number} clientHeight - The height of the window.
+ * @returns {number} The number of visible remote thumbnails.
+ */
+export function verticalFilmstripVisibleCount(clientHeight: number): number {
+ const thumbnailHeight = DEFAULT_FILMSTRIP_WIDTH / TILE_ASPECT_RATIO;
+ const available = clientHeight - TOOLBAR_HEIGHT - VERTICAL_FILMSTRIP_VERTICAL_MARGIN;
+
+ return Math.max(0, Math.floor(available / (thumbnailHeight + TILE_VERTICAL_MARGIN)) - 1);
+}
+
+/**
+ * The height of the large video in stage view: the window minus the toolbar.
+ *
+ * @param {number} clientHeight - The height of the window.
+ * @returns {number} The height in pixels.
+ */
+export function largeVideoHeight(clientHeight: number): number {
+ return clientHeight - TOOLBAR_HEIGHT;
+}
diff --git a/react/features/load-test/loadTestParticipant.ts b/react/features/load-test/loadTestParticipant.ts
new file mode 100644
index 0000000000..b0952bd566
--- /dev/null
+++ b/react/features/load-test/loadTestParticipant.ts
@@ -0,0 +1,199 @@
+/* global config */
+
+/**
+ * The entry point of the load-test client bundle: a page that joins a conference with lib-jitsi-meet only, no
+ * UI, to generate load. Built by `npm run build:load-test` into build/load-test-participant.min.js; it is not
+ * part of the deployed application. Malleus (tests/malleus) uploads it into the browsers it drives together
+ * with tests/resources/loadTest.html, which loads config.js and lib-jitsi-meet from the deployment under test.
+ *
+ * Page parameters are passed in the URL hash the way jitsi-meet does it (JSON values, e.g. room="foo"):
+ * - config.*: overrides applied to the deployment's config, as in jitsi-meet;
+ * - room: the room name; if missing it is taken from the URL path as jitsi-meet would;
+ * - domain: the deployment's host, used to absolutize protocol-relative XMPP URLs in its config;
+ * - jwt: a token to connect with (also accepted as a ?jwt= query parameter);
+ * - numClients, clientInterval: how many clients to run in this page and the delay between starting them;
+ * - isHuman: whether to receive (and render) remote media, off by default;
+ * - localVideo, localAudio, remoteVideo, remoteAudio, autoPlayVideo, stageView: explicit overrides of the
+ * behavior otherwise derived from the config;
+ * - windowWidth, windowHeight: the window size of the emulated jitsi-meet client, which decides the video sizes
+ * it asks the bridge for (default 1280x1024, what the test suite runs Chrome with).
+ */
+// @ts-expect-error
+import Logger from '@jitsi/logger';
+
+import JitsiMeetInMemoryLogStorage from '../base/logging/JitsiMeetInMemoryLogStorage';
+import { parseURLParams } from '../base/util/parseURLParams';
+import { parseURIString } from '../base/util/uri';
+
+import { ILoadTestParams, LoadTestClient } from './LoadTestClient';
+import { DEFAULT_WINDOW_HEIGHT, DEFAULT_WINDOW_WIDTH } from './layout';
+
+/**
+ * Applies the config.* URL parameters to the config, without the whitelist the application uses.
+ *
+ * @param {Object} params - The parsed URL parameters.
+ * @returns {void}
+ */
+function setConfigFromURLParams(params: Record<string, any>): void {
+ for (const param of Object.keys(params)) {
+ const names = param.split('.');
+
+ if (names.shift() !== 'config' || !names.length) {
+ continue;
+ }
+
+ let base: any = config;
+ const last = names.pop() as string;
+
+ for (const name of names) {
+ base = base[name] = base[name] || {};
+ }
+ base[last] = params[param];
+ }
+}
+
+/**
+ * Makes protocol-relative XMPP URLs ("//host/http-bind") absolute, using the given host if the URL has none.
+ * Needed because the page is loaded from a file:// URL, not from the deployment.
+ *
+ * @param {string|undefined} domain - The deployment's host.
+ * @returns {void}
+ */
+function absolutizeXmppUrls(domain?: string): void {
+ const conf = config as any;
+
+ for (const key of [ 'bosh', 'websocket', 'websocketKeepAliveUrl' ]) {
+ const value = conf[key];
+
+ if (typeof value !== 'string') {
+ continue;
+ }
+ if (value.startsWith('//')) {
+ conf[key] = `${key === 'bosh' ? 'https:' : 'wss:'}${value}`;
+ } else if (value.startsWith('/') && domain) {
+ conf[key] = `${key === 'bosh' ? 'https' : 'wss'}://${domain}${value}`;
+ }
+ }
+}
+
+const params = parseURLParams(window.location.toString(), false, 'hash');
+
+setConfigFromURLParams(params);
+absolutizeXmppUrls(params.domain);
+
+const { isHuman = false } = params;
+const {
+ localVideo = config.startWithVideoMuted !== true,
+ localAudio = !config.disableInitialGUM && !config.startWithAudioMuted,
+ remoteVideo = isHuman,
+ remoteAudio = isHuman,
+ autoPlayVideo = config.testing?.noAutoPlayVideo !== true,
+ stageView = Boolean(config.disableTileView),
+ numClients = 1,
+ clientInterval = 100, // ms
+ windowWidth = DEFAULT_WINDOW_WIDTH,
+ windowHeight = DEFAULT_WINDOW_HEIGHT
+} = params;
+
+const roomName: string = params.room || parseURIString(window.location.toString())?.room;
+const jwt: string | undefined = params.jwt || parseURLParams(window.location.toString(), true, 'search').jwt;
+
+const loadTestParams: ILoadTestParams = {
+ autoPlayVideo,
+ jwt,
+ localAudio,
+ localVideo,
+ remoteAudio,
+ remoteVideo,
+ roomName,
+ stageView,
+ windowHeight,
+ windowWidth
+};
+
+let clients: LoadTestClient[] = [];
+
+// The same surface that the tests use on the real application (APP.conference.*), plus load-test specifics.
+(window as any).APP = {
+ conference: {
+ getStats() {
+ return clients[0]?.room?.connectionQuality.getStats();
+ },
+ getConnectionState() {
+ return clients[0]?.room?.getConnectionState();
+ },
+ muteAudio(mute: boolean, num?: number) {
+ if (num === undefined) {
+ clients.forEach(client => client.muteAudio(mute));
+ } else {
+ clients[num]?.muteAudio(mute);
+ }
+ }
+ },
+
+ get room() {
+ return clients[0]?.room;
+ },
+ get connection() {
+ return clients[0]?.connection;
+ },
+ get numParticipants() {
+ return clients[0]?.numParticipants;
+ },
+ get localTracks() {
+ return clients[0]?.localTracks;
+ },
+ get remoteTracks() {
+ return clients[0]?.remoteTracks;
+ },
+ get params() {
+ return loadTestParams;
+ },
+ debugLogs: new JitsiMeetInMemoryLogStorage()
+};
+
+/**
+ * Leaves the conferences and disconnects all the clients.
+ *
+ * @returns {void}
+ */
+function unload() {
+ clients.forEach(client => client.unload());
+ clients = [];
+}
+
+window.addEventListener('beforeunload', unload);
+window.addEventListener('unload', unload);
+
+JitsiMeetJS.setLogLevel(JitsiMeetJS.logLevels.TRACE);
+
+const debugLogCollector = new Logger.LogCollector((window as any).APP.debugLogs, { storeInterval: 1000 });
+
+Logger.addGlobalTransport(debugLogCollector);
+JitsiMeetJS.addGlobalLogTransport(debugLogCollector);
+debugLogCollector.start();
+
+JitsiMeetJS.init(config);
+
+/**
+ * Starts a client, and schedules the next one.
+ *
+ * @param {number} i - The index of the client to start.
+ * @returns {void}
+ */
+function startClient(i: number) {
+ // Each client gets its own copy of the config, as it modifies it.
+ clients[i] = new LoadTestClient(i, JSON.parse(JSON.stringify(config)), loadTestParams);
+ clients[i].connect();
+ if (i + 1 < numClients) {
+ setTimeout(() => startClient(i + 1), clientInterval);
+ }
+}
+
+if (!roomName) {
+ throw new Error('No room name given (room="..." in the URL hash, or a room path).');
+}
+
+if (numClients > 0) {
+ startClient(0);
+}
diff --git a/tests/env.example b/tests/env.example
index 8e05cc551b..614a26cf1f 100644
--- a/tests/env.example
+++ b/tests/env.example
@@ -91,3 +91,39 @@
# A stream key abd broadcast ID that can be used by the tests to stream to YouTube
#YTUBE_TEST_STREAM_KEY=
#YTUBE_TEST_BROADCAST_ID=
+
+# Malleus Jitsificus (the load tester, see malleus/README.md) settings. Normally set through the flags of
+# `npm run malleus`, which override these. The regular settings above (BASE_URL, GRID_HOST_URL, HEADLESS,
+# ALLOW_INSECURE_CERTS, VIDEO_CAPTURE_FILE, ROOM_NAME_PREFIX, ROOM_NAME_SUFFIX, RESOLVER_RULES) apply too; a
+# comma-separated ROOM_NAME_SUFFIX spreads the conferences over the suffixes.
+#MALLEUS_CONFERENCES=1
+#MALLEUS_PARTICIPANTS=3
+#MALLEUS_SENDERS=3
+#MALLEUS_AUDIO_SENDERS=3
+#MALLEUS_DURATION=60
+#MALLEUS_JOIN_DELAY=0
+#MALLEUS_ROOM_NAME_PREFIX=anvil-
+#MALLEUS_REGIONS=
+#MALLEUS_ENABLE_P2P=true
+#MALLEUS_USE_STAGE_VIEW=false
+#MALLEUS_SWITCH_SPEAKERS=false
+#MALLEUS_USE_LOAD_TEST=false
+#MALLEUS_USE_LITE_MODE=false
+#MALLEUS_SENDERS_PER_TAB=1
+#MALLEUS_RECEIVERS_PER_TAB=1
+#MALLEUS_SENDER_TABS_PER_BROWSER=1
+#MALLEUS_RECEIVER_TABS_PER_BROWSER=1
+# Requires the grid to declare nodename:applicationName malleusSender / malleusReceiver stereotypes.
+#MALLEUS_USE_NODE_TYPES=false
+#MALLEUS_MAX_DISRUPTED_BRIDGES_PCT=0
+#MALLEUS_BLIP_SCRIPT=
+#MALLEUS_EXTRA_SENDER_PARAMS=
+#MALLEUS_EXTRA_RECEIVER_PARAMS=
+#MALLEUS_JWT=
+# Mint a JaaS token per participant with JAAS_KID / JAAS_PRIVATE_KEY_PATH (default: true when those are set)
+#MALLEUS_GENERATE_JAAS_TOKENS=
+# Whether minted JaaS tokens are moderator tokens, which bypass a lobby (default: true)
+#MALLEUS_JAAS_MODERATOR=
+#MALLEUS_SAVE_LOGS=false
+# The browserVersion to request from the grid (default: jitsi-stable, the grid's alias for current stable Chrome)
+#MALLEUS_BROWSER_VERSION=
diff --git a/tests/helpers/Participant.ts b/tests/helpers/Participant.ts
index 8dd13ed55a..b6fd8b5d76 100644
--- a/tests/helpers/Participant.ts
+++ b/tests/helpers/Participant.ts
@@ -63,6 +63,16 @@ export class Participant {
*/
private _name: string;
private _endpointId: string;
+
+ /**
+ * The browser session this participant is bound to, when not using a multiremote instance.
+ */
+ private _driver?: WebdriverIO.Browser;
+
+ /**
+ * Whether this participant runs the load-test client rather than the full application.
+ */
+ private _loadTest: boolean;
/**
* The token that this participant was initialized with.
*/
@@ -143,6 +153,8 @@ export class Participant {
this._name = options.name;
this._token = options.token;
this._iFrameApi = options.iFrameApi || false;
+ this._loadTest = options.loadTest || false;
+ this._driver = options.driver;
}
/**
@@ -209,7 +221,14 @@ export class Participant {
* The driver it uses.
*/
get driver() {
- return multiRemoteBrowser.getInstance(this._name);
+ return this._driver ?? multiRemoteBrowser.getInstance(this._name);
+ }
+
+ /**
+ * Whether this participant runs the load-test client rather than the full application.
+ */
+ get isLoadTest() {
+ return this._loadTest;
}
/**
@@ -256,11 +275,28 @@ export class Participant {
if (this._iFrameApi) {
config.room = 'iframeAPITest.html';
+ } else if (this._loadTest) {
+ config.room = 'loadTest.html';
}
let url = urlObjectToString(config) || '';
- if (this._iFrameApi) {
+ if (this._loadTest) {
+ // The uploaded wrapper page (see the malleus wdio config); it loads config.js and lib-jitsi-meet from
+ // the deployment and the uploaded client bundle, which takes the room and config from the hash.
+ const baseUrl = new URL(this.driver.options.baseUrl || '');
+ let tenant = options.tenant ?? (baseUrl.pathname.length > 1 ? baseUrl.pathname.substring(1) : '');
+
+ // The page prepends it to "config.js", so it needs the trailing slash options.tenant comes without.
+ if (tenant && !tenant.endsWith('/')) {
+ tenant += '/';
+ }
+
+ // @ts-ignore
+ url = `${this.driver.loadTestPageBase}${url}&domain="${baseUrl.host}"&room="${options.roomName}"`
+ // @ts-ignore
+ + `&tenant="${tenant}"&bundle="${this.driver.loadTestBundle}"`;
+ } else if (this._iFrameApi) {
const baseUrl = new URL(this.driver.options.baseUrl || '');
// @ts-ignore
@@ -282,8 +318,8 @@ export class Participant {
// drop the leading '/' so we can use the tenant if any
url = url.startsWith('/') ? url.substring(1) : url;
- if (options.tenant && !this._iFrameApi) {
- // For the iFrame API the tenant is passed in a different way.
+ if (options.tenant && !this._iFrameApi && !this._loadTest) {
+ // For the iFrame API and the load-test page the tenant is passed in a different way.
url = `/${options.tenant}/${url}`;
}
if (options.urlAppendString) {
@@ -305,7 +341,7 @@ export class Participant {
await this.switchToIFrame();
}
- if (!options.skipPrejoinButtonClick) {
+ if (!options.skipPrejoinButtonClick && !this._loadTest) {
// The prejoin Join button can be in the DOM before conference.init has run and React click
// handlers are mounted (e.g. when driver.url() returns before the page fully loads on a slow
// remote grid, or when the iFrame API wrapper fires onload before the embedded app inits).
@@ -346,7 +382,15 @@ export class Participant {
await this.waitForMucJoinedOrError();
}
- await this.postLoadProcess();
+ if (this._loadTest) {
+ // The load-test client has no UI to adjust; just record the session like postLoadProcess does.
+ await this.execute((name, sessionId, prefix) => {
+ document.title = `${name}`;
+ console.log(`${new Date().toISOString()} ${prefix} sessionId: ${sessionId}`);
+ }, this._name, this.driver.sessionId, LOG_PREFIX);
+ } else {
+ await this.postLoadProcess();
+ }
return this;
}
@@ -424,6 +468,11 @@ export class Participant {
* Checks if the participant is in the meeting.
*/
isInMuc() {
+ if (this._loadTest) {
+ // @ts-ignore
+ return this.execute(() => typeof APP !== 'undefined' && Boolean(APP.room?.isJoined()));
+ }
+
return this.execute(() => typeof APP !== 'undefined' && APP.conference?.isJoined());
}
@@ -433,6 +482,10 @@ export class Participant {
*/
async waitForMucJoinedOrError(): Promise<void> {
await this.driver.waitUntil(async () => {
+ if (this._loadTest) {
+ return await this.isInMuc();
+ }
+
return await this.isInMuc() || await this.getPasswordDialog().isOpen()
|| await this.getNotifications().getNotificationText(MAX_USERS_TEST_ID)
|| await this.getNotifications().getNotificationText(TOKEN_AUTH_FAILED_TEST_ID)
@@ -878,6 +931,15 @@ export class Participant {
return;
}
+ if (this._loadTest) {
+ // The load-test client leaves the room and disconnects from its unload handler, so navigating away
+ // is the hangup. There is no iframe to switch out of either.
+ await this.driver.url('/base.html');
+ console.log(`Hung up (${this.name})`);
+
+ return;
+ }
+
// @ts-ignore
await this.execute(() => window.APP?.conference?.hangup());
diff --git a/tests/helpers/grid.ts b/tests/helpers/grid.ts
new file mode 100644
index 0000000000..7b5b2518fd
--- /dev/null
+++ b/tests/helpers/grid.ts
@@ -0,0 +1,46 @@
+import { URL } from 'url';
+
+/**
+ * Points a wdio config at the Selenium Grid given by GRID_HOST_URL (e.g. https://mygrid.com/wd/hub) and rewrites
+ * the fake audio capture path in every capability to the copy of the resource available on the grid nodes
+ * (REMOTE_RESOURCE_PATH), since a path on this machine means nothing to a remote browser.
+ *
+ * @param baseConfig - The config to extend. It is not modified.
+ * @returns The extended config.
+ */
+export function applyGridConfig<T extends WebdriverIO.MultiremoteConfig>(baseConfig: T): T {
+ const gridUrl = new URL(process.env.GRID_HOST_URL as string);
+ const protocol = gridUrl.protocol.replace(':', '');
+
+ const mergedConfig = {
+ ...baseConfig,
+ protocol,
+ hostname: gridUrl.hostname,
+ port: gridUrl.port ? parseInt(gridUrl.port, 10) // Convert port to number
+ : protocol === 'http' ? 80 : 443,
+ path: gridUrl.pathname
+ };
+
+ const capabilities = mergedConfig.capabilities as Record<string, any>;
+
+ Object.keys(capabilities).forEach(browser => {
+ const chromeOptions = capabilities[browser].capabilities['goog:chromeOptions'];
+
+ if (chromeOptions?.args) {
+ chromeOptions.args = updateRemoteResource(chromeOptions.args);
+ }
+ });
+
+ return mergedConfig;
+}
+
+/**
+ * Updates the array of arguments for the Chrome browser to use a remote resource for fake audio capture.
+ * @param arr
+ */
+function updateRemoteResource(arr: string[]): string[] {
+ // eslint-disable-next-line no-confusing-arrow
+ return arr.map((item: string) => item.startsWith('--use-file-for-fake-audio-capture=')
+ ? `--use-file-for-fake-audio-capture=${process.env.REMOTE_RESOURCE_PATH}/fakeAudioStream.wav` : item
+ );
+}
diff --git a/tests/helpers/types.ts b/tests/helpers/types.ts
index f0c4192035..a2becfa058 100644
--- a/tests/helpers/types.ts
+++ b/tests/helpers/types.ts
@@ -45,10 +45,21 @@ export type IContext = {
};
export type IParticipantOptions = {
+ /**
+ * The browser session to bind the participant to. When omitted, the multiremote instance named `name`
+ * (one of p1..p6) is used. Set it for participants created outside the multiremote setup, such as
+ * load-test participants that have their own sessions or share one via tabs.
+ */
+ driver?: WebdriverIO.Browser;
/** Whether it should use the iFrame API. */
iFrameApi?: boolean;
- /** Determines the browser instance to use. */
- name: 'p1' | 'p2' | 'p3' | 'p4' | 'p5' | 'p6';
+ /**
+ * Whether the participant runs the lightweight load-test client (lib-jitsi-meet only, no UI) instead of
+ * the full Jitsi Meet application. UI-only steps (prejoin, styling, dialogs) are skipped for such participants.
+ */
+ loadTest?: boolean;
+ /** Determines the browser instance to use. Regular tests use p1..p6, load tests use generated names. */
+ name: string;
/** An optional token to use. */
token?: IToken;
};
diff --git a/tests/helpers/utils.ts b/tests/helpers/utils.ts
index e47d7340fe..d1579988b7 100644
--- a/tests/helpers/utils.ts
+++ b/tests/helpers/utils.ts
@@ -2,22 +2,40 @@ import { config as testsConfig } from './TestsConfig';
const https = require('https');
+/**
+ * Assembles a room name from a base name and the optional prefix and suffix, using the suite's convention.
+ * The suffix goes last so that infrastructure which pins a conference to a release by a shard name at the end
+ * of the room name keeps working whatever the base name looks like.
+ *
+ * @param baseName - The middle part of the room name, e.g. the test name plus a random number.
+ * @param prefix - The prefix to prepend, defaults to ROOM_NAME_PREFIX.
+ * @param suffix - The suffix to append, defaults to ROOM_NAME_SUFFIX.
+ * @returns The lowercased room name.
+ */
+export function buildRoomName(
+ baseName: string,
+ prefix: string | undefined = testsConfig.roomName.prefix,
+ suffix: string | undefined = testsConfig.roomName.suffix) {
+ let roomName = baseName;
+
+ if (prefix) {
+ roomName = `${prefix}_${roomName}`;
+ }
+ if (suffix) {
+ roomName += `_${suffix}`;
+ }
+
+ return roomName.toLowerCase();
+}
+
export function generateRoomName(testName: string) {
if (testsConfig.roomName.name) {
return testsConfig.roomName.name;
}
const rand = (Math.floor(Math.random() * 400) + 1).toString();
- let roomName = `${testName}-${rand}`;
-
- if (testsConfig.roomName.prefix) {
- roomName = `${testsConfig.roomName.prefix}_${roomName}`;
- }
- if (testsConfig.roomName.suffix) {
- roomName += `_${testsConfig.roomName.suffix}`;
- }
- return roomName.toLowerCase();
+ return buildRoomName(`${testName}-${rand}`);
}
/**
diff --git a/tests/malleus/MalleusConfig.ts b/tests/malleus/MalleusConfig.ts
new file mode 100644
index 0000000000..71f04f4630
--- /dev/null
+++ b/tests/malleus/MalleusConfig.ts
@@ -0,0 +1,416 @@
+import path from 'node:path';
+
+import { config as testsConfig } from '../helpers/TestsConfig';
+import { buildRoomName } from '../helpers/utils';
+
+/**
+ * Where `npm run build:load-test` (at the repository root) writes the load-test client bundle.
+ */
+export const DEFAULT_LOAD_TEST_BUNDLE = path.join(__dirname, '..', '..', 'build', 'load-test-participant.min.js');
+
+/**
+ * The wrapper page for the load-test client, uploaded into the browsers together with the bundle.
+ */
+export const LOAD_TEST_PAGE = path.join(__dirname, '..', 'resources', 'loadTest.html');
+
+/**
+ * The maximum number of audio senders per browser. This is a hard-coded Chrome limit, so hard-code it here too.
+ */
+export const MAX_AUDIO_SENDERS_PER_BROWSER = 16;
+
+/**
+ * The values of the "nodename:applicationName" capability requested for senders and receivers respectively when
+ * node types are in use; the grid's node stereotypes have to declare them.
+ */
+export const SENDER_NODE_APP_NAME = 'malleusSender';
+export const RECEIVER_NODE_APP_NAME = 'malleusReceiver';
+
+/**
+ * The malleus settings. Every field comes from a MALLEUS_* environment variable; the CLI (cli.ts) maps its
+ * command line flags onto those variables before starting wdio, and the defaults below are the single source
+ * of truth for both.
+ */
+export interface IMalleusConfig {
+ /** The number of audio senders in each conference; the rest never unmute. */
+ audioSenders: number;
+
+ /** The path of the script to run in order to disrupt bridges (see blip.ts). */
+ blipScript?: string;
+
+ /** The number of conferences to run in parallel. */
+ conferences: number;
+
+ /** The number of seconds each participant stays in the conference. */
+ durationMs: number;
+
+ /** Whether P2P is enabled in the conferences. */
+ enableP2p: boolean;
+
+ /** Extra URL parameters appended to receivers' URLs, in "config.a=1&config.b=2" form. */
+ extraReceiverParams?: string;
+
+ /** Extra URL parameters appended to senders' URLs, in "config.a=1&config.b=2" form. */
+ extraSenderParams?: string;
+
+ /**
+ * Whether to mint a JaaS token for every participant with the suite's JaaS key (JAAS_KID, JAAS_PRIVATE_KEY_PATH,
+ * JAAS_TENANT). Defaults to whether that key is configured; an explicit --jwt takes precedence.
+ */
+ generateJaasTokens: boolean;
+
+ /** Whether the minted JaaS tokens make the participants moderators (which bypasses a lobby). */
+ jaasModerator: boolean;
+
+ /** The delay in milliseconds between consecutive participants joining a conference. */
+ joinDelayMs: number;
+
+ /** An optional JWT to join with. */
+ jwt?: string;
+
+ /** The built load-test client bundle to inject into the browsers in load-test mode. */
+ loadTestBundle: string;
+
+ /** The percentage of bridges to disrupt during the run; 0 disables bridge disruption. */
+ maxDisruptedBridgesPct: number;
+
+ /** The number of participants in each conference. */
+ participants: number;
+
+ /** The number of receiver tabs to open in each browser. */
+ receiverTabsPerBrowser: number;
+
+ /** The number of load-test clients to run in each receiver tab (load-test mode only). */
+ receiversPerTab: number;
+
+ /** Regions to assign to participants (round robin), via config.deploymentInfo.userRegion. */
+ regions: string[];
+
+ /** The prefix of the conference room names; the conference index is appended to it. */
+ roomNamePrefix: string;
+
+ /** Whether to save the browser logs of every participant. */
+ saveLogs: boolean;
+
+ /** The number of sender tabs to open in each browser. */
+ senderTabsPerBrowser: number;
+
+ /** The number of video senders in each conference; the rest join with video muted. */
+ senders: number;
+
+ /** The number of load-test clients to run in each sender tab (load-test mode only). */
+ sendersPerTab: number;
+
+ /** Whether to randomly switch the active speakers among the audio senders. */
+ switchSpeakers: boolean;
+
+ /** Whether receivers run in lite mode (config.flags.runInLiteMode). */
+ useLiteMode: boolean;
+
+ /** Whether to use the lightweight load-test client instead of the full Jitsi Meet application. */
+ useLoadTest: boolean;
+
+ /** Whether to request typed grid nodes (nodename:applicationName malleusSender / malleusReceiver). */
+ useNodeTypes: boolean;
+
+ /** Whether to use stage view rather than tile view. */
+ useStageView: boolean;
+}
+
+function intFromEnv(name: string, defaultValue: number): number {
+ const value = process.env[name]?.trim();
+
+ if (!value) {
+ return defaultValue;
+ }
+
+ const parsed = parseInt(value, 10);
+
+ if (Number.isNaN(parsed)) {
+ throw new Error(`${name} must be an integer, got "${value}"`);
+ }
+
+ return parsed;
+}
+
+function floatFromEnv(name: string, defaultValue: number): number {
+ const value = process.env[name]?.trim();
+
+ if (!value) {
+ return defaultValue;
+ }
+
+ const parsed = parseFloat(value);
+
+ if (Number.isNaN(parsed)) {
+ throw new Error(`${name} must be a number, got "${value}"`);
+ }
+
+ return parsed;
+}
+
+function boolFromEnv(name: string, defaultValue: boolean): boolean {
+ const value = process.env[name]?.trim();
+
+ if (!value) {
+ return defaultValue;
+ }
+
+ return value === 'true';
+}
+
+function stringFromEnv(name: string): string | undefined {
+ const value = process.env[name]?.trim();
+
+ return value || undefined;
+}
+
+/**
+ * Reads the malleus configuration from the environment and validates it.
+ */
+export function loadMalleusConfig(): IMalleusConfig {
+ const participants = intFromEnv('MALLEUS_PARTICIPANTS', 3);
+ const config: IMalleusConfig = {
+ audioSenders: intFromEnv('MALLEUS_AUDIO_SENDERS', participants),
+ blipScript: stringFromEnv('MALLEUS_BLIP_SCRIPT'),
+ conferences: intFromEnv('MALLEUS_CONFERENCES', 1),
+ durationMs: 1000 * intFromEnv('MALLEUS_DURATION', 60),
+ enableP2p: boolFromEnv('MALLEUS_ENABLE_P2P', true),
+ extraReceiverParams: stringFromEnv('MALLEUS_EXTRA_RECEIVER_PARAMS'),
+ extraSenderParams: stringFromEnv('MALLEUS_EXTRA_SENDER_PARAMS'),
+ generateJaasTokens: boolFromEnv('MALLEUS_GENERATE_JAAS_TOKENS', testsConfig.jaas.enabled),
+ jaasModerator: boolFromEnv('MALLEUS_JAAS_MODERATOR', true),
+ joinDelayMs: intFromEnv('MALLEUS_JOIN_DELAY', 0),
+ jwt: stringFromEnv('MALLEUS_JWT'),
+ loadTestBundle: stringFromEnv('MALLEUS_LOAD_TEST_BUNDLE') ?? DEFAULT_LOAD_TEST_BUNDLE,
+ maxDisruptedBridgesPct: floatFromEnv('MALLEUS_MAX_DISRUPTED_BRIDGES_PCT', 0),
+ participants,
+ receiversPerTab: intFromEnv('MALLEUS_RECEIVERS_PER_TAB', 1),
+ receiverTabsPerBrowser: intFromEnv('MALLEUS_RECEIVER_TABS_PER_BROWSER', 1),
+ regions: stringFromEnv('MALLEUS_REGIONS')?.split(',').map(r => r.trim()).filter(Boolean) ?? [],
+ roomNamePrefix: stringFromEnv('MALLEUS_ROOM_NAME_PREFIX') ?? 'anvil-',
+ saveLogs: boolFromEnv('MALLEUS_SAVE_LOGS', false),
+ senders: intFromEnv('MALLEUS_SENDERS', participants),
+ sendersPerTab: intFromEnv('MALLEUS_SENDERS_PER_TAB', 1),
+ senderTabsPerBrowser: intFromEnv('MALLEUS_SENDER_TABS_PER_BROWSER', 1),
+ switchSpeakers: boolFromEnv('MALLEUS_SWITCH_SPEAKERS', false),
+ useLoadTest: boolFromEnv('MALLEUS_USE_LOAD_TEST', false),
+ useLiteMode: boolFromEnv('MALLEUS_USE_LITE_MODE', false),
+ useNodeTypes: boolFromEnv('MALLEUS_USE_NODE_TYPES', false),
+ useStageView: boolFromEnv('MALLEUS_USE_STAGE_VIEW', false)
+ };
+
+ validateMalleusConfig(config);
+
+ return config;
+}
+
+/**
+ * Checks the settings for combinations that cannot work, so a run fails before any browser is started.
+ */
+export function validateMalleusConfig(config: IMalleusConfig): void {
+ const errors: string[] = [];
+
+ if (config.conferences < 1) {
+ errors.push('conferences must be at least 1');
+ }
+ if (config.participants < 1) {
+ errors.push('participants must be at least 1');
+ }
+ if (config.senders < 0 || config.senders > config.participants) {
+ errors.push('senders must be between 0 and the number of participants');
+ }
+ if (config.audioSenders < 0 || config.audioSenders > config.participants) {
+ errors.push('audio senders must be between 0 and the number of participants');
+ }
+ if (config.durationMs <= 0) {
+ errors.push('duration must be positive');
+ }
+ if (config.joinDelayMs < 0) {
+ errors.push('join delay must not be negative');
+ }
+ if ((config.sendersPerTab > 1 || config.receiversPerTab > 1) && !config.useLoadTest) {
+ errors.push('senders-per-tab and receivers-per-tab require load-test mode');
+ }
+ if ((config.senderTabsPerBrowser > 1 || config.receiverTabsPerBrowser > 1) && !config.useLoadTest) {
+ // The Participant page objects assume they own the browser; only the load-test client is driven with the
+ // handful of commands the tab multiplexing (TabbedSession) covers.
+ errors.push('sender-tabs-per-browser and receiver-tabs-per-browser require load-test mode');
+ }
+ if (config.sendersPerTab < 1 || config.receiversPerTab < 1) {
+ errors.push('senders-per-tab and receivers-per-tab must be at least 1');
+ }
+ if (config.senderTabsPerBrowser < 1 || config.receiverTabsPerBrowser < 1) {
+ errors.push('sender-tabs-per-browser and receiver-tabs-per-browser must be at least 1');
+ }
+ if (config.maxDisruptedBridgesPct < 0 || config.maxDisruptedBridgesPct > 100) {
+ errors.push('max-disrupted-bridges-pct must be between 0 and 100');
+ }
+
+ if (errors.length) {
+ throw new Error(`Invalid malleus configuration:\n ${errors.join('\n ')}`);
+ }
+}
+
+/**
+ * A human-readable summary of the settings, printed at the start of a run.
+ */
+export function describeMalleusConfig(config: IMalleusConfig): string {
+ return [
+ 'will run with:',
+ `conferences=${config.conferences}`,
+ `participants=${config.participants}`,
+ `senders=${config.senders}`,
+ `audio senders=${config.audioSenders}${config.switchSpeakers ? ' (switched)' : ''}`,
+ `duration=${config.durationMs}ms`,
+ `join delay=${config.joinDelayMs}ms`,
+ `room_name_prefix=${config.roomNamePrefix}`,
+ `room_name_suffix=${testsConfig.roomName.suffix ?? ''}`,
+ `enable_p2p=${config.enableP2p}`,
+ `max_disrupted_bridges_pct=${config.maxDisruptedBridgesPct}`,
+ `regions=${config.regions.length ? config.regions.join(',') : 'null'}`,
+ `stage view=${config.useStageView}`,
+ `load test=${config.useLoadTest}${config.useLiteMode ? ' (lite mode)' : ''}${
+ config.useLoadTest ? ` bundle=${config.loadTestBundle}` : ''}`,
+ `node types=${config.useNodeTypes}`,
+ `tabs per browser=${config.senderTabsPerBrowser} send / ${config.receiverTabsPerBrowser} recv`,
+ `participants per tab=${config.sendersPerTab} send / ${config.receiversPerTab} recv`,
+ `jwt=${config.jwt ? 'given' : config.generateJaasTokens
+ ? `generated per participant (JaaS${config.jaasModerator ? ', moderator' : ''})` : 'none'}`,
+ `extra sender params=${config.extraSenderParams ?? ''}`,
+ `extra receiver params=${config.extraReceiverParams ?? ''}`
+ ].join('\n');
+}
+
+/**
+ * The room name of a conference. The suite's ROOM_NAME_SUFFIX may hold a comma-separated list, in which case
+ * conferences are spread over the suffixes round robin (e.g. to pin different conferences to different shards).
+ */
+export function malleusRoomName(config: IMalleusConfig, conferenceIndex: number): string {
+ const suffixes = testsConfig.roomName.suffix?.split(',').map(s => s.trim()).filter(Boolean) ?? [];
+ const suffix = suffixes.length ? suffixes[conferenceIndex % suffixes.length] : undefined;
+
+ return buildRoomName(`${config.roomNamePrefix}${conferenceIndex}`, testsConfig.roomName.prefix, suffix);
+}
+
+/**
+ * A participant's role in the run.
+ */
+export interface IMalleusRole {
+ /** Whether the participant unmutes audio (or is eligible to when speakers are switched). */
+ audioSender: boolean;
+
+ /** The multiremote instance name of the browser the participant runs in. */
+ browser: string;
+
+ /** The conference index. */
+ conference: number;
+
+ /** The participant index within the conference. */
+ index: number;
+
+ /** The number of load-test clients sharing this participant's tab (1 unless in load-test mode). */
+ numClients: number;
+
+ /** The region to report via config.deploymentInfo.userRegion, if any. */
+ region?: string;
+
+ /** Whether the participant sends video. */
+ sender: boolean;
+
+ /** The index of the participant's tab within its browser. */
+ tab: number;
+}
+
+/**
+ * A browser session and the participants (tabs) it runs.
+ */
+export interface IMalleusBrowser {
+ /** The multiremote instance name. */
+ instance: string;
+
+ /** Whether the browser runs video senders (as opposed to receivers), for grid node typing. */
+ sender: boolean;
+
+ /** The participants, in tab order. */
+ tabs: IMalleusRole[];
+}
+
+/**
+ * Lays out the participants of one conference: the
+ * first `senders` participants send video, audio senders are filled from the start of the list, and in
+ * load-test mode consecutive participants of the same kind are packed into one tab.
+ */
+export function layoutConference(config: IMalleusConfig, conference: number): IMalleusRole[] {
+ const roles: IMalleusRole[] = [];
+ let audioSenders = 0;
+
+ for (let i = 0; i < config.participants;) {
+ const sender = i < config.senders;
+ const audioSender = audioSenders < config.audioSenders;
+ let numClients = sender ? config.sendersPerTab : config.receiversPerTab;
+
+ if (sender && i + numClients > config.senders) {
+ numClients = config.senders - i;
+ }
+ if (audioSender && audioSenders + numClients > config.audioSenders) {
+ numClients = config.audioSenders - audioSenders;
+ }
+ if (i + numClients > config.participants) {
+ numClients = config.participants - i;
+ }
+
+ roles.push({
+ audioSender,
+ browser: '',
+ conference,
+ index: i,
+ numClients,
+ region: config.regions.length ? config.regions[i % config.regions.length] : undefined,
+ sender,
+ tab: 0
+ });
+
+ i += numClients;
+ if (audioSender) {
+ audioSenders += numClients;
+ }
+ }
+
+ return roles;
+}
+
+/**
+ * Groups the participants of one conference into browser sessions: senders `senderTabsPerBrowser` to a browser
+ * and the rest `receiverTabsPerBrowser` to a browser, never mixing the two (they may run on differently typed
+ * grid nodes). Fills in the roles' browser and tab fields.
+ */
+export function layoutBrowsers(config: IMalleusConfig, conference: number): IMalleusBrowser[] {
+ const browsers: IMalleusBrowser[] = [];
+ let current: IMalleusBrowser | undefined;
+
+ for (const role of layoutConference(config, conference)) {
+ const tabsPerBrowser = role.sender ? config.senderTabsPerBrowser : config.receiverTabsPerBrowser;
+
+ if (!current || current.sender !== role.sender || current.tabs.length >= tabsPerBrowser) {
+ current = {
+ instance: `c${conference}b${browsers.length}`,
+ sender: role.sender,
+ tabs: []
+ };
+ browsers.push(current);
+ }
+
+ role.browser = current.instance;
+ role.tab = current.tabs.length;
+ current.tabs.push(role);
+ }
+
+ return browsers;
+}
+
+/**
+ * The name of a participant, for logging: conference and participant index.
+ */
+export function participantName(role: IMalleusRole): string {
+ return `c${role.conference}p${role.index}`;
+}
diff --git a/tests/malleus/MalleusParticipant.ts b/tests/malleus/MalleusParticipant.ts
new file mode 100644
index 0000000000..94df24b853
--- /dev/null
+++ b/tests/malleus/MalleusParticipant.ts
@@ -0,0 +1,358 @@
+import { IConfig } from '../../react/features/base/config/configType';
+import { Participant } from '../helpers/Participant';
+import { generateJaasToken } from '../helpers/jaas';
+import { IToken } from '../helpers/token';
+
+import {
+ IMalleusConfig,
+ IMalleusRole,
+ MAX_AUDIO_SENDERS_PER_BROWSER,
+ participantName
+} from './MalleusConfig';
+import type { TabbedSession } from './TabbedSession';
+import type { BridgeSelection } from './blip';
+
+const HEALTH_CHECK_INTERVAL_MS = 5000;
+
+/**
+ * Every malleus participant created in this worker, across conferences, in creation order. The wdio hooks in
+ * wdio.malleus.conf.ts use it to hang everybody up when the run fails.
+ */
+export const allMalleusParticipants: MalleusParticipant[] = [];
+
+function sleep(ms: number): Promise<void> {
+ return new Promise(resolve => {
+ setTimeout(resolve, ms);
+ });
+}
+
+/**
+ * Normalizes an extra URL parameters string ("config.a=1&config.b=2", possibly with a leading '&' or '#') so it
+ * can be appended to a join URL which already has a hash.
+ */
+function extraParamsToAppendString(params?: string): string | undefined {
+ const trimmed = params?.trim().replace(/^[#&]+/, '');
+
+ return trimmed ? `&${trimmed}` : undefined;
+}
+
+/**
+ * One malleus participant: joins its conference after its offset, stays for the duration and hangs up.
+ */
+export class MalleusParticipant {
+ readonly role: IMalleusRole;
+ readonly roomName: string;
+
+ /**
+ * The test-suite participant driving the browser (tab). With a TabbedSession it only exists once the tab has
+ * been opened, which happens when the participant starts.
+ */
+ participant!: Participant;
+
+ private readonly config: IMalleusConfig;
+ private readonly joinOffsetMs: number;
+ private readonly session?: TabbedSession;
+
+ /**
+ * Whether the participant is currently in the conference (joined and not yet hung up).
+ */
+ running = false;
+
+ /**
+ * Whether audio is currently muted. Kept here so the speaker switcher can toggle without reading the UI.
+ */
+ audioMuted: boolean;
+
+ /**
+ * Whether this participant is allowed to unmute (it did GUM at startup).
+ */
+ audioSender: boolean;
+
+ /**
+ * The IP of the bridge the participant is connected to, once known.
+ */
+ bridgeIp?: string;
+
+ /**
+ * Whether ICE failures against a bridge from `bridgesToFail` are to be tolerated as expected reconnects.
+ */
+ bridgesToFail?: Set<string>;
+
+ /**
+ * Where to report the bridge after joining, when bridges are going to be disrupted.
+ */
+ bridgeSelection?: BridgeSelection;
+
+ /**
+ * @param config - The run's settings.
+ * @param role - The participant's role.
+ * @param roomName - The conference to join.
+ * @param driver - The browser session to drive, when the participant has one to itself.
+ * @param session - The browser session shared with other participants, when running one per tab.
+ */
+ constructor( // eslint-disable-line max-params
+ config: IMalleusConfig,
+ role: IMalleusRole,
+ roomName: string,
+ driver?: WebdriverIO.Browser,
+ session?: TabbedSession) {
+ this.config = config;
+ this.role = role;
+ this.roomName = roomName;
+ this.joinOffsetMs = role.index * config.joinDelayMs;
+ this.audioSender = role.audioSender;
+ this.session = session;
+
+ if (role.tab >= MAX_AUDIO_SENDERS_PER_BROWSER && role.audioSender) {
+ // Chrome can't support more than that many audio sender tabs per browser, so this one doesn't send.
+ console.log(`${participantName(role)} is tab ${role.tab} of its browser, not sending audio`);
+ this.audioSender = false;
+ }
+
+ // Speaker switching starts everybody muted and unmutes on demand; otherwise audio senders start unmuted.
+ this.audioMuted = config.switchSpeakers || !this.audioSender;
+
+ if (driver) {
+ this.participant = this.createParticipant(driver);
+ }
+
+ allMalleusParticipants.push(this);
+ }
+
+ private createParticipant(driver: WebdriverIO.Browser): Participant {
+ return new Participant({
+ driver,
+ loadTest: this.config.useLoadTest,
+ name: this.name,
+ token: this.token()
+ });
+ }
+
+ /**
+ * The token to join with: the one given, or a freshly minted JaaS one (with its own user id, so the deployment
+ * sees distinct users) valid for the whole run.
+ */
+ private token(): IToken | undefined {
+ const { config } = this;
+
+ if (config.jwt) {
+ return { jwt: config.jwt };
+ }
+ if (!config.generateJaasTokens) {
+ return undefined;
+ }
+
+ const runMinutes = Math.ceil((config.durationMs + config.joinDelayMs * config.participants) / 60_000);
+
+ return generateJaasToken({
+ displayName: this.name,
+ exp: `${runMinutes + 60}m`,
+ moderator: config.jaasModerator
+ });
+ }
+
+ /**
+ * The name of the participant, for logging.
+ */
+ get name(): string {
+ return participantName(this.role);
+ }
+
+ /**
+ * The config overrides this participant joins with.
+ */
+ private buildConfigOverwrite(): IConfig {
+ const { config, role } = this;
+ const overwrite: IConfig = {
+ // XXX Carried over from the original malleus: "I don't remember if/why these are needed."
+ p2p: {
+ enabled: config.enableP2p
+ },
+ disable1On1Mode: false,
+ testing: {
+ noAutoPlayVideo: true,
+ testMode: true
+ },
+ pcStatsInterval: 10000
+ };
+
+ if (config.useStageView) {
+ overwrite.disableTileView = true;
+ }
+ if (!this.audioSender) {
+ // Don't do GUM before unmuting.
+ overwrite.disableInitialGUM = true;
+ }
+ if (!role.sender) {
+ overwrite.startWithVideoMuted = true;
+ }
+ if (this.audioMuted) {
+ overwrite.startWithAudioMuted = true;
+ }
+ if (!role.sender && config.useLiteMode) {
+ // A lib-jitsi-meet feature flag, passed through config.flags; not part of jitsi-meet's own config type.
+ overwrite.flags = { runInLiteMode: true } as unknown as IConfig['flags'];
+ }
+ if (role.region) {
+ overwrite.deploymentInfo = { userRegion: role.region };
+ }
+
+ return overwrite;
+ }
+
+ /**
+ * Runs the whole lifecycle: wait for the join offset, join, stay for the duration, hang up.
+ *
+ * @param healthCheck - Whether to periodically verify the participant is still connected.
+ */
+ async run(healthCheck: boolean): Promise<void> {
+ await sleep(this.joinOffsetMs);
+
+ try {
+ if (!this.participant) {
+ this.participant = this.createParticipant(await this.session!.openTab(this.role.tab));
+ }
+ await this.join();
+
+ if (this.bridgeSelection) {
+ this.bridgeIp = await this.getBridgeIp();
+ this.bridgeSelection.report(this.bridgeIp);
+ }
+ } catch (e) {
+ // Don't hold up the bridge disruption waiting for a participant that never made it.
+ this.bridgeSelection?.report();
+
+ // The page may have joined after the check gave up; don't leave a ghost in the conference.
+ await this.finish();
+ throw e;
+ }
+
+ const leaveAt = Date.now() + this.config.durationMs;
+
+ try {
+ if (healthCheck) {
+ while (Date.now() < leaveAt) {
+ await sleep(Math.min(HEALTH_CHECK_INTERVAL_MS, Math.max(0, leaveAt - Date.now())));
+ if (Date.now() < leaveAt) {
+ await this.check();
+ }
+ }
+ } else {
+ await sleep(this.config.durationMs);
+ }
+ } finally {
+ await this.finish();
+ }
+ }
+
+ private async join(): Promise<void> {
+ const { config, role } = this;
+
+ console.log(`${this.name} is joining ${this.roomName}`);
+
+ let urlAppendString = extraParamsToAppendString(
+ role.sender ? config.extraSenderParams : config.extraReceiverParams) ?? '';
+
+ if (role.numClients !== 1) {
+ urlAppendString += `&numClients=${role.numClients}&clientInterval=${config.joinDelayMs}`;
+ }
+
+ await this.participant.joinConference({
+ configOverwrite: this.buildConfigOverwrite(),
+ roomName: this.roomName,
+ skipDisplayName: true,
+ urlAppendString: urlAppendString || undefined
+ });
+
+ this.running = true;
+ console.log(`${this.name} joined ${this.roomName}`);
+ }
+
+ private async finish(): Promise<void> {
+ this.running = false;
+
+ try {
+ await this.participant.hangup();
+ } catch (e) {
+ console.error(`Exception hanging up ${this.name}`, e);
+ }
+ }
+
+ /**
+ * Verifies the participant is still connected to the bridge, tolerating a reconnect when its bridge is one
+ * of those being deliberately disrupted.
+ */
+ private async check(): Promise<void> {
+ try {
+ await this.participant.waitForIceConnected();
+ } catch (e) {
+ console.log(`${this.name} is NOT connected.`);
+
+ if (!this.bridgeIp || !this.bridgesToFail?.has(this.bridgeIp)) {
+ throw e;
+ }
+
+ // Wait for the reconnect.
+ await this.participant.driver.waitUntil(
+ () => this.participant.execute(() => APP?.conference?.getConnectionState() === 'connected'), {
+ timeout: 20_000,
+ timeoutMsg: `${this.name} did not reconnect after its bridge was disrupted`
+ });
+ console.log(`${this.name} reconnected.`);
+ }
+ }
+
+ /**
+ * Mutes or unmutes the participant's audio. In load-test mode with several clients per tab, `clientIndex`
+ * selects the client; otherwise all clients of the tab (i.e. the single participant) are affected.
+ */
+ async muteAudio(mute: boolean, clientIndex?: number): Promise<void> {
+ if (clientIndex === undefined) {
+ // The application's muteAudio takes (mute, showUI), so don't pass a second argument.
+ await this.participant.execute(m => {
+ APP.conference.muteAudio(m);
+ }, mute);
+ } else {
+ await this.participant.execute((m, num) => {
+ // @ts-ignore The load-test client's muteAudio takes the client index.
+ APP.conference.muteAudio(m, num);
+ }, mute, clientIndex);
+ }
+ this.audioMuted = mute;
+ }
+
+ /**
+ * The IP of the bridge the participant is connected to. With the default stats interval this can take a
+ * while to show up in the stats, so waits up to 30 seconds. Returns undefined for a P2P connection.
+ */
+ async getBridgeIp(): Promise<string | undefined> {
+ let socket: string | undefined;
+
+ await this.participant.driver.waitUntil(async () => {
+ const transport = await this.participant.execute(
+ () => APP?.conference?.getStats()?.transport as Array<{ ip?: string; p2p?: boolean; }> | undefined);
+
+ if (!transport?.length) {
+ return false;
+ }
+ if (transport[0].p2p) {
+ return true;
+ }
+ socket = transport[0].ip;
+
+ return Boolean(socket);
+ }, {
+ timeout: 30_000,
+ timeoutMsg: `Timeout waiting for the bridge address of ${this.name}`
+ });
+
+ if (!socket) {
+ return undefined;
+ }
+
+ // "ip:port" or "[ipv6]:port".
+ const bracket = socket.match(/^\[([^\]]+)\]/);
+
+ return bracket ? bracket[1] : socket.split(':')[0];
+ }
+}
diff --git a/tests/malleus/README.md b/tests/malleus/README.md
new file mode 100644
index 0000000000..2c1bf39039
--- /dev/null
+++ b/tests/malleus/README.md
@@ -0,0 +1,83 @@
+# Malleus Jitsificus
+
+The jitsi-meet load tester: it fills one or more conferences on a deployment with browser-driven participants for
+a while and reports whether they all made it. It reuses the regular WebdriverIO test suite (Chrome setup, grid
+support, `Participant`, browser logs) but is not part of the regular runs.
+
+## Running
+
+Install the tests' dependencies once (`npm install` in this directory), then:
+
+```
+npm run malleus -- --instance-url=https://meet.example.com/ --participants=20 --senders=5 --duration=300
+npm run malleus -- --help
+```
+
+Every flag maps onto an environment variable (see `--help` and `env.example`), so a run can also be configured
+in `.env`; a flag wins over the environment. The regular suite's settings apply too: `BASE_URL`, `GRID_HOST_URL`,
+`HEADLESS`, `ALLOW_INSECURE_CERTS`, `VIDEO_CAPTURE_FILE`, `ROOM_NAME_PREFIX`, `ROOM_NAME_SUFFIX`. Room names are
+built as `<prefix><conference index><suffix>`, with the suffix last so that infrastructure which pins a room to a
+release by a shard name at the end of the room name keeps working; a comma-separated `ROOM_NAME_SUFFIX`
+(`--room-name-suffix=a,b`) spreads the conferences over the suffixes.
+
+`scripts/malleus.sh` forwards its arguments to `npm run malleus`, for callers that expect a shell script.
+
+## What a run does
+
+- `--conferences` conferences run in parallel, each with `--participants` participants. The first `--senders` send
+ video, the rest join video muted; `--audio-senders` of them send audio, the rest never do GUM.
+- Participants join `--join-delay` milliseconds apart, stay `--duration` seconds and hang up. Any participant that
+ fails to join (or, when bridges are disrupted, to stay connected) fails the run, after everybody has been given
+ the chance to finish.
+- `--switch-speakers` mutes and unmutes the audio senders following the ITU-T P.59 conversation model.
+- `--max-disrupted-bridges-pct` collects the bridges the participants land on and hands that percentage of them to
+ the blip script (`scripts/blip.sh`, a placeholder to replace with one for your infrastructure, or
+ `--blip-script`), then checks the participants stay or get back connected.
+- Participants join with `--jwt` if given; otherwise, when the suite's JaaS key is configured (`JAAS_KID`,
+ `JAAS_PRIVATE_KEY_PATH`, `JAAS_TENANT`), each participant gets its own freshly minted JaaS token, so
+ tenant deployments that require tokens work out of the box. The tokens are moderator tokens so that a lobby
+ does not hold the participants back (`--jaas-moderator=false` to change that); `--generate-jaas-tokens=false`
+ turns the minting off.
+- `--regions` assigns `config.deploymentInfo.userRegion` values round robin; `--extra-sender-params` and
+ `--extra-receiver-params` append raw `config.x=y` URL parameters; `--use-stage-view` disables tile view.
+
+## Load-test mode
+
+`--use-load-test` replaces the full application with the lightweight client in `react/features/load-test`, which
+only uses lib-jitsi-meet and can run several participants per tab (`--senders-per-tab`, `--receivers-per-tab`)
+and several tabs per browser (`--sender-tabs-per-browser`, `--receiver-tabs-per-browser`). Nothing has to be
+installed on the deployment: the client is uploaded into each browser together with `resources/loadTest.html`,
+which loads `config.js` and lib-jitsi-meet from the deployment under test. `--use-lite-mode` makes the receivers
+run lib-jitsi-meet in lite mode.
+
+The client asks the bridge for the same video as a real jitsi-meet client would in the common case (no pinning,
+no screen sharing, default filmstrip): only the sources on the first page of tiles, at the quality the tile size
+for a 1280x1024 window allows, or in stage view the on-stage source at large-video quality plus the first
+filmstrip page of thumbnails, with `defaultConstraints` 0 and lastN from the config (-1 by default). The window
+size can be changed with the `windowWidth` and `windowHeight` page parameters, e.g.
+`--extra-receiver-params='windowWidth=1920&windowHeight=1080'`.
+
+The client bundle is built with `npm run build:load-test` at the repository root (into
+`build/load-test-participant.min.js`); the CLI builds it when it is missing. `--load-test-bundle` points at a
+build elsewhere, for machines that only have `tests/` installed. The bundle is deliberately not part of the
+deployed application.
+
+Since the client runs from a `file://` page, deployments that only offer BOSH need CORS headers on `/http-bind`;
+WebSocket, the default on modern deployments, has no such restriction.
+
+## Grid
+
+`--hub-url` runs the browsers on a Selenium Grid. With `--use-node-types` the browsers of video senders (which
+need CPU) request the capability `nodename:applicationName` = `malleusSender` and all the others `malleusReceiver`,
+so that the two can be routed to differently sized node pools. The grid has to declare those values in the
+stereotypes of the nodes meant for each role; nothing on the grid is changed by a run.
+
+## Layout
+
+- `cli.ts`: the command line, flags to environment, builds the bundle, then runs wdio.
+- `../wdio.malleus.conf.ts`: the wdio config, generating one browser session per `layoutBrowsers()` entry.
+- `malleus.spec.ts`: the single spec: one async task per conference.
+- `MalleusConfig.ts`: settings, validation and the participant / browser layout.
+- `MalleusParticipant.ts`: one participant's lifecycle (offset, join, health check, hang up).
+- `TabbedSession.ts`: several participants per browser session, one per tab.
+- `speakers.ts`, `blip.ts`: speaker switching and bridge disruption.
diff --git a/tests/malleus/TabbedSession.ts b/tests/malleus/TabbedSession.ts
new file mode 100644
index 0000000000..81dae3ea14
--- /dev/null
+++ b/tests/malleus/TabbedSession.ts
@@ -0,0 +1,97 @@
+/**
+ * Runs several participants in one browser session, one per tab.
+ *
+ * Every WebDriver command a tab's participant issues is serialized with the other tabs' commands and preceded,
+ * when needed, by a switch to the tab's window handle. Commands that are plain JS loops around other commands
+ * (waitUntil) are not serialized themselves, or they would deadlock on the commands they issue.
+ */
+/**
+ * Browser methods that must not be serialized: they are not WebDriver commands but helpers that call other
+ * (serialized) commands, or event-emitter plumbing that is not tab specific.
+ */
+const PASSTHROUGH: Set<string | symbol> = new Set([
+ 'waitUntil', 'pause', 'call', 'debug',
+ 'on', 'once', 'off', 'emit', 'addListener', 'removeListener', 'removeAllListeners', 'listeners',
+ 'addCommand', 'overwriteCommand', 'sessionSubscribe', 'sessionUnsubscribe',
+ 'then', 'catch', 'finally'
+]);
+
+export class TabbedSession {
+ readonly browser: WebdriverIO.Browser;
+
+ private tabs: string[] = [];
+ private currentTab?: string;
+ private lock: Promise<unknown> = Promise.resolve();
+
+ constructor(browser: WebdriverIO.Browser) {
+ this.browser = browser;
+ }
+
+ /**
+ * Runs `fn` while holding the session's lock, i.e. with no other tab's command in flight.
+ */
+ private withLock<T>(fn: () => Promise<T>): Promise<T> {
+ const run = this.lock.then(fn, fn);
+
+ this.lock = run.catch(() => undefined);
+
+ return run;
+ }
+
+ /**
+ * Makes sure the browser is on the given tab. Must be called with the lock held.
+ */
+ private async switchTo(handle: string): Promise<void> {
+ if (this.currentTab !== handle) {
+ await this.browser.switchToWindow(handle);
+ this.currentTab = handle;
+ }
+ }
+
+ /**
+ * Opens the tab with the given index (the first one is the browser's initial tab) and returns a driver bound to
+ * it. Tabs are opened in order, so this is meant to be called with 0, 1, 2... as participants start.
+ */
+ async openTab(index: number): Promise<WebdriverIO.Browser> {
+ await this.withLock(async () => {
+ if (this.tabs.length === 0) {
+ this.tabs.push(await this.browser.getWindowHandle());
+ this.currentTab = this.tabs[0];
+ }
+ while (this.tabs.length <= index) {
+ // Creating a window does not make it the current browsing context (WebDriver "New Window"), so
+ // switch explicitly; the tab's first command would otherwise run in whatever tab was current.
+ const { handle } = await this.browser.createWindow('tab');
+
+ await this.browser.switchToWindow(handle);
+ this.tabs.push(handle);
+ this.currentTab = handle;
+ }
+ });
+
+ return this.tabDriver(this.tabs[index]);
+ }
+
+ /**
+ * A proxy of the browser whose commands run on the given tab.
+ */
+ private tabDriver(handle: string): WebdriverIO.Browser {
+ const { browser } = this;
+
+ return new Proxy(browser, {
+ get: (target, prop, receiver) => {
+ const value = Reflect.get(target, prop, receiver);
+
+ if (typeof value !== 'function' || PASSTHROUGH.has(prop)) {
+ return value;
+ }
+
+ return (...args: unknown[]) => this.withLock(async () => {
+ await this.switchTo(handle);
+
+ return value.apply(target, args);
+ });
+ }
+ });
+ }
+}
diff --git a/tests/malleus/blip.ts b/tests/malleus/blip.ts
new file mode 100644
index 0000000000..305706a203
--- /dev/null
+++ b/tests/malleus/blip.ts
@@ -0,0 +1,99 @@
+import { spawn } from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+
+import { MalleusParticipant } from './MalleusParticipant';
+
+/**
+ * The script run to disrupt bridges when no MALLEUS_BLIP_SCRIPT is given. The copy in the repository is a
+ * placeholder; it has to be replaced with one that knows the infrastructure under test. It gets
+ * --duration=<seconds> and --bridge-ips=<ip>[,<ip>...].
+ */
+const DEFAULT_BLIP_SCRIPT = path.join(__dirname, '..', 'scripts', 'blip.sh');
+
+/**
+ * Collects the bridge every participant of a conference ends up on, and resolves once all of them have
+ * reported (or failed to join, which counts as a report so the disruption is not held up forever).
+ */
+export class BridgeSelection {
+ readonly bridges = new Set<string>();
+ readonly allReported: Promise<void>;
+
+ private pending: number;
+ private resolveAll!: () => void;
+
+ constructor(expectedReports: number) {
+ this.pending = expectedReports;
+ this.allReported = new Promise<void>(resolve => {
+ this.resolveAll = resolve;
+ });
+ if (this.pending === 0) {
+ this.resolveAll();
+ }
+ }
+
+ /**
+ * Records a participant's bridge, or just the fact that it will not report one.
+ */
+ report(bridgeIp?: string): void {
+ if (bridgeIp) {
+ this.bridges.add(bridgeIp);
+ }
+ this.pending--;
+ if (this.pending <= 0) {
+ this.resolveAll();
+ }
+ }
+}
+
+/**
+ * Runs the blip script against the given bridges for the given number of seconds.
+ */
+export function runBlipScript(bridges: Set<string>, durationSeconds: number, script?: string): Promise<void> {
+ const file = path.resolve(script || DEFAULT_BLIP_SCRIPT);
+
+ try {
+ fs.accessSync(file, fs.constants.X_OK);
+ } catch {
+ return Promise.reject(new Error(`Could not find or could not execute the blip script: ${file}`));
+ }
+
+ return new Promise<void>((resolve, reject) => {
+ const child = spawn(file, [ `--duration=${durationSeconds}`, `--bridge-ips=${[ ...bridges ].join(',')}` ], {
+ stdio: 'inherit'
+ });
+
+ child.on('error', reject);
+ child.on('exit', code => {
+ if (code === 0) {
+ resolve();
+ } else {
+ reject(new Error(`The blip script has failed with status ${code}.`));
+ }
+ });
+ });
+}
+
+/**
+ * Once every participant has reported its bridge, picks `maxDisruptedPct` percent of the bridges (rounded up),
+ * marks them as expected to fail on all the participants, and runs the blip script against them.
+ */
+export async function disruptBridges(
+ participants: MalleusParticipant[],
+ selection: BridgeSelection,
+ maxDisruptedPct: number,
+ durationSeconds: number,
+ script?: string): Promise<void> {
+ await selection.allReported;
+
+ const count = Math.ceil(selection.bridges.size * maxDisruptedPct / 100);
+ const bridgesToFail = new Set([ ...selection.bridges ].slice(0, count));
+
+ console.log(`Disrupting ${bridgesToFail.size} of ${selection.bridges.size} bridges: ${[ ...bridgesToFail ].join(', ')}`);
+
+ participants.forEach(p => {
+ p.bridgesToFail = bridgesToFail;
+ });
+
+ await runBlipScript(bridgesToFail, durationSeconds, script);
+}
diff --git a/tests/malleus/cli.ts b/tests/malleus/cli.ts
new file mode 100644
index 0000000000..7458d5b062
--- /dev/null
+++ b/tests/malleus/cli.ts
@@ -0,0 +1,211 @@
+/* eslint-disable no-console */
+/**
+ * The command line entry point of Malleus Jitsificus, the jitsi-meet load tester: `npm run malleus -- [flags]`
+ * from tests/. Maps the flags onto the environment variables that wdio.malleus.conf.ts and MalleusConfig.ts read,
+ * validates them, builds the load-test client if needed, and runs wdio.
+ */
+import 'dotenv/config';
+
+import { spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+import process from 'node:process';
+import { parseArgs } from 'node:util';
+
+import type { IMalleusConfig } from './MalleusConfig';
+
+interface IFlag {
+ /** Whether the flag is a boolean; it can then be given without a value, meaning true. */
+ boolean?: boolean;
+ description: string;
+ /** The environment variable the flag maps onto. */
+ env: string;
+}
+
+const FLAGS: Record<string, IFlag> = {
+ 'conferences': { description: 'number of conferences to run in parallel', env: 'MALLEUS_CONFERENCES' },
+ 'participants': { description: 'number of participants in each conference', env: 'MALLEUS_PARTICIPANTS' },
+ 'senders': { description: 'number of video senders per conference (default: all)', env: 'MALLEUS_SENDERS' },
+ 'audio-senders': {
+ description: 'number of audio senders per conference (default: all)', env: 'MALLEUS_AUDIO_SENDERS' },
+ 'duration': { description: 'seconds each participant stays in the conference', env: 'MALLEUS_DURATION' },
+ 'join-delay': { description: 'milliseconds between participants joining', env: 'MALLEUS_JOIN_DELAY' },
+ 'room-name-prefix': { description: 'room name prefix (default: anvil-)', env: 'MALLEUS_ROOM_NAME_PREFIX' },
+ 'room-name-suffix': {
+ description: 'room name suffix(es), comma-separated, e.g. to pin conferences to shards', env: 'ROOM_NAME_SUFFIX' },
+ 'instance-url': {
+ description: 'the jitsi-meet deployment to test (default: https://alpha.jitsi.net/torture/)', env: 'BASE_URL' },
+ 'hub-url': { description: 'the Selenium Grid hub URL (default: run browsers locally)', env: 'GRID_HOST_URL' },
+ 'regions': {
+ description: 'comma-separated regions to assign to participants round robin', env: 'MALLEUS_REGIONS' },
+ 'enable-p2p': { boolean: true, description: 'enable P2P (default: true)', env: 'MALLEUS_ENABLE_P2P' },
+ 'use-stage-view': { boolean: true, description: 'use stage view instead of tile view', env: 'MALLEUS_USE_STAGE_VIEW' },
+ 'switch-speakers': {
+ boolean: true, description: 'randomly switch the active speakers', env: 'MALLEUS_SWITCH_SPEAKERS' },
+ 'use-load-test': {
+ boolean: true, description: 'use the lightweight load-test client instead of the full app',
+ env: 'MALLEUS_USE_LOAD_TEST' },
+ 'use-lite-mode': { boolean: true, description: 'run receivers in lite mode', env: 'MALLEUS_USE_LITE_MODE' },
+ 'senders-per-tab': {
+ description: 'load-test clients per sender tab (load-test mode only)', env: 'MALLEUS_SENDERS_PER_TAB' },
+ 'receivers-per-tab': {
+ description: 'load-test clients per receiver tab (load-test mode only)', env: 'MALLEUS_RECEIVERS_PER_TAB' },
+ 'sender-tabs-per-browser': { description: 'sender tabs per browser', env: 'MALLEUS_SENDER_TABS_PER_BROWSER' },
+ 'receiver-tabs-per-browser': {
+ description: 'receiver tabs per browser', env: 'MALLEUS_RECEIVER_TABS_PER_BROWSER' },
+ 'use-node-types': {
+ boolean: true,
+ description: 'request grid nodes typed nodename:applicationName=malleusSender/malleusReceiver',
+ env: 'MALLEUS_USE_NODE_TYPES' },
+ 'max-disrupted-bridges-pct': {
+ description: 'percentage of bridges to disrupt with the blip script', env: 'MALLEUS_MAX_DISRUPTED_BRIDGES_PCT' },
+ 'blip-script': { description: 'the script that disrupts bridges (default: scripts/blip.sh)', env: 'MALLEUS_BLIP_SCRIPT' },
+ 'extra-sender-params': {
+ description: 'extra URL params for senders, e.g. config.a=1&config.b=2', env: 'MALLEUS_EXTRA_SENDER_PARAMS' },
+ 'extra-receiver-params': {
+ description: 'extra URL params for receivers, e.g. config.a=1&config.b=2', env: 'MALLEUS_EXTRA_RECEIVER_PARAMS' },
+ 'jwt': {
+ description: 'a JWT to join with (default: mint a JaaS token per participant if JAAS_* is configured, else none)',
+ env: 'MALLEUS_JWT' },
+ 'jaas-moderator': {
+ boolean: true, description: 'minted JaaS tokens are moderator tokens, bypassing a lobby (default: true)',
+ env: 'MALLEUS_JAAS_MODERATOR' },
+ 'generate-jaas-tokens': {
+ boolean: true, description: 'mint a JaaS token per participant with the JAAS_* key (default: if configured)',
+ env: 'MALLEUS_GENERATE_JAAS_TOKENS' },
+ 'load-test-bundle': {
+ description: 'a built load-test client bundle (default: build/load-test-participant.min.js, built if missing)',
+ env: 'MALLEUS_LOAD_TEST_BUNDLE' },
+ 'video-file': {
+ description: 'the y4m file to use as the fake camera (default: Chrome\'s generated video)',
+ env: 'VIDEO_CAPTURE_FILE' },
+ 'headless': { boolean: true, description: 'run the browsers headless', env: 'HEADLESS' },
+ 'allow-insecure-certs': { boolean: true, description: 'ignore certificate errors', env: 'ALLOW_INSECURE_CERTS' },
+ 'save-logs': { boolean: true, description: 'save the browser logs of every participant', env: 'MALLEUS_SAVE_LOGS' },
+ 'debug': { boolean: true, description: 'enable debug logging', env: 'JITSI_DEBUG' }
+};
+
+function usage(): string {
+ const width = Math.max(...Object.keys(FLAGS).map(f => f.length)) + 2;
+ const lines = Object.entries(FLAGS).map(([ flag, { boolean, description, env } ]) =>
+ ` --${flag}${boolean ? '[=BOOL]' : '=VALUE'}`.padEnd(width + 12) + `${description} [${env}]`);
+
+ return [
+ 'Usage: npm run malleus -- [--flag=value ...]',
+ '',
+ 'Every flag maps onto an environment variable (in brackets), which can be set in .env instead;',
+ 'the flag wins. Boolean flags given without a value mean true.',
+ '',
+ ...lines
+ ].join('\n');
+}
+
+/**
+ * Applies the flags to the environment. Returns false if they could not be parsed.
+ */
+function applyFlags(argv: string[]): boolean {
+ // parseArgs cannot express "string, but the value is optional", so give boolean flags without a value one.
+ const normalized = argv.map(arg => {
+ const name = arg.replace(/^--/, '');
+
+ return arg.startsWith('--') && FLAGS[name]?.boolean ? `--${name}=true` : arg;
+ });
+
+ let values: Record<string, string | undefined>;
+
+ try {
+ ({ values } = parseArgs({
+ args: normalized,
+ options: Object.fromEntries([
+ ...Object.keys(FLAGS).map(flag => [ flag, { type: 'string' } ]),
+ [ 'help', { type: 'boolean', short: 'h' } ]
+ ]),
+ strict: true
+ }) as { values: Record<string, string | undefined>; });
+ } catch (e) {
+ console.error((e as Error).message);
+
+ return false;
+ }
+
+ if (values.help) {
+ console.log(usage());
+ process.exit(0);
+ }
+
+ for (const [ flag, value ] of Object.entries(values)) {
+ if (value !== undefined) {
+ process.env[FLAGS[flag].env] = value;
+ }
+ }
+
+ return true;
+}
+
+/**
+ * Builds the load-test client bundle if the default one is missing (needs the repository's dependencies).
+ */
+function ensureLoadTestBundle(config: IMalleusConfig): void {
+ if (fs.existsSync(config.loadTestBundle)) {
+ return;
+ }
+
+ const { DEFAULT_LOAD_TEST_BUNDLE } = require('./MalleusConfig');
+
+ if (config.loadTestBundle !== DEFAULT_LOAD_TEST_BUNDLE) {
+ throw new Error(`The load-test client bundle is missing: ${config.loadTestBundle}`);
+ }
+
+ console.log('Building the load-test client bundle...');
+
+ const result = spawnSync('npm', [ 'run', 'build:load-test' ], {
+ cwd: path.join(__dirname, '..', '..'),
+ stdio: 'inherit'
+ });
+
+ if (result.status !== 0 || !fs.existsSync(config.loadTestBundle)) {
+ throw new Error('Building the load-test client bundle failed; is this a full jitsi-meet checkout with '
+ + 'its dependencies installed?');
+ }
+}
+
+function main(): number {
+ if (!applyFlags(process.argv.slice(2))) {
+ console.error(`\n${usage()}`);
+
+ return 1;
+ }
+
+ // Loaded only now: the config modules read the environment when they are first imported, and the flags
+ // have to be applied to it before that.
+ const { describeMalleusConfig, loadMalleusConfig } = require('./MalleusConfig');
+ const config: IMalleusConfig = loadMalleusConfig();
+
+ console.log(describeMalleusConfig(config));
+
+ if (config.useNodeTypes && !process.env.GRID_HOST_URL) {
+ throw new Error('--use-node-types requires a grid (--hub-url)');
+ }
+
+ if (config.useLoadTest) {
+ ensureLoadTestBundle(config);
+ }
+
+ // Run wdio from tests/ with the malleus config, like the test-* scripts do for the regular suite. The
+ // package's exports map hides bin/wdio.js from require.resolve, so locate it from the package's main entry.
+ const wdio = path.join(path.dirname(require.resolve('@wdio/cli')), '..', 'bin', 'wdio.js');
+ const result = spawnSync(process.execPath, [ wdio, 'run', 'wdio.malleus.conf.ts' ], {
+ cwd: path.join(__dirname, '..'),
+ env: process.env,
+ stdio: 'inherit'
+ });
+
+ return result.status ?? 1;
+}
+
+try {
+ process.exit(main());
+} catch (e) {
+ console.error((e as Error).message);
+ process.exit(1);
+}
diff --git a/tests/malleus/malleus.spec.ts b/tests/malleus/malleus.spec.ts
new file mode 100644
index 0000000000..6feca03cec
--- /dev/null
+++ b/tests/malleus/malleus.spec.ts
@@ -0,0 +1,105 @@
+import { setTestProperties } from '../helpers/TestProperties';
+
+import {
+ IMalleusConfig,
+ describeMalleusConfig,
+ layoutBrowsers,
+ loadMalleusConfig,
+ malleusRoomName
+} from './MalleusConfig';
+import { MalleusParticipant } from './MalleusParticipant';
+import { TabbedSession } from './TabbedSession';
+import { BridgeSelection, disruptBridges } from './blip';
+import { SpeakerTask, switchSpeakers } from './speakers';
+
+setTestProperties(__filename, {
+ description: 'Malleus Jitsificus: the jitsi-meet load tester. Not part of the regular test suite, see '
+ + 'wdio.malleus.conf.ts.',
+ usesBrowsers: []
+});
+
+/**
+ * Runs a single conference: all its participants, plus the per-conference side tasks (speaker switching,
+ * bridge disruption). Returns the errors encountered rather than throwing, so every conference runs to the end.
+ */
+async function runConference(config: IMalleusConfig, conference: number): Promise<Error[]> {
+ const roomName = malleusRoomName(config, conference);
+ const browsers = layoutBrowsers(config, conference);
+ const participants: MalleusParticipant[] = [];
+
+ for (const browser of browsers) {
+ const instance = multiRemoteBrowser.getInstance(browser.instance);
+
+ if (browser.tabs.length === 1) {
+ participants.push(new MalleusParticipant(config, browser.tabs[0], roomName, instance));
+ } else {
+ const session = new TabbedSession(instance);
+
+ browser.tabs.forEach(role => {
+ participants.push(new MalleusParticipant(config, role, roomName, undefined, session));
+ });
+ }
+ }
+
+ console.log(`Conference ${conference}: room ${roomName}, ${config.participants} participants in ${
+ participants.length} tabs over ${browsers.length} browser sessions`);
+
+ const disrupt = config.maxDisruptedBridgesPct > 0;
+ const tasks: Promise<void>[] = [];
+
+ if (disrupt) {
+ const selection = new BridgeSelection(participants.length);
+
+ participants.forEach(p => {
+ p.bridgeSelection = selection;
+ });
+ tasks.push(disruptBridges(
+ participants, selection, config.maxDisruptedBridgesPct, config.durationMs / 1000, config.blipScript));
+ }
+
+ if (config.switchSpeakers) {
+ const speakers: SpeakerTask[] = [];
+
+ participants.filter(p => p.audioSender).forEach(p => {
+ if (p.role.numClients === 1) {
+ speakers.push(new SpeakerTask(p));
+ } else {
+ for (let j = 0; j < p.role.numClients; j++) {
+ speakers.push(new SpeakerTask(p, j));
+ }
+ }
+ });
+ tasks.push(switchSpeakers(speakers, config.durationMs + config.joinDelayMs * config.participants));
+ }
+
+ tasks.push(...participants.map(p => p.run(disrupt)));
+
+ const results = await Promise.allSettled(tasks);
+
+ return results
+ .filter((r): r is PromiseRejectedResult => r.status === 'rejected')
+ .map(r => r.reason instanceof Error ? r.reason : new Error(String(r.reason)));
+}
+
+describe('Malleus Jitsificus', () => {
+ it('load test', async () => {
+ const config = loadMalleusConfig();
+
+ console.log(describeMalleusConfig(config));
+
+
+ const conferences = [];
+
+ for (let c = 0; c < config.conferences; c++) {
+ conferences.push(runConference(config, c));
+ }
+
+ const errors = (await Promise.all(conferences)).flat();
+
+ if (errors.length) {
+ errors.forEach(e => console.error(e));
+
+ throw new Error(`Failed with ${errors.length} error(s). Throwing the first: ${errors[0].message}`);
+ }
+ });
+});
diff --git a/tests/malleus/speakers.ts b/tests/malleus/speakers.ts
new file mode 100644
index 0000000000..748ed1ea43
--- /dev/null
+++ b/tests/malleus/speakers.ts
@@ -0,0 +1,175 @@
+import { MalleusParticipant } from './MalleusParticipant';
+
+/* Mean durations of the ITU-T P.59 conversational speech model. */
+const SINGLE_TALK_MS = 854;
+const DOUBLE_TALK_MS = 226;
+const SILENCE_MS = 456;
+
+/* The probability of moving from single talk to silence rather than to double talk. */
+const P_SILENCE = 0.4;
+
+function sleep(ms: number): Promise<void> {
+ return new Promise(resolve => {
+ setTimeout(resolve, ms);
+ });
+}
+
+/**
+ * A random duration, exponentially distributed with mean `t`.
+ */
+function randomDuration(t: number): number {
+ return -t * Math.log(1 - Math.random());
+}
+
+/**
+ * One potential speaker: an audio-sending participant, or in load-test mode one of the clients of a tab.
+ */
+export class SpeakerTask {
+ readonly participant: MalleusParticipant;
+ readonly clientIndex?: number;
+
+ /** Whether this speaker has spoken at least once during the run. */
+ spoken = false;
+
+ private muted: boolean;
+
+ constructor(participant: MalleusParticipant, clientIndex?: number) {
+ this.participant = participant;
+ this.clientIndex = clientIndex;
+ this.muted = participant.audioMuted;
+ }
+
+ /**
+ * The participant index this speaker corresponds to, for logging.
+ */
+ get label(): string {
+ const { conference, index } = this.participant.role;
+
+ if (this.clientIndex === undefined) {
+ return `c${conference}p${index}`;
+ }
+
+ return `c${conference}p${index + this.clientIndex} (${index}+${this.clientIndex})`;
+ }
+
+ /**
+ * Mutes or unmutes this speaker. Fire-and-forget, so a slow browser does not distort the model's timing.
+ */
+ setMuted(mute: boolean): void {
+ if (mute === this.muted) {
+ return;
+ }
+ this.muted = mute;
+ if (!mute) {
+ this.spoken = true;
+ }
+ if (!this.participant.running) {
+ // Already hung up (or not joined yet): nothing to mute, and the page is gone.
+ return;
+ }
+
+ this.participant.muteAudio(mute, this.clientIndex)
+ .then(() => console.log(`${mute ? 'Muted' : 'Unmuted'} participant ${this.label}`))
+ .catch(e => console.error(`Failed to ${mute ? 'mute' : 'unmute'} participant ${this.label}`, e));
+ }
+}
+
+/**
+ * Randomly chooses the next speaker among the active tasks. If there are N past speakers a past speaker is
+ * chosen with probability N / (N + 1) and somebody who has not spoken yet with probability 1 / (N + 1),
+ * unless everyone is a past speaker.
+ */
+export function chooseSpeaker(tasks: SpeakerTask[], currentSpeakers: SpeakerTask[]): SpeakerTask | undefined {
+ const candidates = tasks.filter(t => t.participant.running && !currentSpeakers.includes(t));
+ const pastSpeakers = candidates.filter(t => t.spoken);
+ const nonSpeakers = candidates.filter(t => !t.spoken && t.participant.audioSender);
+
+ if (!pastSpeakers.length && !nonSpeakers.length) {
+ return undefined;
+ }
+
+ const randMax = pastSpeakers.length + (nonSpeakers.length ? 1 : 0);
+ const idx = Math.floor(Math.random() * randMax);
+
+ if (idx < pastSpeakers.length) {
+ return pastSpeakers[idx];
+ }
+
+ return nonSpeakers[Math.floor(Math.random() * nonSpeakers.length)];
+}
+
+/**
+ * Randomly switches speakers for `durationMs`. Modeled on ITU-T P.59, but choosing among N speakers rather
+ * than just 2 (at most 2 talk at a time).
+ */
+export async function switchSpeakers(tasks: SpeakerTask[], durationMs: number): Promise<void> {
+ const currentSpeakers: SpeakerTask[] = [];
+ let remainingMs = durationMs;
+
+ while (remainingMs > 0) {
+ // Speakers that hung up in the meantime are silent already; drop them from the model.
+ for (let i = currentSpeakers.length - 1; i >= 0; i--) {
+ if (!currentSpeakers[i].participant.running) {
+ currentSpeakers.splice(i, 1);
+ }
+ }
+
+ switch (currentSpeakers.length) {
+ case 0: {
+ // No speakers: add one.
+ const newSpeaker = chooseSpeaker(tasks, currentSpeakers);
+
+ if (newSpeaker) {
+ newSpeaker.setMuted(false);
+ currentSpeakers.push(newSpeaker);
+ }
+ break;
+ }
+ case 1: {
+ // One speaker: either add or remove one.
+ if (Math.random() < P_SILENCE) {
+ currentSpeakers.pop()!.setMuted(true);
+ } else {
+ const newSpeaker = chooseSpeaker(tasks, currentSpeakers);
+
+ if (newSpeaker) {
+ newSpeaker.setMuted(false);
+ currentSpeakers.push(newSpeaker);
+ }
+ }
+ break;
+ }
+ default: {
+ // More than one speaker: remove one.
+ const idx = Math.floor(Math.random() * currentSpeakers.length);
+
+ currentSpeakers.splice(idx, 1)[0].setMuted(true);
+ break;
+ }
+ }
+
+ let stateMs: number;
+
+ switch (currentSpeakers.length) {
+ case 0: {
+ // Silence, at least 200ms of it.
+ stateMs = 0;
+ while (stateMs < 200) {
+ stateMs += randomDuration(SILENCE_MS);
+ }
+ break;
+ }
+ case 1:
+ stateMs = randomDuration(SINGLE_TALK_MS);
+ break;
+ default:
+ stateMs = randomDuration(DOUBLE_TALK_MS);
+ break;
+ }
+
+ const sleepMs = Math.min(stateMs, remainingMs);
+
+ remainingMs -= sleepMs;
+ await sleep(sleepMs);
+ }
+}
diff --git a/tests/package-lock.json b/tests/package-lock.json
index 45fb984a0d..cb9652491d 100644
--- a/tests/package-lock.json
+++ b/tests/package-lock.json
@@ -23,6 +23,7 @@
"junit-report-builder": "5.1.1",
"lodash-es": "4.18.1",
"pretty": "2.0.0",
+ "tsx": "4.23.13",
"uuid": "14.0.0",
"webdriverio": "9.27.0",
"ws": "6.2.3"
diff --git a/tests/package.json b/tests/package.json
index 27ab1b5749..c9375a060d 100644
--- a/tests/package.json
+++ b/tests/package.json
@@ -13,7 +13,8 @@
"test-grid": "DOTENV_CONFIG_PATH=.env NODE_PATH=\"$(pwd)/node_modules\" wdio run wdio.grid.conf.ts",
"test-grid-single": "DOTENV_CONFIG_PATH=.env NODE_PATH=\"$(pwd)/node_modules\" wdio run wdio.grid.conf.ts --spec",
"test-grid-ff": "DOTENV_CONFIG_PATH=.env NODE_PATH=\"$(pwd)/node_modules\" wdio run wdio.grid.firefox.conf.ts",
- "test-grid-ff-single": "DOTENV_CONFIG_PATH=.env NODE_PATH=\"$(pwd)/node_modules\" wdio run wdio.grid.firefox.conf.ts --spec"
+ "test-grid-ff-single": "DOTENV_CONFIG_PATH=.env NODE_PATH=\"$(pwd)/node_modules\" wdio run wdio.grid.firefox.conf.ts --spec",
+ "malleus": "DOTENV_CONFIG_PATH=.env NODE_PATH=\"$(pwd)/node_modules\" tsx malleus/cli.ts"
},
"dependencies": {
"@braintree/sanitize-url": "7.0.0",
@@ -31,6 +32,7 @@
"junit-report-builder": "5.1.1",
"lodash-es": "4.18.1",
"pretty": "2.0.0",
+ "tsx": "4.23.13",
"uuid": "14.0.0",
"webdriverio": "9.27.0",
"ws": "6.2.3"
diff --git a/tests/resources/loadTest.html b/tests/resources/loadTest.html
new file mode 100644
index 0000000000..a27b92ce85
--- /dev/null
+++ b/tests/resources/loadTest.html
@@ -0,0 +1,66 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>load test</title>
+</head>
+<body>
+<div>Number of participants: <span id="participants">1</span></div>
+<script>
+ /**
+ * Wrapper page for the load-test client (react/features/load-test), uploaded into the browser by Malleus.
+ * Loads config.js and lib-jitsi-meet from the deployment under test, then the uploaded client bundle, which
+ * reads its parameters from this page's URL hash. The parameters this page itself needs are:
+ * - domain: the deployment's host;
+ * - tenant: the deployment's tenant path (e.g. "torture/"), if any, for the location of config.js;
+ * - bundle: the local path of the uploaded load-test-participant bundle;
+ * - room: the room, also read by the client; passed along when fetching config.js as jitsi-meet does, so
+ * that deployments which route by room name serve the config of the shard the room lives on.
+ * Values are JSON-encoded like all jitsi-meet URL parameters.
+ */
+ const params = {};
+
+ (document.location.hash || '').substring(1).split('&').forEach(part => {
+ const [ key, value ] = part.split('=');
+
+ if (![ 'domain', 'tenant', 'bundle', 'room' ].includes(key)) {
+ return;
+ }
+ try {
+ params[key] = JSON.parse(decodeURIComponent(value));
+ } catch (e) {
+ console.error(`Failed to parse URL parameter ${key}`, e);
+ }
+ });
+
+ function log(msg) {
+ console.log(`${new Date().toISOString()} [LoadTestPage] ${msg}`);
+ }
+
+ function loadScript(src) {
+ return new Promise((resolve, reject) => {
+ const script = document.createElement('script');
+
+ script.src = src;
+ script.onload = () => {
+ log(`loaded ${src}`);
+ resolve();
+ };
+ script.onerror = () => reject(new Error(`Failed to load ${src}`));
+ document.head.appendChild(script);
+ });
+ }
+
+ const { domain, tenant = '', bundle, room } = params;
+
+ if (!domain || !bundle) {
+ log('Missing the domain or bundle parameter, not starting.');
+ } else {
+ loadScript(`https://${domain}/${tenant}config.js${room ? `?room=${encodeURIComponent(room)}` : ''}`)
+ .then(() => loadScript(`https://${domain}/libs/lib-jitsi-meet.min.js`))
+ .then(() => loadScript(bundle.startsWith('file://') ? bundle : `file://${bundle}`))
+ .catch(e => console.error(e));
+ }
+</script>
+</body>
+</html>
diff --git a/tests/scripts/blip.sh b/tests/scripts/blip.sh
new file mode 100755
index 0000000000..171efbad51
--- /dev/null
+++ b/tests/scripts/blip.sh
@@ -0,0 +1,17 @@
+#!/bin/sh
+
+if [ -n "$DEBUG" ]; then
+ set -x
+fi
+
+# This is a non-functional placeholder script that needs to be replaced with one
+# that is designed for your specific infrastructure. The command line parameters
+# that are necessary for malleus to function properly are listed
+# bellow. You can further customize your script with environment variables.
+
+usage() {
+ echo "Usage: $0 --duration=DURATION --bridge-ips=IP1[,IP2,...]" >&2
+ exit 1
+}
+
+usage
diff --git a/tests/scripts/malleus.sh b/tests/scripts/malleus.sh
new file mode 100755
index 0000000000..2ac6e6f5bd
--- /dev/null
+++ b/tests/scripts/malleus.sh
@@ -0,0 +1,3 @@
+#!/bin/sh
+# Forwards to the malleus CLI (../malleus/cli.ts). Run `npm run malleus -- --help` for usage.
+cd "$(dirname "$0")/.." && exec npm run malleus -- "$@"
diff --git a/tests/wdio.conf.ts b/tests/wdio.conf.ts
index 0aefbe8aed..5df74ffbce 100644
--- a/tests/wdio.conf.ts
+++ b/tests/wdio.conf.ts
@@ -23,7 +23,7 @@ const allure = require('allure-commandline');
// we need it to be able to reuse jitsi-meet code in tests
require.extensions['.web.ts'] = require.extensions['.ts'];
-const chromeArgs = [
+export const chromeArgs = [
'--allow-insecure-localhost',
'--use-fake-ui-for-media-stream',
'--use-fake-device-for-media-stream',
@@ -60,7 +60,7 @@ if (process.env.VIDEO_CAPTURE_FILE) {
chromeArgs.push(`--use-file-for-fake-video-capture=${process.env.VIDEO_CAPTURE_FILE}`);
}
-const chromePreferences = {
+export const chromePreferences = {
'intl.accept_languages': 'en-US'
};
@@ -205,7 +205,7 @@ function generateCapabilitiesFromSpecs(): { capabilities: Record<string, any>; e
const { capabilities, excludedSpecs } = generateCapabilitiesFromSpecs();
-const TEST_RESULTS_DIR = 'test-results';
+export const TEST_RESULTS_DIR = 'test-results';
const keepAlive: Array<any> = [];
diff --git a/tests/wdio.grid.conf.ts b/tests/wdio.grid.conf.ts
index 97b8d45369..2153a4bdfc 100644
--- a/tests/wdio.grid.conf.ts
+++ b/tests/wdio.grid.conf.ts
@@ -1,36 +1,8 @@
// wdio.grid.conf.ts
// extends the main configuration file to add the selenium grid address
-import { URL } from 'url';
+import { applyGridConfig } from './helpers/grid';
// @ts-ignore
import { config as defaultConfig } from './wdio.conf.ts';
-const gridUrl = new URL(process.env.GRID_HOST_URL as string);
-const protocol = gridUrl.protocol.replace(':', '');
-
-const mergedConfig = {
- ...defaultConfig,
- protocol,
- hostname: gridUrl.hostname,
- port: gridUrl.port ? parseInt(gridUrl.port, 10) // Convert port to number
- : protocol === 'http' ? 80 : 443,
- path: gridUrl.pathname
-};
-
-Object.keys(mergedConfig.capabilities).forEach(browser => {
- mergedConfig.capabilities[browser].capabilities['goog:chromeOptions'].args
- = updateRemoteResource(mergedConfig.capabilities[browser].capabilities['goog:chromeOptions'].args);
-});
-
-export const config = mergedConfig;
-
-/**
- * Updates the array of arguments for the Chrome browser to use a remote resource for fake audio capture.
- * @param arr
- */
-function updateRemoteResource(arr: string[]): string[] {
- // eslint-disable-next-line no-confusing-arrow
- return arr.map((item: string) => item.startsWith('--use-file-for-fake-audio-capture=')
- ? `--use-file-for-fake-audio-capture=${process.env.REMOTE_RESOURCE_PATH}/fakeAudioStream.wav` : item
- );
-}
+export const config = applyGridConfig(defaultConfig);
diff --git a/tests/wdio.grid.firefox.conf.ts b/tests/wdio.grid.firefox.conf.ts
index ac3ce5ce2a..674bfca6c1 100644
--- a/tests/wdio.grid.firefox.conf.ts
+++ b/tests/wdio.grid.firefox.conf.ts
@@ -1,18 +1,8 @@
-// wdio.grid.conf.ts
-// extends the main configuration file to add the selenium grid address
-import { URL } from 'url';
+// wdio.grid.firefox.conf.ts
+// extends the firefox configuration file to add the selenium grid address
+import { applyGridConfig } from './helpers/grid';
// @ts-ignore
import { config as defaultConfig } from './wdio.firefox.conf.ts';
-const gridUrl = new URL(process.env.GRID_HOST_URL as string);
-const protocol = gridUrl.protocol.replace(':', '');
-
-export const config = {
- ...defaultConfig,
- protocol,
- hostname: gridUrl.hostname,
- port: gridUrl.port ? parseInt(gridUrl.port, 10) // Convert port to number
- : protocol === 'http' ? 80 : 443,
- path: gridUrl.pathname
-};
+export const config = applyGridConfig(defaultConfig);
diff --git a/tests/wdio.malleus.conf.ts b/tests/wdio.malleus.conf.ts
new file mode 100644
index 0000000000..3e75bd0e53
--- /dev/null
+++ b/tests/wdio.malleus.conf.ts
@@ -0,0 +1,159 @@
+// wdio.malleus.conf.ts
+// The configuration for Malleus Jitsificus, the load tester. It reuses the regular configuration (Chrome
+// arguments, grid support, reporting and log handling) but generates one browser session per participant
+// from the MALLEUS_* settings instead of from the spec files, and runs the single malleus spec with no timeout.
+// Start it through malleus/cli.ts (npm run malleus), which maps command line flags onto the environment.
+import fs from 'fs';
+import path from 'node:path';
+import process from 'node:process';
+
+import { getTestProperties } from './helpers/TestProperties';
+import { initLogger } from './helpers/browserLogger';
+import { applyGridConfig } from './helpers/grid';
+import { IContext } from './helpers/types';
+import {
+ LOAD_TEST_PAGE,
+ RECEIVER_NODE_APP_NAME,
+ SENDER_NODE_APP_NAME,
+ layoutBrowsers,
+ loadMalleusConfig
+} from './malleus/MalleusConfig';
+// @ts-ignore
+import { TEST_RESULTS_DIR, chromeArgs, chromePreferences, config as defaultConfig } from './wdio.conf.ts';
+
+// Validated here too, so a bad setting fails the run before any browser starts. The spec prints the summary.
+const malleusConfig = loadMalleusConfig();
+
+/**
+ * One multiremote instance per browser session; with tabs per browser a session runs several participants.
+ */
+function generateCapabilities(): Record<string, any> {
+ const capabilities: Record<string, any> = {};
+
+ for (let c = 0; c < malleusConfig.conferences; c++) {
+ for (const browser of layoutBrowsers(malleusConfig, c)) {
+ const caps: Record<string, any> = {
+ browserName: 'chrome',
+
+ // On the grid a bare browserName matches every Chrome slot, beta included; pin the alias the grid
+ // uses for stable, as the regular suite does. Local chromedriver does not know the alias.
+ ...(process.env.GRID_HOST_URL ? { browserVersion: process.env.MALLEUS_BROWSER_VERSION || 'jitsi-stable' } : {}),
+ 'goog:chromeOptions': {
+ args: chromeArgs,
+ prefs: chromePreferences
+ }
+ };
+
+ if (malleusConfig.useNodeTypes) {
+ // Video senders go to sender nodes; everybody else, audio senders included, to receiver nodes.
+ caps['nodename:applicationName'] = browser.sender ? SENDER_NODE_APP_NAME : RECEIVER_NODE_APP_NAME;
+ }
+
+ capabilities[browser.instance] = { capabilities: caps };
+ }
+ }
+
+ return capabilities;
+}
+
+const specs = [ 'malleus/malleus.spec.ts' ];
+
+let config: WebdriverIO.MultiremoteConfig = {
+ ...defaultConfig,
+
+ specs,
+ exclude: [],
+ maxInstances: 1,
+
+ capabilities: generateCapabilities(),
+
+ // Browsers on a loaded grid or deployment can be slow to respond.
+ connectionRetryTimeout: 120_000,
+
+ mochaOpts: {
+ // A run lasts as long as the configured duration plus the join delays, plus whatever it takes to start
+ // and stop the browsers. (A timeout of 0, mocha's "no timeout", is not honored by the wdio wrapper.)
+ timeout: malleusConfig.durationMs + malleusConfig.joinDelayMs * malleusConfig.participants + 10 * 60_000
+ },
+
+ /**
+ * Prepares the context. Unlike the regular suite there is no iframe API page to upload and no keep-alive
+ * (the participants are busy for the whole run), and browser logs are only collected on request since
+ * subscribing to them for hundreds of sessions is expensive.
+ */
+ async before(cid, _, files) {
+ const testFilePath = files[0].replace(/^file:\/\//, '');
+ const testProperties = await getTestProperties(testFilePath);
+
+ console.log(`Running malleus via worker: ${cid} browser instances:${multiRemoteBrowser.instances.length}`);
+
+ const globalAny: any = global;
+
+ globalAny.ctx = {
+ times: {},
+ testProperties,
+ roomName: ''
+ } as IContext;
+
+ if (malleusConfig.saveLogs) {
+ fs.mkdirSync(TEST_RESULTS_DIR, { recursive: true });
+ multiRemoteBrowser.instances.forEach((instance: string) => {
+ initLogger(multiRemoteBrowser.getInstance(instance), `${instance}-${cid}-malleus`, TEST_RESULTS_DIR);
+ });
+ }
+
+ if (malleusConfig.useLoadTest) {
+ if (!fs.existsSync(malleusConfig.loadTestBundle)) {
+ throw new Error(`The load-test client bundle is missing: ${malleusConfig.loadTestBundle}. `
+ + 'Build it with `npm run build:load-test` at the repository root, or point '
+ + 'MALLEUS_LOAD_TEST_BUNDLE at a build.');
+ }
+
+ // Inject the load-test page and client into every browser, the way the regular suite uploads its
+ // iframe API page. The uploads land wherever the (possibly remote) browser keeps them, hence the
+ // paths are recorded per session for Participant.joinConference to build the URL from.
+ await Promise.all(multiRemoteBrowser.instances.map(async (instance: string) => {
+ const bInstance = multiRemoteBrowser.getInstance(instance);
+ const pagePath = await bInstance.uploadFile(LOAD_TEST_PAGE);
+ const bundlePath = await bInstance.uploadFile(malleusConfig.loadTestBundle);
+
+ // @ts-ignore
+ bInstance.loadTestPageBase = `file://${path.dirname(pagePath)}`;
+ // @ts-ignore
+ bInstance.loadTestBundle = bundlePath;
+ }));
+ }
+ },
+
+ /**
+ * On failure, hang up everybody who is still in a conference. Skips the screenshots and page sources the
+ * regular suite attaches, which do not scale to a load test.
+ */
+ async afterTest(test, _context, { error }) {
+ if (!error) {
+ return;
+ }
+
+ console.log(`Malleus failed (${test.title}): ${error.message}`);
+ console.log('Hanging up all participants');
+
+ // Loaded lazily: Participant pulls in jitsi-meet modules with .web.ts variants, which only resolve once
+ // wdio.conf.ts has registered its require hook for them, i.e. not while this file's imports are evaluated.
+ const { allMalleusParticipants } = require('./malleus/MalleusParticipant');
+
+ await Promise.allSettled(allMalleusParticipants
+ .filter((p: { running: boolean; }) => p.running)
+ .map((p: { participant: { hangup: () => Promise<void>; }; }) => p.participant.hangup()));
+ }
+};
+
+if (process.env.GRID_HOST_URL) {
+ config = applyGridConfig(config);
+}
+
+// Sanity check: the spec must exist where we expect it, or wdio reports "no specs found" which is confusing.
+if (!fs.existsSync(path.join(__dirname, specs[0]))) {
+ throw new Error(`Malleus spec not found at ${specs[0]}`);
+}
+
+export { config };
diff --git a/tsconfig.native.json b/tsconfig.native.json
index 3439b8bfef..83505fc451 100644
--- a/tsconfig.native.json
+++ b/tsconfig.native.json
@@ -26,6 +26,7 @@
"react/features/embed-meeting",
"react/features/face-landmarks",
"react/features/keyboard-shortcuts",
+ "react/features/load-test",
"react/features/no-audio-signal",
"react/features/pip",
"react/features/noise-suppression",
diff --git a/webpack.config.js b/webpack.config.js
index 54985658d0..e2970e829a 100644
--- a/webpack.config.js
+++ b/webpack.config.js
@@ -358,6 +358,19 @@ module.exports = (_env, argv) => {
...getBundleAnalyzerPlugin(analyzeBundle, 'alwaysontop')
],
performance: getPerformanceHints(perfHintOptions, 800 * 1024) },
+
+ // The load-test client used by Malleus (tests/malleus). Not part of the application: it is built only by
+ // `npm run build:load-test` (BUILD_LOAD_TEST=true) and injected into the browsers by the load tester.
+ ...process.env.BUILD_LOAD_TEST ? [ { ...config,
+ name: 'load-test',
+ entry: {
+ 'load-test-participant': './react/features/load-test/loadTestParticipant.ts'
+ },
+ plugins: [
+ ...config.plugins,
+ ...getBundleAnalyzerPlugin(analyzeBundle, 'load-test-participant')
+ ],
+ performance: getPerformanceHints(perfHintOptions, 400 * 1024) } ] : [],
{ ...config,
entry: {
'documentpip': './react/features/always-on-top/document-pip-index.tsx'