Skip to content

Commit ff8b80c

Browse files
committed
Delete a project: admins delete from Settings, hidden at once, purged after 7 days, staff restore before then
1 parent 5add582 commit ff8b80c

44 files changed

Lines changed: 1559 additions & 72 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
//! Deleting a project: `deleted_at` hides it at once (lists, URLs, tokens, uploads, webhooks), and the purge
2+
//! (`domain::project_deletion`) removes its rows and blob objects 7 days later. Until then staff can restore it.
3+
//!
4+
//! The slug is unique only among live projects (a partial index), so a new project, or a repository picked again,
5+
//! can take a deleted project's slug at once. Restoring refuses while a live project has it.
6+
7+
use laravel::db::AnyTransaction;
8+
9+
pub async fn migrate(tx: &mut AnyTransaction<'_>) -> laravel::Result<()> {
10+
tx.query(SCHEMA).unprepared().await?;
11+
Ok(())
12+
}
13+
14+
const SCHEMA: &str = r"
15+
ALTER TABLE projects ADD COLUMN deleted_at TIMESTAMPTZ;
16+
ALTER TABLE projects ADD COLUMN deleted_by BIGINT REFERENCES users(id) ON DELETE SET NULL;
17+
ALTER TABLE projects DROP CONSTRAINT projects_organization_id_slug_key;
18+
CREATE UNIQUE INDEX projects_organization_slug_live ON projects (organization_id, slug) WHERE deleted_at IS NULL;
19+
CREATE INDEX projects_deleted ON projects (deleted_at) WHERE deleted_at IS NOT NULL;
20+
CREATE INDEX projects_deleted_by ON projects (deleted_by) WHERE deleted_by IS NOT NULL;
21+
";

‎app/src/auth/memberships.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ async fn linked_projects(forge: ForgeKind) -> laravel::Result<Vec<LinkedProject>
4848
let rows = db::query!(
4949
"SELECT organization_id, repository_url, repository_id FROM projects \
5050
WHERE forge = {forge_name} AND repository_url IS NOT NULL AND repository_id IS NOT NULL \
51-
AND forge_installation IS NOT NULL"
51+
AND forge_installation IS NOT NULL AND deleted_at IS NULL"
5252
)
5353
.select()
5454
.await?;

‎app/src/auth/mod.rs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ use axum::http::request::Parts;
2626
use laravel::auth::Auth;
2727
use laravel::db;
2828

29-
use crate::models::{ProjectToken, User, UserToken, token_hash};
29+
use crate::models::{Project, ProjectToken, User, UserToken, token_hash};
3030

3131
/// What someone may do in a project's organization, lowest first.
3232
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
@@ -185,7 +185,7 @@ impl Principal {
185185
let user_id = user.id;
186186
db::query!(
187187
"SELECT p.id FROM projects p JOIN memberships m ON m.organization_id = p.organization_id \
188-
WHERE m.user_id = {user_id} ORDER BY p.id"
188+
WHERE m.user_id = {user_id} AND p.deleted_at IS NULL ORDER BY p.id"
189189
)
190190
.select_as::<i64>()
191191
.await
@@ -203,6 +203,10 @@ impl Principal {
203203
// doesn't write on every request
204204
if token.starts_with("vci_") {
205205
let Some(t) = ProjectToken::first_where(ProjectToken::token_hash.eq(&hash)).await? else { return Ok(None) };
206+
// A deleted project's tokens stop working at once (its rows stay until the purge, for a restore).
207+
if Project::find_live(t.project_id).await?.is_none() {
208+
return Ok(None);
209+
}
206210
let id = t.id;
207211
db::query!(
208212
"UPDATE project_tokens SET last_used_at = now() WHERE id = {id} \

‎app/src/auth/orgs.rs‎

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -134,23 +134,27 @@ fn build_summary(b: &Build) -> Value {
134134
})
135135
}
136136

137-
/// This month's credits per project, with how much came from the open source pool, for the Usage tab.
137+
/// This month's credits per project, with how much came from the open source pool, for the Usage tab. A deleted
138+
/// project stays listed (`deleted`) while it has credits this month: what it used still counts.
138139
async fn usage_by_project(org_id: i64) -> laravel::Result<Vec<Value>> {
139140
let since = crate::domain::credits::month_start();
140141
let rows = db::query!(
141142
"SELECT p.slug, p.name, (p.open_source AND p.public AND NOT p.open_source_withdrawn) AS open_source, \
143+
p.deleted_at IS NOT NULL AS deleted, \
142144
COALESCE(-SUM(t.amount), 0)::bigint AS credits, COALESCE(SUM(t.open_source_credits), 0)::bigint AS pool \
143145
FROM projects p LEFT JOIN credit_transactions t ON t.project_id = p.id AND t.created_at >= {since} \
144146
AND t.kind IN ('build', 'render', 'gallery') \
145-
WHERE p.organization_id = {org_id} GROUP BY p.id ORDER BY credits DESC, p.slug"
147+
WHERE p.organization_id = {org_id} GROUP BY p.id \
148+
HAVING p.deleted_at IS NULL OR COUNT(t.id) > 0 ORDER BY credits DESC, p.slug, p.id"
146149
)
147150
.select()
148151
.await?;
149152
rows.iter()
150153
.map(|r| {
151154
Ok(json!({
152155
"project": r.try_get::<String>("slug")?, "name": r.try_get::<String>("name")?,
153-
"open_source": r.try_get::<bool>("open_source")?, "credits": r.try_get::<i64>("credits")?,
156+
"open_source": r.try_get::<bool>("open_source")?, "deleted": r.try_get::<bool>("deleted")?,
157+
"credits": r.try_get::<i64>("credits")?,
154158
"open_source_credits": r.try_get::<i64>("pool")?,
155159
}))
156160
})
@@ -168,13 +172,14 @@ pub async fn show(
168172
let (org_id, _, role) = super::invitations::org_role(&user, &org).await?;
169173
let org = Organization::find_or_fail(org_id).await?;
170174
let admin = role == Role::Admin;
171-
let projects: Vec<(i64, String, String)> =
172-
db::query!("SELECT id, slug, name FROM projects WHERE organization_id = {org_id} ORDER BY slug")
173-
.select()
174-
.await?
175-
.iter()
176-
.map(|r| Ok((r.try_get("id")?, r.try_get("slug")?, r.try_get("name")?)))
177-
.collect::<laravel::Result<_>>()?;
175+
let projects: Vec<(i64, String, String)> = db::query!(
176+
"SELECT id, slug, name FROM projects WHERE organization_id = {org_id} AND deleted_at IS NULL ORDER BY slug"
177+
)
178+
.select()
179+
.await?
180+
.iter()
181+
.map(|r| Ok((r.try_get("id")?, r.try_get("slug")?, r.try_get("name")?)))
182+
.collect::<laravel::Result<_>>()?;
178183
let mut list = Vec::new();
179184
for (id, slug, name) in projects {
180185
let last = crate::domain::builds::recent(id, None, false, 1).await?;

‎app/src/auth/tokens.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ async fn admin_project(user: &User, org: &str, project: &str, action: &str) -> l
115115
let row = db::query!(
116116
"SELECT p.id, p.organization_id, p.slug, m.role FROM projects p JOIN organizations o ON o.id = p.organization_id \
117117
LEFT JOIN memberships m ON m.organization_id = o.id AND m.user_id = {user_id} \
118-
WHERE o.slug = {org} AND p.slug = {project}"
118+
WHERE o.slug = {org} AND p.slug = {project} AND p.deleted_at IS NULL"
119119
)
120120
.select_one()
121121
.await?

‎app/src/console/mod.rs‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! The schedule (`laravel schedule:run` every minute, in production a CronJob): the builds sweep every five minutes;
2-
//! retention, the groups check, the demo reset and the credit override reminders daily. Each run pushes its result to
3-
//! a heartbeat, so a task that failed or stopped running alerts.
2+
//! retention, the groups check, the demo reset, the credit override reminders and the deleted projects' purge daily.
3+
//! Each run pushes its result to a heartbeat, so a task that failed or stopped running alerts; the purge is watched
4+
//! through `/status` instead (`oldest_deleted_project_unpurged_seconds`).
45
56
use laravel::schedule::{self, Schedule};
67

@@ -18,6 +19,19 @@ fn schedule(schedule: &mut Schedule) {
1819
schedule.command("groups:check").daily_at("04:00").without_overlapping().on_one_runner();
1920
schedule.command("demo:reset").name("demo-reset").daily_at("05:00").without_overlapping().on_one_runner();
2021
schedule.command("credits:override-reminders").daily_at("06:00").without_overlapping().on_one_runner();
22+
schedule.call(purge_projects).name("projects-purge").daily_at("02:00").without_overlapping().on_one_runner();
23+
}
24+
25+
/// [`crate::domain::project_deletion::sweep`]: deleted projects past their 7 days whose queued purge was lost.
26+
/// `/status` reports `oldest_deleted_project_unpurged_seconds`, which stays under 8 days while this or the jobs run.
27+
async fn purge_projects() -> laravel::Result<()> {
28+
let store = crate::storage::BlobStore::current().await?;
29+
let outcome = crate::domain::project_deletion::sweep(Some(&store)).await;
30+
match &outcome {
31+
Ok(n) => tracing::info!(purged = n, "deleted projects swept"),
32+
Err(e) => tracing::error!(error = %e, "sweeping deleted projects failed"),
33+
}
34+
outcome.map(|_| ())
2135
}
2236

2337
/// [`crate::domain::processing::sweep`], with its heartbeat (`VISUALCI_BUILDS_EXPIRE_HEARTBEAT_URL` and `_TOKEN`).

‎app/src/domain/credits.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ pub async fn reloads_this_month(organization_id: i64) -> laravel::Result<i64> {
387387
pub async fn open_source_projects(organization_id: i64) -> laravel::Result<i64> {
388388
Ok(db::query!(
389389
"SELECT COUNT(*) FROM projects WHERE organization_id = {organization_id} AND open_source AND public \
390-
AND NOT open_source_withdrawn"
390+
AND NOT open_source_withdrawn AND deleted_at IS NULL"
391391
)
392392
.scalar()
393393
.await?

‎app/src/domain/gallery.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -300,7 +300,7 @@ pub async fn project_by_slugs(org: &str, project: &str) -> laravel::Result<Optio
300300
let Some(organization) = Organization::query().filter(Organization::slug.eq(org)).first().await? else {
301301
return Ok(None);
302302
};
303-
let found = Project::query()
303+
let found = Project::live()
304304
.filter(Project::organization_id.eq(organization.id) & Project::slug.eq(project))
305305
.first()
306306
.await?

‎app/src/domain/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ pub mod lenient;
2323
pub mod matching;
2424
pub mod pages;
2525
pub mod processing;
26+
pub mod project_deletion;
2627
pub mod projects;
2728
pub mod renders;
2829
pub mod reruns;

0 commit comments

Comments
 (0)