instant_record 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +58 -0
  3. data/README.md +267 -61
  4. data/app/controllers/instant_record/bootstraps_controller.rb +39 -12
  5. data/app/controllers/instant_record/events_controller.rb +58 -6
  6. data/app/controllers/instant_record/files_controller.rb +116 -0
  7. data/app/controllers/instant_record/mutations_controller.rb +84 -5
  8. data/app/controllers/instant_record/native_screens_controller.rb +60 -0
  9. data/app/controllers/instant_record/records_controller.rb +86 -8
  10. data/app/controllers/instant_record/shells_controller.rb +64 -0
  11. data/app/controllers/instant_record/sync_notices_controller.rb +81 -0
  12. data/app/helpers/instant_record/sync_notices_helper.rb +41 -0
  13. data/app/jobs/instant_record/shell_build_job.rb +16 -0
  14. data/app/models/instant_record/change.rb +36 -3
  15. data/app/models/instant_record/mutation_applier.rb +633 -50
  16. data/app/views/instant_record/sync_notices/_notices.html.erb +63 -0
  17. data/compiled/README.md +272 -0
  18. data/compiled/pipeline/browser_migrations.rb +18 -0
  19. data/compiled/pipeline/build.rb +13 -0
  20. data/compiled/pipeline/build_native.rb +14 -0
  21. data/compiled/pipeline/native/host.c +78 -0
  22. data/compiled/pipeline/native/instant_record_native.h +57 -0
  23. data/compiled/pipeline/native_shim.c +149 -0
  24. data/compiled/pipeline/reactor_shim.c +66 -0
  25. data/compiled/pipeline/sqlite/rh_shim.c +5 -0
  26. data/compiled/pipeline/sqlite_release.rb +43 -0
  27. data/compiled/toolchain.env.example +22 -0
  28. data/compiled/web/index.html +20 -0
  29. data/compiled/web/package-lock.json +884 -0
  30. data/compiled/web/package.json +17 -0
  31. data/compiled/web/src/app-host-core.js +556 -0
  32. data/compiled/web/src/app-host.js +16 -0
  33. data/compiled/web/src/branch-manager.js +140 -0
  34. data/compiled/web/src/branch-preview.js +397 -0
  35. data/compiled/web/src/changes.js +191 -0
  36. data/compiled/web/src/faults.js +172 -0
  37. data/compiled/web/src/flight-recorder.js +347 -0
  38. data/compiled/web/src/history-fill.js +68 -0
  39. data/compiled/web/src/http-headers.js +100 -0
  40. data/compiled/web/src/leader-election.js +705 -0
  41. data/compiled/web/src/main.js +608 -0
  42. data/compiled/web/src/manifest.js +112 -0
  43. data/compiled/web/src/opfs-wasi-core.js +109 -0
  44. data/compiled/web/src/opfs-wasi-file.js +8 -0
  45. data/compiled/web/src/reactor-runtime.js +1692 -0
  46. data/compiled/web/src/redactor.js +518 -0
  47. data/compiled/web/src/release-updates.js +48 -0
  48. data/compiled/web/src/replay.js +338 -0
  49. data/compiled/web/src/schema-recovery.js +204 -0
  50. data/compiled/web/src/server-request.js +68 -0
  51. data/compiled/web/src/sha256.js +98 -0
  52. data/compiled/web/src/shell.js +52 -0
  53. data/compiled/web/src/snapshot-store.js +38 -0
  54. data/compiled/web/src/sqlite-redactor.js +111 -0
  55. data/compiled/web/src/storage-backend.js +159 -0
  56. data/compiled/web/src/stream-leader.js +675 -0
  57. data/compiled/web/src/sync-context.js +91 -0
  58. data/compiled/web/src/sync-drain.js +104 -0
  59. data/compiled/web/src/sync-schedule.js +9 -0
  60. data/compiled/web/src/wasi-minimal.js +275 -0
  61. data/compiled/web/src/worker.js +39 -0
  62. data/compiled/web/vite.config.js +27 -0
  63. data/config/routes.rb +25 -0
  64. data/db/migrate/20261119000201_add_scope_to_instant_record_changes.rb +7 -0
  65. data/db/migrate/20261121000001_create_instant_record_sync_notices.rb +21 -0
  66. data/db/migrate/20261121000101_add_partition_to_instant_record_changes.rb +8 -0
  67. data/db/migrate/20261121230300_add_delay_line_to_instant_record_outbox.rb +10 -0
  68. data/exe/instant_record_mcp +6 -0
  69. data/frontend/LiveList.js +67 -0
  70. data/frontend/chord.js +79 -0
  71. data/frontend/file.js +65 -0
  72. data/frontend/files.js +738 -0
  73. data/frontend/focus.js +10 -0
  74. data/frontend/held.js +192 -0
  75. data/frontend/http.js +76 -0
  76. data/frontend/index.js +53 -0
  77. data/frontend/keyboard.js +56 -0
  78. data/frontend/live.js +298 -0
  79. data/frontend/notices.js +118 -0
  80. data/frontend/package.json +15 -0
  81. data/frontend/range.js +10 -0
  82. data/frontend/selection.js +47 -0
  83. data/frontend/shortcuts.js +25 -0
  84. data/frontend/sync-notices.js +130 -0
  85. data/frontend/undo.js +48 -0
  86. data/frontend/window.js +181 -0
  87. data/lib/generators/instant_record/install/install_generator.rb +18 -30
  88. data/lib/generators/instant_record/install/templates/instant_record.rb +34 -0
  89. data/lib/generators/instant_record/ios/ios_generator.rb +71 -0
  90. data/lib/generators/instant_record/ios/templates/App.swift.tt +35 -0
  91. data/lib/generators/instant_record/ios/templates/Info.plist +11 -0
  92. data/lib/generators/instant_record/ios/templates/LibraryEngine.swift +30 -0
  93. data/lib/instant_record/branch/sqlite_store.rb +142 -0
  94. data/lib/instant_record/branch.rb +388 -0
  95. data/lib/instant_record/client/notifier.rb +8 -12
  96. data/lib/instant_record/client/rebaser.rb +565 -0
  97. data/lib/instant_record/client/transport.rb +64 -42
  98. data/lib/instant_record/client.rb +1600 -169
  99. data/lib/instant_record/compiled_site.rb +85 -0
  100. data/lib/instant_record/compiler/app_stage.rb +212 -0
  101. data/lib/instant_record/compiler/ast_lowerer.rb +659 -0
  102. data/lib/instant_record/compiler/browser_migrations.rb +161 -0
  103. data/lib/instant_record/compiler/entry_builder.rb +832 -0
  104. data/lib/instant_record/compiler/fts5_smoke.rb +205 -0
  105. data/lib/instant_record/compiler/gem_vendor.rb +194 -0
  106. data/lib/instant_record/compiler/host_adapters.rb +506 -0
  107. data/lib/instant_record/compiler/kotlin_codegen.rb +209 -0
  108. data/lib/instant_record/compiler/manifest.rb +178 -0
  109. data/lib/instant_record/compiler/native_build.rb +586 -0
  110. data/lib/instant_record/compiler/native_contracts.rb +338 -0
  111. data/lib/instant_record/compiler/path_scrubber.rb +31 -0
  112. data/lib/instant_record/compiler/reachability_tracer.rb +1188 -0
  113. data/lib/instant_record/compiler/route_analyzer.rb +623 -0
  114. data/lib/instant_record/compiler/runner.rb +42 -0
  115. data/lib/instant_record/compiler/schema_lock.rb +606 -0
  116. data/lib/instant_record/compiler/source_pages.rb +77 -0
  117. data/lib/instant_record/compiler/static_linter.rb +770 -0
  118. data/lib/instant_record/compiler/swift_codegen.rb +341 -0
  119. data/lib/instant_record/compiler/toolchain.rb +219 -0
  120. data/lib/instant_record/compiler/wasm_build.rb +704 -0
  121. data/lib/instant_record/compiler/wasm_tree.rb +518 -0
  122. data/lib/instant_record/compiler.rb +277 -0
  123. data/lib/instant_record/configuration.rb +104 -0
  124. data/lib/instant_record/engine.rb +68 -18
  125. data/lib/instant_record/file_store.rb +162 -0
  126. data/lib/instant_record/files.rb +92 -0
  127. data/lib/instant_record/hlc.rb +387 -0
  128. data/lib/instant_record/host.rb +66 -0
  129. data/lib/instant_record/inertia/renderer.rb +52 -0
  130. data/lib/instant_record/inertia.rb +222 -0
  131. data/lib/instant_record/mcp/cli.rb +319 -0
  132. data/lib/instant_record/mcp/host_process.rb +229 -0
  133. data/lib/instant_record/mcp/http_exchange.rb +233 -0
  134. data/lib/instant_record/mcp/replica.rb +556 -0
  135. data/lib/instant_record/mcp/runtime.rb +406 -0
  136. data/lib/instant_record/mcp/server.rb +429 -0
  137. data/lib/instant_record/mcp.rb +47 -0
  138. data/lib/instant_record/native/contract.rb +367 -0
  139. data/lib/instant_record/native/node.rb +125 -0
  140. data/lib/instant_record/native/screen.rb +366 -0
  141. data/lib/instant_record/native/xcode_project.rb +344 -0
  142. data/lib/instant_record/native.rb +41 -0
  143. data/lib/instant_record/outbox_mutation.rb +81 -9
  144. data/lib/instant_record/outbox_upcaster.rb +161 -0
  145. data/lib/instant_record/read_tracker.rb +610 -0
  146. data/lib/instant_record/routing.rb +33 -0
  147. data/lib/instant_record/runtime_scoped.rb +4 -0
  148. data/lib/instant_record/shell.rb +486 -0
  149. data/lib/instant_record/sync_actions.rb +800 -0
  150. data/lib/instant_record/sync_metadata.rb +17 -2
  151. data/lib/instant_record/sync_notice.rb +234 -0
  152. data/lib/instant_record/sync_partition.rb +63 -0
  153. data/lib/instant_record/sync_scope.rb +300 -0
  154. data/lib/instant_record/sync_shape.rb +102 -0
  155. data/lib/instant_record/sync_window.rb +92 -15
  156. data/lib/instant_record/syncable.rb +313 -17
  157. data/lib/instant_record/testing/authoritative_server.rb +547 -0
  158. data/lib/instant_record/testing/chaos_simulator.rb +429 -0
  159. data/lib/instant_record/testing/cruby_host_bridge.rb +370 -0
  160. data/lib/instant_record/testing/fault_network.rb +140 -0
  161. data/lib/instant_record/testing/parity_suite.rb +435 -0
  162. data/lib/instant_record/testing/runtimes/base.rb +184 -0
  163. data/lib/instant_record/testing/runtimes/cruby_runtime.rb +255 -0
  164. data/lib/instant_record/testing/runtimes/native_runtime.rb +346 -0
  165. data/lib/instant_record/testing/runtimes/wasm_runtime.rb +371 -0
  166. data/lib/instant_record/testing/wasm_host_bridge.mjs +240 -0
  167. data/lib/instant_record/testing.rb +333 -0
  168. data/lib/instant_record/trace/redactor.rb +278 -0
  169. data/lib/instant_record/trace/replayer.rb +126 -0
  170. data/lib/instant_record/trace/schema_extractor.rb +37 -0
  171. data/lib/instant_record/trace.rb +22 -0
  172. data/lib/instant_record/version.rb +1 -1
  173. data/lib/instant_record.rb +107 -37
  174. data/lib/tasks/instant_record.rake +299 -47
  175. data/native/ios/InstantRecordNative/Package.swift +12 -0
  176. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/AppHost.swift +706 -0
  177. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Engine.swift +64 -0
  178. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/FileStore.swift +1048 -0
  179. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/HTTPEngine.swift +36 -0
  180. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Icons.swift +19 -0
  181. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Node.swift +64 -0
  182. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/ScreenView.swift +481 -0
  183. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Screens.swift +94 -0
  184. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/StreamClient.swift +74 -0
  185. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncNotice.swift +282 -0
  186. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncSchedule.swift +153 -0
  187. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Theme.swift +140 -0
  188. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Transport.swift +108 -0
  189. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/TypedContracts.swift +237 -0
  190. data/native/ios/README.md +341 -0
  191. data/sig/instant_record/inertia.rbs +47 -0
  192. data/sig/instant_record/native.rbs +38 -0
  193. metadata +194 -18
  194. data/lib/generators/instant_record/install/templates/database.js +0 -32
  195. data/lib/generators/instant_record/install/templates/index.html +0 -69
  196. data/lib/generators/instant_record/install/templates/rails.sw.js +0 -750
  197. data/lib/instant_record/local_schema.rb +0 -75
  198. data/lib/instant_record/pglite_compat.rb +0 -40
@@ -0,0 +1,94 @@
1
+ import SwiftUI
2
+
3
+ /// Views written in SwiftUI by hand, for a screen that asks for one by name:
4
+ ///
5
+ /// # Ruby // Swift, once at launch
6
+ /// swift "ConversationView" do var views = Screens()
7
+ /// prop "subject", message.subject views.register("ConversationView") { props, actions in
8
+ /// flag "archived", archived? ConversationView(props: props, actions: actions)
9
+ /// end }
10
+ ///
11
+ /// The app fills one and hands it to its `AppHost`. The renderer looks the
12
+ /// name up when it meets the element. This package knows none of the views.
13
+ public struct Screens {
14
+ private var views: [String: (Props, Actions) -> AnyView] = [:]
15
+
16
+ public init() {}
17
+
18
+ public mutating func register<Content: View>(_ name: String, @ViewBuilder _ view: @escaping (Props, Actions) -> Content) {
19
+ views[name] = { AnyView(view($0, $1)) }
20
+ }
21
+
22
+ func view(_ name: String, _ props: Props, _ actions: Actions) -> AnyView? {
23
+ views[name]?(props, actions)
24
+ }
25
+ }
26
+
27
+ /// What a Ruby screen handed a Swift view: values by name, each the kind the
28
+ /// screen said it was, and lists of records that are themselves Props. A
29
+ /// prop that was not sent reads as empty, false, zero or nil.
30
+ ///
31
+ /// props["subject"] // from `prop`
32
+ /// props.bool("archived") // from `flag`
33
+ /// props.int("unread") // from `number`
34
+ /// props.date("sent") // from `time`
35
+ /// props.list("messages").map { $0["author"] }
36
+ public struct Props: Equatable {
37
+ struct Value: Equatable {
38
+ let type: String
39
+ let text: String
40
+ }
41
+
42
+ let values: [String: Value]
43
+ let nestedObjects: [String: Props]
44
+ let lists: [String: [Props]]
45
+ let scalarLists: [String: [Value]]
46
+
47
+ public init(_ node: Node) {
48
+ values = Dictionary(node.children(of: "prop").map { ($0.prop("name"), Value(type: $0.prop("type"), text: $0.text)) }) { $1 }
49
+ nestedObjects = Dictionary(
50
+ node.children(of: "record")
51
+ .filter { !$0.prop("name").isEmpty }
52
+ .map { ($0.prop("name"), Props($0)) }
53
+ ) { $1 }
54
+
55
+ var recordLists: [String: [Props]] = [:]
56
+ var valueLists: [String: [Value]] = [:]
57
+ for listNode in node.children(of: "props") {
58
+ let name = listNode.prop("name")
59
+ let propItems = listNode.children(of: "prop")
60
+ if !propItems.isEmpty && listNode.children(of: "record").isEmpty {
61
+ valueLists[name] = propItems.map { Value(type: $0.prop("type"), text: $0.text) }
62
+ } else {
63
+ recordLists[name] = listNode.children(of: "record").map(Props.init)
64
+ }
65
+ }
66
+ lists = recordLists
67
+ scalarLists = valueLists
68
+ }
69
+
70
+ public subscript(name: String) -> String { values[name]?.text ?? "" }
71
+ public func bool(_ name: String) -> Bool { value(name, "bool") == "true" }
72
+ public func int(_ name: String) -> Int { Int(value(name, "int") ?? "") ?? 0 }
73
+ public func double(_ name: String) -> Double { Double(value(name, "float") ?? "") ?? 0 }
74
+ public func date(_ name: String) -> Date? { value(name, "date").flatMap(Moment.date) }
75
+ public func nested(_ name: String) -> Props? { nestedObjects[name] }
76
+ public func list(_ name: String) -> [Props] { lists[name] ?? [] }
77
+
78
+ // A value read as another kind than the screen sent is not there.
79
+ private func value(_ name: String, _ type: String) -> String? {
80
+ values[name].flatMap { $0.type == type ? $0.text : nil }
81
+ }
82
+ }
83
+
84
+ /// How a Swift view sends a tap back to the Ruby screen that drew it. It
85
+ /// takes the same road as a tap on a Ruby-drawn button: the screen performs
86
+ /// it, the screens are drawn again, and the write syncs.
87
+ public struct Actions {
88
+ let host: AppHost
89
+ let route: Route
90
+
91
+ public func perform(_ action: String, _ args: [String: String] = [:], values: [String: String] = [:]) {
92
+ host.perform(action, args: args, values: values, on: route)
93
+ }
94
+ }
@@ -0,0 +1,74 @@
1
+ import Foundation
2
+
3
+ /// Follows the server's events while the app is in front, so a change made
4
+ /// elsewhere shows without a touch. It asks `<endpoint>/events?after=<cursor>`
5
+ /// and hands each event to the app as it arrives. A server that answers with
6
+ /// what it has and closes is asked again a second later. One that holds the
7
+ /// connection delivers as it goes. Only a failed request waits longer: five
8
+ /// seconds, then twice that, up to a minute.
9
+ final class StreamClient {
10
+ private let transport: Transport
11
+ private let address: () async -> (address: String, store: AppHost.Store)?
12
+ private let feed: (String, AppHost.Store) async -> Void
13
+ private let session: URLSession
14
+ private var task: Task<Void, Never>?
15
+
16
+ /// `address` is where to ask from the app's present cursor and the
17
+ /// database that address belongs to, or nil while there is nothing to
18
+ /// follow. `feed` takes one event's text and that same database, so an
19
+ /// event that arrives after the app has moved to another is not given to it.
20
+ init(transport: Transport, address: @escaping () async -> (address: String, store: AppHost.Store)?, feed: @escaping (String, AppHost.Store) async -> Void) {
21
+ self.transport = transport
22
+ self.address = address
23
+ self.feed = feed
24
+ // A held stream is quiet between events, so it gets longer than a request does.
25
+ let configuration = URLSessionConfiguration.ephemeral
26
+ configuration.timeoutIntervalForRequest = 90
27
+ session = URLSession(configuration: configuration)
28
+ }
29
+
30
+ func start() {
31
+ guard task == nil else { return }
32
+ task = Task { [weak self] in await self?.follow() }
33
+ }
34
+
35
+ func stop() {
36
+ task?.cancel()
37
+ task = nil
38
+ }
39
+
40
+ private func follow() async {
41
+ var wait: UInt64 = 5
42
+ while !Task.isCancelled {
43
+ do {
44
+ guard let (address, store) = await address() else {
45
+ try await Task.sleep(nanoseconds: 1_000_000_000)
46
+ continue
47
+ }
48
+ let headerBlock = store.headers.isEmpty ? "" : store.headers.sorted { $0.key < $1.key }.map { "\($0.key): \($0.value)" }.joined(separator: "\n") + "\n\n"
49
+ guard let request = transport.request("GET " + address + "\n" + headerBlock) else {
50
+ try await Task.sleep(nanoseconds: 1_000_000_000)
51
+ continue
52
+ }
53
+ let (bytes, response) = try await session.bytes(for: request)
54
+ guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else { throw URLError(.badServerResponse) }
55
+ var event: [UInt8] = []
56
+ for try await byte in bytes {
57
+ event.append(byte)
58
+ if event.count >= 2, event[event.count - 1] == 10, event[event.count - 2] == 10 {
59
+ await feed(String(decoding: event, as: UTF8.self), store)
60
+ event = []
61
+ }
62
+ }
63
+ wait = 5
64
+ try await Task.sleep(nanoseconds: 1_000_000_000)
65
+ } catch is CancellationError {
66
+ return
67
+ } catch {
68
+ if Task.isCancelled { return }
69
+ try? await Task.sleep(nanoseconds: wait * 1_000_000_000)
70
+ wait = min(wait * 2, 60)
71
+ }
72
+ }
73
+ }
74
+ }
@@ -0,0 +1,282 @@
1
+ import Foundation
2
+ import SwiftUI
3
+
4
+ /// A quarantined offline write that the server rejected or last-write-wins
5
+ /// overwrote. Kept in the local SQLite ledger until the user retries it, forks
6
+ /// it as a new record, or dismisses it.
7
+ public struct SyncNotice: Identifiable, Equatable, Decodable {
8
+ public struct FieldDiff: Identifiable, Equatable {
9
+ public var id: String { field }
10
+ public let field: String
11
+ public let localValue: String?
12
+ public let serverValue: String?
13
+
14
+ public init(field: String, localValue: String?, serverValue: String?) {
15
+ self.field = field
16
+ self.localValue = localValue
17
+ self.serverValue = serverValue
18
+ }
19
+ }
20
+
21
+ public let id: String
22
+ public let mutationId: String
23
+ public let kind: String
24
+ public let recordType: String
25
+ public let recordId: String
26
+ public let operation: String
27
+ public let reason: String
28
+ public let attemptedChanges: [String: String]
29
+ public let serverAttributes: [String: String]
30
+ public let serverVersion: Int
31
+ public let createdAt: String?
32
+
33
+ public var isConflict: Bool { kind == "conflict" }
34
+ public var isRejected: Bool { kind == "rejected" }
35
+
36
+ private static let bookkeepingColumns: Set<String> = [
37
+ "id", "server_version", "sync_state", "created_at", "updated_at",
38
+ ]
39
+
40
+ public init(
41
+ id: String,
42
+ mutationId: String = "",
43
+ kind: String,
44
+ recordType: String,
45
+ recordId: String,
46
+ operation: String,
47
+ reason: String,
48
+ attemptedChanges: [String: String] = [:],
49
+ serverAttributes: [String: String] = [:],
50
+ serverVersion: Int = 0,
51
+ createdAt: String? = nil
52
+ ) {
53
+ self.id = id
54
+ self.mutationId = mutationId
55
+ self.kind = kind
56
+ self.recordType = recordType
57
+ self.recordId = recordId
58
+ self.operation = operation
59
+ self.reason = reason
60
+ self.attemptedChanges = attemptedChanges
61
+ self.serverAttributes = serverAttributes
62
+ self.serverVersion = serverVersion
63
+ self.createdAt = createdAt
64
+ }
65
+
66
+ enum CodingKeys: String, CodingKey {
67
+ case id
68
+ case mutationId = "mutation_id"
69
+ case kind
70
+ case recordType = "record_type"
71
+ case recordId = "record_id"
72
+ case operation
73
+ case reason
74
+ case attemptedChanges = "attempted_changes"
75
+ case serverAttributes = "server_attributes"
76
+ case serverVersion = "server_version"
77
+ case createdAt = "created_at"
78
+ }
79
+
80
+ public init(from decoder: Decoder) throws {
81
+ let container = try decoder.container(keyedBy: CodingKeys.self)
82
+ id = try container.decode(String.self, forKey: .id)
83
+ mutationId = try container.decodeIfPresent(String.self, forKey: .mutationId) ?? ""
84
+ kind = try container.decode(String.self, forKey: .kind)
85
+ recordType = try container.decode(String.self, forKey: .recordType)
86
+ recordId = try container.decode(String.self, forKey: .recordId)
87
+ operation = try container.decode(String.self, forKey: .operation)
88
+ reason = try container.decodeIfPresent(String.self, forKey: .reason) ?? ""
89
+ attemptedChanges = Self.decodeStringMap(from: container, forKey: .attemptedChanges)
90
+ serverAttributes = Self.decodeStringMap(from: container, forKey: .serverAttributes)
91
+ serverVersion = try container.decodeIfPresent(Int.self, forKey: .serverVersion) ?? 0
92
+ createdAt = try container.decodeIfPresent(String.self, forKey: .createdAt)
93
+ }
94
+
95
+ /// Field-level differences between attempted local values and the winning
96
+ /// server attributes, omitting gem bookkeeping columns.
97
+ public var fieldDiffs: [FieldDiff] {
98
+ let keys = (operation == "destroy" ? Array(serverAttributes.keys) : Array(attemptedChanges.keys))
99
+ .filter { !Self.bookkeepingColumns.contains($0) }
100
+ .sorted()
101
+
102
+ return keys.compactMap { field in
103
+ let local = operation == "destroy" ? nil : attemptedChanges[field]
104
+ let server = serverAttributes[field]
105
+ if !serverAttributes.isEmpty, local == server { return nil }
106
+ return FieldDiff(field: field, localValue: local, serverValue: server)
107
+ }
108
+ }
109
+
110
+ private static func decodeStringMap(from container: KeyedDecodingContainer<CodingKeys>, forKey key: CodingKeys) -> [String: String] {
111
+ guard let raw = try? container.decodeIfPresent([String: JSONValue].self, forKey: key) else { return [:] }
112
+ var out: [String: String] = [:]
113
+ for (name, value) in raw {
114
+ if let text = value.displayString { out[name] = text }
115
+ }
116
+ return out
117
+ }
118
+ }
119
+
120
+ private enum JSONValue: Decodable {
121
+ case string(String)
122
+ case int(Int)
123
+ case double(Double)
124
+ case bool(Bool)
125
+ case null
126
+
127
+ init(from decoder: Decoder) throws {
128
+ let single = try decoder.singleValueContainer()
129
+ if single.decodeNil() {
130
+ self = .null
131
+ } else if let bool = try? single.decode(Bool.self) {
132
+ self = .bool(bool)
133
+ } else if let int = try? single.decode(Int.self) {
134
+ self = .int(int)
135
+ } else if let double = try? single.decode(Double.self) {
136
+ self = .double(double)
137
+ } else if let string = try? single.decode(String.self) {
138
+ self = .string(string)
139
+ } else {
140
+ self = .null
141
+ }
142
+ }
143
+
144
+ var displayString: String? {
145
+ switch self {
146
+ case .string(let value): value
147
+ case .int(let value): String(value)
148
+ case .double(let value): String(value)
149
+ case .bool(let value): value ? "true" : "false"
150
+ case .null: nil
151
+ }
152
+ }
153
+ }
154
+
155
+ /// Parses `ir_notice()` output: `"records_changed"`, optional `"Type:id"` lines,
156
+ /// and optional `"sync_notice:<json>"` lines.
157
+ enum NoticeSignal {
158
+ struct Parsed: Equatable {
159
+ let recordsChanged: Bool
160
+ let syncNotices: [SyncNotice]
161
+ }
162
+
163
+ private static let prefix = "sync_notice:"
164
+
165
+ static func parse(_ raw: String) -> Parsed {
166
+ guard raw.hasPrefix("records_changed") else {
167
+ return Parsed(recordsChanged: false, syncNotices: [])
168
+ }
169
+ let decoder = JSONDecoder()
170
+ var found: [SyncNotice] = []
171
+ for line in raw.split(separator: "\n", omittingEmptySubsequences: true).dropFirst() {
172
+ guard line.hasPrefix(prefix) else { continue }
173
+ let json = String(line.dropFirst(prefix.count))
174
+ if let notice = try? decoder.decode(SyncNotice.self, from: Data(json.utf8)) {
175
+ found.append(notice)
176
+ }
177
+ }
178
+ return Parsed(recordsChanged: true, syncNotices: found)
179
+ }
180
+ }
181
+
182
+ struct SyncNoticesResponse: Decodable {
183
+ let ok: Bool
184
+ let error: String?
185
+ let recordId: String?
186
+ let notices: [SyncNotice]?
187
+
188
+ enum CodingKeys: String, CodingKey {
189
+ case ok, error, notices
190
+ case recordId = "record_id"
191
+ }
192
+ }
193
+
194
+ /// Modal sheet letting the user inspect quarantined offline writes and choose
195
+ /// to retry them, fork them as new records, or dismiss them.
196
+ struct SyncNoticesSheet: View {
197
+ @ObservedObject var host: AppHost
198
+ let theme: Theme
199
+ @Environment(\.dismiss) private var dismiss
200
+
201
+ var body: some View {
202
+ NavigationStack {
203
+ Group {
204
+ if host.notices.isEmpty {
205
+ Text("No sync conflicts or rejections.")
206
+ .font(.body)
207
+ .fontDesign(theme.ui)
208
+ .foregroundStyle(theme.muted)
209
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
210
+ } else {
211
+ List(host.notices) { notice in
212
+ VStack(alignment: .leading, spacing: 8) {
213
+ HStack(spacing: 6) {
214
+ Text(notice.isConflict ? "Conflict" : "Rejected")
215
+ .font(.caption.weight(.semibold))
216
+ .padding(.horizontal, 6)
217
+ .padding(.vertical, 2)
218
+ .background((notice.isConflict ? Color.orange : Color.red).opacity(0.18), in: Capsule())
219
+ .foregroundStyle(notice.isConflict ? Color.orange : Color.red)
220
+ Text("\(notice.recordType) (\(notice.operation))")
221
+ .font(.headline)
222
+ .fontDesign(theme.ui)
223
+ .foregroundStyle(theme.ink)
224
+ }
225
+
226
+ if !notice.reason.isEmpty {
227
+ Text(notice.reason)
228
+ .font(.subheadline)
229
+ .fontDesign(theme.ui)
230
+ .foregroundStyle(theme.muted)
231
+ }
232
+
233
+ if !notice.fieldDiffs.isEmpty {
234
+ VStack(alignment: .leading, spacing: 4) {
235
+ ForEach(notice.fieldDiffs) { diff in
236
+ VStack(alignment: .leading, spacing: 2) {
237
+ Text(diff.field)
238
+ .font(.caption.weight(.medium))
239
+ .foregroundStyle(theme.muted)
240
+ Text("Yours: \(diff.localValue ?? "(removed)")")
241
+ .font(.caption)
242
+ .foregroundStyle(theme.ink)
243
+ if let server = diff.serverValue {
244
+ Text("Server: \(server)")
245
+ .font(.caption)
246
+ .foregroundStyle(theme.muted)
247
+ }
248
+ }
249
+ }
250
+ }
251
+ .padding(.vertical, 2)
252
+ }
253
+
254
+ HStack(spacing: 12) {
255
+ Button("Retry") { host.retryNotice(notice.id) }
256
+ .buttonStyle(.borderedProminent)
257
+ .accessibilityIdentifier("notice-retry-\(notice.id)")
258
+ Button("Fork as New") { host.forkNotice(notice.id) }
259
+ .buttonStyle(.bordered)
260
+ .accessibilityIdentifier("notice-fork-\(notice.id)")
261
+ Button("Dismiss", role: .destructive) { host.dismissNotice(notice.id) }
262
+ .buttonStyle(.borderless)
263
+ .accessibilityIdentifier("notice-dismiss-\(notice.id)")
264
+ }
265
+ .font(.footnote)
266
+ .fontDesign(theme.ui)
267
+ }
268
+ .padding(.vertical, 4)
269
+ }
270
+ }
271
+ }
272
+ .navigationTitle("Sync Notices")
273
+ .toolbar {
274
+ ToolbarItem(placement: .confirmationAction) {
275
+ Button("Done") { dismiss() }
276
+ }
277
+ }
278
+ }
279
+ .tint(theme.tint)
280
+ .environment(\.theme, theme)
281
+ }
282
+ }
@@ -0,0 +1,153 @@
1
+ import Foundation
2
+ import Network
3
+
4
+ /// Something that can run a block later and take it back.
5
+ public protocol Timekeeper {
6
+ func after(_ seconds: TimeInterval, _ block: @escaping () -> Void) -> () -> Void
7
+ }
8
+
9
+ /// The main queue's clock.
10
+ public struct MainClock: Timekeeper {
11
+ public init() {}
12
+
13
+ public func after(_ seconds: TimeInterval, _ block: @escaping () -> Void) -> () -> Void {
14
+ let item = DispatchWorkItem(block: block)
15
+ DispatchQueue.main.asyncAfter(deadline: .now() + seconds, execute: item)
16
+ return { item.cancel() }
17
+ }
18
+ }
19
+
20
+ /// Tells when the network comes back.
21
+ public protocol Reachability {
22
+ func watch(_ reachable: @escaping () -> Void)
23
+ }
24
+
25
+ /// The system's network path. It calls back on the main queue each time the
26
+ /// path becomes usable.
27
+ public final class NetworkPath: Reachability {
28
+ private let monitor = NWPathMonitor()
29
+
30
+ public init() {}
31
+
32
+ public func watch(_ reachable: @escaping () -> Void) {
33
+ monitor.pathUpdateHandler = { path in
34
+ if path.status == .satisfied { DispatchQueue.main.async(execute: reachable) }
35
+ }
36
+ monitor.start(queue: DispatchQueue(label: "instant-record-path"))
37
+ }
38
+ }
39
+
40
+ /// Decides when the app syncs, so that nothing else has to.
41
+ ///
42
+ /// - Requests made close together run as one pass.
43
+ /// - A pass that failed, or left writes waiting, is tried again: after
44
+ /// `retry` seconds, then twice that, up to `ceiling`.
45
+ /// - With `poll` above zero a pass also runs that often while the app is in
46
+ /// front. An app that follows the server's events (StreamClient) leaves
47
+ /// it at zero.
48
+ ///
49
+ /// It is used from the main thread only. `run` starts a pass, and the pass
50
+ /// reports back through `finished`.
51
+ public final class SyncSchedule {
52
+ public struct Pace {
53
+ public var delay: TimeInterval
54
+ public var retry: TimeInterval
55
+ public var ceiling: TimeInterval
56
+ public var poll: TimeInterval
57
+
58
+ public init(delay: TimeInterval = 0.3, retry: TimeInterval = 5, ceiling: TimeInterval = 60, poll: TimeInterval = 0) {
59
+ self.delay = delay
60
+ self.retry = retry
61
+ self.ceiling = ceiling
62
+ self.poll = poll
63
+ }
64
+ }
65
+
66
+ private let pace: Pace
67
+ private let clock: Timekeeper
68
+ private let run: () -> Void
69
+ private var cancel: (() -> Void)?
70
+ private var due: TimeInterval?
71
+ private var running = false
72
+ private var wanted = false
73
+ private var inFront = false
74
+ private var wait: TimeInterval
75
+
76
+ public init(pace: Pace = Pace(), clock: Timekeeper = MainClock(), run: @escaping () -> Void) {
77
+ self.pace = pace
78
+ self.clock = clock
79
+ self.run = run
80
+ wait = pace.retry
81
+ }
82
+
83
+ /// Something was written, or someone asked: sync soon.
84
+ public func request() {
85
+ plan(pace.delay)
86
+ }
87
+
88
+ /// Someone pulled to refresh: sync now.
89
+ public func now() {
90
+ plan(0)
91
+ }
92
+
93
+ /// The network is back: sync now, and forget how long we were waiting.
94
+ public func reachable() {
95
+ wait = pace.retry
96
+ plan(0)
97
+ }
98
+
99
+ /// The app came to the front or left it.
100
+ public func front(_ on: Bool) {
101
+ inFront = on
102
+ if on {
103
+ plan(0)
104
+ } else {
105
+ cancel?()
106
+ cancel = nil
107
+ due = nil
108
+ }
109
+ }
110
+
111
+ /// A pass ended. `ok` is false when the server could not be reached.
112
+ /// `nextRelease` is seconds until the earliest held outbox mutation matures, if any.
113
+ public func finished(ok: Bool, pending: Int, nextRelease: TimeInterval? = nil) {
114
+ running = false
115
+ // The wait starts over only when nothing is left to send. A server
116
+ // that answers but keeps refusing the writes is asked less and less often.
117
+ if ok && pending == 0 { wait = pace.retry }
118
+ if wanted {
119
+ wanted = false
120
+ plan(pace.delay)
121
+ } else if !ok || pending > 0 {
122
+ plan(wait)
123
+ wait = min(wait * 2, pace.ceiling)
124
+ } else {
125
+ var next = nextRelease.map { max(0, $0) }
126
+ if inFront, pace.poll > 0 {
127
+ next = next.map { min($0, pace.poll) } ?? pace.poll
128
+ }
129
+ if let next {
130
+ plan(next)
131
+ }
132
+ }
133
+ }
134
+
135
+ // One pass is planned at a time, and a sooner one replaces a later one.
136
+ private func plan(_ seconds: TimeInterval) {
137
+ if running {
138
+ wanted = true
139
+ return
140
+ }
141
+ if let due, due <= seconds { return }
142
+ cancel?()
143
+ due = seconds
144
+ cancel = clock.after(seconds) { [weak self] in self?.start() }
145
+ }
146
+
147
+ private func start() {
148
+ cancel = nil
149
+ due = nil
150
+ running = true
151
+ run()
152
+ }
153
+ }