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,102 @@
1
+ module InstantRecord
2
+ # Declarative sync shape on a Syncable model (`sync_shape`): defines the root
3
+ # relation for windowed bootstrap and keyset history paging, optional related
4
+ # rows that ride along with each page of roots, optional server-side search
5
+ # widening, optional single-root lookup, and optional background history-fill.
6
+ class SyncShape
7
+ attr_reader :model, :limit, :min_limit, :max_limit, :fill_page_size, :fill_budget_bytes
8
+
9
+ def initialize(model, limit: 50, min_limit: 1, max_limit: 200, roots: nil, include: nil,
10
+ search: nil, lookup: nil, background_fill: false, fill_page_size: nil, fill_budget_bytes: nil)
11
+ unless limit.is_a?(Integer) && limit.positive?
12
+ raise ArgumentError, "sync_shape limit must be a positive integer (got #{limit.inspect})"
13
+ end
14
+ unless min_limit.is_a?(Integer) && min_limit.positive?
15
+ raise ArgumentError, "sync_shape min_limit must be a positive integer (got #{min_limit.inspect})"
16
+ end
17
+ unless max_limit.is_a?(Integer) && max_limit >= limit && max_limit >= min_limit
18
+ raise ArgumentError, "sync_shape max_limit must be an integer >= limit and min_limit (got #{max_limit.inspect})"
19
+ end
20
+
21
+ @model = model
22
+ @limit = limit
23
+ @min_limit = min_limit
24
+ @max_limit = max_limit
25
+ @roots = roots
26
+ @include = include
27
+ @search = search
28
+ @lookup = lookup
29
+ @background_fill = !!background_fill
30
+ @fill_page_size = (fill_page_size || max_limit).to_i
31
+ @fill_budget_bytes = fill_budget_bytes
32
+ end
33
+
34
+ def searchable? = !@search.nil?
35
+ def background_fill? = @background_fill
36
+
37
+ # Base relation for root rows, narrowed by the caller's visibility/partition scope.
38
+ def root_scope(base)
39
+ @roots ? base.instance_exec(&@roots) : base
40
+ end
41
+
42
+ # First-sync bootstrap page: newest `limit` root rows plus any related rows.
43
+ def bootstrap_records(base)
44
+ pk = @model.primary_key
45
+ roots = root_scope(base).order(created_at: :desc, pk => :desc).limit(@limit).to_a
46
+ expand(base, roots)
47
+ end
48
+
49
+ # Keyset page below (before_at, before_id) — or from newest when omitted —
50
+ # optionally narrowed by `search`. Returns { records:, has_more:, next_before: }.
51
+ def page(base, before_at: nil, before_id: nil, limit: nil, search: nil)
52
+ pk = @model.primary_key
53
+ size = (limit ? limit.to_i : @limit).clamp(@min_limit, @max_limit)
54
+ relation = root_scope(base)
55
+ if search.present?
56
+ raise ArgumentError, "#{@model.name} sync_shape does not support search" unless @search
57
+
58
+ relation = relation.instance_exec(search, &@search)
59
+ end
60
+ if before_at && before_id.present?
61
+ relation = relation.where("created_at < :at OR (created_at = :at AND #{pk} < :id)", at: before_at, id: before_id)
62
+ end
63
+
64
+ fetched = relation.order(created_at: :desc, pk => :desc).limit(size + 1).to_a
65
+ has_more = fetched.size > size
66
+ roots = fetched.first(size)
67
+ last = roots.last
68
+ next_before = last && {
69
+ created_at: last.created_at.utc.iso8601(InstantRecord::TIME_PRECISION),
70
+ id: last.id
71
+ }
72
+ { records: expand(base, roots), has_more: has_more, next_before: next_before }
73
+ end
74
+
75
+ # Single-root lookup (e.g. deep link to a record outside the bootstrap window),
76
+ # expanded with its related rows.
77
+ def lookup(base, id)
78
+ relation = @lookup ? base.instance_exec(id, &@lookup) : base.where(@model.primary_key => id)
79
+ expand(base, relation.to_a)
80
+ end
81
+
82
+ # Descriptor sent in bootstrap JSON so the browser/native worker knows how
83
+ # to background-fill this model without hardcoding model names or columns.
84
+ def fill_descriptor(partition: nil)
85
+ return nil unless background_fill?
86
+
87
+ descriptor = { type: @model.name, page_size: @fill_page_size }
88
+ descriptor[:partition] = partition if partition
89
+ descriptor[:budget_bytes] = @fill_budget_bytes if @fill_budget_bytes
90
+ descriptor
91
+ end
92
+
93
+ private
94
+
95
+ def expand(base, roots)
96
+ return roots if roots.empty? || @include.nil?
97
+
98
+ related = base.instance_exec(roots, &@include).to_a
99
+ roots + related
100
+ end
101
+ end
102
+ end
@@ -16,56 +16,133 @@ module InstantRecord
16
16
  @partition_by = partition_by&.to_s
17
17
  end
18
18
 
19
- # Rows inside the window (the newest `limit` per partition).
20
- def in_window
21
- @model.where("#{quoted_primary_key} IN (#{ranked_ids_sql("<=")})")
19
+ # Rows inside the window (the newest `limit` per partition), ranked
20
+ # strictly within `scope`.
21
+ def in_window(scope = @model.all)
22
+ window_relation("<=", scope)
22
23
  end
23
24
 
24
- # Rows outside the window — eviction's target. An extra `scope` narrows
25
- # further (e.g. excluding sync_state "pending").
25
+ # Rows outside the window — eviction's target, ranked strictly within
26
+ # `scope` (e.g. excluding sync_state "pending").
26
27
  def beyond_window(scope = @model.all)
27
- scope.where("#{quoted_primary_key} IN (#{ranked_ids_sql(">")})")
28
+ window_relation(">", scope)
28
29
  end
29
30
 
30
31
  # Keyset page scope: rows strictly below the (created_at, id) tuple within
31
32
  # one partition, newest first. Shared by the records endpoint (server) and
32
33
  # the client's local-page checks — one predicate, no OFFSET.
33
- def keyset_below(at:, id:, partition: nil)
34
+ def keyset_below(at:, id:, partition: nil, scope: @model.all)
35
+ validate_columns!
36
+ scope ||= @model.all
37
+ return @model.none if null_relation?(scope)
38
+
34
39
  pk = @model.primary_key
35
- scope = @partition_by ? @model.where(@partition_by => partition) : @model.all
36
- scope
37
- .where("created_at < :at OR (created_at = :at AND #{pk} < :id)", at: at, id: id)
38
- .order(created_at: :desc, pk => :desc)
40
+ created_at = "#{quoted_table_name}.#{@model.connection.quote_column_name("created_at")}"
41
+ rows = keyset_base(scope)
42
+ rows = rows.where(@partition_by => partition) if @partition_by
43
+ rows = rows.where("(#{created_at} < :at OR (#{created_at} = :at AND #{qualified_primary_key} < :id))", at: at, id: id)
44
+ rows.respond_to?(:reorder) ? rows.reorder(created_at: :desc, pk => :desc) : rows.order(created_at: :desc, pk => :desc)
39
45
  end
40
46
 
41
47
  private
42
48
 
43
- # ROW_NUMBER() runs identically on Postgres, PGlite, and SQLite >= 3.25 —
44
- # the three engines the same model file can find itself on.
45
- def ranked_ids_sql(comparison)
49
+ def window_relation(comparison, scope)
46
50
  validate_columns!
51
+ scope ||= @model.all
52
+ return @model.none if null_relation?(scope)
53
+
54
+ unscoped_model.where("#{qualified_primary_key} IN (#{ranked_ids_sql(comparison, scope)})")
55
+ end
56
+
57
+ # ROW_NUMBER() runs identically on Postgres and SQLite >= 3.25 —
58
+ # the three engines the same model file can find itself on.
59
+ def ranked_ids_sql(comparison, scope)
47
60
  connection = @model.connection
48
- table = connection.quote_table_name(@model.table_name)
61
+ table = quoted_table_name
49
62
  created_at = connection.quote_column_name("created_at")
50
63
  over = [partition_clause(connection), "ORDER BY #{created_at} DESC, #{quoted_primary_key} DESC"].compact.join(" ")
64
+ filter = scope_filter_sql(scope, table)
51
65
 
52
66
  <<~SQL.squish
53
67
  SELECT #{quoted_primary_key} FROM (
54
68
  SELECT #{quoted_primary_key}, ROW_NUMBER() OVER (#{over}) AS instant_record_rank
55
69
  FROM #{table}
70
+ #{filter}
56
71
  ) instant_record_ranked
57
72
  WHERE instant_record_rank #{comparison} #{@limit}
58
73
  SQL
59
74
  end
60
75
 
76
+ def scope_filter_sql(scope, table)
77
+ ids_sql = scope_ids_sql(scope)
78
+ return "WHERE 1 = 0" if ids_sql.empty?
79
+ return "" if ids_sql == "SELECT #{qualified_primary_key} FROM #{table}"
80
+
81
+ "WHERE #{qualified_primary_key} IN (#{ids_sql})"
82
+ end
83
+
84
+ def scope_ids_sql(scope)
85
+ if scope.respond_to?(:reselect)
86
+ if scope.limit_value || scope.offset_value
87
+ if scope.distinct_value || scope.order_values.any?
88
+ return "SELECT #{quoted_primary_key} FROM (#{scope.to_sql}) instant_record_scope"
89
+ end
90
+
91
+ scope.reselect(qualified_primary_key).to_sql
92
+ else
93
+ scope.reorder(nil).reselect(qualified_primary_key).to_sql
94
+ end
95
+ else
96
+ sql = scope.to_sql
97
+ sql.empty? ? "" : "SELECT #{quoted_primary_key} FROM (#{sql}) instant_record_scope"
98
+ end
99
+ end
100
+
101
+ def keyset_base(scope)
102
+ if scope.respond_to?(:joins_values) && complex_scope?(scope)
103
+ ids_sql = scope_ids_sql(scope)
104
+ return @model.none if ids_sql.empty?
105
+
106
+ unscoped_model.where("#{qualified_primary_key} IN (#{ids_sql})")
107
+ else
108
+ scope
109
+ end
110
+ end
111
+
112
+ def complex_scope?(scope)
113
+ scope.joins_values.any? ||
114
+ scope.left_outer_joins_values.any? ||
115
+ scope.select_values.any? ||
116
+ scope.group_values.any? ||
117
+ scope.distinct_value ||
118
+ scope.limit_value ||
119
+ scope.offset_value
120
+ end
121
+
122
+ def null_relation?(scope)
123
+ scope.respond_to?(:null_relation?) && scope.null_relation?
124
+ end
125
+
126
+ def unscoped_model
127
+ @model.respond_to?(:unscoped) ? @model.unscoped : @model
128
+ end
129
+
61
130
  def partition_clause(connection)
62
131
  @partition_by && "PARTITION BY #{connection.quote_column_name(@partition_by)}"
63
132
  end
64
133
 
134
+ def quoted_table_name
135
+ @model.connection.quote_table_name(@model.table_name)
136
+ end
137
+
65
138
  def quoted_primary_key
66
139
  @model.connection.quote_column_name(@model.primary_key)
67
140
  end
68
141
 
142
+ def qualified_primary_key
143
+ "#{quoted_table_name}.#{quoted_primary_key}"
144
+ end
145
+
69
146
  # Deferred to first use: at declaration time the table may not exist yet
70
147
  # (class load precedes migrations).
71
148
  def validate_columns!
@@ -2,7 +2,7 @@ require "securerandom"
2
2
 
3
3
  module InstantRecord
4
4
  # Makes a model local-first syncable. The same file loads in both runtimes:
5
- # in the browser (ruby.wasm) every write also records an outbox mutation in
5
+ # in the compiled browser app every write also records an outbox mutation in
6
6
  # the same local transaction; on the server the concern only provides the
7
7
  # shared column conventions (uuid ids, server_version, sync_state).
8
8
  module Syncable
@@ -10,26 +10,143 @@ module InstantRecord
10
10
 
11
11
  included do
12
12
  extend InstantRecord::RuntimeScoped
13
+ extend InstantRecord::SyncActions::ClassMethods
13
14
 
14
15
  before_create :assign_instant_record_uuid
15
16
 
16
17
  # Guarded at call time, not include time, so the same class works in
17
18
  # both runtimes and tests can stub the runtime without re-including.
19
+ # Capture the server-confirmed row snapshot BEFORE the first unacked
20
+ # local write mutates the row, inside the same transaction as the write
21
+ # and outbox insert so rollbacks undo all three atomically.
22
+ before_create { capture_confirmed_snapshot(true) if instant_record_local_write? && !InstantRecord::SyncActions.recording_client_mutator? }
23
+ before_update { capture_confirmed_snapshot(false) if instant_record_local_write? && !InstantRecord::SyncActions.recording_client_mutator? }
24
+ before_destroy { capture_confirmed_snapshot(false) if instant_record_local_write? && !InstantRecord::SyncActions.recording_client_mutator? }
25
+
18
26
  # after_create/update/destroy run INSIDE the wrapping transaction
19
27
  # (unlike after_commit), which is what gives us write+outbox atomicity.
20
- before_save { self.sync_state = "pending" if instant_record_local_write? }
21
- after_create { record_outbox_mutation("create") if instant_record_local_write? }
22
- after_update { record_outbox_mutation("update") if instant_record_local_write? }
23
- after_destroy { record_outbox_mutation("destroy") if instant_record_local_write? }
28
+ before_save do
29
+ if instant_record_local_write?
30
+ if persisted? && InstantRecord::SyncActions.recording_client_mutator?
31
+ InstantRecord::SyncActions.client_frame.capture_before(self, "update")
32
+ end
33
+ self.sync_state = "pending"
34
+ end
35
+ end
36
+ before_destroy do
37
+ if instant_record_local_write? && InstantRecord::SyncActions.recording_client_mutator?
38
+ InstantRecord::SyncActions.client_frame.capture_before(self, "destroy")
39
+ end
40
+ end
41
+ after_create do
42
+ if instant_record_local_write?
43
+ if InstantRecord::SyncActions.recording_client_mutator?
44
+ InstantRecord::SyncActions.client_frame.record_create(self)
45
+ else
46
+ record_outbox_mutation("create")
47
+ end
48
+ end
49
+ end
50
+ after_update { record_outbox_mutation("update") if instant_record_local_write? && !InstantRecord::SyncActions.recording_client_mutator? }
51
+ after_destroy { record_outbox_mutation("destroy") if instant_record_local_write? && !InstantRecord::SyncActions.recording_client_mutator? }
52
+ after_validation { @hold_for = nil if errors.any? } if respond_to?(:after_validation)
53
+ after_save { @hold_for = nil }
54
+ after_destroy { @hold_for = nil }
55
+ after_rollback { @hold_for = nil } if respond_to?(:after_rollback)
24
56
 
25
57
  # Server-originated writes (jobs, console, seeds) are change-logged so
26
- # they stream to clients like any other change. Client mutations are
27
- # excluded — MutationApplier versions and logs those itself.
28
- before_create { self.server_version = 1 if instant_record_server_write? }
29
- before_update { self.server_version += 1 if instant_record_server_write? }
30
- after_create { record_server_change("create") if instant_record_server_write? }
31
- after_update { record_server_change("update") if instant_record_server_write? }
32
- after_destroy { record_server_change("destroy") if instant_record_server_write? }
58
+ # they stream to clients like any other change. Client row mutations are
59
+ # excluded — MutationApplier versions and logs those itself. Server-replayed
60
+ # sync_actions enforce SyncScope, bump versions, and log changes through
61
+ # InstantRecord::SyncActions server hooks (no-ops in compiled builds).
62
+ before_create do
63
+ if instant_record_server_mutator_write?
64
+ InstantRecord::SyncActions.server_authorize_create!(self)
65
+ self.server_version = 1
66
+ self.sync_state = "synced"
67
+ elsif instant_record_server_write?
68
+ self.server_version = 1
69
+ end
70
+ end
71
+ before_update do
72
+ if instant_record_server_mutator_write?
73
+ InstantRecord::SyncActions.server_authorize_update_before!(self)
74
+ self.server_version += 1
75
+ self.sync_state = "synced"
76
+ elsif instant_record_server_write?
77
+ self.server_version += 1
78
+ end
79
+ end
80
+ before_destroy do
81
+ if instant_record_server_mutator_write?
82
+ InstantRecord::SyncActions.server_authorize_destroy!(self)
83
+ end
84
+ end
85
+ after_create do
86
+ if instant_record_server_mutator_write?
87
+ InstantRecord::SyncActions.server_finalize_create!(self)
88
+ elsif instant_record_server_write?
89
+ record_server_change("create")
90
+ end
91
+ end
92
+ after_update do
93
+ if instant_record_server_mutator_write?
94
+ InstantRecord::SyncActions.server_finalize_update!(self)
95
+ elsif instant_record_server_write?
96
+ record_server_change("update")
97
+ end
98
+ end
99
+ after_destroy do
100
+ if instant_record_server_mutator_write?
101
+ InstantRecord::SyncActions.server_finalize_destroy!(self)
102
+ elsif instant_record_server_write?
103
+ record_server_change("destroy")
104
+ end
105
+ end
106
+
107
+ server_only do
108
+ after_find do
109
+ InstantRecord::SyncActions.server_note_read(self) if instant_record_server_mutator_write?
110
+ end
111
+ end
112
+ end
113
+
114
+ # Plain methods, not attr_accessor inside `included`: the compiler that carries a model
115
+ # into the browser reads these, and cannot read an accessor declared in that block.
116
+ def hold_for
117
+ @hold_for
118
+ end
119
+
120
+ def hold_for=(seconds)
121
+ @hold_for = seconds
122
+ end
123
+
124
+ def last_outbox_mutation_id
125
+ @last_outbox_mutation_id
126
+ end
127
+
128
+ def destroy(hold_for: nil)
129
+ return super() if hold_for.nil?
130
+
131
+ @hold_for = nil
132
+ previous = InstantRecord::Client.enter_hold(hold_for)
133
+ begin
134
+ super()
135
+ ensure
136
+ InstantRecord::Client.leave_hold(previous)
137
+ end
138
+ end
139
+
140
+ def destroy!(hold_for: nil)
141
+ return super() if hold_for.nil?
142
+
143
+ @hold_for = nil
144
+ previous = InstantRecord::Client.enter_hold(hold_for)
145
+ begin
146
+ super()
147
+ ensure
148
+ InstantRecord::Client.leave_hold(previous)
149
+ end
33
150
  end
34
151
 
35
152
  class_methods do
@@ -48,6 +165,66 @@ module InstantRecord
48
165
  @instant_record_sync_window
49
166
  end
50
167
 
168
+ # Keep a model's rows to the client they belong to. `column` holds the
169
+ # owner's scope, the value InstantRecord.config.scope_from reads off each
170
+ # sync request: a client is sent the rows whose column equals its scope
171
+ # and the rows where it is NULL, which belong to everyone. A create is
172
+ # stamped with the sender's scope, and a row of another scope cannot be
173
+ # changed or removed. Models without a declaration sync to every client.
174
+ def sync_scope(column)
175
+ @instant_record_sync_scope = column.to_s
176
+ end
177
+
178
+ def instant_record_sync_scope
179
+ @instant_record_sync_scope
180
+ end
181
+
182
+ # Partition a model's rows and change feed by a tenant/workspace column
183
+ # (e.g. `sync_partition :mailbox_id`). Partitioned models never sync on
184
+ # unpartitioned requests; a client selects a partition via
185
+ # `X-Instant-Record-Partition` (or `config.partition_from`) and receives
186
+ # only that partition's rows and events.
187
+ def sync_partition(column, name: nil)
188
+ @instant_record_sync_partition = InstantRecord::SyncPartition.new(self, column, name: name)
189
+ end
190
+
191
+ def instant_record_sync_partition
192
+ @instant_record_sync_partition
193
+ end
194
+
195
+ # The rows of this model a client with `scope` may be sent.
196
+ def instant_record_visible_to(scope)
197
+ column = instant_record_sync_scope
198
+ column ? where(column => [nil, scope.presence].uniq) : all
199
+ end
200
+
201
+ # This record carries a file: bytes too large for a column, kept beside
202
+ # the record and never inside it. In the browser they are written first
203
+ # to the origin's private file system (frontend/files.js), so they are
204
+ # there with no connection. They reach the server in the background, and
205
+ # another device fetches them when it asks. The record is what syncs,
206
+ # and its sync rules are the file's: who may be sent the record may read
207
+ # its bytes, who may write it may send them. A file never changes: new
208
+ # bytes are a new record. `max_size` is the most bytes the server takes
209
+ # for one.
210
+ def sync_file(max_size: nil, chunk_size: nil)
211
+ @instant_record_sync_file = true
212
+ @instant_record_file_max_size = max_size
213
+ @instant_record_file_chunk_size = chunk_size
214
+ end
215
+
216
+ def instant_record_sync_file
217
+ @instant_record_sync_file
218
+ end
219
+
220
+ def instant_record_file_max_size
221
+ @instant_record_file_max_size
222
+ end
223
+
224
+ def instant_record_file_chunk_size
225
+ @instant_record_file_chunk_size
226
+ end
227
+
51
228
  # Observe a value from the server that last-write-wins threw away. The
52
229
  # block runs with the losing attribute hash at the moment it is dropped,
53
230
  # which is the only moment it exists in this runtime — the gem assigns
@@ -59,6 +236,61 @@ module InstantRecord
59
236
  def instant_record_discarded_change_handler
60
237
  @instant_record_discarded_change_handler
61
238
  end
239
+
240
+ # Transform queued client outbox payloads before MutationApplier writes
241
+ # them on the server. Handles rolling-deploy schema skew (N-1 -> N
242
+ # upcasts and N+1 -> N downcasts) without rejecting offline writes.
243
+ def upcast_outbox(from: nil, to: nil, operation: nil, &block)
244
+ return nil if InstantRecord.browser?
245
+ raise ArgumentError, "upcast_outbox requires a block" unless block
246
+
247
+ @instant_record_outbox_upcasters ||= []
248
+ @instant_record_outbox_upcasters << { from: from, to: to, operation: operation, transform: block }
249
+ nil
250
+ end
251
+
252
+ def instant_record_outbox_upcasters
253
+ inherited = superclass.respond_to?(:instant_record_outbox_upcasters) ? superclass.instant_record_outbox_upcasters : []
254
+ inherited + (@instant_record_outbox_upcasters || [])
255
+ end
256
+
257
+ # Deterministic replay hook for GGPO dirty-row rebasing. When incoming
258
+ # server truth rewinds a dirty row to its confirmed snapshot, this block
259
+ # receives `(record, mutation)` for each remaining unacked mutation so
260
+ # custom domain mutators (e.g. counters, set merges, state transitions)
261
+ # can replay deterministically on top of server truth. Return `:destroy`
262
+ # to delete the row, truthy to keep the mutated record, or `nil`/`:default`
263
+ # to fall back to standard attribute replay.
264
+ def on_replay_mutation(&block)
265
+ @instant_record_replay_mutation_handler = block
266
+ end
267
+
268
+ def instant_record_replay_mutation_handler
269
+ @instant_record_replay_mutation_handler
270
+ end
271
+
272
+ # Declare how same-column concurrent collisions resolve on this column:
273
+ # :lww - last-write-wins by server-anchored HLC (default)
274
+ # :union - 3-way set/collection union (arrays, JSON arrays, CSV, hashes)
275
+ # :server_wins - server's already-committed value wins on collision
276
+ def sync_merge(column, policy)
277
+ policy = policy.to_sym
278
+ unless %i[lww union server_wins].include?(policy)
279
+ raise ArgumentError, "Unknown sync_merge policy #{policy.inspect}; expected :lww, :union, or :server_wins"
280
+ end
281
+
282
+ @instant_record_merge_policies ||= {}
283
+ @instant_record_merge_policies[column.to_s] = policy
284
+ end
285
+
286
+ def instant_record_merge_policies
287
+ parent = superclass.respond_to?(:instant_record_merge_policies) ? superclass.instant_record_merge_policies : {}
288
+ @instant_record_merge_policies ? parent.merge(@instant_record_merge_policies) : parent
289
+ end
290
+
291
+ def instant_record_merge_policy(column)
292
+ instant_record_merge_policies[column.to_s] || :lww
293
+ end
62
294
  end
63
295
 
64
296
  private
@@ -71,8 +303,19 @@ module InstantRecord
71
303
  !InstantRecord.browser? && !InstantRecord.applying_client_mutation?
72
304
  end
73
305
 
306
+ def instant_record_server_mutator_write?
307
+ !InstantRecord.browser? && InstantRecord::SyncActions.enforcing_server_mutator?
308
+ end
309
+
74
310
  def assign_instant_record_uuid
75
- self.id ||= SecureRandom.uuid
311
+ return unless InstantRecord::Host.blank_id?(id)
312
+
313
+ frame = InstantRecord::SyncActions.active_frame
314
+ self.id = frame ? frame.next_uuid : SecureRandom.uuid
315
+ end
316
+
317
+ def capture_confirmed_snapshot(creating)
318
+ InstantRecord::Client::Rebaser.capture_before_local_write(self.class, id, creating)
76
319
  end
77
320
 
78
321
  def record_outbox_mutation(operation)
@@ -83,24 +326,77 @@ module InstantRecord
83
326
  when "destroy" then {}
84
327
  end
85
328
 
86
- InstantRecord::OutboxMutation.create!(
329
+ hlc = InstantRecord::HLC.tick
330
+ hold = consume_hold_for
331
+ release_at = hold ? Time.now.utc + hold : nil
332
+ rollback_payload = release_at ? capture_rollback_payload(operation) : nil
333
+
334
+ mutation = InstantRecord::OutboxMutation.create!(
87
335
  record_type: self.class.name,
88
336
  record_id: id,
89
337
  operation: operation,
90
338
  changes_payload: changes_payload,
91
- base_version: self[:server_version] || 0
339
+ base_version: self[:server_version] || 0,
340
+ release_at: release_at,
341
+ rollback_payload: rollback_payload
92
342
  )
343
+ InstantRecord::HLC.set_mutation_hlc(mutation.id, hlc)
344
+ if operation == "destroy"
345
+ InstantRecord::HLC.delete_row_hlc(self.class.name, id)
346
+ else
347
+ InstantRecord::HLC.set_row_hlc(self.class.name, id, hlc, force: true)
348
+ end
349
+ @last_outbox_mutation_id = mutation.id
350
+
351
+ if InstantRecord::Client.capturing_changes?
352
+ changed_cols = operation == "update" ? saved_changes.keys : nil
353
+ InstantRecord::Client.note_record_change(self, operation, changed_columns: changed_cols)
354
+ end
355
+ end
356
+
357
+ def consume_hold_for
358
+ raw = @hold_for
359
+ @hold_for = nil
360
+ raw = InstantRecord::Client.current_hold_for if raw.nil?
361
+ return nil if raw.nil?
362
+
363
+ seconds = raw.to_f
364
+ raise ArgumentError, "hold_for must be non-negative" if seconds < 0.0
365
+ return nil if seconds == 0.0
366
+
367
+ seconds
368
+ end
369
+
370
+ def capture_rollback_payload(operation)
371
+ case operation
372
+ when "create"
373
+ nil
374
+ when "update"
375
+ previous = attributes.merge(saved_changes.transform_values(&:first))
376
+ InstantRecord.snapshot_attributes(previous)
377
+ when "destroy"
378
+ InstantRecord.snapshot_attributes(attributes)
379
+ end
93
380
  end
94
381
 
95
382
  # Mirrors MutationApplier's log_change/log_destroy payload shapes.
96
383
  def record_server_change(operation)
97
- InstantRecord::Change.create!(
384
+ hlc = InstantRecord::HLC.tick(node: InstantRecord::HLC::SERVER_NODE)
385
+ change = InstantRecord::Change.create!(
98
386
  record_type: self.class.name,
99
387
  record_id: id,
100
388
  operation: operation,
101
389
  version: operation == "destroy" ? 0 : self[:server_version],
102
- attributes_payload: operation == "destroy" ? {} : InstantRecord.wire_attributes(attributes)
390
+ attributes_payload: operation == "destroy" ? {} : InstantRecord.wire_attributes(attributes),
391
+ scope: InstantRecord.scope_of(self),
392
+ partition: InstantRecord.partition_of(self)
103
393
  )
394
+ InstantRecord::HLC.set_change_hlc(change.id, hlc)
395
+ if operation == "destroy"
396
+ InstantRecord::HLC.delete_record_hlc(self.class.name, id)
397
+ else
398
+ InstantRecord::HLC.set_record_hlc(self.class.name, id, hlc)
399
+ end
104
400
  end
105
401
  end
106
402
  end