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,706 @@
1
+ import Combine
2
+ import Foundation
3
+
4
+ /// Runs a compiled InstantRecord app behind its screens: boots it, keeps the
5
+ /// screens on show drawn from its local database, sends it taps and keeps it
6
+ /// in sync with the server. It knows a screen only by name and params.
7
+ ///
8
+ /// Every call into the app runs on one thread, and none of them waits for
9
+ /// the network. A sync pass asks the app what it needs, fetches that on
10
+ /// another queue, and only then hands the answers over, so a tap made
11
+ /// meanwhile is performed and drawn first.
12
+ public final class AppHost: ObservableObject {
13
+ /// Where a first screen keeps its data: the SQLite file, the sync endpoint,
14
+ /// and any per-store headers (e.g. X-Instant-Record-Partition).
15
+ public struct Store: Equatable {
16
+ public let database: String
17
+ public let endpoint: String
18
+ public let headers: [String: String]
19
+
20
+ public init(database: String, endpoint: String, headers: [String: String] = [:]) {
21
+ self.database = database
22
+ self.endpoint = endpoint
23
+ self.headers = headers
24
+ }
25
+ }
26
+
27
+ /// What the app's one line says: what went wrong with a tap or a screen,
28
+ /// then what went wrong with sync, then whether it is offline, then how
29
+ /// many changes wait.
30
+ public struct Status: Equatable {
31
+ public var pending = 0
32
+ public var offline = false
33
+ /// What a tap, an opened screen or a draw reported. It stays until it
34
+ /// is dismissed, or, for a screen that could not be drawn, until it can.
35
+ public var error = ""
36
+ /// What the last sync pass reported. The next pass that succeeds clears it.
37
+ public var syncError = ""
38
+
39
+ public var message: String? {
40
+ if !error.isEmpty { return error }
41
+ if !syncError.isEmpty { return syncError }
42
+ if offline { return "Offline. Changes will send when you are back." }
43
+ if pending > 0 { return pending == 1 ? "1 change waiting to send" : "\(pending) changes waiting to send" }
44
+ return nil
45
+ }
46
+ }
47
+
48
+ /// How a list's next page stands, by the key its `more` element gave.
49
+ public enum Paging: Equatable {
50
+ case loading, failed
51
+ }
52
+
53
+ /// The screens on show, as the app last described them.
54
+ @Published public private(set) var screens: [Route: Node] = [:]
55
+ @Published public private(set) var status = Status()
56
+ /// Quarantined offline writes the server rejected or LWW overwrote.
57
+ @Published public private(set) var notices: [SyncNotice] = []
58
+ /// True from launch until the first sync of a database that has never
59
+ /// synced has ended: there is nothing to show yet, and that is not "empty".
60
+ @Published public private(set) var fetchingFirst = false
61
+ @Published public private(set) var paging: [String: Paging] = [:]
62
+ /// What has been typed into each screen's fields and not yet sent.
63
+ @Published public var typed: [Route: [String: String]] = [:]
64
+ /// The first screen.
65
+ @Published public private(set) var root: Route
66
+ /// The screens pushed over the first one.
67
+ @Published public var path: [Route] = [] {
68
+ didSet {
69
+ // A screen pushed over the others is told it opened, before it is drawn.
70
+ if path.count == oldValue.count + 1, Array(path.dropLast()) == oldValue, let opened = path.last {
71
+ thread.run { self.act("open", [:], [:], on: opened) }
72
+ // Opening may write, as marking a message read does.
73
+ schedule.request()
74
+ }
75
+ show()
76
+ }
77
+ }
78
+ /// The screen brought up as a sheet over the others, if one is. It is
79
+ /// told it opened, like a pushed one, and forgotten once it is put away.
80
+ @Published public var sheet: Route? {
81
+ didSet {
82
+ guard sheet != oldValue else { return }
83
+ if let sheet {
84
+ thread.run { self.act("open", [:], [:], on: sheet) }
85
+ schedule.request()
86
+ }
87
+ show()
88
+ }
89
+ }
90
+ private var showing: [Route] { [root] + path + (sheet.map { [$0] } ?? []) }
91
+
92
+ /// The SwiftUI views a screen can ask for by name.
93
+ public let views: Screens
94
+ private let engine: Engine
95
+ private let store: (Route) -> Store
96
+ private let transport: Transport
97
+ private let exchange: (String) -> String
98
+ private let download: (String) -> (status: Int, data: Data)?
99
+ private let shellFingerprint: String
100
+ private let follows: Bool
101
+ private let leaveWithin: TimeInterval
102
+ private let thread = EngineThread()
103
+ private let network = DispatchQueue(label: "instant-record-network", attributes: .concurrent)
104
+ private let lock = NSLock()
105
+ private var visible: [Route]
106
+ private var schedule: SyncSchedule!
107
+ private var stream: StreamClient!
108
+ private var refreshing: [() -> Void] = []
109
+ private var inFront = false
110
+ // True while the error on show is a screen that could not be drawn.
111
+ private var undrawn = false
112
+ // Read and written on the engine's thread only.
113
+ private var open: Store?
114
+ private var prepared: [String: String]?
115
+ private var unanswered = false
116
+
117
+ /// `store` says where the first screen's data lives. It is asked again
118
+ /// when a menu item puts another screen in the first one's place.
119
+ /// `follows` is whether it follows the server's events while in front.
120
+ /// `leaveWithin` is how long writes waiting in a database may hold up
121
+ /// leaving it. `exchange` stands in for the network in tests.
122
+ public init(engine: Engine, root: Route, views: Screens = Screens(), store: @escaping (Route) -> Store,
123
+ transport: Transport = Transport(), follows: Bool = true, leaveWithin: TimeInterval = 1, exchange: ((String) -> String)? = nil,
124
+ download: ((String) -> (status: Int, data: Data)?)? = nil, shellFingerprint: String = "",
125
+ pace: SyncSchedule.Pace = SyncSchedule.Pace(), clock: Timekeeper = MainClock(), reachability: Reachability = NetworkPath()) {
126
+ self.engine = engine
127
+ self.root = root
128
+ self.views = views
129
+ self.store = store
130
+ self.transport = transport
131
+ self.follows = follows
132
+ self.leaveWithin = leaveWithin
133
+ self.exchange = exchange ?? transport.exchange
134
+ self.download = download ?? transport.download
135
+ self.shellFingerprint = shellFingerprint
136
+ visible = [root]
137
+ schedule = SyncSchedule(pace: pace, clock: clock) { [weak self] in self?.pass() }
138
+ stream = StreamClient(transport: transport, address: { [weak self] in await self?.streamAddress() }, feed: { [weak self] in await self?.feed($0, from: $1) })
139
+ reachability.watch { [weak self] in self?.schedule.reachable() }
140
+ }
141
+
142
+ /// Open the database, draw from it, then sync. The first screen does not
143
+ /// wait for the network.
144
+ public func start() {
145
+ let store = store(root)
146
+ thread.run {
147
+ // During a pass the app is answered from what was fetched for it,
148
+ // and anything else is "offline": the network is never asked here.
149
+ self.engine.onExchange { request in
150
+ if let answer = self.prepared?[request] { return answer }
151
+ self.unanswered = true
152
+ return Transport.offline
153
+ }
154
+ if self.engine.boot(database: store.database) { self.open = store } else { self.report() }
155
+ let pos = self.engine.syncs ? self.position() : [:]
156
+ let first = self.engine.syncs && pos["bootstrap"] == "needed"
157
+ DispatchQueue.main.async { self.fetchingFirst = first }
158
+ self.loadNoticesIfNeeded(from: pos)
159
+ self.draw()
160
+ }
161
+ schedule.request()
162
+ }
163
+
164
+ /// Sync soon. Requests made close together run as one pass.
165
+ public func sync() {
166
+ schedule.request()
167
+ }
168
+
169
+ /// The app came to the front, or left it. In front it syncs at once and
170
+ /// follows the server's events, which is how changes from elsewhere arrive.
171
+ public func front(_ on: Bool) {
172
+ schedule.front(on)
173
+ inFront = on
174
+ follow()
175
+ }
176
+
177
+ /// A pull on a list: sync now, and return when that pass has ended and
178
+ /// the screens have been drawn again.
179
+ @MainActor
180
+ public func refresh() async {
181
+ await withCheckedContinuation { done in
182
+ refreshing.append { done.resume() }
183
+ schedule.now()
184
+ }
185
+ }
186
+
187
+ /// A tap: the screen at `route` performs `action` with the arguments the
188
+ /// element carried and whatever is typed into the screen's fields (plus
189
+ /// any explicit `values` passed by a typed native view). The screens are
190
+ /// drawn again from the local database, and the write goes to the server
191
+ /// soon after.
192
+ public func perform(_ action: String, args: [String: String] = [:], values: [String: String] = [:], on route: Route) {
193
+ let fieldValues = typed[route] ?? [:]
194
+ let mergedValues = values.isEmpty ? fieldValues : fieldValues.merging(values) { _, explicit in explicit }
195
+ thread.run {
196
+ let performed = self.act(action, args, mergedValues, on: route)
197
+ self.draw()
198
+ // What was typed is forgotten once it has been handed over, unless
199
+ // more was typed since.
200
+ if performed, !fieldValues.isEmpty {
201
+ DispatchQueue.main.async { if self.typed[route] == fieldValues { self.typed[route] = nil } }
202
+ }
203
+ }
204
+ schedule.request()
205
+ }
206
+
207
+ /// Put another screen in the first one's place, as choosing another
208
+ /// account does. Its data may live in another database, which is opened
209
+ /// and drawn at once from what is on the phone: no network stands
210
+ /// between the tap and the rows. It syncs afterwards, as any pass does.
211
+ ///
212
+ /// Writes still waiting in the database being left get one pass first,
213
+ /// for at most `leaveWithin` seconds. Whatever comes of it the switch
214
+ /// happens, and what did not go out stays in that file until it is
215
+ /// opened again.
216
+ public func replace(with route: Route) {
217
+ let next = store(route)
218
+ thread.run {
219
+ let leaving = self.open
220
+ if leaving?.database == next.database || !self.engine.syncs {
221
+ self.open = next
222
+ return self.arrive(at: route)
223
+ }
224
+ var changed = false
225
+ let change = {
226
+ guard !changed else { return }
227
+ changed = true
228
+ if self.engine.open(database: next.database) {
229
+ self.open = next
230
+ self.arrive(at: route)
231
+ } else {
232
+ // The app has gone back to the database it had, so the
233
+ // screen stays where it was.
234
+ self.report()
235
+ }
236
+ }
237
+ guard let leaving, self.pending() > 0 else { return change() }
238
+ self.run(leaving) { _ in change() }
239
+ self.network.asyncAfter(deadline: .now() + self.leaveWithin) { self.thread.run(change) }
240
+ }
241
+ }
242
+
243
+ /// Fetch the page a `more` element stands for and hand it to the app,
244
+ /// which keeps it and says whether more lies below.
245
+ public func loadMore(_ key: String, query: String) {
246
+ guard paging[key] != .loading else { return }
247
+ paging[key] = .loading
248
+ thread.run {
249
+ guard let store = self.open else { return self.paged(key, failed: true) }
250
+ self.network.async {
251
+ let reply = Reply(self.exchange(Self.withHeaders("GET \(store.endpoint)/records?\(query)\n", store.headers)))
252
+ self.thread.run {
253
+ guard reply.ok, self.open == store else { return self.paged(key, failed: true) }
254
+ let input = (try? JSONSerialization.data(withJSONObject: ["key": key, "response": reply.body])).map { String(decoding: $0, as: UTF8.self) } ?? "{}"
255
+ let kept = self.engine.call("history", input) != nil
256
+ if !kept { self.report() }
257
+ self.draw()
258
+ self.paged(key, failed: !kept)
259
+ }
260
+ }
261
+ }
262
+ }
263
+
264
+ /// The error on show has been read.
265
+ public func dismissError() {
266
+ status.error = ""
267
+ status.syncError = ""
268
+ undrawn = false
269
+ }
270
+
271
+ /// Re-apply a quarantined local write so it queues a fresh outbox mutation.
272
+ public func retryNotice(_ id: String, overrides: [String: String] = [:]) {
273
+ resolveNotice("retry", id: id, overrides: overrides)
274
+ }
275
+
276
+ /// Fork a quarantined local write into a new record with a fresh UUID.
277
+ public func forkNotice(_ id: String, overrides: [String: String] = [:]) {
278
+ resolveNotice("fork", id: id, overrides: overrides)
279
+ }
280
+
281
+ /// Dismiss a quarantined sync notice without deleting its audit row.
282
+ public func dismissNotice(_ id: String) {
283
+ resolveNotice("dismiss", id: id, overrides: [:])
284
+ }
285
+
286
+ // Follow the server's events while in front, from the database now open.
287
+ // Called again when another database opens, which drops the request
288
+ // held for the one that was left.
289
+ private func follow() {
290
+ stream.stop()
291
+ if inFront && engine.syncs && follows { stream.start() }
292
+ }
293
+
294
+ /// Returns when everything asked of the app so far has run and its
295
+ /// results have been published. For tests.
296
+ func settle() {
297
+ for _ in 0..<3 {
298
+ thread.wait()
299
+ network.sync(flags: .barrier) {}
300
+ }
301
+ thread.wait()
302
+ if Thread.isMainThread {
303
+ RunLoop.main.run(until: Date().addingTimeInterval(0.01))
304
+ } else {
305
+ DispatchQueue.main.sync {}
306
+ }
307
+ }
308
+
309
+ private func show() {
310
+ let showing = showing
311
+ lock.withLock { visible = showing }
312
+ screens = screens.filter { showing.contains($0.key) }
313
+ typed = typed.filter { showing.contains($0.key) }
314
+ thread.run { self.draw() }
315
+ }
316
+
317
+ // The schedule starts a pass on the main thread.
318
+ private func pass() {
319
+ thread.run {
320
+ guard let store = self.open, self.engine.syncs else {
321
+ // Nothing can sync. Say the pass ended, or the schedule
322
+ // would wait for it and never start another.
323
+ return self.ended(ok: self.engine.syncs == false, pending: 0, offline: false, error: nil, nextRelease: nil)
324
+ }
325
+ self.run(store) { outcome in
326
+ self.ended(ok: outcome.ok, pending: outcome.pending, offline: outcome.offline, error: outcome.error, nextRelease: outcome.nextRelease)
327
+ // A tap between the fetch and the hand-over changed what the
328
+ // app wanted to send. It goes out with a pass of its own.
329
+ if outcome.outdated { DispatchQueue.main.async { self.schedule.request() } }
330
+ }
331
+ }
332
+ }
333
+
334
+ // Where the stream client should ask, from the app's present cursor, and
335
+ // the database that address belongs to.
336
+ private func streamAddress() async -> (address: String, store: Store)? {
337
+ await withCheckedContinuation { answer in
338
+ thread.run {
339
+ let position = self.position()
340
+ guard let store = self.open, let cursor = position["cursor"], position["bootstrap"] == "ready" else { return answer.resume(returning: nil) }
341
+ let who = (position["identity"] ?? "").isEmpty ? "" : "&identity=" + position["identity"]!
342
+ answer.resume(returning: ("\(store.endpoint)/events?after=\(cursor)\(who)", store))
343
+ }
344
+ }
345
+ }
346
+
347
+ // One event from the server, handed to the app. The screens are drawn
348
+ // again when it says records changed. An event read for a database that
349
+ // has since been left is not this one's and is dropped.
350
+ func feed(_ event: String, from store: Store) async {
351
+ await withCheckedContinuation { done in
352
+ thread.run {
353
+ guard self.open == store else { return done.resume() }
354
+ if self.engine.call("stream", event) == nil { self.report() }
355
+ let signal = NoticeSignal.parse(self.engine.notice())
356
+ if !signal.syncNotices.isEmpty { self.mergeNotices(signal.syncNotices) }
357
+ if signal.recordsChanged { self.draw() }
358
+ done.resume()
359
+ }
360
+ }
361
+ }
362
+
363
+ // Everything below runs on the engine's thread, unless it says otherwise.
364
+
365
+ private struct Outcome {
366
+ var ok = false
367
+ var pending = 0
368
+ var offline = false
369
+ var outdated = false
370
+ var error: String?
371
+ var nextRelease: TimeInterval?
372
+ }
373
+
374
+ private static let sqliteHeader = Data("SQLite format 3\0".utf8)
375
+
376
+ /// One sync pass for `store`: ask the app what it will want, fetch that
377
+ /// off this thread, then let the app sync against the answers alone.
378
+ /// When a brand-new database needs a bootstrap and carries a schema
379
+ /// fingerprint, try hydrating from a prebuilt SQLite shell via `ir_open`
380
+ /// first, falling back seamlessly to `/bootstrap` on any miss or error.
381
+ /// `then` runs on this thread when the pass has ended.
382
+ private func run(_ store: Store, allowShell: Bool = true, then: @escaping (Outcome) -> Void) {
383
+ guard let plan = engine.call("sync_plan", "").flatMap(Self.object) else {
384
+ return then(Outcome(pending: pending(), error: engine.error(), nextRelease: nextRelease()))
385
+ }
386
+ let push = (plan["push"] as? String) ?? ""
387
+ let needsBootstrap = plan["bootstrap"] as? Bool == true
388
+ let planFingerprint = (plan["fingerprint"] as? String) ?? ""
389
+ let fingerprint = planFingerprint.isEmpty ? shellFingerprint : planFingerprint
390
+ if allowShell, needsBootstrap, push.isEmpty, !fingerprint.isEmpty {
391
+ return hydrateFromShell(store, fingerprint: fingerprint, then: then)
392
+ }
393
+ let position = position()
394
+ var wanted: [String] = []
395
+ if !push.isEmpty { wanted.append("POST \(store.endpoint)/mutations\n\(push)") }
396
+ if needsBootstrap {
397
+ wanted.append("GET \(store.endpoint)/bootstrap\n")
398
+ } else {
399
+ let who = (position["identity"] ?? "").isEmpty ? "" : "&identity=" + position["identity"]!
400
+ wanted.append("GET \(store.endpoint)/events?after=\(position["cursor"] ?? "0")&window=0\(who)\n")
401
+ }
402
+ network.async {
403
+ var replies: [String: String] = [:]
404
+ var outcome = Outcome()
405
+ for request in wanted {
406
+ let answer = self.exchange(Self.withHeaders(request, store.headers))
407
+ replies[request] = answer
408
+ let reply = Reply(answer)
409
+ if reply.status == 0 {
410
+ outcome.offline = true
411
+ break
412
+ }
413
+ if !reply.ok, outcome.error == nil {
414
+ outcome.error = "Could not sync: \(request.prefix { $0 != "\n" }.replacingOccurrences(of: store.endpoint, with: "")) answered \(reply.status)"
415
+ }
416
+ }
417
+ self.thread.run {
418
+ // The database may have been changed for another while the
419
+ // answers were fetched. They are not this one's.
420
+ guard self.open == store else { return then(outcome) }
421
+ self.prepared = replies
422
+ self.unanswered = false
423
+ let synced = self.engine.call("sync", store.endpoint)
424
+ self.prepared = nil
425
+ if synced == nil { outcome.error = self.engine.error() }
426
+ let signal = NoticeSignal.parse(self.engine.notice())
427
+ if !signal.syncNotices.isEmpty { self.mergeNotices(signal.syncNotices) }
428
+ if signal.recordsChanged { self.draw() }
429
+ let state = self.position()
430
+ outcome.pending = Int(state["pending"] ?? "") ?? 0
431
+ outcome.nextRelease = Self.releaseDelay(from: state)
432
+ outcome.outdated = self.unanswered && !outcome.offline
433
+ outcome.ok = synced != nil && !outcome.offline && outcome.error == nil
434
+ then(outcome)
435
+ }
436
+ }
437
+ }
438
+
439
+ private func hydrateFromShell(_ store: Store, fingerprint: String, then: @escaping (Outcome) -> Void) {
440
+ let grantRequest = "GET \(store.endpoint)/shell?fingerprint=\(fingerprint)\n"
441
+ network.async {
442
+ let grantReply = Reply(self.exchange(grantRequest))
443
+ if grantReply.status == 0 {
444
+ return self.thread.run { then(Outcome(offline: true)) }
445
+ }
446
+ guard grantReply.status == 200,
447
+ let grant = Self.object(grantReply.body),
448
+ let filePath = grant["path"] as? String,
449
+ filePath.hasPrefix("/shell/file"),
450
+ let cursor = grant["cursor"] as? Int,
451
+ cursor >= 0,
452
+ let fetched = self.download(store.endpoint + filePath),
453
+ fetched.status == 200,
454
+ fetched.data.count >= Self.sqliteHeader.count,
455
+ fetched.data.prefix(Self.sqliteHeader.count) == Self.sqliteHeader
456
+ else {
457
+ return self.thread.run {
458
+ guard self.open == store else { return then(Outcome()) }
459
+ self.run(store, allowShell: false, then: then)
460
+ }
461
+ }
462
+ let expectedIdentity = grant["identity"] as? String ?? ""
463
+ let staged = store.database + ".shell.\(UUID().uuidString).tmp"
464
+ let stagedURL = URL(fileURLWithPath: staged)
465
+ do {
466
+ try FileManager.default.createDirectory(at: stagedURL.deletingLastPathComponent(), withIntermediateDirectories: true)
467
+ try fetched.data.write(to: stagedURL, options: .atomic)
468
+ } catch {
469
+ Self.removeSQLiteFiles(atPath: staged)
470
+ return self.thread.run {
471
+ guard self.open == store else { return then(Outcome()) }
472
+ self.run(store, allowShell: false, then: then)
473
+ }
474
+ }
475
+ self.thread.run {
476
+ guard self.open == store else {
477
+ Self.removeSQLiteFiles(atPath: staged)
478
+ return then(Outcome())
479
+ }
480
+ let current = self.position()
481
+ guard current["bootstrap"] == "needed", self.pending() == 0 else {
482
+ Self.removeSQLiteFiles(atPath: staged)
483
+ return self.run(store, allowShell: false, then: then)
484
+ }
485
+ guard self.engine.open(database: staged) else {
486
+ Self.removeSQLiteFiles(atPath: staged)
487
+ return self.run(store, allowShell: false, then: then)
488
+ }
489
+ let state = self.position()
490
+ let validCursor = state["bootstrap"] == "ready" && Int(state["cursor"] ?? "") == cursor
491
+ let validIdentity = expectedIdentity.isEmpty || state["identity"] == expectedIdentity
492
+ guard validCursor && validIdentity else {
493
+ _ = self.engine.open(database: store.database)
494
+ Self.removeSQLiteFiles(atPath: staged)
495
+ return self.run(store, allowShell: false, then: then)
496
+ }
497
+ guard self.promoteShell(staged: staged, to: store.database) else {
498
+ _ = self.engine.open(database: store.database)
499
+ Self.removeSQLiteFiles(atPath: staged)
500
+ return self.run(store, allowShell: false, then: then)
501
+ }
502
+ self.draw()
503
+ // Hydrated and drawn; schedule an immediate catch-up pass from the shell's cursor.
504
+ then(Outcome(ok: true, pending: self.pending(), offline: false, outdated: true, error: nil, nextRelease: self.nextRelease()))
505
+ }
506
+ }
507
+ }
508
+
509
+ private func promoteShell(staged: String, to target: String) -> Bool {
510
+ let fm = FileManager.default
511
+ let backup = target + ".shell-backup.\(UUID().uuidString).tmp"
512
+ let hadTarget = fm.fileExists(atPath: target)
513
+ do {
514
+ if hadTarget {
515
+ try fm.moveItem(atPath: target, toPath: backup)
516
+ for suffix in ["-wal", "-shm", "-journal"] {
517
+ try? fm.removeItem(atPath: target + suffix)
518
+ }
519
+ }
520
+ try fm.moveItem(atPath: staged, toPath: target)
521
+ guard engine.open(database: target) else {
522
+ try? fm.removeItem(atPath: target)
523
+ if hadTarget { try? fm.moveItem(atPath: backup, toPath: target) }
524
+ return false
525
+ }
526
+ Self.removeSQLiteFiles(atPath: staged)
527
+ if hadTarget { Self.removeSQLiteFiles(atPath: backup) }
528
+ return true
529
+ } catch {
530
+ if !fm.fileExists(atPath: target), hadTarget, fm.fileExists(atPath: backup) {
531
+ try? fm.moveItem(atPath: backup, toPath: target)
532
+ }
533
+ return false
534
+ }
535
+ }
536
+
537
+ private static func removeSQLiteFiles(atPath path: String) {
538
+ let fm = FileManager.default
539
+ for suffix in ["", "-wal", "-shm", "-journal"] {
540
+ try? fm.removeItem(atPath: path + suffix)
541
+ }
542
+ }
543
+
544
+ private func ended(ok: Bool, pending: Int, offline: Bool, error: String?, nextRelease: TimeInterval?) {
545
+ draw()
546
+ DispatchQueue.main.async {
547
+ self.fetchingFirst = false
548
+ self.status.pending = pending
549
+ self.status.offline = offline
550
+ if let error { self.status.syncError = error } else if ok { self.status.syncError = "" }
551
+ self.schedule.finished(ok: ok, pending: pending, nextRelease: nextRelease)
552
+ let waiting = self.refreshing
553
+ self.refreshing = []
554
+ waiting.forEach { $0() }
555
+ }
556
+ }
557
+
558
+ // The first screen changes. It is drawn here, on the engine's thread,
559
+ // from the database now open, and shown together with the change, so
560
+ // its rows are on screen before anything is fetched. Only a database
561
+ // that has never synced has nothing to show yet.
562
+ private func arrive(at route: Route) {
563
+ let drawn = engine.call("render", route.input()).flatMap { try? Node(json: $0) }
564
+ let pos = engine.syncs ? position() : [:]
565
+ let first = engine.syncs && pos["bootstrap"] == "needed"
566
+ loadNoticesIfNeeded(from: pos)
567
+ DispatchQueue.main.async {
568
+ self.root = route
569
+ if let drawn { self.screens[route] = drawn }
570
+ self.fetchingFirst = first
571
+ self.sheet = nil
572
+ self.path = []
573
+ self.follow()
574
+ self.schedule.now()
575
+ }
576
+ }
577
+
578
+ private func paged(_ key: String, failed: Bool) {
579
+ DispatchQueue.main.async { self.paging[key] = failed ? .failed : nil }
580
+ }
581
+
582
+ @discardableResult
583
+ private func act(_ action: String, _ args: [String: String], _ values: [String: String], on route: Route) -> Bool {
584
+ if engine.call("action", route.input(action: action, args: args, values: values)) != nil { return true }
585
+ report()
586
+ return false
587
+ }
588
+
589
+ /// The app's own account of where it is: cursor, pending, bootstrap, identity.
590
+ private func position() -> [String: String] {
591
+ var fields: [String: String] = [:]
592
+ for field in (engine.call("cursor", "") ?? "").split(separator: " ") {
593
+ let pair = field.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
594
+ if pair.count == 2 { fields[String(pair[0])] = String(pair[1]) }
595
+ }
596
+ return fields
597
+ }
598
+
599
+ private func pending() -> Int {
600
+ Int(position()["pending"] ?? "") ?? 0
601
+ }
602
+
603
+ private func nextRelease() -> TimeInterval? {
604
+ Self.releaseDelay(from: position())
605
+ }
606
+
607
+ private static func releaseDelay(from state: [String: String]) -> TimeInterval? {
608
+ guard let raw = state["next_release_ms"], let ms = Double(raw) else { return nil }
609
+ return max(0, ms / 1000.0)
610
+ }
611
+
612
+ // A screen that cannot be drawn keeps the last one that could, and the
613
+ // reason is shown.
614
+ private func draw() {
615
+ let routes = lock.withLock { visible }
616
+ var drawn: [Route: Node] = [:]
617
+ var problem: String?
618
+ for route in routes {
619
+ guard let json = engine.call("render", route.input()) else {
620
+ problem = engine.error()
621
+ continue
622
+ }
623
+ if let node = try? Node(json: json) { drawn[route] = node } else { problem = "The screen \(route.screen) could not be read." }
624
+ }
625
+ DispatchQueue.main.async {
626
+ let showing = self.showing
627
+ for (route, node) in drawn where showing.contains(route) && self.screens[route] != node {
628
+ self.screens[route] = node
629
+ }
630
+ if let problem {
631
+ self.status.error = problem
632
+ self.undrawn = true
633
+ } else if self.undrawn {
634
+ self.status.error = ""
635
+ self.undrawn = false
636
+ }
637
+ }
638
+ }
639
+
640
+ private func report() {
641
+ let message = engine.error()
642
+ DispatchQueue.main.async {
643
+ self.status.error = message
644
+ self.undrawn = false
645
+ }
646
+ }
647
+
648
+ private func resolveNotice(_ action: String, id: String, overrides: [String: String]) {
649
+ let payload: [String: Any] = ["action": action, "id": id, "overrides": overrides]
650
+ let input = (try? JSONSerialization.data(withJSONObject: payload)).map { String(decoding: $0, as: UTF8.self) } ?? "{}"
651
+ thread.run {
652
+ guard let raw = self.engine.call("notices", input) else {
653
+ self.report()
654
+ return
655
+ }
656
+ if let response = try? JSONDecoder().decode(SyncNoticesResponse.self, from: Data(raw.utf8)) {
657
+ DispatchQueue.main.async {
658
+ if let list = response.notices { self.notices = list }
659
+ if !response.ok, let message = response.error {
660
+ self.status.error = message
661
+ self.undrawn = false
662
+ }
663
+ }
664
+ }
665
+ self.draw()
666
+ }
667
+ if action == "retry" || action == "fork" {
668
+ schedule.request()
669
+ }
670
+ }
671
+
672
+ private func loadNoticesIfNeeded(from position: [String: String]) {
673
+ let count = Int(position["notices"] ?? "") ?? 0
674
+ guard count > 0 else {
675
+ DispatchQueue.main.async { self.notices = [] }
676
+ return
677
+ }
678
+ guard let raw = engine.call("notices", "{\"action\":\"list\"}"),
679
+ let response = try? JSONDecoder().decode(SyncNoticesResponse.self, from: Data(raw.utf8)),
680
+ let list = response.notices else { return }
681
+ DispatchQueue.main.async { self.notices = list }
682
+ }
683
+
684
+ private func mergeNotices(_ incoming: [SyncNotice]) {
685
+ DispatchQueue.main.async {
686
+ var merged = incoming
687
+ let incomingIds = Set(incoming.map(\.id))
688
+ for existing in self.notices where !incomingIds.contains(existing.id) {
689
+ merged.append(existing)
690
+ }
691
+ self.notices = merged
692
+ }
693
+ }
694
+
695
+ private static func object(_ json: String) -> [String: Any]? {
696
+ (try? JSONSerialization.jsonObject(with: Data(json.utf8))) as? [String: Any]
697
+ }
698
+
699
+ private static func withHeaders(_ request: String, _ headers: [String: String]) -> String {
700
+ guard !headers.isEmpty, let newline = request.firstIndex(of: "\n") else { return request }
701
+ let line = request[..<newline]
702
+ let body = request[request.index(after: newline)...]
703
+ let block = headers.sorted { $0.key < $1.key }.map { "\($0.key): \($0.value)" }.joined(separator: "\n")
704
+ return "\(line)\n\(block)\n\n\(body)"
705
+ }
706
+ }