@workerstack/clients 1.0.0-rc.27 → 1.0.0-rc.29

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 (145) hide show
  1. package/README.md +30 -7
  2. package/dist/emit/cli/commands.js +25 -5
  3. package/dist/emit/cli/flags.js +7 -3
  4. package/dist/emit/cli/skills.js +5 -1
  5. package/dist/emit/csharp/realtime.d.ts +1 -8
  6. package/dist/emit/csharp/realtime.js +25 -25
  7. package/dist/emit/csharp/sdk-answer.d.ts +10 -2
  8. package/dist/emit/csharp/sdk-method.js +9 -2
  9. package/dist/emit/csharp/sse.d.ts +0 -11
  10. package/dist/emit/csharp/sse.js +91 -10
  11. package/dist/emit/csharp/transport.js +3 -3
  12. package/dist/emit/csharp/types-messages.d.ts +47 -0
  13. package/dist/emit/csharp/types-messages.js +172 -0
  14. package/dist/emit/csharp/types-names.js +3 -2
  15. package/dist/emit/csharp/ws.d.ts +0 -15
  16. package/dist/emit/csharp/ws.js +26 -5
  17. package/dist/emit/go/sdk-answer.d.ts +24 -1
  18. package/dist/emit/go/sdk-method.d.ts +3 -0
  19. package/dist/emit/go/sdk-method.js +16 -10
  20. package/dist/emit/go/sse.d.ts +2 -10
  21. package/dist/emit/go/sse.js +87 -12
  22. package/dist/emit/go/types-union.d.ts +3 -2
  23. package/dist/emit/go/types-union.js +2 -0
  24. package/dist/emit/go/types.d.ts +6 -0
  25. package/dist/emit/go/types.js +12 -1
  26. package/dist/emit/go/ws.d.ts +4 -11
  27. package/dist/emit/go/ws.js +214 -58
  28. package/dist/emit/java/json.d.ts +3 -0
  29. package/dist/emit/java/layout-ast.d.ts +4 -1
  30. package/dist/emit/java/layout-types.js +1 -1
  31. package/dist/emit/java/models-names.d.ts +2 -0
  32. package/dist/emit/java/models-names.js +1 -0
  33. package/dist/emit/java/models-union.d.ts +12 -1
  34. package/dist/emit/java/models-union.js +11 -5
  35. package/dist/emit/java/models.d.ts +5 -0
  36. package/dist/emit/java/models.js +22 -7
  37. package/dist/emit/java/realtime.d.ts +29 -9
  38. package/dist/emit/java/realtime.js +45 -10
  39. package/dist/emit/java/sdk-mirror.js +6 -5
  40. package/dist/emit/java/sdk-op.js +1 -1
  41. package/dist/emit/java/sse.d.ts +11 -10
  42. package/dist/emit/java/sse.js +104 -5
  43. package/dist/emit/java/ws.d.ts +46 -7
  44. package/dist/emit/java/ws.js +89 -4
  45. package/dist/emit/mcp/output-schema.d.ts +4 -2
  46. package/dist/emit/mcp/output-schema.js +56 -12
  47. package/dist/emit/python/realtime.d.ts +9 -6
  48. package/dist/emit/python/realtime.js +21 -19
  49. package/dist/emit/python/sdk-answer.d.ts +5 -1
  50. package/dist/emit/python/sdk-method.d.ts +1 -1
  51. package/dist/emit/python/sdk-method.js +33 -6
  52. package/dist/emit/python/sdk.js +22 -2
  53. package/dist/emit/python/sse.d.ts +0 -5
  54. package/dist/emit/python/sse.js +35 -5
  55. package/dist/emit/python/types.d.ts +7 -0
  56. package/dist/emit/python/types.js +20 -3
  57. package/dist/emit/python/ws.d.ts +20 -6
  58. package/dist/emit/python/ws.js +67 -1
  59. package/dist/emit/rust/realtime.d.ts +7 -5
  60. package/dist/emit/rust/realtime.js +14 -17
  61. package/dist/emit/rust/sdk-method.js +1 -1
  62. package/dist/emit/rust/sse.d.ts +11 -7
  63. package/dist/emit/rust/sse.js +52 -6
  64. package/dist/emit/rust/types-union.d.ts +9 -1
  65. package/dist/emit/rust/types-union.js +4 -0
  66. package/dist/emit/rust/types.d.ts +9 -0
  67. package/dist/emit/rust/types.js +13 -7
  68. package/dist/emit/rust/ws.d.ts +22 -4
  69. package/dist/emit/rust/ws.js +57 -7
  70. package/dist/emit/ts/route-tree.d.ts +1 -1
  71. package/dist/emit/ts/route-tree.js +0 -11
  72. package/dist/emit/ts/sdk-types-preamble.js +4 -0
  73. package/dist/emit/ts/sdk-types.js +49 -10
  74. package/dist/emit/ts/sdk.js +2 -2
  75. package/dist/emit/ts/service-map.d.ts +8 -2
  76. package/dist/emit/ts/service-map.js +30 -2
  77. package/dist/emit/ts/type-gen.d.ts +4 -3
  78. package/dist/emit/ts/type-gen.js +83 -40
  79. package/dist/extract/chain.d.ts +10 -6
  80. package/dist/extract/chain.js +5 -19
  81. package/dist/extract/extract.d.ts +2 -2
  82. package/dist/extract/extract.js +37 -23
  83. package/dist/extract/walk.d.ts +15 -4
  84. package/dist/extract/walk.js +159 -15
  85. package/dist/ir/build.js +4 -0
  86. package/dist/ir/model.d.ts +16 -0
  87. package/dist/ir/sdk-model.d.ts +25 -1
  88. package/dist/ir/sdk-model.js +35 -5
  89. package/dist/ir/slots.d.ts +1 -1
  90. package/dist/ir/slots.js +11 -3
  91. package/dist/ir/streams.d.ts +16 -0
  92. package/dist/ir/streams.js +40 -0
  93. package/dist/runtime/cli/socket.go +107 -13
  94. package/dist/runtime/cli/stream.go +18 -11
  95. package/dist/runtime/csharp/Adapters.cs +12 -11
  96. package/dist/runtime/csharp/Events.cs +22 -17
  97. package/dist/runtime/csharp/Realtime.cs +50 -23
  98. package/dist/runtime/csharp/RealtimeLoop.cs +1 -1
  99. package/dist/runtime/csharp/TransportSse.cs +3 -3
  100. package/dist/runtime/csharp/Ws.cs +1 -1
  101. package/dist/runtime/csharp/WsDial.cs +19 -1
  102. package/dist/runtime/csharp/WsTyped.cs +109 -0
  103. package/dist/runtime/go/realtime.go +125 -41
  104. package/dist/runtime/go/realtime_loop.go +21 -18
  105. package/dist/runtime/go/result.go +2 -1
  106. package/dist/runtime/go/sse.go +11 -0
  107. package/dist/runtime/go/stream.go +29 -13
  108. package/dist/runtime/go/transport.go +15 -21
  109. package/dist/runtime/go/transport_longpoll.go +3 -4
  110. package/dist/runtime/go/transport_sse.go +6 -6
  111. package/dist/runtime/go/ws.go +157 -61
  112. package/dist/runtime/java/EventStream.java +47 -29
  113. package/dist/runtime/java/Exchange.java +5 -5
  114. package/dist/runtime/java/Flight.java +3 -3
  115. package/dist/runtime/java/Realtime.java +45 -11
  116. package/dist/runtime/java/ResumableConnection.java +77 -32
  117. package/dist/runtime/java/Socket.java +8 -4
  118. package/dist/runtime/java/SseAdapter.java +1 -1
  119. package/dist/runtime/java/TypedWebSocket.java +81 -24
  120. package/dist/runtime/java/WsAdapter.java +4 -2
  121. package/dist/runtime/java/WsDial.java +12 -5
  122. package/dist/runtime/python/events.py +25 -11
  123. package/dist/runtime/python/operation.py +6 -1
  124. package/dist/runtime/python/realtime.py +47 -33
  125. package/dist/runtime/python/send_async.py +1 -0
  126. package/dist/runtime/python/transport_sse.py +2 -2
  127. package/dist/runtime/python/transport_ws.py +1 -1
  128. package/dist/runtime/python/ws.py +100 -39
  129. package/dist/runtime/rust/events.rs +64 -41
  130. package/dist/runtime/rust/realtime.rs +80 -34
  131. package/dist/runtime/rust/realtime_loop.rs +37 -12
  132. package/dist/runtime/rust/sse.rs +3 -2
  133. package/dist/runtime/rust/transport_sse.rs +1 -1
  134. package/dist/runtime/rust/transport_ws.rs +3 -2
  135. package/dist/runtime/rust/ws.rs +122 -50
  136. package/dist/runtime/ts/realtime-connection.ts +22 -0
  137. package/dist/runtime/ts/realtime-transports.ts +13 -4
  138. package/dist/runtime/ts/realtime.ts +27 -3
  139. package/dist/runtime/ts/sdk-realtime.ts +1 -1
  140. package/dist/runtime/ts/sdk-sse.ts +31 -14
  141. package/dist/runtime/ts/sdk-ws.ts +2 -1
  142. package/dist/runtime/ts/sdk.ts +9 -2
  143. package/dist/runtime/ts/sse.ts +8 -0
  144. package/dist/runtime/ts/ws.ts +88 -50
  145. package/package.json +3 -61
@@ -16,7 +16,7 @@ use crate::transport::{Transport, TransportConn, TransportKind, TransportOpts};
16
16
  use crate::transport_longpoll::LongpollTransport;
17
17
  use crate::transport_sse::SseTransport;
18
18
  use crate::transport_ws::WsTransport;
19
- use crate::ws::canceled;
19
+ use crate::ws::{Handler, canceled};
20
20
 
21
21
  /// Where a realtime connection is in its life.
22
22
  #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@@ -29,12 +29,16 @@ pub enum ConnectionState {
29
29
  Disconnected,
30
30
  }
31
31
 
32
- /// A realtime connection: `recv` reads the next message as `E`, reconnecting through the chain
33
- /// after a drop, the advanced cursor resuming it. Reconnects back off exponentially from the
34
- /// reconnect delay (an SSE `retry` the server sent, else `reconnect_delay_ms`, else 1 s; capped at
35
- /// 30 s, with jitter) for up to `max_reconnect_attempts` (5 when `None`). Dropping it closes the
36
- /// transport.
37
- pub struct ResumableConnection<E = Value> {
32
+ /// How a connection reads a message's text into the value its cursor is read from and `In` is
33
+ /// decoded from.
34
+ pub(crate) type Parse = fn(String) -> Result<Value, Error>;
35
+
36
+ /// A realtime connection: `recv` reads the next message as `In`, what the server sends, reconnecting
37
+ /// through the chain after a drop, the advanced cursor resuming it; `send` takes `Out`, what the
38
+ /// server receives. Reconnects back off exponentially from the reconnect delay (an SSE `retry` the
39
+ /// server sent, else `reconnect_delay_ms`, else 1 s; capped at 30 s, with jitter) for up to
40
+ /// `max_reconnect_attempts` (5 when `None`). Dropping it closes the transport.
41
+ pub struct ResumableConnection<In = Value, Out = Value> {
38
42
  pub(crate) url: String,
39
43
  pub(crate) transports: Vec<Box<dyn Transport>>,
40
44
  pub(crate) opts: TransportOpts,
@@ -46,32 +50,31 @@ pub struct ResumableConnection<E = Value> {
46
50
  pub(crate) retry: Option<u64>,
47
51
  pub(crate) failure: Option<Error>,
48
52
  pub(crate) cancel: Option<Signal>,
49
- pub(crate) events: PhantomData<fn() -> E>,
53
+ pub(crate) parse: Parse,
54
+ pub(crate) on_message: Vec<Handler<In>>,
55
+ pub(crate) sends: PhantomData<fn(&Out)>,
56
+ }
57
+
58
+ /// A message's text as JSON, else as a JSON string: an untyped connection reads any text.
59
+ pub(crate) fn lenient(text: String) -> Result<Value, Error> {
60
+ Ok(serde_json::from_str(&text).unwrap_or(Value::String(text)))
50
61
  }
51
62
 
52
- impl<E: DeserializeOwned> ResumableConnection<E> {
63
+ /// A message's text as JSON, else the error naming it: a typed connection reads only JSON.
64
+ #[allow(dead_code)] // an SDK reads the message types its operations declare
65
+ pub(crate) fn strict(text: String) -> Result<Value, Error> {
66
+ serde_json::from_str(&text)
67
+ .map_err(|e| Error::decode(format!("realtime message is not valid JSON: {e}")))
68
+ }
69
+
70
+ impl ResumableConnection {
53
71
  /// Opens `url` over the first of `transports` that opens, in order, with `opts`' cursor.
54
72
  pub async fn connect(
55
73
  url: impl Into<String>,
56
74
  opts: TransportOpts,
57
75
  transports: Vec<Box<dyn Transport>>,
58
76
  ) -> Result<Self, Error> {
59
- let mut rc = ResumableConnection {
60
- url: url.into(),
61
- transports,
62
- opts,
63
- conn: None,
64
- current: None,
65
- proven: None,
66
- state: ConnectionState::Disconnected,
67
- attempts: 0,
68
- retry: None,
69
- failure: None,
70
- cancel: None,
71
- events: PhantomData,
72
- };
73
- rc.bounded_open().await?;
74
- Ok(rc)
77
+ Self::open_with(url.into(), opts, transports, lenient).await
75
78
  }
76
79
 
77
80
  /// Opens `url` over the default chain, each transport dialing with `client`'s configuration.
@@ -87,11 +90,41 @@ impl<E: DeserializeOwned> ResumableConnection<E> {
87
90
  ];
88
91
  Self::connect(url, opts, chain).await
89
92
  }
93
+ }
90
94
 
91
- /// The next message; after a drop it reconnects first. `None` once closed or the call's
92
- /// `cancel_on` fired. Giving up returns the last failure once, then `None`. Cancel-safe: a
93
- /// dropped `recv` loses no delivered message.
94
- pub async fn recv(&mut self) -> Option<Result<E, Error>> {
95
+ impl<In: DeserializeOwned, Out> ResumableConnection<In, Out> {
96
+ /// Opens `url` over the first of `transports` that opens, each message read by `parse`.
97
+ pub(crate) async fn open_with(
98
+ url: String,
99
+ opts: TransportOpts,
100
+ transports: Vec<Box<dyn Transport>>,
101
+ parse: Parse,
102
+ ) -> Result<Self, Error> {
103
+ let mut rc = ResumableConnection {
104
+ url,
105
+ transports,
106
+ opts,
107
+ conn: None,
108
+ current: None,
109
+ proven: None,
110
+ state: ConnectionState::Disconnected,
111
+ attempts: 0,
112
+ retry: None,
113
+ failure: None,
114
+ cancel: None,
115
+ parse,
116
+ on_message: Vec::new(),
117
+ sends: PhantomData,
118
+ };
119
+ rc.bounded_open().await?;
120
+ Ok(rc)
121
+ }
122
+
123
+ /// The next message, after each `on_message` handler ran on it; after a drop it reconnects
124
+ /// first. A message that is no `In` is `Err(Error::Decode)` once, and the next one reads on.
125
+ /// `None` once closed or the call's `cancel_on` fired. Giving up returns the last failure once,
126
+ /// then `None`. Cancel-safe: a dropped `recv` loses no delivered message.
127
+ pub async fn recv(&mut self) -> Option<Result<In, Error>> {
95
128
  let signal = self.cancel.clone();
96
129
  let read = tokio::select! {
97
130
  biased;
@@ -108,7 +141,7 @@ impl<E: DeserializeOwned> ResumableConnection<E> {
108
141
  }
109
142
  }
110
143
 
111
- async fn read(&mut self) -> Option<Result<E, Error>> {
144
+ async fn read(&mut self) -> Option<Result<In, Error>> {
112
145
  loop {
113
146
  if self.state == ConnectionState::Disconnected {
114
147
  return None;
@@ -120,7 +153,13 @@ impl<E: DeserializeOwned> ResumableConnection<E> {
120
153
  continue;
121
154
  };
122
155
  match conn.recv().await {
123
- Some(Ok(message)) => return Some(self.deliver(message)),
156
+ Some(Ok(message)) => {
157
+ let delivered = self.deliver(message);
158
+ if let Ok(m) = &delivered {
159
+ self.on_message.iter_mut().for_each(|handler| handler(m));
160
+ }
161
+ return Some(delivered);
162
+ }
124
163
  failed => {
125
164
  let e = failed.and_then(Result::err).unwrap_or(Error::Closed);
126
165
  self.dropped(e);
@@ -128,12 +167,21 @@ impl<E: DeserializeOwned> ResumableConnection<E> {
128
167
  }
129
168
  }
130
169
  }
170
+ }
131
171
 
172
+ impl<In, Out: Serialize> ResumableConnection<In, Out> {
132
173
  /// Sends `message` as JSON on the open transport (an SSE or long-poll one POSTs it).
133
- pub async fn send<T: Serialize + ?Sized>(&mut self, message: &T) -> Result<(), Error> {
174
+ pub async fn send(&mut self, message: &Out) -> Result<(), Error> {
134
175
  let text = serde_json::to_string(message).map_err(Error::decode)?;
135
176
  self.send_text(&text).await
136
177
  }
178
+ }
179
+
180
+ impl<In, Out> ResumableConnection<In, Out> {
181
+ /// Calls `handler` on each message `recv` reads, before it returns it.
182
+ pub fn on_message(&mut self, handler: impl FnMut(&In) + Send + 'static) {
183
+ self.on_message.push(Box::new(handler));
184
+ }
137
185
 
138
186
  /// Sends `text` as it is on the open transport (an SSE or long-poll one POSTs it).
139
187
  pub async fn send_text(&mut self, text: &str) -> Result<(), Error> {
@@ -142,9 +190,7 @@ impl<E: DeserializeOwned> ResumableConnection<E> {
142
190
  None => Err(Error::Closed),
143
191
  }
144
192
  }
145
- }
146
193
 
147
- impl<E> ResumableConnection<E> {
148
194
  /// Where the connection is in its life.
149
195
  pub fn state(&self) -> ConnectionState {
150
196
  self.state
@@ -9,13 +9,12 @@ use std::sync::{Arc, PoisonError};
9
9
  use std::time::Duration;
10
10
 
11
11
  use serde::de::DeserializeOwned;
12
- use serde_json::Value;
13
12
 
14
13
  use crate::call::{Overrides, Run};
15
14
  use crate::config::Inner;
16
15
  use crate::errors::Error;
17
16
  use crate::exchange::url_of;
18
- use crate::realtime::{ConnectionState, ResumableConnection};
17
+ use crate::realtime::{ConnectionState, Parse, ResumableConnection, lenient, strict};
19
18
  use crate::request::RequestSpec;
20
19
  use crate::transport::{
21
20
  Dial, Route, Transport, TransportMessage, TransportOpts, advance, payload_cursor,
@@ -43,7 +42,7 @@ fn weight(e: &Error) -> u8 {
43
42
  }
44
43
  }
45
44
 
46
- impl<E: DeserializeOwned> ResumableConnection<E> {
45
+ impl<In: DeserializeOwned, Out> ResumableConnection<In, Out> {
47
46
  /// Opens the chain, the proven transport first, once more after a refreshed 401; else the heaviest failure.
48
47
  pub(crate) async fn open(&mut self) -> Result<(), Error> {
49
48
  let proven = self.proven;
@@ -82,15 +81,22 @@ impl<E: DeserializeOwned> ResumableConnection<E> {
82
81
  .unwrap_or(Err(Error::Timeout))
83
82
  }
84
83
 
85
- /// A delivered message as `E`, the cursor advanced past it (its SSE id, else the payload's), an
86
- /// SSE `retry` kept as the next reconnect's delay.
87
- pub(crate) fn deliver(&mut self, message: TransportMessage) -> Result<E, Error> {
84
+ /// A delivered message as `In`, parsed once, the cursor advanced past it (its SSE id, else the
85
+ /// payload's) even when it is no `In`, an SSE `retry` kept as the next reconnect's delay.
86
+ pub(crate) fn deliver(&mut self, message: TransportMessage) -> Result<In, Error> {
88
87
  self.attempts = 0;
89
- let value = serde_json::from_str(&message.text).unwrap_or(Value::String(message.text));
88
+ self.retry = message.retry.or(self.retry);
89
+ let value = match (self.parse)(message.text) {
90
+ Ok(value) => value,
91
+ Err(e) => {
92
+ advance(&mut self.opts, message.id, None);
93
+ return Err(e);
94
+ }
95
+ };
90
96
  let (id, token) = payload_cursor(&value);
91
97
  advance(&mut self.opts, message.id.or(id), token);
92
- self.retry = message.retry.or(self.retry);
93
- serde_json::from_value(value).map_err(Error::decode)
98
+ serde_json::from_value(value)
99
+ .map_err(|e| Error::decode(format!("realtime message does not decode: {e}")))
94
100
  }
95
101
 
96
102
  /// The open transport failed or ended with `e`: drop it, and reconnect the whole chain next.
@@ -132,12 +138,29 @@ impl<E: DeserializeOwned> ResumableConnection<E> {
132
138
  }
133
139
  }
134
140
 
141
+ /// A realtime operation without messages: `opened`, each message JSON else text.
142
+ #[allow(dead_code)] // an SDK opens the message types its operations declare
143
+ pub(crate) fn connect<In: DeserializeOwned + Send + 'static, Out: 'static>(
144
+ opts: TransportOpts,
145
+ ) -> Run<ResumableConnection<In, Out>> {
146
+ opened(opts, lenient)
147
+ }
148
+
149
+ /// A realtime operation with messages: `opened`, a message that is no JSON an error.
150
+ #[allow(dead_code)] // an SDK opens the message types its operations declare
151
+ pub(crate) fn typed<In: DeserializeOwned + Send + 'static, Out: 'static>(
152
+ opts: TransportOpts,
153
+ ) -> Run<ResumableConnection<In, Out>> {
154
+ opened(opts, strict)
155
+ }
156
+
135
157
  /// A realtime operation: opens the connection over the default chain before the call resolves,
136
158
  /// each dial sending the call's path, query and headers with its overrides (and its own
137
159
  /// `X-Request-Id` unless one is set); its answer is the one the opening transport dialed.
138
- pub(crate) fn connect<E: DeserializeOwned + Send + 'static>(
160
+ fn opened<In: DeserializeOwned + Send + 'static, Out: 'static>(
139
161
  opts: TransportOpts,
140
- ) -> Run<ResumableConnection<E>> {
162
+ parse: Parse,
163
+ ) -> Run<ResumableConnection<In, Out>> {
141
164
  Box::new(
142
165
  move |inner: Arc<Inner>, mut spec: RequestSpec, mut ov: Overrides| {
143
166
  Box::pin(async move {
@@ -166,7 +189,9 @@ pub(crate) fn connect<E: DeserializeOwned + Send + 'static>(
166
189
  Box::new(SseTransport(dial.clone())),
167
190
  Box::new(LongpollTransport(dial)),
168
191
  ];
169
- let mut rc = ResumableConnection::connect(url.as_str(), opts, chain).await?;
192
+ let mut rc =
193
+ ResumableConnection::open_with(url.as_str().to_owned(), opts, chain, parse)
194
+ .await?;
170
195
  rc.cancel = cancel;
171
196
  /* each default transport keeps the answer it opened with */
172
197
  let raw = opened.lock().unwrap_or_else(PoisonError::into_inner).take();
@@ -9,8 +9,9 @@ use crate::errors::Error;
9
9
  const MAX_LINE: usize = 1 << 20;
10
10
  const MAX_EVENT: usize = 8 << 20;
11
11
 
12
- /// One server-sent event. `id` is the last event id seen on the stream so far, to resume from.
13
- #[derive(Debug, Clone, Default, PartialEq)]
12
+ /// One server-sent event. `id` is the last event id seen on the stream so far, to resume from. It
13
+ /// serializes as `{data, event, id, retry}`, as an operation's event enum does.
14
+ #[derive(Debug, Clone, Default, PartialEq, serde::Serialize)]
14
15
  pub struct SseEvent<T = String> {
15
16
  pub data: T,
16
17
  pub event: String,
@@ -27,7 +27,7 @@ impl SseTransport {
27
27
  struct SseConn {
28
28
  dial: Dial,
29
29
  url: String,
30
- events: EventStream<String>,
30
+ events: EventStream,
31
31
  }
32
32
 
33
33
  impl Transport for SseTransport {
@@ -8,7 +8,7 @@ use crate::transport::{
8
8
  Dial, Transport, TransportConn, TransportFuture, TransportKind, TransportMessage,
9
9
  TransportOpts, with_cursor,
10
10
  };
11
- use crate::ws::{TypedWebSocket, WS_STATUS_NORMAL_CLOSURE, connect};
11
+ use crate::ws::{TypedWebSocket, WS_STATUS_NORMAL_CLOSURE, connect, frame_bytes};
12
12
 
13
13
  /// The default WebSocket adapter: dials with a client's auth, headers and credential.
14
14
  #[derive(Clone)]
@@ -39,7 +39,8 @@ impl Transport for WsTransport {
39
39
  let (mut spec, mut ov) = self.0.spec("GET", url);
40
40
  self.0.hold(&mut ov).await;
41
41
  with_cursor(&mut spec, opts);
42
- let (socket, raw) = connect(&self.0.inner, &spec, &ov, &opts.protocols).await?;
42
+ let (socket, raw): (TypedWebSocket, _) =
43
+ connect(&self.0.inner, &spec, &ov, &opts.protocols, frame_bytes).await?;
43
44
  self.0.opened(raw);
44
45
  Ok(Box::new(socket) as Box<dyn TransportConn>)
45
46
  })
@@ -3,14 +3,18 @@
3
3
  //! credential, its offered subprotocols, and a 16 MiB message cap. The call's `cancel_on` bounds the
4
4
  //! handshake and ends an open socket's reads quietly; dropping it closes the connection. Its dial
5
5
  //! runs no `on_request` or `on_response` hook, and a refused handshake's 401 is its error, with no
6
- //! `on_auth_expired` refresh.
6
+ //! `on_auth_expired` refresh. A socket typed by the operation's messages sends each value as JSON
7
+ //! and reads each frame as its message type.
7
8
 
9
+ use std::marker::PhantomData;
8
10
  use std::sync::Arc;
9
11
  use std::time::Duration;
10
12
 
11
13
  use bytes::Bytes;
12
14
  use futures_util::{SinkExt, StreamExt};
13
15
  use reqwest::header::HeaderValue;
16
+ use serde::Serialize;
17
+ use serde::de::DeserializeOwned;
14
18
  use tokio::io::AsyncReadExt;
15
19
  use tokio_tungstenite::tungstenite::client::IntoClientRequest;
16
20
  use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
@@ -44,15 +48,6 @@ pub const WS_STATUS_PROTOCOL_ERROR: u16 = 1002;
44
48
  type Socket =
45
49
  tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
46
50
 
47
- /// What an `on` handler is called for: each message read, the close (with its reason), or the error
48
- /// the socket ended on (with its text). The socket's end fires one of the two, once.
49
- #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50
- pub enum WsEvent {
51
- Message,
52
- Close,
53
- Error,
54
- }
55
-
56
51
  /// The close frame the server ended the socket with.
57
52
  #[derive(Debug, Clone, PartialEq, Eq)]
58
53
  pub struct WsClose {
@@ -60,17 +55,25 @@ pub struct WsClose {
60
55
  pub reason: String,
61
56
  }
62
57
 
63
- type Handler = Box<dyn FnMut(&[u8]) + Send>;
58
+ pub(crate) type Handler<T> = Box<dyn FnMut(&T) + Send>;
64
59
 
65
- /// An open WebSocket: messages in and out, JSON on top. Reading `None` means it closed: `closed_by`
66
- /// holds the server's close frame, if it sent one.
67
- pub struct TypedWebSocket {
60
+ /// How a socket reads one frame's bytes into `In`.
61
+ pub(crate) type Read<In> = fn(&[u8]) -> Result<In, Error>;
62
+
63
+ /// An open WebSocket: it reads `In`, what the server sends, and sends `Out`, what it receives, as
64
+ /// JSON. Untyped, it reads each frame's bytes and sends any JSON value. Reading `None` means it
65
+ /// closed: `closed_by` holds the server's close frame, if it sent one.
66
+ pub struct TypedWebSocket<In = Vec<u8>, Out = serde_json::Value> {
68
67
  socket: Socket,
69
- handlers: Vec<(WsEvent, Handler)>,
68
+ read: Read<In>,
69
+ on_message: Vec<Handler<In>>,
70
+ on_close: Vec<Handler<str>>,
71
+ on_error: Vec<Handler<Error>>,
70
72
  closed_by: Option<WsClose>,
71
73
  ended: bool,
72
74
  cancel: Option<Signal>,
73
75
  keepalive: Option<Keepalive>,
76
+ sends: PhantomData<fn(&Out)>,
74
77
  }
75
78
 
76
79
  /// Resolves once `signal` fires; never without one.
@@ -96,24 +99,60 @@ fn transport(e: tungstenite::Error) -> Error {
96
99
  }
97
100
  }
98
101
 
99
- impl TypedWebSocket {
100
- /// Calls `handler` on each `event` (TypeScript parity); a read loop is the typed way in.
101
- pub fn on(&mut self, event: WsEvent, handler: impl FnMut(&[u8]) + Send + 'static) {
102
- self.handlers.push((event, Box::new(handler)));
102
+ /// A frame as its bytes, as sent.
103
+ pub(crate) fn frame_bytes(data: &[u8]) -> Result<Vec<u8>, Error> {
104
+ Ok(data.to_vec())
105
+ }
106
+
107
+ /// A frame as the JSON message `In`: a frame that is no JSON, or does not fit `In`, is `Error::Decode`.
108
+ #[allow(dead_code)] // an SDK reads the message types its operations declare
109
+ pub(crate) fn frame_json<In: DeserializeOwned>(data: &[u8]) -> Result<In, Error> {
110
+ serde_json::from_slice(data).map_err(|e| {
111
+ let what = if e.is_data() {
112
+ "does not decode"
113
+ } else {
114
+ "is not valid JSON"
115
+ };
116
+ Error::decode(format!("WebSocket frame {what}: {e}"))
117
+ })
118
+ }
119
+
120
+ impl<In, Out> TypedWebSocket<In, Out> {
121
+ /// Calls `handler` on each message read, before `recv` returns it.
122
+ pub fn on_message(&mut self, handler: impl FnMut(&In) + Send + 'static) {
123
+ self.on_message.push(Box::new(handler));
124
+ }
125
+
126
+ /// Calls `handler` once the socket closes, with the close's reason.
127
+ pub fn on_close(&mut self, handler: impl FnMut(&str) + Send + 'static) {
128
+ self.on_close.push(Box::new(handler));
129
+ }
130
+
131
+ /// Calls `handler` on each error `recv` returns: one the socket ended on, or a frame that does
132
+ /// not decode, after which it reads on.
133
+ pub fn on_error(&mut self, handler: impl FnMut(&Error) + Send + 'static) {
134
+ self.on_error.push(Box::new(handler));
103
135
  }
104
136
 
105
- fn fire(&mut self, event: WsEvent, data: &[u8]) {
106
- for (on, handler) in &mut self.handlers {
107
- if *on == event {
108
- handler(data);
137
+ fn failed(&mut self, e: &Error) {
138
+ for handler in &mut self.on_error {
139
+ handler(e);
140
+ }
141
+ }
142
+
143
+ /// Marks the socket ended, firing `on_close` once.
144
+ fn closed(&mut self, reason: &str) {
145
+ if !std::mem::replace(&mut self.ended, true) {
146
+ for handler in &mut self.on_close {
147
+ handler(reason);
109
148
  }
110
149
  }
111
150
  }
112
151
 
113
- /// Marks the socket ended, firing `event` once.
114
- fn end(&mut self, event: WsEvent, data: &[u8]) {
152
+ /// Marks the socket ended on `e`, firing `on_error` once.
153
+ fn broke(&mut self, e: &Error) {
115
154
  if !std::mem::replace(&mut self.ended, true) {
116
- self.fire(event, data);
155
+ self.failed(e);
117
156
  }
118
157
  }
119
158
 
@@ -136,17 +175,17 @@ impl TypedWebSocket {
136
175
  }
137
176
 
138
177
  /// Sends `value` as JSON in one text frame.
139
- pub async fn send_json<T: serde::Serialize + ?Sized>(
140
- &mut self,
141
- value: &T,
142
- ) -> Result<(), Error> {
178
+ pub async fn send(&mut self, value: &Out) -> Result<(), Error>
179
+ where
180
+ Out: Serialize,
181
+ {
143
182
  let text = serde_json::to_string(value).map_err(Error::decode)?;
144
183
  self.send_text(text).await
145
184
  }
146
185
 
147
- /// The next message's bytes (text or binary); `None` once the socket closed, failed or the
148
- /// call's `cancel_on` fired.
149
- pub async fn recv(&mut self) -> Option<Result<Vec<u8>, Error>> {
186
+ /// The next message (a text or binary frame) as `In`; `None` once the socket closed, failed or
187
+ /// the call's `cancel_on` fired. A frame that does not decode is its error, and the socket reads on.
188
+ pub async fn recv(&mut self) -> Option<Result<In, Error>> {
150
189
  while !self.ended {
151
190
  let signal = self.cancel.clone();
152
191
  let at = self.keepalive.as_ref().map(|k| k.due);
@@ -171,15 +210,15 @@ impl TypedWebSocket {
171
210
  k.pinged = false;
172
211
  }
173
212
  match read {
174
- Some(Ok(Message::Text(t))) => return Some(Ok(self.message(t.as_bytes()))),
175
- Some(Ok(Message::Binary(b))) => return Some(Ok(self.message(&b))),
213
+ Some(Ok(Message::Text(t))) => return Some(self.message(t.as_bytes())),
214
+ Some(Ok(Message::Binary(b))) => return Some(self.message(&b)),
176
215
  Some(Ok(Message::Close(frame))) => {
177
216
  let (code, reason) = frame.map_or((1005, String::new()), |f| {
178
217
  (f.code.into(), f.reason.as_str().to_owned())
179
218
  });
180
219
  /* send the close echo tungstenite queued, completing the handshake */
181
220
  let _ = self.socket.flush().await;
182
- self.end(WsEvent::Close, reason.as_bytes());
221
+ self.closed(&reason);
183
222
  self.closed_by = Some(WsClose { code, reason });
184
223
  }
185
224
  Some(Ok(_)) => {}
@@ -199,10 +238,10 @@ impl TypedWebSocket {
199
238
  let _ = tokio::time::timeout(CLOSE_WAIT, drain).await;
200
239
  }
201
240
  let e = transport(e);
202
- self.end(WsEvent::Error, e.to_string().as_bytes());
241
+ self.broke(&e);
203
242
  return Some(Err(e));
204
243
  }
205
- None => self.end(WsEvent::Close, b""),
244
+ None => self.closed(""),
206
245
  }
207
246
  }
208
247
  None
@@ -220,13 +259,24 @@ impl TypedWebSocket {
220
259
  ping.await.map_err(transport)
221
260
  };
222
261
  let e = sent.err()?;
223
- self.end(WsEvent::Error, e.to_string().as_bytes());
262
+ self.broke(&e);
224
263
  Some(e)
225
264
  }
226
265
 
227
- fn message(&mut self, data: &[u8]) -> Vec<u8> {
228
- self.fire(WsEvent::Message, data);
229
- data.to_vec()
266
+ /// A frame read as `In`, handed to `on_message`, or its decode error to `on_error`.
267
+ fn message(&mut self, data: &[u8]) -> Result<In, Error> {
268
+ match (self.read)(data) {
269
+ Ok(m) => {
270
+ for handler in &mut self.on_message {
271
+ handler(&m);
272
+ }
273
+ Ok(m)
274
+ }
275
+ Err(e) => {
276
+ self.failed(&e);
277
+ Err(e)
278
+ }
279
+ }
230
280
  }
231
281
 
232
282
  /// The close frame the server sent, once `recv` read it.
@@ -250,7 +300,7 @@ impl TypedWebSocket {
250
300
  reason: reason[..cut].into(),
251
301
  };
252
302
  let sent = self.socket.close(Some(frame)).await;
253
- self.end(WsEvent::Close, &reason.as_bytes()[..cut]);
303
+ self.closed(&reason[..cut]);
254
304
  let echo = async { while let Some(Ok(_)) = self.socket.next().await {} };
255
305
  let _ = tokio::time::timeout(CLOSE_WAIT, echo).await;
256
306
  sent.map_err(transport)
@@ -258,13 +308,14 @@ impl TypedWebSocket {
258
308
  }
259
309
 
260
310
  /// Dials the socket of `spec`: its URL with a ws(s) scheme, the call's headers and credential (a fresh
261
- /// `X-Request-Id` unless one is set), and `protocols` offered.
262
- pub(crate) async fn connect(
311
+ /// `X-Request-Id` unless one is set), and `protocols` offered; its frames read by `read`.
312
+ pub(crate) async fn connect<In, Out>(
263
313
  inner: &Inner,
264
314
  spec: &RequestSpec,
265
315
  ov: &Overrides,
266
316
  protocols: &[String],
267
- ) -> Result<(TypedWebSocket, RawResponse), Error> {
317
+ read: Read<In>,
318
+ ) -> Result<(TypedWebSocket<In, Out>, RawResponse), Error> {
268
319
  let mut url = url_of(inner, spec, ov)?;
269
320
  let scheme = if url.scheme() == "https" { "wss" } else { "ws" };
270
321
  url.set_scheme(scheme)
@@ -293,7 +344,10 @@ pub(crate) async fn connect(
293
344
  };
294
345
  let socket = TypedWebSocket {
295
346
  socket,
296
- handlers: Vec::new(),
347
+ read,
348
+ on_message: Vec::new(),
349
+ on_close: Vec::new(),
350
+ on_error: Vec::new(),
297
351
  closed_by: None,
298
352
  ended: false,
299
353
  cancel: ov.cancel.clone(),
@@ -302,20 +356,38 @@ pub(crate) async fn connect(
302
356
  due: tokio::time::Instant::now() + every,
303
357
  pinged: false,
304
358
  }),
359
+ sends: PhantomData,
305
360
  };
306
361
  Ok((socket, raw))
307
362
  }
308
363
 
309
- /// A WebSocket operation: dials offering `protocols`.
364
+ /// A WebSocket operation that declares no message it reads: dials offering `protocols`, its frames
365
+ /// read as bytes.
366
+ #[allow(dead_code)] // a realtime-only SDK dials through its transports
367
+ pub(crate) fn dial<Out: 'static>(protocols: Vec<String>) -> Run<TypedWebSocket<Vec<u8>, Out>> {
368
+ opened(protocols, frame_bytes)
369
+ }
370
+
371
+ /// A WebSocket operation with messages: dials offering `protocols`, its frames read as JSON `In`.
372
+ #[allow(dead_code)] // an SDK dials the message types its operations declare
373
+ pub(crate) fn typed<In: DeserializeOwned + Send + 'static, Out: 'static>(
374
+ protocols: Vec<String>,
375
+ ) -> Run<TypedWebSocket<In, Out>> {
376
+ opened(protocols, frame_json::<In>)
377
+ }
378
+
310
379
  #[allow(dead_code)] // a realtime-only SDK dials through its transports
311
- pub(crate) fn dial(protocols: Vec<String>) -> Run<TypedWebSocket> {
380
+ fn opened<In: Send + 'static, Out: 'static>(
381
+ protocols: Vec<String>,
382
+ read: Read<In>,
383
+ ) -> Run<TypedWebSocket<In, Out>> {
312
384
  Box::new(
313
385
  move |inner: Arc<Inner>, mut spec: RequestSpec, ov: Overrides| {
314
386
  Box::pin(async move {
315
387
  if let Some(e) = spec.take_failure() {
316
388
  return Err(e.into());
317
389
  }
318
- Ok(connect(&inner, &spec, &ov, &protocols).await?)
390
+ Ok(connect(&inner, &spec, &ov, &protocols, read).await?)
319
391
  })
320
392
  },
321
393
  )