-
Notifications
You must be signed in to change notification settings - Fork 301
/
websocket-connection.service.ts
202 lines (175 loc) · 5.5 KB
/
websocket-connection.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import { Inject, Injectable } from '@angular/core';
import { UUID } from 'angular2-uuid';
import { environment } from 'environments/environment';
import {
BehaviorSubject, interval, NEVER, Observable, of, switchMap, tap, timer,
} from 'rxjs';
import { webSocket as rxjsWebSocket, WebSocketSubject } from 'rxjs/webSocket';
import { IncomingApiMessageType, OutgoingApiMessageType } from 'app/enums/api-message-type.enum';
import { WEBSOCKET } from 'app/helpers/websocket.helper';
import { WINDOW } from 'app/helpers/window.helper';
import { ApiEventMethod, ApiEventTyped, IncomingWebSocketMessage } from 'app/interfaces/api-message.interface';
@Injectable({
providedIn: 'root',
})
export class WebSocketConnectionService {
private ws$: WebSocketSubject<unknown>;
private readonly pingTimeoutMillis = 20 * 1000;
private readonly reconnectTimeoutMillis = 5 * 1000;
private pendingCallsBeforeConnectionReady = new Map<string, unknown>();
isTryingReconnect = false;
shutDownInProgress = false;
private connectionUrl = (this.window.location.protocol === 'https:' ? 'wss://' : 'ws://') + environment.remote + '/websocket';
private isConnectionReady = false;
private wsAsObservable$: Observable<unknown>;
get websocket$(): Observable<unknown> {
return this.wsAsObservable$;
}
readonly isConnected$ = new BehaviorSubject(false);
private readonly _isClosed$ = new BehaviorSubject(false);
private readonly _isAccessRestricted$ = new BehaviorSubject(false);
set isClosed$(value: boolean) {
this._isClosed$.next(value);
}
get isClosed$(): Observable<boolean> {
return this._isClosed$;
}
set isAccessRestricted$(value: boolean) {
this._isAccessRestricted$.next(value);
}
get isAccessRestricted$(): Observable<boolean> {
return this._isAccessRestricted$;
}
constructor(
@Inject(WINDOW) protected window: Window,
@Inject(WEBSOCKET) private webSocket: typeof rxjsWebSocket,
) {
this.initializeWebSocket();
this.subscribeToConnectionStatus();
this.setupPing();
}
private initializeWebSocket(): void {
if (this.ws$) {
this.ws$.complete();
}
this.ws$ = this.webSocket({
url: this.connectionUrl,
openObserver: {
next: this.onOpen.bind(this),
},
closeObserver: {
next: this.onClose.bind(this),
},
});
this.wsAsObservable$ = this.ws$.asObservable().pipe(
switchMap((data: IncomingWebSocketMessage) => {
if (this.hasAuthError(data)) {
console.error(data);
this.ws$.complete();
}
return of(data);
}),
);
// At least one explicit subscription required to keep the connection open
this.ws$.pipe(
tap((response: IncomingWebSocketMessage) => {
if (response.msg === IncomingApiMessageType.Connected) {
this.isConnected$.next(true);
}
}),
).subscribe();
}
private onOpen(): void {
if (this.isTryingReconnect) {
this.closeWebSocketConnection();
return;
}
this.shutDownInProgress = false;
this.sendConnectMessage();
}
/** TODO: Extract disconnection logic somewhere else */
private onClose(event: CloseEvent): void {
if (this.isTryingReconnect) {
return;
}
this.isTryingReconnect = true;
this.isConnected$.next(false);
this.isClosed$ = true;
if (event.code === 1008) {
this.isAccessRestricted$ = true;
} else {
this.reconnect();
}
}
reconnect(): void {
timer(this.reconnectTimeoutMillis).subscribe({
next: () => {
this.isTryingReconnect = false;
this.initializeWebSocket();
},
});
}
private hasAuthError(data: IncomingWebSocketMessage): boolean {
return 'error' in data && data.error.error === 207;
}
private setupPing(): void {
this.isConnected$.pipe(
switchMap((isConnected) => {
if (!isConnected) {
return NEVER;
}
return interval(this.pingTimeoutMillis);
}),
).subscribe(() => {
this.ws$.next({ msg: OutgoingApiMessageType.Ping, id: UUID.UUID() });
});
}
private sendConnectMessage(): void {
this.ws$.next({
msg: OutgoingApiMessageType.Connect,
version: '1',
support: ['1'],
});
}
buildSubscriber<K extends ApiEventMethod, R extends ApiEventTyped<K>>(name: K): Observable<R> {
const id = UUID.UUID();
return this.ws$.multiplex(
() => ({ id, name, msg: OutgoingApiMessageType.Sub }),
() => ({ id, msg: OutgoingApiMessageType.UnSub }),
(message: R) => (message.collection === name && message.msg !== IncomingApiMessageType.NoSub),
) as Observable<R>;
}
send(payload: unknown): void {
if (this.isConnectionReady) {
this.ws$.next(payload);
} else {
this.pendingCallsBeforeConnectionReady.set(UUID.UUID(), payload);
}
}
sendPendingCalls(): void {
this.pendingCallsBeforeConnectionReady.forEach((value, key) => {
this.send(value);
this.pendingCallsBeforeConnectionReady.delete(key);
});
}
closeWebSocketConnection(): void {
this.ws$.complete();
}
prepareShutdown(): void {
this.shutDownInProgress = true;
}
setupConnectionUrl(protocol: string, remote: string): void {
this.connectionUrl = (protocol === 'https:' ? 'wss://' : 'ws://')
+ remote + '/websocket';
}
private subscribeToConnectionStatus(): void {
this.isConnected$.subscribe({
next: (isConnected) => {
this.isConnectionReady = isConnected;
if (isConnected) {
this.sendPendingCalls();
}
},
});
}
}