2

This is the old famous Chromium bug: https://bugs.chromium.org/p/chromium/issues/detail?id=825576

The error is: Failed to construct 'RTCPeerConnection': Cannot create so many PeerConnections

Now because Edge is based on Chromium, not only Chrome is affected by this bug making things even worst.

We need to find a way to force Garbage Collector cycle.

I posted my current workaround but i'd be glad to find a better workaround, if any...?

A. Wolff
  • 74,033
  • 9
  • 94
  • 155

2 Answers2

4

After some times trying to figure it out, the best workaround i found to force/invoke Garbage Collector is to create then revoke some data buffers.

Simplest fix on Chrome/Edge was to use:

URL.revokeObjectURL(URL.createObjectURL(new Blob([new ArrayBuffer(5e+7)]))) // 50Mo buffer

BUT then, this would introduce memory leaks on Firefox. On Firefox, it seems like ObjectURL cannot be revoked without being bound to DOM element. Cannot find anything about it in the spec.

So cross browser solution (Chrome/Edge/Firefox, other browsers not tested), would be:

queueMicrotask(() => { // || >> requestIdleCallback
  let img = document.createElement("img");
  img.src = window.URL.createObjectURL(new Blob([new ArrayBuffer(5e+7)])); // 50Mo
  img.onerror = function() {
    window.URL.revokeObjectURL(this.src);
    img = null
  }
})

Here is a sample working code fixing WebRTC bug:

var i = 1;

function peer() {
  var peer = new RTCPeerConnection();
  setTimeout(() => {
    peer.close();
    peer = null;
  }, 10);
  console.log(i++);
  if (!(i % 20)) {
    // try to invoke GC on each 20ish iteration
    queueMicrotask(() => { 
      let img = document.createElement("img");
      img.src = window.URL.createObjectURL(new Blob([new ArrayBuffer(5e+7)])); // 50Mo or less or more depending as you wish to force/invoke GC cycle run
      img.onerror = function() {
        window.URL.revokeObjectURL(this.src);
        img = null
      }
    })
  }
}

setInterval(peer, 20);
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
1

If you have control over the chromium process, you can actually expose the garbage collector to javascript. See the edit on this answer https://stackoverflow.com/a/13951759/1563399.

The edit states that you can add --js-flags="--expose-gc" to your launch flags. Which will then expose a global function called gc that can be called to invoke the garbage collector.

I tried using the solution A. Wolff posted here. But this seems to cause a memory leak in my embedded raspberry pi project.

luveti
  • 129
  • 4
  • 15