steid

@jamesgill /

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