[CouchDB] Re-establish feed connection if EventSource is closed due to error (#5845)

* Re-establish feed connection if EventSource is closed due to error

* Use keepAlive timer

* Get rid of magic numbers and add comment
This commit is contained in:
Jesse Mazzella 2022-10-06 12:41:38 -07:00 committed by GitHub
parent afc54f41f6
commit 866859a937
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -2,6 +2,9 @@
const connections = []; const connections = [];
let connected = false; let connected = false;
let couchEventSource; let couchEventSource;
let changesFeedUrl;
const keepAliveTime = 20 * 1000;
let keepAliveTimer;
const controller = new AbortController(); const controller = new AbortController();
self.onconnect = function (e) { self.onconnect = function (e) {
@ -35,7 +38,8 @@
return; return;
} }
self.listenForChanges(event.data.url); changesFeedUrl = event.data.url;
self.listenForChanges();
} }
}; };
@ -63,17 +67,28 @@
}); });
}; };
self.listenForChanges = function (url) { self.listenForChanges = function () {
console.debug('⇿ Opening CouchDB change feed connection ⇿'); if (keepAliveTimer) {
clearTimeout(keepAliveTimer);
}
couchEventSource = new EventSource(url); /**
couchEventSource.onerror = self.onerror; * Once the connection has been opened, poll every 20 seconds to see if the EventSource has closed unexpectedly.
couchEventSource.onopen = self.onopen; * If it has, attempt to reconnect.
*/
keepAliveTimer = setTimeout(self.listenForChanges, keepAliveTime);
// start listening for events if (!couchEventSource || couchEventSource.readyState === EventSource.CLOSED) {
couchEventSource.addEventListener('message', self.onCouchMessage); console.debug('⇿ Opening CouchDB change feed connection ⇿');
connected = true; couchEventSource = new EventSource(changesFeedUrl);
console.debug('⇿ Opened connection ⇿'); couchEventSource.onerror = self.onerror;
couchEventSource.onopen = self.onopen;
// start listening for events
couchEventSource.addEventListener('message', self.onCouchMessage);
connected = true;
console.debug('⇿ Opened connection ⇿');
}
}; };
self.updateCouchStateIndicator = function () { self.updateCouchStateIndicator = function () {