Skip to main content

rigspark_runtime/
acquire.rs

1use async_trait::async_trait;
2use futures_util::TryStreamExt;
3use serde::{Deserialize, Serialize};
4use sha2::{Digest, Sha256};
5use std::{
6    collections::HashSet,
7    path::{Path, PathBuf},
8    pin::Pin,
9    time::Duration,
10};
11use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt};
12use tokio_util::{io::StreamReader, sync::CancellationToken};
13
14#[derive(Debug, Clone, Deserialize, Serialize)]
15#[serde(deny_unknown_fields)]
16pub struct Artifact {
17    pub backend: String,
18    pub repo: String,
19    pub revision: String,
20    pub file: String,
21    pub sha256: String,
22    pub bytes: u64,
23}
24pub struct DownloadResponse {
25    pub status: u16,
26    pub commit: Option<String>,
27    pub length: Option<u64>,
28    pub body: Pin<Box<dyn AsyncRead + Send>>,
29}
30#[async_trait]
31pub trait DownloadTransport: Send + Sync {
32    async fn get(&self, url: &str) -> Result<DownloadResponse, String>;
33}
34pub struct HfTransport {
35    client: reqwest::Client,
36}
37fn retain_commit(evidence: &mut Option<String>, observed: Option<&str>) -> Result<(), String> {
38    if let Some(observed) = observed {
39        if observed.len() != 40 || !observed.bytes().all(|byte| byte.is_ascii_hexdigit()) {
40            return Err("invalid repository commit evidence".into());
41        }
42        if evidence
43            .as_ref()
44            .is_some_and(|previous| !previous.eq_ignore_ascii_case(observed))
45        {
46            return Err("conflicting repository commit evidence".into());
47        }
48        *evidence = Some(observed.to_owned());
49    }
50    Ok(())
51}
52#[test]
53fn commit_evidence_survives_cdn_redirects_and_rejects_conflicts() {
54    let revision = "a".repeat(40);
55    let mut evidence = None;
56    retain_commit(&mut evidence, Some(&revision)).unwrap();
57    retain_commit(&mut evidence, None).unwrap();
58    assert_eq!(evidence.as_deref(), Some(revision.as_str()));
59    assert!(retain_commit(&mut evidence, Some(&"b".repeat(40))).is_err());
60    assert!(retain_commit(&mut None, Some("not-a-commit")).is_err());
61    let mut absent = None;
62    retain_commit(&mut absent, None).unwrap();
63    assert!(absent.is_none());
64}
65impl HfTransport {
66    pub fn new() -> Result<Self, String> {
67        Ok(Self {
68            client: reqwest::Client::builder()
69                .redirect(reqwest::redirect::Policy::none())
70                .no_proxy()
71                .dns_resolver(std::sync::Arc::new(PublicResolver))
72                .connect_timeout(Duration::from_secs(10))
73                .build()
74                .map_err(|error| error.to_string())?,
75        })
76    }
77}
78fn safe_url(raw: &str) -> Result<url::Url, String> {
79    let url = url::Url::parse(raw).map_err(|error| error.to_string())?;
80    let host = url.host_str().ok_or("missing download host")?;
81    if url.scheme() != "https"
82        || !url.username().is_empty()
83        || url.password().is_some()
84        || url.port().is_some()
85        || !["huggingface.co", "hf.co"]
86            .iter()
87            .any(|allowed| host == *allowed || host.ends_with(&format!(".{allowed}")))
88    {
89        return Err("download URL is not approved HTTPS source".into());
90    }
91    Ok(url)
92}
93#[async_trait]
94impl DownloadTransport for HfTransport {
95    async fn get(&self, raw: &str) -> Result<DownloadResponse, String> {
96        let mut url = safe_url(raw)?;
97        let mut commit = None;
98        for redirect in 0..=5 {
99            let response = self
100                .client
101                .get(url.clone())
102                .send()
103                .await
104                .map_err(|_| "download transport failed".to_owned())?;
105            retain_commit(
106                &mut commit,
107                response
108                    .headers()
109                    .get("x-repo-commit")
110                    .map(|value| {
111                        value
112                            .to_str()
113                            .map_err(|_| "invalid repository commit header".to_owned())
114                    })
115                    .transpose()?,
116            )?;
117            if response.status().is_redirection() {
118                if redirect == 5 {
119                    return Err("too many download redirects".into());
120                }
121                let location = response
122                    .headers()
123                    .get("location")
124                    .and_then(|value| value.to_str().ok())
125                    .ok_or("redirect has no location")?;
126                url = safe_url(
127                    url.join(location)
128                        .map_err(|error| error.to_string())?
129                        .as_str(),
130                )?;
131                continue;
132            }
133            let length = response.content_length();
134            let status = response.status().as_u16();
135            let stream = response.bytes_stream().map_err(std::io::Error::other);
136            return Ok(DownloadResponse {
137                status,
138                commit,
139                length,
140                body: Box::pin(StreamReader::new(stream)),
141            });
142        }
143        Err("download redirect limit".into())
144    }
145}
146
147pub fn public_addresses(
148    addresses: Vec<std::net::SocketAddr>,
149) -> Result<Vec<std::net::SocketAddr>, String> {
150    fn public(address: std::net::IpAddr) -> bool {
151        match address {
152            std::net::IpAddr::V4(address) => {
153                let octets = address.octets();
154                !address.is_private()
155                    && !address.is_loopback()
156                    && !address.is_link_local()
157                    && !address.is_multicast()
158                    && !address.is_unspecified()
159                    && !address.is_broadcast()
160                    && !address.is_documentation()
161                    && octets[0] != 0
162                    && octets[0] < 224
163                    && !(octets[0] == 100 && (64..=127).contains(&octets[1]))
164                    && !(octets[0] == 198 && (18..=19).contains(&octets[1]))
165                    && !(octets[0] == 192 && octets[1] == 0 && octets[2] == 0)
166            }
167            std::net::IpAddr::V6(address) => {
168                if let Some(mapped) = address.to_ipv4_mapped() {
169                    return public(mapped.into());
170                }
171                let segments = address.segments();
172                segments[0] & 0xe000 == 0x2000
173                    && segments[0] != 0x2002
174                    && !(segments[0] == 0x2001 && (segments[1] < 0x200 || segments[1] == 0xdb8))
175            }
176        }
177    }
178    if addresses.is_empty()
179        || addresses.len() > 64
180        || addresses.iter().any(|address| !public(address.ip()))
181    {
182        return Err("download DNS contains private or unsupported addresses".into());
183    }
184    Ok(addresses)
185}
186struct PublicResolver;
187impl reqwest::dns::Resolve for PublicResolver {
188    fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
189        Box::pin(async move {
190            let addresses = tokio::time::timeout(
191                Duration::from_secs(5),
192                tokio::net::lookup_host((name.as_str(), 0)),
193            )
194            .await
195            .map_err(|_| std::io::Error::other("download DNS timed out"))??;
196            let addresses =
197                public_addresses(addresses.take(65).collect()).map_err(std::io::Error::other)?;
198            Ok(Box::new(addresses.into_iter()) as reqwest::dns::Addrs)
199        })
200    }
201}
202
203#[derive(Debug)]
204pub struct Acquired {
205    pub path: PathBuf,
206    pub bytes: u64,
207    pub cached: bool,
208}
209#[derive(Debug, Clone, Copy)]
210pub enum SizePolicy {
211    Exact,
212    Ceiling,
213}
214impl SizePolicy {
215    fn accepts(self, actual: u64, expected: u64) -> bool {
216        actual > 0
217            && match self {
218                Self::Exact => actual == expected,
219                Self::Ceiling => actual <= expected,
220            }
221    }
222}
223pub struct Acquisition {
224    root: PathBuf,
225    progress: Option<std::sync::Arc<Progress>>,
226}
227type Progress = dyn Fn(u64, u64, &str) + Send + Sync;
228
229struct ArtifactLock {
230    guard: crate::state::LockGuard,
231}
232impl ArtifactLock {
233    fn acquire(path: PathBuf) -> Result<Self, String> {
234        let mut config =
235            crate::state::Config::from_home(path.parent().ok_or("missing lock parent")?)
236                .map_err(|error| error.to_string())?;
237        config.lock = path;
238        let guard = crate::state::StateStore::new(config)
239            .lock(Duration::ZERO)
240            .map_err(|error| error.to_string())?;
241        Ok(Self { guard })
242    }
243    fn check(&self) -> Result<(), String> {
244        self.guard.assert_owned().map_err(|error| error.to_string())
245    }
246}
247fn suffix(path: &Path, suffix: &str) -> PathBuf {
248    let mut value = path.as_os_str().to_owned();
249    value.push(suffix);
250    PathBuf::from(value)
251}
252pub fn cleanup_partials(parent: &Path, alive: impl Fn(u32) -> bool) -> Result<(), String> {
253    for (index, entry) in std::fs::read_dir(parent)
254        .map_err(|error| error.to_string())?
255        .enumerate()
256    {
257        if index >= 10000 {
258            return Err("cache directory exceeds cleanup entry limit".into());
259        }
260        let entry = entry.map_err(|error| error.to_string())?;
261        let name = entry.file_name();
262        let Some(name) = name.to_str() else {
263            continue;
264        };
265        let Some(rest) = name
266            .strip_prefix(".llmup-download.")
267            .and_then(|value| value.strip_suffix(".part"))
268        else {
269            continue;
270        };
271        let Some((pid, unique)) = rest.split_once('.') else {
272            continue;
273        };
274        if unique.is_empty()
275            || unique.contains('.')
276            || !pid.bytes().all(|byte| byte.is_ascii_digit())
277            || pid.starts_with('0')
278        {
279            continue;
280        }
281        let Some(pid) = pid
282            .parse::<u32>()
283            .ok()
284            .filter(|pid| *pid > 0 && *pid <= i32::MAX as u32)
285        else {
286            continue;
287        };
288        if entry
289            .file_type()
290            .map_err(|error| error.to_string())?
291            .is_file()
292            && !alive(pid)
293        {
294            std::fs::remove_file(entry.path()).map_err(|error| error.to_string())?;
295        }
296    }
297    Ok(())
298}
299fn segment(value: &str) -> bool {
300    !value.is_empty()
301        && portable_component(value)
302        && value.as_bytes()[0].is_ascii_alphanumeric()
303        && value
304            .bytes()
305            .all(|byte| byte.is_ascii_alphanumeric() || b"._-".contains(&byte))
306}
307fn portable_component(value: &str) -> bool {
308    let base = value.split('.').next().unwrap_or("").to_ascii_uppercase();
309    !value.is_empty()
310        && value != "."
311        && value != ".."
312        && !value.ends_with('.')
313        && value.trim() == value
314        && !["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"].contains(&base.as_str())
315        && !(base.starts_with("COM") || base.starts_with("LPT"))
316            .then(|| &base[3..])
317            .is_some_and(|suffix| {
318                [
319                    "1", "2", "3", "4", "5", "6", "7", "8", "9", "\u{b9}", "\u{b2}", "\u{b3}",
320                ]
321                .contains(&suffix)
322            })
323}
324pub fn safe_file(value: &str) -> bool {
325    !value.is_empty()
326        && value.len() <= 512
327        && !value
328            .chars()
329            .any(|ch| ch.is_control() || "\\%*?[]{}:".contains(ch))
330        && value.split('/').all(portable_component)
331}
332fn digest(value: &str, length: usize) -> bool {
333    value.len() == length && value.bytes().all(|byte| byte.is_ascii_hexdigit())
334}
335impl Artifact {
336    pub fn validate(&self) -> Result<(), String> {
337        let coordinates: Vec<_> = self.repo.split('/').collect();
338        if !["llamacpp", "mlx"].contains(&self.backend.as_str())
339            || coordinates.len() != 2
340            || !coordinates.iter().all(|part| segment(part))
341            || !digest(&self.revision, 40)
342            || !digest(&self.sha256, 64)
343            || !safe_file(&self.file)
344            || self.bytes == 0
345            || self.bytes > 9007199254740991
346        {
347            return Err("invalid pinned artifact".into());
348        }
349        Ok(())
350    }
351}
352fn private_directory(path: &Path) -> Result<(), String> {
353    match std::fs::symlink_metadata(path) {
354        Ok(metadata) => {
355            if !metadata.is_dir() || metadata.file_type().is_symlink() {
356                return Err("unsafe cache directory".into());
357            }
358        }
359        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
360            if let Some(parent) = path.parent() {
361                private_directory(parent)?;
362            }
363            let builder = std::fs::DirBuilder::new();
364            #[cfg(unix)]
365            let mut builder = builder;
366            #[cfg(unix)]
367            {
368                use std::os::unix::fs::DirBuilderExt;
369                builder.mode(0o700);
370            }
371            match builder.create(path) {
372                Ok(()) => (),
373                Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
374                    return private_directory(path);
375                }
376                Err(error) => return Err(error.to_string()),
377            }
378        }
379        Err(error) => return Err(error.to_string()),
380    }
381    Ok(())
382}
383pub async fn hash_file(path: &Path, cancel: &CancellationToken) -> Result<(String, u64), String> {
384    let mut options = std::fs::OpenOptions::new();
385    options.read(true);
386    #[cfg(unix)]
387    {
388        use std::os::unix::fs::OpenOptionsExt;
389        options.custom_flags(
390            (rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK).bits() as i32,
391        );
392    }
393    let file = options.open(path).map_err(|error| error.to_string())?;
394    if !file
395        .metadata()
396        .map_err(|error| error.to_string())?
397        .is_file()
398        || std::fs::symlink_metadata(path)
399            .map_err(|error| error.to_string())?
400            .file_type()
401            .is_symlink()
402    {
403        return Err("artifact is not a regular file".into());
404    }
405    let mut file = tokio::fs::File::from_std(file);
406    let mut hash = Sha256::new();
407    let mut total = 0u64;
408    let mut buffer = vec![0u8; 65536];
409    loop {
410        let count = tokio::select! { _=cancel.cancelled()=>return Err("cancelled".into()), result=file.read(&mut buffer)=>result.map_err(|error|error.to_string())? };
411        if count == 0 {
412            break;
413        }
414        total = total
415            .checked_add(count as u64)
416            .ok_or("artifact size overflow")?;
417        hash.update(&buffer[..count]);
418    }
419    Ok((format!("{:x}", hash.finalize()), total))
420}
421impl Acquisition {
422    fn cache_directory(&self, path: &Path) -> Result<(), String> {
423        let relative = path
424            .strip_prefix(&self.root)
425            .map_err(|_| "cache path escaped root")?;
426        let mut current = self.root.clone();
427        private_directory(&current)?;
428        for component in relative.components() {
429            let std::path::Component::Normal(name) = component else {
430                return Err("invalid cache path component".into());
431            };
432            current.push(name);
433            private_directory(&current)?;
434            if !current
435                .canonicalize()
436                .map_err(|error| error.to_string())?
437                .starts_with(&self.root)
438            {
439                return Err("cache path escaped root".into());
440            }
441        }
442        Ok(())
443    }
444    pub fn new(root: impl AsRef<Path>) -> Result<Self, String> {
445        let root = std::path::absolute(root).map_err(|error| error.to_string())?;
446        private_directory(&root)?;
447        #[cfg(unix)]
448        {
449            use std::os::unix::fs::PermissionsExt;
450            std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700))
451                .map_err(|error| error.to_string())?;
452        }
453        Ok(Self {
454            root: root.canonicalize().map_err(|error| error.to_string())?,
455            progress: None,
456        })
457    }
458    pub fn with_progress(
459        mut self,
460        progress: impl Fn(u64, u64, &str) + Send + Sync + 'static,
461    ) -> Self {
462        self.progress = Some(std::sync::Arc::new(progress));
463        self
464    }
465    fn emit(&self, completed: u64, artifact: &Artifact) {
466        if let Some(progress) = &self.progress {
467            progress(completed, artifact.bytes, &artifact.file);
468        }
469    }
470    pub async fn acquire(
471        &self,
472        artifact: &Artifact,
473        transport: &dyn DownloadTransport,
474        cancel: &CancellationToken,
475    ) -> Result<Acquired, String> {
476        self.acquire_sized(artifact, SizePolicy::Exact, transport, cancel)
477            .await
478    }
479    pub async fn acquire_sized(
480        &self,
481        artifact: &Artifact,
482        size: SizePolicy,
483        transport: &dyn DownloadTransport,
484        cancel: &CancellationToken,
485    ) -> Result<Acquired, String> {
486        let operation = async {
487            artifact.validate()?;
488            let coordinates: Vec<_> = artifact.repo.split('/').collect();
489            let owner = self.root.join(&artifact.backend).join(coordinates[0]);
490            self.cache_directory(&owner)?;
491            let repository = owner.join(format!("{}@{}", coordinates[1], artifact.revision));
492            let lock = ArtifactLock::acquire(suffix(&repository, ".repository.lock"))?;
493            let acquired = self
494                .acquire_inner(artifact, size, transport, cancel)
495                .await?;
496            lock.check()?;
497            Ok(acquired)
498        };
499        tokio::select! {biased;_=cancel.cancelled()=>Err("cancelled".into()),result=tokio::time::timeout(Duration::from_secs(1800),operation)=>result.map_err(|_|"acquisition timed out".to_owned())?}
500    }
501    async fn acquire_inner(
502        &self,
503        artifact: &Artifact,
504        size: SizePolicy,
505        transport: &dyn DownloadTransport,
506        cancel: &CancellationToken,
507    ) -> Result<Acquired, String> {
508        artifact.validate()?;
509        if cancel.is_cancelled() {
510            return Err("cancelled".into());
511        }
512        let coordinates: Vec<_> = artifact.repo.split('/').collect();
513        let directory = self
514            .root
515            .join(&artifact.backend)
516            .join(coordinates[0])
517            .join(format!("{}@{}", coordinates[1], artifact.revision));
518        let target = directory.join(&artifact.file);
519        let parent = target.parent().ok_or("missing artifact parent")?;
520        self.cache_directory(parent)?;
521        if !parent
522            .canonicalize()
523            .map_err(|error| error.to_string())?
524            .starts_with(&self.root)
525        {
526            return Err("cache escaped root".into());
527        }
528        let lock = ArtifactLock::acquire(suffix(&target, ".lock"))?;
529        cleanup_partials(parent, crate::state::process_alive)?;
530        self.emit(0, artifact);
531        if let Ok(metadata) = std::fs::symlink_metadata(&target) {
532            if !metadata.is_file() || metadata.file_type().is_symlink() {
533                return Err("unsafe cached artifact".into());
534            }
535            let (sha, bytes) = hash_file(&target, cancel).await?;
536            if sha.eq_ignore_ascii_case(&artifact.sha256) && size.accepts(bytes, artifact.bytes) {
537                lock.check()?;
538                self.emit(bytes, artifact);
539                return Ok(Acquired {
540                    path: target,
541                    bytes,
542                    cached: true,
543                });
544            }
545        }
546        let mut url =
547            url::Url::parse("https://huggingface.co").map_err(|error| error.to_string())?;
548        {
549            let mut path = url.path_segments_mut().map_err(|_| "invalid URL base")?;
550            path.extend(coordinates)
551                .push("resolve")
552                .push(&artifact.revision)
553                .extend(artifact.file.split('/'));
554        }
555        url.set_query(Some("download=true"));
556        let operation = async {
557            let mut response = transport.get(url.as_str()).await?;
558            if !(200..300).contains(&response.status) {
559                return Err(format!("download HTTP {}", response.status));
560            }
561            if response
562                .commit
563                .as_ref()
564                .is_none_or(|commit| !commit.eq_ignore_ascii_case(&artifact.revision))
565            {
566                return Err("resolved commit mismatch".into());
567            }
568            if response
569                .length
570                .is_some_and(|length| length > artifact.bytes)
571            {
572                return Err("download exceeds byte limit".into());
573            }
574            let temporary = tempfile::Builder::new()
575                .prefix(&format!(".llmup-download.{}.", std::process::id()))
576                .suffix(".part")
577                .tempfile_in(parent)
578                .map_err(|error| error.to_string())?;
579            let mut output =
580                tokio::fs::File::from_std(temporary.reopen().map_err(|error| error.to_string())?);
581            let mut hash = Sha256::new();
582            let mut total = 0u64;
583            let mut reported = 0u64;
584            let mut buffer = vec![0u8; 65536];
585            loop {
586                let count = response
587                    .body
588                    .read(&mut buffer)
589                    .await
590                    .map_err(|error| error.to_string())?;
591                if count == 0 {
592                    break;
593                }
594                total = total
595                    .checked_add(count as u64)
596                    .ok_or("download size overflow")?;
597                if total > artifact.bytes {
598                    return Err("download exceeds byte limit".into());
599                }
600                hash.update(&buffer[..count]);
601                output
602                    .write_all(&buffer[..count])
603                    .await
604                    .map_err(|error| error.to_string())?;
605                if total - reported >= 8 * 1024 * 1024 {
606                    self.emit(total, artifact);
607                    reported = total;
608                }
609            }
610            if !size.accepts(total, artifact.bytes)
611                || !format!("{:x}", hash.finalize()).eq_ignore_ascii_case(&artifact.sha256)
612            {
613                return Err("artifact integrity mismatch".into());
614            }
615            output.sync_all().await.map_err(|error| error.to_string())?;
616            drop(output);
617            lock.check()?;
618            if cancel.is_cancelled() {
619                return Err("cancelled".into());
620            }
621            temporary
622                .persist(&target)
623                .map_err(|error| error.to_string())?;
624            self.emit(total, artifact);
625            Ok(Acquired {
626                path: target.clone(),
627                bytes: total,
628                cached: false,
629            })
630        };
631        tokio::select! { _=cancel.cancelled()=>Err("cancelled".into()), result=tokio::time::timeout(Duration::from_secs(1800),operation)=>result.map_err(|_|"download timed out".to_owned())? }
632    }
633    pub async fn repository(
634        &self,
635        artifacts: &[Artifact],
636        transport: &dyn DownloadTransport,
637        cancel: &CancellationToken,
638    ) -> Result<PathBuf, String> {
639        tokio::select! {biased;_=cancel.cancelled()=>Err("cancelled".into()),result=tokio::time::timeout(Duration::from_secs(1800),self.repository_inner(artifacts,transport,cancel))=>result.map_err(|_|"repository acquisition timed out".to_owned())?}
640    }
641    async fn repository_inner(
642        &self,
643        artifacts: &[Artifact],
644        transport: &dyn DownloadTransport,
645        cancel: &CancellationToken,
646    ) -> Result<PathBuf, String> {
647        let first = artifacts.first().ok_or("empty repository manifest")?;
648        if artifacts.len() > 256 {
649            return Err("repository file count exceeds limit".into());
650        }
651        let mut names = HashSet::new();
652        let mut root = None;
653        for artifact in artifacts {
654            artifact.validate()?;
655            if ["py", "pyc", "pyo", "so", "dylib", "dll", "bundle"]
656                .iter()
657                .any(|extension| {
658                    artifact
659                        .file
660                        .to_ascii_lowercase()
661                        .ends_with(&format!(".{extension}"))
662                })
663            {
664                return Err("executable repository artifact forbidden".into());
665            }
666            if artifact.repo != first.repo
667                || artifact.revision != first.revision
668                || artifact.backend != first.backend
669                || !names.insert(artifact.file.clone())
670            {
671                return Err("inconsistent repository manifest".into());
672            }
673        }
674        let folded: HashSet<_> = names.iter().map(|name| name.to_lowercase()).collect();
675        if folded.len() != names.len()
676            || folded.iter().any(|name| {
677                name.match_indices('/')
678                    .any(|(index, _)| folded.contains(&name[..index]))
679            })
680        {
681            return Err("repository contains path aliases or file/directory collisions".into());
682        }
683        if first.backend == "mlx"
684            && (artifacts.len() < 3
685                || !names.contains("config.json")
686                || !names.contains("tokenizer_config.json")
687                || !names.iter().any(|name| name.ends_with(".safetensors")))
688        {
689            return Err("incomplete MLX repository manifest".into());
690        }
691        let total = artifacts
692            .iter()
693            .try_fold(0u64, |total, artifact| total.checked_add(artifact.bytes))
694            .ok_or("repository byte total overflow")?;
695        if total > 9007199254740991 {
696            return Err("repository byte total exceeds safe integer".into());
697        }
698        let coordinates: Vec<_> = first.repo.split('/').collect();
699        let owner = self.root.join(&first.backend).join(coordinates[0]);
700        self.cache_directory(&owner)?;
701        let repository = owner.join(format!("{}@{}", coordinates[1], first.revision));
702        let lock = ArtifactLock::acquire(suffix(&repository, ".repository.lock"))?;
703        for artifact in artifacts {
704            let acquired = self
705                .acquire_inner(artifact, SizePolicy::Exact, transport, cancel)
706                .await?;
707            let mut directory = acquired.path;
708            for _ in artifact.file.split('/') {
709                directory.pop();
710            }
711            if root.as_ref().is_some_and(|prior| prior != &directory) {
712                return Err("repository root mismatch".into());
713            }
714            root = Some(directory);
715        }
716        let root = root.ok_or("missing repository root")?;
717        fn list(root: &Path, path: &Path, files: &mut HashSet<String>) -> Result<(), String> {
718            for entry in std::fs::read_dir(path).map_err(|error| error.to_string())? {
719                let entry = entry.map_err(|error| error.to_string())?;
720                let kind = entry.file_type().map_err(|error| error.to_string())?;
721                if kind.is_symlink() {
722                    return Err("symlink in repository".into());
723                }
724                if kind.is_dir() {
725                    list(root, &entry.path(), files)?;
726                } else if kind.is_file() {
727                    files.insert(
728                        entry
729                            .path()
730                            .strip_prefix(root)
731                            .map_err(|error| error.to_string())?
732                            .to_string_lossy()
733                            .replace('\\', "/"),
734                    );
735                } else {
736                    return Err("special file in repository".into());
737                }
738            }
739            Ok(())
740        }
741        let mut actual = HashSet::new();
742        list(&root, &root, &mut actual)?;
743        if actual != names {
744            return Err("repository content differs from manifest".into());
745        }
746        lock.check()?;
747        Ok(root)
748    }
749}