1mod maintenance;
4
5use super::{
6 cluster::{validate_keys, AtomicJournalStore, JournalVersion},
7 error,
8};
9use crate::LinkError;
10use base64::{engine::general_purpose::STANDARD, Engine as _};
11use serde_json::{json, Value};
12use std::{io::Read, time::Duration};
13
14fn generation(value: &str) -> Option<u64> {
15 if value.is_empty()
16 || value.starts_with('0')
17 || !value.bytes().all(|byte| byte.is_ascii_digit())
18 {
19 return None;
20 }
21 value
22 .parse()
23 .ok()
24 .filter(|number| *number <= i64::MAX as u64)
25}
26
27pub struct EtcdJournalStore {
28 endpoints: Vec<String>,
29 prefix: String,
30 agent: ureq::Agent,
31 cursor: usize,
32 pub headers: Vec<(String, String)>,
33 pub max_request_bytes: usize,
34 pub max_response_bytes: usize,
35}
36impl EtcdJournalStore {
37 pub fn new(endpoints: Vec<String>, prefix: String) -> Result<Self, LinkError> {
38 let agent = ureq::Agent::config_builder()
39 .timeout_global(Some(Duration::from_secs(10)))
40 .max_redirects(0)
41 .build()
42 .into();
43 Self::with_agent(endpoints, prefix, agent)
44 }
45 pub fn with_agent(
47 endpoints: Vec<String>,
48 prefix: String,
49 agent: ureq::Agent,
50 ) -> Result<Self, LinkError> {
51 if endpoints.is_empty() || prefix.len() < 2 || !prefix.ends_with('/') {
52 return Err(error("provide endpoints and a nonempty prefix ending in /"));
53 }
54 for endpoint in &endpoints {
55 let uri = endpoint
56 .parse::<ureq::http::Uri>()
57 .map_err(|_| error("invalid etcd endpoint"))?;
58 if !matches!(uri.scheme_str(), Some("http" | "https"))
59 || uri.authority().is_none()
60 || uri.query().is_some()
61 {
62 return Err(error("etcd endpoints must be HTTP(S) URLs"));
63 }
64 }
65 Ok(Self {
66 endpoints: endpoints
67 .into_iter()
68 .map(|url| url.trim_end_matches('/').into())
69 .collect(),
70 prefix,
71 agent,
72 cursor: 0,
73 headers: Vec::new(),
74 max_request_bytes: 1_048_576,
75 max_response_bytes: 8_388_608,
76 })
77 }
78 fn key(&self, key: &str) -> String {
79 STANDARD.encode(format!("{}{key}", self.prefix))
80 }
81 fn post(&self, body: Value) -> Result<Value, LinkError> {
82 let body = serde_json::to_vec(&body).map_err(|cause| error(&cause.to_string()))?;
83 if body.len() > self.max_request_bytes {
84 return Err(error("coordinator request exceeds byte limit"));
85 }
86 let mut request = self
87 .agent
88 .post(format!("{}/v3/kv/txn", self.endpoints[self.cursor]))
89 .header("Content-Type", "application/json");
90 for (name, value) in &self.headers {
91 request = request.header(name.as_str(), value.as_str());
92 }
93 let mut response = request
94 .send(body)
95 .map_err(|cause| error(&format!("coordinator request failed: {cause}")))?;
96 let mut bytes = Vec::new();
97 response
98 .body_mut()
99 .as_reader()
100 .take(self.max_response_bytes.saturating_add(1) as u64)
101 .read_to_end(&mut bytes)
102 .map_err(|cause| error(&format!("coordinator response failed: {cause}")))?;
103 if bytes.len() > self.max_response_bytes {
104 return Err(error("coordinator response exceeds byte limit"));
105 }
106 serde_json::from_slice(&bytes)
107 .map_err(|cause| error(&format!("invalid coordinator response: {cause}")))
108 }
109 fn read_once(&self, keys: &[String]) -> Result<Vec<JournalVersion>, LinkError> {
110 let result = self.post(json!({ "success": keys.iter().map(|key| json!({ "request_range": { "key": self.key(key) } })).collect::<Vec<_>>() }))?;
111 let responses = result["responses"]
112 .as_array()
113 .ok_or_else(|| error("incomplete coordinator snapshot"))?;
114 if result["succeeded"] != true || responses.len() != keys.len() {
115 return Err(error("invalid coordinator snapshot"));
116 }
117 responses
118 .iter()
119 .zip(keys)
120 .map(|(response, key)| {
121 let range = response["response_range"]
122 .as_object()
123 .ok_or_else(|| error("invalid coordinator range"))?;
124 if range.get("more").is_some_and(|more| more != false) {
125 return Err(error("incomplete coordinator range"));
126 }
127 let values = match range.get("kvs") {
128 None => &[][..],
129 Some(value) => value
130 .as_array()
131 .ok_or_else(|| error("invalid coordinator keys"))?
132 .as_slice(),
133 };
134 if values.is_empty() {
135 return Ok(JournalVersion::default());
136 }
137 let value = &values[0];
138 let generation = value["mod_revision"]
139 .as_str()
140 .and_then(generation)
141 .filter(|generation| *generation > 0 && *generation <= i64::MAX as u64)
142 .ok_or_else(|| error("invalid coordinator generation"))?;
143 if values.len() != 1 || value["key"] != self.key(key) {
144 return Err(error("invalid coordinator key"));
145 }
146 let bytes = STANDARD
147 .decode(
148 value["value"]
149 .as_str()
150 .ok_or_else(|| error("missing coordinator journal"))?,
151 )
152 .map_err(|_| error("invalid coordinator base64"))?;
153 let entries = serde_json::from_slice(&bytes)
154 .map_err(|_| error("invalid coordinator journal"))?;
155 Ok(JournalVersion {
156 generation,
157 entries,
158 })
159 })
160 .collect()
161 }
162}
163impl AtomicJournalStore for EtcdJournalStore {
164 fn supports_durable_flush(&self) -> bool {
165 true
166 }
167 fn read(&mut self, keys: &[String]) -> Result<Vec<JournalVersion>, LinkError> {
168 validate_keys(keys)?;
169 let mut failure = error("no etcd endpoint available");
170 for _ in 0..self.endpoints.len() {
171 match self.read_once(keys) {
172 Ok(snapshot) => return Ok(snapshot),
173 Err(cause) => {
174 failure = cause;
175 self.cursor = (self.cursor + 1) % self.endpoints.len();
176 }
177 }
178 }
179 Err(failure)
180 }
181 fn compare_exchange(
182 &mut self,
183 keys: &[String],
184 expected: &[JournalVersion],
185 updates: &[Option<Vec<String>>],
186 ) -> Result<bool, LinkError> {
187 validate_keys(keys)?;
188 if expected.len() != keys.len()
189 || updates.len() != keys.len()
190 || expected
191 .iter()
192 .any(|version| version.generation > i64::MAX as u64)
193 {
194 return Err(error("invalid coordinator compare arrays"));
195 }
196 let compare: Vec<_> = keys.iter().zip(expected).map(|(key, version)| json!({ "key": self.key(key), "target": "MOD", "result": "EQUAL", "mod_revision": version.generation.to_string() })).collect();
197 let mut success = Vec::new();
198 for (key, entries) in keys.iter().zip(updates) {
199 if let Some(entries) = entries {
200 success.push(json!({ "request_put": { "key": self.key(key), "value": STANDARD.encode(serde_json::to_vec(entries).map_err(|cause| error(&cause.to_string()))?) } }));
201 }
202 }
203 let result = self.post(json!({ "compare": compare, "success": success }))?;
206 if result["header"]["revision"]
207 .as_str()
208 .and_then(generation)
209 .filter(|revision| *revision > 0 && *revision <= i64::MAX as u64)
210 .is_none()
211 {
212 return Err(error("indeterminate coordinator response"));
213 }
214 match result.get("succeeded") {
216 None => Ok(false),
217 Some(value) => value
218 .as_bool()
219 .ok_or_else(|| error("indeterminate coordinator response")),
220 }
221 }
222}