Debian Codegraph @

addons/html_editor/static/src/others/collaboration/PeerToPeer.js

raw
1 const urlParams = new URLSearchParams(window.location.search);
2 const collaborationDebug = urlParams.get("collaborationDebug");
3 const COLLABORATION_LOCALSTORAGE_KEY = "odoo_editor_collaboration_debug";
4 if (typeof collaborationDebug === "string") {
5 if (collaborationDebug === "false") {
6 localStorage.removeItem(
7 COLLABORATION_LOCALSTORAGE_KEY,
8 urlParams.get("collaborationDebug")
9 );
10 } else {
11 localStorage.setItem(COLLABORATION_LOCALSTORAGE_KEY, urlParams.get("collaborationDebug"));
12 }
13 }
14 const debugValue = localStorage.getItem(COLLABORATION_LOCALSTORAGE_KEY);
15
16 const debugShowLog = ["", "true", "all"].includes(debugValue);
17 const debugShowNotifications = debugValue === "all";
18
19 const baseNotificationMethods = {
20 ptp_request: async function (notification) {
21 const { requestId, requestName, requestPayload, requestTransport } =
22 notification.notificationPayload;
23 this._onRequest(
24 notification.fromPeerId,
25 requestId,
26 requestName,
27 requestPayload,
28 requestTransport
29 );
30 },
31 ptp_request_result: function (notification) {
32 const { requestId, result } = notification.notificationPayload;
33 // If not in _pendingRequestResolver, it means it has timeout.
34 if (this._pendingRequestResolver[requestId]) {
35 clearTimeout(this._pendingRequestResolver[requestId].rejectTimeout);
36 this._pendingRequestResolver[requestId].resolve(result);
37 delete this._pendingRequestResolver[requestId];
38 }
39 },
40
41 ptp_join: async function (notification) {
42 const peerId = notification.fromPeerId;
43 if (this.peersInfos[peerId] && this.peersInfos[peerId].peerConnection) {
44 return this.peersInfos[peerId];
45 }
46 this._createPeer(peerId);
47 },
48
49 rtc_signal_icecandidate: async function (notification) {
50 if (debugShowLog) {
51 console.log(`%creceive candidate`, "background: darkgreen; color: white;");
52 }
53 const peerInfos = this.peersInfos[notification.fromPeerId];
54 if (
55 !peerInfos ||
56 !peerInfos.peerConnection ||
57 peerInfos.peerConnection.connectionState === "closed"
58 ) {
59 console.groupCollapsed("=== ERROR: Handle Ice Candidate from undefined|closed ===");
60 console.trace(peerInfos);
61 console.groupEnd();
62 return;
63 }
64 if (!peerInfos.peerConnection.remoteDescription) {
65 peerInfos.iceCandidateBuffer.push(notification.notificationPayload);
66 } else {
67 this._addIceCandidate(peerInfos, notification.notificationPayload);
68 }
69 },
70 rtc_signal_description: async function (notification) {
71 const description = notification.notificationPayload;
72 if (debugShowLog) {
73 console.log(
74 `%cdescription received:`,
75 "background: blueviolet; color: white;",
76 description
77 );
78 }
79
80 const peerInfos =
81 this.peersInfos[notification.fromPeerId] || this._createPeer(notification.fromPeerId);
82 const pc = peerInfos.peerConnection;
83
84 if (!pc || pc.connectionState === "closed") {
85 if (debugShowLog) {
86 console.groupCollapsed("=== ERROR: handle offer ===");
87 console.log(
88 "An offer has been received for a non-existent peer connection - peer: " +
89 notification.fromPeerId
90 );
91 console.trace(pc && pc.connectionState);
92 console.groupEnd();
93 }
94 return;
95 }
96
97 // Skip if we already have an offer.
98 if (pc.signalingState === "have-remote-offer") {
99 return;
100 }
101
102 // If there is a racing conditing with the signaling offer (two
103 // being sent at the same time). We need one peer that abort by
104 // rollbacking to a stable signaling state where the other is
105 // continuing the process. The peer that is polite is the one that
106 // will rollback.
107 const isPolite =
108 ("" + notification.fromPeerId).localeCompare("" + this._currentPeerId) === 1;
109 if (debugShowLog) {
110 console.log(
111 `%cisPolite: %c${isPolite}`,
112 "background: deepskyblue;",
113 `background:${isPolite ? "green" : "red"}`
114 );
115 }
116
117 const isOfferRacing =
118 description.type === "offer" &&
119 (peerInfos.makingOffer || pc.signalingState !== "stable");
120 // If there is a racing conditing with the signaling offer and the
121 // peer is impolite, we must not process this offer and wait for
122 // the answer for the signaling process to continue.
123 if (isOfferRacing && !isPolite) {
124 if (debugShowLog) {
125 console.log(
126 `%creturn because isOfferRacing && !isPolite. pc.signalingState: ${pc.signalingState}`,
127 "background: red;"
128 );
129 }
130 return;
131 }
132 if (debugShowLog) {
133 console.log(`%cisOfferRacing: ${isOfferRacing}`, "background: red;");
134 console.log(`%c SETREMOTEDESCRIPTION`, "background: navy; color:white;");
135 }
136 try {
137 await pc.setRemoteDescription(description);
138 } catch (e) {
139 if (e instanceof DOMException && e.name === "InvalidStateError") {
140 console.error(e);
141 return;
142 } else {
143 throw e;
144 }
145 }
146 if (peerInfos.iceCandidateBuffer.length) {
147 for (const candidate of peerInfos.iceCandidateBuffer) {
148 await this._addIceCandidate(peerInfos, candidate);
149 }
150 peerInfos.iceCandidateBuffer.splice(0);
151 }
152 if (description.type === "offer") {
153 const answerDescription = await pc.createAnswer();
154 try {
155 await pc.setLocalDescription(answerDescription);
156 } catch (e) {
157 if (e instanceof DOMException && e.name === "InvalidStateError") {
158 console.error(e);
159 return;
160 } else {
161 throw e;
162 }
163 }
164 this.notifyPeer(notification.fromPeerId, "rtc_signal_description", pc.localDescription);
165 }
166 },
167 };
168
169 export class PeerToPeer {
170 constructor(options) {
171 this.options = options;
172 this._currentPeerId = this.options.currentPeerId;
173 if (debugShowLog) {
174 console.log(
175 `%c currentPeerId:${this._currentPeerId}`,
176 "background: blue; color: white;"
177 );
178 }
179
180 // peerId -> PeerInfos
181 this.peersInfos = {};
182 this._lastRequestId = -1;
183 this._pendingRequestResolver = {};
184 this._stopped = false;
185 }
186
187 stop() {
188 this.closeAllConnections();
189 this._stopped = true;
190 }
191
192 getConnectedPeerIds() {
193 return Object.entries(this.peersInfos)
194 .filter(
195 ([id, infos]) =>
196 infos.peerConnection &&
197 infos.peerConnection.iceConnectionState === "connected" &&
198 infos.dataChannel &&
199 infos.dataChannel.readyState === "open"
200 )
201 .map(([id]) => id);
202 }
203
204 removePeer(peerId) {
205 if (debugShowLog) {
206 console.log(`%c REMOVE PEER ${peerId}`, "background: chocolate;");
207 }
208 this.notifySelf("ptp_remove", peerId);
209 const peerInfos = this.peersInfos[peerId];
210 if (!peerInfos) {
211 return;
212 }
213 clearTimeout(peerInfos.fallbackTimeout);
214 clearTimeout(peerInfos.zombieTimeout);
215 peerInfos.dataChannel && peerInfos.dataChannel.close();
216 peerInfos.peerConnection && peerInfos.peerConnection.close();
217 delete this.peersInfos[peerId];
218 }
219
220 closeAllConnections() {
221 for (const peerId of Object.keys(this.peersInfos)) {
222 this.notifyAllPeers("ptp_disconnect");
223 this.removePeer(peerId);
224 }
225 }
226
227 async notifyAllPeers(notificationName, notificationPayload, { transport = "server" } = {}) {
228 if (this._stopped) {
229 return;
230 }
231 const transportPayload = {
232 fromPeerId: this._currentPeerId,
233 notificationName,
234 notificationPayload,
235 };
236 if (transport === "server") {
237 await this.options.broadcastAll(transportPayload);
238 } else if (transport === "rtc") {
239 for (const cliendId of Object.keys(this.peersInfos)) {
240 this._channelNotify(cliendId, transportPayload);
241 }
242 } else {
243 throw new Error(
244 `Transport "${transport}" is not supported. Use "server" or "rtc" transport.`
245 );
246 }
247 }
248
249 notifyPeer(peerId, notificationName, notificationPayload, { transport = "server" } = {}) {
250 if (this._stopped) {
251 return;
252 }
253 if (debugShowNotifications) {
254 if (notificationName === "ptp_request_result") {
255 console.log(
256 `%c${Date.now()} - REQUEST RESULT SEND: %c${transport}:${
257 notificationPayload.requestId
258 }:${this._currentPeerId.slice("-5")}:${peerId.slice("-5")}`,
259 "color: #aaa;font-weight:bold;",
260 "color: #aaa;font-weight:normal"
261 );
262 } else if (notificationName === "ptp_request") {
263 console.log(
264 `%c${Date.now()} - REQUEST SEND: %c${transport}:${
265 notificationPayload.requestName
266 }|${notificationPayload.requestId}:${this._currentPeerId.slice(
267 "-5"
268 )}:${peerId.slice("-5")}`,
269 "color: #aaa;font-weight:bold;",
270 "color: #aaa;font-weight:normal"
271 );
272 } else {
273 console.log(
274 `%c${Date.now()} - NOTIFICATION SEND: %c${transport}:${notificationName}:${this._currentPeerId.slice(
275 "-5"
276 )}:${peerId.slice("-5")}`,
277 "color: #aaa;font-weight:bold;",
278 "color: #aaa;font-weight:normal"
279 );
280 }
281 }
282 const transportPayload = {
283 fromPeerId: this._currentPeerId,
284 toPeerId: peerId,
285 notificationName,
286 notificationPayload,
287 };
288 if (transport === "server") {
289 this.options.broadcastAll(transportPayload);
290 } else if (transport === "rtc") {
291 this._channelNotify(peerId, transportPayload);
292 } else {
293 throw new Error(
294 `Transport "${transport}" is not supported. Use "server" or "rtc" transport.`
295 );
296 }
297 }
298
299 notifySelf(notificationName, notificationPayload) {
300 if (this._stopped) {
301 return;
302 }
303 return this.handleNotification({ notificationName, notificationPayload });
304 }
305
306 handleNotification(notification) {
307 if (this._stopped) {
308 return;
309 }
310 const isInternalNotification =
311 typeof notification.fromPeerId === "undefined" &&
312 typeof notification.toPeerId === "undefined";
313 if (
314 isInternalNotification ||
315 (notification.fromPeerId !== this._currentPeerId && !notification.toPeerId) ||
316 notification.toPeerId === this._currentPeerId
317 ) {
318 if (debugShowNotifications) {
319 if (notification.notificationName === "ptp_request_result") {
320 console.log(
321 `%c${Date.now()} - REQUEST RESULT RECEIVE: %c${
322 notification.notificationPayload.requestId
323 }:${notification.fromPeerId.slice("-5")}:${notification.toPeerId.slice(
324 "-5"
325 )}`,
326 "color: #aaa;font-weight:bold;",
327 "color: #aaa;font-weight:normal"
328 );
329 } else if (notification.notificationName === "ptp_request") {
330 console.log(
331 `%c${Date.now()} - REQUEST RECEIVE: %c${
332 notification.notificationPayload.requestName
333 }|${
334 notification.notificationPayload.requestId
335 }:${notification.fromPeerId.slice("-5")}:${notification.toPeerId.slice(
336 "-5"
337 )}`,
338 "color: #aaa;font-weight:bold;",
339 "color: #aaa;font-weight:normal"
340 );
341 } else {
342 console.log(
343 `%c${Date.now()} - NOTIFICATION RECEIVE: %c${
344 notification.notificationName
345 }:${notification.fromPeerId}:${notification.toPeerId}`,
346 "color: #aaa;font-weight:bold;",
347 "color: #aaa;font-weight:normal"
348 );
349 }
350 }
351 try {
352 const baseMethod = baseNotificationMethods[notification.notificationName];
353 if (baseMethod) {
354 return baseMethod.call(this, notification);
355 }
356 if (this.options.onNotification) {
357 return this.options.onNotification(notification);
358 }
359 } catch (error) {
360 console.groupCollapsed("=== ERROR: On notification in collaboration ===");
361 console.error(error);
362 console.groupEnd();
363 }
364 }
365 }
366
367 requestPeer(peerId, requestName, requestPayload, { transport = "server" } = {}) {
368 if (this._stopped) {
369 return;
370 }
371 return new Promise((resolve, reject) => {
372 const requestId = this._getRequestId();
373
374 const abort = (reason) => {
375 clearTimeout(rejectTimeout);
376 delete this._pendingRequestResolver[requestId];
377 reject(new RequestError(reason || "Request was aborted."));
378 };
379 const rejectTimeout = setTimeout(
380 () => abort("Request took too long (more than 10 seconds)."),
381 10000
382 );
383
384 this._pendingRequestResolver[requestId] = {
385 resolve,
386 rejectTimeout,
387 abort,
388 };
389
390 this.notifyPeer(
391 peerId,
392 "ptp_request",
393 {
394 requestId,
395 requestName,
396 requestPayload,
397 requestTransport: transport,
398 },
399 { transport }
400 );
401 });
402 }
403 abortCurrentRequests() {
404 for (const { abort } of Object.values(this._pendingRequestResolver)) {
405 abort();
406 }
407 }
408 _createPeer(peerId, { makeOffer = true } = {}) {
409 if (this._stopped) {
410 return;
411 }
412 if (debugShowLog) {
413 console.log("CREATE CONNECTION with peer id:", peerId);
414 }
415 this.peersInfos[peerId] = {
416 makingOffer: false,
417 iceCandidateBuffer: [],
418 backoffFactor: 0,
419 };
420
421 if (!navigator.onLine) {
422 return this.peersInfos[peerId];
423 }
424 const pc = new RTCPeerConnection(this.options.peerConnectionConfig);
425
426 if (makeOffer) {
427 pc.onnegotiationneeded = async () => {
428 if (debugShowLog) {
429 console.log(
430 `%c NEGONATION NEEDED: ${pc.connectionState}`,
431 "background: deeppink;"
432 );
433 }
434 try {
435 this.peersInfos[peerId].makingOffer = true;
436 if (debugShowLog) {
437 console.log(
438 `%ccreating and sending an offer`,
439 "background: darkmagenta; color: white;"
440 );
441 }
442 const offer = await pc.createOffer();
443 // Avoid race condition.
444 if (pc.signalingState !== "stable") {
445 return;
446 }
447 await pc.setLocalDescription(offer);
448 this.notifyPeer(peerId, "rtc_signal_description", pc.localDescription);
449 } catch (err) {
450 console.error(err);
451 } finally {
452 this.peersInfos[peerId].makingOffer = false;
453 }
454 };
455 }
456 pc.onicecandidate = async (event) => {
457 if (event.candidate) {
458 this.notifyPeer(peerId, "rtc_signal_icecandidate", event.candidate);
459 }
460 };
461 pc.oniceconnectionstatechange = async () => {
462 if (debugShowLog) {
463 console.log("ICE STATE UPDATE: " + pc.iceConnectionState);
464 }
465
466 switch (pc.iceConnectionState) {
467 case "failed":
468 case "closed":
469 this.removePeer(peerId);
470 break;
471 case "disconnected":
472 if (navigator.onLine) {
473 await this._recoverConnection(peerId, {
474 delay: 3000,
475 reason: "ice connection disconnected",
476 });
477 }
478 break;
479 case "connected":
480 this.peersInfos[peerId].backoffFactor = 0;
481 break;
482 }
483 };
484 // This event does not work in FF. Let's try with oniceconnectionstatechange if it is sufficient.
485 pc.onconnectionstatechange = async () => {
486 if (debugShowLog) {
487 console.log("CONNECTION STATE UPDATE:" + pc.connectionState);
488 }
489
490 switch (pc.connectionState) {
491 case "failed":
492 case "closed":
493 this.removePeer(peerId);
494 break;
495 case "disconnected":
496 if (navigator.onLine) {
497 await this._recoverConnection(peerId, {
498 delay: 3000,
499 reason: "connection disconnected",
500 });
501 }
502 break;
503 case "connected":
504 case "completed":
505 this.peersInfos[peerId].backoffFactor = 0;
506 break;
507 }
508 };
509 pc.onicecandidateerror = async (error) => {
510 if (debugShowLog) {
511 console.groupCollapsed("=== ERROR: onIceCandidate ===");
512 console.log(
513 "connectionState: " +
514 pc.connectionState +
515 " - iceState: " +
516 pc.iceConnectionState
517 );
518 console.trace(error);
519 console.groupEnd();
520 }
521 this._recoverConnection(peerId, { delay: 3000, reason: "ice candidate error" });
522 };
523 const dataChannel = pc.createDataChannel("notifications", { negotiated: true, id: 1 });
524 let message = [];
525 dataChannel.onmessage = (event) => {
526 if (event.data !== "-") {
527 message.push(event.data);
528 } else {
529 this.handleNotification(JSON.parse(message.join("")));
530 message = [];
531 }
532 };
533 dataChannel.onopen = (event) => {
534 this.notifySelf("rtc_data_channel_open", {
535 connectionPeerId: peerId,
536 });
537 };
538
539 this.peersInfos[peerId].peerConnection = pc;
540 this.peersInfos[peerId].dataChannel = dataChannel;
541
542 return this.peersInfos[peerId];
543 }
544 async _addIceCandidate(peerInfos, candidate) {
545 const rtcIceCandidate = new RTCIceCandidate(candidate);
546 try {
547 await peerInfos.peerConnection.addIceCandidate(rtcIceCandidate);
548 } catch (error) {
549 // Ignored.
550 console.groupCollapsed("=== ERROR: ADD ICE CANDIDATE ===");
551 console.trace(error);
552 console.groupEnd();
553 }
554 }
555
556 _channelNotify(peerId, transportPayload) {
557 if (this._stopped) {
558 return;
559 }
560 const peerInfo = this.peersInfos[peerId];
561 const dataChannel = peerInfo && peerInfo.dataChannel;
562
563 if (!dataChannel || dataChannel.readyState !== "open") {
564 if (peerInfo && !peerInfo.zombieTimeout) {
565 if (debugShowLog) {
566 console.warn(
567 `Impossible to communicate with peer ${peerId}. The connection will be killed in 10 seconds if the datachannel state has not changed.`
568 );
569 }
570 this._killPotentialZombie(peerId);
571 }
572 } else {
573 const str = JSON.stringify(transportPayload);
574 const size = str.length;
575 const maxStringLength = 5000;
576 let from = 0;
577 let to = maxStringLength;
578 while (from < size) {
579 dataChannel.send(str.slice(from, to));
580 from = to;
581 to = to += maxStringLength;
582 }
583 dataChannel.send("-");
584 }
585 }
586
587 _getRequestId() {
588 this._lastRequestId++;
589 return this._lastRequestId;
590 }
591
592 async _onRequest(fromPeerId, requestId, requestName, requestPayload, requestTransport) {
593 if (this._stopped) {
594 return;
595 }
596 const requestFunction = this.options.onRequest && this.options.onRequest[requestName];
597 const result = await requestFunction({
598 fromPeerId,
599 requestId,
600 requestName,
601 requestPayload,
602 });
603 this.notifyPeer(
604 fromPeerId,
605 "ptp_request_result",
606 { requestId, result },
607 { transport: requestTransport }
608 );
609 }
610 /**
611 * Attempts a connection recovery by updating the tracks, which will start
612 * a new transaction: negotiationneeded -> offer -> answer -> ...
613 *
614 * @private
615 * @param {Object} [param1]
616 * @param {number} [param1.delay] in ms
617 * @param {string} [param1.reason]
618 */
619 _recoverConnection(peerId, { delay = 0, reason = "" } = {}) {
620 if (this._stopped) {
621 this.removePeer(peerId);
622 return;
623 }
624 const peerInfos = this.peersInfos[peerId];
625 if (!peerInfos || peerInfos.fallbackTimeout) {
626 return;
627 }
628 const backoffFactor = this.peersInfos[peerId].backoffFactor;
629 const backoffDelay = delay * Math.pow(2, backoffFactor);
630 // Stop trying to recover the connection after 10 attempts.
631 if (backoffFactor > 10) {
632 if (debugShowLog) {
633 console.log(
634 `%c STOP RTC RECOVERY: impossible to connect to peer ${peerId}: ${reason}`,
635 "background: darkred; color: white;"
636 );
637 }
638 return;
639 }
640
641 peerInfos.fallbackTimeout = setTimeout(async () => {
642 peerInfos.fallbackTimeout = undefined;
643 const pc = peerInfos.peerConnection;
644 if (!pc || pc.iceConnectionState === "connected") {
645 return;
646 }
647 if (["connected", "closed"].includes(pc.connectionState)) {
648 return;
649 }
650 // hard reset: recreating a RTCPeerConnection
651 if (debugShowLog) {
652 console.log(
653 `%c RTC RECOVERY: calling back peer ${peerId} to salvage the connection ${pc.iceConnectionState} after ${backoffDelay}ms, reason: ${reason}`,
654 "background: darkorange; color: white;"
655 );
656 }
657 this.removePeer(peerId);
658 const newPeerInfos = this._createPeer(peerId);
659 newPeerInfos.backoffFactor = backoffFactor + 1;
660 }, backoffDelay);
661 }
662 // todo: do we try to salvage the connection after killing the zombie ?
663 // Maybe the salvage should be done when the connection is dropped.
664 _killPotentialZombie(peerId) {
665 if (this._stopped) {
666 this.removePeer(peerId);
667 return;
668 }
669 const peerInfos = this.peersInfos[peerId];
670 if (!peerInfos || peerInfos.zombieTimeout) {
671 return;
672 }
673
674 // If there is no connection after 10 seconds, terminate.
675 peerInfos.zombieTimeout = setTimeout(() => {
676 if (peerInfos && peerInfos.dataChannel && peerInfos.dataChannel.readyState !== "open") {
677 if (debugShowLog) {
678 console.log(`%c KILL ZOMBIE ${peerId}`, "background: red;");
679 }
680 this.removePeer(peerId);
681 } else {
682 if (debugShowLog) {
683 console.log(`%c NOT A ZOMBIE ${peerId}`, "background: green;");
684 }
685 }
686 }, 10000);
687 }
688 }
689
690 export class RequestError extends Error {
691 constructor(message) {
692 super(message);
693 this.name = "RequestError";
694 }
695 }