Files
sorsfonalak/services/worker/src/cleanup.rs
T
fecoandClaude Opus 5.5 2c63384606
CI / build (push) Skipped
CI / deploy (push) Skipped
CI / test (push) Successful in 4m27s
Admin tools for Claude: an MCP server, connected with an admin's approval
- services/mcp: the MCP server at /mcp (Streamable HTTP, stateless): the
  admin's reading tools, the daily tasks and the forum's moderation; every
  tool calls the site's API with the caller's token, and members' e-mail
  addresses and names are masked in the answers.
- Backend: OAuth 2.1 for MCP clients (registration with Claude's or a local
  return address only, PKCE, rotating refresh tokens, revocation); the admin
  guards accept the token for reading and the writes in MCP_WRITES only.
- Forum: an admin's token reaches the moderator endpoints only.
- Frontend: the approval page (/oauth/engedely), Admin → Claude to revoke a
  connection, the authorization server's metadata at its standard address.
- Deploy: the mcp service in compose, Caddy, CI; the worker removes old
  codes, tokens and clients. docs/mcp.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-27 17:09:14 +00:00

105 lines
4.6 KiB
Rust

//! Hourly removal of data that is no longer needed.
use std::time::Duration;
use sqlx::PgPool;
use tokio::sync::watch;
const INTERVAL: Duration = Duration::from_secs(3600);
/// (what, statement) pairs; each returns the number of deleted rows.
const STATEMENTS: [(&str, &str); 20] = [
("sessions", "DELETE FROM sessions WHERE expires_at < now()"),
("auth_tokens", "DELETE FROM auth_tokens WHERE expires_at < now()"),
// Sent e-mails contain links with tokens; keep them a week for support.
(
"emails",
"DELETE FROM email_outbox WHERE sent_at < now() - interval '7 days' \
OR failed_at < now() - interval '30 days'",
),
("invites", "DELETE FROM synastry_invites WHERE accepted_at IS NULL AND expires_at < now() - interval '30 days'"),
// Unused invitations 30 days after they closed; accepted ones once the account is deleted.
(
"invitations",
"DELETE FROM invitations WHERE (accepted_at IS NULL \
AND least(coalesce(revoked_at, expires_at), expires_at) < now() - interval '30 days') \
OR (accepted_at IS NOT NULL AND accepted_by IS NULL)",
),
("prompt_previews", "DELETE FROM prompt_previews WHERE created_at < now() - interval '30 days'"),
("generation_errors", "DELETE FROM generation_errors WHERE created_at < now() - interval '90 days'"),
// Gifts never paid (Stripe's payment page is long closed by then), with
// the recipient's address in them.
("gifts", "DELETE FROM gifts WHERE paid_at IS NULL AND created_at < now() - interval '7 days'"),
// The forum (the privacy policy's retention periods): what moderators
// removed is kept a year for objections, then only its place and reason stay.
(
"forum_removed_posts",
"UPDATE forum.posts SET body = '' WHERE deleted_at < now() - interval '1 year' AND body <> ''",
),
(
"forum_removed_threads",
"UPDATE forum.posts p SET body = '' FROM forum.threads th \
WHERE th.id = p.thread_id AND th.deleted_at < now() - interval '1 year' AND p.body <> ''",
),
(
"forum_removed_titles",
"UPDATE forum.threads SET title = 'Eltávolított szál' \
WHERE deleted_at < now() - interval '1 year' AND title <> 'Eltávolított szál'",
),
("forum_nicknames", "DELETE FROM forum.retired_nicknames WHERE until < now()"),
("forum_reports", "DELETE FROM forum.reports WHERE status <> 'open' AND handled_at < now() - interval '1 year'"),
("forum_mod_log", "DELETE FROM forum.mod_log WHERE created_at < now() - interval '2 years'"),
(
"forum_bans",
"UPDATE forum.members SET banned_until = NULL, ban_reason = NULL WHERE banned_until < now() - interval '1 year'",
),
// Requests never accepted (declined or expired), with their introduction;
// a block stays as long as the blocker keeps it.
(
"forum_requests",
"DELETE FROM forum.conversations WHERE status IN ('pending', 'declined') AND last_message_at IS NULL \
AND coalesce(responded_at, created_at) < now() - interval '90 days'",
),
// MCP clients (docs/mcp.md): codes and tokens past their time, connections
// revoked a month ago or with no token left, and clients a month without
// a connection (a client registered but never approved, or long revoked).
("oauth_codes", "DELETE FROM oauth_codes WHERE expires_at < now() - interval '1 day'"),
("oauth_tokens", "DELETE FROM oauth_tokens WHERE refresh_expires_at < now()"),
(
"oauth_grants",
"DELETE FROM oauth_grants g WHERE g.revoked_at < now() - interval '30 days' \
OR NOT EXISTS (SELECT 1 FROM oauth_tokens t WHERE t.grant_id = g.id)",
),
(
"oauth_clients",
"DELETE FROM oauth_clients c WHERE c.created_at < now() - interval '30 days' \
AND NOT EXISTS (SELECT 1 FROM oauth_grants g WHERE g.client_id = c.id)",
),
];
pub async fn run_once(db: &PgPool) -> Result<Vec<(&'static str, u64)>, sqlx::Error> {
let mut deleted = Vec::new();
for (what, sql) in STATEMENTS {
deleted.push((what, sqlx::query(sql).execute(db).await?.rows_affected()));
}
Ok(deleted)
}
pub async fn run(db: PgPool, stop: watch::Receiver<bool>) {
loop {
match run_once(&db).await {
Ok(deleted) => {
let total: u64 = deleted.iter().map(|(_, n)| n).sum();
if total > 0 {
tracing::info!(?deleted, "cleanup");
}
}
Err(e) => tracing::error!(error = %e, "cleanup"),
}
tokio::select! {
() = tokio::time::sleep(INTERVAL) => {}
() = crate::stopped(stop.clone()) => break,
}
}
}