hyperlane-core 23.3.0

A lightweight, high-performance, and cross-platform Rust HTTP server library built on Tokio. It simplifies modern web service development by providing built-in support for middleware, WebSocket, Server-Sent Events (SSE), and raw TCP communication. With a unified and ergonomic API across Windows, Linux, and MacOS, it enables developers to build robust, scalable, and event-driven network applications with minimal overhead and maximum flexibility.
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
use super::*;

/// Removes the inline registry entry when the owning hook handler is dropped.
impl Drop for InlineHookGuard {
    /// Unregisters the associated handler address from the global inline registry.
    fn drop(&mut self) {
        let Self { key } = self;
        let value: usize = key.load(sync::atomic::Ordering::Relaxed);
        unregister_inline_hook(value);
    }
}

/// Drops an initialized inline future on normal completion or unwind.
impl<F> Drop for InlineDropGuard<F> {
    /// Drops the pointed-to future in place.
    #[inline(always)]
    fn drop(&mut self) {
        let Self { ptr } = self;
        // SAFETY: Guard owns the initialized `F` in inline storage until forgotten on `Pending`.
        unsafe {
            ptr::drop_in_place(*ptr);
        }
    }
}

/// SAFETY: `InlineHookCall` only stores `Send` references, function pointers,
/// and `Send` futures constructed via `start_inline_future`.
unsafe impl Send for InlineHookCall<'_> {}

/// Inherent implementation of [`InlineHookCall`].
impl<'a> InlineHookCall<'a> {
    /// Creates a new uninitialized inline hook call future.
    ///
    /// # Arguments
    ///
    /// - `&'a mut Stream` - The active stream.
    /// - `&'a mut Context` - The active context.
    /// - `InlineStartFn` - The monomorphized fused hook starter.
    ///
    /// # Returns
    ///
    /// - `Self` - The future ready to be pinned and polled.
    #[inline(always)]
    pub(crate) fn new(stream: &'a mut Stream, ctx: &'a mut Context, start: InlineStartFn) -> Self {
        Self {
            stream,
            ctx,
            start,
            state: InlinePollState::Uninit,
            storage: MaybeUninit::uninit(),
            _pinned: PhantomPinned,
        }
    }
}

/// Drops any active inline future if cancelled or unwound before completion.
impl Drop for InlineHookCall<'_> {
    /// Drops the in-place future when active.
    #[inline(always)]
    fn drop(&mut self) {
        let Self { state, storage, .. } = self;
        if matches!(state, InlinePollState::Uninit | InlinePollState::Done) {
            return;
        }
        let previous: InlinePollState = mem::replace(state, InlinePollState::Done);
        if let InlinePollState::Inline { drop_fn, .. } = previous {
            let ptr: *mut u8 = storage.as_mut_ptr().cast::<u8>();
            // SAFETY: `state` was `Inline`, so `storage` holds an initialized future dropped once.
            unsafe {
                drop_fn(ptr);
            }
        }
    }
}

/// Polls the inline-or-boxed [`ServerHook`] future directly in pinned stack storage.
impl Future for InlineHookCall<'_> {
    type Output = Status;

    /// Constructs and polls the concrete future on first poll, driving it to completion.
    ///
    /// # Arguments
    ///
    /// - `Pin<&mut Self>` - The pinned inline call future.
    /// - `&mut task::Context<'_>` - The task waker context.
    ///
    /// # Returns
    ///
    /// - `Poll<Self::Output>` - The hook status once ready, or pending.
    #[inline(always)]
    fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
        // SAFETY: We never move `storage` once initialized; all field projections respect pinning.
        let Self {
            stream,
            ctx,
            start,
            state,
            storage,
            ..
        } = unsafe { self.get_unchecked_mut() };
        match state {
            InlinePollState::Uninit => {
                let stream_addr: usize = (&mut **stream).into();
                let ctx_addr: usize = (&mut **ctx).into();
                let slot: *mut u8 = storage.as_mut_ptr().cast::<u8>();
                let slot_len: usize = mem::size_of::<[usize; INLINE_FUTURE_WORDS]>();
                match (*start)(stream_addr, ctx_addr, slot, slot_len, cx) {
                    InlineStartOutcome::Ready(status) => Poll::Ready(status),
                    InlineStartOutcome::PendingInline { poll_fn, drop_fn } => {
                        *state = InlinePollState::Inline { poll_fn, drop_fn };
                        Poll::Pending
                    }
                    InlineStartOutcome::PendingBoxed(future) => {
                        *state = InlinePollState::Boxed(future);
                        Poll::Pending
                    }
                }
            }
            InlinePollState::Inline { poll_fn, drop_fn } => {
                let poll_entry: InlinePollFn = *poll_fn;
                let drop_entry: unsafe fn(*mut u8) = *drop_fn;
                let ptr: *mut u8 = storage.as_mut_ptr().cast::<u8>();
                // SAFETY: `storage` holds the pinned concrete future initialized above.
                match unsafe { poll_entry(ptr, cx) } {
                    Poll::Ready(status) => {
                        *state = InlinePollState::Done;
                        // SAFETY: Completed future is dropped exactly once here.
                        unsafe {
                            drop_entry(ptr);
                        }
                        Poll::Ready(status)
                    }
                    Poll::Pending => Poll::Pending,
                }
            }
            InlinePollState::Boxed(future) => match future.as_mut().poll(cx) {
                Poll::Ready(status) => {
                    *state = InlinePollState::Done;
                    Poll::Ready(status)
                }
                Poll::Pending => Poll::Pending,
            },
            InlinePollState::Done => Poll::Ready(Status::default()),
        }
    }
}

/// SAFETY: `InlineHookChain` only stores `Send` references, slices of `Send + Sync` hooks,
/// and `Send` futures constructed via `start_inline_future` or `ServerHookHandler`.
unsafe impl Send for InlineHookChain<'_> {}

/// Inherent implementation of [`InlineHookChain`].
impl<'a> InlineHookChain<'a> {
    /// Creates a new hook chain future for a middleware slice.
    ///
    /// # Arguments
    ///
    /// - `&'a mut Stream` - The active stream.
    /// - `&'a mut Context` - The active context.
    /// - `&'a [CompiledHook]` - The middleware slice to execute in order.
    ///
    /// # Returns
    ///
    /// - `Self` - The chain future ready to be pinned and polled.
    #[inline(always)]
    pub(crate) fn new(
        stream: &'a mut Stream,
        ctx: &'a mut Context,
        hooks: &'a [CompiledHook],
    ) -> Self {
        Self {
            stream,
            ctx,
            hooks,
            index: 0,
            state: InlinePollState::Uninit,
            storage: MaybeUninit::uninit(),
            _pinned: PhantomPinned,
        }
    }
}

/// Drops any active pending inline future if the middleware chain is cancelled or unwound.
impl Drop for InlineHookChain<'_> {
    /// Drops the active in-place future when present.
    #[inline(always)]
    fn drop(&mut self) {
        let Self { state, storage, .. } = self;
        if matches!(state, InlinePollState::Uninit | InlinePollState::Done) {
            return;
        }
        let previous: InlinePollState = mem::replace(state, InlinePollState::Done);
        if let InlinePollState::Inline { drop_fn, .. } = previous {
            let ptr: *mut u8 = storage.as_mut_ptr().cast::<u8>();
            // SAFETY: `state` was `Inline`, so `storage` holds an initialized future dropped once.
            unsafe {
                drop_fn(ptr);
            }
        }
    }
}

/// Executes a slice of middleware hooks in a tight synchronous-first loop.
impl Future for InlineHookChain<'_> {
    type Output = Status;

    /// Resumes any pending hook and advances through remaining hooks without re-entering async state.
    ///
    /// # Arguments
    ///
    /// - `Pin<&mut Self>` - The pinned hook chain future.
    /// - `&mut task::Context<'_>` - The task waker context.
    ///
    /// # Returns
    ///
    /// - `Poll<Self::Output>` - `Status::Reject` on first rejecting hook, `Status::Continue` when complete, or pending.
    #[inline(always)]
    fn poll(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Self::Output> {
        // SAFETY: `storage` is never moved once initialized; field projections preserve pinning.
        let Self {
            stream,
            ctx,
            hooks,
            index,
            state,
            storage,
            ..
        } = unsafe { self.get_unchecked_mut() };
        match state {
            InlinePollState::Inline { poll_fn, drop_fn } => {
                let poll_entry: InlinePollFn = *poll_fn;
                let drop_entry: unsafe fn(*mut u8) = *drop_fn;
                let ptr: *mut u8 = storage.as_mut_ptr().cast::<u8>();
                // SAFETY: `storage` holds the pinned active hook future.
                match unsafe { poll_entry(ptr, cx) } {
                    Poll::Ready(status) => {
                        *state = InlinePollState::Uninit;
                        // SAFETY: Completed future is dropped once before advancing.
                        unsafe {
                            drop_entry(ptr);
                        }
                        if status.is_reject() {
                            return Poll::Ready(status);
                        }
                    }
                    Poll::Pending => return Poll::Pending,
                }
            }
            InlinePollState::Boxed(future) => match future.as_mut().poll(cx) {
                Poll::Ready(status) => {
                    *state = InlinePollState::Uninit;
                    if status.is_reject() {
                        return Poll::Ready(status);
                    }
                }
                Poll::Pending => return Poll::Pending,
            },
            InlinePollState::Uninit => {}
            InlinePollState::Done => return Poll::Ready(Status::Continue),
        }
        let stream_addr: usize = (&mut **stream).into();
        let ctx_addr: usize = (&mut **ctx).into();
        let slot: *mut u8 = storage.as_mut_ptr().cast::<u8>();
        let slot_len: usize = mem::size_of::<[usize; INLINE_FUTURE_WORDS]>();
        let total: usize = hooks.len();
        while *index < total {
            let hook: &CompiledHook = &hooks[*index];
            *index += 1;
            match hook {
                CompiledHook::Inline(start) => {
                    match (*start)(stream_addr, ctx_addr, slot, slot_len, cx) {
                        InlineStartOutcome::Ready(status) => {
                            if status.is_reject() {
                                return Poll::Ready(status);
                            }
                        }
                        InlineStartOutcome::PendingInline { poll_fn, drop_fn } => {
                            *state = InlinePollState::Inline { poll_fn, drop_fn };
                            return Poll::Pending;
                        }
                        InlineStartOutcome::PendingBoxed(future) => {
                            *state = InlinePollState::Boxed(future);
                            return Poll::Pending;
                        }
                    }
                }
                CompiledHook::Dynamic(handler) => {
                    let mut future: FutureBox<Status> = handler(stream, ctx);
                    match future.as_mut().poll(cx) {
                        Poll::Ready(status) => {
                            if status.is_reject() {
                                return Poll::Ready(status);
                            }
                        }
                        Poll::Pending => {
                            *state = InlinePollState::Boxed(future);
                            return Poll::Pending;
                        }
                    }
                }
            }
        }
        Poll::Ready(Status::Continue)
    }
}

/// Inherent implementation of [`CompiledHook`].
impl CompiledHook {
    /// Invokes the hook inline on the stack when possible, or dynamically otherwise.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - The active stream.
    /// - `&mut Context` - The active request context.
    ///
    /// # Returns
    ///
    /// - `Status` - The hook lifecycle decision.
    #[inline(always)]
    pub(crate) async fn call(&self, stream: &mut Stream, ctx: &mut Context) -> Status {
        match self {
            Self::Inline(start) => InlineHookCall::new(stream, ctx, *start).await,
            Self::Dynamic(handler) => handler(stream, ctx).await,
        }
    }
}

/// Inherent implementation of [`CompiledPipeline`].
impl CompiledPipeline {
    /// Compiles a server's routes and middleware once before accepting connections.
    ///
    /// # Arguments
    ///
    /// - `&Server` - The configured server instance.
    ///
    /// # Returns
    ///
    /// - `Self` - The compiled zero-lock dispatch table.
    pub(crate) fn from_server(server: &Server) -> Self {
        let matcher: &RouteMatcher = server.get_route_matcher();
        let static_count: usize = matcher.get_static_route().len();
        let mut small_static_routes: SmallStaticRoutes = if static_count <= SMALL_STATIC_ROUTE_LIMIT
        {
            Vec::with_capacity(static_count)
        } else {
            Vec::new()
        };
        let mut static_routes: HashMapXxHash3_64<String, CompiledHook> = hash_map_xx_hash3_64();
        let mut min_static_len: usize = usize::MAX;
        let mut max_static_len: usize = 0;
        for (path, handler) in matcher.get_static_route().iter() {
            let len: usize = path.len();
            if len < min_static_len {
                min_static_len = len;
            }
            if len > max_static_len {
                max_static_len = len;
            }
            let compiled: CompiledHook = lookup_inline_hook(handler);
            if static_count <= SMALL_STATIC_ROUTE_LIMIT {
                small_static_routes.push((path.clone(), compiled));
            } else {
                static_routes.insert(path.clone(), compiled);
            }
        }
        let max_dyn_seg: usize = matcher
            .get_dynamic_route()
            .keys()
            .copied()
            .max()
            .unwrap_or(0);
        let has_dynamic: bool = !matcher.get_dynamic_route().is_empty();
        let mut dynamic_routes: CompiledPatternBuckets = if has_dynamic {
            vec![Vec::new(); max_dyn_seg + 1]
        } else {
            Vec::new()
        };
        for (&count, list) in matcher.get_dynamic_route().iter() {
            let compiled: Vec<(RoutePattern, CompiledHook)> = list
                .iter()
                .map(|(pattern, handler): &(RoutePattern, ServerHookHandler)| {
                    (pattern.clone(), lookup_inline_hook(handler))
                })
                .collect();
            dynamic_routes[count] = compiled;
        }
        let max_regex_seg: usize = matcher.get_regex_route().keys().copied().max().unwrap_or(0);
        let has_regex: bool = !matcher.get_regex_route().is_empty();
        let mut regex_routes: CompiledPatternBuckets = if has_regex {
            vec![Vec::new(); max_regex_seg + 1]
        } else {
            Vec::new()
        };
        let mut regex_tail_routes: CompiledTailRegexRoutes = Vec::new();
        for (&count, list) in matcher.get_regex_route().iter() {
            let mut compiled: Vec<(RoutePattern, CompiledHook)> = Vec::with_capacity(list.len());
            for (pattern, handler) in list.iter() {
                let hook: CompiledHook = lookup_inline_hook(handler);
                if pattern.has_tail_regex() {
                    regex_tail_routes.push((count, pattern.clone(), hook.clone()));
                }
                compiled.push((pattern.clone(), hook));
            }
            regex_routes[count] = compiled;
        }
        let request_middleware: Vec<CompiledHook> = server
            .get_request_middleware()
            .iter()
            .map(lookup_inline_hook)
            .collect();
        let response_middleware: Vec<CompiledHook> = server
            .get_response_middleware()
            .iter()
            .map(lookup_inline_hook)
            .collect();
        Self {
            small_static_routes,
            static_routes,
            min_static_len,
            max_static_len,
            dynamic_routes,
            has_dynamic,
            regex_routes,
            regex_tail_routes,
            has_regex,
            request_middleware,
            response_middleware,
        }
    }

    /// Resolves a route path into a compiled hook, filling `params` in place for dynamic/regex routes.
    ///
    /// # Arguments
    ///
    /// - `&mut HashMapXxHash3_64<String, String>` - The context route parameter map to fill.
    /// - `&str` - The request path to match.
    ///
    /// # Returns
    ///
    /// - `Option<&CompiledHook>` - The matched compiled hook, if any.
    #[inline(always)]
    pub(crate) fn resolve_route(
        &self,
        params: &mut HashMapXxHash3_64<String, String>,
        path: &str,
    ) -> Option<&CompiledHook> {
        let Self {
            small_static_routes,
            static_routes,
            min_static_len,
            max_static_len,
            dynamic_routes,
            has_dynamic,
            regex_routes,
            regex_tail_routes,
            has_regex,
            ..
        } = self;
        let path_len: usize = path.len();
        if path_len >= *min_static_len && path_len <= *max_static_len {
            if !small_static_routes.is_empty() {
                let path_bytes: &[u8] = path.as_bytes();
                for (route_path, hook) in small_static_routes.iter() {
                    if route_path.as_bytes() == path_bytes {
                        return Some(hook);
                    }
                }
            } else if let Some(hook) = static_routes.get(path) {
                return Some(hook);
            }
        }
        if !*has_dynamic && !*has_regex {
            return None;
        }
        let trimmed: &str = path.strip_prefix(DEFAULT_HTTP_PATH).unwrap_or(path);
        let segment_count: usize = if trimmed.is_empty() {
            0
        } else {
            let sep: u8 = DEFAULT_HTTP_PATH_BYTES[0];
            let mut count: usize = 1;
            for &byte in trimmed.as_bytes() {
                if byte == sep {
                    count += 1;
                }
            }
            count
        };
        if *has_dynamic && let Some(routes) = dynamic_routes.get(segment_count) {
            for (pattern, hook) in routes.iter() {
                if pattern.try_match_path_into(path, params) {
                    return Some(hook);
                }
            }
        }
        if *has_regex {
            if let Some(routes) = regex_routes.get(segment_count) {
                for (pattern, hook) in routes.iter() {
                    if pattern.try_match_path_into(path, params) {
                        return Some(hook);
                    }
                }
            }
            for (pattern_seg_count, pattern, hook) in regex_tail_routes.iter() {
                if *pattern_seg_count != segment_count
                    && *pattern_seg_count <= segment_count + 1
                    && pattern.try_match_path_into(path, params)
                {
                    return Some(hook);
                }
            }
        }
        None
    }

    /// Checks whether both the request and response allow keeping the connection open.
    ///
    /// # Arguments
    ///
    /// - `&Context` - The request context after running hooks.
    /// - `bool` - Whether the request itself allowed keep-alive.
    ///
    /// # Returns
    ///
    /// - `bool` - `false` when the request or response demands closing the connection.
    #[inline(always)]
    fn response_allows_keep_alive(ctx: &Context, req_keep_alive: bool) -> bool {
        if !req_keep_alive {
            return false;
        }
        let headers: &ResponseHeaders = ctx.get_response().get_headers();
        if headers.is_empty() {
            return true;
        }
        if let Some(values) = headers.get(CONNECTION) {
            for header_value in values {
                if header_value == KEEP_ALIVE {
                    continue;
                }
                for token in header_value.split(COMMA) {
                    if token.trim().eq_ignore_ascii_case(CLOSE) {
                        return false;
                    }
                }
            }
            return true;
        }
        for (name, values) in headers {
            if name.eq_ignore_ascii_case(CONNECTION) {
                for header_value in values {
                    for token in header_value.split(COMMA) {
                        if token.trim().eq_ignore_ascii_case(CLOSE) {
                            return false;
                        }
                    }
                }
            }
        }
        true
    }

    /// Executes the full request pipeline inline without per-hook `Box::pin` allocations.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - The active stream.
    /// - `&mut Context` - The active request context.
    /// - `Option<String>` - The original request target supplied by multiplexed protocols.
    ///
    /// # Returns
    ///
    /// - `bool` - Whether the connection should remain open for keep-alive.
    #[inline(always)]
    pub(crate) async fn run_request(
        &self,
        stream: &mut Stream,
        ctx: &mut Context,
        target: Option<String>,
    ) -> bool {
        let Self {
            request_middleware,
            response_middleware,
            ..
        } = self;
        let keep_alive: bool = ctx.get_request().is_enable_keep_alive();
        ctx.set_original_head(Some(ctx.get_request().get_method().is_head()));
        if ctx.get_request().get_version().is_http1_1() {
            ctx.get_mut_response().reset();
        } else {
            let version: HttpVersion = ctx.get_request().get_version().clone();
            ctx.get_mut_response().reset().set_version(version);
        }
        ctx.clear_route_params();
        ctx.reset_request_attributes();
        match target {
            Some(target) => {
                ctx.set_request_target(target);
            }
            None => {
                let parsed_target: Option<&str> = stream.get_request_target_slice().or_else(|| {
                    let line: &str = stream.get_line_buffer();
                    line.split_ascii_whitespace().nth(1)
                });
                if let Some(target) = parsed_target {
                    ctx.set_request_target(target);
                } else {
                    let _: Option<String> = ctx.take_original_target();
                }
            }
        }
        stream.set_closed(false);
        if !request_middleware.is_empty()
            && InlineHookChain::new(stream, ctx, request_middleware)
                .await
                .is_reject()
        {
            return stream.is_keep_alive(Self::response_allows_keep_alive(ctx, keep_alive));
        }
        let matched_hook: Option<&CompiledHook> = {
            let path: &str = ctx.request.get_path().as_str();
            self.resolve_route(&mut ctx.route_params, path)
        };
        if let Some(hook) = matched_hook
            && hook.call(stream, ctx).await.is_reject()
        {
            return stream.is_keep_alive(Self::response_allows_keep_alive(ctx, keep_alive));
        }
        if !response_middleware.is_empty()
            && InlineHookChain::new(stream, ctx, response_middleware)
                .await
                .is_reject()
        {
            return stream.is_keep_alive(Self::response_allows_keep_alive(ctx, keep_alive));
        }
        stream.is_keep_alive(Self::response_allows_keep_alive(ctx, keep_alive))
    }
}