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
@@ -1,34 +1,61 @@
1
1
  module InstantRecord
2
- # First-sync hydration: current state (windowed per model when a sync_window
3
- # is declared) plus the change-log cursor, so a fresh client never replays
2
+ # First-sync hydration: current state (shaped via sync_shape or windowed via
3
+ # sync_window) plus the change-log cursor, so a fresh client never replays
4
4
  # the whole change log. The cursor is read BEFORE the rows, inside one
5
5
  # transaction: events committed between cursor and response re-apply
6
6
  # idempotently client-side, whereas the reverse order would skip them.
7
7
  class BootstrapsController < ActionController::API
8
8
  before_action { headers.merge!(InstantRecord::CORS_HEADERS) }
9
+ rescue_from InstantRecord::Unauthorized, with: -> { head :unauthorized }
10
+ rescue_from InstantRecord::Forbidden, with: -> { head :forbidden }
11
+
12
+ def preflight
13
+ head :no_content
14
+ end
9
15
 
10
16
  def show
17
+ SyncScope.authenticate!(request)
18
+ identity = SyncScope.identity(request)
19
+ partition = SyncScope.partition(request, identity)
20
+ models = bootstrap_models(partition)
21
+ SyncScope.authorize_models!(models, partition, identity, request)
22
+
11
23
  payload = ActiveRecord::Base.transaction do
12
24
  cursor = Change.maximum(:id) || 0
13
- { cursor: cursor, records: bootstrap_models.flat_map { |model| serialize_rows(model) } }
25
+ { cursor: cursor, records: models.flat_map { |model| serialize_rows(model, identity, partition) } }
14
26
  end
27
+ fill = models.filter_map do |model|
28
+ shape = model.instant_record_sync_shape
29
+ shape&.fill_descriptor(partition: SyncScope.partition_value(model, partition))
30
+ end
31
+ payload[:fill] = fill if fill.any?
32
+ # The key a client keeps and sends back, so the server notices when the
33
+ # person behind the browser or active partition changes.
34
+ payload[:identity] = SyncScope.key(identity, partition: partition)
35
+ payload[:server_time] = InstantRecord::HLC.iso_now
36
+ headers["cache-control"] = "no-store"
15
37
  render json: payload
16
38
  end
17
39
 
18
40
  private
19
41
 
20
42
  # Eager-load first so development doesn't miss lazily-loaded models;
21
- # syncable_models then resolves like synced_model (allowlist or all
22
- # Syncable includers).
23
- def bootstrap_models
24
- Rails.application.eager_load! unless Rails.application.config.eager_load
25
- InstantRecord.syncable_models
43
+ # SyncScope.models_for selects unpartitioned models by default, or matching
44
+ # partitioned models when a partition is requested.
45
+ def bootstrap_models(partition)
46
+ Rails.application.eager_load! if defined?(Rails) && Rails.application && !Rails.application.config.eager_load
47
+ SyncScope.models_for(partition)
26
48
  end
27
49
 
28
- def serialize_rows(model)
29
- window = model.instant_record_sync_window
30
- scope = window ? window.in_window : model.all
31
- scope.map { |record| InstantRecord.record_payload(record) }
50
+ def serialize_rows(model, identity, partition)
51
+ visible = SyncScope.visible(model, identity, partition: partition)
52
+ if (shape = model.instant_record_sync_shape)
53
+ shape.bootstrap_records(visible).map { |record| InstantRecord.record_payload(record) }
54
+ elsif (window = model.instant_record_sync_window)
55
+ window.in_window(visible).map { |record| InstantRecord.record_payload(record) }
56
+ else
57
+ visible.map { |record| InstantRecord.record_payload(record) }
58
+ end
32
59
  end
33
60
  end
34
61
  end
@@ -18,30 +18,82 @@ module InstantRecord
18
18
  "x-accel-buffering" => "no"
19
19
  }.freeze
20
20
 
21
+ rescue_from InstantRecord::Unauthorized, with: -> { head :unauthorized }
22
+ rescue_from InstantRecord::Forbidden, with: -> { head :forbidden }
23
+
21
24
  class EventStream
22
- def initialize(cursor:, deadline:)
25
+ # `identity` and `partition` are fixed when the stream opens.
26
+ def initialize(cursor:, deadline:, heartbeat: 15.0, identity: nil, partition: nil, partition_spec: nil)
23
27
  @cursor = cursor
28
+ @identity = identity
29
+ @partition = partition
30
+ @partition_spec = partition_spec
24
31
  @deadline = deadline
32
+ @heartbeat = heartbeat
33
+ @last_write = Time.current
25
34
  end
26
35
 
27
36
  def each
28
37
  loop do
29
- Change.poll(@cursor).each do |change|
30
- @cursor = change.id
31
- yield "id: #{change.id}\nevent: change\ndata: #{change.as_event.to_json}\n\n"
38
+ changes = Change.poll(@cursor, scope: SyncScope.token(@identity), partition: @partition)
39
+ SyncScope.events_for(changes, @identity, partition: @partition_spec).each do |id, event|
40
+ @cursor = id
41
+ @last_write = Time.current
42
+ stamped = event.merge(server_time: InstantRecord::HLC.iso_now)
43
+ yield "id: #{id}\nevent: change\ndata: #{stamped.to_json}\n\n"
44
+ end
45
+
46
+ # An SSE comment, written only when the stream has been quiet for a
47
+ # full interval. Keeps idle-connection reapers (reverse proxies) at
48
+ # bay, and doubles as the write that discovers a vanished client.
49
+ if @heartbeat.positive? && Time.current - @last_write >= @heartbeat
50
+ @last_write = Time.current
51
+ yield ": hb\n\n"
32
52
  end
33
53
 
34
54
  break if Time.current >= @deadline
35
55
  sleep 0.5
36
56
  end
57
+ rescue Errno::EPIPE, Errno::ECONNRESET, IOError
58
+ # The client hung up mid-stream — the normal end of an SSE stream.
37
59
  end
38
60
  end
39
61
 
62
+ def preflight
63
+ headers.merge!(InstantRecord::CORS_HEADERS)
64
+ head :no_content
65
+ end
66
+
40
67
  def index
68
+ headers.merge!(InstantRecord::CORS_HEADERS)
41
69
  cursor = (request.headers["Last-Event-ID"] || params[:after] || 0).to_i
42
70
 
43
- headers.merge!(EVENT_STREAM_HEADERS).merge!(InstantRecord::CORS_HEADERS)
44
- self.response_body = EventStream.new(cursor: cursor, deadline: Time.current + window_seconds)
71
+ SyncScope.authenticate!(request)
72
+ identity = SyncScope.identity(request)
73
+ partition_spec = SyncScope.partition(request, identity)
74
+ Rails.application.eager_load! if defined?(Rails) && Rails.application && !Rails.application.config.eager_load
75
+ models = SyncScope.models_for(partition_spec)
76
+ SyncScope.authorize_models!(models, partition_spec, identity, request)
77
+ change_partitions = SyncScope.change_partitions_for(models, partition_spec)
78
+
79
+ headers.merge!(EVENT_STREAM_HEADERS)
80
+
81
+ # A client that synced as someone else is told to start over, and nothing
82
+ # more: no id line, so the cursor it is about to drop does not move.
83
+ if SyncScope.stale?(params[:identity], identity, partition: partition_spec)
84
+ reset_payload = SyncScope.reset_event(identity, partition: partition_spec).merge(server_time: InstantRecord::HLC.iso_now)
85
+ self.response_body = ["event: reset\ndata: #{reset_payload.to_json}\n\n"]
86
+ return
87
+ end
88
+
89
+ self.response_body = EventStream.new(
90
+ cursor: cursor,
91
+ identity: identity,
92
+ partition: change_partitions,
93
+ partition_spec: partition_spec,
94
+ deadline: Time.current + window_seconds,
95
+ heartbeat: Rails.application.config.instant_record.sse_heartbeat_seconds.to_f
96
+ )
45
97
  end
46
98
 
47
99
  private
@@ -0,0 +1,116 @@
1
+ module InstantRecord
2
+ # The bytes of records that declare `sync_file`. A browser writes a file to
3
+ # its own disk first and sends it here in pieces when it has a connection;
4
+ # another device asks for it when it is wanted there.
5
+ #
6
+ # The record decides who may do either. A file may be read by whoever may be
7
+ # sent its record and written by whoever may write it, and a record the
8
+ # asker may not see answers as a missing one does. The record itself arrives
9
+ # through the mutations endpoint, so a file sent before its record has been
10
+ # is 404 too, and the browser tries again.
11
+ class FilesController < ActionController::API
12
+ CORS = InstantRecord::CORS_HEADERS.merge(
13
+ "access-control-allow-methods" => "GET, HEAD, PUT, OPTIONS",
14
+ "access-control-allow-headers" => "content-type, range, authorization, x-instant-record-scope, x-instant-record-partition, x-instant-record-member",
15
+ "access-control-expose-headers" => "accept-ranges, content-length, content-range, x-instant-record-chunk-size"
16
+ ).freeze
17
+
18
+ # What a file is said to be comes from whoever sent it, so a browser is
19
+ # told to keep it as a download and to run nothing in it.
20
+ INERT = {
21
+ "content-disposition" => "attachment",
22
+ "x-content-type-options" => "nosniff",
23
+ "content-security-policy" => "default-src 'none'; sandbox",
24
+ "cache-control" => "private, no-cache"
25
+ }.freeze
26
+
27
+ before_action { headers.merge!(CORS) }
28
+ before_action :find_model, except: :preflight
29
+ rescue_from InstantRecord::Unauthorized, with: -> { head :unauthorized }
30
+ rescue_from InstantRecord::Forbidden, with: -> { head :forbidden }
31
+
32
+ def preflight
33
+ head :no_content
34
+ end
35
+
36
+ # The file, or the part of it a Range header names.
37
+ def show
38
+ SyncScope.authenticate!(request)
39
+ record = SyncScope.visible(@model, identity, partition: partition).find_by(id: params[:id])
40
+ key = record && Files.key(@model, record.id)
41
+ return head :not_found unless key && store.exist?(key)
42
+
43
+ status, file_headers, body = store.serve(key, request)
44
+ headers.merge!(file_headers).merge!(INERT)
45
+ headers["content-type"] = Files.content_type(record)
46
+ headers["x-instant-record-chunk-size"] = chunk_size.to_s
47
+ self.status = status
48
+ self.response_body = body
49
+ end
50
+
51
+ # Where an upload stands, so one that was cut off goes on from there.
52
+ def progress
53
+ return head :not_found unless (key = writable_key)
54
+ return render json: { complete: true, offset: store.size(key), chunk_size: chunk_size } if store.exist?(key)
55
+ return head :bad_request unless upload?
56
+
57
+ render json: { complete: false, offset: store.offset(key, params[:upload]), chunk_size: chunk_size }
58
+ end
59
+
60
+ # One piece of an upload: `size` bytes in all, this piece starting at
61
+ # `offset`. The last piece makes the file. A file that is already here
62
+ # stays as it is, and the answer says so.
63
+ def update
64
+ return head :unsupported_media_type unless request.media_type == "application/octet-stream"
65
+ return head :not_found unless (key = writable_key)
66
+ return render json: { complete: true, offset: store.size(key), chunk_size: chunk_size } if store.exist?(key)
67
+ return head :bad_request unless upload?
68
+ length = request.content_length
69
+ return head :length_required unless length.positive?
70
+
71
+ size = params[:size].to_i
72
+ at = params[:offset].to_i
73
+ limit = chunk_size
74
+ return refuse("a file needs a size") unless size.positive?
75
+ return refuse("larger than this server takes", 413) if size > Files.max_size(@model)
76
+ return refuse("not the size the record gives") if @declared && @declared != size
77
+ return refuse("past the end of the file") if at.negative? || at + length > size
78
+ return render json: { error: "piece larger than this server takes", chunk_size: limit }, status: 413 if length > limit
79
+
80
+ reached = store.append(key, params[:upload], request.body, at: at, length: length)
81
+ store.finish(key, params[:upload]) if reached == size
82
+ render json: { complete: reached == size, offset: reached, chunk_size: limit }
83
+ rescue FileStore::Misplaced => e
84
+ render json: { complete: false, offset: e.offset, chunk_size: chunk_size }, status: :conflict
85
+ rescue FileStore::ChunkTooLarge => e
86
+ render json: { error: "piece larger than this server takes", chunk_size: e.limit }, status: 413
87
+ end
88
+
89
+ private
90
+
91
+ def store = Files.store
92
+ def chunk_size = Files.chunk_size(@model)
93
+ def identity = @identity ||= SyncScope.identity(request)
94
+ def partition = @partition ||= SyncScope.partition(request, identity)
95
+ def upload? = FileStore::UPLOAD.match?(params[:upload].to_s)
96
+
97
+ def find_model
98
+ @model = Files.model(params[:type])
99
+ head :not_found unless @model
100
+ end
101
+
102
+ # Where the file of a record the sender may write is kept.
103
+ def writable_key
104
+ SyncScope.authenticate!(request)
105
+ record = SyncScope.writable(@model, identity, partition: partition).find_by(id: params[:id])
106
+ return unless record
107
+
108
+ @declared = Files.declared_size(record)
109
+ Files.key(@model, record.id)
110
+ end
111
+
112
+ def refuse(reason, status = :unprocessable_entity)
113
+ render json: { error: reason }, status: status
114
+ end
115
+ end
116
+ end
@@ -1,6 +1,8 @@
1
1
  module InstantRecord
2
2
  class MutationsController < ActionController::API
3
3
  before_action { headers.merge!(InstantRecord::CORS_HEADERS) }
4
+ rescue_from InstantRecord::Unauthorized, with: -> { head :unauthorized }
5
+ rescue_from InstantRecord::Forbidden, with: -> { head :forbidden }
4
6
 
5
7
  def preflight
6
8
  head :no_content
@@ -9,13 +11,90 @@ module InstantRecord
9
11
  # Accepts a batch of client mutations; MutationApplier owns the sync
10
12
  # semantics (idempotency, LWW, versioning, change logging).
11
13
  def create
12
- results = Array(params.require(:mutations)).map do |raw|
13
- MutationApplier.apply(
14
- raw.permit(:id, :record_type, :record_id, :operation, :base_version, changes: {})
15
- )
14
+ # Who is asking may come from a session cookie, so this endpoint must not
15
+ # take a cross-site form post: a form cannot send JSON.
16
+ return head :unsupported_media_type unless request.content_mime_type&.json?
17
+
18
+ SyncScope.authenticate!(request)
19
+ identity = SyncScope.identity(request)
20
+ partition = SyncScope.partition(request, identity)
21
+ Rails.application.eager_load! if defined?(Rails) && Rails.application && !Rails.application.config.eager_load
22
+ SyncScope.authorize_models!(SyncScope.models_for(partition), partition, identity, request)
23
+
24
+ batch = params.require(:mutations)
25
+ return head :bad_request unless batch.is_a?(Array) && batch.all? { |item| item.is_a?(ActionController::Parameters) }
26
+
27
+ # Writes to scoped records that were queued as someone else are refused.
28
+ # They are not written to the ledger: the client drops them when its next
29
+ # poll tells it to reset.
30
+ stale = SyncScope.stale?(params[:identity], identity, partition: partition) ? SyncScope.reset_types(identity, partition: partition) : []
31
+ permitted = batch.map { |raw| permit_mutation(raw) }
32
+
33
+ # Offline creates can share a timestamp; apply parents before children
34
+ # that reference them in the same batch while preserving response order.
35
+ applied = {}
36
+ order_by_dependency(permitted).each do |index, mutation|
37
+ owner_type = mutation[:record_type].presence ||
38
+ (mutation[:mutator].present? ? SyncActions.owner_type_of(mutation[:mutator].to_s) : nil)
39
+ mutation_id = mutation[:mutation_id] || mutation[:id]
40
+ applied[index] =
41
+ if owner_type && stale.include?(owner_type)
42
+ { mutation_id: mutation_id, status: "rejected", reason: "identity changed" }
43
+ else
44
+ MutationApplier.apply(mutation, identity, partition)
45
+ end
46
+ end
47
+
48
+ results = permitted.each_index.map { |index| applied[index] }
49
+ render json: { results: results, server_time: InstantRecord::HLC.iso_now }
50
+ end
51
+
52
+ private
53
+
54
+ # Places creates whose record_id is referenced by another create's
55
+ # parent_id (or parent_message_id) in the same batch ahead of dependents.
56
+ def order_by_dependency(mutations)
57
+ indexed = mutations.each_with_index.map { |mutation, index| [index, mutation] }
58
+ created_ids = indexed.each_with_object({}) do |(_, mutation), map|
59
+ map[mutation[:record_id].to_s] = true if mutation[:operation] == "create" && mutation[:record_id].present?
16
60
  end
61
+ return indexed if created_ids.size < 2
17
62
 
18
- render json: { results: results }
63
+ dependents, roots = indexed.partition do |_, mutation|
64
+ next false unless mutation[:operation] == "create"
65
+
66
+ changes = mutation[:changes]
67
+ next false unless changes
68
+
69
+ parent = changes[:parent_id].presence || changes[:parent_message_id].presence
70
+ parent && parent.to_s != mutation[:record_id].to_s && created_ids.key?(parent.to_s)
71
+ end
72
+ roots + dependents
73
+ end
74
+
75
+ def permit_mutation(raw)
76
+ if raw[:mutator].present? || raw[:operation].to_s == "mutator"
77
+ base = raw.permit(:id, :mutation_id, :record_type, :record_id, :operation, :mutator).to_h.symbolize_keys
78
+ base[:args] = sanitize_json_value(raw[:args]) || {}
79
+ base
80
+ else
81
+ raw.permit(:id, :record_type, :record_id, :operation, :base_version, :hlc, :schema_version, changes: {})
82
+ end
83
+ end
84
+
85
+ def sanitize_json_value(value)
86
+ case value
87
+ when ActionController::Parameters
88
+ value.to_unsafe_h.each_with_object({}) { |(k, v), out| out[k.to_s] = sanitize_json_value(v) }
89
+ when Hash
90
+ value.each_with_object({}) { |(k, v), out| out[k.to_s] = sanitize_json_value(v) }
91
+ when Array
92
+ value.map { |item| sanitize_json_value(item) }
93
+ when String, Integer, Float, TrueClass, FalseClass, NilClass
94
+ value
95
+ else
96
+ value.to_s
97
+ end
19
98
  end
20
99
  end
21
100
  end
@@ -0,0 +1,60 @@
1
+ module InstantRecord
2
+ # A native app's screens, asked of this server while developing: the phone
3
+ # sends what it would send its compiled library and gets the same JSON back,
4
+ # so editing a screen's Ruby shows after a pull with no rebuild
5
+ # (HTTPEngine in native/ios).
6
+ #
7
+ # A screen's actions write as whoever its params name, with no session or
8
+ # token consulted. So this answers only when the app turned it on
9
+ # (config.instant_record.native_dev), in a local environment, to a request
10
+ # from this machine. It takes JSON alone and sends no CORS headers: a web
11
+ # page cannot drive it.
12
+ class NativeScreensController < ActionController::API
13
+ before_action :local_development_only
14
+ before_action { head :unsupported_media_type unless request.content_mime_type&.json? }
15
+
16
+ def show
17
+ with_screen { |screen| render json: screen.json }
18
+ end
19
+
20
+ def perform
21
+ with_screen do |screen|
22
+ screen.perform(input["action"].to_s, Native::Screen.strings(input["args"]), Native::Screen.strings(input["values"]))
23
+ head :no_content
24
+ end
25
+ end
26
+
27
+ private
28
+
29
+ def local_development_only
30
+ head :not_found unless Rails.application.config.instant_record.native_dev && Rails.env.local? && request.local?
31
+ end
32
+
33
+ def input
34
+ @input ||= begin
35
+ parsed = JSON.parse(request.raw_post)
36
+ parsed.is_a?(Hash) ? parsed : {}
37
+ rescue JSON::ParserError
38
+ {}
39
+ end
40
+ end
41
+
42
+ # Found by constant each time, from the rule that names a screen's file,
43
+ # so that autoloading finds it and a screen edited since the last request
44
+ # is the one that answers.
45
+ def with_screen
46
+ name = input["screen"].to_s
47
+ found = screen_class(name)
48
+ return render(plain: "No screen named #{name}", status: :not_found) unless found
49
+
50
+ yield found.new(Native::Screen.strings(input["params"]))
51
+ end
52
+
53
+ def screen_class(name)
54
+ found = Native.class_name(name).safe_constantize
55
+ found if found.is_a?(Class) && found < Native::Screen
56
+ rescue ArgumentError
57
+ nil
58
+ end
59
+ end
60
+ end
@@ -1,18 +1,41 @@
1
1
  module InstantRecord
2
- # Keyset-cursor history pages for windowed models: rows strictly below the
3
- # (created_at, id) tuple, newest first. Backs InstantRecord.fetch_history;
4
- # never uses OFFSET, so page cost stays flat at any depth.
2
+ # Keyset-cursor history pages, search widening, and single-record lookups for
3
+ # shaped (`sync_shape`) and windowed (`sync_window`) models. Never uses
4
+ # OFFSET, so page cost stays flat at any depth.
5
5
  class RecordsController < ActionController::API
6
6
  # Independent of any model's window size: the ceiling a client can
7
7
  # request in one page.
8
8
  HARD_LIMIT = 200
9
9
 
10
10
  before_action { headers.merge!(InstantRecord::CORS_HEADERS) }
11
+ rescue_from InstantRecord::Unauthorized, with: -> { head :unauthorized }
12
+ rescue_from InstantRecord::Forbidden, with: -> { head :forbidden }
13
+
14
+ def preflight
15
+ head :no_content
16
+ end
11
17
 
12
18
  def index
13
- model = InstantRecord.synced_model(params[:type])
19
+ SyncScope.authenticate!(request)
20
+ identity = SyncScope.identity(request)
21
+ partition = SyncScope.partition(request, identity)
22
+ Rails.application.eager_load! if defined?(Rails) && Rails.application && !Rails.application.config.eager_load
23
+
24
+ model = resolve_model(partition)
14
25
  return head :not_found unless model
15
26
 
27
+ if SyncScope.partitioned?(model)
28
+ part_value = SyncScope.partition_value(model, partition)
29
+ return head :forbidden if part_value.nil?
30
+
31
+ SyncScope.authorize_partition!(model, part_value, identity, request)
32
+ end
33
+
34
+ base = SyncScope.visible(model, identity, partition: partition)
35
+ if (shape = model.instant_record_sync_shape)
36
+ return render_shape(shape, base)
37
+ end
38
+
16
39
  window = model.instant_record_sync_window
17
40
  return head :unprocessable_entity unless window
18
41
  return head :bad_request if window.partition_by && params[:partition].blank?
@@ -22,18 +45,73 @@ module InstantRecord
22
45
 
23
46
  limit = (params[:limit].presence || window.limit).to_i.clamp(1, HARD_LIMIT)
24
47
  rows = window
25
- .keyset_below(at: before_at, id: params[:before_id], partition: params[:partition])
48
+ .keyset_below(at: before_at, id: params[:before_id], partition: params[:partition], scope: base)
26
49
  .limit(limit + 1)
27
50
  .to_a
28
51
 
29
- render json: {
30
- records: rows.first(limit).map { |record| InstantRecord.record_payload(record) },
31
- has_more: rows.size > limit
52
+ page = rows.first(limit)
53
+ last = page.last
54
+ payload = {
55
+ records: page.map { |record| InstantRecord.record_payload(record) },
56
+ has_more: rows.size > limit,
57
+ server_time: InstantRecord::HLC.iso_now
32
58
  }
59
+ if last
60
+ payload[:next_before] = {
61
+ created_at: last.created_at.utc.iso8601(InstantRecord::TIME_PRECISION),
62
+ id: last.id
63
+ }
64
+ end
65
+ render json: payload
33
66
  end
34
67
 
35
68
  private
36
69
 
70
+ def resolve_model(partition)
71
+ return InstantRecord.synced_model(params[:type]) if params[:type].present?
72
+ return nil if partition.nil?
73
+
74
+ models = SyncScope.models_for(partition)
75
+ models.one? ? models.first : nil
76
+ end
77
+
78
+ def render_shape(shape, base)
79
+ lookup_id = params[:id].presence || params[:lookup].presence || params[:thread].presence
80
+ if lookup_id
81
+ rows = shape.lookup(base, lookup_id)
82
+ return render json: {
83
+ records: rows.map { |record| InstantRecord.record_payload(record) },
84
+ has_more: false,
85
+ server_time: InstantRecord::HLC.iso_now
86
+ }
87
+ end
88
+
89
+ searching = params[:search].present?
90
+ return head :bad_request unless searching || params[:before_id].present?
91
+ return head :bad_request if searching && !shape.searchable?
92
+
93
+ before_at = nil
94
+ if params[:before_id].present?
95
+ before_at = parse_time(params[:before_created_at])
96
+ return head :bad_request if before_at.nil?
97
+ end
98
+
99
+ result = shape.page(
100
+ base,
101
+ before_at: before_at,
102
+ before_id: params[:before_id].presence,
103
+ limit: params[:limit].presence,
104
+ search: params[:search].presence
105
+ )
106
+ payload = {
107
+ records: result[:records].map { |record| InstantRecord.record_payload(record) },
108
+ has_more: result[:has_more],
109
+ server_time: InstantRecord::HLC.iso_now
110
+ }
111
+ payload[:next_before] = result[:next_before] if result[:next_before]
112
+ render json: payload
113
+ end
114
+
37
115
  # Time.zone.parse returns nil for unparseable input but raises
38
116
  # ArgumentError for out-of-range components ("25:61"); treat both as a bad
39
117
  # cursor so a crafted param is a 400, not a 500.
@@ -0,0 +1,64 @@
1
+ module InstantRecord
2
+ # Prebuilt SQLite cold-start shell delivery, partitioned by SyncScope.
3
+ #
4
+ # GET /instant_record/shell?fingerprint=<sha256>
5
+ # Returns a short-lived signed grant URL when a shell matching the client's
6
+ # compiled schema fingerprint exists and is still within retention. Returns
7
+ # 204 No Content otherwise (sending the client to /bootstrap) and schedules
8
+ # an out-of-band build when the caller's identity is job-serializable.
9
+ #
10
+ # GET /instant_record/shell/file?token=<signed>
11
+ # Verifies the HMAC signature, expiry, purpose, AND that the live request's
12
+ # SyncScope identity matches the partition the grant was issued for.
13
+ # Marked `private, no-store` so private shells never enter shared caches.
14
+ class ShellsController < ActionController::API
15
+ HEADERS = InstantRecord::CORS_HEADERS.merge(
16
+ "cache-control" => "private, no-store",
17
+ "vary" => "Authorization, Cookie"
18
+ ).freeze
19
+
20
+ before_action { headers.merge!(HEADERS) }
21
+ rescue_from InstantRecord::Unauthorized, with: -> { head :unauthorized }
22
+ rescue_from InstantRecord::Forbidden, with: -> { head :forbidden }
23
+
24
+ def preflight
25
+ head :no_content
26
+ end
27
+
28
+ def show
29
+ SyncScope.authenticate!(request)
30
+ expected = Shell.fingerprint
31
+ return head :no_content unless params[:fingerprint].to_s == expected
32
+
33
+ identity = SyncScope.identity(request)
34
+ partition = Shell.partition_key(identity)
35
+ revision = Change.maximum(:id) || 0
36
+ shell = Shell.latest(partition, fingerprint: expected)
37
+
38
+ if (shell.nil? || shell.stale?(revision)) && Shell.serializable_identity?(identity)
39
+ ShellBuildJob.perform_later(Shell.dump_identity(identity))
40
+ end
41
+
42
+ return head :no_content unless shell&.servable?(revision)
43
+
44
+ render json: {
45
+ cursor: shell.cursor,
46
+ bytes: shell.bytes,
47
+ built_at: shell.built_at.utc.iso8601,
48
+ identity: SyncScope.key(identity),
49
+ path: "/shell/file?#{{ token: shell.signed_token(holder: partition) }.to_query}"
50
+ }
51
+ end
52
+
53
+ def file
54
+ SyncScope.authenticate!(request)
55
+ identity = SyncScope.identity(request)
56
+ partition = Shell.partition_key(identity)
57
+ shell = Shell.find_signed(params[:token].to_s, partition: partition, holder: partition)
58
+ return head :not_found unless shell
59
+
60
+ headers["x-content-type-options"] = "nosniff"
61
+ send_file shell.path, type: "application/vnd.sqlite3", disposition: "inline"
62
+ end
63
+ end
64
+ end