Diffinery

homeflare/celldpublic

celld/crates/ltx/src/replica_url.rs
441 lines · 14.7 KBRaw History
1//! replica_url.rs — parse `s3://` and `file://` replica URLs + S3 endpoint
2//! detection helpers.
3//!
4//! Ported from [email protected] `replica_url.go`. Scope is the KEEP set (D-7):
5//! the pure URL-parsing and endpoint-detection functions for the **s3** and
6//! **file** schemes. The `RegisterReplicaClientFactory` registry and the
7//! `NewReplicaClientFromURL` *client construction* path are deferred to the
8//! client implementations. The crate does not include the gs, abs, oss, sftp,
9//! or webdav schemes.
10
11use crate::error::{Error, Result};
12
13fn url_err(msg: impl Into<String>) -> Error {
14 Error::Other(msg.into().into())
15}
16
17// ── Query (a tiny ordered multimap, like Go's url.Values) ─────────────────────
18
19/// Parsed query parameters. Mirrors `url.Values`: ordered, allows duplicate
20/// keys, and `get` returns the first value for a key.
21#[derive(Debug, Clone, Default, PartialEq, Eq)]
22pub struct Query(Vec<(String, String)>);
23
24impl Query {
25 pub fn is_empty(&self) -> bool {
26 self.0.is_empty()
27 }
28
29 /// First value for `key`, or `""` if absent (matches Go `url.Values.Get`).
30 pub fn get(&self, key: &str) -> &str {
31 self.0
32 .iter()
33 .find(|(k, _)| k == key)
34 .map(|(_, v)| v.as_str())
35 .unwrap_or("")
36 }
37
38 pub fn contains(&self, key: &str) -> bool {
39 self.0.iter().any(|(k, _)| k == key)
40 }
41}
42
43/// Parses an `a=b&c=d` query string with percent-decoding, like
44/// `url.ParseQuery`. `+` decodes to a space (form semantics).
45fn parse_query(s: &str) -> Query {
46 let mut out = Vec::new();
47 for pair in s.split('&') {
48 if pair.is_empty() {
49 continue;
50 }
51 let (k, v) = match pair.split_once('=') {
52 Some((k, v)) => (k, v),
53 None => (pair, ""),
54 };
55 out.push((percent_decode(k), percent_decode(v)));
56 }
57 Query(out)
58}
59
60/// Minimal `application/x-www-form-urlencoded` decode: `+` → space and
61/// `%XX` → byte. Invalid escapes are left verbatim (best effort).
62fn percent_decode(s: &str) -> String {
63 let bytes = s.as_bytes();
64 let mut out = Vec::with_capacity(bytes.len());
65 let mut i = 0;
66 while i < bytes.len() {
67 match bytes[i] {
68 b'+' => {
69 out.push(b' ');
70 i += 1;
71 }
72 b'%' if i + 2 < bytes.len() => {
73 let hi = (bytes[i + 1] as char).to_digit(16);
74 let lo = (bytes[i + 2] as char).to_digit(16);
75 if let (Some(h), Some(l)) = (hi, lo) {
76 out.push((h * 16 + l) as u8);
77 i += 3;
78 } else {
79 out.push(bytes[i]);
80 i += 1;
81 }
82 }
83 b => {
84 out.push(b);
85 i += 1;
86 }
87 }
88 }
89 String::from_utf8_lossy(&out).into_owned()
90}
91
92// ── Scheme + URL parsing ──────────────────────────────────────────────────────
93
94/// The fields parsed from a replica URL.
95#[derive(Debug, Clone, Default, PartialEq, Eq)]
96pub struct ParsedReplicaUrl {
97 pub scheme: String,
98 pub host: String,
99 pub path: String,
100 pub query: Query,
101 /// `user[:password]` userinfo, if present.
102 pub userinfo: Option<String>,
103}
104
105/// Extracts and lowercases the URL scheme (matching Go `net/url`, which
106/// lowercases schemes). Returns `("", s)` when there is no valid leading
107/// `scheme:` (e.g. `"invalid"`, `"relative/path"`).
108fn parse_scheme(s: &str) -> (String, &str) {
109 let bytes = s.as_bytes();
110 for (i, &c) in bytes.iter().enumerate() {
111 match c {
112 b'a'..=b'z' | b'A'..=b'Z' => {}
113 b'0'..=b'9' | b'+' | b'-' | b'.' if i > 0 => {}
114 b':' if i > 0 => return (s[..i].to_ascii_lowercase(), &s[i + 1..]),
115 _ => return (String::new(), s),
116 }
117 }
118 (String::new(), s)
119}
120
121/// Parses a replica URL into scheme/host/path/query/userinfo.
122///
123/// Ported from `ParseReplicaURLWithQuery` (replica_url.go:79-104). The
124/// `s3://arn:` Access-Point form is handled specially because a raw ARN is not
125/// a parseable authority.
126pub fn parse_replica_url_with_query(s: &str) -> Result<ParsedReplicaUrl> {
127 if s.to_ascii_lowercase().starts_with("s3://arn:") {
128 let (scheme, host, path, query) = parse_s3_access_point_url(s)?;
129 return Ok(ParsedReplicaUrl {
130 scheme,
131 host,
132 path,
133 query,
134 userinfo: None,
135 });
136 }
137
138 let (scheme, rest) = parse_scheme(s);
139 if scheme.is_empty() {
140 return Err(url_err(format!("replica url scheme required: {s}")));
141 }
142
143 if scheme == "file" {
144 // Go blanks the scheme + query and returns path.Clean(u.String()).
145 let no_query = rest.split('?').next().unwrap_or(rest);
146 let (_, host, path, _) = split_authority(no_query);
147 let reconstructed = if host.is_empty() {
148 path
149 } else {
150 format!("//{host}{path}")
151 };
152 return Ok(ParsedReplicaUrl {
153 scheme,
154 host: String::new(),
155 path: crate::path_clean(&reconstructed),
156 query: Query::default(),
157 userinfo: None,
158 });
159 }
160
161 // Default (s3, …): scheme://[userinfo@]host[/path][?query].
162 let (q_str, before_q) = match rest.split_once('?') {
163 Some((a, b)) => (Some(b), a),
164 None => (None, rest),
165 };
166 let (userinfo, host, path, _) = split_authority(before_q);
167 let query = q_str.map(parse_query).unwrap_or_default();
168 Ok(ParsedReplicaUrl {
169 scheme,
170 host,
171 // strings.TrimPrefix(path.Clean(u.Path), "/")
172 path: crate::path_clean(&path)
173 .strip_prefix('/')
174 .map(str::to_string)
175 .unwrap_or_else(|| crate::path_clean(&path)),
176 query,
177 userinfo,
178 })
179}
180
181/// Splits a post-scheme remainder of the form `//[user@]host[/path]` into
182/// `(userinfo, host, path)`. The leading `//` is optional/tolerated; `path`
183/// keeps its leading slash. `query` is always returned empty here (callers
184/// split it off first).
185fn split_authority(rest: &str) -> (Option<String>, String, String, Query) {
186 let r = rest.strip_prefix("//").unwrap_or(rest);
187 let (authority, path) = match r.find('/') {
188 Some(i) => (&r[..i], &r[i..]),
189 None => (r, ""),
190 };
191 let (userinfo, host) = match authority.rfind('@') {
192 Some(i) => (Some(authority[..i].to_string()), &authority[i + 1..]),
193 None => (None, authority),
194 };
195 (
196 userinfo,
197 host.to_string(),
198 path.to_string(),
199 Query::default(),
200 )
201}
202
203/// Parses a replica URL into scheme/host/path (no query/userinfo).
204///
205/// Ported from `ParseReplicaURL` (replica_url.go:68-76).
206pub fn parse_replica_url(s: &str) -> Result<(String, String, String)> {
207 let p = parse_replica_url_with_query(s)?;
208 Ok((p.scheme, p.host, p.path))
209}
210
211/// Returns the replica backend type from a URL (`""` if no scheme).
212/// `webdavs` normalizes to `webdav`. Ported from replica_url.go:56-65.
213pub fn replica_type_from_url(s: &str) -> String {
214 let (scheme, _) = parse_scheme(s);
215 if scheme.is_empty() {
216 return String::new();
217 }
218 if scheme == "webdavs" {
219 return "webdav".to_string();
220 }
221 scheme
222}
223
224/// `true` if `s` looks like a URL (`^\w+://`). Ported from replica_url.go:364-369.
225pub fn is_url(s: &str) -> bool {
226 if let Some(idx) = s.find("://") {
227 idx > 0
228 && s[..idx]
229 .bytes()
230 .all(|b| b.is_ascii_alphanumeric() || b == b'_')
231 } else {
232 false
233 }
234}
235
236// ── S3 Access Point ARN parsing ───────────────────────────────────────────────
237
238/// Parses an `s3://arn:…:accesspoint/<name>[/key]` URL.
239/// Ported from `parseS3AccessPointURL` (replica_url.go:107-136).
240fn parse_s3_access_point_url(s: &str) -> Result<(String, String, String, Query)> {
241 const PREFIX: &str = "s3://";
242 if !s.to_ascii_lowercase().starts_with(PREFIX) {
243 return Err(url_err(format!("invalid s3 access point url: {s}")));
244 }
245 let arn_with_path = &s[PREFIX.len()..];
246
247 let (arn_with_path, query_str) = match arn_with_path.find('?') {
248 Some(idx) => (&arn_with_path[..idx], Some(&arn_with_path[idx + 1..])),
249 None => (arn_with_path, None),
250 };
251
252 let (bucket, key) = split_s3_access_point_arn(arn_with_path)?;
253 let query = query_str.map(parse_query).unwrap_or_default();
254 Ok((
255 "s3".to_string(),
256 bucket,
257 clean_replica_url_path(&key),
258 query,
259 ))
260}
261
262/// Splits an S3 Access Point ARN into `(bucket, key)`.
263/// Ported from `splitS3AccessPointARN` (replica_url.go:139-162).
264fn split_s3_access_point_arn(s: &str) -> Result<(String, String)> {
265 const MARKER: &str = ":accesspoint/";
266 let lower = s.to_ascii_lowercase();
267 let idx = lower
268 .find(MARKER)
269 .ok_or_else(|| url_err(format!("invalid s3 access point arn: {s}")))?;
270 let name_start = idx + MARKER.len();
271 if name_start >= s.len() {
272 return Err(url_err(format!("invalid s3 access point arn: {s}")));
273 }
274 let remainder = &s[name_start..];
275 match remainder.find('/') {
276 None => Ok((s.to_string(), String::new())),
277 Some(slash_idx) => {
278 let bucket_end = name_start + slash_idx;
279 Ok((
280 s[..bucket_end].to_string(),
281 remainder[slash_idx + 1..].to_string(),
282 ))
283 }
284 }
285}
286
287/// Cleans a URL path for replica storage. Ported from replica_url.go:165-175.
288pub fn clean_replica_url_path(p: &str) -> String {
289 if p.is_empty() {
290 return String::new();
291 }
292 let cleaned = crate::path_clean(&format!("/{p}"));
293 let cleaned = cleaned.strip_prefix('/').unwrap_or(&cleaned);
294 if cleaned == "." {
295 return String::new();
296 }
297 cleaned.to_string()
298}
299
300/// Extracts the region from an S3 ARN (`arn:aws:s3:<region>:…`).
301/// Ported from replica_url.go:178-184.
302pub fn region_from_s3_arn(arn: &str) -> String {
303 let parts: Vec<&str> = arn.splitn(6, ':').collect();
304 if parts.len() >= 4 {
305 parts[3].to_string()
306 } else {
307 String::new()
308 }
309}
310
311/// Reads a boolean from query params, checking `keys` in order. Returns `None`
312/// when no key is set (Go's `ok == false`); an unrecognized value yields
313/// `Some(false)`. Ported from `BoolQueryValue` (replica_url.go:188-205).
314pub fn bool_query_value(query: Option<&Query>, keys: &[&str]) -> Option<bool> {
315 let query = query?;
316 for key in keys {
317 let raw = query.get(key);
318 if !raw.is_empty() {
319 return Some(matches!(
320 raw.to_ascii_lowercase().as_str(),
321 "true" | "1" | "t" | "yes"
322 ));
323 }
324 }
325 None
326}
327
328// ── Endpoint detection (S3 provider/local heuristics) ─────────────────────────
329
330/// Extracts the host from an endpoint URL, or returns it as-is.
331/// Ported from `extractEndpointHost` (replica_url.go:351-362).
332fn extract_endpoint_host(endpoint: &str) -> String {
333 let endpoint = endpoint.trim().to_ascii_lowercase();
334 if endpoint.is_empty() {
335 return String::new();
336 }
337 for scheme in ["http://", "https://"] {
338 if let Some(rest) = endpoint.strip_prefix(scheme) {
339 let host = rest.split('/').next().unwrap_or(rest);
340 if !host.is_empty() {
341 return host.to_string();
342 }
343 return endpoint;
344 }
345 }
346 endpoint
347}
348
349fn host_has_suffix(endpoint: &str, suffix: &str) -> bool {
350 let host = extract_endpoint_host(endpoint);
351 !host.is_empty() && host.ends_with(suffix)
352}
353
354pub fn is_tigris_endpoint(endpoint: &str) -> bool {
355 let host = extract_endpoint_host(endpoint);
356 host == "fly.storage.tigris.dev" || host == "t3.storage.dev"
357}
358pub fn is_hetzner_endpoint(endpoint: &str) -> bool {
359 host_has_suffix(endpoint, ".your-objectstorage.com")
360}
361pub fn is_digitalocean_endpoint(endpoint: &str) -> bool {
362 host_has_suffix(endpoint, ".digitaloceanspaces.com")
363}
364pub fn is_backblaze_endpoint(endpoint: &str) -> bool {
365 host_has_suffix(endpoint, ".backblazeb2.com")
366}
367pub fn is_filebase_endpoint(endpoint: &str) -> bool {
368 extract_endpoint_host(endpoint) == "s3.filebase.com"
369}
370pub fn is_scaleway_endpoint(endpoint: &str) -> bool {
371 host_has_suffix(endpoint, ".scw.cloud")
372}
373pub fn is_cloudflare_r2_endpoint(endpoint: &str) -> bool {
374 host_has_suffix(endpoint, ".r2.cloudflarestorage.com")
375}
376pub fn is_supabase_endpoint(endpoint: &str) -> bool {
377 host_has_suffix(endpoint, ".supabase.co")
378}
379
380/// `true` if the endpoint looks like MinIO (a custom `host:port` that is not a
381/// known cloud). Ported from `IsMinIOEndpoint` (replica_url.go:278-301).
382pub fn is_minio_endpoint(endpoint: &str) -> bool {
383 let host = extract_endpoint_host(endpoint);
384 if host.is_empty() || !host.contains(':') {
385 return false;
386 }
387 const KNOWN: [&str; 9] = [
388 ".amazonaws.com",
389 ".digitaloceanspaces.com",
390 ".backblazeb2.com",
391 ".filebase.com",
392 ".scw.cloud",
393 ".r2.cloudflarestorage.com",
394 "tigris.dev",
395 "t3.storage.dev",
396 ".supabase.co",
397 ];
398 !KNOWN.iter().any(|k| host.contains(k))
399}
400
401/// `true` for localhost / loopback / RFC1918 / `.local` endpoints.
402/// Ported from `IsLocalEndpoint` (replica_url.go:306-329).
403pub fn is_local_endpoint(endpoint: &str) -> bool {
404 let mut host = extract_endpoint_host(endpoint);
405 if host.is_empty() {
406 return false;
407 }
408 if let Some(idx) = host.rfind(':') {
409 host = host[..idx].to_string();
410 }
411 host == "localhost"
412 || host == "127.0.0.1"
413 || host.starts_with("192.168.")
414 || host.starts_with("10.")
415 || host.starts_with("172.16.")
416 || host.starts_with("172.17.")
417 || host.starts_with("172.18.")
418 || host.starts_with("172.19.")
419 || host.starts_with("172.2")
420 || host.starts_with("172.30.")
421 || host.starts_with("172.31.")
422 || host.ends_with(".local")
423 || host.ends_with(".localhost")
424}
425
426/// Ensures an endpoint has an http(s) scheme: local → `http://`, else
427/// `https://`. Returns `(endpoint, scheme_was_added)`.
428/// Ported from `EnsureEndpointScheme` (replica_url.go:335-347).
429pub fn ensure_endpoint_scheme(endpoint: &str) -> (String, bool) {
430 if endpoint.is_empty() {
431 return (String::new(), false);
432 }
433 if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
434 return (endpoint.to_string(), false);
435 }
436 if is_local_endpoint(endpoint) {
437 (format!("http://{endpoint}"), true)
438 } else {
439 (format!("https://{endpoint}"), true)
440 }
441}