sgx_jmp.rb

  1# frozen_string_literal: true
  2
  3require "pg/em"
  4require "bigdecimal"
  5require "blather/client/dsl" # Require this first to not auto-include
  6require "blather/client"
  7require "braintree"
  8require "dhall"
  9require "em-hiredis"
 10require "em_promise"
 11require "ruby-bandwidth-iris"
 12
 13CONFIG =
 14	Dhall::Coder
 15	.new(safe: Dhall::Coder::JSON_LIKE + [Symbol, Proc])
 16	.load(ARGV[0], transform_keys: ->(k) { k&.to_sym })
 17
 18singleton_class.class_eval do
 19	include Blather::DSL
 20	Blather::DSL.append_features(self)
 21end
 22
 23require_relative "lib/backend_sgx"
 24require_relative "lib/bandwidth_tn_order"
 25require_relative "lib/btc_sell_prices"
 26require_relative "lib/buy_account_credit_form"
 27require_relative "lib/customer"
 28require_relative "lib/electrum"
 29require_relative "lib/em"
 30require_relative "lib/payment_methods"
 31require_relative "lib/registration"
 32require_relative "lib/transaction"
 33require_relative "lib/web_register_manager"
 34
 35ELECTRUM = Electrum.new(**CONFIG[:electrum])
 36
 37Faraday.default_adapter = :em_synchrony
 38BandwidthIris::Client.global_options = {
 39	account_id: CONFIG[:creds][:account],
 40	username: CONFIG[:creds][:username],
 41	password: CONFIG[:creds][:password]
 42}
 43
 44# Braintree is not async, so wrap in EM.defer for now
 45class AsyncBraintree
 46	def initialize(environment:, merchant_id:, public_key:, private_key:, **)
 47		@gateway = Braintree::Gateway.new(
 48			environment: environment,
 49			merchant_id: merchant_id,
 50			public_key: public_key,
 51			private_key: private_key
 52		)
 53	end
 54
 55	def respond_to_missing?(m, *)
 56		@gateway.respond_to?(m)
 57	end
 58
 59	def method_missing(m, *args)
 60		return super unless respond_to_missing?(m, *args)
 61
 62		EM.promise_defer(klass: PromiseChain) do
 63			@gateway.public_send(m, *args)
 64		end
 65	end
 66
 67	class PromiseChain < EMPromise
 68		def respond_to_missing?(*)
 69			false # We don't actually know what we respond to...
 70		end
 71
 72		def method_missing(m, *args)
 73			return super if respond_to_missing?(m, *args)
 74			self.then { |o| o.public_send(m, *args) }
 75		end
 76	end
 77end
 78
 79BRAINTREE = AsyncBraintree.new(**CONFIG[:braintree])
 80
 81def panic(e)
 82	m = e.respond_to?(:message) ? e.message : e
 83	warn "Error raised during event loop: #{e.class}: #{m}"
 84	warn e.backtrace if e.respond_to?(:backtrace)
 85	exit 1
 86end
 87
 88EM.error_handler(&method(:panic))
 89
 90when_ready do
 91	BLATHER = self
 92	REDIS = EM::Hiredis.connect
 93	BTC_SELL_PRICES = BTCSellPrices.new(REDIS, CONFIG[:oxr_app_id])
 94	DB = PG::EM::Client.new(dbname: "jmp")
 95	DB.type_map_for_results = PG::BasicTypeMapForResults.new(DB)
 96	DB.type_map_for_queries = PG::BasicTypeMapForQueries.new(DB)
 97
 98	EM.add_periodic_timer(3600) do
 99		ping = Blather::Stanza::Iq::Ping.new(:get, CONFIG[:server][:host])
100		ping.from = CONFIG[:component][:jid]
101		self << ping
102	end
103end
104
105# workqueue_count MUST be 0 or else Blather uses threads!
106setup(
107	CONFIG[:component][:jid],
108	CONFIG[:component][:secret],
109	CONFIG[:server][:host],
110	CONFIG[:server][:port],
111	nil,
112	nil,
113	workqueue_count: 0
114)
115
116message :error? do |m|
117	puts "MESSAGE ERROR: #{m.inspect}"
118end
119
120class SessionManager
121	def initialize(blather, id_msg, timeout: 5)
122		@blather = blather
123		@sessions = {}
124		@id_msg = id_msg
125		@timeout = timeout
126	end
127
128	def promise_for(stanza)
129		id = "#{stanza.to.stripped}/#{stanza.public_send(@id_msg)}"
130		@sessions.fetch(id) do
131			@sessions[id] = EMPromise.new
132			EM.add_timer(@timeout) do
133				@sessions.delete(id)&.reject(:timeout)
134			end
135			@sessions[id]
136		end
137	end
138
139	def write(stanza)
140		promise = promise_for(stanza)
141		@blather << stanza
142		promise
143	end
144
145	def fulfill(stanza)
146		id = "#{stanza.from.stripped}/#{stanza.public_send(@id_msg)}"
147		if stanza.error?
148			@sessions.delete(id)&.reject(stanza)
149		else
150			@sessions.delete(id)&.fulfill(stanza)
151		end
152	end
153end
154
155IQ_MANAGER = SessionManager.new(self, :id)
156COMMAND_MANAGER = SessionManager.new(self, :sessionid, timeout: 60 * 60)
157web_register_manager = WebRegisterManager.new
158
159disco_items node: "http://jabber.org/protocol/commands" do |iq|
160	reply = iq.reply
161	reply.items = [
162		# TODO: don't show this item if no braintree methods available
163		# TODO: don't show this item if no plan for this customer
164		Blather::Stanza::DiscoItems::Item.new(
165			iq.to,
166			"buy-credit",
167			"Buy account credit"
168		),
169		Blather::Stanza::DiscoItems::Item.new(
170			iq.to,
171			"jabber:iq:register",
172			"Register"
173		)
174	]
175	self << reply
176end
177
178command :execute?, node: "jabber:iq:register", sessionid: nil do |iq|
179	Customer.for_jid(iq.from.stripped).catch {
180		Customer.create(iq.from.stripped)
181	}.then { |customer|
182		Registration.for(
183			iq,
184			customer,
185			web_register_manager
186		).then(&:write)
187	}.catch(&method(:panic))
188end
189
190def reply_with_note(iq, text, type: :info)
191	reply = iq.reply
192	reply.status = :completed
193	reply.note_type = type
194	reply.note_text = text
195
196	self << reply
197end
198
199command :execute?, node: "buy-credit", sessionid: nil do |iq|
200	reply = iq.reply
201	reply.allowed_actions = [:complete]
202
203	Customer.for_jid(iq.from.stripped).then { |customer|
204		BuyAccountCreditForm.new(customer).add_to_form(reply.form).then { customer }
205	}.then { |customer|
206		EMPromise.all([
207			customer,
208			customer.payment_methods,
209			COMMAND_MANAGER.write(reply)
210		])
211	}.then { |(customer, payment_methods, iq2)|
212		iq = iq2 # This allows the catch to use it also
213		payment_method = payment_methods.fetch(
214			iq.form.field("payment_method")&.value.to_i
215		)
216		amount = iq.form.field("amount").value.to_s
217		Transaction.sale(customer, amount, payment_method)
218	}.then { |transaction|
219		transaction.insert.then { transaction.amount }
220	}.then { |amount|
221		reply_with_note(iq, "$#{'%.2f' % amount} added to your account balance.")
222	}.catch { |e|
223		text = "Failed to buy credit, system said: #{e.message}"
224		reply_with_note(iq, text, type: :error)
225	}.catch(&method(:panic))
226end
227
228command sessionid: /./ do |iq|
229	COMMAND_MANAGER.fulfill(iq)
230end
231
232iq :result? do |iq|
233	IQ_MANAGER.fulfill(iq)
234end
235
236iq :error? do |iq|
237	IQ_MANAGER.fulfill(iq)
238end