rocketmq-protocol 1.1.0

Runtime-neutral RocketMQ wire protocol contracts
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
// Copyright 2026 The RocketMQ Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::EncodeSink;
use super::HeaderFieldSource;
use super::HeaderFieldSpec;
use super::HeaderFlattenSpec;
use super::ProtocolContractViolation;
use super::ResolvedHeaderKey;
use crate::HeaderMap;

/// Statically dispatched codec contract for an explicit request-header schema.
///
/// Implementations are generated by `RequestHeaderCodec`. Map and binary
/// destinations share [`Self::encode_into`], so validation, canonical keys,
/// Java ranges, flattening, and value conversion cannot diverge by format.
pub trait HeaderCodec: Sized {
    /// Stable, fully qualified Rust schema identifier.
    const TYPE_ID: &'static str;
    /// Rust header name used in diagnostics.
    const HEADER_NAME: &'static str;
    /// Fully qualified Java peer when one is declared.
    const JAVA_CLASS: Option<&'static str>;
    /// Recursive upper bound used to reserve map entries.
    const FIELD_COUNT_HINT: usize;
    /// Fields declared directly by this header, in stable binary order.
    const LOCAL_FIELD_SPECS: &'static [HeaderFieldSpec];
    /// Flatten groups declared directly by this header, in stable binary order.
    const LOCAL_FLATTEN_SPECS: &'static [HeaderFlattenSpec];
    /// Whether direct binary generation was requested for the schema.
    const FAST_ENABLED: bool;
    /// Whether [`Self::decode_from_slots`] reads values recorded by [`Self::collect_slot`].
    ///
    /// Generated codecs set this so a header and its flattened children decode
    /// from one pass over the source. The default keeps manually implemented
    /// codecs on their own [`Self::decode_from_source`] scan.
    #[doc(hidden)]
    const SUPPORTS_SLOT_DECODE: bool = false;
    /// Number of borrowed value slots used by this header and its flattened children.
    #[doc(hidden)]
    const SLOT_COUNT: usize = 0;

    /// Validates this header layer before it writes to a wire destination.
    ///
    /// # Errors
    ///
    /// Returns a classified structural or header-specific validation failure.
    fn validate_for_wire(&self) -> Result<(), ProtocolContractViolation>;

    /// Appends canonical fields to a statically dispatched destination.
    ///
    /// # Errors
    ///
    /// Returns a typed validation, range, or destination representation error.
    fn encode_into<S: EncodeSink>(&self, sink: &mut S) -> Result<(), ProtocolContractViolation>;

    /// Decodes this header from borrowed extension fields.
    ///
    /// # Errors
    ///
    /// Returns a typed missing, conflict, conversion, range, or validation error.
    fn decode_from_map(map: &HeaderMap) -> Result<Self, ProtocolContractViolation>;

    /// Decodes this header directly from a borrowed field source.
    ///
    /// Generated request-header codecs override this method with a zero-materialization
    /// scan. The default keeps manually implemented codecs source-compatible.
    ///
    /// # Errors
    ///
    /// Returns the same classified failures as [`Self::decode_from_map`].
    #[inline]
    fn decode_from_source(source: &dyn HeaderFieldSource) -> Result<Self, ProtocolContractViolation> {
        let map = source.to_header_map();
        Self::decode_from_map(&map)
    }

    /// Records one visited field when its key belongs to this schema or a flattened child.
    ///
    /// `slots` must hold [`Self::SLOT_COUNT`] entries. A later value for the
    /// same key replaces the earlier one, matching repeated source scans.
    #[doc(hidden)]
    #[inline]
    fn collect_slot<'a>(_slots: &mut [Option<&'a str>], _key: &str, _value: &'a str) {}

    /// Builds the header from slots filled by [`Self::collect_slot`] during one scan of `source`.
    ///
    /// Codecs without slot support ignore `slots` and scan `source` themselves,
    /// so a generated parent can flatten them without changing their behavior.
    ///
    /// # Errors
    ///
    /// Returns the same classified failures as [`Self::decode_from_source`].
    #[doc(hidden)]
    #[inline]
    fn decode_from_slots(
        _slots: &[Option<&str>],
        source: &dyn HeaderFieldSource,
    ) -> Result<Self, ProtocolContractViolation> {
        Self::decode_from_source(source)
    }

    /// Returns whether this header or any flattened child owns a present key.
    fn contains_any_field(map: &HeaderMap) -> bool;

    /// Returns whether this header or a flattened child owns a source field.
    #[inline]
    fn contains_any_field_source(source: &dyn HeaderFieldSource) -> bool {
        let mut contains = false;
        source.visit_fields_while(&mut |key, _value| {
            if Self::contains_wire_key(key) {
                contains = true;
                false
            } else {
                true
            }
        });
        contains
    }

    /// Estimates the encoded ROCKETMQ extension-field payload length.
    ///
    /// The result saturates at [`usize::MAX`]. It is a capacity hint and does
    /// not validate the header or guarantee that a specific format can encode it.
    fn encoded_len_hint(&self) -> usize;

    /// Visits field schemas declared here and recursively by flattened headers.
    fn visit_field_specs(visitor: &mut dyn FnMut(&HeaderFieldSpec));

    /// Visits flatten schemas declared here and recursively by flattened headers.
    fn visit_flatten_specs(visitor: &mut dyn FnMut(&HeaderFlattenSpec));

    /// Resolves a canonical key or alias to its owning typed field.
    fn resolve_wire_key(key: &str) -> Option<ResolvedHeaderKey>;

    /// Resolves a key and returns its canonical wire key.
    #[inline]
    fn canonical_wire_key(key: &str) -> Option<&'static str> {
        Self::resolve_wire_key(key).map(|resolved| resolved.canonical)
    }

    /// Returns whether a canonical key or alias belongs to this schema.
    #[inline]
    fn contains_wire_key(key: &str) -> bool {
        Self::resolve_wire_key(key).is_some()
    }
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;

    use cheetah_string::CheetahString;
    use rocketmq_macros::RequestHeaderCodec;

    use super::*;
    use crate::protocol::header_codec::private::FieldSourceSealed;
    use crate::protocol::header_codec::AliasConflictPolicy;
    use crate::protocol::header_codec::DynamicCollisionPolicy;
    use crate::protocol::header_codec::HeaderFieldContext;
    use crate::protocol::header_codec::HeaderValueKind;

    /// Counts how often a decoder walks the extension fields.
    struct CountingSource<'m> {
        fields: &'m HeaderMap,
        scans: Cell<usize>,
    }

    impl<'m> CountingSource<'m> {
        fn new(fields: &'m HeaderMap) -> Self {
            Self {
                fields,
                scans: Cell::new(0),
            }
        }
    }

    impl FieldSourceSealed for CountingSource<'_> {}

    impl HeaderFieldSource for CountingSource<'_> {
        fn visit_fields_while<'a>(&'a self, visitor: &mut dyn FnMut(&'a str, &'a str) -> bool) {
            self.scans.set(self.scans.get() + 1);
            self.fields.visit_fields_while(visitor);
        }

        fn to_header_map(&self) -> HeaderMap {
            self.fields.clone()
        }
    }

    #[derive(Debug, PartialEq, RequestHeaderCodec)]
    #[header(type_id = "rocketmq_protocol::tests::SlotLeaf")]
    struct SlotLeaf {
        #[header(key = "leaf", alias = "legacyLeaf", alias_conflict = "prefer_canonical")]
        leaf: Option<CheetahString>,
        shared: Option<i32>,
    }

    #[derive(Debug, PartialEq, RequestHeaderCodec)]
    #[header(type_id = "rocketmq_protocol::tests::SlotMiddle")]
    struct SlotMiddle {
        middle: Option<bool>,
        #[header(flatten, presence = "any")]
        leaf: Option<SlotLeaf>,
    }

    #[derive(Debug, PartialEq, RequestHeaderCodec)]
    #[header(type_id = "rocketmq_protocol::tests::SlotRoot")]
    struct SlotRoot {
        #[header(required)]
        id: i32,
        shared: Option<i32>,
        #[header(flatten, presence = "always")]
        middle: Option<SlotMiddle>,
    }

    /// A codec written by hand, which therefore has no slot support.
    #[derive(Debug, PartialEq)]
    struct ManualChild {
        token: Option<CheetahString>,
    }

    impl ManualChild {
        const TOKEN: HeaderFieldContext = HeaderFieldContext::new(
            "rocketmq_protocol::tests::ManualChild",
            "token",
            HeaderValueKind::String,
            None,
        );
    }

    impl HeaderCodec for ManualChild {
        const TYPE_ID: &'static str = "rocketmq_protocol::tests::ManualChild";
        const HEADER_NAME: &'static str = "ManualChild";
        const JAVA_CLASS: Option<&'static str> = None;
        const FIELD_COUNT_HINT: usize = 1;
        const LOCAL_FIELD_SPECS: &'static [HeaderFieldSpec] = &[];
        const LOCAL_FLATTEN_SPECS: &'static [HeaderFlattenSpec] = &[];
        const FAST_ENABLED: bool = false;

        fn validate_for_wire(&self) -> Result<(), ProtocolContractViolation> {
            Ok(())
        }

        fn encode_into<S: EncodeSink>(&self, sink: &mut S) -> Result<(), ProtocolContractViolation> {
            if let Some(token) = &self.token {
                sink.write("token", token, Self::TOKEN)?;
            }
            Ok(())
        }

        fn decode_from_map(map: &HeaderMap) -> Result<Self, ProtocolContractViolation> {
            Ok(Self {
                token: map.get("token").cloned(),
            })
        }

        fn contains_any_field(map: &HeaderMap) -> bool {
            map.contains_key("token")
        }

        fn encoded_len_hint(&self) -> usize {
            0
        }

        fn visit_field_specs(_visitor: &mut dyn FnMut(&HeaderFieldSpec)) {}

        fn visit_flatten_specs(_visitor: &mut dyn FnMut(&HeaderFlattenSpec)) {}

        fn resolve_wire_key(key: &str) -> Option<ResolvedHeaderKey> {
            (key == "token").then_some(ResolvedHeaderKey {
                header: Self::HEADER_NAME,
                owner_type_id: Self::TYPE_ID,
                canonical: "token",
                precedence: 0,
                alias_conflict: AliasConflictPolicy::Error,
                dynamic_collision: DynamicCollisionPolicy::ErrorOnDifferentValue,
            })
        }
    }

    #[derive(Debug, PartialEq, RequestHeaderCodec)]
    #[header(type_id = "rocketmq_protocol::tests::ManualParent")]
    struct ManualParent {
        #[header(required)]
        id: i32,
        #[header(flatten, presence = "any")]
        child: Option<ManualChild>,
    }

    fn fields(entries: &[(&str, &str)]) -> HeaderMap {
        entries
            .iter()
            .map(|(key, value)| (CheetahString::from_slice(key), CheetahString::from_slice(value)))
            .collect()
    }

    #[test]
    fn flattened_generated_headers_decode_from_one_source_scan() {
        const {
            assert!(<SlotRoot as HeaderCodec>::SUPPORTS_SLOT_DECODE);
            assert!(<SlotLeaf as HeaderCodec>::SLOT_COUNT == 3);
            assert!(<SlotMiddle as HeaderCodec>::SLOT_COUNT == 4);
            assert!(<SlotRoot as HeaderCodec>::SLOT_COUNT == 6);
        }
        let fields = fields(&[
            ("id", "7"),
            ("middle", "true"),
            ("legacyLeaf", "leaf-a"),
            ("unrelated", "ignored"),
        ]);
        let source = CountingSource::new(&fields);

        let decoded = SlotRoot::decode_from_source(&source).unwrap();

        assert_eq!(source.scans.get(), 1);
        assert_eq!(
            decoded,
            SlotRoot {
                id: 7,
                shared: None,
                middle: Some(SlotMiddle {
                    middle: Some(true),
                    leaf: Some(SlotLeaf {
                        leaf: Some("leaf-a".into()),
                        shared: None,
                    }),
                }),
            }
        );
        assert_eq!(decoded, SlotRoot::decode_from_map(&fields).unwrap());
    }

    #[test]
    fn single_scan_keeps_presence_alias_and_shared_key_semantics() {
        let absent_leaf = fields(&[("id", "7")]);
        let source = CountingSource::new(&absent_leaf);
        let decoded = SlotRoot::decode_from_source(&source).unwrap();
        assert_eq!(source.scans.get(), 1);
        assert_eq!(
            decoded.middle,
            Some(SlotMiddle {
                middle: None,
                leaf: None,
            })
        );

        // A key declared by two layers reaches both, as it did with one scan per layer.
        let shared = fields(&[
            ("id", "7"),
            ("shared", "3"),
            ("leaf", "canonical"),
            ("legacyLeaf", "legacy"),
        ]);
        let decoded = SlotRoot::decode_from_source(&shared).unwrap();
        assert_eq!(decoded.shared, Some(3));
        let leaf = decoded.middle.and_then(|middle| middle.leaf).unwrap();
        assert_eq!(leaf.shared, Some(3));
        assert_eq!(leaf.leaf.as_deref(), Some("canonical"));

        let invalid = fields(&[("id", "7"), ("shared", "not-a-number")]);
        assert!(matches!(
            SlotRoot::decode_from_source(&invalid),
            Err(ProtocolContractViolation::InvalidValue {
                header: "rocketmq_protocol::tests::SlotRoot",
                key: "shared",
                ..
            })
        ));
        let missing = fields(&[("shared", "3")]);
        assert!(matches!(
            SlotRoot::decode_from_source(&missing),
            Err(ProtocolContractViolation::Missing { key: "id", .. })
        ));
    }

    #[test]
    fn slots_keep_the_last_value_and_reject_a_foreign_layout() {
        let mut slots = [None; <SlotLeaf as HeaderCodec>::SLOT_COUNT];
        SlotLeaf::collect_slot(&mut slots, "leaf", "first");
        SlotLeaf::collect_slot(&mut slots, "leaf", "last");
        SlotLeaf::collect_slot(&mut slots, "other", "ignored");
        let empty = HeaderMap::new();
        let decoded = SlotLeaf::decode_from_slots(&slots, &empty).unwrap();
        assert_eq!(decoded.leaf.as_deref(), Some("last"));

        // Slots sized for another schema are ignored in favor of a fresh scan.
        let fields = fields(&[("id", "7"), ("middle", "false")]);
        let source = CountingSource::new(&fields);
        let mut foreign = [None; 2];
        SlotRoot::collect_slot(&mut foreign, "id", "9");
        assert_eq!(foreign, [None; 2]);
        let decoded = SlotRoot::decode_from_slots(&foreign, &source).unwrap();
        assert_eq!(source.scans.get(), 1);
        assert_eq!(decoded.id, 7);
        assert_eq!(decoded.middle.and_then(|middle| middle.middle), Some(false));
    }

    #[test]
    fn handwritten_codecs_stay_flattenable_through_their_own_decoder() {
        const {
            assert!(!<ManualChild as HeaderCodec>::SUPPORTS_SLOT_DECODE);
            assert!(<ManualChild as HeaderCodec>::SLOT_COUNT == 0);
            assert!(<ManualParent as HeaderCodec>::SLOT_COUNT == 1);
        }
        let present = fields(&[("id", "7"), ("token", "secret")]);
        let source = CountingSource::new(&present);
        let decoded = ManualParent::decode_from_source(&source).unwrap();
        assert_eq!(
            decoded,
            ManualParent {
                id: 7,
                child: Some(ManualChild {
                    token: Some("secret".into()),
                }),
            }
        );
        // One scan for the generated layer and one presence probe for the handwritten child.
        assert_eq!(source.scans.get(), 2);

        let absent = fields(&[("id", "7")]);
        assert_eq!(ManualParent::decode_from_source(&absent).unwrap().child, None);
    }
}