steid

@jamesgill /

Rust25.4 KBCode·Blame·History·Raw
1//! Importing a repository from a URL — the second way to create one.
2//!
3//! The form lives on `/{handle}/repos/new` beside the create form, but everything it
4//! needs is here: its own POST route at `/{handle}/repos/import` (a static segment, and
5//! `RepoName` reserves `import` so the two agree), the background task, and the two
6//! panels the repository page shows while a copy is running or after it failed.
7
8use std::{
9 collections::HashSet,
10 sync::{Arc, Mutex},
11};
12
13use serde::Deserialize;
14use tokio::sync::{OwnedSemaphorePermit, Semaphore};
15use topcoat::{
16 Result,
17 context::{Cx, app_context},
18 icon::{icon, iconify::iconify_icon},
19 router::{StatusCode, content::Form, error::not_found, page},
20 view::{attributes, component, view},
21};
22
23use crate::{
24 application::{
25 AppConfig, Error, ImportStatus, NewImport, RepoView, Stores, import_failure_message,
26 import_repo, retry_import, run_import,
27 },
28 components::{
29 button::{ButtonSize, ButtonVariant, button},
30 flash::{FlashKind, flash},
31 input::input,
32 label::label,
33 },
34 domain::{DomainError, ImportSource, RepoName, Visibility},
35 infrastructure::{
36 git::{DiskGitImport, DiskGitStorage},
37 repository::SqliteRepoRepo,
38 },
39};
40
41use super::{
42 context::{
43 current_actor, git_features, location, memberships, orgs, pool, repos, server_error,
44 },
45 csrf::{CsrfGuard, csrf_field, csrf_verified},
46 profile::profile_for,
47 repo::{Tab, clone_block, clone_url_for, new_repo_form, repo_for, repo_header},
48};
49
50/// How many clones may run at once.
51///
52/// **Two, chosen rather than derived.** One would serialise a small import behind a slow
53/// one and make the feature feel broken on the only instance that has ever run it — a
54/// personal one, where the second import is usually the interesting one. Much more than
55/// two stops being a limit: `git clone --mirror` is network-bound while it fetches and
56/// then CPU- and disk-bound while `index-pack` runs, so N clones of large repositories
57/// peak together on a box that is typically one or two vCPUs, and the wave-2 pass ran
58/// four at once on a laptop, which is evidence about a laptop. Two keeps a queue moving
59/// while bounding the peak to something a small VPS survives.
60///
61/// It bounds concurrency and nothing else. **There is still no size cap**: a single 10 GB
62/// source fills the disk exactly as before.
63pub const MAX_CONCURRENT_IMPORTS: usize = 2;
64
65/// The gate every import passes through, and the record of which ones are past it.
66///
67/// One per process, in app context, cloned into each spawned task — the `Arc`s are the
68/// whole of it, so cloning costs nothing.
69///
70/// The set is what lets the panel tell "queued" from "cloning". A semaphore can say how
71/// many permits are free but not *who* holds one, and the honest sentence on a repository
72/// page is about that repository rather than about the instance.
73#[derive(Debug, Clone)]
74pub struct ImportQueue {
75 permits: Arc<Semaphore>,
76 /// `{handle}/{name}` of every import currently holding a permit. A rename is refused
77 /// while an import is landing, so the pair is stable for as long as an entry lives.
78 running: Arc<Mutex<HashSet<String>>>,
79}
80
81impl Default for ImportQueue {
82 fn default() -> Self {
83 Self {
84 permits: Arc::new(Semaphore::new(MAX_CONCURRENT_IMPORTS)),
85 running: Arc::default(),
86 }
87 }
88}
89
90impl ImportQueue {
91 /// Waits for a permit, and marks the repository as cloning until the slot is dropped.
92 pub async fn enter(&self, handle: &str, name: &str) -> ImportSlot {
93 let key = format!("{handle}/{name}");
94
95 // `acquire_owned` on a closed semaphore is the only failure, and nothing closes
96 // this one — it lives as long as the process.
97 let permit = Arc::clone(&self.permits)
98 .acquire_owned()
99 .await
100 .expect("the import semaphore is never closed");
101
102 self.running
103 .lock()
104 .expect("lock poisoned")
105 .insert(key.clone());
106
107 ImportSlot {
108 _permit: permit,
109 running: Arc::clone(&self.running),
110 key,
111 }
112 }
113
114 /// How many imports hold a permit — cloning, as opposed to queued behind one.
115 ///
116 /// Exposed as `steid_active_imports`. Sampled at scrape time from the set itself
117 /// rather than mirrored into a counter, so it cannot drift from what the panels say;
118 /// a poisoned lock reports nothing rather than failing a scrape.
119 #[must_use]
120 pub fn active(&self) -> usize {
121 self.running.lock().map_or(0, |running| running.len())
122 }
123
124 /// Whether this repository's clone is actually running rather than waiting its turn.
125 pub fn is_running(&self, handle: &str, name: &str) -> bool {
126 self.running
127 .lock()
128 .expect("lock poisoned")
129 .contains(&format!("{handle}/{name}"))
130 }
131}
132
133/// A held permit. Dropping it releases the slot and unmarks the repository.
134///
135/// A guard rather than a pair of calls, so a clone that panics still gives its permit
136/// back — two lost permits would stop every future import on the instance with no error
137/// anywhere.
138pub struct ImportSlot {
139 _permit: OwnedSemaphorePermit,
140 running: Arc<Mutex<HashSet<String>>>,
141 key: String,
142}
143
144impl Drop for ImportSlot {
145 fn drop(&mut self) {
146 self.running
147 .lock()
148 .expect("lock poisoned")
149 .remove(&self.key);
150 }
151}
152
153#[derive(Debug, Deserialize)]
154struct ImportForm {
155 /// The hidden field every form carries; see [`csrf`](super::csrf).
156 ///
157 /// `default` so that a submission with no token at all is refused by
158 /// `csrf_verified` — a 403 saying what happened — rather than failing
159 /// deserialization into a bare 400 that says nothing.
160 #[serde(default)]
161 csrf_token: String,
162 name: String,
163 source: String,
164}
165
166/// Starts an import, then hands the work to a background task.
167///
168/// Success redirects to the repository, which already exists as a row and renders the
169/// importing panel — so the owner watches it from the page they would have landed on
170/// anyway rather than from a screen that exists only during an import.
171///
172/// **The task is spawned here, not in the use case.** The application layer has no
173/// business owning a runtime, and a use case that starts a task cannot be tested
174/// without waiting for one. What it needs is cloned in: a pool handle and the data
175/// directory, both cheap to clone and neither borrowing the request.
176#[page(POST "/{handle}/repos/import")]
177async fn start_import(cx: &Cx, Form(submitted): Form<ImportForm>) -> Result {
178 csrf_verified(cx, &submitted.csrf_token).await?;
179
180 let profile = profile_for(cx).await?;
181
182 let outcome = import_repo(
183 &current_actor(cx).await?,
184 &profile.handle,
185 &NewImport {
186 name: submitted.name.clone(),
187 source: submitted.source.clone(),
188 },
189 &Stores::new(&orgs(cx), &memberships(cx), &repos(cx)),
190 )
191 .await;
192
193 let repo = match outcome {
194 Ok(repo) => repo,
195 Err(Error::Domain(DomainError::Forbidden)) => return Err(not_found().into()),
196 Err(error) => {
197 let Some(message) = import_failure_message(&error, &submitted.name) else {
198 return Err(server_error(std::io::Error::other(error.to_string())));
199 };
200
201 // Re-rendered rather than redirected, so the URL that was typed is still in
202 // the box beside the reason it was refused.
203 let state = ImportBlock {
204 name: submitted.name,
205 source: submitted.source,
206 error: message,
207 };
208
209 return view! {
210 new_repo_form(
211 handle: profile.handle.as_str(),
212 name: "",
213 description: "",
214 visibility: Visibility::default(),
215 error: "",
216 import: &state,
217 )
218 };
219 }
220 };
221
222 spawn_import(cx, &profile.handle, &repo.id, &repo.name);
223
224 view! {
225 (StatusCode::SEE_OTHER)
226 (location(&format!("/{}/repos/{}", profile.handle, repo.name))?)
227 }
228}
229
230/// Starts a failed import over, and hands the work to the same background task.
231///
232/// Owner only — [`retry_import`] decides that, and a repository whose import did not fail
233/// answers `NotFound`, which is what the button's absence already said. The panel that
234/// carries the button renders only for the owner, so reaching here as anyone else means
235/// the URL was typed.
236#[page(POST "/{handle}/repos/{name}/import/retry")]
237async fn retry(cx: &Cx, Form(guard): Form<CsrfGuard>) -> Result {
238 csrf_verified(cx, &guard.csrf_token).await?;
239
240 let repo = repo_for(cx).await?;
241
242 let restarted = retry_import(
243 &current_actor(cx).await?,
244 &repo.handle,
245 &repo.name,
246 &Stores::new(&orgs(cx), &memberships(cx), &repos(cx)),
247 )
248 .await;
249
250 match restarted {
251 Ok(restarted) => spawn_import(cx, &repo.handle, &restarted.id, &restarted.name),
252 // The same 404 the settings pages give someone who does not own the repository:
253 // a 403 would confirm that a private one by this name exists.
254 Err(Error::Domain(DomainError::Forbidden | DomainError::NotFound { .. })) => {
255 return Err(not_found().into());
256 }
257 Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))),
258 }
259
260 view! {
261 (StatusCode::SEE_OTHER)
262 (location(&format!("/{}/repos/{}", repo.handle, repo.name))?)
263 }
264}
265
266/// Runs one import in the background, behind the instance's concurrency gate.
267///
268/// **The task is spawned here, not in the use case.** The application layer has no
269/// business owning a runtime, and a use case that starts a task cannot be tested without
270/// waiting for one. What it needs is cloned in: a pool handle, the data directory and the
271/// queue, all cheap to clone and none borrowing the request.
272///
273/// The permit is taken *inside* the task rather than before spawning it, so the form
274/// answers immediately whether or not there is a slot free — a submission that blocked
275/// until a clone finished would look like a hung page. Waiting is a state the repository
276/// page renders, which is the point of the queue knowing who holds a permit.
277fn spawn_import(
278 cx: &Cx,
279 handle: &crate::domain::OrgName,
280 id: &crate::domain::RepoId,
281 name: &RepoName,
282) {
283 let data_dir = app_context::<AppConfig>(cx).data_dir.clone();
284 // Read at boot. Below git 2.37 the import is refused with the reason on the
285 // repository page, because an older git cannot be pinned to the checked address.
286 let features = git_features(cx);
287 let queue = app_context::<ImportQueue>(cx).clone();
288 let pool = pool(cx).clone();
289 let handle = handle.clone();
290 let id = id.clone();
291 let name = name.clone();
292
293 tokio::spawn(async move {
294 // Held for the whole clone and released by the guard, whatever happens to it.
295 let _slot = queue.enter(handle.as_str(), name.as_str()).await;
296
297 if let Err(error) = run_import(
298 &id,
299 &handle,
300 &SqliteRepoRepo::new(pool),
301 &DiskGitImport::new(data_dir.clone(), features),
302 &DiskGitStorage::new(data_dir),
303 )
304 .await
305 {
306 // The import's own failure is recorded on the repository. Reaching here
307 // means the *recording* failed, which leaves a row stuck at `importing`
308 // until the next restart sweeps it — worth a log line, and nothing else can
309 // be done about it from in here.
310 eprintln!("steid: import of {handle}/{name} could not be recorded: {error}");
311 }
312 });
313}
314
315/// What the import block is showing.
316///
317/// Grouped rather than passed as three more parameters to
318/// [`new_repo_form`](super::repo::new_repo_form), which already carries the create
319/// form's own three: past about seven, an argument list stops being readable and starts
320/// being a place to put a value in the wrong slot.
321///
322/// Owned rather than borrowed because it is built once per render out of values with
323/// different lifetimes — a submitted form, or nothing at all.
324#[derive(Debug, Default, Clone)]
325pub(super) struct ImportBlock {
326 pub name: String,
327 pub source: String,
328 /// Empty when there is nothing to complain about.
329 pub error: String,
330}
331
332/// The second block on the new-repository page.
333///
334/// Clearly secondary: a rule above it, a quieter heading, and two fields instead of
335/// four. Creating an empty repository is what most visits are for, and an import that
336/// looked equally weighted would make the page read as a choice rather than a default
337/// with an alternative.
338///
339/// No JavaScript, so the name is not filled in from the URL as it is typed. The field
340/// may be left blank instead and the last path segment is used — which is the same
341/// answer a script would have given, arrived at on the server.
342#[component]
343pub(super) async fn import_block(handle: &str, state: &ImportBlock) -> Result {
344 let ImportBlock {
345 name,
346 source,
347 error,
348 } = state;
349 view! {
350 <section class="mt-10 border-t border-border pt-8">
351 <h2 class="text-sm font-medium">"Or import an existing repository"</h2>
352 <p class="mt-1 text-xs text-muted-foreground">
353 "Copies every branch and tag from a public "
354 <span class="font-mono">"https://"</span>
355 " repository. It runs in the background."
356 </p>
357
358 if !error.is_empty() {
359 <div class="mt-4">
360 flash(kind: FlashKind::Error, (error.as_str()))
361 </div>
362 }
363
364 <form method="post" action=(format!("/{handle}/repos/import")) class="mt-4 space-y-5">
365 csrf_field()
366 <div class="space-y-2">
367 label(attrs: attributes! { for="source" }, "URL")
368 input(attrs: attributes! {
369 id="source"
370 name="source"
371 type="url"
372 value=(source.as_str())
373 placeholder="https://github.com/owner/project.git"
374 required=(true)
375 maxlength=(ImportSource::MAX_LEN.to_string())
376 })
377 <p class="text-xs text-muted-foreground">
378 "Public repositories only. Steid will not send credentials."
379 </p>
380 </div>
381
382 <div class="space-y-2">
383 label(attrs: attributes! { for="import-name" }, "Name")
384 input(attrs: attributes! {
385 id="import-name"
386 name="name"
387 type="text"
388 value=(name.as_str())
389 placeholder="taken from the URL"
390 maxlength=(RepoName::MAX_LEN.to_string())
391 })
392 <p class="text-xs text-muted-foreground">
393 "Optional. Blank uses the last part of the URL, without "
394 <span class="font-mono">".git"</span> "."
395 </p>
396 </div>
397
398 // Outline, where the create form's is solid. Two identical buttons on
399 // one page make it read as a choice between equals; the heading and the
400 // rule above say this is the alternative, and the button should agree.
401 button(
402 attrs: attributes! { type="submit" },
403 variant: ButtonVariant::Outline,
404 "Import repository"
405 )
406 </form>
407 </section>
408 }
409}
410
411/// The repository page, for a repository whose contents have not arrived.
412///
413/// Stands where the file listing would, so the page is the same page — header, tabs,
414/// sidebar — with the one part that cannot be true yet replaced. A screen of its own
415/// would mean the owner watching a URL they then have to leave.
416#[component]
417pub(super) async fn import_state_panel(cx: &Cx, repo: &RepoView, status: &ImportStatus) -> Result {
418 let source = status
419 .source
420 .as_ref()
421 .map(ImportSource::as_str)
422 .unwrap_or("its source");
423
424 // A row that says `importing` is either being cloned or waiting for a slot, and only
425 // the queue knows which. Saying "importing" for a repository nothing has started on
426 // yet is the sentence that makes a busy instance look broken.
427 let queued = status.is_running()
428 && !app_context::<ImportQueue>(cx).is_running(repo.handle.as_str(), repo.name.as_str());
429
430 view! {
431 if status.is_running() {
432 <div class="rounded-lg border border-border px-4 py-5">
433 // The sentence is one child of the flex row, not three. As siblings the
434 // icon, the words and the address become flex items, and at 800px a
435 // long URL turns the line into three ragged columns.
436 <p class="flex items-start gap-2 text-sm">
437 // The one live thing on the page, so it carries the primary colour
438 // — the same rule as the latest-commit dot. A queued import is not
439 // live yet, so it gets the muted clock instead.
440 if queued {
441 icon(data: iconify_icon!("feather:clock"), attrs: attributes! {
442 class="mt-0.5 size-4 shrink-0 text-muted-foreground"
443 })
444 } else {
445 icon(data: iconify_icon!("feather:download-cloud"), attrs: attributes! {
446 class="mt-0.5 size-4 shrink-0 text-primary"
447 })
448 }
449 <span class="min-w-0">
450 (if queued { "Queued — waiting to import from " } else { "Importing from " })
451 // The ellipsis is inside the span so it sits against the
452 // address rather than a word-space away from it.
453 <span class="font-mono break-all">(format!("{source}…"))</span>
454 </span>
455 </p>
456 <p class="mt-2 text-xs text-muted-foreground">
457 if queued {
458 (format!(
459 "Steid copies {MAX_CONCURRENT_IMPORTS} repositories at a time, and \
460 this one is next in line. Refresh this page to check."
461 ))
462 } else {
463 "Every branch and tag is being copied. Refresh this page to check — \
464 there is nothing to wait on here."
465 }
466 </p>
467 </div>
468 } else {
469 <div class="rounded-lg border border-border px-4 py-5">
470 <p class="flex items-start gap-2 text-sm">
471 icon(data: iconify_icon!("feather:alert-triangle"), attrs: attributes! {
472 class="mt-0.5 size-4 shrink-0 text-muted-foreground"
473 })
474 <span class="min-w-0">
475 "The import from "
476 <span class="font-mono break-all">(source)</span>
477 " did not finish."
478 </span>
479 </p>
480 match &status.error {
481 // git's own words. The owner supplied the address, so the reason is
482 // theirs to read — usually "repository not found" or a name that
483 // does not resolve.
484 Some(reason) => <pre class="mt-3 overflow-x-auto rounded-lg border border-border bg-surface px-4 py-3 font-mono text-xs whitespace-pre-wrap">(reason)</pre>,
485 None => "",
486 }
487 if repo.viewer_is_owner {
488 // Retry first, because a failed import is usually a remote that was
489 // briefly unreachable rather than an address that was wrong. Deleting
490 // is the way out when it is not, and it stays a sentence rather than a
491 // second button: one destructive control beside one ordinary one reads
492 // as a choice between equals.
493 <div class="mt-4 flex flex-wrap items-center gap-3">
494 <form
495 method="post"
496 action=(format!("/{}/repos/{}/import/retry", repo.handle, repo.name))
497 >
498 csrf_field()
499 button(
500 attrs: attributes! { type="submit" },
501 variant: ButtonVariant::Outline,
502 size: ButtonSize::Sm,
503 "Retry import"
504 )
505 </form>
506 <p class="text-xs text-muted-foreground">
507 "Nothing was kept. Retrying copies from the same address again, or "
508 "delete this repository from its "
509 <a
510 href=(format!("/{}/repos/{}/settings", repo.handle, repo.name))
511 class="underline hover:text-foreground"
512 >"settings"</a>
513 " to free the name."
514 </p>
515 </div>
516 }
517 </div>
518 }
519 }
520}
521
522/// The About sidebar, for a repository that has no contents to count.
523///
524/// The same shape as the ready one — description, a definition list, the clone address
525/// — with every number an em dash. Leaving the rows out would make the sidebar change
526/// height when the import lands; a zero would be a claim that the repository is empty.
527#[component]
528pub(super) async fn import_about(repo: &RepoView, clone: &str) -> Result {
529 view! {
530 <section class="text-sm">
531 <h2 class="text-xs font-medium uppercase tracking-wider text-muted-foreground">
532 "About"
533 </h2>
534 match &repo.description {
535 Some(description) => <p class="mt-2 leading-relaxed">(description)</p>,
536 None => <p class="mt-2 text-muted-foreground">"No description."</p>,
537 }
538 </section>
539
540 <dl class="mt-4 space-y-1.5 border-t border-border pt-4 text-xs">
541 for term in ["Commits", "Branches", "Tags", "Pushed"] {
542 <div class="flex items-baseline justify-between gap-3">
543 <dt class="text-muted-foreground">(term)</dt>
544 <dd class="font-mono text-muted-foreground">"—"</dd>
545 </div>
546 }
547 </dl>
548
549 clone_block(
550 handle: repo.handle.as_str(),
551 name: repo.name.as_str(),
552 // No revision, so no archive links: there is nothing to pack yet. Empty is
553 // exactly what an empty repository passes, and `clone_block` already treats
554 // it that way.
555 rev: "",
556 url: clone,
557 )
558 }
559}
560
561/// The whole repository page while an import is running or after it failed.
562///
563/// A component rather than a branch inside `repo_page`, so the landing page keeps one
564/// shape: resolve the repository, and if it has not arrived, render this instead of
565/// asking git five questions about an empty directory.
566#[component]
567pub(super) async fn importing_page(cx: &Cx, repo: &RepoView, status: &ImportStatus) -> Result {
568 let clone = clone_url_for(cx, repo);
569
570 view! {
571 repo_header(repo: repo, rev: "", active: Tab::Code)
572
573 <div class="flex flex-col lg:flex-row lg:items-start lg:gap-6">
574 <div class="min-w-0 lg:flex-1">
575 import_state_panel(repo: repo, status: status)
576 </div>
577 <aside class="order-first mb-6 w-full shrink-0 border-b border-border pb-6 lg:order-none lg:sticky lg:top-6 lg:mb-0 lg:w-72 lg:border-b-0 lg:pb-0">
578 import_about(repo: repo, clone: clone.as_str())
579 </aside>
580 </div>
581 }
582}
583
584#[cfg(test)]
585mod tests {
586 use super::*;
587
588 #[tokio::test]
589 async fn a_slot_marks_the_repository_and_gives_the_permit_back_when_dropped() {
590 let queue = ImportQueue::default();
591
592 assert!(!queue.is_running("acme", "steid"));
593
594 {
595 let _slot = queue.enter("acme", "steid").await;
596 assert!(queue.is_running("acme", "steid"));
597 assert!(!queue.is_running("acme", "other"));
598 }
599
600 assert!(!queue.is_running("acme", "steid"));
601 }
602
603 #[tokio::test]
604 async fn a_third_import_waits_and_the_page_can_tell() {
605 let queue = ImportQueue::default();
606
607 let first = queue.enter("acme", "one").await;
608 let second = queue.enter("acme", "two").await;
609
610 // The third acquires nothing while the first two hold their permits, so its row
611 // reads as queued rather than as importing.
612 let waiting = tokio::spawn({
613 let queue = queue.clone();
614 async move { queue.enter("acme", "three").await }
615 });
616
617 tokio::task::yield_now().await;
618 assert!(!queue.is_running("acme", "three"));
619
620 drop(first);
621 let third = waiting.await.expect("the waiter is not cancelled");
622
623 assert!(queue.is_running("acme", "three"));
624 assert!(queue.is_running("acme", "two"));
625
626 drop(second);
627 drop(third);
628 assert!(!queue.is_running("acme", "three"));
629 }
630}