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,832 @@
|
|
|
1
|
+
require "fileutils"
|
|
2
|
+
require "json"
|
|
3
|
+
require "prism"
|
|
4
|
+
require_relative "../native"
|
|
5
|
+
require_relative "manifest"
|
|
6
|
+
require_relative "host_adapters"
|
|
7
|
+
require_relative "runner"
|
|
8
|
+
|
|
9
|
+
module InstantRecord
|
|
10
|
+
class Compiler
|
|
11
|
+
# Builds the reactor entry files (`main_wasm.rb` and `main_native.rb`) from
|
|
12
|
+
# a shared bridge and boot template, driven by `instant_record.manifest.json`.
|
|
13
|
+
module EntryBuilder
|
|
14
|
+
BANNER = "\n\n# ── persistent reactor entry"
|
|
15
|
+
MODEL_NAME_PATTERN = /\A[A-Z]\w*(?:::[A-Z]\w*)*\z/
|
|
16
|
+
COLUMN_NAME_PATTERN = /\A[a-z_][a-z0-9_]*\z/
|
|
17
|
+
|
|
18
|
+
PRELUDE = <<~'RUBY'
|
|
19
|
+
|
|
20
|
+
class Hash
|
|
21
|
+
def deep_stringify_keys
|
|
22
|
+
result = {}
|
|
23
|
+
each do |key, value|
|
|
24
|
+
result[key.to_s] = value.is_a?(Hash) ? value.deep_stringify_keys : value
|
|
25
|
+
end
|
|
26
|
+
result
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
RUBY
|
|
30
|
+
|
|
31
|
+
# <<read:NAME>> and <<write:NAME>> are the host's two calls, filled per target.
|
|
32
|
+
BRIDGE = <<~'RUBY'
|
|
33
|
+
|
|
34
|
+
module <<bridge>>
|
|
35
|
+
def self.handle_request
|
|
36
|
+
InstantRecord::Client.clear_events
|
|
37
|
+
req = Tep::Parser.parse(<<read:in>>)
|
|
38
|
+
res = Tep::Response.new
|
|
39
|
+
reads = InstantRecord::ReadTracker.track do
|
|
40
|
+
InstantRecord::Client.capture_local_changes do
|
|
41
|
+
Tep::APP.dispatch(req, res)
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
out = +""
|
|
45
|
+
out << res.status.to_s << "\n"
|
|
46
|
+
res.headers.each { |name, value| out << name.to_s << ": " << value.to_s << "\n" }
|
|
47
|
+
res.header_fields.each { |pair| out << pair[0].to_s << ": " << pair[1].to_s << "\n" }
|
|
48
|
+
res.set_cookies.each { |cookie| out << "Set-Cookie: " << cookie.to_s << "\n" }
|
|
49
|
+
out << "X-File-Path: " << res.file_path << "\n" if res.file_path.length > 0
|
|
50
|
+
reads_json = InstantRecord::ReadTracker.serialize(reads)
|
|
51
|
+
out << "X-Instant-Record-Reads: " << reads_json << "\n" unless reads_json.empty?
|
|
52
|
+
out << "\n" << res.body
|
|
53
|
+
<<write:out>>out)
|
|
54
|
+
0
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# Capture the next bounded outgoing batch before the worker yields to browser requests.
|
|
58
|
+
def self.sync_plan
|
|
59
|
+
InstantRecord::Client.clear_events
|
|
60
|
+
mutations = InstantRecord::Client.plan_drain
|
|
61
|
+
push = mutations.empty? ? "" : JSON.generate(InstantRecord::Client.mutations_payload(mutations))
|
|
62
|
+
headers = InstantRecord::Client.request_headers
|
|
63
|
+
next_ms = InstantRecord::Client.next_release_ms
|
|
64
|
+
plan = {
|
|
65
|
+
push: push,
|
|
66
|
+
mutation_ids: mutations.map { |m| m[:id] },
|
|
67
|
+
bootstrap: !InstantRecord::Client.bootstrapped?,
|
|
68
|
+
fingerprint: "<<shell_fingerprint>>"
|
|
69
|
+
}
|
|
70
|
+
plan[:headers] = headers unless headers.empty?
|
|
71
|
+
plan[:next_release_ms] = next_ms unless next_ms.nil?
|
|
72
|
+
<<write:out>>JSON.generate(plan))
|
|
73
|
+
0
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def self.handle_sync
|
|
77
|
+
InstantRecord::Client.clear_events
|
|
78
|
+
raw = <<read:in>>.strip
|
|
79
|
+
if raw.start_with?("{")
|
|
80
|
+
input = JSON.parse(raw)
|
|
81
|
+
endpoint = input["endpoint"].to_s.strip
|
|
82
|
+
InstantRecord.config.endpoint = endpoint if endpoint.length > 0
|
|
83
|
+
outcome = InstantRecord::Client.apply_prepared_sync(
|
|
84
|
+
push: input["push"],
|
|
85
|
+
bootstrap: input["bootstrap"]
|
|
86
|
+
)
|
|
87
|
+
changed = outcome[:changed]
|
|
88
|
+
suffix = " progressed=" + (outcome[:progressed] ? "1" : "0") +
|
|
89
|
+
" failed=" + (outcome[:failed] ? "1" : "0") +
|
|
90
|
+
" quarantined=" + outcome[:quarantined].to_s
|
|
91
|
+
else
|
|
92
|
+
InstantRecord.config.endpoint = raw if raw.length > 0
|
|
93
|
+
changed = InstantRecord::Client.sync_pass
|
|
94
|
+
suffix = ""
|
|
95
|
+
end
|
|
96
|
+
next_ms = InstantRecord::Client.next_release_ms
|
|
97
|
+
out = (changed ? "changed" : "unchanged") +
|
|
98
|
+
" pending=" + InstantRecord::Client.pending_count.to_s +
|
|
99
|
+
" cursor=" + InstantRecord::Client.cursor.to_s +
|
|
100
|
+
" held=" + InstantRecord::Client.held_count.to_s
|
|
101
|
+
out += " next_release_ms=" + next_ms.to_s unless next_ms.nil?
|
|
102
|
+
out += suffix
|
|
103
|
+
<<write:out>>out)
|
|
104
|
+
0
|
|
105
|
+
ensure
|
|
106
|
+
InstantRecord::Client.clear_planned_drain
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def self.handle_stream
|
|
110
|
+
InstantRecord::Client.clear_events
|
|
111
|
+
applied = InstantRecord::Client.consume_stream(<<read:in>>)
|
|
112
|
+
# A batch can be the server's reset, after which there is no cursor to report.
|
|
113
|
+
<<write:out>>"applied=" + applied.to_s + " cursor=" + InstantRecord::Client.cursor.to_s + " bootstrap=" + (InstantRecord::Client.bootstrapped? ? "ready" : "needed"))
|
|
114
|
+
0
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# History has its own keyset and must not advance the live change cursor.
|
|
118
|
+
# Route through Client's durable SQLite history ledger so CRuby, WASM,
|
|
119
|
+
# and Native share one contiguity model and eviction invalidates it.
|
|
120
|
+
def self.history
|
|
121
|
+
InstantRecord::Client.clear_events
|
|
122
|
+
input = JSON.parse(<<read:in>>)
|
|
123
|
+
result = InstantRecord::Client.handle_history(
|
|
124
|
+
key: input["key"].to_s,
|
|
125
|
+
response: input["response"].to_s
|
|
126
|
+
)
|
|
127
|
+
<<write:out>>JSON.generate(result))
|
|
128
|
+
0
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
def self.cursor
|
|
132
|
+
InstantRecord::Client.clear_events
|
|
133
|
+
key = InstantRecord::Client.identity_key
|
|
134
|
+
next_ms = InstantRecord::Client.next_release_ms
|
|
135
|
+
out = "cursor=" + InstantRecord::Client.cursor.to_s + " pending=" + InstantRecord::Client.pending_count.to_s + " bootstrap=" + (InstantRecord::Client.bootstrapped? ? "ready" : "needed") + " identity=" + (key.nil? ? "" : key) + " notices=" + InstantRecord::SyncNotice.active.count.to_s + " held=" + InstantRecord::Client.held_count.to_s
|
|
136
|
+
out += " next_release_ms=" + next_ms.to_s unless next_ms.nil?
|
|
137
|
+
<<write:out>>out)
|
|
138
|
+
0
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
# List or resolve quarantined sync notices ("list", "retry", "fork", "dismiss").
|
|
142
|
+
def self.notices
|
|
143
|
+
InstantRecord::Client.clear_events
|
|
144
|
+
raw = <<read:in>>.to_s.strip
|
|
145
|
+
input = raw.empty? ? {} : JSON.parse(raw)
|
|
146
|
+
action = input["action"].to_s
|
|
147
|
+
action = "list" if action.empty?
|
|
148
|
+
result =
|
|
149
|
+
if action == "list"
|
|
150
|
+
{ "ok" => true, "notices" => InstantRecord::SyncNotice.active.recent.map { |n| n.as_notice } }
|
|
151
|
+
else
|
|
152
|
+
resolved = InstantRecord::SyncNotice.resolve(input["id"], action: action, overrides: input["overrides"])
|
|
153
|
+
if action == "retry" || action == "fork"
|
|
154
|
+
InstantRecord::Client.unlisted_changes
|
|
155
|
+
InstantRecord::Client.notify_changed
|
|
156
|
+
end
|
|
157
|
+
resolved
|
|
158
|
+
end
|
|
159
|
+
<<write:out>>JSON.generate(result))
|
|
160
|
+
0
|
|
161
|
+
rescue StandardError => error
|
|
162
|
+
<<write:out>>JSON.generate({ "ok" => false, "error" => error.message, "notices" => InstantRecord::SyncNotice.active.recent.map { |n| n.as_notice } }))
|
|
163
|
+
0
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
# Extract pending outbox rows directly from SQLite so a drifted or
|
|
167
|
+
# unmigratable database can be rebuilt cleanly without losing offline writes.
|
|
168
|
+
def self.export_outbox
|
|
169
|
+
InstantRecord::Client.clear_events
|
|
170
|
+
rows = []
|
|
171
|
+
begin
|
|
172
|
+
SqliteAdapter.each_row("SELECT id, record_type, record_id, operation, changes_payload, base_version, created_at, updated_at FROM instant_record_outbox ORDER BY created_at, id") do |row|
|
|
173
|
+
payload = row["changes_payload"]
|
|
174
|
+
rows << {
|
|
175
|
+
"id" => row["id"].to_s,
|
|
176
|
+
"record_type" => row["record_type"].to_s,
|
|
177
|
+
"record_id" => row["record_id"].to_s,
|
|
178
|
+
"operation" => row["operation"].to_s,
|
|
179
|
+
"changes_payload" => payload.nil? ? "{}" : payload.to_s,
|
|
180
|
+
"base_version" => row["base_version"].to_s.to_i,
|
|
181
|
+
"created_at" => row["created_at"].to_s,
|
|
182
|
+
"updated_at" => row["updated_at"].to_s
|
|
183
|
+
}
|
|
184
|
+
end
|
|
185
|
+
rescue StandardError
|
|
186
|
+
rows = []
|
|
187
|
+
end
|
|
188
|
+
<<write:out>>JSON.generate(rows))
|
|
189
|
+
0
|
|
190
|
+
end
|
|
191
|
+
|
|
192
|
+
# Re-insert preserved outbox rows into a freshly rebuilt database in
|
|
193
|
+
# one atomic SQLite transaction, keeping original ids and order.
|
|
194
|
+
def self.import_outbox
|
|
195
|
+
InstantRecord::Client.clear_events
|
|
196
|
+
rows = JSON.parse(<<read:in>>)
|
|
197
|
+
inserted = 0
|
|
198
|
+
Db.exec("BEGIN IMMEDIATE")
|
|
199
|
+
begin
|
|
200
|
+
rows.each do |row|
|
|
201
|
+
payload = row["changes_payload"]
|
|
202
|
+
sql = "INSERT OR IGNORE INTO instant_record_outbox " \
|
|
203
|
+
"(id, record_type, record_id, operation, changes_payload, base_version, created_at, updated_at) VALUES (" +
|
|
204
|
+
Db.escape_string(row["id"].to_s) + ", " +
|
|
205
|
+
Db.escape_string(row["record_type"].to_s) + ", " +
|
|
206
|
+
Db.escape_string(row["record_id"].to_s) + ", " +
|
|
207
|
+
Db.escape_string(row["operation"].to_s) + ", " +
|
|
208
|
+
Db.escape_string(payload.nil? ? "{}" : payload.to_s) + ", " +
|
|
209
|
+
row["base_version"].to_i.to_s + ", " +
|
|
210
|
+
Db.escape_string(row["created_at"].to_s) + ", " +
|
|
211
|
+
Db.escape_string(row["updated_at"].to_s) + ")"
|
|
212
|
+
Db.exec(sql)
|
|
213
|
+
inserted += 1
|
|
214
|
+
end
|
|
215
|
+
Db.exec("COMMIT")
|
|
216
|
+
rescue StandardError
|
|
217
|
+
begin
|
|
218
|
+
Db.exec("ROLLBACK")
|
|
219
|
+
rescue StandardError
|
|
220
|
+
end
|
|
221
|
+
raise
|
|
222
|
+
end
|
|
223
|
+
<<write:out>>JSON.generate({ imported: inserted }))
|
|
224
|
+
0
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
# Staging branch diff: OutboxMutations recorded after `exclude_ids`.
|
|
228
|
+
def self.branch_outbox
|
|
229
|
+
InstantRecord::Client.clear_events
|
|
230
|
+
raw = <<read:in>>.strip
|
|
231
|
+
input = raw.empty? ? {} : JSON.parse(raw)
|
|
232
|
+
summary = InstantRecord::Branch.summary(since_ids: Array(input["exclude_ids"]))
|
|
233
|
+
<<write:out>>JSON.generate(summary))
|
|
234
|
+
0
|
|
235
|
+
end
|
|
236
|
+
|
|
237
|
+
# Safely replay extracted staging branch OutboxMutations onto current `main`.
|
|
238
|
+
def self.branch_replay
|
|
239
|
+
InstantRecord::Client.clear_events
|
|
240
|
+
raw = <<read:in>>.strip
|
|
241
|
+
input = raw.empty? ? {} : JSON.parse(raw)
|
|
242
|
+
conflict = input["conflict"].to_s
|
|
243
|
+
conflict = "lww" if conflict.empty?
|
|
244
|
+
result = InstantRecord::Branch.replay_mutations(Array(input["mutations"]), conflict: conflict)
|
|
245
|
+
<<write:out>>JSON.generate(result))
|
|
246
|
+
0
|
|
247
|
+
end
|
|
248
|
+
<<entries>>end
|
|
249
|
+
RUBY
|
|
250
|
+
|
|
251
|
+
DATABASE = <<~'RUBY'
|
|
252
|
+
restored = File.exist?(db_path) && File.size(db_path) > 0
|
|
253
|
+
recovery = <<recovery>>
|
|
254
|
+
SqliteAdapter.configure(db_path)
|
|
255
|
+
ActiveRecord.adapter = SqliteAdapter
|
|
256
|
+
<<pragmas>>unless recovery
|
|
257
|
+
Schema.statements.each { |sql| SqliteAdapter.execute_ddl(sql) } unless restored
|
|
258
|
+
<<migrations>>
|
|
259
|
+
# Earlier demos saved a cursor before Note was a synced model. Rehydrate once
|
|
260
|
+
# on a model-set change, preserving all local rows and pending mutations.
|
|
261
|
+
model_set = "<<model_set>>"
|
|
262
|
+
if InstantRecord::SyncMetadata.get("compiled_models") != model_set
|
|
263
|
+
Schema.statements.each { |sql| SqliteAdapter.execute_ddl(sql) } if restored
|
|
264
|
+
InstantRecord::SyncMetadata.where(key: "cursor").delete_all if restored
|
|
265
|
+
InstantRecord::SyncMetadata.set("compiled_models", model_set)
|
|
266
|
+
end
|
|
267
|
+
end
|
|
268
|
+
RUBY
|
|
269
|
+
|
|
270
|
+
START = <<~'RUBY'
|
|
271
|
+
Tep::APP.name = Rails.application.global_id_app
|
|
272
|
+
<<config>><<windows>>InstantRecord.sync(<<models>>)
|
|
273
|
+
<<streaming>>
|
|
274
|
+
RUBY
|
|
275
|
+
|
|
276
|
+
NATIVE_HOST = <<~'RUBY'
|
|
277
|
+
|
|
278
|
+
# The native host's side of the bridge (native_shim.c).
|
|
279
|
+
module NativeHost
|
|
280
|
+
ffi_func :ir_host_take, [:str], :str
|
|
281
|
+
ffi_func :ir_host_give, [:str, :str], :void
|
|
282
|
+
end
|
|
283
|
+
RUBY
|
|
284
|
+
|
|
285
|
+
NATIVE_ENTRIES = <<~'RUBY'
|
|
286
|
+
|
|
287
|
+
# In: {"screen": name, "params": {...}}. Out: the screen as JSON.
|
|
288
|
+
def self.render
|
|
289
|
+
input = JSON.parse(NativeHost.ir_host_take("in"))
|
|
290
|
+
screen = NativeScreens.find(input["screen"].to_s, InstantRecord::Native::Screen.strings(input["params"]))
|
|
291
|
+
rendered = ""
|
|
292
|
+
reads = InstantRecord::ReadTracker.track do
|
|
293
|
+
rendered = screen.json
|
|
294
|
+
end
|
|
295
|
+
NativeHost.ir_host_give("reads", InstantRecord::ReadTracker.serialize(reads))
|
|
296
|
+
NativeHost.ir_host_give("out", rendered)
|
|
297
|
+
0
|
|
298
|
+
end
|
|
299
|
+
|
|
300
|
+
# In: the same, with "action", the "args" the tapped element carried and
|
|
301
|
+
# the "values" a form's fields held.
|
|
302
|
+
def self.action
|
|
303
|
+
input = JSON.parse(NativeHost.ir_host_take("in"))
|
|
304
|
+
screen = NativeScreens.find(input["screen"].to_s, InstantRecord::Native::Screen.strings(input["params"]))
|
|
305
|
+
InstantRecord::Client.capture_local_changes do
|
|
306
|
+
screen.perform(input["action"].to_s, InstantRecord::Native::Screen.strings(input["args"]), InstantRecord::Native::Screen.strings(input["values"]))
|
|
307
|
+
end
|
|
308
|
+
0
|
|
309
|
+
end
|
|
310
|
+
|
|
311
|
+
# In: the SQLite file to work in from here on. The one open before is closed.
|
|
312
|
+
def self.open
|
|
313
|
+
NativeDatabase.open(NativeHost.ir_host_take("in"))
|
|
314
|
+
0
|
|
315
|
+
end
|
|
316
|
+
RUBY
|
|
317
|
+
|
|
318
|
+
NATIVE_DATABASE = <<~'RUBY'
|
|
319
|
+
|
|
320
|
+
module NativeDatabase
|
|
321
|
+
# A file that will not open leaves the app in the one it had: the host is told of
|
|
322
|
+
# the failure and its screens go on working.
|
|
323
|
+
def self.open(db_path)
|
|
324
|
+
if @opened
|
|
325
|
+
previous = @path
|
|
326
|
+
begin
|
|
327
|
+
use(db_path)
|
|
328
|
+
rescue StandardError => error
|
|
329
|
+
use(previous)
|
|
330
|
+
raise error
|
|
331
|
+
end
|
|
332
|
+
else
|
|
333
|
+
use(db_path)
|
|
334
|
+
end
|
|
335
|
+
0
|
|
336
|
+
end
|
|
337
|
+
|
|
338
|
+
def self.use(db_path)
|
|
339
|
+
Db.close if @opened
|
|
340
|
+
@opened = true
|
|
341
|
+
@path = db_path
|
|
342
|
+
<<database>> InstantRecord::Client.forget_database
|
|
343
|
+
0
|
|
344
|
+
end
|
|
345
|
+
end
|
|
346
|
+
RUBY
|
|
347
|
+
|
|
348
|
+
NATIVE_SCREENS = <<~'RUBY'
|
|
349
|
+
|
|
350
|
+
module NativeScreens
|
|
351
|
+
def self.find(name, params)
|
|
352
|
+
case name
|
|
353
|
+
<<cases>> else raise ArgumentError, "No screen named " + name
|
|
354
|
+
end
|
|
355
|
+
end
|
|
356
|
+
end
|
|
357
|
+
RUBY
|
|
358
|
+
|
|
359
|
+
SYNC_ACTIONS_EMPTY = <<~'RUBY'
|
|
360
|
+
|
|
361
|
+
module InstantRecord
|
|
362
|
+
module SyncActions
|
|
363
|
+
def self.dispatch(name, _args)
|
|
364
|
+
raise ArgumentError, "Unknown sync_action: " + name
|
|
365
|
+
end
|
|
366
|
+
end
|
|
367
|
+
end
|
|
368
|
+
RUBY
|
|
369
|
+
|
|
370
|
+
SYNC_ACTIONS = <<~'RUBY'
|
|
371
|
+
|
|
372
|
+
module InstantRecord
|
|
373
|
+
module SyncActions
|
|
374
|
+
def self.dispatch(name, args)
|
|
375
|
+
case name
|
|
376
|
+
<<cases>> else raise ArgumentError, "Unknown sync_action: " + name
|
|
377
|
+
end
|
|
378
|
+
end
|
|
379
|
+
end
|
|
380
|
+
end
|
|
381
|
+
RUBY
|
|
382
|
+
|
|
383
|
+
module_function
|
|
384
|
+
|
|
385
|
+
def coerce_manifest(manifest)
|
|
386
|
+
return nil if manifest.nil?
|
|
387
|
+
return manifest if manifest.is_a?(Manifest)
|
|
388
|
+
return Manifest.new(manifest) if manifest.is_a?(Hash)
|
|
389
|
+
return Manifest.read(manifest.to_s) if manifest.is_a?(String) || manifest.is_a?(Pathname)
|
|
390
|
+
|
|
391
|
+
raise ArgumentError, "Unsupported manifest: #{manifest.inspect}"
|
|
392
|
+
end
|
|
393
|
+
|
|
394
|
+
def app_models(manifest: nil, models: nil)
|
|
395
|
+
parsed = coerce_manifest(manifest)
|
|
396
|
+
list =
|
|
397
|
+
if parsed&.island?
|
|
398
|
+
parsed.synced_model_names
|
|
399
|
+
elsif parsed && parsed.synced_model_names.any?
|
|
400
|
+
parsed.synced_model_names
|
|
401
|
+
else
|
|
402
|
+
Array(models)
|
|
403
|
+
end
|
|
404
|
+
if list.empty? || !list.all? { |name| name.is_a?(String) && MODEL_NAME_PATTERN.match?(name) }
|
|
405
|
+
raise BuildError, "Declare at least one named model that includes InstantRecord::Syncable."
|
|
406
|
+
end
|
|
407
|
+
list
|
|
408
|
+
end
|
|
409
|
+
|
|
410
|
+
def ruby_string_literal(value)
|
|
411
|
+
JSON.generate(value.to_s)
|
|
412
|
+
.gsub('#{', '\\#{')
|
|
413
|
+
.gsub('#@', '\\#@')
|
|
414
|
+
.gsub('#$', '\\#$')
|
|
415
|
+
end
|
|
416
|
+
|
|
417
|
+
def sync_windows_code(demo: false, manifest: nil, sync_windows: nil)
|
|
418
|
+
parsed = coerce_manifest(manifest)
|
|
419
|
+
resolved =
|
|
420
|
+
if sync_windows
|
|
421
|
+
sync_windows
|
|
422
|
+
elsif parsed
|
|
423
|
+
parsed.sync_windows
|
|
424
|
+
else
|
|
425
|
+
{}
|
|
426
|
+
end
|
|
427
|
+
resolved.sort_by { |name, _| name.to_s }.map do |model_name, spec|
|
|
428
|
+
name = model_name.to_s
|
|
429
|
+
unless MODEL_NAME_PATTERN.match?(name)
|
|
430
|
+
raise BuildError, "Invalid sync_window model name: #{name.inspect}"
|
|
431
|
+
end
|
|
432
|
+
|
|
433
|
+
limit = spec[:limit] || spec["limit"]
|
|
434
|
+
unless limit.is_a?(Integer) && limit.positive?
|
|
435
|
+
raise BuildError, "Invalid sync_window limit for #{name}: #{limit.inspect}"
|
|
436
|
+
end
|
|
437
|
+
|
|
438
|
+
partition = spec[:partition_by] || spec["partition_by"]
|
|
439
|
+
if partition && !partition.to_s.empty?
|
|
440
|
+
col = partition.to_s
|
|
441
|
+
unless COLUMN_NAME_PATTERN.match?(col)
|
|
442
|
+
raise BuildError, "Invalid sync_window partition_by column for #{name}: #{col.inspect}"
|
|
443
|
+
end
|
|
444
|
+
"#{name}.sync_window(limit: #{limit}, partition_by: :#{col})\n"
|
|
445
|
+
else
|
|
446
|
+
"#{name}.sync_window(limit: #{limit})\n"
|
|
447
|
+
end
|
|
448
|
+
end.join
|
|
449
|
+
end
|
|
450
|
+
|
|
451
|
+
def sync_scopes_code(manifest:)
|
|
452
|
+
parsed = coerce_manifest(manifest)
|
|
453
|
+
return "" unless parsed
|
|
454
|
+
|
|
455
|
+
parsed.models.filter_map do |entry|
|
|
456
|
+
name = entry["name"]
|
|
457
|
+
next unless name.is_a?(String) && MODEL_NAME_PATTERN.match?(name)
|
|
458
|
+
|
|
459
|
+
column = entry.dig("sync_scope", "column")
|
|
460
|
+
next unless column && !column.to_s.empty?
|
|
461
|
+
|
|
462
|
+
unless COLUMN_NAME_PATTERN.match?(column.to_s)
|
|
463
|
+
raise BuildError, "Invalid sync_scope column #{column.inspect} on #{name}"
|
|
464
|
+
end
|
|
465
|
+
"#{name}.sync_scope(:#{column})\n"
|
|
466
|
+
end.join
|
|
467
|
+
end
|
|
468
|
+
|
|
469
|
+
def config_code(endpoint:, mount_path:)
|
|
470
|
+
lines = []
|
|
471
|
+
lines << "InstantRecord.config.endpoint = #{ruby_string_literal(endpoint)}\n" if endpoint && !endpoint.to_s.empty?
|
|
472
|
+
lines << "InstantRecord.config.mount_path = #{ruby_string_literal(mount_path)}\n" if mount_path && !mount_path.to_s.empty?
|
|
473
|
+
lines.join
|
|
474
|
+
end
|
|
475
|
+
|
|
476
|
+
def migrations(demo:, plan:, previous:, applied: "")
|
|
477
|
+
return "" if demo
|
|
478
|
+
|
|
479
|
+
steps = ["if restored", " previous = #{previous}"]
|
|
480
|
+
migrations_map = plan.fetch("migrations", {})
|
|
481
|
+
migrations_map.sort_by { |version, _| version.to_i }.each do |version, statements|
|
|
482
|
+
padded = format("%020d", version.to_i)
|
|
483
|
+
steps << %( if previous < "#{padded}")
|
|
484
|
+
if statements.any?
|
|
485
|
+
steps << ' Db.exec("BEGIN IMMEDIATE")'
|
|
486
|
+
steps << " begin"
|
|
487
|
+
statements.each do |sql|
|
|
488
|
+
steps << " Db.exec(#{ruby_string_literal(sql)})"
|
|
489
|
+
end
|
|
490
|
+
steps << ' Db.exec("COMMIT")'
|
|
491
|
+
steps << " rescue StandardError"
|
|
492
|
+
steps << " begin"
|
|
493
|
+
steps << ' Db.exec("ROLLBACK")'
|
|
494
|
+
steps << " rescue StandardError"
|
|
495
|
+
steps << " end"
|
|
496
|
+
steps << " raise"
|
|
497
|
+
steps << " end"
|
|
498
|
+
end
|
|
499
|
+
unless applied.empty?
|
|
500
|
+
steps << " " + applied.gsub("<<version>>") { padded }
|
|
501
|
+
end
|
|
502
|
+
steps << " end"
|
|
503
|
+
end
|
|
504
|
+
steps << "end"
|
|
505
|
+
unless applied.empty?
|
|
506
|
+
latest = [plan["version"].to_i, *migrations_map.keys.map(&:to_i)].max
|
|
507
|
+
steps << applied.gsub("<<version>>") { format("%020d", latest) }
|
|
508
|
+
end
|
|
509
|
+
"\n#{steps.join("\n")}\n"
|
|
510
|
+
end
|
|
511
|
+
|
|
512
|
+
def fill(text, values, read: nil, write: nil)
|
|
513
|
+
result = text.dup
|
|
514
|
+
values.each do |name, value|
|
|
515
|
+
result = result.gsub("<<#{name}>>") { value }
|
|
516
|
+
end
|
|
517
|
+
if read
|
|
518
|
+
result = result.gsub(/<<read:(\w+)>>/) { read.call(Regexp.last_match(1)) }
|
|
519
|
+
result = result.gsub(/<<write:(\w+)>>/) { write.call(Regexp.last_match(1)) }
|
|
520
|
+
end
|
|
521
|
+
if (left = result[/<<[\w:]+>>/])
|
|
522
|
+
raise BuildError, "EntryBuilder: nothing filled #{left}"
|
|
523
|
+
end
|
|
524
|
+
result
|
|
525
|
+
end
|
|
526
|
+
|
|
527
|
+
def bridge(name, read:, write:, entries: "", shell_fingerprint: "")
|
|
528
|
+
fill(BRIDGE, { "bridge" => name, "entries" => entries, "shell_fingerprint" => shell_fingerprint.to_s }, read: read, write: write)
|
|
529
|
+
end
|
|
530
|
+
|
|
531
|
+
def database(pragmas:, steps:, models:, recovery: "false")
|
|
532
|
+
lines = pragmas.map { |pragma| %(SqliteAdapter.execute_ddl("PRAGMA #{pragma}")\n) }.join
|
|
533
|
+
indented_steps = steps.empty? ? "" : indent(steps, " ")
|
|
534
|
+
fill(DATABASE, { "pragmas" => lines, "migrations" => indented_steps, "model_set" => models.sort.join(","), "recovery" => recovery })
|
|
535
|
+
end
|
|
536
|
+
|
|
537
|
+
def start(streaming:, comment:, models:, demo: false, manifest: nil, sync_windows: nil, endpoint: nil, mount_path: nil)
|
|
538
|
+
cfg = config_code(endpoint: endpoint, mount_path: mount_path)
|
|
539
|
+
declarations = sync_windows_code(demo: demo, manifest: manifest, sync_windows: sync_windows) + sync_scopes_code(manifest: manifest)
|
|
540
|
+
flag = "#{comment}\nInstantRecord::Client.streaming = #{streaming ? 'true' : 'false'}"
|
|
541
|
+
fill(START, { "config" => cfg, "windows" => declarations, "models" => models.join(", "), "streaming" => flag })
|
|
542
|
+
end
|
|
543
|
+
|
|
544
|
+
def write_wasm_entry(emit_dir:, demo: false, manifest: nil, models: nil, migration_plan:, pipeline_dir:, app_dir: nil, sync_windows: nil, endpoint: nil, mount_path: nil, shell_fingerprint: "")
|
|
545
|
+
if demo
|
|
546
|
+
FileUtils.cp(
|
|
547
|
+
File.join(pipeline_dir, "sqlite_release.rb"),
|
|
548
|
+
File.join(emit_dir, "app/models/release.rb")
|
|
549
|
+
)
|
|
550
|
+
end
|
|
551
|
+
|
|
552
|
+
source = File.read(File.join(emit_dir, "main.rb"))
|
|
553
|
+
marker = %(\nif ARGV.length > 0 && ARGV[0] == "sidekiq")
|
|
554
|
+
cut = source.index(marker)
|
|
555
|
+
raise BuildError, "Expected sidekiq marker in #{File.join(emit_dir, 'main.rb')}" unless cut
|
|
556
|
+
|
|
557
|
+
head = source[0...cut]
|
|
558
|
+
resolved_models = app_models(manifest: manifest, models: models)
|
|
559
|
+
entry = BANNER + " for wasm32-wasi (see EntryBuilder) ─────────\n" +
|
|
560
|
+
PRELUDE +
|
|
561
|
+
sync_actions_module(app_dir) +
|
|
562
|
+
bridge(
|
|
563
|
+
"WasmBridge",
|
|
564
|
+
read: ->(name) { %(File.read("/host/#{name}")) },
|
|
565
|
+
write: ->(name) { "File.write(\"/host/#{name}\", " },
|
|
566
|
+
shell_fingerprint: shell_fingerprint
|
|
567
|
+
) +
|
|
568
|
+
"\ndb_path = Main.default_db_path\n" +
|
|
569
|
+
database(
|
|
570
|
+
pragmas: ["locking_mode = EXCLUSIVE", "journal_mode = MEMORY", "cache_size = -4000"],
|
|
571
|
+
steps: migrations(demo: demo, plan: migration_plan, previous: 'File.read("/host/schema_version")'),
|
|
572
|
+
models: resolved_models,
|
|
573
|
+
recovery: 'File.exist?("/host/recovery") && File.read("/host/recovery") == "extract_outbox"'
|
|
574
|
+
) +
|
|
575
|
+
start(
|
|
576
|
+
streaming: true,
|
|
577
|
+
comment: "# JS worker owns non-blocking inbound polling; Client#sync_pass handles bootstrap + outbox drain.",
|
|
578
|
+
demo: demo,
|
|
579
|
+
models: resolved_models,
|
|
580
|
+
manifest: manifest,
|
|
581
|
+
sync_windows: sync_windows,
|
|
582
|
+
endpoint: endpoint,
|
|
583
|
+
mount_path: mount_path
|
|
584
|
+
)
|
|
585
|
+
|
|
586
|
+
File.write(File.join(emit_dir, "main_wasm.rb"), head + entry)
|
|
587
|
+
end
|
|
588
|
+
|
|
589
|
+
def discover_sync_actions(app_dir)
|
|
590
|
+
return [] unless app_dir
|
|
591
|
+
|
|
592
|
+
models_dir = File.join(app_dir, "app/models")
|
|
593
|
+
return [] unless File.directory?(models_dir)
|
|
594
|
+
|
|
595
|
+
discovered = []
|
|
596
|
+
Dir.glob("**/*.rb", base: models_dir).sort.each do |rel|
|
|
597
|
+
path = File.join(models_dir, rel)
|
|
598
|
+
parsed = Prism.parse_file(path)
|
|
599
|
+
raise BuildError, "Could not parse #{path} for sync_action discovery" unless parsed.success?
|
|
600
|
+
|
|
601
|
+
collect_sync_actions(parsed.value, [], path, discovered)
|
|
602
|
+
end
|
|
603
|
+
discovered.sort_by { |entry| "#{entry[:class_name]}.#{entry[:action]}" }
|
|
604
|
+
end
|
|
605
|
+
|
|
606
|
+
def sync_actions_module(app_dir)
|
|
607
|
+
found = discover_sync_actions(app_dir)
|
|
608
|
+
return SYNC_ACTIONS_EMPTY if found.empty?
|
|
609
|
+
|
|
610
|
+
cases = found.map { |entry| " when #{JSON.generate("#{entry[:class_name]}.#{entry[:action]}")} then #{entry[:call]}\n" }.join
|
|
611
|
+
fill(SYNC_ACTIONS, { "cases" => cases })
|
|
612
|
+
end
|
|
613
|
+
|
|
614
|
+
def collect_sync_actions(node, namespace, path, discovered)
|
|
615
|
+
return unless node
|
|
616
|
+
|
|
617
|
+
case node
|
|
618
|
+
when Prism::ProgramNode
|
|
619
|
+
collect_sync_actions(node.statements, namespace, path, discovered)
|
|
620
|
+
when Prism::StatementsNode
|
|
621
|
+
node.body.each { |child| collect_sync_actions(child, namespace, path, discovered) }
|
|
622
|
+
when Prism::ModuleNode
|
|
623
|
+
parts = constant_path_parts(node.constant_path)
|
|
624
|
+
next_ns = parts ? namespace + parts : namespace
|
|
625
|
+
collect_sync_actions(node.body, next_ns, path, discovered)
|
|
626
|
+
when Prism::ClassNode
|
|
627
|
+
parts = constant_path_parts(node.constant_path)
|
|
628
|
+
next_ns = parts ? namespace + parts : namespace
|
|
629
|
+
class_name = next_ns.join("::")
|
|
630
|
+
unless class_name.empty?
|
|
631
|
+
class_defs = {}
|
|
632
|
+
actions = []
|
|
633
|
+
scan_class_body(node.body, class_defs, actions, path)
|
|
634
|
+
actions.each do |action_name|
|
|
635
|
+
call_expr = format_sync_action_call(class_name, action_name, class_defs[action_name], path)
|
|
636
|
+
discovered << { class_name: class_name, action: action_name, call: call_expr }
|
|
637
|
+
end
|
|
638
|
+
end
|
|
639
|
+
collect_sync_actions(node.body, next_ns, path, discovered)
|
|
640
|
+
end
|
|
641
|
+
end
|
|
642
|
+
|
|
643
|
+
def scan_class_body(body, class_defs, actions, path)
|
|
644
|
+
return unless body.is_a?(Prism::StatementsNode)
|
|
645
|
+
|
|
646
|
+
body.body.each do |stmt|
|
|
647
|
+
case stmt
|
|
648
|
+
when Prism::DefNode
|
|
649
|
+
if stmt.receiver.is_a?(Prism::SelfNode)
|
|
650
|
+
class_defs[stmt.name.to_s] = stmt
|
|
651
|
+
end
|
|
652
|
+
when Prism::SingletonClassNode
|
|
653
|
+
if stmt.expression.is_a?(Prism::SelfNode) && stmt.body.is_a?(Prism::StatementsNode)
|
|
654
|
+
stmt.body.body.each do |inner|
|
|
655
|
+
class_defs[inner.name.to_s] = inner if inner.is_a?(Prism::DefNode) && inner.receiver.nil?
|
|
656
|
+
end
|
|
657
|
+
end
|
|
658
|
+
when Prism::CallNode
|
|
659
|
+
next unless stmt.receiver.nil? && stmt.name == :sync_action
|
|
660
|
+
|
|
661
|
+
args = Array(stmt.arguments&.arguments)
|
|
662
|
+
first = args.first
|
|
663
|
+
action_name =
|
|
664
|
+
case first
|
|
665
|
+
when Prism::SymbolNode then first.unescaped
|
|
666
|
+
when Prism::StringNode then first.unescaped
|
|
667
|
+
else
|
|
668
|
+
raise BuildError, "#{path}:#{stmt.location.start_line}: sync_action requires a literal symbol or string name."
|
|
669
|
+
end
|
|
670
|
+
|
|
671
|
+
unless /\A[a-z_][a-zA-Z0-9_]*[!?]?\z/.match?(action_name)
|
|
672
|
+
raise BuildError, "#{path}:#{stmt.location.start_line}: Invalid sync_action name #{action_name.inspect}."
|
|
673
|
+
end
|
|
674
|
+
|
|
675
|
+
if stmt.block
|
|
676
|
+
raise BuildError, "#{path}:#{stmt.location.start_line}: sync_action :#{action_name} cannot use a block in compiled builds; define def self.#{action_name}(args) instead."
|
|
677
|
+
end
|
|
678
|
+
|
|
679
|
+
actions << action_name unless actions.include?(action_name)
|
|
680
|
+
end
|
|
681
|
+
end
|
|
682
|
+
end
|
|
683
|
+
|
|
684
|
+
def format_sync_action_call(class_name, action_name, def_node, path)
|
|
685
|
+
return "#{class_name}.#{action_name}(args)" unless def_node
|
|
686
|
+
|
|
687
|
+
params = def_node.parameters
|
|
688
|
+
return "#{class_name}.#{action_name}" unless params
|
|
689
|
+
|
|
690
|
+
positionals = Array(params.requireds) + Array(params.optionals)
|
|
691
|
+
keywords = Array(params.keywords)
|
|
692
|
+
has_rest = !params.rest.nil? || !params.keyword_rest.nil?
|
|
693
|
+
|
|
694
|
+
if positionals.empty? && keywords.empty? && !has_rest
|
|
695
|
+
"#{class_name}.#{action_name}"
|
|
696
|
+
elsif positionals.empty? && !keywords.empty? && params.keyword_rest.nil?
|
|
697
|
+
kw_parts = keywords.map do |kw|
|
|
698
|
+
key = kw.name.to_s.delete_suffix(":")
|
|
699
|
+
key_lit = JSON.generate(key)
|
|
700
|
+
case kw
|
|
701
|
+
when Prism::RequiredKeywordParameterNode
|
|
702
|
+
"#{key}: args[#{key_lit}]"
|
|
703
|
+
when Prism::OptionalKeywordParameterNode
|
|
704
|
+
default_expr = literal_expr(kw.value)
|
|
705
|
+
if default_expr
|
|
706
|
+
"#{key}: args.key?(#{key_lit}) ? args[#{key_lit}] : #{default_expr}"
|
|
707
|
+
else
|
|
708
|
+
"#{key}: args[#{key_lit}]"
|
|
709
|
+
end
|
|
710
|
+
else
|
|
711
|
+
raise BuildError, "#{path}:#{def_node.location.start_line}: Unsupported sync_action keyword parameter."
|
|
712
|
+
end
|
|
713
|
+
end
|
|
714
|
+
"#{class_name}.#{action_name}(#{kw_parts.join(', ')})"
|
|
715
|
+
else
|
|
716
|
+
"#{class_name}.#{action_name}(args)"
|
|
717
|
+
end
|
|
718
|
+
end
|
|
719
|
+
|
|
720
|
+
def literal_expr(node)
|
|
721
|
+
case node
|
|
722
|
+
when Prism::NilNode then "nil"
|
|
723
|
+
when Prism::TrueNode then "true"
|
|
724
|
+
when Prism::FalseNode then "false"
|
|
725
|
+
when Prism::IntegerNode, Prism::FloatNode then node.value.inspect
|
|
726
|
+
when Prism::StringNode then JSON.generate(node.unescaped)
|
|
727
|
+
when Prism::SymbolNode then node.unescaped.to_sym.inspect
|
|
728
|
+
else nil
|
|
729
|
+
end
|
|
730
|
+
end
|
|
731
|
+
|
|
732
|
+
def constant_path_parts(node)
|
|
733
|
+
case node
|
|
734
|
+
when Prism::ConstantReadNode
|
|
735
|
+
[node.name.to_s]
|
|
736
|
+
when Prism::ConstantPathNode
|
|
737
|
+
parent = node.parent ? constant_path_parts(node.parent) : []
|
|
738
|
+
return nil unless parent
|
|
739
|
+
|
|
740
|
+
parent + [node.name.to_s]
|
|
741
|
+
else
|
|
742
|
+
nil
|
|
743
|
+
end
|
|
744
|
+
end
|
|
745
|
+
|
|
746
|
+
def discover_screens(app_dir)
|
|
747
|
+
folder = File.join(app_dir, "app/screens")
|
|
748
|
+
return [] unless File.directory?(folder)
|
|
749
|
+
|
|
750
|
+
Dir.glob("*_screen.rb", base: folder)
|
|
751
|
+
.map { |file| file.delete_suffix("_screen.rb") }
|
|
752
|
+
.sort
|
|
753
|
+
.map { |name| [name, InstantRecord::Native.class_name(name)] }
|
|
754
|
+
rescue ArgumentError => e
|
|
755
|
+
raise BuildError, e.message
|
|
756
|
+
end
|
|
757
|
+
|
|
758
|
+
def write_native_entry(tree_dir:, app_dir:, demo: false, manifest: nil, models: nil, migration_plan:, sync_windows: nil, endpoint: nil, mount_path: nil, shell_fingerprint: "")
|
|
759
|
+
wasm_main = File.read(File.join(tree_dir, "main_wasm.rb"))
|
|
760
|
+
unless wasm_main.scan(BANNER).length == 1
|
|
761
|
+
raise BuildError, "main_wasm.rb has no entry to start from"
|
|
762
|
+
end
|
|
763
|
+
|
|
764
|
+
head = wasm_main[0...wasm_main.index(BANNER)]
|
|
765
|
+
found = discover_screens(app_dir)
|
|
766
|
+
screens_block =
|
|
767
|
+
if found.empty?
|
|
768
|
+
"\nmodule NativeScreens\n def self.find(name, _params)\n raise ArgumentError, \"No screen named \" + name\n end\nend\n"
|
|
769
|
+
else
|
|
770
|
+
cases = found.map { |name, cls| %( when "#{name}" then #{cls}.new(params)\n) }.join
|
|
771
|
+
fill(NATIVE_SCREENS, { "cases" => cases })
|
|
772
|
+
end
|
|
773
|
+
resolved_models = app_models(manifest: manifest, models: models)
|
|
774
|
+
previous = 'InstantRecord::SyncMetadata.get("schema_version").to_s'
|
|
775
|
+
applied = 'InstantRecord::SyncMetadata.set("schema_version", "<<version>>")'
|
|
776
|
+
db_body = database(
|
|
777
|
+
pragmas: ["cache_size = -4000"],
|
|
778
|
+
steps: migrations(demo: demo, plan: migration_plan, previous: previous, applied: applied),
|
|
779
|
+
models: resolved_models
|
|
780
|
+
)
|
|
781
|
+
|
|
782
|
+
entry = BANNER + " for a native host (see EntryBuilder) ─────────\n" +
|
|
783
|
+
PRELUDE +
|
|
784
|
+
sync_actions_module(app_dir) +
|
|
785
|
+
NATIVE_HOST +
|
|
786
|
+
screens_block +
|
|
787
|
+
bridge(
|
|
788
|
+
"NativeBridge",
|
|
789
|
+
read: ->(name) { %(NativeHost.ir_host_take("#{name}")) },
|
|
790
|
+
write: ->(name) { "NativeHost.ir_host_give(\"#{name}\", " },
|
|
791
|
+
entries: NATIVE_ENTRIES,
|
|
792
|
+
shell_fingerprint: shell_fingerprint
|
|
793
|
+
) +
|
|
794
|
+
fill(NATIVE_DATABASE, { "database" => indent(db_body, " ") }) +
|
|
795
|
+
"\nNativeDatabase.open(Main.default_db_path)\n" +
|
|
796
|
+
start(
|
|
797
|
+
streaming: false,
|
|
798
|
+
comment: "# A sync pass pulls through the host: Client#sync_pass handles bootstrap, outbox drain and the poll.",
|
|
799
|
+
demo: demo,
|
|
800
|
+
models: resolved_models,
|
|
801
|
+
manifest: manifest,
|
|
802
|
+
sync_windows: sync_windows,
|
|
803
|
+
endpoint: endpoint,
|
|
804
|
+
mount_path: mount_path
|
|
805
|
+
)
|
|
806
|
+
|
|
807
|
+
File.write(File.join(tree_dir, "main_native.rb"), head + entry)
|
|
808
|
+
install_native_host_adapter(tree_dir)
|
|
809
|
+
found.map(&:first)
|
|
810
|
+
end
|
|
811
|
+
|
|
812
|
+
def install_native_host_adapter(tree_dir)
|
|
813
|
+
candidates = [
|
|
814
|
+
File.join(tree_dir, "app/models/instant_record/host.rb"),
|
|
815
|
+
File.join(tree_dir, "lib/instant_record/host.rb")
|
|
816
|
+
].select { |path| File.file?(path) }
|
|
817
|
+
|
|
818
|
+
if candidates.empty?
|
|
819
|
+
raise BuildError, "expected emitted InstantRecord::Host adapter in #{tree_dir}"
|
|
820
|
+
end
|
|
821
|
+
|
|
822
|
+
candidates.each do |path|
|
|
823
|
+
File.write(path, HostAdapters::Native.host_source)
|
|
824
|
+
end
|
|
825
|
+
end
|
|
826
|
+
|
|
827
|
+
def indent(text, by)
|
|
828
|
+
text.lines.map { |line| line.strip.empty? ? line : "#{by}#{line}" }.join
|
|
829
|
+
end
|
|
830
|
+
end
|
|
831
|
+
end
|
|
832
|
+
end
|