compmd_host/registry/
proxy.rs1use compmd_pack::PackName;
10use http::{Response, StatusCode, header};
11use serde_json::Value;
12
13use super::client::Client;
14use super::metadata::{ABBREVIATED, answered_versions};
15use super::options::Options;
16use super::step::Answer;
17
18const TARBALL: &str = "-/tarball/";
20
21#[derive(Clone, Debug)]
23pub struct Proxy {
24 options: Options,
25 client: Client,
26}
27
28fn text(status: StatusCode, text: &str) -> Response<Vec<u8>> {
30 Response::builder()
31 .status(status)
32 .header(header::CONTENT_TYPE, "text/plain")
33 .body(text.as_bytes().to_vec())
34 .unwrap_or_default()
35}
36
37fn decoded(path: &str) -> Option<String> {
39 let bytes = path.as_bytes();
40 let mut out = Vec::with_capacity(bytes.len());
41 let mut at = 0;
42 while at < bytes.len() {
43 let escape = (bytes[at] == b'%')
44 .then(|| path.get(at + 1..at + 3))
45 .flatten()
46 .and_then(|hex| u8::from_str_radix(hex, 16).ok());
47 if let Some(byte) = escape {
48 out.push(byte);
49 at += 3;
50 } else {
51 out.push(bytes[at]);
52 at += 1;
53 }
54 }
55 String::from_utf8(out).ok()
56}
57
58enum Asked {
60 Metadata(PackName),
61 Tarball(PackName, String),
62}
63
64fn asked(path: &str) -> Option<Asked> {
66 let path = decoded(path)?;
67 let Some(tarball) = path.strip_prefix(TARBALL) else {
68 return path.parse().ok().map(Asked::Metadata);
69 };
70 let (name, version) = tarball.rsplit_once('/')?;
71 Some(Asked::Tarball(name.parse().ok()?, version.to_owned()))
72}
73
74impl Proxy {
75 #[must_use]
77 pub fn new(options: Options, client: Client) -> Self {
78 Self { options, client }
79 }
80
81 #[must_use]
85 pub fn answer(&self, path: &str, base: &str) -> Response<Vec<u8>> {
86 let not_found = || text(StatusCode::NOT_FOUND, "Not found");
87 let Some(asked) = asked(path) else {
88 return not_found();
89 };
90 let pack = match &asked {
91 Asked::Metadata(pack) | Asked::Tarball(pack, _) => pack,
92 };
93 let Some(registry) = self.options.registry_of(pack) else {
94 return not_found();
95 };
96 let answered = match &asked {
97 Asked::Metadata(pack) => self.metadata(registry, pack, base),
98 Asked::Tarball(pack, version) => self.tarball(registry, pack, version),
99 };
100 answered.unwrap_or_else(|| text(StatusCode::BAD_GATEWAY, "Bad gateway"))
101 }
102
103 fn metadata(&self, registry: &str, pack: &PackName, base: &str) -> Option<Response<Vec<u8>>> {
105 let metadata = self.client.metadata(registry, pack).ok()?;
106 if metadata.status == 404 {
107 return Some(text(StatusCode::NOT_FOUND, "Not found"));
108 }
109 if !(200..300).contains(&metadata.status) {
110 return None;
111 }
112 let mut packument: Value = serde_json::from_str(&metadata.body).ok()?;
113 if let Some(versions) = packument["versions"].as_object_mut() {
114 for (version, entry) in versions {
115 if let Some(dist) = entry.get_mut("dist").and_then(Value::as_object_mut) {
116 let tarball = format!("{base}{TARBALL}{pack}/{version}");
117 dist.insert("tarball".to_owned(), Value::String(tarball));
118 }
119 }
120 }
121 Response::builder()
122 .header(header::CONTENT_TYPE, ABBREVIATED)
123 .header(
124 header::CACHE_CONTROL,
125 format!("public, max-age={}", metadata.max_age),
126 )
127 .body(packument.to_string().into_bytes())
128 .ok()
129 }
130
131 fn tarball(&self, registry: &str, pack: &PackName, version: &str) -> Option<Response<Vec<u8>>> {
133 let metadata = self.client.metadata(registry, pack).ok()?;
134 let versions = answered_versions(registry, pack, metadata.status, &metadata.body).ok()?;
135 let Some(info) = versions
136 .iter()
137 .find(|info| info.version.to_string() == version)
138 else {
139 return Some(text(StatusCode::NOT_FOUND, "Not found"));
140 };
141 let Answer::Tarball { bytes } =
142 self.client
143 .tarball(registry, info, self.options.max_pack_size)
144 else {
145 return None;
146 };
147 Response::builder()
149 .header(header::CONTENT_TYPE, "application/octet-stream")
150 .header(header::CACHE_CONTROL, "public, max-age=31536000, immutable")
151 .body(bytes)
152 .ok()
153 }
154}
155
156#[cfg(test)]
157mod tests;