diff --git a/internal/api/gdpr.go b/internal/api/gdpr.go index d1425c3..3bd4bf3 100644 --- a/internal/api/gdpr.go +++ b/internal/api/gdpr.go @@ -651,19 +651,6 @@ func (s *Server) loadUser(ctx context.Context, id uuid.UUID) (store.User, error) return u, err } -// purgeOrg deletes an organization with everything in it, including check -// results and status page server storage, which have no foreign key. -func purgeOrg(ctx context.Context, q *store.Queries, org uuid.UUID) error { - if err := q.PurgeOrgCheckData(ctx, org); err != nil { - return err - } - if err := q.DeleteOrgStorage(ctx, org); err != nil { - return err - } - _, err := q.DeleteOrg(ctx, org) - return err -} - // deleteAccount erases the signed-in user (Art. 17). Organizations the // user is the last owner of go with the account, monitors and all, even // when they have other members: nobody would be left to run them. The user @@ -744,6 +731,9 @@ func (s *Server) eraseAccount(ctx context.Context, u store.User) (orgsDeleted in if err != nil { return 0, err } + if orgsDeleted > 0 { + s.wakeOrgPurges() + } if err := s.sessions.DeleteAllForUser(ctx, u.ID); err != nil { s.log.ErrorContext(ctx, "ending sessions of deleted account failed", "error", err) } @@ -790,6 +780,7 @@ func (s *Server) deleteOrg(c *gin.Context) { internalError(c, err) return } + s.wakeOrgPurges() if sess := auth.Current(c); sess != nil { _ = s.sessions.SwitchOrg(ctx, sess, uuid.Nil) } diff --git a/internal/api/gdpr_test.go b/internal/api/gdpr_test.go index 6530b94..73eda26 100644 --- a/internal/api/gdpr_test.go +++ b/internal/api/gdpr_test.go @@ -176,6 +176,12 @@ func TestDeleteOrganization(t *testing.T) { }) keepOrg := uuid.MustParse(keep.orgID()) e.seedResults(t, keepOrg, uuid.MustParse(km["id"].(string))) + // Results older than a week are compressed; the purge goes through them + // as well. + if _, err := e.dbPool.Exec(context.Background(), + `SELECT compress_chunk(c, if_not_compressed => true) FROM show_chunks('check_results', older_than => now() - interval '1 day') c`); err != nil { + t.Fatalf("compressing chunks: %v", err) + } admin := e.joinVia(t, owner.invite("a@"+uniq("d")+".test", owner.roleID("admin"))) if st, body := admin.do("POST", "/api/v1/org/delete", map[string]any{"slug": slug, "password": password}); st != http.StatusForbidden { @@ -191,17 +197,33 @@ func TestDeleteOrganization(t *testing.T) { t.Fatalf("owner deletes org = %d %v", st, body) } + // The organization is gone at once, its check data is purged in the + // background, chunk by chunk. for query, want := range map[string]int{ - `SELECT count(*) FROM orgs WHERE id = $1`: 0, - `SELECT count(*) FROM monitors WHERE org_id = $1`: 0, - `SELECT count(*) FROM check_results WHERE org_id = $1`: 0, - `SELECT count(*) FROM check_results_1h WHERE org_id = $1`: 0, - `SELECT count(*) FROM audit_events WHERE org_id = $1`: 0, + `SELECT count(*) FROM orgs WHERE id = $1`: 0, + `SELECT count(*) FROM monitors WHERE org_id = $1`: 0, + `SELECT count(*) FROM org_purges WHERE org_id = $1`: 1, } { if got := e.count(t, query, org); got != want { t.Errorf("%s = %d, want %d", query, got, want) } } + if err := e.api.PurgeDeletedOrgs(context.Background()); err != nil { + t.Fatalf("PurgeDeletedOrgs() = %v", err) + } + for query, want := range map[string]int{ + `SELECT count(*) FROM check_results WHERE org_id = $1`: 0, + `SELECT count(*) FROM check_results_1h WHERE org_id = $1`: 0, + `SELECT count(*) FROM audit_events WHERE org_id = $1`: 0, + `SELECT count(*) FROM org_purges WHERE org_id = $1`: 0, + } { + if got := e.count(t, query, org); got != want { + t.Errorf("%s = %d, want %d", query, got, want) + } + } + if e.count(t, `SELECT count(*) FROM check_results WHERE org_id = $1`, keepOrg) != 30 { + t.Error("another organization's results were deleted") + } if e.count(t, `SELECT count(*) FROM check_results_1h WHERE org_id = $1`, keepOrg) == 0 { t.Error("another organization's aggregates were deleted") } diff --git a/internal/api/housekeeping.go b/internal/api/housekeeping.go index 336716f..2267699 100644 --- a/internal/api/housekeeping.go +++ b/internal/api/housekeeping.go @@ -29,6 +29,7 @@ func (s *Server) RunHousekeeping(ctx context.Context) { // policies as owner. s.log.WarnContext(ctx, "applying retention policies failed", "error", err) } + go s.runOrgPurges(ctx) tick := time.NewTicker(time.Hour) defer tick.Stop() for { diff --git a/internal/api/moderation.go b/internal/api/moderation.go index 7c8686b..de37113 100644 --- a/internal/api/moderation.go +++ b/internal/api/moderation.go @@ -205,6 +205,7 @@ func (s *Server) adminDeleteOrg(c *gin.Context) { return purgeOrg(ctx, q, id) }) if moderated(c, err) { + s.wakeOrgPurges() c.Status(http.StatusNoContent) } } diff --git a/internal/api/orgpurge.go b/internal/api/orgpurge.go new file mode 100644 index 0000000..783449c --- /dev/null +++ b/internal/api/orgpurge.go @@ -0,0 +1,119 @@ +package api + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +// orgPurgeEvery is how often an instance looks for deleted organizations +// whose check data is left, besides right after a deletion. +const orgPurgeEvery = time.Minute + +// purgeOrg deletes an organization with everything in it at once, except +// its check results and aggregates: they carry no foreign key and can run +// to gigabytes, more than a request can delete in time, so it queues them +// for PurgeDeletedOrgs. Nothing shows them once the organization is gone. +func purgeOrg(ctx context.Context, q *store.Queries, org uuid.UUID) error { + if err := q.QueueOrgPurge(ctx, org); err != nil { + return err + } + if err := q.DeleteOrgStorage(ctx, org); err != nil { + return err + } + _, err := q.DeleteOrg(ctx, org) + return err +} + +// wakeOrgPurges has PurgeDeletedOrgs run soon after a deletion instead of +// at the next tick. +func (s *Server) wakeOrgPurges() { + select { + case s.orgPurges <- struct{}{}: + default: + } +} + +// runOrgPurges purges the check data of deleted organizations every +// orgPurgeEvery and when woken, until ctx ends. +func (s *Server) runOrgPurges(ctx context.Context) { + tick := time.NewTicker(orgPurgeEvery) + defer tick.Stop() + for { + if err := s.PurgeDeletedOrgs(ctx); err != nil && ctx.Err() == nil { + s.log.ErrorContext(ctx, "purging deleted organizations failed", "error", err) + } + select { + case <-ctx.Done(): + return + case <-tick.C: + case <-s.orgPurges: + } + } +} + +// PurgeDeletedOrgs deletes the check data of deleted organizations a chunk +// at a time, each in a transaction of its own, until none is left. An +// instance leases an organization while it purges it; if it stops, another +// takes over once the lease runs out and repeats the chunks, which then +// delete nothing. +func (s *Server) PurgeDeletedOrgs(ctx context.Context) error { + for ctx.Err() == nil { + var org uuid.UUID + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + var err error + org, err = q.ClaimOrgPurge(ctx) + return err + }) + if errors.Is(err, pgx.ErrNoRows) { + return nil + } + if err != nil { + return err + } + if err := s.purgeOrgCheckData(ctx, org); err != nil { + return err + } + } + return ctx.Err() +} + +func (s *Server) purgeOrgCheckData(ctx context.Context, org uuid.UUID) error { + start := time.Now() + var chunks []string + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + var err error + chunks, err = q.OrgCheckDataChunks(ctx) + return err + }) + if err != nil { + return err + } + var rows int64 + for _, chunk := range chunks { + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + n, err := q.PurgeOrgCheckChunk(ctx, store.PurgeOrgCheckChunkParams{OrgID: org, Chunk: chunk}) + if err != nil { + return err + } + rows += n + return q.ExtendOrgPurge(ctx, org) + }) + if err != nil { + return err + } + } + err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { return q.FinishOrgPurge(ctx, org) }) + if err != nil { + return err + } + s.log.InfoContext(ctx, "purged check data of deleted organization", + "org", org, "rows", rows, "chunks", len(chunks), "duration", time.Since(start).Round(time.Millisecond)) + return nil +} diff --git a/internal/api/server.go b/internal/api/server.go index 2d043a7..0f5483f 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -31,20 +31,22 @@ const localeCookie = "lang" // Server holds the dependencies shared by all handlers. type Server struct { - cfg config.API - log *slog.Logger - db *tenant.DB - rdb redis.UniversalClient - keys *sealed.Keyring - catalog *i18n.Catalog - sessions *auth.Sessions - limiter *auth.Limiter - totp *auth.TOTPVerifier - sso *sso.Client - sched *schedule.Scheduler - eval *evaluate.Evaluator - smtp *notify.SMTP - legal *versioned[[]agentapi.LegalDoc] + // orgPurges wakes runOrgPurges after an organization was deleted. + orgPurges chan struct{} + cfg config.API + log *slog.Logger + db *tenant.DB + rdb redis.UniversalClient + keys *sealed.Keyring + catalog *i18n.Catalog + sessions *auth.Sessions + limiter *auth.Limiter + totp *auth.TOTPVerifier + sso *sso.Client + sched *schedule.Scheduler + eval *evaluate.Evaluator + smtp *notify.SMTP + legal *versioned[[]agentapi.LegalDoc] // consent caches the versions of the documents accounts accept. consent *versioned[map[string]int64] // checkTypes caches the check types switched off platform-wide. @@ -82,6 +84,7 @@ func New(cfg config.API, d Deps) *Server { allowPrivate := cfg.SSOAllowPrivate() mail, _ := notify.ParseSMTP(cfg.SMTPURL) return &Server{ + orgPurges: make(chan struct{}, 1), eval: evaluate.New(d.Redis), smtp: mail, cfg: cfg, diff --git a/internal/migrations/sql/00057_org_purges.sql b/internal/migrations/sql/00057_org_purges.sql new file mode 100644 index 0000000..7e6d2f6 --- /dev/null +++ b/internal/migrations/sql/00057_org_purges.sql @@ -0,0 +1,72 @@ +-- +goose Up +-- Deleting an organization removes it at once but leaves its check results +-- and aggregates, which carry no foreign key, to the background: years of +-- results take far longer to delete than a request may last. The purge +-- goes a chunk at a time, each in a transaction of its own, so it never +-- holds locks for long and resumes where it stopped. +CREATE TABLE org_purges ( + org_id uuid PRIMARY KEY, + requested_at timestamptz NOT NULL DEFAULT now(), + -- An API instance purging the organization holds it until then. + leased_until timestamptz NOT NULL DEFAULT '-infinity' +); + +ALTER TABLE org_purges ENABLE ROW LEVEL SECURITY; +ALTER TABLE org_purges FORCE ROW LEVEL SECURITY; +CREATE POLICY org_purges_system ON org_purges FOR ALL + USING (app_scope_system()) WITH CHECK (app_scope_system()); + +-- +goose StatementBegin +-- The chunks holding check data: those of the raw results first, so the +-- aggregates' refresh does not materialize again what was purged from them, +-- then those of both aggregates, oldest first. Runs with the owner's rights because the application role +-- may not reach TimescaleDB's internal schema. +CREATE FUNCTION org_check_data_chunks() RETURNS SETOF text +LANGUAGE sql STABLE SECURITY DEFINER SET search_path = public, pg_temp AS $$ + SELECT format('%I.%I', c.chunk_schema, c.chunk_name) + FROM timescaledb_information.chunks c + WHERE (c.hypertable_schema, c.hypertable_name) IN ( + SELECT 'public'::name, 'check_results'::name + UNION ALL + SELECT materialization_hypertable_schema, materialization_hypertable_name + FROM timescaledb_information.continuous_aggregates + WHERE view_name IN ('check_results_1h', 'check_results_1d')) + ORDER BY c.hypertable_name <> 'check_results', c.range_start, 1 +$$; +-- +goose StatementEnd + +-- +goose StatementBegin +-- Deletes an organization's rows in one chunk of org_check_data_chunks, +-- through its hypertable and limited to the chunk's time range, so that +-- TimescaleDB handles compressed chunks. Chunks dropped meanwhile, and +-- names of anything else, delete nothing. +CREATE FUNCTION purge_org_check_chunk(org uuid, chunk text) RETURNS bigint +LANGUAGE plpgsql SECURITY DEFINER SET search_path = public, pg_temp AS $$ +DECLARE + r record; + n bigint; +BEGIN + SELECT c.hypertable_schema AS hs, c.hypertable_name AS hn, d.column_name AS col, + c.range_start AS lo, c.range_end AS hi + INTO r + FROM timescaledb_information.chunks c + JOIN timescaledb_information.dimensions d + ON d.hypertable_schema = c.hypertable_schema AND d.hypertable_name = c.hypertable_name + AND d.dimension_number = 1 + WHERE format('%I.%I', c.chunk_schema, c.chunk_name) = chunk + AND chunk IN (SELECT org_check_data_chunks()); + IF NOT FOUND THEN + RETURN 0; + END IF; + EXECUTE format('DELETE FROM %I.%I WHERE org_id = $1 AND %I >= $2 AND %I < $3', r.hs, r.hn, r.col, r.col) + USING org, r.lo, r.hi; + GET DIAGNOSTICS n = ROW_COUNT; + RETURN n; +END +$$; +-- +goose StatementEnd + +-- +goose Down +DROP FUNCTION purge_org_check_chunk(uuid, text); +DROP FUNCTION org_check_data_chunks(); +DROP TABLE org_purges; diff --git a/internal/store/gdpr.sql.go b/internal/store/gdpr.sql.go index 6eaaa5a..e235a5f 100644 --- a/internal/store/gdpr.sql.go +++ b/internal/store/gdpr.sql.go @@ -345,15 +345,6 @@ func (q *Queries) OwnedOrgs(ctx context.Context, userID uuid.UUID) ([]OwnedOrgsR return items, nil } -const purgeOrgCheckData = `-- name: PurgeOrgCheckData :exec -SELECT purge_org_check_data($1) -` - -func (q *Queries) PurgeOrgCheckData(ctx context.Context, org uuid.UUID) error { - _, err := q.db.Exec(ctx, purgeOrgCheckData, org) - return err -} - const scrubAuditEmail = `-- name: ScrubAuditEmail :exec UPDATE audit_events SET details = details - 'email' WHERE lower(details->>'email') = lower($1::text) ` diff --git a/internal/store/models.go b/internal/store/models.go index ceb653d..b1bb974 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -337,6 +337,12 @@ type Org struct { LimitSubscribersPerWeek *int32 } +type OrgPurge struct { + OrgID uuid.UUID + RequestedAt time.Time + LeasedUntil time.Time +} + type PlatformIdentity struct { ProviderID uuid.UUID Subject string diff --git a/internal/store/org_purges.sql.go b/internal/store/org_purges.sql.go new file mode 100644 index 0000000..02c692d --- /dev/null +++ b/internal/store/org_purges.sql.go @@ -0,0 +1,109 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: org_purges.sql + +package store + +import ( + "context" + + "github.com/google/uuid" +) + +const claimOrgPurge = `-- name: ClaimOrgPurge :one +UPDATE org_purges SET leased_until = now() + interval '15 minutes' +WHERE org_id = ( + SELECT org_id FROM org_purges WHERE leased_until < now() + ORDER BY requested_at LIMIT 1 + FOR UPDATE SKIP LOCKED +) +RETURNING org_id +` + +// System scope: leases the longest waiting purge no other instance holds. +func (q *Queries) ClaimOrgPurge(ctx context.Context) (uuid.UUID, error) { + row := q.db.QueryRow(ctx, claimOrgPurge) + var org_id uuid.UUID + err := row.Scan(&org_id) + return org_id, err +} + +const countOrgPurges = `-- name: CountOrgPurges :one +SELECT count(*) FROM org_purges +` + +func (q *Queries) CountOrgPurges(ctx context.Context) (int64, error) { + row := q.db.QueryRow(ctx, countOrgPurges) + var count int64 + err := row.Scan(&count) + return count, err +} + +const extendOrgPurge = `-- name: ExtendOrgPurge :exec +UPDATE org_purges SET leased_until = now() + interval '15 minutes' WHERE org_id = $1 +` + +func (q *Queries) ExtendOrgPurge(ctx context.Context, orgID uuid.UUID) error { + _, err := q.db.Exec(ctx, extendOrgPurge, orgID) + return err +} + +const finishOrgPurge = `-- name: FinishOrgPurge :exec +DELETE FROM org_purges WHERE org_id = $1 +` + +func (q *Queries) FinishOrgPurge(ctx context.Context, orgID uuid.UUID) error { + _, err := q.db.Exec(ctx, finishOrgPurge, orgID) + return err +} + +const orgCheckDataChunks = `-- name: OrgCheckDataChunks :many +SELECT chunk::text FROM org_check_data_chunks() AS chunk +` + +func (q *Queries) OrgCheckDataChunks(ctx context.Context) ([]string, error) { + rows, err := q.db.Query(ctx, orgCheckDataChunks) + if err != nil { + return nil, err + } + defer rows.Close() + items := []string{} + for rows.Next() { + var chunk string + if err := rows.Scan(&chunk); err != nil { + return nil, err + } + items = append(items, chunk) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const purgeOrgCheckChunk = `-- name: PurgeOrgCheckChunk :one +SELECT purge_org_check_chunk($1::uuid, $2::text)::bigint AS rows +` + +type PurgeOrgCheckChunkParams struct { + OrgID uuid.UUID + Chunk string +} + +func (q *Queries) PurgeOrgCheckChunk(ctx context.Context, arg PurgeOrgCheckChunkParams) (int64, error) { + row := q.db.QueryRow(ctx, purgeOrgCheckChunk, arg.OrgID, arg.Chunk) + var rows int64 + err := row.Scan(&rows) + return rows, err +} + +const queueOrgPurge = `-- name: QueueOrgPurge :exec +INSERT INTO org_purges (org_id) VALUES ($1) ON CONFLICT DO NOTHING +` + +// System scope: has the check data of a deleted organization purged. +func (q *Queries) QueueOrgPurge(ctx context.Context, orgID uuid.UUID) error { + _, err := q.db.Exec(ctx, queueOrgPurge, orgID) + return err +} diff --git a/internal/store/querier.go b/internal/store/querier.go index beec538..1b61fe3 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -46,6 +46,8 @@ type Querier interface { // System scope. Leases due rows for five minutes so a crashed sender's rows // come back; SKIP LOCKED lets every API replica work the outbox. ClaimNotifications(ctx context.Context, max int32) ([]uuid.UUID, error) + // System scope: leases the longest waiting purge no other instance holds. + ClaimOrgPurge(ctx context.Context) (uuid.UUID, error) // System scope; leased like ClaimNotifications. ClaimSubscriberNotifications(ctx context.Context, max int32) ([]uuid.UUID, error) // Shortens tokens that would outlive a newly set maximum lifetime. @@ -56,6 +58,7 @@ type Querier interface { ConfirmPageSubscriber(ctx context.Context, id uuid.UUID) error CountMonitors(ctx context.Context, orgID uuid.UUID) (int64, error) CountOpenSupportTickets(ctx context.Context, userID uuid.UUID) (int64, error) + CountOrgPurges(ctx context.Context) (int64, error) CountOwnedOrgs(ctx context.Context, userID uuid.UUID) (int64, error) CountOwners(ctx context.Context, orgID uuid.UUID) (int64, error) CountPageSubscribers(ctx context.Context, pageID uuid.UUID) (CountPageSubscribersRow, error) @@ -147,9 +150,11 @@ type Querier interface { EnsurePlatformRegion(ctx context.Context, arg EnsurePlatformRegionParams) (Region, error) // Evidence of a monitor in a time span, to link results to it. EvidenceBetween(ctx context.Context, arg EvidenceBetweenParams) ([]EvidenceBetweenRow, error) + ExtendOrgPurge(ctx context.Context, orgID uuid.UUID) error // System scope: resolves a request to a page by verified custom domain or // by slug. FindPublishedPage(ctx context.Context, arg FindPublishedPageParams) (StatusPage, error) + FinishOrgPurge(ctx context.Context, orgID uuid.UUID) error // Alerts of org that fire and were repeated within the stale period. FiringAlerts(ctx context.Context, arg FiringAlertsParams) ([]FiringAlertsRow, error) // FiringAlerts newest first, a page from a keyset cursor (see paging.go) @@ -323,6 +328,7 @@ type Querier interface { OpenIncidents(ctx context.Context, orgID uuid.UUID) ([]Incident, error) OrgAssignmentsExport(ctx context.Context, orgID uuid.UUID) ([]OrgAssignmentsExportRow, error) OrgAuditExport(ctx context.Context, orgID uuid.UUID) ([]OrgAuditExportRow, error) + OrgCheckDataChunks(ctx context.Context) ([]string, error) OrgDailyStats(ctx context.Context, orgID uuid.UUID) ([]OrgDailyStatsRow, error) OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) OrgIncidentUpdatesExport(ctx context.Context, orgID uuid.UUID) ([]OrgIncidentUpdatesExportRow, error) @@ -347,13 +353,15 @@ type Querier interface { PurgeInvitations(ctx context.Context, expiresAt time.Time) (int64, error) // Delivered and given-up notifications; pending ones are still being worked. PurgeNotifications(ctx context.Context, createdAt time.Time) (int64, error) - PurgeOrgCheckData(ctx context.Context, org uuid.UUID) error + PurgeOrgCheckChunk(ctx context.Context, arg PurgeOrgCheckChunkParams) (int64, error) PurgeSubscriberNotifications(ctx context.Context, createdAt time.Time) (int64, error) // Unconfirmed subscriptions are kept for as long as they count towards the // weekly limit, so letting them lapse frees no room for more. PurgeUnconfirmedSubscribers(ctx context.Context, createdAt time.Time) (int64, error) // Accounts never confirmed; they belong to no organization. PurgeUnverifiedUsers(ctx context.Context, createdAt time.Time) (int64, error) + // System scope: has the check data of a deleted organization purged. + QueueOrgPurge(ctx context.Context, orgID uuid.UUID) error // Raw results bucketed by width since a point in time, for short ranges. RangeBuckets(ctx context.Context, arg RangeBucketsParams) ([]RangeBucketsRow, error) // The daily aggregate rebucketed by width, for ranges of months. diff --git a/internal/store/queries/gdpr.sql b/internal/store/queries/gdpr.sql index 8e476f5..0fe1900 100644 --- a/internal/store/queries/gdpr.sql +++ b/internal/store/queries/gdpr.sql @@ -49,9 +49,6 @@ UPDATE audit_events SET details = details - 'email' WHERE lower(details->>'email -- name: DeleteInvitationsForEmail :exec DELETE FROM invitations WHERE email = $1; --- name: PurgeOrgCheckData :exec -SELECT purge_org_check_data($1); - -- name: DeleteOrgStorage :exec DELETE FROM agent_storage WHERE owner = 'org:' || sqlc.arg(org_id)::uuid::text; diff --git a/internal/store/queries/org_purges.sql b/internal/store/queries/org_purges.sql new file mode 100644 index 0000000..dd77496 --- /dev/null +++ b/internal/store/queries/org_purges.sql @@ -0,0 +1,28 @@ +-- name: QueueOrgPurge :exec +-- System scope: has the check data of a deleted organization purged. +INSERT INTO org_purges (org_id) VALUES ($1) ON CONFLICT DO NOTHING; + +-- name: ClaimOrgPurge :one +-- System scope: leases the longest waiting purge no other instance holds. +UPDATE org_purges SET leased_until = now() + interval '15 minutes' +WHERE org_id = ( + SELECT org_id FROM org_purges WHERE leased_until < now() + ORDER BY requested_at LIMIT 1 + FOR UPDATE SKIP LOCKED +) +RETURNING org_id; + +-- name: ExtendOrgPurge :exec +UPDATE org_purges SET leased_until = now() + interval '15 minutes' WHERE org_id = $1; + +-- name: FinishOrgPurge :exec +DELETE FROM org_purges WHERE org_id = $1; + +-- name: CountOrgPurges :one +SELECT count(*) FROM org_purges; + +-- name: OrgCheckDataChunks :many +SELECT chunk::text FROM org_check_data_chunks() AS chunk; + +-- name: PurgeOrgCheckChunk :one +SELECT purge_org_check_chunk(sqlc.arg(org_id)::uuid, sqlc.arg(chunk)::text)::bigint AS rows;