Skip to content

Instantly share code, notes, and snippets.

@litch
Created April 7, 2015 16:11
Show Gist options
  • Save litch/fd5ab4cfc15b918cedda to your computer and use it in GitHub Desktop.
Save litch/fd5ab4cfc15b918cedda to your computer and use it in GitHub Desktop.
Sample EventStore Consumption
require 'http_eventstore'
client = HttpEventstore::Connection.new
stream_name = 'accounts-002'
#event_data = { event_type: "AccountCreated",
# data: { phoneNumber: '15128798439' }}
#client.append_to_stream(stream_name, event_data)
EventData = Struct.new(:data, :event_type)
event_data = EventData.new({amount: 1000 }, "DepositCreated")
client.append_to_stream(stream_name, event_data)
@last_event = 0
@balances = {}
def calculate_balances
client = HttpEventstore::Connection.new
all_accounts_stream_name = '$ce-accounts'
events = client.read_events_forward(all_accounts_stream_name, @last_event+1, 1000).reverse
events.each do |event|
p event
if event.type == "AccountCreated"
@balances[event.stream_name] = {amount: 0, position: event.id}
elsif event.type == "DepositCreated"
prev_balance = @balances[event.stream_name][:amount]
@balances[event.stream_name] = {amount: prev_balance + event.data['amount'], position: event.id}
elsif event.type == "WithdrawalCreated"
prev_balance = @balances[event.stream_name][:amount]
@balances[event.stream_name] = {amount: prev_balance - event.data['amount'], position: event.id}
end
@last_event = event.position
end
@balances
end
calculate_balances
# ?> @balances
# => {"accounts-001"=>{:amount=>1000, :position=>5}}
def random_withdrawal
@client = HttpEventstore::Connection.new
p stream_name = "accounts-00#{rand(2)+1}"
withdrawal_amount = rand(1000)
if @balances[stream_name][:amount] > withdrawal_amount
event_data = EventData.new({amount: withdrawal_amount }, "WithdrawalCreated")
@client.append_to_stream(stream_name, event_data, @balances[stream_name][:position])
else
p "NSF - depositing"
event_data = EventData.new({amount: 1000 }, "DepositCreated")
@client.append_to_stream(stream_name, event_data)
end
calculate_balances
end
n = 100
Benchmark.bm do |x|
x.report { n.times {random_withdrawal} }
end
# 0.270000 0.070000 0.340000 ( 0.665584)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment