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,705 @@
1
+ // Single-leader election and peer RPC coordinator per (origin, scope).
2
+ //
3
+ // One dedicated worker per (origin, scope) acquires an exclusive Web Lock
4
+ // (`navigator.locks`) and owns the OPFS FileSystemSyncAccessHandle and hot AppHost.
5
+ // Peer tabs connect as followers over a lightweight control BroadcastChannel plus a
6
+ // dedicated per-follower RPC channel (compatible with MessageChannel ports), while
7
+ // queueing on the same Web Lock so browser-automatic lock release on leader close or
8
+ // crash promotes a surviving follower immediately.
9
+
10
+ export function leaderLockName(scope) {
11
+ return "instant-record-leader" + (scope ? "/" + scope : "");
12
+ }
13
+
14
+ export function controlChannelName(scope) {
15
+ return "instant-record-leader" + (scope ? "/" + scope : "");
16
+ }
17
+
18
+ export function peerChannelName(followerId) {
19
+ return "instant-record-peer/" + followerId;
20
+ }
21
+
22
+ export function tabPresenceLockName(workerId) {
23
+ return "instant-record-tab/" + workerId;
24
+ }
25
+
26
+ export function aggregateSimulations(leaderSim, peerSims) {
27
+ const all = [leaderSim, ...peerSims].filter(Boolean);
28
+ if (all.length === 0) return { offline: false, latencyMs: 0 };
29
+ const offline = all.every(sim => !!sim.offline);
30
+ let latencyMs = 0;
31
+ for (const sim of all) {
32
+ if (typeof sim.latencyMs === "number" && sim.latencyMs > latencyMs) latencyMs = sim.latencyMs;
33
+ }
34
+ return { offline, latencyMs };
35
+ }
36
+
37
+ function defaultCreateChannel(name) {
38
+ if (typeof BroadcastChannel !== "function") return null;
39
+ return new BroadcastChannel(name);
40
+ }
41
+
42
+ function makeId() {
43
+ if (typeof globalThis.crypto?.randomUUID === "function") return globalThis.crypto.randomUUID();
44
+ return "w-" + Math.random().toString(36).slice(2) + "-" + Date.now().toString(36);
45
+ }
46
+
47
+ export function createLeaderCoordinator({
48
+ scope = "",
49
+ sourceVersion = "",
50
+ targetSchema = 0,
51
+ workerId = makeId(),
52
+ locks = globalThis.navigator?.locks,
53
+ createChannel = defaultCreateChannel,
54
+ onBecomeLeader,
55
+ onRpc,
56
+ onLeaderMessage,
57
+ onLeaderSimulationChange,
58
+ onFollowerPush,
59
+ onRoleChange,
60
+ discoveryRetryMs = 100,
61
+ pruneIntervalMs = 2000,
62
+ rpcLivenessMs = 1500,
63
+ } = {}) {
64
+ const lockName = leaderLockName(scope);
65
+ const controlName = controlChannelName(scope);
66
+
67
+ let role = "idle"; // "idle" | "leader" | "follower" | "standalone"
68
+ let closed = false;
69
+ let epoch = 0;
70
+ let storageMode = "indexeddb";
71
+
72
+ // Leader state
73
+ let releaseLeaderLock = null;
74
+ let leaderBooting = false;
75
+ let leaderReady = false;
76
+ let lastBootResult = null;
77
+ let leaderSim = { offline: false, latencyMs: 0, report: false };
78
+ let lastEffectiveSim = { offline: false, latencyMs: 0 };
79
+ const peers = new Map(); // followerId -> { port, simulation, alive }
80
+ let pruneTimer = null;
81
+
82
+ // Follower state
83
+ let controlChannel = null;
84
+ let peerChannel = null;
85
+ let releaseTabLock = null;
86
+ let activeLeaderId = null;
87
+ let activeLeaderEpoch = 0;
88
+ let attached = false;
89
+ let discoveryTimer = null;
90
+ let standbyActive = false;
91
+ let localSim = { offline: false, latencyMs: 0, report: false };
92
+ let nextRpcSeq = 1;
93
+ const pendingRpcs = new Map(); // rpcId -> { method, payload, idempotent, acked, leaderId, resolve, reject, timer }
94
+ const attachWaiters = [];
95
+
96
+ function setRole(next) {
97
+ if (role === next) return;
98
+ role = next;
99
+ onRoleChange?.(next);
100
+ }
101
+
102
+ function effectiveSimulation() {
103
+ if (role === "standalone") return { offline: !!leaderSim.offline, latencyMs: Number(leaderSim.latencyMs) || 0 };
104
+ const peerSims = [];
105
+ for (const peer of peers.values()) peerSims.push(peer.simulation);
106
+ return aggregateSimulations(leaderSim, peerSims);
107
+ }
108
+
109
+ function refreshEffectiveSimulation() {
110
+ const next = effectiveSimulation();
111
+ const prev = lastEffectiveSim;
112
+ lastEffectiveSim = next;
113
+ if (prev.offline !== next.offline || prev.latencyMs !== next.latencyMs) {
114
+ onLeaderSimulationChange?.(next, prev);
115
+ }
116
+ return next;
117
+ }
118
+
119
+ function sendControl(msg) {
120
+ try { controlChannel?.postMessage(msg); } catch {}
121
+ }
122
+
123
+ function broadcast(message, { excludeTabId = null } = {}) {
124
+ if (role !== "leader") return;
125
+ if (excludeTabId !== workerId) {
126
+ onFollowerPush?.(message);
127
+ }
128
+ if (peers.size > 0) {
129
+ sendControl({ type: "broadcast", leaderId: workerId, excludeTabId, message });
130
+ }
131
+ }
132
+
133
+ function sendToPeer(followerId, message) {
134
+ const peer = peers.get(followerId);
135
+ if (!peer) return;
136
+ try { peer.port.postMessage({ type: "push", leaderId: workerId, message }); } catch {}
137
+ }
138
+
139
+ function removePeer(followerId) {
140
+ const peer = peers.get(followerId);
141
+ if (!peer) return;
142
+ peers.delete(followerId);
143
+ try { peer.port.close(); } catch {}
144
+ refreshEffectiveSimulation();
145
+ }
146
+
147
+ async function pruneDeadPeers() {
148
+ if (role !== "leader" || peers.size === 0) return;
149
+ if (typeof locks?.query !== "function") return;
150
+ try {
151
+ const state = await locks.query();
152
+ const held = new Set((state?.held || []).map(entry => entry.name));
153
+ for (const followerId of [...peers.keys()]) {
154
+ if (!held.has(tabPresenceLockName(followerId))) {
155
+ removePeer(followerId);
156
+ }
157
+ }
158
+ } catch {
159
+ // Ignore query failures in environments that restrict locks.query().
160
+ }
161
+ }
162
+
163
+ function attachPeer(followerId, simulation, peerSourceVersion, peerTargetSchema) {
164
+ if (role !== "leader") return;
165
+ if (peerTargetSchema && targetSchema && peerTargetSchema < targetSchema) {
166
+ sendControl({ type: "release_required", leaderId: workerId, targetId: followerId });
167
+ return;
168
+ }
169
+ if (peerTargetSchema && targetSchema && peerTargetSchema > targetSchema) {
170
+ onFollowerPush?.({ type: "release_required" });
171
+ }
172
+ let peer = peers.get(followerId);
173
+ if (!peer) {
174
+ const port = createChannel(peerChannelName(followerId));
175
+ if (!port) return;
176
+ peer = { port, simulation: simulation || { offline: false, latencyMs: 0, report: false } };
177
+ port.onmessage = event => handleLeaderPeerMessage(followerId, event.data);
178
+ peers.set(followerId, peer);
179
+ } else if (simulation) {
180
+ peer.simulation = simulation;
181
+ }
182
+ refreshEffectiveSimulation();
183
+ try {
184
+ peer.port.postMessage({
185
+ type: "attached",
186
+ leaderId: workerId,
187
+ epoch,
188
+ storageMode,
189
+ sourceVersion,
190
+ targetSchema,
191
+ });
192
+ } catch {}
193
+ }
194
+
195
+ async function handleLeaderPeerMessage(followerId, data) {
196
+ if (!data || role !== "leader") return;
197
+ if (data.leaderId && data.leaderId !== workerId) return;
198
+
199
+ if (data.type === "ping") {
200
+ const peer = peers.get(followerId);
201
+ try { peer?.port.postMessage({ type: "pong", pingId: data.pingId, leaderId: workerId }); } catch {}
202
+ return;
203
+ }
204
+
205
+ if (data.type === "simulate") {
206
+ const peer = peers.get(followerId);
207
+ if (peer) {
208
+ peer.simulation = data.settings || { offline: false, latencyMs: 0, report: false };
209
+ refreshEffectiveSimulation();
210
+ }
211
+ onLeaderMessage?.({ type: "simulate", settings: data.settings, backlog: !!data.backlog }, {
212
+ tabId: followerId,
213
+ reply: message => sendToPeer(followerId, message),
214
+ });
215
+ return;
216
+ }
217
+
218
+ if (data.type === "clear_log") {
219
+ onLeaderMessage?.({ type: "clear_log" }, { tabId: followerId });
220
+ return;
221
+ }
222
+
223
+ if (data.type === "rpc") {
224
+ const peer = peers.get(followerId);
225
+ if (!peer) return;
226
+ try { peer.port.postMessage({ type: "rpc_ack", rpcId: data.rpcId, leaderId: workerId }); } catch {}
227
+ try {
228
+ const result = await onRpc(data.method, data.payload, { tabId: followerId });
229
+ try { peer.port.postMessage({ type: "rpc_reply", rpcId: data.rpcId, leaderId: workerId, ok: true, result }); } catch {}
230
+ } catch (error) {
231
+ const message = String(error && error.message ? error.message : error);
232
+ try { peer.port.postMessage({ type: "rpc_reply", rpcId: data.rpcId, leaderId: workerId, ok: false, error: message }); } catch {}
233
+ }
234
+ }
235
+ }
236
+
237
+ function handleControlMessage(event) {
238
+ const data = event.data;
239
+ if (!data || closed) return;
240
+
241
+ if (role === "leader") {
242
+ if (data.type === "who_is_leader") {
243
+ if (data.targetSchema && targetSchema && data.targetSchema < targetSchema) {
244
+ sendControl({ type: "release_required", leaderId: workerId, targetId: data.followerId });
245
+ return;
246
+ }
247
+ if (data.targetSchema && targetSchema && data.targetSchema > targetSchema) {
248
+ onFollowerPush?.({ type: "release_required" });
249
+ }
250
+ if (leaderReady) {
251
+ sendControl({ type: "leader_ready", leaderId: workerId, epoch, storageMode, sourceVersion, targetSchema });
252
+ } else if (leaderBooting) {
253
+ sendControl({ type: "leader_booting", leaderId: workerId, epoch, sourceVersion, targetSchema });
254
+ }
255
+ } else if (data.type === "attach" && data.followerId && data.followerId !== workerId) {
256
+ if (leaderReady) {
257
+ attachPeer(data.followerId, data.simulation, data.sourceVersion, data.targetSchema);
258
+ }
259
+ } else if (data.type === "detach" && data.followerId) {
260
+ removePeer(data.followerId);
261
+ }
262
+ return;
263
+ }
264
+
265
+ if (role === "follower") {
266
+ if (data.type === "release_required" && (!data.targetId || data.targetId === workerId)) {
267
+ onFollowerPush?.({ type: "release_required" });
268
+ failAllPending("A newer Rails release migrated this database. Reload to continue.");
269
+ return;
270
+ }
271
+ if (data.type === "leader_ready" && data.leaderId !== workerId) {
272
+ if (data.targetSchema && targetSchema && data.targetSchema > targetSchema) {
273
+ onFollowerPush?.({ type: "release_required" });
274
+ failAllPending("A newer Rails release migrated this database. Reload to continue.");
275
+ return;
276
+ }
277
+ const changed = activeLeaderId !== data.leaderId || activeLeaderEpoch !== data.epoch || !attached;
278
+ activeLeaderId = data.leaderId;
279
+ activeLeaderEpoch = data.epoch || 0;
280
+ storageMode = data.storageMode || storageMode;
281
+ if (changed) {
282
+ attached = false;
283
+ sendAttach();
284
+ }
285
+ return;
286
+ }
287
+ if (data.type === "leader_bye" && data.leaderId === activeLeaderId) {
288
+ handleLeaderLost(data.leaderId);
289
+ return;
290
+ }
291
+ if (data.type === "broadcast" && data.leaderId === activeLeaderId) {
292
+ if (data.excludeTabId === workerId) return;
293
+ const msg = data.message;
294
+ if (msg?.type === "instant_record.debug" && !localSim.report) return;
295
+ onFollowerPush?.(msg);
296
+ }
297
+ }
298
+ }
299
+
300
+ function handleFollowerPeerMessage(event) {
301
+ const data = event.data;
302
+ if (!data || role !== "follower" || closed) return;
303
+
304
+ if (data.type === "attached" && data.leaderId) {
305
+ activeLeaderId = data.leaderId;
306
+ activeLeaderEpoch = data.epoch || 0;
307
+ storageMode = data.storageMode || storageMode;
308
+ attached = true;
309
+ clearInterval(discoveryTimer);
310
+ discoveryTimer = null;
311
+ while (attachWaiters.length > 0) attachWaiters.shift().resolve();
312
+ replayPendingRpcsToLeader();
313
+ return;
314
+ }
315
+
316
+ if (data.type === "push" && data.leaderId === activeLeaderId) {
317
+ onFollowerPush?.(data.message);
318
+ return;
319
+ }
320
+
321
+ if (data.type === "rpc_ack" && data.leaderId === activeLeaderId) {
322
+ const pending = pendingRpcs.get(data.rpcId);
323
+ if (pending) {
324
+ pending.acked = true;
325
+ clearTimeout(pending.timer);
326
+ pending.timer = null;
327
+ }
328
+ return;
329
+ }
330
+
331
+ if (data.type === "rpc_reply" && data.leaderId === activeLeaderId) {
332
+ const pending = pendingRpcs.get(data.rpcId);
333
+ if (!pending) return;
334
+ clearTimeout(pending.timer);
335
+ pendingRpcs.delete(data.rpcId);
336
+ if (data.ok) pending.resolve(data.result);
337
+ else pending.reject(new Error(data.error || "Leader RPC failed"));
338
+ return;
339
+ }
340
+ }
341
+
342
+ function sendAttach() {
343
+ sendControl({
344
+ type: "attach",
345
+ followerId: workerId,
346
+ simulation: localSim,
347
+ sourceVersion,
348
+ targetSchema,
349
+ });
350
+ }
351
+
352
+ function sendRpcFrame(rpcId, pending) {
353
+ pending.leaderId = activeLeaderId;
354
+ pending.acked = false;
355
+ clearTimeout(pending.timer);
356
+ pending.timer = setTimeout(() => {
357
+ if (role !== "follower" || !pendingRpcs.has(rpcId) || pending.acked) return;
358
+ // Probe leader liveness if an RPC goes unacknowledged.
359
+ sendControl({ type: "who_is_leader", followerId: workerId, sourceVersion, targetSchema });
360
+ }, rpcLivenessMs);
361
+ try {
362
+ peerChannel?.postMessage({
363
+ type: "rpc",
364
+ rpcId,
365
+ leaderId: activeLeaderId,
366
+ followerId: workerId,
367
+ method: pending.method,
368
+ payload: pending.payload,
369
+ idempotent: pending.idempotent,
370
+ });
371
+ } catch {}
372
+ }
373
+
374
+ function replayPendingRpcsToLeader() {
375
+ for (const [rpcId, pending] of [...pendingRpcs.entries()]) {
376
+ if (pending.leaderId === activeLeaderId) continue;
377
+ if (pending.acked && !pending.idempotent) {
378
+ clearTimeout(pending.timer);
379
+ pendingRpcs.delete(rpcId);
380
+ pending.reject(new Error("Leader closed while applying write; reload or retry."));
381
+ continue;
382
+ }
383
+ sendRpcFrame(rpcId, pending);
384
+ }
385
+ }
386
+
387
+ async function replayPendingRpcsLocally() {
388
+ for (const [rpcId, pending] of [...pendingRpcs.entries()]) {
389
+ clearTimeout(pending.timer);
390
+ pendingRpcs.delete(rpcId);
391
+ if (pending.acked && !pending.idempotent) {
392
+ pending.reject(new Error("Leader closed while applying write; reload or retry."));
393
+ continue;
394
+ }
395
+ try {
396
+ const result = await onRpc(pending.method, pending.payload, { tabId: workerId });
397
+ pending.resolve(result);
398
+ } catch (error) {
399
+ pending.reject(error);
400
+ }
401
+ }
402
+ }
403
+
404
+ function handleLeaderLost(deadLeaderId) {
405
+ if (activeLeaderId !== deadLeaderId) return;
406
+ activeLeaderId = null;
407
+ attached = false;
408
+ startDiscovery();
409
+ }
410
+
411
+ function failAllPending(message) {
412
+ const error = new Error(message);
413
+ for (const [rpcId, pending] of [...pendingRpcs.entries()]) {
414
+ clearTimeout(pending.timer);
415
+ pendingRpcs.delete(rpcId);
416
+ pending.reject(error);
417
+ }
418
+ while (attachWaiters.length > 0) attachWaiters.shift().reject(error);
419
+ }
420
+
421
+ function startDiscovery() {
422
+ if (discoveryTimer || role !== "follower" || closed) return;
423
+ sendControl({ type: "who_is_leader", followerId: workerId, sourceVersion, targetSchema });
424
+ discoveryTimer = setInterval(() => {
425
+ if (role !== "follower" || attached || closed) {
426
+ clearInterval(discoveryTimer);
427
+ discoveryTimer = null;
428
+ return;
429
+ }
430
+ sendControl({ type: "who_is_leader", followerId: workerId, sourceVersion, targetSchema });
431
+ }, discoveryRetryMs);
432
+ }
433
+
434
+ function acquireTabPresenceLock() {
435
+ if (typeof locks?.request !== "function") return Promise.resolve();
436
+ return new Promise(resolveAcquired => {
437
+ locks.request(tabPresenceLockName(workerId), () => {
438
+ resolveAcquired();
439
+ return new Promise(resolve => {
440
+ releaseTabLock = resolve;
441
+ });
442
+ }).catch(() => resolveAcquired());
443
+ });
444
+ }
445
+
446
+ async function enterLeaderRole({ promoted = false } = {}) {
447
+ leaderBooting = true;
448
+ leaderReady = false;
449
+ epoch = Math.max(epoch + 1, activeLeaderEpoch + 1);
450
+ setRole("leader");
451
+
452
+ if (promoted) {
453
+ clearInterval(discoveryTimer);
454
+ discoveryTimer = null;
455
+ if (peerChannel) {
456
+ try { peerChannel.close(); } catch {}
457
+ peerChannel = null;
458
+ }
459
+ leaderSim = { ...localSim };
460
+ lastEffectiveSim = effectiveSimulation();
461
+ activeLeaderId = null;
462
+ attached = false;
463
+ }
464
+
465
+ const result = await onBecomeLeader({
466
+ role: "leader",
467
+ promoted,
468
+ leaderId: workerId,
469
+ epoch,
470
+ broadcast,
471
+ notifyOthers: (excludeTabId, message) => broadcast(message, { excludeTabId }),
472
+ effectiveSimulation,
473
+ pruneDeadPeers,
474
+ connectedTabsCount: () => 1 + peers.size,
475
+ });
476
+ storageMode = result?.storageMode || storageMode;
477
+ lastBootResult = result;
478
+ leaderBooting = false;
479
+ leaderReady = true;
480
+
481
+ if (pruneIntervalMs > 0) {
482
+ clearInterval(pruneTimer);
483
+ pruneTimer = setInterval(pruneDeadPeers, pruneIntervalMs);
484
+ }
485
+
486
+ sendControl({ type: "leader_ready", leaderId: workerId, epoch, storageMode, sourceVersion, targetSchema });
487
+ while (attachWaiters.length > 0) attachWaiters.shift().resolve();
488
+ if (promoted && pendingRpcs.size > 0) {
489
+ // Drain this tab's pending RPCs directly now that we own the reactor.
490
+ replayPendingRpcsLocally();
491
+ }
492
+ return result;
493
+ }
494
+
495
+ function startStandbyLockWaiter() {
496
+ if (standbyActive || closed) return;
497
+ standbyActive = true;
498
+ locks.request(lockName, async () => {
499
+ standbyActive = false;
500
+ if (closed) return;
501
+ try {
502
+ await enterLeaderRole({ promoted: true });
503
+ } catch (error) {
504
+ failAllPending(error?.message || String(error));
505
+ return;
506
+ }
507
+ await new Promise(resolve => { releaseLeaderLock = resolve; });
508
+ }).catch(() => {
509
+ standbyActive = false;
510
+ });
511
+ }
512
+
513
+ function waitForReady() {
514
+ if ((role === "leader" && leaderReady) || role === "standalone" || attached) return Promise.resolve();
515
+ return new Promise((resolve, reject) => {
516
+ attachWaiters.push({ resolve, reject });
517
+ });
518
+ }
519
+
520
+ async function start() {
521
+ if (role !== "idle") return { role, storageMode };
522
+
523
+ if (!locks || typeof locks.request !== "function" || typeof createChannel !== "function") {
524
+ setRole("standalone");
525
+ const result = await onBecomeLeader({
526
+ role: "standalone",
527
+ promoted: false,
528
+ leaderId: workerId,
529
+ epoch: 1,
530
+ broadcast: message => onFollowerPush?.(message),
531
+ notifyOthers: () => {},
532
+ effectiveSimulation,
533
+ pruneDeadPeers: async () => {},
534
+ connectedTabsCount: () => 1,
535
+ });
536
+ storageMode = result?.storageMode || storageMode;
537
+ return { role: "standalone", storageMode, bootResult: result };
538
+ }
539
+
540
+ controlChannel = createChannel(controlName);
541
+ if (!controlChannel) {
542
+ setRole("standalone");
543
+ const result = await onBecomeLeader({
544
+ role: "standalone",
545
+ promoted: false,
546
+ leaderId: workerId,
547
+ epoch: 1,
548
+ broadcast: message => onFollowerPush?.(message),
549
+ notifyOthers: () => {},
550
+ effectiveSimulation,
551
+ pruneDeadPeers: async () => {},
552
+ connectedTabsCount: () => 1,
553
+ });
554
+ storageMode = result?.storageMode || storageMode;
555
+ return { role: "standalone", storageMode, bootResult: result };
556
+ }
557
+
558
+ controlChannel.onmessage = handleControlMessage;
559
+ await acquireTabPresenceLock();
560
+
561
+ let acquiredImmediate = false;
562
+ let bootResult = null;
563
+ await new Promise((resolveAttempt, rejectAttempt) => {
564
+ locks.request(lockName, { ifAvailable: true }, async lock => {
565
+ if (!lock) {
566
+ resolveAttempt();
567
+ return;
568
+ }
569
+ acquiredImmediate = true;
570
+ try {
571
+ bootResult = await enterLeaderRole({ promoted: false });
572
+ resolveAttempt();
573
+ } catch (error) {
574
+ close({ announceBye: false });
575
+ rejectAttempt(error);
576
+ return;
577
+ }
578
+ await new Promise(resolve => { releaseLeaderLock = resolve; });
579
+ }).catch(rejectAttempt);
580
+ });
581
+
582
+ if (acquiredImmediate) {
583
+ return { role: "leader", storageMode, bootResult };
584
+ }
585
+
586
+ // Another worker holds the leader lock: attach as follower and queue for failover.
587
+ setRole("follower");
588
+ peerChannel = createChannel(peerChannelName(workerId));
589
+ peerChannel.onmessage = handleFollowerPeerMessage;
590
+ startStandbyLockWaiter();
591
+ startDiscovery();
592
+ await waitForReady();
593
+ return { role, storageMode, bootResult: role === "leader" ? lastBootResult : null };
594
+ }
595
+
596
+ async function call(method, payload, { idempotent = true } = {}) {
597
+ if (closed) throw new Error("Coordinator is closed");
598
+ if ((role === "leader" && leaderReady) || role === "standalone") {
599
+ return onRpc(method, payload, { tabId: workerId });
600
+ }
601
+ await waitForReady();
602
+ if (role === "leader" || role === "standalone") {
603
+ return onRpc(method, payload, { tabId: workerId });
604
+ }
605
+ const rpcId = workerId + ":" + (nextRpcSeq++);
606
+ return new Promise((resolve, reject) => {
607
+ const pending = { method, payload, idempotent, acked: false, leaderId: null, resolve, reject, timer: null };
608
+ pendingRpcs.set(rpcId, pending);
609
+ sendRpcFrame(rpcId, pending);
610
+ });
611
+ }
612
+
613
+ function updateSimulation(settings, { backlog = false } = {}) {
614
+ const normalized = {
615
+ offline: !!settings?.offline,
616
+ latencyMs: Number(settings?.latencyMs) || 0,
617
+ report: !!settings?.report,
618
+ };
619
+ localSim = normalized;
620
+ if (role === "leader" || role === "standalone") {
621
+ leaderSim = normalized;
622
+ refreshEffectiveSimulation();
623
+ onLeaderMessage?.({ type: "simulate", settings: normalized, backlog }, {
624
+ tabId: workerId,
625
+ reply: message => onFollowerPush?.(message),
626
+ });
627
+ return;
628
+ }
629
+ if (role === "follower" && attached && activeLeaderId) {
630
+ try {
631
+ peerChannel?.postMessage({
632
+ type: "simulate",
633
+ leaderId: activeLeaderId,
634
+ followerId: workerId,
635
+ settings: normalized,
636
+ backlog,
637
+ });
638
+ } catch {}
639
+ }
640
+ }
641
+
642
+ function clearLog() {
643
+ if (role === "leader" || role === "standalone") {
644
+ onLeaderMessage?.({ type: "clear_log" }, { tabId: workerId });
645
+ return;
646
+ }
647
+ if (role === "follower" && attached && activeLeaderId) {
648
+ try {
649
+ peerChannel?.postMessage({ type: "clear_log", leaderId: activeLeaderId, followerId: workerId });
650
+ } catch {}
651
+ }
652
+ }
653
+
654
+ function close({ announceBye = true } = {}) {
655
+ if (closed) return;
656
+ closed = true;
657
+ clearInterval(discoveryTimer);
658
+ clearInterval(pruneTimer);
659
+ if (role === "leader") {
660
+ if (announceBye) sendControl({ type: "leader_bye", leaderId: workerId });
661
+ for (const peer of peers.values()) {
662
+ try { peer.port.close(); } catch {}
663
+ }
664
+ peers.clear();
665
+ } else if (role === "follower" && announceBye) {
666
+ sendControl({ type: "detach", followerId: workerId });
667
+ }
668
+ if (peerChannel) {
669
+ try { peerChannel.close(); } catch {}
670
+ peerChannel = null;
671
+ }
672
+ if (controlChannel) {
673
+ try { controlChannel.close(); } catch {}
674
+ controlChannel = null;
675
+ }
676
+ if (releaseLeaderLock) {
677
+ const release = releaseLeaderLock;
678
+ releaseLeaderLock = null;
679
+ release();
680
+ }
681
+ if (releaseTabLock) {
682
+ const release = releaseTabLock;
683
+ releaseTabLock = null;
684
+ release();
685
+ }
686
+ failAllPending("Worker closed");
687
+ }
688
+
689
+ return {
690
+ workerId,
691
+ lockName,
692
+ get role() { return role; },
693
+ get storageMode() { return storageMode; },
694
+ get activeLeaderId() { return activeLeaderId; },
695
+ start,
696
+ call,
697
+ updateSimulation,
698
+ clearLog,
699
+ broadcast,
700
+ notifyOthers: (excludeTabId, message) => broadcast(message, { excludeTabId }),
701
+ effectiveSimulation,
702
+ pruneDeadPeers,
703
+ close,
704
+ };
705
+ }