Repository Public
1// SP Notes Core2// File: Sources/SPNotesSync/Repositories/TimelineRepository.swift3// Description: Timeline and time machine for the apps: the events journal paged from the server and kept in the local events table for offline reading, the state of a page or project at a date (cached), and the restore of a history entry.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import SPNotesAPI9import SPNotesStore1011/// One page of the journal.12public struct TimelinePage: Sendable, Equatable {13 public var events: [EventRecord]14 /// Pass back to `events(_:)` as `query.cursor` for the next (older) page; nil at the end, and always nil offline.15 public var nextCursor: String?16 public var source: Cached<Int>.Source17 /// When the oldest of these events was fetched (offline: show « mis à jour il y a … »).18 public var fetchedAt: Date?19}2021public struct TimelineRepository: Sendable {22 let context: RepositoryContext23 public init(context: RepositoryContext) { self.context = context }2425 /// The journal, newest first. Online: one page from the server (stored locally). Offline or `.cacheOnly`: the26 /// events already on the device that match the query (page, kinds — exact names or `family.*` —, dates);27 /// `projectId` cannot be evaluated offline and then throws `.notCached`.28 public func events(_ query: JournalQuery = JournalQuery(), policy: CachePolicy = .networkFirst) async throws -> TimelinePage {29 try await context.require(ServerFeature.events)30 if policy != .cacheOnly {31 do {32 let page = try await context.api.events(query)33 let now = Date()34 let records = page.events.map { Self.record($0, fetchedAt: now) }35 try? await context.store.cacheEvents(records, fetchedAt: now)36 return TimelinePage(events: records, nextCursor: page.nextCursor, source: .network, fetchedAt: now)37 } catch {38 let mapped = RepositoryError.from(error)39 guard mapped == .offline, policy != .networkOnly else { throw mapped }40 }41 }42 guard query.projectId == nil else { throw RepositoryError.notCached }43 do {44 var all: [EventRecord] = []45 let exact = query.kinds.filter { !$0.hasSuffix(".*") }46 let families = query.kinds.filter { $0.hasSuffix(".*") }.map { String($0.dropLast(1)) }47 if query.kinds.isEmpty || !exact.isEmpty {48 all += try await context.store.events(EventQuery(pageId: query.pageId, kinds: exact, from: query.from, to: query.to, limit: query.limit ?? 50))49 }50 for prefix in families {51 all += try await context.store.events(EventQuery(pageId: query.pageId, kindPrefix: prefix, from: query.from, to: query.to, limit: query.limit ?? 50))52 }53 var seen = Set<String>()54 var merged = Array(all.filter { seen.insert($0.id).inserted }.sorted { ($0.at, $0.id) > ($1.at, $1.id) }.prefix(query.limit ?? 50))55 // The page title is not stored with the event: read it from the device's copy of the page (current title).56 var titles: [String: String] = [:]57 for index in merged.indices {58 guard let pageId = merged[index].pageId else { continue }59 if titles[pageId] == nil { titles[pageId] = (try? await context.store.summary(id: pageId))?.title ?? "" }60 if let title = titles[pageId], !title.isEmpty { merged[index].pageTitle = title }61 }62 return TimelinePage(events: merged, nextCursor: nil, source: .cache, fetchedAt: merged.map(\.fetchedAt).min())63 } catch { throw RepositoryError.from(error) }64 }6566 static func record(_ event: KnowledgeEvent, fetchedAt: Date) -> EventRecord {67 EventRecord(id: event.id, at: event.at, kind: event.kind, pageId: event.pageId, entityKind: event.entityKind, entityId: event.entityId,68 actor: event.actor ?? "user", device: event.device, summary: event.summary ?? "", data: event.data?.data, fetchedAt: fetchedAt,69 pageTitle: event.pageTitle, pageIcon: event.pageIcon)70 }7172 /// The state of a page at a date (nearest history entry; `source` / `exact` say how faithful it is).73 public func timeMachine(pageId: String, at date: Date, policy: CachePolicy = .cacheFirst(maxAge: Staleness.timeMachine)) async throws -> Cached<TimeMachineSnapshot> {74 try await context.require(ServerFeature.timeMachine)75 return try await context.read(CacheKey.timeMachine(scope: "page." + pageId, at: APIDate.string(from: date)), policy: policy) { try await context.api.timeMachine(pageID: pageId, at: date) }76 }7778 /// The state of a project (a page and its sub-pages) at a date.79 public func timeMachine(projectId: String, at date: Date, policy: CachePolicy = .cacheFirst(maxAge: Staleness.timeMachine)) async throws -> Cached<TimeMachineSnapshot> {80 try await context.require(ServerFeature.timeMachine)81 return try await context.read(CacheKey.timeMachine(scope: "project." + projectId, at: APIDate.string(from: date)), policy: policy) { try await context.api.timeMachine(projectID: projectId, at: date) }82 }8384 /// Brings a page back to a history entry (online only; the current state is saved in the history first). Pass85 /// the version the device holds as `baseVersion`: `.server(error)` with `error.isConflict` when the page moved.86 /// The restored content reaches the device through the next sync cycle, which is requested here.87 @discardableResult88 public func restore(pageId: String, versionId: String, baseVersion: Int? = nil) async throws -> HistoryRestoreResult {89 let result = try await context.online { try await context.api.restoreHistoryEntry(pageID: pageId, versionID: versionId, baseVersion: baseVersion) }90 await context.scheduleSync()91 return result92 }93}94