-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.rb
88 lines (82 loc) · 2.35 KB
/
server.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
require "sinatra"
require 'json'
require "bunny"
require 'haml'
require 'securerandom'
require 'thread'
$base_uri=nil
rabbitConn = Bunny.new(ENV["RABBITMQ"])
rabbitConn.start
channel=rabbitConn.create_channel
$registryExchange=channel.topic("registry")
$orderExchange=channel.topic("orders")
def notify_product
if not $base_uri.nil?
$registryExchange.publish('{"key":"buy","priority":0,"uri-template":"'+$base_uri+'/buy-button?product={product}"}', :routing_key => "action.product.registration")
end
end
queue = channel.queue("", :exclusive => true, :durable=>false)
queue.bind($registryExchange, :routing_key=>"product.registration")
queue.subscribe(:manual_ack => true, :block => false) do |delivery_info, properties, body|
begin
notify_product
rescue
#TODO
end
channel.ack(delivery_info.delivery_tag)
end
error do
@e = request.env['sinatra_error']
puts @e
"500 server error".to_json
end
get '/buy-button' do
haml :buy_button ,:locals=>{:uri=>params['product']}
end
get '/buy-button/buy-button-component' do
haml :buy_button_component
end
get '/buy-button/register-hack' do
$base_uri=request.base_url
notify_product
"OK"
end
post '/buy-button/order' do
request.body.rewind
payload = JSON.parse request.body.read
id=SecureRandom.uuid.to_s
response={}
unblock = Thread::Queue.new
order_queue = channel.queue("", :exclusive => true, :durable=>false)
order_queue.bind($orderExchange, :routing_key=>"created.order")
subscriber = order_queue.subscribe() do |delivery_info, properties, body|
message=JSON.parse body
if(message["id"]==id)
puts id
response[:uri]=message["uri"]
unblock.enq true
end
end
failed_queue = channel.queue("", :exclusive => true, :durable=>false)
failed_queue.bind($orderExchange, :routing_key=>"rejected.order")
fail_subscriber = failed_queue.subscribe() do |delivery_info, properties, body|
message=JSON.parse body
if(message["id"]==id)
puts "THIS FAILED:"
puts payload
response[:failure]="hmmmmm"
unblock.enq true
end
end
$orderExchange.publish('{"id":"'+id+'","items":[{"product":"'+payload['product']+'","Quantity":1}]}', :routing_key =>"create.order")
Thread.new{
sleep 10
puts "TIMEOUT"
response[:failure]="Timeout"
unblock.enq true
}
unblock.deq
subscriber.cancel
fail_subscriber.cancel
response.to_json
end