Repository Public
1// SP Notes Core2// File: Sources/SPNotesStore/EntityModels.swift3// Description: Value types of the 2.0 tables: generic synced entities and their outbox, parked ops, canvases,4// the cached events journal and the cache of server-computed read models.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910/// The kinds of the entity change feed (`GET /api/sync?kinds=`). A kind is a string: one this build does not list11/// is stored and returned like the others.12public struct EntityKind: RawRepresentable, Sendable, Hashable, Codable, CustomStringConvertible, ExpressibleByStringLiteral {13 public var rawValue: String14 public init(rawValue: String) { self.rawValue = rawValue }15 public init(_ rawValue: String) { self.rawValue = rawValue }16 public init(stringLiteral value: String) { self.rawValue = value }17 public init(from decoder: Decoder) throws { rawValue = try decoder.singleValueContainer().decode(String.self) }18 public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer(); try c.encode(rawValue) }19 public var description: String { rawValue }2021 public static let task: EntityKind = "task"22 public static let database: EntityKind = "database"23 public static let databaseProperty: EntityKind = "database_property"24 public static let databaseView: EntityKind = "database_view"25 public static let databaseRow: EntityKind = "database_row"26 public static let edge: EntityKind = "edge"27 public static let reference: EntityKind = "reference"28 public static let canvas: EntityKind = "canvas"29 public static let concept: EntityKind = "concept"3031 /// The nine kinds of SPEC §3.1, in feed order.32 public static let all: [EntityKind] = [.task, .database, .databaseProperty, .databaseView, .databaseRow, .edge, .reference, .canvas, .concept]3334 /// The value of the `kinds` query parameter for a set of kinds.35 public static func feedParameter(_ kinds: [EntityKind] = all) -> String { kinds.map(\.rawValue).joined(separator: ",") }36}3738/// The value an entity is ordered by inside its scope (a position, a due date…).39public enum EntitySort: Sendable, Hashable {40 case number(Double)41 case text(String)42}4344/// The lookup columns of an entity row, extracted from its JSON so that typed queries use an index:45/// `scope` = the owner (database of a property / view / row, page of a task or canvas, source of an edge),46/// `ref` = a second id (target of an edge), `sort` = the order inside the scope.47public struct EntityIndex: Sendable, Hashable {48 public var scope: String?49 public var ref: String?50 public var sort: EntitySort?5152 public init(scope: String? = nil, ref: String? = nil, sort: EntitySort? = nil) {53 self.scope = scope54 self.ref = ref55 self.sort = sort56 }5758 /// The JSON keys read for each lookup column, per kind; the first key present wins. The first names are those of59 /// the feed rows of `API-NEXT.md` §3.1 (`fromId` / `toId` for an edge, `pageId` for the page a reference is60 /// attached to); the others are kept for rows written before that contract. A caller that knows better passes an61 /// explicit `EntityIndex`.62 public static let defaultKeys: [EntityKind: (scope: [String], ref: [String], sort: [String])] = [63 .task: (["pageId", "page_id"], ["blockId", "block_id"], ["due", "dueAt", "due_at"]),64 .database: ([], [], ["title", "name"]),65 .databaseProperty: (["databaseId", "database_id"], [], ["position"]),66 .databaseView: (["databaseId", "database_id"], [], ["position"]),67 .databaseRow: (["databaseId", "database_id"], ["pageId", "page_id"], ["position"]),68 .edge: (["fromId", "sourceId", "source_id", "source", "from"], ["toId", "targetId", "target_id", "target", "to"], []),69 .reference: (["pageId", "projectId", "project_id"], [], ["title"]),70 .canvas: (["pageId", "page_id"], [], []),71 .concept: ([], [], ["name"]),72 ]7374 /// The lookup columns read from an entity's JSON object with `defaultKeys` (all nil for an unknown kind).75 public static func extract(kind: EntityKind, json: Data) -> EntityIndex {76 guard let keys = defaultKeys[kind], let object = (try? JSONSerialization.jsonObject(with: json)) as? [String: Any] else { return EntityIndex() }77 func string(_ names: [String]) -> String? {78 for name in names { if let value = object[name] as? String, !value.isEmpty { return value } }79 return nil80 }81 var sort: EntitySort?82 for name in keys.sort {83 if let text = object[name] as? String { sort = .text(text); break }84 if let number = object[name] as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID() { sort = .number(number.doubleValue); break }85 }86 return EntityIndex(scope: string(keys.scope), ref: string(keys.ref), sort: sort)87 }88}8990/// One row of the generic `entities` table.91public struct EntityRecord: Sendable, Equatable, Identifiable {92 public var kind: EntityKind93 public var id: String94 /// Server change sequence of the row (0 = never seen on the server).95 public var rev: Int6496 /// The entity as JSON (the server row, or the local edit while `dirty`).97 public var json: Data98 public var deleted: Bool99 public var updatedAt: Date100 public var index: EntityIndex101 /// True while local changes wait in the entity outbox.102 public var dirty: Bool103 /// The server's copy received while `dirty` (the local JSON was kept); nil otherwise.104 public var remoteJSON: Data?105106 /// Decodes the JSON into a typed value.107 public func decode<T: Decodable>(_ type: T.Type = T.self, decoder: JSONDecoder = JSONDecoder()) throws -> T {108 try decoder.decode(T.self, from: json)109 }110}111112/// An entity as the change feed delivers it.113public struct RemoteEntity: Sendable, Equatable {114 public var kind: EntityKind115 public var id: String116 public var rev: Int64117 public var json: Data118 public var updatedAt: Date?119 /// nil = extracted from the JSON with `EntityIndex.extract`.120 public var index: EntityIndex?121122 public init(kind: EntityKind, id: String, rev: Int64, json: Data, updatedAt: Date? = nil, index: EntityIndex? = nil) {123 self.kind = kind124 self.id = id125 self.rev = rev126 self.json = json127 self.updatedAt = updatedAt128 self.index = index129 }130}131132/// A tombstone of the entity feed.133public struct EntityTombstone: Sendable, Hashable {134 public var kind: EntityKind135 public var id: String136 public init(kind: EntityKind, id: String) { self.kind = kind; self.id = id }137}138139/// What `applyRemoteEntities` did.140public struct EntityApplySummary: Sendable, Equatable {141 public var applied = 0142 /// Rows whose stored `rev` was already at least the incoming one.143 public var stale = 0144 /// Rows with local changes pending: the server copy was kept aside in `remoteJSON`, the local JSON untouched.145 public var keptLocal: [EntityTombstone] = []146 public var removed = 0147}148149/// The verbs of the entity outbox. A verb is a string so that a newer build's verbs survive in the table.150public enum EntityOpVerb {151 public static let create = "create"152 public static let update = "update"153 public static let delete = "delete"154}155156/// One row of the entity outbox.157public struct EntityOp: Sendable, Equatable, Identifiable {158 public enum State: String, Sendable, Codable {159 /// Waiting to be sent.160 case pending161 /// This build has no handler for (`kind`, `op`): kept, surfaced, never sent, never dropped.162 case unsupported163 /// The server refused it for good: kept and surfaced until the user retries or discards it.164 case rejected165 }166167 /// Outbox sequence number (order of execution).168 public var id: Int64169 public var kind: EntityKind170 public var entityId: String171 public var op: String172 /// JSON body of the request, when the verb has one.173 public var payload: Data?174 /// The version the edit was made on (optimistic concurrency), when the kind has one.175 public var baseVersion: Int?176 public var idempotencyKey: String177 public var createdAt: Date178 public var attempts: Int179 public var nextAttemptAt: Date180 public var lastError: String?181 public var state: State182}183184/// An op of the 1.x queue that this build cannot execute (see `NotesStore.parkOp`).185public struct ParkedOp: Sendable, Equatable, Identifiable {186 public var op: PendingOp187 public var reason: String188 public var parkedAt: Date189 public var id: Int64 { op.id }190}191192/// The local copy of a canvas (`spn-canvas-1` JSON, opaque to the store).193public struct CanvasRecord: Sendable, Equatable, Identifiable {194 public var pageId: String195 public var json: Data196 /// Server version of the last synced copy (0 = never pushed).197 public var version: Int198 /// The last copy common with the server, kept while `dirty` for the three-way merge.199 public var baseJSON: Data?200 public var dirty: Bool201 public var rev: Int64202 public var editSeq: Int64203 /// A server copy that could not be merged; the local JSON was not touched.204 public var conflictJSON: Data?205 public var conflictVersion: Int?206 public var syncError: String?207 public var updatedAt: Date208 public var id: String { pageId }209 public var hasConflict: Bool { conflictJSON != nil }210}211212/// What `applyRemoteCanvas` did.213public enum CanvasApplyResult: Sendable, Equatable {214 /// The server copy replaced the (clean) local one.215 case applied216 /// Nothing to do: same or older version.217 case unchanged218 /// The canvas has local changes: nothing was written. Merge `local` and `remote` over `base` (in219 /// `SPNotesDocument`: `CanvasDocument.merge`), then call `resolveCanvas` or `recordCanvasConflict`.220 case diverged(base: Data?, local: Data, remote: Data, remoteVersion: Int)221}222223/// An entry of the knowledge events journal (`GET /api/events`), cached for offline reading.224public struct EventRecord: Sendable, Equatable, Identifiable {225 public var id: String226 public var at: Date227 /// `page.created`, `task.completed`, `ai.applied`…228 public var kind: String229 public var pageId: String?230 public var entityKind: String?231 public var entityId: String?232 /// `user`, `agent`, `ai` or `system`.233 public var actor: String234 public var device: String?235 public var summary: String236 /// The event's `data` object as JSON.237 public var data: Data?238 public var fetchedAt: Date239 /// Title and icon of `pageId` as the server sent them with the event. They are **not stored** in the events table:240 /// an event read back from the device has nil here unless the reader filled them from the local page241 /// (`TimelineRepository` does).242 public var pageTitle: String?243 public var pageIcon: String?244245 public init(id: String, at: Date, kind: String, pageId: String? = nil, entityKind: String? = nil, entityId: String? = nil,246 actor: String = "user", device: String? = nil, summary: String = "", data: Data? = nil, fetchedAt: Date = Date(),247 pageTitle: String? = nil, pageIcon: String? = nil) {248 self.pageTitle = pageTitle249 self.pageIcon = pageIcon250 self.id = id251 self.at = at252 self.kind = kind253 self.pageId = pageId254 self.entityKind = entityKind255 self.entityId = entityId256 self.actor = actor257 self.device = device258 self.summary = summary259 self.data = data260 self.fetchedAt = fetchedAt261 }262}263264/// Filter of `NotesStore.events`.265public struct EventQuery: Sendable, Equatable {266 public var pageId: String?267 public var kinds: [String] = []268 /// A kind prefix such as `page.` or `task.`.269 public var kindPrefix: String?270 public var from: Date?271 public var to: Date?272 public var actor: String?273 public var limit = 200274 public var offset = 0275276 public init(pageId: String? = nil, kinds: [String] = [], kindPrefix: String? = nil, from: Date? = nil, to: Date? = nil,277 actor: String? = nil, limit: Int = 200, offset: Int = 0) {278 self.pageId = pageId279 self.kinds = kinds280 self.kindPrefix = kindPrefix281 self.from = from282 self.to = to283 self.actor = actor284 self.limit = limit285 self.offset = offset286 }287}288289/// A cached server answer with the moment it was fetched.290public struct CachedValue: Sendable, Equatable {291 public var key: String292 public var json: Data293 public var fetchedAt: Date294 public var etag: String?295296 /// Seconds since the value was fetched.297 public func age(now: Date = Date()) -> TimeInterval { now.timeIntervalSince(fetchedAt) }298 public func isFresh(maxAge: TimeInterval, now: Date = Date()) -> Bool { age(now: now) <= maxAge }299 public func decode<T: Decodable>(_ type: T.Type = T.self, decoder: JSONDecoder = JSONDecoder()) throws -> T {300 try decoder.decode(T.self, from: json)301 }302}303304/// Keys of the read-model cache. Server-computed views are readable offline from their last fetched copy.305public enum CacheKey {306 public static let meta = "meta"307 public static let health = "health.knowledge"308 public static let brief = "brief"309 public static let briefSummary = "brief.summary"310 public static let insights = "graph.insights"311 public static let constellation = "graph.constellation"312 public static let models = "ai.models"313 /// `view` = global, local, project, timeline, concepts, documents, references; `scope` = the page or project id.314 public static func graph(view: String, scope: String? = nil) -> String { "graph.\(view)" + (scope.map { ".\($0)" } ?? "") }315 public static func zoom(pageId: String, level: Int) -> String { "zoom.\(pageId).\(level)" }316 /// A living block's rows; `fingerprint` identifies the query (source, filter, limit).317 public static func query(_ fingerprint: String) -> String { "query.\(fingerprint)" }318 public static func timeMachine(scope: String, at: String) -> String { "timemachine.\(scope).\(at)" }319}320