@celljs/rpc 4.3.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (545) hide show
  1. package/README.md +117 -1
  2. package/cell.schema.json +100 -0
  3. package/cell.yml +12 -8
  4. package/esm/common/annotation/index.d.ts +2 -0
  5. package/esm/common/annotation/index.js +2 -0
  6. package/esm/common/annotation/index.js.map +1 -1
  7. package/esm/common/annotation/rpc-client.d.ts +7 -0
  8. package/esm/common/annotation/rpc-client.js +18 -0
  9. package/esm/common/annotation/rpc-client.js.map +1 -0
  10. package/esm/common/annotation/rpc-protocol.d.ts +7 -0
  11. package/esm/common/annotation/rpc-protocol.js +2 -0
  12. package/esm/common/annotation/rpc-protocol.js.map +1 -0
  13. package/esm/common/annotation/rpc.d.ts +4 -0
  14. package/esm/common/annotation/rpc.js +14 -18
  15. package/esm/common/annotation/rpc.js.map +1 -1
  16. package/esm/common/client/client-protocol.d.ts +6 -0
  17. package/esm/common/client/client-protocol.js +2 -0
  18. package/esm/common/client/client-protocol.js.map +1 -0
  19. package/esm/common/client/index.d.ts +2 -0
  20. package/esm/common/client/index.js +3 -0
  21. package/esm/common/client/index.js.map +1 -0
  22. package/esm/common/client/rpc-client-registry.d.ts +14 -0
  23. package/esm/common/client/rpc-client-registry.js +51 -0
  24. package/esm/common/client/rpc-client-registry.js.map +1 -0
  25. package/esm/common/constants.d.ts +3 -1
  26. package/esm/common/constants.js +3 -1
  27. package/esm/common/constants.js.map +1 -1
  28. package/esm/common/converter/converter-protocol.d.ts +6 -2
  29. package/esm/common/converter/converter-protocol.js +1 -0
  30. package/esm/common/converter/converter-protocol.js.map +1 -1
  31. package/esm/common/endpoint/endpoint-protocol.d.ts +3 -0
  32. package/esm/common/endpoint/endpoint-resolver.d.ts +2 -0
  33. package/esm/common/endpoint/endpoint-resolver.js +17 -3
  34. package/esm/common/endpoint/endpoint-resolver.js.map +1 -1
  35. package/esm/common/error/error.d.ts +23 -0
  36. package/esm/common/error/error.js +34 -2
  37. package/esm/common/error/error.js.map +1 -1
  38. package/esm/common/index.d.ts +6 -6
  39. package/esm/common/index.js +6 -6
  40. package/esm/common/index.js.map +1 -1
  41. package/esm/common/module.js +5 -4
  42. package/esm/common/module.js.map +1 -1
  43. package/esm/common/processor/client-config-processor.d.ts +2 -2
  44. package/esm/common/processor/client-config-processor.js.map +1 -1
  45. package/esm/common/processor/processor-protocol.d.ts +2 -2
  46. package/esm/common/protocol/index.d.ts +1 -0
  47. package/esm/common/protocol/index.js +2 -0
  48. package/esm/common/protocol/index.js.map +1 -0
  49. package/esm/common/protocol/json-rpc.d.ts +42 -0
  50. package/esm/common/protocol/json-rpc.js +48 -0
  51. package/esm/common/protocol/json-rpc.js.map +1 -0
  52. package/esm/common/proxy/index.d.ts +1 -4
  53. package/esm/common/proxy/index.js +1 -4
  54. package/esm/common/proxy/index.js.map +1 -1
  55. package/esm/common/proxy/rpc-proxy.d.ts +6 -0
  56. package/esm/common/proxy/rpc-proxy.js +40 -0
  57. package/esm/common/proxy/rpc-proxy.js.map +1 -0
  58. package/esm/common/transport/http-transport.d.ts +50 -0
  59. package/esm/common/transport/http-transport.js +98 -0
  60. package/esm/common/transport/http-transport.js.map +1 -0
  61. package/esm/common/transport/index.d.ts +4 -0
  62. package/esm/common/transport/index.js +5 -0
  63. package/esm/common/transport/index.js.map +1 -0
  64. package/esm/common/transport/transport-protocol.d.ts +12 -0
  65. package/esm/common/transport/transport-protocol.js +2 -0
  66. package/esm/common/transport/transport-protocol.js.map +1 -0
  67. package/esm/common/transport/transport-provider.d.ts +34 -0
  68. package/esm/common/transport/transport-provider.js +103 -0
  69. package/esm/common/transport/transport-provider.js.map +1 -0
  70. package/esm/common/transport/websocket-transport.d.ts +54 -0
  71. package/esm/common/transport/websocket-transport.js +144 -0
  72. package/esm/common/transport/websocket-transport.js.map +1 -0
  73. package/esm/common/utils/index.d.ts +1 -1
  74. package/esm/common/utils/index.js +1 -1
  75. package/esm/common/utils/index.js.map +1 -1
  76. package/esm/common/utils/rpc-method-util.d.ts +10 -0
  77. package/esm/common/utils/rpc-method-util.js +28 -0
  78. package/esm/common/utils/rpc-method-util.js.map +1 -0
  79. package/esm/common/utils/rpc-util.d.ts +9 -9
  80. package/esm/common/utils/rpc-util.js +24 -30
  81. package/esm/common/utils/rpc-util.js.map +1 -1
  82. package/esm/node/connection/connection-protocol.d.ts +26 -0
  83. package/esm/node/connection/connection-protocol.js +3 -0
  84. package/esm/node/connection/connection-protocol.js.map +1 -0
  85. package/esm/node/connection/index.d.ts +4 -0
  86. package/esm/node/connection/index.js +5 -0
  87. package/esm/node/connection/index.js.map +1 -0
  88. package/esm/node/connection/rpc-connection-manager.d.ts +10 -0
  89. package/esm/node/connection/rpc-connection-manager.js +35 -0
  90. package/esm/node/connection/rpc-connection-manager.js.map +1 -0
  91. package/esm/node/connection/rpc-connection.d.ts +33 -0
  92. package/esm/node/connection/rpc-connection.js +106 -0
  93. package/esm/node/connection/rpc-connection.js.map +1 -0
  94. package/esm/node/connection/rpc-context.d.ts +14 -0
  95. package/esm/node/connection/rpc-context.js +29 -0
  96. package/esm/node/connection/rpc-context.js.map +1 -0
  97. package/esm/node/index.d.ts +3 -2
  98. package/esm/node/index.js +3 -2
  99. package/esm/node/index.js.map +1 -1
  100. package/esm/node/server/index.d.ts +2 -0
  101. package/esm/node/server/index.js +3 -0
  102. package/esm/node/server/index.js.map +1 -0
  103. package/esm/node/server/rpc-handler-adapter.d.ts +15 -0
  104. package/esm/node/server/rpc-handler-adapter.js +74 -0
  105. package/esm/node/server/rpc-handler-adapter.js.map +1 -0
  106. package/esm/node/server/rpc-invoker.d.ts +28 -0
  107. package/esm/node/server/rpc-invoker.js +113 -0
  108. package/esm/node/server/rpc-invoker.js.map +1 -0
  109. package/esm/node/test/websocket-fixture-protocol.d.ts +36 -0
  110. package/esm/node/test/websocket-fixture-protocol.js +7 -0
  111. package/esm/node/test/websocket-fixture-protocol.js.map +1 -0
  112. package/esm/node/test/websocket-fixture.d.ts +40 -0
  113. package/esm/node/test/websocket-fixture.js +128 -0
  114. package/esm/node/test/websocket-fixture.js.map +1 -0
  115. package/esm/node/websocket/index.d.ts +4 -0
  116. package/esm/node/websocket/index.js +5 -0
  117. package/esm/node/websocket/index.js.map +1 -0
  118. package/esm/node/websocket/rpc-websocket-server.d.ts +45 -0
  119. package/esm/node/websocket/rpc-websocket-server.js +167 -0
  120. package/esm/node/websocket/rpc-websocket-server.js.map +1 -0
  121. package/esm/node/websocket/websocket-connection.d.ts +55 -0
  122. package/esm/node/websocket/websocket-connection.js +181 -0
  123. package/esm/node/websocket/websocket-connection.js.map +1 -0
  124. package/esm/node/websocket/websocket-exchange.d.ts +38 -0
  125. package/esm/node/websocket/websocket-exchange.js +124 -0
  126. package/esm/node/websocket/websocket-exchange.js.map +1 -0
  127. package/esm/node/websocket/websocket-frames.d.ts +31 -0
  128. package/esm/node/websocket/websocket-frames.js +119 -0
  129. package/esm/node/websocket/websocket-frames.js.map +1 -0
  130. package/lib/common/annotation/index.d.ts +2 -0
  131. package/lib/common/annotation/index.d.ts.map +1 -1
  132. package/lib/common/annotation/index.js +2 -0
  133. package/lib/common/annotation/index.js.map +1 -1
  134. package/lib/common/annotation/rpc-client.d.ts +8 -0
  135. package/lib/common/annotation/rpc-client.d.ts.map +1 -0
  136. package/lib/common/annotation/rpc-client.js +21 -0
  137. package/lib/common/annotation/rpc-client.js.map +1 -0
  138. package/lib/common/annotation/rpc-protocol.d.ts +8 -0
  139. package/lib/common/annotation/rpc-protocol.d.ts.map +1 -0
  140. package/lib/common/annotation/rpc-protocol.js +5 -0
  141. package/lib/common/annotation/rpc-protocol.js.map +1 -0
  142. package/lib/common/annotation/rpc.d.ts +4 -0
  143. package/lib/common/annotation/rpc.d.ts.map +1 -1
  144. package/lib/common/annotation/rpc.js +12 -16
  145. package/lib/common/annotation/rpc.js.map +1 -1
  146. package/lib/common/client/client-protocol.d.ts +7 -0
  147. package/lib/common/client/client-protocol.d.ts.map +1 -0
  148. package/lib/common/client/client-protocol.js +5 -0
  149. package/lib/common/client/client-protocol.js.map +1 -0
  150. package/lib/common/client/index.d.ts +3 -0
  151. package/lib/common/client/index.d.ts.map +1 -0
  152. package/lib/common/{handler → client}/index.js +2 -2
  153. package/lib/common/client/index.js.map +1 -0
  154. package/lib/common/client/rpc-client-registry.d.ts +15 -0
  155. package/lib/common/client/rpc-client-registry.d.ts.map +1 -0
  156. package/lib/common/client/rpc-client-registry.js +54 -0
  157. package/lib/common/client/rpc-client-registry.js.map +1 -0
  158. package/lib/common/constants.d.ts +3 -1
  159. package/lib/common/constants.d.ts.map +1 -1
  160. package/lib/common/constants.js +4 -2
  161. package/lib/common/constants.js.map +1 -1
  162. package/lib/common/converter/converter-protocol.d.ts +6 -2
  163. package/lib/common/converter/converter-protocol.d.ts.map +1 -1
  164. package/lib/common/converter/converter-protocol.js +1 -0
  165. package/lib/common/converter/converter-protocol.js.map +1 -1
  166. package/lib/common/endpoint/endpoint-protocol.d.ts +3 -0
  167. package/lib/common/endpoint/endpoint-protocol.d.ts.map +1 -1
  168. package/lib/common/endpoint/endpoint-resolver.d.ts +2 -0
  169. package/lib/common/endpoint/endpoint-resolver.d.ts.map +1 -1
  170. package/lib/common/endpoint/endpoint-resolver.js +16 -2
  171. package/lib/common/endpoint/endpoint-resolver.js.map +1 -1
  172. package/lib/common/error/error.d.ts +23 -0
  173. package/lib/common/error/error.d.ts.map +1 -1
  174. package/lib/common/error/error.js +35 -2
  175. package/lib/common/error/error.js.map +1 -1
  176. package/lib/common/index.d.ts +6 -6
  177. package/lib/common/index.d.ts.map +1 -1
  178. package/lib/common/index.js +6 -6
  179. package/lib/common/index.js.map +1 -1
  180. package/lib/common/module.d.ts.map +1 -1
  181. package/lib/common/module.js +4 -3
  182. package/lib/common/module.js.map +1 -1
  183. package/lib/common/processor/client-config-processor.d.ts +2 -2
  184. package/lib/common/processor/client-config-processor.d.ts.map +1 -1
  185. package/lib/common/processor/client-config-processor.js.map +1 -1
  186. package/lib/common/processor/processor-protocol.d.ts +2 -2
  187. package/lib/common/processor/processor-protocol.d.ts.map +1 -1
  188. package/lib/common/protocol/index.d.ts +2 -0
  189. package/lib/common/protocol/index.d.ts.map +1 -0
  190. package/lib/common/{channal → protocol}/index.js +1 -2
  191. package/lib/common/protocol/index.js.map +1 -0
  192. package/lib/common/protocol/json-rpc.d.ts +43 -0
  193. package/lib/common/protocol/json-rpc.d.ts.map +1 -0
  194. package/lib/common/protocol/json-rpc.js +51 -0
  195. package/lib/common/protocol/json-rpc.js.map +1 -0
  196. package/lib/common/proxy/index.d.ts +1 -4
  197. package/lib/common/proxy/index.d.ts.map +1 -1
  198. package/lib/common/proxy/index.js +1 -4
  199. package/lib/common/proxy/index.js.map +1 -1
  200. package/lib/common/proxy/rpc-proxy.d.ts +7 -0
  201. package/lib/common/proxy/rpc-proxy.d.ts.map +1 -0
  202. package/lib/common/proxy/rpc-proxy.js +43 -0
  203. package/lib/common/proxy/rpc-proxy.js.map +1 -0
  204. package/lib/common/transport/http-transport.d.ts +51 -0
  205. package/lib/common/transport/http-transport.d.ts.map +1 -0
  206. package/lib/common/transport/http-transport.js +102 -0
  207. package/lib/common/transport/http-transport.js.map +1 -0
  208. package/lib/common/transport/index.d.ts +5 -0
  209. package/lib/common/transport/index.d.ts.map +1 -0
  210. package/lib/common/{factory → transport}/index.js +4 -4
  211. package/lib/common/transport/index.js.map +1 -0
  212. package/lib/common/transport/transport-protocol.d.ts +13 -0
  213. package/lib/common/transport/transport-protocol.d.ts.map +1 -0
  214. package/lib/common/transport/transport-protocol.js +5 -0
  215. package/lib/common/transport/transport-protocol.js.map +1 -0
  216. package/lib/common/transport/transport-provider.d.ts +35 -0
  217. package/lib/common/transport/transport-provider.d.ts.map +1 -0
  218. package/lib/common/transport/transport-provider.js +106 -0
  219. package/lib/common/transport/transport-provider.js.map +1 -0
  220. package/lib/common/transport/websocket-transport.d.ts +55 -0
  221. package/lib/common/transport/websocket-transport.d.ts.map +1 -0
  222. package/lib/common/transport/websocket-transport.js +148 -0
  223. package/lib/common/transport/websocket-transport.js.map +1 -0
  224. package/lib/common/utils/index.d.ts +1 -1
  225. package/lib/common/utils/index.d.ts.map +1 -1
  226. package/lib/common/utils/index.js +1 -1
  227. package/lib/common/utils/index.js.map +1 -1
  228. package/lib/common/utils/rpc-method-util.d.ts +11 -0
  229. package/lib/common/utils/rpc-method-util.d.ts.map +1 -0
  230. package/lib/common/utils/rpc-method-util.js +31 -0
  231. package/lib/common/utils/rpc-method-util.js.map +1 -0
  232. package/lib/common/utils/rpc-util.d.ts +9 -9
  233. package/lib/common/utils/rpc-util.d.ts.map +1 -1
  234. package/lib/common/utils/rpc-util.js +24 -30
  235. package/lib/common/utils/rpc-util.js.map +1 -1
  236. package/lib/node/connection/connection-protocol.d.ts +27 -0
  237. package/lib/node/connection/connection-protocol.d.ts.map +1 -0
  238. package/lib/node/connection/connection-protocol.js +6 -0
  239. package/lib/node/connection/connection-protocol.js.map +1 -0
  240. package/lib/node/connection/index.d.ts +5 -0
  241. package/lib/node/connection/index.d.ts.map +1 -0
  242. package/lib/node/{channel → connection}/index.js +4 -4
  243. package/lib/node/connection/index.js.map +1 -0
  244. package/lib/node/connection/rpc-connection-manager.d.ts +11 -0
  245. package/lib/node/connection/rpc-connection-manager.d.ts.map +1 -0
  246. package/lib/node/connection/rpc-connection-manager.js +38 -0
  247. package/lib/node/connection/rpc-connection-manager.js.map +1 -0
  248. package/lib/node/connection/rpc-connection.d.ts +34 -0
  249. package/lib/node/connection/rpc-connection.d.ts.map +1 -0
  250. package/lib/node/connection/rpc-connection.js +110 -0
  251. package/lib/node/connection/rpc-connection.js.map +1 -0
  252. package/lib/node/connection/rpc-context.d.ts +15 -0
  253. package/lib/node/connection/rpc-context.d.ts.map +1 -0
  254. package/lib/node/connection/rpc-context.js +33 -0
  255. package/lib/node/connection/rpc-context.js.map +1 -0
  256. package/lib/node/index.d.ts +3 -2
  257. package/lib/node/index.d.ts.map +1 -1
  258. package/lib/node/index.js +3 -2
  259. package/lib/node/index.js.map +1 -1
  260. package/lib/node/rpc-http.spec.d.ts +2 -0
  261. package/lib/node/rpc-http.spec.d.ts.map +1 -0
  262. package/lib/node/rpc-http.spec.js +121 -0
  263. package/lib/node/rpc-http.spec.js.map +1 -0
  264. package/lib/node/rpc-websocket.spec.d.ts +6 -0
  265. package/lib/node/rpc-websocket.spec.d.ts.map +1 -0
  266. package/lib/node/rpc-websocket.spec.js +196 -0
  267. package/lib/node/rpc-websocket.spec.js.map +1 -0
  268. package/lib/node/server/index.d.ts +3 -0
  269. package/lib/node/server/index.d.ts.map +1 -0
  270. package/lib/node/{handler → server}/index.js +2 -2
  271. package/lib/node/server/index.js.map +1 -0
  272. package/lib/node/server/rpc-handler-adapter.d.ts +16 -0
  273. package/lib/node/server/rpc-handler-adapter.d.ts.map +1 -0
  274. package/lib/node/{handler/handler-adapter.js → server/rpc-handler-adapter.js} +40 -18
  275. package/lib/node/server/rpc-handler-adapter.js.map +1 -0
  276. package/lib/node/server/rpc-invoker.d.ts +29 -0
  277. package/lib/node/server/rpc-invoker.d.ts.map +1 -0
  278. package/lib/node/server/rpc-invoker.js +116 -0
  279. package/lib/node/server/rpc-invoker.js.map +1 -0
  280. package/lib/node/test/websocket-fixture-protocol.d.ts +37 -0
  281. package/lib/node/test/websocket-fixture-protocol.d.ts.map +1 -0
  282. package/lib/node/test/websocket-fixture-protocol.js +10 -0
  283. package/lib/node/test/websocket-fixture-protocol.js.map +1 -0
  284. package/lib/node/test/websocket-fixture.d.ts +41 -0
  285. package/lib/node/test/websocket-fixture.d.ts.map +1 -0
  286. package/lib/node/test/websocket-fixture.js +135 -0
  287. package/lib/node/test/websocket-fixture.js.map +1 -0
  288. package/lib/node/websocket/index.d.ts +5 -0
  289. package/lib/node/websocket/index.d.ts.map +1 -0
  290. package/lib/node/websocket/index.js +21 -0
  291. package/lib/node/websocket/index.js.map +1 -0
  292. package/lib/node/websocket/rpc-websocket-server.d.ts +46 -0
  293. package/lib/node/websocket/rpc-websocket-server.d.ts.map +1 -0
  294. package/lib/node/websocket/rpc-websocket-server.js +170 -0
  295. package/lib/node/websocket/rpc-websocket-server.js.map +1 -0
  296. package/lib/node/websocket/websocket-connection.d.ts +56 -0
  297. package/lib/node/websocket/websocket-connection.d.ts.map +1 -0
  298. package/lib/node/websocket/websocket-connection.js +185 -0
  299. package/lib/node/websocket/websocket-connection.js.map +1 -0
  300. package/lib/node/websocket/websocket-exchange.d.ts +39 -0
  301. package/lib/node/websocket/websocket-exchange.d.ts.map +1 -0
  302. package/lib/node/websocket/websocket-exchange.js +128 -0
  303. package/lib/node/websocket/websocket-exchange.js.map +1 -0
  304. package/lib/node/websocket/websocket-frames.d.ts +32 -0
  305. package/lib/node/websocket/websocket-frames.d.ts.map +1 -0
  306. package/lib/node/websocket/websocket-frames.js +124 -0
  307. package/lib/node/websocket/websocket-frames.js.map +1 -0
  308. package/lib/node/websocket/websocket-frames.spec.d.ts +2 -0
  309. package/lib/node/websocket/websocket-frames.spec.d.ts.map +1 -0
  310. package/lib/node/websocket/websocket-frames.spec.js +59 -0
  311. package/lib/node/websocket/websocket-frames.spec.js.map +1 -0
  312. package/package.json +28 -25
  313. package/src/common/annotation/index.ts +2 -0
  314. package/src/common/annotation/rpc-client.ts +17 -0
  315. package/src/common/annotation/rpc-protocol.ts +8 -0
  316. package/src/common/annotation/rpc.ts +13 -21
  317. package/src/common/client/client-protocol.ts +7 -0
  318. package/src/common/client/index.ts +2 -0
  319. package/src/common/client/rpc-client-registry.ts +42 -0
  320. package/src/common/constants.ts +4 -1
  321. package/src/common/converter/converter-protocol.ts +7 -2
  322. package/src/common/endpoint/endpoint-protocol.ts +3 -0
  323. package/src/common/endpoint/endpoint-resolver.ts +18 -4
  324. package/src/common/error/error.ts +41 -2
  325. package/src/common/index.ts +6 -6
  326. package/src/common/module.ts +7 -8
  327. package/src/common/processor/client-config-processor.ts +2 -2
  328. package/src/common/processor/processor-protocol.ts +2 -2
  329. package/src/common/protocol/index.ts +1 -0
  330. package/src/common/protocol/json-rpc.ts +74 -0
  331. package/src/common/proxy/index.ts +1 -5
  332. package/src/common/proxy/rpc-proxy.ts +42 -0
  333. package/src/common/transport/http-transport.ts +134 -0
  334. package/src/common/transport/index.ts +4 -0
  335. package/src/common/transport/transport-protocol.ts +16 -0
  336. package/src/common/transport/transport-provider.ts +86 -0
  337. package/src/common/transport/websocket-transport.ts +171 -0
  338. package/src/common/utils/index.ts +1 -1
  339. package/src/common/utils/rpc-method-util.ts +26 -0
  340. package/src/common/utils/rpc-util.ts +24 -35
  341. package/src/node/connection/connection-protocol.ts +30 -0
  342. package/src/node/connection/index.ts +3 -0
  343. package/src/node/connection/rpc-connection-manager.ts +29 -0
  344. package/src/node/connection/rpc-connection.ts +122 -0
  345. package/src/node/connection/rpc-context.ts +29 -0
  346. package/src/node/index.ts +3 -2
  347. package/src/node/rpc-http.spec.ts +126 -0
  348. package/src/node/rpc-websocket.spec.ts +196 -0
  349. package/src/node/server/index.ts +2 -0
  350. package/src/node/server/rpc-handler-adapter.ts +60 -0
  351. package/src/node/server/rpc-invoker.ts +104 -0
  352. package/src/node/test/websocket-fixture-protocol.ts +32 -0
  353. package/src/node/test/websocket-fixture.ts +122 -0
  354. package/src/node/websocket/index.ts +4 -0
  355. package/src/node/websocket/rpc-websocket-server.ts +163 -0
  356. package/src/node/websocket/websocket-connection.ts +198 -0
  357. package/src/node/websocket/websocket-exchange.ts +138 -0
  358. package/src/node/websocket/websocket-frames.spec.ts +62 -0
  359. package/src/node/websocket/websocket-frames.ts +122 -0
  360. package/esm/common/channal/channel-protocol.d.ts +0 -51
  361. package/esm/common/channal/channel-protocol.js +0 -34
  362. package/esm/common/channal/channel-protocol.js.map +0 -1
  363. package/esm/common/channal/http-channel.d.ts +0 -8
  364. package/esm/common/channal/http-channel.js +0 -22
  365. package/esm/common/channal/http-channel.js.map +0 -1
  366. package/esm/common/channal/index.d.ts +0 -2
  367. package/esm/common/channal/index.js +0 -3
  368. package/esm/common/channal/index.js.map +0 -1
  369. package/esm/common/factory/connection-factory.d.ts +0 -9
  370. package/esm/common/factory/connection-factory.js +0 -25
  371. package/esm/common/factory/connection-factory.js.map +0 -1
  372. package/esm/common/factory/index.d.ts +0 -4
  373. package/esm/common/factory/index.js +0 -5
  374. package/esm/common/factory/index.js.map +0 -1
  375. package/esm/common/factory/proxy-factory.d.ts +0 -56
  376. package/esm/common/factory/proxy-factory.js +0 -177
  377. package/esm/common/factory/proxy-factory.js.map +0 -1
  378. package/esm/common/factory/reader.d.ts +0 -15
  379. package/esm/common/factory/reader.js +0 -44
  380. package/esm/common/factory/reader.js.map +0 -1
  381. package/esm/common/factory/writer.d.ts +0 -9
  382. package/esm/common/factory/writer.js +0 -21
  383. package/esm/common/factory/writer.js.map +0 -1
  384. package/esm/common/handler/connection-handler.d.ts +0 -6
  385. package/esm/common/handler/connection-handler.js +0 -4
  386. package/esm/common/handler/connection-handler.js.map +0 -1
  387. package/esm/common/handler/handler-protocol.d.ts +0 -6
  388. package/esm/common/handler/handler-protocol.js +0 -2
  389. package/esm/common/handler/handler-protocol.js.map +0 -1
  390. package/esm/common/handler/index.d.ts +0 -2
  391. package/esm/common/handler/index.js +0 -3
  392. package/esm/common/handler/index.js.map +0 -1
  393. package/esm/common/proxy/delegating-http-proxy-creator.d.ts +0 -23
  394. package/esm/common/proxy/delegating-http-proxy-creator.js +0 -86
  395. package/esm/common/proxy/delegating-http-proxy-creator.js.map +0 -1
  396. package/esm/common/proxy/http-proxy-creator.d.ts +0 -42
  397. package/esm/common/proxy/http-proxy-creator.js +0 -139
  398. package/esm/common/proxy/http-proxy-creator.js.map +0 -1
  399. package/esm/common/proxy/proxy-protocol.d.ts +0 -20
  400. package/esm/common/proxy/proxy-protocol.js +0 -3
  401. package/esm/common/proxy/proxy-protocol.js.map +0 -1
  402. package/esm/common/proxy/proxy-provider.d.ts +0 -9
  403. package/esm/common/proxy/proxy-provider.js +0 -40
  404. package/esm/common/proxy/proxy-provider.js.map +0 -1
  405. package/esm/common/utils/logger.d.ts +0 -8
  406. package/esm/common/utils/logger.js +0 -18
  407. package/esm/common/utils/logger.js.map +0 -1
  408. package/esm/node/channel/channel-manager.d.ts +0 -9
  409. package/esm/node/channel/channel-manager.js +0 -56
  410. package/esm/node/channel/channel-manager.js.map +0 -1
  411. package/esm/node/channel/channel-middleware.d.ts +0 -7
  412. package/esm/node/channel/channel-middleware.js +0 -37
  413. package/esm/node/channel/channel-middleware.js.map +0 -1
  414. package/esm/node/channel/channel-protocol.d.ts +0 -12
  415. package/esm/node/channel/channel-protocol.js +0 -6
  416. package/esm/node/channel/channel-protocol.js.map +0 -1
  417. package/esm/node/channel/channel-strategy.d.ts +0 -9
  418. package/esm/node/channel/channel-strategy.js +0 -61
  419. package/esm/node/channel/channel-strategy.js.map +0 -1
  420. package/esm/node/channel/index.d.ts +0 -4
  421. package/esm/node/channel/index.js +0 -5
  422. package/esm/node/channel/index.js.map +0 -1
  423. package/esm/node/handler/handler-adapter.d.ts +0 -13
  424. package/esm/node/handler/handler-adapter.js +0 -52
  425. package/esm/node/handler/handler-adapter.js.map +0 -1
  426. package/esm/node/handler/handler-protocol.d.ts +0 -1
  427. package/esm/node/handler/handler-protocol.js +0 -2
  428. package/esm/node/handler/handler-protocol.js.map +0 -1
  429. package/esm/node/handler/index.d.ts +0 -2
  430. package/esm/node/handler/index.js +0 -3
  431. package/esm/node/handler/index.js.map +0 -1
  432. package/lib/common/channal/channel-protocol.d.ts +0 -52
  433. package/lib/common/channal/channel-protocol.d.ts.map +0 -1
  434. package/lib/common/channal/channel-protocol.js +0 -38
  435. package/lib/common/channal/channel-protocol.js.map +0 -1
  436. package/lib/common/channal/http-channel.d.ts +0 -9
  437. package/lib/common/channal/http-channel.d.ts.map +0 -1
  438. package/lib/common/channal/http-channel.js +0 -26
  439. package/lib/common/channal/http-channel.js.map +0 -1
  440. package/lib/common/channal/index.d.ts +0 -3
  441. package/lib/common/channal/index.d.ts.map +0 -1
  442. package/lib/common/channal/index.js.map +0 -1
  443. package/lib/common/factory/connection-factory.d.ts +0 -10
  444. package/lib/common/factory/connection-factory.d.ts.map +0 -1
  445. package/lib/common/factory/connection-factory.js +0 -28
  446. package/lib/common/factory/connection-factory.js.map +0 -1
  447. package/lib/common/factory/index.d.ts +0 -5
  448. package/lib/common/factory/index.d.ts.map +0 -1
  449. package/lib/common/factory/index.js.map +0 -1
  450. package/lib/common/factory/proxy-factory.d.ts +0 -57
  451. package/lib/common/factory/proxy-factory.d.ts.map +0 -1
  452. package/lib/common/factory/proxy-factory.js +0 -182
  453. package/lib/common/factory/proxy-factory.js.map +0 -1
  454. package/lib/common/factory/reader.d.ts +0 -16
  455. package/lib/common/factory/reader.d.ts.map +0 -1
  456. package/lib/common/factory/reader.js +0 -48
  457. package/lib/common/factory/reader.js.map +0 -1
  458. package/lib/common/factory/writer.d.ts +0 -10
  459. package/lib/common/factory/writer.d.ts.map +0 -1
  460. package/lib/common/factory/writer.js +0 -25
  461. package/lib/common/factory/writer.js.map +0 -1
  462. package/lib/common/handler/connection-handler.d.ts +0 -7
  463. package/lib/common/handler/connection-handler.d.ts.map +0 -1
  464. package/lib/common/handler/connection-handler.js +0 -8
  465. package/lib/common/handler/connection-handler.js.map +0 -1
  466. package/lib/common/handler/handler-protocol.d.ts +0 -7
  467. package/lib/common/handler/handler-protocol.d.ts.map +0 -1
  468. package/lib/common/handler/handler-protocol.js +0 -5
  469. package/lib/common/handler/handler-protocol.js.map +0 -1
  470. package/lib/common/handler/index.d.ts +0 -3
  471. package/lib/common/handler/index.d.ts.map +0 -1
  472. package/lib/common/handler/index.js.map +0 -1
  473. package/lib/common/proxy/delegating-http-proxy-creator.d.ts +0 -24
  474. package/lib/common/proxy/delegating-http-proxy-creator.d.ts.map +0 -1
  475. package/lib/common/proxy/delegating-http-proxy-creator.js +0 -89
  476. package/lib/common/proxy/delegating-http-proxy-creator.js.map +0 -1
  477. package/lib/common/proxy/http-proxy-creator.d.ts +0 -43
  478. package/lib/common/proxy/http-proxy-creator.d.ts.map +0 -1
  479. package/lib/common/proxy/http-proxy-creator.js +0 -143
  480. package/lib/common/proxy/http-proxy-creator.js.map +0 -1
  481. package/lib/common/proxy/proxy-protocol.d.ts +0 -21
  482. package/lib/common/proxy/proxy-protocol.d.ts.map +0 -1
  483. package/lib/common/proxy/proxy-protocol.js +0 -6
  484. package/lib/common/proxy/proxy-protocol.js.map +0 -1
  485. package/lib/common/proxy/proxy-provider.d.ts +0 -10
  486. package/lib/common/proxy/proxy-provider.d.ts.map +0 -1
  487. package/lib/common/proxy/proxy-provider.js +0 -43
  488. package/lib/common/proxy/proxy-provider.js.map +0 -1
  489. package/lib/common/utils/logger.d.ts +0 -9
  490. package/lib/common/utils/logger.d.ts.map +0 -1
  491. package/lib/common/utils/logger.js +0 -22
  492. package/lib/common/utils/logger.js.map +0 -1
  493. package/lib/node/channel/channel-manager.d.ts +0 -10
  494. package/lib/node/channel/channel-manager.d.ts.map +0 -1
  495. package/lib/node/channel/channel-manager.js +0 -59
  496. package/lib/node/channel/channel-manager.js.map +0 -1
  497. package/lib/node/channel/channel-middleware.d.ts +0 -8
  498. package/lib/node/channel/channel-middleware.d.ts.map +0 -1
  499. package/lib/node/channel/channel-middleware.js +0 -40
  500. package/lib/node/channel/channel-middleware.js.map +0 -1
  501. package/lib/node/channel/channel-protocol.d.ts +0 -13
  502. package/lib/node/channel/channel-protocol.d.ts.map +0 -1
  503. package/lib/node/channel/channel-protocol.js +0 -9
  504. package/lib/node/channel/channel-protocol.js.map +0 -1
  505. package/lib/node/channel/channel-strategy.d.ts +0 -10
  506. package/lib/node/channel/channel-strategy.d.ts.map +0 -1
  507. package/lib/node/channel/channel-strategy.js +0 -64
  508. package/lib/node/channel/channel-strategy.js.map +0 -1
  509. package/lib/node/channel/index.d.ts +0 -5
  510. package/lib/node/channel/index.d.ts.map +0 -1
  511. package/lib/node/channel/index.js.map +0 -1
  512. package/lib/node/handler/handler-adapter.d.ts +0 -14
  513. package/lib/node/handler/handler-adapter.d.ts.map +0 -1
  514. package/lib/node/handler/handler-adapter.js.map +0 -1
  515. package/lib/node/handler/handler-protocol.d.ts +0 -2
  516. package/lib/node/handler/handler-protocol.d.ts.map +0 -1
  517. package/lib/node/handler/handler-protocol.js +0 -5
  518. package/lib/node/handler/handler-protocol.js.map +0 -1
  519. package/lib/node/handler/index.d.ts +0 -3
  520. package/lib/node/handler/index.d.ts.map +0 -1
  521. package/lib/node/handler/index.js.map +0 -1
  522. package/src/common/channal/channel-protocol.ts +0 -82
  523. package/src/common/channal/http-channel.ts +0 -30
  524. package/src/common/channal/index.ts +0 -2
  525. package/src/common/factory/connection-factory.ts +0 -21
  526. package/src/common/factory/index.ts +0 -4
  527. package/src/common/factory/proxy-factory.ts +0 -219
  528. package/src/common/factory/reader.ts +0 -50
  529. package/src/common/factory/writer.ts +0 -26
  530. package/src/common/handler/connection-handler.ts +0 -7
  531. package/src/common/handler/handler-protocol.ts +0 -8
  532. package/src/common/handler/index.ts +0 -2
  533. package/src/common/proxy/delegating-http-proxy-creator.ts +0 -68
  534. package/src/common/proxy/http-proxy-creator.ts +0 -179
  535. package/src/common/proxy/proxy-protocol.ts +0 -26
  536. package/src/common/proxy/proxy-provider.ts +0 -29
  537. package/src/common/utils/logger.ts +0 -23
  538. package/src/node/channel/channel-manager.ts +0 -44
  539. package/src/node/channel/channel-middleware.ts +0 -27
  540. package/src/node/channel/channel-protocol.ts +0 -21
  541. package/src/node/channel/channel-strategy.ts +0 -56
  542. package/src/node/channel/index.ts +0 -4
  543. package/src/node/handler/handler-adapter.ts +0 -38
  544. package/src/node/handler/handler-protocol.ts +0 -1
  545. package/src/node/handler/index.ts +0 -2
@@ -0,0 +1,122 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+ import { ComponentId, Disposable, Emitter } from '@celljs/core';
3
+ import { Request } from '@celljs/web/lib/node';
4
+ import { JsonRpc, RpcProxy, RpcTransport, RpcUtil } from '../../common';
5
+ import { WebSocketConnection } from '../websocket/websocket-connection';
6
+ import { RpcConnection } from './connection-protocol';
7
+
8
+ let seq = 0;
9
+
10
+ /** An {@link RpcConnection} on a {@link WebSocketConnection}: requests of the client go to `dispatch`. */
11
+ export class RpcConnectionImpl implements RpcConnection, RpcTransport {
12
+
13
+ readonly id = `${Date.now().toString(36)}-${(++seq).toString(36)}`;
14
+ protected readonly pending = new Map<JsonRpc.Id, { resolve(response: JsonRpc.Response): void, timer: ReturnType<typeof setTimeout> }>();
15
+ protected readonly onCloseEmitter = new Emitter<void>();
16
+ protected readonly clients = new Map<string, object>();
17
+ protected callSeq = 0;
18
+ protected _closed = false;
19
+
20
+ constructor(
21
+ protected readonly socket: WebSocketConnection,
22
+ protected readonly upgrade: IncomingMessage,
23
+ protected readonly dispatch: (connection: RpcConnectionImpl, request: JsonRpc.Request) => Promise<JsonRpc.Response | undefined>,
24
+ protected readonly callTimeout: number,
25
+ ) {
26
+ socket.onMessage(text => this.receive(text));
27
+ socket.onClose(() => this.closeConnection());
28
+ }
29
+
30
+ get request(): Request {
31
+ return this.upgrade as Request;
32
+ }
33
+
34
+ get closed(): boolean {
35
+ return this._closed;
36
+ }
37
+
38
+ client<T extends object>(id: ComponentId<T>): T {
39
+ const path = RpcUtil.toPath(id);
40
+ let client = this.clients.get(path);
41
+ if (!client) {
42
+ client = RpcProxy.create<T>(path, this);
43
+ this.clients.set(path, client);
44
+ }
45
+ return client as T;
46
+ }
47
+
48
+ onClose(listener: () => void): Disposable {
49
+ if (this._closed) {
50
+ listener();
51
+ return Disposable.NULL;
52
+ }
53
+ return this.onCloseEmitter.event(listener);
54
+ }
55
+
56
+ close(code = 1000, reason = ''): void {
57
+ this.socket.close(code, reason);
58
+ }
59
+
60
+ /** A call to the client: the transport of the proxies of {@link client}. */
61
+ call(service: string, method: string, params: unknown[]): Promise<JsonRpc.Response> {
62
+ const id = ++this.callSeq;
63
+ if (this._closed) {
64
+ return Promise.resolve(this.closedError(id));
65
+ }
66
+ return new Promise<JsonRpc.Response>(resolve => {
67
+ const timer = setTimeout(() => {
68
+ this.pending.delete(id);
69
+ resolve(JsonRpc.error(id, JsonRpc.TIMEOUT, `The client did not answer ${service}.${method} within ${this.callTimeout} ms.`));
70
+ }, this.callTimeout);
71
+ this.pending.set(id, { resolve, timer });
72
+ this.socket.send(JSON.stringify(JsonRpc.request(id, `${service}/${method}`, params)));
73
+ });
74
+ }
75
+
76
+ protected receive(text: string): void {
77
+ let message: unknown;
78
+ try {
79
+ message = JSON.parse(text);
80
+ } catch {
81
+ this.socket.send(JSON.stringify(JsonRpc.error(null, JsonRpc.PARSE_ERROR, 'The message is not JSON.')));
82
+ return;
83
+ }
84
+ if (JsonRpc.isResponse(message)) {
85
+ const pending = message.id === null ? undefined : this.pending.get(message.id);
86
+ if (pending) {
87
+ clearTimeout(pending.timer);
88
+ this.pending.delete(message.id!);
89
+ pending.resolve(message);
90
+ }
91
+ return;
92
+ }
93
+ if (!JsonRpc.isRequest(message)) {
94
+ this.socket.send(JSON.stringify(JsonRpc.error(null, JsonRpc.INVALID_REQUEST, 'Not a JSON-RPC 2.0 request or response.')));
95
+ return;
96
+ }
97
+ const request = message;
98
+ void this.dispatch(this, request).then(response => {
99
+ if (response && request.id !== undefined) {
100
+ this.socket.send(JSON.stringify(response));
101
+ }
102
+ });
103
+ }
104
+
105
+ protected closeConnection(): void {
106
+ if (this._closed) {
107
+ return;
108
+ }
109
+ this._closed = true;
110
+ for (const [id, pending] of this.pending) {
111
+ clearTimeout(pending.timer);
112
+ pending.resolve(this.closedError(id));
113
+ }
114
+ this.pending.clear();
115
+ this.onCloseEmitter.fire();
116
+ this.onCloseEmitter.dispose();
117
+ }
118
+
119
+ protected closedError(id: JsonRpc.Id): JsonRpc.Response {
120
+ return JsonRpc.error(id, JsonRpc.CONNECTION_CLOSED, 'The WebSocket connection of the client is closed.');
121
+ }
122
+ }
@@ -0,0 +1,29 @@
1
+ import { Context, HttpError } from '@celljs/web/lib/node';
2
+ import { RPC_CONNECTION_KEY, RpcConnection } from './connection-protocol';
3
+
4
+ /** A call over HTTP asked for the WebSocket connection of the client: a 400 with its message. */
5
+ export class RpcNoConnectionError extends HttpError {
6
+ readonly code = 'CELL_RPC_NO_CONNECTION';
7
+ readonly hint = 'Set rpc.transport: websocket, and run the backend where WebSocket connections are accepted (not on a serverless platform).';
8
+
9
+ constructor() {
10
+ super(400, 'This call did not come over a WebSocket connection, so the server cannot call the client back.');
11
+ }
12
+ }
13
+
14
+ export namespace RpcContext {
15
+
16
+ /** The WebSocket connection of the current call; undefined for a call over HTTP. */
17
+ export function connection(): RpcConnection | undefined {
18
+ return (Context.getCurrent() as unknown as Record<string, RpcConnection | undefined> | undefined)?.[RPC_CONNECTION_KEY];
19
+ }
20
+
21
+ /** The WebSocket connection of the current call; throws {@link RpcNoConnectionError} without one. */
22
+ export function requireConnection(): RpcConnection {
23
+ const connection = RpcContext.connection();
24
+ if (!connection) {
25
+ throw new RpcNoConnectionError();
26
+ }
27
+ return connection;
28
+ }
29
+ }
package/src/node/index.ts CHANGED
@@ -1,2 +1,3 @@
1
- export * from './channel';
2
- export * from './handler';
1
+ export * from './connection';
2
+ export * from './server';
3
+ export * from './websocket';
@@ -0,0 +1,126 @@
1
+ import { describe, it, beforeAll, afterAll, expect } from 'bun:test';
2
+ import { Server } from 'node:http';
3
+ import { AddressInfo } from 'node:net';
4
+ // The load order of the generated backend entry: the static modules of core, then the modules of the
5
+ // packages (see ContainerGenerator in @celljs/vite and the cell field of each package.json).
6
+ import coreCommonStatic from '@celljs/core/lib/common/static-module';
7
+ import coreNodeStatic from '@celljs/core/lib/node/static-module';
8
+ import httpCommonModule from '@celljs/http/lib/common/module';
9
+ import webCommonModule from '@celljs/web/lib/common/module';
10
+ import webNodeModule from '@celljs/web/lib/node/module';
11
+ import rpcCommonModule from '../common/module';
12
+ import rpcNodeModule from './module';
13
+ import { Container } from '@celljs/core/lib/common/container/container';
14
+ import { ContainerProvider } from '@celljs/core/lib/common/container/container-provider';
15
+ import { autoBind } from '@celljs/core/lib/common/container/auto-bind';
16
+ import { currentThis } from '@celljs/core/lib/common/utils';
17
+ import { Application } from '@celljs/core/lib/common/application/application-protocol';
18
+ import { HttpServerUtil } from '@celljs/web/lib/node';
19
+ import { DefaultRestOperations } from '@celljs/http';
20
+ import { Rpc } from '../common/annotation';
21
+ import { RpcUtil } from '../common/utils';
22
+ import { RpcError } from '../common/error';
23
+
24
+ /**
25
+ * An RPC proxy calls a real backend over HTTP: RestOperations (fetch) → POST /api → RpcHandlerAdapter → @Rpc
26
+ * service. The config is the merged default of the cell.yml files of core, web, http and rpc.
27
+ */
28
+ const CONFIG = {
29
+ html: { title: 'Cell Framework' }, component: { proxy: false }, aop: { enabled: true }, logger: { level: 'error' }, tenant: { enabled: false },
30
+ server: { path: '/', port: 3000, host: '127.0.0.1', endpoint: 'http://localhost:3000' },
31
+ web: { session: { autoCommit: true, maxAge: 86400000, sessionIdKey: 'cell:sessionId', sessionKey: 'cell:session' }, trace: { requestField: 'X-Cell-Trace-ID', responseField: 'X-Cell-Trace-ID' }, health: { url: '/health', method: 'GET' }, cookies: { keys: [ 'abcdef' ] }, route: { cacheSize: 500 }, validationPipeOptions: { detailedOutputDisabled: false, transformEnabled: true } },
32
+ http: { client: { headers: { 'X-Requested-With': 'XMLHttpRequest' } } },
33
+ rpc: { path: 'api', merge: { enabled: false, timerDelay: 35, maxLength: 5242880, maxCount: 100 } },
34
+ };
35
+
36
+ const WelcomeServer = Symbol('WelcomeServer');
37
+ interface WelcomeServer {
38
+ say(name: string): Promise<string>;
39
+ fail(): Promise<void>;
40
+ }
41
+
42
+ @Rpc(WelcomeServer)
43
+ class WelcomeServerImpl implements WelcomeServer {
44
+ async say(name: string): Promise<string> {
45
+ return `Welcome, ${name}`;
46
+ }
47
+
48
+ async fail(): Promise<void> {
49
+ throw new Error('boom');
50
+ }
51
+ }
52
+
53
+ let server: Server;
54
+ let endpoint: string;
55
+
56
+ beforeAll(async () => {
57
+ expect(WelcomeServerImpl).toBeDefined();
58
+ currentThis.cellProps = structuredClone(CONFIG);
59
+ const container = new Container(coreCommonStatic, coreNodeStatic, httpCommonModule, webCommonModule, webNodeModule, rpcCommonModule, rpcNodeModule, autoBind());
60
+ ContainerProvider.set(container);
61
+ await container.get<Application>(Application).start();
62
+ server = HttpServerUtil.createHttpServer(HttpServerUtil.createHandler(container));
63
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
64
+ endpoint = `http://127.0.0.1:${(server.address() as AddressInfo).port}/api`;
65
+ });
66
+
67
+ afterAll(() => {
68
+ server.closeAllConnections();
69
+ server.close();
70
+ });
71
+
72
+ describe('rpc over HTTP', () => {
73
+
74
+ it('calls a method of an @Rpc service and returns its result', async () => {
75
+ const welcome = RpcUtil.create<WelcomeServer>(endpoint, WelcomeServer);
76
+ expect(await welcome.say('Tom')).toBe('Welcome, Tom');
77
+ });
78
+
79
+ it('rejects with the error the service threw', async () => {
80
+ const welcome = RpcUtil.create<WelcomeServer>(endpoint, WelcomeServer);
81
+ let message: string | undefined;
82
+ try {
83
+ await welcome.fail();
84
+ } catch (error) {
85
+ message = (error as Error).message;
86
+ }
87
+ expect(message).toContain('boom');
88
+ });
89
+
90
+ it('sends the calls of one tick in one request when merging is enabled', async () => {
91
+ const restOperations = new DefaultRestOperations();
92
+ let requests = 0;
93
+ restOperations.interceptors.request.use(config => {
94
+ requests++;
95
+ return config;
96
+ });
97
+ const welcome = RpcUtil.create<WelcomeServer>(endpoint, WelcomeServer, { restOperations, merge: { enabled: true, timerDelay: 5 } });
98
+ expect(await Promise.all([ welcome.say('a'), welcome.say('b') ])).toEqual([ 'Welcome, a', 'Welcome, b' ]);
99
+ expect(requests).toBe(1);
100
+ });
101
+
102
+ it('speaks JSON-RPC 2.0: batches, notifications, and only the methods the service declares', async () => {
103
+ const post = async (body: unknown) => {
104
+ const response = await fetch(`${endpoint}/WelcomeServer`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
105
+ return { status: response.status, body: response.status === 204 ? undefined : await response.json() };
106
+ };
107
+ expect(await post({ jsonrpc: '2.0', id: 1, method: 'say', params: ['a'] })).toEqual({ status: 200, body: { jsonrpc: '2.0', id: 1, result: 'Welcome, a' } });
108
+ const batch = await post([{ jsonrpc: '2.0', id: 1, method: 'say', params: ['a'] }, { jsonrpc: '2.0', method: 'say', params: ['b'] }, { jsonrpc: '2.0', id: 2, method: 'constructor' }, { id: 3 }]);
109
+ expect(batch.body.map((r: any) => [r.id, r.result ?? r.error.code])).toEqual([[1, 'Welcome, a'], [2, -32601], [3, -32600]]);
110
+ expect(await post({ jsonrpc: '2.0', method: 'say', params: ['c'] })).toEqual({ status: 204, body: undefined });
111
+ expect((await post({ jsonrpc: '2.0', id: 4, method: 'toString' })).body.error.code).toBe(-32601);
112
+ expect((await post({ jsonrpc: '2.0', id: 5, method: '__proto__' })).body.error.code).toBe(-32601);
113
+ });
114
+
115
+ it('leaves other paths and unknown services to the other handlers', async () => {
116
+ expect((await fetch(`${endpoint}/NoSuchServer`, { method: 'POST', body: '{}' })).status).toBe(404);
117
+ expect((await fetch(`${endpoint}/WelcomeServer`)).status).toBe(404);
118
+ });
119
+
120
+ it('turns an answer that is not JSON-RPC (a refusing middleware, a proxy) into an RpcError with the status', async () => {
121
+ const welcome = RpcUtil.create<WelcomeServer>(endpoint.replace('/api', '/elsewhere'), WelcomeServer);
122
+ const error = await welcome.say('x').catch(e => e) as RpcError;
123
+ expect(error).toBeInstanceOf(RpcError);
124
+ expect(error.status).toBe(404);
125
+ });
126
+ });
@@ -0,0 +1,196 @@
1
+ import { describe, it, beforeAll, afterAll, expect } from 'bun:test';
2
+ import { ChildProcess, spawn } from 'node:child_process';
3
+ import { request as httpRequest } from 'node:http';
4
+ import { join } from 'node:path';
5
+ import coreCommonStatic from '@celljs/core/lib/common/static-module';
6
+ import coreNodeStatic from '@celljs/core/lib/node/static-module';
7
+ import httpCommonModule from '@celljs/http/lib/common/module';
8
+ import webCommonModule from '@celljs/web/lib/common/module';
9
+ import { Container } from '@celljs/core/lib/common/container/container';
10
+ import { ContainerProvider } from '@celljs/core/lib/common/container/container-provider';
11
+ import { autoBind } from '@celljs/core/lib/common/container/auto-bind';
12
+ import { currentThis } from '@celljs/core/lib/common/utils';
13
+ import { Application } from '@celljs/core/lib/common/application/application-protocol';
14
+ import rpcCommonModule from '../common/module';
15
+ import { HttpTransport, JsonRpc, RpcClient, RpcError, RpcProxy, RpcUtil, WebSocketTransport } from '../common';
16
+ // Not ./websocket: its components would join the client container of this file.
17
+ import { WebSocketConnection } from './websocket/websocket-connection';
18
+ import { ChatClient, ChatServer, NotYours } from './test/websocket-fixture-protocol';
19
+
20
+ const received: string[] = [];
21
+
22
+ /** The client side: a container like a frontend's, with a component the server calls. */
23
+ @RpcClient(ChatClient)
24
+ export class ChatClientImpl implements ChatClient {
25
+ async receive(text: string) {
26
+ received.push(text);
27
+ return `got ${text}`;
28
+ }
29
+ }
30
+
31
+ let child: ChildProcess;
32
+ let base: string;
33
+ let wsUrl: string;
34
+ let container: Container;
35
+
36
+ const http = () => new HttpTransport({ endpointResolver: { resolve: async s => `${base}/api/${s}` } });
37
+ const chat = (transport = new WebSocketTransport({ url: async () => wsUrl, fallback: http() })) => RpcProxy.create<ChatServer>('ChatServer', transport);
38
+
39
+ function upgrade(headers: Record<string, string>): Promise<number> {
40
+ return new Promise((resolve, reject) => {
41
+ const req = httpRequest(wsUrl.replace('ws', 'http'), { agent: false, headers: { Connection: 'Upgrade', Upgrade: 'websocket', 'Sec-WebSocket-Version': '13', 'Sec-WebSocket-Key': 'dGhlIHNhbXBsZSBub25jZQ==', ...headers } });
42
+ req.on('upgrade', (res, socket) => {
43
+ socket.destroy();
44
+ resolve(res.statusCode ?? 101);
45
+ });
46
+ req.on('response', res => {
47
+ res.resume();
48
+ resolve(res.statusCode ?? 0);
49
+ });
50
+ req.on('error', reject);
51
+ req.end();
52
+ });
53
+ }
54
+
55
+ function raw(messages: string[], expected: number, headers: Record<string, string> = {}): Promise<any[]> {
56
+ return new Promise((resolve, reject) => {
57
+ const socket = new WebSocket(wsUrl, { headers } as any);
58
+ const replies: any[] = [];
59
+ socket.onopen = () => messages.forEach(m => socket.send(m));
60
+ socket.onmessage = event => {
61
+ replies.push(JSON.parse(String(event.data)));
62
+ if (replies.length === expected) {
63
+ socket.close();
64
+ resolve(replies);
65
+ }
66
+ };
67
+ socket.onerror = reject;
68
+ });
69
+ }
70
+
71
+ beforeAll(async () => {
72
+ // The server runs in Node.js: node:http of Bun < 1.4 cannot answer upgrades.
73
+ const fixture = join(__dirname, 'test', 'websocket-fixture.js');
74
+ child = spawn('node', ['-e', `require(${JSON.stringify(fixture)}).startFixtureServer().then(s => console.log('PORT ' + s.port))`], { stdio: ['ignore', 'pipe', 'inherit'] });
75
+ const port = await new Promise<number>((resolve, reject) => {
76
+ child.stdout!.on('data', (chunk: Buffer) => {
77
+ const match = /PORT (\d+)/.exec(String(chunk));
78
+ if (match) {
79
+ resolve(Number(match[1]));
80
+ }
81
+ });
82
+ child.once('exit', code => reject(new Error(`the fixture server exited with ${code}`)));
83
+ });
84
+ base = `http://127.0.0.1:${port}`;
85
+ wsUrl = `ws://127.0.0.1:${port}/api/ws`;
86
+ currentThis.cellProps = {
87
+ component: { proxy: false }, aop: { enabled: false }, logger: { level: 'error' },
88
+ server: { path: '/' }, http: { client: { headers: {} } },
89
+ rpc: { path: 'api', transport: 'websocket', defaultEndpoint: `${base}{rpcPath}/{serviceIdentifier}`, websocket: { endpoint: wsUrl, reconnectDelay: 100 } },
90
+ };
91
+ container = new Container(coreCommonStatic, coreNodeStatic, httpCommonModule, webCommonModule, rpcCommonModule, autoBind());
92
+ ContainerProvider.set(container);
93
+ await container.get<Application>(Application).start();
94
+ }, 30000);
95
+
96
+ afterAll(async () => {
97
+ await container?.get<Application>(Application).stop();
98
+ child?.kill();
99
+ });
100
+
101
+ describe('rpc over WebSocket', () => {
102
+
103
+ it('calls the services over one connection, which the server calls the @RpcClient components back over', async () => {
104
+ const proxy = RpcUtil.get<ChatServer>(ChatServer);
105
+ expect(await proxy.echo('hello')).toBe('hello');
106
+ expect(await proxy.viaWebSocket()).toBe(true);
107
+ expect(await proxy.connections()).toBe(1);
108
+ expect(await proxy.broadcast('news')).toEqual(['got news']);
109
+ expect(received).toEqual(['news']);
110
+ });
111
+
112
+ it('answers like HTTP: application errors with code and data, refusals with their message, internal errors without it', async () => {
113
+ const proxy = RpcUtil.get<ChatServer>(ChatServer);
114
+ const application = await proxy.rejectApplication().catch(e => e);
115
+ expect(NotYours.is(application) || application.code === NotYours.code).toBe(true);
116
+ expect(application.data).toEqual({ id: '42' });
117
+ const refused = await proxy.refuse().catch(e => e) as RpcError;
118
+ expect([refused.message, refused.status]).toEqual(['not yours', 403]);
119
+ const failed = await proxy.fail().catch(e => e) as RpcError;
120
+ expect(failed).toBeInstanceOf(RpcError);
121
+ expect([failed.message, failed.status]).toEqual(['Internal Server Error', 500]);
122
+ // The stack leads to the caller and holds nothing of the server.
123
+ expect(failed.stack).toContain('rpc-websocket.spec');
124
+ expect(failed.stack).not.toContain('ECONNREFUSED');
125
+ });
126
+
127
+ it('runs the middlewares with the headers of the upgrade request', async () => {
128
+ const call = JSON.stringify(JsonRpc.request(1, 'Guarded/secret', []));
129
+ expect((await raw([call], 1))[0].error).toEqual({ code: JsonRpc.SERVER_ERROR, message: 'token required', data: { status: 401 } });
130
+ expect((await raw([call], 1, { 'x-token': 'open sesame' }))[0].result).toBe('treasure');
131
+ });
132
+
133
+ it('accepts its own origin, listed origins and clients without one; refuses other origins and versions', async () => {
134
+ expect(await upgrade({})).toBe(101);
135
+ expect(await upgrade({ Origin: base })).toBe(101);
136
+ expect(await upgrade({ Origin: 'https://app.example.com' })).toBe(101);
137
+ expect(await upgrade({ Origin: 'https://evil.example.com' })).toBe(403);
138
+ expect(await upgrade({ 'Sec-WebSocket-Version': '8' })).toBe(426);
139
+ });
140
+
141
+ it('answers unknown methods, methods a service does not declare and messages that are not JSON-RPC', async () => {
142
+ const replies = await raw([
143
+ JSON.stringify(JsonRpc.request(1, 'ChatServer/nope', [])),
144
+ JSON.stringify(JsonRpc.request(2, 'ChatServer/constructor', [])),
145
+ JSON.stringify(JsonRpc.request(3, 'ChatServer/toString', [])),
146
+ JSON.stringify(JsonRpc.request(4, 'Unknown/echo', [])),
147
+ JSON.stringify(JsonRpc.request(5, 'echo', [])),
148
+ 'not json',
149
+ ], 6);
150
+ expect(Object.fromEntries(replies.map(r => [r.id ?? 'null', r.error.code]))).toEqual({
151
+ 1: JsonRpc.METHOD_NOT_FOUND, 2: JsonRpc.METHOD_NOT_FOUND, 3: JsonRpc.METHOD_NOT_FOUND, 4: JsonRpc.METHOD_NOT_FOUND, 5: JsonRpc.METHOD_NOT_FOUND, null: JsonRpc.PARSE_ERROR,
152
+ });
153
+ });
154
+
155
+ it('answers the pending calls of the server when a client goes away, and runs onClose once', async () => {
156
+ const transport = new WebSocketTransport({ url: async () => wsUrl, fallback: http() });
157
+ const own = chat(transport);
158
+ await own.join();
159
+ // This client has no @RpcClient: the server's call fails with METHOD_NOT_FOUND.
160
+ const observer = RpcUtil.get<ChatServer>(ChatServer);
161
+ expect((await observer.callJoined('x')).code).toBe(JsonRpc.METHOD_NOT_FOUND);
162
+ transport.close();
163
+ let state = await observer.joinedState();
164
+ for (let i = 0; i < 50 && !state.closed; i++) {
165
+ await new Promise(r => setTimeout(r, 20));
166
+ state = await observer.joinedState();
167
+ }
168
+ expect(state).toEqual({ closed: true, closes: 1 });
169
+ expect((await observer.callJoined('late')).code).toBe(JsonRpc.CONNECTION_CLOSED);
170
+ });
171
+
172
+ it('falls back to HTTP while no connection can be made, where calls have no connection', async () => {
173
+ const transport = new WebSocketTransport({ url: async () => `${wsUrl}-missing`, fallback: http(), connectTimeout: 1000 });
174
+ const proxy = chat(transport);
175
+ expect(await proxy.viaWebSocket()).toBe(false);
176
+ expect(transport.connected).toBe(false);
177
+ const error = await proxy.join().catch(e => e) as RpcError;
178
+ expect([error.status, error.message]).toEqual([400, 'This call did not come over a WebSocket connection, so the server cannot call the client back.']);
179
+ });
180
+
181
+ it('closes connections whose messages are too large with 1009', async () => {
182
+ const code = await new Promise<number>(resolve => {
183
+ const socket = new WebSocket(wsUrl);
184
+ socket.onopen = () => socket.send('x'.repeat(70000));
185
+ socket.onclose = event => resolve(event.code);
186
+ });
187
+ expect(code).toBe(1009);
188
+ });
189
+
190
+ it('knows the Bun versions whose node:http answers upgrades', () => {
191
+ expect(WebSocketConnection.runtimeSupported(null)).toBe(true);
192
+ expect(WebSocketConnection.runtimeSupported('1.3.11')).toBe(false);
193
+ expect(WebSocketConnection.runtimeSupported('1.4.0')).toBe(true);
194
+ expect(WebSocketConnection.runtimeSupported('2.0.1')).toBe(true);
195
+ });
196
+ });
@@ -0,0 +1,2 @@
1
+ export * from './rpc-invoker';
2
+ export * from './rpc-handler-adapter';
@@ -0,0 +1,60 @@
1
+ import { Autowired, Component, Value } from '@celljs/core';
2
+ import { HttpHeaders, MediaType } from '@celljs/http';
3
+ import { PathResolver } from '@celljs/web';
4
+ import { Context, HandlerAdapter } from '@celljs/web/lib/node';
5
+ import { RPC_PATH } from '../../common';
6
+ import { RpcInvoker } from './rpc-invoker';
7
+
8
+ export const RPC_HANDLER_ADAPTER_PRIORITY = 1000;
9
+
10
+ /** `POST /<rpc.path>/<service>` with a JSON-RPC request or batch. */
11
+ @Component(HandlerAdapter)
12
+ export class RpcHandlerAdapter implements HandlerAdapter {
13
+ readonly priority = RPC_HANDLER_ADAPTER_PRIORITY;
14
+
15
+ @Autowired(RpcInvoker)
16
+ protected readonly invoker: RpcInvoker;
17
+
18
+ @Autowired(PathResolver)
19
+ protected readonly pathResolver: PathResolver;
20
+
21
+ @Value(RPC_PATH)
22
+ protected readonly rpcPath: string;
23
+
24
+ protected prefix?: string;
25
+
26
+ async canHandle(): Promise<boolean> {
27
+ const service = await this.service();
28
+ return service !== undefined && this.invoker.has(service);
29
+ }
30
+
31
+ async handle(): Promise<void> {
32
+ const response = Context.getResponse();
33
+ const result = await this.invoker.invoke((await this.service())!, Context.getRequest().body);
34
+ response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8);
35
+ if (result === undefined) {
36
+ response.statusCode = 204;
37
+ response.body = '';
38
+ } else {
39
+ response.statusCode = 200;
40
+ response.body = JSON.stringify(result);
41
+ }
42
+ }
43
+
44
+ protected async service(): Promise<string | undefined> {
45
+ const request = Context.getRequest();
46
+ if (request.method !== 'POST') {
47
+ return undefined;
48
+ }
49
+ this.prefix ??= `${(await this.pathResolver.resolve(this.rpcPath)).replace(/\/$/, '')}/`;
50
+ const path = request.path;
51
+ if (!path.startsWith(this.prefix) || path.length === this.prefix.length) {
52
+ return undefined;
53
+ }
54
+ try {
55
+ return decodeURIComponent(path.slice(this.prefix.length));
56
+ } catch {
57
+ return undefined;
58
+ }
59
+ }
60
+ }
@@ -0,0 +1,104 @@
1
+ import { ApplicationError, Autowired, Component, Logger, Optional } from '@celljs/core';
2
+ import { PipeManager } from '@celljs/web';
3
+ import { ErrorMessageResolver } from '@celljs/web/lib/node';
4
+ import { JsonRpc, RPC_SERVICE, RpcMethodUtil, RpcServiceMetadata, ConverterUtil } from '../../common';
5
+
6
+ export const RpcInvoker = Symbol('RpcInvoker');
7
+
8
+ /** Runs JSON-RPC requests on the `@Rpc` services: one request, a batch, or notifications. */
9
+ export interface RpcInvoker {
10
+ has(service: string): boolean;
11
+ /** The response (or responses of a batch); undefined when every request was a notification. */
12
+ invoke(service: string, body: unknown): Promise<JsonRpc.Response | JsonRpc.Response[] | undefined>;
13
+ }
14
+
15
+ @Component(RpcInvoker)
16
+ export class RpcInvokerImpl implements RpcInvoker {
17
+
18
+ @Autowired(RPC_SERVICE) @Optional()
19
+ protected readonly metadata: RpcServiceMetadata[] = [];
20
+
21
+ @Autowired(PipeManager)
22
+ protected readonly pipeManager: PipeManager;
23
+
24
+ @Autowired(ErrorMessageResolver)
25
+ protected readonly errorMessageResolver: ErrorMessageResolver;
26
+
27
+ @Autowired(Logger)
28
+ protected readonly logger: Logger;
29
+
30
+ protected services?: Map<string, RpcServiceMetadata>;
31
+
32
+ has(service: string): boolean {
33
+ return this.byPath().has(service);
34
+ }
35
+
36
+ async invoke(service: string, body: unknown): Promise<JsonRpc.Response | JsonRpc.Response[] | undefined> {
37
+ if (Array.isArray(body)) {
38
+ if (body.length === 0) {
39
+ return JsonRpc.error(null, JsonRpc.INVALID_REQUEST, 'An empty batch.');
40
+ }
41
+ const responses = (await Promise.all(body.map(message => this.invokeOne(service, message)))).filter(r => r !== undefined);
42
+ return responses.length ? responses : undefined;
43
+ }
44
+ return this.invokeOne(service, body);
45
+ }
46
+
47
+ protected byPath(): Map<string, RpcServiceMetadata> {
48
+ this.services ??= new Map(this.metadata.map(m => [m.path, m]));
49
+ return this.services;
50
+ }
51
+
52
+ protected async invokeOne(service: string, message: unknown): Promise<JsonRpc.Response | undefined> {
53
+ if (!JsonRpc.isRequest(message)) {
54
+ const id = typeof message === 'object' && message !== null && 'id' in message ? (message as { id: JsonRpc.Id }).id : null;
55
+ return JsonRpc.error(id ?? null, JsonRpc.INVALID_REQUEST, 'Not a JSON-RPC 2.0 request: { "jsonrpc": "2.0", "id": 1, "method": "name", "params": [] }.');
56
+ }
57
+ const { id, method, params = [] } = message;
58
+ const metadata = this.byPath().get(service);
59
+ const target = metadata?.get() as Record<string, (...args: unknown[]) => unknown> | undefined;
60
+ if (!target || !RpcMethodUtil.callable(target, method)) {
61
+ return id === undefined ? undefined : JsonRpc.error(id, JsonRpc.METHOD_NOT_FOUND, `${service} has no method ${method}.`);
62
+ }
63
+ const debug = this.logger.isEnabled('debug');
64
+ const start = debug ? Date.now() : 0;
65
+ try {
66
+ await this.pipeManager.apply({ target: target as any, method }, params);
67
+ const result = await target[method](...params);
68
+ return id === undefined ? undefined : JsonRpc.result(id, result);
69
+ } catch (error) {
70
+ return id === undefined ? undefined : JsonRpc.error(id, ...this.toError(metadata!, method, error));
71
+ } finally {
72
+ if (debug) {
73
+ this.logger.debug(`rpc ${service}.${method} [${Date.now() - start}ms]`);
74
+ }
75
+ }
76
+ }
77
+
78
+ /**
79
+ * An `ApplicationError` keeps its code, message and data. Other errors answer like HTTP errors do
80
+ * (`ErrorMessageResolver`): the message of a 4xx `HttpError`, the status text of an internal error
81
+ * in production, which is logged. The stack never leaves the server.
82
+ */
83
+ protected toError(metadata: RpcServiceMetadata, method: string, error: unknown): [number, string, unknown] {
84
+ const service = metadata.path;
85
+ const own = ConverterUtil.getErrorConverters(metadata.id);
86
+ for (const converter of [...ConverterUtil.getGlobalErrorConverters(), ...(own ? [own] : [])]) {
87
+ const converted = converter.serialize(error);
88
+ if (converted) {
89
+ return [converted.code, converted.message, converted.data];
90
+ }
91
+ }
92
+ if (ApplicationError.is(error as object)) {
93
+ const application = error as ApplicationError<number, unknown>;
94
+ return [application.code, application.message, { kind: 'application', data: application.data }];
95
+ }
96
+ const { status, message } = this.errorMessageResolver.resolve(error);
97
+ if (status >= 500) {
98
+ this.logger.error(error instanceof Error ? error : `rpc ${service}.${method} failed: ${String(error)}`);
99
+ } else {
100
+ this.logger.debug(`rpc ${service}.${method} refused: ${message}`);
101
+ }
102
+ return [JsonRpc.SERVER_ERROR, message, { status }];
103
+ }
104
+ }