avx-http 0.4.0

Pure Rust HTTP/1.1 + HTTP/2 implementation with ZERO dependencies - no tokio, no serde, no hyper, 100% proprietary
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
//! Hierarchical Timer Wheel for efficient timeout management
//!
//! Inspired by Kafka's timer implementation:
//! - O(1) insertion
//! - O(1) cancellation
//! - O(m) expiration where m = number of expired timers
//!
//! Uses a hierarchical wheel with multiple levels of granularity

use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
use std::task::Waker;
use std::time::{Duration, Instant};

/// Timer wheel tick duration
const TICK_MS: u64 = 1;

/// Number of slots per wheel
const WHEEL_SIZE: usize = 256;

/// Timeout callback
type TimeoutCallback = Box<dyn FnOnce() + Send + 'static>;

/// Timer entry
struct TimerEntry {
    /// Expiration time
    expiration: Instant,
    /// Callback to execute on expiration
    callback: TimeoutCallback,
    /// Optional waker to wake
    waker: Option<Waker>,
}

/// A single wheel level
struct TimerWheel {
    /// Slots in this wheel
    slots: Vec<VecDeque<TimerEntry>>,
    /// Tick duration for this wheel
    tick_duration: Duration,
    /// Current tick
    current_tick: u64,
}

impl TimerWheel {
    fn new(tick_duration: Duration) -> Self {
        Self {
            slots: (0..WHEEL_SIZE).map(|_| VecDeque::new()).collect(),
            tick_duration,
            current_tick: 0,
        }
    }

    /// Add timer to this wheel, returning the entry if it can't be added
    fn add(&mut self, entry: TimerEntry, now: Instant) -> Option<TimerEntry> {
        let delay = entry.expiration.saturating_duration_since(now);
        let ticks = (delay.as_millis() as u64) / self.tick_duration.as_millis() as u64;

        // If timer is too far in the future for this wheel, return the entry back
        if ticks >= WHEEL_SIZE as u64 {
            return Some(entry);
        }

        let slot = ((self.current_tick + ticks) % WHEEL_SIZE as u64) as usize;
        self.slots[slot].push_back(entry);
        None
    }

    /// Advance wheel by one tick and return expired timers
    fn tick(&mut self, now: Instant) -> Vec<TimerEntry> {
        let slot_idx = (self.current_tick % WHEEL_SIZE as u64) as usize;
        self.current_tick += 1;

        // Collect expired timers
        let mut expired = Vec::new();
        while let Some(entry) = self.slots[slot_idx].pop_front() {
            if entry.expiration <= now {
                expired.push(entry);
            } else {
                // Timer moved to future wheel, needs re-insertion
                self.slots[slot_idx].push_back(entry);
            }
        }

        expired
    }
}

/// Hierarchical timer wheel
pub struct TimerWheelScheduler {
    /// Level 0: 1ms granularity (0-255ms)
    wheel_l0: TimerWheel,
    /// Level 1: 256ms granularity (256ms-65s)
    wheel_l1: TimerWheel,
    /// Level 2: 65s granularity (65s-4h)
    wheel_l2: TimerWheel,
    /// Start time
    start_time: Instant,
    /// Pending timers (too far in future)
    pending: Vec<TimerEntry>,
}

impl TimerWheelScheduler {
    /// Create new timer wheel
    pub fn new() -> Self {
        Self {
            wheel_l0: TimerWheel::new(Duration::from_millis(TICK_MS)),
            wheel_l1: TimerWheel::new(Duration::from_millis(TICK_MS * WHEEL_SIZE as u64)),
            wheel_l2: TimerWheel::new(Duration::from_millis(TICK_MS * WHEEL_SIZE as u64 * WHEEL_SIZE as u64)),
            start_time: Instant::now(),
            pending: Vec::new(),
        }
    }

    /// Schedule a timeout
    pub fn schedule<F>(&mut self, delay: Duration, callback: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let expiration = Instant::now() + delay;
        let entry = TimerEntry {
            expiration,
            callback: Box::new(callback),
            waker: None,
        };

        self.add_entry(entry);
    }

    /// Schedule with waker
    pub fn schedule_with_waker<F>(&mut self, delay: Duration, waker: Waker, callback: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let expiration = Instant::now() + delay;
        let entry = TimerEntry {
            expiration,
            callback: Box::new(callback),
            waker: Some(waker),
        };

        self.add_entry(entry);
    }

    /// Add entry to appropriate wheel
    fn add_entry(&mut self, mut entry: TimerEntry) {
        let now = Instant::now();

        // Try to add to L0 wheel (finest granularity)
        entry = match self.wheel_l0.add(entry, now) {
            Some(e) => e,
            None => return,
        };

        // Try L1 wheel
        entry = match self.wheel_l1.add(entry, now) {
            Some(e) => e,
            None => return,
        };

        // Try L2 wheel
        entry = match self.wheel_l2.add(entry, now) {
            Some(e) => e,
            None => return,
        };

        // Too far in future, add to pending
        self.pending.push(entry);
    }

    /// Advance time and process expired timers
    pub fn tick(&mut self) -> usize {
        let now = Instant::now();
        let mut expired_count = 0;

        // Tick L0 wheel
        let mut expired = self.wheel_l0.tick(now);
        expired_count += expired.len();

        // Execute callbacks
        for entry in expired.drain(..) {
            if let Some(waker) = entry.waker {
                waker.wake();
            }
            (entry.callback)();
        }

        // Cascade from L1 to L0 every 256 ticks
        if self.wheel_l0.current_tick % WHEEL_SIZE as u64 == 0 {
            let l1_expired = self.wheel_l1.tick(now);
            for entry in l1_expired {
                if let Some(entry) = self.wheel_l0.add(entry, now) {
                    // Shouldn't happen, but re-add to L1
                    let _ = self.wheel_l1.add(entry, now);
                }
            }
        }

        // Cascade from L2 to L1 every 256*256 ticks
        if self.wheel_l0.current_tick % (WHEEL_SIZE as u64 * WHEEL_SIZE as u64) == 0 {
            let l2_expired = self.wheel_l2.tick(now);
            for entry in l2_expired {
                let entry = match self.wheel_l1.add(entry, now) {
                    Some(e) => e,
                    None => continue,
                };

                let entry = match self.wheel_l2.add(entry, now) {
                    Some(e) => e,
                    None => continue,
                };

                self.pending.push(entry);
            }
        }

        // Process pending timers
        let pending: Vec<_> = self.pending.drain(..).collect();
        let mut still_pending = Vec::new();
        for entry in pending {
            if let Some(entry) = self.add_from_pending(entry, now) {
                still_pending.push(entry);
            }
        }
        self.pending = still_pending;

        expired_count
    }

    fn add_from_pending(&mut self, mut entry: TimerEntry, now: Instant) -> Option<TimerEntry> {
        entry = match self.wheel_l0.add(entry, now) {
            Some(e) => e,
            None => return None,
        };

        entry = match self.wheel_l1.add(entry, now) {
            Some(e) => e,
            None => return None,
        };

        entry = match self.wheel_l2.add(entry, now) {
            Some(e) => e,
            None => return None,
        };

        Some(entry)
    }

    /// Get time until next expiration
    pub fn time_until_next(&self) -> Option<Duration> {
        // Simplified: just return tick duration
        // Real implementation would scan wheels
        Some(Duration::from_millis(TICK_MS))
    }
}

impl Default for TimerWheelScheduler {
    fn default() -> Self {
        Self::new()
    }
}

/// Global timer wheel (thread-safe)
pub struct GlobalTimerWheel {
    inner: Arc<Mutex<TimerWheelScheduler>>,
}

impl GlobalTimerWheel {
    /// Create new global timer wheel
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(TimerWheelScheduler::new())),
        }
    }

    /// Schedule timeout
    pub fn schedule<F>(&self, delay: Duration, callback: F)
    where
        F: FnOnce() + Send + 'static,
    {
        let mut wheel = self.inner.lock().unwrap();
        wheel.schedule(delay, callback);
    }

    /// Tick the timer wheel
    pub fn tick(&self) -> usize {
        let mut wheel = self.inner.lock().unwrap();
        wheel.tick()
    }
}

impl Default for GlobalTimerWheel {
    fn default() -> Self {
        Self::new()
    }
}

/// Sleep future using timer wheel
pub struct Sleep {
    deadline: Instant,
    registered: bool,
}

impl Sleep {
    /// Create new sleep future
    pub fn new(duration: Duration) -> Self {
        Self {
            deadline: Instant::now() + duration,
            registered: false,
        }
    }
}

impl std::future::Future for Sleep {
    type Output = ();

    fn poll(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Self::Output> {
        if Instant::now() >= self.deadline {
            return std::task::Poll::Ready(());
        }

        if !self.registered {
            // In a real implementation, we'd register with the timer wheel here
            self.registered = true;
        }

        std::task::Poll::Pending
    }
}

/// Sleep for a duration
pub fn sleep(duration: Duration) -> Sleep {
    Sleep::new(duration)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_timer_wheel_creation() {
        let wheel = TimerWheelScheduler::new();
        assert_eq!(wheel.wheel_l0.slots.len(), WHEEL_SIZE);
    }

    #[test]
    fn test_schedule_immediate() {
        let mut wheel = TimerWheelScheduler::new();
        let called = Arc::new(Mutex::new(false));
        let called_clone = Arc::clone(&called);

        wheel.schedule(Duration::from_millis(1), move || {
            *called_clone.lock().unwrap() = true;
        });

        // Wait and tick
        std::thread::sleep(Duration::from_millis(5));
        wheel.tick();

        assert!(*called.lock().unwrap());
    }

    #[test]
    fn test_timer_wheel_tick() {
        let mut wheel = TimerWheelScheduler::new();

        let count = Arc::new(Mutex::new(0));
        let count_clone = Arc::clone(&count);

        // Schedule multiple timers
        for i in 0..10 {
            let c = Arc::clone(&count);
            wheel.schedule(Duration::from_millis(i * 10), move || {
                *c.lock().unwrap() += 1;
            });
        }

        // Tick multiple times
        for _ in 0..200 {
            wheel.tick();
            std::thread::sleep(Duration::from_millis(1));
        }

        assert!(*count.lock().unwrap() > 0);
    }

    #[test]
    fn test_global_timer_wheel() {
        let wheel = GlobalTimerWheel::new();

        let called = Arc::new(Mutex::new(false));
        let called_clone = Arc::clone(&called);

        wheel.schedule(Duration::from_millis(5), move || {
            *called_clone.lock().unwrap() = true;
        });

        // Manually tick since no runtime is running
        std::thread::sleep(Duration::from_millis(10));
        for _ in 0..20 {
            wheel.tick();
            std::thread::sleep(Duration::from_millis(1));
        }

        assert!(*called.lock().unwrap());
    }

    #[test]
    fn test_sleep_future() {
        let sleep = sleep(Duration::from_millis(10));
        // Future test would require executor
    }
}