'use strict' import http = require('http'); import bsock = require('bsock'); import * as T from './Types'; import * as U from './Utils'; import * as I from './Interfaces'; /** * A Websocket-server-on-steroids with built-in RPC capabilities */ export class RPCServer< SubResType = {} > implements I.Destroyable{ private ws = http.createServer() private io = bsock.createServer() private visibility:T.Visibility private closeHandler:T.CloseHandler private errorHandler: T.ErrorHandler private connectionHandler: T.ConnectionHandler /** * @throws On RPC with no name * @param port The port to listen on * @param exporters A list of {@link RPCExporter} to publish * @param conf A {@link SocketConf} object with optional settings */ constructor( private port:number, private exporters: I.RPCExporter[] = [], conf: T.SocketConf = {} ){ if(!conf.visibility) this.visibility = "127.0.0.1" this.errorHandler = (socket:I.Socket) => (error:any) => { if(conf.errorHandler) conf.errorHandler(socket, error) socket.destroy(); console.error("Caught websocket error", String(error)) } this.closeHandler = (socket:I.Socket) => { if(!conf.closeHandler) console.log("Socket on port "+socket.port+" closing") else conf.closeHandler(socket) } this.connectionHandler = (socket:I.Socket) => { if(!conf.connectionHandler) console.log("New websocket connection on port "+socket.port) else conf.connectionHandler(socket) } let badRPC if(badRPC = exporters.flatMap(ex => ex.exportRPCs()).find(rpc => !rpc.name)) throw new Error(` RPC did not provide a name. \nUse 'funtion name(..){ .. }' syntax instead. \n \n<------------OFFENDING RPC: \n`+badRPC.toString()+` \n>------------OFFENDING RPC`) this.startWebsocket() } private startWebsocket(){ try{ this.io.attach(this.ws) this.io.on('socket', (socket:I.Socket) => { socket.on('error', (err) => this.errorHandler(socket, err)) socket.on('close', () => this.closeHandler(socket)) this.connectionHandler(socket) this.initRPCs(socket) }) this.ws.listen(this.port, this.visibility) }catch(e){ //@ts-ignore this.errorHandler(undefined)("Unable to connect to socket") } } protected initRPCs(socket:I.Socket){ socket.hook('info', () => rpcInfos) const rpcInfos:T.ExtendedRpcInfo[] = [ ...this.exporters.flatMap(exporter => U.rpcHooker(socket, exporter)) ] } async destroy(): Promise { this.io.close() this.ws.close() } }