@workerstack/clients 1.0.0-rc.28 → 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.
- package/README.md +30 -7
- package/dist/emit/cli/commands.js +25 -5
- package/dist/emit/cli/flags.js +7 -3
- package/dist/emit/cli/skills.js +5 -1
- package/dist/emit/csharp/realtime.d.ts +1 -8
- package/dist/emit/csharp/realtime.js +25 -25
- package/dist/emit/csharp/sdk-answer.d.ts +10 -2
- package/dist/emit/csharp/sdk-method.js +9 -2
- package/dist/emit/csharp/sse.d.ts +0 -11
- package/dist/emit/csharp/sse.js +91 -10
- package/dist/emit/csharp/transport.js +3 -3
- package/dist/emit/csharp/types-messages.d.ts +47 -0
- package/dist/emit/csharp/types-messages.js +172 -0
- package/dist/emit/csharp/types-names.js +3 -2
- package/dist/emit/csharp/ws.d.ts +0 -15
- package/dist/emit/csharp/ws.js +26 -5
- package/dist/emit/go/sdk-answer.d.ts +24 -1
- package/dist/emit/go/sdk-method.d.ts +3 -0
- package/dist/emit/go/sdk-method.js +16 -10
- package/dist/emit/go/sse.d.ts +2 -10
- package/dist/emit/go/sse.js +87 -12
- package/dist/emit/go/types-union.d.ts +3 -2
- package/dist/emit/go/types-union.js +2 -0
- package/dist/emit/go/types.d.ts +6 -0
- package/dist/emit/go/types.js +12 -1
- package/dist/emit/go/ws.d.ts +4 -11
- package/dist/emit/go/ws.js +214 -58
- package/dist/emit/java/json.d.ts +3 -0
- package/dist/emit/java/layout-ast.d.ts +4 -1
- package/dist/emit/java/layout-types.js +1 -1
- package/dist/emit/java/models-names.d.ts +2 -0
- package/dist/emit/java/models-names.js +1 -0
- package/dist/emit/java/models-union.d.ts +12 -1
- package/dist/emit/java/models-union.js +11 -5
- package/dist/emit/java/models.d.ts +5 -0
- package/dist/emit/java/models.js +22 -7
- package/dist/emit/java/realtime.d.ts +29 -9
- package/dist/emit/java/realtime.js +45 -10
- package/dist/emit/java/sdk-mirror.js +6 -5
- package/dist/emit/java/sdk-op.js +1 -1
- package/dist/emit/java/sse.d.ts +11 -10
- package/dist/emit/java/sse.js +104 -5
- package/dist/emit/java/ws.d.ts +46 -7
- package/dist/emit/java/ws.js +89 -4
- package/dist/emit/mcp/output-schema.d.ts +4 -2
- package/dist/emit/mcp/output-schema.js +56 -12
- package/dist/emit/python/realtime.d.ts +9 -6
- package/dist/emit/python/realtime.js +21 -19
- package/dist/emit/python/sdk-answer.d.ts +5 -1
- package/dist/emit/python/sdk-method.d.ts +1 -1
- package/dist/emit/python/sdk-method.js +33 -6
- package/dist/emit/python/sdk.js +22 -2
- package/dist/emit/python/sse.d.ts +0 -5
- package/dist/emit/python/sse.js +35 -5
- package/dist/emit/python/types.d.ts +7 -0
- package/dist/emit/python/types.js +20 -3
- package/dist/emit/python/ws.d.ts +20 -6
- package/dist/emit/python/ws.js +67 -1
- package/dist/emit/rust/realtime.d.ts +7 -5
- package/dist/emit/rust/realtime.js +14 -17
- package/dist/emit/rust/sdk-method.js +1 -1
- package/dist/emit/rust/sse.d.ts +11 -7
- package/dist/emit/rust/sse.js +52 -6
- package/dist/emit/rust/types-union.d.ts +9 -1
- package/dist/emit/rust/types-union.js +4 -0
- package/dist/emit/rust/types.d.ts +9 -0
- package/dist/emit/rust/types.js +13 -7
- package/dist/emit/rust/ws.d.ts +22 -4
- package/dist/emit/rust/ws.js +57 -7
- package/dist/emit/ts/sdk-types-preamble.js +4 -0
- package/dist/emit/ts/sdk-types.js +49 -10
- package/dist/emit/ts/sdk.js +2 -2
- package/dist/emit/ts/service-map.d.ts +8 -2
- package/dist/emit/ts/service-map.js +30 -2
- package/dist/emit/ts/type-gen.js +6 -4
- package/dist/ir/build.js +4 -0
- package/dist/ir/model.d.ts +14 -0
- package/dist/ir/sdk-model.d.ts +25 -1
- package/dist/ir/sdk-model.js +35 -5
- package/dist/ir/slots.d.ts +1 -1
- package/dist/ir/slots.js +9 -3
- package/dist/ir/streams.d.ts +16 -0
- package/dist/ir/streams.js +40 -0
- package/dist/runtime/cli/socket.go +107 -13
- package/dist/runtime/cli/stream.go +18 -11
- package/dist/runtime/csharp/Adapters.cs +12 -11
- package/dist/runtime/csharp/Events.cs +22 -17
- package/dist/runtime/csharp/Realtime.cs +50 -23
- package/dist/runtime/csharp/RealtimeLoop.cs +1 -1
- package/dist/runtime/csharp/TransportSse.cs +3 -3
- package/dist/runtime/csharp/Ws.cs +1 -1
- package/dist/runtime/csharp/WsDial.cs +19 -1
- package/dist/runtime/csharp/WsTyped.cs +109 -0
- package/dist/runtime/go/realtime.go +125 -41
- package/dist/runtime/go/realtime_loop.go +21 -18
- package/dist/runtime/go/result.go +2 -1
- package/dist/runtime/go/sse.go +11 -0
- package/dist/runtime/go/stream.go +29 -13
- package/dist/runtime/go/transport.go +15 -21
- package/dist/runtime/go/transport_longpoll.go +3 -4
- package/dist/runtime/go/transport_sse.go +6 -6
- package/dist/runtime/go/ws.go +157 -61
- package/dist/runtime/java/EventStream.java +47 -29
- package/dist/runtime/java/Exchange.java +5 -5
- package/dist/runtime/java/Flight.java +3 -3
- package/dist/runtime/java/Realtime.java +45 -11
- package/dist/runtime/java/ResumableConnection.java +77 -32
- package/dist/runtime/java/Socket.java +8 -4
- package/dist/runtime/java/SseAdapter.java +1 -1
- package/dist/runtime/java/TypedWebSocket.java +81 -24
- package/dist/runtime/java/WsAdapter.java +4 -2
- package/dist/runtime/java/WsDial.java +12 -5
- package/dist/runtime/python/events.py +25 -11
- package/dist/runtime/python/operation.py +6 -1
- package/dist/runtime/python/realtime.py +47 -33
- package/dist/runtime/python/send_async.py +1 -0
- package/dist/runtime/python/transport_sse.py +2 -2
- package/dist/runtime/python/transport_ws.py +1 -1
- package/dist/runtime/python/ws.py +100 -39
- package/dist/runtime/rust/events.rs +64 -41
- package/dist/runtime/rust/realtime.rs +80 -34
- package/dist/runtime/rust/realtime_loop.rs +37 -12
- package/dist/runtime/rust/sse.rs +3 -2
- package/dist/runtime/rust/transport_sse.rs +1 -1
- package/dist/runtime/rust/transport_ws.rs +3 -2
- package/dist/runtime/rust/ws.rs +122 -50
- package/dist/runtime/ts/realtime-connection.ts +22 -0
- package/dist/runtime/ts/realtime-transports.ts +13 -4
- package/dist/runtime/ts/realtime.ts +27 -3
- package/dist/runtime/ts/sdk-realtime.ts +1 -1
- package/dist/runtime/ts/sdk-sse.ts +31 -14
- package/dist/runtime/ts/sdk-ws.ts +2 -1
- package/dist/runtime/ts/sdk.ts +9 -2
- package/dist/runtime/ts/sse.ts +8 -0
- package/dist/runtime/ts/ws.ts +88 -50
- package/package.json +3 -34
|
@@ -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
|
-
///
|
|
33
|
-
///
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
///
|
|
37
|
-
|
|
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)
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
92
|
-
/// `
|
|
93
|
-
|
|
94
|
-
|
|
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<
|
|
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)) =>
|
|
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
|
|
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<
|
|
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 `
|
|
86
|
-
/// SSE `retry` kept as the next reconnect's delay.
|
|
87
|
-
pub(crate) fn deliver(&mut self, message: TransportMessage) -> Result<
|
|
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
|
-
|
|
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
|
-
|
|
93
|
-
|
|
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
|
-
|
|
160
|
+
fn opened<In: DeserializeOwned + Send + 'static, Out: 'static>(
|
|
139
161
|
opts: TransportOpts,
|
|
140
|
-
|
|
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 =
|
|
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();
|
package/dist/runtime/rust/sse.rs
CHANGED
|
@@ -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
|
-
|
|
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,
|
|
@@ -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)
|
|
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
|
})
|
package/dist/runtime/rust/ws.rs
CHANGED
|
@@ -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(&
|
|
58
|
+
pub(crate) type Handler<T> = Box<dyn FnMut(&T) + Send>;
|
|
64
59
|
|
|
65
|
-
///
|
|
66
|
-
|
|
67
|
-
|
|
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
|
-
|
|
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
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
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
|
|
106
|
-
for
|
|
107
|
-
|
|
108
|
-
|
|
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
|
|
114
|
-
fn
|
|
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.
|
|
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
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
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
|
|
148
|
-
/// call's `cancel_on` fired.
|
|
149
|
-
pub async fn recv(&mut self) -> Option<Result<
|
|
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(
|
|
175
|
-
Some(Ok(Message::Binary(b))) => return Some(
|
|
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.
|
|
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.
|
|
241
|
+
self.broke(&e);
|
|
203
242
|
return Some(Err(e));
|
|
204
243
|
}
|
|
205
|
-
None => self.
|
|
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.
|
|
262
|
+
self.broke(&e);
|
|
224
263
|
Some(e)
|
|
225
264
|
}
|
|
226
265
|
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
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.
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
)
|