http-type 23.2.0

A comprehensive Rust type library for HTTP operations and concurrent programming. Provides core HTTP types (Request/Response with builder patterns, Method, HttpStatus, HttpVersion, ContentType, FileExtension with MIME mapping, Cookie parsing/building, HttpUrl parsing, WebSocket frame/opcode, protocol upgrade types, stream/task management, panic handling), thread-safe concurrent wrappers (ArcMutex, ArcRwLock, BoxRwLock, RcRwLock), dynamic dispatch types (BoxAny, RcAny, ArcAny with Send/Sync variants), high-performance hash collections (HashMapXxHash3_64, HashSetXxHash3_64), and static lifetime utilities (BoxLeak, Lifetime trait).
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
use super::*;

/// Decodes chunked request content on the same reader that owns pipelined bytes.
///
/// # Arguments
///
/// - `&mut PooledReader<'_>` - The reader positioned after the initial fields.
/// - `&mut Request` - The request to populate with decoded content.
/// - `&RequestConfig` - The request size limits.
/// # Returns
///
/// - `Result<(), RequestError>` - Whether the complete chunked request was read.
#[cold]
pub(super) async fn fill_chunked_request(
    reader: &mut PooledReader<'_>,
    request: &mut Request,
    config: &RequestConfig,
) -> Result<(), RequestError> {
    if expects_http_continue(request) {
        let transport: &mut Box<dyn Transport> = reader.get_mut_stream();
        transport.write_all(HTTP_CONTINUE_RESPONSE).await?;
        transport.flush().await?;
    }
    fill_chunked_body(reader, request.get_mut_body(), config).await?;
    request.normalize_chunked_headers();
    Ok(())
}

/// Checks for the continue expectation on a request that has unread content.
///
/// # Arguments
///
/// - `&Request` - The request with a validated header section.
///
/// # Returns
///
/// - `bool` - Whether to send an HTTP/1.1 interim response.
#[cold]
pub(super) fn expects_http_continue(request: &Request) -> bool {
    request.get_version().is_http1_1()
        && request
            .get_headers()
            .get(EXPECT)
            .is_some_and(|values: &VecDeque<String>| {
                values
                    .iter()
                    .any(|value: &String| contains_continue_member(value))
            })
}

/// Finds the continue token without treating commas inside quoted values as separators.
///
/// # Arguments
///
/// - `&str` - One Expect field value.
/// # Returns
///
/// - `bool` - Whether the field contains the bare continue expectation.
fn contains_continue_member(value: &str) -> bool {
    let mut start: usize = 0;
    let mut quoted: bool = false;
    let mut escaped: bool = false;
    for (offset, byte) in value.bytes().enumerate() {
        match byte {
            _ if escaped => escaped = false,
            HTTP_QUOTED_FIELD_ESCAPE if quoted => escaped = true,
            HTTP_QUOTED_FIELD_QUOTE => quoted = !quoted,
            COMMA_U8 if !quoted => {
                if value[start..offset]
                    .trim_matches([' ', '\t'])
                    .eq_ignore_ascii_case(CONTINUE_EXPECT)
                {
                    return true;
                }
                start = offset + 1;
            }
            _ => {}
        }
    }
    value[start..]
        .trim_matches([' ', '\t'])
        .eq_ignore_ascii_case(CONTINUE_EXPECT)
}

/// Takes a recycled header entry from the pool.
///
/// # Returns
///
/// - `Option<(String, VecDeque<String>)>` - The recycled entry, or `None` when
///   the pool is empty.
pub(crate) fn take_header_entry() -> Option<(String, VecDeque<String>)> {
    HEADER_ENTRY_POOL
        .with(|pool: &RefCell<Vec<(String, VecDeque<String>)>>| pool.borrow_mut().pop())
}

/// Returns a header entry to the pool for reuse.
///
/// # Arguments
///
/// - `(String, VecDeque<String>)` - The entry to recycle.
pub(crate) fn return_header_entry(entry: (String, VecDeque<String>)) {
    if entry.0.capacity() > MAX_POOLED_HEADER_STRING_CAPACITY
        || entry.1.capacity() > MAX_POOLED_HEADER_VALUE_CAPACITY
    {
        return;
    }
    if entry
        .1
        .iter()
        .any(|value: &String| value.capacity() > MAX_POOLED_HEADER_STRING_CAPACITY)
    {
        return;
    }
    HEADER_ENTRY_POOL.with(|pool: &RefCell<Vec<(String, VecDeque<String>)>>| {
        let mut pool: RefMut<'_, Vec<(String, VecDeque<String>)>> = pool.borrow_mut();
        if pool.len() < MAX_POOLED_HEADER_ENTRIES {
            pool.push(entry);
        }
    });
}

/// Returns multiple header or query entries to the worker-local pool in a single lookup.
///
/// # Arguments
///
/// - `I` - An iterator yielding header or query entries to recycle.
#[inline(always)]
pub(crate) fn return_header_entries<I>(entries: I)
where
    I: IntoIterator<Item = (String, VecDeque<String>)>,
{
    HEADER_ENTRY_POOL.with(|pool: &RefCell<Vec<(String, VecDeque<String>)>>| {
        let mut pool: RefMut<'_, Vec<(String, VecDeque<String>)>> = pool.borrow_mut();
        for entry in entries {
            if pool.len() >= MAX_POOLED_HEADER_ENTRIES {
                break;
            }
            if entry.0.capacity() > MAX_POOLED_HEADER_STRING_CAPACITY
                || entry.1.capacity() > MAX_POOLED_HEADER_VALUE_CAPACITY
            {
                continue;
            }
            let values_ok: bool = if entry.1.len() == 1 {
                entry.1[0].capacity() <= MAX_POOLED_HEADER_STRING_CAPACITY
            } else {
                !entry
                    .1
                    .iter()
                    .any(|value: &String| value.capacity() > MAX_POOLED_HEADER_STRING_CAPACITY)
            };
            if !values_ok {
                continue;
            }
            pool.push(entry);
        }
    });
}

/// Polls a future once before lazily arming or reusing a connection-scoped sleep timer.
///
/// The reusable timer stays armed in Tokio's timer wheel across consecutive
/// keep-alive requests so high-concurrency loops avoid per-request timer wheel
/// insertion and removal while still firing at the exact request deadline.
///
/// # Arguments
///
/// - `Pin<&mut F>` - The future to drive.
/// - `&mut Option<Pin<Box<Sleep>>>` - Reusable sleep slot owned by the connection.
/// - `Duration` - Maximum time to wait once the first poll returns `Poll::Pending`.
///
/// # Returns
///
/// - `Option<F::Output>` - `Some` with the completed value, or `None` on timeout.
pub(crate) async fn poll_with_timeout<F>(
    mut future: Pin<&mut F>,
    timer_slot: &mut Option<Pin<Box<Sleep>>>,
    duration: Duration,
) -> Option<F::Output>
where
    F: Future,
{
    let mut exact_deadline: Option<Instant> = None;
    future::poll_fn(|context: &mut Context<'_>| {
        if let Poll::Ready(value) = future.as_mut().poll(context) {
            return Poll::Ready(Some(value));
        }
        let deadline: Instant = *exact_deadline.get_or_insert_with(|| Instant::now() + duration);
        let timer: &mut Pin<Box<Sleep>> = match timer_slot {
            Some(existing) => {
                if existing.deadline() > deadline {
                    existing.as_mut().reset(deadline);
                }
                existing
            }
            None => timer_slot.insert(Box::pin(sleep_until(deadline))),
        };
        loop {
            match timer.as_mut().poll(context) {
                Poll::Pending => return Poll::Pending,
                Poll::Ready(()) => {
                    if Instant::now() < deadline {
                        timer.as_mut().reset(deadline);
                        continue;
                    }
                    return Poll::Ready(None);
                }
            }
        }
    })
    .await
}

/// Takes a read buffer from the thread-local pool or allocates a new one.
///
/// # Arguments
///
/// - `usize` - The required buffer length in bytes.
///
/// # Returns
///
/// - `Vec<u8>` - A buffer with at least the requested length.
pub(crate) fn take_read_buffer(capacity: usize) -> Vec<u8> {
    READ_BUFFER_POOL.with(|pool: &RefCell<Vec<Vec<u8>>>| {
        let mut pool: RefMut<'_, Vec<Vec<u8>>> = pool.borrow_mut();
        match pool.pop() {
            Some(mut buffer) => {
                if buffer.len() < capacity {
                    buffer.resize(capacity, 0);
                }
                buffer
            }
            None => vec![0; capacity],
        }
    })
}

/// Returns a read buffer to the thread-local pool for reuse.
///
/// Buffers larger than `MAX_POOLED_READ_BUFFER_SIZE` are dropped instead
/// of being retained, and the pool is capped at `MAX_POOLED_READ_BUFFERS`.
///
/// # Arguments
///
/// - `Vec<u8>` - The buffer to recycle.
pub(crate) fn return_read_buffer(buffer: Vec<u8>) {
    if buffer.is_empty() || buffer.capacity() > MAX_POOLED_READ_BUFFER_SIZE {
        return;
    }
    READ_BUFFER_POOL.with(|pool: &RefCell<Vec<Vec<u8>>>| {
        let mut pool: RefMut<'_, Vec<Vec<u8>>> = pool.borrow_mut();
        if pool.len() < MAX_POOLED_READ_BUFFERS {
            pool.push(buffer);
        }
    });
}

/// Validates an RFC 6455 Close control frame payload and returns the resulting request error.
///
/// # Arguments
///
/// - `&[u8]` - Unmasked Close frame payload bytes.
///
/// # Returns
///
/// - `RequestError` - Protocol violation error or [`RequestError::ClientClosedConnection`].
#[cold]
pub(super) fn validate_ws_close_frame(payload: &[u8]) -> RequestError {
    if payload.len() == 1 {
        return RequestError::WebSocketInvalidCloseCode(HttpStatus::BadRequest);
    }
    if payload.len() >= 2 {
        let code: u16 = u16::from_be_bytes([payload[0], payload[1]]);
        let is_std_close: bool = (WS_CLOSE_STD_RANGE_1_START..=WS_CLOSE_STD_RANGE_1_END)
            .contains(&code)
            || (WS_CLOSE_STD_RANGE_2_START..=WS_CLOSE_STD_RANGE_2_END).contains(&code);
        let valid_code: bool =
            is_std_close || (WS_CLOSE_APP_RANGE_START..=WS_CLOSE_APP_RANGE_END).contains(&code);
        if !valid_code {
            return RequestError::WebSocketInvalidCloseCode(HttpStatus::BadRequest);
        }
        if from_utf8(&payload[2..]).is_err() {
            return RequestError::WebSocketInvalidUtf8(HttpStatus::BadRequest);
        }
    }
    RequestError::ClientClosedConnection(HttpStatus::BadRequest)
}

/// Processes one decoded WebSocket frame, allocating persistent state only when fragmented.
///
/// # Arguments
///
/// - `WebSocketFrame` - Decoded and unmasked RFC 6455 frame.
/// - `usize` - Configured maximum WebSocket message payload size.
/// - `&mut Option<Box<WebSocketReadState>>` - Lazily allocated parser state for fragments/leftovers.
///
/// # Returns
///
/// - `Result<Option<WebSocketParseStep>, RequestError>` - Completed step, `Ok(None)` to continue parsing, or error.
#[inline]
pub(super) fn process_ws_frame(
    frame: WebSocketFrame,
    max_body_size: usize,
    websocket_state: &mut Option<Box<WebSocketReadState>>,
) -> Result<Option<WebSocketParseStep>, RequestError> {
    match frame.get_opcode() {
        WebSocketOpcode::Close => Err(validate_ws_close_frame(frame.get_payload_data())),
        WebSocketOpcode::Ping => {
            let WebSocketFrame { payload_data, .. }: WebSocketFrame = frame;
            Ok(Some(WebSocketParseStep::Ping(payload_data)))
        }
        WebSocketOpcode::Pong => Ok(None),
        WebSocketOpcode::Text | WebSocketOpcode::Binary => {
            if websocket_state
                .as_deref()
                .is_some_and(|st: &WebSocketReadState| st.try_get_fragment_opcode().is_some())
            {
                return Err(RequestError::WebSocketPayloadCorrupted(
                    HttpStatus::BadRequest,
                ));
            }
            let is_text: bool = frame.is_text_opcode();
            if frame.get_fin() {
                let WebSocketFrame { payload_data, .. }: WebSocketFrame = frame;
                if is_text && from_utf8(&payload_data).is_err() {
                    return Err(RequestError::WebSocketInvalidUtf8(HttpStatus::BadRequest));
                }
                return Ok(Some(WebSocketParseStep::Message(payload_data)));
            }
            let opcode: WebSocketOpcode = *frame.get_opcode();
            let WebSocketFrame { payload_data, .. }: WebSocketFrame = frame;
            if max_body_size != DEFAULT_LOW_SECURITY_MAX_BODY_SIZE
                && payload_data.len() > max_body_size
            {
                return Err(RequestError::WebSocketFrameTooLarge(
                    HttpStatus::PayloadTooLarge,
                ));
            }
            let state: &mut WebSocketReadState =
                websocket_state.get_or_insert_with(|| Box::new(WebSocketReadState::default()));
            state.set_full_frame(payload_data);
            state.set_fragment_opcode(Some(opcode));
            Ok(None)
        }
        WebSocketOpcode::Continuation => {
            let Some(state) = websocket_state.as_deref_mut() else {
                return Err(RequestError::WebSocketPayloadCorrupted(
                    HttpStatus::BadRequest,
                ));
            };
            let WebSocketReadState {
                full_frame,
                fragment_opcode,
                ..
            }: &mut WebSocketReadState = state;
            let Some(active_opcode) = fragment_opcode.as_ref() else {
                return Err(RequestError::WebSocketPayloadCorrupted(
                    HttpStatus::BadRequest,
                ));
            };
            let is_text: bool = active_opcode.is_text();
            let payload: &[u8] = frame.get_payload_data();
            if max_body_size != DEFAULT_LOW_SECURITY_MAX_BODY_SIZE
                && payload.len() > max_body_size.saturating_sub(full_frame.len())
            {
                return Err(RequestError::WebSocketFrameTooLarge(
                    HttpStatus::PayloadTooLarge,
                ));
            }
            full_frame.extend_from_slice(payload);
            if frame.get_fin() {
                *fragment_opcode = None;
                let body: Vec<u8> = mem::take(full_frame);
                if is_text && from_utf8(&body).is_err() {
                    return Err(RequestError::WebSocketInvalidUtf8(HttpStatus::BadRequest));
                }
                return Ok(Some(WebSocketParseStep::Message(body)));
            }
            Ok(None)
        }
        WebSocketOpcode::Reserved(_) => Err(RequestError::WebSocketOpcodeUnsupported(
            HttpStatus::NotImplemented,
        )),
    }
}

/// Drops an empty [`WebSocketReadState`] box so idle WebSocket connections retain zero parser heap.
///
/// # Arguments
///
/// - `&mut Option<Box<WebSocketReadState>>` - Connection's lazy WebSocket parsing state slot.
#[inline(always)]
pub(super) fn release_empty_ws_state(websocket_state: &mut Option<Box<WebSocketReadState>>) {
    let is_empty: bool = websocket_state
        .as_deref()
        .is_some_and(|st: &WebSocketReadState| {
            st.get_cursor() >= st.get_buffer().len()
                && st.get_full_frame().is_empty()
                && st.try_get_fragment_opcode().is_none()
        });
    if is_empty {
        *websocket_state = None;
    }
}

/// Polls one transport read for WebSocket frames, returning pooled buffers without zeroing or idle retention.
///
/// # Arguments
///
/// - `&mut Box<dyn Transport>` - Active connection transport.
/// - `&RequestConfig` - Buffer size and maximum body size limits.
/// - `&mut Option<Box<WebSocketReadState>>` - Lazily boxed partial/fragmented WebSocket state.
/// - `&mut bool` - Flag marking whether peer activity was observed since the last heartbeat.
/// - `&mut Context<'_>` - Task waker context.
///
/// # Returns
///
/// - `Poll<Result<WebSocketParseStep, RequestError>>` - Parsed step, pending readiness, EOF, or protocol error.
pub(super) fn poll_websocket_transport_step(
    transport: &mut Box<dyn Transport>,
    config: &RequestConfig,
    websocket_state: &mut Option<Box<WebSocketReadState>>,
    ws_client_response: &mut bool,
    cx: &mut Context<'_>,
) -> Poll<Result<WebSocketParseStep, RequestError>> {
    let capacity: usize = config.get_buffer_size();
    let max_body_size: usize = config.get_max_body_size();
    if let Some(state) = websocket_state.as_deref() {
        let unread: usize = state.get_buffer().len().saturating_sub(state.get_cursor());
        if max_body_size != DEFAULT_LOW_SECURITY_MAX_BODY_SIZE
            && unread > max_body_size.saturating_add(WS_MAX_FRAME_HEADER_BYTES)
        {
            return Poll::Ready(Err(RequestError::from(io::Error::new(
                io::ErrorKind::InvalidData,
                WEBSOCKET_FRAME_TOO_LARGE_ERROR,
            ))));
        }
    }
    let mut temporary: Vec<u8> = take_read_buffer(capacity);
    let mut read_buffer: ReadBuf<'_> = ReadBuf::new(&mut temporary[..capacity]);
    match Pin::new(&mut **transport).poll_read(cx, &mut read_buffer) {
        Poll::Pending => {
            return_read_buffer(temporary);
            Poll::Pending
        }
        Poll::Ready(Err(error)) => {
            return_read_buffer(temporary);
            Poll::Ready(Err(error.into()))
        }
        Poll::Ready(Ok(())) => {
            let len: usize = read_buffer.filled().len();
            if len == 0 {
                return_read_buffer(temporary);
                return Poll::Ready(Ok(WebSocketParseStep::Eof));
            }
            if websocket_state.is_none() {
                let decoded: Result<Option<(WebSocketFrame, usize)>, RequestError> =
                    WebSocketFrame::decode_ws_frame_checked(&temporary[..len], max_body_size);
                match decoded {
                    Err(error) => {
                        return_read_buffer(temporary);
                        return Poll::Ready(Err(error));
                    }
                    Ok(Some((frame, consumed))) => {
                        *ws_client_response = true;
                        if consumed < len {
                            *websocket_state = Some(Box::new(WebSocketReadState {
                                buffer: temporary[consumed..len].to_vec(),
                                ..WebSocketReadState::default()
                            }));
                        }
                        return_read_buffer(temporary);
                        let step: Result<Option<WebSocketParseStep>, RequestError> =
                            process_ws_frame(frame, max_body_size, websocket_state);
                        release_empty_ws_state(websocket_state);
                        return match step {
                            Ok(Some(parsed)) => Poll::Ready(Ok(parsed)),
                            Ok(None) => Poll::Ready(Ok(WebSocketParseStep::NeedMore)),
                            Err(error) => Poll::Ready(Err(error)),
                        };
                    }
                    Ok(None) => {
                        *websocket_state = Some(Box::new(WebSocketReadState {
                            buffer: temporary[..len].to_vec(),
                            ..WebSocketReadState::default()
                        }));
                        return_read_buffer(temporary);
                        return Poll::Ready(Ok(WebSocketParseStep::NeedMore));
                    }
                }
            }
            let Some(state) = websocket_state.as_deref_mut() else {
                return_read_buffer(temporary);
                return Poll::Ready(Err(RequestError::from(io::Error::new(
                    io::ErrorKind::InvalidData,
                    WEBSOCKET_STATE_ERROR,
                ))));
            };
            let cursor: usize = state.get_cursor();
            if cursor >= state.get_buffer().len() {
                state.set_cursor(0);
                state.get_mut_buffer().clear();
            } else if cursor > 0 {
                state.get_mut_buffer().drain(..cursor);
                state.set_cursor(0);
            }
            state.get_mut_buffer().extend_from_slice(&temporary[..len]);
            return_read_buffer(temporary);
            Poll::Ready(Ok(WebSocketParseStep::NeedMore))
        }
    }
}

/// Subscribes to a runtime-scoped shared staggered WebSocket heartbeat bucket for `interval_ms`.
///
/// # Arguments
///
/// - `u64` - Adjusted WebSocket ping interval in milliseconds.
///
/// # Returns
///
/// - `Receiver<u64>` - Watch receiver firing once every `interval_ms` without per-connection timers.
pub(super) fn subscribe_ws_heartbeat(interval_ms: u64) -> Receiver<u64> {
    let registry: &WsHeartbeatRegistry =
        WS_HEARTBEAT_WHEELS.get_or_init(|| sync::Mutex::new(HashMap::new()));
    let key: (Id, u64) = (Handle::current().id(), interval_ms);
    let Ok(mut map) = registry.lock() else {
        let (tx, rx): (Sender<u64>, Receiver<u64>) = watch::channel(0u64);
        drop(tx);
        return rx;
    };
    if let Some(existing) = map.get(&key)
        && existing.alive.load(Ordering::Acquire)
    {
        return existing.subscribe_staggered();
    }
    let wheel: Arc<WsHeartbeatWheel> = Arc::new(WsHeartbeatWheel::new(WS_HEARTBEAT_BUCKETS));
    let rx: Receiver<u64> = wheel.subscribe_staggered();
    let _: Option<Arc<WsHeartbeatWheel>> = map.insert(key, Arc::clone(&wheel));
    let step_micros: u64 = interval_ms
        .saturating_mul(WS_MICROS_PER_MS)
        .checked_div(WS_HEARTBEAT_BUCKETS as u64)
        .unwrap_or(WS_HEARTBEAT_MIN_STEP_MICROS)
        .max(WS_HEARTBEAT_MIN_STEP_MICROS);
    let step: Duration = Duration::from_micros(step_micros);
    let _: JoinHandle<()> = spawn(drive_ws_heartbeat_wheel(key, wheel, step));
    rx
}

/// Drives one shared staggered WebSocket heartbeat wheel until every subscribed connection closes.
///
/// # Arguments
///
/// - `(Id, u64)` - Runtime-scoped `(runtime_id, interval_ms)` registry key.
/// - `Arc<WsHeartbeatWheel>` - Shared staggered wheel to advance.
/// - `Duration` - Step interval between consecutive bucket ticks.
async fn drive_ws_heartbeat_wheel(key: (Id, u64), wheel: Arc<WsHeartbeatWheel>, step: Duration) {
    let mut ticker: Interval = interval(step);
    ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
    let _: Instant = ticker.tick().await;
    let bucket_count: usize = wheel.buckets.len();
    loop {
        let _: Instant = ticker.tick().await;
        if wheel.total_receivers() == 0 {
            let Some(registry) = WS_HEARTBEAT_WHEELS.get() else {
                wheel.alive.store(false, Ordering::Release);
                return;
            };
            if let Ok(mut map) = registry.lock()
                && wheel.total_receivers() == 0
            {
                wheel.alive.store(false, Ordering::Release);
                if map
                    .get(&key)
                    .is_some_and(|cur: &Arc<WsHeartbeatWheel>| Arc::ptr_eq(cur, &wheel))
                {
                    let _: Option<Arc<WsHeartbeatWheel>> = map.remove(&key);
                }
                return;
            }
        }
        let step_idx: usize = wheel.phase.fetch_add(1, Ordering::AcqRel) % bucket_count;
        wheel.buckets[step_idx].send_modify(|tick: &mut u64| {
            *tick = tick.wrapping_add(1);
        });
    }
}