You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Backend.ts 4.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. 'use strict'
  2. import http = require('http');
  3. import bsock = require('bsock');
  4. import * as T from './Types';
  5. import * as U from './Utils';
  6. import * as I from './Interfaces';
  7. import { Socket } from 'dgram';
  8. type Exporters<InterfaceT extends T.RPCInterface = T.RPCInterface, SubResType = {}> = I.RPCExporter<T.RPCInterface<InterfaceT>, keyof InterfaceT, SubResType>[]
  9. /**
  10. * A Websocket-server-on-steroids with built-in RPC capabilities
  11. */
  12. export class RPCServer<
  13. SubResType = {},
  14. InterfaceT extends T.RPCInterface = T.RPCInterface,
  15. > implements I.Destroyable{
  16. private ws = http.createServer()
  17. private io = bsock.createServer()
  18. private visibility:T.Visibility
  19. private closeHandler:T.CloseHandler
  20. private errorHandler: T.ErrorHandler
  21. private connectionHandler: T.ConnectionHandler
  22. private sesame? : T.SesameFunction
  23. private accessFilter: T.AccessFilter<InterfaceT, SubResType>
  24. /**
  25. * @throws On RPC with no name
  26. * @param port The port to listen on
  27. * @param exporters A list of {@link RPCExporter} to publish
  28. * @param conf A {@link SocketConf} object with optional settings
  29. */
  30. constructor(
  31. private port:number,
  32. private exporters: Exporters<InterfaceT, SubResType> = [],
  33. conf: T.ServerConf<InterfaceT, SubResType> = {}
  34. ){
  35. if(!conf.visibility) this.visibility = "127.0.0.1"
  36. this.accessFilter = conf.accessFilter || (async () => true)
  37. if(conf.sesame){
  38. this.sesame = U.makeSesameFunction(conf.sesame)
  39. }
  40. this.errorHandler = (socket:I.Socket) => (error:any, rpcName:string, args: any[]) => {
  41. if(conf.errorHandler) conf.errorHandler(socket, error, rpcName, args)
  42. else throw error
  43. }
  44. this.closeHandler = (socket:I.Socket) => {
  45. if(conf.closeHandler) conf.closeHandler(socket)
  46. }
  47. this.connectionHandler = (socket:I.Socket) => {
  48. if(conf.connectionHandler) conf.connectionHandler(socket)
  49. }
  50. exporters.forEach(U.fixNames) //TSC for some reason doesn't preserve name properties of methods
  51. let badRPC = exporters.flatMap(ex => ex.exportRPCs()).find(rpc => !rpc.name)
  52. if(badRPC){
  53. throw new Error(`
  54. RPC did not provide a name.
  55. \nUse 'funtion name(..){ .. }' syntax instead.
  56. \n
  57. \n<------------OFFENDING RPC:
  58. \n`+badRPC.toString()+`
  59. \n>------------OFFENDING RPC`)
  60. }
  61. this.startWebsocket()
  62. }
  63. private startWebsocket(){
  64. try{
  65. this.io.attach(this.ws)
  66. this.io.on('socket', (socket:I.Socket) => {
  67. socket.on('error', (err) => this.errorHandler(socket, err, "system", []))
  68. socket.on('close', () => this.closeHandler(socket))
  69. this.connectionHandler(socket)
  70. this.initRPCs(socket)
  71. })
  72. this.ws.listen(this.port, this.visibility)
  73. }catch(e){
  74. this.errorHandler(this.io, e, 'system', [])
  75. }
  76. }
  77. protected initRPCs(socket:I.Socket){
  78. socket.hook('info', async (sesame? : string) => {
  79. const rpcs = await Promise.all(this.exporters.map(async exp => {
  80. const allowed = await this.accessFilter(sesame, exp)
  81. if(!allowed) return []
  82. return U.rpcHooker(socket, exp, this.errorHandler, this.sesame)
  83. }))
  84. return rpcs.flat()
  85. })
  86. }
  87. /**
  88. * Publishes a new list of Exporters. This destroys and restarts the socket
  89. * @param exporters the exporters to publish
  90. */
  91. public setExporters(exporters: Exporters<InterfaceT, SubResType>):any{
  92. exporters.forEach(U.fixNames)
  93. this.destroy()
  94. this.ws = http.createServer()
  95. this.io = bsock.createServer()
  96. this.exporters = exporters
  97. this.startWebsocket()
  98. }
  99. destroy(): void {
  100. this.io.close()
  101. this.ws.close()
  102. }
  103. }