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,255 @@
1
+ require "fileutils"
2
+ require "json"
3
+ require "open3"
4
+ require "rbconfig"
5
+ require "tmpdir"
6
+ require_relative "base"
7
+
8
+ module InstantRecord
9
+ module Testing
10
+ module Runtimes
11
+ # Multi-client CRuby runtime driving InstantRecord::Client through its
12
+ # injectable transport and notifier seams (lib/instant_record/client.rb:28-38)
13
+ # inside an isolated persistent SQLite-only CRuby child process.
14
+ #
15
+ # Isolating CRuby clients in their own process mirrors WasmRuntime (Node)
16
+ # and prevents ActiveRecord StatementCache / adapter collisions when the
17
+ # authoritative server runs on PostgreSQL.
18
+ class CRubyRuntime
19
+ include Base
20
+
21
+ BRIDGE_SCRIPT = File.expand_path("../cruby_host_bridge.rb", __dir__)
22
+
23
+ class ClientHandle
24
+ attr_reader :id, :runtime, :db_path
25
+
26
+ def initialize(id:, runtime:, db_path:)
27
+ @id = id.to_s
28
+ @runtime = runtime
29
+ @db_path = db_path
30
+ end
31
+
32
+ def runtime_name = :cruby
33
+
34
+ def request(method, path, body: "", content_type: "application/x-www-form-urlencoded")
35
+ @runtime.execute_request(self, method, path, body: body, content_type: content_type)
36
+ end
37
+
38
+ def sync(endpoint = InstantRecord::DEFAULT_MOUNT_PATH)
39
+ @runtime.execute_sync(self, endpoint)
40
+ end
41
+
42
+ def sync_plan
43
+ @runtime.execute_sync_plan(self)
44
+ end
45
+
46
+ def consume_stream(chunk)
47
+ @runtime.execute_consume_stream(self, chunk)
48
+ end
49
+
50
+ def sync_state
51
+ @runtime.execute_sync_state(self)
52
+ end
53
+
54
+ def history(key, response = "")
55
+ @runtime.execute_history(self, key, response)
56
+ end
57
+
58
+ def local_write(model:, operation:, id: nil, attributes: {})
59
+ @runtime.execute_local_write(self, model: model, operation: operation, id: id, attributes: attributes)
60
+ end
61
+
62
+ def snapshot_state(model_names:)
63
+ @runtime.read_sqlite_file_state(@db_path, model_names: model_names)
64
+ end
65
+ end
66
+
67
+ attr_reader :network, :server
68
+
69
+ def initialize(network:, server:, model_names: %w[Issue AuthNote])
70
+ @network = network
71
+ @server = server
72
+ @model_names = Array(model_names)
73
+ @tmpdir = Dir.mktmpdir("instant-record-cruby-clients")
74
+ @stdin = nil
75
+ @stdout = nil
76
+ @stderr = nil
77
+ @wait_thr = nil
78
+ start_bridge!
79
+ end
80
+
81
+ def name = :cruby
82
+
83
+ def create_client(client_id, env: {})
84
+ _ = env
85
+ res = rpc({ op: "create_client", client: client_id.to_s })
86
+ assert_clean_stderr!(res["errors"], context: "cruby create_client(#{client_id})")
87
+ ClientHandle.new(id: client_id, runtime: self, db_path: res["db_path"])
88
+ end
89
+
90
+ def close
91
+ if @stdin && !@stdin.closed?
92
+ begin
93
+ rpc({ op: "shutdown" })
94
+ rescue StandardError
95
+ nil
96
+ end
97
+ end
98
+ ensure
99
+ [@stdin, @stdout, @stderr].each do |io|
100
+ io.close if io && !io.closed?
101
+ rescue StandardError
102
+ nil
103
+ end
104
+ @wait_thr&.join(2)
105
+ FileUtils.remove_entry(@tmpdir) if @tmpdir && Dir.exist?(@tmpdir)
106
+ end
107
+
108
+ def execute_request(client, method, path, body:, content_type:)
109
+ res = rpc({
110
+ op: "request",
111
+ client: client.id,
112
+ method: method.to_s.upcase,
113
+ path: path.to_s,
114
+ body: body.to_s,
115
+ contentType: content_type
116
+ })
117
+ assert_clean_stderr!(res["errors"], context: "cruby request(#{client.id}, #{method} #{path})")
118
+ {
119
+ status: res["status"].to_i,
120
+ headers: res["headers"] || [],
121
+ body: res["body"].to_s,
122
+ exit: res["exit"].to_i,
123
+ errors: res["errors"] || []
124
+ }
125
+ end
126
+
127
+ def execute_sync(client, endpoint)
128
+ res, fault_fired = @network.track_faults do
129
+ rpc({ op: "sync", client: client.id, endpoint: endpoint.to_s })
130
+ end
131
+ assert_clean_stderr!(res["errors"], context: "cruby sync(#{client.id})", allow_offline_warning: fault_fired)
132
+ {
133
+ changed: !!res["changed"],
134
+ pending: res["pending"].to_i,
135
+ cursor: res["cursor"].to_i,
136
+ **parse_notice(res["notice"]),
137
+ exchanges: res["exchanges"] || [],
138
+ exit: res["exit"].to_i,
139
+ errors: res["errors"] || [],
140
+ fault_fired: fault_fired
141
+ }
142
+ end
143
+
144
+ def execute_sync_plan(client)
145
+ res = rpc({ op: "sync_plan", client: client.id })
146
+ assert_clean_stderr!(res["errors"], context: "cruby sync_plan(#{client.id})")
147
+ res["plan"]
148
+ end
149
+
150
+ def execute_consume_stream(client, chunk)
151
+ res = rpc({ op: "consume_stream", client: client.id, chunk: chunk.to_s })
152
+ assert_clean_stderr!(res["errors"], context: "cruby consume_stream(#{client.id})")
153
+ {
154
+ applied: res["applied"].to_i,
155
+ cursor: res["cursor"].to_i,
156
+ bootstrapped: !!res["bootstrapped"],
157
+ **parse_notice(res["notice"]),
158
+ exit: res["exit"].to_i,
159
+ errors: res["errors"] || []
160
+ }
161
+ end
162
+
163
+ def execute_sync_state(client)
164
+ res = rpc({ op: "sync_state", client: client.id })
165
+ assert_clean_stderr!(res["errors"], context: "cruby sync_state(#{client.id})")
166
+ {
167
+ bootstrapped: !!res["bootstrapped"],
168
+ cursor: res["cursor"].to_i,
169
+ pending: res["pending"].to_i,
170
+ identity: res["identity"].to_s
171
+ }
172
+ end
173
+
174
+ def execute_history(client, key, response)
175
+ res = rpc({ op: "history", client: client.id, key: key.to_s, response: response.to_s })
176
+ assert_clean_stderr!(res["errors"], context: "cruby history(#{client.id})")
177
+ res["history"]
178
+ end
179
+
180
+ def execute_local_write(client, model:, operation:, id:, attributes:)
181
+ skew = @network.policy(client.id).clock_skew.to_f
182
+ res = rpc({
183
+ op: "local_write",
184
+ client: client.id,
185
+ model: model.to_s,
186
+ operation: operation.to_s,
187
+ id: id,
188
+ attributes: attributes,
189
+ clockSkew: skew
190
+ })
191
+ assert_clean_stderr!(res["errors"], context: "cruby local_write(#{client.id}, #{model}##{operation})")
192
+ res["record_id"]
193
+ end
194
+
195
+ private
196
+
197
+ def start_bridge!
198
+ lib_dir = File.join(InstantRecord::Testing.gem_root.to_s, "lib")
199
+ @stdin, @stdout, @stderr, @wait_thr = Open3.popen3(RbConfig.ruby, "-I#{lib_dir}", BRIDGE_SCRIPT, @tmpdir)
200
+ @stdin.sync = true
201
+
202
+ ready = read_message
203
+ unless ready && ready["type"] == "ready"
204
+ err_out = read_bridge_stderr
205
+ raise InstantRecord::Testing::Error, "CRuby bridge failed to start: #{ready.inspect} #{err_out}"
206
+ end
207
+ end
208
+
209
+ def rpc(payload)
210
+ @stdin.puts(JSON.generate(payload))
211
+ @stdin.flush
212
+
213
+ loop do
214
+ msg = read_message
215
+ unless msg
216
+ err_out = read_bridge_stderr
217
+ raise InstantRecord::Testing::Error, "CRuby bridge exited unexpectedly during #{payload[:op]}: #{err_out}"
218
+ end
219
+
220
+ case msg["type"]
221
+ when "exchange"
222
+ reply = @network.exchange(msg["client"], msg["method"], msg["url"], msg["body"].to_s)
223
+ @stdin.puts(JSON.generate({ status: reply[:status], body: reply[:body].to_s }))
224
+ @stdin.flush
225
+ when "result"
226
+ return msg
227
+ when "error"
228
+ raise InstantRecord::Testing::Error, "CRuby bridge error during #{payload[:op]}: #{msg['message']}"
229
+ else
230
+ raise InstantRecord::Testing::Error, "Unexpected CRuby bridge message: #{msg.inspect}"
231
+ end
232
+ end
233
+ end
234
+
235
+ def read_message
236
+ line = @stdout.gets
237
+ return nil unless line
238
+
239
+ JSON.parse(line)
240
+ end
241
+
242
+ def read_bridge_stderr
243
+ return "" unless @stderr && !@stderr.closed?
244
+
245
+ out = +""
246
+ loop do
247
+ out << @stderr.read_nonblock(4096)
248
+ end
249
+ rescue IO::WaitReadable, EOFError
250
+ out
251
+ end
252
+ end
253
+ end
254
+ end
255
+ end
@@ -0,0 +1,346 @@
1
+ require "fileutils"
2
+ require "json"
3
+ require "tmpdir"
4
+ require "uri"
5
+ require_relative "base"
6
+
7
+ module InstantRecord
8
+ module Testing
9
+ module Runtimes
10
+ # Compiled Native C ABI runtime loaded directly in-process via Ruby Fiddle
11
+ # against compiled/pipeline/native/instant_record_native.h:
12
+ # ir_set_exchange, ir_boot, ir_open, ir_call, ir_notice, ir_error.
13
+ #
14
+ # Because native_shim.c boots Spinel once per process, LibrarySession caches
15
+ # the booted Fiddle handle and multiplexes N isolated client SQLite files
16
+ # seamlessly via ir_open(db_path).
17
+ class NativeRuntime
18
+ include Base
19
+
20
+ # Process-wide booted handle per shared library path.
21
+ class LibrarySession
22
+ @sessions = {}
23
+
24
+ def self.for(lib_path)
25
+ canonical = File.realpath(lib_path)
26
+ @sessions[canonical] ||= new(canonical)
27
+ end
28
+
29
+ def initialize(lib_path)
30
+ require "fiddle"
31
+ @lib_path = lib_path
32
+ @handle = Fiddle.dlopen(lib_path)
33
+ @ir_set_exchange = Fiddle::Function.new(@handle["ir_set_exchange"], [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP], Fiddle::TYPE_VOID)
34
+ @ir_boot = Fiddle::Function.new(@handle["ir_boot"], [Fiddle::TYPE_VOIDP], Fiddle::TYPE_INT)
35
+ @ir_open = Fiddle::Function.new(@handle["ir_open"], [Fiddle::TYPE_VOIDP], Fiddle::TYPE_INT)
36
+ @ir_call = Fiddle::Function.new(@handle["ir_call"], [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP], Fiddle::TYPE_VOIDP)
37
+ @ir_notice = Fiddle::Function.new(@handle["ir_notice"], [], Fiddle::TYPE_VOIDP)
38
+ @ir_error = Fiddle::Function.new(@handle["ir_error"], [], Fiddle::TYPE_VOIDP)
39
+
40
+ @booted = false
41
+ @active_db_path = nil
42
+ @active_exchange = nil
43
+ @pinned_response = nil
44
+
45
+ # Pin the closure in an instance variable so it is never GC'd while
46
+ # C holds its function pointer.
47
+ @exchange_closure = Fiddle::Closure::BlockCaller.new(
48
+ Fiddle::TYPE_VOIDP,
49
+ [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP]
50
+ ) do |req_ptr, _ctx|
51
+ req_str = req_ptr.null? ? "" : req_ptr.to_s
52
+ newline = req_str.index("\n") || req_str.length
53
+ method, url = req_str[0, newline].split(" ", 2)
54
+ body = req_str[(newline + 1)..] || ""
55
+ reply =
56
+ if @active_exchange
57
+ @active_exchange.call(method.to_s, url.to_s, body)
58
+ else
59
+ { status: 0, body: "" }
60
+ end
61
+ @pinned_response = "#{reply[:status]}\n#{reply[:body]}\0".b
62
+ Fiddle::Pointer[@pinned_response]
63
+ end
64
+
65
+ @ir_set_exchange.call(@exchange_closure, Fiddle::NULL)
66
+ end
67
+
68
+ def ensure_open(db_path)
69
+ return [] if @booted && @active_db_path == db_path
70
+
71
+ code, stderr_lines = capture_fd2 do
72
+ if @booted
73
+ @ir_open.call(db_path)
74
+ else
75
+ @ir_boot.call(db_path)
76
+ end
77
+ end
78
+ if code != 0
79
+ raise InstantRecord::Testing::Error, "Native #{@booted ? 'ir_open' : 'ir_boot'} failed (#{db_path}): #{last_error}"
80
+ end
81
+ @booted = true
82
+ @active_db_path = db_path
83
+ stderr_lines
84
+ end
85
+
86
+ def call_entry(db_path, entry, input, exchange: nil)
87
+ open_stderr = ensure_open(db_path)
88
+ @active_exchange = exchange
89
+ ptr, call_stderr = capture_fd2 { @ir_call.call(entry.to_s, input.to_s) }
90
+ errors = open_stderr + call_stderr
91
+
92
+ if ptr.null?
93
+ err = last_error
94
+ errors << err unless err.empty?
95
+ return { ok: false, out: "", notice: "", errors: errors }
96
+ end
97
+
98
+ out = ptr.to_s.dup.force_encoding(Encoding::UTF_8)
99
+ notice_ptr = @ir_notice.call
100
+ notice = notice_ptr.null? ? "" : notice_ptr.to_s.dup.force_encoding(Encoding::UTF_8)
101
+ { ok: true, out: out, notice: notice, errors: errors }
102
+ ensure
103
+ @active_exchange = nil
104
+ end
105
+
106
+ def last_error
107
+ ptr = @ir_error.call
108
+ ptr.null? ? "" : ptr.to_s.dup.force_encoding(Encoding::UTF_8)
109
+ end
110
+
111
+ private
112
+
113
+ # Capture C-level stderr (fd 2) around native Fiddle calls so Ruby warn
114
+ # or Spinel runtime diagnostics are caught identically to WASI stderr.
115
+ def capture_fd2
116
+ $stderr.flush
117
+ saved_fd = IO.new(2).dup
118
+ read_io, write_io = IO.pipe
119
+ $stderr.reopen(write_io)
120
+ write_io.close
121
+
122
+ result = yield
123
+ $stderr.flush
124
+ $stderr.reopen(saved_fd)
125
+ saved_fd.close
126
+ captured = read_io.read
127
+ read_io.close
128
+ [result, captured.lines(chomp: true)]
129
+ rescue StandardError
130
+ begin
131
+ $stderr.reopen(saved_fd) if saved_fd && !saved_fd.closed?
132
+ saved_fd&.close
133
+ write_io&.close unless write_io&.closed?
134
+ read_io&.close unless read_io&.closed?
135
+ rescue StandardError
136
+ nil
137
+ end
138
+ raise
139
+ end
140
+ end
141
+
142
+ class ClientHandle
143
+ attr_reader :id, :runtime, :db_path, :cookies
144
+
145
+ def initialize(id:, runtime:, db_path:)
146
+ @id = id.to_s
147
+ @runtime = runtime
148
+ @db_path = db_path
149
+ @cookies = {}
150
+ end
151
+
152
+ def runtime_name = :native
153
+
154
+ def request(method, path, body: "", content_type: "application/x-www-form-urlencoded")
155
+ @runtime.execute_request(self, method, path, body: body, content_type: content_type)
156
+ end
157
+
158
+ def sync(endpoint = InstantRecord::DEFAULT_MOUNT_PATH)
159
+ @runtime.execute_sync(self, endpoint)
160
+ end
161
+
162
+ def sync_plan
163
+ @runtime.execute_sync_plan(self)
164
+ end
165
+
166
+ def consume_stream(chunk)
167
+ @runtime.execute_consume_stream(self, chunk)
168
+ end
169
+
170
+ def sync_state
171
+ @runtime.execute_sync_state(self)
172
+ end
173
+
174
+ def history(key, response = "")
175
+ @runtime.execute_history(self, key, response)
176
+ end
177
+
178
+ def local_write(model:, operation:, id: nil, attributes: {})
179
+ @runtime.execute_local_write(self, model: model, operation: operation, id: id, attributes: attributes)
180
+ end
181
+
182
+ def snapshot_state(model_names:)
183
+ @runtime.read_sqlite_file_state(@db_path, model_names: model_names)
184
+ end
185
+ end
186
+
187
+ attr_reader :lib_path, :network
188
+
189
+ def initialize(lib_path:, network:)
190
+ @lib_path = File.expand_path(lib_path.to_s)
191
+ @network = network
192
+ @session = LibrarySession.for(@lib_path)
193
+ @tmpdir = Dir.mktmpdir("instant-record-native-clients")
194
+ @counter = 0
195
+ end
196
+
197
+ def name = :native
198
+
199
+ def create_client(client_id, env: {})
200
+ _ = env
201
+ @counter += 1
202
+ db_path = File.join(@tmpdir, "#{client_id.to_s.gsub(/[^a-zA-Z0-9_-]/, '_')}_#{@counter}.sqlite3")
203
+ stderr = @session.ensure_open(db_path)
204
+ assert_clean_stderr!(stderr, context: "native boot/open(#{client_id})")
205
+ ClientHandle.new(id: client_id, runtime: self, db_path: db_path)
206
+ end
207
+
208
+ def close
209
+ # Point Spinel at a harmless temp db before removing client temp dir
210
+ # so the next NativeRuntime session doesn't hold an unlinked path.
211
+ FileUtils.remove_entry(@tmpdir) if @tmpdir && Dir.exist?(@tmpdir)
212
+ end
213
+
214
+ def execute_request(client, method, path, body:, content_type:)
215
+ raw_req = build_http_request(method, path, body: body, content_type: content_type, cookies: client.cookies)
216
+ res = @session.call_entry(client.db_path, "request", raw_req)
217
+ assert_clean_stderr!(res[:errors], context: "native request(#{client.id}, #{method} #{path})")
218
+ raise InstantRecord::Testing::Error, "native request failed: #{res[:errors].join('; ')}" unless res[:ok]
219
+
220
+ parsed = parse_bridge_http_response(res[:out], cookies: client.cookies)
221
+ parsed.merge(exit: 0, errors: res[:errors])
222
+ end
223
+
224
+ def execute_sync(client, endpoint)
225
+ exchanges = []
226
+ exchange_cb = lambda do |method, url, body|
227
+ reply = @network.exchange(client.id, method, url, body)
228
+ exchanges << "#{method} #{url} -> #{reply[:status]}"
229
+ reply
230
+ end
231
+
232
+ res, fault_fired = @network.track_faults do
233
+ @session.call_entry(client.db_path, "sync", endpoint.to_s, exchange: exchange_cb)
234
+ end
235
+ assert_clean_stderr!(res[:errors], context: "native sync(#{client.id})", allow_offline_warning: fault_fired)
236
+ raise InstantRecord::Testing::Error, "native sync failed: #{res[:errors].join('; ')}" unless res[:ok]
237
+
238
+ text = res[:out]
239
+ pending = (text[/pending=(\d+)/, 1] || -1).to_i
240
+ cursor = (text[/cursor=(\d+)/, 1] || 0).to_i
241
+ raise InstantRecord::Testing::Error, "native sync reported pending=#{pending}" if pending < 0
242
+
243
+ {
244
+ changed: text.start_with?("changed"),
245
+ pending: pending,
246
+ cursor: cursor,
247
+ **parse_notice(res[:notice]),
248
+ exchanges: exchanges,
249
+ exit: 0,
250
+ errors: res[:errors],
251
+ fault_fired: fault_fired
252
+ }
253
+ end
254
+
255
+ def execute_sync_plan(client)
256
+ res = @session.call_entry(client.db_path, "sync_plan", "")
257
+ assert_clean_stderr!(res[:errors], context: "native sync_plan(#{client.id})")
258
+ raise InstantRecord::Testing::Error, "native sync_plan failed: #{res[:errors].join('; ')}" unless res[:ok]
259
+
260
+ JSON.parse(res[:out])
261
+ end
262
+
263
+ def execute_consume_stream(client, chunk)
264
+ res = @session.call_entry(client.db_path, "stream", chunk.to_s)
265
+ assert_clean_stderr!(res[:errors], context: "native stream(#{client.id})")
266
+ raise InstantRecord::Testing::Error, "native stream failed: #{res[:errors].join('; ')}" unless res[:ok]
267
+
268
+ text = res[:out]
269
+ {
270
+ applied: (text[/applied=(\d+)/, 1] || 0).to_i,
271
+ cursor: (text[/cursor=(\d+)/, 1] || 0).to_i,
272
+ bootstrapped: !text.include?("bootstrap=needed"),
273
+ **parse_notice(res[:notice]),
274
+ exit: 0,
275
+ errors: res[:errors]
276
+ }
277
+ end
278
+
279
+ def execute_sync_state(client)
280
+ res = @session.call_entry(client.db_path, "cursor", "")
281
+ assert_clean_stderr!(res[:errors], context: "native cursor(#{client.id})")
282
+ raise InstantRecord::Testing::Error, "native cursor failed: #{res[:errors].join('; ')}" unless res[:ok]
283
+
284
+ text = res[:out]
285
+ {
286
+ bootstrapped: text.include?("bootstrap=ready"),
287
+ cursor: (text[/cursor=(\d+)/, 1] || 0).to_i,
288
+ pending: (text[/pending=(\d+)/, 1] || 0).to_i,
289
+ identity: text[/identity=(\S+)/, 1].to_s
290
+ }
291
+ end
292
+
293
+ def execute_history(client, key, response)
294
+ res = @session.call_entry(client.db_path, "history", JSON.generate({ key: key.to_s, response: response.to_s }))
295
+ assert_clean_stderr!(res[:errors], context: "native history(#{client.id})")
296
+ raise InstantRecord::Testing::Error, "native history failed: #{res[:errors].join('; ')}" unless res[:ok]
297
+
298
+ JSON.parse(res[:out])
299
+ end
300
+
301
+ def execute_local_write(client, model:, operation:, id:, attributes:)
302
+ attrs = attributes.transform_keys(&:to_s)
303
+ case [model.to_s, operation.to_s]
304
+ when ["Issue", "create"]
305
+ res = execute_request(client, "POST", "/todo/issues", body: URI.encode_www_form("issue[title]" => attrs["title"]), content_type: "application/x-www-form-urlencoded")
306
+ raise Error, "Expected 200/302 on POST /todo/issues, got #{res[:status]}" unless [200, 302, 303].include?(res[:status])
307
+ newest_id_from_snapshot(client, "Issue", title: attrs["title"])
308
+ when ["Issue", "update"]
309
+ done = attrs["state"].to_s == "done" ? "1" : "0"
310
+ res = execute_request(client, "POST", "/todo/issues/#{id}", body: URI.encode_www_form("_method" => "patch", "done" => done), content_type: "application/x-www-form-urlencoded")
311
+ raise Error, "Expected 200/302 on PATCH /todo/issues/#{id}, got #{res[:status]}" unless [200, 302, 303].include?(res[:status])
312
+ id
313
+ when ["Issue", "destroy"]
314
+ res = execute_request(client, "POST", "/todo/issues/#{id}", body: URI.encode_www_form("_method" => "delete"), content_type: "application/x-www-form-urlencoded")
315
+ raise Error, "Expected 200/302 on DELETE /todo/issues/#{id}, got #{res[:status]}" unless [200, 302, 303].include?(res[:status])
316
+ id
317
+ when ["AuthNote", "create"]
318
+ form = {
319
+ "note[title]" => attrs["title"],
320
+ "note[body]" => attrs["body"].to_s,
321
+ "note[audience]" => attrs["audience"] || "owner",
322
+ "note[owner_id]" => attrs["owner_id"].to_s
323
+ }
324
+ res = execute_request(client, "POST", "/auth/notes", body: URI.encode_www_form(form), content_type: "application/x-www-form-urlencoded")
325
+ raise Error, "Expected 200/302 on POST /auth/notes, got #{res[:status]}" unless [200, 302, 303].include?(res[:status])
326
+ newest_id_from_snapshot(client, "AuthNote", title: attrs["title"])
327
+ when ["AuthNote", "destroy"]
328
+ res = execute_request(client, "POST", "/auth/notes/#{id}", body: URI.encode_www_form("_method" => "delete"), content_type: "application/x-www-form-urlencoded")
329
+ raise Error, "Expected 200/302 on DELETE /auth/notes/#{id}, got #{res[:status]}" unless [200, 302, 303].include?(res[:status])
330
+ id
331
+ else
332
+ raise ArgumentError, "Unsupported native local_write: #{model}##{operation}"
333
+ end
334
+ end
335
+
336
+ private
337
+
338
+ def newest_id_from_snapshot(client, model_name, title:)
339
+ state = read_sqlite_file_state(client.db_path, model_names: [model_name])
340
+ rows = state[:tables][model_name].select { |r| r["title"] == title }
341
+ rows.max_by { |r| r["created_at"].to_s }&.fetch("id")
342
+ end
343
+ end
344
+ end
345
+ end
346
+ end