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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +58 -0
- data/README.md +267 -61
- data/app/controllers/instant_record/bootstraps_controller.rb +39 -12
- data/app/controllers/instant_record/events_controller.rb +58 -6
- data/app/controllers/instant_record/files_controller.rb +116 -0
- data/app/controllers/instant_record/mutations_controller.rb +84 -5
- data/app/controllers/instant_record/native_screens_controller.rb +60 -0
- data/app/controllers/instant_record/records_controller.rb +86 -8
- data/app/controllers/instant_record/shells_controller.rb +64 -0
- data/app/controllers/instant_record/sync_notices_controller.rb +81 -0
- data/app/helpers/instant_record/sync_notices_helper.rb +41 -0
- data/app/jobs/instant_record/shell_build_job.rb +16 -0
- data/app/models/instant_record/change.rb +36 -3
- data/app/models/instant_record/mutation_applier.rb +633 -50
- data/app/views/instant_record/sync_notices/_notices.html.erb +63 -0
- data/compiled/README.md +272 -0
- data/compiled/pipeline/browser_migrations.rb +18 -0
- data/compiled/pipeline/build.rb +13 -0
- data/compiled/pipeline/build_native.rb +14 -0
- data/compiled/pipeline/native/host.c +78 -0
- data/compiled/pipeline/native/instant_record_native.h +57 -0
- data/compiled/pipeline/native_shim.c +149 -0
- data/compiled/pipeline/reactor_shim.c +66 -0
- data/compiled/pipeline/sqlite/rh_shim.c +5 -0
- data/compiled/pipeline/sqlite_release.rb +43 -0
- data/compiled/toolchain.env.example +22 -0
- data/compiled/web/index.html +20 -0
- data/compiled/web/package-lock.json +884 -0
- data/compiled/web/package.json +17 -0
- data/compiled/web/src/app-host-core.js +556 -0
- data/compiled/web/src/app-host.js +16 -0
- data/compiled/web/src/branch-manager.js +140 -0
- data/compiled/web/src/branch-preview.js +397 -0
- data/compiled/web/src/changes.js +191 -0
- data/compiled/web/src/faults.js +172 -0
- data/compiled/web/src/flight-recorder.js +347 -0
- data/compiled/web/src/history-fill.js +68 -0
- data/compiled/web/src/http-headers.js +100 -0
- data/compiled/web/src/leader-election.js +705 -0
- data/compiled/web/src/main.js +608 -0
- data/compiled/web/src/manifest.js +112 -0
- data/compiled/web/src/opfs-wasi-core.js +109 -0
- data/compiled/web/src/opfs-wasi-file.js +8 -0
- data/compiled/web/src/reactor-runtime.js +1692 -0
- data/compiled/web/src/redactor.js +518 -0
- data/compiled/web/src/release-updates.js +48 -0
- data/compiled/web/src/replay.js +338 -0
- data/compiled/web/src/schema-recovery.js +204 -0
- data/compiled/web/src/server-request.js +68 -0
- data/compiled/web/src/sha256.js +98 -0
- data/compiled/web/src/shell.js +52 -0
- data/compiled/web/src/snapshot-store.js +38 -0
- data/compiled/web/src/sqlite-redactor.js +111 -0
- data/compiled/web/src/storage-backend.js +159 -0
- data/compiled/web/src/stream-leader.js +675 -0
- data/compiled/web/src/sync-context.js +91 -0
- data/compiled/web/src/sync-drain.js +104 -0
- data/compiled/web/src/sync-schedule.js +9 -0
- data/compiled/web/src/wasi-minimal.js +275 -0
- data/compiled/web/src/worker.js +39 -0
- data/compiled/web/vite.config.js +27 -0
- data/config/routes.rb +25 -0
- data/db/migrate/20261119000201_add_scope_to_instant_record_changes.rb +7 -0
- data/db/migrate/20261121000001_create_instant_record_sync_notices.rb +21 -0
- data/db/migrate/20261121000101_add_partition_to_instant_record_changes.rb +8 -0
- data/db/migrate/20261121230300_add_delay_line_to_instant_record_outbox.rb +10 -0
- data/exe/instant_record_mcp +6 -0
- data/frontend/LiveList.js +67 -0
- data/frontend/chord.js +79 -0
- data/frontend/file.js +65 -0
- data/frontend/files.js +738 -0
- data/frontend/focus.js +10 -0
- data/frontend/held.js +192 -0
- data/frontend/http.js +76 -0
- data/frontend/index.js +53 -0
- data/frontend/keyboard.js +56 -0
- data/frontend/live.js +298 -0
- data/frontend/notices.js +118 -0
- data/frontend/package.json +15 -0
- data/frontend/range.js +10 -0
- data/frontend/selection.js +47 -0
- data/frontend/shortcuts.js +25 -0
- data/frontend/sync-notices.js +130 -0
- data/frontend/undo.js +48 -0
- data/frontend/window.js +181 -0
- data/lib/generators/instant_record/install/install_generator.rb +18 -30
- data/lib/generators/instant_record/install/templates/instant_record.rb +34 -0
- data/lib/generators/instant_record/ios/ios_generator.rb +71 -0
- data/lib/generators/instant_record/ios/templates/App.swift.tt +35 -0
- data/lib/generators/instant_record/ios/templates/Info.plist +11 -0
- data/lib/generators/instant_record/ios/templates/LibraryEngine.swift +30 -0
- data/lib/instant_record/branch/sqlite_store.rb +142 -0
- data/lib/instant_record/branch.rb +388 -0
- data/lib/instant_record/client/notifier.rb +8 -12
- data/lib/instant_record/client/rebaser.rb +565 -0
- data/lib/instant_record/client/transport.rb +64 -42
- data/lib/instant_record/client.rb +1600 -169
- data/lib/instant_record/compiled_site.rb +85 -0
- data/lib/instant_record/compiler/app_stage.rb +212 -0
- data/lib/instant_record/compiler/ast_lowerer.rb +659 -0
- data/lib/instant_record/compiler/browser_migrations.rb +161 -0
- data/lib/instant_record/compiler/entry_builder.rb +832 -0
- data/lib/instant_record/compiler/fts5_smoke.rb +205 -0
- data/lib/instant_record/compiler/gem_vendor.rb +194 -0
- data/lib/instant_record/compiler/host_adapters.rb +506 -0
- data/lib/instant_record/compiler/kotlin_codegen.rb +209 -0
- data/lib/instant_record/compiler/manifest.rb +178 -0
- data/lib/instant_record/compiler/native_build.rb +586 -0
- data/lib/instant_record/compiler/native_contracts.rb +338 -0
- data/lib/instant_record/compiler/path_scrubber.rb +31 -0
- data/lib/instant_record/compiler/reachability_tracer.rb +1188 -0
- data/lib/instant_record/compiler/route_analyzer.rb +623 -0
- data/lib/instant_record/compiler/runner.rb +42 -0
- data/lib/instant_record/compiler/schema_lock.rb +606 -0
- data/lib/instant_record/compiler/source_pages.rb +77 -0
- data/lib/instant_record/compiler/static_linter.rb +770 -0
- data/lib/instant_record/compiler/swift_codegen.rb +341 -0
- data/lib/instant_record/compiler/toolchain.rb +219 -0
- data/lib/instant_record/compiler/wasm_build.rb +704 -0
- data/lib/instant_record/compiler/wasm_tree.rb +518 -0
- data/lib/instant_record/compiler.rb +277 -0
- data/lib/instant_record/configuration.rb +104 -0
- data/lib/instant_record/engine.rb +68 -18
- data/lib/instant_record/file_store.rb +162 -0
- data/lib/instant_record/files.rb +92 -0
- data/lib/instant_record/hlc.rb +387 -0
- data/lib/instant_record/host.rb +66 -0
- data/lib/instant_record/inertia/renderer.rb +52 -0
- data/lib/instant_record/inertia.rb +222 -0
- data/lib/instant_record/mcp/cli.rb +319 -0
- data/lib/instant_record/mcp/host_process.rb +229 -0
- data/lib/instant_record/mcp/http_exchange.rb +233 -0
- data/lib/instant_record/mcp/replica.rb +556 -0
- data/lib/instant_record/mcp/runtime.rb +406 -0
- data/lib/instant_record/mcp/server.rb +429 -0
- data/lib/instant_record/mcp.rb +47 -0
- data/lib/instant_record/native/contract.rb +367 -0
- data/lib/instant_record/native/node.rb +125 -0
- data/lib/instant_record/native/screen.rb +366 -0
- data/lib/instant_record/native/xcode_project.rb +344 -0
- data/lib/instant_record/native.rb +41 -0
- data/lib/instant_record/outbox_mutation.rb +81 -9
- data/lib/instant_record/outbox_upcaster.rb +161 -0
- data/lib/instant_record/read_tracker.rb +610 -0
- data/lib/instant_record/routing.rb +33 -0
- data/lib/instant_record/runtime_scoped.rb +4 -0
- data/lib/instant_record/shell.rb +486 -0
- data/lib/instant_record/sync_actions.rb +800 -0
- data/lib/instant_record/sync_metadata.rb +17 -2
- data/lib/instant_record/sync_notice.rb +234 -0
- data/lib/instant_record/sync_partition.rb +63 -0
- data/lib/instant_record/sync_scope.rb +300 -0
- data/lib/instant_record/sync_shape.rb +102 -0
- data/lib/instant_record/sync_window.rb +92 -15
- data/lib/instant_record/syncable.rb +313 -17
- data/lib/instant_record/testing/authoritative_server.rb +547 -0
- data/lib/instant_record/testing/chaos_simulator.rb +429 -0
- data/lib/instant_record/testing/cruby_host_bridge.rb +370 -0
- data/lib/instant_record/testing/fault_network.rb +140 -0
- data/lib/instant_record/testing/parity_suite.rb +435 -0
- data/lib/instant_record/testing/runtimes/base.rb +184 -0
- data/lib/instant_record/testing/runtimes/cruby_runtime.rb +255 -0
- data/lib/instant_record/testing/runtimes/native_runtime.rb +346 -0
- data/lib/instant_record/testing/runtimes/wasm_runtime.rb +371 -0
- data/lib/instant_record/testing/wasm_host_bridge.mjs +240 -0
- data/lib/instant_record/testing.rb +333 -0
- data/lib/instant_record/trace/redactor.rb +278 -0
- data/lib/instant_record/trace/replayer.rb +126 -0
- data/lib/instant_record/trace/schema_extractor.rb +37 -0
- data/lib/instant_record/trace.rb +22 -0
- data/lib/instant_record/version.rb +1 -1
- data/lib/instant_record.rb +107 -37
- data/lib/tasks/instant_record.rake +299 -47
- data/native/ios/InstantRecordNative/Package.swift +12 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/AppHost.swift +706 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Engine.swift +64 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/FileStore.swift +1048 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/HTTPEngine.swift +36 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Icons.swift +19 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Node.swift +64 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/ScreenView.swift +481 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Screens.swift +94 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/StreamClient.swift +74 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncNotice.swift +282 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncSchedule.swift +153 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Theme.swift +140 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Transport.swift +108 -0
- data/native/ios/InstantRecordNative/Sources/InstantRecordNative/TypedContracts.swift +237 -0
- data/native/ios/README.md +341 -0
- data/sig/instant_record/inertia.rbs +47 -0
- data/sig/instant_record/native.rbs +38 -0
- metadata +194 -18
- data/lib/generators/instant_record/install/templates/database.js +0 -32
- data/lib/generators/instant_record/install/templates/index.html +0 -69
- data/lib/generators/instant_record/install/templates/rails.sw.js +0 -750
- data/lib/instant_record/local_schema.rb +0 -75
- data/lib/instant_record/pglite_compat.rb +0 -40
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
require "cgi"
|
|
2
|
+
require "json"
|
|
3
|
+
require "rack"
|
|
4
|
+
require "securerandom"
|
|
5
|
+
require "tmpdir"
|
|
6
|
+
require "uri"
|
|
7
|
+
|
|
8
|
+
module InstantRecord
|
|
9
|
+
module Testing
|
|
10
|
+
# Authoritative sync server backing dual-runtime parity checks and multi-client
|
|
11
|
+
# chaos traces. Supports two modes behind one identical interface:
|
|
12
|
+
#
|
|
13
|
+
# 1. RackServer: dispatches real HTTP requests through a mounted Rails app
|
|
14
|
+
# (CRuby + PostgreSQL) with full session/cookie identity management.
|
|
15
|
+
# 2. StandaloneServer: self-contained ActiveRecord server (PostgreSQL via
|
|
16
|
+
# DATABASE_URL when set, or isolated SQLite otherwise) exercising the gem's
|
|
17
|
+
# real MutationApplier, SyncScope, Change, and AppliedMutation classes.
|
|
18
|
+
module AuthoritativeServer
|
|
19
|
+
def self.build(rails_app: nil, database_url: nil, models: %w[Issue AuthNote])
|
|
20
|
+
if rails_app
|
|
21
|
+
RackServer.new(app: rails_app, model_names: models)
|
|
22
|
+
else
|
|
23
|
+
StandaloneServer.new(database_url: database_url, model_names: models)
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
|
|
27
|
+
# Shared helpers for querying visible rows, advancing cursors to 32-bit
|
|
28
|
+
# boundaries, and performing server-originated writes.
|
|
29
|
+
module SharedOperations
|
|
30
|
+
attr_reader :model_names
|
|
31
|
+
|
|
32
|
+
def backend_label
|
|
33
|
+
adapter = ActiveRecord::Base.connection_db_config.adapter
|
|
34
|
+
"CRuby+#{adapter}"
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def models
|
|
38
|
+
@model_names.filter_map { |name| InstantRecord.synced_model(name) || name.safe_constantize }
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
def model_for(name)
|
|
42
|
+
InstantRecord.synced_model(name.to_s) || name.to_s.safe_constantize ||
|
|
43
|
+
raise(ArgumentError, "Unknown synced model: #{name}")
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def current_cursor
|
|
47
|
+
InstantRecord::Change.maximum(:id) || 0
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Advance instant_record_changes.id sequence so subsequent changes emit
|
|
51
|
+
# cursors right at wasm32 signed 32-bit boundaries (e.g. 2_147_483_645).
|
|
52
|
+
def set_cursor_floor(cursor_value)
|
|
53
|
+
target = Integer(cursor_value)
|
|
54
|
+
conn = ActiveRecord::Base.connection
|
|
55
|
+
adapter = conn.adapter_name.downcase
|
|
56
|
+
if adapter.include?("postgres")
|
|
57
|
+
seq = conn.select_value("SELECT pg_get_serial_sequence('instant_record_changes', 'id')")
|
|
58
|
+
if seq
|
|
59
|
+
if target <= 0
|
|
60
|
+
conn.execute("SELECT setval(#{conn.quote(seq)}, 1, false)")
|
|
61
|
+
else
|
|
62
|
+
conn.execute("SELECT setval(#{conn.quote(seq)}, #{target}, true)")
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
elsif adapter.include?("sqlite")
|
|
66
|
+
exists = conn.select_value("SELECT name FROM sqlite_master WHERE type='table' AND name='sqlite_sequence'")
|
|
67
|
+
if exists
|
|
68
|
+
updated = conn.update("UPDATE sqlite_sequence SET seq = #{target} WHERE name = 'instant_record_changes'")
|
|
69
|
+
if updated == 0
|
|
70
|
+
conn.execute("INSERT INTO sqlite_sequence (name, seq) VALUES ('instant_record_changes', #{target})")
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
target
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# Insert a synthetic change row directly at a specific cursor id (e.g. INT32_MAX)
|
|
78
|
+
# along with updating the underlying record's server_version, so compiled clients
|
|
79
|
+
# are tested directly against boundary integer values on the wire.
|
|
80
|
+
def seed_boundary_record(model_name: "Issue", id: nil, title: "int32 boundary", server_version: INT32_MAX, cursor_id: nil, updated_at: nil)
|
|
81
|
+
model = model_for(model_name)
|
|
82
|
+
record_id = id || SecureRandom.uuid
|
|
83
|
+
stamp = updated_at || Time.now.utc
|
|
84
|
+
|
|
85
|
+
InstantRecord.applying_client_mutation do
|
|
86
|
+
record = model.find_or_initialize_by(id: record_id)
|
|
87
|
+
attrs = { "title" => title, "updated_at" => stamp }
|
|
88
|
+
attrs["state"] = "open" if model.column_names.include?("state") && record.new_record?
|
|
89
|
+
attrs["created_at"] = stamp if record.new_record?
|
|
90
|
+
record.assign_attributes(attrs.slice(*model.column_names))
|
|
91
|
+
record.server_version = server_version
|
|
92
|
+
record.sync_state = "synced"
|
|
93
|
+
record.save!(validate: false)
|
|
94
|
+
|
|
95
|
+
change_attrs = {
|
|
96
|
+
record_type: model.name,
|
|
97
|
+
record_id: record.id,
|
|
98
|
+
operation: record.previously_new_record? ? "create" : "update",
|
|
99
|
+
version: server_version,
|
|
100
|
+
attributes_payload: InstantRecord.wire_attributes(record.attributes),
|
|
101
|
+
scope: InstantRecord.scope_of(record)
|
|
102
|
+
}
|
|
103
|
+
if cursor_id
|
|
104
|
+
change_attrs[:id] = Integer(cursor_id)
|
|
105
|
+
end
|
|
106
|
+
change = InstantRecord::Change.create!(change_attrs)
|
|
107
|
+
{ record: record, change: change }
|
|
108
|
+
end
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
# Authoritative server-originated write (simulates a background job or server request).
|
|
112
|
+
def server_write(model_name:, operation:, id: nil, attributes: {}, clock_offset: 0)
|
|
113
|
+
model = model_for(model_name)
|
|
114
|
+
stamp = Time.now.utc + clock_offset.to_f
|
|
115
|
+
case operation.to_s
|
|
116
|
+
when "create"
|
|
117
|
+
attrs = attributes.transform_keys(&:to_s)
|
|
118
|
+
attrs["id"] = id if id
|
|
119
|
+
attrs["created_at"] ||= stamp
|
|
120
|
+
attrs["updated_at"] ||= stamp
|
|
121
|
+
model.create!(attrs.slice(*model.column_names))
|
|
122
|
+
when "update"
|
|
123
|
+
record = model.find_by(id: id)
|
|
124
|
+
return nil unless record
|
|
125
|
+
|
|
126
|
+
attrs = attributes.transform_keys(&:to_s).merge("updated_at" => stamp)
|
|
127
|
+
record.update!(attrs.slice(*model.column_names))
|
|
128
|
+
record
|
|
129
|
+
when "destroy"
|
|
130
|
+
record = model.find_by(id: id)
|
|
131
|
+
return nil unless record
|
|
132
|
+
|
|
133
|
+
record.destroy!
|
|
134
|
+
record
|
|
135
|
+
else
|
|
136
|
+
raise ArgumentError, "Unknown server_write operation: #{operation}"
|
|
137
|
+
end
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
def visible_state(identity: nil)
|
|
141
|
+
asker = identity_object(identity)
|
|
142
|
+
models.each_with_object({}) do |model, state|
|
|
143
|
+
rows = InstantRecord::SyncScope.visible(model, asker).order(:id).map(&:attributes)
|
|
144
|
+
state[model.name] = InstantRecord::Testing.canonical_rows(rows)
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def reset_data!
|
|
149
|
+
models.each(&:delete_all)
|
|
150
|
+
InstantRecord::Change.delete_all
|
|
151
|
+
InstantRecord::AppliedMutation.delete_all
|
|
152
|
+
InstantRecord::OutboxMutation.delete_all if ActiveRecord::Base.connection.data_source_exists?("instant_record_outbox")
|
|
153
|
+
InstantRecord::SyncMetadata.delete_all if ActiveRecord::Base.connection.data_source_exists?("instant_record_sync_metadata")
|
|
154
|
+
set_cursor_floor(0)
|
|
155
|
+
end
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
# Drives a live mounted Rails application (CRuby + PostgreSQL) via Rack.
|
|
159
|
+
class RackServer
|
|
160
|
+
include SharedOperations
|
|
161
|
+
|
|
162
|
+
def initialize(app:, model_names: %w[Issue AuthNote])
|
|
163
|
+
@app = app
|
|
164
|
+
@model_names = Array(model_names)
|
|
165
|
+
@cookies_by_identity = {}
|
|
166
|
+
@mount_path = (app.config.instant_record.mount_path || InstantRecord::DEFAULT_MOUNT_PATH).to_s.sub(%r{/+\z}, "")
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
def close
|
|
170
|
+
nil
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
def identity_object(person_id)
|
|
174
|
+
if defined?(::DemoAsker)
|
|
175
|
+
::DemoAsker.new(nil, person_id)
|
|
176
|
+
else
|
|
177
|
+
person_id
|
|
178
|
+
end
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
def reset_data!
|
|
182
|
+
@cookies_by_identity.clear
|
|
183
|
+
super
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
# Dispatch an HTTP request against the mounted Rails app. If `identity`
|
|
187
|
+
# is provided, ensures a signed Rails session cookie for that person via
|
|
188
|
+
# the app's auth session endpoint (when present) so real `SyncScope.identity`
|
|
189
|
+
# reads the real Rails session cookie.
|
|
190
|
+
def exchange(method, url, body = "", identity: nil, content_type: nil)
|
|
191
|
+
uri = URI.parse(url.to_s)
|
|
192
|
+
path_with_query = uri.path.to_s
|
|
193
|
+
path_with_query = "#{@mount_path}#{path_with_query}" unless path_with_query.start_with?(@mount_path) || path_with_query.start_with?("/todo", "/auth", "/notes", "/slack", "/email", "/up")
|
|
194
|
+
path_with_query = "#{path_with_query}?#{uri.query}" if uri.query && !uri.query.empty?
|
|
195
|
+
|
|
196
|
+
cookie = cookie_for_identity(identity)
|
|
197
|
+
ct = content_type || (method.to_s.upcase == "POST" && body.to_s.lstrip.start_with?("{", "[") ? "application/json" : "application/x-www-form-urlencoded")
|
|
198
|
+
|
|
199
|
+
env = Rack::MockRequest.env_for(
|
|
200
|
+
path_with_query,
|
|
201
|
+
method: method.to_s.upcase,
|
|
202
|
+
input: body.to_s,
|
|
203
|
+
"CONTENT_TYPE" => ct,
|
|
204
|
+
"HTTP_HOST" => "localhost",
|
|
205
|
+
"HTTP_COOKIE" => cookie.to_s
|
|
206
|
+
)
|
|
207
|
+
status, headers, response_body = @app.call(env)
|
|
208
|
+
chunks = +""
|
|
209
|
+
response_body.each { |part| chunks << part.to_s }
|
|
210
|
+
response_body.close if response_body.respond_to?(:close)
|
|
211
|
+
|
|
212
|
+
{ status: status.to_i, headers: headers, body: chunks }
|
|
213
|
+
end
|
|
214
|
+
|
|
215
|
+
private
|
|
216
|
+
|
|
217
|
+
def cookie_for_identity(person_id)
|
|
218
|
+
return "" if person_id.nil? || person_id.to_s.empty?
|
|
219
|
+
return @cookies_by_identity[person_id] if @cookies_by_identity.key?(person_id)
|
|
220
|
+
|
|
221
|
+
# Establish a real Rails session cookie via the JSON auth session endpoint.
|
|
222
|
+
env = Rack::MockRequest.env_for(
|
|
223
|
+
"/auth/session",
|
|
224
|
+
method: "POST",
|
|
225
|
+
input: JSON.generate(person: person_id),
|
|
226
|
+
"CONTENT_TYPE" => "application/json",
|
|
227
|
+
"HTTP_HOST" => "localhost"
|
|
228
|
+
)
|
|
229
|
+
status, headers, body = @app.call(env)
|
|
230
|
+
body.close if body.respond_to?(:close)
|
|
231
|
+
raise InstantRecord::Testing::Error, "POST /auth/session failed for #{person_id.inspect}: status=#{status}" unless status.to_i == 200
|
|
232
|
+
|
|
233
|
+
set_cookie = headers["set-cookie"] || headers["Set-Cookie"]
|
|
234
|
+
pair = Array(set_cookie).flat_map { |line| line.to_s.split("\n") }.map { |c| c.split(";").first }.join("; ")
|
|
235
|
+
@cookies_by_identity[person_id] = pair
|
|
236
|
+
end
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
# Lightweight standalone ActiveRecord server (Postgres via DATABASE_URL or
|
|
240
|
+
# isolated SQLite) that mirrors the exact demo schema, models, SyncScope,
|
|
241
|
+
# and Engine controller wire contracts without requiring a Rails boot.
|
|
242
|
+
class StandaloneServer
|
|
243
|
+
include SharedOperations
|
|
244
|
+
|
|
245
|
+
DemoPerson = Struct.new(:person_id) do
|
|
246
|
+
def to_s = ""
|
|
247
|
+
def sync_identity_key = person_id || "anonymous"
|
|
248
|
+
def sync_reset_types = ["AuthNote"]
|
|
249
|
+
end
|
|
250
|
+
|
|
251
|
+
ROLE_BY_PERSON = { "ada" => "admin", "ben" => "member", "cleo" => "member" }.freeze
|
|
252
|
+
|
|
253
|
+
attr_reader :db_path
|
|
254
|
+
|
|
255
|
+
def initialize(database_url: nil, model_names: %w[Issue AuthNote])
|
|
256
|
+
@model_names = Array(model_names)
|
|
257
|
+
@database_url = database_url && !database_url.to_s.empty? ? database_url.to_s : nil
|
|
258
|
+
@tmpdir = @database_url ? nil : Dir.mktmpdir("instant-record-server")
|
|
259
|
+
@db_path = @tmpdir ? File.join(@tmpdir, "server.sqlite3") : nil
|
|
260
|
+
@shard = :"ir_standalone_server_#{object_id}"
|
|
261
|
+
@previous_synced = InstantRecord.synced_models.dup
|
|
262
|
+
@previous_scope_from = InstantRecord.config.scope_from
|
|
263
|
+
|
|
264
|
+
setup_database!
|
|
265
|
+
ensure_models!
|
|
266
|
+
InstantRecord.sync(*models)
|
|
267
|
+
end
|
|
268
|
+
|
|
269
|
+
def close
|
|
270
|
+
InstantRecord.sync(*@previous_synced)
|
|
271
|
+
InstantRecord.config.scope_from = @previous_scope_from
|
|
272
|
+
ActiveRecord::Base.connection_handler.remove_connection_pool(
|
|
273
|
+
ActiveRecord::Base.name,
|
|
274
|
+
role: :writing,
|
|
275
|
+
shard: @shard
|
|
276
|
+
)
|
|
277
|
+
FileUtils.remove_entry(@tmpdir) if @tmpdir && Dir.exist?(@tmpdir)
|
|
278
|
+
rescue StandardError
|
|
279
|
+
FileUtils.remove_entry(@tmpdir) if @tmpdir && Dir.exist?(@tmpdir)
|
|
280
|
+
end
|
|
281
|
+
|
|
282
|
+
def backend_label
|
|
283
|
+
with_server_shard { super }
|
|
284
|
+
end
|
|
285
|
+
|
|
286
|
+
def current_cursor
|
|
287
|
+
with_server_shard { super }
|
|
288
|
+
end
|
|
289
|
+
|
|
290
|
+
def set_cursor_floor(cursor_value)
|
|
291
|
+
with_server_shard { super }
|
|
292
|
+
end
|
|
293
|
+
|
|
294
|
+
def seed_boundary_record(**kwargs)
|
|
295
|
+
with_server_shard { super }
|
|
296
|
+
end
|
|
297
|
+
|
|
298
|
+
def server_write(**kwargs)
|
|
299
|
+
with_server_shard { super }
|
|
300
|
+
end
|
|
301
|
+
|
|
302
|
+
def visible_state(identity: nil)
|
|
303
|
+
with_server_shard { super }
|
|
304
|
+
end
|
|
305
|
+
|
|
306
|
+
def reset_data!
|
|
307
|
+
with_server_shard { super }
|
|
308
|
+
end
|
|
309
|
+
|
|
310
|
+
def identity_object(person_id)
|
|
311
|
+
known = ROLE_BY_PERSON.key?(person_id.to_s) ? person_id.to_s : nil
|
|
312
|
+
DemoPerson.new(known)
|
|
313
|
+
end
|
|
314
|
+
|
|
315
|
+
def exchange(method, url, body = "", identity: nil, content_type: nil)
|
|
316
|
+
with_server_shard do
|
|
317
|
+
uri = URI.parse(url.to_s)
|
|
318
|
+
path = uri.path.to_s
|
|
319
|
+
params = URI.decode_www_form(uri.query.to_s).to_h
|
|
320
|
+
verb = method.to_s.upcase
|
|
321
|
+
asker = identity_object(identity)
|
|
322
|
+
|
|
323
|
+
if verb == "GET" && path.end_with?("/bootstrap")
|
|
324
|
+
handle_bootstrap(asker)
|
|
325
|
+
elsif verb == "POST" && path.end_with?("/mutations")
|
|
326
|
+
handle_mutations(body, asker)
|
|
327
|
+
elsif verb == "GET" && path.end_with?("/events")
|
|
328
|
+
handle_events(params, asker)
|
|
329
|
+
elsif verb == "GET" && path.end_with?("/records")
|
|
330
|
+
handle_records(params, asker)
|
|
331
|
+
elsif verb == "GET" && path.end_with?("/todo")
|
|
332
|
+
handle_todo_index
|
|
333
|
+
elsif verb == "POST" && path.end_with?("/todo/issues")
|
|
334
|
+
handle_todo_create(body)
|
|
335
|
+
elsif verb == "PATCH" && path =~ %r{/todo/issues/([^/]+)\z}
|
|
336
|
+
handle_todo_update(Regexp.last_match(1), body)
|
|
337
|
+
elsif verb == "DELETE" && path =~ %r{/todo/issues/([^/]+)\z}
|
|
338
|
+
handle_todo_destroy(Regexp.last_match(1))
|
|
339
|
+
else
|
|
340
|
+
{ status: 404, headers: {}, body: "Not Found: #{verb} #{path}" }
|
|
341
|
+
end
|
|
342
|
+
end
|
|
343
|
+
end
|
|
344
|
+
|
|
345
|
+
private
|
|
346
|
+
|
|
347
|
+
def with_server_shard(&block)
|
|
348
|
+
ActiveRecord::Base.connected_to(role: :writing, shard: @shard, &block)
|
|
349
|
+
end
|
|
350
|
+
|
|
351
|
+
def setup_database!
|
|
352
|
+
require "active_record"
|
|
353
|
+
require "active_support/core_ext/time"
|
|
354
|
+
Time.zone ||= "UTC"
|
|
355
|
+
|
|
356
|
+
gem_root = InstantRecord::Testing.gem_root.to_s
|
|
357
|
+
require File.join(gem_root, "app/models/instant_record/change")
|
|
358
|
+
require File.join(gem_root, "app/models/instant_record/applied_mutation")
|
|
359
|
+
require File.join(gem_root, "app/models/instant_record/mutation_applier")
|
|
360
|
+
require "instant_record/sync_scope"
|
|
361
|
+
|
|
362
|
+
config = @database_url || { adapter: "sqlite3", database: @db_path }
|
|
363
|
+
ActiveRecord::Base.connection_handler.establish_connection(
|
|
364
|
+
config,
|
|
365
|
+
owner_name: ActiveRecord::Base.name,
|
|
366
|
+
role: :writing,
|
|
367
|
+
shard: @shard
|
|
368
|
+
)
|
|
369
|
+
|
|
370
|
+
migrations_dir = File.join(gem_root, "db/migrate")
|
|
371
|
+
with_server_shard do
|
|
372
|
+
ActiveRecord::Migration.suppress_messages do
|
|
373
|
+
ActiveRecord::MigrationContext.new(migrations_dir).migrate
|
|
374
|
+
ActiveRecord::Schema.define do
|
|
375
|
+
unless data_source_exists?(:issues)
|
|
376
|
+
create_table :issues, id: :string do |t|
|
|
377
|
+
t.string :title, null: false
|
|
378
|
+
t.string :state, null: false, default: "open"
|
|
379
|
+
t.integer :server_version, null: false, default: 0
|
|
380
|
+
t.string :sync_state, null: false, default: "synced"
|
|
381
|
+
t.timestamps
|
|
382
|
+
end
|
|
383
|
+
end
|
|
384
|
+
|
|
385
|
+
unless data_source_exists?(:auth_notes)
|
|
386
|
+
create_table :auth_notes, id: :string do |t|
|
|
387
|
+
t.string :title, null: false
|
|
388
|
+
t.text :body, null: false, default: ""
|
|
389
|
+
t.string :audience, null: false, default: "owner"
|
|
390
|
+
t.string :owner_id, null: false
|
|
391
|
+
t.integer :server_version, null: false, default: 0
|
|
392
|
+
t.string :sync_state, null: false, default: "synced"
|
|
393
|
+
t.timestamps
|
|
394
|
+
end
|
|
395
|
+
end
|
|
396
|
+
end
|
|
397
|
+
end
|
|
398
|
+
end
|
|
399
|
+
end
|
|
400
|
+
|
|
401
|
+
def ensure_models!
|
|
402
|
+
unless Object.const_defined?(:Issue, false)
|
|
403
|
+
Object.const_set(:Issue, Class.new(ActiveRecord::Base) do
|
|
404
|
+
self.table_name = "issues"
|
|
405
|
+
include InstantRecord::Syncable
|
|
406
|
+
validates :title, presence: true, length: { maximum: 200 }
|
|
407
|
+
validates :title, exclusion: { in: ["reject me"], message: "is not allowed by the server" }, unless: -> { InstantRecord.browser? }
|
|
408
|
+
end)
|
|
409
|
+
end
|
|
410
|
+
|
|
411
|
+
unless Object.const_defined?(:AuthNote, false)
|
|
412
|
+
roles = ROLE_BY_PERSON
|
|
413
|
+
Object.const_set(:AuthNote, Class.new(ActiveRecord::Base) do
|
|
414
|
+
self.table_name = "auth_notes"
|
|
415
|
+
include InstantRecord::Syncable
|
|
416
|
+
|
|
417
|
+
const_set(:AUDIENCES, %w[everyone members admins owner].freeze)
|
|
418
|
+
validates :title, presence: true, length: { maximum: 120 }
|
|
419
|
+
validates :body, length: { maximum: 2_000 }
|
|
420
|
+
validates :audience, inclusion: { in: const_get(:AUDIENCES) }
|
|
421
|
+
validates :owner_id, presence: true
|
|
422
|
+
|
|
423
|
+
syncable_to do |asker|
|
|
424
|
+
person = asker&.person_id
|
|
425
|
+
if person.nil?
|
|
426
|
+
where(audience: "everyone")
|
|
427
|
+
elsif roles[person] == "admin"
|
|
428
|
+
where(audience: %w[everyone members admins]).or(where(owner_id: person))
|
|
429
|
+
else
|
|
430
|
+
where(audience: %w[everyone members]).or(where(owner_id: person))
|
|
431
|
+
end
|
|
432
|
+
end
|
|
433
|
+
|
|
434
|
+
writable_by do |asker|
|
|
435
|
+
asker&.person_id ? where(owner_id: asker.person_id) : none
|
|
436
|
+
end
|
|
437
|
+
end)
|
|
438
|
+
end
|
|
439
|
+
end
|
|
440
|
+
|
|
441
|
+
def handle_bootstrap(asker)
|
|
442
|
+
payload = ActiveRecord::Base.transaction do
|
|
443
|
+
cursor = InstantRecord::Change.maximum(:id) || 0
|
|
444
|
+
records = models.flat_map do |model|
|
|
445
|
+
visible = InstantRecord::SyncScope.visible(model, asker)
|
|
446
|
+
window = model.instant_record_sync_window
|
|
447
|
+
rows = window ? window.in_window(visible) : visible
|
|
448
|
+
rows.map { |record| InstantRecord.record_payload(record) }
|
|
449
|
+
end
|
|
450
|
+
{
|
|
451
|
+
cursor: cursor,
|
|
452
|
+
records: records,
|
|
453
|
+
identity: InstantRecord::SyncScope.key(asker),
|
|
454
|
+
server_time: InstantRecord::HLC.iso_now
|
|
455
|
+
}
|
|
456
|
+
end
|
|
457
|
+
{ status: 200, headers: { "content-type" => "application/json" }, body: JSON.generate(payload) }
|
|
458
|
+
end
|
|
459
|
+
|
|
460
|
+
def handle_mutations(body, asker)
|
|
461
|
+
parsed = JSON.parse(body.to_s)
|
|
462
|
+
stale = InstantRecord::SyncScope.stale?(parsed["identity"], asker) ? InstantRecord::SyncScope.reset_types(asker) : []
|
|
463
|
+
results = Array(parsed["mutations"]).map do |raw|
|
|
464
|
+
mutation = {
|
|
465
|
+
id: raw["id"],
|
|
466
|
+
record_type: raw["record_type"],
|
|
467
|
+
record_id: raw["record_id"],
|
|
468
|
+
operation: raw["operation"],
|
|
469
|
+
base_version: raw["base_version"],
|
|
470
|
+
hlc: raw["hlc"],
|
|
471
|
+
changes: raw["changes"] || {}
|
|
472
|
+
}
|
|
473
|
+
if stale.include?(mutation[:record_type])
|
|
474
|
+
{ mutation_id: mutation[:id], status: "rejected", reason: "identity changed" }
|
|
475
|
+
else
|
|
476
|
+
InstantRecord::MutationApplier.apply(mutation, asker)
|
|
477
|
+
end
|
|
478
|
+
end
|
|
479
|
+
{ status: 200, headers: { "content-type" => "application/json" }, body: JSON.generate(results: results, server_time: InstantRecord::HLC.iso_now) }
|
|
480
|
+
end
|
|
481
|
+
|
|
482
|
+
def handle_events(params, asker)
|
|
483
|
+
cursor = (params["after"] || 0).to_i
|
|
484
|
+
if InstantRecord::SyncScope.stale?(params["identity"], asker)
|
|
485
|
+
body = "event: reset\ndata: #{JSON.generate(InstantRecord::SyncScope.reset_event(asker))}\n\n"
|
|
486
|
+
return { status: 200, headers: { "content-type" => "text/event-stream" }, body: body }
|
|
487
|
+
end
|
|
488
|
+
|
|
489
|
+
changes = InstantRecord::Change.poll(cursor, scope: InstantRecord::SyncScope.token(asker))
|
|
490
|
+
sse = +""
|
|
491
|
+
InstantRecord::SyncScope.events_for(changes, asker).each do |id, event|
|
|
492
|
+
sse << "id: #{id}\nevent: change\ndata: #{JSON.generate(event)}\n\n"
|
|
493
|
+
end
|
|
494
|
+
{ status: 200, headers: { "content-type" => "text/event-stream" }, body: sse }
|
|
495
|
+
end
|
|
496
|
+
|
|
497
|
+
def handle_records(params, asker)
|
|
498
|
+
model = InstantRecord.synced_model(params["type"])
|
|
499
|
+
return { status: 404, headers: {}, body: "" } unless model
|
|
500
|
+
|
|
501
|
+
window = model.instant_record_sync_window
|
|
502
|
+
return { status: 422, headers: {}, body: "" } unless window
|
|
503
|
+
|
|
504
|
+
before_at = Time.zone.parse(params["before_created_at"].to_s)
|
|
505
|
+
return { status: 400, headers: {}, body: "" } if before_at.nil? || params["before_id"].to_s.empty?
|
|
506
|
+
|
|
507
|
+
limit = (params["limit"].to_i > 0 ? params["limit"].to_i : window.limit).clamp(1, 200)
|
|
508
|
+
rows = window.keyset_below(at: before_at, id: params["before_id"], partition: params["partition"])
|
|
509
|
+
.merge(InstantRecord::SyncScope.visible(model, asker))
|
|
510
|
+
.limit(limit + 1)
|
|
511
|
+
.to_a
|
|
512
|
+
|
|
513
|
+
payload = {
|
|
514
|
+
records: rows.first(limit).map { |r| InstantRecord.record_payload(r) },
|
|
515
|
+
has_more: rows.size > limit
|
|
516
|
+
}
|
|
517
|
+
{ status: 200, headers: { "content-type" => "application/json" }, body: JSON.generate(payload) }
|
|
518
|
+
end
|
|
519
|
+
|
|
520
|
+
def handle_todo_index
|
|
521
|
+
issues = model_for("Issue").order(created_at: :desc)
|
|
522
|
+
html = issues.map { |i| %(<li data-id="#{CGI.escapeHTML(i.id.to_s)}" class="#{i.state}">#{CGI.escapeHTML(i.title.to_s)}</li>) }.join("\n")
|
|
523
|
+
{ status: 200, headers: { "content-type" => "text/html" }, body: "<ul class=\"issues\">#{html}</ul>" }
|
|
524
|
+
end
|
|
525
|
+
|
|
526
|
+
def handle_todo_create(body)
|
|
527
|
+
fields = URI.decode_www_form(body.to_s).to_h
|
|
528
|
+
title = fields["issue[title]"] || fields["title"]
|
|
529
|
+
model_for("Issue").create!(title: title)
|
|
530
|
+
{ status: 302, headers: { "location" => "/todo" }, body: "" }
|
|
531
|
+
end
|
|
532
|
+
|
|
533
|
+
def handle_todo_update(id, body)
|
|
534
|
+
fields = URI.decode_www_form(body.to_s).to_h
|
|
535
|
+
issue = model_for("Issue").find(id)
|
|
536
|
+
issue.update!(state: fields["done"] == "1" ? "done" : "open")
|
|
537
|
+
{ status: 302, headers: { "location" => "/todo" }, body: "" }
|
|
538
|
+
end
|
|
539
|
+
|
|
540
|
+
def handle_todo_destroy(id)
|
|
541
|
+
model_for("Issue").find(id).destroy!
|
|
542
|
+
{ status: 302, headers: { "location" => "/todo" }, body: "" }
|
|
543
|
+
end
|
|
544
|
+
end
|
|
545
|
+
end
|
|
546
|
+
end
|
|
547
|
+
end
|