steid

@jamesgill /

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