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,229 @@
|
|
|
1
|
+
require "fileutils"
|
|
2
|
+
require "open3"
|
|
3
|
+
|
|
4
|
+
module InstantRecord
|
|
5
|
+
module Mcp
|
|
6
|
+
# Persistent driver for the screenless native `host` binary compiled by
|
|
7
|
+
# InstantRecord::Compiler::NativeBuild (compiled/pipeline/native/host.c).
|
|
8
|
+
#
|
|
9
|
+
# Protocol (byte-counted over binary stdin/stdout):
|
|
10
|
+
# driver -> host: call <entry> <bytes>\n<input>
|
|
11
|
+
# boot <bytes>\n<path>
|
|
12
|
+
# open <bytes>\n<path>
|
|
13
|
+
# host -> driver: ok <out_bytes> <notice_bytes>\n<out><notice>
|
|
14
|
+
# error <bytes>\n<message>
|
|
15
|
+
# exchange <bytes>\n<request>
|
|
16
|
+
# driver -> host: <response_bytes>\n<response>
|
|
17
|
+
class HostProcess
|
|
18
|
+
Result = Struct.new(:out, :notice, keyword_init: true)
|
|
19
|
+
ENTRY_PATTERN = /\A[a-z][a-z0-9_]{0,30}\z/
|
|
20
|
+
MAX_STDERR_LINES = 50
|
|
21
|
+
|
|
22
|
+
attr_reader :binary, :database_path
|
|
23
|
+
|
|
24
|
+
def initialize(binary:, database:, exchange: nil, chdir: nil, err: nil)
|
|
25
|
+
@binary = File.expand_path(binary.to_s)
|
|
26
|
+
unless File.file?(@binary) && File.executable?(@binary)
|
|
27
|
+
raise ArgumentError, "Native host binary is not executable: #{@binary}. Build it with `bin/rails instant_record:native`."
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
@database_path = database.nil? || database == "-" ? nil : File.expand_path(database.to_s)
|
|
31
|
+
FileUtils.mkdir_p(File.dirname(@database_path)) if @database_path
|
|
32
|
+
@chdir = chdir ? File.expand_path(chdir.to_s) : (@database_path ? File.dirname(@database_path) : Dir.pwd)
|
|
33
|
+
FileUtils.mkdir_p(@chdir)
|
|
34
|
+
|
|
35
|
+
@exchange = exchange
|
|
36
|
+
@err = err
|
|
37
|
+
@mutex = Mutex.new
|
|
38
|
+
@stderr_mutex = Mutex.new
|
|
39
|
+
@stderr_lines = []
|
|
40
|
+
@closed = false
|
|
41
|
+
|
|
42
|
+
spawn_process!
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def alive?
|
|
46
|
+
!@closed && @wait_thread&.alive?
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def stderr_tail
|
|
50
|
+
@stderr_mutex.synchronize { @stderr_lines.join }
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def call(entry, input = "")
|
|
54
|
+
entry_name = entry.to_s
|
|
55
|
+
raise ArgumentError, "Invalid native entry name: #{entry_name.inspect}" unless ENTRY_PATTERN.match?(entry_name)
|
|
56
|
+
|
|
57
|
+
@mutex.synchronize do
|
|
58
|
+
ensure_open!
|
|
59
|
+
payload = input.to_s.b
|
|
60
|
+
write_all("call #{entry_name} #{payload.bytesize}\n")
|
|
61
|
+
write_all(payload) unless payload.empty?
|
|
62
|
+
@stdin.flush
|
|
63
|
+
read_reply
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
def boot(path)
|
|
68
|
+
expanded = File.expand_path(path.to_s)
|
|
69
|
+
FileUtils.mkdir_p(File.dirname(expanded))
|
|
70
|
+
result = send_path("boot", expanded)
|
|
71
|
+
@database_path = expanded
|
|
72
|
+
result
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def open(path)
|
|
76
|
+
expanded = File.expand_path(path.to_s)
|
|
77
|
+
FileUtils.mkdir_p(File.dirname(expanded))
|
|
78
|
+
result = send_path("open", expanded)
|
|
79
|
+
@database_path = expanded
|
|
80
|
+
result
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
def close
|
|
84
|
+
@mutex.synchronize do
|
|
85
|
+
return if @closed
|
|
86
|
+
|
|
87
|
+
@closed = true
|
|
88
|
+
begin
|
|
89
|
+
@stdin.close unless @stdin.closed?
|
|
90
|
+
rescue IOError
|
|
91
|
+
nil
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
if @wait_thread&.alive?
|
|
95
|
+
unless @wait_thread.join(2)
|
|
96
|
+
begin
|
|
97
|
+
Process.kill("TERM", @wait_thread.pid)
|
|
98
|
+
rescue Errno::ESRCH
|
|
99
|
+
nil
|
|
100
|
+
end
|
|
101
|
+
@wait_thread.join(1)
|
|
102
|
+
end
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
@stderr_thread&.join(1)
|
|
106
|
+
[@stdout, @stderr].each do |io|
|
|
107
|
+
io.close unless io.nil? || io.closed?
|
|
108
|
+
rescue IOError
|
|
109
|
+
nil
|
|
110
|
+
end
|
|
111
|
+
end
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
private
|
|
115
|
+
|
|
116
|
+
def spawn_process!
|
|
117
|
+
@stdin, @stdout, @stderr, @wait_thread = Open3.popen3(@binary, @database_path || "-", chdir: @chdir)
|
|
118
|
+
@stdin.binmode
|
|
119
|
+
@stdout.binmode
|
|
120
|
+
@stderr.binmode
|
|
121
|
+
start_stderr_drain
|
|
122
|
+
read_reply
|
|
123
|
+
rescue StandardError
|
|
124
|
+
close
|
|
125
|
+
raise
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
def start_stderr_drain
|
|
129
|
+
@stderr_thread = Thread.new do
|
|
130
|
+
while (line = @stderr.gets)
|
|
131
|
+
line.force_encoding(Encoding::UTF_8)
|
|
132
|
+
line = line.scrub
|
|
133
|
+
@stderr_mutex.synchronize do
|
|
134
|
+
@stderr_lines << line
|
|
135
|
+
@stderr_lines.shift while @stderr_lines.size > MAX_STDERR_LINES
|
|
136
|
+
end
|
|
137
|
+
@err&.write(line)
|
|
138
|
+
end
|
|
139
|
+
rescue IOError
|
|
140
|
+
nil
|
|
141
|
+
end
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
def send_path(verb, path)
|
|
145
|
+
@mutex.synchronize do
|
|
146
|
+
ensure_open!
|
|
147
|
+
bytes = path.b
|
|
148
|
+
write_all("#{verb} #{bytes.bytesize}\n")
|
|
149
|
+
write_all(bytes)
|
|
150
|
+
@stdin.flush
|
|
151
|
+
read_reply
|
|
152
|
+
end
|
|
153
|
+
end
|
|
154
|
+
|
|
155
|
+
def ensure_open!
|
|
156
|
+
raise HostCrashedError, "Native host process is closed" if @closed
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
def read_reply
|
|
160
|
+
loop do
|
|
161
|
+
line = @stdout.gets
|
|
162
|
+
if line.nil?
|
|
163
|
+
tail = stderr_tail.strip
|
|
164
|
+
detail = tail.empty? ? "unexpected EOF" : "unexpected EOF (#{tail})"
|
|
165
|
+
raise HostCrashedError, "Native host exited: #{detail}"
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
parts = line.strip.split
|
|
169
|
+
case parts[0]
|
|
170
|
+
when "ok"
|
|
171
|
+
raise HostCrashedError, "Malformed ok frame from native host: #{line.inspect}" unless parts.size >= 3
|
|
172
|
+
|
|
173
|
+
out_len = Integer(parts[1])
|
|
174
|
+
notice_len = Integer(parts[2])
|
|
175
|
+
out = read_exact(@stdout, out_len).force_encoding(Encoding::UTF_8)
|
|
176
|
+
notice = read_exact(@stdout, notice_len).force_encoding(Encoding::UTF_8)
|
|
177
|
+
return Result.new(out: out, notice: notice)
|
|
178
|
+
when "exchange"
|
|
179
|
+
raise HostCrashedError, "Malformed exchange frame from native host: #{line.inspect}" unless parts.size >= 2
|
|
180
|
+
|
|
181
|
+
req_len = Integer(parts[1])
|
|
182
|
+
request = read_exact(@stdout, req_len).force_encoding(Encoding::UTF_8)
|
|
183
|
+
answer = (@exchange ? @exchange.call(request) : HttpExchange::OFFLINE_REPLY).to_s.b
|
|
184
|
+
write_all("#{answer.bytesize}\n")
|
|
185
|
+
write_all(answer)
|
|
186
|
+
@stdin.flush
|
|
187
|
+
when "error"
|
|
188
|
+
raise HostCrashedError, "Malformed error frame from native host: #{line.inspect}" unless parts.size >= 2
|
|
189
|
+
|
|
190
|
+
err_len = Integer(parts[1])
|
|
191
|
+
message = read_exact(@stdout, err_len).force_encoding(Encoding::UTF_8)
|
|
192
|
+
raise HostError, message
|
|
193
|
+
else
|
|
194
|
+
raise HostCrashedError, "Unexpected response from native host: #{line.inspect}"
|
|
195
|
+
end
|
|
196
|
+
end
|
|
197
|
+
rescue ArgumentError, TypeError => e
|
|
198
|
+
raise HostCrashedError, "Invalid frame header from native host: #{e.message}"
|
|
199
|
+
rescue Errno::EPIPE, IOError => e
|
|
200
|
+
raise HostCrashedError, "Native host pipe error: #{e.message}"
|
|
201
|
+
end
|
|
202
|
+
|
|
203
|
+
def read_exact(io, length)
|
|
204
|
+
return "".b if length <= 0
|
|
205
|
+
|
|
206
|
+
buffer = String.new(capacity: length, encoding: Encoding::BINARY)
|
|
207
|
+
remaining = length
|
|
208
|
+
while remaining > 0
|
|
209
|
+
chunk = io.read(remaining)
|
|
210
|
+
if chunk.nil? || chunk.empty?
|
|
211
|
+
raise HostCrashedError, "Native host closed stream mid-frame (expected #{length} bytes, got #{buffer.bytesize})"
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
buffer << chunk
|
|
215
|
+
remaining -= chunk.bytesize
|
|
216
|
+
end
|
|
217
|
+
buffer
|
|
218
|
+
end
|
|
219
|
+
|
|
220
|
+
def write_all(bytes)
|
|
221
|
+
written = 0
|
|
222
|
+
total = bytes.bytesize
|
|
223
|
+
while written < total
|
|
224
|
+
written += @stdin.write(bytes.byteslice(written, total - written))
|
|
225
|
+
end
|
|
226
|
+
end
|
|
227
|
+
end
|
|
228
|
+
end
|
|
229
|
+
end
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
require "net/http"
|
|
2
|
+
require "openssl"
|
|
3
|
+
require "uri"
|
|
4
|
+
|
|
5
|
+
module InstantRecord
|
|
6
|
+
module Mcp
|
|
7
|
+
# Answers the compiled native host's `exchange` requests ("METHOD URL\nBODY")
|
|
8
|
+
# over HTTP/HTTPS (or an injected Rack/test adapter) with configurable
|
|
9
|
+
# token, cookie/session, custom header, and scope-parameter auth.
|
|
10
|
+
#
|
|
11
|
+
# Returns "STATUS\nBODY" on HTTP responses, or "0\n" on network failures or
|
|
12
|
+
# offline mode — matching compiled/pipeline/native/instant_record_native.h.
|
|
13
|
+
class HttpExchange
|
|
14
|
+
OFFLINE_REPLY = "0\n".freeze
|
|
15
|
+
DEFAULT_TIMEOUT = 10
|
|
16
|
+
|
|
17
|
+
attr_reader :token, :cookie, :headers, :scope, :timeout, :trace
|
|
18
|
+
attr_accessor :offline
|
|
19
|
+
|
|
20
|
+
def initialize(
|
|
21
|
+
token: nil,
|
|
22
|
+
cookie: nil,
|
|
23
|
+
headers: {},
|
|
24
|
+
scope: nil,
|
|
25
|
+
offline: false,
|
|
26
|
+
timeout: DEFAULT_TIMEOUT,
|
|
27
|
+
persist_cookies: true,
|
|
28
|
+
adapter: nil
|
|
29
|
+
)
|
|
30
|
+
@token = blank_to_nil(token)
|
|
31
|
+
@cookie = blank_to_nil(cookie)
|
|
32
|
+
@headers = normalize_headers(headers)
|
|
33
|
+
@scope = blank_to_nil(scope)
|
|
34
|
+
@offline = !!offline
|
|
35
|
+
@timeout = (timeout || DEFAULT_TIMEOUT).to_f
|
|
36
|
+
@persist_cookies = !!persist_cookies
|
|
37
|
+
@adapter = adapter
|
|
38
|
+
@cookie_jar = parse_cookie_header(@cookie)
|
|
39
|
+
@trace = []
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
def offline?
|
|
43
|
+
@offline
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def reset_trace!
|
|
47
|
+
@trace = []
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
def any_offline?
|
|
51
|
+
@trace.any? { |entry| entry[:status] == 0 }
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def last_error_status
|
|
55
|
+
@trace.reverse_each.find { |entry| entry[:status] && entry[:status] >= 400 }&.dig(:status)
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def last_status
|
|
59
|
+
@trace.last&.dig(:status)
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
def call(raw_request)
|
|
63
|
+
return record_offline(nil, nil, "offline mode") if offline?
|
|
64
|
+
|
|
65
|
+
head, body = raw_request.to_s.split("\n", 2)
|
|
66
|
+
verb, raw_url = head.to_s.split(" ", 2)
|
|
67
|
+
return record_offline(verb, raw_url, "invalid exchange request") if verb.nil? || raw_url.nil? || raw_url.empty?
|
|
68
|
+
|
|
69
|
+
uri = prepare_uri(raw_url)
|
|
70
|
+
return record_offline(verb, raw_url, "invalid URL") unless uri && uri.scheme
|
|
71
|
+
|
|
72
|
+
req_headers = build_headers(verb, body.to_s)
|
|
73
|
+
status, response_body, response_headers =
|
|
74
|
+
if @adapter
|
|
75
|
+
perform_adapter(verb, uri, req_headers, body.to_s)
|
|
76
|
+
else
|
|
77
|
+
perform_http(verb, uri, req_headers, body.to_s)
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
absorb_cookies(response_headers) if @persist_cookies && response_headers
|
|
81
|
+
@trace << { method: verb, url: uri.to_s, status: status.to_i, error: nil }
|
|
82
|
+
"#{status.to_i}\n#{response_body}"
|
|
83
|
+
rescue URI::InvalidURIError, SocketError, SystemCallError, Timeout::Error,
|
|
84
|
+
IOError, EOFError, OpenSSL::SSL::SSLError, Net::HTTPError => e
|
|
85
|
+
record_offline(verb, raw_url, e.message)
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
# Expose effective Cookie header (initial cookie merged with any Set-Cookie).
|
|
89
|
+
def current_cookie_header
|
|
90
|
+
return nil if @cookie_jar.empty?
|
|
91
|
+
|
|
92
|
+
@cookie_jar.map { |name, value| "#{name}=#{value}" }.join("; ")
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
private
|
|
96
|
+
|
|
97
|
+
def prepare_uri(raw_url)
|
|
98
|
+
uri = URI.parse(raw_url.to_s.strip)
|
|
99
|
+
return nil unless uri.is_a?(URI::HTTP) || uri.is_a?(URI::HTTPS)
|
|
100
|
+
|
|
101
|
+
if @scope
|
|
102
|
+
params = URI.decode_www_form(uri.query.to_s)
|
|
103
|
+
unless params.any? { |key, _| key == "scope" }
|
|
104
|
+
params << ["scope", @scope]
|
|
105
|
+
uri.query = URI.encode_www_form(params)
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
uri
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
def build_headers(verb, _body)
|
|
112
|
+
built = {}
|
|
113
|
+
@headers.each { |key, value| built[key] = value }
|
|
114
|
+
|
|
115
|
+
if @token && !header_present?(built, "authorization")
|
|
116
|
+
built["Authorization"] = "Bearer #{@token}"
|
|
117
|
+
end
|
|
118
|
+
|
|
119
|
+
cookie_str = current_cookie_header
|
|
120
|
+
if cookie_str && !header_present?(built, "cookie")
|
|
121
|
+
built["Cookie"] = cookie_str
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
if verb.upcase != "GET" && verb.upcase != "HEAD" && !header_present?(built, "content-type")
|
|
125
|
+
built["Content-Type"] = "application/json"
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
built
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
def perform_adapter(verb, uri, req_headers, body)
|
|
132
|
+
result = @adapter.call(verb.upcase, uri, req_headers, body)
|
|
133
|
+
if result.is_a?(String)
|
|
134
|
+
status_line, res_body = result.split("\n", 2)
|
|
135
|
+
[status_line.to_i, res_body.to_s, nil]
|
|
136
|
+
else
|
|
137
|
+
status, res_body, res_headers = result
|
|
138
|
+
[status.to_i, res_body.to_s, res_headers]
|
|
139
|
+
end
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
def perform_http(verb, uri, req_headers, body)
|
|
143
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
|
144
|
+
http.use_ssl = uri.scheme == "https"
|
|
145
|
+
http.open_timeout = @timeout
|
|
146
|
+
http.read_timeout = @timeout
|
|
147
|
+
|
|
148
|
+
request_class =
|
|
149
|
+
case verb.upcase
|
|
150
|
+
when "GET" then Net::HTTP::Get
|
|
151
|
+
when "POST" then Net::HTTP::Post
|
|
152
|
+
when "PUT" then Net::HTTP::Put
|
|
153
|
+
when "PATCH" then Net::HTTP::Patch
|
|
154
|
+
when "DELETE" then Net::HTTP::Delete
|
|
155
|
+
when "HEAD" then Net::HTTP::Head
|
|
156
|
+
else raise ArgumentError, "Unsupported HTTP verb: #{verb}"
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
req = request_class.new(uri.request_uri)
|
|
160
|
+
req_headers.each { |key, value| req[key] = value }
|
|
161
|
+
req.body = body unless verb.upcase == "GET" || verb.upcase == "HEAD"
|
|
162
|
+
|
|
163
|
+
res = http.request(req)
|
|
164
|
+
set_cookies = res.get_fields("set-cookie")
|
|
165
|
+
[res.code.to_i, res.body.to_s, set_cookies ? { "set-cookie" => set_cookies } : nil]
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
def absorb_cookies(response_headers)
|
|
169
|
+
raw = response_headers.each_with_object([]) do |(key, value), acc|
|
|
170
|
+
next unless key.to_s.casecmp?("set-cookie")
|
|
171
|
+
|
|
172
|
+
Array(value).each do |entry|
|
|
173
|
+
entry.to_s.split("\n").each { |line| acc << line }
|
|
174
|
+
end
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
raw.each do |line|
|
|
178
|
+
pair, attrs = line.split(";", 2)
|
|
179
|
+
pair = pair.to_s.strip
|
|
180
|
+
next unless pair.include?("=")
|
|
181
|
+
|
|
182
|
+
name, value = pair.split("=", 2)
|
|
183
|
+
next if name.empty?
|
|
184
|
+
|
|
185
|
+
if attrs.to_s.match?(/\bmax-age\s*=\s*0\b/i)
|
|
186
|
+
@cookie_jar.delete(name)
|
|
187
|
+
else
|
|
188
|
+
@cookie_jar[name] = value
|
|
189
|
+
end
|
|
190
|
+
end
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
def parse_cookie_header(header)
|
|
194
|
+
jar = {}
|
|
195
|
+
return jar if header.nil? || header.empty?
|
|
196
|
+
|
|
197
|
+
header.split(";").each do |segment|
|
|
198
|
+
pair = segment.strip
|
|
199
|
+
next unless pair.include?("=")
|
|
200
|
+
|
|
201
|
+
name, value = pair.split("=", 2)
|
|
202
|
+
jar[name.strip] = value.to_s.strip unless name.strip.empty?
|
|
203
|
+
end
|
|
204
|
+
jar
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
def normalize_headers(headers)
|
|
208
|
+
return {} unless headers.is_a?(Hash)
|
|
209
|
+
|
|
210
|
+
headers.each_with_object({}) do |(key, value), acc|
|
|
211
|
+
name = key.to_s.strip
|
|
212
|
+
next if name.empty? || value.nil?
|
|
213
|
+
|
|
214
|
+
acc[name] = value.to_s
|
|
215
|
+
end
|
|
216
|
+
end
|
|
217
|
+
|
|
218
|
+
def header_present?(hash, downcased_name)
|
|
219
|
+
hash.keys.any? { |key| key.to_s.downcase == downcased_name }
|
|
220
|
+
end
|
|
221
|
+
|
|
222
|
+
def blank_to_nil(value)
|
|
223
|
+
str = value.to_s.strip
|
|
224
|
+
str.empty? ? nil : str
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
def record_offline(verb, url, error)
|
|
228
|
+
@trace << { method: verb, url: url, status: 0, error: error }
|
|
229
|
+
OFFLINE_REPLY
|
|
230
|
+
end
|
|
231
|
+
end
|
|
232
|
+
end
|
|
233
|
+
end
|