Path: redb/redb.Core/Services/BackgroundDeletionService.cs Snapshot: redb, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Services/BackgroundDeletionService.cs ---- using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using redb.Core.Models.Contracts; namespace redb.Core.Services; /// /// Background deletion service backed by DB polling. /// /// Earlier revisions used an in-memory Channel<PurgeTask> for low-latency /// wake-up plus a startup-only RecoverOrphanedTasksAsync sweep for crash /// recovery. That created a dual-state problem: state of truth split between the /// channel (in memory, lost on kill) and the DB (durable). Worker force-kills always /// left a tail of orphaned 'pending' rows that the next startup had to drain in a /// flood of single-item purges. The "fix" of a periodic sweeper would have raced /// against the live channel reader unless we added age filters to the SQL. /// /// /// This revision drops the channel entirely. The DB IS the queue. /// polls on a fixed /// interval, atomically claims each pending row via /// (cluster-safe), and /// purges each container with the existing batched . /// Force-kill leaves nothing in memory because nothing was in memory — the next poll /// cycle (or next startup) just claims whatever's still 'pending'. /// /// /// Trade-off: cleanup latency shifts from "milliseconds via channel" to "≤ poll /// interval", but cleanup is invisible to API consumers anyway (the object is /// re-parented under the trash scheme by SoftDeleteAsync synchronously, so /// it disappears from queries immediately — only the physical purge of the /// _values cascade is deferred). /// /// public class BackgroundDeletionService : BackgroundService, IBackgroundDeletionService { private readonly IServiceProvider _serviceProvider; private readonly ILogger? _logger; /// /// Minutes after which a 'running' task is considered orphaned and re-claimed. /// Conservative — covers the case where another live instance is still working it. /// private const int OrphanTimeoutMinutes = 30; /// Default batch size for trash-container purges. private const int DefaultBatchSize = 10; /// How often the polling loop scans the DB for pending purge work. private static readonly TimeSpan PollInterval = TimeSpan.FromSeconds(5); /// Maximum number of trash containers claimed per poll cycle. private const int PollPageSize = 50; /// /// Creates a new BackgroundDeletionService. /// public BackgroundDeletionService( IServiceProvider serviceProvider, ILogger? logger = null) { _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); _logger = logger; } /// /// Always 0 in the DB-polling design — there is no in-memory queue. The "queue" lives /// in _objects as rows with _value_string='pending'; callers that need /// that count should call /// directly. /// public int QueueLength => 0; /// /// Mark objects for deletion. Returns once SoftDeleteAsync has re-parented /// the objects under the trash scheme (so they immediately disappear from regular /// queries). The physical purge runs in a future poll /// cycle on a separate DB connection. /// public async Task DeleteAsync( IEnumerable objectIds, IRedbUser user, int batchSize = 10, long? trashParentId = null) { var ids = objectIds.ToArray(); if (ids.Length == 0) return new DeletionMark(0, 0); await using var scope = _serviceProvider.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); // SoftDeleteAsync writes the trash container with status='pending' in DB. The // polling loop in ExecuteAsync picks it up on the next cycle (≤ PollInterval // wait, typically much less). No channel write — DB is the queue. return await redb.SoftDeleteAsync(ids, user, trashParentId); } /// /// No-op. Kept on the interface for backward compatibility with callers like /// GroupService.AddMemberAsync that did manual SoftDeleteAsync + /// EnqueuePurge. The trash row those callers created is picked up by the /// next poll cycle, so the explicit wake-up signal is no longer needed. /// public void EnqueuePurge(long trashId, int totalCount, long userId, int batchSize = 10) { // Intentionally empty — the polling loop finds the row by itself. } /// /// Get current progress for a trash container from database. /// public async Task GetProgressAsync(long trashId) { await using var scope = _serviceProvider.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); return await redb.GetDeletionProgressAsync(trashId); } /// /// Get all active deletions for a user from database. /// public async Task> GetUserActiveProgressAsync(long userId) { await using var scope = _serviceProvider.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); return await redb.GetUserActiveDeletionsAsync(userId); } /// /// Polling loop — every finds up to /// pending trash containers, atomically claims each via /// , and purges with /// . Cluster-safe by the claim's atomic UPDATE — if /// another worker instance grabbed the same row, the claim returns false and we /// skip it. /// protected override async Task ExecuteAsync(CancellationToken stoppingToken) { _logger?.LogInformation("BackgroundDeletionService started (DB polling, interval={Interval})", PollInterval); while (!stoppingToken.IsCancellationRequested) { try { var processed = await PollAndProcessAsync(stoppingToken).ConfigureAwait(false); // No back-off when we found work — drain as fast as the DB lets us; one // poll cycle handles up to PollPageSize containers. When the page is // empty, sleep PollInterval. Saturates only when there is real load. if (processed == 0) { try { await Task.Delay(PollInterval, stoppingToken).ConfigureAwait(false); } catch (OperationCanceledException) { break; } } } catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested) { break; } catch (Exception ex) { _logger?.LogError(ex, "BackgroundDeletionService poll cycle failed; backing off {Interval}", PollInterval); try { await Task.Delay(PollInterval, stoppingToken).ConfigureAwait(false); } catch (OperationCanceledException) { break; } } } _logger?.LogInformation("BackgroundDeletionService stopped"); } /// /// One poll cycle: scan, claim, and process up to tasks. /// Returns the number of tasks actually processed (after claim contention with /// peer workers) so the outer loop can decide whether to keep draining or sleep. /// private async Task PollAndProcessAsync(CancellationToken ct) { // Short scopes: the scan's scope (and its connection) ends before the first purge starts, // and each claim gets its own - no connection of this cycle stays checked out across the // purges, which open their own scopes per batch. List tasks; await using (var scanScope = _serviceProvider.CreateAsyncScope()) { var scanRedb = scanScope.ServiceProvider.GetRequiredService(); tasks = await scanRedb.GetOrphanedDeletionTasksAsync(OrphanTimeoutMinutes).ConfigureAwait(false); } if (tasks.Count == 0) return 0; // Cap per cycle so a giant backlog doesn't block shutdown — anything not handled // here gets picked up on the next cycle (or by another worker in a cluster). var page = tasks.Take(PollPageSize).ToList(); _logger?.LogDebug("Poll cycle found {Total} pending tasks, processing up to {Page}", tasks.Count, page.Count); var processed = 0; foreach (var task in page) { if (ct.IsCancellationRequested) break; // The claim sits inside the per-task try: one container whose claim fails must not end // the cycle for every container after it. try { bool claimed; await using (var claimScope = _serviceProvider.CreateAsyncScope()) { var claimRedb = claimScope.ServiceProvider.GetRequiredService(); claimed = await claimRedb.TryClaimOrphanedTaskAsync(task.TrashId, OrphanTimeoutMinutes).ConfigureAwait(false); } if (!claimed) { _logger?.LogDebug("Task TrashId={TrashId} already claimed by another worker", task.TrashId); continue; } await ProcessPurgeTask(task.TrashId, task.Total, ct).ConfigureAwait(false); processed++; } catch (OperationCanceledException) when (ct.IsCancellationRequested) { break; } catch (redb.Core.Exceptions.RedbObjectReferencedException ex) { // Handled outcome, not a crash: the container is 'failed' and no longer claimed. It // waits for someone to remove the references and purge it again. _logger?.LogWarning(ex, "Purge of TrashId={TrashId} stopped: objects are referenced by live objects; container marked failed", task.TrashId); processed++; } catch (Exception ex) { _logger?.LogError(ex, "Purge failed for TrashId={TrashId}; will be retried next cycle once stale", task.TrashId); } } return processed; } /// /// Drain one trash container in batches of . The /// inter-batch Task.Delay(50) is backpressure: a single user-delete can /// cascade to thousands of _values rows, and the small pause lets live /// traffic (token issuance, /me reads) fit between purge batches instead of /// fighting for the same row locks. /// private async Task ProcessPurgeTask(long trashId, int totalCount, CancellationToken ct) { _logger?.LogDebug("Processing purge: TrashId={TrashId}, Total={Total}", trashId, totalCount); while (!ct.IsCancellationRequested) { await using var scope = _serviceProvider.CreateAsyncScope(); var redb = scope.ServiceProvider.GetRequiredService(); var progress = await redb.GetDeletionProgressAsync(trashId).ConfigureAwait(false); if (progress == null) { _logger?.LogDebug("Trash container {TrashId} already gone, purge done", trashId); break; } if (progress.Status == PurgeStatus.Completed) { _logger?.LogDebug("Purge completed: TrashId={TrashId}", trashId); break; } if (progress.Status == PurgeStatus.Failed) { _logger?.LogDebug("Purge of TrashId={TrashId} already failed; not retried automatically", trashId); break; } await redb.PurgeTrashAsync(trashId, totalCount, DefaultBatchSize, cancellationToken: ct).ConfigureAwait(false); try { await Task.Delay(50, ct).ConfigureAwait(false); } catch (OperationCanceledException) { break; } } } }