steid

@jamesgill /

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