typeway-server 0.1.0

Server runtime for the typeway type-level web framework
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
//! Unified REST + gRPC serving.
//!
//! When the `grpc` feature is enabled, [`crate::Server::with_grpc`] returns a
//! [`GrpcServer`] that serves both REST and gRPC on the same port. Incoming
//! requests are routed based on the `content-type` header:
//!
//! - `application/grpc*` requests are dispatched directly to handlers via
//!   the native gRPC dispatch (HashMap lookup, real HTTP/2 trailers).
//! - All other requests are handled by the normal REST router.
//!
//! Built-in gRPC services (reflection and health check) are handled directly
//! by the multiplexer.
//!
//! # Example
//!
//! ```ignore
//! Server::<API>::new(handlers)
//!     .with_state(state)
//!     .with_grpc("UserService", "users.v1")
//!     .serve("0.0.0.0:3000".parse()?)
//!     .await?;
//! ```

use std::convert::Infallible;
use std::future::Future;
use std::marker::PhantomData;
use std::net::SocketAddr;
use std::sync::Arc;

use hyper_util::rt::{TokioExecutor, TokioIo};
use tokio::net::TcpListener;

use typeway_core::ApiSpec;
use typeway_grpc::health::HealthService;
use typeway_grpc::reflection::ReflectionService;
use typeway_grpc::service::{ApiToServiceDescriptor, GrpcServiceDescriptor};
use typeway_grpc::CollectRpcs;

use crate::body::BoxBody;
use crate::router::{Router, RouterService};

/// A server that serves both REST and gRPC on the same port.
///
/// Created by [`Server::with_grpc`](crate::server::Server::with_grpc).
/// gRPC requests are dispatched directly to handlers via HashMap lookup
/// with real HTTP/2 trailers. REST requests go through the normal router.
///
/// Includes built-in support for:
/// - **Server reflection** (`grpc.reflection.v1alpha`) — enabled by default,
///   allows tools like `grpcurl` to discover available services.
/// - **Health checking** (`grpc.health.v1.Health/Check`) — always enabled,
///   with a runtime-toggleable serving status for graceful shutdown.
///
/// # Type parameter
///
/// - `A`: The API type (a tuple of endpoints). Must implement both
///   [`ApiSpec`] and [`CollectRpcs`].
pub struct GrpcServer<A: ApiSpec> {
    router: Arc<Router>,
    service_name: String,
    package: String,
    reflection: ReflectionService,
    health: HealthService,
    reflection_enabled: bool,
    grpc_spec_json: Option<Arc<String>>,
    grpc_docs_html: Option<Arc<String>>,
    #[cfg(feature = "grpc-proto-binary")]
    transcoder: Option<Arc<typeway_grpc::ProtoTranscoder>>,
    _api: PhantomData<A>,
}

impl<A: ApiSpec + CollectRpcs> GrpcServer<A> {
    /// Create a new `GrpcServer` wrapping the given router.
    pub(crate) fn new(router: Arc<Router>, service_name: String, package: String) -> Self {
        let reflection = ReflectionService::from_api::<A>(&service_name, &package);
        let health = HealthService::new();
        GrpcServer {
            router,
            service_name,
            package,
            reflection,
            health,
            reflection_enabled: true,
            grpc_spec_json: None,
            grpc_docs_html: None,
            #[cfg(feature = "grpc-proto-binary")]
            transcoder: None,
            _api: PhantomData,
        }
    }

    /// Add shared application state accessible via
    /// [`State<T>`](crate::extract::State) extractors.
    pub fn with_state<T: Clone + Send + Sync + 'static>(self, state: T) -> Self {
        self.router.set_state_injector(Arc::new(move |ext| {
            ext.insert(state.clone());
        }));
        self
    }

    /// Enable or disable gRPC server reflection.
    pub fn with_reflection(mut self, enabled: bool) -> Self {
        self.reflection_enabled = enabled;
        self
    }

    /// Get a handle to the health service.
    pub fn health_service(&self) -> HealthService {
        self.health.clone()
    }

    /// Set a path prefix for all routes.
    pub fn nest(self, prefix: &str) -> Self {
        self.router.set_prefix(prefix);
        self
    }

    /// Set the maximum request body size in bytes.
    pub fn max_body_size(self, max: usize) -> Self {
        self.router.set_max_body_size(max);
        self
    }

    /// Serve a gRPC service specification at `GET /grpc-spec` (JSON) and an
    /// HTML documentation page at `GET /grpc-docs`.
    pub fn with_grpc_docs(mut self) -> Self {
        use typeway_grpc::spec::ApiToGrpcSpec;
        let spec = A::grpc_spec(&self.service_name, &self.package);
        let json = serde_json::to_string_pretty(&spec).expect("spec serialization");
        let html = typeway_grpc::docs_page::generate_docs_html(&spec);
        self.grpc_spec_json = Some(Arc::new(json));
        self.grpc_docs_html = Some(Arc::new(html));
        self
    }

    /// Serve a gRPC service specification with handler documentation applied.
    pub fn with_grpc_docs_with_handler_docs(mut self, docs: &[typeway_core::HandlerDoc]) -> Self {
        use typeway_grpc::spec::ApiToGrpcSpec;
        let spec = A::grpc_spec_with_docs(&self.service_name, &self.package, docs);
        let json = serde_json::to_string_pretty(&spec).expect("spec serialization");
        let html = typeway_grpc::docs_page::generate_docs_html(&spec);
        self.grpc_spec_json = Some(Arc::new(json));
        self.grpc_docs_html = Some(Arc::new(html));
        self
    }

    /// Enable binary protobuf support for standard gRPC client interop.
    #[cfg(feature = "grpc-proto-binary")]
    pub fn with_proto_binary(mut self) -> Self {
        use typeway_grpc::spec::ApiToGrpcSpec;
        let spec = A::grpc_spec(&self.service_name, &self.package);
        self.transcoder = Some(Arc::new(typeway_grpc::ProtoTranscoder::new(spec)));
        self
    }

    /// Start serving both REST and gRPC.
    pub async fn serve(
        self,
        addr: SocketAddr,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let listener = TcpListener::bind(addr).await?;
        tracing::info!("Listening on http://{addr} (REST + gRPC)");
        tracing::info!("  gRPC service: {}.{}", self.package, self.service_name);
        if self.reflection_enabled {
            tracing::info!("  gRPC reflection: enabled");
        }
        tracing::info!("  gRPC health check: enabled");
        self.serve_with_shutdown(listener, std::future::pending())
            .await
    }

    /// Start serving with graceful shutdown.
    pub async fn serve_with_shutdown(
        self,
        listener: TcpListener,
        shutdown: impl Future<Output = ()> + Send,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let multiplexer = self.build_multiplexer();

        tokio::pin!(shutdown);

        loop {
            tokio::select! {
                result = listener.accept() => {
                    let (stream, _) = result?;
                    let io = TokioIo::new(stream);
                    let svc = multiplexer.clone();
                    let hyper_svc = hyper_util::service::TowerToHyperService::new(svc);

                    tokio::task::spawn(async move {
                        if let Err(e) = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new())
                            .serve_connection(io, hyper_svc)
                            .await
                        {
                            tracing::debug!("Connection closed: {e}");
                        }
                    });
                }
                () = &mut shutdown => {
                    tracing::info!("Shutting down gracefully...");
                    return Ok(());
                }
            }
        }
    }

    /// Start serving with direct gRPC handlers registered.
    ///
    /// Direct handlers bypass the extractor pipeline for maximum throughput.
    /// Each entry is `(grpc_method_path, handler)`.
    #[cfg(feature = "protobuf")]
    pub async fn serve_with_direct_handlers(
        self,
        addr: SocketAddr,
        direct_handlers: Vec<(String, crate::grpc_direct::DirectHandler)>,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let listener = TcpListener::bind(addr).await?;
        tracing::info!("Listening on http://{addr} (REST + gRPC)");
        let multiplexer = self.build_multiplexer_with_directs(direct_handlers);

        let shutdown = std::future::pending::<()>();
        tokio::pin!(shutdown);

        loop {
            tokio::select! {
                result = listener.accept() => {
                    let (stream, _) = result?;
                    let io = TokioIo::new(stream);
                    let svc = multiplexer.clone();
                    let hyper_svc = hyper_util::service::TowerToHyperService::new(svc);
                    tokio::task::spawn(async move {
                        let _ = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new())
                            .serve_connection(io, hyper_svc)
                            .await;
                    });
                }
                () = &mut shutdown => { return Ok(()); }
            }
        }
    }

    /// Get a reference to the service descriptor.
    pub fn service_descriptor(&self) -> GrpcServiceDescriptor {
        A::service_descriptor(&self.service_name, &self.package)
    }

    /// Apply a Tower middleware layer.
    pub fn layer<L>(self, layer: L) -> LayeredGrpcServer<A, L::Service>
    where
        L: tower_layer::Layer<crate::grpc_dispatch::GrpcMultiplexer>,
        L::Service: tower_service::Service<
                http::Request<hyper::body::Incoming>,
                Response = http::Response<BoxBody>,
                Error = Infallible,
            > + Clone
            + Send
            + 'static,
        <L::Service as tower_service::Service<http::Request<hyper::body::Incoming>>>::Future:
            Send + 'static,
    {
        let multiplexer = self.build_multiplexer();
        LayeredGrpcServer {
            service: layer.layer(multiplexer),
            _api: PhantomData,
        }
    }

    /// Build the multiplexer, returning it with a mutable router for direct handler registration.
    #[cfg(feature = "protobuf")]
    fn build_multiplexer_with_directs(
        self,
        direct_handlers: Vec<(String, crate::grpc_direct::DirectHandler)>,
    ) -> crate::grpc_dispatch::GrpcMultiplexer {
        let descriptor = A::service_descriptor(&self.service_name, &self.package);
        let mut grpc_router =
            crate::grpc_dispatch::GrpcRouter::from_router(&self.router, &descriptor);
        for (path, handler) in direct_handlers {
            grpc_router.add_direct_handler(path, handler);
        }

        crate::grpc_dispatch::GrpcMultiplexer {
            rest: RouterService::new(self.router),
            grpc_router: Arc::new(grpc_router),
            reflection: Arc::new(self.reflection),
            health: self.health,
            reflection_enabled: self.reflection_enabled,
            grpc_spec_json: self.grpc_spec_json,
            grpc_docs_html: self.grpc_docs_html,
            #[cfg(feature = "grpc-proto-binary")]
            transcoder: self.transcoder,
        }
    }

    /// Build the native multiplexer from the current configuration.
    fn build_multiplexer(self) -> crate::grpc_dispatch::GrpcMultiplexer {
        let descriptor = A::service_descriptor(&self.service_name, &self.package);
        let grpc_router = crate::grpc_dispatch::GrpcRouter::from_router(&self.router, &descriptor);

        crate::grpc_dispatch::GrpcMultiplexer {
            rest: RouterService::new(self.router),
            grpc_router: Arc::new(grpc_router),
            reflection: Arc::new(self.reflection),
            health: self.health,
            reflection_enabled: self.reflection_enabled,
            grpc_spec_json: self.grpc_spec_json,
            grpc_docs_html: self.grpc_docs_html,
            #[cfg(feature = "grpc-proto-binary")]
            transcoder: self.transcoder,
        }
    }
}

/// A gRPC+REST server with Tower middleware layers applied.
pub struct LayeredGrpcServer<A: ApiSpec, S> {
    service: S,
    _api: PhantomData<A>,
}

impl<A, S> LayeredGrpcServer<A, S>
where
    A: ApiSpec + CollectRpcs,
    S: tower_service::Service<
            http::Request<hyper::body::Incoming>,
            Response = http::Response<BoxBody>,
            Error = Infallible,
        > + Clone
        + Send
        + 'static,
    S::Future: Send + 'static,
{
    /// Start serving both REST and gRPC.
    pub async fn serve(
        self,
        addr: SocketAddr,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let listener = TcpListener::bind(addr).await?;
        tracing::info!("Listening on http://{addr} (REST + gRPC, layered)");
        self.serve_with_shutdown(listener, std::future::pending())
            .await
    }

    /// Start serving with graceful shutdown.
    pub async fn serve_with_shutdown(
        self,
        listener: TcpListener,
        shutdown: impl Future<Output = ()> + Send,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let svc = self.service;
        tokio::pin!(shutdown);

        loop {
            tokio::select! {
                result = listener.accept() => {
                    let (stream, _) = result?;
                    let io = TokioIo::new(stream);
                    let svc = svc.clone();
                    let hyper_svc = hyper_util::service::TowerToHyperService::new(svc);

                    tokio::task::spawn(async move {
                        if let Err(e) = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new())
                            .serve_connection(io, hyper_svc)
                            .await
                        {
                            tracing::debug!("Connection closed: {e}");
                        }
                    });
                }
                () = &mut shutdown => {
                    tracing::info!("Shutting down gracefully...");
                    return Ok(());
                }
            }
        }
    }

    /// Apply another Tower middleware layer.
    pub fn layer<L>(self, layer: L) -> LayeredGrpcServer<A, L::Service>
    where
        L: tower_layer::Layer<S>,
        L::Service: tower_service::Service<
                http::Request<hyper::body::Incoming>,
                Response = http::Response<BoxBody>,
                Error = Infallible,
            > + Clone
            + Send
            + 'static,
        <L::Service as tower_service::Service<http::Request<hyper::body::Incoming>>>::Future:
            Send + 'static,
    {
        LayeredGrpcServer {
            service: layer.layer(self.service),
            _api: PhantomData,
        }
    }
}

/// Helper: create a [`GrpcServer`] from a router and service metadata.
pub(crate) fn make_grpc_server<A: ApiSpec + CollectRpcs>(
    router: Arc<Router>,
    service_name: &str,
    package: &str,
) -> GrpcServer<A> {
    GrpcServer::new(router, service_name.to_string(), package.to_string())
}

// ---------------------------------------------------------------------------
// EndpointToRpc / CollectRpcs delegation for wrapper types
// ---------------------------------------------------------------------------

use typeway_grpc::{EndpointToRpc, RpcMethod};

/// `Protected<Auth, E>` delegates gRPC mapping to the inner endpoint.
impl<Auth, E: EndpointToRpc> EndpointToRpc for crate::auth::Protected<Auth, E> {
    fn to_rpc() -> RpcMethod {
        E::to_rpc()
    }
}

/// `Validated<V, E>` delegates gRPC mapping to the inner endpoint.
impl<V: Send + Sync + 'static, E: EndpointToRpc> EndpointToRpc for crate::typed::Validated<V, E> {
    fn to_rpc() -> RpcMethod {
        E::to_rpc()
    }
}

// ---------------------------------------------------------------------------
// GrpcReady delegation for server-specific wrapper types
// ---------------------------------------------------------------------------

impl<Auth, E: typeway_grpc::GrpcReady> typeway_grpc::GrpcReady for crate::auth::Protected<Auth, E> {}

impl<V: Send + Sync + 'static, E: typeway_grpc::GrpcReady> typeway_grpc::GrpcReady
    for crate::typed::Validated<V, E>
{
}

// ---------------------------------------------------------------------------
// BindableEndpoint delegation for streaming wrapper types
// ---------------------------------------------------------------------------

use crate::handler_for::BindableEndpoint;

impl<E: BindableEndpoint> BindableEndpoint for typeway_grpc::streaming::ServerStream<E> {
    fn method() -> http::Method {
        E::method()
    }
    fn pattern() -> String {
        E::pattern()
    }
    fn match_fn() -> crate::router::MatchFn {
        E::match_fn()
    }
}

impl<E: BindableEndpoint> BindableEndpoint for typeway_grpc::streaming::ClientStream<E> {
    fn method() -> http::Method {
        E::method()
    }
    fn pattern() -> String {
        E::pattern()
    }
    fn match_fn() -> crate::router::MatchFn {
        E::match_fn()
    }
}

impl<E: BindableEndpoint> BindableEndpoint for typeway_grpc::streaming::BidirectionalStream<E> {
    fn method() -> http::Method {
        E::method()
    }
    fn pattern() -> String {
        E::pattern()
    }
    fn match_fn() -> crate::router::MatchFn {
        E::match_fn()
    }
}