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.

Frontend.ts 7.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. 'use strict'
  2. import { PromiseIOClient } from './PromiseIO/Client'
  3. import * as T from './Types';
  4. import * as I from './Interfaces';
  5. import { stripAfterEquals, appendComma } from './Utils';
  6. /**
  7. * A websocket-on-steroids with built-in RPC capabilities
  8. */
  9. export class RPCSocket<Ifc extends T.RPCInterface = T.RPCInterface> implements I.Socket{
  10. static async makeSocket<T extends T.RPCInterface = T.RPCInterface>(port:number, server: string, sesame?:string, conf?:T.SocketConf): Promise<T.ConnectedSocket<T>> {
  11. const socket = new RPCSocket<T>(port, server, conf)
  12. return await socket.connect(sesame)
  13. }
  14. private socket: I.Socket
  15. private handlers : {
  16. [name in string]: T.AnyFunction[]
  17. } = {
  18. error: [],
  19. close: []
  20. }
  21. private hooks : {[name in string]: T.AnyFunction} = {}
  22. /**
  23. *
  24. * @param port Port to connect to
  25. * @param server Server address
  26. * @param tls @default false use TLS
  27. */
  28. constructor(public port:number, private server: string, private conf:T.SocketConf = { tls: false }){
  29. Object.defineProperty(this, 'socket', {value: undefined, writable: true})
  30. }
  31. /**
  32. * Hooks a handler to a function name. Use {@link call} to trigger it.
  33. * @param name The function name to listen on
  34. * @param handler The handler to attach
  35. */
  36. public hook(name: string, handler: (...args:any[]) => any | Promise<any>){
  37. if(!this.socket){
  38. this.hooks[name] = handler
  39. }else{
  40. this.socket.hook(name, handler)
  41. }
  42. }
  43. /**
  44. * Hooks a handler to a function name. Use {@link call} to trigger it.
  45. * @param name The function name to listen on
  46. * @param handler The handler to attach
  47. */
  48. public bind(name: string, handler: (...args:any[]) => any | Promise<any>){
  49. if(!this.socket){
  50. this.hooks[name] = handler
  51. }else{
  52. this.socket.bind(name, handler)
  53. }
  54. }
  55. /**
  56. * Removes a {@link hook} listener by name.
  57. * @param name The function name
  58. */
  59. public unhook(name: string){
  60. if(!this.socket){
  61. delete this.hooks[name]
  62. }else{
  63. this.socket.unhook(name)
  64. }
  65. }
  66. /**
  67. * Attach a listener to error or close events
  68. * @param type 'error' or 'close'
  69. * @param f The listener to attach
  70. */
  71. public on(type: string, f: T.AnyFunction){
  72. if(!this.socket){
  73. if(!this.handlers[type])
  74. this.handlers[type] = []
  75. this.handlers[type].push(f)
  76. }else{
  77. this.socket.on(type, f)
  78. }
  79. }
  80. /**
  81. * Emit a LOCAL event
  82. * @param eventName The event name to emit under
  83. * @param data The data the event carries
  84. */
  85. public emit(eventName:string, data:any){
  86. if(!this.socket) return
  87. this.socket.emit(eventName, data)
  88. }
  89. /**
  90. * Closes the socket. It may attempt to reconnect.
  91. */
  92. public close(){
  93. if(!this.socket) return;
  94. this.socket.close()
  95. }
  96. /**
  97. * Trigger a hooked handler on the server
  98. * @param rpcname The function to call
  99. * @param args other arguments
  100. */
  101. public async call (rpcname: string, ...args: any[]) : Promise<any>{
  102. if(!this.socket) throw new Error("The socket is not connected! Use socket.connect() first")
  103. try{
  104. const val = await this.socket.call.apply(this.socket, [rpcname, ...args])
  105. return val
  106. }catch(e){
  107. this.emit('error', e)
  108. throw e
  109. }
  110. }
  111. /**
  112. * An alternative to call that does not wait for confirmation and doesn't return a value.
  113. * @param rpcname The function to call
  114. * @param args other arguments
  115. */
  116. public async fire(rpcname: string, ...args: any[]) : Promise<void>{
  117. if(!this.socket) throw new Error("The socket is not connected! Use socket.connect() first")
  118. await this.socket.fire.apply(this.socket, [rpcname, ...args])
  119. }
  120. /**
  121. * Connects to the server and attaches available RPCs to this object
  122. */
  123. public async connect( sesame?: string ) : Promise<T.ConnectedSocket<Ifc>> {
  124. try{
  125. this.socket = await PromiseIOClient.connect(this.port, this.server, /*this.conf.tls?this.conf.tls:false*/)
  126. }catch(e){
  127. this.handlers['error'].forEach(h => h(e))
  128. throw e
  129. }
  130. Object.entries(this.handlers).forEach(([k,v])=>{
  131. v.forEach(h => this.socket.on(k, h))
  132. })
  133. Object.entries(this.hooks).forEach((kv: [string, T.AnyFunction]) => {
  134. this.socket.hook(kv[0], kv[1])
  135. })
  136. const info:T.ExtendedRpcInfo[] = await this.info(sesame)
  137. info.forEach(i => {
  138. let f: any
  139. switch (i.type) {
  140. case 'Call':
  141. f = this.callGenerator(i.uniqueName, i.argNames, sesame)
  142. break
  143. case 'Hook':
  144. f = this.frontEndHookGenerator(i.uniqueName, i.argNames, sesame)
  145. break
  146. }
  147. if(this[i.owner] == null)
  148. this[i.owner] = {}
  149. this[i.owner][i.name] = f
  150. this[i.owner][i.name].bind(this)
  151. })
  152. return <T.ConnectedSocket<Ifc>> (this as any)
  153. }
  154. /**
  155. * Get a list of available RPCs from the server
  156. */
  157. public async info(sesame?:string){
  158. if(!this.socket) throw new Error("The socket is not connected! Use socket.connect() first")
  159. return await this.socket.call('info', sesame)
  160. }
  161. /**
  162. * Utility {@link AsyncFunction} generator
  163. * @param fnName The function name
  164. * @param fnArgs A string-list of parameters
  165. */
  166. private callGenerator(fnName: string, fnArgs:string[], sesame?:string): T.AnyFunction{
  167. const headerArgs = fnArgs.join(",")
  168. const argParams = fnArgs.map(stripAfterEquals).join(",")
  169. sesame = appendComma(sesame)
  170. return eval(`async (${headerArgs}) => {
  171. return await this.call("${fnName}", ${sesame} ${argParams})
  172. }`)
  173. }
  174. /**
  175. * Utility {@link HookFunction} generator
  176. * @param fnName The function name
  177. * @param fnArgs A string-list of parameters
  178. */
  179. private frontEndHookGenerator(fnName: string, fnArgs:string[], sesame?:string): T.HookFunction{
  180. if(sesame)
  181. fnArgs.shift()
  182. let headerArgs = fnArgs.join(",")
  183. const argParams = fnArgs.map(stripAfterEquals).join(",")
  184. sesame = appendComma(sesame, true)
  185. headerArgs = fnArgs.length>0?headerArgs+",":headerArgs
  186. return eval( `
  187. async (${headerArgs} callback) => {
  188. const r = await this.call("${fnName}", ${sesame} ${argParams})
  189. try{
  190. if(r){
  191. if(r.uuid){
  192. callback['destroy'] = () => { this.socket.unhook(r.uuid) }
  193. this.socket.hook(r.uuid, callback)
  194. }
  195. return r.return
  196. }else{
  197. throw new Error("Empty response")
  198. }
  199. }catch(e){
  200. throw e
  201. }
  202. }`)
  203. }
  204. }