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

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