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
use std::time::Duration;

use futures_util::{Stream, StreamExt};
use poem::{
    web::sse::{Event, SSE},
    IntoResponse, Response,
};

use crate::{
    payload::Payload,
    registry::{MetaMediaType, MetaResponse, MetaResponses, MetaSchema, MetaSchemaRef, Registry},
    types::{ToJSON, Type},
    ApiResponse,
};

type ToEventFn<T> = Box<dyn (FnMut(T) -> Event) + Send + 'static>;

/// An event stream payload.
///
/// Reference: <https://github.com/OAI/OpenAPI-Specification/issues/396#issuecomment-894718960>
pub struct EventStream<T: Stream + Send + 'static> {
    stream: T,
    keep_alive: Option<Duration>,
    to_event: Option<ToEventFn<T::Item>>,
}

impl<T: Stream + Send + 'static> EventStream<T> {
    /// Create an event stream payload.
    pub fn new(stream: T) -> Self {
        Self {
            stream,
            keep_alive: None,
            to_event: None,
        }
    }

    /// Set the keep alive interval.
    #[must_use]
    pub fn keep_alive(self, duration: Duration) -> Self {
        Self {
            keep_alive: Some(duration),
            ..self
        }
    }

    /// Set a function used to convert the message to SSE event.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use poem::web::sse::Event;
    /// use poem_openapi::{payload::EventStream, types::ToJSON, Object};
    ///
    /// #[derive(Debug, Object)]
    /// struct MyEvent {
    ///     value: i32,
    /// }
    ///
    /// EventStream::new(futures_util::stream::iter(vec![
    ///     MyEvent { value: 1 },
    ///     MyEvent { value: 2 },
    ///     MyEvent { value: 3 },
    /// ]))
    /// .to_event(|event| {
    ///     let json = event.to_json_string();
    ///     Event::message(json).event_type("push")
    /// });
    /// ```
    #[must_use]
    pub fn to_event(self, f: impl FnMut(T::Item) -> Event + Send + 'static) -> Self {
        Self {
            to_event: Some(Box::new(f)),
            ..self
        }
    }
}

impl<T: Stream<Item = E> + Send + 'static, E: Type + ToJSON> Payload for EventStream<T> {
    const CONTENT_TYPE: &'static str = "text/event-stream";

    fn schema_ref() -> MetaSchemaRef {
        MetaSchemaRef::Inline(Box::new(MetaSchema {
            items: Some(Box::new(E::schema_ref())),
            ..MetaSchema::new_with_format("array", "event-stream")
        }))
    }

    fn register(registry: &mut Registry) {
        E::register(registry);
    }
}

impl<T: Stream<Item = E> + Send + 'static, E: Type + ToJSON + 'static> IntoResponse
    for EventStream<T>
{
    fn into_response(self) -> Response {
        let mut sse = match self.to_event {
            Some(to_event) => SSE::new(self.stream.map(to_event)),
            None => SSE::new(
                self.stream
                    .map(|message| message.to_json_string())
                    .map(Event::message),
            ),
        };

        if let Some(keep_alive) = self.keep_alive {
            sse = sse.keep_alive(keep_alive);
        }

        sse.into_response()
    }
}

impl<T: Stream<Item = E> + Send + 'static, E: Type + ToJSON> ApiResponse for EventStream<T> {
    fn meta() -> MetaResponses {
        MetaResponses {
            responses: vec![MetaResponse {
                description: "",
                status: Some(200),
                content: vec![MetaMediaType {
                    content_type: Self::CONTENT_TYPE,
                    schema: Self::schema_ref(),
                }],
                headers: vec![],
            }],
        }
    }

    fn register(registry: &mut Registry) {
        E::register(registry);
    }
}