1 const MinimumJitterFactor = 1
2 const MaximumJitterFactor = 1.5
3 const MaxBackoffInMilliseconds = 32_000
6 * If the connection is still connected after this time, reset backoff attempts. This is to avoid cases where a conneciton open then quickly shutters, which would bypass increasing exponentinal backoff. Instead, we wait this interval before deciding to reset connection attempts
8 const BackoffResetThresholdInMilliseconds = 10_000
10 export interface WebsocketStateInterface {
12 didFailToFetchToken(): void
19 export class WebsocketState implements WebsocketStateInterface {
21 private connected: boolean = false
22 private resetTimeout: ReturnType<typeof setTimeout> | null = null
27 if (this.resetTimeout) {
28 clearTimeout(this.resetTimeout)
31 this.resetTimeout = setTimeout(() => {
35 }, BackoffResetThresholdInMilliseconds)
39 if (this.resetTimeout) {
40 clearTimeout(this.resetTimeout)
44 didFailToFetchToken() {
45 this.incrementAttempts()
49 this.connected = false
51 this.incrementAttempts()
54 get isConnected(): boolean {
58 getBackoff(): number {
59 return this.getBackoffWithoutJitter() * this.getJitterFactor()
62 getBackoffWithoutJitter(): number {
63 const exponent = Math.max(this.attempts, 1)
64 const backoff = Math.pow(2, exponent) * 1000
66 return Math.min(backoff, MaxBackoffInMilliseconds)
69 getJitterFactor(): number {
70 return Math.random() * (MaximumJitterFactor - MinimumJitterFactor) + MinimumJitterFactor
73 get attemptCount(): number {