fix(orgs): delete organizations at once and purge their check data later
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 6m28s
ci / test (pull_request) Successful in 12m39s
ci / build (pull_request) Successful in 16m10s
ci / image (pull_request) Successful in 5m20s
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 6m28s
ci / test (pull_request) Successful in 12m39s
ci / build (pull_request) Successful in 16m10s
ci / image (pull_request) Successful in 5m20s
Deleting an organization removed its check results and aggregates in the same transaction as the request. With gigabytes of results that took longer than the request may last, it was cut off and rolled back, so a large organization could not be deleted at all. The organization and everything with a foreign key on it now go in the request; its check data is queued in org_purges. Every API instance purges the queue a chunk at a time, each chunk in a transaction of its own, right after a deletion and every minute. Raw results go first, so the aggregates' refresh does not rebuild what was purged. A lease lets another instance take over a purge whose instance stopped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
9d01b62b98
commit
8ff4a86371
13 files changed
+393
-45
No files matched your search
+4
-13
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
+17
-14
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user