forked from anthropics/connect-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.rs
More file actions
1442 lines (1307 loc) · 48.7 KB
/
handler.rs
File metadata and controls
1442 lines (1307 loc) · 48.7 KB
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Handler traits for implementing RPC methods.
//!
//! This module defines the traits that RPC method implementations must satisfy,
//! supporting both unary and streaming RPC patterns.
use std::pin::Pin;
use std::sync::Arc;
use buffa::Message;
use buffa::view::MessageView;
use buffa::view::OwnedView;
use bytes::Bytes;
use futures::Stream;
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::codec::CodecFormat;
use crate::error::ConnectError;
/// Decode a request message from bytes using the specified codec format.
///
/// This helper is used by both unary and streaming handler wrappers to avoid duplication.
pub(crate) fn decode_request<Req>(request: &Bytes, format: CodecFormat) -> Result<Req, ConnectError>
where
Req: Message + DeserializeOwned,
{
match format {
CodecFormat::Proto => Req::decode_from_slice(&request[..]).map_err(|e| {
ConnectError::invalid_argument(format!("failed to decode proto request: {e}"))
}),
CodecFormat::Json => serde_json::from_slice(request).map_err(|e| {
ConnectError::invalid_argument(format!("failed to decode JSON request: {e}"))
}),
}
}
/// Encode a response message to bytes using the specified codec format.
///
/// This helper is used by both unary and streaming handler wrappers to avoid duplication.
#[doc(hidden)] // exposed only for dispatcher::codegen (generated code)
pub fn encode_response<Res>(res: &Res, format: CodecFormat) -> Result<Bytes, ConnectError>
where
Res: Message + Serialize,
{
match format {
CodecFormat::Proto => Ok(res.encode_to_bytes()),
CodecFormat::Json => serde_json::to_vec(res)
.map(Bytes::from)
.map_err(|e| ConnectError::internal(format!("failed to encode JSON response: {e}"))),
}
}
/// Context passed to RPC handlers.
#[derive(Debug, Clone, Default)]
pub struct Context {
/// Request headers.
pub headers: http::HeaderMap,
/// Response headers to be set by the handler.
pub response_headers: http::HeaderMap,
/// Response trailers to be set by the handler.
pub trailers: http::HeaderMap,
/// Request timeout/deadline, if specified.
pub deadline: Option<std::time::Instant>,
/// Whether to compress the response. `None` uses the server's compression
/// policy. Set to `Some(false)` to disable compression for this response,
/// or `Some(true)` to force it.
pub compress_response: Option<bool>,
/// Request extensions carried from the underlying `http::Request`.
///
/// This is the passthrough for connection-scoped metadata that a
/// tower layer in front of the service can attach — TLS peer
/// certificates, remote socket address, auth context, etc. The
/// dispatch path moves `parts.extensions` here verbatim; handlers
/// read it with `ctx.extensions.get::<T>()`.
pub extensions: http::Extensions,
}
impl Context {
/// Create a new context with the given headers.
#[inline]
pub fn new(headers: http::HeaderMap) -> Self {
Self {
headers,
response_headers: http::HeaderMap::new(),
trailers: http::HeaderMap::new(),
deadline: None,
compress_response: None,
extensions: http::Extensions::new(),
}
}
/// Set the request deadline (absolute `Instant`).
///
/// Used by the server dispatch paths to expose the parsed timeout
/// to handlers, allowing deadline propagation to downstream calls.
#[inline]
#[must_use]
pub fn with_deadline(mut self, deadline: Option<std::time::Instant>) -> Self {
self.deadline = deadline;
self
}
/// Attach request extensions captured from the underlying `http::Request`.
///
/// Used by the server dispatch paths; see [`Context::extensions`].
#[inline]
#[must_use]
pub fn with_extensions(mut self, extensions: http::Extensions) -> Self {
self.extensions = extensions;
self
}
/// Set a response trailer.
pub fn set_trailer(&mut self, key: http::header::HeaderName, value: http::header::HeaderValue) {
self.trailers.insert(key, value);
}
/// Set whether to compress the response for this RPC.
pub fn set_compression(&mut self, enabled: bool) {
self.compress_response = Some(enabled);
}
/// Get a request header value.
#[inline]
pub fn header(&self, key: &http::header::HeaderName) -> Option<&http::header::HeaderValue> {
self.headers.get(key)
}
}
/// Type alias for a boxed future used in handlers.
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
/// Trait for unary RPC handlers.
///
/// A unary handler takes a single request message and returns a single response.
///
/// # Context Ownership
///
/// The handler takes ownership of [`Context`] and returns it along with the response.
/// This design is intentional for async compatibility:
///
/// - The returned future is `'static`, meaning it cannot borrow from external state
/// - Taking ownership allows the future to move the `Context` into itself
/// - Using `&mut Context` would require non-`'static` lifetimes, complicating tower integration
///
/// Handlers should set response headers/trailers on the context before returning:
///
/// ```ignore
/// async fn my_handler(mut ctx: Context, req: MyRequest) -> Result<(MyResponse, Context), ConnectError> {
/// ctx.response_headers.insert("x-custom-header", "value".parse().unwrap());
/// Ok((MyResponse::default(), ctx))
/// }
/// ```
pub trait Handler<Req, Res>: Send + Sync + 'static
where
Req: Message + Send + 'static,
Res: Message + Send + 'static,
{
/// Handle a unary RPC request.
fn call(
&self,
ctx: Context,
request: Req,
) -> BoxFuture<'static, Result<(Res, Context), ConnectError>>;
}
/// Wrapper that implements Handler for async functions.
pub struct FnHandler<F> {
f: Arc<F>,
}
impl<F> FnHandler<F> {
/// Create a new function handler.
pub fn new(f: F) -> Self {
Self { f: Arc::new(f) }
}
}
impl<F, Fut, Req, Res> Handler<Req, Res> for FnHandler<F>
where
F: Fn(Context, Req) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(Res, Context), ConnectError>> + Send + 'static,
Req: Message + Send + 'static,
Res: Message + Send + 'static,
{
fn call(
&self,
ctx: Context,
request: Req,
) -> BoxFuture<'static, Result<(Res, Context), ConnectError>> {
let f = Arc::clone(&self.f);
Box::pin(async move { f(ctx, request).await })
}
}
/// Trait for server streaming RPC handlers.
///
/// A streaming handler takes a single request and returns a stream of responses.
pub trait StreamingHandler<Req, Res>: Send + Sync + 'static
where
Req: Message + Send + 'static,
Res: Message + Send + 'static,
{
/// The stream type returned by this handler.
type Stream: Stream<Item = Result<Res, ConnectError>> + Send + 'static;
/// Handle a server streaming RPC request.
fn call(
&self,
ctx: Context,
request: Req,
) -> BoxFuture<'static, Result<(Self::Stream, Context), ConnectError>>;
}
/// Wrapper that implements StreamingHandler for async functions.
pub struct FnStreamingHandler<F> {
f: Arc<F>,
}
impl<F> FnStreamingHandler<F> {
/// Create a new function streaming handler.
pub fn new(f: F) -> Self {
Self { f: Arc::new(f) }
}
}
impl<F, Fut, S, Req, Res> StreamingHandler<Req, Res> for FnStreamingHandler<F>
where
F: Fn(Context, Req) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(S, Context), ConnectError>> + Send + 'static,
S: Stream<Item = Result<Res, ConnectError>> + Send + 'static,
Req: Message + Send + 'static,
Res: Message + Send + 'static,
{
type Stream = S;
fn call(
&self,
ctx: Context,
request: Req,
) -> BoxFuture<'static, Result<(Self::Stream, Context), ConnectError>> {
let f = Arc::clone(&self.f);
Box::pin(async move { f(ctx, request).await })
}
}
/// Helper function to create a streaming handler from an async function.
///
/// This is the recommended way to create streaming handlers from async functions.
///
/// # Example
///
/// ```rust,ignore
/// use connectrpc::{streaming_handler_fn, Context, ConnectError};
/// use futures::stream;
///
/// async fn my_handler(ctx: Context, req: MyRequest) -> Result<(impl Stream<Item = Result<MyResponse, ConnectError>>, Context), ConnectError> {
/// let responses = stream::iter(vec![
/// Ok(MyResponse { ... }),
/// Ok(MyResponse { ... }),
/// ]);
/// Ok((responses, ctx))
/// }
///
/// let router = Router::new()
/// .route_server_stream("my.Service", "Method", streaming_handler_fn(my_handler));
/// ```
pub fn streaming_handler_fn<F, Fut, S, Req, Res>(f: F) -> FnStreamingHandler<F>
where
F: Fn(Context, Req) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(S, Context), ConnectError>> + Send + 'static,
S: Stream<Item = Result<Res, ConnectError>> + Send + 'static,
Req: Message + Send + 'static,
Res: Message + Send + 'static,
{
FnStreamingHandler::new(f)
}
/// Type-erased handler for use in the router.
pub(crate) trait ErasedHandler: Send + Sync {
/// Handle a request with raw bytes and specified codec format.
fn call_erased(
&self,
ctx: Context,
request: Bytes,
format: CodecFormat,
) -> BoxFuture<'static, Result<(Bytes, Context), ConnectError>>;
/// Check if this is a streaming handler.
#[allow(dead_code)]
fn is_streaming(&self) -> bool;
}
/// Wrapper to erase the types from a unary handler.
///
/// The request and response types must implement both buffa::Message (for proto encoding)
/// and serde traits (for JSON encoding).
pub(crate) struct UnaryHandlerWrapper<H, Req, Res>
where
H: Handler<Req, Res>,
Req: Message + DeserializeOwned + Send + 'static,
Res: Message + Serialize + Send + 'static,
{
handler: Arc<H>,
_phantom: std::marker::PhantomData<fn(Req) -> Res>,
}
impl<H, Req, Res> UnaryHandlerWrapper<H, Req, Res>
where
H: Handler<Req, Res>,
Req: Message + DeserializeOwned + Send + 'static,
Res: Message + Serialize + Send + 'static,
{
/// Create a new wrapper around the given handler.
pub fn new(handler: H) -> Self {
Self {
handler: Arc::new(handler),
_phantom: std::marker::PhantomData,
}
}
}
impl<H, Req, Res> ErasedHandler for UnaryHandlerWrapper<H, Req, Res>
where
H: Handler<Req, Res>,
Req: Message + DeserializeOwned + Send + 'static,
Res: Message + Serialize + Send + 'static,
{
fn call_erased(
&self,
ctx: Context,
request: Bytes,
format: CodecFormat,
) -> BoxFuture<'static, Result<(Bytes, Context), ConnectError>> {
let handler = Arc::clone(&self.handler);
Box::pin(async move {
let req: Req = decode_request(&request, format)?;
let (res, ctx) = handler.call(ctx, req).await?;
let response_bytes = encode_response(&res, format)?;
Ok((response_bytes, ctx))
})
}
fn is_streaming(&self) -> bool {
false
}
}
/// Type alias for a boxed stream of encoded response bytes.
pub type BoxStream<T> = Pin<Box<dyn Stream<Item = T> + Send>>;
/// Type-erased streaming handler for use in the router.
pub(crate) trait ErasedStreamingHandler: Send + Sync {
/// Handle a streaming request with raw bytes and specified codec format.
///
/// Returns the initial context (with response headers) and a stream of encoded response bytes.
/// The stream yields `Result<Bytes, ConnectError>` for each response message.
fn call_erased(
&self,
ctx: Context,
request: Bytes,
format: CodecFormat,
) -> StreamingHandlerResult;
}
/// Result type for erased streaming handlers.
pub(crate) type StreamingHandlerResult =
BoxFuture<'static, Result<(BoxStream<Result<Bytes, ConnectError>>, Context), ConnectError>>;
/// Wrapper to erase the types from a server streaming handler.
pub(crate) struct ServerStreamingHandlerWrapper<H, Req, Res>
where
H: StreamingHandler<Req, Res>,
Req: Message + DeserializeOwned + Send + 'static,
Res: Message + Serialize + Send + 'static,
{
handler: Arc<H>,
_phantom: std::marker::PhantomData<fn(Req) -> Res>,
}
impl<H, Req, Res> ServerStreamingHandlerWrapper<H, Req, Res>
where
H: StreamingHandler<Req, Res>,
Req: Message + DeserializeOwned + Send + 'static,
Res: Message + Serialize + Send + 'static,
{
/// Create a new wrapper around the given streaming handler.
pub fn new(handler: H) -> Self {
Self {
handler: Arc::new(handler),
_phantom: std::marker::PhantomData,
}
}
}
impl<H, Req, Res> ErasedStreamingHandler for ServerStreamingHandlerWrapper<H, Req, Res>
where
H: StreamingHandler<Req, Res>,
Req: Message + DeserializeOwned + Send + 'static,
Res: Message + Serialize + Send + 'static,
{
fn call_erased(
&self,
ctx: Context,
request: Bytes,
format: CodecFormat,
) -> StreamingHandlerResult {
let handler = Arc::clone(&self.handler);
Box::pin(async move {
let req: Req = decode_request(&request, format)?;
let (stream, ctx) = handler.call(ctx, req).await?;
// Map the stream to encode each response
// Use .fuse() to make the stream safe to poll after returning None
let encoded_stream: BoxStream<Result<Bytes, ConnectError>> = {
use futures::StreamExt as _;
Box::pin(
futures::stream::unfold(
(
Box::pin(stream)
as Pin<Box<dyn Stream<Item = Result<Res, ConnectError>> + Send>>,
format,
),
async |(mut stream, format)| match stream.next().await {
Some(Ok(res)) => {
let encoded = encode_response(&res, format);
Some((encoded, (stream, format)))
}
Some(Err(e)) => Some((Err(e), (stream, format))),
None => None,
},
)
.fuse(),
)
};
Ok((encoded_stream, ctx))
})
}
}
/// Helper function to create a handler from an async function.
///
/// This is the recommended way to create handlers from async functions.
///
/// # Example
///
/// ```rust,ignore
/// use connectrpc::{handler_fn, Context, ConnectError};
///
/// async fn my_handler(ctx: Context, req: MyRequest) -> Result<(MyResponse, Context), ConnectError> {
/// Ok((MyResponse { ... }, ctx))
/// }
///
/// let router = Router::new()
/// .route("my.Service", "Method", handler_fn(my_handler));
/// ```
pub fn handler_fn<F, Fut, Req, Res>(f: F) -> FnHandler<F>
where
F: Fn(Context, Req) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(Res, Context), ConnectError>> + Send + 'static,
Req: Message + Send + 'static,
Res: Message + Send + 'static,
{
FnHandler::new(f)
}
/// Trait for client streaming RPC handlers.
///
/// A client streaming handler receives a stream of request messages and returns a single response.
pub trait ClientStreamingHandler<Req, Res>: Send + Sync + 'static
where
Req: Message + Send + 'static,
Res: Message + Send + 'static,
{
/// Handle a client streaming RPC request.
fn call(
&self,
ctx: Context,
requests: BoxStream<Result<Req, ConnectError>>,
) -> BoxFuture<'static, Result<(Res, Context), ConnectError>>;
}
/// Wrapper that implements ClientStreamingHandler for async functions.
pub struct FnClientStreamingHandler<F> {
f: Arc<F>,
}
impl<F> FnClientStreamingHandler<F> {
/// Create a new function client streaming handler.
pub fn new(f: F) -> Self {
Self { f: Arc::new(f) }
}
}
impl<F, Fut, Req, Res> ClientStreamingHandler<Req, Res> for FnClientStreamingHandler<F>
where
F: Fn(Context, BoxStream<Result<Req, ConnectError>>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(Res, Context), ConnectError>> + Send + 'static,
Req: Message + Send + 'static,
Res: Message + Send + 'static,
{
fn call(
&self,
ctx: Context,
requests: BoxStream<Result<Req, ConnectError>>,
) -> BoxFuture<'static, Result<(Res, Context), ConnectError>> {
let f = Arc::clone(&self.f);
Box::pin(async move { f(ctx, requests).await })
}
}
/// Helper function to create a client streaming handler from an async function.
pub fn client_streaming_handler_fn<F, Fut, Req, Res>(f: F) -> FnClientStreamingHandler<F>
where
F: Fn(Context, BoxStream<Result<Req, ConnectError>>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(Res, Context), ConnectError>> + Send + 'static,
Req: Message + Send + 'static,
Res: Message + Send + 'static,
{
FnClientStreamingHandler::new(f)
}
/// Type-erased client streaming handler for use in the router.
pub(crate) trait ErasedClientStreamingHandler: Send + Sync {
/// Handle a client streaming request with a stream of raw message bytes.
fn call_erased(
&self,
ctx: Context,
requests: BoxStream<Result<Bytes, ConnectError>>,
format: CodecFormat,
) -> BoxFuture<'static, Result<(Bytes, Context), ConnectError>>;
}
/// Wrapper to erase the types from a client streaming handler.
pub(crate) struct ClientStreamingHandlerWrapper<H, Req, Res>
where
H: ClientStreamingHandler<Req, Res>,
Req: Message + DeserializeOwned + Send + 'static,
Res: Message + Serialize + Send + 'static,
{
handler: Arc<H>,
_phantom: std::marker::PhantomData<fn(Req) -> Res>,
}
impl<H, Req, Res> ClientStreamingHandlerWrapper<H, Req, Res>
where
H: ClientStreamingHandler<Req, Res>,
Req: Message + DeserializeOwned + Send + 'static,
Res: Message + Serialize + Send + 'static,
{
/// Create a new wrapper around the given client streaming handler.
pub fn new(handler: H) -> Self {
Self {
handler: Arc::new(handler),
_phantom: std::marker::PhantomData,
}
}
}
impl<H, Req, Res> ErasedClientStreamingHandler for ClientStreamingHandlerWrapper<H, Req, Res>
where
H: ClientStreamingHandler<Req, Res>,
Req: Message + DeserializeOwned + Send + 'static,
Res: Message + Serialize + Send + 'static,
{
fn call_erased(
&self,
ctx: Context,
requests: BoxStream<Result<Bytes, ConnectError>>,
format: CodecFormat,
) -> BoxFuture<'static, Result<(Bytes, Context), ConnectError>> {
use futures::StreamExt as _;
let handler = Arc::clone(&self.handler);
Box::pin(async move {
// Map the raw bytes stream through decode to create a typed stream
let request_stream: BoxStream<Result<Req, ConnectError>> = Box::pin(
requests.map(move |result| result.and_then(|raw| decode_request(&raw, format))),
);
let (res, ctx) = handler.call(ctx, request_stream).await?;
let response_bytes = encode_response(&res, format)?;
Ok((response_bytes, ctx))
})
}
}
/// Trait for bidirectional streaming RPC handlers.
///
/// A bidi streaming handler receives a stream of request messages and returns a stream of responses.
pub trait BidiStreamingHandler<Req, Res>: Send + Sync + 'static
where
Req: Message + Send + 'static,
Res: Message + Send + 'static,
{
/// The stream type returned by this handler.
type Stream: Stream<Item = Result<Res, ConnectError>> + Send + 'static;
/// Handle a bidi streaming RPC request.
fn call(
&self,
ctx: Context,
requests: BoxStream<Result<Req, ConnectError>>,
) -> BoxFuture<'static, Result<(Self::Stream, Context), ConnectError>>;
}
/// Wrapper that implements BidiStreamingHandler for async functions.
pub struct FnBidiStreamingHandler<F> {
f: Arc<F>,
}
impl<F> FnBidiStreamingHandler<F> {
/// Create a new function bidi streaming handler.
pub fn new(f: F) -> Self {
Self { f: Arc::new(f) }
}
}
impl<F, Fut, S, Req, Res> BidiStreamingHandler<Req, Res> for FnBidiStreamingHandler<F>
where
F: Fn(Context, BoxStream<Result<Req, ConnectError>>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(S, Context), ConnectError>> + Send + 'static,
S: Stream<Item = Result<Res, ConnectError>> + Send + 'static,
Req: Message + Send + 'static,
Res: Message + Send + 'static,
{
type Stream = S;
fn call(
&self,
ctx: Context,
requests: BoxStream<Result<Req, ConnectError>>,
) -> BoxFuture<'static, Result<(Self::Stream, Context), ConnectError>> {
let f = Arc::clone(&self.f);
Box::pin(async move { f(ctx, requests).await })
}
}
/// Helper function to create a bidi streaming handler from an async function.
pub fn bidi_streaming_handler_fn<F, Fut, S, Req, Res>(f: F) -> FnBidiStreamingHandler<F>
where
F: Fn(Context, BoxStream<Result<Req, ConnectError>>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(S, Context), ConnectError>> + Send + 'static,
S: Stream<Item = Result<Res, ConnectError>> + Send + 'static,
Req: Message + Send + 'static,
Res: Message + Send + 'static,
{
FnBidiStreamingHandler::new(f)
}
// ============================================================================
// View-based handler infrastructure (zero-copy request deserialization)
// ============================================================================
/// Decode a request as an `OwnedView` from bytes using the specified codec format.
///
/// For proto-encoded requests, this is a true zero-copy decode — the view borrows
/// directly from the input bytes. For JSON-encoded requests, the data is first
/// deserialized to an owned message, then re-encoded to proto bytes and decoded as
/// a view. This JSON round-trip adds overhead relative to owned-type decoding, but
/// is negligible compared to JSON parsing itself.
#[doc(hidden)] // exposed only for dispatcher::codegen (generated code)
pub fn decode_request_view<ReqView>(
request: Bytes,
format: CodecFormat,
) -> Result<OwnedView<ReqView>, ConnectError>
where
ReqView: MessageView<'static> + Send,
ReqView::Owned: Message + DeserializeOwned,
{
match format {
CodecFormat::Proto => OwnedView::<ReqView>::decode(request).map_err(|e| {
ConnectError::invalid_argument(format!("failed to decode proto request: {e}"))
}),
CodecFormat::Json => {
let owned: ReqView::Owned = serde_json::from_slice(&request).map_err(|e| {
ConnectError::invalid_argument(format!("failed to decode JSON request: {e}"))
})?;
OwnedView::<ReqView>::from_owned(&owned)
.map_err(|e| ConnectError::internal(format!("failed to re-encode for view: {e}")))
}
}
}
/// Trait for unary RPC handlers using zero-copy request views.
pub trait ViewHandler<ReqView, Res>: Send + Sync + 'static
where
ReqView: MessageView<'static> + Send + Sync + 'static,
Res: Message + Send + 'static,
{
/// Handle a unary RPC request with a zero-copy view.
fn call(
&self,
ctx: Context,
request: OwnedView<ReqView>,
) -> BoxFuture<'static, Result<(Res, Context), ConnectError>>;
}
/// Wrapper that implements ViewHandler for async functions.
pub struct FnViewHandler<F> {
f: Arc<F>,
}
impl<F> FnViewHandler<F> {
/// Create a new function view handler.
pub fn new(f: F) -> Self {
Self { f: Arc::new(f) }
}
}
impl<F, Fut, ReqView, Res> ViewHandler<ReqView, Res> for FnViewHandler<F>
where
F: Fn(Context, OwnedView<ReqView>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(Res, Context), ConnectError>> + Send + 'static,
ReqView: MessageView<'static> + Send + Sync + 'static,
Res: Message + Send + 'static,
{
fn call(
&self,
ctx: Context,
request: OwnedView<ReqView>,
) -> BoxFuture<'static, Result<(Res, Context), ConnectError>> {
let f = Arc::clone(&self.f);
Box::pin(async move { f(ctx, request).await })
}
}
/// Helper function to create a view handler from an async function.
pub fn view_handler_fn<F, Fut, ReqView, Res>(f: F) -> FnViewHandler<F>
where
F: Fn(Context, OwnedView<ReqView>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(Res, Context), ConnectError>> + Send + 'static,
ReqView: MessageView<'static> + Send + Sync + 'static,
Res: Message + Send + 'static,
{
FnViewHandler::new(f)
}
/// Wrapper to erase the types from a unary view handler.
pub(crate) struct UnaryViewHandlerWrapper<H, ReqView, Res>
where
H: ViewHandler<ReqView, Res>,
ReqView: MessageView<'static> + Send + Sync + 'static,
ReqView::Owned: Message + DeserializeOwned,
Res: Message + Serialize + Send + 'static,
{
handler: Arc<H>,
_phantom: std::marker::PhantomData<fn(ReqView) -> Res>,
}
impl<H, ReqView, Res> UnaryViewHandlerWrapper<H, ReqView, Res>
where
H: ViewHandler<ReqView, Res>,
ReqView: MessageView<'static> + Send + Sync + 'static,
ReqView::Owned: Message + DeserializeOwned,
Res: Message + Serialize + Send + 'static,
{
pub fn new(handler: H) -> Self {
Self {
handler: Arc::new(handler),
_phantom: std::marker::PhantomData,
}
}
}
impl<H, ReqView, Res> ErasedHandler for UnaryViewHandlerWrapper<H, ReqView, Res>
where
H: ViewHandler<ReqView, Res>,
ReqView: MessageView<'static> + Send + Sync + 'static,
ReqView::Owned: Message + DeserializeOwned,
Res: Message + Serialize + Send + 'static,
{
fn call_erased(
&self,
ctx: Context,
request: Bytes,
format: CodecFormat,
) -> BoxFuture<'static, Result<(Bytes, Context), ConnectError>> {
let handler = Arc::clone(&self.handler);
Box::pin(async move {
let req = decode_request_view::<ReqView>(request, format)?;
let (res, ctx) = handler.call(ctx, req).await?;
let response_bytes = encode_response(&res, format)?;
Ok((response_bytes, ctx))
})
}
fn is_streaming(&self) -> bool {
false
}
}
/// Trait for server streaming RPC handlers using zero-copy request views.
pub trait ViewStreamingHandler<ReqView, Res>: Send + Sync + 'static
where
ReqView: MessageView<'static> + Send + Sync + 'static,
Res: Message + Send + 'static,
{
/// The stream type returned by this handler.
type Stream: Stream<Item = Result<Res, ConnectError>> + Send + 'static;
/// Handle a server streaming RPC request with a zero-copy view.
fn call(
&self,
ctx: Context,
request: OwnedView<ReqView>,
) -> BoxFuture<'static, Result<(Self::Stream, Context), ConnectError>>;
}
/// Wrapper that implements ViewStreamingHandler for async functions.
pub struct FnViewStreamingHandler<F> {
f: Arc<F>,
}
impl<F> FnViewStreamingHandler<F> {
/// Create a new function view streaming handler.
pub fn new(f: F) -> Self {
Self { f: Arc::new(f) }
}
}
impl<F, Fut, S, ReqView, Res> ViewStreamingHandler<ReqView, Res> for FnViewStreamingHandler<F>
where
F: Fn(Context, OwnedView<ReqView>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(S, Context), ConnectError>> + Send + 'static,
S: Stream<Item = Result<Res, ConnectError>> + Send + 'static,
ReqView: MessageView<'static> + Send + Sync + 'static,
Res: Message + Send + 'static,
{
type Stream = S;
fn call(
&self,
ctx: Context,
request: OwnedView<ReqView>,
) -> BoxFuture<'static, Result<(Self::Stream, Context), ConnectError>> {
let f = Arc::clone(&self.f);
Box::pin(async move { f(ctx, request).await })
}
}
/// Helper function to create a view streaming handler from an async function.
pub fn view_streaming_handler_fn<F, Fut, S, ReqView, Res>(f: F) -> FnViewStreamingHandler<F>
where
F: Fn(Context, OwnedView<ReqView>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(S, Context), ConnectError>> + Send + 'static,
S: Stream<Item = Result<Res, ConnectError>> + Send + 'static,
ReqView: MessageView<'static> + Send + Sync + 'static,
Res: Message + Send + 'static,
{
FnViewStreamingHandler::new(f)
}
/// Wrapper to erase the types from a server streaming view handler.
pub(crate) struct ServerStreamingViewHandlerWrapper<H, ReqView, Res>
where
H: ViewStreamingHandler<ReqView, Res>,
ReqView: MessageView<'static> + Send + Sync + 'static,
ReqView::Owned: Message + DeserializeOwned,
Res: Message + Serialize + Send + 'static,
{
handler: Arc<H>,
_phantom: std::marker::PhantomData<fn(ReqView) -> Res>,
}
impl<H, ReqView, Res> ServerStreamingViewHandlerWrapper<H, ReqView, Res>
where
H: ViewStreamingHandler<ReqView, Res>,
ReqView: MessageView<'static> + Send + Sync + 'static,
ReqView::Owned: Message + DeserializeOwned,
Res: Message + Serialize + Send + 'static,
{
pub fn new(handler: H) -> Self {
Self {
handler: Arc::new(handler),
_phantom: std::marker::PhantomData,
}
}
}
impl<H, ReqView, Res> ErasedStreamingHandler for ServerStreamingViewHandlerWrapper<H, ReqView, Res>
where
H: ViewStreamingHandler<ReqView, Res>,
ReqView: MessageView<'static> + Send + Sync + 'static,
ReqView::Owned: Message + DeserializeOwned,
Res: Message + Serialize + Send + 'static,
{
fn call_erased(
&self,
ctx: Context,
request: Bytes,
format: CodecFormat,
) -> StreamingHandlerResult {
let handler = Arc::clone(&self.handler);
Box::pin(async move {
let req = decode_request_view::<ReqView>(request, format)?;
let (stream, ctx) = handler.call(ctx, req).await?;
let encoded_stream: BoxStream<Result<Bytes, ConnectError>> = {
use futures::StreamExt as _;
Box::pin(
futures::stream::unfold(
(
Box::pin(stream)
as Pin<Box<dyn Stream<Item = Result<Res, ConnectError>> + Send>>,
format,
),
async |(mut stream, format)| match stream.next().await {
Some(Ok(res)) => {
let encoded = encode_response(&res, format);
Some((encoded, (stream, format)))
}
Some(Err(e)) => Some((Err(e), (stream, format))),
None => None,
},
)
.fuse(),
)
};
Ok((encoded_stream, ctx))
})
}
}
/// Trait for client streaming RPC handlers using zero-copy request views.
pub trait ViewClientStreamingHandler<ReqView, Res>: Send + Sync + 'static
where
ReqView: MessageView<'static> + Send + Sync + 'static,
Res: Message + Send + 'static,
{
/// Handle a client streaming RPC request with zero-copy view items.
fn call(
&self,
ctx: Context,
requests: BoxStream<Result<OwnedView<ReqView>, ConnectError>>,
) -> BoxFuture<'static, Result<(Res, Context), ConnectError>>;
}
/// Wrapper that implements ViewClientStreamingHandler for async functions.
pub struct FnViewClientStreamingHandler<F> {
f: Arc<F>,
}
impl<F> FnViewClientStreamingHandler<F> {
/// Create a new function view client streaming handler.
pub fn new(f: F) -> Self {
Self { f: Arc::new(f) }
}
}
impl<F, Fut, ReqView, Res> ViewClientStreamingHandler<ReqView, Res>
for FnViewClientStreamingHandler<F>
where
F: Fn(Context, BoxStream<Result<OwnedView<ReqView>, ConnectError>>) -> Fut
+ Send
+ Sync
+ 'static,
Fut: Future<Output = Result<(Res, Context), ConnectError>> + Send + 'static,
ReqView: MessageView<'static> + Send + Sync + 'static,
Res: Message + Send + 'static,
{
fn call(
&self,
ctx: Context,
requests: BoxStream<Result<OwnedView<ReqView>, ConnectError>>,
) -> BoxFuture<'static, Result<(Res, Context), ConnectError>> {
let f = Arc::clone(&self.f);
Box::pin(async move { f(ctx, requests).await })
}
}
/// Helper function to create a view client streaming handler from an async function.
pub fn view_client_streaming_handler_fn<F, Fut, ReqView, Res>(
f: F,
) -> FnViewClientStreamingHandler<F>
where
F: Fn(Context, BoxStream<Result<OwnedView<ReqView>, ConnectError>>) -> Fut
+ Send
+ Sync
+ 'static,
Fut: Future<Output = Result<(Res, Context), ConnectError>> + Send + 'static,
ReqView: MessageView<'static> + Send + Sync + 'static,
Res: Message + Send + 'static,
{
FnViewClientStreamingHandler::new(f)
}
/// Wrapper to erase the types from a client streaming view handler.
pub(crate) struct ClientStreamingViewHandlerWrapper<H, ReqView, Res>
where
H: ViewClientStreamingHandler<ReqView, Res>,
ReqView: MessageView<'static> + Send + Sync + 'static,
ReqView::Owned: Message + DeserializeOwned,
Res: Message + Serialize + Send + 'static,
{
handler: Arc<H>,
_phantom: std::marker::PhantomData<fn(ReqView) -> Res>,
}