Repository Public License
1import CryptoKit2import Foundation3import NavigatorCore4import Persistence5import Testing6@testable import SyncEngine78struct SeededGenerator: RandomNumberGenerator {9 private var state: UInt6410 init(seed: UInt64) { state = seed &+ 0x9E37_79B9_7F4A_7C15 }11 mutating func next() -> UInt64 {12 state &+= 0x9E37_79B9_7F4A_7C1513 var z = state14 z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B915 z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB16 return z ^ (z >> 31)17 }18}1920func day(_ offset: Double = 0) -> Date { Date(timeIntervalSince1970: 1_800_000_000 + offset) }2122func temporaryDirectory() -> URL {23 let url = FileManager.default.temporaryDirectory.appending(path: "orix-sync-tests-\(UUID().uuidString)", directoryHint: .isDirectory)24 try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)25 return url26}2728/// A database with one profile and, optionally, a representative set of user data.29struct World {30 let database: NavigatorDatabase31 let profile: Profile32 var space: OrbitSpace33 var folder: Bookmark34 var link: Bookmark35 var nested: Bookmark36 var note: Note37 var canvas: CanvasDocument38 var workflow: Workflow39 var archive: Archive40 let archiveDirectory: URL41 let attachmentDirectory: URL42 static let attachmentName = String(repeating: "ab", count: 32) + ".png"4344 static func empty(name: String = "Personal") async throws -> (NavigatorDatabase, Profile) {45 let database = try await NavigatorDatabase.inMemory()46 let profile = Profile(name: name, createdAt: day())47 try await database.profiles.save(profile)48 return (database, profile)49 }5051 static func populated() async throws -> World {52 let (database, profile) = try await empty()53 let root = temporaryDirectory()54 let archives = root.appending(path: "archives", directoryHint: .isDirectory), attachments = root.appending(path: "attachments", directoryHint: .isDirectory)55 let space = OrbitSpace(profileID: profile.id, name: "Research", symbol: "book", tint: .ocean, createdAt: day(), updatedAt: day())56 try await database.spaces.save(space)57 let window = BrowserWindow(spaceID: space.id)58 try await database.windows.save(window)59 try await database.tabs.save([60 Tab(windowID: window.id, spaceID: space.id, url: URL(string: "https://example.org/one"), title: "One", isPinned: true, order: 0,61 sessionState: Data("MARKER-SESSION-STATE".utf8), createdAt: day(), lastActiveAt: day()),62 Tab(windowID: window.id, spaceID: space.id, url: URL(string: "https://example.org/two"), title: "Two", order: 1, createdAt: day(), lastActiveAt: day()),63 ])64 let folder = Bookmark(profileID: profile.id, kind: .folder, title: "Reading", order: 0, createdAt: day(), updatedAt: day())65 let link = Bookmark(profileID: profile.id, parentID: folder.id, title: "Swift", url: URL(string: "https://www.swift.org/"), order: 0, tags: ["dev", "lang"],66 isFavorite: true, createdAt: day(), updatedAt: day())67 let subfolder = Bookmark(profileID: profile.id, parentID: folder.id, kind: .folder, title: "Deep", order: 1, createdAt: day(), updatedAt: day())68 let nested = Bookmark(profileID: profile.id, parentID: subfolder.id, title: "Nested", url: URL(string: "https://example.org/nested"), createdAt: day(), updatedAt: day())69 let loose = Bookmark(profileID: profile.id, title: "Loose", url: URL(string: "https://example.org/loose"), order: 1, createdAt: day(), updatedAt: day())70 for bookmark in [folder, link, subfolder, nested, loose] { try await database.bookmarks.save(bookmark) }71 let note = Note(spaceID: space.id, url: URL(string: "https://example.org/one"), title: "Idea", body: "Remember this.", quote: "a quote", tint: .solar,72 createdAt: day(), updatedAt: day())73 try await database.notes.save(note)74 let first = CanvasCard(content: .page(url: URL(string: "https://example.org/one")!, title: "One"), origin: CanvasPoint(x: 0, y: 0))75 let second = CanvasCard(content: .image(relativePath: attachmentName), origin: CanvasPoint(x: 300, y: 0), zIndex: 1)76 let canvas = CanvasDocument(spaceID: space.id, title: "Board", cards: [first, second], connections: [CanvasConnection(from: first.id, to: second.id, label: "see")],77 createdAt: day(), updatedAt: day())78 try await database.canvases.save(canvas)79 try FileManager.default.createDirectory(at: attachments.appending(path: canvas.id.string), withIntermediateDirectories: true)80 try Data([0x89, 0x50, 0x4E, 0x47] + Array("image-bytes".utf8)).write(to: attachments.appending(path: canvas.id.string).appending(path: attachmentName))81 let workflow = Workflow(name: "Brief", source: "flow \"Brief\" version 1\nnotify \"hi\"\n", createdAt: day(), updatedAt: day())82 try await database.workflows.save(workflow)83 try FileManager.default.createDirectory(at: archives.appending(path: "2026"), withIntermediateDirectories: true)84 let archiveBytes = Data("<html><body>archived page</body></html>".utf8)85 try archiveBytes.write(to: archives.appending(path: "2026/page one.html"))86 let archive = Archive(profileID: profile.id, url: URL(string: "https://example.org/one")!, title: "One, archived", format: .html, relativePath: "2026/page one.html",87 byteSize: Int64(archiveBytes.count), contentHash: SHA256.hash(data: archiveBytes).map { String(format: "%02x", $0) }.joined(),88 isComplete: true, capturedAt: day())89 try await database.archives.save(archive)90 try await database.history.recordVisits([91 NavigationEntry(profileID: profile.id, url: URL(string: "https://history.example/MARKER-HISTORY")!, title: "Visited", visitedAt: day(10), transition: .typed),92 NavigationEntry(profileID: profile.id, url: URL(string: "https://example.org/one")!, title: "One", visitedAt: day(20)),93 ])94 return World(database: database, profile: profile, space: space, folder: folder, link: link, nested: nested, note: note, canvas: canvas,95 workflow: workflow, archive: archive, archiveDirectory: archives, attachmentDirectory: attachments)96 }9798 var exporter: CapsuleExporter {99 CapsuleExporter(database: database, appVersion: "1.0 (test)", archiveDirectory: archiveDirectory, canvasAttachmentDirectory: attachmentDirectory)100 }101102 var everything: CapsuleSelection {103 var selection = CapsuleSelection(profileID: profile.id)104 selection.bookmarks = .all; selection.notes = .all; selection.canvases = .all; selection.workflows = .all105 selection.spaces = .all; selection.archives = .all106 return selection107 }108}109110/// Builds container bytes by hand, following docs/CAPSULE_FORMAT.md rather than the module's writer, so the111/// reader is tested against the specification — including entries a well-behaved writer never produces.112enum RawCapsule {113 struct Entry {114 var name: Data115 var compression: UInt8 = 0116 var stored: Data117 var originalLength: UInt64?118 init(_ name: String, _ stored: Data, compression: UInt8 = 0, originalLength: UInt64? = nil) {119 self.name = Data(name.utf8); self.stored = stored; self.compression = compression; self.originalLength = originalLength120 }121 }122123 static func big<T: FixedWidthInteger>(_ value: T) -> Data { withUnsafeBytes(of: value.bigEndian) { Data($0) } }124125 static func build(_ entries: [Entry], version: UInt16 = 1, flags: UInt16 = 0, header: Data = Data("{}".utf8), declaredCount: UInt32? = nil,126 trailing: Data = Data()) -> Data {127 var file = Data("ORIXCAPS".utf8) + big(version) + big(flags) + big(UInt32(header.count)) + header128 for entry in entries {129 file += big(UInt16(entry.name.count)) + entry.name + Data([entry.compression]) + big(UInt64(entry.stored.count))130 file += big(entry.originalLength ?? UInt64(entry.stored.count)) + entry.stored131 }132 file += big(UInt16(0)) + big(declaredCount ?? UInt32(entries.count)) + trailing133 return file + Data(SHA256.hash(data: file))134 }135136 static func sha(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }137138 /// A manifest followed by the given payload entries, all consistent (sizes and hashes), as the reader expects.139 static func consistent(_ payloads: [(name: String, kind: String, count: Int, data: Data)], includesHistory: Bool = false,140 formatVersion: Int = 1, format: String = "orix.capsule") -> Data {141 let items = payloads.map { "{\"byteSize\":\($0.data.count),\"count\":\($0.count),\"kind\":\"\($0.kind)\",\"name\":\"\($0.name)\",\"sha256\":\"\(sha($0.data))\"}" }142 let manifest = "{\"appVersion\":\"t\",\"createdAt\":1800000000,\"format\":\"\(format)\",\"formatVersion\":\(formatVersion),\"includesHistory\":\(includesHistory),\"items\":[\(items.joined(separator: ","))]}"143 return build([Entry("manifest.json", Data(manifest.utf8))] + payloads.map { Entry($0.name, $0.data) })144 }145}146147/// A transport wrapper that lets a test misbehave on the receiving side: replay, reorder, tamper, drop.148actor HostileTransport: BridgeTransport {149 enum Mode { case honest, replayPrevious, swapNextTwo, flipBit(Int), dropNext, truncate }150 private let inner: any BridgeTransport151 private var mode = Mode.honest152 private var previous: Data?153 private(set) var seen: [Data] = []154155 init(_ inner: any BridgeTransport) { self.inner = inner }156 func set(_ mode: Mode) { self.mode = mode }157158 func send(_ frame: Data) async throws { try await inner.send(frame) }159160 func receive() async throws -> Data {161 switch mode {162 case .honest:163 let frame = try await inner.receive()164 previous = frame; seen.append(frame)165 return frame166 case .replayPrevious:167 mode = .honest168 guard let previous else { return try await inner.receive() }169 return previous170 case .swapNextTwo:171 mode = .honest172 let first = try await inner.receive()173 let second = try await inner.receive()174 previous = first175 return second176 case .flipBit(let index):177 mode = .honest178 var frame = try await inner.receive()179 frame[frame.startIndex + min(index, frame.count - 1)] ^= 0x01180 return frame181 case .dropNext:182 mode = .honest183 _ = try await inner.receive()184 return try await inner.receive()185 case .truncate:186 mode = .honest187 return Data(try await inner.receive().dropLast(3))188 }189 }190191 func close() async { await inner.close() }192}193194/// Pairs two in-memory endpoints with the same code and returns the two channels.195func pairedChannels(wrapping: Bool = false) async throws -> (BridgeSecureChannel, BridgeSecureChannel, HostileTransport?) {196 let (a, b) = InMemoryBridgeTransport.pair()197 let offer = BridgePairingOffer()198 let hostile = wrapping ? HostileTransport(b) : nil199 let responderTransport: any BridgeTransport = hostile ?? b200 async let responder = offer.accept(over: responderTransport)201 let initiator = try await BridgePairing.initiate(code: try BridgePairingCode(offer.code.digits), over: a)202 return (initiator, try await responder, hostile)203}204205/// The synchronised content of a database in a comparable, device-neutral form.206struct SyncedContent: Equatable, CustomStringConvertible {207 var bookmarks: [String: String] = [:]208 var notes: [String: String] = [:]209 var canvases: [String: String] = [:]210 var workflows: [String: String] = [:]211 var spaces: [String: String] = [:]212 var stamps: [String: String] = [:]213214 var description: String { "bookmarks \(bookmarks.sorted { $0.key < $1.key })\nnotes \(notes.sorted { $0.key < $1.key })\ncanvases \(canvases.count) workflows \(workflows.sorted { $0.key < $1.key })\nspaces \(spaces)\nstamps \(stamps.sorted { $0.key < $1.key })" }215216 static func of(_ database: NavigatorDatabase) async throws -> SyncedContent {217 var content = SyncedContent()218 for profile in try await database.profiles.all() {219 for bookmark in try await database.bookmarks.all(profile: profile.id) {220 content.bookmarks[bookmark.id.string] = "\(bookmark.title)|\(bookmark.parentID?.string ?? "root")|\(bookmark.url?.absoluteString ?? "")|\(bookmark.order)|\(bookmark.tags)"221 }222 for space in try await database.spaces.spaces(profile: profile.id) { content.spaces[space.id.string] = "\(space.name)|\(space.tint.rawValue)" }223 }224 for note in try await database.notes.notes(limit: 100_000) { content.notes[note.id.string] = "\(note.title)|\(note.body)" }225 for canvas in try await database.canvases.documents() { content.canvases[canvas.id.string] = "\(canvas.title)|\(canvas.cards.count)|\(canvas.connections.count)" }226 for workflow in try await database.workflows.all() { content.workflows[workflow.id.string] = "\(workflow.name)|\(workflow.source)" }227 for record in try await database.sync.changes(since: -1, limit: 1_000_000) {228 content.stamps["\(record.entity.rawValue):\(record.entityID)"] = "\(record.version)|\(record.deviceID)|\(record.modifiedAt.timeIntervalSince1970)|\(record.deletedAt != nil)|\(record.payloadHash ?? "-")"229 }230 return content231 }232}233234/// One full exchange between two coordinators without any transport: what a Bridge session does, step by step.235func exchange(_ a: SyncCoordinator, _ b: SyncCoordinator) async throws {236 let indexA = try await a.index(), indexB = try await b.index()237 let planA = try await a.plan(remote: indexB), planB = try await b.plan(remote: indexA)238 let toA = try await b.changes(for: planA.request) + planA.tombstones.map { SyncChange(stamp: $0, payload: nil) }239 let toB = try await a.changes(for: planB.request) + planB.tombstones.map { SyncChange(stamp: $0, payload: nil) }240 _ = try await a.apply(toA)241 _ = try await b.apply(toB)242}243244/// The error a task ended with, if any (`async let` values cannot be used inside `#expect` closures).245func failure<T: Sendable>(of task: Task<T, any Error>) async -> (any Error)? {246 if case .failure(let error) = await task.result { return error }247 return nil248}249