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,486 @@
|
|
|
1
|
+
require "digest"
|
|
2
|
+
require "fileutils"
|
|
3
|
+
require "json"
|
|
4
|
+
require "pathname"
|
|
5
|
+
require "securerandom"
|
|
6
|
+
require "sqlite3"
|
|
7
|
+
require "time"
|
|
8
|
+
require "active_support/core_ext/numeric/time"
|
|
9
|
+
require "active_support/message_verifier"
|
|
10
|
+
require "instant_record/compiler/browser_migrations"
|
|
11
|
+
require "instant_record/sync_scope"
|
|
12
|
+
|
|
13
|
+
module InstantRecord
|
|
14
|
+
# A head start for a first sync: one prebuilt SQLite file a browser or native
|
|
15
|
+
# iOS app can open as its local database, holding what bootstrap would send
|
|
16
|
+
# and stamped with the cursor it was read at. It never has to be current: a
|
|
17
|
+
# client that starts from it polls the change feed from the stamp, and
|
|
18
|
+
# applying a change twice is an idempotent upsert, so an older shell is slower
|
|
19
|
+
# to catch up and never wrong.
|
|
20
|
+
#
|
|
21
|
+
# Partitioned per SyncScope (both identity key and scope token) so private
|
|
22
|
+
# rows are never shared across callers or written into public caches.
|
|
23
|
+
#
|
|
24
|
+
# The file's name carries the stamp: <partition>.<cursor>.<fingerprint>.sqlite3.
|
|
25
|
+
class Shell
|
|
26
|
+
FORMAT = 1
|
|
27
|
+
|
|
28
|
+
# Rebuild once a file is this far behind. Catch-up stays short.
|
|
29
|
+
REBUILD_AFTER_CHANGES = 200
|
|
30
|
+
REBUILD_AFTER = 1.hour
|
|
31
|
+
|
|
32
|
+
# Past this a client takes the normal bootstrap instead of a stale shell.
|
|
33
|
+
SERVE_WITHIN_CHANGES = 1_000
|
|
34
|
+
SERVE_WITHIN = 24.hours
|
|
35
|
+
|
|
36
|
+
URL_LIFETIME = 5.minutes
|
|
37
|
+
SIGNING_PURPOSE = :instant_record_shell
|
|
38
|
+
SQLITE_HEADER = "SQLite format 3\x00".b.freeze
|
|
39
|
+
PARTITION_PATTERN = /\A[A-Za-z0-9_-]+\z/
|
|
40
|
+
|
|
41
|
+
# How the compiled runtime stores a datetime: UTC, a space, six decimals and
|
|
42
|
+
# no zone ("2026-11-19 06:10:30.814075"). Queries order by this text, so a
|
|
43
|
+
# row written any other way sorts apart from rows that sync in later.
|
|
44
|
+
DB_TIME = "%Y-%m-%d %H:%M:%S.%6N"
|
|
45
|
+
|
|
46
|
+
SQLITE_TYPES = {
|
|
47
|
+
string: "varchar",
|
|
48
|
+
text: "text",
|
|
49
|
+
integer: "integer",
|
|
50
|
+
bigint: "integer",
|
|
51
|
+
float: "float",
|
|
52
|
+
decimal: "decimal",
|
|
53
|
+
datetime: "datetime(6)",
|
|
54
|
+
date: "date",
|
|
55
|
+
boolean: "boolean",
|
|
56
|
+
json: "json",
|
|
57
|
+
jsonb: "json"
|
|
58
|
+
}.freeze
|
|
59
|
+
|
|
60
|
+
SERVER_TABLES = %w[schema_migrations ar_internal_metadata].freeze
|
|
61
|
+
|
|
62
|
+
attr_reader :path, :partition, :cursor
|
|
63
|
+
|
|
64
|
+
class << self
|
|
65
|
+
attr_writer :root, :models, :verifier, :identity_serializer, :identity_deserializer
|
|
66
|
+
|
|
67
|
+
def root
|
|
68
|
+
@root ||= if defined?(Rails) && Rails.respond_to?(:root) && Rails.root
|
|
69
|
+
Rails.root.join("storage/instant_record/shells")
|
|
70
|
+
else
|
|
71
|
+
Pathname(Dir.tmpdir).join("instant_record_shells")
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def models
|
|
76
|
+
resolved_models
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# Named custom shell sources (for feeds that manage their own cursor and
|
|
80
|
+
# bootstrap snapshot, like the demo's shared Inbox).
|
|
81
|
+
def sources
|
|
82
|
+
@sources ||= {}
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def register(name, &block)
|
|
86
|
+
sources[name.to_s] = block
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# What a compiled build (browser Wasm or Native iOS) and this server must
|
|
90
|
+
# agree on before a file built here may stand in for a database created
|
|
91
|
+
# there. WasmBuild and NativeBuild compute the same digest.
|
|
92
|
+
def fingerprint(models: nil, schema: nil, schema_path: nil)
|
|
93
|
+
model_list = resolved_models(models).join(",")
|
|
94
|
+
schema_source = if !schema.nil?
|
|
95
|
+
schema.to_s
|
|
96
|
+
elsif (path = schema_path || default_schema_path) && File.file?(path)
|
|
97
|
+
File.read(path)
|
|
98
|
+
else
|
|
99
|
+
connection_schema_statements.join("\n")
|
|
100
|
+
end
|
|
101
|
+
Digest::SHA256.hexdigest([FORMAT, model_list, schema_source].join("\n"))
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# Opaque, filesystem-safe partition name for one SyncScope caller. Hashes
|
|
105
|
+
# BOTH SyncScope.key (syncable_to / auth identity) and SyncScope.token
|
|
106
|
+
# (sync_scope column) so callers differing on either dimension never share
|
|
107
|
+
# a shell file.
|
|
108
|
+
def partition_key(identity)
|
|
109
|
+
Digest::SHA256.hexdigest([SyncScope.key(identity), SyncScope.token(identity).to_s].join("\0"))[0, 24]
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
def valid_sqlite?(bytes)
|
|
113
|
+
bytes.respond_to?(:bytesize) && bytes.bytesize >= SQLITE_HEADER.bytesize &&
|
|
114
|
+
bytes.byteslice(0, SQLITE_HEADER.bytesize) == SQLITE_HEADER
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def serializable_identity?(identity)
|
|
118
|
+
return true if @identity_serializer
|
|
119
|
+
return true if identity.nil? || identity.is_a?(String) || identity.is_a?(Integer)
|
|
120
|
+
return true if defined?(GlobalID::Identification) && identity.is_a?(GlobalID::Identification)
|
|
121
|
+
|
|
122
|
+
false
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
def dump_identity(identity)
|
|
126
|
+
return { "custom" => true, "value" => @identity_serializer.call(identity) } if @identity_serializer
|
|
127
|
+
|
|
128
|
+
identity
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
def load_identity(payload)
|
|
132
|
+
if @identity_deserializer && payload.is_a?(Hash) && payload["custom"]
|
|
133
|
+
return @identity_deserializer.call(payload["value"])
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
payload
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
def latest(partition, fingerprint: nil, root: nil)
|
|
140
|
+
name = validate_partition!(partition)
|
|
141
|
+
fp = (fingerprint || self.fingerprint).first(16)
|
|
142
|
+
dir = Pathname(root || self.root)
|
|
143
|
+
Dir.glob(dir.join("#{name}.*.#{fp}.sqlite3").to_s).map { |path| new(path) }.max_by(&:cursor)
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
# One build at a time per partition, and none when a racing request
|
|
147
|
+
# already brought the file up to date.
|
|
148
|
+
def build(identity: nil, partition: nil, revision: nil, models: nil, identity_key: :auto,
|
|
149
|
+
root: nil, app_root: nil, migration_paths: nil, &snapshot_block)
|
|
150
|
+
name = validate_partition!(partition || partition_key(identity))
|
|
151
|
+
dir = Pathname(root || self.root)
|
|
152
|
+
schema_root = app_root || default_app_root
|
|
153
|
+
schema_file = schema_root ? File.join(schema_root.to_s, "db/schema.rb") : nil
|
|
154
|
+
model_list = resolved_models(models)
|
|
155
|
+
fp = fingerprint(models: model_list, schema_path: schema_file)
|
|
156
|
+
|
|
157
|
+
FileUtils.mkdir_p(dir)
|
|
158
|
+
File.open(dir.join("#{name}.lock"), "w") do |lock|
|
|
159
|
+
return latest(name, fingerprint: fp, root: dir) unless lock.flock(File::LOCK_EX | File::LOCK_NB)
|
|
160
|
+
|
|
161
|
+
current_rev = revision.respond_to?(:call) ? revision.call : (revision || Change.maximum(:id) || 0)
|
|
162
|
+
current = latest(name, fingerprint: fp, root: dir)
|
|
163
|
+
return current if current && !current.stale?(current_rev)
|
|
164
|
+
|
|
165
|
+
snap = take_snapshot(identity: identity, models: models, &snapshot_block)
|
|
166
|
+
resolved_identity = if snap.key?(:identity)
|
|
167
|
+
snap[:identity]
|
|
168
|
+
elsif identity_key == :auto
|
|
169
|
+
SyncScope.key(identity)
|
|
170
|
+
else
|
|
171
|
+
identity_key
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
ddl = resolve_schema_ddl(app_root: schema_root, migration_paths: migration_paths)
|
|
175
|
+
write(
|
|
176
|
+
name,
|
|
177
|
+
cursor: snap.fetch(:cursor),
|
|
178
|
+
records: snap.fetch(:records),
|
|
179
|
+
fingerprint: fp,
|
|
180
|
+
models: model_list,
|
|
181
|
+
identity_key: resolved_identity,
|
|
182
|
+
ddl: ddl,
|
|
183
|
+
root: dir
|
|
184
|
+
)
|
|
185
|
+
end
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
def build_source(name, arg = nil, **options)
|
|
189
|
+
builder = sources[name.to_s]
|
|
190
|
+
raise ArgumentError, "Unknown shell source: #{name.inspect}" unless builder
|
|
191
|
+
|
|
192
|
+
spec = builder.call(arg)
|
|
193
|
+
return nil unless spec
|
|
194
|
+
|
|
195
|
+
snapshot_proc = spec.fetch(:snapshot)
|
|
196
|
+
build(
|
|
197
|
+
partition: spec.fetch(:partition),
|
|
198
|
+
revision: spec[:revision],
|
|
199
|
+
models: spec[:models] || options[:models],
|
|
200
|
+
identity_key: spec.key?(:identity_key) ? spec[:identity_key] : nil,
|
|
201
|
+
root: options[:root],
|
|
202
|
+
app_root: options[:app_root],
|
|
203
|
+
migration_paths: options[:migration_paths],
|
|
204
|
+
&snapshot_proc
|
|
205
|
+
)
|
|
206
|
+
end
|
|
207
|
+
|
|
208
|
+
# Model-agnostic bootstrap snapshot: change-log cursor read BEFORE rows
|
|
209
|
+
# inside one transaction, filtered by SyncWindow and SyncScope.visible.
|
|
210
|
+
def snapshot(identity: nil, models: nil)
|
|
211
|
+
in_snapshot_transaction do
|
|
212
|
+
cursor = Change.maximum(:id) || 0
|
|
213
|
+
records = snapshot_models(models).flat_map do |model|
|
|
214
|
+
visible = SyncScope.visible(model, identity)
|
|
215
|
+
window = model.instant_record_sync_window
|
|
216
|
+
rows = window ? window.in_window(visible) : visible
|
|
217
|
+
rows.map { |record| InstantRecord.record_payload(record) }
|
|
218
|
+
end
|
|
219
|
+
{ cursor: cursor, records: records }
|
|
220
|
+
end
|
|
221
|
+
end
|
|
222
|
+
|
|
223
|
+
def verifier
|
|
224
|
+
@verifier ||= begin
|
|
225
|
+
secret = if defined?(Rails) && Rails.application
|
|
226
|
+
Rails.application.key_generator.generate_key("instant_record_shell")
|
|
227
|
+
else
|
|
228
|
+
@fallback_secret ||= SecureRandom.random_bytes(32)
|
|
229
|
+
end
|
|
230
|
+
ActiveSupport::MessageVerifier.new(secret, url_safe: true, serializer: JSON)
|
|
231
|
+
end
|
|
232
|
+
end
|
|
233
|
+
|
|
234
|
+
def find_signed(token, partition:, holder: nil, root: nil)
|
|
235
|
+
return if token.to_s.empty?
|
|
236
|
+
|
|
237
|
+
name = validate_partition!(partition)
|
|
238
|
+
expected_holder = (holder.nil? ? name : holder).to_s
|
|
239
|
+
grant = verifier.verified(token, purpose: SIGNING_PURPOSE)
|
|
240
|
+
return unless grant.is_a?(Hash) &&
|
|
241
|
+
grant["partition"] == name &&
|
|
242
|
+
grant["holder"] == expected_holder &&
|
|
243
|
+
grant["file"].is_a?(String) &&
|
|
244
|
+
File.basename(grant["file"]) == grant["file"] &&
|
|
245
|
+
grant["file"].start_with?("#{name}.")
|
|
246
|
+
|
|
247
|
+
path = Pathname(root || self.root).join(File.basename(grant["file"]))
|
|
248
|
+
new(path.to_s) if path.file?
|
|
249
|
+
rescue ArgumentError
|
|
250
|
+
nil
|
|
251
|
+
end
|
|
252
|
+
|
|
253
|
+
# Resolve SQLite DDL statements and schema version, preferring
|
|
254
|
+
# BrowserMigrations (the same SQLite DDL the compiled client uses) and
|
|
255
|
+
# falling back to ActiveRecord connection introspection when no
|
|
256
|
+
# db/schema.rb or portable migrations are present.
|
|
257
|
+
def resolve_schema_ddl(app_root: default_app_root, migration_paths: nil)
|
|
258
|
+
if app_root && File.file?(File.join(app_root.to_s, "db/schema.rb"))
|
|
259
|
+
paths = migration_paths || default_migration_paths(app_root)
|
|
260
|
+
if paths.any? { |dir| File.directory?(dir) && Dir.glob("[0-9]*_*.rb", base: dir).any? }
|
|
261
|
+
begin
|
|
262
|
+
return Compiler::BrowserMigrations.schema_ddl(root: app_root.to_s, migration_paths: paths)
|
|
263
|
+
rescue Compiler::BuildError
|
|
264
|
+
# Fall back to live connection introspection if an app has a
|
|
265
|
+
# pre-baseline non-portable migration without a .sql companion.
|
|
266
|
+
end
|
|
267
|
+
end
|
|
268
|
+
version = extract_schema_version(File.join(app_root.to_s, "db/schema.rb"))
|
|
269
|
+
return { version: version, statements: connection_schema_statements }
|
|
270
|
+
end
|
|
271
|
+
|
|
272
|
+
{ version: nil, statements: connection_schema_statements }
|
|
273
|
+
end
|
|
274
|
+
|
|
275
|
+
private
|
|
276
|
+
|
|
277
|
+
def validate_partition!(partition)
|
|
278
|
+
name = partition.to_s
|
|
279
|
+
raise ArgumentError, "Invalid shell partition: #{partition.inspect}" unless PARTITION_PATTERN.match?(name)
|
|
280
|
+
|
|
281
|
+
name
|
|
282
|
+
end
|
|
283
|
+
|
|
284
|
+
def default_app_root
|
|
285
|
+
Rails.root if defined?(Rails) && Rails.respond_to?(:root) && Rails.root
|
|
286
|
+
end
|
|
287
|
+
|
|
288
|
+
def default_schema_path
|
|
289
|
+
root_dir = default_app_root
|
|
290
|
+
root_dir&.join("db/schema.rb")
|
|
291
|
+
end
|
|
292
|
+
|
|
293
|
+
def default_migration_paths(app_root)
|
|
294
|
+
if defined?(Rails) && Rails.application && Rails.application.root.to_s == app_root.to_s
|
|
295
|
+
Rails.application.config.paths["db/migrate"].existent
|
|
296
|
+
else
|
|
297
|
+
[File.join(app_root.to_s, "db/migrate")]
|
|
298
|
+
end
|
|
299
|
+
end
|
|
300
|
+
|
|
301
|
+
def eager_load_if_rails!
|
|
302
|
+
if defined?(Rails) && Rails.application && !Rails.application.config.eager_load
|
|
303
|
+
Rails.application.eager_load!
|
|
304
|
+
end
|
|
305
|
+
end
|
|
306
|
+
|
|
307
|
+
def resolved_models(explicit = nil)
|
|
308
|
+
list = if explicit
|
|
309
|
+
Array(explicit).map { |m| m.is_a?(Class) ? m.name : m.to_s }
|
|
310
|
+
elsif @models
|
|
311
|
+
Array(@models).map(&:to_s)
|
|
312
|
+
else
|
|
313
|
+
eager_load_if_rails!
|
|
314
|
+
InstantRecord.syncable_models.map(&:name)
|
|
315
|
+
end
|
|
316
|
+
list.compact.sort
|
|
317
|
+
end
|
|
318
|
+
|
|
319
|
+
def snapshot_models(explicit = nil)
|
|
320
|
+
if explicit
|
|
321
|
+
Array(explicit).filter_map { |m| m.is_a?(Class) ? m : InstantRecord.synced_model(m.to_s) }
|
|
322
|
+
else
|
|
323
|
+
eager_load_if_rails!
|
|
324
|
+
InstantRecord.syncable_models
|
|
325
|
+
end
|
|
326
|
+
end
|
|
327
|
+
|
|
328
|
+
def take_snapshot(identity:, models:, &snapshot_block)
|
|
329
|
+
if snapshot_block
|
|
330
|
+
in_snapshot_transaction(&snapshot_block)
|
|
331
|
+
else
|
|
332
|
+
snapshot(identity: identity, models: models)
|
|
333
|
+
end
|
|
334
|
+
end
|
|
335
|
+
|
|
336
|
+
def in_snapshot_transaction(&block)
|
|
337
|
+
conn = ActiveRecord::Base.connection
|
|
338
|
+
isolated = conn.open_transactions.zero? && conn.supports_transaction_isolation? && !conn.adapter_name.match?(/sqlite/i)
|
|
339
|
+
ActiveRecord::Base.transaction(**(isolated ? { isolation: :repeatable_read } : {})) { block.call }
|
|
340
|
+
end
|
|
341
|
+
|
|
342
|
+
def write(partition, cursor:, records:, fingerprint:, models:, identity_key:, ddl:, root:)
|
|
343
|
+
final = root.join("#{partition}.#{cursor}.#{fingerprint.first(16)}.sqlite3")
|
|
344
|
+
draft = root.join("#{final.basename}.#{SecureRandom.hex(4)}.tmp")
|
|
345
|
+
stamp = Time.current.utc.strftime(DB_TIME)
|
|
346
|
+
database = SQLite3::Database.new(draft.to_s)
|
|
347
|
+
# Most tables in a shell may be empty, and an empty table or index still
|
|
348
|
+
# takes a page. Small pages keep the download small.
|
|
349
|
+
database.execute("PRAGMA page_size = 1024")
|
|
350
|
+
database.transaction do
|
|
351
|
+
ddl.fetch(:statements).each { |sql| database.execute(sql) }
|
|
352
|
+
records.each { |record| insert(database, record) }
|
|
353
|
+
|
|
354
|
+
metadata = {
|
|
355
|
+
"compiled_models" => models.join(","),
|
|
356
|
+
"shell_fingerprint" => fingerprint
|
|
357
|
+
}
|
|
358
|
+
metadata["schema_version"] = format("%020d", ddl[:version].to_i) if ddl[:version]
|
|
359
|
+
metadata["identity"] = identity_key.to_s if identity_key && !identity_key.to_s.empty?
|
|
360
|
+
# Cursor goes in last, matching the client's bootstrap invariant:
|
|
361
|
+
# a database without one is a database that still has to sync.
|
|
362
|
+
metadata["cursor"] = cursor.to_s
|
|
363
|
+
|
|
364
|
+
metadata.each do |key, value|
|
|
365
|
+
database.execute(
|
|
366
|
+
"INSERT INTO instant_record_sync_metadata (key, value, created_at, updated_at) VALUES (?, ?, ?, ?)",
|
|
367
|
+
[key, value, stamp, stamp]
|
|
368
|
+
)
|
|
369
|
+
end
|
|
370
|
+
end
|
|
371
|
+
database.execute("VACUUM")
|
|
372
|
+
database.close
|
|
373
|
+
File.rename(draft, final)
|
|
374
|
+
|
|
375
|
+
# Keep files that may still have live signed URLs until URL_LIFETIME passes.
|
|
376
|
+
Dir.glob(root.join("#{partition}.*.sqlite3").to_s).each do |old|
|
|
377
|
+
File.delete(old) if old != final.to_s && File.mtime(old) < URL_LIFETIME.ago
|
|
378
|
+
end
|
|
379
|
+
new(final.to_s)
|
|
380
|
+
ensure
|
|
381
|
+
database&.close unless database&.closed?
|
|
382
|
+
FileUtils.rm_f(draft) if draft
|
|
383
|
+
end
|
|
384
|
+
|
|
385
|
+
# A row as the client's upsert would leave it: wire values with datetimes
|
|
386
|
+
# in the compiled runtime's format, server_version set, sync_state synced.
|
|
387
|
+
def insert(database, record)
|
|
388
|
+
type = record[:type] || record["type"]
|
|
389
|
+
model = InstantRecord.synced_model(type) || type.to_s.constantize
|
|
390
|
+
raw = record[:attributes] || record["attributes"] || {}
|
|
391
|
+
attributes = raw.transform_keys(&:to_s).slice(*model.column_names)
|
|
392
|
+
if model.column_names.include?("server_version")
|
|
393
|
+
attributes["server_version"] = record[:version] || record["version"] || attributes["server_version"] || 0
|
|
394
|
+
end
|
|
395
|
+
attributes["sync_state"] = "synced" if model.column_names.include?("sync_state")
|
|
396
|
+
|
|
397
|
+
model.columns.each do |column|
|
|
398
|
+
val = attributes[column.name]
|
|
399
|
+
next if val.nil?
|
|
400
|
+
|
|
401
|
+
if column.type == :datetime
|
|
402
|
+
attributes[column.name] = format_datetime(val)
|
|
403
|
+
elsif column.type == :date && val.is_a?(Date)
|
|
404
|
+
attributes[column.name] = val.iso8601
|
|
405
|
+
end
|
|
406
|
+
end
|
|
407
|
+
|
|
408
|
+
columns = attributes.keys.map { |name| %("#{name}") }.join(", ")
|
|
409
|
+
values = attributes.values.map { |value| sqlite_value(value) }
|
|
410
|
+
placeholders = (["?"] * values.size).join(", ")
|
|
411
|
+
database.execute(%(INSERT INTO "#{model.table_name}" (#{columns}) VALUES (#{placeholders})), values)
|
|
412
|
+
end
|
|
413
|
+
|
|
414
|
+
def format_datetime(value)
|
|
415
|
+
time = value.is_a?(String) ? Time.iso8601(value) : value.to_time
|
|
416
|
+
time.utc.strftime(DB_TIME)
|
|
417
|
+
rescue ArgumentError
|
|
418
|
+
Time.parse(value.to_s).utc.strftime(DB_TIME)
|
|
419
|
+
end
|
|
420
|
+
|
|
421
|
+
def sqlite_value(value)
|
|
422
|
+
case value
|
|
423
|
+
when true then 1
|
|
424
|
+
when false then 0
|
|
425
|
+
when Hash, Array then JSON.generate(value)
|
|
426
|
+
else value
|
|
427
|
+
end
|
|
428
|
+
end
|
|
429
|
+
|
|
430
|
+
def extract_schema_version(schema_path)
|
|
431
|
+
match = File.read(schema_path).match(/\.define\s*\(\s*version:\s*([\d_]+)/)
|
|
432
|
+
match ? Integer(match[1], 10) : nil
|
|
433
|
+
end
|
|
434
|
+
|
|
435
|
+
def connection_schema_statements
|
|
436
|
+
connection = ActiveRecord::Base.connection
|
|
437
|
+
(connection.tables - SERVER_TABLES).sort.flat_map do |table|
|
|
438
|
+
keys = Array(connection.primary_key(table))
|
|
439
|
+
columns = connection.columns(table).map do |column|
|
|
440
|
+
sql = %("#{column.name}" #{SQLITE_TYPES.fetch(column.type, "text")})
|
|
441
|
+
sql << " NOT NULL" unless column.null
|
|
442
|
+
sql << " DEFAULT #{connection.quote(column.default)}" if column.default && !column.default_function
|
|
443
|
+
sql << " PRIMARY KEY AUTOINCREMENT" if keys == [column.name] && %i[integer bigint].include?(column.type)
|
|
444
|
+
sql
|
|
445
|
+
end
|
|
446
|
+
if keys.any? && columns.none? { |sql| sql.include?("AUTOINCREMENT") }
|
|
447
|
+
columns << "PRIMARY KEY (#{keys.map { |key| %("#{key}") }.join(", ")})"
|
|
448
|
+
end
|
|
449
|
+
indexes = connection.indexes(table).select { |index| index.columns.is_a?(Array) && index.where.nil? }.map do |index|
|
|
450
|
+
%(CREATE #{"UNIQUE " if index.unique}INDEX "#{index.name}" ON "#{table}" (#{index.columns.map { |name| %("#{name}") }.join(", ")}))
|
|
451
|
+
end
|
|
452
|
+
[%(CREATE TABLE "#{table}" (#{columns.join(", ")})), *indexes]
|
|
453
|
+
end
|
|
454
|
+
end
|
|
455
|
+
end
|
|
456
|
+
|
|
457
|
+
def initialize(path)
|
|
458
|
+
@path = path.to_s
|
|
459
|
+
@partition, cursor, = File.basename(@path).split(".")
|
|
460
|
+
@cursor = cursor.to_i
|
|
461
|
+
end
|
|
462
|
+
|
|
463
|
+
def built_at = File.mtime(path)
|
|
464
|
+
def bytes = File.size(path)
|
|
465
|
+
|
|
466
|
+
def stale?(revision)
|
|
467
|
+
revision - cursor > REBUILD_AFTER_CHANGES || built_at < REBUILD_AFTER.ago
|
|
468
|
+
end
|
|
469
|
+
|
|
470
|
+
def servable?(revision)
|
|
471
|
+
revision - cursor <= SERVE_WITHIN_CHANGES && built_at >= SERVE_WITHIN.ago
|
|
472
|
+
end
|
|
473
|
+
|
|
474
|
+
def signed_token(holder: nil)
|
|
475
|
+
self.class.verifier.generate(
|
|
476
|
+
{
|
|
477
|
+
"partition" => partition,
|
|
478
|
+
"holder" => (holder.nil? ? partition : holder).to_s,
|
|
479
|
+
"file" => File.basename(path)
|
|
480
|
+
},
|
|
481
|
+
expires_in: URL_LIFETIME,
|
|
482
|
+
purpose: SIGNING_PURPOSE
|
|
483
|
+
)
|
|
484
|
+
end
|
|
485
|
+
end
|
|
486
|
+
end
|