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
//! Web server configuration limits and timeouts
//!
//! # Security-First Defaults
//!
//! Default limits are intentionally conservative to prevent:
//! - Resource exhaustion attacks
//! - Memory overflows
//! - Slowloris attacks
//! - Header flooding
//!
//! # Memory Consumption
//!
//! Each active connection consumes memory according to:
//!
//! `Total` = [`Request Buffer`](crate::limits::ReqLimits#memory-allocation-strategy) +
//! [`Response Buffer`](crate::limits::RespLimits#buffer-management) +
//! `Runtime Overhead`
//!
//! See each component's documentation for details and configuration options.
//!
//! # Examples
//!
//! ```no_run
//! # maker_web::impt_default_handler!{MyHandler}
//! use maker_web::{Server, limits::{ConnLimits, ReqLimits, ServerLimits}};
//! use tokio::net::TcpListener;
//! use std::time::Duration;
//!
//! #[tokio::main]
//! async fn main() {
//! Server::builder()
//! .listener(TcpListener::bind("127.0.0.1:8080").await.unwrap())
//! .handler(MyHandler)
//! .server_limits(ServerLimits {
//! max_connections: 5000, // Higher concurrency
//! ..ServerLimits::default()
//! })
//! .connection_limits(ConnLimits {
//! socket_read_timeout: Duration::from_secs(5),
//! max_requests_per_connection: 10_000,
//! ..ConnLimits::default()
//! })
//! .request_limits(ReqLimits {
//! header_count: 18, // More headers for complex APIs
//! body_size: 16 * 1024, // 16KB for larger payloads
//! ..ReqLimits::default()
//! })
//! .build()
//! .launch()
//! .await;
//! }
//! ```
use Duration;
/// Controls server-level concurrency, queueing, and performance behavior.
///
/// Configures how the server handles connection admission, worker pools,
/// and overload protection with tunable parameters for different workloads.
///
/// # Connection management
/// ```text
/// [------------]
/// [ Tcp accept ]
/// [------------]
/// ||
/// || TCP_STREAM
/// \/
/// [--------------] Yes /----------------\ No [-------------]
/// [ Add to queue ] <====== | Queue if full? | =====> [ Sending 503 ]
/// [--------------] \----------------/ [-------------]
/// ||
/// \==================\\ //====================\
/// V V ||
/// [---------] Yes /--------------------------\ No [------]
/// [ Handler ] <====== | Is there a free handler? | =====> [ Wait ]
/// [---------] \--------------------------/ [------]
/// ```
///
/// The queue acts as a buffer between connection acceptance and processing.
/// Workers continuously poll the queue using the configured `wait_strategy`.
///
/// # Handler
/// A worker process is a continuously running asynchronous task, created once
/// during initialization (from [tokio::spawn]). It runs in an infinite loop,
/// processing connections from a shared queue, which is replenished by a TCP
/// listener. This design eliminates the need to create tasks for each connection,
/// allowing for efficient resource reuse across an unlimited number of connections.
/// Strategy for worker task waiting when no connections are available
///
/// Different strategies optimize for different workload patterns.
/// Choose based on your latency requirements and resource constraints.
/// Connection-level limits and timeouts
///
/// Controls individual TCP connection behavior including timeouts,
/// lifetime, and request limits.
///
/// Default values balance performance, resource usage, and security.
/// Only change if you understand the consequences.
/// Configuration for `HTTP/0.9+` protocol support
///
/// HTTP/0.9+ is an optimized protocol variant for high-performance scenarios
/// that maintains backward compatibility with original HTTP/0.9 while adding
/// modern features like keep_alive connections and query string support.
///
/// # Protocol Features
///
/// - **Ultra-minimal format**:
/// [See transcript](crate::Request#general-designations)
/// ```text
/// [METHOD] SP [PATH] CRLF
/// ```
/// - **Keep_alive support**: Paths starting with `/keep_alive/` maintain persistent connections
/// - **Query strings**: Full URL parsing with query parameters supported
/// - **Zero overhead**: No headers, status codes, or other `HTTP/1.x` metadata
/// - **Support all HTTP methods**:
///
/// Starting with `maker_web@0.1.2` `HTTP/0.9+` starts supporting
/// [all methods](crate::Method) that `HTTP/1.x`.
///
/// **Examples**:
/// ```text
/// GET /users/123/posts\r\n
/// POST /orders\r\n
/// PUT /products/456\r\n
/// DELETE /comments/789\r\n
/// HEAD /api/status\r\n
/// PATCH /profile/settings\r\n
/// OPTIONS /auth\r\n
/// GET /feed?page=2&limit=20\r\n
/// DELETE /sessions?all=true\r\n
/// ```
/// And it all works now :D
///
/// # Request Format
///
/// ```text
/// Standard: GET /path\r\n
/// Keep_alive: POST /keep_alive/path\r\n
/// With query: PUT /path?param=value\r\n
/// Combined: HEAD /keep_alive/path?param=value\r\n
/// ```
///
/// # Response Format
///
/// ```text
/// Raw response body without headers
/// Connection closes unless `keep_alive` path used
/// ```
///
/// # Error Handling
///
/// - **Client errors**: `ERROR: [code] [message]\r\n` response for malformed
/// requests (e.g., `ERROR: 400 Bad Request\r\n`, `ERROR: 404 Not Found\r\n`)
/// - **Server failures**: Immediate connection termination for I/O errors and
/// timeout conditions
///
/// # Keep-Alive Management
///
/// Connections are automatically closed when:
/// - **Timeout reached**: no requests within the
/// [`set time limit`](ConnLimits::socket_read_timeout)
/// - **Request limit exceeded**: Processed
/// [`max_requests_per_connection`](Http09Limits::max_requests_per_connection)
/// on single connection
/// - **Explicit close**: Use non-keep_alive path to close connection
///
/// To explicitly close a keep_alive connection:
/// ```text
/// GET /close-connection\r\n # Regular path (no /keep_alive/) closes connection
/// ```
///
/// # Protocol Compatibility & Usage Strategies
///
/// ## Pure HTTP/0.9+ (Maximum Performance)
///
/// Ideal for controlled environments where you implement both client and server:
/// ```no_run
/// // Simple HTTP/0.9+ client in 16 lines:
/// use std::{net::TcpStream, io::{Result, Read, Write}};
///
/// # fn main() -> Result<()> {
/// let mut stream = TcpStream::connect("localhost:8080")?;
/// let response = http09_client(&mut stream, "GET /hello/world\r\n")?;
/// println!("{}", response);
/// # Ok(())
/// # }
///
/// fn http09_client(stream: &mut TcpStream, request: &str) -> Result<String> {
/// // Sending a request
/// stream.write_all(request.as_bytes())?;
///
/// // Reading a response
/// let mut line = String::new();
/// stream.read_to_string(&mut line)?;
///
/// Ok(line)
/// }
/// ```
///
/// ## Hybrid HTTP/1.X + HTTP/0.9+ (Browser & Complex Scenarios)
///
/// **Note**: HTTP/1.X requests interleaved in a connection are subject to [`ConnLimits`].
///
/// Combine protocols when you need advanced features or browser compatibility:
///
/// - **Initial setup with HTTP/1.X** (authentication, complex headers):
/// ```text
/// GET /api HTTP/1.1\r
/// Host: localhost\r
/// Authorization: Basic YWxhZGRpbjpvcGVuc2VzYW1l\r
/// User-Agent: curl/7.64.1\r
/// \r\n
/// ```
///
/// - **High-frequency data with HTTP/0.9+**:
/// ```text
/// GET /keep_alive/api/user/first_name\r
/// GET /keep_alive/api/user/last_name\r
/// GET /keep_alive/api/user/country\r
/// GET /keep_alive/api/user/city\r\n
///
/// POST /keep_alive/api/user?last_name=Qwe\r\n
/// POST /keep_alive/api/user?first_name=Rty\r\n
/// POST /keep_alive/api/user?city=123\r\n
///
/// DELETE /keep_alive/api/user/123\r\n
/// ```
///
/// - **Final request** (is selected depending on the conditions):
/// - HTTP/0.9+:
/// ```text
/// GET /api/user/time\r\n`
/// ```
/// - HTTP/1.X:
/// ```text
/// POST /api/user/time HTTP/1.1\r
/// Host: localhost\r
/// Connection: close\r
/// \r\n
/// ```
///
/// ## HTTP/1.X Only (Public APIs & Maximum Compatibility)
///
/// Use standard HTTP/1.X when:
/// - Serving public APIs to unknown clients
/// - Browser compatibility is required without custom client implementation
/// - Advanced HTTP features are needed (CORS, caching headers, etc.)
///
/// # Limits
///
/// This setting only works for `HTTP/0.9+`. The same-named fields in [`ConnLimits`]
/// are ignored for this protocol.
/// HTTP request parsing limits and buffer pre-allocation strategy
///
/// ⚠️ **SECURITY-FIRST DEFAULTS**
///
/// These limits are intentionally conservative to prevent resource exhaustion
/// and various parsing attacks. They work well for:
/// - Simple REST APIs
/// - Microservices
/// - Internal tools
/// - Low-memory environments
///
/// 🔧 **You MAY need to increase these if you see:**
/// - `413 Payload Too Large` for legitimate requests
/// - `414 URI Too Long` for normal API calls
/// - `431 Request Header Fields Too Large`
///
/// # Memory Allocation Strategy
///
/// Each TCP connection pre-allocates a fixed-size buffer based on these limits:
///
/// ```text
/// Total Buffer = First Line + (Headers × Header Line) + Body + Overhead
/// ```
///
/// ## Buffer Size Calculation (Default Values)
///
/// | Component | Formula | Size | Purpose |
/// |-----------|---------|------|---------|
/// | First Line | `19 + url_size` | 275 B | `METHOD URL HTTP/1.1\r\n` |
/// | Headers | `header_count × Header Line` | 9,280 B | Headers storage |
/// | Header Line | `header_name_size + header_value_size + 4` | 580 B | `Name: Value\r\n` |
/// | Body | `body_size` | 4,096 B | Request payload |
/// | **Total** | **Sum + 2 bytes CRLF + struct (64 B)** | **13,717 B = ~13.4 KB** | Per connection buffer |
///
/// # Memory Planning
///
/// # Example
/// ```
/// use maker_web::limits::ReqLimits;
///
/// let mut limits = ReqLimits::default();
/// let buffer_size = limits.estimated_buffer_size();
/// println!("Each connection needs {} bytes for data buffer", buffer_size);
/// ```
///
/// # Trade-off Considerations
///
/// - **Small limits**: Less memory, faster parsing, but may reject legitimate requests
/// - **Large limits**: More memory overhead, but handles complex APIs and large payloads
///
/// Adjust based on your specific use case and available resources.
/// Configuration for response processing and memory allocation limits.
///
/// Controls how response buffers are allocated and managed to balance
/// memory usage and performance.
///
/// # Buffer Management
///
/// Based on the configured limits, response buffers are managed as follows:
/// ```rust
/// # use maker_web::limits::RespLimits;
/// # let limits = RespLimits::default();
/// # let mut buffer: Vec<()> = Vec::with_capacity(limits.default_capacity);
/// #
/// // `buffer` is Vec
/// if buffer.capacity() > limits.max_capacity {
/// buffer = Vec::with_capacity(limits.default_capacity);
/// } else {
/// buffer.clear();
/// }
/// ```
///
/// When the server starts, buffers are created with a capacity equal to `default_capacity`.