steid

@jamesgill /

Rust53.7 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::{collections::HashMap, path::PathBuf, pin::Pin};
7
8use tokio::io::AsyncRead;
9
10use crate::domain::{
11 BranchRow, CommitDetail, CommitEntry, CommitSummary, DomainError, EntryCommit, GitRef, GrepHit,
12 ImportSource, ObjectId, OrgName, PasswordHash, RefName, RepoName, RepoPath, TagRow, TagSummary,
13 TreeEntry,
14};
15
16use super::blame::Blame;
17
18/// Hashes and verifies passwords.
19///
20/// A port rather than a direct Argon2 call so tests can substitute a fast stub —
21/// Argon2 is deliberately slow, and a use case suite that hashes for real takes
22/// seconds per test.
23pub trait PasswordHasher: Send + Sync {
24 /// Hashes a plaintext password.
25 fn hash(&self, plaintext: &str) -> Result<PasswordHash, PasswordError>;
26
27 /// Checks a plaintext password against a stored hash.
28 ///
29 /// Returns `Ok(false)` for a wrong password and `Err` only when the hash itself
30 /// cannot be parsed — a corrupt stored hash is a different problem from a failed
31 /// login, and collapsing them hides real faults.
32 fn verify(&self, plaintext: &str, hash: &PasswordHash) -> Result<bool, PasswordError>;
33}
34
35/// A password could not be hashed or a stored hash could not be parsed.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct PasswordError(String);
38
39impl PasswordError {
40 pub fn new(message: impl Into<String>) -> Self {
41 Self(message.into())
42 }
43}
44
45impl std::fmt::Display for PasswordError {
46 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47 write!(f, "password hashing failed: {}", self.0)
48 }
49}
50
51impl std::error::Error for PasswordError {}
52
53/// Where bare git repositories live on disk.
54///
55/// Laid out as `{data_dir}/{handle}/{name}.git`. Keyed by handle rather than
56/// [`OrgId`](crate::domain::OrgId) so the data directory is legible to anyone who has
57/// to debug it; the cost is that renaming a handle becomes a directory move rather
58/// than a row update.
59///
60/// Deliberately narrow. Serving the git protocol and browsing a tree are separate
61/// concerns with separate shapes — streaming and querying — and get their own ports as
62/// their use cases arrive, rather than accreting here. See
63/// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md).
64pub trait GitStorage: Send + Sync {
65 /// Creates an empty bare repository.
66 ///
67 /// Empty means empty: no initial commit, no branch, matching what GitHub does for
68 /// a repository created without a README.
69 ///
70 /// Fails with [`GitStorageError::AlreadyExists`] rather than adopting whatever is
71 /// already there.
72 fn init_bare(
73 &self,
74 handle: &OrgName,
75 name: &RepoName,
76 ) -> impl Future<Output = Result<(), GitStorageError>> + Send;
77
78 /// Removes a bare repository, succeeding if there was nothing to remove.
79 ///
80 /// This exists to compensate a failed record insert — a repository row and its
81 /// directory cannot share a transaction — not as a user-facing delete. Deleting a
82 /// repository properly is a separate use case with its own authorization.
83 fn remove(
84 &self,
85 handle: &OrgName,
86 name: &RepoName,
87 ) -> impl Future<Output = Result<(), GitStorageError>> + Send;
88
89 /// Moves a bare repository to a new name under the same handle.
90 ///
91 /// The filesystem half of a rename. The record half is
92 /// [`rename_repo`](super::repo::rename_repo)'s, which is also where the two are
93 /// ordered and compensated — this port only moves a directory.
94 ///
95 /// Fails with [`GitStorageError::AlreadyExists`] rather than overwriting whatever
96 /// is at the destination, for the reason [`init_bare`](Self::init_bare) does: with
97 /// no matching record, something already there is an orphan, and adopting it would
98 /// hand somebody else's objects to this repository.
99 fn rename(
100 &self,
101 handle: &OrgName,
102 from: &RepoName,
103 to: &RepoName,
104 ) -> impl Future<Output = Result<(), GitStorageError>> + Send;
105
106 /// Points `HEAD` at a branch, making it the repository's default.
107 ///
108 /// **There is no column for this.** git already holds the answer in the bare
109 /// repository's `HEAD`, every read goes through
110 /// [`default_branch`](GitQuery::default_branch), and a copy in the database would
111 /// be a second answer that can disagree with the first — including with whatever a
112 /// push did.
113 ///
114 /// A write rather than a query, which is why it is here and not on [`GitQuery`]:
115 /// that port's whole contract is reading.
116 ///
117 /// Says nothing about whether the branch exists. Checking that is the use case's
118 /// job, because it is a rule about what an owner may choose rather than a fact
119 /// about the filesystem.
120 fn set_default_branch(
121 &self,
122 handle: &OrgName,
123 name: &RepoName,
124 branch: &RefName,
125 ) -> impl Future<Output = Result<(), GitStorageError>> + Send;
126
127 /// Turns the reflog on in every bare repository that has not got it, and reports how
128 /// many were changed.
129 ///
130 /// **A migration that cannot be a migration.** `git init --bare` leaves
131 /// `core.logAllRefUpdates` off, so a bare repository keeps no reflog and the
132 /// `REMOTE_USER` a push is served with has nowhere to be recorded —
133 /// [`init_bare`](Self::init_bare) sets it now, but every repository created before
134 /// that keeps no history of who moved a ref, and the state lives in a file rather
135 /// than in a row that `sqlx migrate` could reach.
136 ///
137 /// Takes no repository, and asks no database: which repositories exist on disk is a
138 /// fact about the data directory, and a sweep that read the rows instead would leave
139 /// a repository whose row went missing without a reflog for a reason nobody could
140 /// see.
141 ///
142 /// Called once on boot. A failure is not fatal — the caller logs it and serves — and
143 /// a repository it cannot fix is one whose pushes stay anonymous, not one that
144 /// breaks.
145 fn enable_reflogs(&self) -> impl Future<Output = Result<u64, GitStorageError>> + Send;
146
147 /// Every repository directory that exists under the data directory.
148 ///
149 /// The filesystem's own answer, uninterpreted: what the names mean — whether a row
150 /// exists for one, whether it even parses as a handle and a name — is the caller's,
151 /// which is what makes the decision testable without a disk. See
152 /// [`sweep_orphan_directories`](super::reconcile::sweep_orphan_directories).
153 ///
154 /// A missing data directory is an empty list rather than an error: a fresh instance
155 /// has not created it yet.
156 fn list_repo_dirs(&self) -> impl Future<Output = Result<Vec<RepoDir>, GitStorageError>> + Send;
157
158 /// Moves a repository directory out of the way, under `label`, and says where it went.
159 ///
160 /// **Aside, never deleted.** Reaching here means a directory has no row, which is
161 /// either a create or a rename that died mid-write or an import whose repository was
162 /// removed underneath it — and in every one of those cases the directory may hold the
163 /// only copy of somebody's objects. Moving it frees the name for reuse, which is the
164 /// actual complaint, and keeps whatever was there.
165 ///
166 /// `label` is the destination's name and is chosen by the caller, so the timestamp in
167 /// it is not a clock this port has to read.
168 fn quarantine(
169 &self,
170 dir: &RepoDir,
171 label: &str,
172 ) -> impl Future<Output = Result<PathBuf, GitStorageError>> + Send;
173
174 /// Where a repository lives.
175 ///
176 /// Pure, and says nothing about whether anything exists there. Milestone 4 hands
177 /// this to `git http-backend`.
178 fn repo_path(&self, handle: &OrgName, name: &RepoName) -> PathBuf;
179}
180
181/// One repository directory as it was found on disk.
182///
183/// Strings rather than [`OrgName`] and [`RepoName`], deliberately: a directory that does
184/// **not** parse as either is exactly the kind of thing a reconciliation sweep exists to
185/// notice, and typing the fields would mean throwing those away before anyone looked.
186#[derive(Debug, Clone, PartialEq, Eq)]
187pub struct RepoDir {
188 /// The first path component under the data directory — a handle, if it is one.
189 pub handle: String,
190 /// The repository name, with `.git` already stripped.
191 pub name: String,
192 /// The directory itself, for the log line and for the move.
193 pub path: PathBuf,
194}
195
196/// A repository could not be created or removed on disk.
197#[derive(Debug)]
198pub enum GitStorageError {
199 /// Something already occupies the repository's path.
200 ///
201 /// Kept distinct from a general failure because it is the one case a use case can
202 /// explain to a user, and because with no matching record it means an orphaned
203 /// directory left by a crashed create.
204 AlreadyExists,
205 /// The filesystem or the `git` binary failed.
206 Backend(Box<dyn std::error::Error + Send + Sync>),
207}
208
209impl GitStorageError {
210 pub fn backend(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
211 Self::Backend(error.into())
212 }
213}
214
215impl std::fmt::Display for GitStorageError {
216 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
217 match self {
218 Self::AlreadyExists => f.write_str("a repository already exists at that path"),
219 Self::Backend(error) => write!(f, "git storage failure: {error}"),
220 }
221 }
222}
223
224impl std::error::Error for GitStorageError {
225 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
226 match self {
227 Self::AlreadyExists => None,
228 Self::Backend(error) => Some(&**error),
229 }
230 }
231}
232
233/// A stream of bytes, in either direction.
234///
235/// Pack data is arbitrarily large and must never be collected into memory — a clone of
236/// a large repository would otherwise be bounded by RAM rather than by disk. Boxed
237/// rather than generic so the port stays object-safe in shape and the adapter can hand
238/// back a subprocess's stdout directly.
239pub type ByteStream = Pin<Box<dyn AsyncRead + Send>>;
240
241/// Which HTTP method a git request uses.
242///
243/// Only these two exist in the smart protocol: the advertisement is a `GET`, the
244/// negotiation and pack transfer are `POST`s.
245#[derive(Debug, Clone, Copy, PartialEq, Eq)]
246pub enum GitMethod {
247 Get,
248 Post,
249}
250
251impl GitMethod {
252 pub fn as_str(self) -> &'static str {
253 match self {
254 Self::Get => "GET",
255 Self::Post => "POST",
256 }
257 }
258}
259
260/// A request to the git protocol, in the shape `git http-backend` wants it.
261///
262/// CGI-shaped rather than one method per operation, because the backend is a CGI —
263/// see the amendment to
264/// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md). **Every field
265/// here is constructed by the use case**, not forwarded from a URL: `path_info` and
266/// `query` in particular are built from an already-validated handle and repository
267/// name, so the transport cannot ask for a path the use case did not authorize.
268pub struct GitRequest {
269 pub method: GitMethod,
270 /// The repository path relative to the project root, e.g. `/acme/steid.git/info/refs`.
271 pub path_info: String,
272 /// The CGI query string, e.g. `service=git-upload-pack`. Empty for an RPC POST.
273 pub query: String,
274 pub content_type: Option<String>,
275 /// The client's `Content-Encoding`. Real clients gzip this body once a repository
276 /// has more than a handful of refs, and the backend inflates it for us — but only
277 /// when it arrives as `HTTP_CONTENT_ENCODING`, which is the adapter's job.
278 pub content_encoding: Option<String>,
279 pub content_length: Option<String>,
280 /// The client's `Git-Protocol`, carrying `version=2` for any modern client.
281 /// Dropping it silently downgrades the exchange to v0 rather than failing.
282 pub git_protocol: Option<String>,
283 /// Whether the backend may run `receive-pack` at all.
284 ///
285 /// `git http-backend` refuses pushes unless `http.receivepack` says otherwise, and
286 /// this is what sets it. The use case turns it on **only after** authorizing the
287 /// write, so git stays a second refusal behind Steid's own rather than being
288 /// switched off wholesale. If the authorization logic is ever wrong, this is what
289 /// still says no.
290 pub allow_receive_pack: bool,
291 /// The pusher's handle, for `REMOTE_USER`.
292 ///
293 /// git puts it in the repository's reflog, so `git reflog show main` on the bare
294 /// repository names who moved a ref rather than saying only that it moved. Steid
295 /// knows the actor by the time the backend is spawned; this is that fact reaching
296 /// the place it is recorded.
297 ///
298 /// `None` for a read, which has nothing to attribute.
299 pub remote_user: Option<String>,
300 pub body: ByteStream,
301}
302
303/// What the git protocol answered.
304///
305/// The status is CGI's, not the framework's: `git http-backend` reports failure with a
306/// `Status:` header and no status at all when it succeeded, so absence means 200 and
307/// the adapter translates it.
308pub struct GitResponse {
309 pub status: u16,
310 pub headers: Vec<(String, String)>,
311 pub body: ByteStream,
312}
313
314/// Written by hand because a body is a stream: it cannot be formatted without being
315/// consumed, and a `Debug` that drains the response would be a trap.
316impl std::fmt::Debug for GitRequest {
317 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
318 f.debug_struct("GitRequest")
319 .field("method", &self.method)
320 .field("path_info", &self.path_info)
321 .field("query", &self.query)
322 .field("content_type", &self.content_type)
323 .field("content_encoding", &self.content_encoding)
324 .field("content_length", &self.content_length)
325 .field("git_protocol", &self.git_protocol)
326 .field("allow_receive_pack", &self.allow_receive_pack)
327 .field("remote_user", &self.remote_user)
328 .finish_non_exhaustive()
329 }
330}
331
332impl std::fmt::Debug for GitResponse {
333 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
334 f.debug_struct("GitResponse")
335 .field("status", &self.status)
336 .field("headers", &self.headers)
337 .finish_non_exhaustive()
338 }
339}
340
341/// Serves the git smart-HTTP protocol for one repository.
342///
343/// Says nothing about who may do this. Authorization is settled before a request ever
344/// reaches here — by the time the backend is running, refusing is no longer possible.
345pub trait GitProtocolServer: Send + Sync {
346 fn serve(
347 &self,
348 request: GitRequest,
349 ) -> impl Future<Output = Result<GitResponse, GitProtocolError>> + Send;
350}
351
352/// The git protocol could not be served.
353///
354/// Deliberately without a `NotFound`: a missing repository is something the backend
355/// reports in its own response, and the use case has already refused anything the
356/// viewer may not see.
357#[derive(Debug)]
358pub struct GitProtocolError(Box<dyn std::error::Error + Send + Sync>);
359
360impl GitProtocolError {
361 pub fn new(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
362 Self(error.into())
363 }
364}
365
366impl std::fmt::Display for GitProtocolError {
367 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
368 write!(f, "git protocol failure: {}", self.0)
369 }
370}
371
372impl std::error::Error for GitProtocolError {
373 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
374 Some(&*self.0)
375 }
376}
377
378/// One outbound webhook request.
379///
380/// Built entirely by the use case — the URL comes from a validated
381/// [`WebhookUrl`](crate::domain::WebhookUrl), the body is what was signed, and the
382/// headers are the ones Steid promises. The adapter dials it and reports what happened;
383/// it decides nothing.
384#[derive(Debug, Clone, PartialEq, Eq)]
385pub struct WebhookRequest {
386 pub url: String,
387 pub headers: Vec<(String, String)>,
388 pub body: Vec<u8>,
389}
390
391/// What one attempt did.
392///
393/// Not a `Result`: a refused connection is an *outcome* to be recorded, not an error to
394/// be propagated. The delivery row is the product either way, and a port that could fail
395/// would put the caller in the business of deciding which failures are worth a row.
396#[derive(Debug, Clone, PartialEq, Eq)]
397pub struct WebhookOutcome {
398 /// `None` when there was never a status: DNS, a refused connection, TLS, the
399 /// timeout, or a URL the adapter refused to dial at all.
400 pub status: Option<u16>,
401 /// The start of the response body, or the reason there wasn't one. Capped again by
402 /// the domain before it is stored.
403 pub body: String,
404 pub duration: std::time::Duration,
405}
406
407/// Delivers one webhook request.
408///
409/// A port because the alternative is a use case that cannot be tested without a
410/// listening socket — and because "what Steid will connect to" is a rule worth having
411/// one implementation of.
412pub trait WebhookSender: Send + Sync {
413 fn send(&self, request: WebhookRequest) -> impl Future<Output = WebhookOutcome> + Send;
414}
415
416/// The current time.
417///
418/// A port for the one case that cannot take a `now` from its caller: a use case that
419/// reads the clock **more than once, at times it chooses itself**. Webhook delivery is
420/// that case — four attempts minutes apart, and a timestamp handed down from the push
421/// would have the deliveries page claim all four happened in one instant.
422///
423/// Everything that needs a single instant takes `now: SystemTime` instead, which is
424/// what `issue_token`, `create_repo`, `serve_git` and the boot sweeps do. Two shapes,
425/// one rule: **no use case reads the clock out of thin air**, so a test can always say
426/// what time it is.
427pub trait Clock: Send + Sync {
428 fn now(&self) -> std::time::SystemTime;
429}
430
431/// A blob, as far as the port will carry it.
432///
433/// `content` is `None` when the blob is larger than the caller's limit: the size is
434/// still reported, so a page can say how big the thing it will not show is. Reading it
435/// anyway would let one URL pull an arbitrarily large file into memory.
436#[derive(Debug, Clone, PartialEq, Eq)]
437pub struct Blob {
438 pub id: ObjectId,
439 pub size: u64,
440 pub content: Option<Vec<u8>>,
441}
442
443/// Reading what is inside a repository.
444///
445/// The third of the three git families named in
446/// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md), arriving with
447/// its use case as that ADR requires. Every method takes a handle and a repository name
448/// rather than a path, matching [`GitStorage`] — where a repository lives is the
449/// adapter's business.
450///
451/// **Bytes are capped, never streamed.** Unlike the protocol, a browse request has a
452/// person waiting on a rendered page, so a bounded read is the right shape.
453///
454/// `Ok(None)` throughout means "no such thing in this repository" — an unknown
455/// revision, a path that is not there. It is not an authorization answer; that is
456/// settled before this port is reached.
457pub trait GitQuery: Send + Sync {
458 /// The repository's default branch, or `None` if it has no commits yet.
459 ///
460 /// Separate from resolving a revision because an empty repository has a `HEAD` that
461 /// names a branch which does not exist, and telling those apart is the difference
462 /// between "nothing pushed yet" and a 404.
463 fn default_branch(
464 &self,
465 handle: &OrgName,
466 name: &RepoName,
467 ) -> impl Future<Output = Result<Option<RefName>, GitQueryError>> + Send;
468
469 /// Resolves a revision to the commit it names.
470 fn resolve(
471 &self,
472 handle: &OrgName,
473 name: &RepoName,
474 rev: &RefName,
475 ) -> impl Future<Output = Result<Option<ObjectId>, GitQueryError>> + Send;
476
477 /// Lists a directory, unsorted — ordering is [`TreeEntry::ordering_key`]'s job.
478 ///
479 /// `Ok(None)` for a path that is not a directory in this revision, which includes a
480 /// path that is a file.
481 fn list_tree(
482 &self,
483 handle: &OrgName,
484 name: &RepoName,
485 rev: &RefName,
486 path: &RepoPath,
487 ) -> impl Future<Output = Result<Option<Vec<TreeEntry>>, GitQueryError>> + Send;
488
489 /// The commit that last touched each of a directory's entries.
490 ///
491 /// `entries` names the direct children to attribute — the listing's own names, not
492 /// paths. The answer holds only what was attributed: an entry missing from the map
493 /// shows nothing, which is the right answer for one whose last change is older than
494 /// the scan reaches.
495 ///
496 /// **One `git` process for the whole directory**, not one per entry. That is the
497 /// entire reason this exists as a method rather than as a loop over
498 /// [`log`](Self::log) in the caller: at one fork per entry a twenty-file directory
499 /// is ~230ms, which is the number the Milestone 5 amendment to
500 /// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md) used to say
501 /// the column was not worth it yet.
502 ///
503 /// The walk is capped — see the adapter — so this is bounded work on a repository of
504 /// any age, and a directory nobody has touched recently is the case that pays the
505 /// cap in full.
506 fn last_commits(
507 &self,
508 handle: &OrgName,
509 name: &RepoName,
510 rev: &RefName,
511 path: &RepoPath,
512 entries: &[String],
513 ) -> impl Future<Output = Result<HashMap<String, EntryCommit>, GitQueryError>> + Send;
514
515 /// Reads a file, up to `max_bytes`.
516 ///
517 /// `Ok(None)` for a path that is not a file in this revision.
518 fn read_blob(
519 &self,
520 handle: &OrgName,
521 name: &RepoName,
522 rev: &RefName,
523 path: &RepoPath,
524 max_bytes: u64,
525 ) -> impl Future<Output = Result<Option<Blob>, GitQueryError>> + Send;
526
527 /// The commits reachable from a revision, newest first, from `offset` onwards.
528 ///
529 /// `offset` is what the log page's `?page=` becomes — git's own `--skip`, not a
530 /// cursor. Paging a log by "the commits before <sha>" reads as the obvious keyset
531 /// answer and is wrong across a merge: `git log` walks a date-interleaved history,
532 /// so the commits still to come after a given sha are not the same set as the
533 /// commits reachable *from* it, and the other parent's line would silently vanish
534 /// from the second page. See [ui.md](../../../plans/ui.md#paging).
535 ///
536 /// An offset past the end is an empty list, not an error: a rewritten branch turns
537 /// a bookmarked deep page into one, and the page it belongs to clamps.
538 fn log(
539 &self,
540 handle: &OrgName,
541 name: &RepoName,
542 rev: &RefName,
543 offset: usize,
544 limit: usize,
545 ) -> impl Future<Output = Result<Vec<CommitSummary>, GitQueryError>> + Send;
546
547 /// The same commits as [`log`](Self::log), each carrying its message body.
548 ///
549 /// A second method rather than a wider [`CommitSummary`], because the two readings
550 /// of a log genuinely differ: a page renders fifty subject lines, and a feed renders
551 /// fifty messages. One `git` process either way — the body costs another format
552 /// field, not another fork.
553 fn log_entries(
554 &self,
555 handle: &OrgName,
556 name: &RepoName,
557 rev: &RefName,
558 limit: usize,
559 ) -> impl Future<Output = Result<Vec<CommitEntry>, GitQueryError>> + Send;
560
561 /// Every branch and every tag, unordered.
562 ///
563 /// Ordering is the use case's decision, the same way it is for
564 /// [`list_tree`](Self::list_tree) — an adapter that sorted would have to be
565 /// re-taught the order every time it changed.
566 ///
567 /// **This costs a whole `git` process** — ~14ms, the most expensive of the read
568 /// commands measured for the Milestone 5 amendment to
569 /// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md), because
570 /// starting the process is the cost. A page that does not show a ref switcher must
571 /// not call it.
572 ///
573 /// An empty repository has no refs and answers with an empty list rather than an
574 /// error: nothing pushed yet is not a failure.
575 fn list_refs(
576 &self,
577 handle: &OrgName,
578 name: &RepoName,
579 ) -> impl Future<Output = Result<Vec<GitRef>, GitQueryError>> + Send;
580
581 /// How many commits are reachable from a revision.
582 ///
583 /// The number a repository page states about itself. A revision that resolves to
584 /// nothing — an empty repository, a branch that is not there — counts `0` rather
585 /// than failing, matching [`log`](Self::log): a page asking how big a repository is
586 /// does not want an error for the answer "nothing yet".
587 fn count_commits(
588 &self,
589 handle: &OrgName,
590 name: &RepoName,
591 rev: &RefName,
592 ) -> impl Future<Output = Result<u64, GitQueryError>> + Send;
593
594 /// The most recently created tag, or `None` if the repository has none.
595 ///
596 /// "Most recent" is by creation date, not by name: version numbers do not sort
597 /// chronologically once there is a `v1.10` beside a `v1.9`, and a repository's own
598 /// history is the only ordering that is always right.
599 ///
600 /// One `git` process, the same cost as [`list_refs`](Self::list_refs). Asked
601 /// separately rather than derived from that list because the ordering needs git's
602 /// `creatordate`, which the ref list deliberately does not carry.
603 fn latest_tag(
604 &self,
605 handle: &OrgName,
606 name: &RepoName,
607 ) -> impl Future<Output = Result<Option<TagSummary>, GitQueryError>> + Send;
608
609 /// One commit, in full.
610 ///
611 /// `Ok(None)` for a revision that names nothing, and for one that names something
612 /// which is not a commit — a tree or a blob addressed by its own id. A commit page
613 /// has nothing to show for either, so both are the same 404.
614 ///
615 /// **Two `git` processes**: the revision is resolved before it is read, for the
616 /// reason [`count_commits`](Self::count_commits) resolves first. The resolved
617 /// [`ObjectId`] comes back on the answer, so a caller that goes on to ask for a
618 /// diff does not pay to resolve it again.
619 fn commit(
620 &self,
621 handle: &OrgName,
622 name: &RepoName,
623 rev: &RefName,
624 ) -> impl Future<Output = Result<Option<CommitDetail>, GitQueryError>> + Send;
625
626 /// The patch between two commits, as git writes it.
627 ///
628 /// Takes resolved ids rather than revisions: the caller has already resolved them
629 /// — that is what [`commit`](Self::commit) and [`resolve`](Self::resolve) hand
630 /// back — and re-resolving here would be a process per call for an answer already
631 /// in hand.
632 ///
633 /// `base` of `None` diffs against the empty tree, which is what a root commit needs
634 /// — a first commit has no parent to compare with, and showing it as an empty diff
635 /// would hide the whole of it.
636 ///
637 /// **Bytes are capped like every other read here**, and unlike the others the cap
638 /// is expected to bite: a merge of a vendored dependency is a legitimately enormous
639 /// patch. [`RawDiff::truncated`] says whether it did, and the per-file counts are
640 /// carried separately *precisely so that they survive it* — see [`RawDiff`].
641 ///
642 /// One `git` process.
643 fn diff(
644 &self,
645 handle: &OrgName,
646 name: &RepoName,
647 base: Option<&ObjectId>,
648 head: &ObjectId,
649 max_bytes: u64,
650 ) -> impl Future<Output = Result<RawDiff, GitQueryError>> + Send;
651
652 /// The best common ancestor of two commits, or `None` when they share none.
653 ///
654 /// `None` is a real answer, not a failure: two histories imported into one
655 /// repository have no merge base, and a compare page says so rather than 500ing.
656 ///
657 /// One `git` process.
658 fn merge_base(
659 &self,
660 handle: &OrgName,
661 name: &RepoName,
662 base: &ObjectId,
663 head: &ObjectId,
664 ) -> impl Future<Output = Result<Option<ObjectId>, GitQueryError>> + Send;
665
666 /// The commits reachable from `head` but not from `base`, newest first.
667 ///
668 /// `base` of `None` is every commit reachable from `head`, which makes this a
669 /// superset of [`log`](Self::log) — kept separate anyway, because `log` takes a
670 /// revision and this takes resolved ids, and collapsing them would put a URL's text
671 /// back in front of git's revision parser.
672 ///
673 /// One `git` process.
674 fn log_between(
675 &self,
676 handle: &OrgName,
677 name: &RepoName,
678 base: Option<&ObjectId>,
679 head: &ObjectId,
680 offset: usize,
681 limit: usize,
682 ) -> impl Future<Output = Result<Vec<CommitSummary>, GitQueryError>> + Send;
683
684 /// How many commits [`log_between`](Self::log_between) has to give, in total.
685 ///
686 /// `rev-list --count` over the same range, and the reason a comparison can say
687 /// "Showing 1–100 of 312 commits" and number its pages. One process, and both ends
688 /// are ids git resolved rather than anything from a URL.
689 fn count_between(
690 &self,
691 handle: &OrgName,
692 name: &RepoName,
693 base: Option<&ObjectId>,
694 head: &ObjectId,
695 ) -> impl Future<Output = Result<usize, GitQueryError>> + Send;
696
697 /// Every branch, with what its tip commit says, newest commit first.
698 ///
699 /// Richer than [`list_refs`](Self::list_refs) and for a different page: the switcher
700 /// wants names, the branches page wants a row. Kept separate rather than widening
701 /// `list_refs`, because a switcher that paid for commit subjects it never shows
702 /// would make every tree page slower.
703 ///
704 /// **One `git` process for the whole page**, including which branch is the default
705 /// — git's own `%(HEAD)` marker carries that, so nothing has to ask `symbolic-ref`
706 /// as well.
707 ///
708 /// Ordered by committer date, newest first, because git sorts for free and the
709 /// alternative is re-sorting the whole list in Rust for the same answer. Pinning
710 /// the default branch to the top is a display decision and belongs to the use case.
711 ///
712 /// An empty repository has no branches and answers with an empty list.
713 fn branches(
714 &self,
715 handle: &OrgName,
716 name: &RepoName,
717 ) -> impl Future<Output = Result<Vec<BranchRow>, GitQueryError>> + Send;
718
719 /// Every tag, newest first by creation date.
720 ///
721 /// The counterpart to [`branches`](Self::branches), and one `git` process for the
722 /// same reason. Both kinds of tag are reported: the commit is peeled through an
723 /// annotated tag's object so a row always names something browsable.
724 fn tags(
725 &self,
726 handle: &OrgName,
727 name: &RepoName,
728 ) -> impl Future<Output = Result<Vec<TagRow>, GitQueryError>> + Send;
729
730 /// Lines matching a fixed string, in the revision's tree.
731 ///
732 /// Fixed-string, not a regular expression: a search box that quietly reads `[` as
733 /// syntax is a search box that fails on real code. Binary files are skipped, so a
734 /// grep never reports a match nobody can read.
735 ///
736 /// `limit` caps the *hits carried back*, not what git does — `git grep` has no
737 /// portable maximum, so it runs to completion and the surplus is dropped here. Ask
738 /// for one more than is to be shown and the caller knows it truncated.
739 ///
740 /// An empty list is a real answer: no matches is not a failure, and neither is a
741 /// query with nothing in the repository to match.
742 fn grep(
743 &self,
744 handle: &OrgName,
745 name: &RepoName,
746 commit: &ObjectId,
747 query: &str,
748 limit: usize,
749 ) -> impl Future<Output = Result<Vec<GrepHit>, GitQueryError>> + Send;
750
751 /// Which commit last touched each line of a file, grouped into runs.
752 ///
753 /// `Ok(None)` for an unknown revision, a path that is not there, and a path that is
754 /// not a file — a directory has no lines to attribute.
755 ///
756 /// **The most expensive read in this port.** git walks history for one file rather
757 /// than answering from an index, so the cost grows with how much of that history
758 /// touched it; on a large file with a long history it is the read most likely to
759 /// meet the adapter's timeout. Nothing calls it except the blame page, which is a
760 /// page a visitor asks for by name.
761 ///
762 /// Says nothing about size. Whether a file is small enough to be worth blaming is
763 /// the caller's cap, applied through [`read_blob`](Self::read_blob) so the blame
764 /// page and the blob page cannot disagree about it.
765 fn blame(
766 &self,
767 handle: &OrgName,
768 name: &RepoName,
769 rev: &RefName,
770 path: &RepoPath,
771 ) -> impl Future<Output = Result<Option<Blame>, GitQueryError>> + Send;
772
773 /// Every ref and the object it names, right now.
774 ///
775 /// The whole of `refs/`, not just branches and tags: a push may move anything, and
776 /// being complete costs nothing here — the cost is the process, not the question,
777 /// exactly as it is for [`list_refs`](Self::list_refs).
778 ///
779 /// Full ref names (`refs/heads/main`), because `refs/heads/x` and `refs/tags/x` are
780 /// different things that shorten alike, and an annotated tag's own object id rather
781 /// than what it peels to, because what changed is the *ref*.
782 ///
783 /// This exists to be called twice around a push and diffed. It is separate from
784 /// [`list_refs`](Self::list_refs) rather than widening it, because that answer feeds
785 /// a switcher that shows names and would then be paying for ids it never renders.
786 ///
787 /// **One `git` process**, and a push pays for two of them. That is the accepted
788 /// cost of recording push events from the application instead of from a
789 /// `post-receive` hook script inside every bare repository.
790 ///
791 /// An empty repository has no refs and answers with an empty list.
792 fn ref_snapshot(
793 &self,
794 handle: &OrgName,
795 name: &RepoName,
796 ) -> impl Future<Output = Result<Vec<(RefName, ObjectId)>, GitQueryError>> + Send;
797
798 /// One page of the commits that touched a path, newest first.
799 ///
800 /// [`log`](Self::log)'s answer narrowed by a pathspec, and paged the same way, by
801 /// `--skip`. A separate method rather than an `Option<&RepoPath>` on `log` because
802 /// `follow` has no meaning without a path and because every existing caller would
803 /// then pass a `None` it does not have an opinion about.
804 ///
805 /// `follow` is git's `--follow`: keep walking through the rename that gave a file
806 /// its current name. It is only ever true for a file — git refuses it for a
807 /// directory, and for more than one path — so the caller decides by asking what is
808 /// at the path, not by guessing here.
809 ///
810 /// **One `git` process**, and a real walk: unlike a whole-history log, git has to
811 /// examine each commit's trees to decide whether the path changed, so this is the
812 /// read that grows with how deep the history is rather than with how much of it is
813 /// shown.
814 ///
815 /// An unknown revision, and a path nothing ever touched, are both the empty list.
816 #[allow(clippy::too_many_arguments)]
817 fn log_at_path(
818 &self,
819 handle: &OrgName,
820 name: &RepoName,
821 rev: &RefName,
822 path: &RepoPath,
823 follow: bool,
824 offset: usize,
825 limit: usize,
826 ) -> impl Future<Output = Result<Vec<CommitSummary>, GitQueryError>> + Send;
827
828 /// How many commits [`log_at_path`](Self::log_at_path) has to give, for the same
829 /// arguments.
830 ///
831 /// Asked with the *same* `follow` the listing uses, deliberately: a total counted
832 /// without following a rename would be smaller than the pages it is meant to
833 /// describe, and a reader would meet a page that says "showing 51–60 of 40".
834 ///
835 /// **One `git` process, and the expensive one.** Without `follow` this is
836 /// `rev-list --count`, which walks but renders nothing and is exact. With it, git's
837 /// `--follow` exists only on `git log`, so the walk is a whole log whose ids are
838 /// counted here — and is **capped**, which is what [`CommitCount::capped`] reports:
839 /// a followed walk reads a tree per commit looking for renames, and on a long
840 /// history that is the read likeliest to meet the timeout. A bounded answer a page
841 /// can label is better than an exact one nobody gets.
842 fn count_commits_at_path(
843 &self,
844 handle: &OrgName,
845 name: &RepoName,
846 rev: &RefName,
847 path: &RepoPath,
848 follow: bool,
849 ) -> impl Future<Output = Result<CommitCount, GitQueryError>> + Send;
850
851 /// What a listing's symlinks point at, by the blob id each link is stored as.
852 ///
853 /// A symlink is a blob whose contents are its target path, so this is a bulk read
854 /// of very small objects — **no `git` process at all**, one round trip to the
855 /// kept-alive `cat-file` per link plus one to size them. Keyed by id rather than by
856 /// name because a listing already holds the ids and two links to the same place
857 /// are one object.
858 ///
859 /// An id that is not a blob, or whose contents are not UTF-8, is simply absent: a
860 /// link Steid cannot read is a link it says nothing about.
861 fn symlink_targets(
862 &self,
863 handle: &OrgName,
864 name: &RepoName,
865 ids: &[ObjectId],
866 ) -> impl Future<Output = Result<HashMap<ObjectId, String>, GitQueryError>> + Send;
867
868 /// What merging `source` into `target` would produce — the merged tree, or the
869 /// paths that conflict.
870 ///
871 /// **A bare repository has no working tree**, which is the whole reason this is one
872 /// method rather than the checkout-merge-commit dance a clone would do. `git
873 /// merge-tree --write-tree` computes the merge entirely in the object database,
874 /// finds the merge base itself, and reports conflicts as a list of paths rather than
875 /// by leaving markers somewhere.
876 ///
877 /// **Needs git 2.38 or newer.** Older versions have a `merge-tree` that means
878 /// something else entirely (a three-way *diff*, not a merge), and it neither takes
879 /// `--write-tree` nor writes a tree. The caller checks the version once at boot and
880 /// does not offer merging where it is absent — this port assumes the check has
881 /// happened and reports an older git as an ordinary failure.
882 ///
883 /// **It writes.** The merged tree and any blobs it needs land in the object
884 /// database, unreferenced, and stay there until git's own garbage collection
885 /// notices. That is what makes the returned [`MergePreview::Clean::tree`] usable by
886 /// `commit_tree` without recomputing anything — and it means asking whether a
887 /// request is mergeable is not quite free, which is why the page asks once.
888 ///
889 /// One `git` process.
890 fn merge_preview(
891 &self,
892 handle: &OrgName,
893 name: &RepoName,
894 target: &ObjectId,
895 source: &ObjectId,
896 ) -> impl Future<Output = Result<MergePreview, GitQueryError>> + Send;
897}
898
899/// How many commits touched a path, and whether the walk that counted them stopped
900/// early.
901///
902/// Two fields rather than a bare number because a capped count is a different statement:
903/// "500" and "at least 500" mean different things to a reader deciding whether they have
904/// seen the whole history, and a page that showed the first as the second would be
905/// lying about a file's age.
906#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
907pub struct CommitCount {
908 /// What the walk found, never more than the cap.
909 pub total: u64,
910 /// Whether there were more and the walk stopped counting.
911 pub capped: bool,
912}
913
914/// What a merge would do.
915///
916/// Not a `Result`: a conflict is an ordinary answer about two branches, and the page
917/// that asked has a sentence to render for it rather than an error to report.
918#[derive(Debug, Clone, PartialEq, Eq)]
919pub enum MergePreview {
920 /// The merge succeeded, and this tree is what it produced.
921 Clean { tree: ObjectId },
922 /// The merge could not be done automatically. The paths are what disagreed, in
923 /// git's order, deduplicated — one path appears once however many stages of it
924 /// conflicted.
925 Conflicted { paths: Vec<String> },
926}
927
928impl MergePreview {
929 pub fn is_clean(&self) -> bool {
930 matches!(self, Self::Clean { .. })
931 }
932}
933
934/// A patch, plus the per-file counts that outlive truncating it.
935///
936/// The two arrive from **one** `git` process, because git will write a `--numstat`
937/// block and a `-p` patch in the same run and writes the counts *first*. That ordering
938/// is the whole reason for asking this way: a diff too large to render still has
939/// complete per-file statistics at the top of what was read, so the page can list every
940/// changed file with its `+a −b` and simply decline to draw the lines. Asking twice
941/// would cost a second process on every commit page to buy something only the rare
942/// oversized one needs.
943#[derive(Debug, Clone, Default, PartialEq, Eq)]
944pub struct RawDiff {
945 /// The `--numstat` block: `<added> TAB <removed> TAB <path>` per changed file, with
946 /// `-` for both counts when the file is binary. Always complete.
947 pub numstat: Vec<u8>,
948 /// The unified patch. Cut short — possibly mid-line — when
949 /// [`truncated`](Self::truncated) is set.
950 pub patch: Vec<u8>,
951 /// Whether the patch hit the byte cap and is therefore not the whole of it.
952 pub truncated: bool,
953}
954/// A repository could not be read.
955#[derive(Debug)]
956pub struct GitQueryError {
957 kind: GitQueryErrorKind,
958 source: Box<dyn std::error::Error + Send + Sync>,
959}
960
961/// Why a read failed — the one distinction a page needs to make.
962///
963/// A timeout is the caller asking too much of one request (blame on a huge file, a grep
964/// across a large tree), and the page should say so and offer less. Anything else is a
965/// fault in the repository or in git, and is a 500.
966#[derive(Debug, Clone, Copy, PartialEq, Eq)]
967pub enum GitQueryErrorKind {
968 Failed,
969 TimedOut,
970}
971
972impl GitQueryError {
973 pub fn new(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
974 Self {
975 kind: GitQueryErrorKind::Failed,
976 source: error.into(),
977 }
978 }
979
980 /// The git process was killed because it exceeded `limit`.
981 pub fn timed_out(limit: std::time::Duration) -> Self {
982 Self {
983 kind: GitQueryErrorKind::TimedOut,
984 source: format!("git did not finish within {limit:?}").into(),
985 }
986 }
987
988 pub fn kind(&self) -> GitQueryErrorKind {
989 self.kind
990 }
991
992 pub fn is_timeout(&self) -> bool {
993 self.kind == GitQueryErrorKind::TimedOut
994 }
995}
996
997impl std::fmt::Display for GitQueryError {
998 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
999 match self.kind {
1000 GitQueryErrorKind::Failed => {
1001 write!(f, "could not read the repository: {}", self.source)
1002 }
1003 GitQueryErrorKind::TimedOut => {
1004 write!(f, "reading the repository took too long: {}", self.source)
1005 }
1006 }
1007 }
1008}
1009
1010impl std::error::Error for GitQueryError {
1011 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1012 Some(&*self.source)
1013 }
1014}
1015
1016/// What an archive is packed as.
1017///
1018/// Two formats because they are what people expect from a forge and what `git archive`
1019/// produces without configuration: `tar.gz` everywhere, `zip` for Windows and for
1020/// anyone who wants to look inside before extracting.
1021#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1022pub enum ArchiveFormat {
1023 TarGz,
1024 Zip,
1025}
1026
1027impl ArchiveFormat {
1028 /// What `git archive --format=` is given. Also the file extension, which is not a
1029 /// coincidence worth breaking apart into two constants.
1030 pub fn as_str(self) -> &'static str {
1031 match self {
1032 Self::TarGz => "tar.gz",
1033 Self::Zip => "zip",
1034 }
1035 }
1036
1037 /// What the response labels the bytes.
1038 ///
1039 /// Honest types, unlike the raw endpoint's deliberate `octet-stream`: neither of
1040 /// these is a type a browser renders, so naming it costs nothing and lets a client
1041 /// decompress without guessing.
1042 pub fn content_type(self) -> &'static str {
1043 match self {
1044 Self::TarGz => "application/gzip",
1045 Self::Zip => "application/zip",
1046 }
1047 }
1048}
1049
1050/// `Result`, never `Option`, per the layer's rule: a silently-defaulted format would
1051/// hand somebody a zip named `.tar.gz`.
1052impl std::str::FromStr for ArchiveFormat {
1053 type Err = DomainError;
1054
1055 fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
1056 match value {
1057 "tar.gz" => Ok(Self::TarGz),
1058 "zip" => Ok(Self::Zip),
1059 other => Err(DomainError::validation(
1060 "format",
1061 format!("unknown archive format {other:?}"),
1062 )),
1063 }
1064 }
1065}
1066
1067/// One repository, packed for download.
1068///
1069/// Every field is built by the use case from values it has already resolved and
1070/// authorized — the commit is an [`ObjectId`] git handed back, never a revision from a
1071/// URL, and the prefix is derived from the repository's own name. Nothing here reaches
1072/// git's revision parser.
1073#[derive(Debug, Clone, PartialEq, Eq)]
1074pub struct ArchiveRequest {
1075 pub handle: OrgName,
1076 pub name: RepoName,
1077 pub format: ArchiveFormat,
1078 pub commit: ObjectId,
1079 /// The directory every entry is nested under, ending in `/`. Extracting an archive
1080 /// that spills its contents into the current directory is a small hostility.
1081 pub prefix: String,
1082}
1083
1084/// Packing a repository into an archive.
1085///
1086/// The fourth narrow git port, and streaming rather than buffered for the same reason
1087/// the protocol is: an archive is as large as the repository, so collecting it would
1088/// bound downloads by RAM. That is the whole reason this is not a [`GitQuery`] method —
1089/// that port's contract is capped bytes, and this one's is a stream.
1090pub trait GitArchive: Send + Sync {
1091 fn archive(
1092 &self,
1093 request: ArchiveRequest,
1094 ) -> impl Future<Output = Result<ByteStream, GitArchiveError>> + Send;
1095}
1096
1097/// A repository could not be packed.
1098///
1099/// No `NotFound`: the use case resolved the commit before asking, so anything failing
1100/// here is git or the filesystem failing.
1101#[derive(Debug)]
1102pub struct GitArchiveError(Box<dyn std::error::Error + Send + Sync>);
1103
1104impl GitArchiveError {
1105 pub fn new(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
1106 Self(error.into())
1107 }
1108}
1109
1110impl std::fmt::Display for GitArchiveError {
1111 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1112 write!(f, "could not archive the repository: {}", self.0)
1113 }
1114}
1115
1116impl std::error::Error for GitArchiveError {
1117 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1118 Some(&*self.0)
1119 }
1120}
1121
1122/// Copying a repository into Steid from somewhere else.
1123///
1124/// The fifth narrow git port. Separate from [`GitStorage`] rather than a second method
1125/// on it because the two have opposite shapes: `init_bare` is a fast local write on a
1126/// request path, and this is a network transfer that can legitimately run for minutes
1127/// and therefore only ever runs in the background.
1128///
1129/// **The adapter, not the caller, is where the address is checked against DNS.**
1130/// [`ImportSource`] already refused a scheme other than `https` and a literal address
1131/// that is not on the public internet, but a hostname can resolve anywhere, and only
1132/// the thing about to open the connection is in a position to look.
1133pub trait GitImport: Send + Sync {
1134 /// Mirrors `source` into the repository's path, leaving an ordinary bare repository
1135 /// behind: every branch under `refs/heads`, every tag under `refs/tags`, `HEAD`
1136 /// pointing at the source's default branch, and no remote configured.
1137 ///
1138 /// Fails rather than adopting anything already at the path — a half-finished import
1139 /// from a killed process must not be silently completed with someone else's history.
1140 fn mirror(
1141 &self,
1142 handle: &OrgName,
1143 name: &RepoName,
1144 source: &ImportSource,
1145 ) -> impl Future<Output = Result<(), GitImportError>> + Send;
1146}
1147
1148/// An import did not finish.
1149///
1150/// One variant, deliberately: every way this fails — a refused address, a repository
1151/// that is not there, a network that gave up, git taking too long — is something the
1152/// owner who typed the URL can read and act on, and nothing else reacts to it
1153/// differently. The message is therefore the whole of the error.
1154#[derive(Debug)]
1155pub struct GitImportError(String);
1156
1157impl GitImportError {
1158 pub fn new(message: impl Into<String>) -> Self {
1159 Self(message.into())
1160 }
1161
1162 /// The reason, for showing to the owner. Safe to render: it is built from git's own
1163 /// output about an address that person supplied.
1164 pub fn message(&self) -> &str {
1165 &self.0
1166 }
1167}
1168
1169impl std::fmt::Display for GitImportError {
1170 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1171 write!(f, "could not import the repository: {}", self.0)
1172 }
1173}
1174
1175impl std::error::Error for GitImportError {}
1176
1177/// Writing a merge into a bare repository.
1178///
1179/// **The fourth git family, and its own narrow port** — the shape
1180/// [0006](../../plans/decisions/0006-git-binary-behind-narrow-ports.md) asks for.
1181/// [`GitStorage`] was the alternative and is the wrong home: its whole subject is a
1182/// repository's *lifecycle* — creating one, moving it, removing it, pointing `HEAD` —
1183/// operations on the repository as a thing. These write objects and refs *inside* one,
1184/// which is a different question with a different failure mode, and folding them in
1185/// would leave `GitStorage` meaning "any git write at all", which is exactly the
1186/// accretion that ADR exists to prevent.
1187///
1188/// Deliberately two verbs and no `merge`. Composing "make the commit" and "move the
1189/// ref" in the use case is what lets a fast-forward skip the first one and a squash
1190/// pass one parent instead of two, without this port growing a strategy enum it would
1191/// then have to keep in step with the domain's.
1192pub trait GitMerge: Send + Sync {
1193 /// Writes a commit object for an existing tree and says what it is called.
1194 ///
1195 /// Writes an object and nothing else: no ref moves, so a commit made and then not
1196 /// referenced is unreachable and costs only disk. That ordering is deliberate —
1197 /// the ref update is the atomic step, and it happens last.
1198 fn commit_tree(
1199 &self,
1200 handle: &OrgName,
1201 name: &RepoName,
1202 request: &CommitTreeRequest,
1203 ) -> impl Future<Output = Result<ObjectId, GitMergeError>> + Send;
1204
1205 /// Moves a branch from `old` to `new`, failing if it is not still at `old`.
1206 ///
1207 /// **The guard is the whole point.** `git update-ref <ref> <new> <old>` is a
1208 /// compare-and-swap: a push that landed between the mergeability check and the
1209 /// merge makes this fail loudly rather than silently discarding what was pushed.
1210 /// The alternative — an unguarded update — would let a merge overwrite a commit
1211 /// nobody ever saw.
1212 fn update_ref(
1213 &self,
1214 handle: &OrgName,
1215 name: &RepoName,
1216 branch: &RefName,
1217 new: &ObjectId,
1218 old: &ObjectId,
1219 ) -> impl Future<Output = Result<(), GitMergeError>> + Send;
1220
1221 /// Deletes a branch, failing if it is not still at `old`.
1222 ///
1223 /// Guarded like [`update_ref`](Self::update_ref), and for a sharper version of the
1224 /// same reason: deleting a branch that moved since the merge would throw away
1225 /// commits that were never merged anywhere.
1226 fn delete_ref(
1227 &self,
1228 handle: &OrgName,
1229 name: &RepoName,
1230 branch: &RefName,
1231 old: &ObjectId,
1232 ) -> impl Future<Output = Result<(), GitMergeError>> + Send;
1233}
1234
1235/// A commit about to be written by [`GitMerge::commit_tree`].
1236///
1237/// A struct rather than seven positional arguments, because four of them are strings
1238/// and two are object ids: a swapped pair would produce a perfectly valid commit
1239/// attributed to the wrong person on the wrong parent.
1240#[derive(Debug, Clone, PartialEq, Eq)]
1241pub struct CommitTreeRequest {
1242 /// The tree the commit points at — [`MergePreview::Clean`]'s, or the source's own
1243 /// for a squash.
1244 pub tree: ObjectId,
1245 /// The commit's parents, in order. Two for a merge commit (target first, so the
1246 /// first-parent line stays the target's history), one for a squash.
1247 pub parents: Vec<ObjectId>,
1248 /// The whole message, subject and body, already assembled.
1249 pub message: String,
1250 /// Who is recorded as author and committer — the person who pressed Merge. Both
1251 /// roles rather than only the committer: nobody else is more the author of a merge
1252 /// commit than whoever decided to make it.
1253 pub author_name: String,
1254 pub author_email: String,
1255 /// The timestamp both identities carry. Passed in rather than left to git's own
1256 /// clock so a use case that takes a `now` actually controls the commit it makes.
1257 pub now: std::time::SystemTime,
1258}
1259
1260/// A merge could not be written.
1261///
1262/// Two variants, because the page's answer differs: [`Stale`](Self::Stale) is somebody
1263/// else having pushed, which is a sentence to render and a page to reload, and
1264/// everything else is a fault.
1265#[derive(Debug)]
1266pub enum GitMergeError {
1267 /// A ref was not where it was expected to be. The merge did nothing.
1268 Stale,
1269 Backend(Box<dyn std::error::Error + Send + Sync>),
1270}
1271
1272impl GitMergeError {
1273 pub fn backend(error: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Self {
1274 Self::Backend(error.into())
1275 }
1276
1277 pub fn is_stale(&self) -> bool {
1278 matches!(self, Self::Stale)
1279 }
1280}
1281
1282impl std::fmt::Display for GitMergeError {
1283 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1284 match self {
1285 Self::Stale => f.write_str(
1286 "the branch moved while the merge was being prepared, so nothing was changed",
1287 ),
1288 Self::Backend(error) => write!(f, "the merge could not be written: {error}"),
1289 }
1290 }
1291}
1292
1293impl std::error::Error for GitMergeError {
1294 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1295 match self {
1296 Self::Stale => None,
1297 Self::Backend(error) => Some(&**error),
1298 }
1299 }
1300}