Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 7 additions & 29 deletions examples/durable_shared_group_host.rb
Original file line number Diff line number Diff line change
@@ -1,24 +1,19 @@
# frozen_string_literal: true
require "json"
require "sqlite3"
require "securerandom"
require_relative "support/sqlite_store"
require_relative "shared_group_host"

module RBBBExamples
# Local SQLite reference adapter. The engine gem has no SQLite dependency.
class DurableSharedGroupHost
include SqliteStore

def initialize(path:, configurations:, clock:)
@path = File.expand_path(path)
@document = canonical({"format" => 1, "configurations" => configurations, "clock" => clock})
build_host # Validate configuration before creating storage.
begin
File.open(@path, File::WRONLY | File::CREAT | File::EXCL, 0o600) { |_| }
rescue Errno::EEXIST
stat = File.lstat(@path)
unless stat.file? && stat.uid == Process.uid && (stat.mode & 0o077).zero?
raise ArgumentError, "database must be an owner-only regular file"
end
end
secure_file!
transaction do |db|
db.execute("CREATE TABLE IF NOT EXISTS metadata (id INTEGER PRIMARY KEY CHECK(id = 1), document TEXT NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS commits (sequence INTEGER PRIMARY KEY, command_id TEXT NOT NULL UNIQUE, request TEXT NOT NULL, result TEXT NOT NULL)")
Expand All @@ -37,7 +32,7 @@ def initialize(path:, configurations:, clock:)
def submit(unit_id:, command:, expected_revision:)
transaction do |db|
host = restore(db)
request = host.send(:normalize_request, unit_id, command, expected_revision)
request = host.normalize_request(unit_id, command, expected_revision)
receipt = host.submit(unit_id: request.fetch("unit_id"), command: request.fetch("command"),
expected_revision: expected_revision)
persist(db, request, receipt)
Expand All @@ -48,7 +43,7 @@ def submit(unit_id:, command:, expected_revision:)
def close_group(command_id:, effective_at:, expected_revision:)
transaction do |db|
host = restore(db)
request = host.send(:normalize_close_request, command_id, effective_at, expected_revision)
request = host.normalize_close_request(command_id, effective_at, expected_revision)
receipt = dispatch(host, request)
persist(db, request, receipt)
receipt
Expand All @@ -58,9 +53,7 @@ def close_group(command_id:, effective_at:, expected_revision:)
# One transaction returns both the revision and all member projections.
def public_view
transaction do |db|
host = restore(db)
snapshot = host.instance_variable_get(:@snapshot)
{"clock" => snapshot.clock.public_view, "units" => host.public_view}
restore(db).public_snapshot
end
end

Expand Down Expand Up @@ -192,21 +185,6 @@ def canonical(value)
JSON.generate(sort.call(normalized))
end

def transaction
db = SQLite3::Database.new(@path)
db.busy_timeout = 5000
db.execute("PRAGMA synchronous = FULL")
db.execute("BEGIN IMMEDIATE")
result = yield db
db.execute("COMMIT")
result
rescue Exception
db.execute("ROLLBACK") if db&.transaction_active?
raise
ensure
db&.close
end

# Fault-injection seam: never deliver notifications before durable commit.
def before_commit(_db)
end
Expand Down
32 changes: 12 additions & 20 deletions examples/live_scheduling_consumer.rb
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
# frozen_string_literal: true

require "sqlite3"
require_relative "support/sqlite_store"
require_relative "live_scheduling_reader"

module RBBBExamples
# Local, trusted snapshot replacement example. No incremental replay API.
# The fetch callback MUST authenticate/authorize each call and return only its
# authorized projection. A digest is integrity bookkeeping, not authentication.
class LiveSchedulingConsumer
include SqliteStore

class InvalidCheckpoint < StandardError; end

def initialize(path:, tenant_id:, auction_id:, visibility:, fetch:)
raise ArgumentError, "unsupported visibility" unless %w[public privileged].include?(visibility)
@path, @tenant, @auction, @visibility, @fetch = path, tenant_id, auction_id, visibility, fetch
File.open(path, File::RDWR | File::CREAT, 0o600) {} unless File.exist?(path)
File.chmod(0o600, path)
@path = File.expand_path(path)
@tenant, @auction, @visibility, @fetch = tenant_id, auction_id, visibility, fetch
secure_file!
transaction do |db|
db.execute("CREATE TABLE IF NOT EXISTS installation (slot INTEGER PRIMARY KEY CHECK(slot = 1), document TEXT NOT NULL)")
end
Expand Down Expand Up @@ -63,24 +65,14 @@ def validate!(result)
payload["decision_sequence"].is_a?(Integer) && payload["decision_sequence"] >= 0 && payload["snapshot"].is_a?(Hash)
raise InvalidCheckpoint, "invalid scope or checkpoint"
end
unless result["sha256"] == Digest::SHA256.hexdigest(JSON.generate(payload))
expected_digest = begin
Digest::SHA256.hexdigest(RBBB::LiveScheduling::Intent.canonical(payload))
rescue RBBB::LiveScheduling::Intent::Invalid
raise InvalidCheckpoint, "invalid digest"
end
unless result["sha256"] == expected_digest
raise InvalidCheckpoint, "invalid digest"
end
end

def transaction
db = SQLite3::Database.new(@path)
db.busy_timeout = 5000
db.execute("PRAGMA synchronous = FULL")
db.execute("BEGIN IMMEDIATE")
value = yield db
db.execute("COMMIT")
value
rescue Exception
db&.execute("ROLLBACK") if db&.transaction_active?
raise
ensure
db&.close
end

# Fault hooks for synthetic tests; no external effects.
Expand Down
64 changes: 30 additions & 34 deletions examples/live_scheduling_host.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,18 @@

require "json"
require "securerandom"
require "sqlite3"
require "rbbb"
require "rbbb/live_scheduling"
require_relative "support/sqlite_store"

module RBBBExamples
# Embedded SQLite reference host, not an HTTP endpoint. Principal/permissions
# must come from the host's authenticated context. BEGIN IMMEDIATE fences all
# writes across connections/processes (stronger than an auction-row lock).
# Snapshot/receipts are privileged; never expose them directly to a bidder.
class LiveSchedulingHost
include SqliteStore

class ResponseLost < StandardError; end
attr_reader :auction_id, :tenant_id

Expand Down Expand Up @@ -68,7 +70,7 @@ def bid(unit_id:, command:, principal_id:)
raise ArgumentError, "server-assigned fields" if command.key?("effective_at") || command.key?("bidder_id")
RBBB::LiveScheduling::Intent.identifier(unit_id)
RBBB::LiveScheduling::Intent.identifier(principal_id)
allowed = %w[type command_id maximum_minor_units bid_id]
allowed = %w[type command_id maximum_minor_units bid_id expected_version]
raise ArgumentError, "unknown bid property" unless (command.keys - allowed).empty?
raise ArgumentError, "unsupported bid operation" unless %w[place_bid reduce_maximum].include?(command["type"])
RBBB::LiveScheduling::Intent.identifier(command["command_id"])
Expand All @@ -88,7 +90,7 @@ def void_bid(unit_id:, command:, principal_id:, permissions:)
def change_reserve(unit_id:, command:, principal_id:, permissions:)
RBBB::LiveScheduling::Intent.identifier(unit_id)
RBBB::LiveScheduling::Intent.identifier(principal_id)
allowed = %w[type command_id reserve_minor_units reason notification_policy]
allowed = %w[type command_id reserve_minor_units reason]
raise ArgumentError, "unknown reserve property" unless (command.keys - allowed).empty?
raise ArgumentError, "unsupported reserve operation" unless command["type"] == "change_reserve"
RBBB::LiveScheduling::Intent.identifier(command["command_id"])
Expand Down Expand Up @@ -175,14 +177,17 @@ def submit(request, principal, permissions)
observed = RBBB::Timestamp.parse(@clock.call)
at = last_time ? [observed, RBBB::Timestamp.parse(last_time)].max : observed
clock_rollback(observed, at) if at > observed
retired_ids = JSON.parse(retired_json)
coordinator = RBBB::LiveScheduling::Coordinator.new(auction_id: auction_id,
configurations: document["configurations"], snapshot: state, policy: document["policy"],
profile: document["profile"], retired_group_ids: JSON.parse(retired_json))
profile: document["profile"], retired_group_ids: retired_ids)
commit_id = next_commit_id
result = if sealed == 1
coordinator.send(:reject, "auction_sealed")
RBBB::LiveScheduling::Coordinator::Result.new(state: coordinator.snapshot, records: [],
rejection_reason: "auction_sealed", retired_group_ids: retired_ids)
elsif !permissions.include?(required)
coordinator.send(:reject, "not_authorized")
RBBB::LiveScheduling::Coordinator::Result.new(state: coordinator.snapshot, records: [],
rejection_reason: "not_authorized", retired_group_ids: retired_ids)
else
case request["kind"]
when "register"
Expand Down Expand Up @@ -248,12 +253,25 @@ def validate_retained_history!(db, stored)
# Successful no-event operations can have a receipt without a journal batch.
journaled = accepted.reject { |response| response.fetch("records").empty? }
valid &&= commits.size == journaled.size
valid &&= commits.all? do |commit_id, encoded|
matching = journaled.select { |response| response["commit_id"] == commit_id }
records = JSON.parse(encoded)
outbox = db.execute("SELECT record_index, record FROM outbox WHERE commit_id = ? ORDER BY record_index", [commit_id])
matching.size == 1 && matching.first.fetch("records") == records &&
outbox == records.each_with_index.map { |record, index| [index, JSON.generate(record)] }
if valid && !commits.empty?
journaled_by_commit = Hash.new { |hash, key| hash[key] = [] }
journaled.each { |response| journaled_by_commit[response["commit_id"]] << response }
outbox_by_commit = Hash.new { |hash, key| hash[key] = [] }
db.execute(
"SELECT o.commit_id, o.record_index, o.record FROM outbox o " \
"INNER JOIN commits c ON c.commit_id = o.commit_id " \
"WHERE c.tenant = ? AND c.auction = ? ORDER BY o.commit_id, o.record_index",
[tenant_id, auction_id]
).each do |commit_id, record_index, record|
outbox_by_commit[commit_id] << [record_index, record]
end
valid &&= commits.all? do |commit_id, encoded|
matching = journaled_by_commit[commit_id]
records = JSON.parse(encoded)
outbox = outbox_by_commit[commit_id]
matching.size == 1 && matching.first.fetch("records") == records &&
outbox == records.each_with_index.map { |record, index| [index, JSON.generate(record)] }
end
end
raise RBBB::InvalidState, "incomplete retained registry or history" unless valid
rescue JSON::ParserError, KeyError, TypeError
Expand All @@ -268,28 +286,6 @@ def row(db)
db.get_first_row("SELECT configuration, state, retired, sealed, last_time, sequence FROM auctions WHERE tenant = ? AND auction = ?", [tenant_id, auction_id])
end

def secure_file!
File.open(@path, File::WRONLY | File::CREAT | File::EXCL, 0o600) { |_| }
rescue Errno::EEXIST
stat = File.lstat(@path)
raise ArgumentError, "database must be an owner-only regular file" unless stat.file? && stat.uid == Process.uid && (stat.mode & 0o077).zero?
end

def transaction
db = SQLite3::Database.new(@path)
db.busy_timeout = 5000
db.execute("PRAGMA synchronous = FULL")
db.execute("BEGIN IMMEDIATE")
result = yield db
db.execute("COMMIT")
result
rescue Exception
db.execute("ROLLBACK") if db&.transaction_active?
raise
ensure
db&.close
end

def before_commit(_db); end
def after_commit(_response); end
def clock_rollback(_observed, _ordered)
Expand Down
2 changes: 1 addition & 1 deletion examples/live_scheduling_reader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def checkpoint(credential:, visibility:)
end
# Hash ONLY this authorized payload, never privileged state for a public
# response. Reauthorize every refetch; no shared cross-principal cache.
{"payload" => payload, "sha256" => Digest::SHA256.hexdigest(JSON.generate(payload))}
{"payload" => payload, "sha256" => Digest::SHA256.hexdigest(RBBB::LiveScheduling::Intent.canonical(payload))}
end
end
end
Expand Down
38 changes: 22 additions & 16 deletions examples/shared_group_host.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,22 +101,10 @@ def public_view
@mutex.synchronize { public_units(@snapshot.states, @snapshot.clock) }
end

private

# A durable adapter needs a database transaction, group-wide lock/CAS,
# and atomic receipt/event outbox writes in place of this publication.
def publish(candidate)
@snapshot = candidate
end

def synchronized_state(state, clock)
RBBB::State.from_h(state.to_h.merge("closes_at" => RBBB::Timestamp.dump(clock.closes_at)))
end

def public_units(states, clock)
states.to_h do |id, state|
[id, synchronized_state(state, clock).public_view.transform_values { |v| v.freeze }.freeze]
end.freeze
def public_snapshot
@mutex.synchronize do
{"clock" => @snapshot.clock.public_view, "units" => public_units(@snapshot.states, @snapshot.clock)}
end
end

def normalize_close_request(command_id, effective_at, revision)
Expand All @@ -143,5 +131,23 @@ def normalize_request(unit_id, command, revision)
copied = values.to_h { |k, v| [k.dup.freeze, v.is_a?(String) ? v.dup.freeze : v] }.freeze
{"unit_id" => unit_id.dup.freeze, "command" => copied, "expected_revision" => revision}.freeze
end

private

# A durable adapter needs a database transaction, group-wide lock/CAS,
# and atomic receipt/event outbox writes in place of this publication.
def publish(candidate)
@snapshot = candidate
end

def synchronized_state(state, clock)
RBBB::State.from_h(state.to_h.merge("closes_at" => RBBB::Timestamp.dump(clock.closes_at)))
end

def public_units(states, clock)
states.to_h do |id, state|
[id, synchronized_state(state, clock).public_view.transform_values { |v| v.freeze }.freeze]
end.freeze
end
end
end
35 changes: 35 additions & 0 deletions examples/support/sqlite_store.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# frozen_string_literal: true

require "sqlite3"

module RBBBExamples
# Shared SQLite file-safety and serialized-transaction helpers for local
# reference adapters. The core engine gem has no SQLite dependency.
module SqliteStore
private

def secure_file!
File.open(@path, File::WRONLY | File::CREAT | File::EXCL, 0o600) { |_| }
rescue Errno::EEXIST
stat = File.lstat(@path)
unless stat.file? && stat.uid == Process.uid && (stat.mode & 0o077).zero?
raise ArgumentError, "database must be an owner-only regular file"
end
end

def transaction
db = SQLite3::Database.new(@path)
db.busy_timeout = 5000
db.execute("PRAGMA synchronous = FULL")
db.execute("BEGIN IMMEDIATE")
result = yield db
db.execute("COMMIT")
result
rescue Exception
db.execute("ROLLBACK") if db&.transaction_active?
raise
ensure
db&.close
end
end
end
Loading