| 1 |
/* eslint-disable max-classes-per-file */ |
| 2 |
import { basicAuth, bearerAuth, encodeBase64Url, topicShortUrl, topicUrlWs } from "./utils"; |
| 3 |
import { EVENT_OPEN, isNotificationEvent } from "./events"; |
| 4 |
|
| 5 |
const retryBackoffSeconds = [5, 10, 20, 30, 60, 120]; |
| 6 |
|
| 7 |
export class ConnectionState { |
| 8 |
static Connected = "connected"; |
| 9 |
|
| 10 |
static Connecting = "connecting"; |
| 11 |
} |
| 12 |
|
| 13 |
/** |
| 14 |
* A connection contains a single WebSocket connection for one topic. It handles its connection |
| 15 |
* status itself, including reconnect attempts and backoff. |
| 16 |
* |
| 17 |
* Incoming messages and state changes are forwarded via listeners. |
| 18 |
*/ |
| 19 |
class Connection { |
| 20 |
constructor(connectionId, subscriptionId, baseUrl, topic, user, since, onNotification, onStateChanged) { |
| 21 |
this.connectionId = connectionId; |
| 22 |
this.subscriptionId = subscriptionId; |
| 23 |
this.baseUrl = baseUrl; |
| 24 |
this.topic = topic; |
| 25 |
this.user = user; |
| 26 |
this.since = since; |
| 27 |
this.shortUrl = topicShortUrl(baseUrl, topic); |
| 28 |
this.onNotification = onNotification; |
| 29 |
this.onStateChanged = onStateChanged; |
| 30 |
this.ws = null; |
| 31 |
this.retryCount = 0; |
| 32 |
this.retryTimeout = null; |
| 33 |
} |
| 34 |
|
| 35 |
start() { |
| 36 |
// Don't fetch old messages; we do that as a poll() when adding a subscription; |
| 37 |
// we don't want to re-trigger the main view re-render potentially hundreds of times. |
| 38 |
|
| 39 |
const wsUrl = this.wsUrl(); |
| 40 |
console.log(`[Connection, ${this.shortUrl}, ${this.connectionId}] Opening connection to ${wsUrl}`); |
| 41 |
|
| 42 |
this.ws = new WebSocket(wsUrl); |
| 43 |
this.ws.onopen = (event) => { |
| 44 |
console.log(`[Connection, ${this.shortUrl}, ${this.connectionId}] Connection established`, event); |
| 45 |
this.retryCount = 0; |
| 46 |
this.onStateChanged(this.subscriptionId, ConnectionState.Connected); |
| 47 |
}; |
| 48 |
this.ws.onmessage = (event) => { |
| 49 |
console.log(`[Connection, ${this.shortUrl}, ${this.connectionId}] Message received from server: ${event.data}`); |
| 50 |
try { |
| 51 |
const data = JSON.parse(event.data); |
| 52 |
if (data.event === EVENT_OPEN) { |
| 53 |
return; |
| 54 |
} |
| 55 |
// Accept message, message_delete, and message_clear events |
| 56 |
const relevantAndValid = isNotificationEvent(data.event) && "id" in data && "time" in data; |
| 57 |
if (!relevantAndValid) { |
| 58 |
console.log(`[Connection, ${this.shortUrl}, ${this.connectionId}] Unexpected message. Ignoring.`); |
| 59 |
return; |
| 60 |
} |
| 61 |
this.since = data.id; |
| 62 |
this.onNotification(this.subscriptionId, data); |
| 63 |
} catch (e) { |
| 64 |
console.log(`[Connection, ${this.shortUrl}, ${this.connectionId}] Error handling message: ${e}`); |
| 65 |
} |
| 66 |
}; |
| 67 |
this.ws.onclose = (event) => { |
| 68 |
if (event.wasClean) { |
| 69 |
console.log( |
| 70 |
`[Connection, ${this.shortUrl}, ${this.connectionId}] Connection closed cleanly, code=${event.code} reason=${event.reason}`, |
| 71 |
); |
| 72 |
this.ws = null; |
| 73 |
} else { |
| 74 |
const retrySeconds = retryBackoffSeconds[Math.min(this.retryCount, retryBackoffSeconds.length - 1)]; |
| 75 |
this.retryCount += 1; |
| 76 |
console.log(`[Connection, ${this.shortUrl}, ${this.connectionId}] Connection died, retrying in ${retrySeconds} seconds`); |
| 77 |
this.retryTimeout = setTimeout(() => this.start(), retrySeconds * 1000); |
| 78 |
this.onStateChanged(this.subscriptionId, ConnectionState.Connecting); |
| 79 |
} |
| 80 |
}; |
| 81 |
this.ws.onerror = (event) => { |
| 82 |
console.log(`[Connection, ${this.shortUrl}, ${this.connectionId}] Error occurred: ${event}`, event); |
| 83 |
}; |
| 84 |
} |
| 85 |
|
| 86 |
close() { |
| 87 |
console.log(`[Connection, ${this.shortUrl}, ${this.connectionId}] Closing connection`); |
| 88 |
const socket = this.ws; |
| 89 |
const { retryTimeout } = this; |
| 90 |
if (socket !== null) { |
| 91 |
socket.close(); |
| 92 |
} |
| 93 |
if (retryTimeout !== null) { |
| 94 |
clearTimeout(retryTimeout); |
| 95 |
} |
| 96 |
this.retryTimeout = null; |
| 97 |
this.ws = null; |
| 98 |
} |
| 99 |
|
| 100 |
wsUrl() { |
| 101 |
const params = []; |
| 102 |
if (this.since) { |
| 103 |
params.push(`since=${this.since}`); |
| 104 |
} |
| 105 |
if (this.user) { |
| 106 |
params.push(`auth=${this.authParam()}`); |
| 107 |
} |
| 108 |
const wsUrl = topicUrlWs(this.baseUrl, this.topic); |
| 109 |
return params.length === 0 ? wsUrl : `${wsUrl}?${params.join("&")}`; |
| 110 |
} |
| 111 |
|
| 112 |
authParam() { |
| 113 |
if (this.user.password) { |
| 114 |
return encodeBase64Url(basicAuth(this.user.username, this.user.password)); |
| 115 |
} |
| 116 |
return encodeBase64Url(bearerAuth(this.user.token)); |
| 117 |
} |
| 118 |
} |
| 119 |
|
| 120 |
export default Connection; |