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,92 @@
1
+ require "digest"
2
+ require "instant_record/syncable"
3
+ require "instant_record/file_store"
4
+
5
+ module InstantRecord
6
+ # The server's half of `sync_file`: where a record's bytes are kept, and
7
+ # when they go. Who may read and write them is the record's own rule
8
+ # (SyncScope), asked by FilesController. Server only: the browser keeps its
9
+ # copy in the origin's private file system (frontend/files.js).
10
+ module Files
11
+ # An id that is safe as a file's name is used as it is.
12
+ PLAIN_ID = /\A[\w-]{1,128}\z/
13
+
14
+ # The most bytes taken for one file where neither the model nor the
15
+ # configuration names a number: two gigabytes.
16
+ MAX_SIZE = 2 * 1024 * 1024 * 1024
17
+
18
+ # Default upload/download piece size: 512 KiB, safely below common 1-2 MB
19
+ # reverse-proxy body ceilings.
20
+ DEFAULT_CHUNK_SIZE = FileStore::DEFAULT_CHUNK_SIZE
21
+
22
+ class << self
23
+ def store
24
+ InstantRecord.config.file_store ||= FileStore.new(Rails.root.join("storage", "instant_record"))
25
+ end
26
+
27
+ def carried_by?(model)
28
+ model.respond_to?(:instant_record_sync_file) && !!model.instant_record_sync_file
29
+ end
30
+
31
+ # The model behind a type in an address, when its records carry files.
32
+ def model(type)
33
+ found = InstantRecord.synced_model(type)
34
+ found if found && carried_by?(found)
35
+ end
36
+
37
+ # Where a record's file is kept. Any other id is kept under its digest,
38
+ # behind a mark no plain id can start with.
39
+ def key(model, id)
40
+ id = id.to_s
41
+ name = PLAIN_ID.match?(id) ? id : "~#{Digest::SHA256.hexdigest(id)}"
42
+ File.join(model.name.underscore, name)
43
+ end
44
+
45
+ # The most bytes the server takes for one record of this model.
46
+ def max_size(model)
47
+ model.instant_record_file_max_size || InstantRecord.config.max_file_size || MAX_SIZE
48
+ end
49
+
50
+ # Maximum bytes accepted per upload piece (and advertised to clients).
51
+ # A model may choose a smaller chunk size, never one larger than the
52
+ # server's configured or store-enforced ceiling.
53
+ def chunk_size(model = nil)
54
+ model_size = model.respond_to?(:instant_record_file_chunk_size) ? model.instant_record_file_chunk_size : nil
55
+ server_limit = store.respond_to?(:chunk_size) ? store.chunk_size : (InstantRecord.config.file_chunk_size || DEFAULT_CHUNK_SIZE)
56
+ unless server_limit.is_a?(Integer) && server_limit.positive?
57
+ raise ArgumentError, "chunk_size must be a positive integer, got #{server_limit.inspect}"
58
+ end
59
+ return server_limit if model_size.nil?
60
+ unless model_size.is_a?(Integer) && model_size.positive?
61
+ raise ArgumentError, "chunk_size must be a positive integer, got #{model_size.inspect}"
62
+ end
63
+
64
+ [model_size, server_limit].min
65
+ end
66
+
67
+ # What the record says its file is, where the model has the columns.
68
+ def declared_size(record)
69
+ record[:byte_size] if record.has_attribute?(:byte_size)
70
+ end
71
+
72
+ def content_type(record)
73
+ (record[:content_type].presence if record.has_attribute?(:content_type)) || "application/octet-stream"
74
+ end
75
+
76
+ # A logged destroy takes the record's file with it. Every destroy on the
77
+ # server is logged, whoever made it, so this is the one place that has
78
+ # to know.
79
+ def forget(change)
80
+ return unless change.operation == "destroy"
81
+
82
+ found = InstantRecord.synced_model(change.record_type) || change.record_type.to_s.safe_constantize
83
+ store.delete(key(found, change.record_id)) if found && carried_by?(found)
84
+ end
85
+
86
+ # Called once per load of the Change model (the engine's to_prepare).
87
+ def forget_on_destroy(log = InstantRecord::Change)
88
+ log.after_commit(on: :create) { InstantRecord::Files.forget(self) }
89
+ end
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,387 @@
1
+ require "time"
2
+ require "securerandom"
3
+
4
+ module InstantRecord
5
+ # Server-anchored, string-encoded Hybrid Logical Clock (HLC).
6
+ #
7
+ # Format (fixed-width, lexicographically sortable):
8
+ # YYYY-MM-DDTHH:MM:SS.UUUUUUZ-CCCC-NNNNNNNN
9
+ # - pt: 27-char UTC ISO-8601 timestamp with 6 microsecond digits
10
+ # - lc: 4-char uppercase hex logical counter (0000..FFFF, fits in 16 bits)
11
+ # - node: 8-char lowercase hex node identifier
12
+ #
13
+ # Why string-encoded instead of 64-bit integer packing:
14
+ # Spinel compiles the browser runtime to wasm32 with 32-bit signed integers
15
+ # and `-DSP_INT_OVERFLOW_MODE_RAISE`. Any 64-bit epoch millisecond/microsecond
16
+ # packing raises `RangeError: integer overflow`. Comparing canonical HLC
17
+ # strings uses pure lexicographical ordering and keeps all integers <= 65_535.
18
+ module HLC
19
+ SERVER_NODE = "00000000".freeze
20
+ LEGACY_NODE = "00000001".freeze
21
+ MAX_COUNTER = 65_535
22
+ COUNTER_WIDTH = 4
23
+ DEFAULT_MAX_DRIFT = 5
24
+ MAX_USEC = 999_999
25
+
26
+ FORMAT = /\A(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z)-([0-9A-F]{4})-([0-9a-zA-Z]{1,16})\z/
27
+
28
+ KEY_NODE = "hlc_node".freeze
29
+ KEY_LAST = "hlc_last".freeze
30
+ KEY_OFFSET = "hlc_offset".freeze
31
+ ROW_PREFIX = "hlc_row:".freeze
32
+ RECORD_PREFIX = "hlc_rec:".freeze
33
+ CHANGE_PREFIX = "hlc_chg:".freeze
34
+ MUTATION_PREFIX = "hlc_mut:".freeze
35
+
36
+ class << self
37
+ # Test seam for injecting a skewed or frozen wall clock without
38
+ # monkeypatching Time.now.
39
+ attr_writer :clock
40
+
41
+ def wall_now
42
+ (@clock ? @clock.call : Time.now).utc
43
+ end
44
+
45
+ def with_clock(callable)
46
+ previous = @clock
47
+ @clock = callable
48
+ yield
49
+ ensure
50
+ @clock = previous
51
+ end
52
+
53
+ def iso_now(time = nil)
54
+ (time || wall_now).utc.iso8601(TIME_PRECISION)
55
+ end
56
+
57
+ def valid?(value)
58
+ value.is_a?(String) && FORMAT.match?(value)
59
+ end
60
+
61
+ def parse(value)
62
+ return nil unless value.is_a?(String)
63
+
64
+ match = FORMAT.match(value)
65
+ return nil unless match
66
+
67
+ { pt: match[1], counter: match[2].to_i(16), node: match[3] }
68
+ end
69
+
70
+ def encode(pt_str, counter, node)
71
+ "#{pt_str}-#{format('%04X', counter)}-#{node}"
72
+ end
73
+
74
+ # -1, 0 or 1, and never nil: the browser's compiler will not compare what `<=>` may
75
+ # give with a number, and two strings always have an order.
76
+ def compare(a, b)
77
+ left = a.to_s
78
+ right = b.to_s
79
+ return 0 if left == right
80
+
81
+ left < right ? -1 : 1
82
+ end
83
+
84
+ def physical_time(hlc)
85
+ parsed = parse(hlc)
86
+ return nil unless parsed
87
+
88
+ Time.parse(parsed[:pt]).utc
89
+ rescue ArgumentError
90
+ nil
91
+ end
92
+
93
+ def node(hlc)
94
+ parse(hlc)&.fetch(:node)
95
+ end
96
+
97
+ def from_time(time, counter: 0, node: LEGACY_NODE)
98
+ return nil if time.nil?
99
+
100
+ parsed = time.is_a?(Time) ? time.utc : Time.parse(time.to_s).utc
101
+ encode(parsed.iso8601(TIME_PRECISION), counter, node)
102
+ rescue ArgumentError
103
+ nil
104
+ end
105
+
106
+ def max_drift
107
+ configured = InstantRecord.config.max_clock_drift
108
+ configured.nil? ? DEFAULT_MAX_DRIFT : configured.to_f
109
+ end
110
+
111
+ # Persistent node identifier for this runtime. Uses SecureRandom.uuid
112
+ # (not SecureRandom.hex) for Spinel compatibility.
113
+ def node_id
114
+ return SERVER_NODE unless InstantRecord.browser?
115
+
116
+ existing = metadata_get(KEY_NODE)
117
+ return existing if existing && !existing.empty?
118
+
119
+ generated = SecureRandom.uuid.delete("-")[0, 8].downcase
120
+ metadata_set(KEY_NODE, generated)
121
+ generated
122
+ end
123
+
124
+ # Server-anchored clock offset in Float seconds (server_utc - local_utc).
125
+ # Only applied on the browser; the server is its own UTC authority.
126
+ def offset
127
+ return 0.0 unless InstantRecord.browser?
128
+
129
+ raw = metadata_get(KEY_OFFSET)
130
+ raw ? raw.to_f : 0.0
131
+ end
132
+
133
+ def anchored_now(now = nil)
134
+ base = (now || wall_now).utc
135
+ InstantRecord.browser? ? (base + offset).utc : base
136
+ end
137
+
138
+ # Anchor this client's physical clock to authoritative server UTC time
139
+ # piggybacked on sync responses. If an earlier unanchored local HLC
140
+ # drifted far into the future relative to the server, re-anchor it so
141
+ # subsequent writes use real server UTC time.
142
+ def observe_server_time(server_time, now: nil)
143
+ return nil if server_time.nil? || server_time.to_s.empty?
144
+
145
+ server_utc = server_time.is_a?(Time) ? server_time.utc : Time.parse(server_time.to_s).utc
146
+ local_utc = (now || wall_now).utc
147
+ delta = server_utc - local_utc
148
+ metadata_set(KEY_OFFSET, format("%.6f", delta)) if InstantRecord.browser?
149
+
150
+ if InstantRecord.browser? && (last_hlc = last)
151
+ last_pt = physical_time(last_hlc)
152
+ if last_pt && (last_pt - server_utc) > max_drift
153
+ parsed = parse(last_hlc)
154
+ metadata_set(KEY_LAST, encode(server_utc.iso8601(TIME_PRECISION), 0, parsed[:node]))
155
+ end
156
+ end
157
+
158
+ delta
159
+ rescue ArgumentError
160
+ nil
161
+ end
162
+
163
+ def last
164
+ metadata_get(KEY_LAST)
165
+ end
166
+
167
+ # Clamp extreme forward physical-time skew relative to `now`.
168
+ # Legitimate offline writes in the past are never clamped backward; only
169
+ # impossible future timestamps past `now + max_drift` are clamped back
170
+ # to `now` so a skewed client cannot dominate future writes.
171
+ def clamp(hlc, now: nil, max_drift: nil)
172
+ parsed = parse(hlc)
173
+ return nil unless parsed
174
+
175
+ reference = (now || wall_now).utc
176
+ limit = max_drift.nil? ? self.max_drift : max_drift.to_f
177
+ pt = Time.parse(parsed[:pt]).utc
178
+
179
+ if (pt - reference) > limit
180
+ encode(reference.iso8601(TIME_PRECISION), parsed[:counter], parsed[:node])
181
+ else
182
+ hlc
183
+ end
184
+ rescue ArgumentError
185
+ nil
186
+ end
187
+
188
+ # Generate the next strictly monotonic HLC for a local event.
189
+ def tick(now: nil, node: nil)
190
+ current_node = node || node_id
191
+ pt_now = anchored_now(now).iso8601(TIME_PRECISION)
192
+ prev = parse(last)
193
+
194
+ next_pt, next_counter =
195
+ if prev.nil? || pt_now > prev[:pt]
196
+ [pt_now, 0]
197
+ else
198
+ increment_counter(prev[:pt], prev[:counter])
199
+ end
200
+
201
+ stamped = encode(next_pt, next_counter, current_node)
202
+ metadata_set(KEY_LAST, stamped)
203
+ stamped
204
+ end
205
+
206
+ # Incorporate a remote HLC into this node's monotonic clock, clamping
207
+ # extreme forward drift so a skewed remote stamp cannot drag our clock
208
+ # arbitrarily far into the future.
209
+ def receive(remote_hlc, now: nil, node: nil)
210
+ return last unless valid?(remote_hlc)
211
+
212
+ reference = anchored_now(now)
213
+ clamped = clamp(remote_hlc, now: reference)
214
+ remote = parse(clamped)
215
+ return last unless remote
216
+
217
+ current_node = node || node_id
218
+ pt_now = reference.iso8601(TIME_PRECISION)
219
+ prev = parse(last)
220
+
221
+ next_pt, next_counter =
222
+ if prev.nil?
223
+ pt_now > remote[:pt] ? [pt_now, 0] : increment_counter(remote[:pt], remote[:counter])
224
+ elsif pt_now > prev[:pt] && pt_now > remote[:pt]
225
+ [pt_now, 0]
226
+ elsif prev[:pt] == remote[:pt]
227
+ max_c = prev[:counter] >= remote[:counter] ? prev[:counter] : remote[:counter]
228
+ increment_counter(prev[:pt], max_c)
229
+ elsif prev[:pt] > remote[:pt]
230
+ increment_counter(prev[:pt], prev[:counter])
231
+ else
232
+ increment_counter(remote[:pt], remote[:counter])
233
+ end
234
+
235
+ stamped = encode(next_pt, next_counter, current_node)
236
+ metadata_set(KEY_LAST, stamped)
237
+ stamped
238
+ end
239
+
240
+ # Produce a new HLC strictly greater than all supplied HLCs and the
241
+ # node's own clock. Used by the server when a 3-way merge creates a new
242
+ # state that must supersede both the prior server row and the client's
243
+ # optimistic local copy.
244
+ def advance_past(*hlcs, now: nil, node: SERVER_NODE)
245
+ candidates = hlcs.compact.select { |h| valid?(h) }
246
+ candidates << last if valid?(last)
247
+
248
+ reference = anchored_now(now)
249
+ pt_now = reference.iso8601(TIME_PRECISION)
250
+ highest = candidates.max
251
+
252
+ next_pt, next_counter =
253
+ if highest.nil?
254
+ [pt_now, 0]
255
+ else
256
+ parsed = parse(highest)
257
+ if pt_now > parsed[:pt]
258
+ [pt_now, 0]
259
+ else
260
+ increment_counter(parsed[:pt], parsed[:counter])
261
+ end
262
+ end
263
+
264
+ stamped = encode(next_pt, next_counter, node)
265
+ metadata_set(KEY_LAST, stamped)
266
+ stamped
267
+ end
268
+
269
+ # --- SyncMetadata storage helpers -------------------------------------
270
+
271
+ def row_hlc(record_type, record_id)
272
+ metadata_get("#{ROW_PREFIX}#{record_type}:#{record_id}")
273
+ end
274
+
275
+ def set_row_hlc(record_type, record_id, hlc, force: false)
276
+ return unless valid?(hlc)
277
+
278
+ key = "#{ROW_PREFIX}#{record_type}:#{record_id}"
279
+ if !force
280
+ existing = metadata_get(key)
281
+ return existing if valid?(existing) && existing >= hlc
282
+ end
283
+ metadata_set(key, hlc)
284
+ hlc
285
+ end
286
+
287
+ def delete_row_hlc(record_type, record_id)
288
+ metadata_delete("#{ROW_PREFIX}#{record_type}:#{record_id}")
289
+ end
290
+
291
+ def record_hlc(record_type, record_id)
292
+ metadata_get("#{RECORD_PREFIX}#{record_type}:#{record_id}")
293
+ end
294
+
295
+ def set_record_hlc(record_type, record_id, hlc)
296
+ return unless valid?(hlc)
297
+
298
+ metadata_set("#{RECORD_PREFIX}#{record_type}:#{record_id}", hlc)
299
+ hlc
300
+ end
301
+
302
+ def delete_record_hlc(record_type, record_id)
303
+ metadata_delete("#{RECORD_PREFIX}#{record_type}:#{record_id}")
304
+ end
305
+
306
+ def change_hlc(change_id)
307
+ return nil if change_id.nil?
308
+
309
+ metadata_get("#{CHANGE_PREFIX}#{change_id}")
310
+ end
311
+
312
+ def set_change_hlc(change_id, hlc)
313
+ return unless change_id && valid?(hlc)
314
+
315
+ metadata_set("#{CHANGE_PREFIX}#{change_id}", hlc)
316
+ hlc
317
+ end
318
+
319
+ def change_hlcs(change_ids)
320
+ ids = Array(change_ids).compact
321
+ return {} if ids.empty? || !defined?(InstantRecord::SyncMetadata)
322
+
323
+ keys = ids.map { |id| "#{CHANGE_PREFIX}#{id}" }
324
+ result = {}
325
+ InstantRecord::SyncMetadata.where(key: keys).each do |entry|
326
+ id_str = entry.key.delete_prefix(CHANGE_PREFIX)
327
+ result[id_str.to_i] = entry.value if valid?(entry.value)
328
+ end
329
+ result
330
+ end
331
+
332
+ def mutation_hlc(mutation_id)
333
+ return nil if mutation_id.nil?
334
+
335
+ metadata_get("#{MUTATION_PREFIX}#{mutation_id}")
336
+ end
337
+
338
+ def set_mutation_hlc(mutation_id, hlc)
339
+ return unless mutation_id && valid?(hlc)
340
+
341
+ metadata_set("#{MUTATION_PREFIX}#{mutation_id}", hlc)
342
+ hlc
343
+ end
344
+
345
+ def delete_mutation_hlc(mutation_id)
346
+ return if mutation_id.nil?
347
+
348
+ metadata_delete("#{MUTATION_PREFIX}#{mutation_id}")
349
+ end
350
+
351
+ private
352
+
353
+ def increment_counter(pt_str, counter)
354
+ if counter >= MAX_COUNTER
355
+ t = Time.parse(pt_str).utc
356
+ bumped =
357
+ if t.usec >= MAX_USEC
358
+ (Time.utc(t.year, t.month, t.day, t.hour, t.min, t.sec) + 1).utc
359
+ else
360
+ Time.utc(t.year, t.month, t.day, t.hour, t.min, t.sec, t.usec + 1)
361
+ end
362
+ [bumped.iso8601(TIME_PRECISION), 0]
363
+ else
364
+ [pt_str, counter + 1]
365
+ end
366
+ end
367
+
368
+ def metadata_get(key)
369
+ return nil unless defined?(InstantRecord::SyncMetadata)
370
+
371
+ InstantRecord::SyncMetadata.get(key)
372
+ end
373
+
374
+ def metadata_set(key, value)
375
+ return unless defined?(InstantRecord::SyncMetadata)
376
+
377
+ InstantRecord::SyncMetadata.set(key, value)
378
+ end
379
+
380
+ def metadata_delete(key)
381
+ return unless defined?(InstantRecord::SyncMetadata)
382
+
383
+ InstantRecord::SyncMetadata.delete(key)
384
+ end
385
+ end
386
+ end
387
+ end
@@ -0,0 +1,66 @@
1
+ module InstantRecord
2
+ # Runtime-specific host adapter. On the Rails server this provides CRuby
3
+ # reflection, Rails engine boot, and default channel helpers; AOT builds swap
4
+ # this file with a target-specific adapter from Compiler::HostAdapters instead
5
+ # of patching gem Ruby source with literal string edits.
6
+ module Host
7
+ module_function
8
+
9
+ def browser? = false
10
+
11
+ def load_engine
12
+ require "instant_record/engine" if defined?(Rails::Engine)
13
+ end
14
+
15
+ def load_inertia_renderer
16
+ require "instant_record/inertia/renderer"
17
+ end
18
+
19
+ def load_branch_store
20
+ require "instant_record/branch/sqlite_store"
21
+ end
22
+
23
+ def install_active_job_guard
24
+ ActiveSupport.on_load(:active_job) do
25
+ require "instant_record/sync_actions"
26
+ InstantRecord::SyncActions.install_active_job_guard!
27
+ end
28
+ end
29
+
30
+ def with_savepoint(&block)
31
+ ActiveRecord::Base.transaction(requires_new: true, &block)
32
+ end
33
+
34
+ def default_mount_path
35
+ configured =
36
+ if defined?(Rails) && Rails.application && Rails.application.config.respond_to?(:instant_record)
37
+ Rails.application.config.instant_record.mount_path
38
+ end
39
+ configured.is_a?(String) ? configured : InstantRecord::DEFAULT_MOUNT_PATH
40
+ end
41
+
42
+ def resolve_syncable_model(record_type)
43
+ klass = record_type.to_s.safe_constantize
44
+ klass if klass.respond_to?(:instant_record_syncable?) && klass.instant_record_syncable?
45
+ end
46
+
47
+ def discover_syncable_models
48
+ ActiveRecord::Base.descendants.select do |model|
49
+ !model.abstract_class? && model.name &&
50
+ model.respond_to?(:instant_record_syncable?) && model.instant_record_syncable?
51
+ end
52
+ end
53
+
54
+ def blank_id?(id)
55
+ id.nil? || id == ""
56
+ end
57
+
58
+ def read_channel(name)
59
+ File.read("/host/#{name}")
60
+ end
61
+
62
+ def write_channel(name, body)
63
+ File.write("/host/#{name}", body)
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,52 @@
1
+ module InstantRecord
2
+ module Inertia
3
+ CHANNEL = { name: CHANNEL_NAME, type: CHANNEL_TYPE }.freeze
4
+
5
+ # The `liveProps` of a page object: one event per model, named for it.
6
+ # Each entry may be a Model / Array<Model> or a Hash with `models:` (or
7
+ # `model:`) and optional `partitions:` / `throttle:`.
8
+ def self.live_props(models_by_prop)
9
+ models_by_prop.to_h do |prop, spec|
10
+ if spec.is_a?(Hash)
11
+ models = Array(spec[:models] || spec["models"] || spec[:model] || spec["model"])
12
+ events = models.map { |model| model.respond_to?(:name) ? model.name : model.to_s }
13
+ partitions = spec[:partitions] || spec["partitions"]
14
+ channel = partitions ? CHANNEL.merge(partitions: normalize_partitions(partitions)) : CHANNEL
15
+ throttle = spec[:throttle] || spec["throttle"] || THROTTLE_MS
16
+ [prop.to_sym, { listeners: [{ channel: channel, events: events }], throttle: throttle }]
17
+ else
18
+ events = Array(spec).map { |model| model.respond_to?(:name) ? model.name : model.to_s }
19
+ [prop.to_sym, { listeners: [{ channel: CHANNEL, events: events }], throttle: THROTTLE_MS }]
20
+ end
21
+ end
22
+ end
23
+
24
+ def self.normalize_partitions(partitions)
25
+ partitions.to_h do |col, val|
26
+ values = Array(val).compact.map(&:to_s).uniq
27
+ [col.to_s, values]
28
+ end
29
+ end
30
+
31
+ # inertia_rails has no word for live props yet, so this adds the key to
32
+ # the page object its renderer builds, and records read tables/models.
33
+ module Renderer
34
+ def initialize(component, controller, request, response, render_method, **options)
35
+ @instant_record_live = options[:live]
36
+ super
37
+ end
38
+
39
+ private
40
+
41
+ def build_page
42
+ page, reads = InstantRecord::ReadTracker.capture { super }
43
+ if @response && reads && (!reads["tables"].empty? || !reads["models"].empty?)
44
+ @response.set_header("X-Instant-Record-Reads", InstantRecord::ReadTracker.serialize(reads))
45
+ end
46
+ return page if @instant_record_live.blank?
47
+
48
+ page.merge(liveProps: InstantRecord::Inertia.live_props(@instant_record_live))
49
+ end
50
+ end
51
+ end
52
+ end