diff --git a/ruby/engine/lib/rbbb.rb b/ruby/engine/lib/rbbb.rb index 184e91d..d4d7574 100644 --- a/ruby/engine/lib/rbbb.rb +++ b/ruby/engine/lib/rbbb.rb @@ -14,7 +14,6 @@ class Error < StandardError; end class InvalidConfiguration < Error; end class InvalidMoney < Error; end class InvalidState < Error; end - class UnsupportedFeature < Error; end end require_relative "rbbb/money" diff --git a/ruby/engine/lib/rbbb/configuration.rb b/ruby/engine/lib/rbbb/configuration.rb index 8ce81bf..47bdb16 100644 --- a/ruby/engine/lib/rbbb/configuration.rb +++ b/ruby/engine/lib/rbbb/configuration.rb @@ -10,6 +10,10 @@ class Configuration :increment_schedule, :bid_ladder, :opens_at, :closes_at, :extension def self.from_h(attributes) + unless attributes.respond_to?(:transform_keys) + raise InvalidConfiguration, "configuration must be an object" + end + values = attributes.transform_keys(&:to_s) new( currency: values.fetch("currency"), @@ -54,6 +58,29 @@ def increment_for(minor_units) increment_schedule.increment_for(minor_units) end + def ==(other) + other.is_a?(Configuration) && equality_key == other.equality_key + end + alias eql? == + + def hash + [self.class, equality_key].hash + end + + protected + + def equality_key + [ + currency, + opening_minor_units, + reserve_minor_units, + increment_schedule.to_a, + Timestamp.dump(opens_at), + Timestamp.dump(closes_at), + extension + ] + end + private def parse_timestamp(value, field) diff --git a/ruby/engine/lib/rbbb/decision.rb b/ruby/engine/lib/rbbb/decision.rb index 8583de7..23ceba1 100644 --- a/ruby/engine/lib/rbbb/decision.rb +++ b/ruby/engine/lib/rbbb/decision.rb @@ -57,5 +57,28 @@ def accepted? def rejected? !accepted? end + + def transition_event + events.find do |event| + event.privileged? && Engine::STATE_TRANSITION_EVENTS.include?(event.type) + end + end + + def public_events + events.select(&:public?) + end + + def privileged_events + events.select(&:privileged?) + end + + def ==(other) + other.is_a?(Decision) && events == other.events && rejection == other.rejection + end + alias eql? == + + def hash + [self.class, events, rejection].hash + end end end diff --git a/ruby/engine/lib/rbbb/engine.rb b/ruby/engine/lib/rbbb/engine.rb index 4af8c8c..9cfaa94 100644 --- a/ruby/engine/lib/rbbb/engine.rb +++ b/ruby/engine/lib/rbbb/engine.rb @@ -21,6 +21,8 @@ class Engine closing_time_changed bidding_closed ].freeze + MAX_IDENTIFIER_LENGTH = 255 + TWO_DECIMAL_CURRENCIES = %w[USD EUR GBP CAD AUD NZD CHF].freeze attr_reader :configuration @@ -43,9 +45,13 @@ def decide(state, command) values = command.transform_keys(&:to_s) command_id = values["command_id"] return reject(command_id, "unsupported_command") unless SUPPORTED_COMMANDS.include?(values["type"]) - return reject(command_id, "invalid_command") unless present_string?(command_id) - if values.key?("expected_version") && values["expected_version"] != state.version - return reject(command_id, "stale_aggregate_version") + return reject(command_id, "invalid_command") unless valid_command_id?(command_id) + if values.key?("expected_version") + expected_version = values["expected_version"] + unless expected_version.is_a?(Integer) && expected_version.between?(0, MAX_SAFE_INTEGER) + return reject(command_id, "invalid_command") + end + return reject(command_id, "stale_aggregate_version") unless expected_version == state.version end return reject(command_id, "bidding_closed") if state.closed? if time_regressed?(state, authoritative_time(values)) @@ -73,25 +79,32 @@ def decide(state, command) end def apply(state, events) + raise InvalidState, "engine requires an RBBB::State" unless state.is_a?(State) + return state if events.empty? + transitions = events.select do |event| - event.privileged? && STATE_TRANSITION_EVENTS.include?(event.type) + event.is_a?(Event) && event.privileged? && STATE_TRANSITION_EVENTS.include?(event.type) end - if transitions.length > 1 + unless transitions.length == 1 raise InvalidState, "apply accepts the events of exactly one accepted command" end - transition = transitions.first - return state unless transition + raise InvalidState, "cannot apply transition to closed state" if state.closed? + raise InvalidState, "aggregate version exhausted" if state.version >= MAX_SAFE_INTEGER + transition = transitions.first aggregate_version = transition.data.fetch("aggregate_version") unless aggregate_version == state.version + 1 raise InvalidState, "event aggregate version is not the next version" end + validate_transition_time!(state, transition) validate_transition_history!(state, transition, aggregate_version) # Every transition carries the full aggregate snapshot, so the next state # is exactly what a host would restore from this event. validate_ladder_state!(State.from_transition(configuration, transition)) + rescue KeyError + raise InvalidState, "transition event is missing required fields" end # Rebuild aggregate state from one privileged state-transition event @@ -126,7 +139,11 @@ def validate_ladder_state!(state) def decide_place_bid(state, command) bidder_id = command.fetch("bidder_id").to_s - bid_id = command["bid_id"] || command.fetch("command_id") + bid_id = if command.key?("bid_id") && !command["bid_id"].nil? + command["bid_id"] + else + command.fetch("command_id") + end maximum = command["maximum_minor_units"] command_id = command["command_id"] return reject(command_id, "invalid_command") unless present_string?(bid_id) @@ -227,11 +244,13 @@ def decide_change_reserve(state, command) def decide_change_closing_time(state, command) command_id = command.fetch("command_id") - unless valid_operator_command?(command) && present_string?(command["closes_at"]) + closes_at_input = command["closes_at"] + unless valid_operator_command?(command) && + (present_string?(closes_at_input) || closes_at_input.is_a?(Time)) return reject(command_id, "invalid_command") end - new_closes_at = Timestamp.parse(command.fetch("closes_at")) + new_closes_at = Timestamp.parse(closes_at_input) effective_at = authoritative_time(command) return reject(command_id, "invalid_command") unless effective_at @@ -261,7 +280,7 @@ def decide_close_bidding(state, command) end def build_bid_decision(state, command, bid_id, bidder_id, maximum, existing, effective_at) - aggregate_version = state.version + 1 + aggregate_version = next_aggregate_version(state) authorization_history = state.authorization_history.map(&:dup) authorization_history << { "type" => "place_bid", @@ -278,9 +297,7 @@ def build_bid_decision(state, command, bid_id, bidder_id, maximum, existing, eff "executed_minor_units" => existing&.executed_minor_units || 0 } - ranked = positions.sort_by do |id, position| - [-position.fetch("executable_maximum_minor_units"), position.fetch("priority"), id] - end + ranked = positions.sort_by { |id, position| leader_key(id, position) } leader_id = ranked.fetch(0).first standing = if existing && existing.executable_maximum_minor_units == configuration.bid_ladder.floor(maximum) state.standing_minor_units @@ -294,75 +311,56 @@ def build_bid_decision(state, command, bid_id, bidder_id, maximum, existing, eff public_result_changed = standing != state.standing_minor_units || leader_id != state.leader_id closes_at = extended_closing_time(state, effective_at, public_result_changed) + return reject(command.fetch("command_id"), "invalid_closing_time") unless closes_at - positions.each do |id, position| - executed = id == leader_id ? standing : position.fetch("executable_maximum_minor_units") - position["executed_minor_units"] = [ - position.fetch("executed_minor_units"), - executed - ].max - end + apply_executions!(positions, "leader_id" => leader_id, "standing_minor_units" => standing) event_type = existing ? "maximum_increased" : "maximum_accepted" privileged = Event.new( type: event_type, visibility: :privileged, - data: { - "command_id" => command.fetch("command_id"), - "aggregate_version" => aggregate_version, + data: transition_snapshot( + state, + command, + aggregate_version, + effective_at: effective_at, + leader_id: leader_id, + standing_minor_units: standing, + next_required_minor_units: next_required, + reserve_status: reserve_status, + closes_at: closes_at, + positions: positions, + authorization_history: authorization_history + ).merge( "bid_id" => bid_id, "bidder_id" => bidder_id, "maximum_minor_units" => maximum, "bidder_notice" => maximum_notice(maximum), - "executed_minor_units" => positions.fetch(bidder_id).fetch("executed_minor_units"), - "leader_id" => leader_id, - "standing_minor_units" => standing, - "next_required_minor_units" => next_required, - "reserve_status" => reserve_status, - "reserve_minor_units" => state.reserve_minor_units, - "effective_at" => Timestamp.dump(effective_at), - "closes_at" => Timestamp.dump(closes_at), - "positions" => positions, - "authorization_history" => authorization_history, - "reserve_history" => state.reserve_history, - "voided_bid_ids" => state.voided_bid_ids - } + "executed_minor_units" => positions.fetch(bidder_id).fetch("executed_minor_units") + ) ) events = [privileged] if standing != state.standing_minor_units || leader_id != state.leader_id || reserve_status != state.reserve_status - public_data = { - "command_id" => command.fetch("command_id"), - "aggregate_version" => aggregate_version, - "standing_minor_units" => standing, - "next_required_minor_units" => next_required, - "leader_changed" => leader_id != state.leader_id - } - public_data["reserve_status"] = reserve_status if reserve_status - events << Event.new( - type: "standing_bid_changed", - visibility: :public, - data: public_data + events << standing_bid_event( + command, + aggregate_version, + standing_minor_units: standing, + next_required_minor_units: next_required, + leader_changed: leader_id != state.leader_id, + reserve_status: reserve_status ) end if closes_at != state.closes_at - events << Event.new( - type: "closing_time_changed", - visibility: :public, - data: { - "command_id" => command.fetch("command_id"), - "aggregate_version" => aggregate_version, - "closes_at" => Timestamp.dump(closes_at) - } - ) + events << closing_time_event(command, aggregate_version, closes_at: closes_at) end Decision.accepted(events) end def build_reduction_decision(state, command, bidder_id, maximum, existing, effective_at) - aggregate_version = state.version + 1 + aggregate_version = next_aggregate_version(state) authorization_history = state.authorization_history.map(&:dup) authorization_history << { "type" => "maximum_reduced", @@ -378,61 +376,51 @@ def build_reduction_decision(state, command, bidder_id, maximum, existing, effec "executed_minor_units" => existing.executed_minor_units } - leader_id = positions.min_by do |id, position| - [-position.fetch("executable_maximum_minor_units"), position.fetch("priority"), id] - end.first + leader_id = positions.min_by { |id, position| leader_key(id, position) }.first leader_changed = leader_id != state.leader_id closes_at = extended_closing_time(state, effective_at, leader_changed) + return reject(command.fetch("command_id"), "invalid_closing_time") unless closes_at event = Event.new( type: "maximum_reduced", visibility: :privileged, - data: { - "command_id" => command.fetch("command_id"), - "aggregate_version" => aggregate_version, + data: transition_snapshot( + state, + command, + aggregate_version, + effective_at: effective_at, + leader_id: leader_id, + closes_at: closes_at, + positions: positions, + authorization_history: authorization_history + ).merge( "bidder_id" => bidder_id, "old_maximum_minor_units" => existing.maximum_minor_units, "new_maximum_minor_units" => maximum, "bidder_notice" => maximum_notice(maximum), - "executed_floor_minor_units" => existing.executed_minor_units, - "leader_id" => leader_id, - "standing_minor_units" => state.standing_minor_units, - "next_required_minor_units" => state.next_required_minor_units, - "reserve_status" => state.reserve_status, - "reserve_minor_units" => state.reserve_minor_units, - "effective_at" => Timestamp.dump(effective_at), - "closes_at" => Timestamp.dump(closes_at), - "positions" => positions, - "authorization_history" => authorization_history, - "reserve_history" => state.reserve_history, - "voided_bid_ids" => state.voided_bid_ids - } + "executed_floor_minor_units" => existing.executed_minor_units + ) ) events = [event] if leader_changed - public_data = { - "command_id" => command.fetch("command_id"), - "aggregate_version" => aggregate_version, - "standing_minor_units" => state.standing_minor_units, - "next_required_minor_units" => state.next_required_minor_units, - "leader_changed" => true - } - public_data["reserve_status"] = state.reserve_status if state.reserve_status - events << Event.new(type: "standing_bid_changed", visibility: :public, data: public_data) + events << standing_bid_event( + command, + aggregate_version, + standing_minor_units: state.standing_minor_units, + next_required_minor_units: state.next_required_minor_units, + leader_changed: true, + reserve_status: state.reserve_status + ) end if closes_at != state.closes_at - events << Event.new(type: "closing_time_changed", visibility: :public, data: { - "command_id" => command.fetch("command_id"), - "aggregate_version" => aggregate_version, - "closes_at" => Timestamp.dump(closes_at) - }) + events << closing_time_event(command, aggregate_version, closes_at: closes_at) end Decision.accepted(events) end def build_reserve_change_decision(state, command, new_reserve, effective_at) - aggregate_version = state.version + 1 + aggregate_version = next_aggregate_version(state) reserve_history = state.reserve_history.map(&:dup) reserve_history << { "old_reserve_minor_units" => state.reserve_minor_units, @@ -441,29 +429,22 @@ def build_reserve_change_decision(state, command, new_reserve, effective_at) } leader = state.position_for(state.leader_id) reserve_status = reserve_status_for(leader&.to_h, new_reserve) - common_data = { - "command_id" => command.fetch("command_id"), - "aggregate_version" => aggregate_version - } transition = Event.new( type: "reserve_changed", visibility: :privileged, - data: common_data.merge( + data: transition_snapshot( + state, + command, + aggregate_version, + effective_at: effective_at, + reserve_status: reserve_status, + reserve_minor_units: new_reserve, + reserve_history: reserve_history + ).merge( "operator_id" => command.fetch("operator_id"), "reason" => command.fetch("reason"), "old_reserve_minor_units" => state.reserve_minor_units, - "new_reserve_minor_units" => new_reserve, - "effective_at" => Timestamp.dump(effective_at), - "leader_id" => state.leader_id, - "standing_minor_units" => state.standing_minor_units, - "next_required_minor_units" => state.next_required_minor_units, - "reserve_status" => reserve_status, - "reserve_minor_units" => new_reserve, - "closes_at" => Timestamp.dump(state.closes_at), - "positions" => state.positions.transform_values(&:to_h), - "authorization_history" => state.authorization_history, - "reserve_history" => reserve_history, - "voided_bid_ids" => state.voided_bid_ids + "new_reserve_minor_units" => new_reserve ) ) @@ -472,7 +453,11 @@ def build_reserve_change_decision(state, command, new_reserve, effective_at) events << Event.new( type: "reserve_status_changed", visibility: :public, - data: common_data.merge("reserve_status" => reserve_status) + data: { + "command_id" => command.fetch("command_id"), + "aggregate_version" => aggregate_version, + "reserve_status" => reserve_status + } ) end @@ -480,72 +465,58 @@ def build_reserve_change_decision(state, command, new_reserve, effective_at) end def build_closing_time_change_decision(state, command, new_closes_at, effective_at) - aggregate_version = state.version + 1 + aggregate_version = next_aggregate_version(state) old_closes_at = state.closes_at - common_data = { - "command_id" => command.fetch("command_id"), - "aggregate_version" => aggregate_version, - "old_closes_at" => Timestamp.dump(old_closes_at), - "closes_at" => Timestamp.dump(new_closes_at) - } transition = Event.new( type: "closing_time_changed", visibility: :privileged, - data: common_data.merge( + data: transition_snapshot( + state, + command, + aggregate_version, + effective_at: effective_at, + closes_at: new_closes_at + ).merge( "operator_id" => command.fetch("operator_id"), "reason" => command.fetch("reason"), - "effective_at" => Timestamp.dump(effective_at), - "leader_id" => state.leader_id, - "standing_minor_units" => state.standing_minor_units, - "next_required_minor_units" => state.next_required_minor_units, - "reserve_status" => state.reserve_status, - "reserve_minor_units" => state.reserve_minor_units, - "positions" => state.positions.transform_values(&:to_h), - "authorization_history" => state.authorization_history, - "reserve_history" => state.reserve_history, - "voided_bid_ids" => state.voided_bid_ids + "old_closes_at" => Timestamp.dump(old_closes_at) ) ) - public_event = Event.new( - type: "closing_time_changed", - visibility: :public, - data: common_data + public_event = closing_time_event( + command, + aggregate_version, + closes_at: new_closes_at, + old_closes_at: old_closes_at ) Decision.accepted([transition, public_event]) end def build_closing_decision(state, command, effective_at) - aggregate_version = state.version + 1 + aggregate_version = next_aggregate_version(state) result = closing_result(state) winner_id = result == "sold" ? state.leader_id : nil winning_minor_units = result == "sold" ? state.standing_minor_units : nil - common_data = { - "command_id" => command.fetch("command_id"), - "aggregate_version" => aggregate_version, - "result" => result - } transition = Event.new( type: "bidding_closed", visibility: :privileged, - data: common_data.merge( - "effective_at" => Timestamp.dump(effective_at), - "leader_id" => state.leader_id, - "standing_minor_units" => state.standing_minor_units, - "next_required_minor_units" => state.next_required_minor_units, - "reserve_status" => state.reserve_status, - "reserve_minor_units" => state.reserve_minor_units, - "closes_at" => Timestamp.dump(state.closes_at), - "positions" => state.positions.transform_values(&:to_h), - "authorization_history" => state.authorization_history, - "reserve_history" => state.reserve_history, - "voided_bid_ids" => state.voided_bid_ids, + data: transition_snapshot( + state, + command, + aggregate_version, + effective_at: effective_at + ).merge( + "result" => result, "status" => "closed", "winner_id" => winner_id, "winning_minor_units" => winning_minor_units ) ) - public_data = common_data.dup + public_data = { + "command_id" => command.fetch("command_id"), + "aggregate_version" => aggregate_version, + "result" => result + } case result when "sold" public_data["winning_minor_units"] = winning_minor_units @@ -562,7 +533,7 @@ def build_closing_decision(state, command, effective_at) end def build_void_decision(state, command, target, effective_at) - aggregate_version = state.version + 1 + aggregate_version = next_aggregate_version(state) voided_bid_ids = [*state.voided_bid_ids, command.fetch("bid_id")] recomputed = replay_authorizations( state.authorization_history, @@ -576,6 +547,8 @@ def build_void_decision(state, command, target, effective_at) else state.closes_at end + return reject(command.fetch("command_id"), "invalid_closing_time") unless closes_at + common_data = { "command_id" => command.fetch("command_id"), "aggregate_version" => aggregate_version @@ -584,23 +557,24 @@ def build_void_decision(state, command, target, effective_at) events = [Event.new( type: "bid_voided", visibility: :privileged, - data: common_data.merge( + data: transition_snapshot( + state, + command, + aggregate_version, + effective_at: effective_at, + leader_id: recomputed.fetch("leader_id"), + standing_minor_units: recomputed.fetch("standing_minor_units"), + next_required_minor_units: recomputed.fetch("next_required_minor_units"), + reserve_status: recomputed.fetch("reserve_status"), + closes_at: closes_at, + positions: recomputed.fetch("positions"), + voided_bid_ids: voided_bid_ids + ).merge( "bid_id" => command.fetch("bid_id"), "bidder_id" => target.fetch("bidder_id"), "operator_id" => command.fetch("operator_id"), "reason" => command.fetch("reason"), - "notification_policy" => command.fetch("notification_policy"), - "effective_at" => Timestamp.dump(effective_at), - "leader_id" => recomputed.fetch("leader_id"), - "standing_minor_units" => recomputed.fetch("standing_minor_units"), - "next_required_minor_units" => recomputed.fetch("next_required_minor_units"), - "reserve_status" => recomputed.fetch("reserve_status"), - "reserve_minor_units" => state.reserve_minor_units, - "closes_at" => Timestamp.dump(closes_at), - "positions" => recomputed.fetch("positions"), - "authorization_history" => state.authorization_history, - "reserve_history" => state.reserve_history, - "voided_bid_ids" => voided_bid_ids + "notification_policy" => command.fetch("notification_policy") ) )] @@ -613,26 +587,18 @@ def build_void_decision(state, command, target, effective_at) end if public_state_changed?(state, recomputed) - public_data = common_data.merge( - "standing_minor_units" => recomputed.fetch("standing_minor_units"), - "next_required_minor_units" => recomputed.fetch("next_required_minor_units"), - "leader_changed" => state.leader_id != recomputed.fetch("leader_id") - ) - reserve_status = recomputed.fetch("reserve_status") - public_data["reserve_status"] = reserve_status if reserve_status - events << Event.new( - type: "standing_bid_changed", - visibility: :public, - data: public_data + events << standing_bid_event( + command, + aggregate_version, + standing_minor_units: recomputed.fetch("standing_minor_units"), + next_required_minor_units: recomputed.fetch("next_required_minor_units"), + leader_changed: state.leader_id != recomputed.fetch("leader_id"), + reserve_status: recomputed.fetch("reserve_status") ) end if closes_at != state.closes_at - events << Event.new( - type: "closing_time_changed", - visibility: :public, - data: common_data.merge("closes_at" => Timestamp.dump(closes_at)) - ) + events << closing_time_event(command, aggregate_version, closes_at: closes_at) end events << Event.new( @@ -703,9 +669,7 @@ def replay_authorizations(history, voided_bid_ids, reserve_history) existing["priority"] = position_priority(existing, maximum, entry.fetch("priority")) existing["maximum_minor_units"] = maximum existing["executable_maximum_minor_units"] = configuration.bid_ladder.floor(maximum) - snapshot["leader_id"] = positions.min_by do |id, position| - [-position.fetch("executable_maximum_minor_units"), position.fetch("priority"), id] - end.first + snapshot["leader_id"] = positions.min_by { |id, position| leader_key(id, position) }.first end end @@ -713,9 +677,7 @@ def replay_authorizations(history, voided_bid_ids, reserve_history) end def price_positions(positions, reserve_minor_units, bidder_id, previous) - ranked = positions.sort_by do |id, position| - [-position.fetch("executable_maximum_minor_units"), position.fetch("priority"), id] - end + ranked = positions.sort_by { |id, position| leader_key(id, position) } leader_id = ranked.fetch(0).first standing = standing_after_bid(ranked, reserve_minor_units, bidder_id, previous.fetch("leader_id"), previous.fetch("standing_minor_units")) @@ -837,7 +799,10 @@ def extended_closing_time(state, effective_at, public_result_changed) # An extension may only push closing later. A duration shorter than the # remaining time must never pull the close forward. - [state.closes_at, effective_at + configuration.extension.fetch("duration_seconds")].max + candidate = [state.closes_at, effective_at + configuration.extension.fetch("duration_seconds")].max + Timestamp.parse(candidate) + rescue ArgumentError, RangeError + nil end # The next required amount saturates at the interoperable bound so that @@ -856,7 +821,7 @@ def maximum_notice(maximum) following = configuration.bid_ladder.above(executable) format_amount = lambda do |amount| - if %w[USD EUR GBP CAD AUD NZD CHF].include?(configuration.currency) + if TWO_DECIMAL_CURRENCIES.include?(configuration.currency) "#{configuration.currency} #{amount / 100}.#{(amount % 100).to_s.rjust(2, '0')}" else "#{amount} minor units (#{configuration.currency})" @@ -906,13 +871,89 @@ def reserve_status_for(leader, reserve_minor_units) end def reject(command_id, reason, **fields) - Decision.rejected(command_id: command_id, reason: reason, **fields) + sanitized_id = valid_command_id?(command_id) ? command_id : nil + Decision.rejected(command_id: sanitized_id, reason: reason, **fields) + end + + def valid_command_id?(value) + present_string?(value) && value.length <= MAX_IDENTIFIER_LENGTH end def present_string?(value) value.is_a?(String) && !value.empty? end + def next_aggregate_version(state) + next_version = state.version + 1 + raise InvalidState, "aggregate version exhausted" if next_version > MAX_SAFE_INTEGER + + next_version + end + + def leader_key(id, position) + [-position.fetch("executable_maximum_minor_units"), position.fetch("priority"), id] + end + + def transition_snapshot(state, command, aggregate_version, effective_at:, + leader_id: state.leader_id, + standing_minor_units: state.standing_minor_units, + next_required_minor_units: state.next_required_minor_units, + reserve_status: state.reserve_status, + reserve_minor_units: state.reserve_minor_units, + closes_at: state.closes_at, + positions: state.positions.transform_values(&:to_h), + authorization_history: state.authorization_history, + reserve_history: state.reserve_history, + voided_bid_ids: state.voided_bid_ids) + { + "command_id" => command.fetch("command_id"), + "aggregate_version" => aggregate_version, + "leader_id" => leader_id, + "standing_minor_units" => standing_minor_units, + "next_required_minor_units" => next_required_minor_units, + "reserve_status" => reserve_status, + "reserve_minor_units" => reserve_minor_units, + "effective_at" => Timestamp.dump(effective_at), + "closes_at" => Timestamp.dump(closes_at), + "positions" => positions, + "authorization_history" => authorization_history, + "reserve_history" => reserve_history, + "voided_bid_ids" => voided_bid_ids + } + end + + def standing_bid_event(command, aggregate_version, standing_minor_units:, next_required_minor_units:, + leader_changed:, reserve_status:) + public_data = { + "command_id" => command.fetch("command_id"), + "aggregate_version" => aggregate_version, + "standing_minor_units" => standing_minor_units, + "next_required_minor_units" => next_required_minor_units, + "leader_changed" => leader_changed + } + public_data["reserve_status"] = reserve_status if reserve_status + Event.new(type: "standing_bid_changed", visibility: :public, data: public_data) + end + + def closing_time_event(command, aggregate_version, closes_at:, old_closes_at: nil) + data = { + "command_id" => command.fetch("command_id"), + "aggregate_version" => aggregate_version, + "closes_at" => Timestamp.dump(closes_at) + } + data["old_closes_at"] = Timestamp.dump(old_closes_at) if old_closes_at + Event.new(type: "closing_time_changed", visibility: :public, data: data) + end + + def validate_transition_time!(state, transition) + effective_at = Timestamp.parse(transition.data.fetch("effective_at")) + if state.last_effective_at && effective_at < state.last_effective_at + raise InvalidState, "transition effective_at precedes state last_effective_at" + end + rescue ArgumentError, KeyError + raise InvalidState, "transition effective_at is invalid" + end + def valid_operator_command?(command) present_string?(command["operator_id"]) && present_string?(command["reason"]) end diff --git a/ruby/engine/lib/rbbb/event.rb b/ruby/engine/lib/rbbb/event.rb index 9d26482..74427b1 100644 --- a/ruby/engine/lib/rbbb/event.rb +++ b/ruby/engine/lib/rbbb/event.rb @@ -28,6 +28,15 @@ def to_h {"type" => type}.merge(data) end + def ==(other) + other.is_a?(Event) && type == other.type && visibility == other.visibility && data == other.data + end + alias eql? == + + def hash + [self.class, type, visibility, data].hash + end + private def deep_freeze(value) diff --git a/ruby/engine/lib/rbbb/initial_closing_schedule.rb b/ruby/engine/lib/rbbb/initial_closing_schedule.rb index 2339b21..62bfbcf 100644 --- a/ruby/engine/lib/rbbb/initial_closing_schedule.rb +++ b/ruby/engine/lib/rbbb/initial_closing_schedule.rb @@ -59,9 +59,7 @@ def identities(values) private_class_method :identities def timestamp(value) - time = Timestamp.parse(value) - raise InvalidConfiguration, "timestamp outside supported year range" unless time.year.between?(1, 9999) - time + Timestamp.parse(value) rescue ArgumentError, RangeError raise InvalidConfiguration, "invalid scheduling timestamp" end diff --git a/ruby/engine/lib/rbbb/shared_closing_clock.rb b/ruby/engine/lib/rbbb/shared_closing_clock.rb index ec6bc94..2f464cf 100644 --- a/ruby/engine/lib/rbbb/shared_closing_clock.rb +++ b/ruby/engine/lib/rbbb/shared_closing_clock.rb @@ -3,7 +3,7 @@ module RBBB # RFC 0003 clock component; the host owns atomic unit/clock persistence. class SharedClosingClock - attr_reader :revision, :closes_at, :quiet_period_seconds, :last_effective_at + attr_reader :group_id, :unit_ids, :revision, :closes_at, :quiet_period_seconds, :last_effective_at def initialize(group_id:, unit_ids:, closes_at:, quiet_period_seconds:, revision: 0, last_effective_at: nil) unless group_id.is_a?(String) && !group_id.empty? && unit_ids.is_a?(Array) && !unit_ids.empty? && @@ -69,6 +69,15 @@ def to_h public_view.merge("quiet_period_seconds" => quiet_period_seconds, "last_effective_at" => Timestamp.dump(last_effective_at)) end + def ==(other) + other.is_a?(SharedClosingClock) && to_h == other.to_h + end + alias eql? == + + def hash + [self.class, to_h].hash + end + private # RFC 0004: any accepted change to the public standing qualifies, except the @@ -82,9 +91,7 @@ def qualifying?(transition, decision) end def parse_time(value) - time = Timestamp.parse(value) - raise InvalidConfiguration, "timestamp outside supported range" unless time.year.between?(1, 9999) - time + Timestamp.parse(value) rescue ArgumentError, RangeError raise InvalidConfiguration, "invalid clock timestamp" end diff --git a/ruby/engine/lib/rbbb/state.rb b/ruby/engine/lib/rbbb/state.rb index 8e142ec..40091ec 100644 --- a/ruby/engine/lib/rbbb/state.rb +++ b/ruby/engine/lib/rbbb/state.rb @@ -73,7 +73,7 @@ def self.empty(configuration) # Rebuild a validated state from a `State#to_h` snapshot. Identity keys # added by the host are ignored; every snapshot key must be present. - def self.from_h(snapshot) + def self.from_h(snapshot, bid_ladder: nil) raise InvalidState, "snapshot must be an object" unless snapshot.respond_to?(:transform_keys) values = snapshot.transform_keys(&:to_s) @@ -97,7 +97,8 @@ def self.from_h(snapshot) status: values.fetch("status"), result: values.fetch("result"), winner_id: values.fetch("winner_id"), - winning_minor_units: values.fetch("winning_minor_units") + winning_minor_units: values.fetch("winning_minor_units"), + bid_ladder: bid_ladder ) rescue NoMethodError, TypeError raise InvalidState, "snapshot is malformed" @@ -117,23 +118,26 @@ def self.from_transition(configuration, event_or_data) raise InvalidState, "transition is missing #{missing.join(', ')}" if missing.any? from_h( - "version" => values.fetch("aggregate_version"), - "status" => values.fetch("status", "open"), - "opens_at" => configuration.opens_at, - "closes_at" => values["closes_at"], - "last_effective_at" => values["effective_at"], - "reserve_minor_units" => values["reserve_minor_units"], - "reserve_status" => values["reserve_status"], - "leader_id" => values["leader_id"], - "standing_minor_units" => values["standing_minor_units"], - "next_required_minor_units" => values["next_required_minor_units"], - "positions" => values["positions"], - "authorization_history" => values["authorization_history"], - "reserve_history" => values["reserve_history"], - "voided_bid_ids" => values["voided_bid_ids"], - "result" => values["result"], - "winner_id" => values["winner_id"], - "winning_minor_units" => values["winning_minor_units"] + { + "version" => values.fetch("aggregate_version"), + "status" => values.fetch("status", "open"), + "opens_at" => configuration.opens_at, + "closes_at" => values["closes_at"], + "last_effective_at" => values["effective_at"], + "reserve_minor_units" => values["reserve_minor_units"], + "reserve_status" => values["reserve_status"], + "leader_id" => values["leader_id"], + "standing_minor_units" => values["standing_minor_units"], + "next_required_minor_units" => values["next_required_minor_units"], + "positions" => values["positions"], + "authorization_history" => values["authorization_history"], + "reserve_history" => values["reserve_history"], + "voided_bid_ids" => values["voided_bid_ids"], + "result" => values["result"], + "winner_id" => values["winner_id"], + "winning_minor_units" => values["winning_minor_units"] + }, + bid_ladder: configuration.bid_ladder ) end @@ -142,7 +146,7 @@ def initialize(version:, positions:, leader_id:, standing_minor_units:, last_effective_at: nil, reserve_minor_units: nil, authorization_history: [], reserve_history: [], voided_bid_ids: [], status: "open", result: nil, winner_id: nil, - winning_minor_units: nil) + winning_minor_units: nil, bid_ladder: nil) @version = version @positions = positions.each_with_object({}) do |(bidder_id, position), copy| copy[bidder_id.to_s.freeze] = coerce_position(position) @@ -166,7 +170,7 @@ def initialize(version:, positions:, leader_id:, standing_minor_units:, @result = result&.to_s&.freeze @winner_id = winner_id&.to_s&.freeze @winning_minor_units = winning_minor_units - validate! + validate!(bid_ladder: bid_ladder) freeze end @@ -234,6 +238,15 @@ def public_view } end + def ==(other) + other.is_a?(State) && to_h == other.to_h + end + alias eql? == + + def hash + [self.class, to_h].hash + end + private def coerce_timestamp(value, field) @@ -285,10 +298,12 @@ def coerce_reserve_change(entry) raise InvalidState, "reserve change is missing #{e.key}" end - def validate! - raise InvalidState, "version must be a non-negative integer" unless version.is_a?(Integer) && version >= 0 - unless next_required_minor_units.is_a?(Integer) && next_required_minor_units >= 0 - raise InvalidState, "next required amount must be a non-negative integer" + def validate!(bid_ladder: nil) + unless version.is_a?(Integer) && version.between?(0, MAX_SAFE_INTEGER) + raise InvalidState, "version must be a non-negative integer no greater than #{MAX_SAFE_INTEGER}" + end + unless Money.amount?(next_required_minor_units) + raise InvalidState, "next required amount must be a non-negative integer no greater than #{Money::MAX_MINOR_UNITS}" end unless [nil, "reserve_not_met", "reserve_met"].include?(reserve_status) raise InvalidState, "reserve status is invalid" @@ -315,8 +330,8 @@ def validate! end positions.each_value do |position| - unless position.maximum_minor_units.is_a?(Integer) && position.maximum_minor_units >= 0 - raise InvalidState, "maximums must be non-negative integers" + unless Money.amount?(position.maximum_minor_units) + raise InvalidState, "maximums must be non-negative integers no greater than #{Money::MAX_MINOR_UNITS}" end unless Money.amount?(position.executable_maximum_minor_units) && position.executable_maximum_minor_units <= position.maximum_minor_units @@ -334,13 +349,19 @@ def validate! return unless leader_id leader = positions.fetch(leader_id) - unless standing_minor_units.is_a?(Integer) && - standing_minor_units.between?(0, leader.executable_maximum_minor_units) + unless Money.amount?(standing_minor_units) && + standing_minor_units <= leader.executable_maximum_minor_units raise InvalidState, "standing amount must be within the leader maximum" end - # The next required amount saturates at the interoperable bound, so the - # two are permitted to be equal only when both sit on that bound. - saturated = standing_minor_units == next_required_minor_units + # The next required amount saturates only at the final rung of the bid + # ladder, where no higher rung fits within Money::MAX_MINOR_UNITS. + saturated = standing_minor_units == next_required_minor_units && + if bid_ladder + bid_ladder.above(standing_minor_units).nil? + else + standing_minor_units == leader.executable_maximum_minor_units && + standing_minor_units > Money::MAX_MINOR_UNITS / 2 + end unless saturated || next_required_minor_units > standing_minor_units raise InvalidState, "next required amount must exceed standing amount" end @@ -365,9 +386,8 @@ def validate_authorization_history! unless %w[place_bid maximum_reduced].include?(entry.fetch("type")) raise InvalidState, "authorization type is invalid" end - unless entry.fetch("maximum_minor_units").is_a?(Integer) && - entry.fetch("maximum_minor_units") >= 0 - raise InvalidState, "authorization maximum must be a non-negative integer" + unless Money.amount?(entry.fetch("maximum_minor_units")) + raise InvalidState, "authorization maximum must be a non-negative integer no greater than #{Money::MAX_MINOR_UNITS}" end if entry.fetch("bidder_id").empty? raise InvalidState, "authorization bidder ID must be present" @@ -425,7 +445,7 @@ def validate_reserve_history! end def valid_optional_minor_units?(value) - value.nil? || (value.is_a?(Integer) && value >= 0) + value.nil? || Money.amount?(value) end def validate_lifecycle! diff --git a/ruby/engine/lib/rbbb/timestamp.rb b/ruby/engine/lib/rbbb/timestamp.rb index e448284..2c3b9b1 100644 --- a/ruby/engine/lib/rbbb/timestamp.rb +++ b/ruby/engine/lib/rbbb/timestamp.rb @@ -10,6 +10,7 @@ module Timestamp # same command stream to the same closing times. PRECISION_DIGITS = 3 NANOSECONDS_PER_UNIT = 10**(9 - PRECISION_DIGITS) + YEAR_RANGE = (1..9999).freeze # Date, "T", time, optional fraction of at most PRECISION_DIGITS digits, # and a mandatory zone designator. Ruby's Time.iso8601 silently treats a @@ -34,11 +35,15 @@ def parse(value) raise ArgumentError, "timestamp must be an ISO 8601 string or Time" end - unless (time.nsec % NANOSECONDS_PER_UNIT).zero? + utc = time.getutc + unless YEAR_RANGE.include?(utc.year) + raise ArgumentError, "timestamp year must be within #{YEAR_RANGE.begin}..#{YEAR_RANGE.end}" + end + unless (utc.nsec % NANOSECONDS_PER_UNIT).zero? raise ArgumentError, "timestamp precision must not exceed #{PRECISION_DIGITS} fractional digits" end - time.getutc.freeze + utc.freeze end # Canonical form: UTC with "Z", the fraction omitted when zero and @@ -46,7 +51,12 @@ def parse(value) def dump(time) return nil unless time - formatted = time.getutc.iso8601(PRECISION_DIGITS) + utc = time.getutc + unless YEAR_RANGE.include?(utc.year) + raise ArgumentError, "timestamp year must be within #{YEAR_RANGE.begin}..#{YEAR_RANGE.end}" + end + + formatted = utc.iso8601(PRECISION_DIGITS) formatted.sub!(/0+Z\z/, "Z") formatted.sub!(/\.Z\z/, "Z") formatted diff --git a/ruby/engine/test/decision_test.rb b/ruby/engine/test/decision_test.rb index 1dd1ad8..26999a5 100644 --- a/ruby/engine/test/decision_test.rb +++ b/ruby/engine/test/decision_test.rb @@ -70,4 +70,45 @@ def test_reason_specific_fields_match_the_rejection_schema assert_equal RBBB::Decision::REASON_SPECIFIC_FIELDS, scoped assert_equal declared.sort, RBBB::Decision::REASON_SPECIFIC_FIELDS.values.flatten.sort end + + def test_event_accessors_and_value_equality + engine = RBBB::Engine.new(RBBB::Configuration.new( + currency: "USD", + opening_minor_units: 10_000, + increments: [{from_minor_units: 0, amount_minor_units: 1_000}], + opens_at: "2026-09-01T12:00:00Z", + closes_at: "2026-09-01T13:00:00Z" + )) + command = { + command_id: "command-1", + type: "place_bid", + bidder_id: "bidder-a", + maximum_minor_units: 50_000, + effective_at: "2026-09-01T12:30:00Z" + } + first = engine.decide(engine.initial_state, command) + second = engine.decide(engine.initial_state, command) + + assert_equal "maximum_accepted", first.transition_event.type + assert_equal ["standing_bid_changed"], first.public_events.map(&:type) + assert_equal ["maximum_accepted"], first.privileged_events.map(&:type) + assert_equal first, second + assert first.eql?(second) + assert_equal first.hash, second.hash + assert_equal first.events.first, second.events.first + assert_equal first.events.first.hash, second.events.first.hash + + public_event = RBBB::Event.new(type: "closing_time_changed", visibility: :public, data: {a: 1}) + privileged_event = RBBB::Event.new(type: "closing_time_changed", visibility: :privileged, data: {a: 1}) + refute_equal public_event, privileged_event + + rejected_a = RBBB::Decision.rejected(command_id: "command-1", reason: "invalid_command") + rejected_b = RBBB::Decision.rejected(command_id: "command-1", reason: "invalid_command") + assert_nil rejected_a.transition_event + assert_empty rejected_a.public_events + assert_empty rejected_a.privileged_events + assert_equal rejected_a, rejected_b + assert_equal rejected_a.hash, rejected_b.hash + refute_equal first, rejected_a + end end diff --git a/ruby/engine/test/engine_test.rb b/ruby/engine/test/engine_test.rb index 51b9ec2..977be8b 100644 --- a/ruby/engine/test/engine_test.rb +++ b/ruby/engine/test/engine_test.rb @@ -247,4 +247,30 @@ def test_every_state_view_carries_the_schedule assert_equal CLOSES_AT, candidate.to_h.fetch("closes_at") end end + + def test_change_closing_time_accepts_time_objects + decision = @engine.decide(@engine.initial_state, { + command_id: "command-close-time", + type: "change_closing_time", + operator_id: "operator-1", + reason: "seller_authorized_change", + closes_at: Time.utc(2026, 9, 1, 14, 0, 0), + effective_at: Time.utc(2026, 9, 1, 12, 10, 0) + }) + + assert decision.accepted?, decision.rejection.inspect + applied = @engine.apply(@engine.initial_state, decision.events) + assert_equal "2026-09-01T14:00:00Z", applied.to_h.fetch("closes_at") + + overflow = @engine.decide(@engine.initial_state, { + command_id: "command-close-overflow", + type: "change_closing_time", + operator_id: "operator-1", + reason: "seller_authorized_change", + closes_at: Time.utc(10_000, 1, 1, 0, 0, 0), + effective_at: Time.utc(2026, 9, 1, 12, 10, 0) + }) + assert overflow.rejected? + assert_equal "invalid_closing_time", overflow.rejection.fetch("reason") + end end diff --git a/ruby/engine/test/hardening_test.rb b/ruby/engine/test/hardening_test.rb index f8d32ee..dc77894 100644 --- a/ruby/engine/test/hardening_test.rb +++ b/ruby/engine/test/hardening_test.rb @@ -154,6 +154,185 @@ def test_state_requires_opens_at_and_closes_at assert_equal CLOSES_AT, state.to_h.fetch("closes_at") end + def test_timestamp_rejects_years_outside_rfc3339_four_digit_range + [ + Time.utc(0, 12, 31, 23, 59, 59), + Time.utc(10_000, 1, 1, 0, 0, 0), + "0000-12-31T23:59:59Z", + "0001-01-01T00:00:00+01:00", + "9999-12-31T23:59:59-01:00" + ].each do |invalid| + assert_raises(ArgumentError) { RBBB::Timestamp.parse(invalid) } + end + + assert_raises(ArgumentError) { RBBB::Timestamp.dump(Time.utc(0, 12, 31, 23, 59, 59)) } + assert_raises(ArgumentError) { RBBB::Timestamp.dump(Time.utc(10_000, 1, 1, 0, 0, 0)) } + assert_equal "0001-01-01T00:00:00Z", RBBB::Timestamp.dump(RBBB::Timestamp.parse("0001-01-01T00:00:00Z")) + assert_equal "9999-12-31T23:59:59.999Z", RBBB::Timestamp.dump(RBBB::Timestamp.parse("9999-12-31T23:59:59.999Z")) + end + + def test_extension_overflow_past_year_9999_is_rejected_cleanly_in_decide + engine = build_engine(extension: { + trigger_window_seconds: 300, + duration_seconds: RBBB::MAX_SAFE_INTEGER, + extend_on_void: true + }) + + bid_overflow = place(engine, engine.initial_state, "cmd-bid", "bidder-a", 50_000, + effective_at: "2026-09-01T12:59:00Z") + assert bid_overflow.rejected? + assert_equal "invalid_closing_time", bid_overflow.rejection.fetch("reason") + + state = engine.apply(engine.initial_state, place(engine, engine.initial_state, "cmd-1", "bidder-a", 50_000, + effective_at: "2026-09-01T12:10:00Z").events) + state = engine.apply(state, place(engine, state, "cmd-2", "bidder-b", 50_000, + effective_at: "2026-09-01T12:11:00Z").events) + state = engine.apply(state, place(engine, state, "cmd-3", "bidder-a", 60_000, + effective_at: "2026-09-01T12:12:00Z").events) + + reduction_overflow = engine.decide(state, { + command_id: "cmd-reduce", + type: "reduce_maximum", + bidder_id: "bidder-a", + maximum_minor_units: 50_000, + effective_at: "2026-09-01T12:59:00Z" + }) + assert reduction_overflow.rejected? + assert_equal "invalid_closing_time", reduction_overflow.rejection.fetch("reason") + + void_overflow = engine.decide(state, { + command_id: "cmd-void", + type: "void_bid", + bid_id: "cmd-2", + operator_id: "operator-1", + reason: "review", + notification_policy: "none", + effective_at: "2026-09-01T12:59:00Z" + }) + assert void_overflow.rejected? + assert_equal "invalid_closing_time", void_overflow.rejection.fetch("reason") + end + + def test_apply_rejects_transitions_on_closed_state_and_backward_effective_at + engine = build_engine + first = place(engine, engine.initial_state, "command-1", "bidder-a", 50_000, + effective_at: "2026-09-01T12:30:00Z") + open_state = engine.apply(engine.initial_state, first.events) + + assert_same open_state, engine.apply(open_state, []) + assert_raises(RBBB::InvalidState) { engine.apply(open_state, first.public_events) } + + second = place(engine, open_state, "command-2", "bidder-b", 60_000, + effective_at: "2026-09-01T12:31:00Z") + backward_transition = RBBB::Event.new( + type: second.transition_event.type, + visibility: :privileged, + data: second.transition_event.data.merge("effective_at" => "2026-09-01T12:29:59Z") + ) + error = assert_raises(RBBB::InvalidState) { engine.apply(open_state, [backward_transition]) } + assert_match(/precedes state last_effective_at/, error.message) + + close_decision = engine.decide(open_state, { + command_id: "command-close", + type: "close_bidding", + effective_at: CLOSES_AT + }) + closed_state = engine.apply(open_state, close_decision.events) + reopen_transition = RBBB::Event.new( + type: "maximum_accepted", + visibility: :privileged, + data: second.transition_event.data.merge( + "aggregate_version" => closed_state.version + 1, + "effective_at" => "2026-09-01T13:01:00Z" + ) + ) + error = assert_raises(RBBB::InvalidState) { engine.apply(closed_state, [reopen_transition]) } + assert_match(/closed state/, error.message) + end + + def test_malformed_command_id_produces_nil_in_rejection + engine = build_engine + ["", 123, false, "x" * 256, nil].each do |bad_id| + invalid = engine.decide(engine.initial_state, { + command_id: bad_id, + type: "place_bid", + bidder_id: "bidder-a", + maximum_minor_units: 50_000, + effective_at: "2026-09-01T12:10:00Z" + }) + assert invalid.rejected? + assert_equal "invalid_command", invalid.rejection.fetch("reason") + assert_nil invalid.rejection.fetch("command_id") + + unsupported = engine.decide(engine.initial_state, { + command_id: bad_id, + type: "unknown_command" + }) + assert unsupported.rejected? + assert_equal "unsupported_command", unsupported.rejection.fetch("reason") + assert_nil unsupported.rejection.fetch("command_id") + end + end + + def test_non_integer_expected_version_and_explicit_false_bid_id_are_rejected + engine = build_engine + + [0.0, "0", -1, RBBB::MAX_SAFE_INTEGER + 1, nil].each do |bad_version| + decision = engine.decide(engine.initial_state, { + command_id: "command-1", + type: "place_bid", + bidder_id: "bidder-a", + maximum_minor_units: 50_000, + expected_version: bad_version, + effective_at: "2026-09-01T12:10:00Z" + }) + assert decision.rejected? + assert_equal "invalid_command", decision.rejection.fetch("reason") + end + + false_bid_id = engine.decide(engine.initial_state, { + command_id: "command-1", + type: "place_bid", + bid_id: false, + bidder_id: "bidder-a", + maximum_minor_units: 50_000, + effective_at: "2026-09-01T12:10:00Z" + }) + assert false_bid_id.rejected? + assert_equal "invalid_command", false_bid_id.rejection.fetch("reason") + end + + def test_version_at_max_safe_integer_is_bounded_cleanly + engine = build_engine + max_state = RBBB::State.new( + version: RBBB::MAX_SAFE_INTEGER, + positions: {}, + leader_id: nil, + standing_minor_units: nil, + next_required_minor_units: 10_000, + opens_at: OPENS_AT, + closes_at: CLOSES_AT + ) + + assert_raises(RBBB::InvalidState) do + place(engine, max_state, "command-overflow", "bidder-a", 50_000, + effective_at: "2026-09-01T12:10:00Z") + end + assert_raises(RBBB::InvalidState) do + RBBB::State.from_h(max_state.to_h.merge("version" => RBBB::MAX_SAFE_INTEGER + 1)) + end + end + + def test_configuration_from_h_rejects_non_hash_as_invalid_configuration + [nil, "not-a-hash", 42, []].each do |input| + assert_raises(RBBB::InvalidConfiguration) { RBBB::Configuration.from_h(input) } + end + end + + def test_unsupported_feature_constant_is_removed + refute defined?(RBBB::UnsupportedFeature) + end + private def build_state(opens_at:, closes_at:) diff --git a/ruby/engine/test/shared_closing_clock_test.rb b/ruby/engine/test/shared_closing_clock_test.rb index dbb0816..82b3dee 100644 --- a/ruby/engine/test/shared_closing_clock_test.rb +++ b/ruby/engine/test/shared_closing_clock_test.rb @@ -134,4 +134,21 @@ def test_revision_overflow_is_refused core = engine(current.closes_at) assert_raises(RBBB::InvalidState) { current.after_decision(unit_id: "lot-12", decision: bid(core, core.initial_state), expected_revision: current.revision) } end + + def test_exposes_group_identity_readers_and_value_equality + first = clock + second = RBBB::SharedClosingClock.new( + group_id: "group-a", + unit_ids: %w[lot-103 lot-12 lot-47], + closes_at: Time.utc(2030, 1, 1, 13, 0, 0), + quiet_period_seconds: 180 + ) + + assert_equal "group-a", first.group_id + assert_equal %w[lot-103 lot-12 lot-47], first.unit_ids + assert_equal first, second + assert first.eql?(second) + assert_equal first.hash, second.hash + refute_equal first, clock(group_id: "group-b") + end end diff --git a/ruby/engine/test/state_snapshot_test.rb b/ruby/engine/test/state_snapshot_test.rb index 5e46448..763067b 100644 --- a/ruby/engine/test/state_snapshot_test.rb +++ b/ruby/engine/test/state_snapshot_test.rb @@ -200,6 +200,71 @@ def test_public_view_matches_the_public_schema_and_discloses_nothing_private refute_includes closed_state.public_view.values, "bidder-c" end + def test_state_from_h_rejects_arbitrary_equal_standing_and_next_required_and_overbound_amounts + open_state, = run_commands(@engine.initial_state, PREFIX_COMMANDS.take(1)) + snapshot = open_state.to_h + + tampered_equal = snapshot.merge( + "standing_minor_units" => 10_000, + "next_required_minor_units" => 10_000, + "positions" => { + "bidder-a" => { + "maximum_minor_units" => 10_000, + "executable_maximum_minor_units" => 10_000, + "priority" => 1, + "executed_minor_units" => 10_000 + } + } + ) + error = assert_raises(RBBB::InvalidState) { RBBB::State.from_h(tampered_equal) } + assert_match(/next required amount must exceed standing amount/, error.message) + + over = RBBB::MAX_SAFE_INTEGER + 1 + [ + snapshot.merge("version" => over), + snapshot.merge("next_required_minor_units" => over), + snapshot.merge("reserve_minor_units" => over), + snapshot.merge("positions" => snapshot.fetch("positions").merge( + "bidder-a" => snapshot.fetch("positions").fetch("bidder-a").merge("maximum_minor_units" => over) + )), + snapshot.merge("authorization_history" => [ + snapshot.fetch("authorization_history").first.merge("maximum_minor_units" => over) + ]), + snapshot.merge("reserve_history" => [ + {"old_reserve_minor_units" => 40_000, "new_reserve_minor_units" => over, "priority" => 1} + ]) + ].each do |invalid| + assert_raises(RBBB::InvalidState) { RBBB::State.from_h(invalid) } + end + end + + def test_state_and_configuration_value_equality + open_state, = run_commands(@engine.initial_state, PREFIX_COMMANDS) + rebuilt = RBBB::State.from_h(open_state.to_h) + + assert_equal open_state, rebuilt + assert open_state.eql?(rebuilt) + assert_equal open_state.hash, rebuilt.hash + refute_equal @engine.initial_state, open_state + + config_a = @engine.configuration + config_b = RBBB::Configuration.new( + currency: "USD", + opening_minor_units: 10_000, + reserve_minor_units: 40_000, + increments: [ + {from_minor_units: 0, amount_minor_units: 1_000}, + {from_minor_units: 100_000, amount_minor_units: 2_500} + ], + opens_at: Time.utc(2026, 9, 1, 12, 0, 0), + closes_at: Time.utc(2026, 9, 1, 13, 0, 0), + extension: {trigger_window_seconds: 300, duration_seconds: 300} + ) + assert_equal config_a, config_b + assert config_a.eql?(config_b) + assert_equal config_a.hash, config_b.hash + end + private def run_commands(state, commands)