concuring 0.1.0

A synchronous, concurrent HTTP client library for Rust that uses io_uring.
Documentation
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
use color_eyre::eyre::{Context, ContextCompat, Result, bail, ensure};
use std::{marker::PhantomData, net::ToSocketAddrs, pin::Pin};
use url::Url;

pub struct Builder<S> {
    data: Vec<u8>,
    conn: Conn,
    _stage: PhantomData<S>,
}

#[derive(Debug, PartialEq, Hash, Clone)]
pub enum Conn {
    Tcp {
        scheme: ConnScheme,
        host: String,
        port: Option<u16>,
    },
    Uds {
        path: String,
    },
}

#[derive(Debug, Hash, Clone, Copy, PartialEq)]
pub enum ConnScheme {
    Http,
    Https,
}

pub struct RequestBuilder;

pub struct HeaderStage;
pub type HeaderBuilder = Builder<HeaderStage>;

#[derive(Debug)]
pub struct Request {
    pub data: Pin<Box<[u8]>>,
    pub conn: Conn,
}

impl Request {
    pub fn create_socket(&self) -> Result<(socket2::Socket, socket2::SockAddr)> {
        let (socket_addr, domain, socket_type, protocol) = match &self.conn {
            Conn::Tcp {
                host,
                port,
                scheme: _,
            } => {
                let socket_addr = match port {
                    Some(port) => (host.as_str(), *port).to_socket_addrs(),
                    None => host.to_socket_addrs(),
                };
                let mut socket_addr = socket_addr
                    .wrap_err_with(|| format!("to socket addrs failed for {}:{:?}", host, port))?;
                let addr = socket_addr
                    .next()
                    .wrap_err_with(|| format!("to socket addrs failed for {}:{:?}", host, port))?;
                (
                    socket2::SockAddr::from(addr),
                    socket2::Domain::IPV4,
                    socket2::Type::STREAM,
                    Some(socket2::Protocol::TCP),
                )
            }
            Conn::Uds { path } => {
                let sock_addr = socket2::SockAddr::unix(path).wrap_err_with(|| {
                    format!("Failed to create Unix socket address for path: {}", path)
                })?;
                (
                    sock_addr,
                    socket2::Domain::UNIX,
                    socket2::Type::STREAM,
                    None,
                )
            }
        };

        let socket = socket2::Socket::new(domain, socket_type, protocol)
            .wrap_err_with(|| format!("Failed to create socket for connection: {:?}", self.conn))?;

        socket
            .set_nonblocking(true)
            .wrap_err("Failed to set socket to nonblocking mode")?;

        socket
            .set_keepalive(true)
            .wrap_err("Failed to set keep‑alive on socket")?;

        Ok((socket, socket_addr))
    }
}

impl RequestBuilder {
    pub fn get(uri: &str) -> Result<HeaderBuilder> {
        let url = Url::parse(uri).wrap_err("url parsing")?;

        let mut v = Vec::new();
        v.extend_from_slice("GET ".as_bytes());

        let conn = match url.scheme() {
            // pub fn default_port(scheme: &str) -> Option<u16> {
            //     match scheme {
            //         "http" | "ws" => Some(80),
            //         "https" | "wss" => Some(443),
            //         "ftp" => Some(21),
            //         _ => None,
            //     }
            // }
            "http" | "https" => {
                v.extend_from_slice(url.path().as_bytes());
                if let Some(query) = url.query() {
                    v.extend_from_slice("?".as_bytes());
                    v.extend_from_slice(query.as_bytes());
                }
                v.extend_from_slice(" HTTP/1.1\r\nHost: ".as_bytes());
                let host = url.host_str().expect("http always has host").to_string();
                v.extend_from_slice(host.as_bytes());
                if let Some(port) = url.port()
                    && port != 80
                {
                    v.extend_from_slice(format!(":{}", port).as_bytes());
                }
                v.extend_from_slice("\r\n".as_bytes());

                let scheme = match url.scheme() {
                    "http" => ConnScheme::Http,
                    "https" => ConnScheme::Https,
                    _ => unreachable!(),
                };

                Conn::Tcp {
                    host,
                    port: url.port(),
                    scheme,
                }
            }
            "unix" => {
                let socket_path = match url.path().split_once("//") {
                    None => {
                        // just the socket path, then use / for resource path
                        v.extend_from_slice("/".as_bytes());
                        String::from(url.path())
                    }
                    Some((socket_path, resource_path)) => {
                        v.extend_from_slice("/".as_bytes());
                        v.extend_from_slice(resource_path.as_bytes());
                        String::from(socket_path)
                    }
                };
                ensure!(!url.has_host(), "uds should not have host");
                v.extend_from_slice(" HTTP/1.1\r\nHost: localhost\r\n".as_bytes());

                Conn::Uds { path: socket_path }
            }
            scheme => {
                bail!("{} not supported", scheme);
            }
        };
        Ok(HeaderBuilder {
            data: v,
            conn,
            _stage: PhantomData,
        })
    }
}

impl HeaderBuilder {
    fn is_valid_header_name(name: &str) -> bool {
        // Per RFC 7230, section 3.2.6
        // token = 1*tchar
        // tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA
        name.chars().all(|c| {
            matches!(c,
                '!' | '#' | '$' | '%' | '&' | '\'' | '*' | '+' | '-' | '.' |
                '^' | '_' | '`' | '|' | '~' |
                '0'..='9' | 'a'..='z' | 'A'..='Z'
            )
        }) && !name.is_empty()
    }

    fn is_valid_header_value(value: &str) -> bool {
        // RFC 7230: header value must not contain CR or LF,
        // though other whitespace is allowed
        !value.contains('\r') && !value.contains('\n')
    }

    pub fn append_header(self, key: &str, value: &str) -> Result<Self> {
        ensure!(
            Self::is_valid_header_name(key),
            "{} is not valid header name",
            key
        );
        ensure!(
            Self::is_valid_header_value(value),
            "{} is not valid header value",
            value
        );
        self.append_header_unchecked(key, value)
    }

    pub fn append_header_unchecked(mut self, key: &str, value: &str) -> Result<Self> {
        self.data.extend_from_slice(key.as_bytes());
        self.data.extend_from_slice(": ".as_bytes());
        self.data.extend_from_slice(value.as_bytes());
        self.data.extend_from_slice("\r\n".as_bytes());
        Ok(self)
    }

    #[allow(dead_code)]
    pub fn build_with_body(mut self, body: &[u8]) -> Request {
        self.data
            .extend_from_slice(format!("Content-Length: {}\r\n\r\n", body.len()).as_bytes());

        self.data.extend_from_slice(body);

        Request {
            data: Pin::new(self.data.into_boxed_slice()),
            conn: self.conn,
        }
    }

    pub fn build_without_body(mut self) -> Request {
        self.data.extend_from_slice("\r\n".as_bytes());

        Request {
            data: Pin::new(self.data.into_boxed_slice()),
            conn: self.conn,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tcp_http_request() {
        let builder = RequestBuilder::get("http://example.com/foo/bar").unwrap();

        // Convert request bytes to string for easier testing
        let req_str = String::from_utf8_lossy(&builder.data);

        // The path and host must be correct
        assert!(req_str.starts_with("GET /foo/bar HTTP/1.1\r\nHost: example.com\r\n"));
    }

    #[test]
    fn test_unix_socket_request() {
        let sock_path = "/tmp/my.sock";
        // The "unix" URL scheme is nonstandard; path is after the triple slash
        let builder = RequestBuilder::get(&format!("unix://{}", sock_path)).unwrap();

        match &builder.conn {
            Conn::Uds { path } => assert_eq!(path, "/tmp/my.sock"),
            _ => panic!("Expected UDS connection"),
        }
        let req_str = String::from_utf8_lossy(&builder.data);
        assert!(req_str.starts_with("GET / HTTP/1.1\r\nHost: localhost\r\n"));
    }

    #[test]
    fn test_unix_socket_request_resource() {
        let sock_path = "/tmp/my.sock";
        let resource_path = "/movies/1";
        // The "unix" URL scheme is nonstandard; path is after the triple slash
        let builder =
            RequestBuilder::get(&format!("unix://{}/{}", sock_path, resource_path)).unwrap();

        match &builder.conn {
            Conn::Uds { path } => assert_eq!(path, "/tmp/my.sock"),
            _ => panic!("Expected UDS connection"),
        }
        let req_str = String::from_utf8_lossy(&builder.data);
        assert!(req_str.starts_with(&format!(
            "GET {} HTTP/1.1\r\nHost: localhost\r\n",
            resource_path
        )));
    }

    #[test]
    fn test_non_supported_scheme() {
        let res = RequestBuilder::get("ftp://example.com/x");
        assert!(res.is_err());
    }

    #[test]
    fn test_uds_with_host_error() {
        // UDS with host (invalid usage)
        let res = RequestBuilder::get("unix://host/tmp/my.sock");
        assert!(res.is_err());
    }

    #[test]
    fn test_tcp_http_request_with_port_default() {
        let builder = RequestBuilder::get("http://example.com:80/foo/bar").unwrap();

        let req_str = String::from_utf8_lossy(&builder.data);
        assert!(req_str.starts_with("GET /foo/bar HTTP/1.1\r\nHost: example.com\r\n"));
    }

    #[test]
    fn test_tcp_http_request_with_port() {
        let builder = RequestBuilder::get("http://example.com:8080/foo/bar").unwrap();

        let req_str = String::from_utf8_lossy(&builder.data);
        assert!(req_str.starts_with("GET /foo/bar HTTP/1.1\r\nHost: example.com:8080\r\n"));
    }

    #[test]
    fn test_tcp_http_request_root_path() {
        let builder = RequestBuilder::get("http://example.com/").unwrap();
        let req_str = String::from_utf8_lossy(&builder.data);
        assert!(req_str.starts_with("GET / HTTP/1.1\r\nHost: example.com\r\n"));
    }

    #[test]
    fn test_unix_socket_request_complex_resource() {
        let sock_path = "/tmp/my.sock";
        let resource_path = "/movies//1"; // Contains double slash
        let builder =
            RequestBuilder::get(&format!("unix://{}/{}", sock_path, resource_path)).unwrap();

        match &builder.conn {
            Conn::Uds { path } => assert_eq!(path, "/tmp/my.sock"),
            _ => panic!("Expected UDS connection"),
        }
        let req_str = String::from_utf8_lossy(&builder.data);
        assert!(req_str.starts_with(&format!(
            "GET {} HTTP/1.1\r\nHost: localhost\r\n",
            resource_path
        )));
    }

    #[test]
    fn test_invalid_url() {
        let res = RequestBuilder::get("not-a-url");
        assert!(res.is_err());
    }

    #[test]
    fn test_append_single_header() {
        let request = RequestBuilder::get("http://example.com/foo")
            .unwrap()
            .append_header("Content-Type", "application/json")
            .unwrap()
            .build_without_body();
        let req_str = String::from_utf8_lossy(&request.data);
        assert!(req_str.contains("Content-Type: application/json\r\n"));
    }

    #[test]
    fn test_append_multiple_headers() {
        let request = RequestBuilder::get("http://example.com/foo")
            .unwrap()
            .append_header("Content-Type", "application/json")
            .unwrap()
            .append_header("Accept", "application/json")
            .unwrap()
            .build_without_body();
        let req_str = String::from_utf8_lossy(&request.data);
        assert!(req_str.contains("Content-Type: application/json\r\n"));
        assert!(req_str.contains("Accept: application/json\r\n"));
    }

    #[test]
    fn test_append_invalid_header_name() {
        let res = RequestBuilder::get("http://example.com/foo")
            .unwrap()
            .append_header("Invalid Name", "value");
        assert!(res.is_err());

        let res_empty = RequestBuilder::get("http://example.com/foo")
            .unwrap()
            .append_header("", "value");
        assert!(res_empty.is_err());
    }

    #[test]
    fn test_append_invalid_header_value() {
        let res = RequestBuilder::get("http://example.com/foo")
            .unwrap()
            .append_header("Name", "value\r\n");
        assert!(res.is_err());
    }

    #[test]
    fn test_build_with_body() {
        let body = "{\"key\":\"value\"}";
        let request = RequestBuilder::get("http://example.com/foo")
            .unwrap()
            .build_with_body(body.as_bytes());

        let req_str = String::from_utf8_lossy(&request.data);
        assert!(req_str.ends_with(body));
        assert!(req_str.contains(&format!("Content-Length: {}\r\n", body.len())));
    }

    #[test]
    fn test_build_with_empty_body() {
        let body = "";
        let request = RequestBuilder::get("http://example.com/foo")
            .unwrap()
            .build_with_body(body.as_bytes());

        let req_str = String::from_utf8_lossy(&request.data);
        assert!(req_str.ends_with("\r\n\r\n")); // Should have headers and then empty body
        assert!(req_str.contains("Content-Length: 0\r\n"));
    }

    #[test]
    fn test_build_without_body() {
        let request = RequestBuilder::get("http://example.com/foo")
            .unwrap()
            .build_without_body();

        let req_str = String::from_utf8_lossy(&request.data);
        assert!(req_str.ends_with("\r\n\r\n"));
        assert!(!req_str.contains("Content-Length:"));
    }

    #[test]
    fn test_header_name_valid_special_characters() {
        // Test all valid special characters from RFC 7230
        let valid_chars =
            "!#$%&'*+-.^_`|~0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        let request = RequestBuilder::get("http://example.com/foo")
            .unwrap()
            .append_header(valid_chars, "test-value")
            .unwrap()
            .build_without_body();

        let req_str = String::from_utf8_lossy(&request.data);
        assert!(req_str.contains(&format!("{}: test-value\r\n", valid_chars)));
    }

    #[test]
    fn test_header_name_invalid_characters() {
        let invalid_names = vec![
            "name with space",
            "name\twith\ttab",
            "name@with@at",
            "name(with)parens",
            "name[with]brackets",
            "name{with}braces",
            "name\"with\"quotes",
            "name\\with\\backslash",
            "name/with/slash",
            "name:with:colon",
            "name;with;semicolon",
            "name<with>angles",
            "name=with=equals",
            "name?with?question",
        ];

        for invalid_name in invalid_names {
            let res = RequestBuilder::get("http://example.com/foo")
                .unwrap()
                .append_header(invalid_name, "value");
            assert!(
                res.is_err(),
                "Expected error for header name: {}",
                invalid_name
            );
        }
    }

    #[test]
    fn test_header_value_individual_control_characters() {
        // Test individual \r and \n characters
        let res_cr = RequestBuilder::get("http://example.com/foo")
            .unwrap()
            .append_header("Name", "value\rafter");
        assert!(res_cr.is_err());

        let res_lf = RequestBuilder::get("http://example.com/foo")
            .unwrap()
            .append_header("Name", "value\nafter");
        assert!(res_lf.is_err());
    }

    #[test]
    fn test_header_value_valid_whitespace() {
        // Other whitespace should be valid
        let request = RequestBuilder::get("http://example.com/foo")
            .unwrap()
            .append_header("Name", "value with spaces\tand\ttabs")
            .unwrap()
            .build_without_body();

        let req_str = String::from_utf8_lossy(&request.data);
        assert!(req_str.contains("Name: value with spaces\tand\ttabs\r\n"));
    }

    #[test]
    fn test_url_with_query_parameters() {
        let builder = RequestBuilder::get("http://example.com/search?q=test&limit=10").unwrap();
        let req_str = String::from_utf8_lossy(&builder.data);
        assert!(
            req_str.starts_with("GET /search?q=test&limit=10 HTTP/1.1\r\nHost: example.com\r\n")
        );
    }

    #[test]
    fn test_url_with_fragment() {
        // Fragments should be ignored in HTTP requests
        let builder = RequestBuilder::get("http://example.com/page#section1").unwrap();
        let req_str = String::from_utf8_lossy(&builder.data);
        assert!(req_str.starts_with("GET /page HTTP/1.1\r\nHost: example.com\r\n"));
    }

    #[test]
    fn test_url_with_query_and_fragment() {
        let builder = RequestBuilder::get("http://example.com/search?q=test#results").unwrap();
        let req_str = String::from_utf8_lossy(&builder.data);
        assert!(req_str.starts_with("GET /search?q=test HTTP/1.1\r\nHost: example.com\r\n"));
    }

    #[test]
    fn test_tcp_connection_values() {
        let builder = RequestBuilder::get("http://example.com:8080/foo").unwrap();

        match &builder.conn {
            Conn::Tcp {
                host,
                port,
                scheme: _,
            } => {
                // Check that host_range points to the correct part of the data
                assert_eq!(host.as_str(), "example.com");
                assert_eq!(*port, Some(8080));
            }
            _ => panic!("Expected TCP connection"),
        }
    }

    #[test]
    fn test_tcp_connection_default_port() {
        let builder = RequestBuilder::get("http://example.com/foo").unwrap();

        match &builder.conn {
            Conn::Tcp { port, .. } => {
                assert_eq!(*port, None); // url.port() returns None for default port
            }
            _ => panic!("Expected TCP connection"),
        }
    }

    #[test]
    fn test_unix_socket_edge_case_paths() {
        // Test various edge cases for unix socket paths
        let test_cases = vec![
            ("unix:///var/run/socket.sock", "/var/run/socket.sock", "/"),
            ("unix:///tmp/app.sock//api/v1", "/tmp/app.sock", "/api/v1"),
            (
                "unix:///home/user/.socket//very//long//path",
                "/home/user/.socket",
                "/very//long//path",
            ),
        ];

        for (url, expected_socket, expected_resource) in test_cases {
            let builder = RequestBuilder::get(url).unwrap();

            match &builder.conn {
                Conn::Uds { path } => assert_eq!(path, expected_socket),
                _ => panic!("Expected UDS connection for {}", url),
            }

            let req_str = String::from_utf8_lossy(&builder.data);
            assert!(req_str.starts_with(&format!(
                "GET {} HTTP/1.1\r\nHost: localhost\r\n",
                expected_resource
            )));
        }
    }

    #[test]
    fn test_malformed_urls() {
        let malformed_urls = vec![
            "http://",                // Missing host
            "ftp://example.com/file", // Unsupported scheme
            "://example.com",         // Missing scheme
            "http://[invalid-ipv6",   // Malformed IPv6
        ];

        for url in malformed_urls {
            let res = RequestBuilder::get(url);
            assert!(res.is_err(), "Expected error for malformed URL: {}", url);
        }
    }

    #[test]
    fn test_complete_request_flow() {
        // Test a complete request with headers and body
        let body = r#"{"user": "test", "action": "login"}"#;
        let request = RequestBuilder::get("http://api.example.com:3000/auth")
            .unwrap()
            .append_header("Content-Type", "application/json")
            .unwrap()
            .append_header("User-Agent", "concuring/0.1")
            .unwrap()
            .append_header("Accept", "application/json")
            .unwrap()
            .build_with_body(body.as_bytes());

        let req_str = String::from_utf8_lossy(&request.data);

        // Verify all components are present
        assert!(req_str.starts_with("GET /auth HTTP/1.1\r\nHost: api.example.com:3000\r\n"));
        assert!(req_str.contains("Content-Type: application/json\r\n"));
        assert!(req_str.contains("User-Agent: concuring/0.1\r\n"));
        assert!(req_str.contains("Accept: application/json\r\n"));
        assert!(req_str.contains(&format!("Content-Length: {}\r\n", body.len())));
        assert!(req_str.ends_with(body));

        // Ensure proper HTTP structure
        assert!(req_str.contains("\r\n\r\n")); // Headers end marker
    }
}