Skip to main content

edgestore_repl/
http_client.rs

1//! HTTP replication client implementing `ReplicationProtocol`.
2//!
3//! Uses MessagePack (rmp-serde) for control messages and raw bytes for segment transfer.
4//! All network errors are mapped to `EdgestoreError::ReplicationError`.
5
6use std::io::Read;
7
8use edgestore::replication::{ReplicationProtocol, SegmentRef};
9use edgestore::{EdgestoreError, WatermarkResponse};
10
11use crate::wire::{hash_to_hex, MerkleResponse, SegmentEntry};
12
13/// HTTP replication client that implements `ReplicationProtocol` against an `HttpReplicationServer`.
14///
15/// Uses MessagePack (rmp-serde) for control messages and raw bytes for segment transfer.
16pub struct HttpReplicationClient {
17    base_url: String,
18}
19
20impl HttpReplicationClient {
21    /// Create a new client pointing at `base_url` (e.g. `"http://127.0.0.1:8900"`).
22    pub fn new(base_url: impl Into<String>) -> Self {
23        HttpReplicationClient {
24            base_url: base_url.into(),
25        }
26    }
27}
28
29impl ReplicationProtocol for HttpReplicationClient {
30    /// Fetch the remote peer's current Merkle root.
31    ///
32    /// Calls `GET {base_url}/merkle`, deserializes MessagePack body as `{root: Vec<u8>}`,
33    /// and converts to `[u8; 32]`.
34    fn merkle_root(&self) -> Result<[u8; 32], EdgestoreError> {
35        let url = format!("{}/merkle", self.base_url);
36        let response = ureq::get(&url)
37            .call()
38            .map_err(|e| EdgestoreError::ReplicationError(format!("GET /merkle: {}", e)))?;
39
40        let resp: MerkleResponse = rmp_serde::from_read(response.into_reader())
41            .map_err(|e| EdgestoreError::ReplicationError(format!("GET /merkle decode: {}", e)))?;
42
43        if resp.root.len() != 32 {
44            return Err(EdgestoreError::ReplicationError(format!(
45                "GET /merkle: expected 32-byte root, got {} bytes",
46                resp.root.len()
47            )));
48        }
49
50        let mut hash = [0u8; 32];
51        hash.copy_from_slice(&resp.root);
52        Ok(hash)
53    }
54
55    /// Fetch the remote peer's full segment manifest.
56    ///
57    /// Calls `GET {base_url}/segments`, deserializes MessagePack as a list of segment entries,
58    /// and converts each to `SegmentRef`.
59    fn list_segments(&self) -> Result<Vec<SegmentRef>, EdgestoreError> {
60        let url = format!("{}/segments", self.base_url);
61        let response = ureq::get(&url)
62            .call()
63            .map_err(|e| EdgestoreError::ReplicationError(format!("GET /segments: {}", e)))?;
64
65        let entries: Vec<SegmentEntry> =
66            rmp_serde::from_read(response.into_reader()).map_err(|e| {
67                EdgestoreError::ReplicationError(format!("GET /segments decode: {}", e))
68            })?;
69
70        let refs = entries
71            .into_iter()
72            .map(|e| {
73                let mut hash = [0u8; 32];
74                let copy_len = e.segment_hash.len().min(32);
75                hash[..copy_len].copy_from_slice(&e.segment_hash[..copy_len]);
76                SegmentRef {
77                    segment_hash: hash,
78                    segment_id: e.segment_id,
79                }
80            })
81            .collect();
82
83        Ok(refs)
84    }
85
86    /// Fetch the primary's commit watermark.
87    ///
88    /// Calls `GET {base_url}/watermark`, deserializes MessagePack as
89    /// `{confirmed_lsn, wtoken}`.  Used by `AntiEntropyLoop` to detect
90    /// primary failovers when `wtoken` increases.
91    fn watermark(&self) -> Result<WatermarkResponse, EdgestoreError> {
92        let url = format!("{}/watermark", self.base_url);
93        let response = ureq::get(&url)
94            .call()
95            .map_err(|e| EdgestoreError::ReplicationError(format!("GET /watermark: {e}")))?;
96        rmp_serde::from_read(response.into_reader())
97            .map_err(|e| EdgestoreError::ReplicationError(format!("GET /watermark decode: {e}")))
98    }
99
100    /// Fetch one segment's raw bytes by content hash.
101    ///
102    /// Calls `GET {base_url}/segments/{hash_hex}`, reads raw bytes from body.
103    /// Caller MUST verify BLAKE3 before applying.
104    fn fetch_segment(&self, hash: &[u8; 32]) -> Result<Vec<u8>, EdgestoreError> {
105        let hash_hex = hash_to_hex(hash);
106        let url = format!("{}/segments/{}", self.base_url, hash_hex);
107
108        let response = ureq::get(&url).call().map_err(|e| {
109            EdgestoreError::ReplicationError(format!("GET /segments/{}: {}", hash_hex, e))
110        })?;
111
112        let mut data = Vec::new();
113        response.into_reader().read_to_end(&mut data).map_err(|e| {
114            EdgestoreError::ReplicationError(format!("GET /segments/{} read body: {}", hash_hex, e))
115        })?;
116
117        Ok(data)
118    }
119}