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

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