import CoreATProtocol import Foundation import Logging import ServiceLifecycle /// DID to PDS endpoint and DID to handle, cached in Postgres (`did_pds` and /// `profiles.handle`) so the cache survives restarts, and refreshed through /// the PLC directory when older than a day. actor IdentityCache { static let freshness: TimeInterval = 24 * 3600 private let database: Database private let resolver: DIDResolver private let logger: Logger private var pending: Set = [] init(database: Database, resolver: DIDResolver, logger: Logger) { self.database = database self.resolver = resolver self.logger = logger } /// Queues a DID for a background refresh of its PDS endpoint and handle, /// so the next read can show a handle without waiting on the network. func noteSeen(_ did: String) { guard !did.isEmpty else { return } pending.insert(did) } /// Resolves every queued DID. Called by the refresh service. func refreshPending() async { let batch = pending pending.removeAll() for did in batch { do { _ = try await pdsEndpoint(for: did) } catch { logger.debug("identity refresh failed", metadata: ["did": "\(did)", "error": "\(error)"]) } } } /// The PDS service URL for a DID, without a trailing slash. func pdsEndpoint(for did: String) async throws -> String { if let row = try await database.first("SELECT pds_endpoint, resolved_at FROM did_pds WHERE did = \(did)"), Date().timeIntervalSince(try row.date("resolved_at")) < Self.freshness { return try row.string("pds_endpoint") } let document = try await resolver.resolve(did: did) guard let endpoint = document.pdsEndpoint, !endpoint.isEmpty else { throw IndexingError("identity for \(did) has no PDS endpoint") } let trimmed = endpoint.hasSuffix("/") ? String(endpoint.dropLast()) : endpoint try await database.execute(""" INSERT INTO did_pds (did, pds_endpoint, resolved_at) VALUES (\(did), \(trimmed), NOW()) ON CONFLICT (did) DO UPDATE SET pds_endpoint = EXCLUDED.pds_endpoint, resolved_at = NOW() """) if let handle = document.handle { try await cacheHandle(handle, for: did) } return trimmed } /// The handle for a DID, from the cache when fresh. func handle(for did: String) async throws -> String? { if let row = try await database.first("SELECT handle, handle_resolved_at FROM profiles WHERE did = \(did)"), let handle = try row.optionalString("handle"), !handle.isEmpty, let resolvedAt = try row.optionalDate("handle_resolved_at"), Date().timeIntervalSince(resolvedAt) < Self.freshness { return handle } let document = try await resolver.resolve(did: did) if let handle = document.handle { try await cacheHandle(handle, for: did) } return document.handle } /// Writes only the handle columns so a profile record indexed earlier /// keeps its display name and description. private func cacheHandle(_ handle: String, for did: String) async throws { try await database.execute(""" INSERT INTO profiles (did, handle, handle_resolved_at, indexed_at) VALUES (\(did), \(handle), NOW(), NOW()) ON CONFLICT (did) DO UPDATE SET handle = EXCLUDED.handle, handle_resolved_at = NOW() """) } } /// Drains the identity cache's refresh queue every few seconds. struct IdentityRefreshService: Service { let cache: IdentityCache let interval: Duration = .seconds(2) func run() async throws { try await cancelWhenGracefulShutdown { while !Task.isCancelled { await cache.refreshPending() try await Task.sleep(for: interval) } } } } /// The DIDs this service has records for. Account, identity and sync events /// arrive for the whole network, and only the known ones are worth storing. /// /// The set is read from the tables at startup and grows as this process /// indexes records. Records indexed by another instance (a backfill on the /// instance serving the API, say) are not in it, so a miss against a set /// older than `refreshInterval` reads the tables again before answering. actor KnownDIDs { static let refreshInterval: Duration = .seconds(300) private let database: Database private let logger: Logger private let refreshInterval: Duration private var dids: Set = [] private var loadedAt: ContinuousClock.Instant? private var isReloading = false init(database: Database, logger: Logger, refreshInterval: Duration = KnownDIDs.refreshInterval) { self.database = database self.logger = logger self.refreshInterval = refreshInterval } func load() async throws { let rows = try await database.rows(""" SELECT did FROM profiles UNION SELECT did FROM did_pds UNION SELECT DISTINCT did FROM subscriptions UNION SELECT DISTINCT did FROM comments UNION SELECT DISTINCT did FROM episode_states """) for row in rows { dids.insert(try row.string("did")) } loadedAt = .now } func insert(_ did: String) { dids.insert(did) } /// Whether the DID is known, after a reload when the set is stale. /// Callers that arrive during a reload get the answer the set has now. func contains(_ did: String) async -> Bool { if dids.contains(did) { return true } guard isStale, !isReloading else { return false } isReloading = true defer { isReloading = false } do { try await load() } catch { logger.warning("known DIDs reload failed", metadata: ["error": "\(error)"]) loadedAt = .now } return dids.contains(did) } var all: [String] { Array(dids) } private var isStale: Bool { guard let loadedAt else { return true } return loadedAt.duration(to: .now) >= refreshInterval } }