steid

@jamesgill /

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