hyperlane-core 23.2.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
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);
    }
}

/// SAFETY: `InlineHookCall` only stores `Send` references, function pointers,
/// and `Send` futures constructed via `place_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.
    /// - `InlineInitFn` - The monomorphized hook initializer.
    ///
    /// # Returns
    ///
    /// - `Self` - The future ready to be pinned and polled.
    #[inline(always)]
    pub(crate) fn new(stream: &'a mut Stream, ctx: &'a mut Context, init: InlineInitFn) -> Self {
        Self {
            stream,
            ctx,
            init,
            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.
    fn drop(&mut self) {
        let Self { state, storage, .. } = self;
        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 the concrete future on first poll and drives 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,
            init,
            state,
            storage,
            ..
        } = unsafe { self.get_unchecked_mut() };
        if matches!(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]>();
            *state = (*init)(stream_addr, ctx_addr, slot, slot_len);
        }
        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 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::Uninit | InlinePollState::Done => Poll::Ready(Status::default()),
        }
    }
}

/// 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(init) => InlineHookCall::new(stream, ctx, *init).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 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;
            }
            static_routes.insert(path.clone(), lookup_inline_hook(handler));
        }
        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 {
            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 {
            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
            && 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();
        let version: HttpVersion = ctx.get_request().get_version().clone();
        ctx.set_original_head(Some(ctx.get_request().get_method().is_head()));
        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 line: &str = stream.get_line_buffer();
                let bytes: &[u8] = line.as_bytes();
                let parsed_target: Option<&str> = if !bytes.is_empty() && bytes[0] > SPACE_U8 {
                    let first_space: Option<usize> = if bytes.len() > 4
                        && bytes[1] > SPACE_U8
                        && bytes[2] > SPACE_U8
                        && bytes[3] == SPACE_U8
                    {
                        Some(3)
                    } else if bytes.len() > 5
                        && bytes[1] > SPACE_U8
                        && bytes[2] > SPACE_U8
                        && bytes[3] > SPACE_U8
                        && bytes[4] == SPACE_U8
                    {
                        Some(4)
                    } else {
                        bytes.iter().position(|byte: &u8| *byte <= SPACE_U8)
                    };
                    match first_space {
                        Some(first_space) if bytes[first_space] == SPACE_U8 => {
                            let start: usize = first_space + 1;
                            if start < bytes.len() && bytes[start] > SPACE_U8 {
                                let rest: &[u8] = &bytes[start..];
                                match rest.iter().position(|byte: &u8| *byte <= SPACE_U8) {
                                    Some(rel_end) => Some(&line[start..start + rel_end]),
                                    None => Some(&line[start..]),
                                }
                            } else {
                                line.split_ascii_whitespace().nth(1)
                            }
                        }
                        _ => line.split_ascii_whitespace().nth(1),
                    }
                } else {
                    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);
        for hook in request_middleware.iter() {
            if hook.call(stream, ctx).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));
        }
        for hook in response_middleware.iter() {
            if hook.call(stream, ctx).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))
    }
}