steid

@jamesgill /

Rust35.3 KBCode·Blame·History·Raw
1//! Service ports the application layer needs.
2//!
3//! Repository ports live in `domain::repository`; these are the non-persistence
4//! collaborators. Adapters live in `infrastructure`.
5
6use std::{path::PathBuf, pin::Pin};
7
8use tokio::io::AsyncRead;
9
10use crate::domain::{
11 BranchRow, CommitDetail, CommitSummary, DomainError, GitRef, GrepHit, ImportSource, ObjectId,
12 OrgName, PasswordHash, RefName, RepoName, RepoPath, TagRow, TagSummary, TreeEntry,
13};
14
15use super::blame::Blame;
16
17/// Hashes and verifies passwords.
18///
19/// A port rather than a direct Argon2 call so tests can substitute a fast stub —
20/// Argon2 is deliberately slow, and a use case suite that hashes for real takes
21/// seconds per test.
22pub trait PasswordHasher: Send + Sync {
23 /// Hashes a plaintext password.
24 fn hash(&self, plaintext: &str) -> Result<PasswordHash, PasswordError>;
25
26 /// Checks a plaintext password against a stored hash.
27 ///
28 /// Returns `Ok(false)` for a wrong password and `Err` only when the hash itself
29 /// cannot be parsed — a corrupt stored hash is a different problem from a failed
30 /// login, and collapsing them hides real faults.
31 fn verify(&self, plaintext: &str, hash: &PasswordHash) -> Result<bool, PasswordError>;
32}
33
34/// A password could not be hashed or a stored hash could not be parsed.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct PasswordError(String);
37
38impl PasswordError {
39 pub fn new(message: impl Into<String>) -> Self {
40 Self(message.into())
41 }
42}
43
44impl std::fmt::Display for PasswordError {
45 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46 write!(f, "password hashing failed: {}", self.0)
47 }
48}
49
50impl std::error::Error for PasswordError {}
51
52/// Where bare git repositories live on disk.
53///
54/// Laid out as `{data_dir}/{handle}/{name}.git`. Keyed by handle rather than
55/// [`OrgId`](crate::domain::OrgId) so the data directory is legible to anyone who has
56/// to debug it; the cost is that renaming a handle becomes a directory move rather
57/// than a row update.
58///
59/// Deliberately narrow. Serving the git protocol and browsing a tree are separate
60/// concerns with separate shapes — streaming and querying — and get their own ports as
61/// their use cases arrive, rather than accreting here. See
62/// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md).
63pub trait GitStorage: Send + Sync {
64 /// Creates an empty bare repository.
65 ///
66 /// Empty means empty: no initial commit, no branch, matching what GitHub does for
67 /// a repository created without a README.
68 ///
69 /// Fails with [`GitStorageError::AlreadyExists`] rather than adopting whatever is
70 /// already there.
71 fn init_bare(
72 &self,
73 handle: &OrgName,
74 name: &RepoName,
75 ) -> impl Future<Output = Result<(), GitStorageError>> + Send;
76
77 /// Removes a bare repository, succeeding if there was nothing to remove.
78 ///
79 /// This exists to compensate a failed record insert — a repository row and its
80 /// directory cannot share a transaction — not as a user-facing delete. Deleting a
81 /// repository properly is a separate use case with its own authorization.
82 fn remove(
83 &self,
84 handle: &OrgName,
85 name: &RepoName,
86 ) -> impl Future<Output = Result<(), GitStorageError>> + Send;
87
88 /// Moves a bare repository to a new name under the same handle.
89 ///
90 /// The filesystem half of a rename. The record half is
91 /// [`rename_repo`](super::repo::rename_repo)'s, which is also where the two are
92 /// ordered and compensated — this port only moves a directory.
93 ///
94 /// Fails with [`GitStorageError::AlreadyExists`] rather than overwriting whatever
95 /// is at the destination, for the reason [`init_bare`](Self::init_bare) does: with
96 /// no matching record, something already there is an orphan, and adopting it would
97 /// hand somebody else's objects to this repository.
98 fn rename(
99 &self,
100 handle: &OrgName,
101 from: &RepoName,
102 to: &RepoName,
103 ) -> impl Future<Output = Result<(), GitStorageError>> + Send;
104
105 /// Points `HEAD` at a branch, making it the repository's default.
106 ///
107 /// **There is no column for this.** git already holds the answer in the bare
108 /// repository's `HEAD`, every read goes through
109 /// [`default_branch`](GitQuery::default_branch), and a copy in the database would
110 /// be a second answer that can disagree with the first — including with whatever a
111 /// push did.
112 ///
113 /// A write rather than a query, which is why it is here and not on [`GitQuery`]:
114 /// that port's whole contract is reading.
115 ///
116 /// Says nothing about whether the branch exists. Checking that is the use case's
117 /// job, because it is a rule about what an owner may choose rather than a fact
118 /// about the filesystem.
119 fn set_default_branch(
120 &self,
121 handle: &OrgName,
122 name: &RepoName,
123 branch: &RefName,
124 ) -> impl Future<Output = Result<(), GitStorageError>> + Send;
125
126 /// Where a repository lives.
127 ///
128 /// Pure, and says nothing about whether anything exists there. Milestone 4 hands
129 /// this to `git http-backend`.
130 fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf;
131}
132
133/// A repository could not be created or removed on disk.
134#[derive(Debug)]
135pub enum GitStorageError {
136 /// Something already occupies the repository's path.
137 ///
138 /// Kept distinct from a general failure because it is the one case a use case can
139 /// explain to a user, and because with no matching record it means an orphaned
140 /// directory left by a crashed create.
141 AlreadyExists,
142 /// The filesystem or the `git` binary failed.
143 Backend(Box<dyn std::error::Error + Send + Sync>),
144}
145
146impl GitStorageError {
147 pub fn backend(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
148 Self::Backend(error.into())
149 }
150}
151
152impl std::fmt::Display for GitStorageError {
153 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154 match self {
155 Self::AlreadyExists => f.write_str("a repository already exists at that path"),
156 Self::Backend(error) => write!(f, "git storage failure: {error}"),
157 }
158 }
159}
160
161impl std::error::Error for GitStorageError {
162 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
163 match self {
164 Self::AlreadyExists => None,
165 Self::Backend(error) => Some(&**error),
166 }
167 }
168}
169
170/// A stream of bytes, in either direction.
171///
172/// Pack data is arbitrarily large and must never be collected into memory — a clone of
173/// a large repository would otherwise be bounded by RAM rather than by disk. Boxed
174/// rather than generic so the port stays object-safe in shape and the adapter can hand
175/// back a subprocess's stdout directly.
176pub type ByteStream = Pin<Box<dyn AsyncRead + Send>>;
177
178/// Which HTTP method a git request uses.
179///
180/// Only these two exist in the smart protocol: the advertisement is a `GET`, the
181/// negotiation and pack transfer are `POST`s.
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183pub enum GitMethod {
184 Get,
185 Post,
186}
187
188impl GitMethod {
189 pub fn as_str(self) -> &'static str {
190 match self {
191 Self::Get => "GET",
192 Self::Post => "POST",
193 }
194 }
195}
196
197/// A request to the git protocol, in the shape `git http-backend` wants it.
198///
199/// CGI-shaped rather than one method per operation, because the backend is a CGI —
200/// see the amendment to
201/// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md). **Every field
202/// here is constructed by the use case**, not forwarded from a URL: `path_info` and
203/// `query` in particular are built from an already-validated handle and repository
204/// name, so the transport cannot ask for a path the use case did not authorize.
205pub struct GitRequest {
206 pub method: GitMethod,
207 /// The repository path relative to the project root, e.g. `/acme/steid.git/info/refs`.
208 pub path_info: String,
209 /// The CGI query string, e.g. `service=git-upload-pack`. Empty for an RPC POST.
210 pub query: String,
211 pub content_type: Option<String>,
212 /// The client's `Content-Encoding`. Real clients gzip this body once a repository
213 /// has more than a handful of refs, and the backend inflates it for us — but only
214 /// when it arrives as `HTTP_CONTENT_ENCODING`, which is the adapter's job.
215 pub content_encoding: Option<String>,
216 pub content_length: Option<String>,
217 /// The client's `Git-Protocol`, carrying `version=2` for any modern client.
218 /// Dropping it silently downgrades the exchange to v0 rather than failing.
219 pub git_protocol: Option<String>,
220 /// Whether the backend may run `receive-pack` at all.
221 ///
222 /// `git http-backend` refuses pushes unless `http.receivepack` says otherwise, and
223 /// this is what sets it. The use case turns it on **only after** authorizing the
224 /// write, so git stays a second refusal behind Steid's own rather than being
225 /// switched off wholesale. If the authorization logic is ever wrong, this is what
226 /// still says no.
227 pub allow_receive_pack: bool,
228 /// The pusher's handle, for `REMOTE_USER`.
229 ///
230 /// git puts it in the repository's reflog, so `git reflog show main` on the bare
231 /// repository names who moved a ref rather than saying only that it moved. Steid
232 /// knows the actor by the time the backend is spawned; this is that fact reaching
233 /// the place it is recorded.
234 ///
235 /// `None` for a read, which has nothing to attribute.
236 pub remote_user: Option<String>,
237 pub body: ByteStream,
238}
239
240/// What the git protocol answered.
241///
242/// The status is CGI's, not the framework's: `git http-backend` reports failure with a
243/// `Status:` header and no status at all when it succeeded, so absence means 200 and
244/// the adapter translates it.
245pub struct GitResponse {
246 pub status: u16,
247 pub headers: Vec<(String, String)>,
248 pub body: ByteStream,
249}
250
251/// Written by hand because a body is a stream: it cannot be formatted without being
252/// consumed, and a `Debug` that drains the response would be a trap.
253impl std::fmt::Debug for GitRequest {
254 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
255 f.debug_struct("GitRequest")
256 .field("method", &self.method)
257 .field("path_info", &self.path_info)
258 .field("query", &self.query)
259 .field("content_type", &self.content_type)
260 .field("content_encoding", &self.content_encoding)
261 .field("content_length", &self.content_length)
262 .field("git_protocol", &self.git_protocol)
263 .field("allow_receive_pack", &self.allow_receive_pack)
264 .field("remote_user", &self.remote_user)
265 .finish_non_exhaustive()
266 }
267}
268
269impl std::fmt::Debug for GitResponse {
270 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
271 f.debug_struct("GitResponse")
272 .field("status", &self.status)
273 .field("headers", &self.headers)
274 .finish_non_exhaustive()
275 }
276}
277
278/// Serves the git smart-HTTP protocol for one repository.
279///
280/// Says nothing about who may do this. Authorization is settled before a request ever
281/// reaches here — by the time the backend is running, refusing is no longer possible.
282pub trait GitProtocolServer: Send + Sync {
283 fn serve(
284 &self,
285 request: GitRequest,
286 ) -> impl Future<Output = Result<GitResponse, GitProtocolError>> + Send;
287}
288
289/// The git protocol could not be served.
290///
291/// Deliberately without a `NotFound`: a missing repository is something the backend
292/// reports in its own response, and the use case has already refused anything the
293/// viewer may not see.
294#[derive(Debug)]
295pub struct GitProtocolError(Box<dyn std::error::Error + Send + Sync>);
296
297impl GitProtocolError {
298 pub fn new(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
299 Self(error.into())
300 }
301}
302
303impl std::fmt::Display for GitProtocolError {
304 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
305 write!(f, "git protocol failure: {}", self.0)
306 }
307}
308
309impl std::error::Error for GitProtocolError {
310 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
311 Some(&*self.0)
312 }
313}
314
315/// One outbound webhook request.
316///
317/// Built entirely by the use case — the URL comes from a validated
318/// [`WebhookUrl`](crate::domain::WebhookUrl), the body is what was signed, and the
319/// headers are the ones Steid promises. The adapter dials it and reports what happened;
320/// it decides nothing.
321#[derive(Debug, Clone, PartialEq, Eq)]
322pub struct WebhookRequest {
323 pub url: String,
324 pub headers: Vec<(String, String)>,
325 pub body: Vec<u8>,
326}
327
328/// What one attempt did.
329///
330/// Not a `Result`: a refused connection is an *outcome* to be recorded, not an error to
331/// be propagated. The delivery row is the product either way, and a port that could fail
332/// would put the caller in the business of deciding which failures are worth a row.
333#[derive(Debug, Clone, PartialEq, Eq)]
334pub struct WebhookOutcome {
335 /// `None` when there was never a status: DNS, a refused connection, TLS, the
336 /// timeout, or a URL the adapter refused to dial at all.
337 pub status: Option<u16>,
338 /// The start of the response body, or the reason there wasn't one. Capped again by
339 /// the domain before it is stored.
340 pub body: String,
341 pub duration: std::time::Duration,
342}
343
344/// Delivers one webhook request.
345///
346/// A port because the alternative is a use case that cannot be tested without a
347/// listening socket — and because "what Steid will connect to" is a rule worth having
348/// one implementation of.
349pub trait WebhookSender: Send + Sync {
350 fn send(&self, request: WebhookRequest) -> impl Future<Output = WebhookOutcome> + Send;
351}
352
353/// A blob, as far as the port will carry it.
354///
355/// `content` is `None` when the blob is larger than the caller's limit: the size is
356/// still reported, so a page can say how big the thing it will not show is. Reading it
357/// anyway would let one URL pull an arbitrarily large file into memory.
358#[derive(Debug, Clone, PartialEq, Eq)]
359pub struct Blob {
360 pub id: ObjectId,
361 pub size: u64,
362 pub content: Option<Vec<u8>>,
363}
364
365/// Reading what is inside a repository.
366///
367/// The third of the three git families named in
368/// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md), arriving with
369/// its use case as that ADR requires. Every method takes a handle and a repository name
370/// rather than a path, matching [`GitStorage`] — where a repository lives is the
371/// adapter's business.
372///
373/// **Bytes are capped, never streamed.** Unlike the protocol, a browse request has a
374/// person waiting on a rendered page, so a bounded read is the right shape.
375///
376/// `Ok(None)` throughout means "no such thing in this repository" — an unknown
377/// revision, a path that is not there. It is not an authorization answer; that is
378/// settled before this port is reached.
379pub trait GitQuery: Send + Sync {
380 /// The repository's default branch, or `None` if it has no commits yet.
381 ///
382 /// Separate from resolving a revision because an empty repository has a `HEAD` that
383 /// names a branch which does not exist, and telling those apart is the difference
384 /// between "nothing pushed yet" and a 404.
385 fn default_branch(
386 &self,
387 handle: &OrgName,
388 name: &RepoName,
389 ) -> impl Future<Output = Result<Option<RefName>, GitQueryError>> + Send;
390
391 /// Resolves a revision to the commit it names.
392 fn resolve(
393 &self,
394 handle: &OrgName,
395 name: &RepoName,
396 rev: &RefName,
397 ) -> impl Future<Output = Result<Option<ObjectId>, GitQueryError>> + Send;
398
399 /// Lists a directory, unsorted — ordering is [`TreeEntry::ordering_key`]'s job.
400 ///
401 /// `Ok(None)` for a path that is not a directory in this revision, which includes a
402 /// path that is a file.
403 fn list_tree(
404 &self,
405 handle: &OrgName,
406 name: &RepoName,
407 rev: &RefName,
408 path: &RepoPath,
409 ) -> impl Future<Output = Result<Option<Vec<TreeEntry>>, GitQueryError>> + Send;
410
411 /// Reads a file, up to `max_bytes`.
412 ///
413 /// `Ok(None)` for a path that is not a file in this revision.
414 fn read_blob(
415 &self,
416 handle: &OrgName,
417 name: &RepoName,
418 rev: &RefName,
419 path: &RepoPath,
420 max_bytes: u64,
421 ) -> impl Future<Output = Result<Option<Blob>, GitQueryError>> + Send;
422
423 /// The most recent commits reachable from a revision, newest first.
424 fn log(
425 &self,
426 handle: &OrgName,
427 name: &RepoName,
428 rev: &RefName,
429 limit: usize,
430 ) -> impl Future<Output = Result<Vec<CommitSummary>, GitQueryError>> + Send;
431
432 /// Every branch and every tag, unordered.
433 ///
434 /// Ordering is the use case's decision, the same way it is for
435 /// [`list_tree`](Self::list_tree) — an adapter that sorted would have to be
436 /// re-taught the order every time it changed.
437 ///
438 /// **This costs a whole `git` process** — ~14ms, the most expensive of the read
439 /// commands measured for the Milestone 5 amendment to
440 /// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md), because
441 /// starting the process is the cost. A page that does not show a ref switcher must
442 /// not call it.
443 ///
444 /// An empty repository has no refs and answers with an empty list rather than an
445 /// error: nothing pushed yet is not a failure.
446 fn list_refs(
447 &self,
448 handle: &OrgName,
449 name: &RepoName,
450 ) -> impl Future<Output = Result<Vec<GitRef>, GitQueryError>> + Send;
451
452 /// How many commits are reachable from a revision.
453 ///
454 /// The number a repository page states about itself. A revision that resolves to
455 /// nothing — an empty repository, a branch that is not there — counts `0` rather
456 /// than failing, matching [`log`](Self::log): a page asking how big a repository is
457 /// does not want an error for the answer "nothing yet".
458 fn count_commits(
459 &self,
460 handle: &OrgName,
461 name: &RepoName,
462 rev: &RefName,
463 ) -> impl Future<Output = Result<u64, GitQueryError>> + Send;
464
465 /// The most recently created tag, or `None` if the repository has none.
466 ///
467 /// "Most recent" is by creation date, not by name: version numbers do not sort
468 /// chronologically once there is a `v1.10` beside a `v1.9`, and a repository's own
469 /// history is the only ordering that is always right.
470 ///
471 /// One `git` process, the same cost as [`list_refs`](Self::list_refs). Asked
472 /// separately rather than derived from that list because the ordering needs git's
473 /// `creatordate`, which the ref list deliberately does not carry.
474 fn latest_tag(
475 &self,
476 handle: &OrgName,
477 name: &RepoName,
478 ) -> impl Future<Output = Result<Option<TagSummary>, GitQueryError>> + Send;
479
480 /// One commit, in full.
481 ///
482 /// `Ok(None)` for a revision that names nothing, and for one that names something
483 /// which is not a commit — a tree or a blob addressed by its own id. A commit page
484 /// has nothing to show for either, so both are the same 404.
485 ///
486 /// **Two `git` processes**: the revision is resolved before it is read, for the
487 /// reason [`count_commits`](Self::count_commits) resolves first. The resolved
488 /// [`ObjectId`] comes back on the answer, so a caller that goes on to ask for a
489 /// diff does not pay to resolve it again.
490 fn commit(
491 &self,
492 handle: &OrgName,
493 name: &RepoName,
494 rev: &RefName,
495 ) -> impl Future<Output = Result<Option<CommitDetail>, GitQueryError>> + Send;
496
497 /// The patch between two commits, as git writes it.
498 ///
499 /// Takes resolved ids rather than revisions: the caller has already resolved them
500 /// — that is what [`commit`](Self::commit) and [`resolve`](Self::resolve) hand
501 /// back — and re-resolving here would be a process per call for an answer already
502 /// in hand.
503 ///
504 /// `base` of `None` diffs against the empty tree, which is what a root commit needs
505 /// — a first commit has no parent to compare with, and showing it as an empty diff
506 /// would hide the whole of it.
507 ///
508 /// **Bytes are capped like every other read here**, and unlike the others the cap
509 /// is expected to bite: a merge of a vendored dependency is a legitimately enormous
510 /// patch. [`RawDiff::truncated`] says whether it did, and the per-file counts are
511 /// carried separately *precisely so that they survive it* — see [`RawDiff`].
512 ///
513 /// One `git` process.
514 fn diff(
515 &self,
516 handle: &OrgName,
517 name: &RepoName,
518 base: Option<&ObjectId>,
519 head: &ObjectId,
520 max_bytes: u64,
521 ) -> impl Future<Output = Result<RawDiff, GitQueryError>> + Send;
522
523 /// The best common ancestor of two commits, or `None` when they share none.
524 ///
525 /// `None` is a real answer, not a failure: two histories imported into one
526 /// repository have no merge base, and a compare page says so rather than 500ing.
527 ///
528 /// One `git` process.
529 fn merge_base(
530 &self,
531 handle: &OrgName,
532 name: &RepoName,
533 base: &ObjectId,
534 head: &ObjectId,
535 ) -> impl Future<Output = Result<Option<ObjectId>, GitQueryError>> + Send;
536
537 /// The commits reachable from `head` but not from `base`, newest first.
538 ///
539 /// `base` of `None` is every commit reachable from `head`, which makes this a
540 /// superset of [`log`](Self::log) — kept separate anyway, because `log` takes a
541 /// revision and this takes resolved ids, and collapsing them would put a URL's text
542 /// back in front of git's revision parser.
543 ///
544 /// One `git` process.
545 fn log_between(
546 &self,
547 handle: &OrgName,
548 name: &RepoName,
549 base: Option<&ObjectId>,
550 head: &ObjectId,
551 limit: usize,
552 ) -> impl Future<Output = Result<Vec<CommitSummary>, GitQueryError>> + Send;
553
554 /// Every branch, with what its tip commit says, newest commit first.
555 ///
556 /// Richer than [`list_refs`](Self::list_refs) and for a different page: the switcher
557 /// wants names, the branches page wants a row. Kept separate rather than widening
558 /// `list_refs`, because a switcher that paid for commit subjects it never shows
559 /// would make every tree page slower.
560 ///
561 /// **One `git` process for the whole page**, including which branch is the default
562 /// — git's own `%(HEAD)` marker carries that, so nothing has to ask `symbolic-ref`
563 /// as well.
564 ///
565 /// Ordered by committer date, newest first, because git sorts for free and the
566 /// alternative is re-sorting the whole list in Rust for the same answer. Pinning
567 /// the default branch to the top is a display decision and belongs to the use case.
568 ///
569 /// An empty repository has no branches and answers with an empty list.
570 fn branches(
571 &self,
572 handle: &OrgName,
573 name: &RepoName,
574 ) -> impl Future<Output = Result<Vec<BranchRow>, GitQueryError>> + Send;
575
576 /// Every tag, newest first by creation date.
577 ///
578 /// The counterpart to [`branches`](Self::branches), and one `git` process for the
579 /// same reason. Both kinds of tag are reported: the commit is peeled through an
580 /// annotated tag's object so a row always names something browsable.
581 fn tags(
582 &self,
583 handle: &OrgName,
584 name: &RepoName,
585 ) -> impl Future<Output = Result<Vec<TagRow>, GitQueryError>> + Send;
586
587 /// Lines matching a fixed string, in the revision's tree.
588 ///
589 /// Fixed-string, not a regular expression: a search box that quietly reads `[` as
590 /// syntax is a search box that fails on real code. Binary files are skipped, so a
591 /// grep never reports a match nobody can read.
592 ///
593 /// `limit` caps the *hits carried back*, not what git does — `git grep` has no
594 /// portable maximum, so it runs to completion and the surplus is dropped here. Ask
595 /// for one more than is to be shown and the caller knows it truncated.
596 ///
597 /// An empty list is a real answer: no matches is not a failure, and neither is a
598 /// query with nothing in the repository to match.
599 fn grep(
600 &self,
601 handle: &OrgName,
602 name: &RepoName,
603 commit: &ObjectId,
604 query: &str,
605 limit: usize,
606 ) -> impl Future<Output = Result<Vec<GrepHit>, GitQueryError>> + Send;
607
608 /// Which commit last touched each line of a file, grouped into runs.
609 ///
610 /// `Ok(None)` for an unknown revision, a path that is not there, and a path that is
611 /// not a file — a directory has no lines to attribute.
612 ///
613 /// **The most expensive read in this port.** git walks history for one file rather
614 /// than answering from an index, so the cost grows with how much of that history
615 /// touched it; on a large file with a long history it is the read most likely to
616 /// meet the adapter's timeout. Nothing calls it except the blame page, which is a
617 /// page a visitor asks for by name.
618 ///
619 /// Says nothing about size. Whether a file is small enough to be worth blaming is
620 /// the caller's cap, applied through [`read_blob`](Self::read_blob) so the blame
621 /// page and the blob page cannot disagree about it.
622 fn blame(
623 &self,
624 handle: &OrgName,
625 name: &RepoName,
626 rev: &RefName,
627 path: &RepoPath,
628 ) -> impl Future<Output = Result<Option<Blame>, GitQueryError>> + Send;
629
630 /// Every ref and the object it names, right now.
631 ///
632 /// The whole of `refs/`, not just branches and tags: a push may move anything, and
633 /// being complete costs nothing here — the cost is the process, not the question,
634 /// exactly as it is for [`list_refs`](Self::list_refs).
635 ///
636 /// Full ref names (`refs/heads/main`), because `refs/heads/x` and `refs/tags/x` are
637 /// different things that shorten alike, and an annotated tag's own object id rather
638 /// than what it peels to, because what changed is the *ref*.
639 ///
640 /// This exists to be called twice around a push and diffed. It is separate from
641 /// [`list_refs`](Self::list_refs) rather than widening it, because that answer feeds
642 /// a switcher that shows names and would then be paying for ids it never renders.
643 ///
644 /// **One `git` process**, and a push pays for two of them. That is the accepted
645 /// cost of recording push events from the application instead of from a
646 /// `post-receive` hook script inside every bare repository.
647 ///
648 /// An empty repository has no refs and answers with an empty list.
649 fn ref_snapshot(
650 &self,
651 handle: &OrgName,
652 name: &RepoName,
653 ) -> impl Future<Output = Result<Vec<(RefName, ObjectId)>, GitQueryError>> + Send;
654}
655
656/// A patch, plus the per-file counts that outlive truncating it.
657///
658/// The two arrive from **one** `git` process, because git will write a `--numstat`
659/// block and a `-p` patch in the same run and writes the counts *first*. That ordering
660/// is the whole reason for asking this way: a diff too large to render still has
661/// complete per-file statistics at the top of what was read, so the page can list every
662/// changed file with its `+a −b` and simply decline to draw the lines. Asking twice
663/// would cost a second process on every commit page to buy something only the rare
664/// oversized one needs.
665#[derive(Debug, Clone, Default, PartialEq, Eq)]
666pub struct RawDiff {
667 /// The `--numstat` block: `<added> TAB <removed> TAB <path>` per changed file, with
668 /// `-` for both counts when the file is binary. Always complete.
669 pub numstat: Vec<u8>,
670 /// The unified patch. Cut short — possibly mid-line — when
671 /// [`truncated`](Self::truncated) is set.
672 pub patch: Vec<u8>,
673 /// Whether the patch hit the byte cap and is therefore not the whole of it.
674 pub truncated: bool,
675}
676/// A repository could not be read.
677#[derive(Debug)]
678pub struct GitQueryError {
679 kind: GitQueryErrorKind,
680 source: Box<dyn std::error::Error + Send + Sync>,
681}
682
683/// Why a read failed — the one distinction a page needs to make.
684///
685/// A timeout is the caller asking too much of one request (blame on a huge file, a grep
686/// across a large tree), and the page should say so and offer less. Anything else is a
687/// fault in the repository or in git, and is a 500.
688#[derive(Debug, Clone, Copy, PartialEq, Eq)]
689pub enum GitQueryErrorKind {
690 Failed,
691 TimedOut,
692}
693
694impl GitQueryError {
695 pub fn new(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
696 Self {
697 kind: GitQueryErrorKind::Failed,
698 source: error.into(),
699 }
700 }
701
702 /// The git process was killed because it exceeded `limit`.
703 pub fn timed_out(limit: std::time::Duration) -> Self {
704 Self {
705 kind: GitQueryErrorKind::TimedOut,
706 source: format!("git did not finish within {limit:?}").into(),
707 }
708 }
709
710 pub fn kind(&self) -> GitQueryErrorKind {
711 self.kind
712 }
713
714 pub fn is_timeout(&self) -> bool {
715 self.kind == GitQueryErrorKind::TimedOut
716 }
717}
718
719impl std::fmt::Display for GitQueryError {
720 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
721 match self.kind {
722 GitQueryErrorKind::Failed => {
723 write!(f, "could not read the repository: {}", self.source)
724 }
725 GitQueryErrorKind::TimedOut => {
726 write!(f, "reading the repository took too long: {}", self.source)
727 }
728 }
729 }
730}
731
732impl std::error::Error for GitQueryError {
733 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
734 Some(&*self.source)
735 }
736}
737
738/// What an archive is packed as.
739///
740/// Two formats because they are what people expect from a forge and what `git archive`
741/// produces without configuration: `tar.gz` everywhere, `zip` for Windows and for
742/// anyone who wants to look inside before extracting.
743#[derive(Debug, Clone, Copy, PartialEq, Eq)]
744pub enum ArchiveFormat {
745 TarGz,
746 Zip,
747}
748
749impl ArchiveFormat {
750 /// What `git archive --format=` is given. Also the file extension, which is not a
751 /// coincidence worth breaking apart into two constants.
752 pub fn as_str(self) -> &'static str {
753 match self {
754 Self::TarGz => "tar.gz",
755 Self::Zip => "zip",
756 }
757 }
758
759 /// What the response labels the bytes.
760 ///
761 /// Honest types, unlike the raw endpoint's deliberate `octet-stream`: neither of
762 /// these is a type a browser renders, so naming it costs nothing and lets a client
763 /// decompress without guessing.
764 pub fn content_type(self) -> &'static str {
765 match self {
766 Self::TarGz => "application/gzip",
767 Self::Zip => "application/zip",
768 }
769 }
770}
771
772/// `Result`, never `Option`, per the layer's rule: a silently-defaulted format would
773/// hand somebody a zip named `.tar.gz`.
774impl std::str::FromStr for ArchiveFormat {
775 type Err = DomainError;
776
777 fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
778 match value {
779 "tar.gz" => Ok(Self::TarGz),
780 "zip" => Ok(Self::Zip),
781 other => Err(DomainError::validation(
782 "format",
783 format!("unknown archive format {other:?}"),
784 )),
785 }
786 }
787}
788
789/// One repository, packed for download.
790///
791/// Every field is built by the use case from values it has already resolved and
792/// authorized — the commit is an [`ObjectId`] git handed back, never a revision from a
793/// URL, and the prefix is derived from the repository's own name. Nothing here reaches
794/// git's revision parser.
795#[derive(Debug, Clone, PartialEq, Eq)]
796pub struct ArchiveRequest {
797 pub handle: OrgName,
798 pub name: RepoName,
799 pub format: ArchiveFormat,
800 pub commit: ObjectId,
801 /// The directory every entry is nested under, ending in `/`. Extracting an archive
802 /// that spills its contents into the current directory is a small hostility.
803 pub prefix: String,
804}
805
806/// Packing a repository into an archive.
807///
808/// The fourth narrow git port, and streaming rather than buffered for the same reason
809/// the protocol is: an archive is as large as the repository, so collecting it would
810/// bound downloads by RAM. That is the whole reason this is not a [`GitQuery`] method —
811/// that port's contract is capped bytes, and this one's is a stream.
812pub trait GitArchive: Send + Sync {
813 fn archive(
814 &self,
815 request: ArchiveRequest,
816 ) -> impl Future<Output = Result<ByteStream, GitArchiveError>> + Send;
817}
818
819/// A repository could not be packed.
820///
821/// No `NotFound`: the use case resolved the commit before asking, so anything failing
822/// here is git or the filesystem failing.
823#[derive(Debug)]
824pub struct GitArchiveError(Box<dyn std::error::Error + Send + Sync>);
825
826impl GitArchiveError {
827 pub fn new(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
828 Self(error.into())
829 }
830}
831
832impl std::fmt::Display for GitArchiveError {
833 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
834 write!(f, "could not archive the repository: {}", self.0)
835 }
836}
837
838impl std::error::Error for GitArchiveError {
839 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
840 Some(&*self.0)
841 }
842}
843
844/// Copying a repository into Steid from somewhere else.
845///
846/// The fifth narrow git port. Separate from [`GitStorage`] rather than a second method
847/// on it because the two have opposite shapes: `init_bare` is a fast local write on a
848/// request path, and this is a network transfer that can legitimately run for minutes
849/// and therefore only ever runs in the background.
850///
851/// **The adapter, not the caller, is where the address is checked against DNS.**
852/// [`ImportSource`] already refused a scheme other than `https` and a literal address
853/// that is not on the public internet, but a hostname can resolve anywhere, and only
854/// the thing about to open the connection is in a position to look.
855pub trait GitImport: Send + Sync {
856 /// Mirrors `source` into the repository's path, leaving an ordinary bare repository
857 /// behind: every branch under `refs/heads`, every tag under `refs/tags`, `HEAD`
858 /// pointing at the source's default branch, and no remote configured.
859 ///
860 /// Fails rather than adopting anything already at the path — a half-finished import
861 /// from a killed process must not be silently completed with someone else's history.
862 fn mirror(
863 &self,
864 handle: &OrgName,
865 name: &RepoName,
866 source: &ImportSource,
867 ) -> impl Future<Output = Result<(), GitImportError>> + Send;
868}
869
870/// An import did not finish.
871///
872/// One variant, deliberately: every way this fails — a refused address, a repository
873/// that is not there, a network that gave up, git taking too long — is something the
874/// owner who typed the URL can read and act on, and nothing else reacts to it
875/// differently. The message is therefore the whole of the error.
876#[derive(Debug)]
877pub struct GitImportError(String);
878
879impl GitImportError {
880 pub fn new(message: impl Into<String>) -> Self {
881 Self(message.into())
882 }
883
884 /// The reason, for showing to the owner. Safe to render: it is built from git's own
885 /// output about an address that person supplied.
886 pub fn message(&self) -> &str {
887 &self.0
888 }
889}
890
891impl std::fmt::Display for GitImportError {
892 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
893 write!(f, "could not import the repository: {}", self.0)
894 }
895}
896
897impl std::error::Error for GitImportError {}