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.3KB

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