frakt 0.1.0

Ergonomic platform HTTP client bindings for Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! WebSocket support with backend abstraction

use crate::Result;

// Backend-specific implementations are in their respective modules

/// [`WebSocket`] message types
#[derive(Debug, Clone)]
pub enum Message {
    /// Text message
    Text(String),
    /// Binary data message
    Binary(Vec<u8>),
}

impl From<Vec<u8>> for Message {
    fn from(data: Vec<u8>) -> Self {
        Message::Binary(data)
    }
}

impl From<String> for Message {
    fn from(text: String) -> Self {
        Message::Text(text)
    }
}

impl Message {
    /// Create a text message
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text(text.into())
    }

    /// Create a binary message
    pub fn binary(data: impl Into<Vec<u8>>) -> Self {
        Self::Binary(data.into())
    }
}

/// [`WebSocket`] close codes.
///
/// These codes indicate the reason why a WebSocket connection was closed.
/// They correspond to the standard WebSocket close codes defined in RFC 6455.
///
/// # Examples
///
/// ```rust,no_run
/// use frakt::{Client, CloseCode};
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new()?;
/// let mut websocket = client
///     .websocket()
///     .connect("wss://echo.websocket.org")
///     .await?;
///
/// // Close the connection normally
/// websocket.close(CloseCode::Normal, Some("Goodbye"));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(i64)]
pub enum CloseCode {
    /// Normal closure (1000).
    ///
    /// The connection was closed normally and the purpose for which it was opened has been fulfilled.
    Normal = 1000,
    /// Going away (1001).
    ///
    /// The endpoint is going away, such as a server going down or a browser navigating away.
    GoingAway = 1001,
    /// Protocol error (1002).
    ///
    /// The connection was terminated due to a protocol error.
    ProtocolError = 1002,
    /// Unsupported data (1003).
    ///
    /// The connection was terminated because the endpoint received data of a type it cannot accept.
    UnsupportedData = 1003,
    /// No status received (1005).
    ///
    /// No status code was actually present. This is a reserved value and MUST NOT be set as a status code.
    NoStatusReceived = 1005,
    /// Abnormal closure (1006).
    ///
    /// The connection was closed abnormally without a close frame being sent.
    AbnormalClosure = 1006,
    /// Invalid frame payload data (1007).
    ///
    /// The connection was terminated because the endpoint received data inconsistent with the type of the message.
    InvalidFramePayloadData = 1007,
    /// Policy violation (1008).
    ///
    /// The connection was terminated because the endpoint received a message that violates its policy.
    PolicyViolation = 1008,
    /// Message too big (1009).
    ///
    /// The connection was terminated because the endpoint received a message that is too big for it to process.
    MessageTooBig = 1009,
    /// Mandatory extension (1010).
    ///
    /// The connection was terminated because the client expected the server to negotiate one or more extensions.
    MandatoryExtension = 1010,
    /// Internal server error (1011).
    ///
    /// The connection was terminated because the server encountered an unexpected condition.
    InternalServerError = 1011,
    /// TLS handshake (1015).
    ///
    /// The connection was closed due to a failure to perform a TLS handshake.
    TlsHandshake = 1015,
}

/// A [`WebSocket`] connection using NSURLSessionWebSocketTask.
///
/// This struct represents an active [`WebSocket`] connection that can send and receive messages.
/// It uses NSURLSession's [`WebSocket`] implementation for optimal performance and integration
/// with the Apple ecosystem.
///
/// # Examples
///
/// ```rust,no_run
/// use frakt::{Client, Message, CloseCode};
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new()?;
/// let mut websocket = client
///     .websocket()
///     .maximum_message_size(1024 * 1024)
///     .connect("wss://echo.websocket.org")
///     .await?;
///
/// // Send a text message
/// websocket.send(Message::text("Hello, WebSocket!")).await?;
///
/// // Receive a message
/// let message = websocket.receive().await?;
/// match message {
///     Message::Text(text) => println!("Received text: {}", text),
///     Message::Binary(data) => println!("Received {} bytes", data.len()),
/// }
///
/// // Close the connection
/// websocket.close(CloseCode::Normal, Some("Goodbye"));
/// # Ok(())
/// # }
/// ```
pub enum WebSocket {
    /// Foundation backend using NSURLSessionWebSocketTask
    #[cfg(target_vendor = "apple")]
    Foundation(crate::backend::foundation::FoundationWebSocket),
    /// Windows backend using MessageWebSocket
    #[cfg(windows)]
    Windows(crate::backend::windows::WindowsWebSocket),
    /// Reqwest backend using tokio-tungstenite
    Reqwest(crate::backend::reqwest::ReqwestWebSocket),
}

impl WebSocket {
    /// Send a message over the [`WebSocket`] connection.
    ///
    /// This method sends a message to the [`WebSocket`] server. The message can be either
    /// text or binary data, and will be automatically converted from types that implement
    /// `Into<Message>`.
    ///
    /// # Arguments
    ///
    /// * `message` - The message to send (`String`, `&str`, `Vec<u8>`, or [`Message`])
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use frakt::{Client, Message};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let mut websocket = client.websocket().connect("wss://echo.websocket.org").await?;
    ///
    /// // Send text directly
    /// websocket.send(Message::text("Hello, World!")).await?;
    ///
    /// // Send binary data
    /// websocket.send(vec![1, 2, 3, 4]).await?;
    ///
    /// // Send a Message explicitly
    /// websocket.send(Message::text("Explicit message")).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn send(&mut self, message: impl Into<Message>) -> Result<()> {
        match self {
            #[cfg(target_vendor = "apple")]
            WebSocket::Foundation(ws) => ws.send(message.into()).await,
            #[cfg(windows)]
            WebSocket::Windows(ws) => ws.send(message.into()).await,
            WebSocket::Reqwest(ws) => ws.send(message.into()).await,
        }
    }

    /// Receive a message from the [`WebSocket`] connection.
    ///
    /// This method waits for and returns the next message from the [`WebSocket`] server.
    /// The method will block until a message is received or an error occurs.
    ///
    /// # Returns
    ///
    /// Returns a [`Message`] which can be either text or binary data.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use frakt::{Client, Message};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let mut websocket = client.websocket().connect("wss://echo.websocket.org").await?;
    ///
    /// // Send a message first
    /// websocket.send(Message::text("Hello")).await?;
    ///
    /// // Receive the echo
    /// let message = websocket.receive().await?;
    /// match message {
    ///     Message::Text(text) => println!("Received text: {}", text),
    ///     Message::Binary(data) => println!("Received {} bytes of binary data", data.len()),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn receive(&mut self) -> Result<Message> {
        match self {
            #[cfg(target_vendor = "apple")]
            WebSocket::Foundation(ws) => ws.receive().await,
            #[cfg(windows)]
            WebSocket::Windows(ws) => ws.receive().await,
            WebSocket::Reqwest(ws) => ws.receive().await,
        }
    }

    /// Close the [`WebSocket`] connection.
    ///
    /// This method closes the [`WebSocket`] connection with the specified close code and reason.
    /// The connection will be terminated and no further messages can be sent or received.
    ///
    /// # Arguments
    ///
    /// * `code` - The close code indicating the reason for closure
    /// * `reason` - Optional human-readable reason for closure
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use frakt::{Client, CloseCode};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let mut websocket = client.websocket().connect("wss://echo.websocket.org").await?;
    ///
    /// // Close normally
    /// websocket.close(CloseCode::Normal, Some("Session ended"));
    ///
    /// // Close due to policy violation
    /// websocket.close(CloseCode::PolicyViolation, None);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn close(&mut self, code: CloseCode, reason: Option<&str>) -> Result<()> {
        match self {
            #[cfg(target_vendor = "apple")]
            WebSocket::Foundation(ws) => ws.close(code, reason).await,
            #[cfg(windows)]
            WebSocket::Windows(ws) => ws.close(code, reason).await,
            WebSocket::Reqwest(ws) => ws.close(code, reason).await,
        }
    }

    /// Get the current close code if the connection has been closed.
    ///
    /// Returns the close code that was used when the connection was closed,
    /// or `None` if the connection is still open.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use frakt::{Client, CloseCode};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let mut websocket = client.websocket().connect("wss://echo.websocket.org").await?;
    ///
    /// // Connection is open
    /// assert_eq!(websocket.close_code(), None);
    ///
    /// websocket.close(CloseCode::Normal, None);
    /// // After closing, code should be available
    /// // (Note: this might not be immediately available)
    /// # Ok(())
    /// # }
    /// ```
    pub fn close_code(&self) -> Option<isize> {
        match self {
            #[cfg(target_vendor = "apple")]
            WebSocket::Foundation(ws) => ws.close_code(),
            #[cfg(windows)]
            WebSocket::Windows(ws) => ws.close_code(),
            WebSocket::Reqwest(ws) => ws.close_code(),
        }
    }

    /// Get the close reason if the connection has been closed.
    ///
    /// Returns the human-readable reason that was provided when the connection
    /// was closed, or `None` if no reason was provided or the connection is still open.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use frakt::{Client, CloseCode};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let mut websocket = client.websocket().connect("wss://echo.websocket.org").await?;
    ///
    /// websocket.close(CloseCode::Normal, Some("User requested"));
    /// // After closing, reason should be available
    /// // (Note: this might not be immediately available)
    /// # Ok(())
    /// # }
    /// ```
    pub fn close_reason(&self) -> Option<String> {
        match self {
            #[cfg(target_vendor = "apple")]
            WebSocket::Foundation(ws) => ws.close_reason(),
            #[cfg(windows)]
            WebSocket::Windows(ws) => ws.close_reason(),
            WebSocket::Reqwest(ws) => ws.close_reason(),
        }
    }

    /// Set the maximum message size for this [`WebSocket`].
    ///
    /// This controls the maximum size of messages that can be sent or received.
    /// Messages larger than this size will be rejected.
    ///
    /// # Arguments
    ///
    /// * `size` - The maximum message size in bytes
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use frakt::{Client, Message};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let mut websocket = client.websocket().connect("wss://echo.websocket.org").await?;
    ///
    /// // Set maximum message size to 1MB
    /// websocket.set_maximum_message_size(1024 * 1024);
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_maximum_message_size(&mut self, size: isize) {
        match self {
            #[cfg(target_vendor = "apple")]
            WebSocket::Foundation(ws) => ws.set_maximum_message_size(size),
            #[cfg(windows)]
            WebSocket::Windows(ws) => ws.set_maximum_message_size(size),
            WebSocket::Reqwest(ws) => ws.set_maximum_message_size(size),
        }
    }

    /// Get the current maximum message size.
    ///
    /// Returns the maximum size of messages that can be sent or received
    /// through this [`WebSocket`] connection.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use frakt::{Client, Message};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let mut websocket = client.websocket().connect("wss://echo.websocket.org").await?;
    ///
    /// let max_size = websocket.maximum_message_size();
    /// println!("Maximum message size: {} bytes", max_size);
    /// # Ok(())
    /// # }
    /// ```
    pub fn maximum_message_size(&self) -> isize {
        match self {
            #[cfg(target_vendor = "apple")]
            WebSocket::Foundation(ws) => ws.maximum_message_size(),
            #[cfg(windows)]
            WebSocket::Windows(ws) => ws.maximum_message_size(),
            WebSocket::Reqwest(ws) => ws.maximum_message_size(),
        }
    }
}

/// Builder for [`WebSocket`] connections.
///
/// This builder allows you to configure [`WebSocket`] connection parameters before
/// establishing the connection. It provides a fluent interface for setting options
/// like maximum message size.
///
/// # Examples
///
/// ```rust,no_run
/// use frakt::{Client, Message};
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let client = Client::new()?;
/// let mut websocket = client
///     .websocket()
///     .maximum_message_size(1024 * 1024)  // 1MB max messages
///     .connect("wss://echo.websocket.org")
///     .await?;
/// # Ok(())
/// # }
/// ```
pub enum WebSocketBuilder {
    /// Foundation backend using NSURLSession
    #[cfg(target_vendor = "apple")]
    Foundation(crate::backend::foundation::FoundationWebSocketBuilder),
    /// Windows backend using MessageWebSocket
    #[cfg(windows)]
    Windows(crate::backend::windows::WindowsWebSocketBuilder),
    /// Reqwest backend using tokio-tungstenite
    Reqwest(crate::backend::reqwest::ReqwestWebSocketBuilder),
}

impl WebSocketBuilder {
    /// Set the maximum message size for the [`WebSocket`] connection.
    ///
    /// This sets the maximum size of messages that can be sent or received
    /// through the [`WebSocket`] connection. Messages larger than this size will be rejected.
    ///
    /// # Arguments
    ///
    /// * `size` - The maximum message size in bytes
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use frakt::{Client, Message};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let mut websocket = client
    ///     .websocket()
    ///     .maximum_message_size(1024 * 1024)  // 1MB
    ///     .connect("wss://echo.websocket.org")
    ///     .await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn maximum_message_size(self, size: isize) -> Self {
        match self {
            #[cfg(target_vendor = "apple")]
            WebSocketBuilder::Foundation(builder) => {
                WebSocketBuilder::Foundation(builder.maximum_message_size(size))
            }
            #[cfg(windows)]
            WebSocketBuilder::Windows(builder) => {
                WebSocketBuilder::Windows(builder.maximum_message_size(size))
            }
            WebSocketBuilder::Reqwest(builder) => {
                WebSocketBuilder::Reqwest(builder.maximum_message_size(size))
            }
        }
    }

    /// Connect to the [`WebSocket`] server at the specified URL.
    ///
    /// This method establishes the [`WebSocket`] connection and returns a [`WebSocket`]
    /// instance that can be used to send and receive messages.
    ///
    /// # Arguments
    ///
    /// * `url` - The WebSocket URL (must use ws:// or wss:// scheme)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use frakt::{Client, Message};
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let client = Client::new()?;
    /// let mut websocket = client
    ///     .websocket()
    ///     .connect("wss://echo.websocket.org")
    ///     .await?;
    ///
    /// // WebSocket is now ready for use
    /// websocket.send(Message::text("Hello, WebSocket!")).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn connect(self, url: &str) -> Result<WebSocket> {
        match self {
            #[cfg(target_vendor = "apple")]
            WebSocketBuilder::Foundation(builder) => {
                let ws = builder.connect(url).await?;
                Ok(WebSocket::Foundation(ws))
            }
            #[cfg(windows)]
            WebSocketBuilder::Windows(builder) => {
                let ws = builder.connect(url).await?;
                Ok(WebSocket::Windows(ws))
            }
            WebSocketBuilder::Reqwest(builder) => {
                let ws = builder.connect(url).await?;
                Ok(WebSocket::Reqwest(ws))
            }
        }
    }
}