@workerstack/clients 1.0.0-rc.28 → 1.0.0-rc.30

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 (368) hide show
  1. package/README.md +403 -21
  2. package/assets/installers/examples/github.config.ts +17 -19
  3. package/assets/installers/examples/goreleaser.config.ts +16 -18
  4. package/assets/installers/examples/raw.config.ts +13 -15
  5. package/bin/clients.js +87 -66
  6. package/bin/installgen.js +19 -10
  7. package/dist/cli.d.ts +4 -4
  8. package/dist/cli.js +18 -12
  9. package/dist/emit/cli/channels.d.ts +2 -2
  10. package/dist/emit/cli/channels.js +18 -13
  11. package/dist/emit/cli/commands.d.ts +1 -1
  12. package/dist/emit/cli/commands.js +39 -13
  13. package/dist/emit/cli/discovery.d.ts +0 -6
  14. package/dist/emit/cli/discovery.js +9 -7
  15. package/dist/emit/cli/flags.d.ts +1 -3
  16. package/dist/emit/cli/flags.js +18 -8
  17. package/dist/emit/cli/install.d.ts +0 -8
  18. package/dist/emit/cli/install.js +3 -3
  19. package/dist/emit/cli/layout.d.ts +1 -1
  20. package/dist/emit/cli/layout.js +13 -10
  21. package/dist/emit/cli/module.d.ts +6 -6
  22. package/dist/emit/cli/module.js +10 -10
  23. package/dist/emit/cli/release.d.ts +0 -11
  24. package/dist/emit/cli/release.js +4 -4
  25. package/dist/emit/cli/skills.js +8 -4
  26. package/dist/emit/csharp/errors.js +4 -4
  27. package/dist/emit/csharp/json.js +8 -8
  28. package/dist/emit/csharp/realtime.d.ts +1 -8
  29. package/dist/emit/csharp/realtime.js +26 -26
  30. package/dist/emit/csharp/sdk-answer.d.ts +10 -2
  31. package/dist/emit/csharp/sdk-answer.js +4 -4
  32. package/dist/emit/csharp/sdk-body.js +8 -6
  33. package/dist/emit/csharp/sdk-client.d.ts +3 -3
  34. package/dist/emit/csharp/sdk-client.js +2 -2
  35. package/dist/emit/csharp/sdk-csproj.d.ts +7 -9
  36. package/dist/emit/csharp/sdk-csproj.js +10 -10
  37. package/dist/emit/csharp/sdk-doc.js +1 -1
  38. package/dist/emit/csharp/sdk-method.d.ts +0 -1
  39. package/dist/emit/csharp/sdk-method.js +19 -8
  40. package/dist/emit/csharp/sdk-plan.js +0 -1
  41. package/dist/emit/csharp/sdk.js +3 -3
  42. package/dist/emit/csharp/sse.d.ts +0 -13
  43. package/dist/emit/csharp/sse.js +92 -11
  44. package/dist/emit/csharp/transport.js +9 -9
  45. package/dist/emit/csharp/types-enum.js +3 -1
  46. package/dist/emit/csharp/types-messages.d.ts +47 -0
  47. package/dist/emit/csharp/types-messages.js +172 -0
  48. package/dist/emit/csharp/types-names.js +13 -14
  49. package/dist/emit/csharp/types-record.js +3 -3
  50. package/dist/emit/csharp/types-union.d.ts +1 -1
  51. package/dist/emit/csharp/types.d.ts +0 -1
  52. package/dist/emit/csharp/types.js +3 -3
  53. package/dist/emit/csharp/ws.d.ts +0 -15
  54. package/dist/emit/csharp/ws.js +26 -5
  55. package/dist/emit/go/errors.js +1 -1
  56. package/dist/emit/go/http.js +2 -2
  57. package/dist/emit/go/module-path.js +2 -2
  58. package/dist/emit/go/sdk-answer.d.ts +24 -1
  59. package/dist/emit/go/sdk-answer.js +1 -1
  60. package/dist/emit/go/sdk-body.js +11 -7
  61. package/dist/emit/go/sdk-client.js +1 -1
  62. package/dist/emit/go/sdk-method.d.ts +3 -0
  63. package/dist/emit/go/sdk-method.js +18 -12
  64. package/dist/emit/go/sdk-mirror.js +2 -2
  65. package/dist/emit/go/sdk-opts.d.ts +0 -2
  66. package/dist/emit/go/sdk-opts.js +3 -3
  67. package/dist/emit/go/sdk.d.ts +1 -1
  68. package/dist/emit/go/sdk.js +9 -9
  69. package/dist/emit/go/sse.d.ts +2 -10
  70. package/dist/emit/go/sse.js +88 -13
  71. package/dist/emit/go/types-names.js +5 -0
  72. package/dist/emit/go/types-struct.d.ts +2 -1
  73. package/dist/emit/go/types-struct.js +1 -1
  74. package/dist/emit/go/types-union.d.ts +3 -2
  75. package/dist/emit/go/types-union.js +2 -0
  76. package/dist/emit/go/types.d.ts +6 -0
  77. package/dist/emit/go/types.js +20 -9
  78. package/dist/emit/go/ws.d.ts +4 -11
  79. package/dist/emit/go/ws.js +215 -59
  80. package/dist/emit/java/gradle.d.ts +7 -9
  81. package/dist/emit/java/gradle.js +8 -8
  82. package/dist/emit/java/json.d.ts +3 -0
  83. package/dist/emit/java/json.js +1 -1
  84. package/dist/emit/java/layout-ast.d.ts +4 -1
  85. package/dist/emit/java/layout-ast.js +1 -1
  86. package/dist/emit/java/layout-decl.js +5 -4
  87. package/dist/emit/java/layout-doc.js +13 -7
  88. package/dist/emit/java/layout-dot.js +1 -1
  89. package/dist/emit/java/layout-strings.js +4 -5
  90. package/dist/emit/java/layout-types.js +7 -5
  91. package/dist/emit/java/layout-visitor.js +4 -3
  92. package/dist/emit/java/layout.js +5 -4
  93. package/dist/emit/java/models-names.d.ts +2 -0
  94. package/dist/emit/java/models-names.js +6 -4
  95. package/dist/emit/java/models-record.d.ts +0 -1
  96. package/dist/emit/java/models-record.js +3 -3
  97. package/dist/emit/java/models-union.d.ts +13 -2
  98. package/dist/emit/java/models-union.js +12 -6
  99. package/dist/emit/java/models.d.ts +5 -1
  100. package/dist/emit/java/models.js +44 -20
  101. package/dist/emit/java/realtime.d.ts +34 -26
  102. package/dist/emit/java/realtime.js +45 -10
  103. package/dist/emit/java/sdk-client.d.ts +6 -6
  104. package/dist/emit/java/sdk-client.js +1 -1
  105. package/dist/emit/java/sdk-decl.js +2 -2
  106. package/dist/emit/java/sdk-errors.js +1 -1
  107. package/dist/emit/java/sdk-headers.js +2 -2
  108. package/dist/emit/java/sdk-mirror.js +7 -6
  109. package/dist/emit/java/sdk-models.d.ts +1 -1
  110. package/dist/emit/java/sdk-models.js +7 -7
  111. package/dist/emit/java/sdk-op.d.ts +1 -10
  112. package/dist/emit/java/sdk-op.js +9 -9
  113. package/dist/emit/java/sdk-params.d.ts +5 -5
  114. package/dist/emit/java/sdk-params.js +3 -2
  115. package/dist/emit/java/sdk-plan.js +0 -1
  116. package/dist/emit/java/sdk.d.ts +1 -1
  117. package/dist/emit/java/sdk.js +14 -13
  118. package/dist/emit/java/sse.d.ts +12 -13
  119. package/dist/emit/java/sse.js +105 -6
  120. package/dist/emit/java/ws.d.ts +48 -9
  121. package/dist/emit/java/ws.js +88 -4
  122. package/dist/emit/mcp/annotations.js +8 -4
  123. package/dist/emit/mcp/files.js +9 -9
  124. package/dist/emit/mcp/mounted.js +2 -2
  125. package/dist/emit/mcp/output-schema.d.ts +4 -2
  126. package/dist/emit/mcp/output-schema.js +58 -14
  127. package/dist/emit/mcp/registry.d.ts +0 -2
  128. package/dist/emit/mcp/registry.js +5 -4
  129. package/dist/emit/mcp/runtime.js +2 -2
  130. package/dist/emit/mcp/schema.js +22 -11
  131. package/dist/emit/mcp/server.d.ts +7 -7
  132. package/dist/emit/mcp/server.js +7 -6
  133. package/dist/emit/mcp/tools.js +7 -6
  134. package/dist/emit/python/errors.js +3 -3
  135. package/dist/emit/python/realtime.d.ts +9 -6
  136. package/dist/emit/python/realtime.js +22 -20
  137. package/dist/emit/python/sdk-answer.d.ts +8 -8
  138. package/dist/emit/python/sdk-answer.js +2 -2
  139. package/dist/emit/python/sdk-body.js +4 -5
  140. package/dist/emit/python/sdk-client.js +5 -5
  141. package/dist/emit/python/sdk-doc.js +2 -2
  142. package/dist/emit/python/sdk-method.d.ts +1 -1
  143. package/dist/emit/python/sdk-method.js +38 -11
  144. package/dist/emit/python/sdk-plan.js +0 -1
  145. package/dist/emit/python/sdk-pyproject.d.ts +0 -2
  146. package/dist/emit/python/sdk-pyproject.js +8 -8
  147. package/dist/emit/python/sdk.d.ts +1 -1
  148. package/dist/emit/python/sdk.js +28 -8
  149. package/dist/emit/python/sse.d.ts +0 -7
  150. package/dist/emit/python/sse.js +36 -6
  151. package/dist/emit/python/transport.js +4 -4
  152. package/dist/emit/python/types-dict.d.ts +2 -2
  153. package/dist/emit/python/types-dict.js +1 -1
  154. package/dist/emit/python/types-names.js +2 -2
  155. package/dist/emit/python/types-union.js +1 -1
  156. package/dist/emit/python/types.d.ts +7 -0
  157. package/dist/emit/python/types.js +23 -6
  158. package/dist/emit/python/ws.d.ts +21 -10
  159. package/dist/emit/python/ws.js +69 -3
  160. package/dist/emit/rust/errors.js +3 -3
  161. package/dist/emit/rust/http.js +4 -4
  162. package/dist/emit/rust/realtime.d.ts +7 -5
  163. package/dist/emit/rust/realtime.js +15 -18
  164. package/dist/emit/rust/sdk-body.js +8 -5
  165. package/dist/emit/rust/sdk-cargo.d.ts +16 -18
  166. package/dist/emit/rust/sdk-cargo.js +12 -12
  167. package/dist/emit/rust/sdk-client.d.ts +1 -1
  168. package/dist/emit/rust/sdk-client.js +3 -3
  169. package/dist/emit/rust/sdk-method.js +3 -3
  170. package/dist/emit/rust/sdk-opts.d.ts +2 -1
  171. package/dist/emit/rust/sdk-opts.js +2 -2
  172. package/dist/emit/rust/sdk-plan.js +0 -1
  173. package/dist/emit/rust/sdk.d.ts +1 -1
  174. package/dist/emit/rust/sdk.js +5 -5
  175. package/dist/emit/rust/sse.d.ts +11 -12
  176. package/dist/emit/rust/sse.js +54 -8
  177. package/dist/emit/rust/types-names.js +3 -3
  178. package/dist/emit/rust/types-struct.js +1 -1
  179. package/dist/emit/rust/types-union.d.ts +10 -2
  180. package/dist/emit/rust/types-union.js +4 -0
  181. package/dist/emit/rust/types.d.ts +9 -0
  182. package/dist/emit/rust/types.js +20 -12
  183. package/dist/emit/rust/ws.d.ts +22 -15
  184. package/dist/emit/rust/ws.js +60 -10
  185. package/dist/emit/shared/escape.js +17 -17
  186. package/dist/emit/shared/format.js +1 -1
  187. package/dist/emit/shared/gofmt.js +1 -1
  188. package/dist/emit/shared/lang.js +10 -10
  189. package/dist/emit/shared/literals.d.ts +5 -0
  190. package/dist/emit/shared/literals.js +8 -0
  191. package/dist/emit/shared/metadata.d.ts +0 -6
  192. package/dist/emit/shared/metadata.js +8 -7
  193. package/dist/emit/shared/ruff.js +1 -1
  194. package/dist/emit/shared/rustfmt.js +1 -1
  195. package/dist/emit/shared/type-emitter.js +37 -20
  196. package/dist/emit/shared/unknown-type.constants.d.ts +2 -0
  197. package/dist/emit/shared/unknown-type.constants.js +2 -0
  198. package/dist/emit/ts/http.d.ts +0 -2
  199. package/dist/emit/ts/http.js +4 -4
  200. package/dist/emit/ts/package.d.ts +14 -12
  201. package/dist/emit/ts/package.js +9 -8
  202. package/dist/emit/ts/route-tree.js +2 -2
  203. package/dist/emit/ts/sdk-types-preamble.d.ts +1 -1
  204. package/dist/emit/ts/sdk-types-preamble.js +6 -2
  205. package/dist/emit/ts/sdk-types.js +59 -20
  206. package/dist/emit/ts/sdk.js +6 -6
  207. package/dist/emit/ts/service-map.d.ts +10 -3
  208. package/dist/emit/ts/service-map.js +30 -2
  209. package/dist/emit/ts/tanstack-query.js +6 -6
  210. package/dist/emit/ts/type-gen.js +36 -21
  211. package/dist/emit/ts/webhooks.d.ts +0 -2
  212. package/dist/emit/ts/webhooks.js +3 -3
  213. package/dist/extract/chain.js +5 -4
  214. package/dist/extract/extract.js +5 -5
  215. package/dist/extract/serialize.d.ts +0 -2
  216. package/dist/extract/serialize.js +14 -15
  217. package/dist/extract/walk.js +15 -12
  218. package/dist/gen/args.js +9 -5
  219. package/dist/gen/formatters.js +5 -3
  220. package/dist/gen/shipped.js +2 -2
  221. package/dist/gen/targets.d.ts +2 -4
  222. package/dist/gen/targets.js +8 -4
  223. package/dist/gen/write.js +4 -2
  224. package/dist/index.js +2 -2
  225. package/dist/installers/cli.d.ts +4 -4
  226. package/dist/installers/cli.js +24 -24
  227. package/dist/installers/commands/build.d.ts +4 -4
  228. package/dist/installers/commands/build.js +2 -3
  229. package/dist/installers/commands/check.d.ts +2 -2
  230. package/dist/installers/commands/check.js +11 -10
  231. package/dist/installers/commands/init.d.ts +2 -2
  232. package/dist/installers/commands/init.js +1 -2
  233. package/dist/installers/config/define-config.d.ts +16 -16
  234. package/dist/installers/config/define-config.js +1 -1
  235. package/dist/installers/config/hooks/bun.d.ts +6 -6
  236. package/dist/installers/config/hooks/node.js +1 -1
  237. package/dist/installers/config/load.d.ts +6 -8
  238. package/dist/installers/config/load.js +7 -8
  239. package/dist/installers/config/resolve.d.ts +1 -2
  240. package/dist/installers/config/resolve.js +28 -33
  241. package/dist/installers/config/types.d.ts +6 -6
  242. package/dist/installers/config/types.js +0 -1
  243. package/dist/installers/render/quote.js +3 -5
  244. package/dist/installers/render/render.d.ts +6 -6
  245. package/dist/installers/render/render.js +26 -26
  246. package/dist/installers/ui.d.ts +4 -4
  247. package/dist/installers/ui.js +3 -3
  248. package/dist/ir/build.d.ts +3 -3
  249. package/dist/ir/build.js +12 -5
  250. package/dist/ir/load.js +9 -10
  251. package/dist/ir/model.d.ts +16 -1
  252. package/dist/ir/model.js +0 -1
  253. package/dist/ir/resolve-refs.js +2 -2
  254. package/dist/ir/resource-tree.js +2 -1
  255. package/dist/ir/route-tree-intern.js +1 -1
  256. package/dist/ir/schema.js +3 -3
  257. package/dist/ir/sdk-model.d.ts +25 -1
  258. package/dist/ir/sdk-model.js +38 -8
  259. package/dist/ir/slots.d.ts +1 -1
  260. package/dist/ir/slots.js +22 -11
  261. package/dist/ir/streams.d.ts +16 -0
  262. package/dist/ir/streams.js +40 -0
  263. package/dist/release/bootstrap.d.ts +3 -3
  264. package/dist/release/bootstrap.js +7 -7
  265. package/dist/release/bump-args.js +4 -4
  266. package/dist/release/bump-command.d.ts +1 -1
  267. package/dist/release/bump-command.js +9 -10
  268. package/dist/release/bump.d.ts +5 -4
  269. package/dist/release/bump.js +2 -2
  270. package/dist/release/cli.d.ts +4 -4
  271. package/dist/release/cli.js +4 -4
  272. package/dist/release/codegen.js +1 -1
  273. package/dist/release/digest.js +5 -7
  274. package/dist/release/git.js +5 -8
  275. package/dist/release/load.js +3 -3
  276. package/dist/release/manifest.js +9 -10
  277. package/dist/release/oasdiff.d.ts +10 -15
  278. package/dist/release/oasdiff.js +5 -6
  279. package/dist/release/registries.d.ts +0 -11
  280. package/dist/release/registries.js +17 -17
  281. package/dist/release/release-state.d.ts +16 -13
  282. package/dist/release/release-workflow.js +5 -7
  283. package/dist/release/repo-settings.d.ts +2 -1
  284. package/dist/release/spec-gate.d.ts +0 -2
  285. package/dist/release/spec-gate.js +6 -10
  286. package/dist/release/sync-command.d.ts +2 -2
  287. package/dist/release/sync-command.js +1 -1
  288. package/dist/release/sync-tree.js +9 -13
  289. package/dist/release/sync.d.ts +6 -6
  290. package/dist/release/sync.js +12 -13
  291. package/dist/release/types.d.ts +22 -22
  292. package/dist/release/types.js +0 -1
  293. package/dist/release/version-files.d.ts +3 -4
  294. package/dist/release/version-files.js +4 -5
  295. package/dist/runtime/.oxfmtrc.jsonc +8 -0
  296. package/dist/runtime/cli/socket.go +107 -13
  297. package/dist/runtime/cli/stream.go +18 -11
  298. package/dist/runtime/csharp/Adapters.cs +12 -11
  299. package/dist/runtime/csharp/Events.cs +22 -17
  300. package/dist/runtime/csharp/Realtime.cs +50 -23
  301. package/dist/runtime/csharp/RealtimeLoop.cs +1 -1
  302. package/dist/runtime/csharp/TransportSse.cs +3 -3
  303. package/dist/runtime/csharp/Ws.cs +1 -1
  304. package/dist/runtime/csharp/WsDial.cs +19 -1
  305. package/dist/runtime/csharp/WsTyped.cs +109 -0
  306. package/dist/runtime/go/realtime.go +125 -41
  307. package/dist/runtime/go/realtime_loop.go +21 -18
  308. package/dist/runtime/go/result.go +2 -1
  309. package/dist/runtime/go/sse.go +11 -0
  310. package/dist/runtime/go/stream.go +29 -13
  311. package/dist/runtime/go/transport.go +15 -21
  312. package/dist/runtime/go/transport_longpoll.go +3 -4
  313. package/dist/runtime/go/transport_sse.go +6 -6
  314. package/dist/runtime/go/ws.go +157 -61
  315. package/dist/runtime/java/EventStream.java +47 -29
  316. package/dist/runtime/java/Exchange.java +5 -5
  317. package/dist/runtime/java/Flight.java +3 -3
  318. package/dist/runtime/java/Realtime.java +45 -11
  319. package/dist/runtime/java/ResumableConnection.java +77 -32
  320. package/dist/runtime/java/Socket.java +8 -4
  321. package/dist/runtime/java/SseAdapter.java +1 -1
  322. package/dist/runtime/java/TypedWebSocket.java +81 -24
  323. package/dist/runtime/java/WsAdapter.java +4 -2
  324. package/dist/runtime/java/WsDial.java +12 -5
  325. package/dist/runtime/mcp/files.ts +1 -1
  326. package/dist/runtime/mcp/http.ts +6 -2
  327. package/dist/runtime/mcp/listen.ts +1 -1
  328. package/dist/runtime/mcp/mount.ts +2 -2
  329. package/dist/runtime/mcp/protocol.ts +1 -1
  330. package/dist/runtime/python/events.py +25 -11
  331. package/dist/runtime/python/operation.py +6 -1
  332. package/dist/runtime/python/realtime.py +47 -33
  333. package/dist/runtime/python/send_async.py +1 -0
  334. package/dist/runtime/python/transport_sse.py +2 -2
  335. package/dist/runtime/python/transport_ws.py +1 -1
  336. package/dist/runtime/python/ws.py +100 -39
  337. package/dist/runtime/rust/events.rs +64 -41
  338. package/dist/runtime/rust/realtime.rs +80 -34
  339. package/dist/runtime/rust/realtime_loop.rs +37 -12
  340. package/dist/runtime/rust/sse.rs +3 -2
  341. package/dist/runtime/rust/transport_sse.rs +1 -1
  342. package/dist/runtime/rust/transport_ws.rs +3 -2
  343. package/dist/runtime/rust/ws.rs +122 -50
  344. package/dist/runtime/ts/realtime-connection.ts +22 -0
  345. package/dist/runtime/ts/realtime-transports.ts +13 -4
  346. package/dist/runtime/ts/realtime.ts +27 -3
  347. package/dist/runtime/ts/sdk-realtime.ts +1 -1
  348. package/dist/runtime/ts/sdk-sse.ts +31 -14
  349. package/dist/runtime/ts/sdk-ws.ts +2 -1
  350. package/dist/runtime/ts/sdk.ts +9 -2
  351. package/dist/runtime/ts/sse.ts +8 -0
  352. package/dist/runtime/ts/ws.ts +88 -50
  353. package/dist/runtime/ts-tanstack-query/query.ts +0 -2
  354. package/package.json +12 -40
  355. package/dist/emit/cli/index.d.ts +0 -1
  356. package/dist/emit/cli/index.js +0 -1
  357. package/dist/emit/csharp/index.d.ts +0 -1
  358. package/dist/emit/csharp/index.js +0 -1
  359. package/dist/emit/go/index.d.ts +0 -1
  360. package/dist/emit/go/index.js +0 -1
  361. package/dist/emit/java/index.d.ts +0 -2
  362. package/dist/emit/java/index.js +0 -2
  363. package/dist/emit/mcp/index.d.ts +0 -3
  364. package/dist/emit/mcp/index.js +0 -3
  365. package/dist/emit/python/index.d.ts +0 -1
  366. package/dist/emit/python/index.js +0 -1
  367. package/dist/emit/rust/index.d.ts +0 -1
  368. package/dist/emit/rust/index.js +0 -1
@@ -4,10 +4,11 @@ long-poll) that reconnects after a drop and resumes past the last message it del
4
4
 
5
5
  import asyncio
6
6
  import contextlib
7
+ import dataclasses
7
8
  import random
8
- from collections.abc import Sequence
9
+ from collections.abc import Callable, Sequence
9
10
  from enum import StrEnum
10
- from typing import Generic, Self, TypeVar, Unpack, cast
11
+ from typing import Any, Generic, Literal, Self, TypeVar, Unpack, cast
11
12
 
12
13
  from .body import dumps
13
14
  from .errors import (
@@ -34,11 +35,13 @@ from .transport import (
34
35
  from .transport_longpoll import LongpollAdapter
35
36
  from .transport_sse import SseAdapter
36
37
  from .transport_ws import WsAdapter
37
- from .ws import AsyncWsTransport
38
+ from .ws import AsyncWsTransport, Listeners
38
39
 
39
40
  __all__ = ["ConnectionState", "ResumableConnection"]
40
41
 
41
42
  T = TypeVar("T")
43
+ Out = TypeVar("Out")
44
+ In = TypeVar("In")
42
45
 
43
46
  JITTER = random.SystemRandom()
44
47
 
@@ -58,20 +61,27 @@ class ConnectionState(StrEnum):
58
61
  DISCONNECTED = "disconnected"
59
62
 
60
63
 
61
- class ResumableConnection(Generic[T]):
62
- """``recv`` (or ``async for``) reads the next message, JSON decoded when it is JSON. After a drop it
64
+ class ResumableConnection(Listeners, Generic[Out, In]):
65
+ """``Out`` what it reads and ``In`` what it sends: ``recv`` (or ``async for``) reads the next message,
66
+ JSON decoded when it is JSON, and hands it to ``on("message")`` and, when the operation's messages are
67
+ keyed, to ``on(value)`` too. An operation that declares its messages sends every value as JSON, and a
68
+ message that is no JSON raises ``DecodeError`` from ``recv`` and the connection reads on. After a drop it
63
69
  reopens the chain in order, backing off from the delay (an SSE ``retry``, else ``reconnect_delay_ms``;
64
70
  doubling to at most 30 s, with jitter) for up to ``max_reconnect_attempts`` in a row; giving up raises
65
71
  the last failure once, and ``recv`` then answers ``None``, as it does once closed or after the call's
66
72
  ``cancel``. A ``recv`` the caller's task cancels raises ``CancelledError`` and leaves it reconnecting:
67
73
  the next ``recv`` resumes from the cursor."""
68
74
 
75
+ taken = frozenset(("message",))
76
+
69
77
  def __init__(
70
78
  self,
71
79
  url: str,
72
80
  adapters: Sequence[TransportAdapter],
73
81
  opts: TransportOpts | None = None,
82
+ op: Operation[Any] | None = None,
74
83
  ) -> None:
84
+ super().__init__(op)
75
85
  self.url = url
76
86
  self.adapters = tuple(adapters)
77
87
  self.opts = opts or TransportOpts()
@@ -82,9 +92,13 @@ class ResumableConnection(Generic[T]):
82
92
  self.retry: int | None = None
83
93
  self.failure: Exception = APIConnectionError("the connection ended")
84
94
  self.cancel: Cancel = None
85
- self.shape: str | None = None
95
+ self.shape = None if op is None else op.shape
86
96
  self.closing = asyncio.Event()
87
97
 
98
+ def on(self, event: Literal["message"], handler: Callable[[Out], None]) -> None:
99
+ """Calls ``handler`` with each message as ``recv`` reads it."""
100
+ self.listen(event, handler)
101
+
88
102
  @property
89
103
  def proven_transport(self) -> TransportKind | None:
90
104
  """The transport that last opened; ``None`` after a drop."""
@@ -127,7 +141,7 @@ class ResumableConnection(Generic[T]):
127
141
  self.state = ConnectionState.DISCONNECTED
128
142
  raise self.failure
129
143
 
130
- async def recv(self) -> T | None:
144
+ async def recv(self) -> Out | None:
131
145
  """The next message; ``None`` once closed, given up or cancelled."""
132
146
  try:
133
147
  return await raced(raced(self.read(), self.closing), self.cancel)
@@ -139,7 +153,7 @@ class ResumableConnection(Generic[T]):
139
153
  await self.drop(self.conn, self.failure)
140
154
  raise
141
155
 
142
- async def read(self) -> T | None:
156
+ async def read(self) -> Out | None:
143
157
  while self.state is not ConnectionState.DISCONNECTED:
144
158
  conn = self.conn
145
159
  if conn is None:
@@ -163,34 +177,42 @@ class ResumableConnection(Generic[T]):
163
177
  with contextlib.suppress(Exception):
164
178
  await conn.close()
165
179
 
166
- def deliver(self, message: TransportMessage) -> T:
167
- """``message`` as ``T``, the cursor advanced past it and an SSE ``retry`` kept."""
180
+ def deliver(self, message: TransportMessage) -> Out:
181
+ """``message`` as ``Out``, the cursor advanced past it, an SSE ``retry`` kept, and handed to ``on``."""
168
182
  self.attempts = 0
169
183
  if message.retry is not None:
170
184
  self.retry = message.retry
171
185
  try:
172
186
  value = loads(message.text.encode())
173
- except ValueError:
187
+ except ValueError as error:
188
+ if self.decode:
189
+ advance(self.opts, message.id, message.text)
190
+ text = f"WebSocket frame is not valid JSON: {error}"
191
+ raise DecodeError(text) from None
174
192
  value = message.text
175
193
  advance(self.opts, message.id, value)
176
194
  if not shaped(value, self.shape):
177
195
  raise DecodeError(f"a message is not a JSON {self.shape}")
178
- return cast("T", value)
196
+ self.hear(value)
197
+ return cast("Out", value)
179
198
 
180
199
  def __aiter__(self) -> Self:
181
200
  return self
182
201
 
183
- async def __anext__(self) -> T:
202
+ async def __anext__(self) -> Out:
184
203
  message = await self.recv()
185
204
  if message is None and self.state is ConnectionState.DISCONNECTED:
186
205
  raise StopAsyncIteration
187
- return cast("T", message)
206
+ return cast("Out", message)
188
207
 
189
- async def send(self, data: object) -> None:
190
- """Sends text as it is, anything else as JSON (an SSE or long-poll connection POSTs it)."""
208
+ async def send(self, data: In) -> None:
209
+ """Sends text as it is, anything else as JSON (an SSE or long-poll connection POSTs it); every value
210
+ as JSON for a connection whose operation declares what it receives."""
191
211
  if self.conn is None:
192
212
  raise APIConnectionError("the connection is not open")
193
- await self.conn.send(data if isinstance(data, str) else dumps(data))
213
+ await self.conn.send(
214
+ data if isinstance(data, str) and not self.encode else dumps(data)
215
+ )
194
216
 
195
217
  async def close(self) -> None:
196
218
  """Closes the open transport and ends a ``recv`` waiting in any task with ``None``."""
@@ -213,32 +235,24 @@ class AsyncRealtimeTransport(AsyncWsTransport):
213
235
  self,
214
236
  op: Operation[T],
215
237
  *,
216
- last_event_id: str | None = None,
217
- reconnect_token: str | None = None,
218
- protocols: Sequence[str] | None = None,
219
- max_reconnect_attempts: int | None = None,
220
- reconnect_delay_ms: int | None = None,
238
+ transport: TransportOpts | None = None,
221
239
  **args: Unpack[CallArgs],
222
- ) -> ResumableConnection[T]:
240
+ ) -> T:
223
241
  x = Exchange(self, op, args, stream=True)
224
242
  x.check()
225
- opts = TransportOpts(
226
- last_event_id,
227
- reconnect_token,
228
- list(protocols or []),
229
- 5 if max_reconnect_attempts is None else max_reconnect_attempts,
230
- 1000 if reconnect_delay_ms is None else reconnect_delay_ms,
231
- )
243
+ # the connection advances its own copy: the caller's value stays as it was
244
+ opts = TransportOpts() if transport is None else dataclasses.replace(transport)
232
245
  dial = Dial(self, op, args, x.options.get("raw"))
233
246
  chain: list[TransportAdapter] = [
234
247
  WsAdapter(dial),
235
248
  SseAdapter(dial),
236
249
  LongpollAdapter(dial),
237
250
  ]
238
- connection = ResumableConnection[T](x.url(), chain, opts)
239
- connection.shape, connection.cancel = op.shape, x.options.get("cancel")
251
+ kind = op.kind or ResumableConnection
252
+ connection: ResumableConnection[Any, Any] = kind(x.url(), chain, opts, op)
253
+ connection.cancel = x.options.get("cancel")
240
254
  try:
241
255
  await raced(asyncio.wait_for(connection.connect(), 30), connection.cancel)
242
256
  except TimeoutError:
243
257
  raise APITimeoutError("no transport opened within 30 s") from None
244
- return connection
258
+ return cast("T", connection)
@@ -75,6 +75,7 @@ class AsyncTransport(ClientCore):
75
75
  live,
76
76
  decode=op.answer == "json",
77
77
  shape=op.shape,
78
+ events=op.events,
78
79
  cancel=x.options.get("cancel"),
79
80
  ),
80
81
  x.raw,
@@ -2,7 +2,7 @@
2
2
  """The SSE adapter: the cursor's id as Last-Event-ID and its token on the query, each event's data a
3
3
  message; a send is a POST."""
4
4
 
5
- from .events import EventStream
5
+ from .events import EventStream, SseEvent
6
6
  from .transport import (
7
7
  Dial,
8
8
  TransportConn,
@@ -15,7 +15,7 @@ __all__ = ["SseAdapter"]
15
15
 
16
16
 
17
17
  class SseConn:
18
- def __init__(self, stream: EventStream[str], dial: Dial) -> None:
18
+ def __init__(self, stream: EventStream[SseEvent[str]], dial: Dial) -> None:
19
19
  self.stream = stream
20
20
  self.dial = dial
21
21
 
@@ -14,7 +14,7 @@ __all__ = ["WsAdapter"]
14
14
 
15
15
 
16
16
  class WsConn:
17
- def __init__(self, socket: TypedWebSocket) -> None:
17
+ def __init__(self, socket: TypedWebSocket[str | bytes, object]) -> None:
18
18
  self.socket = socket
19
19
 
20
20
  async def recv(self) -> TransportMessage | None:
@@ -1,7 +1,8 @@
1
1
  # @generated by clients. DO NOT EDIT.
2
2
  """A WebSocket operation's answer: the open socket, messages both ways, JSON on top. The socket lives in
3
- a task of its own, so any task may use or close it; the call's ``cancel``, ``close`` and a cancelled read
4
- end it. Open it with ``async with`` or call ``close()`` to free its connection; a dropped socket frees it
3
+ a task of its own, so any task may use or close it. A socket whose operation declares its messages sends
4
+ every value as JSON and parses every frame; a frame that is no JSON fires ``on("error")`` and raises from
5
+ ``recv()``, the socket still open. The call's ``cancel``, ``close`` and a cancelled read end it. Open it with ``async with`` or call ``close()`` to free its connection; a dropped socket frees it
5
6
  only when collected. Its dial runs no ``on_request`` or ``on_response`` hook, and a refused handshake's 401 is
6
7
  its error, with no ``on_auth_expired`` refresh."""
7
8
 
@@ -12,7 +13,7 @@ import os
12
13
  import weakref
13
14
  from collections.abc import Callable, Mapping, Sequence
14
15
  from dataclasses import dataclass
15
- from typing import Any, Literal, Self, TypeVar, Unpack
16
+ from typing import Any, Generic, Literal, Self, TypeVar, Unpack, cast, overload
16
17
 
17
18
  import httpx2
18
19
  import wsproto.events
@@ -29,7 +30,9 @@ from .errors import (
29
30
  APIConnectionError,
30
31
  APITimeoutError,
31
32
  CanceledError,
33
+ DecodeError,
32
34
  HttpError,
35
+ loads,
33
36
  status_error,
34
37
  )
35
38
  from .events import Cancel, raced
@@ -46,12 +49,13 @@ __all__ = [
46
49
  ]
47
50
 
48
51
  T = TypeVar("T")
52
+ Out = TypeVar("Out")
53
+ In = TypeVar("In")
49
54
 
50
55
  WS_STATUS_NORMAL_CLOSURE = 1000
51
56
  WS_STATUS_GOING_AWAY = 1001
52
57
  WS_STATUS_PROTOCOL_ERROR = 1002
53
58
 
54
- SocketEvent = Literal["message", "close", "error"]
55
59
 
56
60
  UPGRADE = {
57
61
  "Connection": "Upgrade",
@@ -68,10 +72,44 @@ class WsClose:
68
72
  reason: str
69
73
 
70
74
 
71
- class TypedWebSocket:
72
- """An open socket: ``recv`` (or ``async for``) reads the next message, ``None`` once it ended.
73
- ``closed_by`` is the server's close frame a read ended on; ``subprotocol`` the server's choice. A read
74
- the caller's task cancels ends the socket and raises ``CancelledError``."""
75
+ class Listeners:
76
+ """How an operation's declared messages are framed, and ``on``'s handlers: each message goes to
77
+ ``on("message")``, then, when the messages are keyed, to ``on(value)``, a value ``taken`` names excepted."""
78
+
79
+ taken: frozenset[str]
80
+
81
+ def __init__(self, op: Operation[Any] | None) -> None:
82
+ self.encode = op is not None and op.encode
83
+ self.decode = op is not None and op.decode
84
+ self.dispatch = None if op is None else op.dispatch
85
+ self.handlers: dict[str, list[Callable[[Any], None]]] = {}
86
+
87
+ def listen(self, event: str, handler: Callable[[Any], None]) -> None:
88
+ self.handlers.setdefault(event, []).append(handler)
89
+
90
+ def fire(self, event: str, value: object) -> None:
91
+ for handler in self.handlers.get(event, ()):
92
+ with contextlib.suppress(Exception):
93
+ handler(value)
94
+
95
+ def hear(self, data: object) -> None:
96
+ self.fire("message", data)
97
+ key = (
98
+ data.get(self.dispatch)
99
+ if isinstance(data, dict) and self.dispatch
100
+ else None
101
+ )
102
+ if isinstance(key, str) and key not in self.taken:
103
+ self.fire(key, data)
104
+
105
+
106
+ class TypedWebSocket(Listeners, Generic[Out, In]):
107
+ """An open socket, ``Out`` what it reads and ``In`` what it sends: ``recv`` (or ``async for``) reads the
108
+ next message, ``None`` once it ended. ``closed_by`` is the server's close frame a read ended on;
109
+ ``subprotocol`` the server's choice. A read the caller's task cancels ends the socket and raises
110
+ ``CancelledError``."""
111
+
112
+ taken = frozenset(("message", "close", "error"))
75
113
 
76
114
  def __init__(
77
115
  self,
@@ -79,28 +117,46 @@ class TypedWebSocket:
79
117
  done: asyncio.Event,
80
118
  task: asyncio.Task[None],
81
119
  cancel: Cancel,
120
+ op: Operation[Any] | None = None,
82
121
  ) -> None:
122
+ super().__init__(op)
83
123
  self.session, self.done, self.task, self.cancel = session, done, task, cancel
84
124
  self.subprotocol = session.subprotocol
85
- self.handlers: dict[SocketEvent, list[Callable[[Any], None]]] = {
86
- "message": [],
87
- "close": [],
88
- "error": [],
89
- }
90
125
  self.closed_by: WsClose | None = None
91
126
  self.ended = False
92
127
  weakref.finalize(self, done.set)
93
128
 
94
- def on(self, event: SocketEvent, handler: Callable[[Any], None]) -> None:
95
- """Calls ``handler`` with each message, the ``WsClose`` or the error; the socket's end fires once."""
96
- self.handlers[event].append(handler)
129
+ @overload
130
+ def on(self, event: Literal["message"], handler: Callable[[Out], None]) -> None: ...
97
131
 
98
- def fire(self, event: SocketEvent, value: object) -> None:
99
- for handler in self.handlers[event]:
100
- with contextlib.suppress(Exception):
101
- handler(value)
132
+ @overload
133
+ def on(
134
+ self, event: Literal["close"], handler: Callable[[WsClose], None]
135
+ ) -> None: ...
136
+
137
+ @overload
138
+ def on(
139
+ self, event: Literal["error"], handler: Callable[[HttpError], None]
140
+ ) -> None: ...
102
141
 
103
- async def recv(self) -> str | bytes | None:
142
+ def on(self, event: str, handler: Callable[[Any], None]) -> None:
143
+ """Calls ``handler`` with each message, the ``WsClose`` or the error; the socket's end fires once."""
144
+ self.listen(event, handler)
145
+
146
+ def message(self, frame: str | bytes) -> Out:
147
+ """``frame`` as the reader gets it: as it came, or parsed and dispatched by its key."""
148
+ data: object = frame
149
+ if self.decode:
150
+ try:
151
+ data = loads(frame.encode() if isinstance(frame, str) else frame)
152
+ except ValueError as error:
153
+ failure = DecodeError(f"WebSocket frame is not valid JSON: {error}")
154
+ self.fire("error", failure)
155
+ raise failure from None
156
+ self.hear(data)
157
+ return cast("Out", data)
158
+
159
+ async def recv(self) -> Out | None:
104
160
  while not self.ended:
105
161
  try:
106
162
  event = await raced(self.session.receive(), self.cancel)
@@ -117,11 +173,8 @@ class TypedWebSocket:
117
173
  raise self.failed("the WebSocket failed") from error
118
174
  else:
119
175
  if isinstance(event, wsproto.events.Message):
120
- data = (
121
- event.data if isinstance(event.data, str) else bytes(event.data)
122
- )
123
- self.fire("message", data)
124
- return data
176
+ data = event.data
177
+ return self.message(data if isinstance(data, str) else bytes(data))
125
178
  return None
126
179
 
127
180
  async def disconnected(self, closed: WebSocketDisconnect) -> None:
@@ -150,23 +203,25 @@ class TypedWebSocket:
150
203
  def __aiter__(self) -> Self:
151
204
  return self
152
205
 
153
- async def __anext__(self) -> str | bytes:
206
+ async def __anext__(self) -> Out:
154
207
  message = await self.recv()
155
208
  if message is None:
156
209
  raise StopAsyncIteration
157
210
  return message
158
211
 
159
- async def send(self, data: object) -> None:
160
- """Sends text or bytes as they are, anything else as JSON text."""
212
+ async def send(self, data: In) -> None:
213
+ """Sends text or bytes as they are, anything else as JSON text; every value as JSON text for a socket
214
+ whose operation declares what it receives."""
161
215
  if self.ended:
162
216
  raise APIConnectionError("the WebSocket is closed")
163
217
  try:
164
- if isinstance(data, bytes):
218
+ if isinstance(data, bytes) and not self.encode:
165
219
  await self.session.send_bytes(data)
166
220
  else:
167
- await self.session.send_text(
168
- data if isinstance(data, str) else dumps(data)
221
+ text = (
222
+ data if isinstance(data, str) and not self.encode else dumps(data)
169
223
  )
224
+ await self.session.send_text(text)
170
225
  except (HTTPXWSException, LocalProtocolError) as error:
171
226
  text = f"the WebSocket send failed: {type(error).__name__}"
172
227
  raise APIConnectionError(text) from None
@@ -193,7 +248,8 @@ async def open_socket(
193
248
  x: Exchange,
194
249
  headers: Mapping[str, str],
195
250
  protocols: Sequence[str],
196
- ) -> TypedWebSocket:
251
+ op: Operation[Any] | None = None,
252
+ ) -> TypedWebSocket[Any, Any]:
197
253
  scheme, sep, rest = x.url().partition("://")
198
254
  url = {"http": "ws", "https": "wss"}.get(scheme, scheme) + sep + rest
199
255
  key = base64.b64encode(os.urandom(16)).decode()
@@ -251,7 +307,8 @@ async def open_socket(
251
307
  if isinstance(error, HttpError) or not isinstance(error, Exception):
252
308
  raise
253
309
  raise APIConnectionError("the WebSocket handshake failed") from error
254
- return TypedWebSocket(opened.result(), done, task, x.options.get("cancel"))
310
+ kind = TypedWebSocket if op is None or op.kind is None else op.kind
311
+ return kind(opened.result(), done, task, x.options.get("cancel"), op)
255
312
 
256
313
 
257
314
  class AsyncWsTransport(AsyncTransport):
@@ -262,15 +319,19 @@ class AsyncWsTransport(AsyncTransport):
262
319
  protocols: Sequence[str] | None = None,
263
320
  reconnect_token: str | None = None,
264
321
  **args: Unpack[CallArgs],
265
- ) -> TypedWebSocket:
322
+ ) -> T:
323
+ """The open socket, of the operation's own socket class when it has one."""
266
324
  resume = {"reconnect_token": reconnect_token or None}
267
325
  query = {**(args.get("query") or {}), **resume}
268
326
  x = Exchange(self, op, {**args, "query": query}, stream=True)
269
- return await self.socket(x, protocols)
327
+ return cast("T", await self.socket(x, protocols, op))
270
328
 
271
329
  async def socket(
272
- self, x: Exchange, protocols: Sequence[str] | None
273
- ) -> TypedWebSocket:
330
+ self,
331
+ x: Exchange,
332
+ protocols: Sequence[str] | None,
333
+ op: Operation[Any] | None = None,
334
+ ) -> TypedWebSocket[Any, Any]:
274
335
  x.check()
275
336
  headers = x.request(self.auth.token, False).headers
276
- return await open_socket(self.http, x, headers, protocols or ())
337
+ return await open_socket(self.http, x, headers, protocols or (), op)
@@ -1,6 +1,6 @@
1
1
  // @generated by clients. DO NOT EDIT.
2
- //! An SSE operation's answer: the open event stream, each event's data as the operation declares
3
- //! it (text, or JSON decoded into `T`). An error status at the open fails with its answer, which the
2
+ //! An SSE operation's answer: the open event stream, each event as the operation declares it (its
3
+ //! data as text, as JSON decoded into `T`, or decoded by its name into the operation's event enum). An error status at the open fails with its answer, which the
4
4
  //! call's style settles; a failure once open is the stream's own. No timeout bounds it once open;
5
5
  //! the call's `cancel_on` ends it quietly, and dropping it closes the connection.
6
6
 
@@ -24,24 +24,27 @@ use crate::sse::{SseEvent, SseParser};
24
24
 
25
25
  type Chunks = Pin<Box<dyn Stream<Item = reqwest::Result<Bytes>> + Send>>;
26
26
 
27
+ /// An open: the stream of events `E` and the response it opened with, or the failure.
28
+ type Opened<E> = BoxFuture<Result<(EventStream<E>, RawResponse), Failed>>;
29
+
27
30
  /// The events of an open stream, in order; it ends when the server closes it, after the first
28
31
  /// error it yields (a cap, a transport failure, data that is not `T`), or when the call's
29
32
  /// `cancel_on` fires. Read it with `next().await`, or as a `futures_util::Stream`.
30
- pub struct EventStream<T> {
33
+ pub struct EventStream<E = SseEvent> {
31
34
  chunks: Chunks,
32
35
  parser: SseParser,
33
36
  ready: VecDeque<SseEvent>,
34
37
  failed: Option<Error>,
35
- decode: fn(String) -> Result<T, Error>,
38
+ decode: fn(SseEvent) -> Result<E, Error>,
36
39
  cancel: Option<Signal>,
37
40
  done: bool,
38
41
  /* the id of the last event handed out: a resume from it skips nothing */
39
42
  delivered: String,
40
43
  }
41
44
 
42
- impl<T> EventStream<T> {
45
+ impl<E> EventStream<E> {
43
46
  /// The next event; `None` once the stream ended.
44
- pub async fn next(&mut self) -> Option<Result<SseEvent<T>, Error>> {
47
+ pub async fn next(&mut self) -> Option<Result<E, Error>> {
45
48
  std::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
46
49
  }
47
50
 
@@ -58,25 +61,10 @@ impl<T> EventStream<T> {
58
61
  self.cancel = None;
59
62
  self.chunks = Box::pin(futures_util::stream::empty());
60
63
  }
61
-
62
- fn event(&self, e: SseEvent) -> Result<SseEvent<T>, Error> {
63
- let SseEvent {
64
- data,
65
- event,
66
- id,
67
- retry,
68
- } = e;
69
- Ok(SseEvent {
70
- data: (self.decode)(data)?,
71
- event,
72
- id,
73
- retry,
74
- })
75
- }
76
64
  }
77
65
 
78
- impl<T> Stream for EventStream<T> {
79
- type Item = Result<SseEvent<T>, Error>;
66
+ impl<E> Stream for EventStream<E> {
67
+ type Item = Result<E, Error>;
80
68
 
81
69
  fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
82
70
  loop {
@@ -88,11 +76,11 @@ impl<T> Stream for EventStream<T> {
88
76
  self.end();
89
77
  }
90
78
  if let Some(e) = self.ready.pop_front() {
91
- let event = self.event(e);
92
- if let Ok(delivered) = &event {
93
- self.delivered.clone_from(&delivered.id);
94
- }
95
- if event.is_err() {
79
+ let id = e.id.clone();
80
+ let event = (self.decode)(e);
81
+ if event.is_ok() {
82
+ self.delivered = id;
83
+ } else {
96
84
  /* data that is not the declared type ends the stream: never a silent skip */
97
85
  self.end();
98
86
  }
@@ -120,21 +108,50 @@ impl<T> Stream for EventStream<T> {
120
108
  }
121
109
  }
122
110
 
123
- fn text_data(data: String) -> Result<String, Error> {
124
- Ok(data)
111
+ /// An operation's event enum: one variant per event name it declares, each decoded by its name.
112
+ pub(crate) trait Named: Sized {
113
+ /// `e` as the variant its name selects; an unnamed event is `message`.
114
+ fn named(e: SseEvent) -> Result<Self, Error>;
115
+ }
116
+
117
+ fn text_data(e: SseEvent) -> Result<SseEvent, Error> {
118
+ Ok(e)
119
+ }
120
+
121
+ /// `e` with its data decoded from JSON into `T`.
122
+ fn json_event<T: DeserializeOwned>(e: SseEvent) -> Result<SseEvent<T>, serde_json::Error> {
123
+ let SseEvent {
124
+ data,
125
+ event,
126
+ id,
127
+ retry,
128
+ } = e;
129
+ Ok(SseEvent {
130
+ data: serde_json::from_str(&data)?,
131
+ event,
132
+ id,
133
+ retry,
134
+ })
135
+ }
136
+
137
+ fn json_data<T: DeserializeOwned>(e: SseEvent) -> Result<SseEvent<T>, Error> {
138
+ json_event(e).map_err(Error::decode)
125
139
  }
126
140
 
127
- fn json_data<T: DeserializeOwned>(data: String) -> Result<T, Error> {
128
- serde_json::from_str(&data).map_err(Error::decode)
141
+ /// A named event's data decoded from JSON into `T`; an error names the event.
142
+ #[allow(dead_code)] // an SDK decodes the event names its operations declare
143
+ pub(crate) fn named_data<T: DeserializeOwned>(e: SseEvent) -> Result<SseEvent<T>, Error> {
144
+ let name = e.event.clone();
145
+ json_event(e).map_err(|err| Error::decode(format!("sse event {name:?}: {err}")))
129
146
  }
130
147
 
131
148
  /// Opens the stream of `spec`, its events read by `decode`.
132
- fn opened<T: Send + 'static>(
149
+ fn opened<E: Send + 'static>(
133
150
  inner: Arc<Inner>,
134
151
  mut spec: RequestSpec,
135
152
  ov: Overrides,
136
- decode: fn(String) -> Result<T, Error>,
137
- ) -> BoxFuture<Result<(EventStream<T>, RawResponse), Failed>> {
153
+ decode: fn(SseEvent) -> Result<E, Error>,
154
+ ) -> Opened<E> {
138
155
  Box::pin(async move {
139
156
  spec.accept("text/event-stream");
140
157
  let answer = open(&inner, &mut spec, &ov).await?;
@@ -158,11 +175,7 @@ fn opened<T: Send + 'static>(
158
175
 
159
176
  /// An SSE operation whose events carry text.
160
177
  #[allow(dead_code)] // an SDK opens the event kinds its operations declare
161
- pub(crate) fn text(
162
- inner: Arc<Inner>,
163
- spec: RequestSpec,
164
- ov: Overrides,
165
- ) -> BoxFuture<Result<(EventStream<String>, RawResponse), Failed>> {
178
+ pub(crate) fn text(inner: Arc<Inner>, spec: RequestSpec, ov: Overrides) -> Opened<SseEvent> {
166
179
  opened(inner, spec, ov, text_data)
167
180
  }
168
181
 
@@ -172,6 +185,16 @@ pub(crate) fn json<T: DeserializeOwned + Send + 'static>(
172
185
  inner: Arc<Inner>,
173
186
  spec: RequestSpec,
174
187
  ov: Overrides,
175
- ) -> BoxFuture<Result<(EventStream<T>, RawResponse), Failed>> {
188
+ ) -> Opened<SseEvent<T>> {
176
189
  opened(inner, spec, ov, json_data::<T>)
177
190
  }
191
+
192
+ /// An SSE operation whose events are decoded by their names into the enum `E`.
193
+ #[allow(dead_code)] // an SDK opens the event kinds its operations declare
194
+ pub(crate) fn named<E: Named + Send + 'static>(
195
+ inner: Arc<Inner>,
196
+ spec: RequestSpec,
197
+ ov: Overrides,
198
+ ) -> Opened<E> {
199
+ opened(inner, spec, ov, E::named)
200
+ }