From d28f3c73aacadd80764634df9ac9289e1defdd58 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 18:38:40 +1300 Subject: [PATCH 1/3] Sign-in redirects at once: the callback reads who they are (at most 3 GitHub calls) and a queued job on the sign-in queue lists their installations and repositories The callback took 6.3 s for Nathan on 4 Dec 2026, listing every installation's repositories one page at a time before it redirected. Now: - the callback reads the verified addresses only for a GitHub account no user has yet, signs them in and redirects (budget 1 counted call, plus the code exchange and /user); it logs 'sign-in callback' with elapsed_ms and github_calls - SyncGithubAccess (queue sign-in, which workers take first and one worker takes alone) lists with the token kept from the sign-in, records installations and repositories in one statement each, and fires SignedIn for memberships - users.github_sync_* says how it's going: the picker and checklist show the last sign-in's repositories while it loads, a failure or a listing over 90 s says so with Try again (POST /api/ui/github/sync, or Sign in with GitHub again when the token expired), and /github/setup waits on a self-reloading page until the listing has the installation - /status reports oldest_sign_in_sync_seconds - tests: the callback under 1 s with slow repository pages and at most 1 counted call; the listing's caps; a failed listing keeps the last one; a journey times the callback (< 1 s, <= 3 GitHub calls) and covers the failed listing and Try again --- .../2026_12_07_000000_github_sign_in_sync.rs | 23 +++ app/src/auth/installations.rs | 75 ++++++++- app/src/auth/setup.rs | 18 +- app/src/auth/sign_in.rs | 68 +++++--- app/src/forge/calls.rs | 21 ++- app/src/forge/github.rs | 78 +++++---- app/src/forge/gitlab.rs | 3 - app/src/forge/installations.rs | 101 ++++++++---- app/src/forge/mod.rs | 12 +- app/src/forge/sign_in_sync.rs | 156 ++++++++++++++++++ app/src/http/status.rs | 10 +- app/tests/github_calls.rs | 105 ++++++++++-- docs/design.md | 19 ++- frontend/content/docs/self-hosting.md | 2 +- frontend/src/api/hooks.ts | 26 ++- frontend/src/api/types.ts | 6 + frontend/src/components/SetupChecklist.tsx | 5 + frontend/src/pages/RepositoriesPage.tsx | 40 ++++- frontend/src/styles.css | 11 ++ scripts/ci/visual.sh | 2 +- scripts/journeys/github-stub.mjs | 19 ++- scripts/journeys/run.sh | 2 +- scripts/screenshots/journeys.mjs | 56 +++++++ 23 files changed, 706 insertions(+), 152 deletions(-) create mode 100644 app/database/migrations/2026_12_07_000000_github_sign_in_sync.rs create mode 100644 app/src/forge/sign_in_sync.rs diff --git a/app/database/migrations/2026_12_07_000000_github_sign_in_sync.rs b/app/database/migrations/2026_12_07_000000_github_sign_in_sync.rs new file mode 100644 index 00000000..a2222192 --- /dev/null +++ b/app/database/migrations/2026_12_07_000000_github_sign_in_sync.rs @@ -0,0 +1,23 @@ +//! A GitHub sign-in's installations and repositories are listed after it, by a queued job (`forge::sign_in_sync`), not +//! in the callback (4 Dec 2026: the callback took 6.3 s listing them before it redirected). +//! +//! - `users.github_sync_requested_at`: when their last GitHub sign-in asked for the listing. +//! - `users.github_synced_at`: when the job that last finished started; the listing is still coming while it's older +//! than the request. +//! - `users.github_sync_error`: why the last listing failed, if it did. + +use laravel::db::AnyTransaction; + +pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> { + tx.query(SCHEMA).unprepared().await?; + Ok(()) +} + +const SCHEMA: &str = r" +ALTER TABLE users + ADD COLUMN github_sync_requested_at TIMESTAMPTZ, + ADD COLUMN github_synced_at TIMESTAMPTZ, + ADD COLUMN github_sync_error TEXT; +CREATE INDEX users_github_sync_waiting ON users (github_sync_requested_at) + WHERE github_sync_requested_at IS NOT NULL; +"; diff --git a/app/src/auth/installations.rs b/app/src/auth/installations.rs index 010bd296..431e6dad 100644 --- a/app/src/auth/installations.rs +++ b/app/src/auth/installations.rs @@ -14,6 +14,8 @@ //! through the organization's installations, from their last GitHub sign-in, with no GitHub call. `POST` with //! `repository_ids` makes the chosen ones into projects through a queued job; `GET //! /api/ui/orgs/{org}/repository-imports/{id}` is its progress. +//! - `POST /api/ui/github/sync` lists what their GitHub sign-in reaches again, after a listing failed: 202, or 409 +//! `sign_in_again` when the token from their sign-in has expired. use laravel::auth::{Auth, Authenticated}; use laravel::prelude::*; @@ -22,6 +24,7 @@ use laravel::session::Session; use crate::config::GithubApp; use crate::forge::github_app; use crate::forge::installations::{self, SetUp}; +use crate::forge::sign_in_sync::{self, State}; use crate::models::User; pub fn routes(route: &mut Router) { @@ -31,6 +34,7 @@ pub fn routes(route: &mut Router) { route.get("/api/ui/orgs/{org}/repositories", picker); route.post("/api/ui/orgs/{org}/repositories", import); route.get("/api/ui/orgs/{org}/repository-imports/{id}", import_progress); + route.post("/api/ui/github/sync", sync_again); } /// The session key holding the `state` sent to GitHub with an install. @@ -61,13 +65,15 @@ pub async fn install(session: Session) -> Redirect { /// Back to this page after signing in with GitHub. The ID is digits and the state letters and digits, so both are /// safe in the URL as they are. -fn through_sign_in(installation_id: &str, state: Option<&str>) -> Redirect { +fn sign_in_url(installation_id: &str, state: Option<&str>) -> String { let state = state .filter(|s| s.bytes().all(|b| b.is_ascii_alphanumeric())) .map_or(String::new(), |s| format!("%26state%3D{s}")); - Redirect::to(format!( - "/auth/github?return_to=%2Fgithub%2Fsetup%3Finstallation_id%3D{installation_id}{state}%26refreshed%3D1" - )) + format!("/auth/github?return_to=%2Fgithub%2Fsetup%3Finstallation_id%3D{installation_id}{state}%26refreshed%3D1") +} + +fn through_sign_in(installation_id: &str, state: Option<&str>) -> Redirect { + Redirect::to(sign_in_url(installation_id, state)) } /// `GET /github/setup`: GitHub's redirect after someone installs the App. @@ -90,7 +96,23 @@ pub async fn setup_page( let Some(user) = auth.user().await? else { return Ok(laravel::http::Response::new(through_sign_in(&id, q.state.as_deref()))); }; - let known = installations::reachable(user.id, &id).await?; + let mut known = installations::reachable(user.id, &id).await?; + // Back from the sign-in that refreshes their installations: its listing runs after it (`sign_in_sync`), so wait + // for it while it hasn't found this one yet + if q.refreshed.is_some() && !(known && installations::knows_repositories(user.id, &id).await?) { + match sign_in_sync::state(user.id).await? { + State::Syncing => return Ok(waiting_page()), + State::Failed | State::SignInAgain => { + return Ok(page_with( + "Couldn't read your GitHub repositories", + "GitHub didn't list your installations of the VisualCI GitHub App this time.", + None, + Some((&sign_in_url(&id, q.state.as_deref()), "Try again")), + )); + } + State::Done => known = installations::reachable(user.id, &id).await?, + } + } // Reachable only through the `installation` webhook (they installed it): sign in once more for its repositories if known && q.refreshed.is_none() && !installations::knows_repositories(user.id, &id).await? { return Ok(laravel::http::Response::new(through_sign_in(&id, q.state.as_deref()))); @@ -142,16 +164,35 @@ pub async fn setup( /// A one-message page, in the sign-in page's style. fn page(title: &str, message: &str) -> laravel::http::Response { + page_with(title, message, None, None) +} + +/// The page shown while the listing after their sign-in runs: it loads itself again every second. +fn waiting_page() -> laravel::http::Response { + page_with("Finding your GitHub repositories…", "This takes a few seconds.", Some(1), None) +} + +/// A one-message page that may load itself again after `refresh` seconds, and may link somewhere other than the app. +fn page_with( + title: &str, + message: &str, + refresh: Option, + link: Option<(&str, &str)>, +) -> laravel::http::Response { let esc = |s: &str| s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """); + let refresh = refresh.map_or(String::new(), |s| format!("")); + let (href, label) = link.unwrap_or(("/", "Go to VisualCI")); let html = format!( "{t} · VisualCI
\ -

{t}

{m}

Go to VisualCI

", +

{t}

{m}

{l}

", t = esc(title), - m = esc(message) + m = esc(message), + h = esc(href), + l = esc(label) ); laravel::http::Response::new(laravel::view::Html::raw(html)) } @@ -222,3 +263,21 @@ pub async fn import_progress( } Ok(Json(state)) } + +/// `POST /api/ui/github/sync`: list what their GitHub sign-in reaches again (the picker's "Try again"). 409 with +/// `sign_in_again` when the token from their sign-in has expired, so they sign in again instead. +pub async fn sync_again(Authenticated(user): Authenticated) -> laravel::Result { + if crate::forge::github::user_token(user.id).await.is_none() { + return Ok(laravel::http::Response::new(Json(serde_json::json!({ + "error": "sign_in_again", + "message": "Sign in with GitHub again to list your repositories", + }))) + .with_status(409)); + } + let limit = laravel::rate_limit::Limit::per_minute(6); + if laravel::rate_limit::attempt(&format!("github-sync:{}", user.id), limit).await?.is_err() { + return Err(laravel::abort_with(429, "too many tries: try again in a minute")); + } + sign_in_sync::request(user.id).await?; + Ok(laravel::http::Response::new(Json(serde_json::json!({ "sync": "syncing" }))).with_status(202)) +} diff --git a/app/src/auth/setup.rs b/app/src/auth/setup.rs index 2369fbd2..2feb0ce6 100644 --- a/app/src/auth/setup.rs +++ b/app/src/auth/setup.rs @@ -53,15 +53,15 @@ pub async fn state(org_id: i64, user_pid: Option) -> laravel let complete = steps.last().is_some_and(|(_, done)| *done); // The person's installations of the App (an offer to set one up that isn't yet), and what setting up this // organization's installations did (the repositories they couldn't add, and why) - let offers = match &subject { - Some(pid) => { - let user_id: Option = db::query!("SELECT id FROM users WHERE pid = {pid}::uuid").scalar().await?; - match user_id { - Some(id) => crate::forge::installations::offers(id).await?, - None => Vec::new(), - } + let user_id: Option = match &subject { + Some(pid) => db::query!("SELECT id FROM users WHERE pid = {pid}::uuid").scalar().await?, + None => None, + }; + let (offers, github_sync) = match user_id { + Some(id) => { + (crate::forge::installations::offers(id).await?, crate::forge::sign_in_sync::state(id).await?.as_str()) } - None => Vec::new(), + None => (Vec::new(), "done"), }; let set_up = db::query!( "SELECT installation_id, account_login, setup_result::text AS result FROM github_installations \ @@ -86,6 +86,8 @@ pub async fn state(org_id: i64, user_pid: Option) -> laravel "dismissed": row.try_get::>("dismissed")?.unwrap_or(false), "install_url": "/github/install", "installations": offers, + // How the listing after their last GitHub sign-in is going (`sign_in_sync::State`): the offers above wait for it + "github_sync": github_sync, "github": set_up, })) } diff --git a/app/src/auth/sign_in.rs b/app/src/auth/sign_in.rs index a71a7396..a3fc365c 100644 --- a/app/src/auth/sign_in.rs +++ b/app/src/auth/sign_in.rs @@ -5,8 +5,10 @@ //! The callback finds the person by their forge identity, else (when they asked to link it) the signed-in user, else //! an account with one of their verified email addresses, else makes an account: or, with sign-ups closed //! (`VISUALCI_WAITLIST=true`), puts them on the waitlist and shows one line instead. A new account fires -//! [`SignedUp`] (the domain side gives it its own organization); every sign-in fires [`SignedIn`] with the -//! repositories the forge says they can reach, for their memberships. +//! [`SignedUp`] (the domain side gives it its own organization). A GitLab sign-in fires [`SignedIn`] with the +//! repositories the forge says they can reach, for their memberships; a GitHub sign-in redirects at once, and a queued +//! job lists what it reaches and fires it (`forge::sign_in_sync`). The log line `sign-in callback` gives each one's +//! time and GitHub calls. use laravel::auth::Auth; use laravel::auth::social::{self, Provider}; @@ -159,6 +161,8 @@ pub async fn callback( hosts: laravel::config::Section, session: Session, ) -> laravel::Result { + // From GitHub's redirect to ours, the code exchange and `/user` included + let started = std::time::Instant::now(); let provider = provider(&forge)?; let return_to: Option = session.pull(RETURN_TO); let linking: bool = session.pull(LINKING).unwrap_or(false); @@ -169,36 +173,47 @@ pub async fn callback( } Err(e) => return Err(e.into()), }; - let sign_in = match ForgeKind::parse(&forge) { - Some(ForgeKind::Gitlab) => forge::gitlab::sign_in(&gitlab.url, &profile).await?, - _ => forge::github::sign_in(&profile).await?, + let kind = ForgeKind::parse(&forge).unwrap_or(ForgeKind::Github); + // Who they are. A GitHub sign-in reads nothing more here (their verified addresses only when no account has this + // GitHub account yet): what it can reach is listed after it, by a queued job (`forge::sign_in_sync`) + let (identity, gitlab_repositories) = match kind { + ForgeKind::Gitlab => { + let sign_in = forge::gitlab::sign_in(&gitlab.url, &profile).await?; + (sign_in.identity, Some(sign_in.repositories)) + } + ForgeKind::Github => { + let mut identity = forge::github::identity(&profile); + if identity_owner(&identity).await?.is_none() { + identity.verified_emails = forge::github::verified_emails(&profile.token.access).await?; + } + (identity, None) + } }; let current = auth.user().await?; let link_to = current.as_ref().filter(|_| linking); let via = return_to.as_deref().and_then(mcp_client).map_or_else(|| "web".to_string(), |c| format!("mcp: {c}")); - if sign_ups.closed() && is_new_person(&sign_in.identity, link_to).await? { - record_waitlist(&sign_in.identity, &via).await?; - return Ok(waitlist_page(&sign_in.identity)); + if sign_ups.closed() && is_new_person(&identity, link_to).await? { + record_waitlist(&identity, &via).await?; + return Ok(waitlist_page(&identity)); } - let (user, created) = user_for_sign_in(&sign_in.identity, link_to).await?; + let (user, created) = user_for_sign_in(&identity, link_to).await?; if created { SignedUp { user_id: user.id, via: via.clone() }.dispatch().await?; } - // The GitHub App's installations they can reach, for the setup page and the checklist's offers - if sign_in.identity.forge == ForgeKind::Github { - forge::installations::remember(user.id, &sign_in.installations, &sign_in.reachable).await?; - forge::installations::remember_listings(user.id, &sign_in.listings).await?; - forge::github::remember_user_token(user.id, &profile.token).await; - } - SignedIn { - user_id: user.id, - forge: sign_in.identity.forge, - site: sign_in.identity.site.clone(), - repositories: sign_in.repositories, + match gitlab_repositories { + Some(repositories) => { + SignedIn { user_id: user.id, forge: identity.forge, site: identity.site.clone(), repositories } + .dispatch() + .await?; + } + None => { + // Their token, for the job and the picker's search; then the job lists what it reaches. What an earlier + // sign-in listed stays until it has + forge::github::remember_user_token(user.id, &profile.token).await; + forge::sign_in_sync::request(user.id).await?; + } } - .dispatch() - .await?; auth.login(&user).await?; // Back where they started: the return address they came with, else the page that sent them to sign in (an MCP // client's consent page), else the app @@ -213,6 +228,15 @@ pub async fn callback( .unwrap_or_else(|| "/".to_string()), ), }; + tracing::info!( + forge = kind.as_str(), + user_id = user.id, + created, + elapsed_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX), + // Besides the code exchange and `/user`, which the framework's own client makes + github_calls = forge::calls::so_far(), + "sign-in callback" + ); Ok(laravel::http::Response::new(back).with_cookie(signed_in_hint(&hosts, true))) } diff --git a/app/src/forge/calls.rs b/app/src/forge/calls.rs index 77bb4fa1..63de31a9 100644 --- a/app/src/forge/calls.rs +++ b/app/src/forge/calls.rs @@ -32,29 +32,36 @@ tokio::task_local! { /// The most GitHub calls a request may make unless [`BUDGETS`] names it. pub const DEFAULT_BUDGET: u32 = 5; -/// A sign-in: the person's verified addresses, one page of their installations ([`super::github::SIGN_IN_INSTALLATIONS`]) -/// and at most [`super::github::SIGN_IN_REPOSITORY_PAGES`] pages of repositories across them. -pub const SIGN_IN_BUDGET: u32 = 2 + super::github::SIGN_IN_REPOSITORY_PAGES; +/// A sign-in's callback: the person's verified addresses, only when no account has their GitHub account yet. With the +/// code exchange and `/user`, which the framework's client makes uncounted, that's three at most. What they can reach +/// is listed by a queued job after it (`sign_in_sync`; 4 Dec 2026: listing it in the callback took 6.3 s). +pub const SIGN_IN_BUDGET: u32 = 1; + +/// The listing after a sign-in (`sign_in_sync`): one page of installations +/// ([`super::github::SIGN_IN_INSTALLATIONS`]) and at most [`super::github::SIGN_IN_REPOSITORY_PAGES`] pages of +/// repositories. +pub const SIGN_IN_SYNC_BUDGET: u32 = 1 + super::github::SIGN_IN_REPOSITORY_PAGES; /// Linking a repository checks it live (`link::link_repository`): the installation that reaches it, the person's /// permission (a token, their login, collaborator and permission), its ID, then its visibility and licence /// (`open_source::refresh`: a token, its path by ID, the repository). pub const LINK_BUDGET: u32 = 10; -/// Requests allowed more than [`DEFAULT_BUDGET`]: method, path (`*` is one segment), the most calls, and why. Each is -/// still a fixed number, whatever the size of the organization. +/// Requests allowed more (or fewer) than [`DEFAULT_BUDGET`]: method, path (`*` is one segment), the most calls, and +/// why. Each is still a fixed number, whatever the size of the organization. pub const BUDGETS: &[(&str, &str, u32, &str)] = &[ ( "GET", "/auth/github/callback", SIGN_IN_BUDGET, - "a sign-in lists the person's installations and repositories, a page at a time, up to fixed caps", + "a sign-in reads the person's verified addresses when no account has their GitHub account yet; the rest is a \ + queued job", ), ("PATCH", "/api/ui/orgs/*/projects/*", LINK_BUDGET, "updating a project may link its repository, checked live"), ("POST", "/mcp", LINK_BUDGET, "the update_project tool may link a repository, checked live"), ]; -/// The most GitHub calls `method path` may make, and why when it's more than [`DEFAULT_BUDGET`]. +/// The most GitHub calls `method path` may make, and why when [`BUDGETS`] names it. #[must_use] pub fn budget(method: &str, path: &str) -> (u32, Option<&'static str>) { BUDGETS diff --git a/app/src/forge/github.rs b/app/src/forge/github.rs index c2333b40..e000eb32 100644 --- a/app/src/forge/github.rs +++ b/app/src/forge/github.rs @@ -1,46 +1,42 @@ //! GitHub, as a sign-in sees it (ported from today's server). Laravel's social login does the OAuth dance with the -//! GitHub App's client ID and hands over the person's token; with it, [`sign_in`] reads every verified email address -//! and the repositories the person can reach through the app's installations, with their permission on each. +//! GitHub App's client ID and hands over the person's token. The callback takes who they are from the profile +//! ([`identity`]), reading their verified addresses ([`verified_emails`]) only when it needs them to find an account; +//! after it, a queued job lists the repositories they can reach through the App's installations, with their permission +//! on each ([`reachable`], `sign_in_sync`). use laravel::http::client; use serde::Deserialize; use serde_json::Value; -use super::{ForgeKind, Identity, Installation, Listing, Permission, Repository, SignIn}; +use super::{ForgeKind, Identity, Installation, Listing, Permission, Repository}; fn api() -> String { super::github_api() } -/// Everything a GitHub sign-in learns, from the profile Laravel's social login fetched and the person's token. -/// -/// # Errors -/// When GitHub can't be reached or refuses. -pub async fn sign_in(profile: &laravel::auth::social::User) -> laravel::Result { - let token = profile.token.access.as_str(); +/// Who a GitHub sign-in is, from the profile Laravel's social login fetched: no GitHub call. Their verified addresses +/// are left empty; [`verified_emails`] reads them. +#[must_use] +pub fn identity(profile: &laravel::auth::social::User) -> Identity { // The GitHub username: the profile's nickname, or the `/user` payload's `login` let login = profile.nickname.clone().or_else(|| profile.raw["login"].as_str().map(str::to_string)).unwrap_or_default(); - let (installations, repositories, reachable, listings) = installations(token).await?; - Ok(SignIn { - identity: Identity { - forge: ForgeKind::Github, - id: profile.id.clone(), - login, - name: profile.name.clone(), - avatar_url: profile.avatar.clone(), - verified_emails: verified_emails(token).await?, - site: String::new(), - }, - repositories, - installations, - reachable, - listings, - }) + Identity { + forge: ForgeKind::Github, + id: profile.id.clone(), + login, + name: profile.name.clone(), + avatar_url: profile.avatar.clone(), + verified_emails: Vec::new(), + site: String::new(), + } } -/// The person's verified addresses, primary first, lowercased. -async fn verified_emails(token: &str) -> laravel::Result> { +/// The person's verified addresses, primary first, lowercased: one GitHub call. +/// +/// # Errors +/// When GitHub can't be reached. +pub async fn verified_emails(token: &str) -> laravel::Result> { #[derive(Deserialize)] struct Email { email: String, @@ -63,20 +59,30 @@ async fn verified_emails(token: &str) -> laravel::Result> { pub const SIGN_IN_INSTALLATIONS: u32 = 100; /// The most pages of repositories (100 each) a sign-in reads across all the installations, so it takes a fixed number -/// of GitHub calls however many repositories the person can reach (sc-9124, `calls::SIGN_IN_BUDGET`). +/// of GitHub calls however many repositories the person can reach (sc-9124, `calls::SIGN_IN_SYNC_BUDGET`). pub const SIGN_IN_REPOSITORY_PAGES: u32 = 20; /// The most pages of repositories a sign-in reads for one installation: 1,000 repositories, so one installation with /// many (anyone's, the App being public) can't use up the pages the others need. pub const SIGN_IN_PAGES_PER_INSTALLATION: u32 = 10; -/// The App's installations the person can reach, every repository the App can see through them that the person has a -/// permission on, and the same repositories by installation (with whether each is private or archived), up to the caps -/// above. What's past a cap isn't listed, and the log says so. -#[allow(clippy::type_complexity)] -async fn installations( - token: &str, -) -> laravel::Result<(Vec, Vec<(Repository, Permission)>, Vec, Vec)> { +/// What a GitHub sign-in can reach: the App's installations, every repository the App can see through them that the +/// person has a permission on, the same repositories by installation (with whether each is private or archived), and +/// how many of each installation's repositories were listed, up to the caps above. What's past a cap isn't listed, and +/// the log says so. +pub struct Reach { + pub installations: Vec, + pub repositories: Vec<(Repository, Permission)>, + pub reachable: Vec, + pub listings: Vec, +} + +/// List what the person's token reaches ([`Reach`]): at most one page of installations and +/// [`SIGN_IN_REPOSITORY_PAGES`] pages of repositories. +/// +/// # Errors +/// When GitHub can't be reached or refuses. +pub async fn reachable(token: &str) -> laravel::Result { let mut listings = Vec::new(); let mut found = Vec::new(); let mut out = Vec::new(); @@ -137,7 +143,7 @@ async fn installations( "a sign-in listed no repositories of some installations: past its page cap" ); } - Ok((found, out, reachable, listings)) + Ok(Reach { installations: found, repositories: out, reachable, listings }) } /// An installation from GitHub's `account` object (on `/user/installations` and the `installation` webhook). diff --git a/app/src/forge/gitlab.rs b/app/src/forge/gitlab.rs index 6ec73e53..9c983167 100644 --- a/app/src/forge/gitlab.rs +++ b/app/src/forge/gitlab.rs @@ -94,9 +94,6 @@ pub async fn sign_in(base: &str, profile: &social::User) -> laravel::Result) -> laravel::Error { /// # Errors /// On a database error. pub async fn remember(user_id: i64, found: &[Installation], reachable: &[Reachable]) -> laravel::Result<()> { - let found = found.to_vec(); - let reachable = reachable.to_vec(); + // Three statements however many there are, each list one JSON parameter (4 Dec 2026: a row at a time, hundreds of + // repositories made the sign-in seconds slower) + let installations = Value::Array( + found + .iter() + .map(|i| { + json!({ "id": i.id, "account_id": i.account_id, "login": i.account_login, "kind": i.account_type }) + }) + .collect(), + ) + .to_string(); + let repositories = Value::Array( + reachable + .iter() + .filter(|r| found.iter().any(|i| i.id == r.installation_id)) + .filter_map(|r| { + Some(json!({ + "installation_id": r.installation_id, + "repository_id": r.repository.id.clone()?, + "full_name": r.repository.path, + "permission": r.permission.as_str(), + "private": r.private, + "archived": r.archived, + })) + }) + .collect(), + ) + .to_string(); db::transaction(async |_| { - for i in &found { - upsert(i).await?; - } - db::query!("DELETE FROM user_installations WHERE user_id = {user_id}").delete().await?; + db::query!( + "INSERT INTO github_installations (installation_id, account_id, account_login, account_type) \ + SELECT id, account_id, login, kind \ + FROM jsonb_to_recordset({installations}::jsonb) AS i(id text, account_id text, login text, kind text) \ + ON CONFLICT (installation_id) DO UPDATE SET account_id = EXCLUDED.account_id, \ + account_login = EXCLUDED.account_login, account_type = EXCLUDED.account_type, deleted_at = NULL, \ + updated_at = now()" + ) + .statement() + .await?; + db::query!( + "DELETE FROM user_installations WHERE user_id = {user_id} AND installation_id NOT IN \ + (SELECT id FROM jsonb_to_recordset({installations}::jsonb) AS i(id text))" + ) + .delete() + .await?; + db::query!( + "INSERT INTO user_installations (user_id, installation_id, seen_at) \ + SELECT {user_id}, id, now() FROM jsonb_to_recordset({installations}::jsonb) AS i(id text) \ + ON CONFLICT (user_id, installation_id) DO UPDATE SET seen_at = now()" + ) + .statement() + .await?; db::query!("DELETE FROM user_repositories WHERE user_id = {user_id}").delete().await?; - for i in &found { - let id = i.id.clone(); - db::query!( - "INSERT INTO user_installations (user_id, installation_id, seen_at) VALUES ({user_id}, {id}, now()) \ - ON CONFLICT (user_id, installation_id) DO UPDATE SET seen_at = now()" - ) - .insert() - .await?; - } - for r in reachable.iter().filter(|r| found.iter().any(|i| i.id == r.installation_id)) { - let (installation, repository_id, name, permission, private, archived) = ( - r.installation_id.clone(), - r.repository.id.clone(), - r.repository.path.clone(), - r.permission.as_str(), - r.private, - r.archived, - ); - db::query!( - "INSERT INTO user_repositories (user_id, installation_id, repository_id, full_name, permission, \ - private, archived) \ - VALUES ({user_id}, {installation}, {repository_id}, {name}, {permission}, {private}, {archived}) \ - ON CONFLICT (user_id, installation_id, repository_id) DO UPDATE SET full_name = EXCLUDED.full_name, \ - permission = EXCLUDED.permission, private = EXCLUDED.private, archived = EXCLUDED.archived, \ - seen_at = now()" - ) - .insert() - .await?; - } + db::query!( + "INSERT INTO user_repositories (user_id, installation_id, repository_id, full_name, permission, private, \ + archived) \ + SELECT {user_id}, installation_id, repository_id, full_name, permission, private, archived \ + FROM jsonb_to_recordset({repositories}::jsonb) AS r(installation_id text, repository_id text, \ + full_name text, permission text, private boolean, archived boolean) \ + ON CONFLICT (user_id, installation_id, repository_id) DO UPDATE SET full_name = EXCLUDED.full_name, \ + permission = EXCLUDED.permission, private = EXCLUDED.private, archived = EXCLUDED.archived, \ + seen_at = now()" + ) + .statement() + .await?; Ok(()) }) .await @@ -672,6 +700,9 @@ pub async fn picker( "installations": installations, "running": running, "search": search, + // How the listing after their last GitHub sign-in is going (`sign_in_sync::State`): the repositories above are + // what the one before listed until it's `done` + "sync": super::sign_in_sync::state(user_id).await?.as_str(), })) } diff --git a/app/src/forge/mod.rs b/app/src/forge/mod.rs index d2721c61..2683acd6 100644 --- a/app/src/forge/mod.rs +++ b/app/src/forge/mod.rs @@ -15,6 +15,7 @@ pub mod open_source; pub mod outbound; pub mod pr_comment; pub mod report; +pub mod sign_in_sync; pub mod sync; pub mod webhooks; @@ -299,18 +300,13 @@ impl Identity { } } -/// What a sign-in learns: who it is and what they can reach. +/// What a GitLab sign-in learns: who it is and what they can reach. (A GitHub sign-in lists what it can reach after +/// the callback: `sign_in_sync`.) #[derive(Debug, Clone)] pub struct SignIn { pub identity: Identity, - /// Every repository the forge app can see that this person has a permission on. + /// Every project this person has a permission on. pub repositories: Vec<(Repository, Permission)>, - /// The GitHub App's installations this person can reach (none on GitLab). - pub installations: Vec, - /// Each repository they can reach through each of those installations, for the repository picker. - pub reachable: Vec, - /// How many of each installation's repositories the sign-in listed, of how many GitHub has. - pub listings: Vec, } /// How many of an installation's repositories a sign-in listed (`reachable`), of how many GitHub has: `total` is diff --git a/app/src/forge/sign_in_sync.rs b/app/src/forge/sign_in_sync.rs new file mode 100644 index 00000000..ce28d139 --- /dev/null +++ b/app/src/forge/sign_in_sync.rs @@ -0,0 +1,156 @@ +//! What a GitHub sign-in can reach, listed right after it by a queued job (4 Dec 2026: listing it in the callback, +//! one GitHub call at a time, took 6.3 s before the person reached the app). +//! +//! The callback only finds the person, signs them in, keeps their GitHub token for a while +//! (`github::remember_user_token`) and asks for the listing ([`request`]). [`SyncGithubAccess`] then lists, with that +//! token, the App's installations they can reach and their repositories through each (up to the caps in `github`), +//! records them for the setup page and the repository picker, and fires `SignedIn` so their memberships follow. What +//! an earlier sign-in listed stays until then, so someone signing in again sees it at once. +//! +//! [`state`] says how it's going: the picker shows their repositories loading, and `/github/setup` waits for it before +//! checking the installation is theirs. A listing that failed, or didn't finish within [`WAIT_SECONDS`], says so, and +//! they try again ([`request`] once more, or a new sign-in when their token has expired). + +use laravel::db; +use laravel::queue::{Queueable, job}; +use serde::Serialize; + +use super::ForgeKind; + +/// How long a listing that hasn't finished counts as coming: past it (the queue stopped, or the job died) pages say it +/// failed, and `/status` says how long the oldest has waited. +pub const WAIT_SECONDS: i64 = 90; + +/// How the listing a person's last GitHub sign-in asked for is going. +#[derive(Clone, Debug, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum State { + /// Listed (or never asked for: a GitLab account, a session from before). + Done, + Syncing, + /// Their GitHub token from signing in has expired: a new sign-in lists it. + SignInAgain, + /// GitHub failed or the listing didn't finish: they try again. + Failed, +} + +impl State { + #[must_use] + pub fn as_str(&self) -> &'static str { + match self { + Self::Done => "done", + Self::Syncing => "syncing", + Self::SignInAgain => "sign_in_again", + Self::Failed => "failed", + } + } +} + +#[derive(Queueable)] +pub struct SyncGithubAccess { + pub user_id: i64, +} + +/// Ask for a listing of what the person's GitHub sign-in can reach. +/// +/// # Errors +/// On a database or queue error. +pub async fn request(user_id: i64) -> laravel::Result<()> { + db::query!( + "UPDATE users SET github_sync_requested_at = clock_timestamp(), github_sync_error = NULL WHERE id = {user_id}" + ) + .update() + .await?; + SyncGithubAccess { user_id }.dispatch().await?; + Ok(()) +} + +/// How the listing the person's last GitHub sign-in asked for is going. +/// +/// # Errors +/// On a database error. +pub async fn state(user_id: i64) -> laravel::Result { + let row = db::query!( + "SELECT github_sync_error AS error, \ + (github_sync_requested_at IS NOT NULL \ + AND (github_synced_at IS NULL OR github_synced_at < github_sync_requested_at)) AS waiting, \ + github_sync_requested_at < now() - make_interval(secs => {WAIT_SECONDS}) AS overdue \ + FROM users WHERE id = {user_id}" + ) + .select_one() + .await?; + let Some(row) = row else { return Ok(State::Done) }; + let waiting: Option = row.try_get("waiting")?; + if waiting == Some(true) { + let overdue: Option = row.try_get("overdue")?; + return Ok(if overdue == Some(true) { State::Failed } else { State::Syncing }); + } + Ok(match row.try_get::>("error")?.as_deref() { + None => State::Done, + Some(SIGN_IN_AGAIN) => State::SignInAgain, + Some(_) => State::Failed, + }) +} + +/// `github_sync_error` when their token from signing in has expired. +const SIGN_IN_AGAIN: &str = "sign_in_again"; + +/// On the `sign-in` queue, which workers take first and one worker takes alone (`queue:work --queue=sign-in`), so a +/// backlog of builds never holds a sign-in up. Tried once: the person tries again from the page that waits for it. +#[job(queue = "sign-in", tries = 1)] +impl SyncGithubAccess { + async fn handle(self) -> laravel::Result<()> { + let user_id = self.user_id; + // The request this run answers: a sign-in after it asks again, and keeps waiting for its own run + let requested: Option = + db::query!("SELECT github_sync_requested_at::text FROM users WHERE id = {user_id}").scalar().await?; + let result = super::calls::in_job("SyncGithubAccess", sync(user_id)).await; + let error = match &result { + Ok(()) => None, + Err(Expired) => Some(SIGN_IN_AGAIN.to_string()), + Err(Failed(e)) => { + tracing::error!(user_id, error = %e, "couldn't list what a GitHub sign-in can reach"); + Some(e.to_string()) + } + }; + db::query!( + "UPDATE users SET github_synced_at = COALESCE({requested}::timestamptz, clock_timestamp()), \ + github_sync_error = {error} \ + WHERE id = {user_id} AND (github_synced_at IS NULL \ + OR github_synced_at <= COALESCE({requested}::timestamptz, clock_timestamp()))" + ) + .update() + .await?; + // A failure is the person's to retry (the page says so), not the queue's + Ok(()) + } +} + +enum SyncError { + Expired, + Failed(laravel::Error), +} +use SyncError::{Expired, Failed}; + +impl From for SyncError { + fn from(e: laravel::Error) -> Self { + Failed(e) + } +} + +/// List what the person can reach with the token from their sign-in, record it, and let their memberships follow. +async fn sync(user_id: i64) -> Result<(), SyncError> { + let Some(token) = super::github::user_token(user_id).await else { return Err(Expired) }; + let reach = super::github::reachable(&token).await?; + super::installations::remember(user_id, &reach.installations, &reach.reachable).await?; + super::installations::remember_listings(user_id, &reach.listings).await?; + crate::auth::sign_in::SignedIn { + user_id, + forge: ForgeKind::Github, + site: String::new(), + repositories: reach.repositories, + } + .dispatch() + .await?; + Ok(()) +} diff --git a/app/src/http/status.rs b/app/src/http/status.rs index fb45e1b4..09e6ce3a 100644 --- a/app/src/http/status.rs +++ b/app/src/http/status.rs @@ -195,7 +195,11 @@ async fn numbers() -> laravel::Result> { COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(queued_at)) FROM access_rechecks), 0)::BIGINT \ AS oldest_access_recheck_seconds, \ COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(received_at)) FROM deferred_webhooks), 0)::BIGINT \ - AS oldest_deferred_webhook_seconds" + AS oldest_deferred_webhook_seconds, \ + COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(github_sync_requested_at)) FROM users \ + WHERE github_sync_requested_at IS NOT NULL \ + AND (github_synced_at IS NULL OR github_synced_at < github_sync_requested_at)), 0)::BIGINT \ + AS oldest_sign_in_sync_seconds" ) .select_one() .await? @@ -240,6 +244,10 @@ async fn numbers() -> laravel::Result> { // The longest a GitHub delivery kept over its installation's rate limit has waited: the drain (every minute) // acts on them at the allowed rate, so past ten minutes it has stopped or the installation is flooding. "oldest_deferred_webhook_seconds": get("oldest_deferred_webhook_seconds")?, + // The longest a GitHub sign-in's listing of its repositories has waited (`sign_in_sync`): the `sign-in` queue's + // worker takes it within a second or two and it takes a few more, so past a minute that worker has stopped and + // people signing in wait for repositories that never come. + "oldest_sign_in_sync_seconds": get("oldest_sign_in_sync_seconds")?, }))) } diff --git a/app/tests/github_calls.rs b/app/tests/github_calls.rs index c83c5255..2f5f3454 100644 --- a/app/tests/github_calls.rs +++ b/app/tests/github_calls.rs @@ -4,7 +4,8 @@ //! a handler fails, one within its budget doesn't, and the routes that read GitHub stay within theirs on fixtures sized //! like a large organization (hundreds of repositories, paged). -use app::forge::calls::{DEFAULT_BUDGET, SIGN_IN_BUDGET}; +use app::forge::calls::{DEFAULT_BUDGET, SIGN_IN_BUDGET, SIGN_IN_SYNC_BUDGET}; +use app::forge::sign_in_sync::{self, State, SyncGithubAccess}; use app::forge::github::{SIGN_IN_PAGES_PER_INSTALLATION, SIGN_IN_REPOSITORY_PAGES}; use hmac::{Hmac, Mac}; use laravel::auth::social::{self, Provider}; @@ -91,10 +92,9 @@ fn page_asked(url: &str) -> usize { url.split(['?', '&']).find_map(|p| p.strip_prefix("page=")).and_then(|p| p.parse().ok()).unwrap_or(1) } -/// A sign-in for someone in four large organizations (250, 5,000, 5,000 and 300 repositories through the App): a -/// fixed number of GitHub calls, the repositories listed up to the caps, and every installation recorded. -#[laravel::test(app = github)] -async fn a_sign_in_reaching_thousands_of_repositories_stays_within_its_budget(app: Application) -> laravel::Result<()> { +/// The GitHub fakes for someone in four large organizations (250, 5,000, 5,000 and 300 repositories through the App), +/// each page of repositories taking `delay`. +fn four_organizations(delay: std::time::Duration) -> client::HttpFake { let sizes = [("acme", 250usize), ("huge", 5000), ("huger", 5000), ("late", 300)]; let mut github = client::fake().with( "api.github.com/user/emails*", @@ -105,6 +105,7 @@ async fn a_sign_in_reaching_thousands_of_repositories_stays_within_its_budget(ap github = github.with( &format!("api.github.com/user/installations/{}/repositories*", i + 1), move |r: &client::Request| { + std::thread::sleep(delay); let page = page_asked(r.url()); let first = (page - 1) * 100; page_of(&owner, first, size.saturating_sub(first).min(100)) @@ -118,16 +119,64 @@ async fn a_sign_in_reaching_thousands_of_repositories_stays_within_its_budget(ap json!({ "id": i + 1, "account": { "id": 5000 + i, "login": owner, "type": "Organization" } }) }) .collect(); - let github = github.with("api.github.com/user/installations*", json!({ "installations": installations })); - let _social = social::fake().with( + github.with("api.github.com/user/installations*", json!({ "installations": installations })) +} + +fn ada() -> social::SocialFake { + social::fake().with( Provider::GITHUB, social::User::fake("gh-1").name("Ada").raw(json!({ "login": "ada" })).verified_email("ada@example.com"), - ); + ) +} + +async fn ada_id() -> laravel::Result { + db::query!("SELECT user_id FROM identities WHERE forge_user_id = 'gh-1'") + .scalar() + .await? + .ok_or_else(|| laravel::Error::msg("no user for gh-1")) +} + +/// The callback reads who they are and redirects: at most the verified addresses (for someone new; with the code +/// exchange and `/user`, three calls), none for someone signing in again, and well under a second even when every +/// page of their repositories is slow, since a queued job lists those (4 Dec 2026: the callback took 6.3 s). +#[laravel::test(app = github)] +async fn a_sign_in_redirects_at_once_and_queues_the_listing(app: Application) -> laravel::Result<()> { + let jobs = laravel::queue::fake(); + let github = four_organizations(std::time::Duration::from_millis(300)); + let _social = ada(); + + let started = std::time::Instant::now(); + app.get("/auth/github/callback").await.assert_redirect(); + let elapsed = started.elapsed(); + assert!(elapsed < std::time::Duration::from_secs(1), "the callback took {elapsed:?}"); + let urls: Vec = github.sent().iter().map(|r| r.url().to_string()).collect(); + assert!(urls.len() <= SIGN_IN_BUDGET as usize, "{urls:?}"); + assert!(urls.iter().all(|u| u.contains("/user/emails")), "{urls:?}"); + jobs.assert_pushed_times::(1); + let user = ada_id().await?; + assert_eq!(sign_in_sync::state(user).await?, State::Syncing); + + // Signing in again: no GitHub call of its own + let before = github.sent().len(); + app.get("/auth/github/callback").await.assert_redirect(); + assert_eq!(github.sent().len(), before, "signing in again made GitHub calls"); + jobs.assert_pushed_times::(2); + Ok(()) +} + +/// The listing after a sign-in (run inline here): a fixed number of GitHub calls, the repositories listed up to the +/// caps in one statement each, every installation recorded, and the listing marked done. +#[laravel::test(app = github)] +async fn the_listing_after_a_sign_in_reaching_thousands_of_repositories_stays_within_its_budget( + app: Application, +) -> laravel::Result<()> { + let github = four_organizations(std::time::Duration::ZERO); + let _social = ada(); app.get("/auth/github/callback").await.assert_redirect(); let calls = github.sent().len(); - assert!(calls <= SIGN_IN_BUDGET as usize, "{calls} GitHub calls"); - assert_eq!(calls, 2 + SIGN_IN_REPOSITORY_PAGES as usize, "every page of the cap used"); + // The addresses in the callback, then the listing's installations and every page of its cap + assert_eq!(calls, 1 + SIGN_IN_SYNC_BUDGET as usize, "{calls} GitHub calls"); let listed: Vec<(String, i64)> = db::query!( "SELECT installation_id, COUNT(*) AS n FROM user_repositories GROUP BY installation_id ORDER BY installation_id" ) @@ -142,6 +191,42 @@ async fn a_sign_in_reaching_thousands_of_repositories_stays_within_its_budget(ap assert_eq!(listed, vec![("1".into(), 250), ("2".into(), per), ("3".into(), left)], "{listed:?}"); let recorded: Option = db::query!("SELECT COUNT(*) FROM user_installations").scalar().await?; assert_eq!(recorded, Some(4), "every installation recorded, repositories listed or not"); + assert_eq!(sign_in_sync::state(ada_id().await?).await?, State::Done); + Ok(()) +} + +/// A listing GitHub fails says so (the picker offers a retry), and leaves what the last sign-in listed; one whose token +/// from signing in is gone asks them to sign in again. +#[laravel::test(app = github)] +async fn a_failed_listing_says_so_and_keeps_the_last_one(app: Application) -> laravel::Result<()> { + let _social = ada(); + { + let _github = four_organizations(std::time::Duration::ZERO); + app.get("/auth/github/callback").await.assert_redirect(); + } + let user = ada_id().await?; + let before: Option = db::query!("SELECT COUNT(*) FROM user_repositories").scalar().await?; + { + let _github = client::fake() + .with("api.github.com/user/installations*", client::response().status(502)); + app.get("/auth/github/callback").await.assert_redirect(); + } + assert_eq!(sign_in_sync::state(user).await?, State::Failed); + let after: Option = db::query!("SELECT COUNT(*) FROM user_repositories").scalar().await?; + assert_eq!(after, before, "a failed listing keeps the last one"); + + // Their token gone: the retry asks them to sign in again + app::forge::github::forget_user_token(user).await; + let ada = app::models::User::find_or_fail(user).await?; + let r = app + .post("/api/ui/github/sync") + .acting_as(&ada) + .header("sec-fetch-site", "same-origin") + .header("accept", "application/json") + .json(json!({})) + .await; + r.assert_status(409); + assert!(r.text().contains("sign_in_again"), "{}", r.text()); Ok(()) } diff --git a/docs/design.md b/docs/design.md index db919c36..42dfbac4 100644 --- a/docs/design.md +++ b/docs/design.md @@ -396,8 +396,16 @@ setting it up at once can't both win. The GET sets up only the install this brow calls at most, so it answers at once even for an organization with hundreds of repositories (3 Dec 2026: making a project per repository inside the request ran past the 30 s limit on DocSpring's 255). It lands on the repository picker (`/{org}/repositories`), which reads `user_repositories`: every repository each person can reach through each -installation, with their permission, as of their last GitHub sign-in (which lists them anyway), so it pages and -searches with no GitHub call. The repositories they pick (Maintain or Admin, not archived, at most 500 at a time) become +installation, with their permission, as of their last GitHub sign-in, so it pages and searches with no GitHub call. +The sign-in's callback doesn't list them: it reads who they are (their verified addresses only when no account has +their GitHub account yet; three GitHub calls at most), signs them in and redirects, and a queued job on the `sign-in` +queue (`SyncGithubAccess`, which workers take first and one worker takes alone) lists their installations and +repositories with the token kept from the sign-in, records them in one statement each, and fires `SignedIn` for their +memberships (4 Dec 2026: listing them in the callback took 6.3 s). What the previous sign-in listed stays until then. +`users.github_sync_*` says how it's going: the picker and the checklist show the repositories loading (`sync`), with a +retry when it failed or took over 90 s (`POST /api/ui/github/sync`, or a new sign-in when the token has expired), and +`/github/setup` back from a sign-in waits on a page that reloads itself until the listing has found the installation. +`/status` reports `oldest_sign_in_sync_seconds`, and the callback logs `sign-in callback` with its time and calls. The repositories they pick (Maintain or Admin, not archived, at most 500 at a time) become a `repository_imports` row and a queued job (`ImportRepositories`) links them one by one through the usual link checks, saving progress after each; the picker shows it, and `/status` reports `stalled_repository_import_seconds`. Nothing becomes a project on its own: repositories added to an installation later wait in the picker too. The checklist (`install_github_app`, `connect_agent`, `add_to_ci`, `review_changes`: the coding agent comes before CI because it adds VisualCI to CI, from a prompt the step pre-fills for the project) offers @@ -441,10 +449,11 @@ one debounced `RecheckAccess` run (30 s after the last delivery, at most 2 minut `oldest_access_recheck_seconds`, and the hourly sync clears the queue too. Installation tokens are cached (encrypted) until five minutes before GitHub's expiry and forgotten on a 401. -Every request's GitHub calls are counted (`forge::calls`): a fixed budget per route (5, more for a sign-in, which reads -at most 20 pages of repositories and 10 per installation, and for linking a repository), logged per request, and under +Every request's GitHub calls are counted (`forge::calls`): a fixed budget per route (5; 1 for a sign-in's callback; more +for linking a repository), logged per request, and under `APP_ENV=testing` a request over budget answers 500, so a handler that loops over a GitHub list fails CI; queued jobs -count their own and stop at page caps. The picker answers each installation's `listed` and `total`; for an installation +count their own and stop at page caps (a sign-in's listing reads at most 20 pages of repositories, 10 per +installation). The picker answers each installation's `listed` and `total`; for an installation the sign-in didn't list completely, its search asks GitHub once as the person (`search/repositories` scoped to the account, with the GitHub token kept encrypted from their sign-in, which reaches only what both they and the App can; 30 searches a minute per person) and records what it finds in `user_repositories`. Repository picks go up to 500 at once, diff --git a/frontend/content/docs/self-hosting.md b/frontend/content/docs/self-hosting.md index 3dd583ca..4ad76075 100644 --- a/frontend/content/docs/self-hosting.md +++ b/frontend/content/docs/self-hosting.md @@ -19,7 +19,7 @@ Run the image four ways, with the same environment: | Command | What it does | | --- | --- | | `serve` | The web server, on port 5150. Health check: `GET /up`. | -| `queue:work` | The worker: comparisons, checks and emails. | +| `queue:work --queue=sign-in,default` | The worker: comparisons, checks and emails, and listing each GitHub sign-in's repositories first. Run one more with `--queue=sign-in` alone, so a long comparison never makes someone signing in wait. | | `schedule:work` | The scheduler: the build sweep every five minutes, and image retention daily. | | `migrate --force` | The migrations. Run it before each new version starts. | diff --git a/frontend/src/api/hooks.ts b/frontend/src/api/hooks.ts index 5fdee348..e274a4c4 100644 --- a/frontend/src/api/hooks.ts +++ b/frontend/src/api/hooks.ts @@ -22,6 +22,7 @@ import type { Providers, InstallationSetUp, RepositoryImport, + GithubSync, RepositoryPicker, Setup, Signup, @@ -78,7 +79,12 @@ export function useProviders(enabled = true) { } export function useOrg(org: string) { - return useQuery({ queryKey: keys.org(org), queryFn: () => get(orgPath(org)) }) + return useQuery({ + queryKey: keys.org(org), + queryFn: () => get(orgPath(org)), + // The checklist's offers wait for the listing after a GitHub sign-in: asked again every second until it's in + refetchInterval: (q) => (q.state.data?.setup?.github_sync === 'syncing' ? SYNC_POLL : false), + }) } const live = (state: string | undefined) => state === 'receiving' || state === 'processing' @@ -481,6 +487,24 @@ export function useRepositoryPicker(org: string, search: { installation?: string queryKey: ['repositories', org, search.installation ?? '', search.q ?? '', search.page ?? 1], queryFn: () => get(`/api/ui/orgs/${org}/repositories${qs ? `?${qs}` : ''}`), placeholderData: (previous) => previous, + // Asked again every second while the listing after their GitHub sign-in runs + refetchInterval: (q) => (q.state.data?.sync === 'syncing' ? SYNC_POLL : false), + }) +} + +/** How often the picker and the checklist ask again while a GitHub sign-in's listing runs. */ +const SYNC_POLL = 1000 + +/** List what their GitHub sign-in reaches again, after a listing failed. Fails with code `sign_in_again` when the + * token from their sign-in has expired. */ +export function useRetryGithubSync() { + const qc = useQueryClient() + return useMutation({ + mutationFn: () => post<{ sync: GithubSync }>('/api/ui/github/sync'), + onSuccess: () => { + qc.invalidateQueries({ queryKey: ['repositories'] }) + qc.invalidateQueries({ queryKey: ['org'] }) + }, }) } diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index cb8144f7..613386cd 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -159,6 +159,9 @@ export type RepositoryImport = { error: string | null } +/** How the listing after the person's last GitHub sign-in is going: until `done`, what the one before listed. */ +export type GithubSync = 'done' | 'syncing' | 'sign_in_again' | 'failed' + /** A page of the repository picker. */ export type RepositoryPicker = { repositories: PickerRepository[] @@ -168,6 +171,7 @@ export type RepositoryPicker = { query: string installations: { installation_id: string; account_login: string }[] running: RepositoryImport | null + sync: GithubSync } /** The "Set up VisualCI" checklist: each step ticks itself from what happened. */ @@ -183,6 +187,8 @@ export type Setup = { installations: InstallationOffer[] /** The installations set up for this organization, with what their last set-up did. */ github: { installation_id: string; account_login: string; result: InstallationSetUp | null }[] + /** How the listing after their last GitHub sign-in is going: `installations` waits for it. */ + github_sync: GithubSync } export type Signup = { name: string; email: string; login: string | null; created_at: string; heard_about: string | null } diff --git a/frontend/src/components/SetupChecklist.tsx b/frontend/src/components/SetupChecklist.tsx index 1470bad1..0800b197 100644 --- a/frontend/src/components/SetupChecklist.tsx +++ b/frontend/src/components/SetupChecklist.tsx @@ -54,6 +54,11 @@ function InstallGithubApp({ org, data, onCreateProject }: { org: string; data: O {results.map((r) => ( ))} + {setup.github_sync === 'syncing' && offers.length === 0 && ( +

+ Looking for your GitHub installations… +

+ )} {offers.length > 0 && (
    {offers.map((o) => ( diff --git a/frontend/src/pages/RepositoriesPage.tsx b/frontend/src/pages/RepositoriesPage.tsx index e3bcc3cb..98945dd7 100644 --- a/frontend/src/pages/RepositoriesPage.tsx +++ b/frontend/src/pages/RepositoriesPage.tsx @@ -1,10 +1,11 @@ import { useEffect, useRef, useState } from 'react' import { Link, getRouteApi, useNavigate } from '@tanstack/react-router' import { ArrowRightIcon, CaretLeftIcon, CaretRightIcon, LockSimpleIcon, MagnifyingGlassIcon } from '@phosphor-icons/react' -import { useImportRepositories, useOrg, useRepositoryImport, useRepositoryPicker } from '../api/hooks' -import type { PickerRepository, RepositoryImport, SetupStepKey } from '../api/types' +import { ApiError } from '../api/client' +import { useImportRepositories, useOrg, useRepositoryImport, useRepositoryPicker, useRetryGithubSync } from '../api/hooks' +import type { GithubSync, PickerRepository, RepositoryImport, SetupStepKey } from '../api/types' import { QueryState } from '../components/QueryState' -import { Button, Empty, Help } from '../components/ui' +import { Button, Empty, Help, Spinner } from '../components/ui' const route = getRouteApi('/_app/$org/repositories') @@ -104,6 +105,8 @@ export function RepositoriesPage() { )} + +
    - {p.total === 0 ? ( + {p.total === 0 && !p.query && p.sync === 'syncing' ? null : p.total === 0 ? ( {!p.query && (

    @@ -315,3 +318,32 @@ function Progress({ org, orgName, next, state, onMore }: { org: string; orgName: ) } + +/** The listing after their last GitHub sign-in: loading, or failed with a way to try again. Nothing once it's in. */ +function SyncNotice({ sync, refresh }: { sync: GithubSync; refresh: string }) { + const retry = useRetryGithubSync() + if (sync === 'done') return null + if (sync === 'syncing') { + return ( +

    + + Loading your repositories from GitHub… +
    + ) + } + const expired = sync === 'sign_in_again' || (retry.error instanceof ApiError && retry.error.code === 'sign_in_again') + return ( +
    + {expired ? 'Sign in with GitHub again to load your repositories.' : 'Couldn’t load your repositories from GitHub.'} + {expired ? ( + + Sign in with GitHub again + + ) : ( + + )} +
    + ) +} diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 33658880..311b9f0b 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -898,6 +898,17 @@ select.input { color: var(--color-ink); } +/* The repository picker while the listing after a GitHub sign-in runs, or after it failed */ +.picker-sync { + align-items: center; + justify-content: space-between; + margin-bottom: var(--space-3); +} + +.picker-sync[aria-live] { + justify-content: flex-start; +} + .project-notice { justify-content: space-between; align-items: center; diff --git a/scripts/ci/visual.sh b/scripts/ci/visual.sh index 454cda3f..f7b48308 100755 --- a/scripts/ci/visual.sh +++ b/scripts/ci/visual.sh @@ -91,7 +91,7 @@ EOF "$app" screenshots:seed >>"$out/seed.log" 2>&1 || { cat "$out/seed.log"; exit 1; } (cd "$run" && exec "$app" serve >"$out/server.log" 2>&1) & server_pid=$! - (cd "$run" && exec "$app" queue:work >"$out/worker.log" 2>&1) & + (cd "$run" && exec "$app" queue:work --queue=sign-in,default >"$out/worker.log" 2>&1) & worker_pid=$! trap 'kill $server_pid $worker_pid 2>/dev/null || true' EXIT for _ in $(seq 1 60); do diff --git a/scripts/journeys/github-stub.mjs b/scripts/journeys/github-stub.mjs index 0495dfb3..a5e0872c 100644 --- a/scripts/journeys/github-stub.mjs +++ b/scripts/journeys/github-stub.mjs @@ -30,6 +30,8 @@ const secret = process.env.STUB_WEBHOOK_SECRET ?? 'journeys-webhook' let person = { id: 424242, login: 'journey-ada', name: 'Ada Journey', email: 'ada@journeys.test', avatar_url: null } const people = new Map([[person.id, person]]) const requests = [] +const timed = [] +let listing = { slow_ms: 0, fail: false } /** id -> { id, account, selection, repos: [{ id, full_name, private, archived }], members: [login], deleted } */ const installations = new Map() let target = null @@ -87,7 +89,13 @@ async function deliver(kind, event) { createServer(async (req, res) => { const url = new URL(req.url, `http://${req.headers.host}`) const path = url.pathname.replace(/^\/api\/v3/, '') - if (!url.pathname.startsWith('/_stub/')) requests.push(`${req.method} ${url.pathname}`) + if (!url.pathname.startsWith('/_stub/')) { + requests.push(`${req.method} ${url.pathname}`) + // When each call came in and was answered, for the journeys that time a sign-in + const call = { call: `${req.method} ${path}`, started: Date.now(), finished: null } + timed.push(call) + res.on('finish', () => (call.finished = Date.now())) + } let body = '' for await (const chunk of req) body += chunk const input = () => (body ? JSON.parse(body) : {}) @@ -102,8 +110,15 @@ createServer(async (req, res) => { if (url.pathname === '/_stub/requests') return json(res, 200, requests) if (url.pathname === '/_stub/requests/clear') { requests.length = 0 + timed.length = 0 return json(res, 200, {}) } + if (url.pathname === '/_stub/timed') return json(res, 200, timed) + // How listing the person's installations goes: `slow_ms` before answering, or `fail` with a 502 + if (url.pathname === '/_stub/listing' && req.method === 'POST') { + listing = { slow_ms: 0, fail: false, ...input() } + return json(res, 200, listing) + } if (url.pathname === '/_stub/target' && req.method === 'POST') { target = input() return json(res, 200, target) @@ -168,6 +183,8 @@ createServer(async (req, res) => { if (path === '/user') return json(res, 200, person) if (path === '/user/emails') return json(res, 200, [{ email: person.email, primary: true, verified: true }]) if (path === '/user/installations') { + if (listing.slow_ms) await new Promise((r) => setTimeout(r, listing.slow_ms)) + if (listing.fail) return json(res, 502, { message: 'Bad Gateway' }) const mine = live().filter((i) => i.members.includes(person.login)) return json(res, 200, { total_count: mine.length, installations: page(mine, url).map((i) => ({ id: i.id, account: i.account })) }) } diff --git a/scripts/journeys/run.sh b/scripts/journeys/run.sh index 6e902c7c..712be779 100755 --- a/scripts/journeys/run.sh +++ b/scripts/journeys/run.sh @@ -117,7 +117,7 @@ trap cleanup EXIT "$app" migrate --force >"$out/migrate.log" 2>&1 || { cat "$out/migrate.log"; exit 1; } (cd "$run" && exec "$app" serve >"$out/server.log" 2>&1) & pids+=($!) -(cd "$run" && exec "$app" queue:work >"$out/worker.log" 2>&1) & +(cd "$run" && exec "$app" queue:work --queue=sign-in,default >"$out/worker.log" 2>&1) & pids+=($!) # The stub sends the App's webhooks straight to the app, signed with its secret STUB_APP_URL="http://127.0.0.1:$port" STUB_WEBHOOK_SECRET=journeys-webhook \ diff --git a/scripts/screenshots/journeys.mjs b/scripts/screenshots/journeys.mjs index e1d7b896..f3dac9e4 100644 --- a/scripts/screenshots/journeys.mjs +++ b/scripts/screenshots/journeys.mjs @@ -455,6 +455,62 @@ await journey('personal-and-organization-installations', async ({ page, shot }) await shot('not-yours') }) +// 10b. Signing in redirects at once (4 Dec 2026: the callback listed every repository first, 6.3 s for Nathan): at most +// three GitHub calls in the callback and under a second, even when GitHub is slow to list installations. The +// listing follows in the background: the picker shows the last sign-in's repositories meanwhile, says when the +// listing failed, and "Try again" lists them. +await journey('sign-in-redirects-at-once-and-lists-after', async ({ page, shot }) => { + const quick = { id: 600004, login: 'journey-quick', name: 'Quinn Journey', email: 'quick@journeys.test' } + await signInAs(page, shot, quick) + await stub(page, '/_stub/target', { account: { id: 600004, login: 'journey-quick', type: 'User' }, selection: 'all', count: 120 }) + const { org } = await install(page) + await page.getByText('1–50 of 120').waitFor() + + const signOut = async () => { + await page.evaluate(() => fetch('/auth/logout', { method: 'POST', headers: { accept: 'application/json' } })) + await page.context().clearCookies() + } + // Signed in again with GitHub slow to list installations: the callback doesn't wait for it + await signOut() + await stub(page, '/_stub/listing', { slow_ms: 3000 }) + await stub(page, '/_stub/requests/clear') + let asked = 0 + let answered = 0 + const onRequest = (r) => r.url().includes('/auth/github/callback') && (asked = Date.now()) + const onResponse = (r) => r.url().includes('/auth/github/callback') && (answered = Date.now()) + page.on('request', onRequest) + page.on('response', onResponse) + await signInFromSite(page, shot) + page.off('request', onRequest) + page.off('response', onResponse) + expect(asked > 0 && answered >= asked, 'never saw the sign-in callback') + const ms = answered - asked + expect(ms < 1000, `the sign-in callback took ${ms} ms`) + const timed = await (await page.request.get(`${GITHUB}/_stub/timed`)).json() + const inCallback = timed.filter((c) => c.started >= asked && c.finished !== null && c.finished <= answered).map((c) => c.call) + expect(inCallback.length <= 3, `the sign-in callback made ${inCallback.length} GitHub calls: ${inCallback.join(', ')}`) + + // The picker meanwhile: the last sign-in's repositories, while the new listing loads + await page.goto(`${APP}/${org}/repositories`) + await page.getByText('1–50 of 120').waitFor() + await page.getByText('Loading your repositories from GitHub…').waitFor() + await shot('picker-refreshing') + await page.getByText('Loading your repositories from GitHub…').waitFor({ state: 'detached', timeout: 15000 }) + + // A listing GitHub fails: said so, the last one kept, and "Try again" lists them + await stub(page, '/_stub/listing', { fail: true }) + await signOut() + await signInFromSite(page, shot) + await page.goto(`${APP}/${org}/repositories`) + await page.getByText('Couldn’t load your repositories from GitHub.').waitFor({ timeout: 15000 }) + expect(await page.getByText('1–50 of 120').isVisible(), 'a failed listing kept the last one') + await shot('picker-listing-failed') + await stub(page, '/_stub/listing', {}) + await page.getByRole('button', { name: 'Try again' }).click() + await page.getByText('Couldn’t load your repositories from GitHub.').waitFor({ state: 'detached', timeout: 15000 }) + await page.getByText('1–50 of 120').waitFor() +}) + // 11. The App is public: an installation on an account with no VisualCI user stays unclaimed, and its deliveries // answer 200 without errors (nothing queued to retry). await journey('strangers-installation-stays-unclaimed', async ({ page }) => { From 515ca2afa122ee8413b7154093eb4b464f2e21c6 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 18:47:31 +1300 Subject: [PATCH 2/3] MCP goldens: setup's github_sync --- .../get_organization.json | 3 ++- .../whoami.json | 3 ++- .../get_organization.json | 3 ++- .../mcp/runs_a_build_from_uploaded_files/get_organization.json | 3 ++- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json index 5e3e699b..041e1d5c 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/get_organization.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", + "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", "type": "text" } ], @@ -45,6 +45,7 @@ "complete": false, "dismissed": false, "github": [], + "github_sync": "done", "install_url": "/github/install", "installations": [], "next": "install_github_app", diff --git a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json index 244a5c5f..ab688bfb 100644 --- a/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json +++ b/app/tests/golden/mcp/a_personal_token_manages_organizations_projects_and_tokens/whoami.json @@ -3,7 +3,7 @@ "result": { "content": [ { - "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"owner\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"via\":{\"source\":\"personal_token\",\"token_name\":\"agent\"},\"waiting_for_review\":[]}", + "text": "{\"email\":\"@example.com\",\"identities\":[],\"kind\":\"user\",\"name\":\"owner\",\"organizations\":[{\"blocked\":null,\"name\":\"Org\",\"projects\":[\"/pdfs\",\"/shots\"],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\"}],\"via\":{\"source\":\"personal_token\",\"token_name\":\"agent\"},\"waiting_for_review\":[]}", "type": "text" } ], @@ -26,6 +26,7 @@ "complete": false, "dismissed": false, "github": [], + "github_sync": "done", "install_url": "/github/install", "installations": [], "next": "install_github_app", diff --git a/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json b/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json index 55822714..7f08643d 100644 --- a/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json +++ b/app/tests/golden/mcp/a_project_token_acts_as_a_member_not_an_admin/get_organization.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"}],\"role\":\"project\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", + "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[],\"name\":\"Org\",\"projects\":[{\"last_build\":null,\"name\":\"PDFs\",\"project\":\"/pdfs\"}],\"role\":\"project\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":false,\"key\":\"connect_agent\"},{\"done\":false,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":0,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[]}", "type": "text" } ], @@ -27,6 +27,7 @@ "complete": false, "dismissed": false, "github": [], + "github_sync": "done", "install_url": "/github/install", "installations": [], "next": "install_github_app", diff --git a/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json b/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json index 746b2ef5..70b82653 100644 --- a/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json +++ b/app/tests/golden/mcp/runs_a_build_from_uploaded_files/get_organization.json @@ -5,7 +5,7 @@ "result": { "content": [ { - "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc\",\"conclusion\":\"changes\",\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":true,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"auto_approved\",\"reviewable\":true,\"reviews\":[],\"state\":\"completed\",\"stats\":{\"added\":1,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":1,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]},\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":1,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[{\"created_at\":\"\",\"credits\":1,\"kind\":\"build\",\"reference\":\"build pdfs/1: 1 snapshot checked\"}]}", + "text": "{\"billing_url\":\"https://app.visualci.test//billing\",\"invitations\":[],\"members\":[{\"avatar_url\":null,\"email\":\"@example.com\",\"id\":\"\",\"identities\":[],\"login\":null,\"name\":\"owner\",\"role\":\"admin\",\"since\":\"\",\"source\":\"created\",\"synced_at\":null}],\"name\":\"Org\",\"projects\":[{\"last_build\":{\"blocked\":null,\"branch\":\"main\",\"ci_mode\":\"review\",\"commit\":\"abc\",\"conclusion\":\"changes\",\"created_at\":\"\",\"environment\":\"ci\",\"environment_info\":{},\"error\":null,\"id\":\"\",\"mode\":\"ci\",\"name\":\"default\",\"number\":1,\"passed\":true,\"pr_number\":null,\"project\":\"/pdfs\",\"review_state\":\"auto_approved\",\"reviewable\":true,\"reviews\":[],\"state\":\"completed\",\"stats\":{\"added\":1,\"changed\":0,\"config\":0,\"failed\":0,\"ignored\":0,\"pending\":0,\"removed\":0,\"total\":1,\"unchanged\":0},\"url\":\"https://app.visualci.test//pdfs/builds/1\",\"warnings\":[]},\"name\":\"PDFs\",\"project\":\"/pdfs\"},{\"last_build\":null,\"name\":\"Screenshots\",\"project\":\"/shots\"}],\"role\":\"admin\",\"setup\":{\"complete\":false,\"dismissed\":false,\"github\":[],\"github_sync\":\"done\",\"install_url\":\"/github/install\",\"installations\":[],\"next\":\"install_github_app\",\"steps\":[{\"done\":false,\"key\":\"install_github_app\"},{\"done\":true,\"key\":\"connect_agent\"},{\"done\":true,\"key\":\"add_to_ci\"},{\"done\":false,\"key\":\"review_changes\"}]},\"slug\":\"\",\"usage\":{\"auto_reload_packs\":4,\"billing_problem\":null,\"credit_pack\":{\"credits\":500000,\"price_cents\":1500,\"reload_below\":100000},\"credits_this_month\":1,\"included_credits\":25000,\"open_source\":{\"pool\":1000000,\"projects\":0,\"used\":0},\"out_of_credits\":false,\"pack_credits\":0,\"plan\":{\"credit_packs\":false,\"id\":\"free\",\"included_credits\":25000,\"name\":\"Free\",\"price_cents\":0,\"unlimited\":false},\"rates\":{\"image_diff\":10,\"rendered_page\":20,\"snapshot_check\":1,\"text_diff\":5},\"reloads_paused\":false,\"reloads_this_month\":0,\"renews_at\":\"\",\"unlimited\":false},\"usage_history\":[{\"created_at\":\"\",\"credits\":1,\"kind\":\"build\",\"reference\":\"build pdfs/1: 1 snapshot checked\"}]}", "type": "text" } ], @@ -79,6 +79,7 @@ "complete": false, "dismissed": false, "github": [], + "github_sync": "done", "install_url": "/github/install", "installations": [], "next": "install_github_app", From 7e07ef27a43af68b02fd4b2c5f18c58449f32801 Mon Sep 17 00:00:00 2001 From: Nathan Broadbent Date: Fri, 4 Dec 2026 19:08:13 +1300 Subject: [PATCH 3/3] Sign-in listing: review fixes - The job has a 60 s timeout and gives up its listing after 45 s, recording a failure, so a killed run can't leave the person waiting; /status counts only listings asked for in the last 15 minutes, so one lost job doesn't alert for good - Two listings for one person serialise: the writes, the listing counts and the done mark happen in one transaction under the person's advisory lock, and only when no newer listing has finished; SignedIn follows only the latest - A token GitHub refuses (401) is forgotten and reads as sign_in_again, so the picker offers a new sign-in, not a Try again that can't work - The checklist shows a failed listing with Try again too, and a failed retry says why (one GithubSyncNotice for both) - The waiting-listings index covers only the waiting rows; docs/deploy.md names both worker commands - The journey allows 1.5 s in the browser with the listing slowed to 8 s --- .../2026_12_07_000000_github_sign_in_sync.rs | 3 +- app/src/auth/installations.rs | 7 +- app/src/forge/github.rs | 4 + app/src/forge/installations.rs | 56 +++++++------ app/src/forge/sign_in_sync.rs | 80 ++++++++++++++----- app/src/http/status.rs | 11 +-- app/tests/github_calls.rs | 8 +- docs/deploy.md | 3 +- frontend/src/components/GithubSyncNotice.tsx | 40 ++++++++++ frontend/src/components/SetupChecklist.tsx | 7 +- frontend/src/pages/RepositoriesPage.tsx | 38 ++------- frontend/src/styles.css | 7 +- scripts/screenshots/journeys.mjs | 10 ++- 13 files changed, 167 insertions(+), 107 deletions(-) create mode 100644 frontend/src/components/GithubSyncNotice.tsx diff --git a/app/database/migrations/2026_12_07_000000_github_sign_in_sync.rs b/app/database/migrations/2026_12_07_000000_github_sign_in_sync.rs index a2222192..958f8aa8 100644 --- a/app/database/migrations/2026_12_07_000000_github_sign_in_sync.rs +++ b/app/database/migrations/2026_12_07_000000_github_sign_in_sync.rs @@ -18,6 +18,7 @@ ALTER TABLE users ADD COLUMN github_sync_requested_at TIMESTAMPTZ, ADD COLUMN github_synced_at TIMESTAMPTZ, ADD COLUMN github_sync_error TEXT; +-- The listings still coming, for /status CREATE INDEX users_github_sync_waiting ON users (github_sync_requested_at) - WHERE github_sync_requested_at IS NOT NULL; + WHERE github_synced_at IS NULL OR github_synced_at < github_sync_requested_at; "; diff --git a/app/src/auth/installations.rs b/app/src/auth/installations.rs index 431e6dad..12215c4b 100644 --- a/app/src/auth/installations.rs +++ b/app/src/auth/installations.rs @@ -173,12 +173,7 @@ fn waiting_page() -> laravel::http::Response { } /// A one-message page that may load itself again after `refresh` seconds, and may link somewhere other than the app. -fn page_with( - title: &str, - message: &str, - refresh: Option, - link: Option<(&str, &str)>, -) -> laravel::http::Response { +fn page_with(title: &str, message: &str, refresh: Option, link: Option<(&str, &str)>) -> laravel::http::Response { let esc = |s: &str| s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """); let refresh = refresh.map_or(String::new(), |s| format!("")); let (href, label) = link.unwrap_or(("/", "Go to VisualCI")); diff --git a/app/src/forge/github.rs b/app/src/forge/github.rs index e000eb32..18de8e72 100644 --- a/app/src/forge/github.rs +++ b/app/src/forge/github.rs @@ -177,6 +177,10 @@ async fn pages(token: &str, path: &str, key: &str, max_pages: u32) -> laravel::R .query([("per_page", 100), ("page", page)]) .await?; paged.read += 1; + if response.status() == 401 { + // The person's token: revoked, or expired before it was forgotten + return Err(laravel::abort_with(401, format!("GitHub {path}: HTTP 401, the token isn't valid"))); + } if !response.successful() { return Err(laravel::Error::msg(format!("GitHub {path}: HTTP {}", response.status()))); } diff --git a/app/src/forge/installations.rs b/app/src/forge/installations.rs index 87e1d2f6..8bc65bd1 100644 --- a/app/src/forge/installations.rs +++ b/app/src/forge/installations.rs @@ -74,7 +74,8 @@ fn refused(status: u16, message: impl Into) -> laravel::Error { } /// Record the installations a person's GitHub sign-in listed, and the repositories they can reach through each (for -/// the repository picker): each installation, and that they can reach exactly these now. +/// the repository picker): each installation, and that they can reach exactly these now. Inside the caller's +/// transaction, which holds the person's lock (`sign_in_sync`). /// /// # Errors /// On a database error. @@ -84,9 +85,9 @@ pub async fn remember(user_id: i64, found: &[Installation], reachable: &[Reachab let installations = Value::Array( found .iter() - .map(|i| { - json!({ "id": i.id, "account_id": i.account_id, "login": i.account_login, "kind": i.account_type }) - }) + .map( + |i| json!({ "id": i.id, "account_id": i.account_id, "login": i.account_login, "kind": i.account_type }), + ) .collect(), ) .to_string(); @@ -107,33 +108,32 @@ pub async fn remember(user_id: i64, found: &[Installation], reachable: &[Reachab .collect(), ) .to_string(); - db::transaction(async |_| { - db::query!( - "INSERT INTO github_installations (installation_id, account_id, account_login, account_type) \ + db::query!( + "INSERT INTO github_installations (installation_id, account_id, account_login, account_type) \ SELECT id, account_id, login, kind \ FROM jsonb_to_recordset({installations}::jsonb) AS i(id text, account_id text, login text, kind text) \ ON CONFLICT (installation_id) DO UPDATE SET account_id = EXCLUDED.account_id, \ account_login = EXCLUDED.account_login, account_type = EXCLUDED.account_type, deleted_at = NULL, \ updated_at = now()" - ) - .statement() - .await?; - db::query!( - "DELETE FROM user_installations WHERE user_id = {user_id} AND installation_id NOT IN \ + ) + .statement() + .await?; + db::query!( + "DELETE FROM user_installations WHERE user_id = {user_id} AND installation_id NOT IN \ (SELECT id FROM jsonb_to_recordset({installations}::jsonb) AS i(id text))" - ) - .delete() - .await?; - db::query!( - "INSERT INTO user_installations (user_id, installation_id, seen_at) \ + ) + .delete() + .await?; + db::query!( + "INSERT INTO user_installations (user_id, installation_id, seen_at) \ SELECT {user_id}, id, now() FROM jsonb_to_recordset({installations}::jsonb) AS i(id text) \ ON CONFLICT (user_id, installation_id) DO UPDATE SET seen_at = now()" - ) - .statement() - .await?; - db::query!("DELETE FROM user_repositories WHERE user_id = {user_id}").delete().await?; - db::query!( - "INSERT INTO user_repositories (user_id, installation_id, repository_id, full_name, permission, private, \ + ) + .statement() + .await?; + db::query!("DELETE FROM user_repositories WHERE user_id = {user_id}").delete().await?; + db::query!( + "INSERT INTO user_repositories (user_id, installation_id, repository_id, full_name, permission, private, \ archived) \ SELECT {user_id}, installation_id, repository_id, full_name, permission, private, archived \ FROM jsonb_to_recordset({repositories}::jsonb) AS r(installation_id text, repository_id text, \ @@ -141,12 +141,10 @@ pub async fn remember(user_id: i64, found: &[Installation], reachable: &[Reachab ON CONFLICT (user_id, installation_id, repository_id) DO UPDATE SET full_name = EXCLUDED.full_name, \ permission = EXCLUDED.permission, private = EXCLUDED.private, archived = EXCLUDED.archived, \ seen_at = now()" - ) - .statement() - .await?; - Ok(()) - }) - .await + ) + .statement() + .await?; + Ok(()) } /// Record how many of each installation's repositories a person's sign-in listed, of how many GitHub has (the picker diff --git a/app/src/forge/sign_in_sync.rs b/app/src/forge/sign_in_sync.rs index ce28d139..32ea77c9 100644 --- a/app/src/forge/sign_in_sync.rs +++ b/app/src/forge/sign_in_sync.rs @@ -95,29 +95,38 @@ pub async fn state(user_id: i64) -> laravel::Result { /// `github_sync_error` when their token from signing in has expired. const SIGN_IN_AGAIN: &str = "sign_in_again"; +/// How long a listing may take before it gives up (and says it failed), well inside the job's own timeout, so a slow +/// GitHub can't leave the person waiting for a run the worker killed. +const LISTING_SECONDS: u64 = 45; + /// On the `sign-in` queue, which workers take first and one worker takes alone (`queue:work --queue=sign-in`), so a /// backlog of builds never holds a sign-in up. Tried once: the person tries again from the page that waits for it. -#[job(queue = "sign-in", tries = 1)] +#[job(queue = "sign-in", tries = 1, timeout = 60.seconds())] impl SyncGithubAccess { async fn handle(self) -> laravel::Result<()> { let user_id = self.user_id; // The request this run answers: a sign-in after it asks again, and keeps waiting for its own run let requested: Option = db::query!("SELECT github_sync_requested_at::text FROM users WHERE id = {user_id}").scalar().await?; - let result = super::calls::in_job("SyncGithubAccess", sync(user_id)).await; - let error = match &result { - Ok(()) => None, - Err(Expired) => Some(SIGN_IN_AGAIN.to_string()), + let listing = super::calls::in_job("SyncGithubAccess", sync(user_id, requested.clone())); + let result = match tokio::time::timeout(std::time::Duration::from_secs(LISTING_SECONDS), listing).await { + Ok(result) => result, + Err(_) => Err(Failed(laravel::Error::msg(format!("listing took over {LISTING_SECONDS} s")))), + }; + let error = match result { + // Recorded with the listing itself, under its lock + Ok(()) => return Ok(()), + Err(Expired) => SIGN_IN_AGAIN.to_string(), Err(Failed(e)) => { tracing::error!(user_id, error = %e, "couldn't list what a GitHub sign-in can reach"); - Some(e.to_string()) + e.to_string() } }; db::query!( "UPDATE users SET github_synced_at = COALESCE({requested}::timestamptz, clock_timestamp()), \ github_sync_error = {error} \ WHERE id = {user_id} AND (github_synced_at IS NULL \ - OR github_synced_at <= COALESCE({requested}::timestamptz, clock_timestamp()))" + OR github_synced_at < COALESCE({requested}::timestamptz, clock_timestamp()))" ) .update() .await?; @@ -139,18 +148,53 @@ impl From for SyncError { } /// List what the person can reach with the token from their sign-in, record it, and let their memberships follow. -async fn sync(user_id: i64) -> Result<(), SyncError> { +/// Two listings for one person can run at once (two sign-ins, or one and "Try again"): the writes happen under the +/// person's lock, and only when no newer listing has finished, so an older one never overwrites a newer one. +async fn sync(user_id: i64, requested: Option) -> Result<(), SyncError> { let Some(token) = super::github::user_token(user_id).await else { return Err(Expired) }; - let reach = super::github::reachable(&token).await?; - super::installations::remember(user_id, &reach.installations, &reach.reachable).await?; - super::installations::remember_listings(user_id, &reach.listings).await?; - crate::auth::sign_in::SignedIn { - user_id, - forge: ForgeKind::Github, - site: String::new(), - repositories: reach.repositories, - } - .dispatch() + let reach = match super::github::reachable(&token).await { + Ok(reach) => reach, + Err(e) if e.status().as_u16() == 401 => { + super::github::forget_user_token(user_id).await; + return Err(Expired); + } + Err(e) => return Err(e.into()), + }; + let lock = format!("sign-in-sync:{user_id}"); + let installations = reach.installations; + let reachable = reach.reachable; + let listings = reach.listings; + let latest = db::transaction(async |_| { + db::query!("SELECT pg_advisory_xact_lock(hashtext({lock}))").statement().await?; + let newer: Option = db::query!( + "SELECT COALESCE(github_synced_at > COALESCE({requested}::timestamptz, '-infinity'), false) \ + FROM users WHERE id = {user_id}" + ) + .scalar() + .await?; + if newer == Some(true) { + return Ok(false); + } + super::installations::remember(user_id, &installations, &reachable).await?; + super::installations::remember_listings(user_id, &listings).await?; + db::query!( + "UPDATE users SET github_synced_at = COALESCE({requested}::timestamptz, clock_timestamp()), \ + github_sync_error = NULL WHERE id = {user_id}" + ) + .update() + .await?; + Ok(true) + }) .await?; + if latest { + crate::auth::sign_in::SignedIn { + user_id, + forge: ForgeKind::Github, + site: String::new(), + repositories: reach.repositories, + } + .dispatch() + .await?; + } Ok(()) } diff --git a/app/src/http/status.rs b/app/src/http/status.rs index 09e6ce3a..7208ca29 100644 --- a/app/src/http/status.rs +++ b/app/src/http/status.rs @@ -197,8 +197,8 @@ async fn numbers() -> laravel::Result> { COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(received_at)) FROM deferred_webhooks), 0)::BIGINT \ AS oldest_deferred_webhook_seconds, \ COALESCE((SELECT EXTRACT(EPOCH FROM now() - MIN(github_sync_requested_at)) FROM users \ - WHERE github_sync_requested_at IS NOT NULL \ - AND (github_synced_at IS NULL OR github_synced_at < github_sync_requested_at)), 0)::BIGINT \ + WHERE (github_synced_at IS NULL OR github_synced_at < github_sync_requested_at) \ + AND github_sync_requested_at > now() - interval '15 minutes'), 0)::BIGINT \ AS oldest_sign_in_sync_seconds" ) .select_one() @@ -244,9 +244,10 @@ async fn numbers() -> laravel::Result> { // The longest a GitHub delivery kept over its installation's rate limit has waited: the drain (every minute) // acts on them at the allowed rate, so past ten minutes it has stopped or the installation is flooding. "oldest_deferred_webhook_seconds": get("oldest_deferred_webhook_seconds")?, - // The longest a GitHub sign-in's listing of its repositories has waited (`sign_in_sync`): the `sign-in` queue's - // worker takes it within a second or two and it takes a few more, so past a minute that worker has stopped and - // people signing in wait for repositories that never come. + // The longest a GitHub sign-in's listing of its repositories has waited (`sign_in_sync`), among those asked for in + // the last 15 minutes: the `sign-in` queue's worker takes it within a second or two and it gives up after 45 s, + // so past two minutes that worker has stopped and people signing in wait for repositories that never come. (A + // listing whose run was killed counts for 15 minutes, then not, so one lost job doesn't alert for good.) "oldest_sign_in_sync_seconds": get("oldest_sign_in_sync_seconds")?, }))) } diff --git a/app/tests/github_calls.rs b/app/tests/github_calls.rs index 2f5f3454..2f8c2364 100644 --- a/app/tests/github_calls.rs +++ b/app/tests/github_calls.rs @@ -5,8 +5,8 @@ //! like a large organization (hundreds of repositories, paged). use app::forge::calls::{DEFAULT_BUDGET, SIGN_IN_BUDGET, SIGN_IN_SYNC_BUDGET}; -use app::forge::sign_in_sync::{self, State, SyncGithubAccess}; use app::forge::github::{SIGN_IN_PAGES_PER_INSTALLATION, SIGN_IN_REPOSITORY_PAGES}; +use app::forge::sign_in_sync::{self, State, SyncGithubAccess}; use hmac::{Hmac, Mac}; use laravel::auth::social::{self, Provider}; use laravel::db; @@ -185,6 +185,9 @@ async fn the_listing_after_a_sign_in_reaching_thousands_of_repositories_stays_wi .iter() .map(|r| Ok((r.try_get("installation_id")?, r.try_get("n")?))) .collect::>()?; + let error: Option = + db::query!("SELECT github_sync_error FROM users WHERE github_sync_error IS NOT NULL").scalar().await?; + assert_eq!(error, None, "the listing failed"); let per = i64::from(SIGN_IN_PAGES_PER_INSTALLATION) * 100; // 3 pages for acme, 10 for huge, the 7 left for huger, none for late let left = (i64::from(SIGN_IN_REPOSITORY_PAGES) - 3 - i64::from(SIGN_IN_PAGES_PER_INSTALLATION)) * 100; @@ -207,8 +210,7 @@ async fn a_failed_listing_says_so_and_keeps_the_last_one(app: Application) -> la let user = ada_id().await?; let before: Option = db::query!("SELECT COUNT(*) FROM user_repositories").scalar().await?; { - let _github = client::fake() - .with("api.github.com/user/installations*", client::response().status(502)); + let _github = client::fake().with("api.github.com/user/installations*", client::response().status(502)); app.get("/auth/github/callback").await.assert_redirect(); } assert_eq!(sign_in_sync::state(user).await?, State::Failed); diff --git a/docs/deploy.md b/docs/deploy.md index cd691649..c2f11158 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -30,7 +30,8 @@ it. | Workload | Image and command | Node | Resources | Probes | |---|---|---|---|---| | web | app, `serve` (port 5150) | products-1 | 250m / 512Mi | readiness and liveness `GET /up` | -| worker | app, `queue:work` | products-1 | 250m / 512Mi | none over HTTP; `/status` covers it (below) | +| worker (3) | app, `queue:work --queue=sign-in,default`: the sign-in listings first, then everything else | products-1 | 250m / 512Mi | none over HTTP; `/status` covers it (below) | +| worker-sign-in | app, `queue:work --queue=sign-in`: only the listing after each GitHub sign-in (`SyncGithubAccess`), so a backlog of builds never holds one up | products-1 | 50m / 256Mi | `/status` `oldest_sign_in_sync_seconds`, alerted above 120 | | scheduler | app, `schedule:work`: the scheduled jobs (below), each with its own heartbeat | products-1 | 250m / 512Mi | the heartbeats | | renderer | renderer (no args) | render-1 only: toleration `talira.ai/untrusted=true:NoSchedule`, `runtimeClassName: gvisor`, `automountServiceAccountToken: false` | 1 CPU / 1.5Gi each, 2 replicas on the cx23 (scale with the node) | liveness: `test $(( $(date +%s) - $(stat -c %Y /tmp/heartbeat) )) -lt 60` (touched after every poll) | | migrate | app, `migrate --force`, an ArgoCD Sync hook Job | products-1 | | | diff --git a/frontend/src/components/GithubSyncNotice.tsx b/frontend/src/components/GithubSyncNotice.tsx new file mode 100644 index 00000000..c018a89f --- /dev/null +++ b/frontend/src/components/GithubSyncNotice.tsx @@ -0,0 +1,40 @@ +import { ApiError, errorMessage } from '../api/client' +import { useRetryGithubSync } from '../api/hooks' +import type { GithubSync } from '../api/types' +import { Button, Spinner } from './ui' + +/** + * The listing after the person's last GitHub sign-in (their installations and repositories): loading, or failed with + * a way to try again (or to sign in again when the token from their sign-in has expired). Nothing once it's in. + */ +export function GithubSyncNotice({ sync, signIn, what }: { sync: GithubSync; signIn: string; what: 'repositories' | 'installations' }) { + const retry = useRetryGithubSync() + if (sync === 'done') return null + if (sync === 'syncing') { + return ( +
    + + Loading your {what} from GitHub… +
    + ) + } + const expired = sync === 'sign_in_again' || (retry.error instanceof ApiError && retry.error.code === 'sign_in_again') + const failedAgain = retry.error && !expired ? errorMessage(retry.error) : null + return ( +
    + + {expired ? `Sign in with GitHub again to load your ${what}.` : `Couldn’t load your ${what} from GitHub.`} + {failedAgain && {failedAgain}} + + {expired ? ( + + Sign in with GitHub again + + ) : ( + + )} +
    + ) +} diff --git a/frontend/src/components/SetupChecklist.tsx b/frontend/src/components/SetupChecklist.tsx index 0800b197..cc6e0427 100644 --- a/frontend/src/components/SetupChecklist.tsx +++ b/frontend/src/components/SetupChecklist.tsx @@ -6,6 +6,7 @@ import type { InstallationSetUp, Org, SetupStepKey } from '../api/types' import { apiUrl, mcpUrl } from '../lib/hosts' import { Button, CodeBlock, CopyButton, Help } from './ui' import { RequestBox } from './RequestBox' +import { GithubSyncNotice } from './GithubSyncNotice' import githubActions from '../../content/docs/ci/github-actions.md?raw' import circleci from '../../content/docs/ci/circleci.md?raw' import gitlab from '../../content/docs/ci/gitlab.md?raw' @@ -54,10 +55,8 @@ function InstallGithubApp({ org, data, onCreateProject }: { org: string; data: O {results.map((r) => ( ))} - {setup.github_sync === 'syncing' && offers.length === 0 && ( -

    - Looking for your GitHub installations… -

    + {(setup.github_sync !== 'syncing' || offers.length === 0) && ( + )} {offers.length > 0 && (
      diff --git a/frontend/src/pages/RepositoriesPage.tsx b/frontend/src/pages/RepositoriesPage.tsx index 98945dd7..40d41fa6 100644 --- a/frontend/src/pages/RepositoriesPage.tsx +++ b/frontend/src/pages/RepositoriesPage.tsx @@ -1,11 +1,11 @@ import { useEffect, useRef, useState } from 'react' import { Link, getRouteApi, useNavigate } from '@tanstack/react-router' import { ArrowRightIcon, CaretLeftIcon, CaretRightIcon, LockSimpleIcon, MagnifyingGlassIcon } from '@phosphor-icons/react' -import { ApiError } from '../api/client' -import { useImportRepositories, useOrg, useRepositoryImport, useRepositoryPicker, useRetryGithubSync } from '../api/hooks' -import type { GithubSync, PickerRepository, RepositoryImport, SetupStepKey } from '../api/types' +import { useImportRepositories, useOrg, useRepositoryImport, useRepositoryPicker } from '../api/hooks' +import type { PickerRepository, RepositoryImport, SetupStepKey } from '../api/types' import { QueryState } from '../components/QueryState' -import { Button, Empty, Help, Spinner } from '../components/ui' +import { Button, Empty, Help } from '../components/ui' +import { GithubSyncNotice } from '../components/GithubSyncNotice' const route = getRouteApi('/_app/$org/repositories') @@ -105,7 +105,7 @@ export function RepositoriesPage() { )} - +