rama-ttrpc 0.4.0

ttRPC (gRPC for low-memory environments) support for rama
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
use std::borrow::Cow;
use std::future::{Future, pending};

use rama_core::futures::async_stream::try_stream_fn;
use rama_core::futures::future::FusedFuture as _;
use rama_core::futures::{FutureExt as _, Stream, StreamExt as _};
use rama_core::stream::wrappers::ReceiverStream;
use tokio::pin;
use tokio::sync::mpsc::{Sender, channel};
use tokio::sync::oneshot;

use crate::io::{StreamReceiver, StreamSender};
use crate::types::encoding::BufExt;
use crate::types::flags::Flags;
use crate::types::frame::StreamFrame;
use crate::types::message::MessageType;
use crate::types::protos::{Data, Request, Response};
use crate::{Client, Code, Result, Status};

pub trait RequestHandler {
    fn handle_unary_request<
        Input: prost::Message + Default + 'static,
        Output: prost::Message + Default + 'static,
    >(
        &self,
        service: &'static str,
        method: &'static str,
        payload: Input,
    ) -> impl Future<Output = Result<Output>> + Send;

    fn handle_server_streaming_request<
        Input: prost::Message + Default + 'static,
        Output: prost::Message + Default + 'static,
    >(
        &self,
        service: &'static str,
        method: &'static str,
        payload: Input,
    ) -> impl Stream<Item = Result<Output>> + Send;

    fn handle_client_streaming_request<
        Input: prost::Message + Default + 'static,
        Output: prost::Message + Default + 'static,
    >(
        &self,
        service: &'static str,
        method: &'static str,
        input: impl Stream<Item = Input> + Send,
    ) -> impl Future<Output = Result<Output>> + Send;

    fn handle_duplex_streaming_request<
        Input: prost::Message + Default + 'static,
        Output: prost::Message + Default + 'static,
    >(
        &self,
        service: &'static str,
        method: &'static str,
        input: impl Stream<Item = Input> + Send,
    ) -> impl Stream<Item = Result<Output>> + Send;
}

macro_rules! try_join_all {
    ($($e:expr),* $(,)?) => { async {
        tokio::try_join! { $($e),* }.map(drop)
    } };
}

macro_rules! join_first {
    ($($e:expr),* $(,)?) => { tokio::select! {
        $(res = $e => res),+
    } };
}

impl RequestHandler for Client {
    async fn handle_unary_request<
        Input: prost::Message + Default + 'static,
        Output: prost::Message + Default + 'static,
    >(
        &self,
        service: &'static str,
        method: &'static str,
        payload: Input,
    ) -> Result<Output> {
        let (output_tx, output_rx) = oneshot::channel();
        let metadata = self.context.metadata.keyvalue_iter().collect();
        let timeout = self.context.timeout;
        let deadline = timeout.deadline();

        let frame = StreamFrame {
            flags: Flags::empty(),
            message: Request {
                service: Cow::Borrowed(service),
                method: Cow::Borrowed(method),
                payload,
                metadata,
                timeout_nano: timeout.as_nanos(),
            },
        };

        let fut = self.spawn_stream(frame, move |res, stream| async move {
            res.await.map_err(Status::send_error)?;

            // The client reads its one response; any trailing frames are the server's concern
            // and we've already got our answer.
            let mut rx = stream.split().1;

            join_first! {
                handle_server_unary(&mut rx, output_tx),
                handle_timeout(deadline),
            }
        });

        tokio::select! {
            Err(err) = fut => Err(err),
            Ok(val) = output_rx => Ok(val),
            else => Err(Status::channel_closed()),
        }
    }

    fn handle_server_streaming_request<
        Input: prost::Message + Default + 'static,
        Output: prost::Message + Default + 'static,
    >(
        &self,
        service: &'static str,
        method: &'static str,
        payload: Input,
    ) -> impl Stream<Item = Result<Output>> + Send {
        let (output_tx, mut output_rx) = channel(crate::io::DEFAULT_MAX_BUFFERED_FRAMES);
        let metadata = self.context.metadata.keyvalue_iter().collect();
        let timeout = self.context.timeout;
        let deadline = timeout.deadline();

        let frame = StreamFrame {
            flags: Flags::REMOTE_CLOSED,
            message: Request {
                service: Cow::Borrowed(service),
                method: Cow::Borrowed(method),
                payload,
                metadata,
                timeout_nano: timeout.as_nanos(),
            },
        };

        let fut = self.spawn_stream(frame, move |res, stream| async move {
            res.await.map_err(Status::send_error)?;

            let mut rx = stream.split().1;

            join_first! {
                handle_server_stream(&mut rx, output_tx),
                handle_timeout(deadline),
            }
        });

        try_stream_fn(move |mut yielder| async move {
            let fut = fut.fuse();
            pin!(fut);
            loop {
                let next = tokio::select! {
                    Err(err) = &mut fut, if !fut.is_terminated() => Err(err),
                    Some(val) = output_rx.recv() => Ok(val),
                    else => break,
                };
                yielder.yield_ok(next?).await;
            }
            Ok(())
        })
    }

    async fn handle_client_streaming_request<
        Input: prost::Message + Default + 'static,
        Output: prost::Message + Default + 'static,
    >(
        &self,
        service: &'static str,
        method: &'static str,
        input: impl Stream<Item = Input> + Send,
    ) -> Result<Output> {
        let (output_tx, output_rx) = oneshot::channel();
        let (input, input_fut) = handle_input_stream(input);
        let metadata = self.context.metadata.keyvalue_iter().collect();
        let timeout = self.context.timeout;
        let deadline = timeout.deadline();

        let frame = StreamFrame {
            // Per the ttRPC spec, a still-sending client sets only REMOTE_OPEN; the request
            // payload is empty and stream data follows in Data frames (NO_DATA is Data-only).
            flags: Flags::REMOTE_OPEN,
            message: Request {
                service: Cow::Borrowed(service),
                method: Cow::Borrowed(method),
                payload: (),
                metadata,
                timeout_nano: timeout.as_nanos(),
            },
        };

        let fut = self.spawn_stream(frame, move |res, stream| async move {
            res.await.map_err(Status::send_error)?;

            let (tx, mut rx) = stream.split();

            let input = handle_client_stream(&tx, input);
            let output = handle_server_unary(&mut rx, output_tx);

            join_first! {
                try_join_all! {
                    input,
                    output,
                },
                handle_timeout(deadline),
            }
        });

        tokio::select! {
            Err(err) = input_fut => Err(err),
            Err(err) = fut => Err(err),
            Ok(val) = output_rx => Ok(val),
            else => Err(Status::channel_closed()),
        }
    }

    fn handle_duplex_streaming_request<
        Input: prost::Message + Default + 'static,
        Output: prost::Message + Default + 'static,
    >(
        &self,
        service: &'static str,
        method: &'static str,
        input: impl Stream<Item = Input> + Send,
    ) -> impl Stream<Item = Result<Output>> + Send {
        let (output_tx, mut output_rx) = channel::<Output>(crate::io::DEFAULT_MAX_BUFFERED_FRAMES);
        let (input, input_fut) = handle_input_stream(input);
        let metadata = self.context.metadata.keyvalue_iter().collect();
        let timeout = self.context.timeout;
        let deadline = timeout.deadline();

        let frame = StreamFrame {
            // Per the ttRPC spec, a still-sending client sets only REMOTE_OPEN; the request
            // payload is empty and stream data follows in Data frames (NO_DATA is Data-only).
            flags: Flags::REMOTE_OPEN,
            message: Request {
                service: Cow::Borrowed(service),
                method: Cow::Borrowed(method),
                payload: (),
                metadata,
                timeout_nano: timeout.as_nanos(),
            },
        };

        let fut = self.spawn_stream(frame, move |res, stream| async move {
            res.await.map_err(Status::send_error)?;

            let (tx, mut rx) = stream.split();

            let input = handle_client_stream(&tx, input);
            let output = handle_server_stream(&mut rx, output_tx);

            join_first! {
                try_join_all! {
                    input,
                    output,
                },
                handle_timeout(deadline),
            }
        });

        try_stream_fn(move |mut yielder| async move {
            let fut = fut.fuse();
            let input_fut = input_fut.fuse();
            pin!(fut);
            pin!(input_fut);
            loop {
                let next = tokio::select! {
                    _ = &mut input_fut, if !input_fut.is_terminated() => continue,
                    Err(err) = &mut fut, if !fut.is_terminated() => Err(err),
                    Some(val) = output_rx.recv() => Ok(val),
                    else => break,
                };
                yielder.yield_ok(next?).await;
            }
            Ok(())
        })
    }
}

async fn handle_client_stream<Input: prost::Message + Default>(
    tx: &StreamSender,
    strm: impl Stream<Item = Input>,
) -> Result<()> {
    struct CloseGuard<'a>(&'a StreamSender);
    impl<'a> Drop for CloseGuard<'a> {
        fn drop(&mut self) {
            self.0.close_data();
        }
    }

    let _guard = CloseGuard(tx);

    tokio::pin!(strm);
    while let Some(data) = strm.next().await {
        tx.data(data).await.map_err(Status::send_error)?;
    }

    Ok(())
}

async fn handle_server_unary<Output: prost::Message + Default>(
    rx: &mut StreamReceiver,
    tx: oneshot::Sender<Output>,
) -> Result<()> {
    let Some(frame) = rx.recv().await else {
        return Err(Status::channel_closed());
    };
    // Response-frame flags carry no meaning; like the Go client (containerd/ttrpc client.go
    // `RecvMsg` never reads them on Response frames) they are ignored.
    let response: Response = frame.message.decode().map_err(Status::failed_to_decode)?;
    let status = response.status.unwrap_or_default();
    if status.code != Code::Ok as i32 {
        return Err(status);
    }
    _ = tx.send(
        response
            .payload
            .decode()
            .map_err(Status::failed_to_decode)?,
    );
    Ok(())
}

async fn handle_server_stream<Output: prost::Message + Default>(
    rx: &mut StreamReceiver,
    tx: Sender<Output>,
) -> Result<()> {
    while let Some(frame) = rx.recv().await {
        if frame.message.ty == MessageType::Response {
            let response: Response = frame.message.decode().map_err(Status::failed_to_decode)?;
            response
                .payload
                .ensure_empty()
                .map_err(Status::failed_to_decode)?;
            let status = response.status.unwrap_or_default();
            // A final `Response` terminates the stream. An OK status is normal termination (the
            // spec permits a final empty OK response after streamed data), not an error.
            if status.code != Code::Ok as i32 {
                return Err(status);
            }
            return Ok(());
        }

        // Anything but Data fails the decode's type check, the per-call protocol error the Go
        // client also raises (containerd/ttrpc client.go `RecvMsg` default arm). Only the
        // REMOTE_CLOSED/NO_DATA flag bits are interpreted; other bits are ignored like Go.
        let Data { payload } = frame
            .message
            .decode::<Data>()
            .map_err(Status::failed_to_decode)?;

        if frame.flags.contains(Flags::NO_DATA) {
            payload.ensure_empty().map_err(Status::failed_to_decode)?;
        } else if tx
            .send(payload.decode().map_err(Status::failed_to_decode)?)
            .await
            .is_err()
        {
            // The consumer dropped the returned stream; stop reading (also applies backpressure
            // when the consumer is merely slow, since the bounded send awaits).
            return Ok(());
        }

        if frame.flags.contains(Flags::REMOTE_CLOSED) {
            break;
        }
    }

    Ok(())
}

async fn handle_timeout(deadline: Option<tokio::time::Instant>) -> Result<()> {
    match deadline {
        Some(deadline) => tokio::time::sleep_until(deadline).await,
        None => pending::<()>().await,
    }
    Err(Status::timeout())
}

fn handle_input_stream<T: Send>(
    input: impl Stream<Item = T> + Send,
) -> (ReceiverStream<T>, impl Future<Output = Result<()>> + Send) {
    let (tx, rx) = channel(crate::io::DEFAULT_MAX_BUFFERED_FRAMES);
    let fut = async move {
        pin!(input);
        while let Some(val) = input.next().await {
            // Bounded send: awaits (backpressuring the input) when the wire side is slow, and
            // errors once the receiver is gone. This also yields on a full channel, so an
            // always-ready input can no longer monopolize the runtime.
            if tx.send(val).await.is_err() {
                break;
            }
        }
        Ok(())
    };

    let input = ReceiverStream::new(rx);

    (input, fut)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn input_forwarding_does_not_monopolize_single_threaded_runtime() {
        let (done_tx, done_rx) = std::sync::mpsc::channel();

        std::thread::spawn(move || {
            let rt = tokio::runtime::Builder::new_current_thread()
                .build()
                .expect("build current-thread runtime");
            rt.block_on(async {
                let input = rama_core::futures::stream::repeat(0u8);
                let (recv, input_fut) = handle_input_stream(input);
                // Keep the receiver alive so the sender stays open.
                let _recv = recv;

                tokio::select! {
                    biased;
                    _ = input_fut => {}
                    _ = async {
                        for _ in 0..500 {
                            tokio::task::yield_now().await;
                        }
                    } => {}
                }
            });
            _ = done_tx.send(());
        });

        assert!(
            done_rx
                .recv_timeout(std::time::Duration::from_secs(2))
                .is_ok(),
            "input forwarding monopolized the single-threaded runtime"
        );
    }

    /// The ttRPC spec lets a server end a non-unary stream with a final OK `Response` (rather
    /// than a `Data(REMOTE_CLOSED)`). The client must treat that as clean termination, not turn
    /// it into `Err(Status { code: Ok })`.
    #[tokio::test]
    async fn server_stream_terminal_ok_response_ends_stream_cleanly() {
        use crate::io::StreamIo;
        use crate::server::method_handlers::MethodHandler;
        use crate::service::Service;
        use crate::types::protos::raw_bytes::RawBytes;
        use crate::{Client, ServerConnection};
        use rama_core::futures::StreamExt as _;
        use std::pin::Pin;
        use std::sync::Arc;

        #[derive(Clone, PartialEq, ::prost::Message)]
        struct Item {
            #[prost(uint32, tag = "1")]
            n: u32,
        }

        struct FinalOkService;
        impl Service for FinalOkService {
            fn methods(&self) -> Vec<(&'static str, Arc<dyn MethodHandler + Send + Sync>)> {
                vec![("/echo.Svc/Stream", Arc::new(FinalOkHandler))]
            }
        }

        struct FinalOkHandler;
        impl MethodHandler for FinalOkHandler {
            fn handle<'a>(
                &'a self,
                _flags: Flags,
                _payload: RawBytes,
                stream: &'a mut StreamIo,
            ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>> {
                Box::pin(async move {
                    stream
                        .tx
                        .data(Item { n: 7 })
                        .await
                        .map_err(Status::send_error)?;
                    // Terminate the stream with a final OK Response instead of Data(REMOTE_CLOSED).
                    stream.tx.respond(()).await.map_err(Status::send_error)?;
                    Ok(())
                })
            }
        }

        let (client_io, server_io) = tokio::io::duplex(64 * 1024);
        tokio::spawn(async move {
            let mut server = ServerConnection::new(server_io);
            server.register(FinalOkService);
            _ = server.start().await;
        });
        let client = Client::new(client_io);

        let stream = client.handle_server_streaming_request::<(), Item>("echo.Svc", "Stream", ());
        let got: Vec<Result<Item>> = Box::pin(stream).collect().await;

        let items: Vec<Item> = got
            .into_iter()
            .map(|r| r.expect("a terminal OK response must not surface as an error"))
            .collect();
        assert_eq!(items, vec![Item { n: 7 }]);
    }
}