Repository navigation
Mobile state sync v2: per-record deltas replace the invalidate-and-refetch loop #8284
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 13 commits
30c424c
2f11b0f
f5d513d
4788fd7
8038b6f
c9f8079
e04e006
1546b8c
a2f59a3
751ff50
f7bcc0d
defc6eb
ffdc47e
d23a913
916fc40
b29d7cf
f440923
364c651
b64707c
cdc2467
d437edb
3983726
2d4571e
11a7e9e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,185 @@ | ||
| import Foundation | ||
|
|
||
| /// Client-held position in one collection's revision stream. Only meaningful | ||
| /// while the Mac's `epoch` is unchanged; a cursor from another epoch always | ||
| /// resolves to a snapshot. | ||
| public struct MobileSyncCursor: Codable, Equatable, Sendable { | ||
| public let epoch: String | ||
| public let rev: UInt64 | ||
|
|
||
| public init(epoch: String, rev: UInt64) { | ||
| self.epoch = epoch | ||
| self.rev = rev | ||
| } | ||
| } | ||
|
|
||
| /// How a fetch response section carries its records. | ||
| public enum MobileSyncPayloadMode: String, Codable, Sendable { | ||
| /// `records` is the full row set; replace local state. | ||
| case snapshot | ||
| /// `records`/`removed_ids` are changes in `(from_rev, rev]`; apply over | ||
| /// local state at `from_rev` or newer. | ||
| case delta | ||
| } | ||
|
|
||
| /// One collection section of a `mobile.sync.fetch` response. | ||
| public struct MobileSyncCollectionPayload<Record: MobileSyncRecord>: Codable, Equatable, Sendable { | ||
| public let mode: MobileSyncPayloadMode | ||
| /// Head revision the payload brings the client to. | ||
| public let rev: UInt64 | ||
| /// The client revision this delta starts from. Absent for snapshots. | ||
| public let fromRev: UInt64? | ||
| public let records: [Record] | ||
| public let removedIDs: [String] | ||
|
|
||
| public init( | ||
| mode: MobileSyncPayloadMode, | ||
| rev: UInt64, | ||
| fromRev: UInt64?, | ||
| records: [Record], | ||
| removedIDs: [String] | ||
| ) { | ||
| self.mode = mode | ||
| self.rev = rev | ||
| self.fromRev = fromRev | ||
| self.records = records | ||
| self.removedIDs = removedIDs | ||
| } | ||
|
|
||
| private enum CodingKeys: String, CodingKey { | ||
| case mode | ||
| case rev | ||
| case fromRev = "from_rev" | ||
| case records | ||
| case removedIDs = "removed_ids" | ||
| } | ||
| } | ||
|
|
||
| /// The `mobile.sync.fetch` request body: one cursor entry per collection the | ||
| /// client wants. A missing cursor means cold start (snapshot). | ||
| public struct MobileSyncFetchRequest: Codable, Equatable, Sendable { | ||
| public struct Collection: Codable, Equatable, Sendable { | ||
| public let id: MobileSyncCollectionID | ||
| public let epoch: String? | ||
| public let rev: UInt64? | ||
|
|
||
| public init(id: MobileSyncCollectionID, epoch: String?, rev: UInt64?) { | ||
| self.id = id | ||
| self.epoch = epoch | ||
| self.rev = rev | ||
| } | ||
|
|
||
| /// The cursor this entry carries, when it carries a complete one. | ||
| public var cursor: MobileSyncCursor? { | ||
| guard let epoch, let rev else { return nil } | ||
| return MobileSyncCursor(epoch: epoch, rev: rev) | ||
| } | ||
| } | ||
|
|
||
| public let collections: [Collection] | ||
|
|
||
| public init(collections: [Collection]) { | ||
| self.collections = collections | ||
| } | ||
| } | ||
|
|
||
| /// The `mobile.sync.fetch` response body. Sections are optional so the shape | ||
| /// can grow collections without breaking older peers; a client ignores | ||
| /// sections it did not request and tolerates missing ones. | ||
| public struct MobileSyncFetchResponse: Codable, Equatable, Sendable { | ||
| public let epoch: String | ||
| public let workspaces: MobileSyncCollectionPayload<WorkspaceSyncRecord>? | ||
| public let groups: MobileSyncCollectionPayload<GroupSyncRecord>? | ||
|
|
||
| public init( | ||
| epoch: String, | ||
| workspaces: MobileSyncCollectionPayload<WorkspaceSyncRecord>?, | ||
| groups: MobileSyncCollectionPayload<GroupSyncRecord>? | ||
| ) { | ||
| self.epoch = epoch | ||
| self.workspaces = workspaces | ||
| self.groups = groups | ||
| } | ||
| } | ||
|
|
||
| /// One `mobile.sync.delta` event: the changes one producer tick made to one | ||
| /// collection. Applies iff the epoch matches and `from_rev <= local rev` | ||
| /// (idempotent overlap); `from_rev > local rev` is a gap the client repairs | ||
| /// with a cursor fetch. | ||
| public struct MobileSyncDeltaEvent<Record: MobileSyncRecord>: Codable, Equatable, Sendable { | ||
| public let epoch: String | ||
| public let collection: MobileSyncCollectionID | ||
| public let fromRev: UInt64 | ||
| public let toRev: UInt64 | ||
| public let records: [Record] | ||
| public let removedIDs: [String] | ||
|
|
||
| public init( | ||
| epoch: String, | ||
| collection: MobileSyncCollectionID, | ||
| fromRev: UInt64, | ||
| toRev: UInt64, | ||
| records: [Record], | ||
| removedIDs: [String] | ||
| ) { | ||
| self.epoch = epoch | ||
| self.collection = collection | ||
| self.fromRev = fromRev | ||
| self.toRev = toRev | ||
| self.records = records | ||
| self.removedIDs = removedIDs | ||
| } | ||
|
|
||
| private enum CodingKeys: String, CodingKey { | ||
| case epoch | ||
| case collection | ||
| case fromRev = "from_rev" | ||
| case toRev = "to_rev" | ||
| case records | ||
| case removedIDs = "removed_ids" | ||
| } | ||
| } | ||
|
|
||
| /// Collection discriminator decoded before choosing the typed | ||
| /// `MobileSyncDeltaEvent` record type for a `mobile.sync.delta` payload. | ||
| public struct MobileSyncDeltaEventHeader: Codable, Equatable, Sendable { | ||
| public let collection: MobileSyncCollectionID | ||
|
|
||
| public init(collection: MobileSyncCollectionID) { | ||
| self.collection = collection | ||
| } | ||
| } | ||
|
|
||
| /// JSON bridging between the typed frames and the `[String: Any]` payloads the | ||
| /// mobile RPC envelope carries. One round-trip through `JSONSerialization` per | ||
| /// frame; frames are small (changed rows only), so this stays off every hot | ||
| /// path that matters. | ||
| public enum MobileSyncFrameJSON { | ||
| public static func jsonObject(from value: some Encodable) throws -> [String: Any] { | ||
| let data = try JSONEncoder().encode(value) | ||
| guard let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { | ||
| throw MobileSyncFrameJSONError.notAnObject | ||
| } | ||
| return object | ||
| } | ||
|
|
||
| public static func decode<Value: Decodable>( | ||
| _ type: Value.Type, | ||
| fromJSONObject object: [String: Any] | ||
| ) throws -> Value { | ||
| let data = try JSONSerialization.data(withJSONObject: object) | ||
| return try JSONDecoder().decode(type, from: data) | ||
| } | ||
|
|
||
| public static func decode<Value: Decodable>( | ||
| _ type: Value.Type, | ||
| fromJSONString string: String | ||
| ) throws -> Value { | ||
| try JSONDecoder().decode(type, from: Data(string.utf8)) | ||
| } | ||
| } | ||
|
|
||
| /// Failure bridging a sync frame to or from the RPC envelope's JSON container. | ||
| public enum MobileSyncFrameJSONError: Error, Equatable, Sendable { | ||
| case notAnObject | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,161 @@ | ||
| /// Outcome of applying a sync frame to a client mirror. | ||
| public enum MobileSyncApplyResult: Equatable, Sendable { | ||
| /// The frame advanced (or re-covered) local state. | ||
| case applied | ||
| /// The frame ended at or before the local revision; nothing to do. | ||
| case staleIgnored | ||
| /// The frame starts past the local revision or belongs to another epoch; | ||
| /// the caller must repair with a cursor fetch. | ||
| case gap | ||
| } | ||
|
|
||
| /// Client-side mirror of one synced collection. | ||
| /// | ||
| /// Holds full records keyed by id plus the cursor that proves how current they | ||
| /// are. Deltas apply iff contiguous-or-overlapping within the same epoch; | ||
| /// anything else reports `.gap` and leaves state untouched so the repair fetch | ||
| /// has a stable cursor to send. Main-actor confined to match its only | ||
| /// consumer, the shell state. | ||
| @MainActor | ||
| public final class MobileSyncCollectionMirror<Record: MobileSyncRecord> { | ||
| public private(set) var epoch: String? | ||
| public private(set) var rev: UInt64 = 0 | ||
| private var recordsByID: [String: Record] = [:] | ||
|
|
||
| public init() {} | ||
|
|
||
| /// Records in presentation order: `syncSortIndex`, then id for | ||
| /// determinism when a delta lands between two rows' index updates. | ||
| public var orderedRecords: [Record] { | ||
| recordsByID.values.sorted { | ||
| ($0.syncSortIndex, $0.syncID) < ($1.syncSortIndex, $1.syncID) | ||
| } | ||
|
Comment on lines
+32
to
+35
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🚀 Performance & Scalability | 🟠 Major | 🏗️ Heavy lift Avoid sorting the full mirror on every projection read. This performs an As per path instructions, production paths over scalable user data must avoid repeated hot-path sorting. 🤖 Prompt for AI AgentsSource: Path instructions |
||
| } | ||
|
|
||
| /// Whether the mirror has adopted any state for `epoch` yet. | ||
| public var hasState: Bool { epoch != nil } | ||
|
|
||
| /// The cursor to present in a `mobile.sync.fetch`, once state exists. | ||
| public var cursor: MobileSyncCursor? { | ||
| guard let epoch else { return nil } | ||
| return MobileSyncCursor(epoch: epoch, rev: rev) | ||
| } | ||
|
|
||
| /// Applies one fetch response section. Snapshots replace state | ||
| /// unconditionally; deltas follow the same contiguity rule as events. | ||
| public func apply(payload: MobileSyncCollectionPayload<Record>, epoch payloadEpoch: String) -> MobileSyncApplyResult { | ||
| switch payload.mode { | ||
| case .snapshot: | ||
| // A same-epoch snapshot older than the cursor is a stale in-flight | ||
| // response overtaken by newer deltas; applying it would roll the | ||
| // mirror back until the next delta gaps and repairs. Ignore it. | ||
| if let epoch, epoch == payloadEpoch, payload.rev < rev { | ||
| return .staleIgnored | ||
| } | ||
| recordsByID = Dictionary( | ||
| payload.records.map { ($0.syncID, $0) }, | ||
| uniquingKeysWith: { _, last in last } | ||
| ) | ||
| epoch = payloadEpoch | ||
| rev = payload.rev | ||
| return .applied | ||
|
coderabbitai[bot] marked this conversation as resolved.
Resolved
|
||
| case .delta: | ||
| return applyChanges( | ||
| epoch: payloadEpoch, | ||
| fromRev: payload.fromRev ?? payload.rev, | ||
| toRev: payload.rev, | ||
| records: payload.records, | ||
| removedIDs: payload.removedIDs | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| /// Applies one `mobile.sync.delta` event. | ||
| public func apply(delta: MobileSyncDeltaEvent<Record>) -> MobileSyncApplyResult { | ||
| applyChanges( | ||
| epoch: delta.epoch, | ||
| fromRev: delta.fromRev, | ||
| toRev: delta.toRev, | ||
| records: delta.records, | ||
| removedIDs: delta.removedIDs | ||
| ) | ||
| } | ||
|
|
||
| private func applyChanges( | ||
| epoch changeEpoch: String, | ||
| fromRev: UInt64, | ||
| toRev: UInt64, | ||
| records: [Record], | ||
| removedIDs: [String] | ||
| ) -> MobileSyncApplyResult { | ||
| guard let epoch, epoch == changeEpoch else { return .gap } | ||
| guard fromRev <= rev else { return .gap } | ||
| guard toRev > rev else { return .staleIgnored } | ||
| // Removals first: the producer already excludes tombstones for | ||
| // currently-live ids, so within one payload an id in both lists means | ||
| // the upsert is the newer fact and must win. | ||
| for id in removedIDs { | ||
| recordsByID[id] = nil | ||
| } | ||
| for record in records { | ||
| recordsByID[record.syncID] = record | ||
| } | ||
| rev = toRev | ||
| return .applied | ||
| } | ||
|
|
||
| /// Drops all state (disconnect-forget, sign-out, Mac unpair). The next | ||
| /// fetch is a cold start. | ||
| public func reset() { | ||
| epoch = nil | ||
| rev = 0 | ||
| recordsByID = [:] | ||
| } | ||
| } | ||
|
|
||
| /// Client-side root mirror pairing the two synced collections, with the | ||
| /// cursor plumbing a `mobile.sync.fetch` round-trip needs. | ||
| @MainActor | ||
| public final class MobileStateSyncMirror { | ||
| public let workspaces = MobileSyncCollectionMirror<WorkspaceSyncRecord>() | ||
| public let groups = MobileSyncCollectionMirror<GroupSyncRecord>() | ||
|
|
||
| public init() {} | ||
|
|
||
| /// The fetch request that brings both collections current from their | ||
| /// respective cursors (snapshots on cold start). | ||
| public var fetchRequest: MobileSyncFetchRequest { | ||
| MobileSyncFetchRequest(collections: [ | ||
| MobileSyncFetchRequest.Collection( | ||
| id: .workspaces, | ||
| epoch: workspaces.cursor?.epoch, | ||
| rev: workspaces.cursor?.rev | ||
| ), | ||
| MobileSyncFetchRequest.Collection( | ||
| id: .groups, | ||
| epoch: groups.cursor?.epoch, | ||
| rev: groups.cursor?.rev | ||
| ), | ||
| ]) | ||
| } | ||
|
|
||
| /// Applies a fetch response to both collections. Returns `.gap` if either | ||
| /// section gapped (caller re-fetches), `.applied` if anything advanced. | ||
| public func apply(response: MobileSyncFetchResponse) -> MobileSyncApplyResult { | ||
| var results: [MobileSyncApplyResult] = [] | ||
| if let payload = response.workspaces { | ||
| results.append(workspaces.apply(payload: payload, epoch: response.epoch)) | ||
| } | ||
| if let payload = response.groups { | ||
| results.append(groups.apply(payload: payload, epoch: response.epoch)) | ||
| } | ||
| if results.contains(.gap) { return .gap } | ||
| if results.contains(.applied) { return .applied } | ||
| return .staleIgnored | ||
| } | ||
|
|
||
| public func reset() { | ||
| workspaces.reset() | ||
| groups.reset() | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
MobileSyncFrameJSONhas no cases and exposes onlystatic funcs — this is the static-namespace anti-pattern thecmux-no-ambient-global-staterule flags. The preferred shape is aprivate/fileprivatefile-scope helper (not exported) or, since this needs to be public, astructwith aprivate init()to prevent accidental instantiation while keeping the type system honest. As apublic enumwith no cases Swift will warn callers that exhaustive switches are trivially satisfied, and the enum form gives no semantic benefit over a namespace struct.Rule Used: Flag new ambient global state in production Swift:... (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!