litebucket 0.2.0-x86_64-linux
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 +7 -0
- data/README.md +100 -0
- data/lib/litebucket/durable_commits.rb +26 -0
- data/lib/litebucket/metrics_endpoint.rb +44 -0
- data/lib/litebucket/native/x86_64-linux/liblitebucket.so +0 -0
- data/lib/litebucket/railtie.rb +28 -0
- data/lib/litebucket/version.rb +3 -0
- data/lib/litebucket/write_forwarding_middleware.rb +305 -0
- data/lib/litebucket.rb +672 -0
- data/lib/puma/plugin/litebucket.rb +37 -0
- data/lib/tasks/litebucket.rake +52 -0
- metadata +88 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 4c4e4771f33f777e822fa48e1d425e23ee3a3d26673a5f11796a67fd55b8353c
|
|
4
|
+
data.tar.gz: 97f6662c2b56f23d995064eea556ed5db90c01d98f439978d448b0fcd7fb3e99
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 5a4fd75e4286e927a9667fe7ad53f6d6877d3bd84201d4502432e5a8cece1684c185718633983810f6ccaa905d90d6cd452d0ba594c0e8e26aa67d6b1c2ff261
|
|
7
|
+
data.tar.gz: 950de50116fedbc0b7d62be84e64379f0ad81426d8482a63fd6a65a1abfa6e2a50b501f52a22efb65d4db098e8cd4109da3793763ae0ba1c956e3304caeec816
|
data/README.md
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# `litebucket` (Ruby Gem + Rails Railtie)
|
|
2
|
+
|
|
3
|
+
Zero-sidecar Rails 8+ integration for S3, Cloudflare R2, and Laravel Cloud Object Storage SQLite (`liblitebucket.so` VFS) — Ruby 3.2–4.0+, x86_64 & ARM64 (`aarch64-linux`).
|
|
4
|
+
|
|
5
|
+
- **Docs:** [litebucket.dev](https://litebucket.dev)
|
|
6
|
+
- **Live Rails 8 Demo (Laravel Cloud ARM64 + R2):** [litebucket-rails-demo](https://litebucket-rails-demo-production-4vmbpk.laravel.cloud) ([source](https://github.com/cole-robertson/litebucket-rails-demo))
|
|
7
|
+
|
|
8
|
+
## Install
|
|
9
|
+
|
|
10
|
+
```ruby
|
|
11
|
+
gem "litebucket"
|
|
12
|
+
# Note: on Laravel Cloud with an attached R2 bucket, add `gem "aws-sdk-s3", require: false`
|
|
13
|
+
# to satisfy the platform's attached-bucket check with zero runtime memory overhead.
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
The built-in `Railtie` automatically:
|
|
17
|
+
1. Registers `liblitebucket.so` in `before_configuration` (before `db:prepare` / `db:migrate` and ActiveRecord pool boot).
|
|
18
|
+
2. Prepends `LiteBucket::WriteForwardingMiddleware` whenever `LITEBUCKET_ADVERTISE_ADDR` is set (horizontal multi-replica scaling with deterministic read-your-writes, HMAC-SHA256 loop protection, and SSRF validation).
|
|
19
|
+
3. Loads `bin/rails litebucket:*` operational Rake tasks and flushes staged writes + releases distributed write leases cleanly on `at_exit`.
|
|
20
|
+
|
|
21
|
+
## `config/database.yml` (1 Line — Including Rails 8 Solid\* DBs)
|
|
22
|
+
|
|
23
|
+
```yaml
|
|
24
|
+
production:
|
|
25
|
+
primary:
|
|
26
|
+
<<: *default
|
|
27
|
+
database: <%= LiteBucket.database_uri_from_env("myapp/primary") %>
|
|
28
|
+
queue:
|
|
29
|
+
<<: *default
|
|
30
|
+
database: <%= LiteBucket.queue_database_uri_from_env %>
|
|
31
|
+
migrations_paths: db/queue_migrate
|
|
32
|
+
cable:
|
|
33
|
+
<<: *default
|
|
34
|
+
database: <%= LiteBucket.cable_database_uri_from_env %>
|
|
35
|
+
migrations_paths: db/cable_migrate
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
For **multi-tenant Rails** (`activerecord-tenanted`):
|
|
39
|
+
|
|
40
|
+
```yaml
|
|
41
|
+
production:
|
|
42
|
+
adapter: sqlite3
|
|
43
|
+
tenanted: true
|
|
44
|
+
database: <%= LiteBucket.tenanted_database_uri_from_env("tenants/%{tenant}/main") %>
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## On-Demand `RPO = 0` Durability on Critical Writes & Models
|
|
48
|
+
|
|
49
|
+
```ruby
|
|
50
|
+
# Per-operation barrier (1 RTT, keeps write lease hot, skips flush on rollback):
|
|
51
|
+
LiteBucket.with_durable_commit do
|
|
52
|
+
order.update!(paid_at: Time.current)
|
|
53
|
+
LedgerEntry.create!(order: order, amount_cents: order.total_cents)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Or model-level concern:
|
|
57
|
+
class Order < ApplicationRecord
|
|
58
|
+
include LiteBucket::DurableCommits
|
|
59
|
+
end
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Built-In Puma Plugin (`config/puma.rb`)
|
|
63
|
+
|
|
64
|
+
```ruby
|
|
65
|
+
plugin :litebucket
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Automatically flushes staged writes, releases distributed write leases, and clears ActiveRecord pools in `before_fork` (safe for `WEB_CONCURRENCY > 1`) and drains cleanly on worker/server shutdown (`SIGTERM`).
|
|
69
|
+
|
|
70
|
+
## Built-In Rake Tasks & Prometheus `/metrics`
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
bin/rails litebucket:doctor # verifies R2/S3 credentials, If-None-Match 412, If-Match CAS, Range 206 & RTT
|
|
74
|
+
bin/rails litebucket:status # loaded binary, PRAGMA integrity_check, write owner, Prometheus metrics
|
|
75
|
+
bin/rails litebucket:verify # PRAGMA integrity_check
|
|
76
|
+
bin/rails litebucket:compact # snapshot compaction + LTX GC
|
|
77
|
+
bin/rails litebucket:flush # flush all staged writes & release write leases
|
|
78
|
+
bin/rails 'litebucket:shred[tenants/acme/main]' CONFIRM=1
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Mount Prometheus metrics in 1 line in `config/routes.rb`:
|
|
82
|
+
|
|
83
|
+
```ruby
|
|
84
|
+
mount LiteBucket::MetricsEndpoint => "/metrics"
|
|
85
|
+
# Or protected by Bearer token:
|
|
86
|
+
# mount LiteBucket::MetricsEndpoint.new(token: ENV["METRICS_TOKEN"]) => "/metrics"
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Tenant Lifecycle & Diagnostics Helpers
|
|
90
|
+
|
|
91
|
+
```ruby
|
|
92
|
+
LiteBucket.doctor # live S3/R2 CAS + Range self-test Hash
|
|
93
|
+
LiteBucket.last_error # actionable last VFS open/read error string
|
|
94
|
+
LiteBucket.prefix_exists?("tenants/acme/main") # 1-RTT existence check + Wave 1 prefetch
|
|
95
|
+
LiteBucket.tenant_exists?("acme") # sanitized `tenants/%{tenant}/main` variant
|
|
96
|
+
LiteBucket.shred_tenant!("acme") # GDPR-shred all LTX/snapshot/manifest objects
|
|
97
|
+
LiteBucket.flush! # flush active connection (keeps write lease hot)
|
|
98
|
+
LiteBucket.flush_all! # shutdown flush + immediate write-lease release
|
|
99
|
+
LiteBucket.prometheus_metrics # Prometheus exposition text
|
|
100
|
+
```
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
module LiteBucket
|
|
2
|
+
# ActiveRecord concern that guarantees `RPO = 0` S3/R2 durability on every committed
|
|
3
|
+
# create/update/destroy for critical models (e.g. `Order`, `Payment`, `User`) while keeping
|
|
4
|
+
# all other models at ~2 us `SyncMode::Batched` speed.
|
|
5
|
+
#
|
|
6
|
+
# Automatically skips flushing when a transaction rolls back, and keeps the active distributed
|
|
7
|
+
# write lease hot in RAM (1 RTT flush, no lease release/re-acquire).
|
|
8
|
+
#
|
|
9
|
+
# Usage:
|
|
10
|
+
# class Order < ApplicationRecord
|
|
11
|
+
# include LiteBucket::DurableCommits
|
|
12
|
+
# end
|
|
13
|
+
module DurableCommits
|
|
14
|
+
def self.included(base)
|
|
15
|
+
base.after_commit(:litebucket_flush_durable_commit) if base.respond_to?(:after_commit)
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
private
|
|
19
|
+
|
|
20
|
+
def litebucket_flush_durable_commit
|
|
21
|
+
return unless LiteBucket.loaded?
|
|
22
|
+
|
|
23
|
+
LiteBucket.flush!(self.class.connection)
|
|
24
|
+
end
|
|
25
|
+
end
|
|
26
|
+
end
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
require "openssl"
|
|
2
|
+
|
|
3
|
+
module LiteBucket
|
|
4
|
+
# Zero-dependency Rack endpoint exposing LiteBucket's Prometheus metrics (`0.0.4`).
|
|
5
|
+
#
|
|
6
|
+
# Usage in `config/routes.rb`:
|
|
7
|
+
# mount LiteBucket::MetricsEndpoint => "/metrics"
|
|
8
|
+
#
|
|
9
|
+
# Or with optional Bearer token protection:
|
|
10
|
+
# mount LiteBucket::MetricsEndpoint.new(token: ENV["METRICS_TOKEN"]) => "/metrics"
|
|
11
|
+
class MetricsEndpoint
|
|
12
|
+
CONTENT_TYPE = "text/plain; version=0.0.4; charset=utf-8".freeze
|
|
13
|
+
|
|
14
|
+
def self.call(env)
|
|
15
|
+
new.call(env)
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
def initialize(token: ENV["LITEBUCKET_METRICS_TOKEN"])
|
|
19
|
+
@token = token && !token.strip.empty? ? token.strip : nil
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def call(env)
|
|
23
|
+
return [405, { "content-type" => "text/plain" }, ["Method Not Allowed\n"]] unless %w[GET HEAD].include?(env["REQUEST_METHOD"].to_s.upcase)
|
|
24
|
+
|
|
25
|
+
if @token && !authorized?(env["HTTP_AUTHORIZATION"])
|
|
26
|
+
return [401, { "content-type" => "text/plain" }, ["Unauthorized\n"]]
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
body = LiteBucket.prometheus_metrics.to_s
|
|
30
|
+
[200, { "content-type" => CONTENT_TYPE }, [env["REQUEST_METHOD"].to_s.upcase == "HEAD" ? "" : body]]
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
private
|
|
34
|
+
|
|
35
|
+
def authorized?(auth_header)
|
|
36
|
+
return false unless auth_header.is_a?(String) && auth_header.start_with?("Bearer ")
|
|
37
|
+
|
|
38
|
+
supplied = auth_header.delete_prefix("Bearer ").strip
|
|
39
|
+
return false unless supplied.bytesize == @token.bytesize
|
|
40
|
+
|
|
41
|
+
OpenSSL.fixed_length_secure_compare(supplied, @token)
|
|
42
|
+
end
|
|
43
|
+
end
|
|
44
|
+
end
|
|
Binary file
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
module LiteBucket
|
|
2
|
+
class Railtie < Rails::Railtie
|
|
3
|
+
# Register `litebucket` SQLite VFS as early as possible (before `db:prepare`/`db:create`
|
|
4
|
+
# AND before ActiveRecord initializes its connection pool!).
|
|
5
|
+
config.before_configuration do
|
|
6
|
+
LiteBucket.register!
|
|
7
|
+
end
|
|
8
|
+
|
|
9
|
+
# Zero-config horizontal scaling: automatically prepend `WriteForwardingMiddleware` whenever
|
|
10
|
+
# `LITEBUCKET_ADVERTISE_ADDR` is configured (unless disabled via `LITEBUCKET_WRITE_FORWARDING=0`).
|
|
11
|
+
initializer "litebucket.write_forwarding" do |app|
|
|
12
|
+
adv = ENV["LITEBUCKET_ADVERTISE_ADDR"].to_s.strip
|
|
13
|
+
enabled = !%w[0 false no].include?(ENV["LITEBUCKET_WRITE_FORWARDING"].to_s.strip.downcase)
|
|
14
|
+
if !adv.empty? && enabled
|
|
15
|
+
app.middleware.insert_before(0, LiteBucket::WriteForwardingMiddleware)
|
|
16
|
+
end
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
initializer "litebucket.register_vfs", before: "active_record.initialize_database" do
|
|
20
|
+
LiteBucket.register!
|
|
21
|
+
at_exit { LiteBucket.flush_all_active_record! }
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
rake_tasks do
|
|
25
|
+
load File.expand_path("../tasks/litebucket.rake", __dir__)
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
end
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
require "ipaddr"
|
|
2
|
+
require "net/http"
|
|
3
|
+
require "openssl"
|
|
4
|
+
require "uri"
|
|
5
|
+
|
|
6
|
+
module LiteBucket
|
|
7
|
+
# Native in-process Rack middleware for horizontal multi-replica scaling on Rails, Sinatra,
|
|
8
|
+
# or any Rack app!
|
|
9
|
+
#
|
|
10
|
+
# - GET / HEAD / OPTIONS always execute locally at L1 RAM speed (< 1 ms).
|
|
11
|
+
# - POST / PUT / PATCH / DELETE check `LiteBucket.write_owner_addr` (~50 ns C-ABI lookup
|
|
12
|
+
# into `liblitebucket.so`, zero SQL or network round-trip).
|
|
13
|
+
# - If another replica currently holds `write_lock.json` and advertised its LAN URL via
|
|
14
|
+
# `LITEBUCKET_ADVERTISE_ADDR`, the request is transparently proxied over a persistent
|
|
15
|
+
# keep-alive HTTP pool with HMAC-SHA256 loop protection, SSRF peer validation, and
|
|
16
|
+
# deterministic read-your-writes catch-up right after the primary commits!
|
|
17
|
+
#
|
|
18
|
+
# Usage in `config/application.rb`:
|
|
19
|
+
# config.middleware.use LiteBucket::WriteForwardingMiddleware
|
|
20
|
+
class WriteForwardingMiddleware
|
|
21
|
+
MUTATING_METHODS = %w[POST PUT PATCH DELETE].freeze
|
|
22
|
+
HOP_BY_HOP_HEADERS = %w[
|
|
23
|
+
connection keep-alive proxy-authenticate proxy-authorization
|
|
24
|
+
te trailer trailers transfer-encoding upgrade content-length
|
|
25
|
+
].freeze
|
|
26
|
+
DEFAULT_MAX_BODY_BYTES = 10 * 1024 * 1024 # 10 MiB
|
|
27
|
+
METADATA_HOSTS = %w[
|
|
28
|
+
metadata.google.internal
|
|
29
|
+
metadata.goog
|
|
30
|
+
metadata
|
|
31
|
+
169.254.169.254
|
|
32
|
+
169.254.170.2
|
|
33
|
+
fd00:ec2::254
|
|
34
|
+
].freeze
|
|
35
|
+
|
|
36
|
+
def initialize(
|
|
37
|
+
app,
|
|
38
|
+
prefix: nil,
|
|
39
|
+
prefix_template: "tenants/%{tenant}/main",
|
|
40
|
+
tenant_resolver: nil,
|
|
41
|
+
owner_resolver: nil,
|
|
42
|
+
open_timeout: 3,
|
|
43
|
+
read_timeout: 30,
|
|
44
|
+
max_body_bytes: DEFAULT_MAX_BODY_BYTES,
|
|
45
|
+
forward_secret: nil
|
|
46
|
+
)
|
|
47
|
+
@app = app
|
|
48
|
+
@prefix = prefix
|
|
49
|
+
@prefix_template = prefix_template
|
|
50
|
+
@tenant_resolver = tenant_resolver
|
|
51
|
+
@owner_resolver = owner_resolver
|
|
52
|
+
@open_timeout = open_timeout
|
|
53
|
+
@read_timeout = read_timeout
|
|
54
|
+
@max_body_bytes = max_body_bytes.to_i
|
|
55
|
+
@forward_secret = forward_secret
|
|
56
|
+
@pool_mutex = Mutex.new
|
|
57
|
+
@http_pools = {}
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def call(env)
|
|
61
|
+
method = env["REQUEST_METHOD"].to_s.upcase
|
|
62
|
+
is_mut = MUTATING_METHODS.include?(method)
|
|
63
|
+
is_forwarded_in = valid_forwarded_header?(env["HTTP_X_LITEBUCKET_FORWARDED"])
|
|
64
|
+
|
|
65
|
+
if is_mut && !is_forwarded_in
|
|
66
|
+
target_prefix = resolve_target_prefix(env)
|
|
67
|
+
owner_url = resolve_owner_url(env, target_prefix)
|
|
68
|
+
if owner_url && !owner_url.empty?
|
|
69
|
+
result = forward_request(env, owner_url)
|
|
70
|
+
if result != :peer_unreachable
|
|
71
|
+
status, headers, body = result
|
|
72
|
+
if status >= 200 && status < 400
|
|
73
|
+
# Read-your-writes across horizontally scaled replicas: pull the freshly committed
|
|
74
|
+
# LTX frame from S3/R2 into local L1 RAM right before returning so an immediate
|
|
75
|
+
# browser `302 -> GET` on this replica sees the write in < 1 ms!
|
|
76
|
+
LiteBucket.catch_up_prefix!(target_prefix)
|
|
77
|
+
end
|
|
78
|
+
return [status, headers, body]
|
|
79
|
+
end
|
|
80
|
+
# Peer refused connection before receiving the request (e.g. primary pod SIGKILLed or
|
|
81
|
+
# restarting): fall through to local execution so SQLite's write-lease takeover claims
|
|
82
|
+
# the expired lease seamlessly with zero 502 errors!
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
status, headers, body = @app.call(env)
|
|
87
|
+
if is_mut && is_forwarded_in && status >= 200 && status < 400
|
|
88
|
+
# Primary handling a forwarded write: flush staged frames to S3/R2 (keeping our write
|
|
89
|
+
# lease hot!) so the forwarding replica's catch-up observes the new LTX immediately.
|
|
90
|
+
target_prefix = resolve_target_prefix(env)
|
|
91
|
+
txid = LiteBucket.flush_staged!(target_prefix)
|
|
92
|
+
if txid && txid > 0
|
|
93
|
+
headers = headers.dup
|
|
94
|
+
headers["x-litebucket-txid"] = txid.to_s
|
|
95
|
+
end
|
|
96
|
+
end
|
|
97
|
+
[status, headers, body]
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
private
|
|
101
|
+
|
|
102
|
+
def resolve_target_prefix(env)
|
|
103
|
+
if @tenant_resolver
|
|
104
|
+
raw_tid = @tenant_resolver.call(env)
|
|
105
|
+
if raw_tid && !raw_tid.to_s.empty?
|
|
106
|
+
clean = LiteBucket.sanitize_tenant_id(raw_tid)
|
|
107
|
+
return @prefix_template.gsub("%{tenant}", clean)
|
|
108
|
+
end
|
|
109
|
+
end
|
|
110
|
+
@prefix
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def resolve_owner_url(env, target_prefix)
|
|
114
|
+
if @owner_resolver
|
|
115
|
+
return @owner_resolver.arity == 0 ? @owner_resolver.call : @owner_resolver.call(env)
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
LiteBucket.write_owner_addr(target_prefix)
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
def forward_loop_token
|
|
122
|
+
secret = @forward_secret || %w[
|
|
123
|
+
LITEBUCKET_FORWARD_SECRET
|
|
124
|
+
LITEBUCKET_ENCRYPTION_KEY
|
|
125
|
+
AWS_SECRET_ACCESS_KEY
|
|
126
|
+
FILESYSTEM_SECRET_ACCESS_KEY
|
|
127
|
+
].map { |k| ENV[k] }.find { |v| v && !v.strip.empty? }
|
|
128
|
+
return nil if secret.nil? || secret.empty?
|
|
129
|
+
|
|
130
|
+
OpenSSL::HMAC.hexdigest("SHA256", secret, "litebucket-write-forward-v1")[0, 32]
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
def valid_forwarded_header?(header_value)
|
|
134
|
+
return false if header_value.nil? || header_value.empty?
|
|
135
|
+
|
|
136
|
+
expected = forward_loop_token
|
|
137
|
+
if expected
|
|
138
|
+
return false unless header_value.bytesize == expected.bytesize
|
|
139
|
+
|
|
140
|
+
OpenSSL.fixed_length_secure_compare(header_value, expected)
|
|
141
|
+
else
|
|
142
|
+
header_value == "1"
|
|
143
|
+
end
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
def validate_peer_base_url(raw_url)
|
|
147
|
+
uri = URI.parse(raw_url.to_s.strip)
|
|
148
|
+
unless %w[http https].include?(uri.scheme) && uri.host && !uri.host.empty?
|
|
149
|
+
raise ArgumentError, "invalid peer scheme or host"
|
|
150
|
+
end
|
|
151
|
+
raise ArgumentError, "peer URL must not contain credentials" if uri.userinfo
|
|
152
|
+
|
|
153
|
+
host_down = uri.host.downcase.delete_prefix("[").delete_suffix("]")
|
|
154
|
+
raise ArgumentError, "blocked metadata peer host" if METADATA_HOSTS.include?(host_down)
|
|
155
|
+
|
|
156
|
+
begin
|
|
157
|
+
ip = IPAddr.new(host_down)
|
|
158
|
+
# Reject AWS/GCP/Azure link-local metadata range 169.254.0.0/16 and unspecified 0.0.0.0/::.
|
|
159
|
+
if IPAddr.new("169.254.0.0/16").include?(ip) || ip == IPAddr.new("0.0.0.0") || ip == IPAddr.new("::")
|
|
160
|
+
raise ArgumentError, "blocked link-local or unspecified peer IP"
|
|
161
|
+
end
|
|
162
|
+
rescue IPAddr::InvalidAddressError
|
|
163
|
+
# Hostname (already checked against METADATA_HOSTS above)
|
|
164
|
+
end
|
|
165
|
+
uri
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
def checkout_http(uri)
|
|
169
|
+
key = "#{uri.scheme}://#{uri.host}:#{uri.port}"
|
|
170
|
+
conn = @pool_mutex.synchronize do
|
|
171
|
+
pool = (@http_pools[key] ||= [])
|
|
172
|
+
pool.pop
|
|
173
|
+
end
|
|
174
|
+
if conn && conn.started?
|
|
175
|
+
return [key, conn]
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
conn = Net::HTTP.new(uri.host, uri.port)
|
|
179
|
+
conn.use_ssl = (uri.scheme == "https")
|
|
180
|
+
conn.open_timeout = @open_timeout
|
|
181
|
+
conn.read_timeout = @read_timeout
|
|
182
|
+
conn.keep_alive_timeout = 30
|
|
183
|
+
conn.start
|
|
184
|
+
[key, conn]
|
|
185
|
+
end
|
|
186
|
+
|
|
187
|
+
def checkin_http(key, conn)
|
|
188
|
+
return unless conn && conn.started?
|
|
189
|
+
|
|
190
|
+
@pool_mutex.synchronize do
|
|
191
|
+
pool = (@http_pools[key] ||= [])
|
|
192
|
+
if pool.length < 16
|
|
193
|
+
pool.push(conn)
|
|
194
|
+
else
|
|
195
|
+
conn.finish rescue nil
|
|
196
|
+
end
|
|
197
|
+
end
|
|
198
|
+
end
|
|
199
|
+
|
|
200
|
+
def read_bounded_body(input)
|
|
201
|
+
return nil unless input
|
|
202
|
+
|
|
203
|
+
chunks = []
|
|
204
|
+
total = 0
|
|
205
|
+
limit = @max_body_bytes
|
|
206
|
+
while (chunk = input.read(65_536))
|
|
207
|
+
total += chunk.bytesize
|
|
208
|
+
return :too_large if limit > 0 && total > limit
|
|
209
|
+
|
|
210
|
+
chunks << chunk
|
|
211
|
+
end
|
|
212
|
+
input.rewind if input.respond_to?(:rewind)
|
|
213
|
+
chunks.empty? ? nil : chunks.join
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
def forward_request(env, owner_url)
|
|
217
|
+
base_uri = begin
|
|
218
|
+
validate_peer_base_url(owner_url)
|
|
219
|
+
rescue ArgumentError
|
|
220
|
+
return [502, { "content-type" => "text/plain" }, ["LiteBucket write-forwarding rejected invalid peer address"]]
|
|
221
|
+
end
|
|
222
|
+
|
|
223
|
+
base = owner_url.sub(%r{/\z}, "")
|
|
224
|
+
path = env["PATH_INFO"].to_s
|
|
225
|
+
path = "/" if path.empty?
|
|
226
|
+
if !path.start_with?("/") || path.start_with?("//")
|
|
227
|
+
return [400, { "content-type" => "text/plain" }, ["Invalid request path"]]
|
|
228
|
+
end
|
|
229
|
+
query = env["QUERY_STRING"].to_s
|
|
230
|
+
target = query.empty? ? "#{base}#{path}" : "#{base}#{path}?#{query}"
|
|
231
|
+
uri = URI.parse(target)
|
|
232
|
+
unless uri.scheme == base_uri.scheme && uri.host == base_uri.host && uri.port == base_uri.port
|
|
233
|
+
return [400, { "content-type" => "text/plain" }, ["Invalid forwarded target URL"]]
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
body = read_bounded_body(env["rack.input"])
|
|
237
|
+
if body == :too_large
|
|
238
|
+
return [413, { "content-type" => "text/plain" }, ["Request body exceeds LiteBucket forward limit"]]
|
|
239
|
+
end
|
|
240
|
+
|
|
241
|
+
req_class = case env["REQUEST_METHOD"].to_s.upcase
|
|
242
|
+
when "POST" then Net::HTTP::Post
|
|
243
|
+
when "PUT" then Net::HTTP::Put
|
|
244
|
+
when "PATCH" then Net::HTTP::Patch
|
|
245
|
+
when "DELETE" then Net::HTTP::Delete
|
|
246
|
+
else Net::HTTP::Post
|
|
247
|
+
end
|
|
248
|
+
|
|
249
|
+
req = req_class.new(uri.request_uri)
|
|
250
|
+
env.each do |k, v|
|
|
251
|
+
next unless k.start_with?("HTTP_")
|
|
252
|
+
|
|
253
|
+
header = k.sub(/\AHTTP_/, "").split("_").map(&:capitalize).join("-")
|
|
254
|
+
lower = header.downcase
|
|
255
|
+
next if HOP_BY_HOP_HEADERS.include?(lower) || lower == "x-litebucket-forwarded"
|
|
256
|
+
|
|
257
|
+
req[header] = v
|
|
258
|
+
end
|
|
259
|
+
req["Content-Type"] = env["CONTENT_TYPE"] if env["CONTENT_TYPE"] && !env["CONTENT_TYPE"].empty?
|
|
260
|
+
req["X-LiteBucket-Forwarded"] = forward_loop_token || "1"
|
|
261
|
+
req.body = body unless body.nil? || body.empty?
|
|
262
|
+
|
|
263
|
+
pool_key, http = begin
|
|
264
|
+
checkout_http(uri)
|
|
265
|
+
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ENETUNREACH, SocketError, Net::OpenTimeout
|
|
266
|
+
return :peer_unreachable
|
|
267
|
+
end
|
|
268
|
+
res = begin
|
|
269
|
+
http.request(req)
|
|
270
|
+
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ENETUNREACH, SocketError, Net::OpenTimeout
|
|
271
|
+
http.finish rescue nil
|
|
272
|
+
return :peer_unreachable
|
|
273
|
+
rescue EOFError, Errno::EPIPE, Errno::ECONNRESET
|
|
274
|
+
# Re-open once if an idle keep-alive socket was closed by the peer before reading request.
|
|
275
|
+
http.finish rescue nil
|
|
276
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
|
277
|
+
http.use_ssl = (uri.scheme == "https")
|
|
278
|
+
http.open_timeout = @open_timeout
|
|
279
|
+
http.read_timeout = @read_timeout
|
|
280
|
+
http.keep_alive_timeout = 30
|
|
281
|
+
begin
|
|
282
|
+
http.start
|
|
283
|
+
rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, Errno::ENETUNREACH, SocketError, Net::OpenTimeout
|
|
284
|
+
return :peer_unreachable
|
|
285
|
+
end
|
|
286
|
+
http.request(req)
|
|
287
|
+
end
|
|
288
|
+
checkin_http(pool_key, http)
|
|
289
|
+
|
|
290
|
+
headers = {}
|
|
291
|
+
res.each_header do |k, v|
|
|
292
|
+
lower = k.downcase
|
|
293
|
+
next if HOP_BY_HOP_HEADERS.include?(lower) || lower == "x-litebucket-txid"
|
|
294
|
+
|
|
295
|
+
headers[k] = v
|
|
296
|
+
end
|
|
297
|
+
# Signal forwarding occurred without leaking internal peer pod IP/URL to public clients.
|
|
298
|
+
headers["x-litebucket-forwarded"] = "1"
|
|
299
|
+
[res.code.to_i, headers, [res.body.to_s]]
|
|
300
|
+
rescue StandardError
|
|
301
|
+
http.finish rescue nil
|
|
302
|
+
[502, { "content-type" => "text/plain" }, ["LiteBucket write-forwarding to primary failed"]]
|
|
303
|
+
end
|
|
304
|
+
end
|
|
305
|
+
end
|
data/lib/litebucket.rb
ADDED
|
@@ -0,0 +1,672 @@
|
|
|
1
|
+
require "json"
|
|
2
|
+
require "rbconfig"
|
|
3
|
+
begin
|
|
4
|
+
require "fiddle"
|
|
5
|
+
rescue LoadError
|
|
6
|
+
# Optional C-ABI helpers (write_owner_addr, prometheus_metrics, flush_all!) degrade gracefully if fiddle is unavailable.
|
|
7
|
+
end
|
|
8
|
+
require "sqlite3"
|
|
9
|
+
require_relative "litebucket/version"
|
|
10
|
+
require_relative "litebucket/write_forwarding_middleware"
|
|
11
|
+
require_relative "litebucket/metrics_endpoint"
|
|
12
|
+
require_relative "litebucket/durable_commits"
|
|
13
|
+
|
|
14
|
+
module LiteBucket
|
|
15
|
+
DEFAULT_SEARCH_PATHS = [
|
|
16
|
+
"/usr/local/lib/liblitebucket.so",
|
|
17
|
+
"/usr/local/lib/liblitebucket.dylib",
|
|
18
|
+
"/usr/lib/liblitebucket.so"
|
|
19
|
+
].freeze
|
|
20
|
+
|
|
21
|
+
@loaded = false
|
|
22
|
+
@loaded_path = nil
|
|
23
|
+
|
|
24
|
+
class << self
|
|
25
|
+
attr_reader :loaded_path
|
|
26
|
+
|
|
27
|
+
def loaded?
|
|
28
|
+
@loaded
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
# Normalized `<cpu>-<os>` directory name used for bundled platform-native gems
|
|
32
|
+
# (e.g. `x86_64-linux`, `aarch64-linux`, `arm64-darwin`, `x86_64-darwin`).
|
|
33
|
+
def native_platform_dir(host_cpu: RbConfig::CONFIG["host_cpu"], host_os: RbConfig::CONFIG["host_os"])
|
|
34
|
+
cpu = case host_cpu.to_s.downcase
|
|
35
|
+
when /x86_64|amd64|x64/ then "x86_64"
|
|
36
|
+
when /aarch64|arm64/ then (host_os.to_s.downcase.include?("darwin") ? "arm64" : "aarch64")
|
|
37
|
+
else host_cpu.to_s.downcase
|
|
38
|
+
end
|
|
39
|
+
os = case host_os.to_s.downcase
|
|
40
|
+
when /darwin/ then "darwin"
|
|
41
|
+
when /linux/ then "linux"
|
|
42
|
+
else host_os.to_s.downcase
|
|
43
|
+
end
|
|
44
|
+
"#{cpu}-#{os}"
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def native_lib_filename(host_os: RbConfig::CONFIG["host_os"])
|
|
48
|
+
host_os.to_s.downcase.include?("darwin") ? "liblitebucket.dylib" : "liblitebucket.so"
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# Path to the prebuilt liblitebucket shared library bundled inside a platform-native gem.
|
|
52
|
+
def bundled_extension_path(root: File.expand_path("litebucket/native", __dir__))
|
|
53
|
+
plat_path = File.join(root, native_platform_dir, native_lib_filename)
|
|
54
|
+
return plat_path if File.exist?(plat_path)
|
|
55
|
+
|
|
56
|
+
flat_path = File.join(root, native_lib_filename)
|
|
57
|
+
return flat_path if File.exist?(flat_path)
|
|
58
|
+
|
|
59
|
+
nil
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Locate liblitebucket shared library in priority order:
|
|
63
|
+
# 1. Explicit path argument
|
|
64
|
+
# 2. ENV["LITEBUCKET_EXT_PATH"] (or legacy S3LTX_EXT_PATH)
|
|
65
|
+
# 3. Prebuilt native binary bundled inside this platform gem (zero-Dockerfile!)
|
|
66
|
+
# 4. Standard system install paths (/usr/local/lib/liblitebucket.so, etc.)
|
|
67
|
+
def resolve_extension_path(explicit_path = nil)
|
|
68
|
+
candidates = [
|
|
69
|
+
explicit_path,
|
|
70
|
+
ENV["LITEBUCKET_EXT_PATH"],
|
|
71
|
+
ENV["S3LTX_EXT_PATH"],
|
|
72
|
+
bundled_extension_path
|
|
73
|
+
].compact.reject(&:empty?) + DEFAULT_SEARCH_PATHS
|
|
74
|
+
candidates.find { |p| File.exist?(p) }
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# Register the `litebucket` SQLite VFS permanently for this Ruby process.
|
|
78
|
+
# Safe to call multiple times (idempotent).
|
|
79
|
+
def register!(path = nil, required: false)
|
|
80
|
+
return true if @loaded
|
|
81
|
+
|
|
82
|
+
ext = resolve_extension_path(path)
|
|
83
|
+
unless ext
|
|
84
|
+
if required
|
|
85
|
+
raise LoadError,
|
|
86
|
+
"Could not locate liblitebucket (#{native_platform_dir}/#{native_lib_filename}). " \
|
|
87
|
+
"Install the platform-native litebucket gem or set LITEBUCKET_EXT_PATH."
|
|
88
|
+
end
|
|
89
|
+
return false
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
boot = SQLite3::Database.new(":memory:")
|
|
93
|
+
boot.enable_load_extension(true)
|
|
94
|
+
boot.load_extension(ext)
|
|
95
|
+
boot.close
|
|
96
|
+
@loaded = true
|
|
97
|
+
@loaded_path = ext
|
|
98
|
+
true
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# Strict InfoSec tenant ID validation matching LiteBucket's Rust `sanitize_tenant_id`:
|
|
102
|
+
# 1..63 ASCII alphanumeric / `-` / `_`, starting with alphanumeric (blocks `..`, `/`, spaces).
|
|
103
|
+
def sanitize_tenant_id(tenant)
|
|
104
|
+
clean = tenant.to_s.strip.downcase
|
|
105
|
+
unless clean.match?(/\A[a-z0-9][a-z0-9_-]{0,62}\z/)
|
|
106
|
+
raise ArgumentError, "invalid LiteBucket tenant_id #{tenant.inspect}: must match /[a-z0-9][a-z0-9_-]{0,62}/"
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
clean
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# Build a clean `file:` URI for config/database.yml or SQLite3::Database.new.
|
|
113
|
+
#
|
|
114
|
+
# Local-speed SQLite in RAM & ephemeral NVMe, backed durably by S3 & R2:
|
|
115
|
+
# - Use `sync: :strict` when running stock Rails/Puma behind `kamal-proxy` with zero
|
|
116
|
+
# Dockerfile changes (guarantees RPO = 0 across overlapping v1/v2 containers!).
|
|
117
|
+
# - Use `sync: :batched` for sub-millisecond local commits (~0.007 ms/insert), paired
|
|
118
|
+
# with `LiteBucket.with_durable_commit` on critical writes or `litebucket run --engine vfs`.
|
|
119
|
+
def database_uri(
|
|
120
|
+
prefix,
|
|
121
|
+
sync: :batched,
|
|
122
|
+
flush_ms: 100,
|
|
123
|
+
write_lease: true,
|
|
124
|
+
refresh_ms: 500,
|
|
125
|
+
disk_cache_mb: 128,
|
|
126
|
+
disk_cache_dir: nil,
|
|
127
|
+
disk_cache_persistent: false,
|
|
128
|
+
compact_every: 16,
|
|
129
|
+
retain_txids: 32,
|
|
130
|
+
retain_hours: nil,
|
|
131
|
+
readahead: nil,
|
|
132
|
+
prefetch_mb: nil,
|
|
133
|
+
prefetch: nil,
|
|
134
|
+
max_unflushed_mb: nil,
|
|
135
|
+
tenant_key_id: nil,
|
|
136
|
+
pin_txid: nil
|
|
137
|
+
)
|
|
138
|
+
params = ["vfs=litebucket", "sync=#{sync}"]
|
|
139
|
+
params << "flush_ms=#{flush_ms}" if sync.to_s == "batched" && flush_ms
|
|
140
|
+
params << "write_lease=1" if write_lease && !pin_txid
|
|
141
|
+
params << "refresh_ms=#{refresh_ms}" if refresh_ms && !pin_txid
|
|
142
|
+
params << "disk_cache_mb=#{disk_cache_mb}" if disk_cache_mb
|
|
143
|
+
params << "disk_cache_dir=#{disk_cache_dir}" if disk_cache_dir
|
|
144
|
+
params << "disk_cache_persistent=1" if disk_cache_persistent
|
|
145
|
+
params << "compact_every=#{compact_every}" if compact_every
|
|
146
|
+
params << "retain_txids=#{retain_txids}" if retain_txids
|
|
147
|
+
params << "retain_hours=#{retain_hours}" if retain_hours
|
|
148
|
+
params << "readahead=#{readahead}" if readahead
|
|
149
|
+
params << "prefetch_mb=#{prefetch_mb}" if prefetch_mb
|
|
150
|
+
params << "prefetch=#{prefetch}" if prefetch
|
|
151
|
+
params << "max_unflushed_mb=#{max_unflushed_mb}" if max_unflushed_mb
|
|
152
|
+
params << "tenant_key_id=#{tenant_key_id}" if tenant_key_id
|
|
153
|
+
params << "pin_txid=#{pin_txid}" if pin_txid
|
|
154
|
+
"file:#{prefix}?#{params.join('&')}"
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
# Drop-in database URI template for Basecamp's `activerecord-tenanted` (`config/database.yml`):
|
|
158
|
+
#
|
|
159
|
+
# production:
|
|
160
|
+
# adapter: sqlite3
|
|
161
|
+
# tenanted: true
|
|
162
|
+
# database: <%= LiteBucket.tenanted_database_uri("tenants/%{tenant}/main") %>
|
|
163
|
+
#
|
|
164
|
+
# When `per_tenant_key: true` (default) and `LITEBUCKET_ENCRYPTION_KEY` is set, LiteBucket derives
|
|
165
|
+
# a cryptographically distinct AES-256-GCM key per tenant via RFC 5869 HKDF-SHA256 so customers
|
|
166
|
+
# enjoy both physical database isolation and cryptographic ciphertext isolation!
|
|
167
|
+
def tenanted_database_uri(
|
|
168
|
+
template = "tenants/%{tenant}/main",
|
|
169
|
+
per_tenant_key: true,
|
|
170
|
+
**opts
|
|
171
|
+
)
|
|
172
|
+
unless template.include?("%{tenant}")
|
|
173
|
+
raise ArgumentError, "tenanted_database_uri template must include `%{tenant}` placeholder"
|
|
174
|
+
end
|
|
175
|
+
|
|
176
|
+
opts = opts.dup
|
|
177
|
+
opts[:tenant_key_id] = "%{tenant}" if per_tenant_key && !opts.key?(:tenant_key_id)
|
|
178
|
+
database_uri(template, **opts)
|
|
179
|
+
end
|
|
180
|
+
|
|
181
|
+
# Return true when an S3/R2/Laravel Cloud Object Storage bucket env var is configured.
|
|
182
|
+
def bucket_configured?
|
|
183
|
+
%w[LITEBUCKET_BUCKET FILESYSTEM_BUCKET AWS_BUCKET S3_BUCKET].any? do |key|
|
|
184
|
+
v = ENV[key]
|
|
185
|
+
v && !v.strip.empty?
|
|
186
|
+
end
|
|
187
|
+
end
|
|
188
|
+
|
|
189
|
+
# 1-line `config/database.yml` helper: returns a LiteBucket URI whenever bucket env vars are
|
|
190
|
+
# present (reading `LITEBUCKET_SYNC_MODE`, `LITEBUCKET_FLUSH_MS`, `LITEBUCKET_DISK_CACHE_MB`,
|
|
191
|
+
# `LITEBUCKET_COMPACT_EVERY`, `LITEBUCKET_RETAIN_TXIDS`, `LITEBUCKET_RETAIN_HOURS`), or falls
|
|
192
|
+
# back to a local SQLite path during build steps (`rails assets:precompile`) and local dev.
|
|
193
|
+
def database_uri_from_env(prefix = ENV.fetch("LITEBUCKET_PREFIX", "app/primary"), fallback: "storage/production.sqlite3", **opts)
|
|
194
|
+
return fallback unless bucket_configured?
|
|
195
|
+
|
|
196
|
+
merged = {
|
|
197
|
+
sync: ENV.fetch("LITEBUCKET_SYNC_MODE", "batched").to_sym,
|
|
198
|
+
flush_ms: ENV.fetch("LITEBUCKET_FLUSH_MS", "100").to_i,
|
|
199
|
+
disk_cache_mb: ENV.fetch("LITEBUCKET_DISK_CACHE_MB", "64").to_i,
|
|
200
|
+
compact_every: ENV.fetch("LITEBUCKET_COMPACT_EVERY", "16").to_i,
|
|
201
|
+
retain_txids: ENV.fetch("LITEBUCKET_RETAIN_TXIDS", "32").to_i
|
|
202
|
+
}
|
|
203
|
+
if ENV["LITEBUCKET_RETAIN_HOURS"] && !ENV["LITEBUCKET_RETAIN_HOURS"].strip.empty?
|
|
204
|
+
merged[:retain_hours] = ENV["LITEBUCKET_RETAIN_HOURS"].to_i
|
|
205
|
+
end
|
|
206
|
+
if %w[1 true yes].include?(ENV["LITEBUCKET_DISK_CACHE_PERSISTENT"].to_s.strip.downcase)
|
|
207
|
+
merged[:disk_cache_persistent] = true
|
|
208
|
+
end
|
|
209
|
+
database_uri(prefix, **merged.merge(opts))
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
# 1-line `activerecord-tenanted` helper that switches from local SQLite to LiteBucket R2/S3
|
|
213
|
+
# automatically whenever bucket env vars are present.
|
|
214
|
+
def tenanted_database_uri_from_env(
|
|
215
|
+
template = "tenants/%{tenant}/main",
|
|
216
|
+
fallback: "storage/tenants/%{tenant}/main.sqlite3",
|
|
217
|
+
per_tenant_key: true,
|
|
218
|
+
**opts
|
|
219
|
+
)
|
|
220
|
+
return fallback unless bucket_configured?
|
|
221
|
+
|
|
222
|
+
opts = opts.dup
|
|
223
|
+
opts[:tenant_key_id] = "%{tenant}" if per_tenant_key && !opts.key?(:tenant_key_id)
|
|
224
|
+
database_uri_from_env(template, fallback: fallback, **opts)
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
# Rails 8 Solid Queue URI helper (stores `queue` DB cleanly under `<app>/queue` in S3/R2).
|
|
228
|
+
def queue_database_uri_from_env(
|
|
229
|
+
prefix = default_sub_prefix("queue"),
|
|
230
|
+
fallback: "storage/production_queue.sqlite3",
|
|
231
|
+
**opts
|
|
232
|
+
)
|
|
233
|
+
database_uri_from_env(prefix, fallback: fallback, **opts)
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
# Rails 8 Solid Cable URI helper (stores `cable` DB cleanly under `<app>/cable` in S3/R2).
|
|
237
|
+
def cable_database_uri_from_env(
|
|
238
|
+
prefix = default_sub_prefix("cable"),
|
|
239
|
+
fallback: "storage/production_cable.sqlite3",
|
|
240
|
+
**opts
|
|
241
|
+
)
|
|
242
|
+
database_uri_from_env(prefix, fallback: fallback, **opts)
|
|
243
|
+
end
|
|
244
|
+
|
|
245
|
+
# Rails 8 Solid Cache URI helper (stores `cache` DB cleanly under `<app>/cache` in S3/R2).
|
|
246
|
+
def cache_database_uri_from_env(
|
|
247
|
+
prefix = default_sub_prefix("cache"),
|
|
248
|
+
fallback: "storage/production_cache.sqlite3",
|
|
249
|
+
**opts
|
|
250
|
+
)
|
|
251
|
+
database_uri_from_env(prefix, fallback: fallback, **opts)
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
# Return the last actionable thread-local error from `liblitebucket.so` (e.g., why SQLite
|
|
255
|
+
# raised `SQLite3::CantOpenException`: wrong encryption key, 403 AccessDenied, missing env).
|
|
256
|
+
def last_error
|
|
257
|
+
return nil unless @loaded_path
|
|
258
|
+
|
|
259
|
+
fn = fiddle_last_error_fn
|
|
260
|
+
return nil unless fn
|
|
261
|
+
|
|
262
|
+
read_c_string_from_fn(fn, initial_cap: 1024)
|
|
263
|
+
rescue StandardError
|
|
264
|
+
nil
|
|
265
|
+
end
|
|
266
|
+
|
|
267
|
+
# Live bucket self-test verifying `ensure_bucket`, `If-None-Match: *` 412 fencing, `If-Match`
|
|
268
|
+
# CAS, Range 206 reads, DELETE, and live RTTs using the current environment credentials.
|
|
269
|
+
# Returns a parsed Hash (`{"ok" => true, "put_rtt_ms" => ..., "range_rtt_ms" => ..., ...}`).
|
|
270
|
+
def doctor
|
|
271
|
+
register!(required: true)
|
|
272
|
+
fn = fiddle_doctor_fn
|
|
273
|
+
raise "liblitebucket does not export litebucket_doctor (upgrade liblitebucket.so)" unless fn
|
|
274
|
+
|
|
275
|
+
raw = read_c_string_from_fn(fn, initial_cap: 4096)
|
|
276
|
+
raise "LiteBucket.doctor returned empty output" if raw.nil? || raw.empty?
|
|
277
|
+
|
|
278
|
+
JSON.parse(raw)
|
|
279
|
+
end
|
|
280
|
+
|
|
281
|
+
# Safe hook for clustered Puma (`before_fork { LiteBucket.before_fork! }`):
|
|
282
|
+
# flushes all staged writes, releases distributed write leases, and disconnects ActiveRecord
|
|
283
|
+
# pools BEFORE `fork()` so child workers never inherit stale handles or dead background threads.
|
|
284
|
+
def before_fork!
|
|
285
|
+
flushed = flush_all!
|
|
286
|
+
ActiveRecord::Base.connection_handler.clear_all_connections!(:all) if defined?(ActiveRecord::Base)
|
|
287
|
+
flushed
|
|
288
|
+
end
|
|
289
|
+
|
|
290
|
+
# Check whether a LiteBucket database exists under `prefix` in S3/R2 (using the warm shared
|
|
291
|
+
# Rust HTTP/TLS pool) and prefetch `manifest.json` + `ltx/` listing for a zero-RTT handoff
|
|
292
|
+
# into the immediately-following SQLite open.
|
|
293
|
+
def prefix_exists?(prefix)
|
|
294
|
+
register!(required: true)
|
|
295
|
+
fn = fiddle_prefix_exists_fn
|
|
296
|
+
raise "liblitebucket does not export litebucket_prefix_exists (upgrade liblitebucket.so)" unless fn
|
|
297
|
+
|
|
298
|
+
rc = fn.call(Fiddle::Pointer[prefix.to_s])
|
|
299
|
+
raise "LiteBucket.prefix_exists?(#{prefix.inspect}) failed (check S3/R2 credentials)" if rc < 0
|
|
300
|
+
|
|
301
|
+
rc == 1
|
|
302
|
+
end
|
|
303
|
+
|
|
304
|
+
# Check whether a tenant database exists under `template` (default `"tenants/%{tenant}/main"`),
|
|
305
|
+
# enforcing `sanitize_tenant_id` first and prefetching its Wave 1 index for zero-RTT open.
|
|
306
|
+
def tenant_exists?(tenant, template: "tenants/%{tenant}/main")
|
|
307
|
+
clean = sanitize_tenant_id(tenant)
|
|
308
|
+
prefix_exists?(render_tenant_prefix(template, clean))
|
|
309
|
+
end
|
|
310
|
+
|
|
311
|
+
# Permanently shred every LTX, snapshot, manifest, and write-lock object under `prefix` in
|
|
312
|
+
# S3/R2 (GDPR tenant offboarding). Returns the number of deleted objects.
|
|
313
|
+
def shred_prefix!(prefix)
|
|
314
|
+
register!(required: true)
|
|
315
|
+
fn = fiddle_shred_prefix_fn
|
|
316
|
+
raise "liblitebucket does not export litebucket_shred_prefix (upgrade liblitebucket.so)" unless fn
|
|
317
|
+
|
|
318
|
+
deleted = fn.call(Fiddle::Pointer[prefix.to_s])
|
|
319
|
+
raise "LiteBucket.shred_prefix!(#{prefix.inspect}) failed" if deleted < 0
|
|
320
|
+
|
|
321
|
+
deleted
|
|
322
|
+
end
|
|
323
|
+
|
|
324
|
+
# GDPR-shred a tenant database under `template` (default `"tenants/%{tenant}/main"`),
|
|
325
|
+
# enforcing `sanitize_tenant_id` first. Returns the number of deleted S3/R2 objects.
|
|
326
|
+
def shred_tenant!(tenant, template: "tenants/%{tenant}/main")
|
|
327
|
+
clean = sanitize_tenant_id(tenant)
|
|
328
|
+
shred_prefix!(render_tenant_prefix(template, clean))
|
|
329
|
+
end
|
|
330
|
+
|
|
331
|
+
# Force an immediate S3/R2 durability barrier (`PRAGMA litebucket_flush`) on the given connection.
|
|
332
|
+
def flush!(connection = default_connection)
|
|
333
|
+
exec_pragma(connection, "PRAGMA litebucket_flush;")
|
|
334
|
+
end
|
|
335
|
+
|
|
336
|
+
# Flush staged writes for `prefix` (or all open DBs when `nil`) WITHOUT releasing the
|
|
337
|
+
# active write lease. When `connection:` is supplied, executes `PRAGMA litebucket_flush;`
|
|
338
|
+
# through `sqlite3` (which releases Ruby's GVL during S3 I/O!).
|
|
339
|
+
def flush_staged!(prefix = nil, connection: nil)
|
|
340
|
+
return nil unless @loaded
|
|
341
|
+
|
|
342
|
+
if connection
|
|
343
|
+
exec_pragma(connection, "PRAGMA litebucket_flush;")
|
|
344
|
+
return 0
|
|
345
|
+
end
|
|
346
|
+
|
|
347
|
+
fn = fiddle_flush_staged_fn
|
|
348
|
+
return nil unless fn
|
|
349
|
+
|
|
350
|
+
ptr = prefix ? Fiddle::Pointer[prefix.to_s] : Fiddle::NULL
|
|
351
|
+
txid = fn.call(ptr)
|
|
352
|
+
txid >= 0 ? txid : nil
|
|
353
|
+
rescue StandardError
|
|
354
|
+
nil
|
|
355
|
+
end
|
|
356
|
+
|
|
357
|
+
# Synchronously catch up open read-replica DB(s) matching `prefix` (or all open DBs when `nil`)
|
|
358
|
+
# from S3/R2 so immediately-following reads see remote commits (read-your-writes after
|
|
359
|
+
# horizontal write forwarding!). Pass `connection:` to execute via GVL-releasing SQLite PRAGMA.
|
|
360
|
+
def catch_up_prefix!(prefix = nil, connection: nil)
|
|
361
|
+
return nil unless @loaded
|
|
362
|
+
|
|
363
|
+
if connection
|
|
364
|
+
exec_pragma(connection, "PRAGMA litebucket_catch_up;")
|
|
365
|
+
return 0
|
|
366
|
+
end
|
|
367
|
+
|
|
368
|
+
fn = fiddle_catch_up_prefix_fn
|
|
369
|
+
return nil unless fn
|
|
370
|
+
|
|
371
|
+
ptr = prefix ? Fiddle::Pointer[prefix.to_s] : Fiddle::NULL
|
|
372
|
+
txid = fn.call(ptr)
|
|
373
|
+
txid >= 0 ? txid : nil
|
|
374
|
+
rescue StandardError
|
|
375
|
+
nil
|
|
376
|
+
end
|
|
377
|
+
|
|
378
|
+
# Flush all open LiteBucket DBs in-process AND release distributed write leases cleanly
|
|
379
|
+
# (safe for at_exit / SIGTERM). Falls back to per-pool `PRAGMA litebucket_flush;` when
|
|
380
|
+
# running against an older `liblitebucket.so` without `litebucket_flush_all`.
|
|
381
|
+
def flush_all!
|
|
382
|
+
return 0 unless @loaded
|
|
383
|
+
|
|
384
|
+
if (fn = fiddle_flush_all_fn)
|
|
385
|
+
return fn.call
|
|
386
|
+
end
|
|
387
|
+
|
|
388
|
+
flush_all_active_record_via_pragma!
|
|
389
|
+
rescue StandardError
|
|
390
|
+
flush_all_active_record_via_pragma!
|
|
391
|
+
end
|
|
392
|
+
|
|
393
|
+
# Flush all active ActiveRecord connections using the `litebucket` VFS (safe for at_exit / SIGTERM).
|
|
394
|
+
def flush_all_active_record!
|
|
395
|
+
return 0 unless @loaded
|
|
396
|
+
|
|
397
|
+
if (fn = fiddle_flush_all_fn)
|
|
398
|
+
return fn.call
|
|
399
|
+
end
|
|
400
|
+
|
|
401
|
+
flush_all_active_record_via_pragma!
|
|
402
|
+
rescue StandardError
|
|
403
|
+
flush_all_active_record_via_pragma!
|
|
404
|
+
end
|
|
405
|
+
|
|
406
|
+
# Trigger snapshot compaction + LTX garbage collection (`PRAGMA litebucket_compact`).
|
|
407
|
+
def compact!(connection = default_connection)
|
|
408
|
+
exec_pragma(connection, "PRAGMA litebucket_compact;")
|
|
409
|
+
end
|
|
410
|
+
|
|
411
|
+
# Fast (~50 ns) C-ABI lookup into `liblitebucket.so`: returns the private LAN URL of the
|
|
412
|
+
# peer replica currently holding `write_lock.json`, or nil when this process owns writes locally.
|
|
413
|
+
def write_owner_addr(prefix = nil)
|
|
414
|
+
return nil unless @loaded_path
|
|
415
|
+
|
|
416
|
+
fn = fiddle_write_owner_fn
|
|
417
|
+
return nil unless fn
|
|
418
|
+
|
|
419
|
+
buf = +"\0" * 512
|
|
420
|
+
prefix_arg = prefix ? Fiddle::Pointer[prefix.to_s] : Fiddle::NULL
|
|
421
|
+
n = fn.call(prefix_arg, buf, buf.bytesize)
|
|
422
|
+
n > 0 ? buf.byteslice(0, n) : nil
|
|
423
|
+
rescue StandardError
|
|
424
|
+
nil
|
|
425
|
+
end
|
|
426
|
+
|
|
427
|
+
# Render Prometheus metrics (`text/plain; version=0.0.4`) for all open LiteBucket DBs in-process.
|
|
428
|
+
def prometheus_metrics
|
|
429
|
+
return "" unless @loaded_path
|
|
430
|
+
|
|
431
|
+
fn = fiddle_metrics_fn
|
|
432
|
+
return "" unless fn
|
|
433
|
+
|
|
434
|
+
cap = 16_384
|
|
435
|
+
2.times do
|
|
436
|
+
buf = +"\0" * cap
|
|
437
|
+
n = fn.call(buf, cap)
|
|
438
|
+
return buf.byteslice(0, n) if n >= 0
|
|
439
|
+
|
|
440
|
+
cap = (-n) + 16
|
|
441
|
+
end
|
|
442
|
+
""
|
|
443
|
+
rescue StandardError
|
|
444
|
+
""
|
|
445
|
+
end
|
|
446
|
+
|
|
447
|
+
# Execute a block inside a transaction and immediately flush to S3/R2 before returning
|
|
448
|
+
# (gives RPO = 0 on critical operations like checkout/billing while keeping batched speed everywhere else!).
|
|
449
|
+
# Skips the R2 flush automatically if the transaction rolls back (e.g. `raise ActiveRecord::Rollback`).
|
|
450
|
+
def with_durable_commit(model_or_connection = nil, &block)
|
|
451
|
+
if defined?(ActiveRecord::Base) && (model_or_connection.nil? || model_or_connection.respond_to?(:transaction))
|
|
452
|
+
target = model_or_connection || ActiveRecord::Base
|
|
453
|
+
committed = false
|
|
454
|
+
result = target.transaction do
|
|
455
|
+
val = block.call
|
|
456
|
+
committed = true
|
|
457
|
+
val
|
|
458
|
+
end
|
|
459
|
+
flush!(target.connection) if committed
|
|
460
|
+
result
|
|
461
|
+
else
|
|
462
|
+
conn = model_or_connection || default_connection
|
|
463
|
+
result = yield conn
|
|
464
|
+
flush!(conn)
|
|
465
|
+
result
|
|
466
|
+
end
|
|
467
|
+
end
|
|
468
|
+
|
|
469
|
+
# Multi-writer optimistic concurrency helper for `sync: :strict` (ideal for Kamal rolling
|
|
470
|
+
# overlaps and multi-replica Rails deployments): catches SQLite BUSY / 412 fencing conflicts,
|
|
471
|
+
# runs `PRAGMA litebucket_catch_up;`, and retries cleanly with brief backoff.
|
|
472
|
+
def with_retry(max_retries: 6, connection: nil)
|
|
473
|
+
attempt = 0
|
|
474
|
+
begin
|
|
475
|
+
yield
|
|
476
|
+
rescue StandardError => e
|
|
477
|
+
msg = e.message.to_s.downcase
|
|
478
|
+
retryable = e.is_a?(SQLite3::BusyException) ||
|
|
479
|
+
msg.include?("database is locked") ||
|
|
480
|
+
msg.include?("busy") ||
|
|
481
|
+
msg.include?("412")
|
|
482
|
+
raise unless retryable && attempt < max_retries
|
|
483
|
+
|
|
484
|
+
attempt += 1
|
|
485
|
+
conn = connection || (defined?(ActiveRecord::Base) ? ActiveRecord::Base.connection : nil)
|
|
486
|
+
exec_pragma(conn, "PRAGMA litebucket_catch_up;") if conn
|
|
487
|
+
sleep(0.015 * attempt)
|
|
488
|
+
retry
|
|
489
|
+
end
|
|
490
|
+
end
|
|
491
|
+
|
|
492
|
+
private
|
|
493
|
+
|
|
494
|
+
def fiddle_handle
|
|
495
|
+
return nil unless defined?(Fiddle)
|
|
496
|
+
|
|
497
|
+
@fiddle_handle ||= Fiddle.dlopen(@loaded_path)
|
|
498
|
+
end
|
|
499
|
+
|
|
500
|
+
def fiddle_write_owner_fn
|
|
501
|
+
return nil unless fiddle_handle
|
|
502
|
+
|
|
503
|
+
@fiddle_write_owner_fn ||= Fiddle::Function.new(
|
|
504
|
+
fiddle_handle["litebucket_write_owner_addr"],
|
|
505
|
+
[Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP, Fiddle::TYPE_SIZE_T],
|
|
506
|
+
Fiddle::TYPE_SSIZE_T
|
|
507
|
+
)
|
|
508
|
+
end
|
|
509
|
+
|
|
510
|
+
def fiddle_metrics_fn
|
|
511
|
+
return nil unless fiddle_handle
|
|
512
|
+
|
|
513
|
+
@fiddle_metrics_fn ||= Fiddle::Function.new(
|
|
514
|
+
fiddle_handle["litebucket_prometheus_metrics"],
|
|
515
|
+
[Fiddle::TYPE_VOIDP, Fiddle::TYPE_SIZE_T],
|
|
516
|
+
Fiddle::TYPE_SSIZE_T
|
|
517
|
+
)
|
|
518
|
+
end
|
|
519
|
+
|
|
520
|
+
def fiddle_flush_all_fn
|
|
521
|
+
return @fiddle_flush_all_fn if defined?(@fiddle_flush_all_fn)
|
|
522
|
+
|
|
523
|
+
@fiddle_flush_all_fn = begin
|
|
524
|
+
return nil unless fiddle_handle
|
|
525
|
+
|
|
526
|
+
sym = fiddle_handle["litebucket_flush_all"]
|
|
527
|
+
Fiddle::Function.new(sym, [], Fiddle::TYPE_SIZE_T)
|
|
528
|
+
rescue StandardError
|
|
529
|
+
nil
|
|
530
|
+
end
|
|
531
|
+
end
|
|
532
|
+
|
|
533
|
+
def fiddle_prefix_exists_fn
|
|
534
|
+
return @fiddle_prefix_exists_fn if defined?(@fiddle_prefix_exists_fn)
|
|
535
|
+
|
|
536
|
+
@fiddle_prefix_exists_fn = begin
|
|
537
|
+
return nil unless fiddle_handle
|
|
538
|
+
|
|
539
|
+
sym = fiddle_handle["litebucket_prefix_exists"]
|
|
540
|
+
Fiddle::Function.new(sym, [Fiddle::TYPE_VOIDP], Fiddle::TYPE_INT)
|
|
541
|
+
rescue StandardError
|
|
542
|
+
nil
|
|
543
|
+
end
|
|
544
|
+
end
|
|
545
|
+
|
|
546
|
+
def fiddle_shred_prefix_fn
|
|
547
|
+
return @fiddle_shred_prefix_fn if defined?(@fiddle_shred_prefix_fn)
|
|
548
|
+
|
|
549
|
+
@fiddle_shred_prefix_fn = begin
|
|
550
|
+
return nil unless fiddle_handle
|
|
551
|
+
|
|
552
|
+
sym = fiddle_handle["litebucket_shred_prefix"]
|
|
553
|
+
Fiddle::Function.new(sym, [Fiddle::TYPE_VOIDP], Fiddle::TYPE_SSIZE_T)
|
|
554
|
+
rescue StandardError
|
|
555
|
+
nil
|
|
556
|
+
end
|
|
557
|
+
end
|
|
558
|
+
|
|
559
|
+
def fiddle_flush_staged_fn
|
|
560
|
+
return @fiddle_flush_staged_fn if defined?(@fiddle_flush_staged_fn)
|
|
561
|
+
|
|
562
|
+
@fiddle_flush_staged_fn = begin
|
|
563
|
+
return nil unless fiddle_handle
|
|
564
|
+
|
|
565
|
+
sym = fiddle_handle["litebucket_flush_staged"]
|
|
566
|
+
Fiddle::Function.new(sym, [Fiddle::TYPE_VOIDP], Fiddle::TYPE_LONG_LONG)
|
|
567
|
+
rescue StandardError
|
|
568
|
+
nil
|
|
569
|
+
end
|
|
570
|
+
end
|
|
571
|
+
|
|
572
|
+
def fiddle_catch_up_prefix_fn
|
|
573
|
+
return @fiddle_catch_up_prefix_fn if defined?(@fiddle_catch_up_prefix_fn)
|
|
574
|
+
|
|
575
|
+
@fiddle_catch_up_prefix_fn = begin
|
|
576
|
+
return nil unless fiddle_handle
|
|
577
|
+
|
|
578
|
+
sym = fiddle_handle["litebucket_catch_up_prefix"]
|
|
579
|
+
Fiddle::Function.new(sym, [Fiddle::TYPE_VOIDP], Fiddle::TYPE_LONG_LONG)
|
|
580
|
+
rescue StandardError
|
|
581
|
+
nil
|
|
582
|
+
end
|
|
583
|
+
end
|
|
584
|
+
|
|
585
|
+
def fiddle_last_error_fn
|
|
586
|
+
return @fiddle_last_error_fn if defined?(@fiddle_last_error_fn)
|
|
587
|
+
|
|
588
|
+
@fiddle_last_error_fn = begin
|
|
589
|
+
return nil unless fiddle_handle
|
|
590
|
+
|
|
591
|
+
sym = fiddle_handle["litebucket_last_error"]
|
|
592
|
+
Fiddle::Function.new(sym, [Fiddle::TYPE_VOIDP, Fiddle::TYPE_SIZE_T], Fiddle::TYPE_SSIZE_T)
|
|
593
|
+
rescue StandardError
|
|
594
|
+
nil
|
|
595
|
+
end
|
|
596
|
+
end
|
|
597
|
+
|
|
598
|
+
def fiddle_doctor_fn
|
|
599
|
+
return @fiddle_doctor_fn if defined?(@fiddle_doctor_fn)
|
|
600
|
+
|
|
601
|
+
@fiddle_doctor_fn = begin
|
|
602
|
+
return nil unless fiddle_handle
|
|
603
|
+
|
|
604
|
+
sym = fiddle_handle["litebucket_doctor"]
|
|
605
|
+
Fiddle::Function.new(sym, [Fiddle::TYPE_VOIDP, Fiddle::TYPE_SIZE_T], Fiddle::TYPE_SSIZE_T)
|
|
606
|
+
rescue StandardError
|
|
607
|
+
nil
|
|
608
|
+
end
|
|
609
|
+
end
|
|
610
|
+
|
|
611
|
+
def read_c_string_from_fn(fn, initial_cap: 1024)
|
|
612
|
+
buf = +"\0" * initial_cap
|
|
613
|
+
len = fn.call(Fiddle::Pointer[buf], buf.bytesize)
|
|
614
|
+
if len < 0
|
|
615
|
+
buf = +"\0" * (-len + 1)
|
|
616
|
+
len = fn.call(Fiddle::Pointer[buf], buf.bytesize)
|
|
617
|
+
end
|
|
618
|
+
return nil if len <= 0
|
|
619
|
+
|
|
620
|
+
buf.byteslice(0, len)
|
|
621
|
+
end
|
|
622
|
+
|
|
623
|
+
def default_sub_prefix(suffix)
|
|
624
|
+
base = ENV.fetch("LITEBUCKET_PREFIX", "app/primary").to_s.strip
|
|
625
|
+
base = "app/primary" if base.empty?
|
|
626
|
+
root = base.sub(%r{/primary\z}, "")
|
|
627
|
+
"#{root}/#{suffix}"
|
|
628
|
+
end
|
|
629
|
+
|
|
630
|
+
def render_tenant_prefix(template, clean_tenant)
|
|
631
|
+
unless template.include?("%{tenant}") || template.include?("{tenant}")
|
|
632
|
+
raise ArgumentError, "tenant prefix template must include `%{tenant}` or `{tenant}`"
|
|
633
|
+
end
|
|
634
|
+
|
|
635
|
+
template.gsub("%{tenant}", clean_tenant).gsub("{tenant}", clean_tenant)
|
|
636
|
+
end
|
|
637
|
+
|
|
638
|
+
def flush_all_active_record_via_pragma!
|
|
639
|
+
return 0 unless defined?(ActiveRecord::Base) && @loaded
|
|
640
|
+
|
|
641
|
+
flushed = 0
|
|
642
|
+
ActiveRecord::Base.connection_handler.each_connection_pool do |pool|
|
|
643
|
+
db_name = pool.db_config.database.to_s
|
|
644
|
+
next unless db_name.include?("vfs=litebucket")
|
|
645
|
+
|
|
646
|
+
pool.with_connection do |conn|
|
|
647
|
+
conn.execute("PRAGMA litebucket_flush;")
|
|
648
|
+
flushed += 1
|
|
649
|
+
end
|
|
650
|
+
rescue StandardError
|
|
651
|
+
nil
|
|
652
|
+
end
|
|
653
|
+
flushed
|
|
654
|
+
end
|
|
655
|
+
|
|
656
|
+
def default_connection
|
|
657
|
+
raise "No connection supplied and ActiveRecord::Base is not loaded" unless defined?(ActiveRecord::Base)
|
|
658
|
+
|
|
659
|
+
ActiveRecord::Base.connection
|
|
660
|
+
end
|
|
661
|
+
|
|
662
|
+
def exec_pragma(connection, sql)
|
|
663
|
+
if connection.respond_to?(:execute)
|
|
664
|
+
connection.execute(sql)
|
|
665
|
+
else
|
|
666
|
+
raise ArgumentError, "unsupported connection object: #{connection.class}"
|
|
667
|
+
end
|
|
668
|
+
end
|
|
669
|
+
end
|
|
670
|
+
end
|
|
671
|
+
|
|
672
|
+
require_relative "litebucket/railtie" if defined?(Rails::Railtie)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
require "puma/plugin"
|
|
2
|
+
require "litebucket"
|
|
3
|
+
|
|
4
|
+
# Built-in Puma plugin for zero-boilerplate clustered Puma & graceful container deploys.
|
|
5
|
+
#
|
|
6
|
+
# Usage in `config/puma.rb`:
|
|
7
|
+
# plugin :litebucket
|
|
8
|
+
#
|
|
9
|
+
# Automatically:
|
|
10
|
+
# - Flushes staged writes, releases distributed write leases, and clears ActiveRecord pools
|
|
11
|
+
# in `before_fork` so forked workers never inherit pre-fork background threads.
|
|
12
|
+
# - Drains staged writes and releases write leases on worker/server shutdown (`SIGTERM`).
|
|
13
|
+
Puma::Plugin.create do
|
|
14
|
+
def config(c)
|
|
15
|
+
c.before_fork do
|
|
16
|
+
LiteBucket.before_fork!
|
|
17
|
+
end
|
|
18
|
+
|
|
19
|
+
if c.respond_to?(:on_worker_shutdown)
|
|
20
|
+
c.on_worker_shutdown do
|
|
21
|
+
LiteBucket.flush_all!
|
|
22
|
+
end
|
|
23
|
+
elsif c.respond_to?(:before_worker_shutdown)
|
|
24
|
+
c.before_worker_shutdown do
|
|
25
|
+
LiteBucket.flush_all!
|
|
26
|
+
end
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
def start(launcher)
|
|
31
|
+
if launcher.respond_to?(:events) && launcher.events.respond_to?(:on_stopped)
|
|
32
|
+
launcher.events.on_stopped do
|
|
33
|
+
LiteBucket.flush_all!
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
end
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
namespace :litebucket do
|
|
2
|
+
desc "Verify S3/R2 bucket access, If-None-Match 412 fencing, If-Match CAS, Range reads, and RTT"
|
|
3
|
+
task doctor: :environment do
|
|
4
|
+
report = LiteBucket.doctor
|
|
5
|
+
puts JSON.pretty_generate(report)
|
|
6
|
+
abort("LiteBucket doctor check FAILED: #{report['error'] || 'unknown error'}") unless report["ok"]
|
|
7
|
+
end
|
|
8
|
+
|
|
9
|
+
desc "Show loaded LiteBucket VFS binary, SQLite integrity check, and open DB metrics"
|
|
10
|
+
task status: :environment do
|
|
11
|
+
LiteBucket.register!(required: true)
|
|
12
|
+
conn = ActiveRecord::Base.connection
|
|
13
|
+
integrity = conn.select_value("PRAGMA integrity_check;")
|
|
14
|
+
puts "LiteBucket v#{LiteBucket::VERSION} (#{LiteBucket.loaded_path})"
|
|
15
|
+
puts "Database: #{ActiveRecord::Base.connection_db_config.database}"
|
|
16
|
+
puts "Integrity check: #{integrity}"
|
|
17
|
+
puts "Write owner: #{LiteBucket.write_owner_addr || '(local / primary)'}"
|
|
18
|
+
puts "--- Prometheus metrics ---"
|
|
19
|
+
puts LiteBucket.prometheus_metrics
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
desc "Run PRAGMA integrity_check on the active LiteBucket database"
|
|
23
|
+
task verify: :environment do
|
|
24
|
+
LiteBucket.register!(required: true)
|
|
25
|
+
res = ActiveRecord::Base.connection.select_value("PRAGMA integrity_check;")
|
|
26
|
+
puts "PRAGMA integrity_check => #{res}"
|
|
27
|
+
abort("Integrity check failed: #{res}") unless res.to_s == "ok"
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
desc "Trigger snapshot compaction + LTX garbage collection on the active database"
|
|
31
|
+
task compact: :environment do
|
|
32
|
+
LiteBucket.register!(required: true)
|
|
33
|
+
LiteBucket.compact!
|
|
34
|
+
puts "LiteBucket compaction + GC complete."
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
desc "Flush all staged LiteBucket writes to S3/R2 and release distributed write leases"
|
|
38
|
+
task flush: :environment do
|
|
39
|
+
count = LiteBucket.flush_all!
|
|
40
|
+
puts "Flushed #{count} LiteBucket database(s)."
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
desc "Permanently GDPR-shred every S3/R2 object under PREFIX (requires CONFIRM=1)"
|
|
44
|
+
task :shred, [:prefix] => :environment do |_t, args|
|
|
45
|
+
prefix = args[:prefix].to_s.strip
|
|
46
|
+
abort("Usage: bin/rails 'litebucket:shred[tenants/acme/main]' CONFIRM=1") if prefix.empty?
|
|
47
|
+
abort("Refusing to shred #{prefix.inspect} without CONFIRM=1") unless ENV["CONFIRM"] == "1"
|
|
48
|
+
|
|
49
|
+
deleted = LiteBucket.shred_prefix!(prefix)
|
|
50
|
+
puts "Shredded #{deleted} object(s) under #{prefix.inspect}."
|
|
51
|
+
end
|
|
52
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: litebucket
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.2.0
|
|
5
|
+
platform: x86_64-linux
|
|
6
|
+
authors:
|
|
7
|
+
- Cole Robertson
|
|
8
|
+
- LiteBucket Contributors
|
|
9
|
+
autorequire:
|
|
10
|
+
bindir: bin
|
|
11
|
+
cert_chain: []
|
|
12
|
+
date: 2026-12-06 00:00:00.000000000 Z
|
|
13
|
+
dependencies:
|
|
14
|
+
- !ruby/object:Gem::Dependency
|
|
15
|
+
name: sqlite3
|
|
16
|
+
requirement: !ruby/object:Gem::Requirement
|
|
17
|
+
requirements:
|
|
18
|
+
- - ">="
|
|
19
|
+
- !ruby/object:Gem::Version
|
|
20
|
+
version: '2.0'
|
|
21
|
+
type: :runtime
|
|
22
|
+
prerelease: false
|
|
23
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
24
|
+
requirements:
|
|
25
|
+
- - ">="
|
|
26
|
+
- !ruby/object:Gem::Version
|
|
27
|
+
version: '2.0'
|
|
28
|
+
- !ruby/object:Gem::Dependency
|
|
29
|
+
name: fiddle
|
|
30
|
+
requirement: !ruby/object:Gem::Requirement
|
|
31
|
+
requirements:
|
|
32
|
+
- - ">="
|
|
33
|
+
- !ruby/object:Gem::Version
|
|
34
|
+
version: '0'
|
|
35
|
+
type: :runtime
|
|
36
|
+
prerelease: false
|
|
37
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
38
|
+
requirements:
|
|
39
|
+
- - ">="
|
|
40
|
+
- !ruby/object:Gem::Version
|
|
41
|
+
version: '0'
|
|
42
|
+
description: 'Zero-Dockerfile Rails & Ruby integration for LiteBucket: bundles liblitebucket
|
|
43
|
+
and auto-registers the litebucket SQLite VFS via a Rails Railtie before ActiveRecord
|
|
44
|
+
connects, giving local RAM/NVMe read/write speed with atomic S3/R2 durability, zero
|
|
45
|
+
persistent volumes, write-forwarding with read-your-writes, Puma plugin, Rake ops
|
|
46
|
+
tasks, and PITR.'
|
|
47
|
+
email:
|
|
48
|
+
executables: []
|
|
49
|
+
extensions: []
|
|
50
|
+
extra_rdoc_files: []
|
|
51
|
+
files:
|
|
52
|
+
- README.md
|
|
53
|
+
- lib/litebucket.rb
|
|
54
|
+
- lib/litebucket/durable_commits.rb
|
|
55
|
+
- lib/litebucket/metrics_endpoint.rb
|
|
56
|
+
- lib/litebucket/native/x86_64-linux/liblitebucket.so
|
|
57
|
+
- lib/litebucket/railtie.rb
|
|
58
|
+
- lib/litebucket/version.rb
|
|
59
|
+
- lib/litebucket/write_forwarding_middleware.rb
|
|
60
|
+
- lib/puma/plugin/litebucket.rb
|
|
61
|
+
- lib/tasks/litebucket.rake
|
|
62
|
+
homepage: https://litebucket.dev
|
|
63
|
+
licenses:
|
|
64
|
+
- MIT
|
|
65
|
+
metadata:
|
|
66
|
+
homepage_uri: https://litebucket.dev
|
|
67
|
+
source_code_uri: https://github.com/cole-robertson/litebucket
|
|
68
|
+
documentation_uri: https://litebucket.dev
|
|
69
|
+
post_install_message:
|
|
70
|
+
rdoc_options: []
|
|
71
|
+
require_paths:
|
|
72
|
+
- lib
|
|
73
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
74
|
+
requirements:
|
|
75
|
+
- - ">="
|
|
76
|
+
- !ruby/object:Gem::Version
|
|
77
|
+
version: 3.2.0
|
|
78
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
79
|
+
requirements:
|
|
80
|
+
- - ">="
|
|
81
|
+
- !ruby/object:Gem::Version
|
|
82
|
+
version: '0'
|
|
83
|
+
requirements: []
|
|
84
|
+
rubygems_version: 3.5.22
|
|
85
|
+
signing_key:
|
|
86
|
+
specification_version: 4
|
|
87
|
+
summary: Local-speed SQLite in RAM & ephemeral NVMe, backed durably by S3 & R2.
|
|
88
|
+
test_files: []
|