1use serde::{Deserialize, Serialize};
2
3pub const MANAGED_REQUEST_VERSION: u32 = 1;
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
13#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
14pub struct MutationPosition {
15 pub topic_generation: u64,
16 pub partition: u32,
17 pub offset: u64,
18}
19
20#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
21#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
22pub struct ManagedRequestEnvelope {
23 pub v: u32,
24 pub operation_id: u128,
25 #[cfg_attr(
26 feature = "schemars",
27 schemars(schema_with = "crate::encoding::bytes_schema")
28 )]
29 #[serde(with = "crate::encoding::bin_bytes")]
30 pub payload: Vec<u8>,
31}
32
33impl ManagedRequestEnvelope {
34 pub fn validate(&self) -> Result<(), &'static str> {
35 if self.v != MANAGED_REQUEST_VERSION {
36 return Err("unsupported managed request version");
37 }
38 if self.operation_id == 0 {
39 return Err("managed request operation id must not be zero");
40 }
41 Ok(())
42 }
43}
44
45#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
47#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
48#[serde(rename_all = "snake_case")]
49pub enum PositionSurface {
50 Kv,
51 Fork,
52 Graph,
53}
54
55impl PositionSurface {
56 pub const fn of_code(code: u32) -> Option<Self> {
59 use crate::codes::{
60 AGDX_FORK_CREATE_CODE, AGDX_FORK_DELETE_CODE, AGDX_FORK_LIST_CODE,
61 AGDX_FORK_PROMOTE_CODE, AGDX_FORK_PUT_CODE, AGDX_GRAPH_NEIGHBORS_CODE,
62 AGDX_GRAPH_QUERY_CODE, AGDX_GRAPH_UPSERT_CODE, AGDX_KV_CAS_CODE,
63 AGDX_KV_CAS_FENCED_CODE, AGDX_KV_COPY_CODE, AGDX_KV_DELETE_CODE,
64 AGDX_KV_DELETE_MANY_CODE, AGDX_KV_EXISTS_CODE, AGDX_KV_EXPIRE_CODE, AGDX_KV_GET_CODE,
65 AGDX_KV_LEASE_CODE, AGDX_KV_LEASE_RENEW_CODE, AGDX_KV_MOVE_CODE,
66 AGDX_KV_NAMESPACES_CODE, AGDX_KV_PATCH_CODE, AGDX_KV_RELEASE_CODE, AGDX_KV_SCAN_CODE,
67 AGDX_KV_SET_CODE,
68 };
69 match code {
70 AGDX_KV_GET_CODE
71 | AGDX_KV_SCAN_CODE
72 | AGDX_KV_NAMESPACES_CODE
73 | AGDX_KV_EXISTS_CODE
74 | AGDX_KV_SET_CODE
75 | AGDX_KV_CAS_CODE
76 | AGDX_KV_DELETE_CODE
77 | AGDX_KV_DELETE_MANY_CODE
78 | AGDX_KV_EXPIRE_CODE
79 | AGDX_KV_PATCH_CODE
80 | AGDX_KV_COPY_CODE
81 | AGDX_KV_MOVE_CODE
82 | AGDX_KV_CAS_FENCED_CODE
83 | AGDX_KV_LEASE_CODE
84 | AGDX_KV_LEASE_RENEW_CODE
85 | AGDX_KV_RELEASE_CODE => Some(Self::Kv),
86 AGDX_FORK_LIST_CODE
87 | AGDX_FORK_CREATE_CODE
88 | AGDX_FORK_DELETE_CODE
89 | AGDX_FORK_PROMOTE_CODE
90 | AGDX_FORK_PUT_CODE => Some(Self::Fork),
91 AGDX_GRAPH_QUERY_CODE | AGDX_GRAPH_NEIGHBORS_CODE | AGDX_GRAPH_UPSERT_CODE => {
92 Some(Self::Graph)
93 }
94 _ => None,
95 }
96 }
97}
98
99#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
113#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
114#[serde(deny_unknown_fields)]
115pub struct ManagedReadEnvelope {
116 pub v: u32,
117 #[cfg_attr(
119 feature = "schemars",
120 schemars(schema_with = "crate::encoding::bytes_schema")
121 )]
122 #[serde(with = "crate::encoding::bin_bytes")]
123 pub read: Vec<u8>,
124 #[serde(default, skip_serializing_if = "Option::is_none")]
125 pub min_position: Option<MutationPosition>,
126 #[serde(default, skip_serializing_if = "is_false")]
127 pub log_head: bool,
128 #[serde(default, skip_serializing_if = "Vec::is_empty")]
132 pub min_sessions: Vec<SessionPosition>,
133}
134
135#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
138#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
139#[serde(deny_unknown_fields)]
140pub struct SessionPosition {
141 pub stream_id: u32,
142 pub stream_generation: u64,
144 pub topic: String,
145 pub topic_generation: u64,
147 pub partition_id: u32,
148 pub offset: u64,
150}
151
152#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
156#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
157#[serde(deny_unknown_fields)]
158pub struct AppliedFrontier {
159 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub kv: Option<MutationPosition>,
161 #[serde(default, skip_serializing_if = "Option::is_none")]
162 pub fork: Option<MutationPosition>,
163 #[serde(default, skip_serializing_if = "Option::is_none")]
164 pub graph: Option<MutationPosition>,
165 #[serde(default, skip_serializing_if = "Vec::is_empty")]
166 pub sessions: Vec<SessionPosition>,
167}
168
169#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
177#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
178#[serde(deny_unknown_fields)]
179pub struct ManagedReplyEnvelope {
180 pub v: u32,
181 #[serde(default)]
182 pub frontier: AppliedFrontier,
183 #[cfg_attr(
184 feature = "schemars",
185 schemars(schema_with = "crate::encoding::bytes_schema")
186 )]
187 #[serde(with = "crate::encoding::bin_bytes")]
188 pub reply: Vec<u8>,
189}
190
191#[expect(clippy::trivially_copy_pass_by_ref, reason = "serde skip predicate")]
192fn is_false(value: &bool) -> bool {
193 !*value
194}
195
196#[derive(Clone, Debug, Serialize, Deserialize)]
201#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
202pub struct MutationCommandEnvelope {
203 pub v: u32,
204 pub operation_id: u128,
205 pub deployment_id: u64,
206 pub timestamp_micros: u64,
207 pub command_code: u32,
208 #[serde(default, skip_serializing_if = "Option::is_none")]
210 pub scope: Option<crate::forward::ForwardedScope>,
211 #[cfg_attr(
212 feature = "schemars",
213 schemars(schema_with = "crate::encoding::bytes_schema")
214 )]
215 #[serde(with = "crate::encoding::bin_bytes")]
216 pub payload: Vec<u8>,
217 #[serde(default, skip_serializing_if = "Option::is_none")]
221 pub caller: Option<crate::forward::Caller>,
222}
223
224impl MutationCommandEnvelope {
225 pub fn validate(&self) -> Result<(), &'static str> {
226 if self.v == 0 {
227 return Err("mutation command version must not be zero");
228 }
229 if self.operation_id == 0 {
230 return Err("mutation command operation id must not be zero");
231 }
232 Ok(())
233 }
234}
235
236#[cfg(all(test, feature = "cbor"))]
237mod tests {
238 use super::*;
239 use crate::codes::{AGDX_KV_SET_CODE, KV_OP_VERSION};
240 use crate::framing::{decode_named, encode_named};
241
242 #[test]
243 fn given_a_read_envelope_when_round_tripped_then_should_keep_the_inner_read() {
244 let get = crate::kv::KvGet {
245 v: KV_OP_VERSION,
246 namespace: "orders".to_owned(),
247 key: b"k".to_vec(),
248 if_none_match: None,
249 min_position: None,
250 };
251 let read = encode_named(&get).expect("encodes");
252 let envelope = ManagedReadEnvelope {
253 v: MANAGED_REQUEST_VERSION,
254 read: read.clone(),
255 min_position: Some(MutationPosition {
256 topic_generation: 3,
257 partition: 0,
258 offset: 41,
259 }),
260 log_head: true,
261 min_sessions: vec![SessionPosition {
262 stream_id: 2,
263 stream_generation: 10,
264 topic: "agent.sessions".to_owned(),
265 topic_generation: 11,
266 partition_id: 1,
267 offset: 7,
268 }],
269 };
270 let decoded: ManagedReadEnvelope =
271 decode_named(&encode_named(&envelope).expect("encodes")).expect("decodes");
272 assert_eq!(decoded, envelope);
273 assert!(decode_named::<ManagedReadEnvelope>(&read).is_err());
276 let managed = encode_named(&ManagedRequestEnvelope {
277 v: MANAGED_REQUEST_VERSION,
278 operation_id: 9,
279 payload: read,
280 })
281 .expect("encodes");
282 assert!(decode_named::<ManagedReadEnvelope>(&managed).is_err());
283 }
284
285 #[test]
286 fn given_a_reply_envelope_when_round_tripped_then_should_keep_the_reply_and_refuse_plain_replies()
287 {
288 let reply =
289 encode_named(&crate::kv::KvReply::Ok(crate::kv::KvOutcome::Written)).expect("encodes");
290 let envelope = ManagedReplyEnvelope {
291 v: MANAGED_REQUEST_VERSION,
292 frontier: AppliedFrontier {
293 kv: Some(MutationPosition {
294 topic_generation: 1,
295 partition: 0,
296 offset: 7,
297 }),
298 fork: None,
299 graph: None,
300 sessions: Vec::new(),
301 },
302 reply: reply.clone(),
303 };
304 let decoded: ManagedReplyEnvelope =
305 decode_named(&encode_named(&envelope).expect("encodes")).expect("decodes");
306 assert_eq!(decoded, envelope);
307 assert!(decode_named::<ManagedReplyEnvelope>(&reply).is_err());
308 let refusal = encode_named(&crate::result::CommandError::new(
309 crate::result::ResultCode::Stale,
310 "behind",
311 ))
312 .expect("encodes");
313 assert!(decode_named::<ManagedReplyEnvelope>(&refusal).is_err());
314 }
315
316 #[test]
317 fn given_command_codes_when_classified_then_should_name_their_surface() {
318 use crate::codes::{
319 AGDX_FORK_LIST_CODE, AGDX_GRAPH_UPSERT_CODE, AGDX_KV_LEASE_CODE, AGDX_QUERY_CODE,
320 AGDX_SESSION_GET_CODE,
321 };
322 assert_eq!(
323 PositionSurface::of_code(AGDX_KV_LEASE_CODE),
324 Some(PositionSurface::Kv)
325 );
326 assert_eq!(
327 PositionSurface::of_code(AGDX_FORK_LIST_CODE),
328 Some(PositionSurface::Fork)
329 );
330 assert_eq!(
331 PositionSurface::of_code(AGDX_GRAPH_UPSERT_CODE),
332 Some(PositionSurface::Graph)
333 );
334 assert_eq!(PositionSurface::of_code(AGDX_SESSION_GET_CODE), None);
335 assert_eq!(PositionSurface::of_code(AGDX_QUERY_CODE), None);
336 }
337
338 #[test]
339 fn given_a_command_envelope_when_round_tripped_then_should_preserve_request_bytes() {
340 let envelope = MutationCommandEnvelope {
341 v: KV_OP_VERSION,
342 operation_id: 42,
343 deployment_id: 3,
344 timestamp_micros: 1_700_000_000_000_000,
345 command_code: AGDX_KV_SET_CODE,
346 scope: None,
347 payload: vec![0, 1, 2, 255],
348 caller: Some(crate::forward::Caller {
349 user_id: 7,
350 agent: None,
351 on_behalf_of: None,
352 }),
353 };
354 let bytes = encode_named(&envelope).expect("encodes");
355 let back: MutationCommandEnvelope = decode_named(&bytes).expect("decodes");
356 back.validate().expect("the envelope is valid");
357 assert_eq!(back.v, KV_OP_VERSION);
358 assert_eq!(back.operation_id, 42);
359 assert_eq!(back.caller.map(|caller| caller.user_id), Some(7));
360 assert_eq!(back.deployment_id, 3);
361 assert_eq!(back.timestamp_micros, 1_700_000_000_000_000);
362 assert_eq!(back.command_code, AGDX_KV_SET_CODE);
363 assert_eq!(back.payload, vec![0, 1, 2, 255]);
364 }
365
366 #[test]
367 fn given_a_managed_request_when_round_tripped_then_should_preserve_operation_identity() {
368 let request = ManagedRequestEnvelope {
369 v: MANAGED_REQUEST_VERSION,
370 operation_id: u128::MAX,
371 payload: vec![4, 3, 2, 1],
372 };
373
374 let bytes = encode_named(&request).expect("managed request encodes");
375 let back: ManagedRequestEnvelope = decode_named(&bytes).expect("managed request decodes");
376
377 assert_eq!(back, request);
378 back.validate().expect("the request is valid");
379 }
380
381 #[test]
382 fn given_a_zero_operation_identity_when_validated_then_should_reject_it() {
383 let request = ManagedRequestEnvelope {
384 v: MANAGED_REQUEST_VERSION,
385 operation_id: 0,
386 payload: Vec::new(),
387 };
388 let command = MutationCommandEnvelope {
389 v: KV_OP_VERSION,
390 operation_id: 0,
391 timestamp_micros: 1,
392 deployment_id: 3,
393 command_code: AGDX_KV_SET_CODE,
394 scope: None,
395 payload: Vec::new(),
396 caller: None,
397 };
398
399 assert!(request.validate().is_err());
400 assert!(command.validate().is_err());
401 }
402}