Skip to main content

lean_ctx/core/hive/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::core::hive::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    /// Waiting for review; stays pending ("held for review").
46    Held { review_id: Option<String> },
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                review_id: s("review_id"),
117            },
118            Some("refused") => Outcome::Refused {
119                code: s("code").ok_or("refused without code")?,
120                reason: s("reason"),
121                field: s("field"),
122                retry_after_s: r.get("retry_after_s").and_then(Value::as_u64),
123            },
124            other => return Err(format!("push result status {other:?}")),
125        };
126        out.push((id, outcome));
127    }
128    Ok((out, response.get("epoch").and_then(Value::as_u64)))
129}
130
131#[cfg(test)]
132mod tests {
133    use std::path::Path;
134
135    use super::*;
136
137    fn fixture(rel: &str) -> Value {
138        let path = Path::new(env!("CARGO_MANIFEST_DIR"))
139            .join("crates/lean-ctx-protocol/tests/fixtures/hive-v2/routes")
140            .join(rel);
141        serde_json::from_slice(&std::fs::read(path).expect("fixture")).expect("json")
142    }
143
144    #[test]
145    fn the_request_matches_the_contract_shape() {
146        let fx = fixture("events_push.request.json");
147        let c = &fx["capture_counts"];
148        let mut counts = CaptureCounts {
149            gate_version: 1,
150            window_from: c["window_from"].as_i64(),
151            window_to: c["window_to"].as_i64(),
152            considered: 14,
153            captured: 3,
154            ..CaptureCounts::default()
155        };
156        for _ in 0..5 {
157            counts.reject(crate::core::hive::capture::ReasonCode::Duplicate);
158        }
159        for _ in 0..6 {
160            counts.reject(crate::core::hive::capture::ReasonCode::TooShort);
161        }
162        let events = fx["events"].as_array().unwrap().clone();
163        assert_eq!(request(&events, Some(&counts), &[]), fx);
164        let bare = request(&events, None, &[]);
165        assert!(bare.get("capture_counts").is_none());
166
167        let acked = fixture("events_push.purge_acks.request.json");
168        let acks = acked["purge_acks"].as_array().unwrap().clone();
169        let events = acked["events"].as_array().unwrap().clone();
170        assert_eq!(request(&events, None, &acks), acked);
171    }
172
173    #[test]
174    fn every_result_kind_is_read() {
175        let (ok, epoch) = results(&fixture("events_push.response.json")).unwrap();
176        assert_eq!(epoch, Some(0));
177        assert_eq!(ok[0].1, Outcome::Accepted { seq: 9 });
178        assert_eq!(ok[2].1, Outcome::Duplicate { seq: 8 });
179        assert!(ok.iter().all(|(_, o)| o.logged() && o.next().is_none()));
180
181        let (limited, _) = results(&fixture(
182            "events_push.refused.retract_rate_limited.response.json",
183        ))
184        .unwrap();
185        assert_eq!(
186            limited[1].1,
187            Outcome::Refused {
188                code: "retract_rate_limited".into(),
189                reason: None,
190                field: None,
191                retry_after_s: Some(1260)
192            }
193        );
194        assert_eq!(limited[1].1.next(), Some(Next::RetryLater));
195        assert!(limited[2].1.logged(), "the batch continues after a refusal");
196
197        let (invalid, _) =
198            results(&fixture("events_push.refused.target_state.response.json")).unwrap();
199        assert!(invalid.iter().all(|(_, o)| o.next() == Some(Next::Fail)));
200
201        let (held, _) = results(&fixture("events_push.refused.held.response.json")).unwrap();
202        assert!(matches!(&held[0].1, Outcome::Held { review_id: Some(_) }));
203        assert!(!held[0].1.logged());
204
205        let (shape, _) = results(&fixture("events_push.refused.shape.response.json")).unwrap();
206        assert!(shape.iter().any(|(_, o)| matches!(
207            o,
208            Outcome::Refused { reason: Some(r), field: Some(f), .. } if r == "shape" && f.starts_with('/')
209        )));
210        assert!(
211            shape
212                .iter()
213                .all(|(_, o)| o.logged() || o.next() == Some(Next::Fail))
214        );
215
216        let skew = Outcome::Refused {
217            code: "hlc_skew".into(),
218            reason: None,
219            field: None,
220            retry_after_s: None,
221        };
222        assert_eq!(skew.next(), Some(Next::Restamp));
223    }
224}