arcadedb_protocol/record/mod.rs
1//! Typed record decoding — the runtime behind [`crate::RecordDecode`].
2//!
3//! Three pieces:
4//!
5//! 1. [`FromGrpcValue`] — a conversion trait from a single [`GrpcValue`],
6//! implemented for the primitives, containers (`Option`, `Vec`, maps), and
7//! any struct deriving [`crate::RecordDecode`]. App-specific types plug in
8//! either by implementing this trait or via the derive's
9//! `#[record(with = "...")]` attribute (which references a plain
10//! `fn(&GrpcValue) -> Result<T, RecordDecodeError>`).
11//! 2. [`RecordDecodeError`] — per-property decode errors carrying the property
12//! path (`tags[2]`, `speech_prefix.lines[3]`) and the expected vs actual
13//! wire kind.
14//! 3. The property-access helpers the derive's generated code calls into
15//! (`get`, `get_opt`, `get_or`, `get_with`, `get_with_or`, `get_opt_with`,
16//! and the `bytes` family for `Vec<u8>` blobs).
17
18mod types;
19
20use std::collections::HashMap;
21use std::fmt;
22
23use crate::proto::com::arcadedb::grpc::{grpc_value::Kind, GrpcMap, GrpcRecord, GrpcValue};
24
25// ---------------------------------------------------------------------------
26// Error
27// ---------------------------------------------------------------------------
28
29/// A decode failure for one property. Carries the property path (dotted for
30/// nested records, `list[3]` for elements) so errors read like
31/// `property `speech_prefix.plain_text`: expected string, got embedded`.
32#[derive(Debug, Clone, PartialEq, Eq)]
33#[non_exhaustive]
34pub enum RecordDecodeError {
35 /// The property is absent and the field is neither `Option` nor defaulted.
36 MissingField {
37 /// Dotted/braced path of the missing property.
38 path: String,
39 },
40 /// The value kind didn't match the target type (or the payload couldn't
41 /// convert, e.g. an out-of-range integer).
42 TypeMismatch {
43 /// Property path; empty when raised deep inside a list/embed.
44 path: String,
45 /// Human-readable target type, e.g. `"i32"`.
46 expected: &'static str,
47 /// Human-readable wire kind, e.g. `"int64"`.
48 actual: &'static str,
49 },
50 /// Anything else — unknown enum variant, custom `with`/trait conversions,
51 /// invalid payload inside an otherwise-matching kind.
52 Conversion { message: String },
53}
54
55impl RecordDecodeError {
56 /// Missing-property error for a `&'static str` property name (codegen).
57 pub fn missing_field(field: &str) -> Self {
58 Self::MissingField {
59 path: field.to_string(),
60 }
61 }
62
63 /// Kind mismatch without a field context (nested conversions).
64 pub fn type_mismatch(expected: &'static str, actual: &'static str) -> Self {
65 Self::TypeMismatch {
66 path: String::new(),
67 expected,
68 actual,
69 }
70 }
71
72 /// Free-form conversion error.
73 pub fn conversion(message: impl Into<String>) -> Self {
74 Self::Conversion {
75 message: message.into(),
76 }
77 }
78
79 /// Unknown enum variant string.
80 pub fn unknown_variant(variant: &str) -> Self {
81 Self::conversion(format!("unknown variant `{variant}`"))
82 }
83
84 /// Prepend a property path segment to this error (used by the generated
85 /// code and the `get_*` helpers to thread field context upward).
86 pub fn with_field(self, field: &str) -> Self {
87 match self {
88 RecordDecodeError::MissingField { mut path } => {
89 if path.is_empty() {
90 path = field.to_string();
91 } else {
92 path = format!("{field}.{path}");
93 }
94 Self::MissingField { path }
95 }
96 RecordDecodeError::TypeMismatch {
97 mut path,
98 expected,
99 actual,
100 } => {
101 if path.is_empty() {
102 path = field.to_string();
103 } else {
104 path = format!("{field}.{path}");
105 }
106 Self::TypeMismatch {
107 path,
108 expected,
109 actual,
110 }
111 }
112 RecordDecodeError::Conversion { message } => Self::Conversion {
113 message: format!("field `{field}`: {message}"),
114 },
115 }
116 }
117}
118
119impl fmt::Display for RecordDecodeError {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 match self {
122 RecordDecodeError::MissingField { path } => {
123 write!(f, "missing property `{path}`")
124 }
125 RecordDecodeError::TypeMismatch {
126 path,
127 expected,
128 actual,
129 } => {
130 if path.is_empty() {
131 write!(f, "expected {expected}, got {actual}")
132 } else {
133 write!(f, "property `{path}`: expected {expected}, got {actual}")
134 }
135 }
136 RecordDecodeError::Conversion { message } => f.write_str(message),
137 }
138 }
139}
140
141impl std::error::Error for RecordDecodeError {}
142
143/// Human name for a `GrpcValue` wire kind (or `null` when the oneof is unset).
144pub fn kind_name(kind: &Option<Kind>) -> &'static str {
145 match kind {
146 None => "null",
147 Some(Kind::BoolValue(_)) => "bool",
148 Some(Kind::Int32Value(_)) => "int32",
149 Some(Kind::Int64Value(_)) => "int64",
150 Some(Kind::FloatValue(_)) => "float",
151 Some(Kind::DoubleValue(_)) => "double",
152 Some(Kind::StringValue(_)) => "string",
153 Some(Kind::BytesValue(_)) => "bytes",
154 Some(Kind::TimestampValue(_)) => "timestamp",
155 Some(Kind::ListValue(_)) => "list",
156 Some(Kind::MapValue(_)) => "map",
157 Some(Kind::EmbeddedValue(_)) => "embedded",
158 Some(Kind::LinkValue(_)) => "link",
159 Some(Kind::DecimalValue(_)) => "decimal",
160 }
161}
162
163// ---------------------------------------------------------------------------
164// Link — the graph-native record id
165// ---------------------------------------------------------------------------
166
167/// A record identifier (`#bucket:pos`) — the typed form of an ArcadeDB link,
168/// covering a record's own `@rid` and edge endpoints (`@in`/`@out`).
169///
170/// Decodes from `LinkValue` (LINK columns, `expand()` projections) and from
171/// rid-shaped strings (`SELECT @out`); encodes as a typed `LinkValue`. Fields
172/// named `@rid` fall back to the record's own metadata via the derive's synth
173/// path, exactly like string rid fields.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
175pub struct Link {
176 /// The bucket id (before the colon).
177 pub bucket: i32,
178 /// The position within the bucket (after the colon).
179 pub pos: i64,
180}
181
182impl Link {
183 pub fn new(bucket: i32, pos: i64) -> Self {
184 Self { bucket, pos }
185 }
186
187 /// Parse `#bucket:pos`. Both parts are non-negative; the leading `#` is
188 /// required.
189 pub fn parse(s: &str) -> Result<Self, RecordDecodeError> {
190 let invalid = || RecordDecodeError::conversion(format!("invalid rid `{s}`"));
191 let (bucket, pos) = s
192 .strip_prefix('#')
193 .and_then(|body| body.split_once(':'))
194 .ok_or_else(invalid)?;
195 let bucket = bucket.parse::<i32>().map_err(|_| invalid())?;
196 let pos = pos.parse::<i64>().map_err(|_| invalid())?;
197 if bucket < 0 || pos < 0 {
198 return Err(invalid());
199 }
200 Ok(Self { bucket, pos })
201 }
202
203 /// The canonical rid string, `#bucket:pos`.
204 pub fn to_rid_string(&self) -> String {
205 format!("#{}:{}", self.bucket, self.pos)
206 }
207}
208
209impl fmt::Display for Link {
210 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211 // Write directly — the old `to_rid_string()` here allocated per
212 // formatting, and Display rides every rid in bulk paths.
213 write!(f, "#{}:{}", self.bucket, self.pos)
214 }
215}
216
217impl std::str::FromStr for Link {
218 type Err = RecordDecodeError;
219 fn from_str(s: &str) -> Result<Self, Self::Err> {
220 Self::parse(s)
221 }
222}
223
224#[cfg(feature = "serde")]
225mod link_serde {
226 use super::*;
227
228 /// Serializes as the rid string (`"#bucket:pos"`) — the JSON-facing form
229 /// consumers already treat as an opaque handle.
230 impl serde::Serialize for Link {
231 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
232 serializer.serialize_str(&self.to_rid_string())
233 }
234 }
235
236 impl<'de> serde::Deserialize<'de> for Link {
237 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
238 let s = String::deserialize(deserializer)?;
239 Self::parse(&s).map_err(serde::de::Error::custom)
240 }
241 }
242}
243
244// ---------------------------------------------------------------------------
245// Conversion trait
246// ---------------------------------------------------------------------------
247
248/// Convert a single [`GrpcValue`] into `Self`, borrowing from the value when
249/// the target type is a borrowed view (`&'de str`, `Cow<'de, str>`,
250/// `&'de [u8]`).
251///
252/// Implemented by the primitives, the containers (`Option`, `Vec`, maps),
253/// `serde_json::Value`, and every struct/enum deriving [`crate::RecordDecode`].
254/// External identity types (opaque string ids, …) that shouldn't be
255/// coupled to this crate implement this trait once and reuse it everywhere, or
256/// use the `#[record(with = "...")]` field attribute per declaration.
257pub trait FromGrpcValue<'de>: Sized {
258 fn from_grpc_value(value: &'de GrpcValue) -> Result<Self, RecordDecodeError>;
259}
260
261// ---------------------------------------------------------------------------
262// Encoding trait
263// ---------------------------------------------------------------------------
264
265/// Encode a typed DTO into a wire [`GrpcRecord`] for writes (`BulkInsert`,
266/// `UPDATE` payloads) — the encode-side mirror of [`FromGrpcValue`].
267///
268/// Implemented by deriving [`crate::RecordEncode`] (which maps each field's
269/// Rust type onto a `GrpcValue` wire kind), and by hand for small value types
270/// that need a specific wire shape. The defaulted methods build on
271/// [`Self::props`] lest custom impls repeat the record-construction code;
272/// override [`Self::to_grpc_value`] when the nested form should not be a map
273/// (e.g. a scalar wrapper used as a field value).
274pub trait ToGrpcRecord {
275 /// The bulk-conflict identity: wire names of the fields marked
276 /// `#[record(key)]` (empty when none — value-shaped or append-only
277 /// types). Consumed by the typed bulk helpers so call sites cannot
278 /// disagree with the DTO about the key.
279 const KEY_COLUMNS: &'static [&'static str] = &[];
280
281 /// Field name → wire value pairs: the record's property map. Fields
282 /// skipped for encoding (`Option::None`, `skip`/`skip_serializing_if`)
283 /// are absent.
284 fn props(&self) -> Vec<(&str, GrpcValue)>;
285
286 /// The whole record, tagged with the target class (`type` on the wire).
287 fn to_grpc_record(&self, class: &str) -> GrpcRecord {
288 crate::rec(class, self.props())
289 }
290
291 /// The type as a nested value: a map of its properties (ArcadeDB's
292 /// `embedded`/`map` shapes). Nested derived structs fall back to this
293 /// automatically.
294 fn to_grpc_value(&self) -> GrpcValue {
295 GrpcValue {
296 kind: Some(Kind::MapValue(GrpcMap {
297 entries: self
298 .props()
299 .into_iter()
300 .map(|(k, v)| (k.to_string(), v))
301 .collect(),
302 })),
303 logical_type: String::new(),
304 }
305 }
306
307 /// The properties as a `name → value` map for SQL `:param` binding
308 /// (`query`/`query_with_values`), where the *record* shape doesn't apply —
309 /// `Option::None` fields stay absent, exactly like `props()`.
310 ///
311 /// The map type is the caller's choice — `std::collections::HashMap`,
312 /// `ahash::AHashMap`, `rustc_hash::FxHashMap`, or the crate's own
313 /// [`Params`](crate::Params):
314 ///
315 /// ```ignore
316 /// use arcadedb_protocol::Params;
317 ///
318 /// // the crate's own parameter map:
319 /// let params = dto.to_param_map::<Params>();
320 /// // an aHash map (the `ahash` feature):
321 /// let params = dto.to_param_map::<ahash::AHashMap<String, GrpcValue>>();
322 /// ```
323 ///
324 /// The target type must be pinned by the call site (an annotation or a
325 /// turbofish): the compiler cannot pick a map type out of thin air, and
326 /// a bare `dto.to_param_map()` leaves the type unconstrained.
327 fn to_param_map<M: FromIterator<(String, GrpcValue)>>(&self) -> M
328 where
329 Self: Sized,
330 {
331 self.props()
332 .into_iter()
333 .map(|(k, v)| (k.to_string(), v))
334 .collect()
335 }
336
337 /// Wire names of the columns that differ between two snapshots of the
338 /// same record (`self` = old, `other` = new). The derive compares Rust
339 /// field values directly — no wire encoding, and allocation proportional
340 /// to the number of CHANGED columns (identical snapshots allocate
341 /// nothing); this default (for hand impls) diffs the encoded `props()`
342 /// of both sides.
343 ///
344 /// Semantics match [`props_diff`]: an `Option` going `Some → None` is not
345 /// SET-expressible and is never reported; fields the NEW snapshot omits
346 /// (`skip_serializing_if`) are never reported. Derived structs require
347 /// `PartialEq` field types — wrap exotic ones in `#[record(with = "...")]`
348 /// (compared via their encoded value) if needed.
349 fn changed_wires(&self, other: &Self) -> Vec<String> {
350 props_diff(self, other)
351 .into_iter()
352 .map(|(k, _)| k)
353 .collect()
354 }
355
356 /// The by-value encode path: consume the DTO, MOVING owned payloads
357 /// (`String`/`Vec<u8>`/`Vec<String>` fields) into the wire record instead
358 /// of cloning them. The derive overrides this with a moving
359 /// implementation; this default falls back to the borrowing
360 /// [`to_grpc_record`](Self::to_grpc_record) (hand impls clone, as before).
361 /// Use it wherever the row is owned and spent — bulk writers in
362 /// particular (`bulk_upsert_dtos` already does).
363 fn into_grpc_record(self, class: &str) -> GrpcRecord
364 where
365 Self: Sized,
366 {
367 self.to_grpc_record(class)
368 }
369}
370
371// ---------------------------------------------------------------------------
372// Diff-based partial updates (built on `props()`)
373// ---------------------------------------------------------------------------
374
375/// The columns whose encoded value differs between two snapshots of the same
376/// record — old-first: a column present in `new` but absent from `old`
377/// (e.g. an `Option` that became `Some`) counts as changed; a column absent
378/// from `new` (an `Option` that became `None`) cannot be expressed as a SET
379/// and is omitted. Re-scrapes that change nothing produce an empty diff and
380/// should skip the write entirely.
381pub fn props_diff<T: ToGrpcRecord + ?Sized>(old: &T, new: &T) -> Vec<(String, GrpcValue)> {
382 let old_props_vec = old.props();
383 let old_props: HashMap<&str, &GrpcValue> = old_props_vec.iter().map(|(k, v)| (*k, v)).collect();
384 new.props()
385 .into_iter()
386 .filter(|(k, v)| old_props.get(*k) != Some(&v))
387 .map(|(k, v)| (k.to_string(), v))
388 .collect()
389}
390
391/// [`props_diff`] as a `:param` map — bind it after `SET`-ing exactly the
392/// changed columns (build the SET list from the map's keys).
393///
394/// The map type is the caller's choice — `std::collections::HashMap`,
395/// `ahash::AHashMap`, `rustc_hash::FxHashMap`, or the crate's own
396/// [`Params`](crate::Params) — and must be pinned by the call site:
397///
398/// ```ignore
399/// let changed = changed_param_map::<Params, _>(&old, &new);
400/// let changed = changed_param_map::<ahash::AHashMap<String, GrpcValue>, _>(&old, &new);
401/// ```
402pub fn changed_param_map<M: FromIterator<(String, GrpcValue)>, T: ToGrpcRecord + ?Sized>(
403 old: &T,
404 new: &T,
405) -> M {
406 props_diff(old, new).into_iter().collect()
407}
408
409/// Decode a struct directly from a property MAP — the zero-copy flatten
410/// path. [`FromGrpcValue`] necessarily goes through an owned
411/// [`GrpcValue`] wrapper (embedded/map), which forces
412/// flattening code to clone the remaining entries; this trait lets derived
413/// structs decode straight from the record's own map with the parent's
414/// consumed keys hidden via `taken` — no rest-map materialization, and
415/// borrowed (`Cow<'de>`) flatten targets become possible.
416///
417/// Implemented by every `#[derive(RecordDecode)]` struct; manual types used
418/// as flatten targets implement it via
419/// [`from_map_via_value`] (the legacy clone-based path) — see the
420/// `impl_decode_from_map_via_value!` macro.
421pub trait DecodeFromMap<'de>: Sized {
422 /// Decode from `props`, treating every key in `taken` as absent (the
423 /// parent flatten scope consumed it). The synth args feed `@rid`/`@type`
424 /// fallbacks exactly like the record-level path.
425 fn from_map(
426 props: &'de HashMap<String, GrpcValue>,
427 taken: &[&str],
428 syn_rid: Option<&'de String>,
429 syn_type: Option<&'de String>,
430 ) -> Result<Self, RecordDecodeError>;
431}
432
433/// The clone-based escape hatch for manual [`FromGrpcValue`] types used as
434/// flatten targets: materializes the (taken-filtered) rest as an owned
435/// embedded value and decodes through `FromGrpcValue` — the pre-zero-copy
436/// behavior. Prefer deriving `RecordDecode` for flatten targets. The rest is
437/// OWNED here, so the decode lifetime is independent of the record's.
438pub fn from_map_via_value<T>(
439 props: &HashMap<String, GrpcValue>,
440 taken: &[&str],
441) -> Result<T, RecordDecodeError>
442where
443 T: for<'a> FromGrpcValue<'a>,
444{
445 let rest: HashMap<String, GrpcValue> = props
446 .iter()
447 .filter(|(k, _)| !taken.contains(&k.as_str()))
448 .map(|(k, v)| (k.clone(), v.clone()))
449 .collect();
450 let gv = crate::GrpcValue {
451 kind: Some(Kind::EmbeddedValue(crate::GrpcEmbedded {
452 fields: rest,
453 r#type: String::new(),
454 })),
455 logical_type: String::new(),
456 };
457 T::from_grpc_value(&gv)
458}
459
460// ---------------------------------------------------------------------------
461// Property-access helpers (used by the derive's generated code)
462// ---------------------------------------------------------------------------
463
464/// The value for `key`, unless a parent flatten scope already consumed it
465/// (`taken`). All decode getters consult this — it is what makes flatten
466/// zero-copy: instead of cloning a filtered rest-map, the parent's taken
467/// keys are simply invisible to the flattened child.
468#[doc(hidden)]
469pub fn visible<'a>(
470 props: &'a HashMap<String, GrpcValue>,
471 key: &str,
472 taken: &[&str],
473) -> Option<&'a GrpcValue> {
474 if taken.contains(&key) {
475 None
476 } else {
477 props.get(key)
478 }
479}
480
481/// Decode a required property. Absent property → `MissingField` error.
482pub fn get<'de, T: FromGrpcValue<'de>>(
483 props: &'de HashMap<String, GrpcValue>,
484 taken: &[&str],
485 key: &str,
486) -> Result<T, RecordDecodeError> {
487 match visible(props, key, taken) {
488 Some(v) => T::from_grpc_value(v).map_err(|e| e.with_field(key)),
489 None => Err(RecordDecodeError::missing_field(key)),
490 }
491}
492
493/// Decode an optional property: absent or explicitly null → `None`.
494pub fn get_opt<'de, T: FromGrpcValue<'de>>(
495 props: &'de HashMap<String, GrpcValue>,
496 taken: &[&str],
497 key: &str,
498) -> Result<Option<T>, RecordDecodeError> {
499 match visible(props, key, taken) {
500 Some(v) => Option::<T>::from_grpc_value(v).map_err(|e| e.with_field(key)),
501 None => Ok(None),
502 }
503}
504
505/// Decode a property, falling back to a default-producing closure when absent.
506pub fn get_or<'de, T: FromGrpcValue<'de>, F>(
507 props: &'de HashMap<String, GrpcValue>,
508 taken: &[&str],
509 key: &str,
510 def: F,
511) -> Result<T, RecordDecodeError>
512where
513 F: FnOnce() -> T,
514{
515 match visible(props, key, taken) {
516 Some(v) => T::from_grpc_value(v).map_err(|e| e.with_field(key)),
517 None => Ok(def()),
518 }
519}
520
521/// Decode a required property through a custom conversion function
522/// (`#[record(with = "...")]`).
523pub fn get_with<T>(
524 props: &HashMap<String, GrpcValue>,
525 taken: &[&str],
526 key: &str,
527 f: fn(&GrpcValue) -> Result<T, RecordDecodeError>,
528) -> Result<T, RecordDecodeError> {
529 match visible(props, key, taken) {
530 Some(v) => f(v).map_err(|e| e.with_field(key)),
531 None => Err(RecordDecodeError::missing_field(key)),
532 }
533}
534
535/// Like [`get_with`], but absent property → default-producing closure
536/// (the `#[serde(default)]` + `#[record(with = "...")]` combination). The
537/// custom fn must still tolerate an explicit null if the server sends one.
538pub fn get_with_or<T>(
539 props: &HashMap<String, GrpcValue>,
540 taken: &[&str],
541 key: &str,
542 f: fn(&GrpcValue) -> Result<T, RecordDecodeError>,
543 def: impl FnOnce() -> T,
544) -> Result<T, RecordDecodeError> {
545 match visible(props, key, taken) {
546 Some(v) => f(v).map_err(|e| e.with_field(key)),
547 None => Ok(def()),
548 }
549}
550
551/// Like [`get_with`], but absent or explicitly null → `None`.
552pub fn get_opt_with<T>(
553 props: &HashMap<String, GrpcValue>,
554 taken: &[&str],
555 key: &str,
556 f: fn(&GrpcValue) -> Result<T, RecordDecodeError>,
557) -> Result<Option<T>, RecordDecodeError> {
558 match visible(props, key, taken) {
559 Some(v) => match &v.kind {
560 None => Ok(None),
561 Some(_) => f(v).map(Some).map_err(|e| e.with_field(key)),
562 },
563 None => Ok(None),
564 }
565}
566
567/// Decode a required `Vec<u8>` blob property.
568///
569/// The wire `bytes` kind maps directly to the blob; a list of small integers
570/// also decodes (both were accepted historically).
571/// Emitted by the derive for `Vec<u8>` fields — the generic [`Vec`]
572/// impl in `types` only handles list-typed elements.
573pub fn get_bytes(
574 props: &HashMap<String, GrpcValue>,
575 taken: &[&str],
576 key: &str,
577) -> Result<Vec<u8>, RecordDecodeError> {
578 match visible(props, key, taken) {
579 Some(v) => decode_bytes(v).map_err(|e| e.with_field(key)),
580 None => Err(RecordDecodeError::missing_field(key)),
581 }
582}
583
584/// Decode an optional byte blob: absent or explicitly null → `None`.
585pub fn get_opt_bytes(
586 props: &HashMap<String, GrpcValue>,
587 taken: &[&str],
588 key: &str,
589) -> Result<Option<Vec<u8>>, RecordDecodeError> {
590 match visible(props, key, taken) {
591 Some(v) => match &v.kind {
592 None => Ok(None),
593 Some(_) => decode_bytes(v).map(Some).map_err(|e| e.with_field(key)),
594 },
595 None => Ok(None),
596 }
597}
598
599/// Decode a byte blob, falling back to a default-producing closure when absent.
600pub fn get_bytes_or(
601 props: &HashMap<String, GrpcValue>,
602 taken: &[&str],
603 key: &str,
604 def: impl FnOnce() -> Vec<u8>,
605) -> Result<Vec<u8>, RecordDecodeError> {
606 match visible(props, key, taken) {
607 Some(v) => decode_bytes(v).map_err(|e| e.with_field(key)),
608 None => Ok(def()),
609 }
610}
611
612// ---------------------------------------------------------------------------
613// Typed property access on the record itself
614// ---------------------------------------------------------------------------
615
616impl GrpcRecord {
617 /// Typed single-property decode — the method form of [`get`], for rows
618 /// consumed outside a derived DTO. Borrow-preserving: string/blob views
619 /// (`&str`, `Cow`, `&[u8]`) borrow from this record.
620 ///
621 /// ```ignore
622 /// let n: u64 = rec.get("n")?; // required
623 /// let t: Option<&str> = rec.get_opt("title")?; // absent/null → None
624 /// let b: bool = rec.get_or("flag", false)?; // defaulted
625 /// ```
626 pub fn get<'a, T: FromGrpcValue<'a>>(&'a self, key: &str) -> Result<T, RecordDecodeError> {
627 get(&self.properties, &[], key)
628 }
629
630 /// Typed optional-property decode (absent or null → `Ok(None)`).
631 pub fn get_opt<'a, T: FromGrpcValue<'a>>(
632 &'a self,
633 key: &str,
634 ) -> Result<Option<T>, RecordDecodeError> {
635 get_opt(&self.properties, &[], key)
636 }
637
638 /// Typed decode with a default for the absent case.
639 pub fn get_or<'a, T: FromGrpcValue<'a>>(
640 &'a self,
641 key: &str,
642 default: T,
643 ) -> Result<T, RecordDecodeError> {
644 get_or(&self.properties, &[], key, || default)
645 }
646}
647
648/// Convert a `GrpcValue` into raw bytes: `bytes` kind → the blob; `list` of
649/// small ints → the concatenated ints (matching the legacy deserializer).
650fn decode_bytes(v: &GrpcValue) -> Result<Vec<u8>, RecordDecodeError> {
651 match &v.kind {
652 Some(Kind::BytesValue(b)) => Ok(b.clone()),
653 Some(Kind::ListValue(l)) => {
654 l.values
655 .iter()
656 .map(|item| match &item.kind {
657 Some(Kind::Int32Value(n)) => u8::try_from(*n)
658 .map_err(|_| RecordDecodeError::type_mismatch("u8", "int32")),
659 Some(Kind::Int64Value(n)) => u8::try_from(*n)
660 .map_err(|_| RecordDecodeError::type_mismatch("u8", "int64")),
661 _ => Err(RecordDecodeError::type_mismatch(
662 "u8",
663 kind_name(&item.kind),
664 )),
665 })
666 .collect()
667 }
668 _ => Err(RecordDecodeError::type_mismatch(
669 "bytes",
670 kind_name(&v.kind),
671 )),
672 }
673}