pdk-classy 1.3.0-alpha.0

PDK Classy
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
// Copyright 2023 Salesforce, Inc. All rights reserved.
use std::{
    cell::{Cell, RefCell},
    convert::TryFrom,
    ops::Deref,
    rc::Rc,
    task::{Poll, Waker},
};

use futures::{Stream, StreamExt};

use crate::{
    host::Host,
    reactor::http::{HttpReactor, WakerId},
    types::HttpCid,
};
use crate::{
    http_constants::{
        DEFAULT_PATH, HEADER_AUTHORITY, HEADER_METHOD, HEADER_PATH, HEADER_SCHEME, HEADER_STATUS,
    },
    reactor::http::ExchangePhase,
};

mod private {
    use crate::host::Host;

    pub trait Sealed {}

    pub trait BodyAccessor {
        fn read_body(host: &dyn Host, offset: usize, max_size: usize) -> Option<Vec<u8>>;

        fn write_body(host: &dyn Host, offset: usize, size: usize, value: &[u8]);
    }
}

use private::{BodyAccessor, Sealed};

pub trait Event: Sealed + Clone + Into<FiniteEvent> + TryFrom<FiniteEvent> + Unpin {
    fn kind() -> EventKind;

    fn body_size(&self) -> usize;

    fn should_pause(&self) -> bool;
}

pub trait After<S: Event>: Event {}
pub trait Before<S: Event>: Event {}

impl<A, B> Before<B> for A
where
    B: After<A>,
    A: Event,
{
}

pub trait BodyEvent: Event + BodyAccessor {
    fn end_of_stream(&self) -> bool;
}

pub trait HeadersEvent: Event {}

/// Alias name for CreateContext event
#[derive(Clone, Debug)]
pub struct Start {
    pub(crate) _context_id: HttpCid,
}

#[derive(Clone, Debug)]
pub struct RequestHeaders {
    pub(crate) _num_headers: usize,
    pub(crate) end_of_stream: bool,
}

impl HeadersEvent for RequestHeaders {}

#[derive(Clone, Debug)]
pub struct RequestBody {
    pub(crate) body_size: usize,
    pub(crate) end_of_stream: bool,
}

impl BodyEvent for RequestBody {
    fn end_of_stream(&self) -> bool {
        self.end_of_stream
    }
}

impl BodyAccessor for RequestBody {
    fn read_body(host: &dyn Host, offset: usize, max_size: usize) -> Option<Vec<u8>> {
        host.get_http_request_body(offset, max_size)
    }

    fn write_body(host: &dyn Host, offset: usize, size: usize, value: &[u8]) {
        host.set_http_request_body(offset, size, value)
    }
}

#[derive(Clone, Debug)]
pub struct RequestTrailers {
    pub(crate) _num_trailers: usize,
}

impl HeadersEvent for RequestTrailers {}

#[derive(Clone, Debug)]
pub struct ResponseHeaders {
    pub(crate) _num_headers: usize,
    pub(crate) end_of_stream: bool,
}

impl HeadersEvent for ResponseHeaders {}

#[derive(Clone, Debug)]
pub struct ResponseBody {
    pub(crate) body_size: usize,
    pub(crate) end_of_stream: bool,
}

impl BodyEvent for ResponseBody {
    fn end_of_stream(&self) -> bool {
        self.end_of_stream
    }
}

impl BodyAccessor for ResponseBody {
    fn read_body(host: &dyn Host, offset: usize, max_size: usize) -> Option<Vec<u8>> {
        host.get_http_response_body(offset, max_size)
    }

    fn write_body(host: &dyn Host, offset: usize, size: usize, value: &[u8]) {
        host.set_http_response_body(offset, size, value)
    }
}

#[derive(Clone, Debug)]
pub struct ResponseTrailers {
    pub(crate) _num_trailers: usize,
}

impl HeadersEvent for ResponseTrailers {}

#[derive(Clone, Debug)]
pub struct ExchangeComplete {}

macro_rules! should_pause {
    (RequestBody, $value:expr) => {
        !$value.end_of_stream
    };

    (ResponseBody, $value:expr) => {
        !$value.end_of_stream
    };

    ($event:ty, $value:expr) => {
        false
    };
}

macro_rules! body_size {
    (RequestBody, $value:expr) => {
        $value.body_size
    };

    (ResponseBody, $value:expr) => {
        $value.body_size
    };

    ($event:ty, $value:expr) => {
        0
    };
}

// Implements After trait for an Event
macro_rules! impl_after {

    ($event:ty) => {};

    ($event:ty, $($after:ty),*) => {
        $(impl After<$after> for $event {})*
        impl_after!($($after),*);
    };
}

// Implements After trait for an ordered sequence of events
macro_rules! after {

    ([] $($reversed:tt)*) => {
        impl_after!($($reversed),*); // base case
    };

    ([$first:tt $($rest:tt)*] $($reversed:tt)*) => {
        after!([$($rest)*] $first $($reversed)*);  // recursion
    };
}

macro_rules! finite_events {

    ($($event:ident,)+) => {

        #[derive(Clone, Copy, PartialEq, Eq, Debug)]
        pub enum EventKind {
            $($event),+
        }

        #[derive(Clone, Debug)]
        pub enum FiniteEvent {
            $($event($event)),+
        }

        impl FiniteEvent {
            pub fn kind(&self) -> EventKind {
                match self {
                    $(Self::$event(_) => EventKind::$event),+
                }
            }
        }

        after!([$($event)*]);

        $(
            impl Sealed for $event {}

            impl Event for $event {
                fn kind() -> EventKind {
                    EventKind::$event
                }

                fn should_pause(&self) -> bool {
                    should_pause!($event, self)
                }

                fn body_size(&self) -> usize {
                    body_size!($event, self)
                }
            }

            impl From<$event> for FiniteEvent {
                fn from(event: $event) -> Self {
                    Self::$event(event)
                }
            }

            impl TryFrom<FiniteEvent> for $event {
                type Error = FiniteEvent;

                fn try_from(finite_event: FiniteEvent) -> Result<Self, FiniteEvent> {
                    match finite_event {
                        FiniteEvent::$event(e) => Ok(e),
                        e => Err(e),
                    }
                }
            }
        )*
    };
}

finite_events! {
    Start,
    RequestHeaders,
    RequestBody,
    RequestTrailers,
    ResponseHeaders,
    ResponseBody,
    ResponseTrailers,
    ExchangeComplete,
}

impl PartialOrd for EventKind {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for EventKind {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.index().cmp(&other.index())
    }
}

impl EventKind {
    fn index(&self) -> usize {
        *self as usize
    }
}

pub struct Exchange<S: Event = Start> {
    pub(crate) reactor: Rc<HttpReactor>,
    pub(crate) host: Rc<dyn Host>,
    first_event: RefCell<Option<S>>,
    empty_stream: Cell<bool>,
    offset: Cell<usize>,
    event_count: Cell<usize>,
}

pub struct EventData<'a, S: Event> {
    exchange: &'a Exchange<S>,
    pub(crate) event: S,
    offset: usize,
}

impl<'a, S: Event> EventData<'a, S> {
    pub(crate) fn new(exchange: &'a Exchange<S>, event: S, offset: usize) -> Self {
        Self {
            exchange,
            event,
            offset,
        }
    }
}

pub trait HeadersAccessor {
    /// Known Limitations: The header value will be converted to an utf-8 String
    /// If the bytes correspond to a non utf-8 string they will be parsed as an iso_8859_1 encoding.
    fn header(&self, name: &str) -> Option<String>;

    /// Known Limitations: The header values will be converted to utf-8 Strings
    /// If the bytes correspond to a non utf-8 string they will be parsed as an iso_8859_1 encoding.
    fn headers(&self) -> Vec<(String, String)>;

    fn add_header(&self, name: &str, value: &str);

    fn set_header(&self, name: &str, value: &str);

    fn set_headers(&self, headers: Vec<(&str, &str)>);

    fn remove_header(&self, name: &str);
}

impl EventData<'_, RequestHeaders> {
    pub fn method(&self) -> String {
        self.header(HEADER_METHOD).unwrap_or_default()
    }

    pub fn scheme(&self) -> String {
        self.header(HEADER_SCHEME).unwrap_or_default()
    }

    pub fn authority(&self) -> String {
        self.header(HEADER_AUTHORITY).unwrap_or_default()
    }

    pub fn path(&self) -> String {
        self.header(HEADER_PATH)
            .unwrap_or_else(|| DEFAULT_PATH.to_string())
    }
}

impl EventData<'_, ResponseHeaders> {
    pub fn status_code(&self) -> u32 {
        self.header(HEADER_STATUS)
            .and_then(|status| status.parse::<u32>().ok())
            .unwrap_or_default()
    }
}

impl HeadersAccessor for EventData<'_, RequestHeaders> {
    fn header(&self, name: &str) -> Option<String> {
        self.exchange.host.get_http_request_header(name)
    }

    fn headers(&self) -> Vec<(String, String)> {
        self.exchange.host.get_http_request_headers()
    }

    fn add_header(&self, name: &str, value: &str) {
        self.exchange.host.add_http_request_header(name, value);
    }

    fn set_header(&self, name: &str, value: &str) {
        self.exchange
            .host
            .set_http_request_header(name, Some(value));
    }

    fn set_headers(&self, headers: Vec<(&str, &str)>) {
        self.exchange.host.set_http_request_headers(headers);
    }

    fn remove_header(&self, name: &str) {
        self.exchange.host.set_http_request_header(name, None);
    }
}

impl EventData<'_, RequestTrailers> {
    pub fn header(&self, name: &str) -> Option<String> {
        self.exchange.host.get_http_request_trailer(name)
    }

    pub fn headers(&self) -> Vec<(String, String)> {
        self.exchange.host.get_http_request_trailers()
    }
}

impl HeadersAccessor for EventData<'_, ResponseHeaders> {
    fn header(&self, name: &str) -> Option<String> {
        self.exchange.host.get_http_response_header(name)
    }

    fn headers(&self) -> Vec<(String, String)> {
        self.exchange.host.get_http_response_headers()
    }

    fn add_header(&self, name: &str, value: &str) {
        self.exchange.host.add_http_response_header(name, value);
    }

    fn set_header(&self, name: &str, value: &str) {
        self.exchange
            .host
            .set_http_response_header(name, Some(value));
    }

    fn set_headers(&self, headers: Vec<(&str, &str)>) {
        self.exchange.host.set_http_response_headers(headers);
    }

    fn remove_header(&self, name: &str) {
        self.exchange.host.set_http_response_header(name, None);
    }
}

impl<S: Event> Exchange<S> {
    pub(crate) fn new(
        reactor: Rc<HttpReactor>,
        host: Rc<dyn Host>,
        first_event: Option<S>,
    ) -> Self {
        let empty_stream = first_event
            .as_ref()
            .map(|e| !e.should_pause())
            .unwrap_or(false);
        Self {
            reactor,
            host,
            first_event: RefCell::new(first_event),
            empty_stream: Cell::new(empty_stream),
            event_count: Cell::new(0),
            offset: Cell::new(0),
        }
    }

    fn take_first_event(&self) -> Option<S> {
        self.first_event.borrow_mut().take()
    }

    pub fn event_data(&self) -> Option<EventData<S>>
    where
        S: HeadersEvent,
    {
        let finite_event = self.reactor.cloned_finite_event();
        S::try_from(finite_event)
            .ok()
            .map(|e| EventData::new(self, e, 0))
    }

    #[must_use]
    pub fn event_data_stream(&self) -> EventDataStream<S>
    where
        S: BodyEvent,
    {
        EventDataStream {
            id_and_waker: None,
            exchange: self,
        }
    }

    pub(crate) async fn wait_for_event<E>(self) -> Exchange<E>
    where
        E: Event,
        S: Before<E>,
    {
        let exchange: Exchange<E> =
            Exchange::new(Rc::clone(&self.reactor), Rc::clone(&self.host), None);

        // Ensure flow resume
        drop(self);

        let mut stream = EventDataStream {
            id_and_waker: None,
            exchange: &exchange,
        };
        let first_event = stream.next().await.map(|ed| ed.event);

        *exchange.first_event.borrow_mut() = first_event;
        exchange.offset.set(0);
        exchange.empty_stream.set(false);

        exchange
    }

    pub async fn wait_for_request_headers(self) -> Exchange<RequestHeaders>
    where
        S: Before<RequestHeaders>,
    {
        self.wait_for_event().await
    }

    pub async fn wait_for_request_body(self) -> Exchange<RequestBody>
    where
        S: Before<RequestBody>,
    {
        self.wait_for_event().await
    }

    pub(crate) async fn _wait_for_request_trailers(self) -> Exchange<RequestTrailers>
    where
        S: Before<RequestTrailers>,
    {
        self.wait_for_event().await
    }

    pub async fn wait_for_response_headers(self) -> Exchange<ResponseHeaders>
    where
        S: Before<ResponseHeaders>,
    {
        self.wait_for_event().await
    }

    pub async fn wait_for_response_body(self) -> Exchange<ResponseBody>
    where
        S: Before<ResponseBody>,
    {
        self.wait_for_event().await
    }

    pub(crate) async fn _wait_for_response_trailers(self) -> Exchange<ResponseTrailers>
    where
        S: Before<ResponseTrailers>,
    {
        self.wait_for_event().await
    }

    pub(crate) async fn _wait_for_exchange_complete(self) -> Exchange<ExchangeComplete>
    where
        S: Before<ExchangeComplete>,
    {
        self.wait_for_event().await
    }

    pub fn send_response(self, status_code: u32, headers: Vec<(&str, &str)>, body: Option<&[u8]>)
    where
        S: After<Start> + Before<ResponseHeaders>,
    {
        self.host
            .set_effective_context(self.reactor.context_id().into());
        self.reactor.set_paused(true);
        self.reactor.cancel_request();
        self.host.send_http_response(status_code, headers, body);
    }
}

impl<S: Event> Drop for Exchange<S> {
    fn drop(&mut self) {
        let reactor = &self.reactor;
        let host = &self.host;
        if !reactor.is_done() && reactor.paused() && !reactor.cancelled_request() {
            reactor.set_paused(false);

            host.set_effective_context(reactor.context_id().into());

            match reactor.phase() {
                ExchangePhase::Request => host.resume_http_request(),
                ExchangePhase::Response => host.resume_http_response(),
            }
        }
    }
}

impl<S> EventData<'_, S>
where
    S: BodyEvent,
{
    pub fn offset(&self) -> usize {
        self.offset
    }

    pub fn chunk_size(&self) -> usize {
        self.event.body_size()
    }

    pub fn read_body(&self, offset: usize, max_size: usize) -> Vec<u8> {
        S::read_body(self.exchange.host.deref(), offset, max_size).unwrap_or_default()
    }

    pub fn read_chunk(&self) -> Vec<u8> {
        self.read_body(self.offset, self.event.body_size())
    }

    pub fn read_payload(&self) -> Vec<u8> {
        self.read_body(0, self.event.body_size())
    }
}

pub struct EventDataStream<'e, S: Event> {
    exchange: &'e Exchange<S>,
    id_and_waker: Option<(WakerId, Waker)>,
}

impl<'e, S: Event> EventDataStream<'e, S> {
    fn process_event(&mut self, event: S) -> EventData<'e, S> {
        let exchange = self.exchange;
        let reactor = exchange.reactor.as_ref();
        reactor.set_paused(event.should_pause());
        let offset = exchange.offset.get();
        exchange.offset.set(event.body_size());
        exchange.empty_stream.set(!event.should_pause());
        EventData::new(exchange, event, offset)
    }
}

impl<'e, S: Event> Stream for EventDataStream<'e, S> {
    type Item = EventData<'e, S>;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> Poll<Option<Self::Item>> {
        let reactor = &self.exchange.reactor;
        let exchange = self.exchange;

        if exchange.empty_stream.get() {
            if let Some((id, _)) = self.id_and_waker.take() {
                // Deregister the waker from the reactor.
                reactor.remove_waker(S::kind(), id);
            }
            return Poll::Ready(None);
        }

        if reactor.current_event() >= S::kind() {
            let event_data = if let Some(event) = exchange.take_first_event() {
                if let Some((id, _)) = self.id_and_waker.take() {
                    // Deregister the waker from the reactor.
                    reactor.remove_waker(S::kind(), id);
                }
                Some(self.process_event(event))
            } else {
                let event_count = reactor.event_count();

                // Ensure that repeated events are not the same
                if event_count > exchange.event_count.get() {
                    exchange.event_count.set(event_count);
                    if let Ok(event) = S::try_from(reactor.cloned_finite_event()) {
                        Some(self.process_event(event))
                    } else {
                        None
                    }
                } else {
                    return Poll::Pending;
                }
            };

            Poll::Ready(event_data)
        } else {
            match &self.id_and_waker {
                None => {
                    // Register the waker in the reactor.
                    let id = reactor.insert_waker(S::kind(), cx.waker().clone());
                    self.id_and_waker = Some((id, cx.waker().clone()));
                }
                Some((id, w)) if !w.will_wake(cx.waker()) => {
                    // Deregister the waker from the reactor to remove the old waker.
                    reactor.remove_waker(S::kind(), *id);

                    // Register the waker in the reactor with the new waker.
                    let id = reactor.insert_waker(S::kind(), cx.waker().clone());
                    self.id_and_waker = Some((id, cx.waker().clone()));
                }
                Some(_) => {}
            }
            Poll::Pending
        }
    }
}