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
use std::{
    fmt,
    ops::{Bound, RangeBounds},
};

use derive_builder::Builder;

use crate::{
    downcast_box::DowncastBox,
    grpc_call::GrpcCode,
    hostcalls::{self, BufferType},
    log_concern, RootContext, Status, Upstream,
};

#[cfg(feature = "stream-metadata")]
use crate::hostcalls::MapType;

/// Outbound GRPC stream (bidirectional)
#[derive(Builder)]
#[builder(setter(into))]
#[builder(pattern = "owned")]
#[allow(clippy::type_complexity)]
pub struct GrpcStream<'a> {
    /// Upstream cluster to send the request to.
    pub cluster: Upstream<'a>,
    /// The GRPC service to call.
    pub service: &'a str,
    /// The GRPC service method to call.
    pub method: &'a str,
    /// Initial GRPC metadata to send with the request.
    #[builder(setter(each(name = "metadata")), default)]
    pub initial_metadata: Vec<(&'a str, &'a [u8])>,
    /// Callback to call when the server sends initial metadata.
    #[cfg(feature = "stream-metadata")]
    #[builder(setter(custom), default)]
    pub on_initial_metadata: Option<
        Box<
            dyn FnMut(
                &mut DowncastBox<dyn RootContext>,
                GrpcStreamHandle,
                &GrpcStreamInitialMetadata,
            ),
        >,
    >,
    /// Callback to call when the server sends a stream message.
    #[builder(setter(custom), default)]
    pub on_message: Option<
        Box<dyn FnMut(&mut DowncastBox<dyn RootContext>, GrpcStreamHandle, &GrpcStreamMessage)>,
    >,
    /// Callback to call when the server sends trailing metadata.
    #[cfg(feature = "stream-metadata")]
    #[builder(setter(custom), default)]
    pub on_trailing_metadata: Option<
        Box<
            dyn FnMut(
                &mut DowncastBox<dyn RootContext>,
                GrpcStreamHandle,
                &GrpcStreamTrailingMetadata,
            ),
        >,
    >,
    /// Callback to call when the stream closes.
    #[builder(setter(custom), default)]
    pub on_close: Option<Box<dyn FnOnce(&mut DowncastBox<dyn RootContext>, &GrpcStreamClose)>>,
}

impl<'a> GrpcStreamBuilder<'a> {
    /// Set an initial metadata callback
    #[cfg(feature = "stream-metadata")]
    pub fn on_initial_metadata<R: RootContext + 'static>(
        mut self,
        mut callback: impl FnMut(&mut R, GrpcStreamHandle, &GrpcStreamInitialMetadata) + 'static,
    ) -> Self {
        self.on_initial_metadata = Some(Some(Box::new(move |root, handle, metadata| {
            callback(
                root.as_any_mut().downcast_mut().expect("invalid root type"),
                handle,
                metadata,
            )
        })));
        self
    }

    /// Set a stream message callback
    pub fn on_message<R: RootContext + 'static>(
        mut self,
        mut callback: impl FnMut(&mut R, GrpcStreamHandle, &GrpcStreamMessage) + 'static,
    ) -> Self {
        self.on_message = Some(Some(Box::new(move |root, handle, message| {
            callback(
                root.as_any_mut().downcast_mut().expect("invalid root type"),
                handle,
                message,
            )
        })));
        self
    }

    /// Set a trailing metadata callback
    #[cfg(feature = "stream-metadata")]
    pub fn on_trailing_metadata<R: RootContext + 'static>(
        mut self,
        mut callback: impl FnMut(&mut R, GrpcStreamHandle, &GrpcStreamTrailingMetadata) + 'static,
    ) -> Self {
        self.on_trailing_metadata = Some(Some(Box::new(move |root, handle, metadata| {
            callback(
                root.as_any_mut().downcast_mut().expect("invalid root type"),
                handle,
                metadata,
            )
        })));
        self
    }

    /// Set a stream close callback
    pub fn on_close<R: RootContext + 'static>(
        mut self,
        callback: impl FnOnce(&mut R, &GrpcStreamClose) + 'static,
    ) -> Self {
        self.on_close = Some(Some(Box::new(move |root, close| {
            callback(
                root.as_any_mut().downcast_mut().expect("invalid root type"),
                close,
            )
        })));
        self
    }
}

/// GRPC stream handle to cancel, close, or send a message over a GRPC stream.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct GrpcStreamHandle(pub(crate) u32);

impl<'a> GrpcStream<'a> {
    /// Open a new outbound GRPC stream.
    pub fn open(self) -> Result<GrpcStreamHandle, Status> {
        let token = hostcalls::open_grpc_stream(
            &self.cluster.0,
            self.service,
            self.method,
            &self.initial_metadata,
        )?;

        #[cfg(feature = "stream-metadata")]
        if let Some(callback) = self.on_initial_metadata {
            crate::dispatcher::register_grpc_stream_initial_meta(token, callback);
        }
        if let Some(callback) = self.on_message {
            crate::dispatcher::register_grpc_stream_message(token, callback);
        }
        #[cfg(feature = "stream-metadata")]
        if let Some(callback) = self.on_trailing_metadata {
            crate::dispatcher::register_grpc_stream_trailing_metadata(token, callback);
        }
        if let Some(callback) = self.on_close {
            crate::dispatcher::register_grpc_stream_close(token, callback);
        }

        Ok(GrpcStreamHandle(token))
    }
}

impl GrpcStreamHandle {
    /// Attempts to cancel the GRPC stream
    pub fn cancel(&self) {
        hostcalls::cancel_grpc_stream(self.0).ok();
    }

    /// Closes the GRPC stream
    pub fn close(&self) {
        hostcalls::close_grpc_stream(self.0).ok();
    }

    /// Sends a message over the GRPC stream
    pub fn send(&self, message: Option<impl AsRef<[u8]>>, end_stream: bool) -> Result<(), Status> {
        hostcalls::send_grpc_stream_message(
            self.0,
            message.as_ref().map(|x| x.as_ref()),
            end_stream,
        )
    }
}

impl PartialEq<u32> for GrpcStreamHandle {
    fn eq(&self, other: &u32) -> bool {
        self.0 == *other
    }
}

impl PartialEq<GrpcStreamHandle> for u32 {
    fn eq(&self, other: &GrpcStreamHandle) -> bool {
        other == self
    }
}

impl fmt::Display for GrpcStreamHandle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// Response type for [`GrpcStream::on_initial_metadata`]
#[cfg(feature = "stream-metadata")]
pub struct GrpcStreamInitialMetadata {
    num_elements: usize,
}

#[cfg(feature = "stream-metadata")]
impl GrpcStreamInitialMetadata {
    pub(crate) fn new(num_elements: usize) -> Self {
        Self { num_elements }
    }

    /// Number of metadata elements
    pub fn num_elements(&self) -> usize {
        self.num_elements
    }

    /// Get all metadata elements
    pub fn all(&self) -> Vec<(String, Vec<u8>)> {
        log_concern(
            "grpc-stream-metadata-all",
            hostcalls::get_map(MapType::GrpcReceiveInitialMetadata),
        )
        .unwrap_or_default()
    }

    /// Get a specific metadata element
    pub fn value(&self, name: impl AsRef<str>) -> Option<Vec<u8>> {
        log_concern(
            "grpc-stream-metadata",
            hostcalls::get_map_value(MapType::GrpcReceiveInitialMetadata, name.as_ref()),
        )
    }
}

/// Response type for [`GrpcStream::on_message`]
pub struct GrpcStreamMessage {
    status_code: GrpcCode,
    body_size: usize,
    message: Option<String>,
}

impl GrpcStreamMessage {
    pub(crate) fn new(status_code: GrpcCode, message: Option<String>, body_size: usize) -> Self {
        Self {
            status_code,
            body_size,
            message,
        }
    }

    /// GRPC status code of the message
    pub fn status_code(&self) -> GrpcCode {
        self.status_code
    }

    /// Optional GRPC status message of the message
    pub fn status_message(&self) -> Option<&str> {
        self.message.as_deref()
    }

    /// Total size of the message body
    pub fn body_size(&self) -> usize {
        self.body_size
    }

    /// Get a range of the message body
    pub fn body(&self, range: impl RangeBounds<usize>) -> Option<Vec<u8>> {
        let start = match range.start_bound() {
            Bound::Included(x) => *x,
            Bound::Excluded(x) => x.saturating_sub(1),
            Bound::Unbounded => 0,
        };
        let size = match range.end_bound() {
            Bound::Included(x) => *x + 1,
            Bound::Excluded(x) => *x,
            Bound::Unbounded => self.body_size,
        }
        .min(self.body_size)
        .saturating_sub(start);
        log_concern(
            "grpc-stream-message-body",
            hostcalls::get_buffer(BufferType::GrpcReceiveBuffer, start, size),
        )
    }

    /// Get the entire message body
    pub fn full_body(&self) -> Option<Vec<u8>> {
        self.body(..self.body_size)
    }
}

/// Response type for [`GrpcStream::on_trailing_metadata`]
#[cfg(feature = "stream-metadata")]
pub struct GrpcStreamTrailingMetadata {
    num_elements: usize,
}

#[cfg(feature = "stream-metadata")]
impl GrpcStreamTrailingMetadata {
    pub(crate) fn new(num_elements: usize) -> Self {
        Self { num_elements }
    }

    /// Number of metadata elements
    pub fn num_elements(&self) -> usize {
        self.num_elements
    }

    /// Get all metadata elements
    pub fn all(&self) -> Vec<(String, Vec<u8>)> {
        log_concern(
            "grpc-stream-trailing-metadata-all",
            hostcalls::get_map(MapType::GrpcReceiveTrailingMetadata),
        )
        .unwrap_or_default()
    }

    /// Get a specific metadata element
    pub fn value(&self, name: impl AsRef<str>) -> Option<Vec<u8>> {
        log_concern(
            "grpc-stream-trailing-metadata",
            hostcalls::get_map_value(MapType::GrpcReceiveTrailingMetadata, name.as_ref()),
        )
    }
}

/// Response type for [`GrpcStream::on_close`]
pub struct GrpcStreamClose {
    handle_id: u32,
    status_code: GrpcCode,
    message: Option<String>,
}

impl GrpcStreamClose {
    pub(crate) fn new(token_id: u32, status_code: GrpcCode, message: Option<String>) -> Self {
        Self {
            handle_id: token_id,
            status_code,
            message,
        }
    }

    /// GRPC handle ID of the message
    pub fn handle_id(&self) -> u32 {
        self.handle_id
    }

    /// GRPC status code of the message
    pub fn status_code(&self) -> GrpcCode {
        self.status_code
    }

    /// Optional GRPC status message of the message
    pub fn status_message(&self) -> Option<&str> {
        self.message.as_deref()
    }
}