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

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