instant_record 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +58 -0
  3. data/README.md +267 -61
  4. data/app/controllers/instant_record/bootstraps_controller.rb +39 -12
  5. data/app/controllers/instant_record/events_controller.rb +58 -6
  6. data/app/controllers/instant_record/files_controller.rb +116 -0
  7. data/app/controllers/instant_record/mutations_controller.rb +84 -5
  8. data/app/controllers/instant_record/native_screens_controller.rb +60 -0
  9. data/app/controllers/instant_record/records_controller.rb +86 -8
  10. data/app/controllers/instant_record/shells_controller.rb +64 -0
  11. data/app/controllers/instant_record/sync_notices_controller.rb +81 -0
  12. data/app/helpers/instant_record/sync_notices_helper.rb +41 -0
  13. data/app/jobs/instant_record/shell_build_job.rb +16 -0
  14. data/app/models/instant_record/change.rb +36 -3
  15. data/app/models/instant_record/mutation_applier.rb +633 -50
  16. data/app/views/instant_record/sync_notices/_notices.html.erb +63 -0
  17. data/compiled/README.md +272 -0
  18. data/compiled/pipeline/browser_migrations.rb +18 -0
  19. data/compiled/pipeline/build.rb +13 -0
  20. data/compiled/pipeline/build_native.rb +14 -0
  21. data/compiled/pipeline/native/host.c +78 -0
  22. data/compiled/pipeline/native/instant_record_native.h +57 -0
  23. data/compiled/pipeline/native_shim.c +149 -0
  24. data/compiled/pipeline/reactor_shim.c +66 -0
  25. data/compiled/pipeline/sqlite/rh_shim.c +5 -0
  26. data/compiled/pipeline/sqlite_release.rb +43 -0
  27. data/compiled/toolchain.env.example +22 -0
  28. data/compiled/web/index.html +20 -0
  29. data/compiled/web/package-lock.json +884 -0
  30. data/compiled/web/package.json +17 -0
  31. data/compiled/web/src/app-host-core.js +556 -0
  32. data/compiled/web/src/app-host.js +16 -0
  33. data/compiled/web/src/branch-manager.js +140 -0
  34. data/compiled/web/src/branch-preview.js +397 -0
  35. data/compiled/web/src/changes.js +191 -0
  36. data/compiled/web/src/faults.js +172 -0
  37. data/compiled/web/src/flight-recorder.js +347 -0
  38. data/compiled/web/src/history-fill.js +68 -0
  39. data/compiled/web/src/http-headers.js +100 -0
  40. data/compiled/web/src/leader-election.js +705 -0
  41. data/compiled/web/src/main.js +608 -0
  42. data/compiled/web/src/manifest.js +112 -0
  43. data/compiled/web/src/opfs-wasi-core.js +109 -0
  44. data/compiled/web/src/opfs-wasi-file.js +8 -0
  45. data/compiled/web/src/reactor-runtime.js +1692 -0
  46. data/compiled/web/src/redactor.js +518 -0
  47. data/compiled/web/src/release-updates.js +48 -0
  48. data/compiled/web/src/replay.js +338 -0
  49. data/compiled/web/src/schema-recovery.js +204 -0
  50. data/compiled/web/src/server-request.js +68 -0
  51. data/compiled/web/src/sha256.js +98 -0
  52. data/compiled/web/src/shell.js +52 -0
  53. data/compiled/web/src/snapshot-store.js +38 -0
  54. data/compiled/web/src/sqlite-redactor.js +111 -0
  55. data/compiled/web/src/storage-backend.js +159 -0
  56. data/compiled/web/src/stream-leader.js +675 -0
  57. data/compiled/web/src/sync-context.js +91 -0
  58. data/compiled/web/src/sync-drain.js +104 -0
  59. data/compiled/web/src/sync-schedule.js +9 -0
  60. data/compiled/web/src/wasi-minimal.js +275 -0
  61. data/compiled/web/src/worker.js +39 -0
  62. data/compiled/web/vite.config.js +27 -0
  63. data/config/routes.rb +25 -0
  64. data/db/migrate/20261119000201_add_scope_to_instant_record_changes.rb +7 -0
  65. data/db/migrate/20261121000001_create_instant_record_sync_notices.rb +21 -0
  66. data/db/migrate/20261121000101_add_partition_to_instant_record_changes.rb +8 -0
  67. data/db/migrate/20261121230300_add_delay_line_to_instant_record_outbox.rb +10 -0
  68. data/exe/instant_record_mcp +6 -0
  69. data/frontend/LiveList.js +67 -0
  70. data/frontend/chord.js +79 -0
  71. data/frontend/file.js +65 -0
  72. data/frontend/files.js +738 -0
  73. data/frontend/focus.js +10 -0
  74. data/frontend/held.js +192 -0
  75. data/frontend/http.js +76 -0
  76. data/frontend/index.js +53 -0
  77. data/frontend/keyboard.js +56 -0
  78. data/frontend/live.js +298 -0
  79. data/frontend/notices.js +118 -0
  80. data/frontend/package.json +15 -0
  81. data/frontend/range.js +10 -0
  82. data/frontend/selection.js +47 -0
  83. data/frontend/shortcuts.js +25 -0
  84. data/frontend/sync-notices.js +130 -0
  85. data/frontend/undo.js +48 -0
  86. data/frontend/window.js +181 -0
  87. data/lib/generators/instant_record/install/install_generator.rb +18 -30
  88. data/lib/generators/instant_record/install/templates/instant_record.rb +34 -0
  89. data/lib/generators/instant_record/ios/ios_generator.rb +71 -0
  90. data/lib/generators/instant_record/ios/templates/App.swift.tt +35 -0
  91. data/lib/generators/instant_record/ios/templates/Info.plist +11 -0
  92. data/lib/generators/instant_record/ios/templates/LibraryEngine.swift +30 -0
  93. data/lib/instant_record/branch/sqlite_store.rb +142 -0
  94. data/lib/instant_record/branch.rb +388 -0
  95. data/lib/instant_record/client/notifier.rb +8 -12
  96. data/lib/instant_record/client/rebaser.rb +565 -0
  97. data/lib/instant_record/client/transport.rb +64 -42
  98. data/lib/instant_record/client.rb +1600 -169
  99. data/lib/instant_record/compiled_site.rb +85 -0
  100. data/lib/instant_record/compiler/app_stage.rb +212 -0
  101. data/lib/instant_record/compiler/ast_lowerer.rb +659 -0
  102. data/lib/instant_record/compiler/browser_migrations.rb +161 -0
  103. data/lib/instant_record/compiler/entry_builder.rb +832 -0
  104. data/lib/instant_record/compiler/fts5_smoke.rb +205 -0
  105. data/lib/instant_record/compiler/gem_vendor.rb +194 -0
  106. data/lib/instant_record/compiler/host_adapters.rb +506 -0
  107. data/lib/instant_record/compiler/kotlin_codegen.rb +209 -0
  108. data/lib/instant_record/compiler/manifest.rb +178 -0
  109. data/lib/instant_record/compiler/native_build.rb +586 -0
  110. data/lib/instant_record/compiler/native_contracts.rb +338 -0
  111. data/lib/instant_record/compiler/path_scrubber.rb +31 -0
  112. data/lib/instant_record/compiler/reachability_tracer.rb +1188 -0
  113. data/lib/instant_record/compiler/route_analyzer.rb +623 -0
  114. data/lib/instant_record/compiler/runner.rb +42 -0
  115. data/lib/instant_record/compiler/schema_lock.rb +606 -0
  116. data/lib/instant_record/compiler/source_pages.rb +77 -0
  117. data/lib/instant_record/compiler/static_linter.rb +770 -0
  118. data/lib/instant_record/compiler/swift_codegen.rb +341 -0
  119. data/lib/instant_record/compiler/toolchain.rb +219 -0
  120. data/lib/instant_record/compiler/wasm_build.rb +704 -0
  121. data/lib/instant_record/compiler/wasm_tree.rb +518 -0
  122. data/lib/instant_record/compiler.rb +277 -0
  123. data/lib/instant_record/configuration.rb +104 -0
  124. data/lib/instant_record/engine.rb +68 -18
  125. data/lib/instant_record/file_store.rb +162 -0
  126. data/lib/instant_record/files.rb +92 -0
  127. data/lib/instant_record/hlc.rb +387 -0
  128. data/lib/instant_record/host.rb +66 -0
  129. data/lib/instant_record/inertia/renderer.rb +52 -0
  130. data/lib/instant_record/inertia.rb +222 -0
  131. data/lib/instant_record/mcp/cli.rb +319 -0
  132. data/lib/instant_record/mcp/host_process.rb +229 -0
  133. data/lib/instant_record/mcp/http_exchange.rb +233 -0
  134. data/lib/instant_record/mcp/replica.rb +556 -0
  135. data/lib/instant_record/mcp/runtime.rb +406 -0
  136. data/lib/instant_record/mcp/server.rb +429 -0
  137. data/lib/instant_record/mcp.rb +47 -0
  138. data/lib/instant_record/native/contract.rb +367 -0
  139. data/lib/instant_record/native/node.rb +125 -0
  140. data/lib/instant_record/native/screen.rb +366 -0
  141. data/lib/instant_record/native/xcode_project.rb +344 -0
  142. data/lib/instant_record/native.rb +41 -0
  143. data/lib/instant_record/outbox_mutation.rb +81 -9
  144. data/lib/instant_record/outbox_upcaster.rb +161 -0
  145. data/lib/instant_record/read_tracker.rb +610 -0
  146. data/lib/instant_record/routing.rb +33 -0
  147. data/lib/instant_record/runtime_scoped.rb +4 -0
  148. data/lib/instant_record/shell.rb +486 -0
  149. data/lib/instant_record/sync_actions.rb +800 -0
  150. data/lib/instant_record/sync_metadata.rb +17 -2
  151. data/lib/instant_record/sync_notice.rb +234 -0
  152. data/lib/instant_record/sync_partition.rb +63 -0
  153. data/lib/instant_record/sync_scope.rb +300 -0
  154. data/lib/instant_record/sync_shape.rb +102 -0
  155. data/lib/instant_record/sync_window.rb +92 -15
  156. data/lib/instant_record/syncable.rb +313 -17
  157. data/lib/instant_record/testing/authoritative_server.rb +547 -0
  158. data/lib/instant_record/testing/chaos_simulator.rb +429 -0
  159. data/lib/instant_record/testing/cruby_host_bridge.rb +370 -0
  160. data/lib/instant_record/testing/fault_network.rb +140 -0
  161. data/lib/instant_record/testing/parity_suite.rb +435 -0
  162. data/lib/instant_record/testing/runtimes/base.rb +184 -0
  163. data/lib/instant_record/testing/runtimes/cruby_runtime.rb +255 -0
  164. data/lib/instant_record/testing/runtimes/native_runtime.rb +346 -0
  165. data/lib/instant_record/testing/runtimes/wasm_runtime.rb +371 -0
  166. data/lib/instant_record/testing/wasm_host_bridge.mjs +240 -0
  167. data/lib/instant_record/testing.rb +333 -0
  168. data/lib/instant_record/trace/redactor.rb +278 -0
  169. data/lib/instant_record/trace/replayer.rb +126 -0
  170. data/lib/instant_record/trace/schema_extractor.rb +37 -0
  171. data/lib/instant_record/trace.rb +22 -0
  172. data/lib/instant_record/version.rb +1 -1
  173. data/lib/instant_record.rb +107 -37
  174. data/lib/tasks/instant_record.rake +299 -47
  175. data/native/ios/InstantRecordNative/Package.swift +12 -0
  176. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/AppHost.swift +706 -0
  177. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Engine.swift +64 -0
  178. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/FileStore.swift +1048 -0
  179. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/HTTPEngine.swift +36 -0
  180. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Icons.swift +19 -0
  181. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Node.swift +64 -0
  182. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/ScreenView.swift +481 -0
  183. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Screens.swift +94 -0
  184. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/StreamClient.swift +74 -0
  185. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncNotice.swift +282 -0
  186. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/SyncSchedule.swift +153 -0
  187. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Theme.swift +140 -0
  188. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/Transport.swift +108 -0
  189. data/native/ios/InstantRecordNative/Sources/InstantRecordNative/TypedContracts.swift +237 -0
  190. data/native/ios/README.md +341 -0
  191. data/sig/instant_record/inertia.rbs +47 -0
  192. data/sig/instant_record/native.rbs +38 -0
  193. metadata +194 -18
  194. data/lib/generators/instant_record/install/templates/database.js +0 -32
  195. data/lib/generators/instant_record/install/templates/index.html +0 -69
  196. data/lib/generators/instant_record/install/templates/rails.sw.js +0 -750
  197. data/lib/instant_record/local_schema.rb +0 -75
  198. data/lib/instant_record/pglite_compat.rb +0 -40
@@ -0,0 +1,34 @@
1
+ # InstantRecord configuration.
2
+ # See README.md and compiled/README.md for full details.
3
+
4
+ InstantRecord.configure do |config|
5
+ # Identify who is making each sync request (for models declaring `sync_scope`
6
+ # or `syncable_to` / `writable_by`). The default trusts a `scope` query param;
7
+ # apps with authentication should read the user from the session instead:
8
+ #
9
+ # config.scope_from = ->(request) { User.find_by(id: request.session[:user_id]) }
10
+
11
+ # Where the server stores files attached to `sync_file` models.
12
+ # Defaults to Rails.root.join("storage/instant_record").
13
+ #
14
+ # config.file_store = InstantRecord::FileStore.new(Rails.root.join("storage/instant_record"))
15
+
16
+ # Default maximum file size in bytes for `sync_file` models without their own `max_size:`.
17
+ # Defaults to 2 GiB (InstantRecord::Files::MAX_SIZE).
18
+ #
19
+ # config.max_file_size = 500 * 1024 * 1024
20
+ end
21
+
22
+ # Optional: restrict syncing to an explicit allowlist of models.
23
+ # Without this, every model that includes `InstantRecord::Syncable` syncs.
24
+ #
25
+ # InstantRecord.sync(Issue, Note)
26
+
27
+ # Railtie options (set in config/application.rb or config/environments/*.rb):
28
+ #
29
+ # config.instant_record.mount_path = "/instant_record" # or false to mount manually
30
+ # config.instant_record.compiled_host = "app.example.com"
31
+ # config.instant_record.build_on_precompile = :compiled # publish during assets:precompile
32
+ # config.instant_record.native_dev = true # serve app/screens over HTTP in development
33
+ # config.instant_record.sse_window_seconds = 25.0 # raise under Falcon (e.g. 600.0)
34
+ # config.instant_record.sse_heartbeat_seconds = 15.0
@@ -0,0 +1,71 @@
1
+ require "rails/generators"
2
+ require "instant_record/native/xcode_project"
3
+
4
+ module InstantRecord
5
+ module Generators
6
+ # Writes an iPhone app for this Rails app's screens (app/screens):
7
+ #
8
+ # bin/rails generate instant_record:ios Shop --screen catalog
9
+ #
10
+ # The app is a thin Xcode project in native/ios/<Name>. It links the
11
+ # libraries `bin/rails instant_record:native[iphonesimulator]` builds and
12
+ # the renderer package that ships with the gem.
13
+ class IosGenerator < Rails::Generators::Base
14
+ source_root File.expand_path("templates", __dir__)
15
+
16
+ argument :app_name, type: :string, banner: "Name"
17
+ class_option :screen, type: :string, required: true, desc: "The first screen, as app/screens names it (catalog for CatalogScreen)"
18
+ class_option :server, type: :string, default: "http://localhost:3000", desc: "Where the Rails app answers"
19
+ class_option :bundle_id, type: :string, desc: "The app's bundle identifier (com.example.<Name>)"
20
+
21
+ def check_name
22
+ raise Thor::Error, "Name the app with letters and digits, starting with a capital: Shop" unless app_name.match?(/\A[A-Z][A-Za-z0-9]*\z/)
23
+ end
24
+
25
+ def write_app
26
+ template "App.swift.tt", "#{folder}/#{app_name}/#{app_name}App.swift"
27
+ copy_file "LibraryEngine.swift", "#{folder}/#{app_name}/LibraryEngine.swift"
28
+ copy_file "Info.plist", "#{folder}/#{app_name}/Info.plist"
29
+ create_file "#{folder}/#{app_name}/#{app_name}-Bridging-Header.h", %(#include "instant_record_native.h"\n)
30
+ end
31
+
32
+ # The project is written from the files now in the folder. Run this
33
+ # generator again, with --force, after adding a Swift file.
34
+ def write_project
35
+ return if options[:pretend]
36
+ create_file "#{folder}/#{app_name}.xcodeproj/project.pbxproj", project.pbxproj
37
+ create_file "#{folder}/#{app_name}.xcodeproj/xcshareddata/xcschemes/#{app_name}.xcscheme", project.scheme
38
+ end
39
+
40
+ def show_next_steps
41
+ say <<~MSG
42
+ Build the libraries, then the app:
43
+
44
+ bin/rails "instant_record:native[iphonesimulator]"
45
+ xcodebuild -project #{folder}/#{app_name}.xcodeproj -scheme #{app_name} -destination 'platform=iOS Simulator,name=iPhone 17' build
46
+
47
+ See the gem's native/ios/README.md.
48
+ MSG
49
+ end
50
+
51
+ private
52
+
53
+ def folder = "native/ios/#{app_name}"
54
+
55
+ def mount_path = Rails.application.config.instant_record.mount_path || InstantRecord::DEFAULT_MOUNT_PATH
56
+
57
+ def project
58
+ gem_root = Pathname(__dir__).join("../../../..").realpath
59
+ here = Pathname(destination_root).join(folder)
60
+ FileUtils.mkdir_p(here)
61
+ from = ->(path) { Pathname(path).relative_path_from(here.realpath).to_s }
62
+ InstantRecord::Native::XcodeProject.new(
63
+ folder: here, name: app_name, bundle_id: options[:bundle_id] || "com.example.#{app_name}",
64
+ package: from.(gem_root.join("native/ios/InstantRecordNative")),
65
+ headers: from.(gem_root.join("compiled/pipeline/native")),
66
+ libraries: from.(Pathname(destination_root).realpath.join("tmp/instant_record/compiled/.build-native"))
67
+ )
68
+ end
69
+ end
70
+ end
71
+ end
@@ -0,0 +1,35 @@
1
+ import InstantRecordNative
2
+ import SwiftUI
3
+
4
+ /// <%= app_name %> on iPhone. Its screens are Ruby, in app/screens. This file
5
+ /// names the first one and says where the app keeps its data and syncs.
6
+ ///
7
+ /// Launch arguments:
8
+ /// -server <%= options[:server] %> the Rails app
9
+ /// -dev YES ask Rails for each screen: no rebuild after an edit
10
+ @main
11
+ struct <%= app_name %>App: App {
12
+ @StateObject private var host: AppHost
13
+
14
+ init() {
15
+ // Views written in SwiftUI that a screen asks for by name
16
+ // (`swift "Name" do ... end`) are registered here:
17
+ // views.register("Name") { props, actions in NameView(props: props, actions: actions) }
18
+ let views = Screens()
19
+
20
+ let defaults = UserDefaults.standard
21
+ let server = defaults.string(forKey: "server") ?? "<%= options[:server] %>"
22
+ let folder = URL.applicationSupportDirectory
23
+ try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
24
+ let engine: Engine = defaults.bool(forKey: "dev") ? HTTPEngine(server: server + "<%= mount_path %>") : LibraryEngine()
25
+ let host = AppHost(engine: engine, root: Route("<%= options[:screen] %>"), views: views, store: { _ in
26
+ AppHost.Store(database: folder.appending(path: "app.sqlite3").path, endpoint: server + "<%= mount_path %>")
27
+ })
28
+ host.start()
29
+ _host = StateObject(wrappedValue: host)
30
+ }
31
+
32
+ var body: some Scene {
33
+ WindowGroup { AppView(host: host) }
34
+ }
35
+ }
@@ -0,0 +1,11 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0">
4
+ <dict>
5
+ <key>NSAppTransportSecurity</key>
6
+ <dict>
7
+ <key>NSAllowsLocalNetworking</key>
8
+ <true/>
9
+ </dict>
10
+ </dict>
11
+ </plist>
@@ -0,0 +1,30 @@
1
+ import Foundation
2
+ import InstantRecordNative
3
+
4
+ /// The compiled app's C library (instant_record_native.h) as the host's engine.
5
+ final class LibraryEngine: Engine {
6
+ // The library hands back one request at a time, always on the engine's
7
+ // thread, so one answer is kept alive at a time.
8
+ private var answer: (String) -> String = { _ in "0\n" }
9
+ private var response: UnsafeMutablePointer<CChar>?
10
+
11
+ func onExchange(_ answer: @escaping (String) -> String) {
12
+ self.answer = answer
13
+ // The library takes a C function, which cannot capture. This engine
14
+ // reaches it as the context the library passes back.
15
+ ir_set_exchange({ request, context in
16
+ guard let context else { return nil }
17
+ let engine = Unmanaged<LibraryEngine>.fromOpaque(context).takeUnretainedValue()
18
+ free(engine.response)
19
+ engine.response = strdup(engine.answer(request.map { String(cString: $0) } ?? ""))
20
+ return UnsafePointer(engine.response)
21
+ }, Unmanaged.passUnretained(self).toOpaque())
22
+ }
23
+
24
+ func boot(database: String) -> Bool { ir_boot(database) == 0 }
25
+ func open(database: String) -> Bool { ir_open(database) == 0 }
26
+ func call(_ entry: String, _ input: String) -> String? { ir_call(entry, input).map { String(cString: $0) } }
27
+ func notice() -> String { String(cString: ir_notice()) }
28
+ func reads() -> String { String(cString: ir_reads()) }
29
+ func error() -> String { String(cString: ir_error()) }
30
+ }
@@ -0,0 +1,142 @@
1
+ require "fileutils"
2
+ require "securerandom"
3
+ require "tmpdir"
4
+
5
+ module InstantRecord
6
+ class Branch
7
+ # CRuby SQLite copy-on-write snapshot & connection switcher.
8
+ #
9
+ # Uses SQLite's online backup API (SQLite3::Backup) so both file-backed
10
+ # databases and `:memory:` databases snapshot transactionally without
11
+ # disturbing WAL state or concurrent readers.
12
+ #
13
+ # For file-backed databases, `main` stays at its original path on disk so
14
+ # external connections or `branch.on_main` can continue applying remote
15
+ # deltas while the staging branch is open; `restore_main!` reconnects
16
+ # directly to that live `main` file without overwriting it.
17
+ class SqliteStore
18
+ attr_reader :branch_path
19
+
20
+ def self.fork!(name:, directory: nil)
21
+ config = ActiveRecord::Base.connection_db_config.configuration_hash.dup
22
+ adapter = config[:adapter].to_s
23
+ unless adapter.include?("sqlite")
24
+ raise Branch::Error, "Staging branches require a local SQLite database (got #{adapter.inspect})"
25
+ end
26
+
27
+ db_spec = config[:database].to_s
28
+ memory = db_spec == ":memory:" || db_spec.empty?
29
+ token = SecureRandom.hex(8)
30
+ safe_name = name.to_s.gsub(/[^a-zA-Z0-9_-]+/, "-").slice(0, 32)
31
+ safe_name = "staging" if safe_name.empty?
32
+
33
+ work_dir = directory || (memory ? Dir.mktmpdir("instant_record_branch_") : File.dirname(File.expand_path(db_spec)))
34
+ FileUtils.mkdir_p(work_dir)
35
+ owns_dir = memory && directory.nil?
36
+
37
+ branch_path = File.join(work_dir, ".ir-branch-#{safe_name}-#{token}.sqlite3")
38
+ main_backup_path = memory ? File.join(work_dir, ".ir-main-#{token}.sqlite3") : nil
39
+
40
+ src_raw = ActiveRecord::Base.connection.raw_connection
41
+ if memory
42
+ backup_database(src_raw, main_backup_path)
43
+ FileUtils.cp(main_backup_path, branch_path)
44
+ else
45
+ backup_database(src_raw, branch_path)
46
+ end
47
+
48
+ store = new(
49
+ main_config: config,
50
+ branch_path: branch_path,
51
+ main_backup_path: main_backup_path,
52
+ owns_dir: owns_dir ? work_dir : nil
53
+ )
54
+ store.activate_branch!
55
+ store
56
+ end
57
+
58
+ def self.backup_database(source_db, destination_path)
59
+ require "sqlite3"
60
+ dest = SQLite3::Database.new(destination_path)
61
+ begin
62
+ backup = SQLite3::Backup.new(dest, "main", source_db, "main")
63
+ begin
64
+ backup.step(-1)
65
+ ensure
66
+ backup.finish
67
+ end
68
+ ensure
69
+ dest.close
70
+ end
71
+ end
72
+
73
+ def self.restore_into_memory(source_path, memory_db)
74
+ require "sqlite3"
75
+ src = SQLite3::Database.new(source_path)
76
+ begin
77
+ backup = SQLite3::Backup.new(memory_db, "main", src, "main")
78
+ begin
79
+ backup.step(-1)
80
+ ensure
81
+ backup.finish
82
+ end
83
+ ensure
84
+ src.close
85
+ end
86
+ end
87
+
88
+ def initialize(main_config:, branch_path:, main_backup_path:, owns_dir:)
89
+ @main_config = main_config
90
+ @branch_path = branch_path
91
+ @main_backup_path = main_backup_path
92
+ @owns_dir = owns_dir
93
+ end
94
+
95
+ def activate_branch!
96
+ reconnect_to(@main_config.merge(database: @branch_path))
97
+ end
98
+
99
+ def with_main
100
+ target_config = @main_backup_path ? @main_config.merge(database: @main_backup_path) : @main_config
101
+ reconnect_to(target_config)
102
+ yield
103
+ ensure
104
+ activate_branch!
105
+ end
106
+
107
+ def restore_main!
108
+ if @main_backup_path
109
+ reconnect_to(@main_config)
110
+ self.class.restore_into_memory(@main_backup_path, ActiveRecord::Base.connection.raw_connection)
111
+ else
112
+ reconnect_to(@main_config)
113
+ end
114
+ end
115
+
116
+ def cleanup!
117
+ remove_sqlite_files(@branch_path)
118
+ remove_sqlite_files(@main_backup_path) if @main_backup_path
119
+ FileUtils.rm_rf(@owns_dir) if @owns_dir && File.directory?(@owns_dir)
120
+ end
121
+
122
+ private
123
+
124
+ def reconnect_to(config)
125
+ ActiveRecord::Base.connection_handler.clear_all_connections!
126
+ ActiveRecord::Base.establish_connection(config)
127
+ ActiveRecord::Base.connection
128
+ end
129
+
130
+ def remove_sqlite_files(base_path)
131
+ return unless base_path
132
+
133
+ ["", "-wal", "-shm", "-journal"].each do |suffix|
134
+ file = "#{base_path}#{suffix}"
135
+ FileUtils.rm_f(file) if File.exist?(file)
136
+ end
137
+ end
138
+ end
139
+
140
+ self.store_class = SqliteStore
141
+ end
142
+ end