steid

@jamesgill /

Rust96.4 KBCode·Blame·History·Raw
1use std::time::SystemTime;
2
3use crate::domain::{
4 Actor, DomainError, ImportSource, ImportState, OrgName, Organization, RefName, RepoId,
5 RepoName, RepoWrite, Repository, Visibility,
6 repository::{IssueRepository, MembershipRepository, OrgRepository, RepoRepository},
7};
8
9use super::{
10 authz::{is_org_member, is_org_owner},
11 error::{Error, Result},
12 port::{GitQuery, GitStorage, GitStorageError},
13};
14
15/// The repository a visitor is asking to create.
16///
17/// Raw input: `name` is whatever was typed, and normalising it is
18/// [`Repository::new`]'s job, not the caller's.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct NewRepo {
21 pub name: String,
22 pub description: Option<String>,
23 pub visibility: Visibility,
24}
25
26/// Creates a repository as a record and as a bare repo on disk.
27///
28/// Owner only. A member's read access is not permission to add to someone's portfolio.
29///
30/// Returns the created [`Repository`] rather than `()` because the name normalises on
31/// the way in — someone who typed `MyRepo` has to be redirected to `myrepo`, and only
32/// the returned value knows that.
33///
34/// **The two writes cannot share a transaction.** The bare repo is created first and
35/// removed again if the record fails to save, per
36/// `plans/architecture.md#db-plus-filesystem-writes`. If the process dies between them
37/// the directory is orphaned; that hole is known and unclosed.
38pub async fn create_repo(
39 actor: &Actor,
40 handle: &OrgName,
41 spec: &NewRepo,
42 orgs: &impl OrgRepository,
43 memberships: &impl MembershipRepository,
44 repos: &impl RepoRepository,
45 storage: &impl GitStorage,
46) -> Result<Repository> {
47 let Some(org) = orgs.find_by_name(handle).await? else {
48 return Err(DomainError::NotFound {
49 entity: "repository owner",
50 }
51 .into());
52 };
53
54 if !is_org_owner(&org, actor, memberships).await? {
55 return Err(DomainError::Forbidden.into());
56 }
57
58 // Validated before anything is written, so a bad name leaves neither a row nor a
59 // directory behind.
60 let repo = Repository::new(
61 RepoId::generate(),
62 org.id.clone(),
63 spec.name.clone(),
64 spec.description.clone(),
65 spec.visibility,
66 // Read here rather than taken as an argument, unlike `touch`: nothing needs to
67 // create a repository *as of* a stated time, and a parameter no caller ever
68 // varies is a parameter every caller has to think about. Revisit if a clock port
69 // appears.
70 SystemTime::now(),
71 )?;
72
73 if repos
74 .find_by_org_and_name(&org.id, &repo.name)
75 .await?
76 .is_some()
77 {
78 return Err(taken());
79 }
80
81 storage
82 .init_bare(handle, &repo.name)
83 .await
84 .map_err(|error| {
85 match error {
86 // No record, but something is already on disk: an orphan from a create that
87 // died between the two writes. The name really is unavailable, so this is
88 // what the visitor is told — at the cost of an orphan being
89 // indistinguishable from a duplicate from the outside. The durable fix is
90 // the reconciliation sweep noted in architecture.md.
91 GitStorageError::AlreadyExists => taken(),
92 other => Error::GitStorage(other),
93 }
94 })?;
95
96 if let Err(error) = repos.save(&repo).await {
97 // Compensation. Safe to delete by path because `init_bare` just proved nothing
98 // was there — this can never remove a repository that won a race, because the
99 // loser of that race never gets past `init_bare`.
100 //
101 // Best effort: if the removal also fails the caller still needs the error that
102 // started this, and an orphaned directory is the documented failure mode.
103 let _ = storage.remove(handle, &repo.name).await;
104 return Err(error.into());
105 }
106
107 Ok(repo)
108}
109
110/// A repository as a viewer is allowed to see it.
111#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct RepoView {
113 /// The owning handle, carried so a page can build links without a second lookup.
114 pub handle: OrgName,
115 pub name: RepoName,
116 pub description: Option<String>,
117 pub visibility: Visibility,
118 /// When code last landed here. The repository page dates itself from this rather
119 /// than asking git, which costs a fork.
120 pub updated_at: SystemTime,
121 /// Whether this repository leads the owner's profile. Here as well as on
122 /// [`RepoSummary`] because the settings page renders the pin control from this view
123 /// and would otherwise have to read the row a second time to know the box's state.
124 pub pinned: bool,
125 /// Whether the repository is archived: readable, not writable. Every repository
126 /// page renders the badge from this, so it travels with the view rather than being
127 /// looked up again per page.
128 pub archived: bool,
129 /// Whether the viewer may change this repository. Decided here so a page and
130 /// `/api` cannot disagree about who sees a management control.
131 pub viewer_is_owner: bool,
132 /// How far an import has got, or `None` for an ordinary repository.
133 ///
134 /// Carried on the view rather than looked up separately because **every page that
135 /// reads a repository has to check it**: the contents are not there yet, and asking
136 /// git for them costs five processes to be told the directory is empty.
137 pub import: Option<ImportStatus>,
138 /// How many issues are open, for the Issues tab.
139 ///
140 /// On the view because the tab is part of the frame *every* repository page draws,
141 /// and a number that appears on three of them is worse than no number at all. One
142 /// `count(*)`, and pull requests will want the same treatment when they arrive.
143 pub open_issues: u64,
144}
145
146/// An import, as a page renders it.
147///
148/// The state, the address and the reason travel together because no page wants one
149/// without the others: the importing panel names the source, and the failed panel names
150/// the source and the reason.
151#[derive(Debug, Clone, PartialEq, Eq)]
152pub struct ImportStatus {
153 pub state: ImportState,
154 pub source: Option<ImportSource>,
155 pub error: Option<String>,
156}
157
158impl ImportStatus {
159 /// Reads the import off a repository, or `None` for an ordinary one.
160 fn of(repo: &Repository) -> Option<Self> {
161 Some(Self {
162 state: repo.import_state?,
163 source: repo.import_source.clone(),
164 error: repo.import_error.clone(),
165 })
166 }
167
168 pub fn is_running(&self) -> bool {
169 self.state == ImportState::Importing
170 }
171}
172
173/// Resolves a handle and name into a repository the viewer may see, as the stored row.
174///
175/// **The authorization half of [`view_repo`], and what the read use cases call.**
176/// Browsing, blame, search, the commit page and the archive endpoint each begin by
177/// asking "may this be seen at all" and then discard the answer, so they should not pay
178/// for a read model — and, since [`view_repo`] now counts issues for the page frame,
179/// paying for it would mean a query per raw blob.
180///
181/// `Ok(None)` covers **both** "no such repository" and "not allowed to see it", and the
182/// caller must render them identically. Distinguishing them would confirm that a private
183/// repository exists and reveal its name, which is the thing being protected — a private
184/// repo has to be absent, not merely unlinked.
185///
186/// Private repositories are visible to any member of the owning organisation, not only
187/// its owner: seeing is weaker than changing.
188pub(crate) async fn visible_repo(
189 handle: &OrgName,
190 name: &RepoName,
191 actor: &Actor,
192 orgs: &impl OrgRepository,
193 memberships: &impl MembershipRepository,
194 repos: &impl RepoRepository,
195) -> Result<Option<(Organization, Repository)>> {
196 let Some(org) = orgs.find_by_name(handle).await? else {
197 return Ok(None);
198 };
199
200 let Some(repo) = repos.find_by_org_and_name(&org.id, name).await? else {
201 return Ok(None);
202 };
203
204 if !repo.visibility.is_public() && !is_org_member(&org, actor, memberships).await? {
205 return Ok(None);
206 }
207
208 Ok(Some((org, repo)))
209}
210
211/// Resolves a handle and name into the repository as a page renders it.
212///
213/// [`visible_repo`] decides whether it may be seen; this adds what the frame every
214/// repository page carries needs, which is one extra query: the open issue count for the
215/// Issues tab. That count used to be an optional parameter the issues pages passed and
216/// nothing else did, so the tab showed a number on three pages out of a dozen — a count
217/// that appears when you click Issues and vanishes when you click Code reads as a bug in
218/// the count rather than as a design.
219///
220/// One `count(*)` per page that draws the header, and *only* those pages: everything
221/// that merely needs the authorization goes through [`visible_repo`] instead.
222pub async fn view_repo(
223 handle: &OrgName,
224 name: &RepoName,
225 actor: &Actor,
226 orgs: &impl OrgRepository,
227 memberships: &impl MembershipRepository,
228 repos: &impl RepoRepository,
229 issues: &impl IssueRepository,
230) -> Result<Option<RepoView>> {
231 let Some((org, repo)) = visible_repo(handle, name, actor, orgs, memberships, repos).await?
232 else {
233 return Ok(None);
234 };
235
236 let open_issues = issues.counts(&repo.id).await?.open;
237
238 Ok(Some(RepoView {
239 handle: org.name.clone(),
240 import: ImportStatus::of(&repo),
241 name: repo.name,
242 description: repo.description,
243 visibility: repo.visibility,
244 updated_at: repo.updated_at,
245 pinned: repo.pinned,
246 archived: repo.archived,
247 viewer_is_owner: is_org_owner(&org, actor, memberships).await?,
248 open_issues,
249 }))
250}
251
252/// A repository as it appears in a listing.
253///
254/// Leaner than [`RepoView`] on purpose: the owning handle and whether the viewer owns
255/// it are constant across a listing and already known to whatever is rendering it.
256#[derive(Debug, Clone, PartialEq, Eq)]
257pub struct RepoSummary {
258 pub name: RepoName,
259 pub description: Option<String>,
260 pub visibility: Visibility,
261 pub updated_at: SystemTime,
262 /// Whether this is the owner's lead repository. Carried in the listing because the
263 /// profile picks the lead *out of* the listing rather than fetching it separately —
264 /// one query, and no chance of the lead and the list disagreeing.
265 pub pinned: bool,
266 /// Whether the repository is archived. Carried for the same reason `pinned` is: the
267 /// profile's badge comes out of the listing rather than a row read per repository.
268 pub archived: bool,
269 /// How far an import has got, or `None` for an ordinary repository.
270 ///
271 /// The state rather than the whole [`ImportStatus`]: a listing row needs to tell
272 /// "still copying" from "did not copy" — a badge saying "Importing" on a row that
273 /// failed an hour ago is a lie — but the address and the reason belong on the page
274 /// that has room for them.
275 pub import_state: Option<ImportState>,
276}
277
278/// Every repository under a handle that the viewer is allowed to see, most recently
279/// updated first — the order [`RepoRepository::list_by_org`] defines.
280///
281/// `Ok(None)` means no such handle — distinct from `Ok(Some(vec![]))`, which means the
282/// handle exists and the viewer can see nothing under it. A caller serving `/api` needs
283/// that difference to answer 404 rather than an empty list.
284///
285/// **The filtering happens here, not in the port.** `list_by_org` deliberately returns
286/// everything, so that the page and `/api` cannot end up applying different rules.
287/// A viewer who may see nothing gets an empty list, never a count or a hint — that
288/// would leak both the existence and the number of private repositories.
289pub async fn list_repos(
290 handle: &OrgName,
291 actor: &Actor,
292 orgs: &impl OrgRepository,
293 memberships: &impl MembershipRepository,
294 repos: &impl RepoRepository,
295) -> Result<Option<Vec<RepoSummary>>> {
296 let Some(org) = orgs.find_by_name(handle).await? else {
297 return Ok(None);
298 };
299
300 // Resolved once rather than per row: membership cannot change mid-listing, and
301 // asking per repository would be a query per repository.
302 let is_member = is_org_member(&org, actor, memberships).await?;
303
304 Ok(Some(
305 repos
306 .list_by_org(&org.id)
307 .await?
308 .into_iter()
309 .filter(|repo| repo.visibility.is_public() || is_member)
310 .map(|repo| RepoSummary {
311 import_state: repo.import_state,
312 name: repo.name,
313 description: repo.description,
314 visibility: repo.visibility,
315 updated_at: repo.updated_at,
316 pinned: repo.pinned,
317 archived: repo.archived,
318 })
319 .collect(),
320 ))
321}
322
323/// Resolves a repository the actor is allowed to **change**.
324///
325/// Two different answers, on purpose, and the split matters:
326///
327/// - A repository the actor may not *see* is [`DomainError::NotFound`], exactly as
328/// [`view_repo`] returns `None` for it. Saying "forbidden" instead would confirm that
329/// a private repository by that name exists, which is the thing being protected.
330/// - A repository the actor *can* see but does not own is [`DomainError::Forbidden`],
331/// matching [`create_repo`]: the resource is public anyway, so pretending it is
332/// missing would be theatre.
333///
334/// A caller that wants to collapse both into a 404 — the settings page does — can; a
335/// caller that wants to explain the difference has the information to.
336pub(crate) async fn changeable_repo(
337 actor: &Actor,
338 handle: &OrgName,
339 name: &RepoName,
340 orgs: &impl OrgRepository,
341 memberships: &impl MembershipRepository,
342 repos: &impl RepoRepository,
343) -> Result<Repository> {
344 let missing = || {
345 Error::Domain(DomainError::NotFound {
346 entity: "repository",
347 })
348 };
349
350 let Some(org) = orgs.find_by_name(handle).await? else {
351 return Err(missing());
352 };
353
354 let Some(repo) = repos.find_by_org_and_name(&org.id, name).await? else {
355 return Err(missing());
356 };
357
358 if !repo.visibility.is_public() && !is_org_member(&org, actor, memberships).await? {
359 return Err(missing());
360 }
361
362 if !is_org_owner(&org, actor, memberships).await? {
363 return Err(DomainError::Forbidden.into());
364 }
365
366 Ok(repo)
367}
368
369/// The changes an owner is asking to make to a repository.
370///
371/// Grouped like [`NewRepo`] rather than passed loose, so that adding a settable field
372/// later does not change every call site — and so the argument list stays readable.
373///
374/// **No `name`.** See [`update_repo`].
375#[derive(Debug, Clone, PartialEq, Eq)]
376pub struct RepoEdit {
377 pub description: Option<String>,
378 pub visibility: Visibility,
379 /// Whether this repository should lead the owner's profile. Setting it unpins
380 /// whichever repository held the spot — see [`update_repo`].
381 pub pinned: bool,
382}
383
384/// Changes a repository's description and visibility.
385///
386/// Owner only. Seeing a private repository is not permission to change it.
387///
388/// **The name is deliberately not changeable here.** A rename is not a column update:
389/// the bare repo lives at `{data_dir}/{handle}/{name}.git`, so renaming means moving a
390/// directory while clones, pushes and in-flight requests point at the old path, and it
391/// needs its own use case with its own answer for the two-writes problem in
392/// `plans/architecture.md#db-plus-filesystem-writes`. Half-doing it — updating the row
393/// and leaving the directory — would break every existing clone silently.
394///
395/// Returns the saved [`Repository`] so a caller can re-render from what was actually
396/// stored rather than from what was submitted; the description normalises on the way in.
397pub async fn update_repo(
398 actor: &Actor,
399 handle: &OrgName,
400 name: &RepoName,
401 edit: &RepoEdit,
402 orgs: &impl OrgRepository,
403 memberships: &impl MembershipRepository,
404 repos: &impl RepoRepository,
405) -> Result<Repository> {
406 let existing = changeable_repo(actor, handle, name, orgs, memberships, repos).await?;
407
408 // Rebuilt through `new` rather than assigned field by field, so the description
409 // length rule lives in exactly one place. The stored name goes back through
410 // validation as a side effect — acceptable because it was validated on the way in
411 // and has not changed, and the alternative is a second copy of the rule here.
412 let mut updated = Repository::new(
413 existing.id,
414 existing.org_id.clone(),
415 existing.name.as_str(),
416 edit.description.clone(),
417 edit.visibility,
418 // The existing timestamp, not the current time. `updated_at` means "code last
419 // landed here" and orders a portfolio by what is being worked on; rewording a
420 // description is not work on the repository and must not jump it to the top.
421 existing.updated_at,
422 )?;
423 updated.pinned = edit.pinned;
424 // Carried, not edited. Archiving is its own use case with its own control; a
425 // description save must not quietly un-archive a repository.
426 updated.archived = existing.archived;
427
428 // **At most one pinned repository per owner**, enforced here rather than in storage.
429 // The rule is not "refuse a second pin" but "pinning this unpins that", and a
430 // constraint — a partial unique index would express the shape exactly — can only
431 // refuse. Enforcing it in the use case also keeps the two `RepoRepository`
432 // implementations from having to agree on a behaviour neither of them is asked for.
433 //
434 // The two writes are not one transaction, so a crash between them can leave nothing
435 // pinned. That is the harmless direction: no lead section, rather than two.
436 if updated.pinned {
437 for other in repos.list_by_org(&existing.org_id).await? {
438 if other.pinned && other.id != updated.id {
439 repos
440 .save(&Repository {
441 pinned: false,
442 ..other
443 })
444 .await?;
445 }
446 }
447 }
448
449 repos.save(&updated).await?;
450
451 Ok(updated)
452}
453
454/// Renames a repository: its record, and the bare repo on disk.
455///
456/// Owner only, and the second of Steid's two writes that cannot share a transaction.
457/// **The directory moves first, then the row**, which is the opposite order from
458/// [`delete_repo`] and the same one as [`create_repo`], for the same reason: a move is
459/// reversible and a delete is not, so the filesystem write can be undone if the record
460/// write fails. If the process dies between them the repository is on disk under its
461/// new name while the row still says the old one, and every page 404s until it is moved
462/// back by hand — the same class of hole `create_repo` documents, and closed by the same
463/// reconciliation sweep in `plans/architecture.md#db-plus-filesystem-writes`.
464///
465/// **Nothing redirects from the old name.** Steid is single tenant and the owner holds
466/// the clones; a permanent alias table would outlive its usefulness on the first repo
467/// that is renamed twice. Existing remotes have to be updated, and the form says so.
468///
469/// Renaming to the name it already has is a no-op rather than an error: the name
470/// normalises on the way in, so `MyRepo` submitted for `myrepo` is somebody confirming
471/// what is already true, not a collision with itself.
472///
473/// **Refused while an import is landing** — [`Repository::refuse_writes`] with
474/// [`RepoWrite::Settings`] — because the directory being moved is the one the clone is
475/// writing into. An archived repository renames freely: archived means finished, not
476/// frozen.
477#[allow(clippy::too_many_arguments)]
478pub async fn rename_repo(
479 actor: &Actor,
480 handle: &OrgName,
481 name: &RepoName,
482 new_name: &str,
483 orgs: &impl OrgRepository,
484 memberships: &impl MembershipRepository,
485 repos: &impl RepoRepository,
486 storage: &impl GitStorage,
487) -> Result<Repository> {
488 let existing = changeable_repo(actor, handle, name, orgs, memberships, repos).await?;
489
490 // Nothing moves while an import is landing: the directory `git clone --mirror` is
491 // writing into is the one this would rename, and git holds a path, not a row. An
492 // *archived* repository renames freely — see [`RepoWrite`].
493 existing.refuse_writes(RepoWrite::Settings)?;
494
495 // Rebuilt through `new` rather than assigning a `RepoName`, so the reserved list and
496 // the traversal rules are applied to the new name exactly as they were to the old.
497 // Validated before anything moves, so a bad name leaves the repository untouched.
498 let mut renamed = Repository::new(
499 existing.id.clone(),
500 existing.org_id.clone(),
501 new_name,
502 existing.description.clone(),
503 existing.visibility,
504 // `updated_at` means "code last landed here". A rename is not a push.
505 existing.updated_at,
506 )?;
507 renamed.pinned = existing.pinned;
508 renamed.archived = existing.archived;
509
510 if renamed.name == existing.name {
511 return Ok(existing);
512 }
513
514 if repos
515 .find_by_org_and_name(&existing.org_id, &renamed.name)
516 .await?
517 .is_some()
518 {
519 return Err(taken());
520 }
521
522 storage
523 .rename(handle, &existing.name, &renamed.name)
524 .await
525 .map_err(|error| match error {
526 // Something is already at the destination with no record to match — an
527 // orphan, exactly as in `create_repo`. The name is genuinely unavailable.
528 GitStorageError::AlreadyExists => taken(),
529 other => Error::GitStorage(other),
530 })?;
531
532 if let Err(error) = repos.save(&renamed).await {
533 // Compensation. Safe because the move above proved the destination was empty,
534 // and the source is the path this repository's own row still names.
535 let _ = storage.rename(handle, &renamed.name, &existing.name).await;
536 return Err(error.into());
537 }
538
539 Ok(renamed)
540}
541
542/// Points the repository's `HEAD` at a different branch.
543///
544/// Owner only. **Nothing is stored in the database**: git already holds the answer, and
545/// every read of it goes through [`GitQuery::default_branch`], so a column would be a
546/// second answer that can drift from the first — see
547/// [`GitStorage::set_default_branch`].
548///
549/// The branch has to exist, and is checked against the repository's own branch list
550/// rather than trusted: `symbolic-ref` will happily point `HEAD` at a branch that is
551/// not there, which is precisely the state an empty repository is in, and doing it to a
552/// repository with commits makes every page say "nothing pushed yet".
553///
554/// **One `git` process to check, one to write.** An empty repository has no branches to
555/// choose from, so the caller does not offer the control at all.
556#[allow(clippy::too_many_arguments)]
557pub async fn set_default_branch(
558 actor: &Actor,
559 handle: &OrgName,
560 name: &RepoName,
561 branch: &str,
562 orgs: &impl OrgRepository,
563 memberships: &impl MembershipRepository,
564 repos: &impl RepoRepository,
565 queries: &impl GitQuery,
566 storage: &impl GitStorage,
567) -> Result<RefName> {
568 let repo = changeable_repo(actor, handle, name, orgs, memberships, repos).await?;
569
570 // Validated before it reaches git, the same way a revision from a URL is: this
571 // value ends up as an argument to the binary.
572 let branch = RefName::new(branch)?;
573
574 let exists = queries
575 .branches(handle, &repo.name)
576 .await?
577 .iter()
578 .any(|row| row.name == branch);
579
580 if !exists {
581 return Err(DomainError::NotFound { entity: "branch" }.into());
582 }
583
584 storage
585 .set_default_branch(handle, &repo.name, &branch)
586 .await?;
587
588 Ok(branch)
589}
590
591/// Archives or unarchives a repository.
592///
593/// Owner only. An archived repository is **finished, not hidden**: everything that
594/// reads keeps working — browsing, cloning, search, archive download — and only writing
595/// stops. The refusal itself lives in [`serve_git`](super::git::serve_git), beside the
596/// `Role::Owner` check, so it applies to every transport rather than to one handler.
597///
598/// Separate from [`update_repo`] rather than a field on [`RepoEdit`], because it is a
599/// state change with its own consequence and its own control: bundling it into the
600/// description form would let a mistyped save silently reopen a repository for writing.
601///
602/// Idempotent. Archiving an archived repository is what a double-clicked button does.
603///
604/// **Refused while an import is landing**, in either direction — see
605/// [`Repository::refuse_writes`]. Declaring a repository finished before its contents
606/// have arrived says something untrue about it, and the state it would be left in is one
607/// no page renders.
608pub async fn set_repo_archived(
609 actor: &Actor,
610 handle: &OrgName,
611 name: &RepoName,
612 archived: bool,
613 orgs: &impl OrgRepository,
614 memberships: &impl MembershipRepository,
615 repos: &impl RepoRepository,
616) -> Result<Repository> {
617 let existing = changeable_repo(actor, handle, name, orgs, memberships, repos).await?;
618
619 // Not while an import is landing, in either direction: "finished" is not a thing to
620 // say about a repository whose contents have not arrived, and the panel the owner is
621 // looking at offers Delete for exactly this case.
622 existing.refuse_writes(RepoWrite::Settings)?;
623
624 // `updated_at` is untouched: archiving is not code landing, and a portfolio ordered
625 // by recency must not float a finished repository to the top on the day it is
626 // declared finished.
627 let updated = Repository {
628 archived,
629 ..existing
630 };
631
632 repos.save(&updated).await?;
633
634 Ok(updated)
635}
636
637/// Deletes a repository: its record, and the bare repo on disk.
638///
639/// Owner only, and irreversible — the git history goes with it.
640///
641/// **The row goes first, then the directory.** The two writes cannot share a
642/// transaction, so one of the two orphans is possible, and this picks the less harmful
643/// one deliberately. An orphaned *directory* only blocks reusing that name, and is
644/// already the documented failure mode of [`create_repo`]'s compensation path. An
645/// orphaned *row* is worse and visible: a repository that still lists on the profile and
646/// 404s the moment anyone clicks it.
647///
648/// If the directory cannot be removed this still reports success, because as far as
649/// Steid is concerned the repository genuinely is gone — there is nothing the caller
650/// could usefully do about it, and failing here would leave the visitor thinking the
651/// delete had not happened when the record is already destroyed. The failure is logged.
652pub async fn delete_repo(
653 actor: &Actor,
654 handle: &OrgName,
655 name: &RepoName,
656 orgs: &impl OrgRepository,
657 memberships: &impl MembershipRepository,
658 repos: &impl RepoRepository,
659 storage: &impl GitStorage,
660) -> Result<()> {
661 let repo = changeable_repo(actor, handle, name, orgs, memberships, repos).await?;
662
663 repos.delete(&repo.id).await?;
664
665 if let Err(error) = storage.remove(handle, &repo.name).await {
666 eprintln!(
667 "steid: repository {handle}/{} deleted, but its directory could not be removed: {error}",
668 repo.name
669 );
670 }
671
672 Ok(())
673}
674
675fn taken() -> Error {
676 DomainError::AlreadyExists {
677 entity: "repository",
678 }
679 .into()
680}
681
682#[cfg(test)]
683mod tests {
684 use super::*;
685 use crate::{
686 domain::{
687 Issue, IssueId, IssueNumber, Membership, MembershipId, OrgId, Organization, RepoName,
688 Role, UserId,
689 repository::{RepositoryError, RepositoryResult},
690 },
691 infrastructure::{
692 git::{DiskGitStorage, InMemoryGitQuery, InMemoryGitStorage},
693 repository::{
694 InMemoryIssueRepo, InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryRepoRepo,
695 },
696 },
697 };
698
699 fn at(seconds: u64) -> SystemTime {
700 SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(seconds)
701 }
702
703 /// A `RepoRepository` whose `save` always fails, for exercising compensation.
704 ///
705 /// Test-local on purpose: fault injection does not belong in the shared fake, where
706 /// every other test would have to know about it.
707 #[derive(Debug, Default)]
708 struct FailingRepoRepo;
709
710 impl RepoRepository for FailingRepoRepo {
711 async fn find_by_id(&self, _id: &RepoId) -> RepositoryResult<Option<Repository>> {
712 Ok(None)
713 }
714
715 async fn find_by_org_and_name(
716 &self,
717 _org_id: &OrgId,
718 _name: &RepoName,
719 ) -> RepositoryResult<Option<Repository>> {
720 Ok(None)
721 }
722
723 async fn list_by_org(&self, _org_id: &OrgId) -> RepositoryResult<Vec<Repository>> {
724 Ok(Vec::new())
725 }
726
727 async fn save(&self, _repo: &Repository) -> RepositoryResult<()> {
728 Err(RepositoryError::backend("save failed on purpose"))
729 }
730
731 async fn touch(&self, _id: &RepoId, _now: SystemTime) -> RepositoryResult<()> {
732 Ok(())
733 }
734
735 async fn fail_interrupted_imports(&self, _reason: &str) -> RepositoryResult<u64> {
736 Ok(0)
737 }
738
739 async fn delete(&self, _id: &RepoId) -> RepositoryResult<()> {
740 Ok(())
741 }
742 }
743
744 struct Fixture {
745 orgs: InMemoryOrgRepo,
746 memberships: InMemoryMembershipRepo,
747 repos: InMemoryRepoRepo,
748 /// Only the open count the view carries comes from here, but a page's frame reads
749 /// it on every repository page, so the fixture has one.
750 issues: InMemoryIssueRepo,
751 storage: InMemoryGitStorage,
752 owner: Actor,
753 member: Actor,
754 stranger: Actor,
755 handle: OrgName,
756 }
757
758 async fn fixture() -> Fixture {
759 let orgs = InMemoryOrgRepo::new();
760 let memberships = InMemoryMembershipRepo::new();
761
762 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
763 orgs.save(&org).await.expect("save org");
764
765 let owner = UserId::generate();
766 let member = UserId::generate();
767
768 for (user, role) in [(&owner, Role::Owner), (&member, Role::Member)] {
769 memberships
770 .save(&Membership::new(
771 MembershipId::generate(),
772 org.id.clone(),
773 user.clone(),
774 role,
775 ))
776 .await
777 .expect("save membership");
778 }
779
780 Fixture {
781 orgs,
782 memberships,
783 repos: InMemoryRepoRepo::new(),
784 issues: InMemoryIssueRepo::new(),
785 storage: InMemoryGitStorage::new(),
786 owner: Actor::User(owner),
787 member: Actor::User(member),
788 stranger: Actor::User(UserId::generate()),
789 handle: org.name,
790 }
791 }
792
793 fn spec(name: &str) -> NewRepo {
794 NewRepo {
795 name: name.to_owned(),
796 description: None,
797 visibility: Visibility::Public,
798 }
799 }
800
801 impl Fixture {
802 async fn create(&self, actor: &Actor, spec: &NewRepo) -> Result<Repository> {
803 create_repo(
804 actor,
805 &self.handle,
806 spec,
807 &self.orgs,
808 &self.memberships,
809 &self.repos,
810 &self.storage,
811 )
812 .await
813 }
814 }
815
816 #[tokio::test]
817 async fn the_owner_creates_a_record_and_a_bare_repo() {
818 let f = fixture().await;
819
820 let repo = f
821 .create(&f.owner, &spec("steid"))
822 .await
823 .expect("should create");
824
825 assert_eq!(repo.name.as_str(), "steid");
826 assert!(
827 f.repos
828 .find_by_org_and_name(&repo.org_id, &repo.name)
829 .await
830 .expect("lookup")
831 .is_some()
832 );
833 assert!(f.storage.contains(&f.handle, &repo.name));
834 }
835
836 #[tokio::test]
837 async fn an_anonymous_visitor_is_refused() {
838 let f = fixture().await;
839
840 let error = f
841 .create(&Actor::Anonymous, &spec("steid"))
842 .await
843 .expect_err("should refuse");
844
845 assert!(matches!(error, Error::Domain(DomainError::Forbidden)));
846 assert!(f.storage.is_empty());
847 }
848
849 #[tokio::test]
850 async fn a_signed_in_stranger_is_refused() {
851 // Signed in is not the same as allowed.
852 let f = fixture().await;
853
854 let error = f
855 .create(&f.stranger, &spec("steid"))
856 .await
857 .expect_err("should refuse");
858
859 assert!(matches!(error, Error::Domain(DomainError::Forbidden)));
860 assert!(f.storage.is_empty());
861 }
862
863 #[tokio::test]
864 async fn a_non_owner_member_is_refused() {
865 // Membership is read access, not permission to add to someone's portfolio.
866 let f = fixture().await;
867
868 let error = f
869 .create(&f.member, &spec("steid"))
870 .await
871 .expect_err("should refuse");
872
873 assert!(matches!(error, Error::Domain(DomainError::Forbidden)));
874 assert!(f.storage.is_empty());
875 }
876
877 #[tokio::test]
878 async fn an_unknown_handle_is_not_found() {
879 let f = fixture().await;
880 let missing = OrgName::new("nobody").expect("valid handle");
881
882 let error = create_repo(
883 &f.owner,
884 &missing,
885 &spec("steid"),
886 &f.orgs,
887 &f.memberships,
888 &f.repos,
889 &f.storage,
890 )
891 .await
892 .expect_err("should not find");
893
894 assert!(matches!(
895 error,
896 Error::Domain(DomainError::NotFound {
897 entity: "repository owner"
898 })
899 ));
900 }
901
902 #[tokio::test]
903 async fn an_invalid_name_writes_nothing() {
904 // Validation precedes both side effects, so a rejected name leaves no trace.
905 let f = fixture().await;
906
907 let error = f
908 .create(&f.owner, &spec("../escape"))
909 .await
910 .expect_err("should reject");
911
912 assert!(matches!(
913 error,
914 Error::Domain(DomainError::Validation { .. })
915 ));
916 assert!(f.storage.is_empty());
917 }
918
919 #[tokio::test]
920 async fn a_duplicate_name_is_refused_and_changes_nothing() {
921 let f = fixture().await;
922 let first = f
923 .create(&f.owner, &spec("steid"))
924 .await
925 .expect("should create");
926
927 let error = f
928 .create(&f.owner, &spec("steid"))
929 .await
930 .expect_err("should refuse");
931
932 assert!(matches!(
933 error,
934 Error::Domain(DomainError::AlreadyExists {
935 entity: "repository"
936 })
937 ));
938 assert_eq!(f.storage.len(), 1, "the existing repo should be untouched");
939 assert_eq!(
940 f.repos
941 .find_by_org_and_name(&first.org_id, &first.name)
942 .await
943 .expect("lookup")
944 .expect("still there")
945 .id,
946 first.id
947 );
948 }
949
950 #[tokio::test]
951 async fn a_duplicate_is_caught_case_insensitively() {
952 // The name normalises, so `Steid` and `steid` are the same repository.
953 let f = fixture().await;
954 f.create(&f.owner, &spec("steid"))
955 .await
956 .expect("should create");
957
958 let error = f
959 .create(&f.owner, &spec("Steid"))
960 .await
961 .expect_err("should refuse");
962
963 assert!(matches!(
964 error,
965 Error::Domain(DomainError::AlreadyExists {
966 entity: "repository"
967 })
968 ));
969 }
970
971 #[tokio::test]
972 async fn an_orphaned_directory_reads_as_a_taken_name() {
973 // No record, but the path is occupied — a create that died between the writes.
974 // The visitor is told the name is taken, because from outside it is.
975 let f = fixture().await;
976 let name = RepoName::new("steid").expect("valid");
977 f.storage
978 .init_bare(&f.handle, &name)
979 .await
980 .expect("orphan the directory");
981
982 let error = f
983 .create(&f.owner, &spec("steid"))
984 .await
985 .expect_err("should refuse");
986
987 assert!(matches!(
988 error,
989 Error::Domain(DomainError::AlreadyExists {
990 entity: "repository"
991 })
992 ));
993 }
994
995 #[tokio::test]
996 async fn the_name_is_normalised_in_what_comes_back() {
997 // The caller redirects using this, so it has to be the stored form.
998 let f = fixture().await;
999
1000 let repo = f
1001 .create(&f.owner, &spec(" MyRepo "))
1002 .await
1003 .expect("should create");
1004
1005 assert_eq!(repo.name.as_str(), "myrepo");
1006 assert!(f.storage.contains(&f.handle, &repo.name));
1007 }
1008
1009 #[tokio::test]
1010 async fn visibility_and_description_are_carried_through() {
1011 let f = fixture().await;
1012
1013 let repo = f
1014 .create(
1015 &f.owner,
1016 &NewRepo {
1017 name: "steid".to_owned(),
1018 description: Some(" A gitforge. ".to_owned()),
1019 visibility: Visibility::Private,
1020 },
1021 )
1022 .await
1023 .expect("should create");
1024
1025 assert_eq!(repo.visibility, Visibility::Private);
1026 assert_eq!(repo.description.as_deref(), Some("A gitforge."));
1027 }
1028
1029 #[tokio::test]
1030 async fn a_blank_description_is_stored_as_unset() {
1031 let f = fixture().await;
1032
1033 let repo = f
1034 .create(
1035 &f.owner,
1036 &NewRepo {
1037 name: "steid".to_owned(),
1038 description: Some(" ".to_owned()),
1039 visibility: Visibility::Public,
1040 },
1041 )
1042 .await
1043 .expect("should create");
1044
1045 assert_eq!(repo.description, None);
1046 }
1047
1048 #[tokio::test]
1049 async fn a_failed_save_removes_the_bare_repo() {
1050 // The compensating transaction. Without it every failed insert leaks a
1051 // directory that then blocks the name forever.
1052 let f = fixture().await;
1053
1054 let error = create_repo(
1055 &f.owner,
1056 &f.handle,
1057 &spec("steid"),
1058 &f.orgs,
1059 &f.memberships,
1060 &FailingRepoRepo,
1061 &f.storage,
1062 )
1063 .await
1064 .expect_err("should fail");
1065
1066 assert!(matches!(error, Error::Repository(_)));
1067 assert!(
1068 f.storage.is_empty(),
1069 "the bare repo should have been compensated away"
1070 );
1071 }
1072
1073 #[tokio::test]
1074 async fn a_successful_save_keeps_the_bare_repo() {
1075 // The other half of the above: compensation must not fire on the happy path.
1076 let f = fixture().await;
1077
1078 let repo = f
1079 .create(&f.owner, &spec("steid"))
1080 .await
1081 .expect("should create");
1082
1083 assert!(f.storage.contains(&f.handle, &repo.name));
1084 }
1085
1086 #[tokio::test]
1087 async fn a_compensated_name_can_be_created_again() {
1088 let f = fixture().await;
1089 let _ = create_repo(
1090 &f.owner,
1091 &f.handle,
1092 &spec("steid"),
1093 &f.orgs,
1094 &f.memberships,
1095 &FailingRepoRepo,
1096 &f.storage,
1097 )
1098 .await;
1099
1100 f.create(&f.owner, &spec("steid"))
1101 .await
1102 .expect("the name should be free again");
1103 }
1104
1105 /// The one test that runs the real adapter. Everything above proves the use case's
1106 /// logic against a fake; this proves the record and the directory actually both
1107 /// appear when it is wired to disk.
1108 #[tokio::test]
1109 async fn against_real_disk_storage_both_the_row_and_the_repo_appear() {
1110 let f = fixture().await;
1111 let dir = tempfile::TempDir::new().expect("temp dir");
1112 let storage = DiskGitStorage::new(dir.path());
1113
1114 let repo = create_repo(
1115 &f.owner,
1116 &f.handle,
1117 &spec("steid"),
1118 &f.orgs,
1119 &f.memberships,
1120 &f.repos,
1121 &storage,
1122 )
1123 .await
1124 .expect("should create");
1125
1126 assert!(
1127 f.repos
1128 .find_by_id(&repo.id)
1129 .await
1130 .expect("lookup")
1131 .is_some()
1132 );
1133 assert!(dir.path().join("acme").join("steid.git").is_dir());
1134 }
1135
1136 // --- view_repo -------------------------------------------------------------
1137
1138 impl Fixture {
1139 async fn view(&self, actor: &Actor, name: &str) -> Option<RepoView> {
1140 view_repo(
1141 &self.handle,
1142 &RepoName::new(name).expect("valid name"),
1143 actor,
1144 &self.orgs,
1145 &self.memberships,
1146 &self.repos,
1147 &self.issues,
1148 )
1149 .await
1150 .expect("lookup should not error")
1151 }
1152
1153 /// Creates a repository and dates it, so an ordering test states its own times
1154 /// rather than depending on how fast it runs.
1155 async fn create_dated(&self, name: &str, seconds: u64) -> Repository {
1156 let repo = self.create_with(Visibility::Public, name).await;
1157 self.repos
1158 .touch(&repo.id, at(seconds))
1159 .await
1160 .expect("touch");
1161 Repository {
1162 updated_at: at(seconds),
1163 ..repo
1164 }
1165 }
1166
1167 async fn create_with(&self, visibility: Visibility, name: &str) -> Repository {
1168 self.create(
1169 &self.owner,
1170 &NewRepo {
1171 name: name.to_owned(),
1172 description: None,
1173 visibility,
1174 },
1175 )
1176 .await
1177 .expect("should create")
1178 }
1179 }
1180
1181 #[tokio::test]
1182 async fn a_public_repository_is_visible_to_anyone() {
1183 let f = fixture().await;
1184 f.create_with(Visibility::Public, "steid").await;
1185
1186 for actor in [&Actor::Anonymous, &f.stranger, &f.member, &f.owner] {
1187 assert!(
1188 f.view(actor, "steid").await.is_some(),
1189 "public repo should be visible to {actor:?}"
1190 );
1191 }
1192 }
1193
1194 #[tokio::test]
1195 async fn a_private_repository_is_absent_for_outsiders() {
1196 // `None`, not an error: distinguishing "forbidden" from "missing" would confirm
1197 // the repository exists and reveal its name.
1198 let f = fixture().await;
1199 f.create_with(Visibility::Private, "secret").await;
1200
1201 assert!(f.view(&Actor::Anonymous, "secret").await.is_none());
1202 assert!(f.view(&f.stranger, "secret").await.is_none());
1203 }
1204
1205 #[tokio::test]
1206 async fn a_private_repository_is_visible_to_any_member() {
1207 // Seeing is weaker than changing: a member who may not create repositories may
1208 // still read the private ones.
1209 let f = fixture().await;
1210 f.create_with(Visibility::Private, "secret").await;
1211
1212 assert!(f.view(&f.member, "secret").await.is_some());
1213 assert!(f.view(&f.owner, "secret").await.is_some());
1214 }
1215
1216 #[tokio::test]
1217 async fn viewer_is_owner_tracks_the_actor() {
1218 let f = fixture().await;
1219 f.create_with(Visibility::Public, "steid").await;
1220
1221 assert!(
1222 f.view(&f.owner, "steid")
1223 .await
1224 .expect("visible")
1225 .viewer_is_owner
1226 );
1227 for actor in [&Actor::Anonymous, &f.stranger, &f.member] {
1228 assert!(
1229 !f.view(actor, "steid")
1230 .await
1231 .expect("visible")
1232 .viewer_is_owner,
1233 "{actor:?} should not be treated as owner"
1234 );
1235 }
1236 }
1237
1238 #[tokio::test]
1239 async fn an_unknown_repository_is_absent() {
1240 let f = fixture().await;
1241 f.create_with(Visibility::Public, "steid").await;
1242
1243 assert!(f.view(&f.owner, "nothing-here").await.is_none());
1244 }
1245
1246 #[tokio::test]
1247 async fn an_unknown_handle_is_absent() {
1248 let f = fixture().await;
1249 let missing = OrgName::new("nobody").expect("valid handle");
1250
1251 let found = view_repo(
1252 &missing,
1253 &RepoName::new("steid").expect("valid"),
1254 &f.owner,
1255 &f.orgs,
1256 &f.memberships,
1257 &f.repos,
1258 &f.issues,
1259 )
1260 .await
1261 .expect("lookup should not error");
1262
1263 assert!(found.is_none());
1264 }
1265
1266 #[tokio::test]
1267 async fn the_view_carries_what_a_page_needs() {
1268 let f = fixture().await;
1269 f.create(
1270 &f.owner,
1271 &NewRepo {
1272 name: "steid".to_owned(),
1273 description: Some("A gitforge.".to_owned()),
1274 visibility: Visibility::Private,
1275 },
1276 )
1277 .await
1278 .expect("should create");
1279
1280 let view = f.view(&f.owner, "steid").await.expect("visible");
1281
1282 assert_eq!(view.handle.as_str(), "acme");
1283 assert_eq!(view.name.as_str(), "steid");
1284 assert_eq!(view.description.as_deref(), Some("A gitforge."));
1285 assert_eq!(view.visibility, Visibility::Private);
1286 assert_eq!(view.open_issues, 0);
1287 }
1288
1289 #[tokio::test]
1290 async fn the_view_counts_the_open_issues_for_the_tab() {
1291 // On the view rather than passed by the issues pages, so the Issues tab states
1292 // the same number wherever you are in the repository. Closed issues are not in
1293 // it: the tab answers "is there anything outstanding".
1294 let f = fixture().await;
1295 let repo = f.create_with(Visibility::Public, "steid").await;
1296
1297 for number in 1..=3 {
1298 let mut issue = Issue::new(
1299 IssueId::generate(),
1300 repo.id.clone(),
1301 IssueNumber::from_trusted(number),
1302 format!("Issue {number}"),
1303 "",
1304 UserId::generate(),
1305 at(1_000),
1306 )
1307 .expect("valid issue");
1308
1309 if number == 3 {
1310 issue.close(at(2_000));
1311 }
1312
1313 f.issues.save(&issue).await.expect("save");
1314 }
1315
1316 let view = f.view(&f.owner, "steid").await.expect("visible");
1317
1318 assert_eq!(view.open_issues, 2);
1319 }
1320
1321 #[tokio::test]
1322 async fn lookup_is_case_insensitive_through_the_name_type() {
1323 let f = fixture().await;
1324 f.create_with(Visibility::Public, "MyRepo").await;
1325
1326 assert!(f.view(&Actor::Anonymous, "myrepo").await.is_some());
1327 }
1328
1329 // --- list_repos ------------------------------------------------------------
1330
1331 impl Fixture {
1332 async fn list(&self, actor: &Actor) -> Vec<RepoSummary> {
1333 list_repos(
1334 &self.handle,
1335 actor,
1336 &self.orgs,
1337 &self.memberships,
1338 &self.repos,
1339 )
1340 .await
1341 .expect("listing should not error")
1342 .expect("the handle exists")
1343 }
1344
1345 fn names(summaries: &[RepoSummary]) -> Vec<&str> {
1346 summaries.iter().map(|repo| repo.name.as_str()).collect()
1347 }
1348 }
1349
1350 /// Two public and one private, dated so that recency and the alphabet disagree.
1351 ///
1352 /// `zebra` is the most recent and `alpha` the oldest, so a listing that came back
1353 /// alphabetical would be visibly wrong rather than accidentally right.
1354 async fn mixed() -> Fixture {
1355 let f = fixture().await;
1356 f.create_dated("zebra", 3_000).await;
1357 f.repos
1358 .save(&Repository {
1359 updated_at: at(2_000),
1360 ..f.create_with(Visibility::Private, "secret").await
1361 })
1362 .await
1363 .expect("date the private repo");
1364 f.create_dated("alpha", 1_000).await;
1365 f
1366 }
1367
1368 #[tokio::test]
1369 async fn outsiders_see_only_public_repositories() {
1370 let f = mixed().await;
1371
1372 for actor in [&Actor::Anonymous, &f.stranger] {
1373 let listed = f.list(actor).await;
1374 assert_eq!(
1375 Fixture::names(&listed),
1376 vec!["zebra", "alpha"],
1377 "{actor:?} should see only the public repositories"
1378 );
1379 }
1380 }
1381
1382 #[tokio::test]
1383 async fn members_and_owners_see_private_repositories_too() {
1384 let f = mixed().await;
1385
1386 for actor in [&f.member, &f.owner] {
1387 let listed = f.list(actor).await;
1388 assert_eq!(
1389 Fixture::names(&listed),
1390 vec!["zebra", "secret", "alpha"],
1391 "{actor:?} should see everything"
1392 );
1393 }
1394 }
1395
1396 #[tokio::test]
1397 async fn listings_are_ordered_by_recency_not_by_name() {
1398 // Changed deliberately from alphabetical: the profile is a portfolio, and
1399 // alphabetical is a filing rule that puts `dotfiles` above the thing being built.
1400 let f = mixed().await;
1401
1402 assert_eq!(
1403 Fixture::names(&f.list(&f.owner).await),
1404 vec!["zebra", "secret", "alpha"]
1405 );
1406 }
1407
1408 #[tokio::test]
1409 async fn repositories_updated_in_the_same_second_are_ordered_by_name() {
1410 // Every repository that predates `updated_at` shares one timestamp, so without a
1411 // tiebreak a profile would reshuffle itself between page loads.
1412 let f = fixture().await;
1413 for name in ["zebra", "alpha", "middle"] {
1414 f.create_dated(name, 1_000).await;
1415 }
1416
1417 assert_eq!(
1418 Fixture::names(&f.list(&f.owner).await),
1419 vec!["alpha", "middle", "zebra"]
1420 );
1421 }
1422
1423 #[tokio::test]
1424 async fn a_new_repository_is_dated_when_it_was_created() {
1425 let f = fixture().await;
1426 let before = SystemTime::now();
1427
1428 let repo = f.create_with(Visibility::Public, "steid").await;
1429
1430 assert!(repo.updated_at >= before);
1431 assert!(repo.updated_at <= SystemTime::now());
1432 assert!(!repo.pinned, "nothing leads a profile by being created");
1433 }
1434
1435 #[tokio::test]
1436 async fn a_viewer_who_may_see_nothing_gets_an_empty_list() {
1437 // Not a count, not a hint. Either would leak that private repositories exist
1438 // and how many.
1439 let f = fixture().await;
1440 f.create_with(Visibility::Private, "secret").await;
1441 f.create_with(Visibility::Private, "other").await;
1442
1443 assert!(f.list(&Actor::Anonymous).await.is_empty());
1444 }
1445
1446 #[tokio::test]
1447 async fn a_handle_with_no_repositories_lists_nothing() {
1448 let f = fixture().await;
1449
1450 assert!(f.list(&f.owner).await.is_empty());
1451 }
1452
1453 #[tokio::test]
1454 async fn an_unknown_handle_is_none_not_an_empty_list() {
1455 // `/api` has to answer 404 for a handle that does not exist rather than `[]`.
1456 let f = fixture().await;
1457 let missing = OrgName::new("nobody").expect("valid handle");
1458
1459 let listed = list_repos(&missing, &f.owner, &f.orgs, &f.memberships, &f.repos)
1460 .await
1461 .expect("listing should not error");
1462
1463 assert!(listed.is_none());
1464 }
1465
1466 #[tokio::test]
1467 async fn a_summary_carries_what_a_listing_renders() {
1468 let f = fixture().await;
1469 f.create(
1470 &f.owner,
1471 &NewRepo {
1472 name: "steid".to_owned(),
1473 description: Some("A gitforge.".to_owned()),
1474 visibility: Visibility::Private,
1475 },
1476 )
1477 .await
1478 .expect("should create");
1479
1480 let listed = f.list(&f.owner).await;
1481 let summary = listed.first().expect("one repository");
1482
1483 assert_eq!(summary.name.as_str(), "steid");
1484 assert_eq!(summary.description.as_deref(), Some("A gitforge."));
1485 assert_eq!(summary.visibility, Visibility::Private);
1486 // The profile dates each row and picks its lead out of the listing, so both
1487 // travel with the summary rather than costing a second lookup.
1488 assert!(!summary.pinned);
1489 assert!(summary.updated_at <= SystemTime::now());
1490 }
1491
1492 #[tokio::test]
1493 async fn listing_only_covers_the_handle_asked_for() {
1494 let f = fixture().await;
1495 f.create_with(Visibility::Public, "mine").await;
1496
1497 let other = Organization::new(OrgId::generate(), "other-org", None).expect("valid org");
1498 f.orgs.save(&other).await.expect("save org");
1499 f.repos
1500 .save(
1501 &Repository::new(
1502 RepoId::generate(),
1503 other.id.clone(),
1504 "theirs",
1505 None,
1506 Visibility::Public,
1507 SystemTime::now(),
1508 )
1509 .expect("valid repo"),
1510 )
1511 .await
1512 .expect("save repo");
1513
1514 assert_eq!(
1515 Fixture::names(&f.list(&Actor::Anonymous).await),
1516 vec!["mine"]
1517 );
1518 }
1519 // --- update_repo -----------------------------------------------------------
1520
1521 impl Fixture {
1522 async fn update(
1523 &self,
1524 actor: &Actor,
1525 name: &str,
1526 description: Option<&str>,
1527 visibility: Visibility,
1528 ) -> Result<Repository> {
1529 update_repo(
1530 actor,
1531 &self.handle,
1532 &RepoName::new(name).expect("valid name"),
1533 &RepoEdit {
1534 description: description.map(str::to_owned),
1535 visibility,
1536 pinned: false,
1537 },
1538 &self.orgs,
1539 &self.memberships,
1540 &self.repos,
1541 )
1542 .await
1543 }
1544
1545 async fn stored(&self, name: &str) -> Option<Repository> {
1546 let org = self
1547 .orgs
1548 .find_by_name(&self.handle)
1549 .await
1550 .expect("lookup")
1551 .expect("the handle exists");
1552
1553 self.repos
1554 .find_by_org_and_name(&org.id, &RepoName::new(name).expect("valid name"))
1555 .await
1556 .expect("lookup")
1557 }
1558 }
1559
1560 #[tokio::test]
1561 async fn the_owner_changes_the_description_and_the_visibility() {
1562 let f = fixture().await;
1563 f.create_with(Visibility::Public, "steid").await;
1564
1565 let updated = f
1566 .update(
1567 &f.owner,
1568 "steid",
1569 Some(" A gitforge. "),
1570 Visibility::Private,
1571 )
1572 .await
1573 .expect("should update");
1574
1575 assert_eq!(updated.description.as_deref(), Some("A gitforge."));
1576 assert_eq!(updated.visibility, Visibility::Private);
1577
1578 let stored = f.stored("steid").await.expect("still there");
1579 assert_eq!(stored.description.as_deref(), Some("A gitforge."));
1580 assert_eq!(stored.visibility, Visibility::Private);
1581 }
1582
1583 #[tokio::test]
1584 async fn a_description_can_be_cleared() {
1585 let f = fixture().await;
1586 f.create(
1587 &f.owner,
1588 &NewRepo {
1589 name: "steid".to_owned(),
1590 description: Some("A gitforge.".to_owned()),
1591 visibility: Visibility::Public,
1592 },
1593 )
1594 .await
1595 .expect("should create");
1596
1597 f.update(&f.owner, "steid", None, Visibility::Public)
1598 .await
1599 .expect("should update");
1600
1601 assert_eq!(
1602 f.stored("steid").await.expect("still there").description,
1603 None
1604 );
1605 }
1606
1607 #[tokio::test]
1608 async fn an_update_never_touches_the_name_or_the_directory() {
1609 // Renaming is a directory move, not a column update, so it is deliberately not
1610 // offered here — and an update must not disturb what is on disk.
1611 let f = fixture().await;
1612 let created = f.create_with(Visibility::Public, "steid").await;
1613
1614 let updated = f
1615 .update(&f.owner, "steid", Some("changed"), Visibility::Private)
1616 .await
1617 .expect("should update");
1618
1619 assert_eq!(updated.name, created.name);
1620 assert_eq!(updated.id, created.id);
1621 assert!(f.storage.contains(&f.handle, &created.name));
1622 assert_eq!(f.storage.len(), 1);
1623 }
1624
1625 #[tokio::test]
1626 async fn a_member_who_is_not_the_owner_cannot_change_a_repository() {
1627 // The repository is public, so the member can see it; seeing is not changing.
1628 let f = fixture().await;
1629 f.create_with(Visibility::Public, "steid").await;
1630
1631 let error = f
1632 .update(&f.member, "steid", Some("mine now"), Visibility::Private)
1633 .await
1634 .expect_err("should refuse");
1635
1636 assert!(matches!(error, Error::Domain(DomainError::Forbidden)));
1637 assert_eq!(
1638 f.stored("steid").await.expect("untouched").visibility,
1639 Visibility::Public
1640 );
1641 }
1642
1643 #[tokio::test]
1644 async fn a_stranger_and_an_anonymous_visitor_cannot_change_a_repository() {
1645 let f = fixture().await;
1646 f.create_with(Visibility::Public, "steid").await;
1647
1648 for actor in [&Actor::Anonymous, &f.stranger] {
1649 let error = f
1650 .update(actor, "steid", Some("mine now"), Visibility::Private)
1651 .await
1652 .expect_err("should refuse");
1653
1654 assert!(
1655 matches!(error, Error::Domain(DomainError::Forbidden)),
1656 "{actor:?} should be refused"
1657 );
1658 }
1659
1660 assert_eq!(
1661 f.stored("steid").await.expect("untouched").description,
1662 None
1663 );
1664 }
1665
1666 #[tokio::test]
1667 async fn a_private_repository_is_not_found_rather_than_forbidden_for_an_outsider() {
1668 // The established rule: "forbidden" would confirm that a private repository by
1669 // that name exists, which is exactly what private is protecting.
1670 let f = fixture().await;
1671 f.create_with(Visibility::Private, "secret").await;
1672
1673 for actor in [&Actor::Anonymous, &f.stranger] {
1674 let error = f
1675 .update(actor, "secret", None, Visibility::Public)
1676 .await
1677 .expect_err("should refuse");
1678
1679 assert!(
1680 matches!(
1681 error,
1682 Error::Domain(DomainError::NotFound {
1683 entity: "repository"
1684 })
1685 ),
1686 "{actor:?} should be told it does not exist"
1687 );
1688 }
1689
1690 assert_eq!(
1691 f.stored("secret").await.expect("untouched").visibility,
1692 Visibility::Private
1693 );
1694 }
1695
1696 #[tokio::test]
1697 async fn an_unknown_repository_or_handle_is_not_found() {
1698 let f = fixture().await;
1699
1700 let error = f
1701 .update(&f.owner, "nothing-here", None, Visibility::Public)
1702 .await
1703 .expect_err("should refuse");
1704
1705 assert!(matches!(
1706 error,
1707 Error::Domain(DomainError::NotFound {
1708 entity: "repository"
1709 })
1710 ));
1711
1712 let missing = OrgName::new("nobody").expect("valid handle");
1713 let error = update_repo(
1714 &f.owner,
1715 &missing,
1716 &RepoName::new("steid").expect("valid"),
1717 &RepoEdit {
1718 description: None,
1719 visibility: Visibility::Public,
1720 pinned: false,
1721 },
1722 &f.orgs,
1723 &f.memberships,
1724 &f.repos,
1725 )
1726 .await
1727 .expect_err("should refuse");
1728
1729 assert!(matches!(
1730 error,
1731 Error::Domain(DomainError::NotFound {
1732 entity: "repository"
1733 })
1734 ));
1735 }
1736
1737 #[tokio::test]
1738 async fn an_over_long_description_is_rejected_and_changes_nothing() {
1739 let f = fixture().await;
1740 f.create_with(Visibility::Public, "steid").await;
1741 let long = "a".repeat(Repository::MAX_DESCRIPTION_LEN + 1);
1742
1743 let error = f
1744 .update(&f.owner, "steid", Some(&long), Visibility::Private)
1745 .await
1746 .expect_err("should reject");
1747
1748 assert!(matches!(
1749 error,
1750 Error::Domain(DomainError::Validation { .. })
1751 ));
1752 let stored = f.stored("steid").await.expect("untouched");
1753 assert_eq!(stored.description, None);
1754 assert_eq!(stored.visibility, Visibility::Public);
1755 }
1756
1757 #[tokio::test]
1758 async fn making_a_public_repository_private_hides_it_from_outsiders() {
1759 // The hole this closes: someone who published by accident can un-publish.
1760 let f = fixture().await;
1761 f.create_with(Visibility::Public, "oops").await;
1762 assert!(f.view(&Actor::Anonymous, "oops").await.is_some());
1763
1764 f.update(&f.owner, "oops", None, Visibility::Private)
1765 .await
1766 .expect("should update");
1767
1768 assert!(
1769 f.view(&Actor::Anonymous, "oops").await.is_none(),
1770 "it should be absent, not merely unlinked"
1771 );
1772 assert!(f.list(&Actor::Anonymous).await.is_empty());
1773 assert!(f.view(&f.owner, "oops").await.is_some());
1774 }
1775
1776 #[tokio::test]
1777 async fn making_a_private_repository_public_reveals_it() {
1778 let f = fixture().await;
1779 f.create_with(Visibility::Private, "secret").await;
1780
1781 f.update(&f.owner, "secret", None, Visibility::Public)
1782 .await
1783 .expect("should update");
1784
1785 assert!(f.view(&Actor::Anonymous, "secret").await.is_some());
1786 assert_eq!(
1787 Fixture::names(&f.list(&Actor::Anonymous).await),
1788 vec!["secret"]
1789 );
1790 }
1791
1792 // --- pinning ---------------------------------------------------------------
1793
1794 impl Fixture {
1795 /// Sets the pin, leaving everything else as stored.
1796 async fn set_pin(&self, actor: &Actor, name: &str, pinned: bool) -> Result<Repository> {
1797 let existing = self.stored(name).await.expect("the repository exists");
1798
1799 update_repo(
1800 actor,
1801 &self.handle,
1802 &existing.name,
1803 &RepoEdit {
1804 description: existing.description.clone(),
1805 visibility: existing.visibility,
1806 pinned,
1807 },
1808 &self.orgs,
1809 &self.memberships,
1810 &self.repos,
1811 )
1812 .await
1813 }
1814
1815 async fn pinned_names(&self) -> Vec<String> {
1816 self.list(&self.owner)
1817 .await
1818 .into_iter()
1819 .filter(|summary| summary.pinned)
1820 .map(|summary| summary.name.to_string())
1821 .collect()
1822 }
1823 }
1824
1825 #[tokio::test]
1826 async fn the_owner_pins_a_repository() {
1827 let f = fixture().await;
1828 f.create_with(Visibility::Public, "steid").await;
1829
1830 let pinned = f
1831 .set_pin(&f.owner, "steid", true)
1832 .await
1833 .expect("should pin");
1834
1835 assert!(pinned.pinned);
1836 assert_eq!(f.pinned_names().await, vec!["steid".to_owned()]);
1837 }
1838
1839 #[tokio::test]
1840 async fn pinning_a_second_repository_unpins_the_first() {
1841 // At most one lead per owner. Two would leave the profile with no rule for
1842 // choosing between them.
1843 let f = fixture().await;
1844 f.create_with(Visibility::Public, "steid").await;
1845 f.create_with(Visibility::Public, "dotfiles").await;
1846 f.set_pin(&f.owner, "steid", true)
1847 .await
1848 .expect("should pin");
1849
1850 f.set_pin(&f.owner, "dotfiles", true)
1851 .await
1852 .expect("should pin");
1853
1854 assert_eq!(f.pinned_names().await, vec!["dotfiles".to_owned()]);
1855 }
1856
1857 #[tokio::test]
1858 async fn re_pinning_the_same_repository_leaves_it_pinned() {
1859 // The unpin sweep skips the repository being saved; getting that wrong would
1860 // make a second save of an unchanged form silently clear the pin.
1861 let f = fixture().await;
1862 f.create_with(Visibility::Public, "steid").await;
1863 f.set_pin(&f.owner, "steid", true)
1864 .await
1865 .expect("should pin");
1866
1867 f.set_pin(&f.owner, "steid", true)
1868 .await
1869 .expect("should pin");
1870
1871 assert_eq!(f.pinned_names().await, vec!["steid".to_owned()]);
1872 }
1873
1874 #[tokio::test]
1875 async fn unpinning_leaves_nothing_pinned() {
1876 let f = fixture().await;
1877 f.create_with(Visibility::Public, "steid").await;
1878 f.set_pin(&f.owner, "steid", true)
1879 .await
1880 .expect("should pin");
1881
1882 f.set_pin(&f.owner, "steid", false)
1883 .await
1884 .expect("should unpin");
1885
1886 assert!(f.pinned_names().await.is_empty());
1887 }
1888
1889 #[tokio::test]
1890 async fn pinning_only_reaches_the_owners_own_repositories() {
1891 // The sweep is scoped to the org. Another owner's lead is not this owner's to
1892 // clear.
1893 let f = fixture().await;
1894 f.create_with(Visibility::Public, "steid").await;
1895
1896 let other = Organization::new(OrgId::generate(), "other-org", None).expect("valid org");
1897 f.orgs.save(&other).await.expect("save org");
1898 let mut theirs = Repository::new(
1899 RepoId::generate(),
1900 other.id.clone(),
1901 "theirs",
1902 None,
1903 Visibility::Public,
1904 SystemTime::now(),
1905 )
1906 .expect("valid repo");
1907 theirs.pinned = true;
1908 f.repos.save(&theirs).await.expect("save repo");
1909
1910 f.set_pin(&f.owner, "steid", true)
1911 .await
1912 .expect("should pin");
1913
1914 assert!(
1915 f.repos
1916 .find_by_id(&theirs.id)
1917 .await
1918 .expect("lookup")
1919 .expect("still there")
1920 .pinned,
1921 "another owner's lead should be untouched"
1922 );
1923 }
1924
1925 #[tokio::test]
1926 async fn a_member_who_is_not_the_owner_cannot_pin() {
1927 // Pinning is a mutation, and every repository mutation is owner-only.
1928 let f = fixture().await;
1929 f.create_with(Visibility::Public, "steid").await;
1930
1931 for actor in [&f.member, &f.stranger, &Actor::Anonymous] {
1932 let error = f
1933 .set_pin(actor, "steid", true)
1934 .await
1935 .expect_err("should refuse");
1936
1937 assert!(
1938 matches!(error, Error::Domain(DomainError::Forbidden)),
1939 "{actor:?} should be forbidden, got {error:?}"
1940 );
1941 }
1942
1943 assert!(f.pinned_names().await.is_empty());
1944 }
1945
1946 #[tokio::test]
1947 async fn editing_a_repository_does_not_move_its_place_in_the_listing() {
1948 // `updated_at` means "code last landed here". Rewording a description must not
1949 // jump a dormant repository to the top of a portfolio.
1950 let f = fixture().await;
1951 let repo = f.create_dated("steid", 1_000).await;
1952
1953 let updated = f
1954 .update(&f.owner, "steid", Some("A gitforge."), Visibility::Public)
1955 .await
1956 .expect("should update");
1957
1958 assert_eq!(updated.updated_at, repo.updated_at);
1959 }
1960
1961 // --- delete_repo -----------------------------------------------------------
1962
1963 /// Git storage whose `remove` always fails, for the best-effort path.
1964 #[derive(Debug, Default)]
1965 struct FailingRemoveStorage;
1966
1967 impl GitStorage for FailingRemoveStorage {
1968 async fn init_bare(
1969 &self,
1970 _handle: &OrgName,
1971 _name: &RepoName,
1972 ) -> std::result::Result<(), GitStorageError> {
1973 Ok(())
1974 }
1975
1976 async fn remove(
1977 &self,
1978 _handle: &OrgName,
1979 _name: &RepoName,
1980 ) -> std::result::Result<(), GitStorageError> {
1981 Err(GitStorageError::backend("remove failed on purpose"))
1982 }
1983
1984 async fn rename(
1985 &self,
1986 _handle: &OrgName,
1987 _from: &RepoName,
1988 _to: &RepoName,
1989 ) -> std::result::Result<(), GitStorageError> {
1990 Ok(())
1991 }
1992
1993 async fn set_default_branch(
1994 &self,
1995 _handle: &OrgName,
1996 _name: &RepoName,
1997 _branch: &RefName,
1998 ) -> std::result::Result<(), GitStorageError> {
1999 Ok(())
2000 }
2001
2002 async fn enable_reflogs(&self) -> std::result::Result<u64, GitStorageError> {
2003 Ok(0)
2004 }
2005
2006 fn repo_path(&self, handle: &OrgName, name: &RepoName) -> std::path::PathBuf {
2007 std::path::PathBuf::from(format!("{handle}/{name}.git"))
2008 }
2009 }
2010
2011 impl Fixture {
2012 async fn delete(&self, actor: &Actor, name: &str) -> Result<()> {
2013 delete_repo(
2014 actor,
2015 &self.handle,
2016 &RepoName::new(name).expect("valid name"),
2017 &self.orgs,
2018 &self.memberships,
2019 &self.repos,
2020 &self.storage,
2021 )
2022 .await
2023 }
2024 }
2025
2026 #[tokio::test]
2027 async fn the_owner_deletes_the_record_and_the_bare_repo() {
2028 let f = fixture().await;
2029 f.create_with(Visibility::Public, "steid").await;
2030
2031 f.delete(&f.owner, "steid").await.expect("should delete");
2032
2033 assert!(f.stored("steid").await.is_none());
2034 assert!(f.storage.is_empty(), "the directory should be gone too");
2035 assert!(f.view(&f.owner, "steid").await.is_none());
2036 assert!(f.list(&f.owner).await.is_empty());
2037 }
2038
2039 #[tokio::test]
2040 async fn a_non_owner_deletes_neither_the_record_nor_the_directory() {
2041 let f = fixture().await;
2042 let repo = f.create_with(Visibility::Public, "steid").await;
2043
2044 for actor in [&Actor::Anonymous, &f.stranger, &f.member] {
2045 let error = f.delete(actor, "steid").await.expect_err("should refuse");
2046
2047 assert!(
2048 matches!(error, Error::Domain(DomainError::Forbidden)),
2049 "{actor:?} should be refused"
2050 );
2051 }
2052
2053 assert!(f.stored("steid").await.is_some());
2054 assert!(f.storage.contains(&f.handle, &repo.name));
2055 }
2056
2057 #[tokio::test]
2058 async fn a_private_repository_is_not_found_for_an_outsider_asking_to_delete_it() {
2059 let f = fixture().await;
2060 let repo = f.create_with(Visibility::Private, "secret").await;
2061
2062 let error = f
2063 .delete(&f.stranger, "secret")
2064 .await
2065 .expect_err("should refuse");
2066
2067 assert!(matches!(
2068 error,
2069 Error::Domain(DomainError::NotFound {
2070 entity: "repository"
2071 })
2072 ));
2073 assert!(f.stored("secret").await.is_some());
2074 assert!(f.storage.contains(&f.handle, &repo.name));
2075 }
2076
2077 #[tokio::test]
2078 async fn deleting_a_repository_that_does_not_exist_is_not_found() {
2079 let f = fixture().await;
2080
2081 let error = f
2082 .delete(&f.owner, "nothing-here")
2083 .await
2084 .expect_err("should refuse");
2085
2086 assert!(matches!(
2087 error,
2088 Error::Domain(DomainError::NotFound {
2089 entity: "repository"
2090 })
2091 ));
2092 }
2093
2094 #[tokio::test]
2095 async fn deleting_one_repository_leaves_the_others_alone() {
2096 let f = fixture().await;
2097 f.create_with(Visibility::Public, "keep").await;
2098 f.create_with(Visibility::Public, "drop").await;
2099
2100 f.delete(&f.owner, "drop").await.expect("should delete");
2101
2102 assert_eq!(Fixture::names(&f.list(&f.owner).await), vec!["keep"]);
2103 assert_eq!(f.storage.len(), 1);
2104 }
2105
2106 #[tokio::test]
2107 async fn a_name_freed_by_deletion_can_be_created_again() {
2108 let f = fixture().await;
2109 f.create_with(Visibility::Public, "steid").await;
2110 f.delete(&f.owner, "steid").await.expect("should delete");
2111
2112 let recreated = f
2113 .create(&f.owner, &spec("steid"))
2114 .await
2115 .expect("the name should be free again");
2116
2117 assert!(f.storage.contains(&f.handle, &recreated.name));
2118 }
2119
2120 #[tokio::test]
2121 async fn a_directory_that_will_not_delete_still_reports_success() {
2122 // The row goes first and is already gone; as far as Steid is concerned the
2123 // repository is deleted, and there is nothing the caller could do about the
2124 // leftover directory. The failure is logged, not returned.
2125 let f = fixture().await;
2126 f.create_with(Visibility::Public, "steid").await;
2127
2128 delete_repo(
2129 &f.owner,
2130 &f.handle,
2131 &RepoName::new("steid").expect("valid"),
2132 &f.orgs,
2133 &f.memberships,
2134 &f.repos,
2135 &FailingRemoveStorage,
2136 )
2137 .await
2138 .expect("should still report success");
2139
2140 assert!(f.stored("steid").await.is_none());
2141 }
2142
2143 /// The real adapter, so that "the directory is gone" is more than a fake's opinion.
2144 #[tokio::test]
2145 async fn against_real_disk_storage_delete_removes_the_directory() {
2146 let f = fixture().await;
2147 let dir = tempfile::TempDir::new().expect("temp dir");
2148 let storage = DiskGitStorage::new(dir.path());
2149
2150 create_repo(
2151 &f.owner,
2152 &f.handle,
2153 &spec("steid"),
2154 &f.orgs,
2155 &f.memberships,
2156 &f.repos,
2157 &storage,
2158 )
2159 .await
2160 .expect("should create");
2161 assert!(dir.path().join("acme").join("steid.git").is_dir());
2162
2163 delete_repo(
2164 &f.owner,
2165 &f.handle,
2166 &RepoName::new("steid").expect("valid"),
2167 &f.orgs,
2168 &f.memberships,
2169 &f.repos,
2170 &storage,
2171 )
2172 .await
2173 .expect("should delete");
2174
2175 assert!(!dir.path().join("acme").join("steid.git").exists());
2176 assert!(f.stored("steid").await.is_none());
2177 }
2178
2179 // --- rename_repo -----------------------------------------------------------
2180
2181 /// An in-memory repository whose `save` fails once armed, for the compensation path.
2182 ///
2183 /// Delegates the rest, unlike [`FailingRepoRepo`], because a rename has to *find*
2184 /// the repository before it can fail to save it.
2185 #[derive(Debug, Default)]
2186 struct SaveFailsRepoRepo {
2187 inner: InMemoryRepoRepo,
2188 armed: std::sync::atomic::AtomicBool,
2189 }
2190
2191 impl RepoRepository for SaveFailsRepoRepo {
2192 async fn find_by_id(&self, id: &RepoId) -> RepositoryResult<Option<Repository>> {
2193 self.inner.find_by_id(id).await
2194 }
2195
2196 async fn find_by_org_and_name(
2197 &self,
2198 org_id: &OrgId,
2199 name: &RepoName,
2200 ) -> RepositoryResult<Option<Repository>> {
2201 self.inner.find_by_org_and_name(org_id, name).await
2202 }
2203
2204 async fn list_by_org(&self, org_id: &OrgId) -> RepositoryResult<Vec<Repository>> {
2205 self.inner.list_by_org(org_id).await
2206 }
2207
2208 async fn save(&self, repo: &Repository) -> RepositoryResult<()> {
2209 if self.armed.load(std::sync::atomic::Ordering::SeqCst) {
2210 return Err(RepositoryError::backend("save failed on purpose"));
2211 }
2212 self.inner.save(repo).await
2213 }
2214
2215 async fn touch(&self, id: &RepoId, now: SystemTime) -> RepositoryResult<()> {
2216 self.inner.touch(id, now).await
2217 }
2218
2219 async fn delete(&self, id: &RepoId) -> RepositoryResult<()> {
2220 self.inner.delete(id).await
2221 }
2222
2223 async fn fail_interrupted_imports(&self, reason: &str) -> RepositoryResult<u64> {
2224 self.inner.fail_interrupted_imports(reason).await
2225 }
2226 }
2227
2228 impl Fixture {
2229 /// Puts a stored repository into the state an import leaves it in, without
2230 /// running one: `import_repo` needs a `GitImport`, and what these tests are
2231 /// about is the guard rather than the clone.
2232 async fn mark_importing(&self, name: &str) {
2233 let mut repo = self.stored(name).await.expect("the repository exists");
2234 repo.start_import(
2235 ImportSource::new("https://example.com/someone/thing.git").expect("valid source"),
2236 );
2237 self.repos.save(&repo).await.expect("save");
2238 }
2239
2240 async fn rename(&self, actor: &Actor, name: &str, to: &str) -> Result<Repository> {
2241 rename_repo(
2242 actor,
2243 &self.handle,
2244 &RepoName::new(name).expect("valid name"),
2245 to,
2246 &self.orgs,
2247 &self.memberships,
2248 &self.repos,
2249 &self.storage,
2250 )
2251 .await
2252 }
2253 }
2254
2255 #[tokio::test]
2256 async fn the_owner_renames_the_record_and_the_directory() {
2257 let f = fixture().await;
2258 f.create_with(Visibility::Public, "steid").await;
2259
2260 let renamed = f
2261 .rename(&f.owner, "steid", "forge")
2262 .await
2263 .expect("should rename");
2264
2265 assert_eq!(renamed.name.as_str(), "forge");
2266 assert!(f.stored("forge").await.is_some());
2267 assert!(f.stored("steid").await.is_none());
2268 assert!(f.storage.contains(&f.handle, &renamed.name));
2269 assert!(
2270 !f.storage
2271 .contains(&f.handle, &RepoName::from_trusted("steid"))
2272 );
2273 }
2274
2275 #[tokio::test]
2276 async fn a_rename_keeps_everything_except_the_name() {
2277 // Including `updated_at`: renaming is not code landing, so a portfolio must not
2278 // reorder itself because somebody tidied a name.
2279 let f = fixture().await;
2280 let before = f.create_dated("steid", 1_000).await;
2281 f.set_pin(&f.owner, "steid", true)
2282 .await
2283 .expect("should pin");
2284
2285 let renamed = f
2286 .rename(&f.owner, "steid", "forge")
2287 .await
2288 .expect("should rename");
2289
2290 assert_eq!(renamed.id, before.id);
2291 assert_eq!(renamed.updated_at, at(1_000));
2292 assert_eq!(renamed.visibility, before.visibility);
2293 assert!(renamed.pinned, "a pinned repository stays the lead");
2294 }
2295
2296 #[tokio::test]
2297 async fn renaming_normalises_the_new_name() {
2298 let f = fixture().await;
2299 f.create_with(Visibility::Public, "steid").await;
2300
2301 let renamed = f
2302 .rename(&f.owner, "steid", " MyForge ")
2303 .await
2304 .expect("should rename");
2305
2306 assert_eq!(renamed.name.as_str(), "myforge");
2307 }
2308
2309 #[tokio::test]
2310 async fn an_importing_repository_cannot_be_renamed() {
2311 // The directory this would move is the one `git clone --mirror` is writing into,
2312 // and git holds a path rather than a row: the clone would carry on filling a
2313 // directory nothing names any more.
2314 let f = fixture().await;
2315 f.create_with(Visibility::Public, "steid").await;
2316 f.mark_importing("steid").await;
2317
2318 let error = f
2319 .rename(&f.owner, "steid", "forge")
2320 .await
2321 .expect_err("should refuse");
2322
2323 assert!(
2324 matches!(
2325 error,
2326 Error::Domain(DomainError::Unavailable {
2327 entity: "repository",
2328 ..
2329 })
2330 ),
2331 "expected an unavailable repository, got {error:?}"
2332 );
2333 assert!(f.stored("steid").await.is_some(), "the row is untouched");
2334 assert!(
2335 f.storage
2336 .contains(&f.handle, &RepoName::from_trusted("steid")),
2337 "and so is the directory"
2338 );
2339 }
2340
2341 #[tokio::test]
2342 async fn an_archived_repository_can_still_be_renamed() {
2343 // Archived is "finished", not "frozen". Pinned here because the guard is the one
2344 // thing between a rename and an archived repository.
2345 let f = fixture().await;
2346 f.create_with(Visibility::Public, "steid").await;
2347 f.set_archived(&f.owner, "steid", true)
2348 .await
2349 .expect("should archive");
2350
2351 let renamed = f
2352 .rename(&f.owner, "steid", "forge")
2353 .await
2354 .expect("should rename");
2355
2356 assert_eq!(renamed.name.as_str(), "forge");
2357 assert!(renamed.archived);
2358 }
2359
2360 #[tokio::test]
2361 async fn renaming_to_the_same_name_changes_nothing() {
2362 // The name normalises, so `Steid` submitted for `steid` is a confirmation, not
2363 // a collision with itself.
2364 let f = fixture().await;
2365 f.create_with(Visibility::Public, "steid").await;
2366
2367 let renamed = f
2368 .rename(&f.owner, "steid", "Steid")
2369 .await
2370 .expect("should be a no-op");
2371
2372 assert_eq!(renamed.name.as_str(), "steid");
2373 assert!(f.storage.contains(&f.handle, &renamed.name));
2374 }
2375
2376 #[tokio::test]
2377 async fn renaming_onto_an_existing_repository_is_refused_and_moves_nothing() {
2378 let f = fixture().await;
2379 f.create_with(Visibility::Public, "steid").await;
2380 f.create_with(Visibility::Public, "forge").await;
2381
2382 let error = f
2383 .rename(&f.owner, "steid", "forge")
2384 .await
2385 .expect_err("should refuse");
2386
2387 assert!(matches!(
2388 error,
2389 Error::Domain(DomainError::AlreadyExists { .. })
2390 ));
2391 assert!(f.stored("steid").await.is_some());
2392 assert!(
2393 f.storage
2394 .contains(&f.handle, &RepoName::from_trusted("steid"))
2395 );
2396 }
2397
2398 #[tokio::test]
2399 async fn an_invalid_new_name_is_rejected_before_anything_moves() {
2400 let f = fixture().await;
2401 f.create_with(Visibility::Public, "steid").await;
2402
2403 for bad in ["../escape", "", "new", "forge.git"] {
2404 let error = f
2405 .rename(&f.owner, "steid", bad)
2406 .await
2407 .expect_err("should reject");
2408
2409 assert!(
2410 matches!(error, Error::Domain(DomainError::Validation { .. })),
2411 "expected {bad:?} to be rejected"
2412 );
2413 }
2414
2415 assert!(f.stored("steid").await.is_some());
2416 assert!(
2417 f.storage
2418 .contains(&f.handle, &RepoName::from_trusted("steid"))
2419 );
2420 }
2421
2422 #[tokio::test]
2423 async fn only_the_owner_can_rename() {
2424 let f = fixture().await;
2425 f.create_with(Visibility::Public, "steid").await;
2426
2427 for actor in [&Actor::Anonymous, &f.stranger, &f.member] {
2428 let error = f
2429 .rename(actor, "steid", "forge")
2430 .await
2431 .expect_err("should refuse");
2432
2433 assert!(
2434 matches!(error, Error::Domain(DomainError::Forbidden)),
2435 "{actor:?} should be forbidden, got {error:?}"
2436 );
2437 }
2438
2439 assert!(f.stored("steid").await.is_some());
2440 }
2441
2442 #[tokio::test]
2443 async fn a_private_repository_is_not_found_rather_than_forbidden_for_an_outsider_renaming_it() {
2444 let f = fixture().await;
2445 f.create_with(Visibility::Private, "secret").await;
2446
2447 for actor in [&Actor::Anonymous, &f.stranger] {
2448 let error = f
2449 .rename(actor, "secret", "forge")
2450 .await
2451 .expect_err("should refuse");
2452
2453 assert!(
2454 matches!(error, Error::Domain(DomainError::NotFound { .. })),
2455 "{actor:?} should see a 404, got {error:?}"
2456 );
2457 }
2458 }
2459
2460 #[tokio::test]
2461 async fn a_failed_record_write_moves_the_directory_back() {
2462 // The compensation. Without it the repository is on disk under a name no row
2463 // names, and every page 404s.
2464 let f = fixture().await;
2465 let repos = SaveFailsRepoRepo::default();
2466 let storage = InMemoryGitStorage::new();
2467
2468 create_repo(
2469 &f.owner,
2470 &f.handle,
2471 &spec("steid"),
2472 &f.orgs,
2473 &f.memberships,
2474 &repos,
2475 &storage,
2476 )
2477 .await
2478 .expect("should create");
2479
2480 repos.armed.store(true, std::sync::atomic::Ordering::SeqCst);
2481
2482 let error = rename_repo(
2483 &f.owner,
2484 &f.handle,
2485 &RepoName::new("steid").expect("valid"),
2486 "forge",
2487 &f.orgs,
2488 &f.memberships,
2489 &repos,
2490 &storage,
2491 )
2492 .await
2493 .expect_err("the save should fail");
2494
2495 assert!(matches!(error, Error::Repository(_)));
2496 assert!(
2497 storage.contains(&f.handle, &RepoName::from_trusted("steid")),
2498 "the directory should be back where the row still says it is"
2499 );
2500 assert!(!storage.contains(&f.handle, &RepoName::from_trusted("forge")));
2501 }
2502
2503 #[tokio::test]
2504 async fn a_name_freed_by_a_rename_can_be_used_again() {
2505 let f = fixture().await;
2506 f.create_with(Visibility::Public, "steid").await;
2507
2508 f.rename(&f.owner, "steid", "forge")
2509 .await
2510 .expect("should rename");
2511
2512 f.create(&f.owner, &spec("steid"))
2513 .await
2514 .expect("the old name is free again");
2515 }
2516
2517 #[tokio::test]
2518 async fn against_real_disk_storage_rename_moves_the_directory() {
2519 let f = fixture().await;
2520 let dir = tempfile::tempdir().expect("tempdir");
2521 let storage = DiskGitStorage::new(dir.path());
2522
2523 create_repo(
2524 &f.owner,
2525 &f.handle,
2526 &spec("steid"),
2527 &f.orgs,
2528 &f.memberships,
2529 &f.repos,
2530 &storage,
2531 )
2532 .await
2533 .expect("should create");
2534
2535 rename_repo(
2536 &f.owner,
2537 &f.handle,
2538 &RepoName::new("steid").expect("valid"),
2539 "forge",
2540 &f.orgs,
2541 &f.memberships,
2542 &f.repos,
2543 &storage,
2544 )
2545 .await
2546 .expect("should rename");
2547
2548 assert!(
2549 dir.path()
2550 .join("acme")
2551 .join("forge.git")
2552 .join("HEAD")
2553 .is_file()
2554 );
2555 assert!(!dir.path().join("acme").join("steid.git").exists());
2556 }
2557
2558 // --- set_default_branch ------------------------------------------------------
2559
2560 impl Fixture {
2561 async fn set_head(
2562 &self,
2563 actor: &Actor,
2564 name: &str,
2565 branch: &str,
2566 queries: &InMemoryGitQuery,
2567 ) -> Result<RefName> {
2568 set_default_branch(
2569 actor,
2570 &self.handle,
2571 &RepoName::new(name).expect("valid name"),
2572 branch,
2573 &self.orgs,
2574 &self.memberships,
2575 &self.repos,
2576 queries,
2577 &self.storage,
2578 )
2579 .await
2580 }
2581 }
2582
2583 /// A repository with two branches, `main` being the default.
2584 fn two_branches() -> InMemoryGitQuery {
2585 InMemoryGitQuery::new()
2586 .with_branch_row("main", true, at(2_000))
2587 .with_branch_row("develop", false, at(3_000))
2588 }
2589
2590 #[tokio::test]
2591 async fn the_owner_points_head_at_another_branch() {
2592 let f = fixture().await;
2593 f.create_with(Visibility::Public, "steid").await;
2594
2595 let branch = f
2596 .set_head(&f.owner, "steid", "develop", &two_branches())
2597 .await
2598 .expect("should set");
2599
2600 assert_eq!(branch.as_str(), "develop");
2601 assert_eq!(
2602 f.storage.head(&f.handle, &RepoName::from_trusted("steid")),
2603 Some(RefName::from_trusted("develop"))
2604 );
2605 }
2606
2607 #[tokio::test]
2608 async fn a_branch_the_repository_does_not_have_is_not_found() {
2609 // `symbolic-ref` would accept it and leave every page saying "nothing pushed
2610 // yet", which is why this is checked rather than trusted.
2611 let f = fixture().await;
2612 f.create_with(Visibility::Public, "steid").await;
2613
2614 let error = f
2615 .set_head(&f.owner, "steid", "nothing-here", &two_branches())
2616 .await
2617 .expect_err("should refuse");
2618
2619 assert!(matches!(
2620 error,
2621 Error::Domain(DomainError::NotFound { entity: "branch" })
2622 ));
2623 assert!(
2624 f.storage
2625 .head(&f.handle, &RepoName::from_trusted("steid"))
2626 .is_none()
2627 );
2628 }
2629
2630 #[tokio::test]
2631 async fn a_tag_is_not_a_branch() {
2632 // `branches()` is the list checked against, so a tag of the same shape cannot
2633 // be smuggled into `refs/heads/`.
2634 let f = fixture().await;
2635 f.create_with(Visibility::Public, "steid").await;
2636 let queries = two_branches().with_tag_row("v0.1.0", true, at(4_000));
2637
2638 let error = f
2639 .set_head(&f.owner, "steid", "v0.1.0", &queries)
2640 .await
2641 .expect_err("should refuse");
2642
2643 assert!(matches!(
2644 error,
2645 Error::Domain(DomainError::NotFound { entity: "branch" })
2646 ));
2647 }
2648
2649 #[tokio::test]
2650 async fn an_empty_repository_has_no_branch_to_choose() {
2651 let f = fixture().await;
2652 f.create_with(Visibility::Public, "steid").await;
2653
2654 let error = f
2655 .set_head(&f.owner, "steid", "main", &InMemoryGitQuery::empty())
2656 .await
2657 .expect_err("should refuse");
2658
2659 assert!(matches!(
2660 error,
2661 Error::Domain(DomainError::NotFound { entity: "branch" })
2662 ));
2663 }
2664
2665 #[tokio::test]
2666 async fn a_malformed_branch_name_never_reaches_git() {
2667 let f = fixture().await;
2668 f.create_with(Visibility::Public, "steid").await;
2669
2670 for bad in ["-flag", "main..develop", "with space", ""] {
2671 let error = f
2672 .set_head(&f.owner, "steid", bad, &two_branches())
2673 .await
2674 .expect_err("should reject");
2675
2676 assert!(
2677 matches!(error, Error::Domain(DomainError::Validation { .. })),
2678 "expected {bad:?} to be rejected, got {error:?}"
2679 );
2680 }
2681
2682 assert!(
2683 f.storage
2684 .head(&f.handle, &RepoName::from_trusted("steid"))
2685 .is_none()
2686 );
2687 }
2688
2689 #[tokio::test]
2690 async fn only_the_owner_can_move_head() {
2691 let f = fixture().await;
2692 f.create_with(Visibility::Public, "steid").await;
2693
2694 for actor in [&Actor::Anonymous, &f.stranger, &f.member] {
2695 let error = f
2696 .set_head(actor, "steid", "develop", &two_branches())
2697 .await
2698 .expect_err("should refuse");
2699
2700 assert!(
2701 matches!(error, Error::Domain(DomainError::Forbidden)),
2702 "{actor:?} should be forbidden, got {error:?}"
2703 );
2704 }
2705
2706 assert!(
2707 f.storage
2708 .head(&f.handle, &RepoName::from_trusted("steid"))
2709 .is_none()
2710 );
2711 }
2712
2713 #[tokio::test]
2714 async fn a_private_repository_is_absent_rather_than_forbidden_when_an_outsider_moves_head() {
2715 let f = fixture().await;
2716 f.create_with(Visibility::Private, "secret").await;
2717
2718 for actor in [&Actor::Anonymous, &f.stranger] {
2719 let error = f
2720 .set_head(actor, "secret", "develop", &two_branches())
2721 .await
2722 .expect_err("should refuse");
2723
2724 assert!(
2725 matches!(error, Error::Domain(DomainError::NotFound { .. })),
2726 "{actor:?} should see a 404, got {error:?}"
2727 );
2728 }
2729 }
2730
2731 // --- archiving ---------------------------------------------------------------
2732
2733 impl Fixture {
2734 async fn set_archived(
2735 &self,
2736 actor: &Actor,
2737 name: &str,
2738 archived: bool,
2739 ) -> Result<Repository> {
2740 set_repo_archived(
2741 actor,
2742 &self.handle,
2743 &RepoName::new(name).expect("valid name"),
2744 archived,
2745 &self.orgs,
2746 &self.memberships,
2747 &self.repos,
2748 )
2749 .await
2750 }
2751 }
2752
2753 #[tokio::test]
2754 async fn the_owner_archives_and_unarchives() {
2755 let f = fixture().await;
2756 f.create_with(Visibility::Public, "steid").await;
2757
2758 assert!(
2759 f.set_archived(&f.owner, "steid", true)
2760 .await
2761 .expect("should archive")
2762 .archived
2763 );
2764 assert!(f.stored("steid").await.expect("stored").archived);
2765
2766 assert!(
2767 !f.set_archived(&f.owner, "steid", false)
2768 .await
2769 .expect("should unarchive")
2770 .archived
2771 );
2772 assert!(!f.stored("steid").await.expect("stored").archived);
2773 }
2774
2775 #[tokio::test]
2776 async fn archiving_twice_is_not_an_error() {
2777 // What a double-clicked button does.
2778 let f = fixture().await;
2779 f.create_with(Visibility::Public, "steid").await;
2780
2781 f.set_archived(&f.owner, "steid", true)
2782 .await
2783 .expect("should archive");
2784 f.set_archived(&f.owner, "steid", true)
2785 .await
2786 .expect("should still be fine");
2787
2788 assert!(f.stored("steid").await.expect("stored").archived);
2789 }
2790
2791 #[tokio::test]
2792 async fn an_importing_repository_cannot_be_archived() {
2793 // "Finished" is not a thing to say about a repository whose contents have not
2794 // arrived. The way out of a stuck import is Delete, which the panel offers.
2795 let f = fixture().await;
2796 f.create_with(Visibility::Public, "steid").await;
2797 f.mark_importing("steid").await;
2798
2799 let error = f
2800 .set_archived(&f.owner, "steid", true)
2801 .await
2802 .expect_err("should refuse");
2803
2804 assert!(
2805 matches!(
2806 error,
2807 Error::Domain(DomainError::Unavailable {
2808 entity: "repository",
2809 ..
2810 })
2811 ),
2812 "expected an unavailable repository, got {error:?}"
2813 );
2814 assert!(!f.stored("steid").await.expect("stored").archived);
2815 }
2816
2817 #[tokio::test]
2818 async fn archiving_does_not_move_a_repository_up_the_listing() {
2819 // `updated_at` means "code last landed here". Declaring something finished is
2820 // not work on it, and must not float it to the top of a portfolio.
2821 let f = fixture().await;
2822 f.create_dated("steid", 1_000).await;
2823
2824 let archived = f
2825 .set_archived(&f.owner, "steid", true)
2826 .await
2827 .expect("should archive");
2828
2829 assert_eq!(archived.updated_at, at(1_000));
2830 }
2831
2832 #[tokio::test]
2833 async fn archiving_is_orthogonal_to_visibility_and_pinning() {
2834 // Archived says "finished", not "hidden": a private pinned repository keeps both
2835 // when it is archived, and stays visible to the people who could already see it.
2836 let f = fixture().await;
2837 f.create_with(Visibility::Private, "secret").await;
2838 f.set_pin(&f.owner, "secret", true)
2839 .await
2840 .expect("should pin");
2841
2842 let archived = f
2843 .set_archived(&f.owner, "secret", true)
2844 .await
2845 .expect("should archive");
2846
2847 assert_eq!(archived.visibility, Visibility::Private);
2848 assert!(archived.pinned);
2849 assert!(
2850 f.view(&f.member, "secret").await.is_some(),
2851 "a member still sees an archived private repository"
2852 );
2853 }
2854
2855 #[tokio::test]
2856 async fn editing_or_renaming_an_archived_repository_leaves_it_archived() {
2857 // The description form does not carry this field, so it must not clear it.
2858 let f = fixture().await;
2859 f.create_with(Visibility::Public, "steid").await;
2860 f.set_archived(&f.owner, "steid", true)
2861 .await
2862 .expect("should archive");
2863
2864 f.update(&f.owner, "steid", Some("Finished."), Visibility::Public)
2865 .await
2866 .expect("should update");
2867 assert!(f.stored("steid").await.expect("stored").archived);
2868
2869 let renamed = f
2870 .rename(&f.owner, "steid", "forge")
2871 .await
2872 .expect("should rename");
2873 assert!(renamed.archived);
2874 }
2875
2876 #[tokio::test]
2877 async fn only_the_owner_can_archive() {
2878 let f = fixture().await;
2879 f.create_with(Visibility::Public, "steid").await;
2880
2881 for actor in [&Actor::Anonymous, &f.stranger, &f.member] {
2882 let error = f
2883 .set_archived(actor, "steid", true)
2884 .await
2885 .expect_err("should refuse");
2886
2887 assert!(
2888 matches!(error, Error::Domain(DomainError::Forbidden)),
2889 "{actor:?} should be forbidden, got {error:?}"
2890 );
2891 }
2892
2893 assert!(!f.stored("steid").await.expect("stored").archived);
2894 }
2895
2896 #[tokio::test]
2897 async fn a_private_repository_is_absent_rather_than_forbidden_when_an_outsider_archives_it() {
2898 let f = fixture().await;
2899 f.create_with(Visibility::Private, "secret").await;
2900
2901 for actor in [&Actor::Anonymous, &f.stranger] {
2902 let error = f
2903 .set_archived(actor, "secret", true)
2904 .await
2905 .expect_err("should refuse");
2906
2907 assert!(
2908 matches!(error, Error::Domain(DomainError::NotFound { .. })),
2909 "{actor:?} should see a 404, got {error:?}"
2910 );
2911 }
2912 }
2913
2914 #[tokio::test]
2915 async fn a_view_and_a_listing_both_report_archived() {
2916 // Both carry it because both render the badge, and a page that had to read the
2917 // row again per repository would cost a query per row.
2918 let f = fixture().await;
2919 f.create_with(Visibility::Public, "steid").await;
2920 f.set_archived(&f.owner, "steid", true)
2921 .await
2922 .expect("should archive");
2923
2924 assert!(
2925 f.view(&Actor::Anonymous, "steid")
2926 .await
2927 .expect("visible")
2928 .archived
2929 );
2930 assert!(
2931 f.list(&Actor::Anonymous)
2932 .await
2933 .iter()
2934 .any(|repo| repo.name.as_str() == "steid" && repo.archived)
2935 );
2936 }
2937}