harrow-server-monoio 0.10.0

Experimental monoio-based HTTP/1.1 server for Harrow
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
//! HTTP/2 protocol implementation using monoio-http.
//!
//! This module provides HTTP/2 support via the monoio-http crate, which offers
//! native io_uring-based HTTP/2 with multiplexed streams and flow control.
//!
//! # Key Features
//!
//! - **Multiplexing**: Multiple concurrent streams per connection
//! - **Flow Control**: HTTP/2 window-based flow control  
//! - **Prior Knowledge**: Direct H2 connections without ALPN
//!
//! # Architecture
//!
//! ```text
//! ┌──────────────────────────────────────────┐
//! │           H2Connection                    │
//! │  ┌──────────────────────────────────┐   │
//! │  │  monoio_http::h2::server         │   │
//! │  │  (connection driver)             │   │
//! │  └──────────┬───────────────────────┘   │
//! │             │                            │
//! │             ▼                            │
//! │  ┌──────────────────────────────────┐   │
//! │  │     Stream Handler Tasks         │   │
//! │  │  ┌─────┐ ┌─────┐ ┌─────┐        │   │
//! │  │  │ S1  │ │ S2  │ │ S3  │ ...    │   │
//! │  │  └──┬──┘ └──┬──┘ └──┬──┘        │   │
//! │  └─────┼───────┼───────┼───────────┘   │
//! │        │       │       │                │
//! │        ▼       ▼       ▼                │
//! │  ┌──────────────────────────────────┐   │
//! │  │   Harrow Dispatch (per-stream)   │   │
//! │  └──────────────────────────────────┘   │
//! └──────────────────────────────────────────┘
//! ```

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::{Duration, Instant};

use bytes::Bytes;
use monoio::net::TcpStream;

use harrow_core::dispatch::{SharedState, dispatch};
use harrow_core::request::Body;
use harrow_core::response::Response;

use crate::o11y::ConnectionMetrics;
use crate::protocol::ProtocolError;

/// Configuration for H2 connections.
pub(crate) struct H2Config {
    /// Shared application state.
    pub shared: Arc<SharedState>,
    /// Timeout for reading request headers.
    pub header_read_timeout: Option<Duration>,
    /// Timeout for reading request bodies.
    pub body_read_timeout: Option<Duration>,
    /// Maximum lifetime of a single connection.
    pub connection_timeout: Option<Duration>,
    /// Maximum concurrent streams allowed on this H2 connection.
    pub max_concurrent_streams: u32,
    /// Connection metrics tracker.
    pub metrics: ConnectionMetrics,
}

/// HTTP/2 connection handler.
///
/// Manages a single HTTP/2 connection with support for multiple
/// concurrent streams. Uses monoio-http's H2 implementation.
pub(crate) struct H2Connection {
    stream: TcpStream,
    config: H2Config,
}

struct ActiveStreamGuard {
    active_streams: Arc<AtomicUsize>,
}

impl ActiveStreamGuard {
    fn new(active_streams: Arc<AtomicUsize>) -> Self {
        active_streams.fetch_add(1, Ordering::AcqRel);
        Self { active_streams }
    }
}

impl Drop for ActiveStreamGuard {
    fn drop(&mut self) {
        self.active_streams.fetch_sub(1, Ordering::AcqRel);
    }
}

impl H2Connection {
    /// Create a new H2 connection handler.
    pub(crate) fn new(stream: TcpStream, config: H2Config) -> Self {
        Self { stream, config }
    }

    /// Run the HTTP/2 connection to completion.
    ///
    /// This drives the HTTP/2 connection state machine, accepting streams
    /// and spawning tasks to handle each request concurrently.
    pub(crate) async fn run(self) -> Result<(), Box<dyn std::error::Error>> {
        let H2Connection { stream, config } = self;
        let H2Config {
            shared,
            header_read_timeout,
            body_read_timeout,
            connection_timeout,
            max_concurrent_streams,
            mut metrics,
        } = config;
        let metrics_id = metrics.id;
        let connection_deadline =
            connection_timeout.and_then(|timeout| Instant::now().checked_add(timeout));

        // Build H2 server with default configuration
        let mut builder = monoio_http::h2::server::Builder::new();
        builder.max_concurrent_streams(max_concurrent_streams);

        // Perform HTTP/2 handshake
        let handshake_timeout = effective_timeout(header_read_timeout, connection_deadline);
        let mut connection = if let Some(timeout) = handshake_timeout {
            match monoio::select! {
                result = builder.handshake(stream) => Ok(result),
                _ = monoio::time::sleep(timeout) => Err(()),
            } {
                Ok(result) => result.map_err(|e| format!("h2 handshake failed: {}", e))?,
                Err(()) => {
                    if deadline_expired(connection_deadline) {
                        tracing::debug!(
                            connection.id = metrics_id,
                            "h2 connection timeout during handshake"
                        );
                    } else {
                        tracing::debug!(
                            connection.id = metrics_id,
                            "h2 header read timeout during handshake"
                        );
                    }
                    let _duration = metrics.close();
                    return Ok(());
                }
            }
        } else {
            builder
                .handshake(stream)
                .await
                .map_err(|e| format!("h2 handshake failed: {}", e))?
        };

        tracing::debug!(connection.id = metrics_id, "h2 connection established");

        let active_streams = Arc::new(AtomicUsize::new(0));

        // Accept incoming streams
        loop {
            let accept_timeout = effective_timeout(header_read_timeout, connection_deadline);

            let accept_result = if let Some(timeout) = accept_timeout {
                match monoio::select! {
                    result = connection.accept() => Ok(result),
                    _ = monoio::time::sleep(timeout) => Err(()),
                } {
                    Ok(result) => result,
                    Err(()) => {
                        if deadline_expired(connection_deadline) {
                            tracing::debug!(connection.id = metrics_id, "h2 connection timeout");
                            break;
                        } else if active_streams.load(Ordering::Acquire) == 0 {
                            tracing::debug!(connection.id = metrics_id, "h2 header read timeout");
                            break;
                        }
                        continue;
                    }
                }
            } else {
                connection.accept().await
            };

            match accept_result {
                Some(Ok((request, respond))) => {
                    // Spawn a task to handle this stream
                    let shared = Arc::clone(&shared);
                    let max_body = shared.max_body_size;
                    let active_streams = Arc::clone(&active_streams);
                    let active_stream = ActiveStreamGuard::new(active_streams);

                    monoio::spawn(async move {
                        let _active_stream = active_stream;
                        if let Err(e) =
                            handle_stream(request, respond, shared, max_body, body_read_timeout)
                                .await
                        {
                            tracing::debug!(
                                connection.id = metrics_id,
                                error = %e,
                                "h2 stream error"
                            );
                        }
                    });
                }
                Some(Err(e)) => {
                    tracing::debug!(
                        connection.id = metrics_id,
                        error = %e,
                        "h2 accept error"
                    );
                    // Continue accepting other streams - one bad stream doesn't kill the connection
                }
                None => {
                    tracing::debug!(connection.id = metrics_id, "h2 connection closed by peer");
                    break;
                }
            }
        }

        // Record connection close
        let _duration = metrics.close();

        Ok(())
    }
}

fn effective_timeout(
    timeout: Option<Duration>,
    connection_deadline: Option<Instant>,
) -> Option<Duration> {
    match (timeout, remaining_until(connection_deadline)) {
        (Some(timeout), Some(remaining)) => Some(timeout.min(remaining)),
        (Some(timeout), None) => Some(timeout),
        (None, Some(remaining)) => Some(remaining),
        (None, None) => None,
    }
}

fn remaining_until(deadline: Option<Instant>) -> Option<Duration> {
    deadline.map(|deadline| deadline.saturating_duration_since(Instant::now()))
}

fn deadline_expired(deadline: Option<Instant>) -> bool {
    deadline.is_some_and(|deadline| Instant::now() >= deadline)
}

/// Handle a single HTTP/2 stream.
///
/// Each stream is an independent request-response exchange.
/// This function bridges monoio-http's H2 types to Harrow's types.
async fn handle_stream(
    mut request: http::Request<monoio_http::h2::RecvStream>,
    mut respond: monoio_http::h2::server::SendResponse<bytes::Bytes>,
    shared: Arc<SharedState>,
    max_body: usize,
    body_read_timeout: Option<Duration>,
) -> Result<(), Box<dyn std::error::Error>> {
    // Read request body from H2 stream
    let body_bytes = match read_h2_body(&mut request, max_body, body_read_timeout).await {
        Ok(body) => body,
        Err(ProtocolError::BodyTooLarge) => {
            send_h2_response(
                &mut respond,
                Response::new(http::StatusCode::PAYLOAD_TOO_LARGE, "payload too large")
                    .into_inner(),
            )
            .await?;
            return Ok(());
        }
        Err(ProtocolError::Timeout) => {
            send_h2_response(
                &mut respond,
                Response::new(http::StatusCode::REQUEST_TIMEOUT, "request timeout").into_inner(),
            )
            .await?;
            return Ok(());
        }
        Err(err) => return Err(Box::new(err)),
    };

    // Convert to Harrow request
    let harrow_request = convert_to_harrow_request(request, body_bytes)?;

    // Dispatch through Harrow
    let harrow_response = dispatch(shared, harrow_request).await;

    // Convert response and send
    send_h2_response(&mut respond, harrow_response).await?;

    Ok(())
}

/// Read the entire body from an HTTP/2 stream.
///
/// HTTP/2 streams use flow control - we must release capacity
/// as we receive data.
async fn read_h2_body(
    request: &mut http::Request<monoio_http::h2::RecvStream>,
    max_body: usize,
    body_read_timeout: Option<Duration>,
) -> Result<Bytes, ProtocolError> {
    let body = request.body_mut();
    let mut chunks = Vec::new();
    let mut total_len: usize = 0;

    loop {
        let data = if let Some(timeout) = body_read_timeout {
            monoio::select! {
                data = body.data() => data,
                _ = monoio::time::sleep(timeout) => return Err(ProtocolError::Timeout),
            }
        } else {
            body.data().await
        };

        let Some(data) = data else {
            break;
        };

        let data = data.map_err(|e| ProtocolError::Parse(format!("h2 body error: {e}")))?;
        let len = data.len();

        // Check body size limit
        if max_body > 0 && total_len + len > max_body {
            return Err(ProtocolError::BodyTooLarge);
        }

        total_len += len;
        chunks.push(data);

        // Release flow control capacity
        body.flow_control()
            .release_capacity(len)
            .map_err(|e| ProtocolError::ProtocolViolation(e.to_string()))?;
    }

    // Combine chunks
    let mut result = bytes::BytesMut::with_capacity(total_len);
    for chunk in chunks {
        result.extend_from_slice(&chunk);
    }

    Ok(result.freeze())
}

/// Convert monoio-http H2 request to Harrow request.
fn convert_to_harrow_request(
    request: http::Request<monoio_http::h2::RecvStream>,
    body_bytes: Bytes,
) -> Result<http::Request<Body>, Box<dyn std::error::Error>> {
    let (parts, _) = request.into_parts();
    let body = crate::protocol::body_from_bytes(body_bytes);

    Ok(http::Request::from_parts(parts, body))
}

/// Send Harrow response via HTTP/2 stream.
async fn send_h2_response(
    respond: &mut monoio_http::h2::server::SendResponse<bytes::Bytes>,
    response: http::Response<harrow_core::response::ResponseBody>,
) -> Result<(), Box<dyn std::error::Error>> {
    use http_body_util::BodyExt;

    let (parts, mut body) = response.into_parts();

    // Build H2 response (H2 always uses HTTP/2 version)
    let mut builder = http::Response::builder()
        .status(parts.status)
        .version(http::Version::HTTP_2);
    for (name, value) in &parts.headers {
        builder = builder.header(name, value);
    }
    let response = builder.body(()).expect("valid response");

    // Collect body to determine if we have trailers
    let mut body_data = Vec::new();
    while let Some(frame) = body.frame().await {
        let frame = frame.map_err(|e| format!("body frame error: {}", e))?;

        if let Ok(data) = frame.into_data() {
            body_data.push(data);
        }
    }

    // Send response headers
    let mut stream = if body_data.is_empty() {
        // No body - send headers with end_stream
        respond.send_response(response, true)?;
        return Ok(());
    } else {
        respond.send_response(response, false)?
    };

    // Send body data frames
    let total_chunks = body_data.len();
    for (i, data) in body_data.into_iter().enumerate() {
        let is_end = i == total_chunks - 1;
        stream.send_data(data, is_end)?;
    }

    Ok(())
}

/// Handle a single TCP connection with HTTP/2.
///
/// This is the public entry point that creates an H2Connection and runs it.
pub(crate) async fn handle_connection(stream: TcpStream, conn: crate::connection::ConnConfig) {
    let remote_addr = conn.remote_addr;
    let shared = conn.shared;
    let header_read_timeout = conn.header_read_timeout;
    let body_read_timeout = conn.body_read_timeout;
    let connection_timeout = conn.connection_timeout;
    let max_concurrent_streams = conn.max_h2_streams;
    let active_count = conn.active_count;
    use crate::o11y::connection_span;
    use tracing::Instrument;

    // Create connection metrics - this increments the active connection gauge
    let metrics = ConnectionMetrics::new(active_count);
    let span = connection_span(metrics.id, remote_addr);

    let config = H2Config {
        shared,
        header_read_timeout,
        body_read_timeout,
        connection_timeout,
        max_concurrent_streams,
        metrics,
    };

    let conn = H2Connection::new(stream, config);
    let connection_id = conn.config.metrics.id;

    // Run the connection within the span
    if let Err(e) = conn.run().instrument(span).await {
        tracing::debug!(
            connection.id = connection_id,
            error = %e,
            "h2 connection error"
        );
    }
}

#[cfg(test)]
mod tests {
    // Tests will be added in Phase 2 integration
}