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,800 @@
1
+ require "securerandom"
2
+
3
+ module InstantRecord
4
+ # Raised by a sync_action to reject a mutation with a clean domain reason.
5
+ # Rolls back the transaction on both client and server; on the server,
6
+ # MutationApplier returns the message in the rejection payload.
7
+ class MutationRejected < StandardError; end
8
+
9
+ # Declarative dual-runtime transactional custom mutators (`sync_action`).
10
+ #
11
+ # A model declares a mutator with `sync_action :action_name` backed by
12
+ # `def self.action_name(args)` (or keyword arguments) and invokes it through
13
+ # `Model.perform_sync_action(:action_name, args)` or
14
+ # `InstantRecord.mutate("Model.action_name", args)`.
15
+ #
16
+ # - In the browser runtime, the mutator runs inside a SQLite savepoint,
17
+ # suppresses per-row outbox mutations, captures local rollback snapshots,
18
+ # and queues a single `{ mutator, args, mutation_id }` outbox intent.
19
+ # - On the server runtime, direct calls run in one transaction with normal
20
+ # server change logging; replayed intents run inside MutationApplier's
21
+ # transaction with AppliedMutation idempotency, unified SyncScope + action
22
+ # authorization, commit-guarded ActiveJob enqueueing, and rollback payloads.
23
+ # - In compiled Spinel builds, EntryBuilder generates a static `case`
24
+ # dispatcher for `SyncActions.dispatch` (zero `send` or `constantize`).
25
+ module SyncActions
26
+ ACTION_NAME_PATTERN = /\A[a-z_][a-zA-Z0-9_]*[!?]?\z/
27
+
28
+ # Pure-Ruby 16-bit-split SHA-256 constants (FIPS 180-4) for deterministic
29
+ # UUID derivation across CRuby and 32-bit signed Spinel (`-DSP_INT_OVERFLOW_MODE_RAISE`)
30
+ # without Digest or >31-bit integer overflow.
31
+ SHA256_K_HI = [
32
+ 0x428a, 0x7137, 0xb5c0, 0xe9b5, 0x3956, 0x59f1, 0x923f, 0xab1c,
33
+ 0xd807, 0x1283, 0x2431, 0x550c, 0x72be, 0x80de, 0x9bdc, 0xc19b,
34
+ 0xe49b, 0xefbe, 0x0fc1, 0x240c, 0x2de9, 0x4a74, 0x5cb0, 0x76f9,
35
+ 0x983e, 0xa831, 0xb003, 0xbf59, 0xc6e0, 0xd5a7, 0x06ca, 0x1429,
36
+ 0x27b7, 0x2e1b, 0x4d2c, 0x5338, 0x650a, 0x766a, 0x81c2, 0x9272,
37
+ 0xa2bf, 0xa81a, 0xc24b, 0xc76c, 0xd192, 0xd699, 0xf40e, 0x106a,
38
+ 0x19a4, 0x1e37, 0x2748, 0x34b0, 0x391c, 0x4ed8, 0x5b9c, 0x682e,
39
+ 0x748f, 0x78a5, 0x84c8, 0x8cc7, 0x90be, 0xa450, 0xbef9, 0xc671
40
+ ].freeze
41
+
42
+ SHA256_K_LO = [
43
+ 0x2f98, 0x4491, 0xfbcf, 0xdba5, 0xc25b, 0x11f1, 0x82a4, 0x5ed5,
44
+ 0xaa98, 0x5b01, 0x85be, 0x7dc3, 0x5d74, 0xb1fe, 0x06a7, 0xf174,
45
+ 0x69c1, 0x4786, 0x9dc6, 0xa1cc, 0x2c6f, 0x84aa, 0xa9dc, 0x88da,
46
+ 0x5152, 0xc66d, 0x27c8, 0x7fc7, 0x0bf3, 0x9147, 0x6351, 0x2967,
47
+ 0x0a85, 0x2138, 0x6dfc, 0x0d13, 0x7354, 0x0abb, 0xc92e, 0x2c85,
48
+ 0xe8a1, 0x664b, 0x8b70, 0x51a3, 0xe819, 0x0624, 0x3585, 0xa070,
49
+ 0xc116, 0x6c08, 0x774c, 0xbcb5, 0x0cb3, 0xaa4a, 0xca4f, 0x6ff3,
50
+ 0x82ee, 0x636f, 0x7814, 0x0208, 0xfffa, 0x6ceb, 0xa3f7, 0x78f2
51
+ ].freeze
52
+
53
+ SHA256_H_HI = [0x6a09, 0xbb67, 0x3c6e, 0xa54f, 0x510e, 0x9b05, 0x1f83, 0x5be0].freeze
54
+ SHA256_H_LO = [0xe667, 0xae85, 0xf372, 0xf53a, 0x527f, 0x688c, 0xd9ab, 0xcd19].freeze
55
+
56
+ HEX_DIGITS = "0123456789abcdef".freeze
57
+ MASK16 = 0xffff
58
+
59
+ def self.included(base)
60
+ base.extend(ClassMethods)
61
+ end
62
+
63
+ module ClassMethods
64
+ # Declare a dual-runtime custom mutator on this class.
65
+ # In compiled builds, define `def self.<action_name>(args)` (no block).
66
+ def sync_action(action_name, &block)
67
+ action = action_name.to_s
68
+ unless ACTION_NAME_PATTERN.match?(action)
69
+ raise ArgumentError, "Invalid sync_action name: #{action_name.inspect}"
70
+ end
71
+
72
+ @instant_record_sync_actions ||= {}
73
+ @instant_record_sync_actions[action] = block
74
+ InstantRecord::SyncActions.register(self, action, block)
75
+ action.to_sym
76
+ end
77
+
78
+ def instant_record_sync_actions
79
+ @instant_record_sync_actions ||= {}
80
+ end
81
+
82
+ # Declare server-side authorization for one action or all actions on this
83
+ # class. Wrap inside `server_only` in models compiled for browser/native.
84
+ def authorize_sync_action(action_name = nil, &block)
85
+ @instant_record_action_authorizers ||= {}
86
+ key = action_name.nil? ? :__all__ : action_name.to_s
87
+ @instant_record_action_authorizers[key] = block
88
+ end
89
+
90
+ def instant_record_action_authorizer(action_name)
91
+ authorizers = @instant_record_action_authorizers
92
+ return nil unless authorizers
93
+
94
+ authorizers[action_name.to_s] || authorizers[:__all__]
95
+ end
96
+
97
+ # Execute a declared sync_action in the current runtime.
98
+ def perform_sync_action(action_name, args = nil, mutation_id: nil, **kwargs)
99
+ merged = args ? (kwargs.empty? ? args : args.merge(kwargs)) : kwargs
100
+ InstantRecord::SyncActions.mutate("#{name}.#{action_name}", merged, mutation_id: mutation_id)
101
+ end
102
+ end
103
+
104
+ # Captures local optimistic changes inside a browser SQLite savepoint so a
105
+ # single outbox intent is queued and rejected intents can roll back cleanly.
106
+ class ClientFrame
107
+ attr_reader :mutation_id
108
+
109
+ def initialize(mutation_id)
110
+ @mutation_id = mutation_id
111
+ @seq = 0
112
+ @touched = {}
113
+ @order = []
114
+ end
115
+
116
+ def next_uuid
117
+ uuid = SyncActions.deterministic_uuid(@mutation_id, @seq)
118
+ @seq += 1
119
+ uuid
120
+ end
121
+
122
+ def record_create(record)
123
+ key = "#{record.class.name}:#{record.id}"
124
+ return if @touched.key?(key)
125
+
126
+ @touched[key] = {
127
+ "type" => record.class.name,
128
+ "id" => record.id,
129
+ "op" => "create"
130
+ }
131
+ @order << key
132
+ end
133
+
134
+ def capture_before(record, operation)
135
+ key = "#{record.class.name}:#{record.id}"
136
+ return if @touched.key?(key)
137
+
138
+ before = record.attributes.dup
139
+ if operation == "update" && record.respond_to?(:changes_to_save)
140
+ record.changes_to_save.each do |col, pair|
141
+ before[col.to_s] = pair[0]
142
+ end
143
+ end
144
+
145
+ @touched[key] = {
146
+ "type" => record.class.name,
147
+ "id" => record.id,
148
+ "op" => operation,
149
+ "before" => SyncActions.snapshot_attributes(before)
150
+ }
151
+ @order << key
152
+ end
153
+
154
+ def touched_list
155
+ list = []
156
+ @order.each { |key| list << @touched[key] }
157
+ list
158
+ end
159
+ end
160
+
161
+ # --- cruby-server-frame:start ---
162
+ # Server-only execution frame used by MutationApplier during authoritative
163
+ # replay (and direct server calls with deterministic mutation_id).
164
+ class ServerFrame
165
+ attr_reader :mutation_id, :identity, :scope, :partition, :enforcing
166
+
167
+ def initialize(mutation_id:, identity: nil, scope: nil, partition: nil, enforcing: false)
168
+ @mutation_id = mutation_id
169
+ @identity = identity
170
+ @scope = scope
171
+ @partition = partition
172
+ @enforcing = enforcing
173
+ @seq = 0
174
+ @touched_refs = []
175
+ @touched_seen = {}
176
+ @applied_order = []
177
+ @applied = {}
178
+ end
179
+
180
+ def enforcing? = @enforcing
181
+
182
+ def next_uuid
183
+ uuid = SyncActions.deterministic_uuid(@mutation_id, @seq)
184
+ @seq += 1
185
+ uuid
186
+ end
187
+
188
+ def note_ref(type, id)
189
+ return if id.nil? || id.to_s.empty?
190
+
191
+ key = "#{type}:#{id}"
192
+ return if @touched_seen[key]
193
+
194
+ @touched_seen[key] = true
195
+ @touched_refs << [type, id]
196
+ end
197
+
198
+ def note_read(record)
199
+ note_ref(record.class.name, record.id)
200
+ end
201
+
202
+ def touched_refs
203
+ @touched_refs
204
+ end
205
+
206
+ def applied_records
207
+ @applied_order.map { |key| @applied[key] }
208
+ end
209
+
210
+ def authorize_create!(record)
211
+ model = record.class
212
+ note_ref(model.name, record.id)
213
+
214
+ if (part = model.instant_record_sync_partition)
215
+ part_value = part.extract(@partition)
216
+ raise MutationApplier::NotPermitted, "a partition is required" unless part_value
217
+
218
+ col = part.column
219
+ given = record[col].presence
220
+ raise MutationApplier::NotPermitted, "record not in active partition" if given && given.to_s != part_value
221
+
222
+ record[col] = part_value
223
+ end
224
+
225
+ if (column = model.instant_record_sync_scope)
226
+ raise MutationApplier::NotPermitted, "a scope is required" unless @scope
227
+
228
+ given = record[column].presence
229
+ raise MutationApplier::NotPermitted if given && given != @scope
230
+
231
+ record[column] = @scope
232
+ end
233
+
234
+ if hidden?(model, record.id)
235
+ raise MutationApplier::NotPermitted
236
+ end
237
+ end
238
+
239
+ def finalize_create!(record)
240
+ model = record.class
241
+ permit_writable!(model, record.id)
242
+ log_change(record, "create")
243
+ record_applied(model.name, record.id, {
244
+ type: model.name,
245
+ id: record.id,
246
+ operation: "create",
247
+ version: record[:server_version],
248
+ attributes: InstantRecord.wire_attributes(record.attributes)
249
+ })
250
+ end
251
+
252
+ def authorize_update_before!(record)
253
+ model = record.class
254
+ note_ref(model.name, record.id)
255
+
256
+ if (part = model.instant_record_sync_partition)
257
+ part_value = part.extract(@partition)
258
+ raise MutationApplier::NotPermitted, "a partition is required" unless part_value
259
+
260
+ col = part.column
261
+ existing_part = record.attribute_in_database(col)
262
+ raise MutationApplier::NotPermitted, "record not in active partition" if existing_part.to_s != part_value || record[col].to_s != part_value
263
+ end
264
+
265
+ if (column = model.instant_record_sync_scope)
266
+ raise MutationApplier::NotPermitted, "a scope is required" unless @scope
267
+
268
+ existing_scope = record.attribute_in_database(column)
269
+ raise MutationApplier::NotPermitted if existing_scope != @scope || record[column] != @scope
270
+ end
271
+
272
+ raise MutationApplier::NotPermitted if hidden?(model, record.id)
273
+ permit_writable!(model, record.id)
274
+ end
275
+
276
+ def finalize_update!(record)
277
+ model = record.class
278
+ permit_writable!(model, record.id)
279
+ log_change(record, "update")
280
+ record_applied(model.name, record.id, {
281
+ type: model.name,
282
+ id: record.id,
283
+ operation: "update",
284
+ version: record[:server_version],
285
+ attributes: InstantRecord.wire_attributes(record.attributes)
286
+ })
287
+ end
288
+
289
+ def authorize_destroy!(record)
290
+ model = record.class
291
+ note_ref(model.name, record.id)
292
+
293
+ if (part = model.instant_record_sync_partition)
294
+ part_value = part.extract(@partition)
295
+ raise MutationApplier::NotPermitted, "a partition is required" unless part_value
296
+ raise MutationApplier::NotPermitted, "record not in active partition" if record[part.column].to_s != part_value
297
+ end
298
+
299
+ if (column = model.instant_record_sync_scope)
300
+ raise MutationApplier::NotPermitted, "a scope is required" unless @scope
301
+ raise MutationApplier::NotPermitted if record[column] != @scope
302
+ end
303
+
304
+ raise MutationApplier::NotPermitted if hidden?(model, record.id)
305
+ permit_writable!(model, record.id)
306
+ end
307
+
308
+ def finalize_destroy!(record)
309
+ model = record.class
310
+ InstantRecord::Change.create!(
311
+ record_type: model.name,
312
+ record_id: record.id,
313
+ operation: "destroy",
314
+ version: 0,
315
+ attributes_payload: {},
316
+ scope: InstantRecord.scope_of(record),
317
+ partition: InstantRecord.partition_of(record)
318
+ )
319
+ record_applied(model.name, record.id, {
320
+ type: model.name,
321
+ id: record.id,
322
+ operation: "destroy",
323
+ version: 0,
324
+ attributes: {}
325
+ })
326
+ end
327
+
328
+ private
329
+
330
+ def hidden?(model, id)
331
+ model.instant_record_visibility && model.exists?(id: id) &&
332
+ !SyncScope.visible(model, @identity, partition: @partition).exists?(id: id)
333
+ end
334
+
335
+ def permit_writable!(model, id)
336
+ return unless model.instant_record_writability
337
+
338
+ raise MutationApplier::NotPermitted unless SyncScope.writable(model, @identity, partition: @partition).exists?(id: id)
339
+ end
340
+
341
+ def log_change(record, operation)
342
+ InstantRecord::Change.create!(
343
+ record_type: record.class.name,
344
+ record_id: record.id,
345
+ operation: operation,
346
+ version: record[:server_version],
347
+ attributes_payload: InstantRecord.wire_attributes(record.attributes),
348
+ scope: InstantRecord.scope_of(record),
349
+ partition: InstantRecord.partition_of(record)
350
+ )
351
+ end
352
+
353
+ def record_applied(type, id, payload)
354
+ key = "#{type}:#{id}"
355
+ @applied_order << key unless @applied.key?(key)
356
+ @applied[key] = payload
357
+ end
358
+ end
359
+ # --- cruby-server-frame:end ---
360
+
361
+ class << self
362
+ def client_frame
363
+ @client_frame
364
+ end
365
+
366
+ def recording_client_mutator?
367
+ !@client_frame.nil?
368
+ end
369
+
370
+ def active_frame
371
+ InstantRecord.browser? ? client_frame : server_frame
372
+ end
373
+
374
+ # Execute a declared sync_action in the active runtime.
375
+ def mutate(mutator_name, args = nil, mutation_id: nil, **kwargs)
376
+ name = mutator_name.to_s
377
+ merged = args ? (kwargs.empty? ? args : args.merge(kwargs)) : kwargs
378
+ normalized = normalize_args(merged)
379
+
380
+ if InstantRecord.browser?
381
+ # Nested mutate inside an active client mutator joins the outer
382
+ # savepoint and single outbox intent rather than splitting intents.
383
+ if @client_frame
384
+ return with_savepoint { dispatch(name, normalized) }
385
+ end
386
+
387
+ id = (mutation_id.nil? || mutation_id.to_s.empty?) ? SecureRandom.uuid : mutation_id.to_s
388
+ owner_type = owner_type_of(name)
389
+ frame = ClientFrame.new(id)
390
+
391
+ with_savepoint do
392
+ @client_frame = frame
393
+ begin
394
+ result = dispatch(name, normalized)
395
+ InstantRecord::OutboxMutation.create!(
396
+ id: id,
397
+ record_type: owner_type,
398
+ record_id: name,
399
+ operation: "mutator",
400
+ changes_payload: {
401
+ "mutator" => name,
402
+ "args" => normalized,
403
+ "touched" => frame.touched_list
404
+ },
405
+ base_version: 0
406
+ )
407
+ result
408
+ ensure
409
+ @client_frame = nil
410
+ end
411
+ end
412
+ else
413
+ execute_on_server(name, normalized, mutation_id)
414
+ end
415
+ end
416
+
417
+ # Delegated to InstantRecord::Host so compiled builds use native SQLite SAVEPOINT.
418
+ def with_savepoint(&block)
419
+ InstantRecord::Host.with_savepoint(&block)
420
+ end
421
+
422
+ # Recursively normalize mutator arguments to JSON-safe string-keyed values.
423
+ def normalize_args(value)
424
+ return {} if value.nil?
425
+ unless value.is_a?(Hash)
426
+ raise ArgumentError, "sync_action args must be a Hash"
427
+ end
428
+
429
+ normalize_hash(value)
430
+ end
431
+
432
+ # Capture full row attributes (including server_version and sync_state)
433
+ # with microsecond timestamp precision for client rollback snapshots.
434
+ def snapshot_attributes(attributes)
435
+ out = {}
436
+ attributes.each do |key, value|
437
+ out[key.to_s] = value.respond_to?(:usec) ? value.iso8601(InstantRecord::TIME_PRECISION) : value
438
+ end
439
+ out
440
+ end
441
+
442
+ def owner_type_of(mutator_name)
443
+ dot = mutator_name.rindex(".")
444
+ dot ? mutator_name[0, dot] : mutator_name
445
+ end
446
+
447
+ # Deterministic RFC 4122 UUIDv5-formatted identifier derived from
448
+ # (mutation_id, seq) using 32-bit-safe pure-Ruby SHA-256.
449
+ def deterministic_uuid(mutation_id, seq)
450
+ bytes = sha256_bytes("#{mutation_id}:#{seq}")
451
+ bytes[6] = (bytes[6] & 0x0f) | 0x50
452
+ bytes[8] = (bytes[8] & 0x3f) | 0x80
453
+ hex = +""
454
+ i = 0
455
+ while i < 16
456
+ byte = bytes[i]
457
+ hex << HEX_DIGITS[byte >> 4] << HEX_DIGITS[byte & 0x0f]
458
+ hex << "-" if i == 3 || i == 5 || i == 7 || i == 9
459
+ i += 1
460
+ end
461
+ hex
462
+ end
463
+
464
+ # --- cruby-only:start ---
465
+ def server_frame
466
+ return nil if InstantRecord.browser?
467
+
468
+ ActiveSupport::IsolatedExecutionState[:instant_record_server_mutator_frame]
469
+ end
470
+
471
+ def enforcing_server_mutator?
472
+ frame = server_frame
473
+ !frame.nil? && frame.enforcing?
474
+ end
475
+
476
+ def server_authorize_create!(record) = server_frame&.authorize_create!(record)
477
+ def server_finalize_create!(record) = server_frame&.finalize_create!(record)
478
+ def server_authorize_update_before!(record) = server_frame&.authorize_update_before!(record)
479
+ def server_finalize_update!(record) = server_frame&.finalize_update!(record)
480
+ def server_authorize_destroy!(record) = server_frame&.authorize_destroy!(record)
481
+ def server_finalize_destroy!(record) = server_frame&.finalize_destroy!(record)
482
+ def server_note_read(record) = server_frame&.note_read(record)
483
+
484
+ def with_server_frame(frame)
485
+ previous = ActiveSupport::IsolatedExecutionState[:instant_record_server_mutator_frame]
486
+ ActiveSupport::IsolatedExecutionState[:instant_record_server_mutator_frame] = frame
487
+ yield frame
488
+ ensure
489
+ ActiveSupport::IsolatedExecutionState[:instant_record_server_mutator_frame] = previous
490
+ end
491
+
492
+ def execute_on_server(name, normalized, mutation_id)
493
+ with_savepoint do
494
+ if mutation_id && !mutation_id.to_s.empty?
495
+ with_server_frame(ServerFrame.new(mutation_id: mutation_id.to_s, enforcing: false)) do
496
+ dispatch(name, normalized)
497
+ end
498
+ else
499
+ dispatch(name, normalized)
500
+ end
501
+ end
502
+ end
503
+
504
+ def registry
505
+ @registry ||= {}
506
+ end
507
+
508
+ def reset_registry!
509
+ @registry = {}
510
+ end
511
+
512
+ def register(klass, action_name, block = nil)
513
+ return unless klass.name
514
+
515
+ registry["#{klass.name}.#{action_name}"] = {
516
+ klass: klass,
517
+ action: action_name.to_s,
518
+ block: block
519
+ }
520
+ end
521
+
522
+ def resolve(mutator_name)
523
+ name = mutator_name.to_s
524
+ entry = registry[name]
525
+ return entry if entry
526
+
527
+ # Fallback for reloaded classes on CRuby: check allowlisted/loaded Syncable models.
528
+ dot = name.rindex(".")
529
+ return nil unless dot
530
+
531
+ owner = name[0, dot]
532
+ action = name[(dot + 1)..]
533
+ model = InstantRecord.synced_model(owner)
534
+ if model && model.respond_to?(:instant_record_sync_actions) && model.instant_record_sync_actions.key?(action)
535
+ return { klass: model, action: action, block: model.instant_record_sync_actions[action] }
536
+ end
537
+
538
+ nil
539
+ end
540
+
541
+ def dispatch(mutator_name, args)
542
+ entry = resolve(mutator_name)
543
+ raise ArgumentError, "Unknown sync_action: #{mutator_name}" unless entry
544
+
545
+ klass = entry[:klass]
546
+ action = entry[:action]
547
+ block = entry[:block]
548
+
549
+ if block
550
+ invoke_callable(klass, block, args)
551
+ else
552
+ unless klass.respond_to?(action)
553
+ raise ArgumentError, "sync_action #{mutator_name} has no class method #{klass.name}.#{action}"
554
+ end
555
+
556
+ method_obj = klass.method(action)
557
+ invoke_callable(klass, method_obj, args, direct_method: true)
558
+ end
559
+ end
560
+
561
+ # Commit guard for ActiveJob: ensures non-DB queue adapters do not enqueue
562
+ # ghost jobs when a server sync_action transaction rolls back.
563
+ module ActiveJobCommitGuard
564
+ private
565
+
566
+ def raw_enqueue
567
+ frame = InstantRecord::SyncActions.server_frame
568
+ if frame && InstantRecord::SyncActions.defer_active_job?(self)
569
+ tx = ActiveRecord::Base.connection.current_transaction
570
+ if tx.respond_to?(:after_commit) && ActiveRecord::Base.connection.open_transactions > 0
571
+ deferred_scheduled_at = scheduled_at
572
+ deferred_queue_name = queue_name
573
+ deferred_priority = priority
574
+ tx.after_commit do
575
+ prev_at, prev_queue, prev_priority = scheduled_at, queue_name, priority
576
+ self.scheduled_at = deferred_scheduled_at
577
+ self.queue_name = deferred_queue_name
578
+ self.priority = deferred_priority
579
+ self.successfully_enqueued = false
580
+ super()
581
+ ensure
582
+ self.scheduled_at = prev_at
583
+ self.queue_name = prev_queue
584
+ self.priority = prev_priority
585
+ end
586
+ self.successfully_enqueued = true
587
+ self
588
+ else
589
+ super
590
+ end
591
+ else
592
+ super
593
+ end
594
+ end
595
+ end
596
+
597
+ def defer_active_job?(job)
598
+ # If Rails' own EnqueueAfterTransactionCommit is already active for this job,
599
+ # let Rails handle deferral without double-wrapping.
600
+ return false if job.class.respond_to?(:enqueue_after_transaction_commit) && job.class.enqueue_after_transaction_commit
601
+
602
+ # DB-transactional queue adapters (e.g., SolidQueue) persist inside the
603
+ # active SQL transaction directly and roll back with it.
604
+ adapter = job.class.queue_adapter
605
+ return false if adapter.class.name.to_s.include?("SolidQueue")
606
+
607
+ true
608
+ end
609
+
610
+ def install_active_job_guard!
611
+ return unless defined?(ActiveJob::Base)
612
+ return if ActiveJob::Base.ancestors.include?(ActiveJobCommitGuard)
613
+
614
+ ActiveJob::Base.prepend(ActiveJobCommitGuard)
615
+ end
616
+
617
+ private
618
+
619
+ def invoke_callable(klass, callable, args, direct_method: false)
620
+ params = callable.parameters
621
+ if params.empty?
622
+ direct_method ? callable.call : klass.instance_exec(&callable)
623
+ elsif params.all? { |kind, _| kind == :key || kind == :keyreq || kind == :keyrest }
624
+ kwargs = {}
625
+ has_keyrest = params.any? { |kind, _| kind == :keyrest }
626
+ if has_keyrest
627
+ args.each { |k, v| kwargs[k.to_sym] = v }
628
+ else
629
+ params.each do |kind, param_name|
630
+ key = param_name.to_s
631
+ if args.key?(key)
632
+ kwargs[param_name] = args[key]
633
+ elsif kind == :keyreq
634
+ kwargs[param_name] = nil
635
+ end
636
+ end
637
+ end
638
+ direct_method ? callable.call(**kwargs) : klass.instance_exec(**kwargs, &callable)
639
+ else
640
+ direct_method ? callable.call(args) : klass.instance_exec(args, &callable)
641
+ end
642
+ end
643
+ # --- cruby-only:end ---
644
+
645
+ def normalize_hash(hash)
646
+ out = {}
647
+ hash.each do |key, val|
648
+ out[key.to_s] = normalize_value(val)
649
+ end
650
+ out
651
+ end
652
+
653
+ def normalize_value(value)
654
+ if value.is_a?(Hash)
655
+ normalize_hash(value)
656
+ elsif value.is_a?(Array)
657
+ list = []
658
+ value.each { |item| list << normalize_value(item) }
659
+ list
660
+ elsif value.is_a?(Symbol)
661
+ value.to_s
662
+ elsif value.respond_to?(:usec)
663
+ value.iso8601(InstantRecord::TIME_PRECISION)
664
+ else
665
+ value
666
+ end
667
+ end
668
+
669
+ def rotr32_hi(hi, lo, n)
670
+ if n < 16
671
+ (hi >> n) | ((lo & ((1 << n) - 1)) << (16 - n))
672
+ else
673
+ m = n - 16
674
+ (lo >> m) | ((hi & ((1 << m) - 1)) << (16 - m))
675
+ end
676
+ end
677
+
678
+ def rotr32_lo(hi, lo, n)
679
+ if n < 16
680
+ (lo >> n) | ((hi & ((1 << n) - 1)) << (16 - n))
681
+ else
682
+ m = n - 16
683
+ (hi >> m) | ((lo & ((1 << m) - 1)) << (16 - m))
684
+ end
685
+ end
686
+
687
+ def sha256_bytes(text)
688
+ msg = []
689
+ text.each_byte { |b| msg << b }
690
+ byte_len = msg.length
691
+ msg << 0x80
692
+ msg << 0 while (msg.length % 64) != 56
693
+
694
+ # Append 64-bit big-endian bit length using 16-bit words (safe on 32-bit signed ints).
695
+ len_lo = (byte_len & 0x1fff) << 3
696
+ len_mid = (byte_len >> 13) & MASK16
697
+ len_hi = (byte_len >> 29) & MASK16
698
+ msg << 0 << 0 << ((len_hi >> 8) & 0xff) << (len_hi & 0xff)
699
+ msg << ((len_mid >> 8) & 0xff) << (len_mid & 0xff) << ((len_lo >> 8) & 0xff) << (len_lo & 0xff)
700
+
701
+ h0_h = SHA256_H_HI[0]; h0_l = SHA256_H_LO[0]
702
+ h1_h = SHA256_H_HI[1]; h1_l = SHA256_H_LO[1]
703
+ h2_h = SHA256_H_HI[2]; h2_l = SHA256_H_LO[2]
704
+ h3_h = SHA256_H_HI[3]; h3_l = SHA256_H_LO[3]
705
+ h4_h = SHA256_H_HI[4]; h4_l = SHA256_H_LO[4]
706
+ h5_h = SHA256_H_HI[5]; h5_l = SHA256_H_LO[5]
707
+ h6_h = SHA256_H_HI[6]; h6_l = SHA256_H_LO[6]
708
+ h7_h = SHA256_H_HI[7]; h7_l = SHA256_H_LO[7]
709
+
710
+ offset = 0
711
+ while offset < msg.length
712
+ w_h = Array.new(64, 0)
713
+ w_l = Array.new(64, 0)
714
+ i = 0
715
+ while i < 16
716
+ j = offset + i * 4
717
+ w_h[i] = (msg[j] << 8) | msg[j + 1]
718
+ w_l[i] = (msg[j + 2] << 8) | msg[j + 3]
719
+ i += 1
720
+ end
721
+ while i < 64
722
+ xh = w_h[i - 15]; xl = w_l[i - 15]
723
+ s0_h = rotr32_hi(xh, xl, 7) ^ rotr32_hi(xh, xl, 18) ^ (xh >> 3)
724
+ s0_l = rotr32_lo(xh, xl, 7) ^ rotr32_lo(xh, xl, 18) ^ ((xl >> 3) | ((xh & 7) << 13))
725
+
726
+ yh = w_h[i - 2]; yl = w_l[i - 2]
727
+ s1_h = rotr32_hi(yh, yl, 17) ^ rotr32_hi(yh, yl, 19) ^ (yh >> 10)
728
+ s1_l = rotr32_lo(yh, yl, 17) ^ rotr32_lo(yh, yl, 19) ^ ((yl >> 10) | ((yh & 0x3ff) << 6))
729
+
730
+ sum_l = w_l[i - 16] + s0_l + w_l[i - 7] + s1_l
731
+ w_l[i] = sum_l & MASK16
732
+ w_h[i] = (w_h[i - 16] + s0_h + w_h[i - 7] + s1_h + (sum_l >> 16)) & MASK16
733
+ i += 1
734
+ end
735
+
736
+ ah = h0_h; al = h0_l
737
+ bh = h1_h; bl = h1_l
738
+ ch = h2_h; cl = h2_l
739
+ dh = h3_h; dl = h3_l
740
+ eh = h4_h; el = h4_l
741
+ fh = h5_h; fl = h5_l
742
+ gh = h6_h; gl = h6_l
743
+ hh = h7_h; hl = h7_l
744
+
745
+ i = 0
746
+ while i < 64
747
+ s1_h = rotr32_hi(eh, el, 6) ^ rotr32_hi(eh, el, 11) ^ rotr32_hi(eh, el, 25)
748
+ s1_l = rotr32_lo(eh, el, 6) ^ rotr32_lo(eh, el, 11) ^ rotr32_lo(eh, el, 25)
749
+ ch_h = (eh & fh) ^ ((eh ^ MASK16) & gh)
750
+ ch_l = (el & fl) ^ ((el ^ MASK16) & gl)
751
+
752
+ t1_l = hl + s1_l + ch_l + SHA256_K_LO[i] + w_l[i]
753
+ t1_h = (hh + s1_h + ch_h + SHA256_K_HI[i] + w_h[i] + (t1_l >> 16)) & MASK16
754
+ t1_l &= MASK16
755
+
756
+ s0_h = rotr32_hi(ah, al, 2) ^ rotr32_hi(ah, al, 13) ^ rotr32_hi(ah, al, 22)
757
+ s0_l = rotr32_lo(ah, al, 2) ^ rotr32_lo(ah, al, 13) ^ rotr32_lo(ah, al, 22)
758
+ maj_h = (ah & bh) ^ (ah & ch) ^ (bh & ch)
759
+ maj_l = (al & bl) ^ (al & cl) ^ (bl & cl)
760
+
761
+ t2_l = s0_l + maj_l
762
+ t2_h = (s0_h + maj_h + (t2_l >> 16)) & MASK16
763
+ t2_l &= MASK16
764
+
765
+ hh = gh; hl = gl
766
+ gh = fh; gl = fl
767
+ fh = eh; fl = el
768
+ el = dl + t1_l
769
+ eh = (dh + t1_h + (el >> 16)) & MASK16
770
+ el &= MASK16
771
+ dh = ch; dl = cl
772
+ ch = bh; cl = bl
773
+ bh = ah; bl = al
774
+ al = t1_l + t2_l
775
+ ah = (t1_h + t2_h + (al >> 16)) & MASK16
776
+ al &= MASK16
777
+ i += 1
778
+ end
779
+
780
+ h0_l += al; h0_h = (h0_h + ah + (h0_l >> 16)) & MASK16; h0_l &= MASK16
781
+ h1_l += bl; h1_h = (h1_h + bh + (h1_l >> 16)) & MASK16; h1_l &= MASK16
782
+ h2_l += cl; h2_h = (h2_h + ch + (h2_l >> 16)) & MASK16; h2_l &= MASK16
783
+ h3_l += dl; h3_h = (h3_h + dh + (h3_l >> 16)) & MASK16; h3_l &= MASK16
784
+ h4_l += el; h4_h = (h4_h + eh + (h4_l >> 16)) & MASK16; h4_l &= MASK16
785
+ h5_l += fl; h5_h = (h5_h + fh + (h5_l >> 16)) & MASK16; h5_l &= MASK16
786
+ h6_l += gl; h6_h = (h6_h + gh + (h6_l >> 16)) & MASK16; h6_l &= MASK16
787
+ h7_l += hl; h7_h = (h7_h + hh + (h7_l >> 16)) & MASK16; h7_l &= MASK16
788
+ offset += 64
789
+ end
790
+
791
+ [
792
+ (h0_h >> 8) & 0xff, h0_h & 0xff, (h0_l >> 8) & 0xff, h0_l & 0xff,
793
+ (h1_h >> 8) & 0xff, h1_h & 0xff, (h1_l >> 8) & 0xff, h1_l & 0xff,
794
+ (h2_h >> 8) & 0xff, h2_h & 0xff, (h2_l >> 8) & 0xff, h2_l & 0xff,
795
+ (h3_h >> 8) & 0xff, h3_h & 0xff, (h3_l >> 8) & 0xff, h3_l & 0xff
796
+ ]
797
+ end
798
+ end
799
+ end
800
+ end