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.

Utils.ts 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import * as uuidv4 from "uuid/v4"
  2. import * as T from "./Types";
  3. import * as I from "./Interfaces";
  4. import { Socket } from "socket.io"
  5. /**
  6. * Translate an RPC to RPCInfo for serialization.
  7. * @param rpc The RPC to transform
  8. * @param owner The owning RPC group's name
  9. * @param errorHandler The error handler to invoke when something goes wrong
  10. * @param sesame optional sesame phrase to prepend before all RPC arguments
  11. * @throws Error on RPC without name property
  12. */
  13. export const rpcToRpcinfo = (socket: I.Socket, rpc: T.RPC<any, any>, owner: string, errorHandler: T.ErrorHandler, sesame?: T.SesameFunction): T.RpcInfo => {
  14. switch (typeof rpc) {
  15. case "object":
  16. if (rpc['call']) {
  17. const _rpc: T.CallRPC<any, any> = rpc
  18. return {
  19. owner: owner,
  20. argNames: extractArgs(rpc['call']),
  21. type: "Call",
  22. name: rpc.name,
  23. call: sesame ? async ($__sesame__$, ...args) => { if (sesame($__sesame__$)) return await rpc['call'].apply({}, args); socket.close() } : rpc['call'], // check & remove sesame
  24. }
  25. } else {
  26. const _rpc: T.HookRPC<any, any> = rpc
  27. const generator = hookGenerator(_rpc, errorHandler, sesame)
  28. return {
  29. owner: owner,
  30. argNames: extractArgs(generator(undefined)),
  31. type: "Hook",
  32. name: _rpc.name,
  33. generator: generator,
  34. }
  35. }
  36. case "function":
  37. if (!rpc.name) throw new Error(`
  38. RPC did not provide a name.
  39. \nUse 'funtion name(..){ .. }' syntax instead.
  40. \n
  41. \n<------------OFFENDING RPC:
  42. \n${rpc.toString()}
  43. \n>------------OFFENDING RPC`)
  44. return {
  45. owner: owner,
  46. argNames: extractArgs(rpc),
  47. type: "Call",
  48. name: rpc.name,
  49. call: sesame ? async ($__sesame__$, ...args) => { if (sesame($__sesame__$)) return await rpc.apply({}, args); throw makeError(rpc.name) } : rpc, // check & remove sesame
  50. }
  51. }
  52. throw new Error("Bad socketIORPC type " + typeof rpc)
  53. }
  54. /**
  55. * Utility function to apply the RPCs of an {@link RPCExporter}.
  56. * @param serverSocket The websocket (implementation: socket.io) to hook on
  57. * @param exporter The exporter
  58. * @param makeUnique @default true Attach a suffix to RPC names
  59. */
  60. export function rpcHooker(serverSocket: I.Socket, exporter: I.RPCExporter<any, any>, errorHandler: T.ErrorHandler, sesame?: T.SesameFunction, makeUnique = true): T.ExtendedRpcInfo[] {
  61. const owner = exporter.name
  62. const RPCs = typeof exporter.RPCs === "function" ? exporter.RPCs() : exporter.RPCs
  63. return RPCs
  64. .map(rpc => rpcToRpcinfo(serverSocket, rpc, owner, errorHandler, sesame))
  65. .map(info => {
  66. const suffix = makeUnique ? "-" + uuidv4().substr(0, 4) : ""
  67. const ret: any = info
  68. ret.uniqueName = info.name + suffix
  69. let rpcFunction = info.type === 'Hook' ? info.generator(serverSocket) : info.call
  70. serverSocket.hook(ret.uniqueName, callGenerator(info.name, serverSocket, rpcFunction, errorHandler))
  71. return ret
  72. })
  73. }
  74. /**
  75. * Decorate an RPC with the error handler
  76. * @param rpcFunction the function to decorate
  77. */
  78. const callGenerator = (rpcName: string, $__socket__$: I.Socket, rpcFunction: T.AnyFunction, errorHandler: T.ErrorHandler): T.AnyFunction => {
  79. const argsArr = extractArgs(rpcFunction)
  80. const args = argsArr.join(',')
  81. const argsStr = argsArr.map(stripAfterEquals).join(',')
  82. const callStr = `async (${args}) => {
  83. try{
  84. return await rpcFunction(${argsStr})
  85. }catch(e){
  86. errorHandler($__socket__$)(e, rpcName, [${args}])
  87. }
  88. }`
  89. return eval(callStr);
  90. }
  91. /**
  92. * Utility function to strip parameters like "a = 3" of their defaults
  93. * @param str The parameter to modify
  94. */
  95. export function stripAfterEquals(str: string): string {
  96. return str.split("=")[0]
  97. }
  98. /**
  99. * Utility function to generate {@link HookFunction} from a RPC for backend
  100. * @param rpc The RPC to transform
  101. * @returns A {@link HookFunction}
  102. */
  103. const hookGenerator = (rpc: T.HookRPC<any, any>, errorHandler: T.ErrorHandler, sesameFn?: T.SesameFunction, injectSocket?: boolean): T.HookInfo['generator'] => {
  104. let argsArr = extractArgs(rpc.hook)
  105. argsArr.pop() //remove callback param
  106. let callArgs = argsArr.join(',')
  107. const args = sesameFn ? (['sesame', ...argsArr].join(','))
  108. : callArgs
  109. callArgs = appendComma(callArgs, false)
  110. const hookStr = `
  111. ($__socket__$) => async (${args}) => {
  112. try{
  113. if(sesameFn && !sesameFn(sesame)) return
  114. const uuid = uuidv4()
  115. const res = await rpc.hook(${callArgs} (...cbargs) => {
  116. ${rpc.onCallback ? `rpc.onCallback.apply({}, cbargs)` : ``}
  117. $__socket__$.call.apply($__socket__$, [uuid, ...cbargs])
  118. })
  119. ${rpc.onDestroy ? `$__socket__$.bind(uuid, () => {
  120. rpc.onDestroy(res, rpc)
  121. })` : ``}
  122. return {'uuid': uuid, 'return': res}
  123. }catch(e){
  124. //can throw to pass exception to client or swallow to keep it local
  125. errorHandler($__socket__$)(e, ${rpc.name}, [${args}])
  126. }
  127. }`
  128. return eval(hookStr)
  129. }
  130. const makeError = (callName: string) => new Error(`Call not found: ${callName}. ; Zone: <root> ; Task: Promise.then ; Value: Error: Call not found: ${callName}`)
  131. /**
  132. * Extract a string list of parameters from a function
  133. * @param f The source function
  134. */
  135. const extractArgs = (f: Function): string[] => {
  136. let fn: string
  137. fn = (fn = String(f)).substr(0, fn.indexOf(")")).substr(fn.indexOf("(") + 1)
  138. return fn !== "" ? fn.split(',') : []
  139. }
  140. export function makeSesameFunction(sesame: T.SesameFunction | string): T.SesameFunction {
  141. if (typeof sesame === 'function') {
  142. return sesame
  143. }
  144. return (testSesame: string) => {
  145. return testSesame === sesame
  146. }
  147. }
  148. export function appendComma(s?: string, turnToString = true): string {
  149. if (turnToString)
  150. return s ? `'${s}',` : ""
  151. return s ? `${s},` : ""
  152. }
  153. /**
  154. * Typescript incorrectly omits the function.name attribute for MethodDeclaration.
  155. * This was supposedly fixed (https://github.com/microsoft/TypeScript/issues/5611) but it still is the case.
  156. * This function sets the name value for all object members that are functions.
  157. */
  158. export function fixNames(o: Object): void {
  159. Object.keys(o).forEach(key => {
  160. if (typeof o[key] === 'function' && !o[key].name) {
  161. Object.defineProperty(o[key], 'name', {
  162. value: key
  163. })
  164. }
  165. })
  166. }
  167. /**
  168. * Transforms a socket.io instance into one conforming to I.Socket
  169. * @param socket A socket.io socket
  170. */
  171. export const makePioSocket = (socket: any): I.Socket => {
  172. return <I.Socket>{
  173. id: socket.id,
  174. bind: (name: string, listener: T.PioBindListener) => socket.on(name, (...args: any) => listener.apply(null, args)),
  175. hook: (name: string, listener: T.PioHookListener) => {
  176. const args = extractArgs(listener)
  177. let argNames
  178. let restParam = args.find(e => e.includes('...'))
  179. if (!restParam) {
  180. argNames = [...args, '...$__args__$'].join(',')
  181. restParam = '$__args__$'
  182. } else {
  183. argNames = [...args].join(',')
  184. restParam = restParam.replace('...', '')
  185. }
  186. const decoratedListener = eval(`(() => async (${argNames}) => {
  187. const __ack__ = ${restParam}.pop()
  188. try{
  189. const response = await listener.apply(null, [${argNames}])
  190. __ack__(response)
  191. }catch(e){
  192. __ack__({
  193. ...e,
  194. stack: e.stack,
  195. message: e.message,
  196. name: e.name,
  197. })
  198. }
  199. })()`)
  200. socket.on(name, decoratedListener)
  201. },
  202. call: (name: string, ...args: any) => {
  203. return new Promise((res, rej) => {
  204. const params: any = [name, ...args, (resp) => {
  205. if (isError(resp)) {
  206. const err = new Error()
  207. err.stack = resp.stack
  208. err.name = resp.name
  209. err.message = resp.message
  210. return rej(err)
  211. }
  212. res(resp)
  213. }]
  214. socket.emit.apply(socket, params)
  215. })
  216. },
  217. fire: (name: string, ...args: any) => new Promise((res, rej) => {
  218. const params: any = [name, ...args]
  219. socket.emit.apply(socket, params)
  220. res()
  221. }),
  222. unhook: (name: string, listener?: T.AnyFunction) => {
  223. if (listener) {
  224. socket.removeListener(name, listener)
  225. } else {
  226. socket.removeAllListeners(name)
  227. }
  228. },
  229. on: (...args) => socket.on.apply(socket, args),
  230. emit: (...args) => socket.emit.apply(socket, args),
  231. close: () => {
  232. socket.disconnect(true)
  233. }
  234. }
  235. }
  236. export const isError = function (e) {
  237. return e && e.stack && e.message && typeof e.stack === 'string'
  238. && typeof e.message === 'string';
  239. }