phora 0.1.2

A git-based artifact package manager and multiplexer for content-addressed file distribution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
//! Mode-aware source routing: dispatches each `SourceBackend` call to the git or
//! http adapter by the source's declared mode.

use std::collections::BTreeMap;
use std::path::Path;

use crate::config::{Refspec, SourceMode};
use crate::kernel::SourceName;
use crate::source::{ExportRequest, ExportResult, SourceBackend, SourceError, TreeEntry};

type Result<T> = std::result::Result<T, SourceError>;

/// Routes each `SourceBackend` call to `git` or `http` by the source's declared
/// mode, looked up by name. An unmapped name defaults to the git backend.
// not sealed: single binary, in-crate test doubles need to impl SourceBackend.
pub struct RouterBackend<G, H> {
    git: G,
    http: H,
    modes: BTreeMap<SourceName, SourceMode>,
}

impl<G, H> RouterBackend<G, H> {
    pub fn new(git: G, http: H, modes: BTreeMap<SourceName, SourceMode>) -> Self {
        Self { git, http, modes }
    }

    fn is_url(&self, source: &SourceName) -> bool {
        matches!(self.modes.get(source), Some(SourceMode::Url))
    }
}

impl<G: SourceBackend, H: SourceBackend> RouterBackend<G, H> {
    fn route(&self, source: &SourceName) -> &dyn SourceBackend {
        if self.is_url(source) {
            &self.http
        } else {
            &self.git
        }
    }
}

impl<G: SourceBackend, H: SourceBackend> SourceBackend for RouterBackend<G, H> {
    fn read_file_at(
        &self,
        source: &SourceName,
        url: &str,
        commit: &str,
        path: &Path,
    ) -> Result<Vec<u8>> {
        self.git.read_file_at(source, url, commit, path)
    }

    fn list_tree_at(
        &self,
        source: &SourceName,
        url: &str,
        commit: &str,
        path: &Path,
    ) -> Result<Vec<TreeEntry>> {
        self.git.list_tree_at(source, url, commit, path)
    }

    fn fetch(&self, source: &SourceName, url: &str) -> Result<()> {
        self.route(source).fetch(source, url)
    }

    fn mirror_ready(&self, url: &str) -> bool {
        self.git.mirror_ready(url)
    }

    fn list_source_leaves(
        &self,
        source: &SourceName,
        url: &str,
        commit: &str,
        root: Option<&Path>,
    ) -> Result<Vec<String>> {
        self.route(source)
            .list_source_leaves(source, url, commit, root)
    }

    fn resolve(&self, source: &SourceName, url: &str, refspec: &Refspec) -> Result<String> {
        self.route(source).resolve(source, url, refspec)
    }

    fn commit_time(&self, source: &SourceName, url: &str, commit: &str) -> Result<u64> {
        self.route(source).commit_time(source, url, commit)
    }

    fn export_artifact(&self, req: &ExportRequest<'_>) -> Result<ExportResult> {
        self.route(req.source).export_artifact(req)
    }

    fn compute_digest(
        &self,
        source: &SourceName,
        url: &str,
        commit: &str,
        root: Option<&Path>,
        include: &[String],
        exclude: &[String],
    ) -> Result<String> {
        self.route(source)
            .compute_digest(source, url, commit, root, include, exclude)
    }
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;
    use std::collections::BTreeMap;
    use std::io::{Read, Write};
    use std::net::{TcpListener, TcpStream};
    use std::path::Path;
    use std::process::Command;
    use std::rc::Rc;
    use std::time::Duration;

    use tempfile::TempDir;

    use crate::config::{Refspec, SourceMode};
    use crate::kernel::SourceName;
    use crate::source::{
        ExportRequest, ExportResult, GitBackend, HttpBackend, RouterBackend, SourceBackend,
        SourceError, TreeEntry,
    };

    type Result<T> = std::result::Result<T, SourceError>;

    fn sn(name: &str) -> SourceName {
        SourceName::trusted(name)
    }

    // ── local http server serving a real .tar.gz ───────────────────

    const HELLO_BODY: &[u8] = b"hi";

    struct TarServer {
        port: u16,
    }

    impl TarServer {
        fn spawn(body: Vec<u8>) -> Self {
            let listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
            let port = listener.local_addr().expect("local addr").port();
            std::thread::spawn(move || {
                if let Ok((stream, _)) = listener.accept() {
                    Self::serve(stream, &body);
                }
            });
            Self { port }
        }

        fn serve(mut stream: TcpStream, body: &[u8]) {
            let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
            let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
            let mut buf = [0u8; 1024];
            let _ = stream.read(&mut buf);
            let header = format!(
                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
                body.len()
            );
            let _ = stream.write_all(header.as_bytes());
            let _ = stream.write_all(body);
            let _ = stream.flush();
        }

        fn url(&self) -> String {
            format!("http://127.0.0.1:{}/pkg-1.0.tar.gz", self.port)
        }
    }

    fn build_pkg_tar_gz() -> Vec<u8> {
        let mut header = tar::Header::new_gnu();
        header.set_size(HELLO_BODY.len() as u64);
        header.set_mode(0o644);
        header.set_entry_type(tar::EntryType::Regular);
        header.set_cksum();

        let mut builder = tar::Builder::new(Vec::new());
        builder
            .append_data(&mut header, "pkg-1.0/hello.txt", HELLO_BODY)
            .expect("append tar entry");
        let tar_bytes = builder.into_inner().expect("finish tar");

        let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
        encoder.write_all(&tar_bytes).expect("gzip tar bytes");
        encoder.finish().expect("finish gzip")
    }

    // ── local git mirror (the GitBackend-test way) ─────────────────

    #[expect(
        clippy::unwrap_used,
        reason = "fixture setup fails loudly; git CLI is assumed present"
    )]
    fn run_git(cwd: &Path, args: &[&str]) {
        crate::store::assert_git_sandboxed(cwd);
        let _serial = crate::store::guard_git_fork();
        let out = Command::new("git")
            .args(args)
            .current_dir(cwd)
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .env("GIT_CONFIG_NOSYSTEM", "1")
            .env("GIT_AUTHOR_DATE", "@1700000000 +0000")
            .env("GIT_COMMITTER_DATE", "@1700000000 +0000")
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git {args:?} failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    #[expect(
        clippy::unwrap_used,
        reason = "fixture setup fails loudly; git CLI is assumed present"
    )]
    fn build_git_repo() -> (TempDir, String, String) {
        let src = TempDir::new().unwrap();
        let p = src.path();
        run_git(p, &["init", "-b", "main", "."]);
        run_git(p, &["config", "user.email", "test@example.com"]);
        run_git(p, &["config", "user.name", "Test"]);
        std::fs::write(p.join("README.md"), b"hello\n").unwrap();
        run_git(p, &["add", "-A"]);
        run_git(p, &["commit", "-m", "initial"]);
        let head = {
            let _serial = crate::store::guard_git_fork();
            let out = Command::new("git")
                .args(["rev-parse", "HEAD"])
                .current_dir(p)
                .output()
                .unwrap();
            String::from_utf8(out.stdout).unwrap().trim().to_string()
        };
        let url = p.to_string_lossy().into_owned();
        (src, url, head)
    }

    // ── behavioral dispatch: real git + real http through the router ──

    #[test]
    fn router_resolves_url_source_via_http_and_git_source_via_git() {
        let (_git_src, g_url, g_head) = build_git_repo();
        let server = TarServer::spawn(build_pkg_tar_gz());
        let u_url = server.url();

        let git_dir = TempDir::new().expect("git_dir tempdir");
        let git = GitBackend::new(git_dir.path().to_path_buf());
        let http = HttpBackend::new(git_dir.path().to_path_buf(), BTreeMap::new());

        let mut modes = BTreeMap::new();
        modes.insert(sn("g"), SourceMode::Git);
        modes.insert(sn("u"), SourceMode::Url);
        let router = RouterBackend::new(git, http, modes);

        router
            .fetch(&sn("g"), &g_url)
            .expect("router fetches git source");
        router
            .fetch(&sn("u"), &u_url)
            .expect("router fetches url source");

        // url source resolved with a bogus git ref: only succeeds if routed to Http
        // (which ignores the refspec and reads refs/heads/phora).
        let u_commit = router
            .resolve(&sn("u"), &u_url, &Refspec::Branch("main".into()))
            .expect("url source must route to Http and resolve despite a git-style refspec");
        assert_eq!(u_commit.len(), 40, "synthetic phora commit is 40-hex");

        // git source resolved with Refspec::None would fail on Http; routing to Git
        // with Branch(main) is what makes it succeed and match the real head.
        let g_commit = router
            .resolve(&sn("g"), &g_url, &Refspec::Branch("main".into()))
            .expect("git source must route to Git and resolve branch main");
        assert_eq!(
            g_commit, g_head,
            "the git source must resolve to its real HEAD commit, proving it was routed to Git"
        );
        assert_ne!(
            u_commit, g_commit,
            "the two sources resolve to distinct commits, ruling out cross-routing"
        );
    }

    #[test]
    fn router_misrouting_would_fail_url_source_through_git() {
        // A url source sent to the Git backend with a Branch refspec must error:
        // the synthetic mirror has no refs/heads/main, only refs/heads/phora.
        let server = TarServer::spawn(build_pkg_tar_gz());
        let u_url = server.url();
        let git_dir = TempDir::new().expect("git_dir tempdir");

        let http = HttpBackend::new(git_dir.path().to_path_buf(), BTreeMap::new());
        http.fetch(&sn("u"), &u_url)
            .expect("import synthetic mirror");

        let git = GitBackend::new(git_dir.path().to_path_buf());
        assert!(
            git.resolve(&sn("u"), &u_url, &Refspec::Branch("main".into()))
                .is_err(),
            "a url source mis-sent to Git with Branch(main) must fail: there is no such branch, \
             only refs/heads/phora. This is why dispatch-on-mode (not url-scheme) is load-bearing."
        );
    }

    // ── spy dispatch: pins routing on name/mode, not url scheme ──────

    #[derive(Default, Clone)]
    struct Spy {
        fetches: Rc<RefCell<Vec<String>>>,
        resolves: Rc<RefCell<Vec<String>>>,
        digests: Rc<RefCell<Vec<String>>>,
        leaf_walks: Rc<RefCell<Vec<String>>>,
        tree_lists: Rc<RefCell<Vec<String>>>,
    }

    impl SourceBackend for Spy {
        fn fetch(&self, source: &SourceName, _url: &str) -> Result<()> {
            self.fetches.borrow_mut().push(source.to_string());
            Ok(())
        }

        fn list_source_leaves(
            &self,
            source: &SourceName,
            _url: &str,
            _commit: &str,
            _root: Option<&Path>,
        ) -> Result<Vec<String>> {
            self.leaf_walks.borrow_mut().push(source.to_string());
            Ok(vec![format!("leaf-{source}")])
        }

        fn list_tree_at(
            &self,
            source: &SourceName,
            _url: &str,
            _commit: &str,
            _path: &Path,
        ) -> Result<Vec<TreeEntry>> {
            self.tree_lists.borrow_mut().push(source.to_string());
            Ok(vec![TreeEntry {
                name: format!("entry-{source}"),
                is_dir: false,
            }])
        }

        fn resolve(&self, source: &SourceName, _url: &str, _refspec: &Refspec) -> Result<String> {
            self.resolves.borrow_mut().push(source.to_string());
            Ok(format!("resolved-{source}"))
        }

        fn commit_time(&self, _source: &SourceName, _url: &str, _commit: &str) -> Result<u64> {
            Ok(0)
        }

        fn export_artifact(&self, _req: &ExportRequest<'_>) -> Result<ExportResult> {
            Err(SourceError::Source("spy export".into()))
        }

        fn compute_digest(
            &self,
            source: &SourceName,
            _url: &str,
            _commit: &str,
            _root: Option<&Path>,
            _include: &[String],
            _exclude: &[String],
        ) -> Result<String> {
            self.digests.borrow_mut().push(source.to_string());
            Ok("blake3:spy".into())
        }
    }

    // git and http share recorded state with their in-router twins via Rc.
    fn spy_router(modes: BTreeMap<SourceName, SourceMode>) -> (RouterBackend<Spy, Spy>, Spy, Spy) {
        let git = Spy::default();
        let http = Spy::default();
        let router = RouterBackend::new(git.clone(), http.clone(), modes);
        (router, git, http)
    }

    #[test]
    fn dispatch_sends_url_mode_to_http_and_git_mode_to_git_by_name() {
        let mut modes = BTreeMap::new();
        modes.insert(sn("g"), SourceMode::Git);
        modes.insert(sn("u"), SourceMode::Url);
        let (router, git, http) = spy_router(modes);

        router
            .fetch(&sn("g"), "https://example.com/o/r.git")
            .expect("git fetch");
        router
            .fetch(&sn("u"), "https://example.com/pkg.tar.gz")
            .expect("url fetch");
        router
            .resolve(&sn("u"), "https://example.com/pkg.tar.gz", &Refspec::None)
            .expect("url resolve");
        router
            .resolve(
                &sn("g"),
                "https://example.com/o/r.git",
                &Refspec::Branch("main".into()),
            )
            .expect("git resolve");

        assert_eq!(
            git.fetches.borrow().as_slice(),
            ["g"],
            "only the git-mode source `g` may reach the git backend's fetch"
        );
        assert_eq!(
            http.fetches.borrow().as_slice(),
            ["u"],
            "only the url-mode source `u` may reach the http backend's fetch"
        );
        assert_eq!(
            git.resolves.borrow().as_slice(),
            ["g"],
            "git-mode resolve routes to git"
        );
        assert_eq!(
            http.resolves.borrow().as_slice(),
            ["u"],
            "url-mode resolve routes to http"
        );
    }

    #[test]
    fn list_source_leaves_routes_url_mode_to_http_and_git_mode_to_git() {
        let mut modes = BTreeMap::new();
        modes.insert(sn("g"), SourceMode::Git);
        modes.insert(sn("u"), SourceMode::Url);
        let (router, git, http) = spy_router(modes);

        router
            .list_source_leaves(&sn("g"), "https://example.com/o/r.git", "c", None)
            .expect("git leaf walk");
        router
            .list_source_leaves(&sn("u"), "https://example.com/pkg.tar.gz", "c", None)
            .expect("url leaf walk");

        assert_eq!(
            git.leaf_walks.borrow().as_slice(),
            ["g"],
            "only the git-mode source `g` may reach the git backend's list_source_leaves"
        );
        assert_eq!(
            http.leaf_walks.borrow().as_slice(),
            ["u"],
            "a url-mode source must route its leaf walk to the http backend, not be walked as a git tree"
        );
    }

    #[test]
    fn list_tree_at_always_routes_to_the_git_backend() {
        let mut modes = BTreeMap::new();
        modes.insert(sn("g"), SourceMode::Git);
        modes.insert(sn("u"), SourceMode::Url);
        let (router, git, http) = spy_router(modes);

        router
            .list_tree_at(&sn("g"), "https://example.com/o/r.git", "c", Path::new("d"))
            .expect("git-mode tree listing");
        router
            .list_tree_at(
                &sn("u"),
                "https://example.com/pkg.tar.gz",
                "c",
                Path::new("d"),
            )
            .expect("url-mode tree listing still reaches the git backend");

        assert_eq!(
            git.tree_lists.borrow().as_slice(),
            ["g", "u"],
            "list_tree_at is the git-only trust read path: BOTH sources (regardless of mode) \
             must reach the git backend, never be routed by mode"
        );
        assert!(
            http.tree_lists.borrow().is_empty(),
            "the http backend must never receive a tree listing"
        );
    }

    #[test]
    fn git_url_ending_in_dot_git_routes_to_git_not_http() {
        // Routing must be by declared mode, never by url scheme/suffix. A `.git`
        // url under SourceMode::Git must hit the git backend, never http.
        let mut modes = BTreeMap::new();
        modes.insert(sn("g"), SourceMode::Git);
        let (router, git, http) = spy_router(modes);

        router
            .fetch(&sn("g"), "https://example.com/o/r.git")
            .expect("git fetch");

        assert_eq!(
            git.fetches.borrow().as_slice(),
            ["g"],
            "a `.git` url declared Git-mode must route to the git backend"
        );
        assert!(
            http.fetches.borrow().is_empty(),
            "a `.git` url must NOT reach the http backend regardless of its scheme/suffix"
        );
    }

    #[test]
    fn digest_dispatch_by_mode() {
        let mut modes = BTreeMap::new();
        modes.insert(sn("u"), SourceMode::Url);
        modes.insert(sn("g"), SourceMode::Git);
        let (router, git, http) = spy_router(modes);

        router
            .compute_digest(&sn("u"), "http://x/pkg.tgz", "c", None, &[], &[])
            .expect("url digest");
        router
            .compute_digest(&sn("g"), "https://x/y.git", "c", None, &[], &[])
            .expect("git digest");

        assert!(
            git.fetches.borrow().is_empty() && http.fetches.borrow().is_empty(),
            "digest must not trigger fetch"
        );

        assert_eq!(
            http.digests.borrow().as_slice(),
            ["u"],
            "the url-mode source `u` must reach the http backend's compute_digest"
        );
        assert_eq!(
            git.digests.borrow().as_slice(),
            ["g"],
            "the git-mode source `g` must reach the git backend's compute_digest"
        );
    }

    #[test]
    fn unknown_source_name_has_a_defined_route() {
        // A name absent from the modes map must resolve to the git backend (the
        // default), never panic and never silently hit http.
        let (router, git, http) = spy_router(BTreeMap::new());
        let _ = router.fetch(&sn("mystery"), "https://example.com/o/r.git");
        assert_eq!(
            git.fetches.borrow().as_slice(),
            ["mystery"],
            "a source with no recorded mode must default to the git backend"
        );
        assert!(
            http.fetches.borrow().is_empty(),
            "an unmapped source must never be routed to http"
        );
    }

    #[test]
    fn router_is_usable_as_dyn_source_backend() {
        let mut modes = BTreeMap::new();
        modes.insert(sn("g"), SourceMode::Git);
        let (router, _git, _http) = spy_router(modes);
        let as_dyn: &dyn SourceBackend = &router;
        let result = as_dyn
            .resolve(&sn("g"), "https://x/y.git", &Refspec::Branch("main".into()))
            .expect("router is a SourceBackend so sync(&dyn SourceBackend) keeps working");
        assert_eq!(
            result, "resolved-g",
            "the value must come back through the vtable from the git-routed Spy, \
             pinning runtime dispatch through &dyn SourceBackend rather than mere compilation"
        );
    }
}