Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions app/database/migrations/2026_12_05_000000_repository_picker.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
//! The repository picker (sc-9027): setting the GitHub App up maps the installation and makes no projects; people pick
//! the repositories they want, and a queued job makes them into projects.
//!
//! `user_repositories` is every repository each person can reach through each installation, with their permission on
//! it, as of their last GitHub sign-in (which lists them anyway): the picker reads it with no GitHub call, so it pages
//! and searches hundreds of repositories at once.
//!
//! `repository_imports` is one choice of repositories to make into projects, and how far the job has got: the picker
//! shows its progress, and `/status` how long the oldest unfinished one has waited.

use laravel::db::AnyTransaction;

pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
tx.query(SCHEMA).unprepared().await?;
Ok(())
}

const SCHEMA: &str = r#"
CREATE TABLE user_repositories (
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
installation_id TEXT NOT NULL REFERENCES github_installations(installation_id) ON DELETE CASCADE,
-- GitHub's ID for the repository, and its `owner/name`.
repository_id TEXT NOT NULL,
full_name TEXT NOT NULL,
-- read, triage, write, maintain or admin.
permission TEXT NOT NULL,
private BOOLEAN NOT NULL DEFAULT false,
archived BOOLEAN NOT NULL DEFAULT false,
seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (user_id, installation_id, repository_id)
);
CREATE INDEX user_repositories_name ON user_repositories (user_id, lower(full_name));

CREATE TABLE repository_imports (
id BIGSERIAL PRIMARY KEY,
organization_id BIGINT NOT NULL REFERENCES organizations(id) ON DELETE CASCADE,
user_id BIGINT REFERENCES users(id) ON DELETE SET NULL,
-- [{installation_id, repository_id, full_name}], in the order they're made.
requested JSONB NOT NULL,
-- [{project, repository}] made, and [{repository, reason}] not made, so far.
linked JSONB NOT NULL DEFAULT '[]'::jsonb,
skipped JSONB NOT NULL DEFAULT '[]'::jsonb,
-- Set when the job has gone through every repository, or stopped on an error (`error`).
finished_at TIMESTAMPTZ,
error TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX repository_imports_organization ON repository_imports (organization_id, created_at DESC);
CREATE INDEX repository_imports_unfinished ON repository_imports (created_at) WHERE finished_at IS NULL;
"#;
89 changes: 84 additions & 5 deletions app/src/auth/installations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@
//! - `GET /github/setup?installation_id=…&state=…` is the App's Setup URL: GitHub sends people there after they
//! install it, with that `state`. Someone signed out signs in first and comes back; an installation their account
//! can't reach yet sends them through GitHub's sign-in once more, which refreshes the list. With the session's
//! `state`, [`set_up`](installations::set_up) gives it an organization and projects, and they land on the
//! organization's page with the next step (adding VisualCI to CI) open. Without it (a link from another site), it
//! `state`, [`set_up`](installations::set_up) gives it an organization (no projects), and they land on the
//! repository picker, where they choose which repositories become projects. Without it (a link from another site), it
//! changes nothing: they land on their own organization's page, where the checklist offers the installation and a
//! click sets it up.
//! - `POST /api/ui/installations/{id}/setup` is that click: it sets up an installation the checklist offers ("already
//! installed on X: set it up"), and answers what it did as JSON.
//! - `GET /api/ui/orgs/{org}/repositories?q=…&page=…` is the picker (admins): the repositories the person can reach
//! 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.

use laravel::auth::{Auth, Authenticated};
use laravel::prelude::*;
Expand All @@ -24,6 +28,9 @@ pub fn routes(route: &mut Router) {
route.get("/github/install", install);
route.get("/github/setup", setup_page);
route.post("/api/ui/installations/{id}/setup", setup);
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);
}

/// The session key holding the `state` sent to GitHub with an install.
Expand All @@ -38,10 +45,10 @@ pub struct SetupQuery {
refreshed: Option<String>,
}

/// Where the organization's page opens after a set-up: the next step, adding VisualCI to CI.
/// Where a set-up lands: the organization's repository picker.
#[must_use]
pub fn landing(outcome: &SetUp) -> String {
format!("/{}?setup=add_to_ci&installation={}", outcome.organization, outcome.installation_id)
format!("/{}/repositories?installation={}", outcome.organization, outcome.installation_id)
}

/// `GET /github/install`: off to GitHub to install the App, with a `state` that brings the set-up back to this
Expand Down Expand Up @@ -83,7 +90,12 @@ 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())));
};
if !installations::reachable(user.id, &id).await? {
let 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())));
}
if !known {
if q.refreshed.is_none() {
return Ok(laravel::http::Response::new(through_sign_in(&id, q.state.as_deref())));
}
Expand Down Expand Up @@ -143,3 +155,70 @@ fn page(title: &str, message: &str) -> laravel::http::Response {
);
laravel::http::Response::new(laravel::view::Html::raw(html))
}

/// The organization's ID, for an admin of it (404 for anyone else, so it doesn't say the organization exists).
async fn admin_of(user: &User, org: &str) -> laravel::Result<i64> {
let user_id = user.id;
let row = laravel::db::query!(
"SELECT o.id, m.role FROM organizations o \
LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} WHERE o.slug = {org}"
)
.select_one()
.await?
.ok_or_else(|| laravel::abort(404))?;
match row.try_get::<Option<String>>("role")?.as_deref().and_then(crate::auth::Role::parse) {
Some(crate::auth::Role::Admin) => Ok(row.try_get("id")?),
Some(_) => Err(laravel::abort_with(403, "only the organization's admins add repositories")),
None => Err(laravel::abort(404)),
}
}

#[derive(serde::Deserialize)]
pub struct PickerQuery {
/// Only this installation's repositories.
installation: Option<String>,
q: Option<String>,
page: Option<i64>,
}

/// `GET /api/ui/orgs/{org}/repositories` (admins): a page of the repository picker.
pub async fn picker(
Authenticated(user): Authenticated<User>,
Params(org): Params<String>,
axum::extract::Query(q): axum::extract::Query<PickerQuery>,
) -> laravel::Result<Json<serde_json::Value>> {
let org_id = admin_of(&user, &org).await?;
let query: String = q.q.unwrap_or_default().chars().take(100).collect();
Ok(Json(installations::picker(user.id, org_id, q.installation.as_deref(), &query, q.page.unwrap_or(1)).await?))
}

#[laravel::input]
#[validate(authenticated)]
pub struct ImportInput {
repository_ids: Vec<String>,
}

/// `POST /api/ui/orgs/{org}/repositories` (admins): make the chosen repositories into projects, in the background.
/// Answers the pick's progress.
pub async fn import(
Authenticated(user): Authenticated<User>,
Params(org): Params<String>,
Valid(p): Valid<ImportInput>,
) -> laravel::Result<Json<serde_json::Value>> {
let org_id = admin_of(&user, &org).await?;
let id = installations::import(&user, org_id, &p.repository_ids).await?;
Ok(Json(installations::import_state(org_id, id).await?))
}

/// `GET /api/ui/orgs/{org}/repository-imports/{id}` (admins): a pick's progress.
pub async fn import_progress(
Authenticated(user): Authenticated<User>,
Params((org, id)): Params<(String, i64)>,
) -> laravel::Result<Json<serde_json::Value>> {
let org_id = admin_of(&user, &org).await?;
let state = installations::import_state(org_id, id).await?;
if state.is_null() {
return Err(laravel::abort(404));
}
Ok(Json(state))
}
2 changes: 1 addition & 1 deletion app/src/auth/sign_in.rs
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ pub async fn callback(
}
// 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).await?;
forge::installations::remember(user.id, &sign_in.installations, &sign_in.reachable).await?;
}
SignedIn {
user_id: user.id,
Expand Down
108 changes: 108 additions & 0 deletions app/src/domain/demo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ pub async fn screenshots_seed(store: &BlobStore, renderer_version: &str) -> lara
.insert()
.await?;
let blog = seed_project(&side, "blog", "Blog").await?;
seed_repository_picker(ada.id, acme_id, side_id).await?;

let seeder = Seeder { store, renderer_version };
Box::pin(seeder.web_builds(&web, ada.id)).await?;
Expand Down Expand Up @@ -626,3 +627,110 @@ fn feed(items: usize) -> String {
text.push_str("</channel>\n</rss>\n");
text
}

/// The repository picker's data: the GitHub App installed on Acme (set up for acme, 60 repositories Ada can reach, web
/// already a project, some she can only write to, two archived) and on her own account (set up for side-project, with a
/// pick of five repositories half made, for the progress page).
async fn seed_repository_picker(ada: i64, acme: i64, side: i64) -> laravel::Result<()> {
for (installation, account_id, login, kind, org) in
[("1", "5005", "acme", "Organization", acme), ("2", "1001", "ada", "User", side)]
{
let result = serde_json::json!({ "installation_id": installation, "account_login": login, "organization": "",
"organization_created": false, "note": null })
.to_string();
db::query!(
"INSERT INTO github_installations (installation_id, account_id, account_login, account_type, \
organization_id, set_up_by, installed_by, setup_result) \
VALUES ({installation}, {account_id}, {login}, {kind}, {org}, {ada}, '1001', {result}::jsonb)"
)
.insert()
.await?;
db::query!("INSERT INTO user_installations (user_id, installation_id) VALUES ({ada}, {installation})")
.insert()
.await?;
}
db::query!(
"UPDATE github_installations SET setup_result = jsonb_set(setup_result, '{{organization}}', \
to_jsonb(CASE installation_id WHEN '1' THEN 'acme' ELSE 'side-project' END))"
)
.update()
.await?;
const NAMES: &[&str] = &[
"web",
"api",
"billing",
"checkout",
"design-system",
"docs",
"emails",
"invoices-pdf",
"mobile",
"marketing-site",
"pdf-templates",
"reports",
"search",
"admin",
"analytics",
"auth",
"cli",
"data-pipeline",
"edge",
"forms",
];
let mut n = 0;
for round in ["", "-v2", "-legacy"] {
for name in NAMES {
n += 1;
let (full, id) = (format!("acme/{name}{round}"), (100 + n).to_string());
let permission = match n % 9 {
0 => "write",
4 => "read",
_ => "admin",
};
let archived = round == "-legacy" && n % 7 == 0;
let private = n % 3 != 0;
db::query!(
"INSERT INTO user_repositories (user_id, installation_id, repository_id, full_name, permission, private, \
archived) VALUES ({ada}, '1', {id}, {full}, {permission}, {private}, {archived})"
)
.insert()
.await?;
}
}
db::query!("UPDATE projects SET repository_id = '101' WHERE organization_id = {acme} AND slug = 'web'")
.update()
.await?;
for (i, name) in ["blog", "notes", "dotfiles", "recipes", "talks"].iter().enumerate() {
let (full, id) = (format!("ada/{name}"), (900 + i).to_string());
db::query!(
"INSERT INTO user_repositories (user_id, installation_id, repository_id, full_name, permission, private) \
VALUES ({ada}, '2', {id}, {full}, 'admin', false)"
)
.insert()
.await?;
}
let requested = serde_json::json!([
{ "installation_id": "2", "repository_id": "901", "full_name": "ada/notes" },
{ "installation_id": "2", "repository_id": "902", "full_name": "ada/dotfiles" },
{ "installation_id": "2", "repository_id": "903", "full_name": "ada/recipes" },
{ "installation_id": "2", "repository_id": "904", "full_name": "ada/talks" },
{ "installation_id": "2", "repository_id": "900", "full_name": "ada/blog" },
])
.to_string();
let linked = serde_json::json!([
{ "project": "notes", "repository": "ada/notes" },
{ "project": "dotfiles", "repository": "ada/dotfiles" },
])
.to_string();
let skipped = serde_json::json!([
{ "repository": "ada/recipes", "reason": "it's archived on GitHub" },
])
.to_string();
db::query!(
"INSERT INTO repository_imports (organization_id, user_id, requested, linked, skipped) \
VALUES ({side}, {ada}, {requested}::jsonb, {linked}::jsonb, {skipped}::jsonb)"
)
.insert()
.await?;
Ok(())
}
26 changes: 20 additions & 6 deletions app/src/forge/github.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub async fn sign_in(profile: &laravel::auth::social::User) -> laravel::Result<S
// 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) = installations(token).await?;
let (installations, repositories, reachable) = installations(token).await?;
Ok(SignIn {
identity: Identity {
forge: ForgeKind::Github,
Expand All @@ -34,6 +34,7 @@ pub async fn sign_in(profile: &laravel::auth::social::User) -> laravel::Result<S
},
repositories,
installations,
reachable,
})
}

Expand All @@ -56,11 +57,14 @@ async fn verified_emails(token: &str) -> laravel::Result<Vec<String>> {
Ok(emails.into_iter().map(|e| e.email.to_lowercase()).collect())
}

/// The App's installations the person can reach, and every repository the App can see through them that the person
/// has a permission on.
async fn installations(token: &str) -> laravel::Result<(Vec<Installation>, Vec<(Repository, Permission)>)> {
/// 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).
async fn installations(
token: &str,
) -> laravel::Result<(Vec<Installation>, Vec<(Repository, Permission)>, Vec<super::Reachable>)> {
let mut found = Vec::new();
let mut out = Vec::new();
let mut reachable = Vec::new();
for item in all_pages(token, "/user/installations", "installations").await? {
let Some(installation) = item["id"].as_i64() else { continue };
if let Some(account) = installation_account(installation.to_string(), &item["account"]) {
Expand All @@ -73,10 +77,20 @@ async fn installations(token: &str) -> laravel::Result<(Vec<Installation>, Vec<(
else {
continue;
};
out.push((repository.with_id(repo["id"].as_i64().map(|i| i.to_string())), permission));
let repository = repository.with_id(repo["id"].as_i64().map(|i| i.to_string()));
if repository.id.is_some() {
reachable.push(super::Reachable {
installation_id: installation.to_string(),
repository: repository.clone(),
permission,
private: repo["private"].as_bool().unwrap_or(false),
archived: repo["archived"].as_bool().unwrap_or(false),
});
}
out.push((repository, permission));
}
}
Ok((found, out))
Ok((found, out, reachable))
}

/// An installation from GitHub's `account` object (on `/user/installations` and the `installation` webhook).
Expand Down
1 change: 1 addition & 0 deletions app/src/forge/gitlab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ pub async fn sign_in(base: &str, profile: &social::User) -> laravel::Result<Sign
},
repositories,
installations: Vec::new(),
reachable: Vec::new(),
})
}

Expand Down
Loading
Loading