Skip to main content

lean_ctx_cloud/sync/
push.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Pushing own events to a place (E5 `POST /v1/places/{p}/events`,
3//! SPEC-ENGINE ยง3.4.4, C0 2.0 `push_request` / `push_response`).
4//!
5//! A batch is not atomic: the server decides every event on its own. The
6//! engine keeps an event pending until the tail delivers it (the server log
7//! is the only source of truth); what a push answers only decides whether
8//! the event is sent again, waits, or moves to the failed queue.
9
10use serde_json::{Value, json};
11
12use crate::capture::CaptureCounts;
13
14/// Events per push.
15pub const MAX_BATCH: usize = 200;
16
17/// The E5 request body. Counts go along only with a complete window.
18pub fn request(events: &[Value], counts: Option<&CaptureCounts>, purge_acks: &[Value]) -> Value {
19    let mut body = json!({ "events": events });
20    if !purge_acks.is_empty() {
21        body["purge_acks"] = Value::Array(purge_acks.to_vec());
22    }
23    if let Some(c) = counts
24        && let (Some(from), Some(to)) = (c.window_from, c.window_to)
25    {
26        body["capture_counts"] = json!({
27            "gate_version": c.gate_version,
28            "window_from": from,
29            "window_to": to,
30            "considered": c.considered,
31            "captured": c.captured,
32            "rejected": c.rejected,
33        });
34    }
35    body
36}
37
38/// What the server decided for one pushed event.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub enum Outcome {
41    /// In the log at `seq`; the tail will deliver it.
42    Accepted { seq: u64 },
43    /// Already in the log (an earlier push got through).
44    Duplicate { seq: u64 },
45    /// Held by the place (e.g. over its retraction limit); stays pending.
46    Held,
47    /// Not taken; what the engine does next is [`Next`].
48    Refused {
49        code: String,
50        reason: Option<String>,
51        /// JSON Pointer of the first failing member (`invalid_event` with
52        /// reason `shape`), e.g. `/body/statement`.
53        field: Option<String>,
54        retry_after_s: Option<u64>,
55    },
56}
57
58/// What the engine does with a refused event.
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum Next {
61    /// Stamp the HLC again and push once more (`hlc_skew`).
62    Restamp,
63    /// Keep it queued and retry after the server's delay.
64    RetryLater,
65    /// Move it to `outbox/failed/events`; nothing retries it.
66    Fail,
67}
68
69impl Outcome {
70    /// Whether the event is in the server log now.
71    pub fn logged(&self) -> bool {
72        matches!(self, Self::Accepted { .. } | Self::Duplicate { .. })
73    }
74
75    pub fn next(&self) -> Option<Next> {
76        let Self::Refused { code, .. } = self else {
77            return None;
78        };
79        Some(match code.as_str() {
80            "hlc_skew" => Next::Restamp,
81            "rate_limited"
82            | "retract_rate_limited"
83            | "keystore_unavailable"
84            | "segment_unavailable"
85            | "vault_migrating"
86            | "conversion_pending" => Next::RetryLater,
87            _ => Next::Fail,
88        })
89    }
90}
91
92/// The per-event results of an E5 response, by event id, and the place
93/// epoch it reports.
94pub fn results(response: &Value) -> Result<(Vec<(String, Outcome)>, Option<u64>), String> {
95    let list = response
96        .get("results")
97        .and_then(Value::as_array)
98        .ok_or("push response without results")?;
99    let mut out = Vec::with_capacity(list.len());
100    for r in list {
101        let id = r
102            .get("event_id")
103            .and_then(Value::as_str)
104            .ok_or("push result without event_id")?
105            .to_string();
106        let seq = r.get("seq").and_then(Value::as_u64);
107        let s = |k: &str| r.get(k).and_then(Value::as_str).map(str::to_string);
108        let outcome = match r.get("status").and_then(Value::as_str) {
109            Some("accepted") => Outcome::Accepted {
110                seq: seq.ok_or("accepted without seq")?,
111            },
112            Some("duplicate") => Outcome::Duplicate {
113                seq: seq.ok_or("duplicate without seq")?,
114            },
115            Some("held") => Outcome::Held,
116            Some("refused") => Outcome::Refused {
117                code: s("code").ok_or("refused without code")?,
118                reason: s("reason"),
119                field: s("field"),
120                retry_after_s: r.get("retry_after_s").and_then(Value::as_u64),
121            },
122            other => return Err(format!("push result status {other:?}")),
123        };
124        out.push((id, outcome));
125    }
126    Ok((out, response.get("epoch").and_then(Value::as_u64)))
127}
128
129#[cfg(test)]
130mod tests {
131    use std::path::Path;
132
133    use super::*;
134
135    fn fixture(rel: &str) -> Value {
136        let path = Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
137            .join("crates/lean-ctx-protocol/tests/fixtures/cloud-v2/routes")
138            .join(rel);
139        serde_json::from_slice(&std::fs::read(path).expect("fixture")).expect("json")
140    }
141
142    #[test]
143    fn the_request_matches_the_contract_shape() {
144        let fx = fixture("events_push.request.json");
145        let c = &fx["capture_counts"];
146        let mut counts = CaptureCounts {
147            gate_version: 1,
148            window_from: c["window_from"].as_i64(),
149            window_to: c["window_to"].as_i64(),
150            considered: 14,
151            captured: 3,
152            ..CaptureCounts::default()
153        };
154        for _ in 0..5 {
155            counts.reject(crate::capture::ReasonCode::Duplicate);
156        }
157        for _ in 0..6 {
158            counts.reject(crate::capture::ReasonCode::TooShort);
159        }
160        let events = fx["events"].as_array().unwrap().clone();
161        assert_eq!(request(&events, Some(&counts), &[]), fx);
162        let bare = request(&events, None, &[]);
163        assert!(bare.get("capture_counts").is_none());
164
165        let acked = fixture("events_push.purge_acks.request.json");
166        let acks = acked["purge_acks"].as_array().unwrap().clone();
167        let events = acked["events"].as_array().unwrap().clone();
168        assert_eq!(request(&events, None, &acks), acked);
169    }
170
171    #[test]
172    fn every_result_kind_is_read() {
173        let (ok, epoch) = results(&fixture("events_push.response.json")).unwrap();
174        assert_eq!(epoch, Some(0));
175        assert_eq!(ok[0].1, Outcome::Accepted { seq: 9 });
176        assert_eq!(ok[2].1, Outcome::Duplicate { seq: 8 });
177        assert!(ok.iter().all(|(_, o)| o.logged() && o.next().is_none()));
178
179        let (limited, _) = results(&fixture(
180            "events_push.refused.retract_rate_limited.response.json",
181        ))
182        .unwrap();
183        assert_eq!(
184            limited[1].1,
185            Outcome::Refused {
186                code: "retract_rate_limited".into(),
187                reason: None,
188                field: None,
189                retry_after_s: Some(1260)
190            }
191        );
192        assert_eq!(limited[1].1.next(), Some(Next::RetryLater));
193        assert!(limited[2].1.logged(), "the batch continues after a refusal");
194
195        let (invalid, _) =
196            results(&fixture("events_push.refused.target_state.response.json")).unwrap();
197        assert!(invalid.iter().all(|(_, o)| o.next() == Some(Next::Fail)));
198
199        let (held, _) = results(&fixture("events_push.refused.held.response.json")).unwrap();
200        assert!(matches!(&held[0].1, Outcome::Held));
201        assert!(!held[0].1.logged());
202
203        let (shape, _) = results(&fixture("events_push.refused.shape.response.json")).unwrap();
204        assert!(shape.iter().any(|(_, o)| matches!(
205            o,
206            Outcome::Refused { reason: Some(r), field: Some(f), .. } if r == "shape" && f.starts_with('/')
207        )));
208        assert!(
209            shape
210                .iter()
211                .all(|(_, o)| o.logged() || o.next() == Some(Next::Fail))
212        );
213
214        let skew = Outcome::Refused {
215            code: "hlc_skew".into(),
216            reason: None,
217            field: None,
218            retry_after_s: None,
219        };
220        assert_eq!(skew.next(), Some(Next::Restamp));
221    }
222}