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
21 changes: 21 additions & 0 deletions app/database/migrations/2026_12_08_000000_project_deletion.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//! Deleting a project: `deleted_at` hides it at once (lists, URLs, tokens, uploads, webhooks), and the purge
//! (`domain::project_deletion`) removes its rows and blob objects 7 days later. Until then staff can restore it.
//!
//! The slug is unique only among live projects (a partial index), so a new project, or a repository picked again,
//! can take a deleted project's slug at once. Restoring refuses while a live project has it.

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 projects ADD COLUMN deleted_at TIMESTAMPTZ;
ALTER TABLE projects ADD COLUMN deleted_by BIGINT REFERENCES users(id) ON DELETE SET NULL;
ALTER TABLE projects DROP CONSTRAINT projects_organization_id_slug_key;
CREATE UNIQUE INDEX projects_organization_slug_live ON projects (organization_id, slug) WHERE deleted_at IS NULL;
CREATE INDEX projects_deleted ON projects (deleted_at) WHERE deleted_at IS NOT NULL;
CREATE INDEX projects_deleted_by ON projects (deleted_by) WHERE deleted_by IS NOT NULL;
";
2 changes: 1 addition & 1 deletion app/src/auth/memberships.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ async fn linked_projects(forge: ForgeKind) -> laravel::Result<Vec<LinkedProject>
let rows = db::query!(
"SELECT organization_id, repository_url, repository_id FROM projects \
WHERE forge = {forge_name} AND repository_url IS NOT NULL AND repository_id IS NOT NULL \
AND forge_installation IS NOT NULL"
AND forge_installation IS NOT NULL AND deleted_at IS NULL"
)
.select()
.await?;
Expand Down
8 changes: 6 additions & 2 deletions app/src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use axum::http::request::Parts;
use laravel::auth::Auth;
use laravel::db;

use crate::models::{ProjectToken, User, UserToken, token_hash};
use crate::models::{Project, ProjectToken, User, UserToken, token_hash};

/// What someone may do in a project's organization, lowest first.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
Expand Down Expand Up @@ -185,7 +185,7 @@ impl Principal {
let user_id = user.id;
db::query!(
"SELECT p.id FROM projects p JOIN memberships m ON m.organization_id = p.organization_id \
WHERE m.user_id = {user_id} ORDER BY p.id"
WHERE m.user_id = {user_id} AND p.deleted_at IS NULL ORDER BY p.id"
)
.select_as::<i64>()
.await
Expand All @@ -203,6 +203,10 @@ impl Principal {
// doesn't write on every request
if token.starts_with("vci_") {
let Some(t) = ProjectToken::first_where(ProjectToken::token_hash.eq(&hash)).await? else { return Ok(None) };
// A deleted project's tokens stop working at once (its rows stay until the purge, for a restore).
if Project::find_live(t.project_id).await?.is_none() {
return Ok(None);
}
let id = t.id;
db::query!(
"UPDATE project_tokens SET last_used_at = now() WHERE id = {id} \
Expand Down
25 changes: 15 additions & 10 deletions app/src/auth/orgs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,23 +134,27 @@ fn build_summary(b: &Build) -> Value {
})
}

/// This month's credits per project, with how much came from the open source pool, for the Usage tab.
/// This month's credits per project, with how much came from the open source pool, for the Usage tab. A deleted
/// project stays listed (`deleted`) while it has credits this month: what it used still counts.
async fn usage_by_project(org_id: i64) -> laravel::Result<Vec<Value>> {
let since = crate::domain::credits::month_start();
let rows = db::query!(
"SELECT p.slug, p.name, (p.open_source AND p.public AND NOT p.open_source_withdrawn) AS open_source, \
p.deleted_at IS NOT NULL AS deleted, \
COALESCE(-SUM(t.amount), 0)::bigint AS credits, COALESCE(SUM(t.open_source_credits), 0)::bigint AS pool \
FROM projects p LEFT JOIN credit_transactions t ON t.project_id = p.id AND t.created_at >= {since} \
AND t.kind IN ('build', 'render', 'gallery') \
WHERE p.organization_id = {org_id} GROUP BY p.id ORDER BY credits DESC, p.slug"
WHERE p.organization_id = {org_id} GROUP BY p.id \
HAVING p.deleted_at IS NULL OR COUNT(t.id) > 0 ORDER BY credits DESC, p.slug, p.id"
)
.select()
.await?;
rows.iter()
.map(|r| {
Ok(json!({
"project": r.try_get::<String>("slug")?, "name": r.try_get::<String>("name")?,
"open_source": r.try_get::<bool>("open_source")?, "credits": r.try_get::<i64>("credits")?,
"open_source": r.try_get::<bool>("open_source")?, "deleted": r.try_get::<bool>("deleted")?,
"credits": r.try_get::<i64>("credits")?,
"open_source_credits": r.try_get::<i64>("pool")?,
}))
})
Expand All @@ -168,13 +172,14 @@ pub async fn show(
let (org_id, _, role) = super::invitations::org_role(&user, &org).await?;
let org = Organization::find_or_fail(org_id).await?;
let admin = role == Role::Admin;
let projects: Vec<(i64, String, String)> =
db::query!("SELECT id, slug, name FROM projects WHERE organization_id = {org_id} ORDER BY slug")
.select()
.await?
.iter()
.map(|r| Ok((r.try_get("id")?, r.try_get("slug")?, r.try_get("name")?)))
.collect::<laravel::Result<_>>()?;
let projects: Vec<(i64, String, String)> = db::query!(
"SELECT id, slug, name FROM projects WHERE organization_id = {org_id} AND deleted_at IS NULL ORDER BY slug"
)
.select()
.await?
.iter()
.map(|r| Ok((r.try_get("id")?, r.try_get("slug")?, r.try_get("name")?)))
.collect::<laravel::Result<_>>()?;
let mut list = Vec::new();
for (id, slug, name) in projects {
let last = crate::domain::builds::recent(id, None, false, 1).await?;
Expand Down
2 changes: 1 addition & 1 deletion app/src/auth/tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ async fn admin_project(user: &User, org: &str, project: &str, action: &str) -> l
let row = db::query!(
"SELECT p.id, p.organization_id, p.slug, m.role FROM projects p JOIN organizations o ON o.id = p.organization_id \
LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} \
WHERE o.slug = {org} AND p.slug = {project}"
WHERE o.slug = {org} AND p.slug = {project} AND p.deleted_at IS NULL"
)
.select_one()
.await?
Expand Down
18 changes: 16 additions & 2 deletions app/src/console/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! The schedule (`laravel schedule:run` every minute, in production a CronJob): the builds sweep every five minutes;
//! retention, the groups check, the demo reset and the credit override reminders daily. Each run pushes its result to
//! a heartbeat, so a task that failed or stopped running alerts.
//! retention, the groups check, the demo reset, the credit override reminders and the deleted projects' purge daily.
//! Each run pushes its result to a heartbeat, so a task that failed or stopped running alerts; the purge is watched
//! through `/status` instead (`oldest_deleted_project_unpurged_seconds`).

use laravel::schedule::{self, Schedule};

Expand All @@ -18,6 +19,19 @@ fn schedule(schedule: &mut Schedule) {
schedule.command("groups:check").daily_at("04:00").without_overlapping().on_one_runner();
schedule.command("demo:reset").name("demo-reset").daily_at("05:00").without_overlapping().on_one_runner();
schedule.command("credits:override-reminders").daily_at("06:00").without_overlapping().on_one_runner();
schedule.call(purge_projects).name("projects-purge").daily_at("02:00").without_overlapping().on_one_runner();
}

/// [`crate::domain::project_deletion::sweep`]: deleted projects past their 7 days whose queued purge was lost.
/// `/status` reports `oldest_deleted_project_unpurged_seconds`, which stays under 8 days while this or the jobs run.
async fn purge_projects() -> laravel::Result<()> {
let store = crate::storage::BlobStore::current().await?;
let outcome = crate::domain::project_deletion::sweep(Some(&store)).await;
match &outcome {
Ok(n) => tracing::info!(purged = n, "deleted projects swept"),
Err(e) => tracing::error!(error = %e, "sweeping deleted projects failed"),
}
outcome.map(|_| ())
}

/// [`crate::domain::processing::sweep`], with its heartbeat (`VISUALCI_BUILDS_EXPIRE_HEARTBEAT_URL` and `_TOKEN`).
Expand Down
2 changes: 1 addition & 1 deletion app/src/domain/credits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ pub async fn reloads_this_month(organization_id: i64) -> laravel::Result<i64> {
pub async fn open_source_projects(organization_id: i64) -> laravel::Result<i64> {
Ok(db::query!(
"SELECT COUNT(*) FROM projects WHERE organization_id = {organization_id} AND open_source AND public \
AND NOT open_source_withdrawn"
AND NOT open_source_withdrawn AND deleted_at IS NULL"
)
.scalar()
.await?
Expand Down
2 changes: 1 addition & 1 deletion app/src/domain/gallery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ pub async fn project_by_slugs(org: &str, project: &str) -> laravel::Result<Optio
let Some(organization) = Organization::query().filter(Organization::slug.eq(org)).first().await? else {
return Ok(None);
};
let found = Project::query()
let found = Project::live()
.filter(Project::organization_id.eq(organization.id) & Project::slug.eq(project))
.first()
.await?
Expand Down
1 change: 1 addition & 0 deletions app/src/domain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ pub mod lenient;
pub mod matching;
pub mod pages;
pub mod processing;
pub mod project_deletion;
pub mod projects;
pub mod renders;
pub mod reruns;
Expand Down
Loading
Loading