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
// Copyright (c) 2026, Salesforce, Inc.,
// All rights reserved.
// For full license text, see the LICENSE.txt file

use std::{cell::RefCell, task::Waker};

use crate::types::HttpCid;

/// Manages WebSocket connection state after HTTP upgrade.
///
/// Handles buffer offsets, pause state, and waker notifications for async frame processing.
pub struct WebSocketReactor {
    #[allow(dead_code)]
    context_id: HttpCid,
    state: RefCell<RawWebSocketReactor>,
}

/// Internal state for WebSocket connection management.
struct RawWebSocketReactor {
    /// Waker for upstream (client→server) handler
    upstream_waker: Option<Waker>,
    /// Waker for downstream (server→client) handler
    downstream_waker: Option<Waker>,
    /// True if upstream data is ready to be read
    upstream_data_ready: bool,
    /// True if downstream data is ready to be read
    downstream_data_ready: bool,
    /// True if upstream (request) flow is paused
    upstream_paused: bool,
    /// True if downstream (response) flow is paused
    downstream_paused: bool,
}

impl WebSocketReactor {
    /// Creates a new WebSocketReactor for the given HTTP context.
    pub fn new(context_id: HttpCid) -> Self {
        Self {
            context_id,
            state: RefCell::new(RawWebSocketReactor {
                upstream_waker: None,
                downstream_waker: None,
                upstream_data_ready: false,
                downstream_data_ready: false,
                upstream_paused: true,   // Start paused
                downstream_paused: true, // Start paused
            }),
        }
    }

    /// Registers a waker for upstream (client→server) state.next() calls.
    pub fn register_upstream_waker(&self, waker: Waker) {
        #[cfg(feature = "debug-logs")]
        log::debug!("WebSocketReactor::register_upstream_waker");
        let mut state = self.state.borrow_mut();
        state.upstream_waker = Some(waker);
    }

    /// Registers a waker for downstream (server→client) state.next() calls.
    pub fn register_downstream_waker(&self, waker: Waker) {
        #[cfg(feature = "debug-logs")]
        log::debug!("WebSocketReactor::register_downstream_waker");
        let mut state = self.state.borrow_mut();
        state.downstream_waker = Some(waker);
    }

    /// Checks if upstream data is ready to be consumed.
    /// Clears the flag after checking (one-shot).
    pub fn poll_upstream_data_ready(&self) -> bool {
        let mut state = self.state.borrow_mut();
        if state.upstream_data_ready {
            #[cfg(feature = "debug-logs")]
            log::debug!("WebSocketReactor::poll_upstream_data_ready: true, clearing flag");
            state.upstream_data_ready = false;
            true
        } else {
            #[cfg(feature = "debug-logs")]
            log::debug!("WebSocketReactor::poll_upstream_data_ready: false");
            false
        }
    }

    /// Sets the upstream data-ready flag.
    pub fn set_upstream_data_ready(&self, ready: bool) {
        let mut state = self.state.borrow_mut();
        state.upstream_data_ready = ready;
    }

    /// Checks if downstream data is ready to be consumed.
    /// Clears the flag after checking (one-shot).
    pub fn poll_downstream_data_ready(&self) -> bool {
        let mut state = self.state.borrow_mut();
        if state.downstream_data_ready {
            #[cfg(feature = "debug-logs")]
            log::debug!("WebSocketReactor::poll_downstream_data_ready: true, clearing flag");
            state.downstream_data_ready = false;
            true
        } else {
            #[cfg(feature = "debug-logs")]
            log::debug!("WebSocketReactor::poll_downstream_data_ready: false");
            false
        }
    }

    /// Sets downstream data ready flag.
    pub fn set_downstream_data_ready(&self, ready: bool) {
        let mut state = self.state.borrow_mut();
        state.downstream_data_ready = ready;
    }

    /// Wakes the upstream (client→server) handler.
    pub fn wake_upstream(&self) {
        #[cfg(feature = "debug-logs")]
        log::debug!("WebSocketReactor::wake_upstream: setting upstream_data_ready=true");
        let mut state = self.state.borrow_mut();
        state.upstream_data_ready = true;
        if let Some(waker) = state.upstream_waker.take() {
            #[cfg(feature = "debug-logs")]
            log::debug!("WebSocketReactor::wake_upstream: waker found, calling wake()");
            waker.wake();
        } else {
            log::debug!(
                "WebSocketReactor::wake_upstream: NO waker registered (handler terminated or not started)"
            );
        }
    }

    /// Wakes the downstream (server→client) handler.
    pub fn wake_downstream(&self) {
        #[cfg(feature = "debug-logs")]
        log::debug!("WebSocketReactor::wake_downstream: setting downstream_data_ready=true");
        let mut state = self.state.borrow_mut();
        state.downstream_data_ready = true;
        if let Some(waker) = state.downstream_waker.take() {
            #[cfg(feature = "debug-logs")]
            log::debug!("WebSocketReactor::wake_downstream: waker found, calling wake()");
            waker.wake();
        } else {
            log::debug!(
                "WebSocketReactor::wake_downstream: NO waker registered (handler terminated or not started)"
            );
        }
    }

    /// Returns true if upstream (request) flow is paused.
    pub fn upstream_paused(&self) -> bool {
        let state = self.state.borrow();
        state.upstream_paused
    }

    /// Sets upstream (request) pause state.
    pub fn set_upstream_paused(&self, paused: bool) {
        #[cfg(feature = "debug-logs")]
        log::debug!("WebSocketReactor::set_upstream_paused({paused})");
        self.state.borrow_mut().upstream_paused = paused;
    }

    /// Returns true if downstream (response) flow is paused.
    pub fn downstream_paused(&self) -> bool {
        let state = self.state.borrow();
        state.downstream_paused
    }

    /// Sets downstream (response) pause state.
    pub fn set_downstream_paused(&self, paused: bool) {
        #[cfg(feature = "debug-logs")]
        log::debug!("WebSocketReactor::set_downstream_paused({paused})");
        self.state.borrow_mut().downstream_paused = paused;
    }
}

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

    fn create_reactor() -> WebSocketReactor {
        WebSocketReactor::new(HttpCid::from(1))
    }

    #[test]
    fn new_reactor_starts_with_paused_state() {
        let reactor = create_reactor();
        assert!(reactor.upstream_paused(), "Upstream should start paused");
    }

    #[test]
    fn set_upstream_paused_changes_state() {
        let reactor = create_reactor();

        reactor.set_upstream_paused(false);
        assert!(
            !reactor.upstream_paused(),
            "Should be unpaused after set_upstream_paused(false)"
        );

        reactor.set_upstream_paused(true);
        assert!(
            reactor.upstream_paused(),
            "Should be paused after set_upstream_paused(true)"
        );
    }

    #[test]
    fn poll_upstream_data_ready_starts_false() {
        let reactor = create_reactor();
        assert!(
            !reactor.poll_upstream_data_ready(),
            "Should start with no data ready"
        );
    }

    #[test]
    fn poll_upstream_data_ready_clears_flag() {
        let reactor = create_reactor();

        // Set flag manually
        reactor.state.borrow_mut().upstream_data_ready = true;

        // First poll returns true and clears
        assert!(
            reactor.poll_upstream_data_ready(),
            "First poll should return true"
        );

        // Second poll returns false (flag cleared)
        assert!(
            !reactor.poll_upstream_data_ready(),
            "Second poll should return false"
        );
    }

    #[test]
    fn downstream_paused_starts_true() {
        let reactor = create_reactor();
        assert!(
            reactor.downstream_paused(),
            "Downstream should start paused"
        );
    }

    #[test]
    fn set_downstream_paused_changes_state() {
        let reactor = create_reactor();

        reactor.set_downstream_paused(false);
        assert!(
            !reactor.downstream_paused(),
            "Should be unpaused after set_downstream_paused(false)"
        );

        reactor.set_downstream_paused(true);
        assert!(
            reactor.downstream_paused(),
            "Should be paused after set_downstream_paused(true)"
        );
    }

    #[test]
    fn poll_downstream_data_ready_starts_false() {
        let reactor = create_reactor();
        assert!(
            !reactor.poll_downstream_data_ready(),
            "Should start with no data ready"
        );
    }

    #[test]
    fn poll_downstream_data_ready_clears_flag() {
        let reactor = create_reactor();

        // Set flag manually
        reactor.state.borrow_mut().downstream_data_ready = true;

        // First poll returns true and clears
        assert!(
            reactor.poll_downstream_data_ready(),
            "First poll should return true"
        );

        // Second poll returns false (flag cleared)
        assert!(
            !reactor.poll_downstream_data_ready(),
            "Second poll should return false"
        );
    }

    #[test]
    fn set_upstream_data_ready_updates_flag() {
        let reactor = create_reactor();

        reactor.set_upstream_data_ready(true);
        assert!(
            reactor.poll_upstream_data_ready(),
            "Flag should be set to true"
        );

        reactor.set_upstream_data_ready(false);
        assert!(
            !reactor.poll_upstream_data_ready(),
            "Flag should be set to false"
        );
    }

    #[test]
    fn set_downstream_data_ready_updates_flag() {
        let reactor = create_reactor();

        reactor.set_downstream_data_ready(true);
        assert!(
            reactor.poll_downstream_data_ready(),
            "Flag should be set to true"
        );

        reactor.set_downstream_data_ready(false);
        assert!(
            !reactor.poll_downstream_data_ready(),
            "Flag should be set to false"
        );
    }

    #[test]
    fn wake_upstream_sets_data_ready() {
        let reactor = create_reactor();

        // Initially false
        assert!(!reactor.poll_upstream_data_ready());

        // Wake should set the flag
        reactor.wake_upstream();

        // Now should be true
        assert!(
            reactor.poll_upstream_data_ready(),
            "wake_upstream should set data_ready flag"
        );
    }

    #[test]
    fn wake_downstream_sets_data_ready() {
        let reactor = create_reactor();

        // Initially false
        assert!(!reactor.poll_downstream_data_ready());

        // Wake should set the flag
        reactor.wake_downstream();

        // Now should be true
        assert!(
            reactor.poll_downstream_data_ready(),
            "wake_downstream should set data_ready flag"
        );
    }

    #[test]
    fn register_upstream_waker_stores_waker() {
        use std::sync::{Arc, Mutex};
        use std::task::Wake;

        struct TestWaker {
            woken: Arc<Mutex<bool>>,
        }

        impl Wake for TestWaker {
            fn wake(self: Arc<Self>) {
                *self.woken.lock().unwrap() = true;
            }
        }

        let reactor = create_reactor();
        let woken = Arc::new(Mutex::new(false));
        let test_waker = Arc::new(TestWaker {
            woken: woken.clone(),
        });
        let waker = test_waker.clone().into();

        // Register the waker
        reactor.register_upstream_waker(waker);

        // Wake should call the waker
        reactor.wake_upstream();

        // Check that waker was called
        assert!(*woken.lock().unwrap(), "Waker should have been called");
    }

    #[test]
    fn register_downstream_waker_stores_waker() {
        use std::sync::{Arc, Mutex};
        use std::task::Wake;

        struct TestWaker {
            woken: Arc<Mutex<bool>>,
        }

        impl Wake for TestWaker {
            fn wake(self: Arc<Self>) {
                *self.woken.lock().unwrap() = true;
            }
        }

        let reactor = create_reactor();
        let woken = Arc::new(Mutex::new(false));
        let test_waker = Arc::new(TestWaker {
            woken: woken.clone(),
        });
        let waker = test_waker.clone().into();

        // Register the waker
        reactor.register_downstream_waker(waker);

        // Wake should call the waker
        reactor.wake_downstream();

        // Check that waker was called
        assert!(*woken.lock().unwrap(), "Waker should have been called");
    }

    #[test]
    fn wake_without_waker_does_not_panic() {
        let reactor = create_reactor();

        // Should not panic even without a registered waker
        reactor.wake_upstream();
        reactor.wake_downstream();

        // Data ready flags should still be set
        assert!(reactor.poll_upstream_data_ready());
        assert!(reactor.poll_downstream_data_ready());
    }
}