reinhardt-grpc 0.2.0

gRPC support for building RPC services
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
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
//! gRPC server configuration
//!
//! This module provides server-level configuration for gRPC services,
//! including message size limits, request timeouts, and connection limits
//! to prevent denial of service attacks.
//!
//! # Default Limits
//!
//! [`GrpcServerConfig`] provides sensible defaults for DoS protection:
//!
//! - **Message size**: 4MB for both encoding and decoding
//! - **Request timeout**: 30 seconds
//! - **Max concurrent connections**: 1000
//!
//! # Example
//!
//! ```rust
//! use reinhardt_grpc::server::GrpcServerConfig;
//! use std::time::Duration;
//!
//! // Use defaults
//! let config = GrpcServerConfig::default();
//! assert_eq!(config.max_decoding_message_size(), 4 * 1024 * 1024);
//! assert_eq!(config.request_timeout(), Duration::from_secs(30));
//! assert_eq!(config.max_concurrent_connections(), 1000);
//!
//! // Custom limits
//! let config = GrpcServerConfig::builder()
//!     .max_decoding_message_size(8 * 1024 * 1024)
//!     .request_timeout(Duration::from_secs(60))
//!     .max_concurrent_connections(500)
//!     .build();
//! ```
//!
//! # Tower Middleware Integration
//!
//! For rate limiting, use tower's middleware ecosystem with tonic. The
//! [`GrpcServerConfig`] values can be applied to a tonic server through
//! tower layers:
//!
//! ```rust,ignore
//! use tonic::transport::Server;
//! use tower::ServiceBuilder;
//! use tower::timeout::TimeoutLayer;
//! use tower::limit::ConcurrencyLimitLayer;
//! use reinhardt_grpc::server::GrpcServerConfig;
//!
//! let config = GrpcServerConfig::default();
//!
//! Server::builder()
//!     .layer(
//!         ServiceBuilder::new()
//!             .layer(TimeoutLayer::new(config.request_timeout()))
//!             .layer(ConcurrencyLimitLayer::new(config.max_concurrent_connections()))
//!             .into_inner(),
//!     )
//!     .add_service(my_service)
//!     .serve(addr)
//!     .await?;
//! ```

// The builder, impls, trait, doctests, and tests in this module all name the
// deprecated `GrpcServerConfig` during the 0.2 compatibility window.
#![allow(deprecated)]

use std::time::Duration;

/// Default maximum decoding (incoming) message size: 4MB
const DEFAULT_MAX_DECODING_MESSAGE_SIZE: usize = 4 * 1024 * 1024;

/// Default maximum encoding (outgoing) message size: 4MB
const DEFAULT_MAX_ENCODING_MESSAGE_SIZE: usize = 4 * 1024 * 1024;

/// Default request timeout: 30 seconds
const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

/// Default maximum concurrent connections: 1000
const DEFAULT_MAX_CONCURRENT_CONNECTIONS: usize = 1000;

/// Configuration for gRPC server DoS protection.
///
/// This struct holds configuration for message size limits, request
/// timeouts, and connection limits. Setting appropriate values prevents
/// denial of service attacks from oversized messages, slow requests,
/// and connection floods.
///
/// Use [`GrpcServerConfig::builder()`] to construct with custom values,
/// or [`GrpcServerConfig::default()`] for sensible defaults.
///
/// # Defaults
///
/// | Setting | Default |
/// |---------|---------|
/// | `max_decoding_message_size` | 4 MB |
/// | `max_encoding_message_size` | 4 MB |
/// | `request_timeout` | 30 seconds |
/// | `max_concurrent_connections` | 1000 |
///
/// # Example
///
/// ```rust
/// use reinhardt_grpc::server::GrpcServerConfig;
/// use std::time::Duration;
///
/// let config = GrpcServerConfig::builder()
///     .max_decoding_message_size(2 * 1024 * 1024)
///     .request_timeout(Duration::from_secs(60))
///     .max_concurrent_connections(500)
///     .build();
///
/// assert_eq!(config.max_decoding_message_size(), 2 * 1024 * 1024);
/// assert_eq!(config.request_timeout(), Duration::from_secs(60));
/// assert_eq!(config.max_concurrent_connections(), 500);
/// ```
#[deprecated(
	since = "0.2.0",
	note = "Use `GrpcServerSettings` with the `#[settings]` macro instead."
)]
#[derive(Debug, Clone)]
pub struct GrpcServerConfig {
	max_decoding_message_size: usize,
	max_encoding_message_size: usize,
	request_timeout: Duration,
	max_concurrent_connections: usize,
}

impl GrpcServerConfig {
	/// Create a new builder for `GrpcServerConfig`.
	pub fn builder() -> GrpcServerConfigBuilder {
		GrpcServerConfigBuilder::default()
	}

	/// Returns the maximum decoding (incoming) message size in bytes.
	pub fn max_decoding_message_size(&self) -> usize {
		self.max_decoding_message_size
	}

	/// Returns the maximum encoding (outgoing) message size in bytes.
	pub fn max_encoding_message_size(&self) -> usize {
		self.max_encoding_message_size
	}

	/// Returns the maximum message size in bytes.
	///
	/// This is an alias for [`max_decoding_message_size`](Self::max_decoding_message_size),
	/// representing the largest message the server will accept from clients.
	pub fn max_message_size(&self) -> usize {
		self.max_decoding_message_size
	}

	/// Returns the request timeout duration.
	///
	/// Requests exceeding this duration will be cancelled with a
	/// `DeadlineExceeded` status. Apply this via tower's `TimeoutLayer`.
	pub fn request_timeout(&self) -> Duration {
		self.request_timeout
	}

	/// Returns the maximum number of concurrent connections allowed.
	///
	/// Apply this via tower's `ConcurrencyLimitLayer` to prevent
	/// connection flood attacks.
	pub fn max_concurrent_connections(&self) -> usize {
		self.max_concurrent_connections
	}
}

impl Default for GrpcServerConfig {
	fn default() -> Self {
		Self {
			max_decoding_message_size: DEFAULT_MAX_DECODING_MESSAGE_SIZE,
			max_encoding_message_size: DEFAULT_MAX_ENCODING_MESSAGE_SIZE,
			request_timeout: DEFAULT_REQUEST_TIMEOUT,
			max_concurrent_connections: DEFAULT_MAX_CONCURRENT_CONNECTIONS,
		}
	}
}

/// Builder for [`GrpcServerConfig`].
///
/// Uses the builder pattern to construct a `GrpcServerConfig` with
/// custom limits. All values default to the same as `GrpcServerConfig::default()`.
#[derive(Debug, Clone)]
pub struct GrpcServerConfigBuilder {
	max_decoding_message_size: usize,
	max_encoding_message_size: usize,
	request_timeout: Duration,
	max_concurrent_connections: usize,
}

impl GrpcServerConfigBuilder {
	/// Set the maximum decoding (incoming) message size in bytes.
	///
	/// This limits the maximum size of a protobuf message that the
	/// server will accept from clients. Messages exceeding this limit
	/// will be rejected with a `ResourceExhausted` status.
	pub fn max_decoding_message_size(mut self, size: usize) -> Self {
		self.max_decoding_message_size = size;
		self
	}

	/// Set the maximum encoding (outgoing) message size in bytes.
	///
	/// This limits the maximum size of a protobuf message that the
	/// server will send to clients.
	pub fn max_encoding_message_size(mut self, size: usize) -> Self {
		self.max_encoding_message_size = size;
		self
	}

	/// Set the maximum message size in bytes.
	///
	/// This is a convenience method that sets both decoding and encoding
	/// limits to the same value.
	pub fn max_message_size(mut self, size: usize) -> Self {
		self.max_decoding_message_size = size;
		self.max_encoding_message_size = size;
		self
	}

	/// Set the request timeout duration.
	///
	/// Requests exceeding this duration will be cancelled. Apply this
	/// via tower's `TimeoutLayer` when building the server.
	pub fn request_timeout(mut self, timeout: Duration) -> Self {
		self.request_timeout = timeout;
		self
	}

	/// Set the maximum number of concurrent connections.
	///
	/// Apply this via tower's `ConcurrencyLimitLayer` when building
	/// the server.
	pub fn max_concurrent_connections(mut self, max: usize) -> Self {
		self.max_concurrent_connections = max;
		self
	}

	/// Build the `GrpcServerConfig`.
	pub fn build(self) -> GrpcServerConfig {
		GrpcServerConfig {
			max_decoding_message_size: self.max_decoding_message_size,
			max_encoding_message_size: self.max_encoding_message_size,
			request_timeout: self.request_timeout,
			max_concurrent_connections: self.max_concurrent_connections,
		}
	}
}

impl Default for GrpcServerConfigBuilder {
	fn default() -> Self {
		Self {
			max_decoding_message_size: DEFAULT_MAX_DECODING_MESSAGE_SIZE,
			max_encoding_message_size: DEFAULT_MAX_ENCODING_MESSAGE_SIZE,
			request_timeout: DEFAULT_REQUEST_TIMEOUT,
			max_concurrent_connections: DEFAULT_MAX_CONCURRENT_CONNECTIONS,
		}
	}
}

/// Trait for applying message size limits to tonic-generated gRPC service servers.
///
/// Tonic generates service server structs (e.g., `GreeterServer<T>`) that have
/// `max_decoding_message_size` and `max_encoding_message_size` methods. This
/// trait provides a unified way to apply [`GrpcServerConfig`] limits to any
/// such service.
///
/// # Example
///
/// ```rust,ignore
/// use reinhardt_grpc::server::{GrpcServerConfig, MessageSizeLimiter};
///
/// let config = GrpcServerConfig::default();
/// let service = MyServiceServer::new(my_impl).apply_message_size_limits(&config);
/// ```
pub trait MessageSizeLimiter: Sized {
	/// Apply message size limits from the given configuration.
	fn apply_message_size_limits(self, config: &GrpcServerConfig) -> Self;
}

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

	#[rstest]
	fn default_config_has_4mb_limits() {
		// Arrange
		let expected_size = 4 * 1024 * 1024;

		// Act
		let config = GrpcServerConfig::default();

		// Assert
		assert_eq!(config.max_decoding_message_size(), expected_size);
		assert_eq!(config.max_encoding_message_size(), expected_size);
	}

	#[rstest]
	fn default_config_has_30s_request_timeout() {
		// Arrange & Act
		let config = GrpcServerConfig::default();

		// Assert
		assert_eq!(config.request_timeout(), Duration::from_secs(30));
	}

	#[rstest]
	fn default_config_has_1000_max_connections() {
		// Arrange & Act
		let config = GrpcServerConfig::default();

		// Assert
		assert_eq!(config.max_concurrent_connections(), 1000);
	}

	#[rstest]
	fn max_message_size_returns_decoding_size() {
		// Arrange
		let config = GrpcServerConfig::builder()
			.max_decoding_message_size(2 * 1024 * 1024)
			.build();

		// Act & Assert
		assert_eq!(config.max_message_size(), 2 * 1024 * 1024);
		assert_eq!(
			config.max_message_size(),
			config.max_decoding_message_size()
		);
	}

	#[rstest]
	fn builder_default_matches_default_config() {
		// Arrange
		let default_config = GrpcServerConfig::default();

		// Act
		let builder_config = GrpcServerConfig::builder().build();

		// Assert
		assert_eq!(
			builder_config.max_decoding_message_size(),
			default_config.max_decoding_message_size()
		);
		assert_eq!(
			builder_config.max_encoding_message_size(),
			default_config.max_encoding_message_size()
		);
		assert_eq!(
			builder_config.request_timeout(),
			default_config.request_timeout()
		);
		assert_eq!(
			builder_config.max_concurrent_connections(),
			default_config.max_concurrent_connections()
		);
	}

	#[rstest]
	fn builder_sets_custom_decoding_limit() {
		// Arrange
		let custom_size = 8 * 1024 * 1024; // 8MB

		// Act
		let config = GrpcServerConfig::builder()
			.max_decoding_message_size(custom_size)
			.build();

		// Assert
		assert_eq!(config.max_decoding_message_size(), custom_size);
		// Encoding should remain default
		assert_eq!(
			config.max_encoding_message_size(),
			DEFAULT_MAX_ENCODING_MESSAGE_SIZE
		);
	}

	#[rstest]
	fn builder_sets_custom_encoding_limit() {
		// Arrange
		let custom_size = 16 * 1024 * 1024; // 16MB

		// Act
		let config = GrpcServerConfig::builder()
			.max_encoding_message_size(custom_size)
			.build();

		// Assert
		assert_eq!(
			config.max_decoding_message_size(),
			DEFAULT_MAX_DECODING_MESSAGE_SIZE
		);
		assert_eq!(config.max_encoding_message_size(), custom_size);
	}

	#[rstest]
	fn builder_sets_both_limits() {
		// Arrange
		let decoding_size = 2 * 1024 * 1024; // 2MB
		let encoding_size = 8 * 1024 * 1024; // 8MB

		// Act
		let config = GrpcServerConfig::builder()
			.max_decoding_message_size(decoding_size)
			.max_encoding_message_size(encoding_size)
			.build();

		// Assert
		assert_eq!(config.max_decoding_message_size(), decoding_size);
		assert_eq!(config.max_encoding_message_size(), encoding_size);
	}

	#[rstest]
	fn builder_sets_max_message_size_for_both() {
		// Arrange
		let size = 2 * 1024 * 1024; // 2MB

		// Act
		let config = GrpcServerConfig::builder().max_message_size(size).build();

		// Assert
		assert_eq!(config.max_decoding_message_size(), size);
		assert_eq!(config.max_encoding_message_size(), size);
	}

	#[rstest]
	fn builder_sets_custom_request_timeout() {
		// Arrange & Act
		let config = GrpcServerConfig::builder()
			.request_timeout(Duration::from_secs(60))
			.build();

		// Assert
		assert_eq!(config.request_timeout(), Duration::from_secs(60));
	}

	#[rstest]
	fn builder_sets_custom_max_concurrent_connections() {
		// Arrange & Act
		let config = GrpcServerConfig::builder()
			.max_concurrent_connections(500)
			.build();

		// Assert
		assert_eq!(config.max_concurrent_connections(), 500);
	}

	#[rstest]
	fn builder_sets_all_custom_values() {
		// Arrange
		let decoding = 2 * 1024 * 1024;
		let encoding = 8 * 1024 * 1024;
		let timeout = Duration::from_secs(60);
		let max_conns = 500;

		// Act
		let config = GrpcServerConfig::builder()
			.max_decoding_message_size(decoding)
			.max_encoding_message_size(encoding)
			.request_timeout(timeout)
			.max_concurrent_connections(max_conns)
			.build();

		// Assert
		assert_eq!(config.max_decoding_message_size(), decoding);
		assert_eq!(config.max_encoding_message_size(), encoding);
		assert_eq!(config.request_timeout(), timeout);
		assert_eq!(config.max_concurrent_connections(), max_conns);
	}

	#[rstest]
	fn config_clone_preserves_values() {
		// Arrange
		let config = GrpcServerConfig::builder()
			.max_decoding_message_size(1024)
			.max_encoding_message_size(2048)
			.request_timeout(Duration::from_secs(45))
			.max_concurrent_connections(200)
			.build();

		// Act
		let cloned = config.clone();

		// Assert
		assert_eq!(
			cloned.max_decoding_message_size(),
			config.max_decoding_message_size()
		);
		assert_eq!(
			cloned.max_encoding_message_size(),
			config.max_encoding_message_size()
		);
		assert_eq!(cloned.request_timeout(), config.request_timeout());
		assert_eq!(
			cloned.max_concurrent_connections(),
			config.max_concurrent_connections()
		);
	}

	#[rstest]
	fn builder_allows_zero_size() {
		// Arrange & Act
		let config = GrpcServerConfig::builder()
			.max_decoding_message_size(0)
			.max_encoding_message_size(0)
			.build();

		// Assert
		assert_eq!(config.max_decoding_message_size(), 0);
		assert_eq!(config.max_encoding_message_size(), 0);
	}

	// Test that MessageSizeLimiter trait can be implemented for a mock service
	struct MockService {
		max_decoding: Option<usize>,
		max_encoding: Option<usize>,
	}

	impl MockService {
		fn new() -> Self {
			Self {
				max_decoding: None,
				max_encoding: None,
			}
		}
	}

	impl MessageSizeLimiter for MockService {
		fn apply_message_size_limits(mut self, config: &GrpcServerConfig) -> Self {
			self.max_decoding = Some(config.max_decoding_message_size());
			self.max_encoding = Some(config.max_encoding_message_size());
			self
		}
	}

	#[rstest]
	fn message_size_limiter_applies_config() {
		// Arrange
		let config = GrpcServerConfig::builder()
			.max_decoding_message_size(1024 * 1024)
			.max_encoding_message_size(2 * 1024 * 1024)
			.build();
		let service = MockService::new();

		// Act
		let service = service.apply_message_size_limits(&config);

		// Assert
		assert_eq!(service.max_decoding, Some(1024 * 1024));
		assert_eq!(service.max_encoding, Some(2 * 1024 * 1024));
	}

	#[rstest]
	fn message_size_limiter_applies_defaults() {
		// Arrange
		let config = GrpcServerConfig::default();
		let service = MockService::new();

		// Act
		let service = service.apply_message_size_limits(&config);

		// Assert
		assert_eq!(
			service.max_decoding,
			Some(DEFAULT_MAX_DECODING_MESSAGE_SIZE)
		);
		assert_eq!(
			service.max_encoding,
			Some(DEFAULT_MAX_ENCODING_MESSAGE_SIZE)
		);
	}
}