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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +58 -0
- data/README.md +267 -61
- data/app/controllers/instant_record/bootstraps_controller.rb +39 -12
- data/app/controllers/instant_record/events_controller.rb +58 -6
- data/app/controllers/instant_record/files_controller.rb +116 -0
- data/app/controllers/instant_record/mutations_controller.rb +84 -5
- data/app/controllers/instant_record/native_screens_controller.rb +60 -0
- data/app/controllers/instant_record/records_controller.rb +86 -8
- data/app/controllers/instant_record/shells_controller.rb +64 -0
- data/app/controllers/instant_record/sync_notices_controller.rb +81 -0
- data/app/helpers/instant_record/sync_notices_helper.rb +41 -0
- data/app/jobs/instant_record/shell_build_job.rb +16 -0
- data/app/models/instant_record/change.rb +36 -3
- data/app/models/instant_record/mutation_applier.rb +633 -50
- data/app/views/instant_record/sync_notices/_notices.html.erb +63 -0
- data/compiled/README.md +272 -0
- data/compiled/pipeline/browser_migrations.rb +18 -0
- data/compiled/pipeline/build.rb +13 -0
- data/compiled/pipeline/build_native.rb +14 -0
- data/compiled/pipeline/native/host.c +78 -0
- data/compiled/pipeline/native/instant_record_native.h +57 -0
- data/compiled/pipeline/native_shim.c +149 -0
- data/compiled/pipeline/reactor_shim.c +66 -0
- data/compiled/pipeline/sqlite/rh_shim.c +5 -0
- data/compiled/pipeline/sqlite_release.rb +43 -0
- data/compiled/toolchain.env.example +22 -0
- data/compiled/web/index.html +20 -0
- data/compiled/web/package-lock.json +884 -0
- data/compiled/web/package.json +17 -0
- data/compiled/web/src/app-host-core.js +556 -0
- data/compiled/web/src/app-host.js +16 -0
- data/compiled/web/src/branch-manager.js +140 -0
- data/compiled/web/src/branch-preview.js +397 -0
- data/compiled/web/src/changes.js +191 -0
- data/compiled/web/src/faults.js +172 -0
- data/compiled/web/src/flight-recorder.js +347 -0
- data/compiled/web/src/history-fill.js +68 -0
- data/compiled/web/src/http-headers.js +100 -0
- data/compiled/web/src/leader-election.js +705 -0
- data/compiled/web/src/main.js +608 -0
- data/compiled/web/src/manifest.js +112 -0
- data/compiled/web/src/opfs-wasi-core.js +109 -0
- data/compiled/web/src/opfs-wasi-file.js +8 -0
- data/compiled/web/src/reactor-runtime.js +1692 -0
- data/compiled/web/src/redactor.js +518 -0
- data/compiled/web/src/release-updates.js +48 -0
- data/compiled/web/src/replay.js +338 -0
- data/compiled/web/src/schema-recovery.js +204 -0
- data/compiled/web/src/server-request.js +68 -0
- data/compiled/web/src/sha256.js +98 -0
- data/compiled/web/src/shell.js +52 -0
- data/compiled/web/src/snapshot-store.js +38 -0
- data/compiled/web/src/sqlite-redactor.js +111 -0
- data/compiled/web/src/storage-backend.js +159 -0
- data/compiled/web/src/stream-leader.js +675 -0
- data/compiled/web/src/sync-context.js +91 -0
- data/compiled/web/src/sync-drain.js +104 -0
- data/compiled/web/src/sync-schedule.js +9 -0
- data/compiled/web/src/wasi-minimal.js +275 -0
- data/compiled/web/src/worker.js +39 -0
- data/compiled/web/vite.config.js +27 -0
- data/config/routes.rb +25 -0
- data/db/migrate/20261119000201_add_scope_to_instant_record_changes.rb +7 -0
- data/db/migrate/20261121000001_create_instant_record_sync_notices.rb +21 -0
- data/db/migrate/20261121000101_add_partition_to_instant_record_changes.rb +8 -0
- data/db/migrate/20261121230300_add_delay_line_to_instant_record_outbox.rb +10 -0
- data/exe/instant_record_mcp +6 -0
- data/frontend/LiveList.js +67 -0
- data/frontend/chord.js +79 -0
- data/frontend/file.js +65 -0
- data/frontend/files.js +738 -0
- data/frontend/focus.js +10 -0
- data/frontend/held.js +192 -0
- data/frontend/http.js +76 -0
- data/frontend/index.js +53 -0
- data/frontend/keyboard.js +56 -0
- data/frontend/live.js +298 -0
- data/frontend/notices.js +118 -0
- data/frontend/package.json +15 -0
- data/frontend/range.js +10 -0
- data/frontend/selection.js +47 -0
- data/frontend/shortcuts.js +25 -0
- data/frontend/sync-notices.js +130 -0
- data/frontend/undo.js +48 -0
- data/frontend/window.js +181 -0
- data/lib/generators/instant_record/install/install_generator.rb +18 -30
- data/lib/generators/instant_record/install/templates/instant_record.rb +34 -0
- data/lib/generators/instant_record/ios/ios_generator.rb +71 -0
- data/lib/generators/instant_record/ios/templates/App.swift.tt +35 -0
- data/lib/generators/instant_record/ios/templates/Info.plist +11 -0
- data/lib/generators/instant_record/ios/templates/LibraryEngine.swift +30 -0
- data/lib/instant_record/branch/sqlite_store.rb +142 -0
- data/lib/instant_record/branch.rb +388 -0
- data/lib/instant_record/client/notifier.rb +8 -12
- data/lib/instant_record/client/rebaser.rb +565 -0
- data/lib/instant_record/client/transport.rb +64 -42
- data/lib/instant_record/client.rb +1600 -169
- data/lib/instant_record/compiled_site.rb +85 -0
- data/lib/instant_record/compiler/app_stage.rb +212 -0
- data/lib/instant_record/compiler/ast_lowerer.rb +659 -0
- data/lib/instant_record/compiler/browser_migrations.rb +161 -0
- data/lib/instant_record/compiler/entry_builder.rb +832 -0
- data/lib/instant_record/compiler/fts5_smoke.rb +205 -0
- data/lib/instant_record/compiler/gem_vendor.rb +194 -0
- data/lib/instant_record/compiler/host_adapters.rb +506 -0
- data/lib/instant_record/compiler/kotlin_codegen.rb +209 -0
- data/lib/instant_record/compiler/manifest.rb +178 -0
- data/lib/instant_record/compiler/native_build.rb +586 -0
- data/lib/instant_record/compiler/native_contracts.rb +338 -0
- data/lib/instant_record/compiler/path_scrubber.rb +31 -0
- data/lib/instant_record/compiler/reachability_tracer.rb +1188 -0
- data/lib/instant_record/compiler/route_analyzer.rb +623 -0
- data/lib/instant_record/compiler/runner.rb +42 -0
- data/lib/instant_record/compiler/schema_lock.rb +606 -0
- data/lib/instant_record/compiler/source_pages.rb +77 -0
- data/lib/instant_record/compiler/static_linter.rb +770 -0
- data/lib/instant_record/compiler/swift_codegen.rb +341 -0
- data/lib/instant_record/compiler/toolchain.rb +219 -0
- data/lib/instant_record/compiler/wasm_build.rb +704 -0
- data/lib/instant_record/compiler/wasm_tree.rb +518 -0
- data/lib/instant_record/compiler.rb +277 -0
- data/lib/instant_record/configuration.rb +104 -0
- data/lib/instant_record/engine.rb +68 -18
- data/lib/instant_record/file_store.rb +162 -0
- data/lib/instant_record/files.rb +92 -0
- data/lib/instant_record/hlc.rb +387 -0
- data/lib/instant_record/host.rb +66 -0
- data/lib/instant_record/inertia/renderer.rb +52 -0
- data/lib/instant_record/inertia.rb +222 -0
- data/lib/instant_record/mcp/cli.rb +319 -0
- data/lib/instant_record/mcp/host_process.rb +229 -0
- data/lib/instant_record/mcp/http_exchange.rb +233 -0
- data/lib/instant_record/mcp/replica.rb +556 -0
- data/lib/instant_record/mcp/runtime.rb +406 -0
- data/lib/instant_record/mcp/server.rb +429 -0
- data/lib/instant_record/mcp.rb +47 -0
- data/lib/instant_record/native/contract.rb +367 -0
- data/lib/instant_record/native/node.rb +125 -0
- data/lib/instant_record/native/screen.rb +366 -0
- data/lib/instant_record/native/xcode_project.rb +344 -0
- data/lib/instant_record/native.rb +41 -0
- data/lib/instant_record/outbox_mutation.rb +81 -9
- data/lib/instant_record/outbox_upcaster.rb +161 -0
- data/lib/instant_record/read_tracker.rb +610 -0
- data/lib/instant_record/routing.rb +33 -0
- data/lib/instant_record/runtime_scoped.rb +4 -0
- data/lib/instant_record/shell.rb +486 -0
- data/lib/instant_record/sync_actions.rb +800 -0
- data/lib/instant_record/sync_metadata.rb +17 -2
- data/lib/instant_record/sync_notice.rb +234 -0
- data/lib/instant_record/sync_partition.rb +63 -0
- data/lib/instant_record/sync_scope.rb +300 -0
- data/lib/instant_record/sync_shape.rb +102 -0
- data/lib/instant_record/sync_window.rb +92 -15
- data/lib/instant_record/syncable.rb +313 -17
- data/lib/instant_record/testing/authoritative_server.rb +547 -0
- data/lib/instant_record/testing/chaos_simulator.rb +429 -0
- data/lib/instant_record/testing/cruby_host_bridge.rb +370 -0
- data/lib/instant_record/testing/fault_network.rb +140 -0
- data/lib/instant_record/testing/parity_suite.rb +435 -0
- data/lib/instant_record/testing/runtimes/base.rb +184 -0
- data/lib/instant_record/testing/runtimes/cruby_runtime.rb +255 -0
- data/lib/instant_record/testing/runtimes/native_runtime.rb +346 -0
- data/lib/instant_record/testing/runtimes/wasm_runtime.rb +371 -0
- data/lib/instant_record/testing/wasm_host_bridge.mjs +240 -0
- data/lib/instant_record/testing.rb +333 -0
- data/lib/instant_record/trace/redactor.rb +278 -0
- data/lib/instant_record/trace/replayer.rb +126 -0
- data/lib/instant_record/trace/schema_extractor.rb +37 -0
- data/lib/instant_record/trace.rb +22 -0
- data/lib/instant_record/version.rb +1 -1
- data/lib/instant_record.rb +107 -37
- data/lib/tasks/instant_record.rake +299 -47
- data/native/ios/InstantRecordNative/Package.swift +12 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/AppHost.swift +706 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Engine.swift +64 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/FileStore.swift +1048 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/HTTPEngine.swift +36 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Icons.swift +19 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Node.swift +64 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/ScreenView.swift +481 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Screens.swift +94 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/StreamClient.swift +74 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncNotice.swift +282 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncSchedule.swift +153 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Theme.swift +140 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Transport.swift +108 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/TypedContracts.swift +237 -0
- data/native/ios/README.md +341 -0
- data/sig/instant_record/inertia.rbs +47 -0
- data/sig/instant_record/native.rbs +38 -0
- metadata +194 -18
- data/lib/generators/instant_record/install/templates/database.js +0 -32
- data/lib/generators/instant_record/install/templates/index.html +0 -69
- data/lib/generators/instant_record/install/templates/rails.sw.js +0 -750
- data/lib/instant_record/local_schema.rb +0 -75
- data/lib/instant_record/pglite_compat.rb +0 -40
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
require "base64"
|
|
2
|
+
require "fileutils"
|
|
3
|
+
require "json"
|
|
4
|
+
require "open3"
|
|
5
|
+
require "tmpdir"
|
|
6
|
+
require "uri"
|
|
7
|
+
require_relative "base"
|
|
8
|
+
|
|
9
|
+
module InstantRecord
|
|
10
|
+
module Testing
|
|
11
|
+
module Runtimes
|
|
12
|
+
# Compiled app.wasm runtime driven headlessly in Node via compiled/web/src/app-host.js.
|
|
13
|
+
# Compiles the WebAssembly.Module once per WasmRuntime instance and hosts N
|
|
14
|
+
# isolated AppHost instances inside one fast persistent Node process.
|
|
15
|
+
class WasmRuntime
|
|
16
|
+
include Base
|
|
17
|
+
|
|
18
|
+
BRIDGE_SCRIPT = File.expand_path("../wasm_host_bridge.mjs", __dir__)
|
|
19
|
+
|
|
20
|
+
class ClientHandle
|
|
21
|
+
attr_reader :id, :runtime
|
|
22
|
+
|
|
23
|
+
def initialize(id:, runtime:)
|
|
24
|
+
@id = id.to_s
|
|
25
|
+
@runtime = runtime
|
|
26
|
+
end
|
|
27
|
+
|
|
28
|
+
def runtime_name = :wasm
|
|
29
|
+
|
|
30
|
+
def request(method, path, body: "", content_type: "application/x-www-form-urlencoded")
|
|
31
|
+
@runtime.execute_request(self, method, path, body: body, content_type: content_type)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# Mirrors compiled/web/src/worker.js:
|
|
35
|
+
# 1. Run wasm_sync (drains outbox and bootstraps if not yet bootstrapped).
|
|
36
|
+
# 2. If bootstrapped, poll GET /events?after=<cursor>&window=0[&identity=<id>]
|
|
37
|
+
# through FaultNetwork and feed the SSE response into wasm_stream.
|
|
38
|
+
# 3. If an identity reset arrived on the stream, run one follow-up wasm_sync
|
|
39
|
+
# so the client re-bootstraps under the new identity.
|
|
40
|
+
def sync(endpoint = InstantRecord::DEFAULT_MOUNT_PATH)
|
|
41
|
+
@runtime.execute_sync(self, endpoint)
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def sync_pass_only(endpoint = InstantRecord::DEFAULT_MOUNT_PATH)
|
|
45
|
+
@runtime.execute_sync_pass_only(self, endpoint)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
def sync_plan
|
|
49
|
+
@runtime.execute_sync_plan(self)
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def consume_stream(chunk)
|
|
53
|
+
@runtime.execute_consume_stream(self, chunk)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def sync_state
|
|
57
|
+
@runtime.execute_sync_state(self)
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def history(key, response = "")
|
|
61
|
+
@runtime.execute_history(self, key, response)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def local_write(model:, operation:, id: nil, attributes: {})
|
|
65
|
+
@runtime.execute_local_write(self, model: model, operation: operation, id: id, attributes: attributes)
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
def verify_frontend_http
|
|
69
|
+
@runtime.execute_verify_frontend_http(self)
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def snapshot_state(model_names:)
|
|
73
|
+
bytes = @runtime.database_bytes(self)
|
|
74
|
+
@runtime.read_sqlite_bytes_state(bytes, model_names: model_names)
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
attr_reader :wasm_path, :network
|
|
79
|
+
|
|
80
|
+
def initialize(wasm_path:, web_node_modules:, network:)
|
|
81
|
+
@wasm_path = File.expand_path(wasm_path.to_s)
|
|
82
|
+
@web_node_modules = File.expand_path(web_node_modules.to_s)
|
|
83
|
+
@network = network
|
|
84
|
+
@stage_dir = nil
|
|
85
|
+
@stdin = nil
|
|
86
|
+
@stdout = nil
|
|
87
|
+
@stderr = nil
|
|
88
|
+
@wait_thr = nil
|
|
89
|
+
start_bridge!
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
def name = :wasm
|
|
93
|
+
|
|
94
|
+
def create_client(client_id, env: {})
|
|
95
|
+
res = rpc({ op: "create_client", client: client_id.to_s, env: env })
|
|
96
|
+
assert_clean_stderr!(res["errors"], context: "wasm boot(#{client_id})")
|
|
97
|
+
ClientHandle.new(id: client_id, runtime: self)
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
def close
|
|
101
|
+
if @stdin && !@stdin.closed?
|
|
102
|
+
begin
|
|
103
|
+
rpc({ op: "shutdown" })
|
|
104
|
+
rescue StandardError
|
|
105
|
+
nil
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
ensure
|
|
109
|
+
[@stdin, @stdout, @stderr].each do |io|
|
|
110
|
+
io.close if io && !io.closed?
|
|
111
|
+
rescue StandardError
|
|
112
|
+
nil
|
|
113
|
+
end
|
|
114
|
+
@wait_thr&.join(2)
|
|
115
|
+
FileUtils.remove_entry(@stage_dir) if @stage_dir && Dir.exist?(@stage_dir)
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
def execute_request(client, method, path, body:, content_type:)
|
|
119
|
+
res = rpc({
|
|
120
|
+
op: "request",
|
|
121
|
+
client: client.id,
|
|
122
|
+
method: method.to_s.upcase,
|
|
123
|
+
path: path.to_s,
|
|
124
|
+
body: body.to_s,
|
|
125
|
+
contentType: content_type
|
|
126
|
+
})
|
|
127
|
+
assert_clean_stderr!(res["errors"], context: "wasm request(#{client.id}, #{method} #{path})")
|
|
128
|
+
if res["exit"] != 0
|
|
129
|
+
raise InstantRecord::Testing::Error, "wasm_request exited with #{res['exit']} on #{method} #{path}"
|
|
130
|
+
end
|
|
131
|
+
{
|
|
132
|
+
status: res["status"].to_i,
|
|
133
|
+
headers: res["headers"] || [],
|
|
134
|
+
body: res["body"].to_s,
|
|
135
|
+
exit: res["exit"],
|
|
136
|
+
errors: res["errors"] || []
|
|
137
|
+
}
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
def execute_sync_pass_only(client, endpoint)
|
|
141
|
+
res, fault_fired = @network.track_faults do
|
|
142
|
+
rpc({ op: "sync", client: client.id, endpoint: endpoint.to_s })
|
|
143
|
+
end
|
|
144
|
+
assert_clean_stderr!(res["errors"], context: "wasm sync(#{client.id})", allow_offline_warning: fault_fired)
|
|
145
|
+
if res["exit"] != 0
|
|
146
|
+
raise InstantRecord::Testing::Error, "wasm_sync exited with #{res['exit']} (errors=#{res['errors'].inspect})"
|
|
147
|
+
end
|
|
148
|
+
if res["pending"].to_i < 0
|
|
149
|
+
raise InstantRecord::Testing::Error, "wasm_sync reported pending=#{res['pending']} (expected >= 0)"
|
|
150
|
+
end
|
|
151
|
+
{
|
|
152
|
+
changed: !!res["changed"],
|
|
153
|
+
pending: res["pending"].to_i,
|
|
154
|
+
cursor: res["cursor"].to_i,
|
|
155
|
+
notified: !!res["notified"],
|
|
156
|
+
changes: normalize_changes(res["changes"]),
|
|
157
|
+
exchanges: res["exchanges"] || [],
|
|
158
|
+
exit: res["exit"],
|
|
159
|
+
errors: res["errors"] || [],
|
|
160
|
+
fault_fired: fault_fired
|
|
161
|
+
}
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
def execute_sync(client, endpoint)
|
|
165
|
+
pass = execute_sync_pass_only(client, endpoint)
|
|
166
|
+
state = execute_sync_state(client)
|
|
167
|
+
return pass unless state[:bootstrapped]
|
|
168
|
+
|
|
169
|
+
# Mirror compiled/web/src/worker.js: pull inbound SSE catch-up and feed
|
|
170
|
+
# into wasm_stream (since main_wasm.rb sets Client.streaming = true).
|
|
171
|
+
events_url = "#{endpoint}/events?after=#{state[:cursor]}&window=0"
|
|
172
|
+
events_url += "&identity=#{state[:identity]}" unless state[:identity].empty?
|
|
173
|
+
|
|
174
|
+
reply, poll_fault = @network.track_faults do
|
|
175
|
+
@network.exchange(client.id, "GET", events_url, "")
|
|
176
|
+
end
|
|
177
|
+
pass[:exchanges] << "GET #{events_url} -> #{reply[:status]}"
|
|
178
|
+
pass[:fault_fired] ||= poll_fault
|
|
179
|
+
|
|
180
|
+
if reply[:status].to_i >= 200 && reply[:status].to_i < 300 && !reply[:body].to_s.empty?
|
|
181
|
+
stream_res = execute_consume_stream(client, reply[:body])
|
|
182
|
+
pass[:changed] ||= stream_res[:applied] > 0
|
|
183
|
+
pass[:cursor] = stream_res[:cursor]
|
|
184
|
+
if stream_res[:notified]
|
|
185
|
+
pass[:notified] = true
|
|
186
|
+
pass[:changes] = stream_res[:changes]
|
|
187
|
+
end
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
pass
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
def execute_sync_plan(client)
|
|
194
|
+
res = rpc({ op: "sync_plan", client: client.id })
|
|
195
|
+
assert_clean_stderr!(res["errors"], context: "wasm sync_plan(#{client.id})")
|
|
196
|
+
res["plan"]
|
|
197
|
+
end
|
|
198
|
+
|
|
199
|
+
def execute_consume_stream(client, chunk)
|
|
200
|
+
res = rpc({ op: "consume_stream", client: client.id, chunk: chunk.to_s })
|
|
201
|
+
assert_clean_stderr!(res["errors"], context: "wasm consume_stream(#{client.id})")
|
|
202
|
+
if res["exit"] != 0
|
|
203
|
+
raise InstantRecord::Testing::Error, "wasm_stream exited with #{res['exit']} (errors=#{res['errors'].inspect})"
|
|
204
|
+
end
|
|
205
|
+
{
|
|
206
|
+
applied: res["applied"].to_i,
|
|
207
|
+
cursor: res["cursor"].to_i,
|
|
208
|
+
bootstrapped: !!res["bootstrapped"],
|
|
209
|
+
notified: !!res["notified"],
|
|
210
|
+
changes: normalize_changes(res["changes"]),
|
|
211
|
+
exit: res["exit"],
|
|
212
|
+
errors: res["errors"] || []
|
|
213
|
+
}
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
def execute_sync_state(client)
|
|
217
|
+
res = rpc({ op: "sync_state", client: client.id })
|
|
218
|
+
assert_clean_stderr!(res["errors"], context: "wasm sync_state(#{client.id})")
|
|
219
|
+
{
|
|
220
|
+
bootstrapped: !!res["bootstrapped"],
|
|
221
|
+
cursor: res["cursor"].to_i,
|
|
222
|
+
pending: res["pending"].to_i,
|
|
223
|
+
identity: res["identity"].to_s
|
|
224
|
+
}
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
def execute_history(client, key, response)
|
|
228
|
+
res = rpc({ op: "history", client: client.id, key: key.to_s, response: response.to_s })
|
|
229
|
+
assert_clean_stderr!(res["errors"], context: "wasm history(#{client.id})")
|
|
230
|
+
res["history"]
|
|
231
|
+
end
|
|
232
|
+
|
|
233
|
+
def execute_local_write(client, model:, operation:, id:, attributes:)
|
|
234
|
+
attrs = attributes.transform_keys(&:to_s)
|
|
235
|
+
case [model.to_s, operation.to_s]
|
|
236
|
+
when ["Issue", "create"]
|
|
237
|
+
res = execute_request(client, "POST", "/todo/issues", body: URI.encode_www_form("issue[title]" => attrs["title"]), content_type: "application/x-www-form-urlencoded")
|
|
238
|
+
raise Error, "Expected 200/302 on POST /todo/issues, got #{res[:status]}" unless [200, 302, 303].include?(res[:status])
|
|
239
|
+
newest_id_from_snapshot(client, "Issue", title: attrs["title"])
|
|
240
|
+
when ["Issue", "update"]
|
|
241
|
+
done = attrs["state"].to_s == "done" ? "1" : "0"
|
|
242
|
+
res = execute_request(client, "POST", "/todo/issues/#{id}", body: URI.encode_www_form("_method" => "patch", "done" => done), content_type: "application/x-www-form-urlencoded")
|
|
243
|
+
raise Error, "Expected 200/302 on PATCH /todo/issues/#{id}, got #{res[:status]}" unless [200, 302, 303].include?(res[:status])
|
|
244
|
+
id
|
|
245
|
+
when ["Issue", "destroy"]
|
|
246
|
+
res = execute_request(client, "POST", "/todo/issues/#{id}", body: URI.encode_www_form("_method" => "delete"), content_type: "application/x-www-form-urlencoded")
|
|
247
|
+
raise Error, "Expected 200/302 on DELETE /todo/issues/#{id}, got #{res[:status]}" unless [200, 302, 303].include?(res[:status])
|
|
248
|
+
id
|
|
249
|
+
when ["AuthNote", "create"]
|
|
250
|
+
form = {
|
|
251
|
+
"note[title]" => attrs["title"],
|
|
252
|
+
"note[body]" => attrs["body"].to_s,
|
|
253
|
+
"note[audience]" => attrs["audience"] || "owner",
|
|
254
|
+
"note[owner_id]" => attrs["owner_id"].to_s
|
|
255
|
+
}
|
|
256
|
+
res = execute_request(client, "POST", "/auth/notes", body: URI.encode_www_form(form), content_type: "application/x-www-form-urlencoded")
|
|
257
|
+
raise Error, "Expected 200/302 on POST /auth/notes, got #{res[:status]}" unless [200, 302, 303].include?(res[:status])
|
|
258
|
+
newest_id_from_snapshot(client, "AuthNote", title: attrs["title"])
|
|
259
|
+
when ["AuthNote", "destroy"]
|
|
260
|
+
res = execute_request(client, "POST", "/auth/notes/#{id}", body: URI.encode_www_form("_method" => "delete"), content_type: "application/x-www-form-urlencoded")
|
|
261
|
+
raise Error, "Expected 200/302 on DELETE /auth/notes/#{id}, got #{res[:status]}" unless [200, 302, 303].include?(res[:status])
|
|
262
|
+
id
|
|
263
|
+
else
|
|
264
|
+
raise ArgumentError, "Unsupported compiled local_write: #{model}##{operation}"
|
|
265
|
+
end
|
|
266
|
+
end
|
|
267
|
+
|
|
268
|
+
def execute_verify_frontend_http(client)
|
|
269
|
+
http_path = File.join(InstantRecord::Testing.gem_root.to_s, "frontend/http.js")
|
|
270
|
+
res = rpc({ op: "verify_frontend_http", client: client.id, httpPath: http_path })
|
|
271
|
+
assert_clean_stderr!(res["errors"], context: "wasm frontend/http.js(#{client.id})")
|
|
272
|
+
res
|
|
273
|
+
end
|
|
274
|
+
|
|
275
|
+
def database_bytes(client)
|
|
276
|
+
res = rpc({ op: "database_bytes", client: client.id })
|
|
277
|
+
Base64.strict_decode64(res["base64"].to_s)
|
|
278
|
+
end
|
|
279
|
+
|
|
280
|
+
private
|
|
281
|
+
|
|
282
|
+
def normalize_changes(list)
|
|
283
|
+
return nil if list.nil?
|
|
284
|
+
|
|
285
|
+
Array(list).map { |c| { type: c["type"].to_s, id: c["id"].to_s } }
|
|
286
|
+
end
|
|
287
|
+
|
|
288
|
+
def newest_id_from_snapshot(client, model_name, title:)
|
|
289
|
+
state = read_sqlite_bytes_state(database_bytes(client), model_names: [model_name])
|
|
290
|
+
rows = state[:tables][model_name].select { |r| r["title"] == title }
|
|
291
|
+
rows.max_by { |r| r["created_at"].to_s }&.fetch("id")
|
|
292
|
+
end
|
|
293
|
+
|
|
294
|
+
def prepare_app_host_path
|
|
295
|
+
gem_root = InstantRecord::Testing.gem_root.to_s
|
|
296
|
+
direct = File.join(gem_root, "compiled/web/src/app-host.js")
|
|
297
|
+
if File.directory?(File.join(gem_root, "compiled/web/node_modules/@bjorn3/browser_wasi_shim"))
|
|
298
|
+
return direct
|
|
299
|
+
end
|
|
300
|
+
|
|
301
|
+
# Stage app-host.js + changes.js beside a symlinked node_modules so ESM
|
|
302
|
+
# resolution of @bjorn3/browser_wasi_shim works on every Node version
|
|
303
|
+
# without modifying the working tree.
|
|
304
|
+
@stage_dir = Dir.mktmpdir("instant-record-wasm-host")
|
|
305
|
+
File.symlink(@web_node_modules, File.join(@stage_dir, "node_modules"))
|
|
306
|
+
FileUtils.cp(File.join(gem_root, "compiled/web/src/app-host.js"), File.join(@stage_dir, "app-host.js"))
|
|
307
|
+
FileUtils.cp(File.join(gem_root, "compiled/web/src/changes.js"), File.join(@stage_dir, "changes.js"))
|
|
308
|
+
File.join(@stage_dir, "app-host.js")
|
|
309
|
+
end
|
|
310
|
+
|
|
311
|
+
def start_bridge!
|
|
312
|
+
app_host_js = prepare_app_host_path
|
|
313
|
+
frontend_http = File.join(InstantRecord::Testing.gem_root.to_s, "frontend/http.js")
|
|
314
|
+
@stdin, @stdout, @stderr, @wait_thr = Open3.popen3("node", BRIDGE_SCRIPT, app_host_js, @wasm_path, frontend_http)
|
|
315
|
+
@stdin.sync = true
|
|
316
|
+
|
|
317
|
+
ready = read_message
|
|
318
|
+
unless ready && ready["type"] == "ready"
|
|
319
|
+
err_out = read_bridge_stderr
|
|
320
|
+
raise InstantRecord::Testing::Error, "Wasm bridge failed to start: #{ready.inspect} #{err_out}"
|
|
321
|
+
end
|
|
322
|
+
end
|
|
323
|
+
|
|
324
|
+
def rpc(payload)
|
|
325
|
+
@stdin.puts(JSON.generate(payload))
|
|
326
|
+
@stdin.flush
|
|
327
|
+
|
|
328
|
+
loop do
|
|
329
|
+
msg = read_message
|
|
330
|
+
unless msg
|
|
331
|
+
err_out = read_bridge_stderr
|
|
332
|
+
raise InstantRecord::Testing::Error, "Wasm bridge exited unexpectedly during #{payload[:op]}: #{err_out}"
|
|
333
|
+
end
|
|
334
|
+
|
|
335
|
+
case msg["type"]
|
|
336
|
+
when "exchange"
|
|
337
|
+
reply = @network.exchange(msg["client"], msg["method"], msg["url"], msg["body"].to_s)
|
|
338
|
+
@stdin.puts(JSON.generate({ status: reply[:status], body: reply[:body].to_s }))
|
|
339
|
+
@stdin.flush
|
|
340
|
+
when "result"
|
|
341
|
+
return msg
|
|
342
|
+
when "error"
|
|
343
|
+
raise InstantRecord::Testing::Error, "Wasm bridge error during #{payload[:op]}: #{msg['message']}"
|
|
344
|
+
else
|
|
345
|
+
raise InstantRecord::Testing::Error, "Unexpected Wasm bridge message: #{msg.inspect}"
|
|
346
|
+
end
|
|
347
|
+
end
|
|
348
|
+
end
|
|
349
|
+
|
|
350
|
+
def read_message
|
|
351
|
+
line = @stdout.gets
|
|
352
|
+
return nil unless line
|
|
353
|
+
|
|
354
|
+
JSON.parse(line)
|
|
355
|
+
end
|
|
356
|
+
|
|
357
|
+
def read_bridge_stderr
|
|
358
|
+
return "" unless @stderr && !@stderr.closed?
|
|
359
|
+
|
|
360
|
+
out = +""
|
|
361
|
+
loop do
|
|
362
|
+
chunk = @stderr.read_nonblock(4096)
|
|
363
|
+
out << chunk
|
|
364
|
+
end
|
|
365
|
+
rescue IO::WaitReadable, EOFError
|
|
366
|
+
out
|
|
367
|
+
end
|
|
368
|
+
end
|
|
369
|
+
end
|
|
370
|
+
end
|
|
371
|
+
end
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
// Persistent Node.js headless bridge for compiled app.wasm using AppHost
|
|
2
|
+
// (compiled/web/src/app-host.js). Speaks synchronous NDJSON over stdin/stdout
|
|
3
|
+
// so Ruby's FaultNetwork answers AppHost's synchronous `exchange(method, url, body)`
|
|
4
|
+
// callback inline with zero sockets and zero polling.
|
|
5
|
+
//
|
|
6
|
+
// Usage: node wasm_host_bridge.mjs <app-host.js path> <app.wasm path> [frontend/http.js path]
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import { pathToFileURL } from "node:url";
|
|
9
|
+
|
|
10
|
+
const [appHostPath, wasmPath, frontendHttpPath] = process.argv.slice(2);
|
|
11
|
+
if (!appHostPath || !wasmPath) {
|
|
12
|
+
process.stderr.write("usage: node wasm_host_bridge.mjs <app-host.js> <app.wasm> [frontend/http.js]\n");
|
|
13
|
+
process.exit(64);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const { AppHost } = await import(pathToFileURL(appHostPath).href);
|
|
17
|
+
const wasmModule = new WebAssembly.Module(fs.readFileSync(wasmPath));
|
|
18
|
+
const clients = new Map();
|
|
19
|
+
|
|
20
|
+
let readBuffer = Buffer.alloc(0);
|
|
21
|
+
|
|
22
|
+
function readLineSync() {
|
|
23
|
+
const chunk = Buffer.alloc(16384);
|
|
24
|
+
while (true) {
|
|
25
|
+
const nl = readBuffer.indexOf(0x0a);
|
|
26
|
+
if (nl !== -1) {
|
|
27
|
+
const line = readBuffer.subarray(0, nl).toString("utf8");
|
|
28
|
+
readBuffer = readBuffer.subarray(nl + 1);
|
|
29
|
+
return line;
|
|
30
|
+
}
|
|
31
|
+
let bytesRead;
|
|
32
|
+
try {
|
|
33
|
+
bytesRead = fs.readSync(0, chunk, 0, chunk.length, null);
|
|
34
|
+
} catch (err) {
|
|
35
|
+
if (err.code === "EAGAIN" || err.code === "EINTR") continue;
|
|
36
|
+
throw err;
|
|
37
|
+
}
|
|
38
|
+
if (bytesRead === 0) return null;
|
|
39
|
+
readBuffer = Buffer.concat([readBuffer, chunk.subarray(0, bytesRead)]);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function writeLineSync(obj) {
|
|
44
|
+
const data = Buffer.from(JSON.stringify(obj) + "\n", "utf8");
|
|
45
|
+
let offset = 0;
|
|
46
|
+
while (offset < data.length) {
|
|
47
|
+
try {
|
|
48
|
+
offset += fs.writeSync(1, data, offset, data.length - offset);
|
|
49
|
+
} catch (err) {
|
|
50
|
+
if (err.code === "EAGAIN" || err.code === "EINTR") continue;
|
|
51
|
+
throw err;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function syncExchange(clientId) {
|
|
57
|
+
return (method, url, body) => {
|
|
58
|
+
writeLineSync({ type: "exchange", client: clientId, method, url, body });
|
|
59
|
+
const raw = readLineSync();
|
|
60
|
+
if (raw === null) throw new Error("EOF waiting for exchange reply");
|
|
61
|
+
const reply = JSON.parse(raw);
|
|
62
|
+
return { status: Number(reply.status || 0), body: String(reply.body ?? "") };
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function getClient(id) {
|
|
67
|
+
const host = clients.get(id);
|
|
68
|
+
if (!host) throw new Error(`Unknown wasm client: ${id}`);
|
|
69
|
+
return host;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Verify frontend/http.js (`write` and `localHttpClient.request`) directly
|
|
73
|
+
// against a live AppHost instance via an injected fetch shim.
|
|
74
|
+
async function verifyFrontendHttp(clientId, httpFilePath) {
|
|
75
|
+
const host = getClient(clientId);
|
|
76
|
+
const rawSource = fs.readFileSync(httpFilePath, "utf8");
|
|
77
|
+
// Inline a minimal HttpResponseError stub so frontend/http.js executes in
|
|
78
|
+
// bare Node without requiring @inertiajs/core in WEB_NODE_MODULES.
|
|
79
|
+
const stubbed = rawSource.replace(
|
|
80
|
+
/import\s+\{\s*HttpResponseError\s*\}\s+from\s+["']@inertiajs\/core["'];?/,
|
|
81
|
+
"class HttpResponseError extends Error { constructor(msg, response, url) { super(msg); this.response = response; this.url = url; } }"
|
|
82
|
+
);
|
|
83
|
+
const modUrl = "data:text/javascript;base64," + Buffer.from(stubbed, "utf8").toString("base64");
|
|
84
|
+
const { write, localHttpClient } = await import(modUrl);
|
|
85
|
+
|
|
86
|
+
const prevWindow = globalThis.window;
|
|
87
|
+
const prevDocument = globalThis.document;
|
|
88
|
+
const prevFetch = globalThis.fetch;
|
|
89
|
+
const calls = [];
|
|
90
|
+
const stderrLines = [];
|
|
91
|
+
|
|
92
|
+
globalThis.window = { location: { href: "http://localhost/todo" } };
|
|
93
|
+
globalThis.document = { cookie: "XSRF-TOKEN=test-csrf-token" };
|
|
94
|
+
globalThis.fetch = async (input, init = {}) => {
|
|
95
|
+
const parsed = new URL(String(input), "http://localhost");
|
|
96
|
+
const method = (init.method || "GET").toUpperCase();
|
|
97
|
+
const bodyText = init.body ? String(init.body) : "";
|
|
98
|
+
const res = host.request(method, parsed.pathname + parsed.search, {
|
|
99
|
+
body: bodyText,
|
|
100
|
+
contentType: "application/x-www-form-urlencoded",
|
|
101
|
+
});
|
|
102
|
+
calls.push({ method, path: parsed.pathname + parsed.search, status: res.status, exit: res.exit });
|
|
103
|
+
stderrLines.push(...res.errors);
|
|
104
|
+
if (res.exit !== 0) {
|
|
105
|
+
throw new Error(`wasm_request failed with exit=${res.exit}: ${res.errors.join("; ")}`);
|
|
106
|
+
}
|
|
107
|
+
const isRedirect = res.status >= 300 && res.status < 400;
|
|
108
|
+
return {
|
|
109
|
+
ok: res.status >= 200 && res.status < 300,
|
|
110
|
+
status: res.status,
|
|
111
|
+
type: isRedirect && init.redirect === "manual" ? "opaqueredirect" : "basic",
|
|
112
|
+
text: async () => res.body,
|
|
113
|
+
};
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
try {
|
|
117
|
+
// 1. Exercise `write()` (frontend/http.js:40-49): form POST with 302 redirect.
|
|
118
|
+
await write("/todo/issues", { "issue[title]": "frontend-http-write" });
|
|
119
|
+
|
|
120
|
+
// 2. Exercise `localHttpClient.request()` GET + _inertia=1 + _only query params.
|
|
121
|
+
const page = await localHttpClient.request({
|
|
122
|
+
method: "GET",
|
|
123
|
+
url: "/todo",
|
|
124
|
+
params: {},
|
|
125
|
+
headers: { "X-Inertia-Partial-Data": "issues" },
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
// 3. Exercise `localHttpClient.request()` POST write followed by page fetch.
|
|
129
|
+
const indexRes = host.request("GET", "/todo");
|
|
130
|
+
stderrLines.push(...indexRes.errors);
|
|
131
|
+
|
|
132
|
+
return {
|
|
133
|
+
ok: true,
|
|
134
|
+
calls,
|
|
135
|
+
pageStatus: page.status,
|
|
136
|
+
containsWrittenTitle: indexRes.body.includes("frontend-http-write"),
|
|
137
|
+
errors: stderrLines,
|
|
138
|
+
};
|
|
139
|
+
} finally {
|
|
140
|
+
globalThis.window = prevWindow;
|
|
141
|
+
globalThis.document = prevDocument;
|
|
142
|
+
globalThis.fetch = prevFetch;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
writeLineSync({ type: "ready" });
|
|
147
|
+
|
|
148
|
+
while (true) {
|
|
149
|
+
const line = readLineSync();
|
|
150
|
+
if (line === null) break;
|
|
151
|
+
if (!line.trim()) continue;
|
|
152
|
+
|
|
153
|
+
try {
|
|
154
|
+
const cmd = JSON.parse(line);
|
|
155
|
+
switch (cmd.op) {
|
|
156
|
+
case "create_client": {
|
|
157
|
+
const host = new AppHost(wasmModule, {
|
|
158
|
+
exchange: syncExchange(cmd.client),
|
|
159
|
+
env: cmd.env || {},
|
|
160
|
+
});
|
|
161
|
+
host.ensureBooted();
|
|
162
|
+
const bootErrors = host.errors.slice();
|
|
163
|
+
clients.set(cmd.client, host);
|
|
164
|
+
writeLineSync({ type: "result", ok: true, errors: bootErrors });
|
|
165
|
+
break;
|
|
166
|
+
}
|
|
167
|
+
case "destroy_client": {
|
|
168
|
+
clients.delete(cmd.client);
|
|
169
|
+
writeLineSync({ type: "result", ok: true });
|
|
170
|
+
break;
|
|
171
|
+
}
|
|
172
|
+
case "request": {
|
|
173
|
+
const host = getClient(cmd.client);
|
|
174
|
+
const res = host.request(cmd.method, cmd.path, {
|
|
175
|
+
body: cmd.body ?? "",
|
|
176
|
+
contentType: cmd.contentType || "application/x-www-form-urlencoded",
|
|
177
|
+
});
|
|
178
|
+
writeLineSync({ type: "result", ...res });
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
case "sync": {
|
|
182
|
+
const host = getClient(cmd.client);
|
|
183
|
+
const res = host.sync(cmd.endpoint || "");
|
|
184
|
+
writeLineSync({ type: "result", ...res });
|
|
185
|
+
break;
|
|
186
|
+
}
|
|
187
|
+
case "sync_plan": {
|
|
188
|
+
const host = getClient(cmd.client);
|
|
189
|
+
const plan = host.syncPlan();
|
|
190
|
+
writeLineSync({ type: "result", plan, errors: host.errors.slice() });
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
case "consume_stream": {
|
|
194
|
+
const host = getClient(cmd.client);
|
|
195
|
+
const res = host.consumeStream(cmd.chunk ?? "");
|
|
196
|
+
writeLineSync({ type: "result", ...res });
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
case "sync_state": {
|
|
200
|
+
const host = getClient(cmd.client);
|
|
201
|
+
const state = host.syncState();
|
|
202
|
+
writeLineSync({ type: "result", ...state, errors: host.errors.slice() });
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
case "history": {
|
|
206
|
+
const host = getClient(cmd.client);
|
|
207
|
+
const res = host.history(cmd.key, cmd.response ?? "");
|
|
208
|
+
writeLineSync({ type: "result", history: res, errors: host.errors.slice() });
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
case "database_bytes": {
|
|
212
|
+
const host = getClient(cmd.client);
|
|
213
|
+
const bytes = host.databaseBytes();
|
|
214
|
+
const b64 = bytes ? Buffer.from(bytes).toString("base64") : "";
|
|
215
|
+
writeLineSync({ type: "result", base64: b64 });
|
|
216
|
+
break;
|
|
217
|
+
}
|
|
218
|
+
case "restore_database": {
|
|
219
|
+
const host = getClient(cmd.client);
|
|
220
|
+
const raw = Buffer.from(cmd.base64 || "", "base64");
|
|
221
|
+
host.restoreDatabase(new Uint8Array(raw), cmd.schemaVersion || 0);
|
|
222
|
+
writeLineSync({ type: "result", ok: true });
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
case "verify_frontend_http": {
|
|
226
|
+
const res = await verifyFrontendHttp(cmd.client, cmd.httpPath || frontendHttpPath);
|
|
227
|
+
writeLineSync({ type: "result", ...res });
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
230
|
+
case "shutdown": {
|
|
231
|
+
writeLineSync({ type: "result", ok: true });
|
|
232
|
+
process.exit(0);
|
|
233
|
+
}
|
|
234
|
+
default:
|
|
235
|
+
writeLineSync({ type: "error", message: `Unknown op: ${cmd.op}` });
|
|
236
|
+
}
|
|
237
|
+
} catch (err) {
|
|
238
|
+
writeLineSync({ type: "error", message: err?.stack || err?.message || String(err) });
|
|
239
|
+
}
|
|
240
|
+
}
|