-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathws-connection-provider.ts
154 lines (135 loc) · 5.62 KB
/
ws-connection-provider.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
// *****************************************************************************
// Copyright (C) 2018 TypeFox and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0.
//
// This Source Code may also be made available under the following Secondary
// Licenses when the conditions for such availability set forth in the Eclipse
// Public License v. 2.0 are satisfied: GNU General Public License, version 2
// with the GNU Classpath Exception which is available at
// https://www.gnu.org/software/classpath/license.html.
//
// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
// *****************************************************************************
import { injectable, interfaces, decorate, unmanaged } from 'inversify';
import { JsonRpcProxyFactory, JsonRpcProxy, Emitter, Event, Channel } from '../../common';
import { Endpoint } from '../endpoint';
import { AbstractConnectionProvider } from '../../common/messaging/abstract-connection-provider';
import { io, Socket } from 'socket.io-client';
import { IWebSocket, WebSocketChannel } from '../../common/messaging/web-socket-channel';
decorate(injectable(), JsonRpcProxyFactory);
decorate(unmanaged(), JsonRpcProxyFactory, 0);
export interface WebSocketOptions {
/**
* True by default.
*/
reconnecting?: boolean;
}
@injectable()
export class WebSocketConnectionProvider extends AbstractConnectionProvider<WebSocketOptions> {
protected readonly onSocketDidOpenEmitter: Emitter<void> = new Emitter();
get onSocketDidOpen(): Event<void> {
return this.onSocketDidOpenEmitter.event;
}
protected readonly onSocketDidCloseEmitter: Emitter<void> = new Emitter();
get onSocketDidClose(): Event<void> {
return this.onSocketDidCloseEmitter.event;
}
static override createProxy<T extends object>(container: interfaces.Container, path: string, arg?: object): JsonRpcProxy<T> {
return container.get(WebSocketConnectionProvider).createProxy<T>(path, arg);
}
protected readonly socket: Socket;
constructor() {
super();
const url = this.createWebSocketUrl(WebSocketChannel.wsPath);
this.socket = this.createWebSocket(url);
this.socket.on('connect', () => {
this.initializeMultiplexer();
if (this.reconnectChannelOpeners.length > 0) {
this.reconnectChannelOpeners.forEach(opener => opener());
this.reconnectChannelOpeners = [];
}
this.socket.on('disconnect', () => this.fireSocketDidClose());
this.socket.on('message', () => this.onIncomingMessageActivityEmitter.fire(undefined));
this.fireSocketDidOpen();
});
this.socket.connect();
}
protected createMainChannel(): Channel {
return new WebSocketChannel(this.toIWebSocket(this.socket));
}
protected toIWebSocket(socket: Socket): IWebSocket {
return {
close: () => {
socket.removeAllListeners('disconnect');
socket.removeAllListeners('error');
socket.removeAllListeners('message');
},
isConnected: () => socket.connected,
onClose: cb => socket.on('disconnect', reason => cb(reason)),
onError: cb => socket.on('error', reason => cb(reason)),
onMessage: cb => socket.on('message', data => cb(data)),
send: message => socket.emit('message', message)
};
}
override async openChannel(path: string, handler: (channel: Channel) => void, options?: WebSocketOptions): Promise<void> {
if (this.socket.connected) {
return super.openChannel(path, handler, options);
} else {
const openChannel = () => {
this.socket.off('connect', openChannel);
this.openChannel(path, handler, options);
};
this.socket.on('connect', openChannel);
}
}
/**
* @param path The handler to reach in the backend.
*/
protected createWebSocketUrl(path: string): string {
// Since we are using Socket.io, the path should look like the following:
// proto://domain.com/{path}
return new Endpoint().getWebSocketUrl().withPath(path).toString();
}
protected createHttpWebSocketUrl(path: string): string {
return new Endpoint({ path }).getRestUrl().toString();
}
/**
* Creates a web socket for the given url
*/
protected createWebSocket(url: string): Socket {
return io(url, {
path: this.createSocketIoPath(url),
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 10000,
reconnectionAttempts: Infinity,
extraHeaders: {
// Socket.io strips the `origin` header
// We need to provide our own for validation
'fix-origin': window.location.origin
}
});
}
/**
* Path for Socket.io to make its requests to.
*/
protected createSocketIoPath(url: string): string | undefined {
if (location.protocol === Endpoint.PROTO_FILE) {
return '/socket.io';
}
let { pathname } = location;
if (!pathname.endsWith('/')) {
pathname += '/';
}
return pathname + 'socket.io';
}
protected fireSocketDidOpen(): void {
this.onSocketDidOpenEmitter.fire(undefined);
}
protected fireSocketDidClose(): void {
this.onSocketDidCloseEmitter.fire(undefined);
}
}