You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

e2eping.js 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. import { getLogger } from '@jitsi/logger';
  2. import * as JitsiConferenceEvents from '../../JitsiConferenceEvents';
  3. import * as JitsiE2EPingEvents from '../../service/e2eping/E2ePingEvents';
  4. const logger = getLogger(__filename);
  5. /**
  6. * The 'type' of a message which designates an e2e ping request.
  7. * @type {string}
  8. */
  9. const E2E_PING_REQUEST = 'e2e-ping-request';
  10. /**
  11. * The 'type' of a message which designates an e2e ping response.
  12. * @type {string}
  13. */
  14. const E2E_PING_RESPONSE = 'e2e-ping-response';
  15. /**
  16. * The number of requests to wait for before emitting an RTT value.
  17. */
  18. const DEFAULT_NUM_REQUESTS = 5;
  19. /**
  20. * The maximum number of messages per second to aim for. This is for the entire
  21. * conference, with the assumption that all endpoints join at once.
  22. */
  23. const DEFAULT_MAX_MESSAGES_PER_SECOND = 250;
  24. /**
  25. * The conference size beyond which e2e pings will be disabled.
  26. */
  27. const DEFAULT_MAX_CONFERENCE_SIZE = 200;
  28. /**
  29. * Saves e2e ping related state for a single JitsiParticipant.
  30. */
  31. class ParticipantWrapper {
  32. /**
  33. * Creates a ParticipantWrapper
  34. * @param {JitsiParticipant} participant - The remote participant that this
  35. * object wraps.
  36. * @param {E2ePing} e2eping
  37. */
  38. constructor(participant, e2eping) {
  39. // The JitsiParticipant
  40. this.participant = participant;
  41. // The E2ePing
  42. this.e2eping = e2eping;
  43. // Caches the ID
  44. this.id = participant.getId();
  45. // Recently sent requests
  46. this.requests = {};
  47. // The ID of the last sent request. We just increment it for each new
  48. // request. Start at 1 so we can consider only thruthy values valid.
  49. this.lastRequestId = 1;
  50. this.sendRequest = this.sendRequest.bind(this);
  51. this.handleResponse = this.handleResponse.bind(this);
  52. this.maybeLogRttAndStop = this.maybeLogRttAndStop.bind(this);
  53. this.scheduleNext = this.scheduleNext.bind(this);
  54. this.stop = this.stop.bind(this);
  55. this.getDelay = this.getDelay.bind(this);
  56. this.timeout = this.scheduleNext();
  57. }
  58. /**
  59. * Schedule the next ping to be sent.
  60. */
  61. scheduleNext() {
  62. return window.setTimeout(this.sendRequest, this.getDelay());
  63. }
  64. /**
  65. * Stop pinging this participant, canceling a scheduled ping, if any.
  66. */
  67. stop() {
  68. if (this.timeout) {
  69. window.clearTimeout(this.timeout);
  70. }
  71. this.e2eping.removeParticipant(this.id);
  72. }
  73. /**
  74. * Get the delay until the next ping in milliseconds.
  75. */
  76. getDelay() {
  77. const conferenceSize = this.e2eping.conference.getParticipants().length;
  78. const endpointPairs = conferenceSize * (conferenceSize - 1) / 2;
  79. const totalMessages = endpointPairs * this.e2eping.numRequests;
  80. const totalSeconds = totalMessages / this.e2eping.maxMessagesPerSecond;
  81. // Randomize between .5 and 1.5
  82. const r = 1.5 - Math.random();
  83. const delayBetweenMessages = r * Math.max(1000 * (totalSeconds / this.e2eping.numRequests), 1000);
  84. return delayBetweenMessages;
  85. }
  86. /**
  87. * Sends the next ping request.
  88. * @type {*}
  89. */
  90. sendRequest() {
  91. const requestId = this.lastRequestId++;
  92. const requestMessage = {
  93. type: E2E_PING_REQUEST,
  94. id: requestId
  95. };
  96. this.e2eping.sendMessage(requestMessage, this.id);
  97. this.requests[requestId] = {
  98. id: requestId,
  99. timeSent: window.performance.now()
  100. };
  101. }
  102. /**
  103. * Handles a response from this participant.
  104. * @type {*}
  105. */
  106. handleResponse(response) {
  107. const request = this.requests[response.id];
  108. if (request) {
  109. request.rtt = window.performance.now() - request.timeSent;
  110. }
  111. this.maybeLogRttAndStop();
  112. }
  113. /**
  114. * Check if we've received the pre-configured number of responses, and if
  115. * so log the measured RTT and stop sending requests.
  116. * @type {*}
  117. */
  118. maybeLogRttAndStop() {
  119. // The RTT we'll report is the minimum RTT measured
  120. let rtt = Infinity;
  121. let request, requestId;
  122. let numRequestsWithResponses = 0;
  123. let totalNumRequests = 0;
  124. for (requestId in this.requests) {
  125. if (this.requests.hasOwnProperty(requestId)) {
  126. request = this.requests[requestId];
  127. totalNumRequests++;
  128. if (request.rtt) {
  129. numRequestsWithResponses++;
  130. rtt = Math.min(rtt, request.rtt);
  131. }
  132. }
  133. }
  134. if (numRequestsWithResponses >= this.e2eping.numRequests) {
  135. logger.info(`Measured RTT=${rtt} ms to ${this.id} (in ${this.participant.getProperty('region')})`);
  136. this.stop();
  137. this.e2eping.conference.eventEmitter.emit(
  138. JitsiE2EPingEvents.E2E_RTT_CHANGED, this.participant, rtt);
  139. return;
  140. } else if (totalNumRequests > 2 * this.e2eping.numRequests) {
  141. logger.info(`Stopping e2eping for ${this.id} because we sent ${totalNumRequests} with only `
  142. + `${numRequestsWithResponses} responses.`);
  143. this.stop();
  144. return;
  145. }
  146. this.timeout = this.scheduleNext();
  147. }
  148. }
  149. /**
  150. * Implements end-to-end ping (from one conference participant to another) via
  151. * the jitsi-videobridge channel (either WebRTC data channel or web socket).
  152. *
  153. * TODO: use a broadcast message instead of individual pings to each remote
  154. * participant.
  155. *
  156. * This class:
  157. * 1. Sends periodic ping requests to all other participants in the
  158. * conference.
  159. * 2. Responds to ping requests from other participants.
  160. * 3. Fires events with the end-to-end RTT to each participant whenever a
  161. * response is received.
  162. * 4. Fires analytics events with the end-to-end RTT periodically.
  163. */
  164. export default class E2ePing {
  165. /**
  166. * @param {JitsiConference} conference - The conference.
  167. * @param {Function} sendMessage - The function to use to send a message.
  168. * @param {Object} options
  169. */
  170. constructor(conference, options, sendMessage) {
  171. this.conference = conference;
  172. this.eventEmitter = conference.eventEmitter;
  173. this.sendMessage = sendMessage;
  174. // Maps a participant ID to its ParticipantWrapper
  175. this.participants = {};
  176. this.numRequests = DEFAULT_NUM_REQUESTS;
  177. this.maxConferenceSize = DEFAULT_MAX_CONFERENCE_SIZE;
  178. this.maxMessagesPerSecond = DEFAULT_MAX_MESSAGES_PER_SECOND;
  179. if (options && options.e2eping) {
  180. if (typeof options.e2eping.numRequests === 'number') {
  181. this.numRequests = options.e2eping.numRequests;
  182. }
  183. if (typeof options.e2eping.maxConferenceSize === 'number') {
  184. this.maxConferenceSize = options.e2eping.maxConferenceSize;
  185. }
  186. if (typeof options.e2eping.maxMessagesPerSecond === 'number') {
  187. this.maxMessagesPerSecond = options.e2eping.maxMessagesPerSecond;
  188. }
  189. }
  190. logger.info(
  191. `Initializing e2e ping with numRequests=${this.numRequests}, maxConferenceSize=${this.maxConferenceSize}, `
  192. + `maxMessagesPerSecond=${this.maxMessagesPerSecond}.`);
  193. this.participantJoined = this.participantJoined.bind(this);
  194. this.participantLeft = this.participantLeft.bind(this);
  195. conference.on(JitsiConferenceEvents.USER_LEFT, this.participantLeft);
  196. this.messageReceived = this.messageReceived.bind(this);
  197. conference.on(JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED, this.messageReceived);
  198. this.conferenceJoined = this.conferenceJoined.bind(this);
  199. conference.on(JitsiConferenceEvents.CONFERENCE_JOINED, this.conferenceJoined);
  200. }
  201. /**
  202. * Delay processing USER_JOINED events until the MUC is fully joined,
  203. * otherwise the apparent conference size will be wrong.
  204. */
  205. conferenceJoined() {
  206. this.conference.getParticipants().forEach(p => this.participantJoined(p.getId(), p));
  207. this.conference.on(JitsiConferenceEvents.USER_JOINED, this.participantJoined);
  208. }
  209. /**
  210. * Handles a message that was received.
  211. *
  212. * @param participant - The message sender.
  213. * @param payload - The payload of the message.
  214. */
  215. messageReceived(participant, payload) {
  216. // Listen to E2E PING requests and responses from other participants
  217. // in the conference.
  218. if (payload.type === E2E_PING_REQUEST) {
  219. this.handleRequest(participant.getId(), payload);
  220. } else if (payload.type === E2E_PING_RESPONSE) {
  221. this.handleResponse(participant.getId(), payload);
  222. }
  223. }
  224. /**
  225. * Handles a participant joining the conference. Starts to send ping
  226. * requests to the participant.
  227. *
  228. * @param {String} id - The ID of the participant.
  229. * @param {JitsiParticipant} participant - The participant that joined.
  230. */
  231. participantJoined(id, participant) {
  232. if (this.participants[id]) {
  233. logger.info(`Participant wrapper already exists for ${id}. Clearing.`);
  234. this.participants[id].stop();
  235. }
  236. if (this.conference.getParticipants().length > this.maxConferenceSize) {
  237. return;
  238. }
  239. // We don't need to send e2eping in both directions for a pair of
  240. // endpoints. Force only one direction with just string comparison of
  241. // the IDs.
  242. if (this.conference.myUserId() > id) {
  243. logger.info(`Starting e2eping for participant ${id}`);
  244. this.participants[id] = new ParticipantWrapper(participant, this);
  245. }
  246. }
  247. /**
  248. * Remove a participant without calling "stop".
  249. */
  250. removeParticipant(id) {
  251. if (this.participants[id]) {
  252. delete this.participants[id];
  253. }
  254. }
  255. /**
  256. * Handles a participant leaving the conference. Stops sending requests.
  257. *
  258. * @param {String} id - The ID of the participant.
  259. */
  260. participantLeft(id) {
  261. if (this.participants[id]) {
  262. this.participants[id].stop();
  263. delete this.participants[id];
  264. }
  265. }
  266. /**
  267. * Handles a ping request coming from another participant.
  268. *
  269. * @param {string} participantId - The ID of the participant who sent the
  270. * request.
  271. * @param {Object} request - The request.
  272. */
  273. handleRequest(participantId, request) {
  274. // If it's a valid request, just send a response.
  275. if (request && request.id) {
  276. const response = {
  277. type: E2E_PING_RESPONSE,
  278. id: request.id
  279. };
  280. this.sendMessage(response, participantId);
  281. } else {
  282. logger.info(`Received an invalid e2e ping request from ${participantId}.`);
  283. }
  284. }
  285. /**
  286. * Handles a ping response coming from another participant
  287. * @param {string} participantId - The ID of the participant who sent the
  288. * response.
  289. * @param {Object} response - The response.
  290. */
  291. handleResponse(participantId, response) {
  292. const participantWrapper = this.participants[participantId];
  293. if (participantWrapper) {
  294. participantWrapper.handleResponse(response);
  295. }
  296. }
  297. /**
  298. * Stops this E2ePing (i.e. stop sending requests).
  299. */
  300. stop() {
  301. logger.info('Stopping e2eping');
  302. this.conference.off(JitsiConferenceEvents.USER_JOINED, this.participantJoined);
  303. this.conference.off(JitsiConferenceEvents.USER_LEFT, this.participantLeft);
  304. this.conference.off(JitsiConferenceEvents.ENDPOINT_MESSAGE_RECEIVED, this.messageReceived);
  305. for (const id in this.participants) {
  306. if (this.participants.hasOwnProperty(id)) {
  307. this.participants[id].stop();
  308. }
  309. }
  310. this.participants = {};
  311. }
  312. }