steid

@jamesgill /

Rust27.9 KBCode·Blame·History·Raw
1//! Importing a repository from a public URL.
2//!
3//! Two halves, on purpose. [`import_repo`] is the part a person waits for: it
4//! authorizes, validates the address, and writes a row that says a copy is coming.
5//! [`run_import`] is the part that takes minutes and runs with nobody watching. The
6//! seam between them is the `importing` row — which is also what makes the failure
7//! modes tractable, because a process that dies leaves a fact behind rather than
8//! nothing.
9
10use std::time::SystemTime;
11
12use crate::domain::{
13 Actor, DomainError, ImportSource, ImportState, OrgName, RepoId, RepoName, Repository,
14 Visibility,
15 repository::{MembershipRepository, OrgRepository, RepoRepository},
16};
17
18use super::{
19 access::{Stores, changeable_repo, is_org_owner},
20 error::{Error, Result},
21 port::{GitImport, GitStorage},
22};
23
24/// What is recorded against a repository whose import was cut short by the process
25/// stopping. See [`sweep_interrupted_imports`].
26pub const INTERRUPTED: &str =
27 "The import was interrupted by a restart. Delete this repository and import it again.";
28
29/// Longest failure message kept on a repository.
30///
31/// git's stderr on a failed clone is usually two lines and occasionally hundreds; the
32/// column is rendered on a page, so it is bounded here rather than trusted.
33const MAX_ERROR_LEN: usize = 500;
34
35/// The repository a visitor is asking to copy in.
36///
37/// Raw input, like [`NewRepo`](super::NewRepo): both fields are whatever was typed, and
38/// validating them is [`ImportSource`] and [`Repository::new`]'s job.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct NewImport {
41 pub name: String,
42 pub source: String,
43}
44
45/// Records that a repository is being imported, and returns it.
46///
47/// Owner only — the same rule as [`create_repo`](super::create_repo), and for the same
48/// reason: a member's read access is not permission to add repositories to the
49/// instance.
50///
51/// **Nothing is written to disk here.** Unlike `create_repo`, which inits a bare
52/// repository and compensates if the row fails to save, an import's directory is
53/// created by `git clone` itself in the background. So the row goes first and is the
54/// only write this function makes, which removes the two-writes problem from the
55/// request path entirely — at the cost of moving it into [`run_import`], where a
56/// failure has somewhere to be recorded.
57///
58/// The caller is expected to spawn [`run_import`] afterwards. It is deliberately not
59/// spawned here: the application layer has no business owning a runtime, and a use case
60/// that starts a task cannot be tested without waiting for one.
61pub async fn import_repo(
62 actor: &Actor,
63 handle: &OrgName,
64 spec: &NewImport,
65 stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>,
66) -> Result<Repository> {
67 let Some(org) = stores.orgs.find_by_name(handle).await? else {
68 return Err(DomainError::NotFound {
69 entity: "repository owner",
70 }
71 .into());
72 };
73
74 if !is_org_owner(&org, actor, stores.memberships).await? {
75 return Err(DomainError::Forbidden.into());
76 }
77
78 // The address before the name: a typo in the URL is the likelier mistake, and
79 // reporting it first means the form does not complain about the name it pre-filled
80 // from an address it has not accepted.
81 let source = ImportSource::new(spec.source.clone())?;
82
83 // A blank name means "call it what the source calls it". The form says so and
84 // offers no JavaScript to fill the box in as the URL is typed, so the fallback is
85 // the whole of that feature — and it lands here rather than in the page so that a
86 // future `/api` cannot answer differently.
87 let name = match spec.name.trim() {
88 "" => source.suggested_name().to_owned(),
89 typed => typed.to_owned(),
90 };
91
92 let mut repo = Repository::new(
93 RepoId::generate(),
94 org.id.clone(),
95 name,
96 None,
97 // Imported repositories are private, matching `Visibility::default()` and the
98 // form, which offers no choice. Publishing one is a visit to its settings page —
99 // and the page exists the moment the row does, importing or not. The default is
100 // read from the domain rather than named here so the two cannot drift.
101 Visibility::default(),
102 SystemTime::now(),
103 )?;
104
105 if stores
106 .repos
107 .find_by_org_and_name(&org.id, &repo.name)
108 .await?
109 .is_some()
110 {
111 return Err(DomainError::AlreadyExists {
112 entity: "repository",
113 }
114 .into());
115 }
116
117 repo.start_import(source);
118 stores.repos.save(&repo).await?;
119
120 Ok(repo)
121}
122
123/// Runs the mirror, then records how it went.
124///
125/// Long-running and spawned, so it takes owned handles rather than borrowing a request.
126/// It reports `Ok(())` for a *failed import* — the failure is data on the repository,
127/// not an error for the caller, which is a background task with nobody to tell. `Err`
128/// is reserved for not being able to record the outcome at all.
129///
130/// **The row is re-read after the clone.** Minutes have passed, and the repository may
131/// have been deleted meanwhile; writing back the copy loaded at the start would
132/// resurrect it as a row pointing at a directory that was removed underneath it.
133pub async fn run_import(
134 id: &RepoId,
135 handle: &OrgName,
136 repos: &impl RepoRepository,
137 importer: &impl GitImport,
138 storage: &impl GitStorage,
139) -> Result<()> {
140 let Some(repo) = repos.find_by_id(id).await? else {
141 return Ok(());
142 };
143
144 let Some(source) = repo.import_source.clone() else {
145 // Only ever reachable if something saved an `importing` row without a source.
146 return Err(DomainError::validation("import source", "is missing").into());
147 };
148
149 let outcome = importer.mirror(handle, &repo.name, &source).await;
150
151 let Some(mut repo) = repos.find_by_id(id).await? else {
152 // Deleted while the clone ran. `delete_repo` removed a directory that did not
153 // exist yet, so what the clone left behind is an orphan and this is the only
154 // code left that knows where it is.
155 let _ = storage.remove(handle, &repo.name).await;
156 return Ok(());
157 };
158
159 match outcome {
160 Ok(()) => {
161 repo.finish_import();
162 // The history landed now, whatever the dates inside it say. The profile
163 // orders by this, and an imported repository has genuinely just arrived.
164 repo.updated_at = SystemTime::now();
165 }
166 Err(error) => {
167 repo.fail_import(explain(error.message()));
168
169 // Whatever the clone left is unusable and must not be browsable: with the
170 // state set to `failed` the page would not read it, but the git transport
171 // and an archive request address the directory, not the row. Best effort —
172 // a directory that will not delete is not a reason to lose the message.
173 if let Err(removal) = storage.remove(handle, &repo.name).await {
174 eprintln!(
175 "steid: import of {handle}/{} failed, and its partial clone could not be removed: {removal}",
176 repo.name
177 );
178 }
179 }
180 }
181
182 repos.save(&repo).await?;
183
184 Ok(())
185}
186
187/// Starts a failed import over, from the address the row still holds.
188///
189/// Owner only, through [`changeable_repo`] — the same predicate that guards renaming and
190/// archiving, because this writes to the repository's directory just as an import does.
191///
192/// **Only a failed import can be retried.** A running one has a task behind it and a
193/// second clone into the same directory would fight it; a repository that was never
194/// imported has no address to retry from. Both answer `NotFound`, which is what the
195/// button being absent already told the visitor.
196///
197/// The source is not re-validated. It passed [`ImportSource::new`] when it was typed, and
198/// re-running a rule that may have tightened since would turn "the remote hung up" into a
199/// repository whose only remaining action is delete. The adapter still re-checks what the
200/// host resolves to, which is the half that matters.
201///
202/// Like [`import_repo`], the caller spawns [`run_import`] afterwards.
203pub async fn retry_import(
204 actor: &Actor,
205 handle: &OrgName,
206 name: &RepoName,
207 stores: &Stores<'_, impl OrgRepository, impl MembershipRepository, impl RepoRepository>,
208) -> Result<Repository> {
209 let mut repo = changeable_repo(actor, handle, name, stores).await?;
210
211 let missing = || {
212 Error::Domain(DomainError::NotFound {
213 entity: "failed import",
214 })
215 };
216
217 if repo.import_state != Some(ImportState::Failed) {
218 return Err(missing());
219 }
220
221 let Some(source) = repo.import_source.clone() else {
222 return Err(missing());
223 };
224
225 // Mutated rather than rebuilt through `Repository::new()`, which resets `pinned`,
226 // `archived` and the import trio — the trap `update_repo` fell into during wave 2.
227 repo.start_import(source);
228 stores.repos.save(&repo).await?;
229
230 Ok(repo)
231}
232
233/// Fails every repository still marked `importing`, and reports how many.
234///
235/// **Called once on boot, before the first request is served.** An import lives in a
236/// background task, so a process that stops takes every running import with it and
237/// leaves rows that will never change again. Without this a restart during an import is
238/// a repository stuck showing "importing…" forever, with no way for its owner to tell
239/// that from one that is merely slow.
240///
241/// Safe precisely because of *when* it runs: nothing has been spawned yet, so there is
242/// no live import for it to mark as dead.
243pub async fn sweep_interrupted_imports(repos: &impl RepoRepository) -> Result<u64> {
244 Ok(repos.fail_interrupted_imports(INTERRUPTED).await?)
245}
246
247/// Turns git's own words into something the owner can act on.
248///
249/// One translation, and it earns its place because it is the **most likely failure
250/// there is**: a typo'd path or a private repository. GitHub answers both with a
251/// challenge rather than a 404, so with `GIT_TERMINAL_PROMPT=0` git reports "could not
252/// read Username", which describes Steid's configuration rather than the mistake.
253/// Every other message is git's, untranslated — inventing a friendlier wording for a
254/// failure nobody anticipated is how a real reason gets hidden.
255fn explain(message: &str) -> String {
256 const PROMPTED: &str = "could not read Username";
257 const AUTHENTICATION: &str = "Authentication failed";
258
259 if message.contains(PROMPTED) || message.contains(AUTHENTICATION) {
260 return "The repository could not be found. It may be private, or the URL may be \
261 wrong — Steid imports public repositories only, and never sends \
262 credentials."
263 .to_owned();
264 }
265
266 truncate(message, MAX_ERROR_LEN)
267}
268
269/// Cuts a message to `limit` bytes on a character boundary, marking that it was cut.
270fn truncate(message: &str, limit: usize) -> String {
271 let message = message.trim();
272
273 if message.len() <= limit {
274 return message.to_owned();
275 }
276
277 let mut cut = limit;
278 while cut > 0 && !message.is_char_boundary(cut) {
279 cut -= 1;
280 }
281
282 format!("{}…", &message[..cut])
283}
284
285/// Turns a use case failure into something the import form can say.
286///
287/// Here rather than in the page so that `/api` and the form cannot disagree about what
288/// a refused address sounds like.
289pub fn import_failure_message(error: &Error, typed_name: &str) -> Option<String> {
290 match error {
291 Error::Domain(DomainError::Validation { field, reason }) => {
292 Some(format!("That {field} is no good: {reason}."))
293 }
294 Error::Domain(DomainError::AlreadyExists { .. }) => Some(format!(
295 "You already have a repository called {}.",
296 typed_name.trim()
297 )),
298 _ => None,
299 }
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305 use crate::{
306 domain::{
307 ImportState, Membership, MembershipId, OrgId, Organization, RepoName, Role, UserId,
308 repository::RepoRepository,
309 },
310 infrastructure::{
311 git::{InMemoryGitImport, InMemoryGitStorage},
312 repository::{InMemoryMembershipRepo, InMemoryOrgRepo, InMemoryRepoRepo},
313 },
314 };
315
316 struct Fixture {
317 orgs: InMemoryOrgRepo,
318 memberships: InMemoryMembershipRepo,
319 repos: InMemoryRepoRepo,
320 storage: InMemoryGitStorage,
321 owner: Actor,
322 member: Actor,
323 stranger: Actor,
324 handle: OrgName,
325 }
326
327 async fn fixture() -> Fixture {
328 let orgs = InMemoryOrgRepo::new();
329 let memberships = InMemoryMembershipRepo::new();
330
331 let org = Organization::new(OrgId::generate(), "acme", None).expect("valid org");
332 orgs.save(&org).await.expect("save org");
333
334 let owner = UserId::generate();
335 let member = UserId::generate();
336
337 for (user, role) in [(&owner, Role::Owner), (&member, Role::Member)] {
338 memberships
339 .save(&Membership::new(
340 MembershipId::generate(),
341 org.id.clone(),
342 user.clone(),
343 role,
344 ))
345 .await
346 .expect("save membership");
347 }
348
349 Fixture {
350 orgs,
351 memberships,
352 repos: InMemoryRepoRepo::new(),
353 storage: InMemoryGitStorage::new(),
354 owner: Actor::User(owner),
355 member: Actor::User(member),
356 stranger: Actor::User(UserId::generate()),
357 handle: org.name,
358 }
359 }
360
361 impl Fixture {
362 async fn import(&self, actor: &Actor, name: &str, source: &str) -> Result<Repository> {
363 import_repo(
364 actor,
365 &self.handle,
366 &NewImport {
367 name: name.to_owned(),
368 source: source.to_owned(),
369 },
370 &Stores::new(&self.orgs, &self.memberships, &self.repos),
371 )
372 .await
373 }
374
375 async fn run(&self, id: &RepoId, importer: &InMemoryGitImport) -> Result<()> {
376 run_import(id, &self.handle, &self.repos, importer, &self.storage).await
377 }
378
379 async fn reload(&self, id: &RepoId) -> Repository {
380 self.repos
381 .find_by_id(id)
382 .await
383 .expect("lookup")
384 .expect("still there")
385 }
386 }
387
388 const SOURCE: &str = "https://example.com/thing.git";
389
390 #[tokio::test]
391 async fn an_owner_starts_an_import_and_the_row_says_so() {
392 let fixture = fixture().await;
393
394 let repo = fixture
395 .import(&fixture.owner, "thing", SOURCE)
396 .await
397 .expect("should start");
398
399 assert_eq!(repo.import_state, Some(ImportState::Importing));
400 assert_eq!(
401 repo.import_source.as_ref().map(ImportSource::as_str),
402 Some(SOURCE)
403 );
404 assert_eq!(repo.import_error, None);
405 // The row is what the background task and the page both read, so it has to be
406 // saved before this returns rather than by the task that has not started.
407 assert!(
408 fixture
409 .repos
410 .find_by_id(&repo.id)
411 .await
412 .expect("lookup")
413 .is_some()
414 );
415 }
416
417 #[tokio::test]
418 async fn a_blank_name_is_taken_from_the_url() {
419 let fixture = fixture().await;
420
421 let repo = fixture
422 .import(
423 &fixture.owner,
424 " ",
425 "https://github.com/rust-lang/mdBook.git",
426 )
427 .await
428 .expect("should start");
429
430 // Lowercased on the way through `RepoName`, like any other name.
431 assert_eq!(repo.name.as_str(), "mdbook");
432 }
433
434 #[tokio::test]
435 async fn a_url_with_no_path_and_no_name_is_a_validation_failure() {
436 let fixture = fixture().await;
437
438 let error = fixture
439 .import(&fixture.owner, "", "https://example.com")
440 .await
441 .expect_err("nothing to call it");
442
443 assert!(matches!(
444 error,
445 Error::Domain(DomainError::Validation { .. })
446 ));
447 }
448
449 #[tokio::test]
450 async fn only_an_owner_may_import() {
451 let fixture = fixture().await;
452
453 for actor in [&fixture.member, &fixture.stranger, &Actor::Anonymous] {
454 let error = fixture
455 .import(actor, "thing", SOURCE)
456 .await
457 .expect_err("should refuse");
458
459 assert!(matches!(error, Error::Domain(DomainError::Forbidden)));
460 }
461
462 // Nothing was recorded for any of them.
463 assert!(
464 fixture
465 .repos
466 .find_by_org_and_name(
467 &fixture
468 .orgs
469 .find_by_name(&fixture.handle)
470 .await
471 .expect("lookup")
472 .expect("org")
473 .id,
474 &RepoName::new("thing").expect("valid"),
475 )
476 .await
477 .expect("lookup")
478 .is_none()
479 );
480 }
481
482 #[tokio::test]
483 async fn a_source_that_is_not_a_public_https_url_is_refused_before_anything_is_written() {
484 let fixture = fixture().await;
485
486 for source in [
487 "http://example.com/thing.git",
488 "file:///etc/passwd",
489 "https://127.0.0.1/thing.git",
490 "https://169.254.169.254/latest/meta-data",
491 "",
492 ] {
493 let error = fixture
494 .import(&fixture.owner, "thing", source)
495 .await
496 .expect_err("should refuse");
497
498 assert!(
499 matches!(error, Error::Domain(DomainError::Validation { .. })),
500 "expected {source:?} to be a validation failure"
501 );
502 }
503 }
504
505 #[tokio::test]
506 async fn an_import_cannot_take_a_name_that_is_already_used() {
507 let fixture = fixture().await;
508 fixture
509 .import(&fixture.owner, "thing", SOURCE)
510 .await
511 .expect("first");
512
513 let error = fixture
514 .import(&fixture.owner, "thing", SOURCE)
515 .await
516 .expect_err("should refuse");
517
518 assert!(matches!(
519 error,
520 Error::Domain(DomainError::AlreadyExists { .. })
521 ));
522 }
523
524 #[tokio::test]
525 async fn a_finished_import_becomes_an_ordinary_repository() {
526 let fixture = fixture().await;
527 let repo = fixture
528 .import(&fixture.owner, "thing", SOURCE)
529 .await
530 .expect("start");
531
532 let importer = InMemoryGitImport::new();
533 fixture.run(&repo.id, &importer).await.expect("run");
534
535 let after = fixture.reload(&repo.id).await;
536
537 assert_eq!(after.import_state, None);
538 assert!(!after.is_importing());
539 assert_eq!(after.import_error, None);
540 // Provenance survives; the repository is still one that came from elsewhere.
541 assert_eq!(
542 after.import_source.as_ref().map(ImportSource::as_str),
543 Some(SOURCE)
544 );
545 assert_eq!(
546 importer.requests(),
547 vec![(
548 fixture.handle.to_string(),
549 "thing".to_owned(),
550 SOURCE.to_owned()
551 )]
552 );
553 }
554
555 #[tokio::test]
556 async fn a_failed_import_records_the_reason_and_removes_what_it_left() {
557 let fixture = fixture().await;
558 let repo = fixture
559 .import(&fixture.owner, "thing", SOURCE)
560 .await
561 .expect("start");
562
563 // The clone would have created the directory itself, so the fake is seeded with
564 // it to prove the cleanup runs.
565 fixture
566 .storage
567 .init_bare(&fixture.handle, &repo.name)
568 .await
569 .expect("seed a partial clone");
570
571 let importer = InMemoryGitImport::failing("repository not found");
572 fixture.run(&repo.id, &importer).await.expect("run");
573
574 let after = fixture.reload(&repo.id).await;
575
576 assert_eq!(after.import_state, Some(ImportState::Failed));
577 assert_eq!(after.import_error.as_deref(), Some("repository not found"));
578 assert!(
579 !fixture.storage.contains(&fixture.handle, &repo.name),
580 "a half-clone must not stay browsable over the git transport"
581 );
582 }
583
584 #[tokio::test]
585 async fn a_repository_deleted_while_it_imported_is_not_resurrected() {
586 let fixture = fixture().await;
587 let repo = fixture
588 .import(&fixture.owner, "thing", SOURCE)
589 .await
590 .expect("start");
591
592 // What `delete_repo` does, mid-clone.
593 fixture.repos.delete(&repo.id).await.expect("delete");
594
595 let importer = InMemoryGitImport::new();
596 fixture.run(&repo.id, &importer).await.expect("run");
597
598 assert!(
599 fixture
600 .repos
601 .find_by_id(&repo.id)
602 .await
603 .expect("lookup")
604 .is_none(),
605 "saving the copy loaded before the clone would bring the row back"
606 );
607 }
608
609 #[tokio::test]
610 async fn the_boot_sweep_fails_a_running_import_and_leaves_everything_else() {
611 let fixture = fixture().await;
612 let running = fixture
613 .import(&fixture.owner, "running", SOURCE)
614 .await
615 .expect("start");
616 let done = fixture
617 .import(&fixture.owner, "done", SOURCE)
618 .await
619 .expect("start");
620
621 let importer = InMemoryGitImport::new();
622 fixture.run(&done.id, &importer).await.expect("run");
623
624 let swept = sweep_interrupted_imports(&fixture.repos)
625 .await
626 .expect("sweep");
627
628 assert_eq!(swept, 1);
629 assert_eq!(
630 fixture.reload(&running.id).await.import_state,
631 Some(ImportState::Failed)
632 );
633 assert_eq!(
634 fixture.reload(&running.id).await.import_error.as_deref(),
635 Some(INTERRUPTED)
636 );
637 assert_eq!(fixture.reload(&done.id).await.import_state, None);
638 }
639
640 #[test]
641 fn a_credential_challenge_is_explained_as_a_missing_repository() {
642 // What GitHub actually answers for a path that is not there, once terminal
643 // prompts are off. Left as git wrote it, it describes Steid's configuration
644 // rather than the mistake.
645 let explained = explain(
646 "fatal: could not read Username for 'https://github.com': terminal prompts disabled",
647 );
648
649 assert!(explained.contains("could not be found"), "{explained}");
650 assert!(
651 explained.contains("public repositories only"),
652 "{explained}"
653 );
654 }
655
656 #[test]
657 fn every_other_failure_keeps_gits_own_words() {
658 // Inventing a friendlier wording for a failure nobody anticipated is how a real
659 // reason gets hidden.
660 assert_eq!(
661 explain("fatal: unable to access 'https://example.com/': Could not resolve host"),
662 "fatal: unable to access 'https://example.com/': Could not resolve host"
663 );
664 }
665
666 #[test]
667 fn a_long_failure_message_is_cut_and_says_so() {
668 let long = "x".repeat(MAX_ERROR_LEN + 50);
669 let cut = truncate(&long, MAX_ERROR_LEN);
670
671 assert!(cut.len() <= MAX_ERROR_LEN + '…'.len_utf8());
672 assert!(cut.ends_with('…'));
673 }
674
675 #[test]
676 fn cutting_a_message_never_splits_a_character() {
677 // A multi-byte character straddling the limit would panic on a byte slice.
678 let long = "é".repeat(MAX_ERROR_LEN);
679
680 let cut = truncate(&long, MAX_ERROR_LEN);
681
682 assert!(cut.ends_with('…'));
683 }
684
685 #[test]
686 fn a_short_message_is_left_alone() {
687 assert_eq!(truncate(" not found ", MAX_ERROR_LEN), "not found");
688 }
689
690 // --- retrying ---------------------------------------------------------------------
691
692 #[tokio::test]
693 async fn a_failed_import_can_be_started_again_from_the_address_it_kept() {
694 let fixture = fixture().await;
695 let repo = fixture
696 .import(&fixture.owner, "thing", SOURCE)
697 .await
698 .expect("should start");
699
700 fixture
701 .run(
702 &repo.id,
703 &InMemoryGitImport::failing("repository not found"),
704 )
705 .await
706 .expect("should record the failure");
707
708 let retried = retry_import(
709 &fixture.owner,
710 &fixture.handle,
711 &repo.name,
712 &Stores::new(&fixture.orgs, &fixture.memberships, &fixture.repos),
713 )
714 .await
715 .expect("should retry");
716
717 assert_eq!(retried.import_state, Some(ImportState::Importing));
718 assert_eq!(retried.import_error, None, "the old reason is cleared");
719 assert_eq!(
720 retried.import_source.as_ref().map(ImportSource::as_str),
721 Some(SOURCE)
722 );
723
724 // And the second run lands, leaving an ordinary repository behind.
725 fixture
726 .run(&repo.id, &InMemoryGitImport::new())
727 .await
728 .expect("should run");
729
730 assert_eq!(fixture.reload(&repo.id).await.import_state, None);
731 }
732
733 #[tokio::test]
734 async fn only_a_failed_import_is_retryable() {
735 let fixture = fixture().await;
736
737 // Still running: a second clone would fight the first for the directory.
738 let running = fixture
739 .import(&fixture.owner, "running", SOURCE)
740 .await
741 .expect("should start");
742
743 assert!(
744 retry_import(
745 &fixture.owner,
746 &fixture.handle,
747 &running.name,
748 &Stores::new(&fixture.orgs, &fixture.memberships, &fixture.repos),
749 )
750 .await
751 .is_err()
752 );
753
754 // Never imported: there is no address to retry from.
755 let plain = Repository::new(
756 RepoId::generate(),
757 fixture
758 .orgs
759 .find_by_name(&fixture.handle)
760 .await
761 .expect("lookup")
762 .expect("org")
763 .id,
764 "plain",
765 None,
766 Visibility::Public,
767 SystemTime::UNIX_EPOCH,
768 )
769 .expect("valid repo");
770 fixture.repos.save(&plain).await.expect("save");
771
772 assert!(
773 retry_import(
774 &fixture.owner,
775 &fixture.handle,
776 &plain.name,
777 &Stores::new(&fixture.orgs, &fixture.memberships, &fixture.repos),
778 )
779 .await
780 .is_err()
781 );
782 }
783
784 #[tokio::test]
785 async fn an_imported_repository_is_private() {
786 // The form offers no choice, so the domain default is the whole of the policy.
787 // Public by accident is the mistake that cannot be taken back.
788 let fixture = fixture().await;
789
790 let repo = fixture
791 .import(&fixture.owner, "thing", SOURCE)
792 .await
793 .expect("should start");
794
795 assert_eq!(repo.visibility, Visibility::default());
796 assert!(!repo.visibility.is_public());
797 }
798
799 #[tokio::test]
800 async fn only_an_owner_may_retry_an_import() {
801 let fixture = fixture().await;
802 let repo = fixture
803 .import(&fixture.owner, "thing", SOURCE)
804 .await
805 .expect("should start");
806
807 fixture
808 .run(&repo.id, &InMemoryGitImport::failing("nope"))
809 .await
810 .expect("should record the failure");
811
812 for actor in [&fixture.member, &fixture.stranger, &Actor::Anonymous] {
813 assert!(
814 retry_import(
815 actor,
816 &fixture.handle,
817 &repo.name,
818 &Stores::new(&fixture.orgs, &fixture.memberships, &fixture.repos),
819 )
820 .await
821 .is_err()
822 );
823 }
824
825 assert_eq!(
826 fixture.reload(&repo.id).await.import_state,
827 Some(ImportState::Failed),
828 "nothing was restarted"
829 );
830 }
831}