sib 0.0.17

A high-performance, secure, and cross-platform modules optimized for efficiency, scalability, and reliability.
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
use crate::network::http::server::H2Config;
use tracing::error;

cfg_if::cfg_if! {
    // Glommio runtime (Linux)
    if #[cfg(all(target_os = "linux", feature = "rt-glommio", not(feature = "rt-tokio")))] {

        use core::pin::Pin;
        use core::task::{Context, Poll};

        struct IoStream<S>(pub S);

        // Adapt glommio's AsyncRead/AsyncWrite to the tokio::io traits
        // that h2 expects.
        impl<S: futures_lite::io::AsyncRead + Unpin> tokio::io::AsyncRead for IoStream<S> {
            fn poll_read(
                mut self: Pin<&mut Self>,
                cx: &mut Context<'_>,
                buf: &mut tokio::io::ReadBuf<'_>,
            ) -> Poll<std::io::Result<()>> {
                let unfilled = buf.initialize_unfilled();
                match Pin::new(&mut self.0).poll_read(cx, unfilled) {
                    Poll::Ready(Ok(n)) => {
                        unsafe { buf.assume_init(n) };
                        buf.advance(n);
                        Poll::Ready(Ok(()))
                    }
                    Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
                    Poll::Pending => Poll::Pending,
                }
            }
        }

        impl<S: futures_lite::io::AsyncWrite + Unpin> tokio::io::AsyncWrite for IoStream<S> {
            fn poll_write(
                mut self: Pin<&mut Self>,
                cx: &mut Context<'_>,
                data: &[u8],
            ) -> Poll<std::io::Result<usize>> {
                Pin::new(&mut self.0).poll_write(cx, data)
            }

            fn poll_flush(
                mut self: Pin<&mut Self>,
                cx: &mut Context<'_>,
            ) -> Poll<std::io::Result<()>> {
                Pin::new(&mut self.0).poll_flush(cx)
            }

            fn poll_shutdown(
                mut self: Pin<&mut Self>,
                cx: &mut Context<'_>,
            ) -> Poll<std::io::Result<()>> {
                Pin::new(&mut self.0).poll_close(cx)
            }
        }

        pub(crate) async fn serve_h2<S, T>(
            stream: S,
            service: T,
            config: &H2Config,
            peer_addr: std::net::IpAddr,
        ) -> std::io::Result<()>
        where
            S: futures_lite::io::AsyncRead + futures_lite::io::AsyncWrite + Unpin + 'static,
            T: crate::network::http::session::HAsyncService + Send + 'static,
        {
            use crate::network::http::h2_session::H2Session;

            let builder = make_h2_server_builder(config);
            let mut conn: h2::server::Connection<IoStream<S>, bytes::Bytes> = builder
                .handshake(IoStream(stream))
                .await
                .map_err(|e| std::io::Error::other(format!("h2 handshake error: {e}")))?;

            // Per-connection service shared among streams
            let svc = std::rc::Rc::new(std::cell::RefCell::new(Some(service)));

            while let Some(r) = conn.accept().await {
                let (request, respond) = match r {
                    Ok(x) => x,
                    Err(e) => {
                        if e.is_io() {
                            // connection-level IO error, just stop this conn
                            return Ok(());
                        }
                        break;
                    }
                };

                let svc_rc = std::rc::Rc::clone(&svc);

                glommio::spawn_local(async move {
                    let mut service = loop {
                        if let Some(s) = {
                            let mut guard = svc_rc.borrow_mut();
                            guard.take()
                        } {
                            break s;
                        }
                        glommio::yield_if_needed().await;
                    };

                    // run the service on this H2 stream
                    let result = service
                        .call(&mut H2Session::new(peer_addr, request, respond))
                        .await;

                    // put service back for the next stream
                    *svc_rc.borrow_mut() = Some(service);

                    if let Err(e) = result {
                        error!("h2 service error: {e}");
                    }
                })
                .detach();

                glommio::yield_if_needed().await;
            }

            Ok(())
        }

        pub(crate) async fn serve_h1<S, T>(
            mut stream: S,
            _service: T,
            config: &H2Config,
            _peer_addr: std::net::IpAddr,
        ) -> std::io::Result<()>
        where
            S: futures_lite::io::AsyncRead + futures_lite::io::AsyncWrite + Unpin + 'static,
            T: crate::network::http::session::HAsyncService + Send + 'static,
        {
            use futures_lite::{AsyncReadExt, AsyncWriteExt};
            use std::str;

            let mut buf = vec![0u8; 8192];
            let mut read = 0usize;

            loop {
                let n = stream.read(&mut buf[read..]).await?;
                if n == 0 {
                    return Err(std::io::Error::new(
                        std::io::ErrorKind::UnexpectedEof,
                        "connection closed before full request",
                    ));
                }
                read += n;
                if buf[..read].windows(4).any(|w| w == b"\r\n\r\n") {
                    break;
                }
                if read == buf.len() {
                    buf.resize(buf.len() * 2, 0);
                }
            }

            // Parse request line + headers (minimal)
            let mut headers = [httparse::EMPTY_HEADER; 32];
            let mut req = httparse::Request::new(&mut headers);
            let status = req.parse(&buf[..read]).map_err(|e| {
                std::io::Error::other(format!("httparse error: {e}"))
            })?;

            let header_len = match status {
                httparse::Status::Complete(len) => len,
                httparse::Status::Partial => {
                    return Err(std::io::Error::other("partial HTTP request"));
                }
            };

            let method = req.method.unwrap_or("GET");
            let path = req.path.unwrap_or("/");
            let version_dbg = match req.version {
                Some(0) => "HTTP/1.0",
                _ => "HTTP/1.1",
            };

            let host = req
                .headers
                .iter()
                .find(|h| h.name.eq_ignore_ascii_case("host"))
                .and_then(|h| str::from_utf8(h.value).ok())
                .unwrap_or("");

            let content_length = req
                .headers
                .iter()
                .find(|h| h.name.eq_ignore_ascii_case("content-length"))
                .and_then(|h| str::from_utf8(h.value).ok())
                .and_then(|s| s.parse::<usize>().ok())
                .unwrap_or(0);

            // Read body if present
            let mut body = buf[header_len..read].to_vec();
            while body.len() < content_length {
                let mut chunk = vec![0u8; content_length - body.len()];
                let n = stream.read(&mut chunk).await?;
                if n == 0 {
                    break;
                }
                body.extend_from_slice(&chunk[..n]);
            }

            let body_str = String::from_utf8_lossy(&body);

            let response_body = format!(
                "Http version: {version_dbg:?}, Echo: {method:?} {host:?} {path:?}\r\nBody: {body_str:?}"
            );

            let headers = format!(
                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nContent-Type: text/plain\r\nConnection: {}\r\n\r\n",
                response_body.len(),
                if config.keep_alive { "keep-alive" } else { "close" },
            );

            stream.write_all(headers.as_bytes()).await?;
            stream.write_all(response_body.as_bytes()).await?;
            stream.flush().await?;

            Ok(())
        }
    }
    else if #[cfg(all(feature = "rt-tokio", not(feature = "rt-glommio")))] {

        pub(crate) async fn serve_h1<S, T>(
            mut stream: S,
            mut service: T,
            config: &H2Config,
            peer_addr: std::net::IpAddr,
            shutdown: tokio_util::sync::CancellationToken,
        ) -> std::io::Result<()>
        where
            S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + 'static,
            T: crate::network::http::session::HAsyncService + 'static,
        {
            use crate::network::http::h1_session_async::H1SessionAsync;
            use bytes::Bytes;
            use http::{header, HeaderMap, HeaderName, HeaderValue, Method, Uri, Version};
            use tokio::io::AsyncReadExt;

            let mut buf: Vec<u8> = vec![0u8; 8192];

            loop {
                // Check for shutdown before each new request
                if shutdown.is_cancelled() {
                    return Ok(());
                }

                // read headers
                let mut read: usize = 0;
                loop {
                    let n = tokio::select! {
                        _ = shutdown.cancelled() => return Ok(()),
                        r = stream.read(&mut buf[read..]) => r?
                    };
                    if n == 0 {
                        return Ok(());
                    }
                    read += n;

                    if buf[..read].windows(4).any(|w| w == b"\r\n\r\n") {
                        break;
                    }
                    if read == buf.len() {
                        buf.resize(buf.len() * 2, 0);
                    }
                }

                // parse request line + headers
                let mut headers = [httparse::EMPTY_HEADER; 64];
                let mut req = httparse::Request::new(&mut headers);

                let status = req
                    .parse(&buf[..read])
                    .map_err(|e| std::io::Error::other(format!("httparse error: {e}")))?;

                let header_len = match status {
                    httparse::Status::Complete(len) => len,
                    httparse::Status::Partial => return Err(std::io::Error::other("partial HTTP request")),
                };

                let method = req
                    .method
                    .map(|m| Method::from_bytes(m.as_bytes()).unwrap_or(Method::GET))
                    .unwrap_or(Method::GET);

                let uri = req
                    .path
                    .and_then(|p| p.parse::<Uri>().ok())
                    .unwrap_or_else(|| Uri::from_static("/"));

                let version = match req.version {
                    Some(0) => Version::HTTP_10,
                    _ => Version::HTTP_11,
                };

                let mut req_headers = HeaderMap::new();
                for h in req.headers.iter() {
                    let name = HeaderName::from_bytes(h.name.as_bytes()).map_err(std::io::Error::other)?;
                    let value = HeaderValue::from_bytes(h.value).map_err(std::io::Error::other)?;
                    req_headers.append(name, value);
                }

                // keep-alive decision
                let conn_hdr = req_headers
                    .get(header::CONNECTION)
                    .and_then(|v| v.to_str().ok())
                    .unwrap_or("")
                    .to_ascii_lowercase();

                let keep_alive = if version == Version::HTTP_11 {
                    conn_hdr != "close"
                } else {
                    conn_hdr == "keep-alive"
                };

                // WS detection BEFORE session creation
                #[cfg(feature = "net-ws-server")]
                let is_ws = crate::network::http::ws::is_h1_ws_upgrade(&method, &req_headers);

                #[cfg(not(feature = "net-ws-server"))]
                let is_ws = false;

                // If WS upgrade: DO NOT read body (service will do ws_accept + ws loop).
                let body_bytes = if is_ws {
                    Bytes::new()
                } else {
                    let content_length = req_headers
                        .get(header::CONTENT_LENGTH)
                        .and_then(|v| v.to_str().ok())
                        .and_then(|s| s.parse::<usize>().ok())
                        .unwrap_or(0);

                    if content_length > config.max_frame_size as usize {
                        return Err(std::io::Error::other("content-length exceeds max frame size"));
                    }

                    let mut body: Vec<u8> = Vec::with_capacity(content_length);
                    body.extend_from_slice(&buf[header_len..read]);

                    while body.len() < content_length {
                        let need = content_length - body.len();
                        let mut tmp = vec![0u8; need.min(64 * 1024)];
                        let n = stream.read(&mut tmp).await?;
                        if n == 0 {
                            break;
                        }
                        body.extend_from_slice(&tmp[..n]);
                    }

                    Bytes::from(body)
                };

                // create session with is_ws
                let mut session = H1SessionAsync::new(
                    peer_addr,
                    &mut stream,
                    (method,version),
                    uri,
                    (req_headers, body_bytes),
                    keep_alive,
                    is_ws
                );

                #[cfg(feature = "net-ws-server")]
                if is_ws && read > header_len {
                    session.ws_seed(&buf[header_len..read]);
                }

                // delegate to service (service does ws_accept + ws loop if is_ws)
                use crate::network::http::session::Session;

                let r = service.call(&mut session).await;

                if is_ws {
                    // Service owns the socket now; it will run WS loop and end.
                    // If service uses ConnectionAborted("ws done") to signal end, treat it as normal.
                    return match r {
                        Ok(()) => Ok(()),
                        Err(e) if e.kind() == std::io::ErrorKind::ConnectionAborted => Ok(()),
                        Err(e) => Err(e),
                    };
                }

                // Normal HTTP error handling
                if let Err(e) = r {
                    error!("h1 service error: {e}");
                    if !session.response_sent() {
                        let _ = session
                            .status_code(http::StatusCode::INTERNAL_SERVER_ERROR)
                            .body(Bytes::new())
                            .eom_async()
                            .await;
                    }
                } else if !session.response_sent() {
                    let _ = session
                        .status_code(http::StatusCode::OK)
                        .body(Bytes::new())
                        .eom_async()
                        .await;
                }

                if !session.keep_alive() {
                    return Ok(());
                }
            }
        }

        pub(crate) async fn serve_h2<S, T>(
            stream: S,
            service: T,
            config: &H2Config,
            peer_addr: std::net::IpAddr,
            shutdown: tokio_util::sync::CancellationToken,
        ) -> std::io::Result<()>
        where
            S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + 'static,
            T: crate::network::http::session::HAsyncService + 'static,
        {
            use crate::network::http::h2_session::H2Session;

            // make h2 server builder
            let builder = make_h2_server_builder(config);

            // Handshake H2 connection
            let mut conn = tokio::select! {
                _ = shutdown.cancelled() => return Ok(()),
                r = builder.handshake(stream) => r
            }
            .map_err(|e| std::io::Error::other(format!("h2 handshake error: {e}")))?;

            // One service instance per connection, shared across streams on this conn
            let svc = std::rc::Rc::new(std::cell::RefCell::new(Some(service)));

            // Serve multiplexed requests
            loop {
                if shutdown.is_cancelled() {
                    return Ok(());
                }
                let svc_rc = std::rc::Rc::clone(&svc);

                let next = tokio::select! {
                    _ = shutdown.cancelled() => return Ok(()),
                    r = conn.accept() => r
                };

                match next {
                    Some(Ok((request, respond))) => {
                        // Each H2 stream runs on the same LocalSet thread
                        tokio::task::spawn_local(async move {
                            let mut service = loop {
                                if let Some(s) = {
                                    let mut guard = svc_rc.borrow_mut();
                                    guard.take()
                                } {
                                    break s;
                                }
                                tokio::task::yield_now().await;
                            };

                            let result = service
                                .call(&mut H2Session::new(peer_addr, request, respond))
                                .await;

                            *svc_rc.borrow_mut() = Some(service);

                            if let Err(e) = result {
                                error!("h2 service error: {e}");
                            }
                        });
                    }
                    Some(Err(e)) => {
                        error!("accept stream error from {peer_addr}: {e}");
                        break;
                    }
                    None => break, // connection closed
                }
            }
            Ok(())
        }
    }
}

fn make_h2_server_builder(config: &H2Config) -> h2::server::Builder {
    let mut builder = h2::server::Builder::new();
    if config.enable_connect_protocol {
        builder.enable_connect_protocol();
    }
    builder
        .initial_connection_window_size(config.initial_connection_window_size)
        .initial_window_size(config.initial_window_size)
        .max_concurrent_streams(config.max_concurrent_streams)
        .max_frame_size(config.max_frame_size)
        .max_header_list_size(config.max_header_list_size);
    builder
}