Module: Kafkr::Producer
- Defined in:
- lib/kafkr/producer.rb
Constant Summary collapse
- MESSAGE_QUEUE =
"./.kafkr/message_queue.txt"
- @@file_mutex =
Mutex.new
Class Method Summary collapse
- .configuration ⇒ Object
- .configure ⇒ Object
- .send_message(message) ⇒ Object
- .send_message_and_wait(message) ⇒ Object
- .structured_data_to_hash(input:, sync_uid:) ⇒ Object
Class Method Details
.configuration ⇒ Object
14 15 16 17 18 19 20 21 22 |
# File 'lib/kafkr/producer.rb', line 14 def self.configuration FileUtils.mkdir_p "./.kafkr" @configuration ||= OpenStruct.new @configuration.queue_file = MESSAGE_QUEUE @configuration. = [] load_queue_from_file @configuration.is_json = false @configuration end |
.configure ⇒ Object
24 25 26 27 28 |
# File 'lib/kafkr/producer.rb', line 24 def self.configure yield(configuration) rescue => e logger.error("Configuration error: #{e.message}") end |
.send_message(message) ⇒ Object
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 89 |
# File 'lib/kafkr/producer.rb', line 52 def self.() return if .nil? || .empty? uuid = SecureRandom.uuid = nil if Kafkr::Producer.configuration.is_json = JSON.parse() ["uuid"] = uuid = JSON.dump() else if .is_a? String = structured_data_to_hash(input: , sync_uid: uuid) = "#{uuid}: #{message}" end if .is_a?(Hash) = "#{uuid}: #{JSON.generate(message)}" end end = Kafkr::Encryptor.new.encrypt() begin socket = TCPSocket.new(@configuration.host, @configuration.port) (socket) socket.puts() rescue Errno::ECONNREFUSED puts "Connection refused. Queuing message: #{encrypted_message_with_uuid}" @configuration..push() save_queue_to_file rescue Errno::EPIPE puts "Broken pipe error. Retrying connection..." retry_connection() end uuid end |
.send_message_and_wait(message) ⇒ Object
91 92 93 94 95 96 97 |
# File 'lib/kafkr/producer.rb', line 91 def self.() Consumer.new.listen_for(, method(:send_message)) do |, sync_uid| if .key? "reply" and ["reply"].dig("uuid") == sync_uid ["reply"].dig("payload") end end end |
.structured_data_to_hash(input:, sync_uid:) ⇒ Object
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# File 'lib/kafkr/producer.rb', line 30 def self.structured_data_to_hash(input:, sync_uid:) unless /\A\w+\s*(=>|<=>)\s*((\w+:\s*['"]?[^'",]*['"]?,\s*)*(\w+:\s*['"]?[^'",]*['"]?)\s*)\z/.match?(input) return input end if input.include?("<=>") type, key_values_str = input.split("<=>").map(&:strip) key_values = key_values_str.scan(/(\w+):\s*['"]?([^'",]*)['"]?/) hash_body = key_values.to_h do |key, value| [key.to_sym, value.strip.gsub(/\A['"]|['"]\z/, "")] end {type.to_sym => hash_body, :sync => true, :sync_uid => sync_uid} else type, key_values_str = input.split("=>").map(&:strip) key_values = key_values_str.scan(/(\w+):\s*['"]?([^'",]*)['"]?/) hash_body = key_values.to_h do |key, value| [key.to_sym, value.strip.gsub(/\A['"]|['"]\z/, "")] end {type.to_sym => hash_body} end end |