2019-02-03 22:31:47 +00:00
|
|
|
import {camelCase} from 'lodash';
|
|
|
|
import SocketEmitter from './emitter';
|
|
|
|
import {Store} from "vuex";
|
|
|
|
|
2019-05-02 03:12:20 +00:00
|
|
|
const SOCKET_CONNECT = 'connect';
|
|
|
|
const SOCKET_ERROR = 'error';
|
|
|
|
const SOCKET_DISCONNECT = 'disconnect';
|
|
|
|
|
|
|
|
// This is defined in the wings daemon code and referenced here so that it is obvious
|
|
|
|
// where we are pulling these random data objects from.
|
|
|
|
type WingsWebsocketResponse = {
|
|
|
|
event: string,
|
|
|
|
args: Array<string>
|
|
|
|
}
|
2019-02-03 22:31:47 +00:00
|
|
|
|
|
|
|
export default class SocketioConnector {
|
|
|
|
/**
|
|
|
|
* The socket instance.
|
|
|
|
*/
|
2019-05-02 03:12:20 +00:00
|
|
|
socket: null | WebSocket;
|
2019-02-03 22:31:47 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* The vuex store being used to persist data and socket state.
|
|
|
|
*/
|
|
|
|
store: Store<any> | undefined;
|
|
|
|
|
2019-05-10 05:42:53 +00:00
|
|
|
/**
|
|
|
|
* Tracks a reconnect attempt for the websocket. Will gradually back off on attempts
|
|
|
|
* after a certain period of time has elapsed.
|
|
|
|
*/
|
|
|
|
private reconnectTimeout: any;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Tracks the number of reconnect attempts which is used to determine the backoff
|
|
|
|
* throttle for connections.
|
|
|
|
*/
|
|
|
|
private reconnectAttempts: number = 0;
|
|
|
|
|
|
|
|
private socketProtocol?: string;
|
|
|
|
private socketUrl?: string;
|
|
|
|
|
2019-02-03 22:31:47 +00:00
|
|
|
constructor(store: Store<any> | undefined) {
|
|
|
|
this.socket = null;
|
|
|
|
this.store = store;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Initialize a new Socket connection.
|
|
|
|
*/
|
2019-05-10 05:42:53 +00:00
|
|
|
public connect(url: string, protocol?: string): void {
|
|
|
|
this.socketUrl = url;
|
|
|
|
this.socketProtocol = protocol;
|
|
|
|
|
|
|
|
this.connectToSocket()
|
|
|
|
.then(socket => {
|
|
|
|
this.socket = socket;
|
|
|
|
this.emitAndPassToStore(SOCKET_CONNECT);
|
|
|
|
this.registerEventListeners();
|
|
|
|
})
|
|
|
|
.catch(() => this.reconnectToSocket());
|
2019-02-03 22:31:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return the socket instance we are working with.
|
|
|
|
*/
|
2019-05-10 05:42:53 +00:00
|
|
|
public instance(): WebSocket | null {
|
2019-02-03 22:31:47 +00:00
|
|
|
return this.socket;
|
|
|
|
}
|
|
|
|
|
2019-05-02 03:12:20 +00:00
|
|
|
/**
|
|
|
|
* Sends an event along to the websocket. If there is no active connection, a void
|
|
|
|
* result is returned.
|
|
|
|
*/
|
2019-05-10 05:42:53 +00:00
|
|
|
public emit(event: string, payload?: string | Array<string>): void | false {
|
2019-05-02 03:12:20 +00:00
|
|
|
if (!this.socket) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
this.socket.send(JSON.stringify({
|
|
|
|
event, args: typeof payload === 'string' ? [payload] : payload
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
|
2019-02-03 22:31:47 +00:00
|
|
|
/**
|
|
|
|
* Register the event listeners for this socket including user-defined ones in the store as
|
|
|
|
* well as global system events from Socekt.io.
|
|
|
|
*/
|
2019-05-10 05:42:53 +00:00
|
|
|
protected registerEventListeners() {
|
2019-02-03 22:31:47 +00:00
|
|
|
if (!this.socket) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2019-05-10 05:42:53 +00:00
|
|
|
this.socket.onclose = () => {
|
|
|
|
this.reconnectToSocket();
|
|
|
|
this.emitAndPassToStore(SOCKET_DISCONNECT);
|
|
|
|
};
|
|
|
|
|
2019-05-02 03:12:20 +00:00
|
|
|
this.socket.onerror = () => {
|
2019-05-10 05:42:53 +00:00
|
|
|
if (this.socket && this.socket.readyState !== WebSocket.OPEN) {
|
2019-05-02 03:12:20 +00:00
|
|
|
this.emitAndPassToStore(SOCKET_ERROR, ['Failed to connect to websocket.']);
|
|
|
|
}
|
2019-02-03 22:31:47 +00:00
|
|
|
};
|
|
|
|
|
2019-05-02 03:12:20 +00:00
|
|
|
this.socket.onmessage = (wse): void => {
|
|
|
|
try {
|
|
|
|
let {event, args}: WingsWebsocketResponse = JSON.parse(wse.data);
|
2019-02-03 22:31:47 +00:00
|
|
|
|
2019-05-02 03:12:20 +00:00
|
|
|
this.emitAndPassToStore(event, args);
|
|
|
|
} catch (ex) {
|
|
|
|
// do nothing, bad JSON response
|
|
|
|
console.error(ex);
|
|
|
|
return
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2019-05-10 05:42:53 +00:00
|
|
|
/**
|
|
|
|
* Performs an actual socket connection, wrapped as a Promise for an easier interface.
|
|
|
|
*/
|
|
|
|
protected connectToSocket(): Promise<WebSocket> {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
let hasReturned = false;
|
|
|
|
const socket = new WebSocket(this.socketUrl!, this.socketProtocol);
|
|
|
|
|
|
|
|
socket.onopen = () => {
|
|
|
|
if (hasReturned) {
|
|
|
|
socket && socket.close();
|
|
|
|
}
|
|
|
|
|
|
|
|
hasReturned = true;
|
|
|
|
this.resetConnectionAttempts();
|
|
|
|
resolve(socket);
|
|
|
|
};
|
|
|
|
|
|
|
|
const rejectFunc = () => {
|
|
|
|
if (!hasReturned) {
|
|
|
|
hasReturned = true;
|
|
|
|
this.emitAndPassToStore(SOCKET_ERROR, ['Failed to connect to websocket.']);
|
|
|
|
reject();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
socket.onerror = rejectFunc;
|
|
|
|
socket.onclose = rejectFunc;
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Attempts to reconnect to the socket instance if it becomes disconnected.
|
|
|
|
*/
|
|
|
|
private reconnectToSocket() {
|
|
|
|
const { socket } = this;
|
|
|
|
if (!socket) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Clear the existing timeout if one exists for some reason.
|
|
|
|
this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
|
|
|
|
|
|
|
|
this.reconnectTimeout = setTimeout(() => {
|
|
|
|
console.warn(`Attempting to reconnect to websocket [${this.reconnectAttempts}]...`);
|
|
|
|
|
|
|
|
this.reconnectAttempts++;
|
|
|
|
this.connect(this.socketUrl!, this.socketProtocol);
|
|
|
|
}, this.getIntervalTimeout());
|
|
|
|
}
|
|
|
|
|
|
|
|
private resetConnectionAttempts() {
|
|
|
|
this.reconnectTimeout && clearTimeout(this.reconnectTimeout);
|
|
|
|
this.reconnectAttempts = 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Determine the amount of time we should wait before attempting to reconnect to the socket.
|
|
|
|
*/
|
|
|
|
private getIntervalTimeout(): number {
|
|
|
|
if (this.reconnectAttempts < 10) {
|
|
|
|
return 50;
|
|
|
|
} else if (this.reconnectAttempts < 25) {
|
|
|
|
return 500;
|
|
|
|
} else if (this.reconnectAttempts < 50) {
|
|
|
|
return 1000;
|
|
|
|
}
|
|
|
|
|
|
|
|
return 2500;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2019-05-02 03:12:20 +00:00
|
|
|
/**
|
|
|
|
* Emits the event over the event emitter and also passes it along to the vuex store.
|
|
|
|
*/
|
2019-05-10 05:42:53 +00:00
|
|
|
private emitAndPassToStore(event: string, payload?: Array<string>) {
|
2019-05-02 03:12:20 +00:00
|
|
|
payload ? SocketEmitter.emit(event, ...payload) : SocketEmitter.emit(event);
|
|
|
|
this.passToStore(event, payload);
|
2019-02-03 22:31:47 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Pass event calls off to the Vuex store if there is a corresponding function.
|
|
|
|
*/
|
2019-05-10 05:42:53 +00:00
|
|
|
private passToStore(event: string, payload?: Array<string>) {
|
2019-02-03 22:31:47 +00:00
|
|
|
if (!this.store) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
const s: Store<any> = this.store;
|
2019-05-02 03:12:20 +00:00
|
|
|
const mutation = `SOCKET_${event.toUpperCase()}`;
|
|
|
|
const action = `socket_${camelCase(event)}`;
|
2019-02-03 22:31:47 +00:00
|
|
|
|
|
|
|
// @ts-ignore
|
|
|
|
Object.keys(this.store._mutations).filter((namespaced: string): boolean => {
|
|
|
|
return namespaced.split('/').pop() === mutation;
|
|
|
|
}).forEach((namespaced: string): void => {
|
2019-05-02 03:12:20 +00:00
|
|
|
s.commit(namespaced, payload ? this.unwrap(payload) : null);
|
2019-02-03 22:31:47 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
// @ts-ignore
|
|
|
|
Object.keys(this.store._actions).filter((namespaced: string): boolean => {
|
|
|
|
return namespaced.split('/').pop() === action;
|
|
|
|
}).forEach((namespaced: string): void => {
|
2019-05-02 03:12:20 +00:00
|
|
|
s.dispatch(namespaced, payload ? this.unwrap(payload) : null).catch(console.error);
|
2019-02-03 22:31:47 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2019-05-10 05:42:53 +00:00
|
|
|
private unwrap(args: Array<string>) {
|
2019-02-03 22:31:47 +00:00
|
|
|
return (args && args.length <= 1) ? args[0] : args;
|
|
|
|
}
|
|
|
|
}
|