ipfrs-interface 0.1.0

HTTP, gRPC, GraphQL and Python interfaces for IPFRS distributed storage
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
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
# IPFRS Interface Configuration Guide

This document provides comprehensive configuration documentation for the IPFRS Gateway interface, covering all configuration options, default values, usage examples, and best practices.

## Table of Contents

- [Gateway Configuration]#gateway-configuration
- [Middleware Configuration]#middleware-configuration
  - [CORS Configuration]#cors-configuration
  - [Rate Limiting Configuration]#rate-limiting-configuration
  - [Compression Configuration]#compression-configuration
  - [Cache Configuration]#cache-configuration
  - [Validation Configuration]#validation-configuration
- [TLS Configuration]#tls-configuration
- [Streaming Configuration]#streaming-configuration
  - [Concurrency Configuration]#concurrency-configuration
  - [Flow Control Configuration]#flow-control-configuration
- [Environment Variables]#environment-variables
- [Best Practices]#best-practices

---

## Gateway Configuration

The main gateway server configuration.

### Structure: `GatewayConfig`

**Location:** `src/gateway.rs`

#### Fields

| Field | Type | Description | Default |
|-------|------|-------------|---------|
| `listen_addr` | `String` | Server bind address (host:port) | `"127.0.0.1:8080"` |
| `storage_config` | `BlockStoreConfig` | Storage backend configuration | `BlockStoreConfig::default()` |
| `tls_config` | `Option<TlsConfig>` | Optional TLS/HTTPS configuration | `None` (HTTP mode) |
| `compression_config` | `CompressionConfig` | HTTP compression settings | `CompressionConfig::default()` |

#### Usage Example

```rust
use ipfrs_interface::gateway::{Gateway, GatewayConfig};
use ipfrs_storage::BlockStoreConfig;

// Basic HTTP gateway
let config = GatewayConfig {
    listen_addr: "0.0.0.0:8080".to_string(),
    storage_config: BlockStoreConfig::default(),
    tls_config: None,
    compression_config: CompressionConfig::default(),
};

let gateway = Gateway::new(config)?;
gateway.start().await?;
```

```rust
// HTTPS gateway with TLS
use ipfrs_interface::tls::TlsConfig;

let tls = TlsConfig::new("certs/cert.pem", "certs/key.pem");

let config = GatewayConfig {
    listen_addr: "0.0.0.0:443".to_string(),
    storage_config: BlockStoreConfig::default(),
    tls_config: Some(tls),
    compression_config: CompressionConfig::default(),
};
```

---

## Middleware Configuration

### CORS Configuration

Cross-Origin Resource Sharing (CORS) settings for controlling web browser access.

#### Structure: `CorsConfig`

**Location:** `src/middleware.rs`

#### Fields

| Field | Type | Description | Default |
|-------|------|-------------|---------|
| `allowed_origins` | `HashSet<String>` | Allowed origin domains (use "*" for any) | Empty (allows all) |
| `allowed_methods` | `HashSet<Method>` | Allowed HTTP methods | GET, POST, PUT, DELETE, OPTIONS, HEAD |
| `allowed_headers` | `HashSet<String>` | Allowed request headers | content-type, authorization, accept, origin, x-requested-with |
| `exposed_headers` | `HashSet<String>` | Headers exposed to client | Empty |
| `allow_credentials` | `bool` | Allow cookies and auth headers | `false` |
| `max_age` | `u64` | Preflight cache duration (seconds) | `86400` (24 hours) |

#### Preset Configurations

```rust
// Permissive CORS (allows all origins)
let cors = CorsConfig::permissive();

// Default CORS (restrictive)
let cors = CorsConfig::default();

// Custom CORS configuration
let cors = CorsConfig::default()
    .allow_origin("https://app.example.com")
    .allow_origin("https://admin.example.com")
    .allow_credentials(true);
```

#### Usage Example

```rust
use ipfrs_interface::middleware::{CorsConfig, CorsState, cors_middleware};
use axum::{Router, middleware};

// Create CORS configuration
let cors_config = CorsConfig::default()
    .allow_origin("https://myapp.com")
    .allow_credentials(true);

let cors_state = CorsState {
    config: cors_config,
};

// Apply to router
let app = Router::new()
    .route("/api/data", get(handler))
    .layer(middleware::from_fn_with_state(cors_state, cors_middleware));
```

#### Best Practices

- **Production:** Use specific origins instead of `"*"` for security
- **Credentials:** Only enable `allow_credentials` when necessary
- **Methods:** Limit to required HTTP methods only
- **Headers:** Minimize exposed headers to reduce information leakage

---

### Rate Limiting Configuration

Token bucket-based rate limiting to prevent abuse and DoS attacks.

#### Structure: `RateLimitConfig`

**Location:** `src/middleware.rs`

#### Fields

| Field | Type | Description | Default |
|-------|------|-------------|---------|
| `max_requests` | `u32` | Maximum requests per window | `100` |
| `window` | `Duration` | Time window duration | `60 seconds` |
| `burst_capacity` | `u32` | Token bucket burst size | `10` |

#### Validation

The configuration includes validation that ensures:
- `max_requests > 0`
- `window > 0`
- `burst_capacity > 0`
- `burst_capacity <= max_requests`

#### Usage Example

```rust
use ipfrs_interface::middleware::{RateLimitConfig, RateLimitState, rate_limit_middleware};
use std::time::Duration;

// Conservative rate limiting (100 req/min, burst of 10)
let config = RateLimitConfig::default();
assert!(config.validate().is_ok());

// Aggressive rate limiting (1000 req/min, burst of 50)
let config = RateLimitConfig {
    max_requests: 1000,
    window: Duration::from_secs(60),
    burst_capacity: 50,
};

let rate_state = RateLimitState::new(config);

// Apply to router
let app = Router::new()
    .route("/api/data", get(handler))
    .layer(middleware::from_fn_with_state(rate_state, rate_limit_middleware));
```

#### Response Headers

Rate limit middleware adds the following headers:
- `X-RateLimit-Limit`: Maximum requests allowed
- `X-RateLimit-Remaining`: Remaining requests in current window
- `Retry-After`: Seconds to wait (on 429 response)

#### Best Practices

- **Public APIs:** Use conservative limits (e.g., 100 req/min)
- **Internal APIs:** Can use higher limits (e.g., 1000 req/min)
- **Burst Capacity:** Set to ~10% of max_requests for traffic spikes
- **Per-IP Tracking:** Rate limiting is automatically per-IP

---

### Compression Configuration

HTTP response compression for bandwidth optimization.

#### Structure: `CompressionConfig`

**Location:** `src/middleware.rs`

#### Fields

| Field | Type | Description | Default |
|-------|------|-------------|---------|
| `enable_gzip` | `bool` | Enable gzip compression | `true` |
| `enable_brotli` | `bool` | Enable Brotli compression | `true` |
| `enable_deflate` | `bool` | Enable deflate compression | `true` |
| `level` | `CompressionLevel` | Compression quality level | `Balanced` |
| `min_size` | `usize` | Minimum bytes to compress | `1024` (1 KB) |

#### Compression Levels

| Level | Description | Speed | Size | Gzip Level | Brotli Quality |
|-------|-------------|-------|------|------------|----------------|
| `Fastest` | Fastest compression | Very Fast | Larger | 1 | 1 |
| `Balanced` | Balanced (default) | Fast | Good | 5 | 6 |
| `Best` | Best compression | Slower | Smallest | 9 | 11 |
| `Custom(u32)` | Custom level | Varies | Varies | 0-9 | 0-11 |

#### Preset Configurations

```rust
// Fast compression (prioritize speed)
let config = CompressionConfig::fast();

// Best compression (prioritize size)
let config = CompressionConfig::best();

// Custom configuration
let config = CompressionConfig::default()
    .with_level(CompressionLevel::Custom(7))
    .with_min_size(2048)
    .with_algorithms(true, true, false); // gzip + brotli, no deflate
```

#### Validation

The configuration validates:
- At least one algorithm must be enabled
- `min_size <= 100 MB`

#### Usage Example

```rust
use ipfrs_interface::middleware::{CompressionConfig, CompressionLevel};

// Production configuration (balanced)
let config = CompressionConfig::default();
assert!(config.validate().is_ok());

// High-speed configuration
let config = CompressionConfig::fast()
    .with_min_size(512); // Compress smaller files

// Maximum compression for large files
let config = CompressionConfig::best()
    .with_min_size(10 * 1024); // Only compress files > 10KB
```

#### Best Practices

- **Default:** Use `Balanced` for most cases
- **Low Latency:** Use `Fastest` for real-time applications
- **Bandwidth Limited:** Use `Best` when bandwidth is expensive
- **Min Size:** Don't compress files < 1KB (overhead not worth it)
- **Content Types:** Disable for pre-compressed content (images, videos)

---

### Cache Configuration

HTTP caching headers for CDN and browser caching.

#### Structure: `CacheConfig`

**Location:** `src/middleware.rs`

#### Fields

| Field | Type | Description | Default |
|-------|------|-------------|---------|
| `default_max_age` | `u64` | Cache duration in seconds | `3600` (1 hour) |
| `public` | `bool` | Allow CDN/proxy caching | `true` |
| `immutable_cids` | `bool` | Mark CID content as immutable | `true` |

#### Validation

- `default_max_age <= 1 year (31,536,000 seconds)`

#### Usage Example

```rust
use ipfrs_interface::middleware::{CacheConfig, add_caching_headers};
use axum::http::HeaderMap;

// Default caching (1 hour, public, immutable CIDs)
let config = CacheConfig::default();

// Long-term caching for static content
let config = CacheConfig {
    default_max_age: 86400 * 30, // 30 days
    public: true,
    immutable_cids: true,
};

// Private caching (no CDN)
let config = CacheConfig {
    default_max_age: 3600,
    public: false,
    immutable_cids: true,
};

// Add cache headers to response
let mut headers = HeaderMap::new();
add_caching_headers(&mut headers, "QmTest123", &config);
```

#### Generated Headers

For a CID response, the following headers are added:
- `ETag`: "CID" (content-addressed = perfect ETag)
- `Cache-Control`: public/private, max-age=X, immutable
- Supports `If-None-Match` for conditional requests (304 Not Modified)

#### Best Practices

- **CID Content:** Always use `immutable_cids: true` (content never changes)
- **Public CDN:** Use `public: true` for public content
- **Private Data:** Use `public: false` for authenticated content
- **Max Age:** Balance between cache hits and staleness
  - Static assets: 30 days
  - API responses: 1 hour
  - Dynamic content: 5 minutes

---

### Validation Configuration

Request validation middleware for input sanitization.

#### Structure: `ValidationConfig`

**Location:** `src/middleware.rs`

#### Fields

| Field | Type | Description | Default |
|-------|------|-------------|---------|
| `max_body_size` | `usize` | Maximum request body (bytes) | `104857600` (100 MB) |
| `max_cid_length` | `usize` | Maximum CID string length | `100` |
| `validate_cid_format` | `bool` | Enable strict CID validation | `true` |
| `content_type_validation` | `bool` | Validate Content-Type headers | `true` |
| `max_batch_size` | `usize` | Maximum batch operation size | `1000` |

#### Preset Configurations

```rust
// Strict validation (smaller limits)
let config = ValidationConfig::strict();
// max_body_size: 10 MB
// max_cid_length: 64
// max_batch_size: 100

// Permissive validation (larger limits)
let config = ValidationConfig::permissive();
// max_body_size: 1 GB
// max_cid_length: 200
// validate_cid_format: false
// max_batch_size: 10000
```

#### Usage Example

```rust
use ipfrs_interface::middleware::{ValidationConfig, ValidationState, validation_middleware};

// Production validation
let config = ValidationConfig::default();

// Strict validation for public API
let config = ValidationConfig::strict();

// Permissive for internal use
let config = ValidationConfig::permissive();

let validation_state = ValidationState { config };

// Apply to router
let app = Router::new()
    .route("/api/upload", post(upload_handler))
    .layer(middleware::from_fn_with_state(validation_state, validation_middleware));
```

#### CID Validation

Validates CID format:
- **CIDv0:** Starts with "Qm", exactly 46 characters (base58btc)
- **CIDv1:** Starts with "b", "z", or "f" (multibase prefixes)

#### Best Practices

- **Public APIs:** Use `strict()` to prevent abuse
- **Internal APIs:** Can use `permissive()` for flexibility
- **Upload Size:** Set `max_body_size` based on expected file sizes
- **Batch Size:** Limit batch operations to prevent resource exhaustion

---

## TLS Configuration

TLS/SSL configuration for HTTPS support.

#### Structure: `TlsConfig`

**Location:** `src/tls.rs`

#### Fields

| Field | Type | Description | Default |
|-------|------|-------------|---------|
| `cert_path` | `PathBuf` | Path to PEM certificate file | None (required) |
| `key_path` | `PathBuf` | Path to PEM private key file | None (required) |

#### Usage Example

```rust
use ipfrs_interface::tls::TlsConfig;
use ipfrs_interface::gateway::GatewayConfig;

// Load TLS certificates
let tls = TlsConfig::new(
    "/etc/ssl/certs/server.crt",
    "/etc/ssl/private/server.key"
);

// Configure gateway with HTTPS
let gateway_config = GatewayConfig {
    listen_addr: "0.0.0.0:443".to_string(),
    tls_config: Some(tls),
    ..Default::default()
};
```

#### Certificate Requirements

- **Format:** PEM-encoded X.509 certificates
- **Private Key:** RSA or ECDSA, PEM-encoded
- **Chain:** Include intermediate certificates in cert file
- **Permissions:** Key file should be readable only by server process

#### Best Practices

- **Certificate Authority:** Use Let's Encrypt for free certificates
- **Auto-Renewal:** Implement certificate rotation (e.g., certbot)
- **Strong Ciphers:** Modern TLS configuration (TLS 1.2+)
- **HSTS:** Enable HTTP Strict Transport Security headers
- **Redirect:** Redirect HTTP (port 80) to HTTPS (port 443)

#### Example: Let's Encrypt Setup

```bash
# Install certbot
sudo apt-get install certbot

# Obtain certificate
sudo certbot certonly --standalone -d gateway.example.com

# Certificates will be in:
# /etc/letsencrypt/live/gateway.example.com/fullchain.pem (cert)
# /etc/letsencrypt/live/gateway.example.com/privkey.pem (key)
```

```rust
let tls = TlsConfig::new(
    "/etc/letsencrypt/live/gateway.example.com/fullchain.pem",
    "/etc/letsencrypt/live/gateway.example.com/privkey.pem"
);
```

---

## Streaming Configuration

Configuration for streaming downloads, uploads, and flow control.

### Concurrency Configuration

Controls parallel task execution for batch operations.

#### Structure: `ConcurrencyConfig`

**Location:** `src/streaming.rs`

#### Fields

| Field | Type | Description | Default |
|-------|------|-------------|---------|
| `max_concurrent_tasks` | `usize` | Max parallel tasks (0 = unlimited) | `100` |
| `parallel_enabled` | `bool` | Enable parallel processing | `true` |

#### Validation

- When `parallel_enabled: true`, `max_concurrent_tasks` must be > 0

#### Preset Configurations

```rust
// Conservative (lower concurrency)
let config = ConcurrencyConfig::conservative();
// max_concurrent_tasks: 50

// Aggressive (higher concurrency)
let config = ConcurrencyConfig::aggressive();
// max_concurrent_tasks: 200

// Sequential (no parallelism)
let config = ConcurrencyConfig::sequential();
// max_concurrent_tasks: 1
// parallel_enabled: false
```

#### Usage Example

```rust
use ipfrs_interface::streaming::ConcurrencyConfig;

// Default configuration (100 concurrent tasks)
let config = ConcurrencyConfig::default();
assert!(config.validate().is_ok());

// High-throughput configuration
let config = ConcurrencyConfig::aggressive();

// Low-resource configuration
let config = ConcurrencyConfig::conservative();
```

#### Best Practices

- **Default:** Use 100 concurrent tasks for balanced performance
- **High CPU:** Use `aggressive()` for multi-core systems
- **Memory Limited:** Use `conservative()` to reduce memory usage
- **Testing/Debug:** Use `sequential()` for deterministic behavior
- **Monitoring:** Track task queue depth to tune concurrency

---

### Flow Control Configuration

Controls streaming bandwidth and window sizing.

#### Structure: `FlowControlConfig`

**Location:** `src/streaming.rs`

#### Fields

| Field | Type | Description | Default |
|-------|------|-------------|---------|
| `max_bytes_per_second` | `u64` | Bandwidth limit (0 = unlimited) | `0` (unlimited) |
| `initial_window_size` | `usize` | Initial send window (bytes) | `262144` (256 KB) |
| `max_window_size` | `usize` | Maximum send window (bytes) | `1048576` (1 MB) |
| `min_window_size` | `usize` | Minimum send window (bytes) | `65536` (64 KB) |
| `dynamic_adjustment` | `bool` | Enable adaptive windowing | `true` |

#### Validation

- `min_window_size <= initial_window_size <= max_window_size`
- `max_bytes_per_second <= 10 GB/s` (if set)

#### Preset Configurations

```rust
// Rate-limited streaming (1 MB/s)
let config = FlowControlConfig::with_rate_limit(1_000_000);

// Conservative (smaller windows)
let config = FlowControlConfig::conservative();
// initial_window_size: 64 KB
// max_window_size: 256 KB
// min_window_size: 32 KB

// Aggressive (larger windows)
let config = FlowControlConfig::aggressive();
// initial_window_size: 512 KB
// max_window_size: 2 MB
// min_window_size: 128 KB
```

#### Usage Example

```rust
use ipfrs_interface::streaming::{FlowControlConfig, FlowController};

// Unlimited bandwidth
let config = FlowControlConfig::default();

// Rate-limited to 10 MB/s
let config = FlowControlConfig::with_rate_limit(10 * 1024 * 1024);

// Conservative for mobile networks
let config = FlowControlConfig::conservative()
    .with_rate_limit(500_000); // 500 KB/s

// Create flow controller
let mut controller = FlowController::new(config);

// During streaming
let chunk_size = controller.window_size();
let delay = controller.calculate_delay(chunk_size);
tokio::time::sleep(delay).await;
controller.on_data_sent(chunk_size);
```

#### Dynamic Window Adjustment

When `dynamic_adjustment: true`, the window size adapts using AIMD:
- **Additive Increase:** Window grows by 10% every 100ms (up to max)
- **Multiplicative Decrease:** Window halves on congestion (down to min)

#### Best Practices

- **LAN/Datacenter:** Use `aggressive()` for high bandwidth
- **Internet:** Use default or `conservative()` for variable networks
- **Rate Limiting:** Set `max_bytes_per_second` for fair sharing
- **Mobile/Satellite:** Use `conservative()` + low rate limit
- **Dynamic Adjustment:** Keep enabled unless you have specific requirements

---

## Environment Variables

While the IPFRS Interface doesn't directly read environment variables, you can use them in your application setup:

```rust
use std::env;
use ipfrs_interface::gateway::GatewayConfig;

// Read configuration from environment
let listen_addr = env::var("IPFRS_LISTEN_ADDR")
    .unwrap_or_else(|_| "0.0.0.0:8080".to_string());

let cert_path = env::var("IPFRS_TLS_CERT").ok();
let key_path = env::var("IPFRS_TLS_KEY").ok();

let tls_config = match (cert_path, key_path) {
    (Some(cert), Some(key)) => Some(TlsConfig::new(cert, key)),
    _ => None,
};

let config = GatewayConfig {
    listen_addr,
    tls_config,
    ..Default::default()
};
```

### Recommended Environment Variables

| Variable | Description | Example |
|----------|-------------|---------|
| `IPFRS_LISTEN_ADDR` | Server bind address | `0.0.0.0:8080` |
| `IPFRS_TLS_CERT` | TLS certificate path | `/etc/ssl/certs/server.crt` |
| `IPFRS_TLS_KEY` | TLS private key path | `/etc/ssl/private/server.key` |
| `IPFRS_STORAGE_PATH` | Storage directory | `/var/lib/ipfrs` |
| `IPFRS_MAX_BODY_SIZE` | Max upload size (bytes) | `104857600` |
| `IPFRS_RATE_LIMIT` | Requests per minute | `100` |
| `IPFRS_CORS_ORIGINS` | Allowed origins (comma-separated) | `https://app.com,https://admin.com` |

---

## Best Practices

### Security

1. **TLS in Production:** Always use HTTPS in production
2. **Rate Limiting:** Enable rate limiting for public APIs
3. **Validation:** Use strict validation for untrusted input
4. **CORS:** Specify exact origins instead of `"*"`
5. **Credentials:** Only enable when necessary

### Performance

1. **Compression:** Enable for text content, disable for images/videos
2. **Caching:** Use aggressive caching for CID content (immutable)
3. **Concurrency:** Tune based on available CPU cores
4. **Flow Control:** Use dynamic adjustment for varying network conditions
5. **Batch Operations:** Prefer batch APIs over many individual requests

### Reliability

1. **Validation:** Validate all inputs to prevent crashes
2. **Resource Limits:** Set reasonable limits for body size, batch size
3. **Graceful Degradation:** Handle validation errors gracefully
4. **Monitoring:** Track rate limit hits, validation failures
5. **Logging:** Log configuration at startup for debugging

### Configuration Examples

#### Development Setup

```rust
use ipfrs_interface::gateway::GatewayConfig;
use ipfrs_interface::middleware::*;

let config = GatewayConfig {
    listen_addr: "127.0.0.1:8080".to_string(),
    storage_config: BlockStoreConfig::default(),
    tls_config: None, // HTTP only
    compression_config: CompressionConfig::fast(), // Fast compression
};

let cors = CorsConfig::permissive(); // Allow all origins
let rate_limit = RateLimitConfig::default(); // Lenient rate limiting
let validation = ValidationConfig::permissive(); // Relaxed validation
```

#### Production Setup

```rust
let tls = TlsConfig::new(
    "/etc/ssl/certs/server.crt",
    "/etc/ssl/private/server.key"
);

let config = GatewayConfig {
    listen_addr: "0.0.0.0:443".to_string(),
    storage_config: BlockStoreConfig::default(),
    tls_config: Some(tls), // HTTPS enabled
    compression_config: CompressionConfig::default(), // Balanced compression
};

let cors = CorsConfig::default()
    .allow_origin("https://app.example.com")
    .allow_credentials(true); // Specific origins only

let rate_limit = RateLimitConfig {
    max_requests: 100,
    window: Duration::from_secs(60),
    burst_capacity: 10,
}; // Strict rate limiting

let validation = ValidationConfig::strict(); // Strict validation

let flow_control = FlowControlConfig::conservative()
    .with_rate_limit(10 * 1024 * 1024); // 10 MB/s limit
```

#### High-Performance Setup

```rust
let config = GatewayConfig {
    listen_addr: "0.0.0.0:8080".to_string(),
    storage_config: BlockStoreConfig::default(),
    tls_config: None,
    compression_config: CompressionConfig::fast(), // Prioritize speed
};

let rate_limit = RateLimitConfig {
    max_requests: 1000,
    window: Duration::from_secs(60),
    burst_capacity: 100,
}; // High throughput

let concurrency = ConcurrencyConfig::aggressive(); // High concurrency

let flow_control = FlowControlConfig::aggressive(); // Large windows
```

---

## Troubleshooting

### Common Issues

#### 1. Rate Limit Too Restrictive

**Symptom:** Clients getting 429 errors frequently

**Solution:**
```rust
// Increase limits
let config = RateLimitConfig {
    max_requests: 500,
    window: Duration::from_secs(60),
    burst_capacity: 50,
};
```

#### 2. Compression Not Working

**Symptom:** Responses not compressed

**Solution:**
- Check `min_size` threshold
- Verify client sends `Accept-Encoding` header
- Ensure at least one algorithm is enabled

#### 3. TLS Certificate Errors

**Symptom:** TLS handshake failures

**Solution:**
- Verify certificate paths are correct
- Check file permissions (readable by process)
- Ensure certificate chain is complete
- Verify certificate is not expired

#### 4. CORS Errors in Browser

**Symptom:** Preflight requests failing

**Solution:**
```rust
let cors = CorsConfig::default()
    .allow_origin("https://your-app.com")
    .allow_credentials(true);
```

#### 5. Batch Operations Timing Out

**Symptom:** Large batch requests fail

**Solution:**
```rust
// Increase batch size limit
let validation = ValidationConfig {
    max_batch_size: 5000,
    ..Default::default()
};

// Increase concurrency
let concurrency = ConcurrencyConfig::aggressive();
```

---

## Version Information

- **Current Version:** 0.3.0
- **Last Updated:** 2026-01-18
- **Compatibility:** ipfrs-core 0.3.0, ipfrs-storage 0.3.0

---

## Additional Resources

- [Axum Documentation]https://docs.rs/axum/
- [Tower HTTP]https://docs.rs/tower-http/
- [RustLS]https://docs.rs/rustls/
- [IPFS Specifications]https://specs.ipfs.tech/

---

For questions or issues, please refer to the main IPFRS documentation or open an issue on the project repository.