Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. import { describe, it, Func } from "mocha";
  2. import { RPCServer, RPCSocket, SubscriptionResponse, makeSubResponse } from '../Index'
  3. import * as uuidv4 from "uuid/v4"
  4. const add = (...args:number[]) => {return args.reduce((a,b)=>a+b, 0)}
  5. function makeServer(){
  6. let subcallback
  7. return new RPCServer<{ topic: string }>(20000, [{
  8. name: "test",
  9. exportRPCs: () => [
  10. {
  11. name: 'echo',
  12. call: async (s:string) => s,
  13. },{
  14. name: 'simpleSubscribe',
  15. hook: async(callback) => {
  16. subcallback = callback
  17. return makeSubResponse<{topic: string}>({topic: "test"})
  18. }
  19. },{
  20. name: 'subscribe',
  21. hook: async (callback) => {
  22. subcallback = callback
  23. return makeSubResponse<{topic: string}>({topic: "test"})
  24. },
  25. onClose: (res, rpc) => {
  26. console.log("onClose", rpc.name === 'subscribe' && res?"OK":"")
  27. subcallback = null
  28. },
  29. onCallback: (...args:any) => {
  30. console.log("onCallback", args[0] === "test" && args[1] === "callback"?"OK":"")
  31. }
  32. },
  33. add,
  34. function triggerCallback(...messages:any[]):number {return subcallback.apply({}, messages)},
  35. ]
  36. }],{
  37. connectionHandler: (socket) => { console.log("connectionHandler OK") },
  38. closeHandler: (socket) => { console.log("closeHandler OK") },
  39. errorHandler: (socket, err) => { console.error("errorHandler OK SO YOU SHOULDN'T SEE THIS"); throw err }
  40. })
  41. }
  42. describe('RPCServer', () => {
  43. let server: RPCServer<{ topic: string }, any>
  44. before((done) => {
  45. server = makeServer()
  46. done()
  47. })
  48. after(async() => {
  49. await server.destroy()
  50. })
  51. it('should be able to use all kinds of RPC definitions', (done) => {
  52. const echo = (x) => x
  53. const server = new RPCServer(20003, [{
  54. name: 'HelloWorldRPCGroup',
  55. exportRPCs: () => [
  56. echo, //named function variable
  57. function echof(x){ return x }, //named function
  58. {
  59. name: 'echoExplicit', //describing object
  60. call: async (x) => x
  61. }
  62. ]
  63. }])
  64. const client = new RPCSocket(20003, 'localhost')
  65. client.connect().then(async () => {
  66. const r0 = await client['HelloWorldRPCGroup'].echo('Hello')
  67. const r1 = await client['HelloWorldRPCGroup'].echof('World')
  68. const r2 = await client['HelloWorldRPCGroup'].echoExplicit('RPC!')
  69. if(r0 === 'Hello' && r1 === 'World' && r2 ==='RPC!'){
  70. client.destroy()
  71. server.destroy()
  72. done()
  73. }
  74. })
  75. })
  76. it('new RPCServer() should fail on bad RPC', (done) => {
  77. try{
  78. new RPCServer(20001, [{
  79. name: "bad",
  80. exportRPCs: () => [
  81. (aaa,bbb,ccc) => { return aaa+bbb+ccc }
  82. ]
  83. }])
  84. done(new Error("Didn't fail with bad RPC"))
  85. }catch(badRPCError){
  86. done()
  87. }
  88. })
  89. })
  90. describe('RPCSocket', () => {
  91. let client: RPCSocket
  92. let server: RPCServer<{topic: string}>
  93. before(async() => {
  94. server = makeServer()
  95. client = new RPCSocket(20000, "localhost")
  96. return await client.connect()
  97. })
  98. after(() => {
  99. client.destroy()
  100. server.destroy()
  101. })
  102. it('should have rpc echo', (done) => {
  103. client['test'].echo("x").then(x => {
  104. if(x === 'x')
  105. done()
  106. else
  107. done(new Error('echo RPC response did not match'))
  108. })
  109. })
  110. it('should add up to 6', (done) => {
  111. client['test'].add(1,2,3).then(x => {
  112. if(x === 6)
  113. done()
  114. else
  115. done(new Error('add RPC response did not match'))
  116. })
  117. })
  118. it('should subscribe with success', (done) => {
  119. client['test'].simpleSubscribe(console.log).then(res => {
  120. if(res.result === 'Success'){
  121. done()
  122. }else{
  123. console.error(res)
  124. done(new Error('Subscribe did not return success'))
  125. }
  126. })
  127. })
  128. it('subscribe should call back', (done) => {
  129. client['test'].subscribe((...args: any) => {
  130. if(args[0] === "test" && args[1] === "callback")
  131. done()
  132. else
  133. done(new Error("Bad callback value "+ args))
  134. }).then( async () => {
  135. await client['test'].triggerCallback("test", "callback")
  136. })
  137. })
  138. it('simpleSubscribe should call back', (done) => {
  139. client['test'].simpleSubscribe((...args: any) => {
  140. if(args[0] === "test_" && args[1] === "callback_")
  141. done()
  142. else
  143. done(new Error("Bad callback value "+ args))
  144. }).then( async () => {
  145. await client['test'].triggerCallback("test_", "callback_")
  146. })
  147. })
  148. })
  149. describe('It should do unhook', () => {
  150. let candy = "OK"
  151. let cb: Function
  152. let client: RPCSocket
  153. let server: RPCServer<{topic: string}>
  154. before(async() => {
  155. server = new RPCServer<{ topic: string }>(20000, [{
  156. name: "test",
  157. exportRPCs: () => [{
  158. name: 'subscribe',
  159. hook: async(callback):Promise<SubscriptionResponse<{topic:string}>> => {
  160. cb = <Function> callback
  161. return {
  162. result: "Success",
  163. uuid: uuidv4(),
  164. topic: "test"
  165. }
  166. }
  167. },
  168. function checkCandy():string { cb(candy); return candy },
  169. function stealCandy():string { candy = "_OK"; cb(candy); cb = (...any) => console.log.apply(console,["Server:", ...any]); return candy }
  170. ]
  171. }],{
  172. connectionHandler: (socket) => { console.log("connectionHandler OK") },
  173. closeHandler: (socket) => { console.log("closeHandler OK") },
  174. errorHandler: (socket, err) => { console.error("errorHandler OK SO YOU SHOULDN'T SEE THIS"); throw err }
  175. })
  176. client = new RPCSocket(20000, "localhost")
  177. return await client.connect()
  178. })
  179. after(() => {
  180. client.destroy()
  181. server.destroy()
  182. })
  183. it('Unhook+unsubscribe should stop callbacks', (done) => {
  184. client['test'].subscribe(c => console.log("Client: "+c)).then( async (res: SubscriptionResponse) => {
  185. const r1 = await client['test'].checkCandy()
  186. const r3 = await client['test'].stealCandy()
  187. client.unhook(res.uuid)
  188. console.log("---- No client output below this line")
  189. const r2 = await client['test'].checkCandy()
  190. const r4 = await client['test'].checkCandy()
  191. console.log("---- More output below")
  192. if(r1 === "OK" && r3 === "_OK" && r2 === "_OK" && r4 === "_OK")
  193. done()
  194. else
  195. done(new Error("Results did not match: "+[r1,r2,r3,r4]))
  196. })
  197. })
  198. })
  199. type SesameTestIfc = {
  200. test: {
  201. checkCandy: ()=>Promise<string>
  202. subscribe: (callback) => Promise<SubscriptionResponse<{ topic: string; }>>
  203. }
  204. }
  205. describe('Sesame should unlock the socket', () => {
  206. let candy = "OK"
  207. let client: RPCSocket & SesameTestIfc
  208. let server: RPCServer
  209. let cb = (...args) => {}
  210. before(async() => {
  211. server = new RPCServer(20004, [{
  212. name: "test",
  213. exportRPCs: () => [
  214. {
  215. name: 'subscribe',
  216. hook: async(callback) => {
  217. cb = callback
  218. return <SubscriptionResponse>{
  219. result: "Success",
  220. uuid: uuidv4(),
  221. topic: 'test'
  222. }
  223. }
  224. },
  225. async function checkCandy():Promise<string> { cb(candy); cb=()=>{}; return candy },
  226. ]}
  227. ],{
  228. sesame: (_sesame) => _sesame === 'sesame!'
  229. })
  230. const sock = new RPCSocket(20004, "localhost")
  231. client = await sock.connect<SesameTestIfc>('sesame!')
  232. })
  233. after(() => {
  234. client.destroy()
  235. server.destroy()
  236. })
  237. it('should work with sesame', (done) => {
  238. client.test.checkCandy().then(c => done())
  239. })
  240. it('should not work without sesame', (done) => {
  241. const sock = new RPCSocket(20004, "localhost")
  242. sock.connect<SesameTestIfc>( /* no sesame */).then(async (c) => {
  243. c.test.checkCandy().then(d => {
  244. if(d === candy)
  245. done("should not be able to get candy")
  246. done()
  247. }).finally(() => {
  248. sock.destroy()
  249. })
  250. })
  251. })
  252. it('callback should work with sesame', (done) => {
  253. client.test.subscribe((c) => {
  254. if(c === candy){
  255. done()
  256. }
  257. }).then(d => {
  258. if(d.result !== 'Success')
  259. done('expected valid response')
  260. client.test.checkCandy()
  261. })
  262. })
  263. it('callback should not work without sesame', (done) => {
  264. const sock = new RPCSocket(20004, "localhost")
  265. sock.connect<SesameTestIfc>( /* no sesame */).then(async (c) => {
  266. c.test.subscribe((c) => {
  267. console.log("CALLBACK TRIGGERED UNEXPECTED");
  268. if(c === candy)
  269. done("super not")
  270. }).then(async d => {
  271. await client.test.checkCandy()
  272. if(d == null){
  273. done()
  274. }else
  275. done('unexpected valid response '+(d) )
  276. c.destroy()
  277. })
  278. })
  279. })
  280. })