pdk-unit 1.9.0

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

use crate::host::implementation::{FlowType, ProxyWasmStub};
use crate::tester::io::{RequestResponse, UnitFrame, UnitHttpResponse};
use crate::tester::unit_test::{add_request_properties, respond_call, Backends};
use pdk_websockets_lib::{Decoder, Encoder, Frame, SinkResult};
use proxy_wasm_stub::stub::Host;
use proxy_wasm_stub::traits::HttpContext;
use proxy_wasm_stub::types::{Action, BufferType, MapType};
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::{Rc, Weak};
use std::task::Poll;
// ── Upgrade ───────────────────────────────────────────────────────────────────

/// A handle to an in-progress WebSocket upgrade being processed by the policy.
///
/// Use [`poll`](Self::poll) to drive the upgrade handshake through
/// `on_http_request_headers` and `on_http_response_headers`.
#[derive(Clone)]
pub struct UnitTestUpgrade {
    pub(crate) inner: Rc<RefCell<InnerUnitUpgrade>>,
}

impl UnitTestUpgrade {
    pub(crate) fn new(inner: InnerUnitUpgrade) -> Self {
        Self {
            inner: Rc::new(RefCell::new(inner)),
        }
    }

    /// Advances the upgrade handshake.
    ///
    /// Returns `Poll::Ready(Ok(conn))` when the upgrade completes,
    /// `Poll::Ready(Err(response))` if the policy rejected, or
    /// `Poll::Pending` if waiting for an async call response.
    pub fn poll(&mut self) -> Poll<Result<UpgradeConnection, UnitHttpResponse>> {
        self.inner.borrow_mut().poll()
    }
}

#[derive(PartialOrd, PartialEq, Copy, Clone, Debug)]
enum UpgradeState {
    RequestHeaders,
    RequestHeadersPaused,
    ResponseHeaders,
    ResponseHeadersPaused,
    Done,
    Rejected,
}

pub(crate) struct InnerUnitUpgrade {
    state: UpgradeState,
    context_id: u32,
    chunk_size: usize,
    request: RequestResponse,
    http_context: Box<dyn HttpContext>,
    backends: Rc<RefCell<Backends>>,
    host: Rc<RefCell<ProxyWasmStub>>,
    cached_connection: Option<Rc<RefCell<ConnectionInner>>>,
    cached_response: Option<UnitHttpResponse>,
}

impl InnerUnitUpgrade {
    pub(crate) fn new(
        context_id: u32,
        request: RequestResponse,
        http_context: Box<dyn HttpContext>,
        backends: Rc<RefCell<Backends>>,
        host: Rc<RefCell<ProxyWasmStub>>,
        chunk_size: usize,
    ) -> Self {
        Self {
            state: UpgradeState::RequestHeaders,
            context_id,
            chunk_size,
            request,
            http_context,
            backends,
            host,
            cached_connection: None,
            cached_response: None,
        }
    }

    pub(crate) fn poll(&mut self) -> Poll<Result<UpgradeConnection, UnitHttpResponse>> {
        if let Poll::Ready(result) = self.build_result() {
            return Poll::Ready(result);
        }

        let context_id = self.context_id;
        self.host.borrow_mut().set_context(context_id);

        self.host.borrow_mut().set_flow_mode(FlowType::Upstream);
        self.resume();

        if self.state == UpgradeState::RequestHeaders {
            self.host.borrow_mut().create_map(
                context_id,
                MapType::HttpRequestHeaders,
                self.request
                    .headers()
                    .iter()
                    .map(|(k, v)| (k.clone(), v.as_bytes().to_vec()))
                    .collect(),
            );

            let action = self
                .http_context
                .on_http_request_headers(self.request.headers().len(), false);

            if action == Action::Pause && self.clear_send_response() {
                self.state = UpgradeState::Rejected;
            } else if action == Action::Pause {
                self.state = UpgradeState::RequestHeadersPaused;
            } else {
                self.state = UpgradeState::ResponseHeaders;
            }

            self.respond_calls();
        }

        self.host.borrow_mut().set_flow_mode(FlowType::Downstream);

        if self.state == UpgradeState::ResponseHeaders {
            let backend_response = self
                .backends
                .borrow()
                .backend
                .call(self.request.clone().into())
                .inner;
            let backend_response = add_request_properties(backend_response, context_id);

            self.host.borrow_mut().create_map(
                context_id,
                MapType::HttpResponseHeaders,
                backend_response
                    .headers()
                    .iter()
                    .map(|(k, v)| (k.clone(), v.as_bytes().to_vec()))
                    .collect(),
            );

            let num_headers = backend_response.headers().len();
            self.cached_response = Some(UnitHttpResponse::from(backend_response));

            let action = self
                .http_context
                .on_http_response_headers(num_headers, false);

            if action == Action::Pause && self.clear_send_response() {
                self.state = UpgradeState::Rejected;
            } else if action == Action::Pause {
                self.state = UpgradeState::ResponseHeadersPaused;
            } else {
                self.state = UpgradeState::Done;
            }

            self.respond_calls();
        }

        self.build_result()
    }

    fn build_result(&mut self) -> Poll<Result<UpgradeConnection, UnitHttpResponse>> {
        match self.state {
            UpgradeState::Done => Poll::Ready(Ok(self.build_connection())),
            UpgradeState::Rejected => Poll::Ready(Err(self.read_response().into())),
            _ => Poll::Pending,
        }
    }
    fn build_connection(&mut self) -> UpgradeConnection {
        if self.cached_connection.is_none() {
            let context_id = self.context_id;
            self.cached_connection = Some(Rc::new(RefCell::new(ConnectionInner {
                context_id,
                chunk_size: self.chunk_size,
                http_context: self.take_http_context(),
                backends: Rc::clone(&self.backends),
                host: Rc::clone(&self.host),
                connection_state: Default::default(),
            })));
        }
        let response = self
            .cached_response
            .clone()
            .unwrap_or_else(UnitHttpResponse::upgrade);
        UpgradeConnection::from_inner(
            Rc::clone(self.cached_connection.as_ref().unwrap()),
            response,
        )
    }

    fn resume(&mut self) -> bool {
        let resume = self.host.borrow_mut().clear_resume(self.context_id);
        let send_response = self.clear_send_response();
        assert!(!(resume && send_response));

        if resume {
            self.state = match self.state {
                UpgradeState::RequestHeadersPaused => UpgradeState::ResponseHeaders,
                UpgradeState::ResponseHeadersPaused => UpgradeState::Done,
                state => panic!("Called resume on non-paused upgrade state {state:?}"),
            };
            true
        } else if send_response {
            self.state = UpgradeState::Rejected;
            true
        } else {
            false
        }
    }

    fn clear_send_response(&mut self) -> bool {
        self.host.borrow_mut().clear_send_response(self.context_id)
    }

    fn respond_calls(&mut self) {
        let prev_flow = self.host.borrow_mut().set_flow_mode(FlowType::Async);
        let mut pending = self.host.borrow_mut().pending_calls(self.context_id);
        while !pending.is_empty() {
            for (id, upstream, call) in pending {
                respond_call(
                    self.http_context.as_mut(),
                    &self.host,
                    &self.backends,
                    self.context_id,
                    id,
                    upstream,
                    call,
                );
                if self.resume() {
                    self.host.borrow_mut().set_flow_mode(prev_flow);
                    return;
                }
            }
            pending = self.host.borrow_mut().pending_calls(self.context_id);
        }
        self.host.borrow_mut().set_flow_mode(prev_flow);
    }

    fn take_http_context(&mut self) -> Box<dyn HttpContext> {
        struct NoopHttp;
        impl proxy_wasm_stub::traits::Context for NoopHttp {}
        impl HttpContext for NoopHttp {}

        let mut placeholder: Box<dyn HttpContext> = Box::new(NoopHttp);
        std::mem::swap(&mut self.http_context, &mut placeholder);
        placeholder
    }

    fn read_response(&self) -> RequestResponse {
        let headers = self
            .host
            .borrow()
            .read_map(self.context_id, MapType::HttpResponseHeaders)
            .into_iter()
            .map(|(k, v)| (k, String::from_utf8(v).unwrap()))
            .collect();
        let body = self
            .host
            .borrow()
            .read_buffer(self.context_id, BufferType::HttpResponseBody);
        RequestResponse::create(headers, body, Default::default())
    }
}

// ── Connection ────────────────────────────────────────────────────────────────

/// A live upgraded WebSocket connection managed by the policy under test.
///
/// Obtained from [`UnitTest::upgrade`] or [`UnitTest::upgrade_partial`]. Use
/// [`client`](Self::client) and [`server`](Self::server) to exchange frames.
/// Pending outgoing calls triggered during body processing are resolved inline;
/// call [`UnitTest::tick`] for calls that require simulated time to elapse.
pub struct UpgradeConnection {
    inner: Rc<RefCell<ConnectionInner>>,
    response: UnitHttpResponse,
}

impl Drop for UpgradeConnection {
    fn drop(&mut self) {
        self.inner.borrow_mut().http_context.on_log();
        self.inner.borrow_mut().http_context.on_done();
    }
}

impl UpgradeConnection {
    fn from_inner(inner: Rc<RefCell<ConnectionInner>>, response: UnitHttpResponse) -> Self {
        Self { inner, response }
    }

    /// Returns the HTTP 101 response that completed the upgrade handshake.
    pub fn response(&self) -> &UnitHttpResponse {
        &self.response
    }

    /// Returns a client-side handle for sending frames to the server and reading frames back.
    pub fn client(&self) -> ClientHandle {
        ClientHandle {
            inner: Rc::clone(&self.inner),
        }
    }

    /// Returns a server-side handle for sending frames to the client and reading frames forwarded toward the server.
    pub fn server(&self) -> ServerHandle {
        ServerHandle {
            inner: Rc::clone(&self.inner),
        }
    }

    pub(crate) fn weak_inner(&self) -> Weak<RefCell<ConnectionInner>> {
        Rc::downgrade(&self.inner)
    }
}

// ── Handles ───────────────────────────────────────────────────────────────────

/// A handle for the client side of an upgraded WebSocket connection.
pub struct ClientHandle {
    inner: Rc<RefCell<ConnectionInner>>,
}

impl ClientHandle {
    /// Encode `frame` and deliver it to the policy via `on_http_request_body`.
    ///
    /// Outgoing calls triggered by the policy are resolved inline.
    pub fn send_to_server(&self, frame: UnitFrame) {
        self.inner.borrow_mut().send_upstream(vec![frame.frame])
    }

    #[cfg(feature = "experimental_websocket_bytes")]
    /// Deliver the bytes to the policy via `on_http_request_body`.
    pub fn send_bytes_to_server(&self, bytes: Vec<u8>) {
        self.inner.borrow_mut().send_upstream_bytes(bytes)
    }

    /// Dequeue the next frame forwarded back to the client by the policy, or `None`.
    pub fn next(&self) -> Option<UnitFrame> {
        self.inner
            .borrow_mut()
            .connection_state
            .client_ready_frames
            .pop_front()
            .map(|frame| UnitFrame { frame })
    }

    #[cfg(feature = "experimental_websocket_bytes")]
    /// Takes the bytes that reached the client.
    pub fn bytes(&self) -> Vec<u8> {
        self.inner
            .borrow_mut()
            .connection_state
            .client_ready_bytes
            .split_off(0)
    }
}

/// A handle for the server side of an upgraded WebSocket connection.
pub struct ServerHandle {
    inner: Rc<RefCell<ConnectionInner>>,
}

impl ServerHandle {
    /// Encode `frame` and deliver it to the policy via `on_http_response_body`.
    ///
    /// Outgoing calls triggered by the policy are resolved inline.
    pub fn send_to_client(&self, frame: UnitFrame) {
        self.inner.borrow_mut().send_downstream(vec![frame.frame])
    }

    #[cfg(feature = "experimental_websocket_bytes")]
    /// Deliver the bytes to the policy via `on_http_response_body`.
    pub fn send_bytes_to_client(&self, bytes: Vec<u8>) {
        self.inner.borrow_mut().send_downstream_bytes(bytes)
    }

    /// Dequeue the next frame forwarded toward the server by the policy, or `None`.
    pub fn next(&self) -> Option<UnitFrame> {
        self.inner
            .borrow_mut()
            .connection_state
            .server_ready_frames
            .pop_front()
            .map(|frame| UnitFrame { frame })
    }

    #[cfg(feature = "experimental_websocket_bytes")]
    /// Takes the bytes that reached the server.
    pub fn bytes(&self) -> Vec<u8> {
        self.inner
            .borrow_mut()
            .connection_state
            .server_ready_bytes
            .split_off(0)
    }
}

// ── Shared connection state ───────────────────────────────────────────────────

pub(crate) struct ConnectionInner {
    context_id: u32,
    chunk_size: usize,
    http_context: Box<dyn HttpContext>,
    backends: Rc<RefCell<Backends>>,
    host: Rc<RefCell<ProxyWasmStub>>,
    connection_state: ConnectionState,
}

#[derive(Copy, Clone)]
pub(crate) enum Direction {
    Upstream,
    Downstream,
}

#[derive(Default)]
struct ConnectionState {
    #[cfg(feature = "experimental_websocket_bytes")]
    server_ready_bytes: Vec<u8>,
    server_ready_decoder: Decoder,
    pub(crate) server_ready_frames: VecDeque<Frame>,
    pub(crate) upstream_paused: bool,
    #[cfg(feature = "experimental_websocket_bytes")]
    client_ready_bytes: Vec<u8>,
    client_ready_decoder: Decoder,
    pub(crate) client_ready_frames: VecDeque<Frame>,
    pub(crate) downstream_paused: bool,
}
impl ConnectionState {
    fn set_paused(&mut self, direction: Direction, value: bool) {
        match direction {
            Direction::Upstream => {
                self.upstream_paused = value;
            }
            Direction::Downstream => {
                self.downstream_paused = value;
            }
        }
    }

    fn on_body(
        &mut self,
        context_id: u32,
        context: &mut dyn HttpContext,
        host: Rc<RefCell<ProxyWasmStub>>,
        direction: Direction,
        bytes: Vec<u8>,
    ) -> Action {
        match direction {
            Direction::Upstream => {
                let mut buffer = host
                    .borrow()
                    .get_buffer(BufferType::HttpRequestBody, 0, usize::MAX)
                    .unwrap_or_default()
                    .unwrap_or_default();

                buffer.extend_from_slice(&bytes);

                let len = buffer.len();
                host.borrow_mut()
                    .create_buffer(context_id, BufferType::HttpRequestBody, buffer);

                context.on_http_request_body(len, false)
            }
            Direction::Downstream => {
                let mut buffer = host
                    .borrow()
                    .get_buffer(BufferType::HttpResponseBody, 0, usize::MAX)
                    .unwrap_or_default()
                    .unwrap_or_default();

                buffer.extend_from_slice(&bytes);

                let len = buffer.len();
                host.borrow_mut()
                    .create_buffer(context_id, BufferType::HttpResponseBody, buffer);
                context.on_http_response_body(len, false)
            }
        }
    }

    fn clean_buffer(&mut self, context_id: u32, host: &mut ProxyWasmStub, direction: Direction) {
        match direction {
            Direction::Upstream => {
                let bytes = host.read_buffer(context_id, BufferType::HttpRequestBody);
                #[cfg(feature = "experimental_websocket_bytes")]
                self.server_ready_bytes.extend_from_slice(&bytes);
                if let SinkResult::Complete(frames) = self.server_ready_decoder.sink(bytes) {
                    frames
                        .into_iter()
                        .for_each(|frame| self.server_ready_frames.push_back(frame))
                }
                host.create_buffer(context_id, BufferType::HttpRequestBody, vec![]);
            }
            Direction::Downstream => {
                let bytes = host.read_buffer(context_id, BufferType::HttpResponseBody);
                #[cfg(feature = "experimental_websocket_bytes")]
                self.client_ready_bytes.extend_from_slice(&bytes);
                if let SinkResult::Complete(frames) = self.client_ready_decoder.sink(bytes) {
                    frames
                        .into_iter()
                        .for_each(|frame| self.client_ready_frames.push_back(frame))
                }
                host.create_buffer(context_id, BufferType::HttpResponseBody, vec![]);
            }
        }
    }

    fn resume(&mut self, context_id: u32, host: &mut ProxyWasmStub, direction: Direction) {
        match direction {
            Direction::Upstream => {
                let resume = host.clear_resume_request(context_id);
                if resume && !self.upstream_paused {
                    panic!("Called resume on non-paused request state")
                }
                if resume {
                    self.clean_buffer(context_id, host, direction)
                }
            }
            Direction::Downstream => {
                let resume = host.clear_resume_response(context_id);
                if resume && !self.downstream_paused {
                    panic!("Called resume on non-paused response state")
                }
                if resume {
                    self.clean_buffer(context_id, host, direction)
                }
            }
        }
    }
}

impl ConnectionInner {
    pub(crate) fn send_upstream(&mut self, frames: Vec<Frame>) {
        let encoded = Encoder::default().encode_client(frames);
        self.send_upstream_bytes(encoded);
    }

    pub(crate) fn send_upstream_bytes(&mut self, bytes: Vec<u8>) {
        self.host.borrow_mut().set_flow_mode(FlowType::Upstream);
        self.drive(Direction::Upstream, bytes);
    }

    pub(crate) fn send_downstream(&mut self, frames: Vec<Frame>) {
        let encoded = Encoder::default().encode_server(frames);
        self.send_downstream_bytes(encoded);
    }

    pub(crate) fn send_downstream_bytes(&mut self, bytes: Vec<u8>) {
        self.host.borrow_mut().set_flow_mode(FlowType::Downstream);
        self.drive(Direction::Downstream, bytes);
    }

    fn drive(&mut self, direction: Direction, bytes: Vec<u8>) {
        self.host.borrow_mut().set_context(self.context_id);

        let mut start = 0;
        let mut end = 0;

        while end < bytes.len() {
            end += self.chunk_size;
            if end > bytes.len() {
                end = bytes.len();
            }

            let buffer = bytes[start..end].to_vec();
            let ctx = self.http_context.as_mut();
            let action = self.connection_state.on_body(
                self.context_id,
                ctx,
                Rc::clone(&self.host),
                direction,
                buffer,
            );
            match action {
                Action::Continue => {
                    self.connection_state.clean_buffer(
                        self.context_id,
                        &mut self.host.borrow_mut(),
                        direction,
                    );
                    self.connection_state.set_paused(direction, false);
                }
                Action::Pause => {
                    self.connection_state.set_paused(direction, true);
                }
                _ => {
                    panic!("unexpected action: {action:?}");
                }
            }
            start = end
        }

        self.respond_calls();
        self.resume(direction);
    }

    pub(crate) fn resume(&mut self, direction: Direction) {
        if self.host.borrow_mut().clear_send_response(self.context_id) {
            panic!("Called send response on websocket flow.")
        }

        self.connection_state
            .resume(self.context_id, &mut self.host.borrow_mut(), direction);
    }

    fn respond_calls(&mut self) {
        self.host.borrow_mut().set_context(self.context_id);
        let prev_flow = self.host.borrow_mut().set_flow_mode(FlowType::Async);
        let mut pending = self.host.borrow_mut().pending_calls(self.context_id);
        while !pending.is_empty() {
            for (id, upstream, call) in pending {
                respond_call(
                    self.http_context.as_mut(),
                    &self.host,
                    &self.backends,
                    self.context_id,
                    id,
                    upstream,
                    call,
                );
            }
            pending = self.host.borrow_mut().pending_calls(self.context_id);
        }
        self.host.borrow_mut().set_flow_mode(prev_flow);
    }
}

impl Drop for ConnectionInner {
    fn drop(&mut self) {
        self.host.borrow_mut().set_context(self.context_id);
        self.http_context.on_done();
    }
}