'use strict' import http = require('http'); import { PromiseIO } from "./PromiseIO/Server"; import * as T from './Types'; import * as U from './Utils'; import * as I from './Interfaces'; export class RPCServer< InterfaceT extends T.RPCInterface = T.RPCInterface, > { private pio = PromiseIO.createServer() private closeHandler: T.CloseHandler private errorHandler: T.ErrorHandler private connectionHandler: T.ConnectionHandler private sesame?: T.SesameFunction private accessFilter: T.AccessFilter private attached = false /** * @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 exporters: T.ExporterArray = [], conf: T.ServerConf = {}, ) { if (conf.sesame) { this.sesame = U.makeSesameFunction(conf.sesame) } this.accessFilter = conf.accessFilter || (async (sesame) => { if (!this.sesame) return true return this.sesame!(sesame!) }) this.errorHandler = (socket: I.Socket | PromiseIO) => (error: any, rpcName: string, args: any[]) => { if (conf.errorHandler) conf.errorHandler(socket, error, rpcName, args) else throw error } this.closeHandler = (socket: I.Socket) => { if (conf.closeHandler) conf.closeHandler(socket) } this.connectionHandler = (socket: I.Socket) => { if (conf.connectionHandler) conf.connectionHandler(socket) } exporters.forEach(U.fixNames) //TSC for some reason doesn't preserve name properties of methods let badRPC = exporters.flatMap(ex => typeof ex.RPCs === "function"?ex.RPCs():(ex as any)).find(rpc => !rpc.name) if (badRPC) { throw new Error(` RPC did not provide a name. \nUse 'funtion name(..){ .. }' syntax instead. \n \n<------------OFFENDING RPC: \n`+ badRPC.toString() + ` \n>------------OFFENDING RPC`) } try { this.pio.on('socket', (socket: I.Socket) => { socket.on('error', (err) => this.errorHandler(socket, err, "system", [])) socket.on('close', () => this.closeHandler(socket)) this.connectionHandler(socket) this.initRPCs(socket) }) } catch (e) { this.errorHandler(this.pio, e, 'system', []) } } public attach = (httpServer = new http.Server()) : RPCServer => { this.pio.attach(httpServer) this.attached = true return this } public listen(port:number) : RPCServer{ if(!this.attached) this.attach() this.pio.listen(port) return this } protected initRPCs(socket: I.Socket) { socket.hook('info', async (sesame?: string) => { const rpcs = await Promise.all(this.exporters.map(async exp => { const allowed = await this.accessFilter(sesame, exp) if (!allowed) return [] return U.rpcHooker(socket, exp, this.errorHandler, this.sesame) })) return rpcs.flat() }) } close(): void { this.pio.close() } }