zerodds-coap-bridge 1.0.0-rc.1

CoAP (RFC 7252 / 7641 / 7959 / 6690) Wire-Codec + Reliability + Observe + Block-Wise + Discovery + DDS-Topic-Bridge — no_std + alloc.
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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 ZeroDDS Contributors

//! CoAP Caching + Proxying nach RFC 7252 §2.3 / §5.6 / §5.7 +
//! HTTP-Cross-Proto-Mapping nach RFC 7252 §10.
//!
//! Wir liefern hier den Configuration-Layer + State-Tracking. Die
//! tatsaechliche HTTP-Translation ist Caller-seitig (z.B. via
//! `crates/grpc-bridge/src/server.rs` als HTTP-Adapter).

use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use core::time::Duration;
use std::sync::Mutex;
use std::time::Instant;

use crate::message::CoapMessage;

// ---------------------------------------------------------------------------
// §5.6 Caching — Freshness + Validation
// ---------------------------------------------------------------------------

/// Spec §5.6.1 — Default Max-Age = 60 Sekunden.
pub const DEFAULT_MAX_AGE: Duration = Duration::from_secs(60);

/// Cache-Entry: Response + Freshness-Lifetime + ETag.
struct CacheEntry {
    response: CoapMessage,
    inserted: Instant,
    max_age: Duration,
    etag: Option<Vec<u8>>,
}

impl core::fmt::Debug for CacheEntry {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("CacheEntry")
            .field("max_age_secs", &self.max_age.as_secs())
            .field("has_etag", &self.etag.is_some())
            .finish()
    }
}

/// CoAP Response-Cache nach RFC 7252 §5.6.
#[derive(Default)]
pub struct CoapCache {
    /// Cache-Key = (Method-Code, full Request-Path) → CacheEntry.
    entries: Mutex<BTreeMap<Vec<u8>, CacheEntry>>,
    /// Spec §5.6.x — DoS-Cap.
    pub max_entries: usize,
}

impl core::fmt::Debug for CoapCache {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        let n = self.entries.lock().map_or(0, |g| g.len());
        f.debug_struct("CoapCache")
            .field("count", &n)
            .field("max_entries", &self.max_entries)
            .finish()
    }
}

/// Cache-Lookup-Result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CacheLookup {
    /// Kein Eintrag.
    Miss,
    /// Frischer Eintrag — direkt als Response verwendbar.
    Fresh(CoapMessage),
    /// Eintrag vorhanden aber stale — Validation via ETag noetig.
    Stale {
        /// Cached Response (kann reused werden falls Server 2.03 Valid
        /// liefert).
        response: CoapMessage,
        /// ETag fuer If-None-Match-Header in Validation-Request.
        etag: Vec<u8>,
    },
}

impl CoapCache {
    /// Konstruktor mit DoS-Cap.
    #[must_use]
    pub fn new(max_entries: usize) -> Self {
        Self {
            entries: Mutex::new(BTreeMap::new()),
            max_entries,
        }
    }

    /// Spec §5.6.1 — Stash a Response.
    pub fn store(
        &self,
        key: Vec<u8>,
        response: CoapMessage,
        max_age: Duration,
        etag: Option<Vec<u8>>,
    ) {
        if let Ok(mut g) = self.entries.lock() {
            if g.len() >= self.max_entries {
                // FIFO-Eviction wenn Cap erreicht.
                if let Some(first) = g.keys().next().cloned() {
                    g.remove(&first);
                }
            }
            g.insert(
                key,
                CacheEntry {
                    response,
                    inserted: Instant::now(),
                    max_age,
                    etag,
                },
            );
        }
    }

    /// Spec §5.6.1 / §5.6.2 — Lookup mit Freshness-Check.
    pub fn lookup(&self, key: &[u8]) -> CacheLookup {
        let g = match self.entries.lock() {
            Ok(g) => g,
            Err(_) => return CacheLookup::Miss,
        };
        let Some(entry) = g.get(key) else {
            return CacheLookup::Miss;
        };
        if entry.inserted.elapsed() < entry.max_age {
            CacheLookup::Fresh(entry.response.clone())
        } else if let Some(etag) = entry.etag.clone() {
            CacheLookup::Stale {
                response: entry.response.clone(),
                etag,
            }
        } else {
            // Stale ohne ETag → cannot validate, treat as Miss.
            CacheLookup::Miss
        }
    }

    /// Anzahl Eintraege.
    pub fn len(&self) -> usize {
        self.entries.lock().map_or(0, |g| g.len())
    }

    /// `true` bei leerem Cache.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Spec §5.6.x — Evict expired (without ETag for revalidation).
    pub fn evict_expired_without_etag(&self) -> usize {
        if let Ok(mut g) = self.entries.lock() {
            let before = g.len();
            g.retain(|_, e| e.inserted.elapsed() < e.max_age || e.etag.is_some());
            before - g.len()
        } else {
            0
        }
    }
}

// ---------------------------------------------------------------------------
// §5.7 Proxying — Forward-Proxy-Configuration
// ---------------------------------------------------------------------------

/// Spec §5.7.2 — Proxy-Mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProxyMode {
    /// `Forward-Proxy` — Client referenziert Proxy via `Proxy-Uri`-Option.
    Forward,
    /// `Reverse-Proxy` — Proxy ist transparent fuer den Client.
    Reverse,
}

/// Spec §5.7.x — Proxy-Konfiguration.
#[derive(Debug, Clone)]
pub struct ProxyConfig {
    /// Modus (Forward/Reverse).
    pub mode: ProxyMode,
    /// `true` wenn der Proxy CoAP↔CoAP forwardet.
    pub coap_to_coap: bool,
    /// `true` wenn der Proxy CoAP↔HTTP translatiert (Spec §10).
    pub http_translation: bool,
    /// Maximaler Hop-Count (Spec §5.7.1: Schutz gegen Forwarding-Loops).
    pub max_hops: u8,
}

impl Default for ProxyConfig {
    fn default() -> Self {
        Self {
            mode: ProxyMode::Forward,
            coap_to_coap: true,
            http_translation: false,
            // Spec §5.7.1 — empfohlen ≤ 16 Hops.
            max_hops: 16,
        }
    }
}

// ---------------------------------------------------------------------------
// §10 HTTP-Cross-Proto-Mapping
// ---------------------------------------------------------------------------

/// Spec §10.1 — HTTP-Status-Codes auf CoAP-Codes mappen.
///
/// Liefert das CoAP-Code-Tupel `(class, detail)` fuer HTTP-Status-Codes
/// nach §10.1 Table 8.
#[must_use]
pub fn http_status_to_coap(http_status: u16) -> Option<(u8, u8)> {
    match http_status {
        200 => Some((2, 5)),  // 2.05 Content (GET)
        201 => Some((2, 1)),  // 2.01 Created
        204 => Some((2, 4)),  // 2.04 Changed (PUT/POST/DELETE)
        400 => Some((4, 0)),  // 4.00 Bad Request
        401 => Some((4, 1)),  // 4.01 Unauthorized
        403 => Some((4, 3)),  // 4.03 Forbidden
        404 => Some((4, 4)),  // 4.04 Not Found
        405 => Some((4, 5)),  // 4.05 Method Not Allowed
        406 => Some((4, 6)),  // 4.06 Not Acceptable
        412 => Some((4, 12)), // 4.12 Precondition Failed
        413 => Some((4, 13)), // 4.13 Request Entity Too Large
        415 => Some((4, 15)), // 4.15 Unsupported Content-Format
        500 => Some((5, 0)),  // 5.00 Internal Server Error
        501 => Some((5, 1)),  // 5.01 Not Implemented
        502 => Some((5, 2)),  // 5.02 Bad Gateway
        503 => Some((5, 3)),  // 5.03 Service Unavailable
        504 => Some((5, 4)),  // 5.04 Gateway Timeout
        _ => None,
    }
}

/// Spec §10.1 — Inverses Mapping (CoAP-Code auf HTTP-Status).
#[must_use]
pub fn coap_to_http_status(class: u8, detail: u8) -> Option<u16> {
    match (class, detail) {
        (2, 1) => Some(201),
        (2, 4) => Some(204),
        (2, 5) => Some(200),
        (4, 0) => Some(400),
        (4, 1) => Some(401),
        (4, 3) => Some(403),
        (4, 4) => Some(404),
        (4, 5) => Some(405),
        (4, 6) => Some(406),
        (4, 12) => Some(412),
        (4, 13) => Some(413),
        (4, 15) => Some(415),
        (5, 0) => Some(500),
        (5, 1) => Some(501),
        (5, 2) => Some(502),
        (5, 3) => Some(503),
        (5, 4) => Some(504),
        _ => None,
    }
}

/// Spec §10.2 — HTTP-Method auf CoAP-Method.
///
/// Liefert `(class=0, detail)` fuer GET/POST/PUT/DELETE; `None` fuer
/// HTTP-spezifische Methods (HEAD/OPTIONS/PATCH/etc.) — die werden
/// vom Proxy abgewiesen.
#[must_use]
pub fn http_method_to_coap(method: &str) -> Option<u8> {
    match method.to_uppercase().as_str() {
        "GET" => Some(1),
        "POST" => Some(2),
        "PUT" => Some(3),
        "DELETE" => Some(4),
        _ => None,
    }
}

/// Spec §10.2 — Inverses Mapping (CoAP-Method auf HTTP).
#[must_use]
pub fn coap_method_to_http(method_detail: u8) -> Option<&'static str> {
    match method_detail {
        1 => Some("GET"),
        2 => Some("POST"),
        3 => Some("PUT"),
        4 => Some("DELETE"),
        _ => None,
    }
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;
    use crate::message::{CoapCode, MessageType};

    fn sample_response() -> CoapMessage {
        CoapMessage::new(MessageType::Acknowledgement, CoapCode::CONTENT, 1)
    }

    // §5.6 Cache
    #[test]
    fn empty_cache_returns_miss() {
        let c = CoapCache::new(10);
        assert_eq!(c.lookup(b"key"), CacheLookup::Miss);
        assert!(c.is_empty());
    }

    #[test]
    fn store_then_fresh_lookup() {
        let c = CoapCache::new(10);
        c.store(
            b"key".to_vec(),
            sample_response(),
            Duration::from_secs(60),
            None,
        );
        assert_eq!(c.len(), 1);
        assert!(matches!(c.lookup(b"key"), CacheLookup::Fresh(_)));
    }

    #[test]
    fn stale_with_etag_yields_validation_path() {
        let c = CoapCache::new(10);
        c.store(
            b"key".to_vec(),
            sample_response(),
            Duration::from_millis(1),
            Some(b"etag-1".to_vec()),
        );
        std::thread::sleep(Duration::from_millis(20));
        match c.lookup(b"key") {
            CacheLookup::Stale { etag, .. } => assert_eq!(etag, b"etag-1"),
            other => panic!("expected Stale, got {other:?}"),
        }
    }

    #[test]
    fn stale_without_etag_yields_miss() {
        let c = CoapCache::new(10);
        c.store(
            b"key".to_vec(),
            sample_response(),
            Duration::from_millis(1),
            None,
        );
        std::thread::sleep(Duration::from_millis(20));
        assert_eq!(c.lookup(b"key"), CacheLookup::Miss);
    }

    #[test]
    fn cap_evicts_oldest() {
        let c = CoapCache::new(2);
        c.store(
            b"a".to_vec(),
            sample_response(),
            Duration::from_secs(60),
            None,
        );
        c.store(
            b"b".to_vec(),
            sample_response(),
            Duration::from_secs(60),
            None,
        );
        c.store(
            b"c".to_vec(),
            sample_response(),
            Duration::from_secs(60),
            None,
        );
        assert_eq!(c.len(), 2);
    }

    #[test]
    fn evict_expired_without_etag_keeps_revalidatable() {
        let c = CoapCache::new(10);
        c.store(
            b"a".to_vec(),
            sample_response(),
            Duration::from_millis(1),
            None,
        );
        c.store(
            b"b".to_vec(),
            sample_response(),
            Duration::from_millis(1),
            Some(b"e".to_vec()),
        );
        std::thread::sleep(Duration::from_millis(20));
        let evicted = c.evict_expired_without_etag();
        assert_eq!(evicted, 1);
        assert_eq!(c.len(), 1);
    }

    // §5.7 Proxy
    #[test]
    fn proxy_config_default_is_forward_coap_to_coap() {
        let c = ProxyConfig::default();
        assert_eq!(c.mode, ProxyMode::Forward);
        assert!(c.coap_to_coap);
        assert!(!c.http_translation);
        assert_eq!(c.max_hops, 16);
    }

    // §10.1 HTTP-Status-Mapping
    #[test]
    fn http_200_maps_to_coap_2_05() {
        assert_eq!(http_status_to_coap(200), Some((2, 5)));
    }

    #[test]
    fn http_404_maps_to_coap_4_04() {
        assert_eq!(http_status_to_coap(404), Some((4, 4)));
    }

    #[test]
    fn http_500_maps_to_coap_5_00() {
        assert_eq!(http_status_to_coap(500), Some((5, 0)));
    }

    #[test]
    fn http_unknown_returns_none() {
        assert!(http_status_to_coap(999).is_none());
    }

    #[test]
    fn coap_to_http_round_trip() {
        for h in [200u16, 201, 204, 400, 401, 403, 404, 405, 412, 500, 503] {
            let (c, d) = http_status_to_coap(h).expect("ok");
            assert_eq!(coap_to_http_status(c, d), Some(h));
        }
    }

    // §10.2 HTTP-Method-Mapping
    #[test]
    fn http_get_maps_to_coap_1() {
        assert_eq!(http_method_to_coap("GET"), Some(1));
        assert_eq!(http_method_to_coap("get"), Some(1));
    }

    #[test]
    fn http_unknown_method_returns_none() {
        assert!(http_method_to_coap("HEAD").is_none());
        assert!(http_method_to_coap("PATCH").is_none());
    }

    #[test]
    fn coap_method_round_trip() {
        for m in ["GET", "POST", "PUT", "DELETE"] {
            let d = http_method_to_coap(m).expect("ok");
            assert_eq!(coap_method_to_http(d), Some(m));
        }
    }
}