steid

@jamesgill /

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