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 3.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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. /**
  8. * A Websocket-server-on-steroids with built-in RPC capabilities
  9. */
  10. export class RPCServer<
  11. InterfaceT extends T.RPCInterface = T.RPCInterface,
  12. > implements I.Destroyable {
  13. private ws = http.createServer()
  14. private io = bsock.createServer()
  15. private visibility: T.Visibility
  16. private closeHandler: T.CloseHandler
  17. private errorHandler: T.ErrorHandler
  18. private connectionHandler: T.ConnectionHandler
  19. private sesame?: T.SesameFunction
  20. private accessFilter: T.AccessFilter<InterfaceT>
  21. /**
  22. * @throws On RPC with no name
  23. * @param port The port to listen on
  24. * @param exporters A list of {@link RPCExporter} to publish
  25. * @param conf A {@link SocketConf} object with optional settings
  26. */
  27. constructor(
  28. private port: number,
  29. private exporters: T.ExporterArray<InterfaceT> = [],
  30. conf: T.ServerConf<InterfaceT> = {}
  31. ) {
  32. if (!conf.visibility) this.visibility = "0.0.0.0"
  33. if (conf.sesame) {
  34. this.sesame = U.makeSesameFunction(conf.sesame)
  35. }
  36. this.accessFilter = conf.accessFilter || (async (sesame) => {
  37. if (!this.sesame) return true
  38. return this.sesame!(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 = 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. public setExporters(exporters: T.ExporterArray<InterfaceT>): any {
  91. exporters.forEach(U.fixNames)
  92. this.destroy()
  93. this.ws = http.createServer()
  94. this.io = bsock.createServer()
  95. this.exporters = exporters
  96. this.startWebsocket()
  97. }
  98. */
  99. destroy(): void {
  100. this.io.close()
  101. this.ws.close()
  102. }
  103. }