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
pub mod emit_metadata;
pub mod emit_metadata_with_response;
pub mod emit_metadata_with_response_stream;
mod event_metadata;

use std::sync::Arc;

use tokio::io::AsyncWrite;
use tokio::sync::Mutex;
use tracing;

use crate::event::EventType;
use crate::ipc::context::Context;
use crate::payload::IntoPayload;
use crate::protocol::AsyncProtocolStream;

pub use emit_metadata_with_response_stream::ResponseStream;
use crate::prelude::emit_metadata::EmitMetadata;

#[macro_export]
macro_rules! poll_unwrap {
    ($val:expr) => {
        if let Some(v) = $val {
            v
        } else {
            tracing::error!("Polling a future with an invalid state.");
            return Poll::Ready(Err(Error::InvalidState));
        }
    };
}

type SendStream = Arc<Mutex<dyn AsyncWrite + Send + Sync + Unpin + 'static>>;

/// An abstraction over any type that implements the AsyncProtocolStream trait
/// to emit events and share a connection across multiple
/// contexts.
#[derive(Clone)]
pub struct StreamEmitter {
    stream: SendStream,
}

impl StreamEmitter {
    pub fn new<P: AsyncProtocolStream + 'static>(stream: P::OwnedSplitWriteHalf) -> Self {
        Self {
            stream: Arc::new(Mutex::new(stream)),
        }
    }

    #[tracing::instrument(level = "trace", skip(self, ctx, payload))]
    fn _emit<P: IntoPayload>(
        &self,
        ctx: Context,
        namespace: Option<String>,
        event: &str,
        payload: P,
        res_id: Option<u64>,
        event_type: EventType,
    ) -> EmitMetadata<P> {
        EmitMetadata::new(
            ctx,
            self.stream.clone(),
            event.to_string(),
            namespace,
            payload,
            res_id,
            event_type,
        )
    }

    /// Emits an event
    #[inline]
    pub(crate) fn emit<S: AsRef<str>, P: IntoPayload>(
        &self,
        ctx: Context,
        event: S,
        payload: P,
    ) -> EmitMetadata<P> {
        self._emit(
            ctx,
            None,
            event.as_ref(),
            payload,
            None,
            EventType::Initiator,
        )
    }

    /// Emits an event to a specific namespace
    #[inline]
    pub(crate) fn emit_to<S1: AsRef<str>, S2: AsRef<str>, P: IntoPayload>(
        &self,
        ctx: Context,
        namespace: S1,
        event: S2,
        payload: P,
    ) -> EmitMetadata<P> {
        self._emit(
            ctx,
            Some(namespace.as_ref().to_string()),
            event.as_ref(),
            payload,
            None,
            EventType::Initiator,
        )
    }

    /// Emits a raw event
    #[inline]
    pub(crate) fn emit_raw<P: IntoPayload>(
        &self,
        ctx: Context,
        res_id: Option<u64>,
        event: &str,
        namespace: Option<String>,
        event_type: EventType,
        payload: P,
    ) -> EmitMetadata<P> {
        self._emit(ctx, namespace, event, payload, res_id, event_type)
    }

    /// Emits a response to an event
    #[inline]
    pub(crate) fn emit_response<S: AsRef<str>, P: IntoPayload>(
        &self,
        ctx: Context,
        event_id: u64,
        event: S,
        payload: P,
    ) -> EmitMetadata<P> {
        self._emit(
            ctx,
            None,
            event.as_ref(),
            payload,
            Some(event_id),
            EventType::Response,
        )
    }

    /// Emits a response to an event to a namespace
    #[inline]
    pub(crate) fn emit_response_to<S1: AsRef<str>, S2: AsRef<str>, P: IntoPayload>(
        &self,
        ctx: Context,
        event_id: u64,
        namespace: S1,
        event: S2,
        payload: P,
    ) -> EmitMetadata<P> {
        self._emit(
            ctx,
            Some(namespace.as_ref().to_string()),
            event.as_ref(),
            payload,
            Some(event_id),
            EventType::Response,
        )
    }
}