1use crate::error::InvalidError;
2use crate::limits::MAX_NAMESPACE_BYTES;
3use crate::mutation::MutationPosition;
4use serde::{Deserialize, Serialize};
5
6#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
10#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
11pub struct MemoryRowScope {
12 #[serde(default, skip_serializing_if = "Option::is_none")]
14 pub kind: Option<String>,
15 #[serde(default, skip_serializing_if = "Option::is_none")]
17 pub agent: Option<String>,
18 #[serde(default, skip_serializing_if = "Option::is_none")]
20 pub user: Option<String>,
21 #[serde(default, skip_serializing_if = "Option::is_none")]
23 pub app: Option<String>,
24 #[serde(default, skip_serializing_if = "Option::is_none")]
26 pub conversation: Option<String>,
27 #[serde(default, skip_serializing_if = "Option::is_none")]
31 pub source: Option<crate::graph::SourceRef>,
32 #[serde(default, skip_serializing_if = "Option::is_none")]
35 pub timestamp_micros: Option<u64>,
36 #[serde(default, skip_serializing_if = "Option::is_none")]
40 pub weight: Option<f32>,
41}
42
43#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
47#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
48pub struct KvEntry {
49 #[cfg_attr(
50 feature = "schemars",
51 schemars(schema_with = "crate::encoding::bytes_schema")
52 )]
53 #[serde(with = "crate::encoding::bin_bytes")]
54 pub key: Vec<u8>,
55 #[cfg_attr(
56 feature = "schemars",
57 schemars(schema_with = "crate::encoding::bytes_schema")
58 )]
59 #[serde(with = "crate::encoding::bin_bytes")]
60 pub value: Vec<u8>,
61 #[serde(default, skip_serializing_if = "Option::is_none")]
64 pub expires_at_micros: Option<u64>,
65 #[serde(default, skip_serializing_if = "is_zero_u64")]
73 pub version: u64,
74 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub scope: Option<Box<MemoryRowScope>>,
79 #[serde(default, skip_serializing_if = "Option::is_none")]
86 pub source: Option<Box<crate::graph::SourceRef>>,
87}
88
89fn is_zero_u64(value: &u64) -> bool {
90 *value == 0
91}
92
93impl KvEntry {
94 pub fn key_str(&self) -> Option<&str> {
97 std::str::from_utf8(&self.key).ok()
98 }
99}
100
101#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
105#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
106pub struct KvPage {
107 pub items: Vec<KvEntry>,
108 pub page: u32,
109 pub total_pages: u32,
110 pub total_results: u32,
111}
112
113#[derive(Clone, Debug, Serialize, Deserialize)]
127#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
128pub struct KvGet {
129 pub v: u32,
130 pub namespace: String,
131 #[cfg_attr(
132 feature = "schemars",
133 schemars(schema_with = "crate::encoding::bytes_schema")
134 )]
135 #[serde(with = "crate::encoding::bin_bytes")]
136 pub key: Vec<u8>,
137 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub if_none_match: Option<u64>,
139 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub min_position: Option<MutationPosition>,
141}
142
143#[derive(Clone, Debug, Serialize, Deserialize)]
145#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
146pub struct KvSet {
147 pub v: u32,
148 pub namespace: String,
149 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub session: Option<crate::agent::SessionRef>,
151 #[cfg_attr(
152 feature = "schemars",
153 schemars(schema_with = "crate::encoding::bytes_schema")
154 )]
155 #[serde(with = "crate::encoding::bin_bytes")]
156 pub key: Vec<u8>,
157 #[cfg_attr(
158 feature = "schemars",
159 schemars(schema_with = "crate::encoding::bytes_schema")
160 )]
161 #[serde(with = "crate::encoding::bin_bytes")]
162 pub value: Vec<u8>,
163 #[serde(default, skip_serializing_if = "Option::is_none")]
164 pub expires_at_micros: Option<u64>,
165 #[serde(default, skip_serializing_if = "Option::is_none")]
170 pub ttl_micros: Option<u64>,
171}
172
173#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
177#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
178pub enum CasExpect {
179 Match(u64),
181 Absent,
183}
184
185#[derive(Clone, Debug, Serialize, Deserialize)]
190#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
191pub struct KvCas {
192 pub v: u32,
193 pub namespace: String,
194 #[serde(default, skip_serializing_if = "Option::is_none")]
195 pub session: Option<crate::agent::SessionRef>,
196 #[cfg_attr(
197 feature = "schemars",
198 schemars(schema_with = "crate::encoding::bytes_schema")
199 )]
200 #[serde(with = "crate::encoding::bin_bytes")]
201 pub key: Vec<u8>,
202 #[cfg_attr(
203 feature = "schemars",
204 schemars(schema_with = "crate::encoding::bytes_schema")
205 )]
206 #[serde(with = "crate::encoding::bin_bytes")]
207 pub value: Vec<u8>,
208 #[serde(default, skip_serializing_if = "Option::is_none")]
209 pub expires_at_micros: Option<u64>,
210 #[serde(default, skip_serializing_if = "Option::is_none")]
215 pub ttl_micros: Option<u64>,
216 pub expect: CasExpect,
217}
218
219#[derive(Clone, Debug, Serialize, Deserialize)]
228#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
229pub struct KvCasFenced {
230 pub v: u32,
231 pub namespace: String,
232 #[serde(default, skip_serializing_if = "Option::is_none")]
234 pub session: Option<crate::agent::SessionRef>,
235 #[cfg_attr(
236 feature = "schemars",
237 schemars(schema_with = "crate::encoding::bytes_schema")
238 )]
239 #[serde(with = "crate::encoding::bin_bytes")]
240 pub key: Vec<u8>,
241 #[cfg_attr(
242 feature = "schemars",
243 schemars(schema_with = "crate::encoding::bytes_schema")
244 )]
245 #[serde(with = "crate::encoding::bin_bytes")]
246 pub value: Vec<u8>,
247 #[serde(default, skip_serializing_if = "Option::is_none")]
248 pub expires_at_micros: Option<u64>,
249 #[serde(default, skip_serializing_if = "Option::is_none")]
254 pub ttl_micros: Option<u64>,
255 pub expect: CasExpect,
256 pub fence_namespace: String,
260 #[cfg_attr(
262 feature = "schemars",
263 schemars(schema_with = "crate::encoding::bytes_schema")
264 )]
265 #[serde(with = "crate::encoding::bin_bytes")]
266 pub fence_key: Vec<u8>,
267 pub fence_token: u64,
270}
271
272#[derive(Clone, Debug, Serialize, Deserialize)]
276#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
277pub struct KvDelete {
278 pub v: u32,
279 pub namespace: String,
280 #[serde(default, skip_serializing_if = "Option::is_none")]
281 pub session: Option<crate::agent::SessionRef>,
282 #[cfg_attr(
283 feature = "schemars",
284 schemars(schema_with = "crate::encoding::bytes_schema")
285 )]
286 #[serde(with = "crate::encoding::bin_bytes")]
287 pub key: Vec<u8>,
288 #[serde(default, skip_serializing_if = "Option::is_none")]
289 pub if_match: Option<u64>,
290}
291
292#[derive(Clone, Debug, Serialize, Deserialize)]
296#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
297pub struct KvExists {
298 pub v: u32,
299 pub namespace: String,
300 #[cfg_attr(
301 feature = "schemars",
302 schemars(schema_with = "crate::encoding::bytes_schema")
303 )]
304 #[serde(with = "crate::encoding::bin_bytes")]
305 pub key: Vec<u8>,
306}
307
308#[derive(Clone, Debug, Serialize, Deserialize)]
312#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
313pub struct KvExpire {
314 pub v: u32,
315 pub namespace: String,
316 #[cfg_attr(
317 feature = "schemars",
318 schemars(schema_with = "crate::encoding::bytes_schema")
319 )]
320 #[serde(with = "crate::encoding::bin_bytes")]
321 pub key: Vec<u8>,
322 #[serde(default, skip_serializing_if = "Option::is_none")]
323 pub expires_at_micros: Option<u64>,
324 #[serde(default, skip_serializing_if = "Option::is_none")]
329 pub ttl_micros: Option<u64>,
330}
331
332#[derive(Clone, Debug, Serialize, Deserialize)]
337#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
338pub struct KvPatch {
339 pub v: u32,
340 pub namespace: String,
341 #[serde(default, skip_serializing_if = "Option::is_none")]
342 pub session: Option<crate::agent::SessionRef>,
343 #[cfg_attr(
344 feature = "schemars",
345 schemars(schema_with = "crate::encoding::bytes_schema")
346 )]
347 #[serde(with = "crate::encoding::bin_bytes")]
348 pub key: Vec<u8>,
349 #[cfg_attr(
350 feature = "schemars",
351 schemars(schema_with = "crate::encoding::bytes_schema")
352 )]
353 #[serde(with = "crate::encoding::bin_bytes")]
354 pub patch: Vec<u8>,
355 #[serde(default, skip_serializing_if = "Option::is_none")]
356 pub if_match: Option<u64>,
357}
358
359#[derive(Clone, Debug, Serialize, Deserialize)]
364#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
365pub struct KvCopy {
366 pub v: u32,
367 pub namespace: String,
368 #[cfg_attr(
369 feature = "schemars",
370 schemars(schema_with = "crate::encoding::bytes_schema")
371 )]
372 #[serde(with = "crate::encoding::bin_bytes")]
373 pub key: Vec<u8>,
374 #[serde(default, skip_serializing_if = "Option::is_none")]
376 pub to_namespace: Option<String>,
377 #[cfg_attr(
378 feature = "schemars",
379 schemars(schema_with = "crate::encoding::bytes_schema")
380 )]
381 #[serde(with = "crate::encoding::bin_bytes")]
382 pub to_key: Vec<u8>,
383}
384
385#[derive(Clone, Debug, Serialize, Deserialize)]
388#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
389pub struct KvMove {
390 pub v: u32,
391 pub namespace: String,
392 #[cfg_attr(
393 feature = "schemars",
394 schemars(schema_with = "crate::encoding::bytes_schema")
395 )]
396 #[serde(with = "crate::encoding::bin_bytes")]
397 pub key: Vec<u8>,
398 #[serde(default, skip_serializing_if = "Option::is_none")]
400 pub to_namespace: Option<String>,
401 #[cfg_attr(
402 feature = "schemars",
403 schemars(schema_with = "crate::encoding::bytes_schema")
404 )]
405 #[serde(with = "crate::encoding::bin_bytes")]
406 pub to_key: Vec<u8>,
407}
408
409#[derive(Clone, Debug, Serialize, Deserialize)]
416#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
417pub struct KvLease {
418 pub v: u32,
419 pub namespace: String,
420 #[cfg_attr(
421 feature = "schemars",
422 schemars(schema_with = "crate::encoding::bytes_schema")
423 )]
424 #[serde(with = "crate::encoding::bin_bytes")]
425 pub key: Vec<u8>,
426 pub lease_ttl_micros: u64,
433 pub holder_id: String,
438 #[serde(default, skip_serializing_if = "Option::is_none")]
443 pub subject_user_id: Option<u32>,
444}
445
446#[derive(Clone, Debug, Serialize, Deserialize)]
453#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
454pub struct KvLeaseRenew {
455 pub v: u32,
456 pub namespace: String,
457 #[cfg_attr(
458 feature = "schemars",
459 schemars(schema_with = "crate::encoding::bytes_schema")
460 )]
461 #[serde(with = "crate::encoding::bin_bytes")]
462 pub key: Vec<u8>,
463 pub holder_id: String,
464 #[serde(default, skip_serializing_if = "Option::is_none")]
465 pub subject_user_id: Option<u32>,
466 pub lease_token: u64,
467 pub lease_ttl_micros: u64,
472}
473
474#[derive(Clone, Debug, Serialize, Deserialize)]
482#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
483pub struct KvRelease {
484 pub v: u32,
485 pub namespace: String,
486 #[cfg_attr(
487 feature = "schemars",
488 schemars(schema_with = "crate::encoding::bytes_schema")
489 )]
490 #[serde(with = "crate::encoding::bin_bytes")]
491 pub key: Vec<u8>,
492 pub lease_token: u64,
493 pub holder_id: String,
494}
495
496#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
499#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
500pub struct KvMetadata {
501 pub version: u64,
502 #[serde(default, skip_serializing_if = "Option::is_none")]
503 pub expires_at_micros: Option<u64>,
504 pub size_bytes: usize,
505}
506
507#[derive(Clone, Debug, Serialize, Deserialize)]
509#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
510pub struct KvNamespaces {
511 pub v: u32,
512 #[serde(default, skip_serializing_if = "Option::is_none")]
516 pub stream: Option<String>,
517}
518
519#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
521#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
522pub struct KvNamespaceInfo {
523 pub namespace: String,
524 pub entries: usize,
525}
526
527#[derive(Clone, Debug, Serialize, Deserialize)]
533#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
534pub struct KvScan {
535 pub v: u32,
536 pub namespace: String,
537 #[cfg_attr(
538 feature = "schemars",
539 schemars(schema_with = "crate::encoding::opt_bytes_schema")
540 )]
541 #[serde(
542 default,
543 skip_serializing_if = "Option::is_none",
544 with = "crate::encoding::opt_bin_bytes"
545 )]
546 pub prefix: Option<Vec<u8>>,
547 #[cfg_attr(
548 feature = "schemars",
549 schemars(schema_with = "crate::encoding::opt_bytes_schema")
550 )]
551 #[serde(
552 default,
553 skip_serializing_if = "Option::is_none",
554 with = "crate::encoding::opt_bin_bytes"
555 )]
556 pub start: Option<Vec<u8>>,
557 #[cfg_attr(
558 feature = "schemars",
559 schemars(schema_with = "crate::encoding::opt_bytes_schema")
560 )]
561 #[serde(
562 default,
563 skip_serializing_if = "Option::is_none",
564 with = "crate::encoding::opt_bin_bytes"
565 )]
566 pub end: Option<Vec<u8>>,
567 #[serde(default, skip_serializing_if = "Option::is_none")]
568 pub key_contains: Option<String>,
569 #[serde(default, skip_serializing_if = "Option::is_none")]
575 pub conversation: Option<String>,
576 #[serde(default, skip_serializing_if = "Option::is_none")]
580 pub stream: Option<String>,
581 #[serde(default, skip_serializing_if = "Option::is_none")]
586 pub user: Option<String>,
587 #[serde(default, skip_serializing_if = "Option::is_none")]
588 pub agent: Option<String>,
589 #[serde(default, skip_serializing_if = "Option::is_none")]
590 pub app: Option<String>,
591 #[serde(default)]
594 pub page: u32,
595 pub results: u32,
598}
599
600#[derive(Clone, Debug, Serialize, Deserialize)]
605#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
606pub struct KvDeleteMany {
607 pub v: u32,
608 pub namespace: String,
609 #[cfg_attr(
610 feature = "schemars",
611 schemars(schema_with = "crate::encoding::opt_bytes_schema")
612 )]
613 #[serde(
614 default,
615 skip_serializing_if = "Option::is_none",
616 with = "crate::encoding::opt_bin_bytes"
617 )]
618 pub prefix: Option<Vec<u8>>,
619 #[cfg_attr(
620 feature = "schemars",
621 schemars(schema_with = "crate::encoding::opt_bytes_schema")
622 )]
623 #[serde(
624 default,
625 skip_serializing_if = "Option::is_none",
626 with = "crate::encoding::opt_bin_bytes"
627 )]
628 pub start: Option<Vec<u8>>,
629 #[cfg_attr(
630 feature = "schemars",
631 schemars(schema_with = "crate::encoding::opt_bytes_schema")
632 )]
633 #[serde(
634 default,
635 skip_serializing_if = "Option::is_none",
636 with = "crate::encoding::opt_bin_bytes"
637 )]
638 pub end: Option<Vec<u8>>,
639 #[serde(default, skip_serializing_if = "Option::is_none")]
640 pub key_contains: Option<String>,
641 #[serde(default, skip_serializing_if = "Option::is_none")]
644 pub conversation: Option<String>,
645 #[serde(default, skip_serializing_if = "Option::is_none")]
647 pub stream: Option<String>,
648}
649
650#[derive(Clone, Debug, Serialize, Deserialize)]
653#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
654#[non_exhaustive]
655pub enum KvReply {
656 Ok(KvOutcome),
657 Err(KvError),
658}
659
660#[derive(Clone, Debug, Serialize, Deserialize)]
662#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
663#[non_exhaustive]
664pub enum KvOutcome {
665 Value(Option<KvEntry>),
667 Written,
669 Committed { version: u64 },
672 Deleted(bool),
674 DeletedMany(usize),
676 Page(KvPage),
678 Namespaces(Vec<KvNamespaceInfo>),
681 NotModified,
684 Metadata(Option<KvMetadata>),
686 Versioned { version: u64 },
689 Leased {
695 lease_token: u64,
696 granted_ttl_micros: u64,
697 position: MutationPosition,
698 },
699 Renewed {
704 lease_token: u64,
705 granted_ttl_micros: u64,
706 position: MutationPosition,
707 },
708 Released(bool),
711}
712
713#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
715#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
716#[non_exhaustive]
717pub enum KvError {
718 #[error("kv not supported: {0}")]
719 Unsupported(String),
720 #[error("invalid key: {0}")]
721 InvalidKey(String),
722 #[error("invalid namespace: {0}")]
724 InvalidNamespace(String),
725 #[error("{what} is {size}B, exceeds cap {cap}B")]
726 TooLarge {
727 what: String,
728 size: usize,
729 cap: usize,
730 },
731 #[error("kv backend error: {0}")]
732 Backend(String),
733 #[error("temporarily unavailable: {0}")]
738 Unavailable(String),
739 #[error("unsupported kv op version (expected {expected}, got {got})")]
740 Version { expected: u32, got: u32 },
741 #[error("kv version conflict (current: {current:?})")]
745 VersionConflict { current: Option<u64> },
746 #[error("kv lease lost")]
750 LeaseLost,
751 #[error("kv lease held (expires at: {expires_at_micros:?})")]
755 LeaseHeld { expires_at_micros: Option<u64> },
756 #[error("kv read barrier not reached (required: {required:?})")]
760 Stale { required: MutationPosition },
761 #[error("kv read barrier unreachable (required: {required:?})")]
766 BarrierUnreachable { required: MutationPosition },
767 #[error("kv key not found")]
770 NotFound,
771 #[error("not the partition leader for this key")]
774 NotLeader,
775 #[error("kv operation not permitted: {0}")]
778 Forbidden(String),
779 #[error("invalid kv expiry: {0}")]
781 InvalidExpiry(String),
782}
783
784pub fn resolve_expiry(
789 expires_at_micros: Option<u64>,
790 ttl_micros: Option<u64>,
791 now_micros: u64,
792) -> Result<Option<u64>, InvalidError> {
793 match (expires_at_micros, ttl_micros) {
794 (Some(_), Some(_)) => Err(InvalidError::new(
795 "a write names either expires_at_micros or ttl_micros, not both",
796 )),
797 (Some(expires_at_micros), None) => Ok(Some(expires_at_micros)),
798 (None, ttl_micros) => Ok(ttl_micros.map(|ttl| now_micros.saturating_add(ttl))),
799 }
800}
801
802pub fn validate_namespace(namespace: &str) -> Result<(), InvalidError> {
807 if namespace.is_empty() {
808 return Err(InvalidError::new("namespace must not be empty"));
809 }
810 if namespace.len() > MAX_NAMESPACE_BYTES {
811 return Err(InvalidError::new(format!(
812 "namespace is {}B, exceeds cap {MAX_NAMESPACE_BYTES}B",
813 namespace.len()
814 )));
815 }
816 if namespace.bytes().any(|byte| byte.is_ascii_control()) {
817 return Err(InvalidError::new(
818 "namespace must not contain ASCII control characters",
819 ));
820 }
821 Ok(())
822}
823
824#[cfg(all(test, feature = "cbor"))]
825mod tests {
826 use super::*;
827 use crate::codes::KV_OP_VERSION;
828 use crate::framing::{decode_named, encode_named};
829 use crate::result::ResultCode;
830
831 #[test]
832 fn given_a_held_lease_or_an_unreachable_barrier_when_round_tripped_then_should_keep_fields_and_codes()
833 {
834 let required = MutationPosition {
835 topic_generation: 7,
836 partition: 0,
837 offset: 3,
838 };
839 for (error, code) in [
840 (
841 KvError::LeaseHeld {
842 expires_at_micros: Some(1_700_000_000_000_000),
843 },
844 ResultCode::Conflict,
845 ),
846 (
847 KvError::BarrierUnreachable { required },
848 ResultCode::StaleGeneration,
849 ),
850 ] {
851 let bytes = encode_named(&KvReply::Err(error.clone())).expect("serializes");
852 let back: KvReply = decode_named(&bytes).expect("deserializes");
853 assert!(matches!(back, KvReply::Err(ref decoded) if *decoded == error));
854 assert_eq!(ResultCode::from(&error), code);
855 }
856 assert!(
857 !ResultCode::StaleGeneration.is_retryable(),
858 "an unreachable barrier is never retried"
859 );
860 }
861
862 #[test]
863 fn given_an_absolute_expiry_or_a_ttl_when_resolved_then_should_store_one_expiry_and_refuse_both()
864 {
865 assert_eq!(resolve_expiry(Some(9), None, 100), Ok(Some(9)));
866 assert_eq!(
867 resolve_expiry(None, Some(30), 100),
868 Ok(Some(130)),
869 "a TTL counts from the server timestamp of the write"
870 );
871 assert_eq!(resolve_expiry(None, None, 100), Ok(None));
872 assert_eq!(
873 resolve_expiry(None, Some(u64::MAX), 100),
874 Ok(Some(u64::MAX))
875 );
876 assert!(resolve_expiry(Some(9), Some(30), 100).is_err());
877 }
878
879 #[test]
880 fn given_kv_delete_many_when_round_tripped_then_should_preserve_bounds() {
881 let request = KvDeleteMany {
882 v: KV_OP_VERSION,
883 namespace: "sessions".to_owned(),
884 prefix: Some(b"user:".to_vec()),
885 start: None,
886 end: None,
887 key_contains: Some("stale".to_owned()),
888 conversation: None,
889 stream: None,
890 };
891 let bytes = encode_named(&request).expect("serializes");
892 let back: KvDeleteMany = decode_named(&bytes).expect("deserializes");
893 assert_eq!(back.prefix, Some(b"user:".to_vec()));
894 assert_eq!(back.key_contains.as_deref(), Some("stale"));
895 }
896
897 #[test]
898 fn given_kv_deleted_many_reply_when_round_tripped_then_should_preserve_count() {
899 let reply = KvReply::Ok(KvOutcome::DeletedMany(7));
900 let bytes = encode_named(&reply).expect("serializes");
901 let back: KvReply = decode_named(&bytes).expect("deserializes");
902 match back {
903 KvReply::Ok(KvOutcome::DeletedMany(n)) => assert_eq!(n, 7),
904 other => panic!("expected DeletedMany, got {other:?}"),
905 }
906 }
907
908 #[test]
909 fn given_a_set_request_when_round_tripped_then_should_preserve_value_and_expiry() {
910 let request = KvSet {
911 v: KV_OP_VERSION,
912 namespace: "sessions".to_owned(),
913 session: None,
914 key: b"user:42".to_vec(),
915 value: b"online".to_vec(),
916 expires_at_micros: Some(1_700_000_000_000_000),
917 ttl_micros: None,
918 };
919 let bytes = encode_named(&request).expect("the request serializes");
920 let back: KvSet = decode_named(&bytes).expect("the request deserializes");
921 assert_eq!(back.key, b"user:42");
922 assert_eq!(back.value, b"online");
923 assert_eq!(back.expires_at_micros, Some(1_700_000_000_000_000));
924 }
925
926 #[test]
927 fn given_a_binary_key_entry_when_round_tripped_then_should_preserve_raw_bytes() {
928 let reply = KvReply::Ok(KvOutcome::Value(Some(KvEntry {
929 key: vec![0xff, 0x00, 0xfe],
930 value: vec![0x00, 0x01, 0x02],
931 expires_at_micros: None,
932 version: 0,
933 scope: None,
934 source: None,
935 })));
936 let bytes = encode_named(&reply).expect("the reply serializes");
937 let back: KvReply = decode_named(&bytes).expect("the reply deserializes");
938 let KvReply::Ok(KvOutcome::Value(Some(entry))) = back else {
939 panic!("expected an Ok(Value(Some)) reply");
940 };
941 assert_eq!(entry.key, vec![0xff, 0x00, 0xfe]);
942 assert_eq!(entry.key_str(), None, "non-UTF-8 key has no string form");
943 assert_eq!(entry.value, vec![0x00, 0x01, 0x02]);
944 }
945
946 #[test]
947 fn given_a_scan_page_when_round_tripped_then_should_preserve_the_page_and_totals() {
948 let page = KvPage {
949 items: vec![KvEntry {
950 key: b"a".to_vec(),
951 value: b"1".to_vec(),
952 expires_at_micros: None,
953 version: 0,
954 scope: None,
955 source: None,
956 }],
957 page: 2,
958 total_pages: 3,
959 total_results: 21,
960 };
961 let bytes = encode_named(&KvReply::Ok(KvOutcome::Page(page.clone()))).expect("serializes");
962 let back: KvReply = decode_named(&bytes).expect("deserializes");
963 let KvReply::Ok(KvOutcome::Page(decoded)) = back else {
964 panic!("expected an Ok(Page) reply");
965 };
966 assert_eq!(decoded, page);
967 }
968
969 #[test]
970 fn given_a_cas_request_when_round_tripped_then_should_preserve_the_precondition() {
971 for expect in [CasExpect::Match(7), CasExpect::Absent] {
972 let request = KvCas {
973 v: KV_OP_VERSION,
974 namespace: "counters".to_owned(),
975 session: None,
976 key: b"hits".to_vec(),
977 value: b"42".to_vec(),
978 expires_at_micros: None,
979 ttl_micros: None,
980 expect,
981 };
982 let bytes = encode_named(&request).expect("serializes");
983 let back: KvCas = decode_named(&bytes).expect("deserializes");
984 assert_eq!(back.expect, expect);
985 assert_eq!(back.key, b"hits");
986 }
987 }
988
989 #[test]
990 fn given_a_committed_reply_when_round_tripped_then_should_preserve_the_version() {
991 let reply = KvReply::Ok(KvOutcome::Committed { version: 9 });
992 let bytes = encode_named(&reply).expect("serializes");
993 let back: KvReply = decode_named(&bytes).expect("deserializes");
994 match back {
995 KvReply::Ok(KvOutcome::Committed { version }) => assert_eq!(version, 9),
996 other => panic!("expected Committed, got {other:?}"),
997 }
998 }
999
1000 #[test]
1001 fn given_an_exists_metadata_reply_when_round_tripped_then_should_preserve_metadata() {
1002 let reply = KvReply::Ok(KvOutcome::Metadata(Some(KvMetadata {
1003 version: 4,
1004 expires_at_micros: Some(1_700_000_000_000_000),
1005 size_bytes: 128,
1006 })));
1007 let bytes = encode_named(&reply).expect("serializes");
1008 let back: KvReply = decode_named(&bytes).expect("deserializes");
1009 let KvReply::Ok(KvOutcome::Metadata(Some(meta))) = back else {
1010 panic!("expected Ok(Metadata(Some))");
1011 };
1012 assert_eq!(meta.version, 4);
1013 assert_eq!(meta.size_bytes, 128);
1014 }
1015
1016 #[test]
1017 fn given_a_patch_request_when_round_tripped_then_should_preserve_patch_and_precondition() {
1018 let request = KvPatch {
1019 v: KV_OP_VERSION,
1020 namespace: "docs".to_owned(),
1021 session: None,
1022 key: b"doc:1".to_vec(),
1023 patch: br#"{"status":"closed"}"#.to_vec(),
1024 if_match: Some(3),
1025 };
1026 let bytes = encode_named(&request).expect("serializes");
1027 let back: KvPatch = decode_named(&bytes).expect("deserializes");
1028 assert_eq!(back.patch, br#"{"status":"closed"}"#);
1029 assert_eq!(back.if_match, Some(3));
1030 }
1031
1032 #[test]
1033 fn given_a_lease_reply_when_round_tripped_then_should_preserve_token_ttl_and_position() {
1034 let position = MutationPosition {
1035 topic_generation: 3,
1036 partition: 1,
1037 offset: 4_200,
1038 };
1039 for reply in [
1040 KvReply::Ok(KvOutcome::Leased {
1041 lease_token: 77,
1042 granted_ttl_micros: 30_000_000,
1043 position,
1044 }),
1045 KvReply::Ok(KvOutcome::Renewed {
1046 lease_token: 77,
1047 granted_ttl_micros: 30_000_000,
1048 position,
1049 }),
1050 ] {
1051 let bytes = encode_named(&reply).expect("serializes");
1052 let back: KvReply = decode_named(&bytes).expect("deserializes");
1053 match back {
1054 KvReply::Ok(
1055 KvOutcome::Leased {
1056 lease_token,
1057 granted_ttl_micros,
1058 position: got,
1059 }
1060 | KvOutcome::Renewed {
1061 lease_token,
1062 granted_ttl_micros,
1063 position: got,
1064 },
1065 ) => {
1066 assert_eq!(lease_token, 77);
1067 assert_eq!(granted_ttl_micros, 30_000_000);
1068 assert_eq!(got, position);
1069 }
1070 other => panic!("expected Leased or Renewed, got {other:?}"),
1071 }
1072 }
1073 }
1074
1075 #[test]
1076 fn given_a_reshaped_lease_request_when_round_tripped_then_should_preserve_holder_and_subject() {
1077 let request = KvLease {
1078 v: crate::codes::KV_LEASE_OP_VERSION,
1079 namespace: "connectors.coordination".to_owned(),
1080 key: b"source-owner".to_vec(),
1081 lease_ttl_micros: 30_000_000,
1082 holder_id: "node-1".to_owned(),
1083 subject_user_id: Some(42),
1084 };
1085 let bytes = encode_named(&request).expect("serializes");
1086 let back: KvLease = decode_named(&bytes).expect("deserializes");
1087 assert_eq!(back.holder_id, "node-1");
1088 assert_eq!(back.subject_user_id, Some(42));
1089 let own = KvLease {
1091 subject_user_id: None,
1092 ..request
1093 };
1094 let json = serde_json::to_string(&own).expect("json");
1095 assert!(!json.contains("subject_user_id"), "absent subject omitted");
1096 }
1097
1098 #[test]
1099 fn given_a_renew_request_when_round_tripped_then_should_preserve_token_and_holder() {
1100 let request = KvLeaseRenew {
1101 v: crate::codes::KV_LEASE_OP_VERSION,
1102 namespace: "connectors.coordination".to_owned(),
1103 key: b"source-owner".to_vec(),
1104 holder_id: "node-1".to_owned(),
1105 subject_user_id: None,
1106 lease_token: 7,
1107 lease_ttl_micros: 30_000_000,
1108 };
1109 let bytes = encode_named(&request).expect("serializes");
1110 let back: KvLeaseRenew = decode_named(&bytes).expect("deserializes");
1111 assert_eq!(back.lease_token, 7);
1112 assert_eq!(back.holder_id, "node-1");
1113 }
1114
1115 #[test]
1116 fn given_a_pre_fencing_lease_payload_when_decoded_then_should_fail_closed() {
1117 #[derive(Serialize)]
1122 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1123 struct LegacyLease<'a> {
1124 v: u32,
1125 namespace: &'a str,
1126 #[cfg_attr(
1127 feature = "schemars",
1128 schemars(schema_with = "crate::encoding::bytes_schema")
1129 )]
1130 #[serde(with = "crate::encoding::bin_bytes")]
1131 key: &'a [u8],
1132 lease_ttl_micros: u64,
1133 }
1134 let legacy = encode_named(&LegacyLease {
1135 v: KV_OP_VERSION,
1136 namespace: "sessions",
1137 key: b"job",
1138 lease_ttl_micros: 30_000_000,
1139 })
1140 .expect("legacy shape serializes");
1141 assert!(
1142 decode_named::<KvLease>(&legacy).is_err(),
1143 "a holder-less lease payload must not decode"
1144 );
1145
1146 #[derive(Serialize)]
1147 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1148 struct LegacyRelease<'a> {
1149 v: u32,
1150 namespace: &'a str,
1151 #[cfg_attr(
1152 feature = "schemars",
1153 schemars(schema_with = "crate::encoding::bytes_schema")
1154 )]
1155 #[serde(with = "crate::encoding::bin_bytes")]
1156 key: &'a [u8],
1157 lease_token: u64,
1158 }
1159 let legacy = encode_named(&LegacyRelease {
1160 v: KV_OP_VERSION,
1161 namespace: "sessions",
1162 key: b"job",
1163 lease_token: 7,
1164 })
1165 .expect("legacy shape serializes");
1166 assert!(
1167 decode_named::<KvRelease>(&legacy).is_err(),
1168 "a holder-less release payload must not decode"
1169 );
1170
1171 #[derive(Serialize)]
1172 #[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
1173 struct LegacyCasFenced<'a> {
1174 v: u32,
1175 namespace: &'a str,
1176 #[cfg_attr(
1177 feature = "schemars",
1178 schemars(schema_with = "crate::encoding::bytes_schema")
1179 )]
1180 #[serde(with = "crate::encoding::bin_bytes")]
1181 key: &'a [u8],
1182 #[cfg_attr(
1183 feature = "schemars",
1184 schemars(schema_with = "crate::encoding::bytes_schema")
1185 )]
1186 #[serde(with = "crate::encoding::bin_bytes")]
1187 value: &'a [u8],
1188 expect: CasExpect,
1189 #[cfg_attr(
1190 feature = "schemars",
1191 schemars(schema_with = "crate::encoding::bytes_schema")
1192 )]
1193 #[serde(with = "crate::encoding::bin_bytes")]
1194 fence_key: &'a [u8],
1195 fence_token: u64,
1196 }
1197 let legacy = encode_named(&LegacyCasFenced {
1198 v: KV_OP_VERSION,
1199 namespace: "sessions",
1200 key: b"cursor",
1201 value: b"42",
1202 expect: CasExpect::Absent,
1203 fence_key: b"job",
1204 fence_token: 7,
1205 })
1206 .expect("legacy shape serializes");
1207 assert!(
1208 decode_named::<KvCasFenced>(&legacy).is_err(),
1209 "a fence-only CAS payload must not decode"
1210 );
1211 }
1212
1213 #[test]
1214 fn given_a_stale_reply_when_round_tripped_then_should_preserve_the_required_position() {
1215 let required = MutationPosition {
1216 topic_generation: 2,
1217 partition: 0,
1218 offset: 99,
1219 };
1220 let reply = KvReply::Err(KvError::Stale { required });
1221 let bytes = encode_named(&reply).expect("serializes");
1222 let back: KvReply = decode_named(&bytes).expect("deserializes");
1223 match back {
1224 KvReply::Err(KvError::Stale { required: got }) => assert_eq!(got, required),
1225 other => panic!("expected Stale, got {other:?}"),
1226 }
1227 }
1228
1229 #[test]
1230 fn given_a_conditional_get_when_round_tripped_then_should_preserve_if_none_match() {
1231 let request = KvGet {
1232 v: KV_OP_VERSION,
1233 namespace: "sessions".to_owned(),
1234 key: b"user:1".to_vec(),
1235 if_none_match: Some(5),
1236 min_position: None,
1237 };
1238 let bytes = encode_named(&request).expect("serializes");
1239 let back: KvGet = decode_named(&bytes).expect("deserializes");
1240 assert_eq!(back.if_none_match, Some(5));
1241 let plain = KvGet {
1244 if_none_match: None,
1245 ..request
1246 };
1247 let json = serde_json::to_string(&plain).expect("json");
1248 assert!(
1249 !json.contains("if_none_match"),
1250 "absent precondition omitted"
1251 );
1252 assert!(!json.contains("min_position"), "absent barrier omitted");
1253 }
1254
1255 #[test]
1256 fn given_a_barriered_get_when_round_tripped_then_should_preserve_the_minimum_position() {
1257 let request = KvGet {
1258 v: KV_OP_VERSION,
1259 namespace: "connectors.state".to_owned(),
1260 key: b"source_state/pg".to_vec(),
1261 if_none_match: None,
1262 min_position: Some(MutationPosition {
1263 topic_generation: 1,
1264 partition: 0,
1265 offset: 512,
1266 }),
1267 };
1268 let bytes = encode_named(&request).expect("serializes");
1269 let back: KvGet = decode_named(&bytes).expect("deserializes");
1270 assert_eq!(
1271 back.min_position,
1272 Some(MutationPosition {
1273 topic_generation: 1,
1274 partition: 0,
1275 offset: 512,
1276 })
1277 );
1278 }
1279
1280 #[test]
1281 fn given_a_version_conflict_when_round_tripped_then_should_preserve_the_current_version() {
1282 for current in [Some(3u64), None] {
1283 let reply = KvReply::Err(KvError::VersionConflict { current });
1284 let bytes = encode_named(&reply).expect("serializes");
1285 let back: KvReply = decode_named(&bytes).expect("deserializes");
1286 match back {
1287 KvReply::Err(KvError::VersionConflict { current: got }) => assert_eq!(got, current),
1288 other => panic!("expected VersionConflict, got {other:?}"),
1289 }
1290 }
1291 }
1292
1293 #[test]
1294 fn given_a_versioned_entry_when_round_tripped_then_should_preserve_version_and_skip_zero() {
1295 let entry = KvEntry {
1296 key: b"k".to_vec(),
1297 value: b"v".to_vec(),
1298 expires_at_micros: None,
1299 version: 5,
1300 scope: None,
1301 source: None,
1302 };
1303 let bytes = encode_named(&entry).expect("serializes");
1304 let back: KvEntry = decode_named(&bytes).expect("deserializes");
1305 assert_eq!(back.version, 5);
1306 let unversioned = KvEntry {
1309 version: 0,
1310 ..entry
1311 };
1312 let json = serde_json::to_string(&unversioned).expect("json");
1313 assert!(
1314 !json.contains("version"),
1315 "version 0 must be omitted: {json}"
1316 );
1317 }
1318
1319 #[test]
1320 fn given_a_scan_with_bounds_when_round_tripped_then_should_preserve_filters() {
1321 let scan = KvScan {
1322 v: KV_OP_VERSION,
1323 namespace: "sessions".to_owned(),
1324 prefix: Some(b"user:".to_vec()),
1325 start: None,
1326 end: None,
1327 key_contains: Some("admin".to_owned()),
1328 conversation: None,
1329 stream: None,
1330 user: None,
1331 agent: None,
1332 app: None,
1333 page: 3,
1334 results: 50,
1335 };
1336 let bytes = encode_named(&scan).expect("serializes");
1337 let back: KvScan = decode_named(&bytes).expect("deserializes");
1338 assert_eq!(back.prefix.as_deref(), Some(b"user:".as_ref()));
1339 assert_eq!(back.key_contains.as_deref(), Some("admin"));
1340 assert_eq!((back.page, back.results), (3, 50));
1341 assert_eq!(back.stream, None);
1342 }
1343
1344 #[test]
1345 fn given_a_lens_with_a_stream_when_round_tripped_then_should_preserve_it_and_omit_it_when_unset()
1346 {
1347 let scan = KvScan {
1348 v: KV_OP_VERSION,
1349 namespace: "stream:acme/memory".to_owned(),
1350 prefix: None,
1351 start: None,
1352 end: None,
1353 key_contains: None,
1354 conversation: Some("01KWM3K3XEP3NP5TN850J17YBP".to_owned()),
1355 stream: Some("acme".to_owned()),
1356 user: Some("reader".to_owned()),
1357 agent: Some("planner".to_owned()),
1358 app: Some("desk".to_owned()),
1359 page: 0,
1360 results: 10,
1361 };
1362 let back: KvScan =
1363 decode_named(&encode_named(&scan).expect("serializes")).expect("deserializes");
1364 assert_eq!(back.stream.as_deref(), Some("acme"));
1365 assert_eq!(
1366 (
1367 back.user.as_deref(),
1368 back.agent.as_deref(),
1369 back.app.as_deref()
1370 ),
1371 (Some("reader"), Some("planner"), Some("desk"))
1372 );
1373 let delete = KvDeleteMany {
1374 v: KV_OP_VERSION,
1375 namespace: "stream:acme/memory".to_owned(),
1376 prefix: None,
1377 start: None,
1378 end: None,
1379 key_contains: None,
1380 conversation: Some("01KWM3K3XEP3NP5TN850J17YBP".to_owned()),
1381 stream: Some("acme".to_owned()),
1382 };
1383 let back: KvDeleteMany =
1384 decode_named(&encode_named(&delete).expect("serializes")).expect("deserializes");
1385 assert_eq!(back.stream.as_deref(), Some("acme"));
1386 let unset = KvDeleteMany {
1387 stream: None,
1388 ..delete
1389 };
1390 assert!(
1391 !serde_json::to_string(&unset)
1392 .expect("serializes")
1393 .contains("\"stream\":"),
1394 "an unset stream is omitted"
1395 );
1396 }
1397}