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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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 { CALLBACK_NAME, DESTROY_PREFIX, 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.GenericFunction[]
  18. } = {
  19. error: [],
  20. close: []
  21. }
  22. private hooks: { [name in string]: T.GenericFunction } = {}
  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.GenericFunction) {
  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. if(this.conf.callTimeoutMs){
  110. return await Promise.race([
  111. this.socket.call.apply(this.socket, [rpcname, ...args]),
  112. new Promise((_, rej) => {
  113. setTimeout(_ => rej(USER_DEFINED_TIMEOUT(this.conf.callTimeoutMs)), this.conf.callTimeoutMs)
  114. })
  115. ])
  116. }else{
  117. return await this.socket.call.apply(this.socket, [rpcname, ...args])
  118. }
  119. } catch (e) {
  120. this.emit('error', e)
  121. throw e
  122. }
  123. }
  124. /**
  125. * An alternative to call that does not wait for confirmation and doesn't return a value.
  126. * @param rpcname The function to call
  127. * @param args other arguments
  128. */
  129. public async fire(rpcname: string, ...args: any[]): Promise<void> {
  130. if (!this.socket) throw new Error(SOCKET_NOT_CONNECTED)
  131. await this.socket.fire.apply(this.socket, [rpcname, ...args])
  132. }
  133. /**
  134. * Connects to the server and attaches available RPCs to this object
  135. */
  136. public async connect(sesame?: string): Promise<T.ConnectedSocket<Ifc>> {
  137. try {
  138. this.socket = await PromiseIOClient.connect(this.port, this.address, this.conf)
  139. } catch (e) {
  140. this.handlers['error'].forEach(h => h(e))
  141. throw e
  142. }
  143. Object.entries(this.handlers).forEach(([k, v]) => {
  144. v.forEach(h => this.socket.on(k, h))
  145. })
  146. Object.entries(this.hooks).forEach((kv: [string, T.GenericFunction]) => {
  147. this.socket.hook(kv[0], kv[1])
  148. })
  149. const info: T.ExtendedRpcInfo[] = await this.info(sesame)
  150. info.forEach(i => {
  151. let f: any
  152. switch (i.type) {
  153. case 'Call':
  154. f = this.callGenerator(i.uniqueName, i.argNames, sesame)
  155. break
  156. case 'Hook':
  157. f = this.frontEndHookGenerator(i.uniqueName, i.argNames, sesame)
  158. break
  159. }
  160. if (this[i.owner] == null)
  161. this[i.owner] = {}
  162. this[i.owner][i.name] = f
  163. this[i.owner][i.name].bind(this)
  164. })
  165. return <T.ConnectedSocket<Ifc>>(this as any)
  166. }
  167. /**
  168. * Get a list of available RPCs from the server
  169. */
  170. public async info(sesame?: string) {
  171. if (!this.socket) throw new Error(SOCKET_NOT_CONNECTED)
  172. return await this.socket.call('info', sesame)
  173. }
  174. /**
  175. * Utility {@link AsyncFunction} generator
  176. * @param fnName The function name
  177. * @param fnArgs A string-list of parameters
  178. */
  179. private callGenerator(fnName: string, fnArgs: string[], sesame?: string): T.GenericFunction {
  180. const headerArgs = fnArgs.join(",")
  181. const argParams = fnArgs.map(stripAfterEquals).join(",")
  182. sesame = appendComma(sesame)
  183. return eval(`async (${headerArgs}) => {
  184. const returnvalue = await this.call("${fnName}", ${sesame} ${argParams})
  185. return returnvalue
  186. }`)
  187. }
  188. /**
  189. * Utility {@link HookFunction} generator
  190. * @param fnName The function name
  191. * @param fnArgs A string-list of parameters
  192. */
  193. private frontEndHookGenerator(fnName: string, fnArgs: string[], sesame?: string): T.GenericFunction {
  194. if (sesame)
  195. fnArgs.shift()
  196. let headerArgs = fnArgs.join(",")
  197. const argParams = fnArgs.map(stripAfterEquals).join(",")
  198. sesame = appendComma(sesame, true)
  199. headerArgs = fnArgs.length > 0 ? headerArgs + "," : headerArgs
  200. const destroy_prefix = DESTROY_PREFIX
  201. const frontendHookStr = `
  202. async (${CALLBACK_NAME}, ${headerArgs}) => {
  203. const r = await this.call("${fnName}", ${sesame} ${argParams})
  204. try{
  205. if(r){
  206. if(r.uuid){
  207. ${CALLBACK_NAME}['destroy'] = () => {
  208. this.socket.fire(destroy_prefix+r.uuid)
  209. this.socket.unhook(r.uuid)
  210. }
  211. ${CALLBACK_NAME} = ${CALLBACK_NAME}.bind({
  212. destroy: ${CALLBACK_NAME}['destroy']
  213. })
  214. this.socket.hook(r.uuid, (...args) => {
  215. ${CALLBACK_NAME}.apply(${CALLBACK_NAME}, args)
  216. })
  217. }
  218. return r.return
  219. }else{
  220. throw new Error("Empty response")
  221. }
  222. }catch(e){
  223. throw e
  224. }
  225. }`
  226. return eval(frontendHookStr)
  227. }
  228. }