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,277 @@
1
+ require "fileutils"
2
+ require "json"
3
+ require "pathname"
4
+ require "tmpdir"
5
+ require_relative "compiler/runner"
6
+ require_relative "compiler/toolchain"
7
+ require_relative "compiler/path_scrubber"
8
+ require_relative "compiler/browser_migrations"
9
+ require_relative "compiler/schema_lock"
10
+ require_relative "compiler/manifest"
11
+ require_relative "compiler/route_analyzer"
12
+ require_relative "compiler/reachability_tracer"
13
+ require_relative "compiler/ast_lowerer"
14
+ require_relative "compiler/host_adapters"
15
+ require_relative "compiler/static_linter"
16
+ require_relative "compiler/app_stage"
17
+ require_relative "compiler/gem_vendor"
18
+ require_relative "compiler/entry_builder"
19
+ require_relative "compiler/native_contracts"
20
+ require_relative "compiler/swift_codegen"
21
+ require_relative "compiler/kotlin_codegen"
22
+ require_relative "compiler/wasm_tree"
23
+ require_relative "compiler/source_pages"
24
+ require_relative "compiler/wasm_build"
25
+ require_relative "compiler/native_build"
26
+ require_relative "compiler/fts5_smoke"
27
+
28
+ module InstantRecord
29
+ # Compiles a Rails app (or this repository's demo) into a static Wasm browser
30
+ # site or native iOS/macOS static libraries in-process from Ruby. A build never
31
+ # writes into an installed gem or replaces the host's public assets until publish.
32
+ class Compiler
33
+ WEB_PARTS = %w[index.html vite.config.js package.json package-lock.json src].freeze
34
+
35
+ def self.gem_root
36
+ Pathname(__dir__).join("../..").realpath
37
+ end
38
+
39
+ def self.demo_toolchain(toolchain = nil)
40
+ toolchain || ENV.fetch("INSTANT_RECORD_TOOLCHAIN") { gem_root.join("compiled/toolchain.env").to_s }
41
+ end
42
+
43
+ def self.build(root:, toolchain:, endpoint:, models: nil, sync_windows: nil, mount_path: nil, baseline: nil, migration_paths: nil, island: nil, overrides: nil, shell_snapshot: nil)
44
+ with_workspace(root: root, toolchain: toolchain, stage_web: true) do |shared|
45
+ WasmBuild.new(
46
+ **shared,
47
+ models: models,
48
+ sync_windows: sync_windows,
49
+ endpoint: endpoint,
50
+ mount_path: mount_path,
51
+ baseline: baseline,
52
+ migration_paths: migration_paths || shared[:migration_paths],
53
+ island: island,
54
+ overrides: overrides,
55
+ shell_snapshot: shell_snapshot
56
+ ).run
57
+ end
58
+ end
59
+
60
+ # The same app as libraries a native host links: for this machine, or
61
+ # with target "iphonesimulator" or "iphoneos" for the iOS simulator or
62
+ # an iPhone. Returns the folder that holds them.
63
+ def self.build_native(
64
+ root:,
65
+ toolchain:,
66
+ endpoint:,
67
+ models: nil,
68
+ target: nil,
69
+ sync_windows: nil,
70
+ mount_path: nil,
71
+ baseline: nil,
72
+ migration_paths: nil,
73
+ island: nil,
74
+ overrides: nil,
75
+ swift_out: nil,
76
+ kotlin: false,
77
+ kotlin_out: nil,
78
+ kotlin_package: "dev.instantrecord.contracts",
79
+ out: $stdout
80
+ )
81
+ with_workspace(root: root, toolchain: toolchain, stage_web: false) do |shared|
82
+ NativeBuild.new(
83
+ **shared,
84
+ models: models,
85
+ sync_windows: sync_windows,
86
+ endpoint: endpoint,
87
+ mount_path: mount_path,
88
+ target: target,
89
+ baseline: baseline,
90
+ migration_paths: migration_paths || shared[:migration_paths],
91
+ island: island,
92
+ overrides: overrides,
93
+ swift_out: swift_out,
94
+ kotlin: kotlin,
95
+ kotlin_out: kotlin_out,
96
+ kotlin_package: kotlin_package,
97
+ out: out
98
+ ).run
99
+ end
100
+ end
101
+
102
+ # Extract typed prop/action contracts from app/screens via Prism and emit
103
+ # Swift (and optionally Kotlin) source files without running a C build.
104
+ def self.generate_native_contracts(screens_dir:, swift_out: nil, kotlin_out: nil, kotlin_package: "dev.instantrecord.contracts", kotlin_serializable: true)
105
+ contracts = NativeContracts.extract_dir(screens_dir)
106
+ written = {}
107
+ return { contracts: contracts, written: written } if contracts.empty?
108
+
109
+ if swift_out
110
+ path = File.expand_path(swift_out.to_s)
111
+ FileUtils.mkdir_p(File.dirname(path))
112
+ File.write(path, SwiftCodegen.generate(contracts))
113
+ written[:swift] = Pathname(path)
114
+ end
115
+
116
+ if kotlin_out
117
+ path = File.expand_path(kotlin_out.to_s)
118
+ FileUtils.mkdir_p(File.dirname(path))
119
+ File.write(path, KotlinCodegen.generate(contracts, package: kotlin_package, serializable: kotlin_serializable))
120
+ written[:kotlin] = Pathname(path)
121
+ end
122
+
123
+ { contracts: contracts, written: written }
124
+ end
125
+
126
+ # Build the repository's own demo into compiled/web/dist.
127
+ def self.build_demo(toolchain: nil, endpoint: nil, shell_snapshot: nil, island: nil)
128
+ WasmBuild.new(
129
+ workspace: gem_root.join("compiled"),
130
+ gem_root: gem_root,
131
+ toolchain: demo_toolchain(toolchain),
132
+ endpoint: endpoint,
133
+ shell_snapshot: shell_snapshot,
134
+ island: island
135
+ ).run
136
+ end
137
+
138
+ # Build the repository's own demo into compiled/.build-native[/target].
139
+ def self.build_demo_native(target: nil, toolchain: nil, endpoint: nil, island: nil, out: $stdout)
140
+ NativeBuild.new(
141
+ workspace: gem_root.join("compiled"),
142
+ gem_root: gem_root,
143
+ toolchain: demo_toolchain(toolchain),
144
+ endpoint: endpoint,
145
+ target: target,
146
+ island: island,
147
+ out: out
148
+ ).run
149
+ end
150
+
151
+ # Analyze a Rails app's local-first island(s) and return its Manifest without compiling.
152
+ def self.manifest(root:, island: nil, overrides: nil, native: false, migration_paths: nil)
153
+ AppStage.analyze(
154
+ source: root,
155
+ native: native,
156
+ island: island,
157
+ overrides: overrides,
158
+ migration_paths: migration_paths
159
+ ).manifest
160
+ end
161
+
162
+ def self.doctor(toolchain:, target: :wasm, web_dir: nil, root: nil, app_root: nil, baseline: nil, migration_paths: nil, models: nil, island: nil, overrides: nil)
163
+ report = Toolchain.load(toolchain).doctor(target: target, web_dir: web_dir)
164
+ if app_root
165
+ report = report.with_lint(lint(app_root, staged: false, island: island, overrides: overrides))
166
+ end
167
+ schema_root = root || app_root
168
+ if schema_root && File.file?(File.join(schema_root.to_s, "db/schema.rb"))
169
+ schema_report = SchemaLock.verify(
170
+ root: schema_root,
171
+ baseline: baseline,
172
+ migration_paths: migration_paths,
173
+ models: models
174
+ )
175
+ schema_report.checks.each do |check|
176
+ report.checks << Toolchain::Check.new(
177
+ name: "schema:#{check.name}",
178
+ status: check.ok? ? :ok : :error,
179
+ detail: check.detail
180
+ )
181
+ end
182
+ end
183
+ report
184
+ end
185
+
186
+ def self.lock_schema(root:, baseline: nil, migration_paths: nil, force: false)
187
+ SchemaLock.write!(root: root, baseline: baseline, migration_paths: migration_paths, force: force)
188
+ end
189
+
190
+ def self.verify_schema(root:, baseline: nil, migration_paths: nil, models: nil)
191
+ SchemaLock.verify(root: root, baseline: baseline, migration_paths: migration_paths, models: models)
192
+ end
193
+
194
+ def self.lint(root, staged: false, exclude: nil, island: nil, overrides: nil)
195
+ resolved = Pathname(root)
196
+ only_files = nil
197
+ if !staged && exclude.nil? && resolved.join("config/routes.rb").file?
198
+ analysis = AppStage.analyze(source: resolved, native: true, island: island, overrides: overrides)
199
+ if analysis.manifest.island?
200
+ staged_map = analysis.manifest.staged
201
+ only_files = (
202
+ Array(staged_map["controllers"]) +
203
+ Array(staged_map["models"]) +
204
+ Array(staged_map["helpers"]) +
205
+ Array(staged_map["screens"]) +
206
+ Array(staged_map["files"]) +
207
+ %w[config/application.rb config/importmap.rb]
208
+ ).select { |rel| rel.end_with?(".rb") }.uniq
209
+ end
210
+ end
211
+ StaticLinter.lint(root, staged: staged, exclude: Array(exclude), only_files: only_files)
212
+ end
213
+
214
+ def self.scrub_path(path, prefix)
215
+ PathScrubber.scrub(path, prefix)
216
+ end
217
+
218
+ def self.verify_fts5(toolchain: nil, target: :native)
219
+ Fts5Smoke.run(toolchain: demo_toolchain(toolchain), target: target)
220
+ end
221
+
222
+ def self.with_workspace(root:, toolchain:, stage_web:)
223
+ app_root = Pathname(root).realpath
224
+ parsed_toolchain = Toolchain.load(toolchain)
225
+ workspace = app_root.join("tmp/instant_record/compiled")
226
+ FileUtils.mkdir_p(workspace)
227
+
228
+ File.open(workspace.join(".lock"), "a") do |lock|
229
+ lock.flock(File::LOCK_EX)
230
+ if stage_web
231
+ package = gem_root.join("compiled/web")
232
+ web = workspace.join("web")
233
+ FileUtils.mkdir_p(web)
234
+ FileUtils.rm_rf(web.join("src"))
235
+ WEB_PARTS.each do |part|
236
+ FileUtils.cp_r(package.join(part), web)
237
+ end
238
+ end
239
+ demo = app_root == gem_root.join("demo")
240
+ yield(
241
+ workspace: workspace,
242
+ gem_root: gem_root,
243
+ toolchain: parsed_toolchain,
244
+ app_source: demo ? nil : app_root.to_s,
245
+ migration_paths: [app_root.join("db/migrate").to_s]
246
+ )
247
+ end
248
+ end
249
+ private_class_method :with_workspace
250
+
251
+ def self.publish(root)
252
+ workspace = Pathname(root).join("tmp/instant_record/compiled")
253
+ public_root = Pathname(root).join("public/instant_record_compiled")
254
+ FileUtils.mkdir_p(public_root)
255
+ File.open(workspace.join(".lock"), "a") do |lock|
256
+ lock.flock(File::LOCK_EX)
257
+ dist = workspace.join("web/dist")
258
+ version = JSON.parse(dist.join("instant-record-release.json").read).fetch("version")
259
+ raise "Invalid compiled release version" unless version.match?(/\A[0-9a-f]{64}\z/)
260
+
261
+ destination = public_root.join(version)
262
+ unless destination.directory?
263
+ Dir.mktmpdir(".release-", public_root) do |temp|
264
+ staged = Pathname(temp).join("site")
265
+ FileUtils.cp_r(dist, staged)
266
+ File.rename(staged, destination)
267
+ end
268
+ end
269
+ Dir.mktmpdir(".publish-", public_root) do |temp|
270
+ link = Pathname(temp).join("current")
271
+ File.symlink(version, link)
272
+ File.rename(link, public_root.join("current"))
273
+ end
274
+ end
275
+ end
276
+ end
277
+ end
@@ -5,15 +5,119 @@ module InstantRecord
5
5
  # setups (e.g. Vite on :5173 talking to Rails on :3000).
6
6
  attr_accessor :endpoint
7
7
 
8
+ # Optional override for the engine's mount path (e.g. "/sync") when
9
+ # Rails.application.config.instant_record is unavailable, such as inside a
10
+ # compiled browser or native build.
11
+ attr_accessor :mount_path
12
+
8
13
  # Base delay, in seconds, for retrying an outbox drain that did not get
9
14
  # through. It is not a poll cadence: the browser has no heartbeat, because
10
15
  # writes trigger their own sync pass and the change stream carries
11
16
  # everything inbound. A client with an empty outbox makes no requests at all.
12
17
  attr_accessor :sync_interval
13
18
 
19
+ # Reads a sync request's scope: whose rows it may be sent, for models that
20
+ # declare sync_scope. The default reads the `X-Instant-Record-Scope` header
21
+ # or `scope` parameter. An app with sign-in reads it from the session or an
22
+ # Authorization header instead:
23
+ #
24
+ # config.scope_from = ->(request) { request.session[:user_id] }
25
+ attr_accessor :scope_from
26
+
27
+ # Reads a sync request's active multi-tenant partition, for models that
28
+ # declare `sync_partition`. Default reads the `X-Instant-Record-Partition`
29
+ # header or `sync_partition` parameter (and `partition` on bootstrap, events,
30
+ # and mutations). May accept `(request)` or `(request, identity)` and may
31
+ # raise `InstantRecord::Unauthorized` or `InstantRecord::Forbidden`.
32
+ attr_accessor :partition_from
33
+
34
+ # Optional server-side request authenticator invoked before serving any
35
+ # non-preflight sync endpoint. Raise `InstantRecord::Unauthorized` (401)
36
+ # or `InstantRecord::Forbidden` (403) to reject the request.
37
+ attr_accessor :authenticate_request
38
+
39
+ # Pluggable client-side headers sent on every outbound sync request
40
+ # (bootstrap, mutations, events, history). Accepts a Hash or a callable
41
+ # returning a Hash.
42
+ attr_accessor :headers
43
+
44
+ # Client-side scope token sent as `X-Instant-Record-Scope`.
45
+ attr_accessor :sync_scope
46
+
47
+ # Client-side active partition sent as `X-Instant-Record-Partition`
48
+ # (String like "support" / "mailbox_id:support", or Hash).
49
+ attr_accessor :sync_partition
50
+
51
+ # Client-side bearer/auth token sent as `Authorization`. Plain tokens are
52
+ # prefixed with "Bearer "; values containing a space are sent verbatim.
53
+ attr_accessor :auth_token
54
+
55
+ # Where the server keeps the bytes of records that declare sync_file:
56
+ # anything that answers as InstantRecord::FileStore does. Left alone, they
57
+ # go under storage/instant_record in the app.
58
+ attr_accessor :file_store
59
+
60
+ # The most bytes the server takes for one file, for a model whose
61
+ # sync_file names no max_size of its own. Left alone it is
62
+ # InstantRecord::Files::MAX_SIZE. That number is written there and not
63
+ # here: this file is compiled for the browser, where an integer has 32
64
+ # bits, and two gigabytes do not fit in one.
65
+ attr_accessor :max_file_size
66
+
67
+ # Maximum number of outbox mutations sent in a single POST /mutations
68
+ # request. Bounding the batch keeps large offline backlogs chunked and
69
+ # lets 5xx poison-pill isolation narrow down a single failing mutation.
70
+ attr_accessor :drain_batch_size
71
+
72
+ # Number of consecutive 5xx responses on an isolated single mutation before
73
+ # quarantining it as a poison pill so subsequent writes can keep draining.
74
+ attr_accessor :max_server_error_retries
75
+
76
+ # Maximum forward clock drift (in seconds) tolerated from a client before
77
+ # clamping its HLC physical time to authoritative server UTC.
78
+ attr_accessor :max_clock_drift
79
+
80
+ # Maximum bytes accepted in a single sync_file upload chunk (and advertised
81
+ # to browser and native clients so requests stay below reverse-proxy body
82
+ # limits). Left alone it is InstantRecord::Files::DEFAULT_CHUNK_SIZE.
83
+ attr_accessor :file_chunk_size
84
+
14
85
  def initialize
15
86
  @endpoint = DEFAULT_MOUNT_PATH
87
+ @mount_path = nil
16
88
  @sync_interval = 3
89
+ @drain_batch_size = 100
90
+ @max_server_error_retries = 3
91
+ @file_store = nil
92
+ @max_file_size = nil
93
+ @max_clock_drift = 5
94
+ @file_chunk_size = nil
95
+ @authenticate_request = nil
96
+ @headers = nil
97
+ @sync_scope = nil
98
+ @sync_partition = nil
99
+ @auth_token = nil
100
+ @scope_from = lambda do |request|
101
+ header = request.respond_to?(:headers) ? request.headers["X-Instant-Record-Scope"] : nil
102
+ value = header && !header.to_s.empty? ? header : request.params["scope"]
103
+ value && !value.to_s.empty? ? value : nil
104
+ end
105
+ @partition_from = lambda do |request|
106
+ header = request.respond_to?(:headers) ? request.headers["X-Instant-Record-Partition"] : nil
107
+ return header if header && !header.to_s.empty?
108
+
109
+ explicit = request.params["sync_partition"]
110
+ return explicit if explicit && !explicit.to_s.empty?
111
+
112
+ # `/records` uses `partition` for `sync_window(partition_by:)`; only fall
113
+ # back to `params["partition"]` when the request is not a windowed query.
114
+ path = request.respond_to?(:path) ? request.path.to_s : ""
115
+ unless path.end_with?("/records") && request.params["before_id"].present?
116
+ param = request.params["partition"]
117
+ return param if param && !param.to_s.empty?
118
+ end
119
+ nil
120
+ end
17
121
  end
18
122
  end
19
123
  end
@@ -1,3 +1,9 @@
1
+ require "instant_record/routing"
2
+ require "instant_record/sync_scope"
3
+ require "instant_record/files"
4
+ require "instant_record/outbox_upcaster"
5
+ require "instant_record/shell"
6
+
1
7
  module InstantRecord
2
8
  class Engine < ::Rails::Engine
3
9
  isolate_namespace InstantRecord
@@ -5,10 +11,70 @@ module InstantRecord
5
11
  config.instant_record = ActiveSupport::OrderedOptions.new
6
12
  config.instant_record.mount_path = DEFAULT_MOUNT_PATH
7
13
  config.instant_record.build_on_precompile = false
14
+ config.instant_record.shell_snapshot = nil
15
+ # Serve a native app's screens over HTTP for development (NativeScreensController).
16
+ config.instant_record.native_dev = false
17
+ # Optional island name (for monoliths declaring multiple local_first(:name) blocks)
18
+ # and explicit manifest include overrides for dynamic Ruby patterns.
19
+ config.instant_record.island = nil
20
+ config.instant_record.include = nil
21
+
22
+ initializer "instant_record.routing", before: :add_routing_paths do
23
+ require "action_dispatch/routing/mapper"
24
+ unless ::ActionDispatch::Routing::Mapper.include?(InstantRecord::Routing)
25
+ ::ActionDispatch::Routing::Mapper.include(InstantRecord::Routing)
26
+ end
27
+ end
28
+
29
+ # `render inertia: ..., live: { prop: Model }` where the app has inertia_rails.
30
+ config.after_initialize do
31
+ if defined?(::InertiaRails::Renderer)
32
+ require "instant_record/inertia"
33
+ require "instant_record/inertia/renderer"
34
+ ::InertiaRails::Renderer.prepend(InstantRecord::Inertia::Renderer)
35
+ end
36
+ end
37
+
38
+ # A record that declares sync_file takes its file with it when it goes.
39
+ config.to_prepare { InstantRecord::Files.forget_on_destroy }
40
+
41
+ initializer "instant_record.helpers" do
42
+ ActiveSupport.on_load(:action_view) do
43
+ include InstantRecord::SyncNoticesHelper
44
+ end
45
+ end
46
+
47
+ initializer "instant_record.compiled_site" do |app|
48
+ host = app.config.instant_record.compiled_host
49
+ if host.present?
50
+ require "instant_record/compiled_site"
51
+ app.middleware.insert_after Rack::Sendfile, InstantRecord::CompiledSite, host: host,
52
+ root: app.root.join("public/instant_record_compiled/current").to_s,
53
+ sync_path: app.config.instant_record.mount_path || DEFAULT_MOUNT_PATH
54
+ end
55
+ end
56
+
8
57
  # How long GET /events tails for new changes before closing (the client
9
58
  # reconnects from its cursor). Clients may request less via ?window=.
59
+ #
60
+ # 25s is sized for Puma, where every open stream holds a request thread —
61
+ # short windows are what keep a small thread pool from starving. Under a
62
+ # fiber-per-request server (Falcon) streams are cheap and the window can be
63
+ # minutes; Mercure, the dedicated SSE hub, defaults to 600s. Whatever the
64
+ # length, the cursor makes the close/reopen lossless.
10
65
  config.instant_record.sse_window_seconds = 25.0
11
66
 
67
+ # Idle heartbeat: an SSE comment written when nothing else has been for
68
+ # this long. Two jobs. Reverse proxies kill connections they think are
69
+ # idle (commonly at 60-100s), and a comment resets that clock. And a
70
+ # vanished client — closed laptop, dropped network — is only discovered
71
+ # when a write fails; on a quiet stream the heartbeat is that write, so a
72
+ # dead peer's fiber is collected within one interval instead of surviving
73
+ # to the end of the window. Comments are invisible to clients: EventSource
74
+ # ignores them by spec, and the gem's own parser skips blocks with no
75
+ # `data:` line. 0 disables.
76
+ config.instant_record.sse_heartbeat_seconds = 15.0
77
+
12
78
  initializer "instant_record.migrations" do |app|
13
79
  unless app.root == root
14
80
  config.paths["db/migrate"].expanded.each do |path|
@@ -17,24 +83,6 @@ module InstantRecord
17
83
  end
18
84
  end
19
85
 
20
- # `ActiveRecord::Migrator.migrations_paths` stays as Rails ships it — the
21
- # relative "db/migrate", which resolves only because a server's working
22
- # directory happens to be Rails.root. The browser VM starts at "/", so
23
- # nothing there can be fixed by an initializer: reconciling
24
- # `schema_migrations` before migrating needs a database connection, which no
25
- # initializer is guaranteed. That work is InstantRecord.prepare_database! —
26
- # the boot path's replacement for `prepare_all`, see LocalSchema. Leaving the
27
- # global default alone is deliberate: it keeps `prepare_all`'s own internal
28
- # migrate a no-op, so the reconciliation runs before any migration does.
29
-
30
- # One gap in the PGlite adapter has to be closed before any of that can run
31
- # a migration; see instant_record/pglite_compat.
32
- initializer "instant_record.pglite_compat" do
33
- next unless InstantRecord.browser?
34
-
35
- require "instant_record/pglite_compat"
36
- end
37
-
38
86
  # Auto-mount the sync endpoints on the server. Set
39
87
  # `config.instant_record.mount_path = false` to mount manually,
40
88
  # or to another string to change the path.
@@ -44,6 +92,8 @@ module InstantRecord
44
92
  mount_path = app.config.instant_record.mount_path
45
93
  next unless mount_path
46
94
 
95
+ InstantRecord.config.endpoint = mount_path if mount_path.is_a?(String) && InstantRecord.config.endpoint == DEFAULT_MOUNT_PATH
96
+
47
97
  app.routes.append do
48
98
  mount InstantRecord::Engine => mount_path
49
99
  end
@@ -0,0 +1,162 @@
1
+ require "fileutils"
2
+ require "rack/files"
3
+
4
+ module InstantRecord
5
+ # Where the server keeps the bytes of records that declare `sync_file`: one
6
+ # file per record, in a folder on disk. A file arrives in pieces, each
7
+ # appended to a partial that belongs to one upload, and becomes the record's
8
+ # file when its last piece lands. It is never written again.
9
+ #
10
+ # `InstantRecord.config.file_store` may be anything that answers what this
11
+ # does (a bucket, say). Keys are made by InstantRecord::Files and are safe
12
+ # as paths.
13
+ class FileStore
14
+ # A piece that does not start where the partial ends. `offset` is where
15
+ # the next piece must start.
16
+ class Misplaced < StandardError
17
+ attr_reader :offset
18
+
19
+ def initialize(offset)
20
+ @offset = offset
21
+ super("the next piece starts at #{offset}")
22
+ end
23
+ end
24
+
25
+ # A piece larger than the store's configured chunk size. `limit` is the
26
+ # largest piece accepted in bytes.
27
+ class ChunkTooLarge < StandardError
28
+ attr_reader :limit
29
+
30
+ def initialize(limit)
31
+ @limit = limit
32
+ super("a piece may be at most #{limit} bytes")
33
+ end
34
+ end
35
+
36
+ UPLOAD = /\A[\w-]{1,64}\z/
37
+
38
+ # Default upload/download piece size: 512 KiB, safely below common 1-2 MB
39
+ # reverse-proxy body ceilings (such as nginx's 1m default).
40
+ DEFAULT_CHUNK_SIZE = 512 * 1024
41
+
42
+ attr_reader :root
43
+
44
+ def initialize(root, chunk_size: nil)
45
+ @root = File.expand_path(root.to_s)
46
+ @chunk_size = chunk_size.nil? ? nil : validate_chunk_size!(chunk_size)
47
+ end
48
+
49
+ def chunk_size
50
+ configured = @chunk_size || (defined?(InstantRecord) && InstantRecord.config.file_chunk_size) || DEFAULT_CHUNK_SIZE
51
+ validate_chunk_size!(configured)
52
+ end
53
+
54
+ def exist?(key) = File.file?(path(key))
55
+ def size(key) = File.size(path(key))
56
+
57
+ # How many bytes of an upload are held.
58
+ def offset(key, upload)
59
+ File.size?(partial(key, upload)) || 0
60
+ end
61
+
62
+ # Add a piece of `length` bytes that starts at `at`. Answers where the
63
+ # next one starts. A piece that arrives twice, or out of turn, is refused
64
+ # and nothing is written: the lock makes two senders of one upload take
65
+ # turns, and the second finds the partial already past its piece.
66
+ def append(key, upload, io, at:, length:)
67
+ limit = chunk_size
68
+ raise ChunkTooLarge.new(limit) if length > limit
69
+
70
+ target = partial(key, upload)
71
+ FileUtils.mkdir_p(File.dirname(target))
72
+ File.open(target, File::RDWR | File::CREAT | File::BINARY) do |file|
73
+ file.flock(File::LOCK_EX)
74
+ raise Misplaced.new(file.size) unless file.size == at
75
+
76
+ file.seek(at)
77
+ begin
78
+ written = IO.copy_stream(io, file, length)
79
+ raise Misplaced.new(at) unless written == length
80
+ rescue StandardError
81
+ # Drop a failed piece whole, including bytes copied before a read
82
+ # error, so it can be retried at the same offset.
83
+ file.truncate(at)
84
+ raise
85
+ end
86
+ file.fsync
87
+ at + written
88
+ end
89
+ end
90
+
91
+ # The upload is whole: it becomes the record's file. The first to finish
92
+ # wins, and a file that is already there is left as it is.
93
+ def finish(key, upload)
94
+ source = partial(key, upload)
95
+ unless exist?(key)
96
+ begin
97
+ # Publish without replacing another upload that finished after
98
+ # the existence check. Both paths are on the same filesystem.
99
+ File.link(source, path(key))
100
+ rescue Errno::EEXIST
101
+ # Another upload won; its file stays intact.
102
+ end
103
+ end
104
+ FileUtils.rm_f(source)
105
+ true
106
+ end
107
+
108
+ def discard(key, upload)
109
+ FileUtils.rm_f(partial(key, upload))
110
+ end
111
+
112
+ # The record is gone: its file and every partial of it.
113
+ def delete(key)
114
+ FileUtils.rm_f([path(key), *partials(key)])
115
+ end
116
+
117
+ # Partials no piece has reached since `before`: uploads that were given up.
118
+ # Answers how many were removed.
119
+ def sweep(before:)
120
+ stale = Dir.glob("**/*.part", base: root).map { |file| File.join(root, file) }
121
+ .select do |file|
122
+ File.mtime(file) < before
123
+ rescue Errno::ENOENT
124
+ # An upload may finish or be discarded after the directory scan.
125
+ false
126
+ end
127
+ FileUtils.rm_f(stale)
128
+ stale.size
129
+ end
130
+
131
+ # The file as a Rack response: ranges, HEAD and If-Modified-Since are
132
+ # Rack::Files's.
133
+ def serve(key, request)
134
+ Rack::Files.new(root, {}, "application/octet-stream").serving(request, path(key))
135
+ end
136
+
137
+ def path(key) = File.join(root, key)
138
+
139
+ private
140
+
141
+ def partial(key, upload)
142
+ raise ArgumentError, "not an upload's name: #{upload.inspect}" unless UPLOAD.match?(upload.to_s)
143
+
144
+ "#{path(key)}.#{upload}.part"
145
+ end
146
+
147
+ def validate_chunk_size!(value)
148
+ raise ArgumentError, "chunk_size must be a positive integer, got #{value.inspect}" unless value.is_a?(Integer) && value.positive?
149
+
150
+ value
151
+ end
152
+
153
+ def partials(key)
154
+ folder, name = File.split(path(key))
155
+ return [] unless File.directory?(folder)
156
+
157
+ Dir.children(folder)
158
+ .select { |entry| entry.start_with?("#{name}.") && entry.end_with?(".part") }
159
+ .map { |entry| File.join(folder, entry) }
160
+ end
161
+ end
162
+ end