Diffinery

homeflare/celldpublic

celld/crates/ltx/src/replica_url.rs
440 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 // A fragment is not part of the replica location. Remove it before the
128 // custom ARN, path, and query parsers can treat it as stored data.
129 let s = s.split_once('#').map_or(s, |(before, _)| before);
130
131 if s.to_ascii_lowercase().starts_with("s3://arn:") {
132 let (scheme, host, path, query) = parse_s3_access_point_url(s)?;
133 return Ok(ParsedReplicaUrl {
134 scheme,
135 host,
136 path,
137 query,
138 userinfo: None,
139 });
140 }
141
142 let (scheme, rest) = parse_scheme(s);
143 if scheme.is_empty() {
144 return Err(url_err(format!("replica url scheme required: {s}")));
145 }
146
147 if scheme == "file" {
148 // Go blanks the scheme + query and returns path.Clean(u.String()).
149 let no_query = rest.split('?').next().unwrap_or(rest);
150 let (_, host, path, _) = split_authority(no_query);
151 let reconstructed = if host.is_empty() {
152 path
153 } else {
154 format!("//{host}{path}")
155 };
156 return Ok(ParsedReplicaUrl {
157 scheme,
158 host: String::new(),
159 path: crate::path_clean(&reconstructed),
160 query: Query::default(),
161 userinfo: None,
162 });
163 }
164
165 // Default (s3, …): scheme://[userinfo@]host[/path][?query].
166 let (q_str, before_q) = match rest.split_once('?') {
167 Some((a, b)) => (Some(b), a),
168 None => (None, rest),
169 };
170 let (userinfo, host, path, _) = split_authority(before_q);
171 let query = q_str.map(parse_query).unwrap_or_default();
172 Ok(ParsedReplicaUrl {
173 scheme,
174 host,
175 // strings.TrimPrefix(path.Clean(u.Path), "/")
176 path: crate::path_clean(&path)
177 .strip_prefix('/')
178 .map(str::to_string)
179 .unwrap_or_else(|| crate::path_clean(&path)),
180 query,
181 userinfo,
182 })
183}
184
185/// Splits a post-scheme remainder of the form `//[user@]host[/path]` into
186/// `(userinfo, host, path)`. The leading `//` is optional/tolerated; `path`
187/// keeps its leading slash. `query` is always returned empty here (callers
188/// split it off first).
189fn split_authority(rest: &str) -> (Option<String>, String, String, Query) {
190 let r = rest.strip_prefix("//").unwrap_or(rest);
191 let (authority, path) = match r.find('/') {
192 Some(i) => (&r[..i], &r[i..]),
193 None => (r, ""),
194 };
195 let (userinfo, host) = match authority.rfind('@') {
196 Some(i) => (Some(authority[..i].to_string()), &authority[i + 1..]),
197 None => (None, authority),
198 };
199 (
200 userinfo,
201 host.to_string(),
202 path.to_string(),
203 Query::default(),
204 )
205}
206
207/// Parses a replica URL into scheme/host/path (no query/userinfo).
208///
209/// Ported from `ParseReplicaURL` (replica_url.go:68-76).
210pub fn parse_replica_url(s: &str) -> Result<(String, String, String)> {
211 let p = parse_replica_url_with_query(s)?;
212 Ok((p.scheme, p.host, p.path))
213}
214
215/// Returns the replica backend type from a URL (`""` if no scheme).
216/// `webdavs` normalizes to `webdav`. Ported from replica_url.go:56-65.
217pub fn replica_type_from_url(s: &str) -> String {
218 let (scheme, _) = parse_scheme(s);
219 if scheme.is_empty() {
220 return String::new();
221 }
222 if scheme == "webdavs" {
223 return "webdav".to_string();
224 }
225 scheme
226}
227
228/// `true` if `s` looks like a URL (`^\w+://`). Ported from replica_url.go:364-369.
229pub fn is_url(s: &str) -> bool {
230 if let Some(idx) = s.find("://") {
231 idx > 0
232 && s[..idx]
233 .bytes()
234 .all(|b| b.is_ascii_alphanumeric() || b == b'_')
235 } else {
236 false
237 }
238}
239
240// ── S3 Access Point ARN parsing ───────────────────────────────────────────────
241
242/// Parses an `s3://arn:…:accesspoint/<name>[/key]` URL.
243/// Ported from `parseS3AccessPointURL` (replica_url.go:107-136).
244fn parse_s3_access_point_url(s: &str) -> Result<(String, String, String, Query)> {
245 const PREFIX: &str = "s3://";
246 if !s.to_ascii_lowercase().starts_with(PREFIX) {
247 return Err(url_err(format!("invalid s3 access point url: {s}")));
248 }
249 let arn_with_path = &s[PREFIX.len()..];
250
251 let (arn_with_path, query_str) = match arn_with_path.find('?') {
252 Some(idx) => (&arn_with_path[..idx], Some(&arn_with_path[idx + 1..])),
253 None => (arn_with_path, None),
254 };
255
256 let (bucket, key) = split_s3_access_point_arn(arn_with_path)?;
257 let query = query_str.map(parse_query).unwrap_or_default();
258 Ok((
259 "s3".to_string(),
260 bucket,
261 clean_replica_url_path(&key),
262 query,
263 ))
264}
265
266/// Splits an S3 Access Point ARN into `(bucket, key)`.
267/// Ported from `splitS3AccessPointARN` (replica_url.go:139-162).
268fn split_s3_access_point_arn(s: &str) -> Result<(String, String)> {
269 const MARKER: &str = ":accesspoint/";
270 let lower = s.to_ascii_lowercase();
271 let idx = lower
272 .find(MARKER)
273 .ok_or_else(|| url_err(format!("invalid s3 access point arn: {s}")))?;
274 let name_start = idx + MARKER.len();
275 if name_start >= s.len() {
276 return Err(url_err(format!("invalid s3 access point arn: {s}")));
277 }
278 let remainder = &s[name_start..];
279 match remainder.find('/') {
280 None => Ok((s.to_string(), String::new())),
281 Some(slash_idx) => {
282 let bucket_end = name_start + slash_idx;
283 Ok((
284 s[..bucket_end].to_string(),
285 remainder[slash_idx + 1..].to_string(),
286 ))
287 }
288 }
289}
290
291/// Cleans a URL path for replica storage. Ported from replica_url.go:165-175.
292pub fn clean_replica_url_path(p: &str) -> String {
293 if p.is_empty() {
294 return String::new();
295 }
296 let cleaned = crate::path_clean(&format!("/{p}"));
297 let cleaned = cleaned.strip_prefix('/').unwrap_or(&cleaned);
298 if cleaned == "." {
299 return String::new();
300 }
301 cleaned.to_string()
302}
303
304/// Extracts the region from an S3 ARN (`arn:aws:s3:<region>:…`).
305/// Ported from replica_url.go:178-184.
306pub fn region_from_s3_arn(arn: &str) -> String {
307 let parts: Vec<&str> = arn.splitn(6, ':').collect();
308 if parts.len() >= 4 {
309 parts[3].to_string()
310 } else {
311 String::new()
312 }
313}
314
315/// Reads a boolean from query params, checking `keys` in order. Returns `None`
316/// when no key is set (Go's `ok == false`); an unrecognized value yields
317/// `Some(false)`. Ported from `BoolQueryValue` (replica_url.go:188-205).
318pub fn bool_query_value(query: Option<&Query>, keys: &[&str]) -> Option<bool> {
319 let query = query?;
320 for key in keys {
321 let raw = query.get(key);
322 if !raw.is_empty() {
323 return Some(matches!(
324 raw.to_ascii_lowercase().as_str(),
325 "true" | "1" | "t" | "yes"
326 ));
327 }
328 }
329 None
330}
331
332// ── Endpoint detection (S3 provider/local heuristics) ─────────────────────────
333
334/// Extracts the host from an endpoint URL, or returns it as-is.
335/// Ported from `extractEndpointHost` (replica_url.go:351-362).
336fn extract_endpoint_host(endpoint: &str) -> String {
337 let endpoint = endpoint.trim().to_ascii_lowercase();
338 if endpoint.is_empty() {
339 return String::new();
340 }
341 for scheme in ["http://", "https://"] {
342 if let Some(rest) = endpoint.strip_prefix(scheme) {
343 let host = rest.split('/').next().unwrap_or(rest);
344 if !host.is_empty() {
345 return host.to_string();
346 }
347 return endpoint;
348 }
349 }
350 endpoint
351}
352
353fn host_has_suffix(endpoint: &str, suffix: &str) -> bool {
354 let host = extract_endpoint_host(endpoint);
355 !host.is_empty() && host.ends_with(suffix)
356}
357
358pub fn is_tigris_endpoint(endpoint: &str) -> bool {
359 let host = extract_endpoint_host(endpoint);
360 host == "fly.storage.tigris.dev" || host == "t3.storage.dev"
361}
362pub fn is_hetzner_endpoint(endpoint: &str) -> bool {
363 host_has_suffix(endpoint, ".your-objectstorage.com")
364}
365pub fn is_digitalocean_endpoint(endpoint: &str) -> bool {
366 host_has_suffix(endpoint, ".digitaloceanspaces.com")
367}
368pub fn is_backblaze_endpoint(endpoint: &str) -> bool {
369 host_has_suffix(endpoint, ".backblazeb2.com")
370}
371pub fn is_filebase_endpoint(endpoint: &str) -> bool {
372 extract_endpoint_host(endpoint) == "s3.filebase.com"
373}
374pub fn is_scaleway_endpoint(endpoint: &str) -> bool {
375 host_has_suffix(endpoint, ".scw.cloud")
376}
377pub fn is_cloudflare_r2_endpoint(endpoint: &str) -> bool {
378 host_has_suffix(endpoint, ".r2.cloudflarestorage.com")
379}
380pub fn is_supabase_endpoint(endpoint: &str) -> bool {
381 host_has_suffix(endpoint, ".supabase.co")
382}
383
384/// `true` if the endpoint looks like MinIO (a custom `host:port` that is not a
385/// known cloud). Ported from `IsMinIOEndpoint` (replica_url.go:278-301).
386pub fn is_minio_endpoint(endpoint: &str) -> bool {
387 let host = extract_endpoint_host(endpoint);
388 if host.is_empty() || !host.contains(':') {
389 return false;
390 }
391 const KNOWN: [&str; 9] = [
392 ".amazonaws.com",
393 ".digitaloceanspaces.com",
394 ".backblazeb2.com",
395 ".filebase.com",
396 ".scw.cloud",
397 ".r2.cloudflarestorage.com",
398 "tigris.dev",
399 "t3.storage.dev",
400 ".supabase.co",
401 ];
402 !KNOWN.iter().any(|k| host.contains(k))
403}
404
405/// `true` for localhost / loopback / RFC1918 / `.local` endpoints.
406/// Ported from `IsLocalEndpoint` (replica_url.go:306-329).
407pub fn is_local_endpoint(endpoint: &str) -> bool {
408 let mut host = extract_endpoint_host(endpoint);
409 if host.is_empty() {
410 return false;
411 }
412 if let Some(idx) = host.rfind(':') {
413 host = host[..idx].to_string();
414 }
415 let is_private_ipv4 = host
416 .parse::<std::net::Ipv4Addr>()
417 .is_ok_and(|address| address.is_private());
418 host == "localhost"
419 || host == "127.0.0.1"
420 || is_private_ipv4
421 || host.ends_with(".local")
422 || host.ends_with(".localhost")
423}
424
425/// Ensures an endpoint has an http(s) scheme: local → `http://`, else
426/// `https://`. Returns `(endpoint, scheme_was_added)`.
427/// Ported from `EnsureEndpointScheme` (replica_url.go:335-347).
428pub fn ensure_endpoint_scheme(endpoint: &str) -> (String, bool) {
429 if endpoint.is_empty() {
430 return (String::new(), false);
431 }
432 if endpoint.starts_with("http://") || endpoint.starts_with("https://") {
433 return (endpoint.to_string(), false);
434 }
435 if is_local_endpoint(endpoint) {
436 (format!("http://{endpoint}"), true)
437 } else {
438 (format!("https://{endpoint}"), true)
439 }
440}