import Foundation import Logging import ServiceLifecycle /// Deletes cache rows that expired more than a month ago: once when the /// service starts, then once a day. An expired row is still useful as a /// stale fallback for a while; after that it is just disk. The first pass /// does not wait a day, because a service that is redeployed more often than /// that would otherwise never clean up. /// /// The answers to `getNewEpisodes` go an hour after they expire. They are /// never served once expired, and there is a new one for every feed and /// every day asked from, so a month of them would be most of the table. /// /// Runs as a service in a long-lived process, or one pass at a time from /// `GET /_cron/cache-cleanup`. struct CacheCleanupService: Service { static let interval: Duration = .seconds(24 * 3600) static let keepExpiredFor: TimeInterval = 30 * 24 * 3600 static let keepExpiredNewEpisodesFor: TimeInterval = 3600 let database: Database let logger: Logger func run() async throws { try await cancelWhenGracefulShutdown { while !Task.isCancelled { _ = await runOnce() try await Task.sleep(for: Self.interval) } } } /// Deletes one batch of old rows. Returns how many went. @discardableResult func runOnce() async -> Int { do { return try await database.scalar(""" WITH removed AS ( DELETE FROM pi_cache WHERE expires_at < \(Date().addingTimeInterval(-Self.keepExpiredFor)) OR (cache_key LIKE \(CacheKeys.newEpisodesPrefix + "%") AND expires_at < \(Date().addingTimeInterval(-Self.keepExpiredNewEpisodesFor))) RETURNING 1 ) SELECT COUNT(*)::int FROM removed """) } catch { logger.warning("pi_cache cleanup failed", metadata: ["error": "\(error)"]) return 0 } } }