Class: Faktory::Client
- Inherits:
-
Object
- Object
- Faktory::Client
- Includes:
- ReadTimeout
- Defined in:
- lib/faktory/client.rb,
lib/faktory/testing.rb
Overview
Faktory::Client provides a low-level connection to a Faktory server and APIs which map to Faktory commands.
Most APIs will return true if the operation succeeded or raise a Faktory::BaseError if there was an unexpected error.
Constant Summary collapse
- DEFAULT_TIMEOUT =
5.0- HASHER =
proc do |iter, pwd, salt| sha = Digest::SHA256.new hashing = pwd + salt iter.times do hashing = sha.digest(hashing) end Digest.hexencode(hashing) end
- @@random_process_wid =
""
Constants included from ReadTimeout
ReadTimeout::BUFSIZE, ReadTimeout::CRLF
Instance Attribute Summary collapse
-
#middleware ⇒ Object
Returns the value of attribute middleware.
Class Method Summary collapse
-
.worker! ⇒ Object
Called when booting the worker process to signal that this process will consume jobs and send BEAT.
Instance Method Summary collapse
- #ack(jid) ⇒ Object
- #batch_status(bid) ⇒ Object
-
#beat(current_state = nil, hash = {}) ⇒ Object
Sends a heartbeat to the server, in order to prove this worker process is still alive.
- #close ⇒ Object
- #create_batch(batch, &block) ⇒ Object
- #fail(jid, ex) ⇒ Object
-
#fetch(*queues) ⇒ Object
Returns either a job hash or falsy.
-
#flush ⇒ Object
Warning: this clears all job data in Faktory.
- #get_track(jid) ⇒ Object
- #info ⇒ Object
-
#initialize(url: uri_from_env || "tcp://localhost:7419", debug: false, timeout: DEFAULT_TIMEOUT) ⇒ Client
constructor
Best practice is to rely on the localhost default for development and configure the environment variables for non-development environments.
-
#open_socket(*args) ⇒ Object
NB: aliased by faktory/testing.
- #pause_queues(queues) ⇒ Object
-
#push(job) ⇒ Object
Push a hash corresponding to a job payload to Faktory.
- #queue_latency(*queues) ⇒ Object
-
#real_open_socket ⇒ Object
NB: aliased by faktory/testing.
-
#real_push ⇒ Object
Push a hash corresponding to a job payload to Faktory.
- #reopen_batch(b) ⇒ Object
- #resume_queues(queues) ⇒ Object
-
#set_track(hash) ⇒ Object
hash must include a ‘jid’ element.
Methods included from ReadTimeout
Constructor Details
#initialize(url: uri_from_env || "tcp://localhost:7419", debug: false, timeout: DEFAULT_TIMEOUT) ⇒ Client
Best practice is to rely on the localhost default for development and configure the environment variables for non-development environments.
FAKTORY_PROVIDER=MY_FAKTORY_URL MY_FAKTORY_URL=tcp://:[email protected]:7419
Note above, the URL can contain the password for secure installations.
54 55 56 57 58 59 60 61 |
# File 'lib/faktory/client.rb', line 54 def initialize(url: uri_from_env || "tcp://localhost:7419", debug: false, timeout: DEFAULT_TIMEOUT) super @debug = debug @location = URI(url) @sock = nil open_socket end |
Instance Attribute Details
#middleware ⇒ Object
Returns the value of attribute middleware.
45 46 47 |
# File 'lib/faktory/client.rb', line 45 def middleware @middleware end |
Class Method Details
.worker! ⇒ Object
Called when booting the worker process to signal that this process will consume jobs and send BEAT.
41 42 43 |
# File 'lib/faktory/client.rb', line 41 def self.worker! @@random_process_wid = SecureRandom.hex(8) end |
Instance Method Details
#ack(jid) ⇒ Object
199 200 201 202 203 204 |
# File 'lib/faktory/client.rb', line 199 def ack(jid) transaction do command("ACK", %({"jid":"#{jid}"})) ok end end |
#batch_status(bid) ⇒ Object
102 103 104 105 106 107 |
# File 'lib/faktory/client.rb', line 102 def batch_status(bid) transaction do command "BATCH STATUS", bid Faktory.load_json result! end end |
#beat(current_state = nil, hash = {}) ⇒ Object
Sends a heartbeat to the server, in order to prove this worker process is still alive.
You can pass in the current_state of the process, for example during shutdown quiet and/or terminate can be supplied.
Return a string signal to process, legal values are “quiet” or “terminate”. The quiet signal is informative: the server won’t allow this process to FETCH any more jobs anyways.
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 |
# File 'lib/faktory/client.rb', line 225 def beat(current_state = nil, hash = {}) transaction do hash["wid"] = @@random_process_wid hash["current_state"] = current_state if current_state command("BEAT", Faktory.dump_json(hash)) str = result! if str == "OK" str else hash = Faktory.load_json(str) hash["state"] end end end |
#close ⇒ Object
63 64 65 66 67 68 |
# File 'lib/faktory/client.rb', line 63 def close return unless @sock command "END" @sock.close @sock = nil end |
#create_batch(batch, &block) ⇒ Object
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/faktory/client.rb', line 78 def create_batch(batch, &block) bid = transaction do command "BATCH NEW", Faktory.dump_json(batch.to_h) result! end batch.instance_variable_set(:@bid, bid) old = Thread.current[:faktory_batch] begin Thread.current[:faktory_batch] = batch # any jobs pushed in this block will implicitly have # their `bid` attribute set so they are associated # with the current batch. yield batch ensure Thread.current[:faktory_batch] = old end transaction do command "BATCH COMMIT", bid ok end bid end |
#fail(jid, ex) ⇒ Object
206 207 208 209 210 211 212 213 214 |
# File 'lib/faktory/client.rb', line 206 def fail(jid, ex) transaction do command("FAIL", Faktory.dump_json({message: ex.[0...1000], errtype: ex.class.name, jid: jid, backtrace: ex.backtrace})) ok end end |
#fetch(*queues) ⇒ Object
Returns either a job hash or falsy.
190 191 192 193 194 195 196 197 |
# File 'lib/faktory/client.rb', line 190 def fetch(*queues) job = nil transaction do command("FETCH", *queues) job = result! end JSON.parse(job) if job end |
#flush ⇒ Object
Warning: this clears all job data in Faktory
71 72 73 74 75 76 |
# File 'lib/faktory/client.rb', line 71 def flush transaction do command "FLUSH" ok end end |
#get_track(jid) ⇒ Object
130 131 132 133 134 135 136 |
# File 'lib/faktory/client.rb', line 130 def get_track(jid) transaction do command "TRACK GET", jid hashstr = result! JSON.parse(hashstr) end end |
#info ⇒ Object
241 242 243 244 245 246 247 |
# File 'lib/faktory/client.rb', line 241 def info transaction do command("INFO") str = result! Faktory.load_json(str) if str end end |
#open_socket(*args) ⇒ Object
NB: aliased by faktory/testing
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 |
# File 'lib/faktory/client.rb', line 261 def open_socket tlserrors = [] if tls? tlserrors << ::OpenSSL::SSL::SSLError sock = TCPSocket.new(@location.hostname, @location.port) sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true) ctx = OpenSSL::SSL::SSLContext.new ctx.min_version = OpenSSL::SSL::TLS1_2_VERSION ENV["FAKTORY_DISABLE_HOSTNAME_VERIFICATION"] ? ctx.set_params(verify_mode: OpenSSL::SSL::VERIFY_NONE) : ctx.set_params(verify_mode: OpenSSL::SSL::VERIFY_PEER) @sock = OpenSSL::SSL::SSLSocket.new(sock, ctx).tap do |socket| socket.sync_close = true socket.hostname = @location.hostname socket.connect end else @sock = TCPSocket.new(@location.hostname, @location.port) @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true) end payload = { wid: @@random_process_wid, hostname: Socket.gethostname, pid: $$, labels: Faktory.[:labels] || ["ruby-#{RUBY_VERSION}"], username: @location.user, v: 2 } hi = result if hi =~ /\AHI (.*)/ hash = JSON.parse($1) ver = hash["v"].to_i if ver > 2 puts "Warning: Faktory server protocol #{ver} in use, this worker doesn't speak that version." puts "We recommend you upgrade this gem with `bundle up faktory_worker_ruby`." end salt = hash["s"] if salt pwd = @location.password if !pwd raise ArgumentError, "Server requires password, but none has been configured" end iter = (hash["i"] || 1).to_i raise ArgumentError, "Invalid hashing" if iter < 1 payload["pwdhash"] = HASHER.call(iter, CGI.unescape(pwd), salt) end end command("HELLO", Faktory.dump_json(payload)) ok rescue Errno::ECONNRESET, Faktory::TimeoutError # A tcp client talking to a TLS server will get ECONNRESET if tls? raise else raise("Server using TLS? Use FAKTORY_URL=tcp+tls://... to enable encryption") end rescue *tlserrors # A TLS client talking to a TCP server will get OpenSSL::SSL::SSLError if tls? raise("Server not using TLS? Use FAKTORY_URL=tcp://... to disable encryption") else raise end end |
#pause_queues(queues) ⇒ Object
146 147 148 149 150 151 152 |
# File 'lib/faktory/client.rb', line 146 def pause_queues(queues) qs = Array(queues) transaction do command "QUEUE PAUSE", qs.join(" ") ok end end |
#push(job) ⇒ Object
Push a hash corresponding to a job payload to Faktory. Hash must contain “jid”, “jobtype” and “args” elements at minimum. Returned value will either be the JID String if successful OR a symbol corresponding to an error. NB: aliased by faktory/testing
176 177 178 179 180 181 182 183 184 185 186 187 |
# File 'lib/faktory/client.rb', line 176 def push(job) job = job.transform_keys(&:to_s) job["jid"] ||= SecureRandom.hex(12) job["queue"] ||= "default" raise ArgumentError, "Missing `jobtype` attribute: #{job.inspect}" unless job["jobtype"] raise ArgumentError, "Missing `args` attribute: #{job.inspect}" unless job["args"] transaction do command "PUSH", Faktory.dump_json(job) ok(job["jid"]) end end |
#queue_latency(*queues) ⇒ Object
162 163 164 165 166 167 168 169 |
# File 'lib/faktory/client.rb', line 162 def queue_latency(*queues) qs = Array(queues) raise ArgumentError, "no queue given" if qs.empty? transaction do command "QUEUE LATENCY", qs.join(" ") JSON.parse(result!) end end |
#real_open_socket ⇒ Object
NB: aliased by faktory/testing
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
# File 'lib/faktory/testing.rb', line 79 def open_socket tlserrors = [] if tls? tlserrors << ::OpenSSL::SSL::SSLError sock = TCPSocket.new(@location.hostname, @location.port) sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true) ctx = OpenSSL::SSL::SSLContext.new ctx.min_version = OpenSSL::SSL::TLS1_2_VERSION ENV["FAKTORY_DISABLE_HOSTNAME_VERIFICATION"] ? ctx.set_params(verify_mode: OpenSSL::SSL::VERIFY_NONE) : ctx.set_params(verify_mode: OpenSSL::SSL::VERIFY_PEER) @sock = OpenSSL::SSL::SSLSocket.new(sock, ctx).tap do |socket| socket.sync_close = true socket.hostname = @location.hostname socket.connect end else @sock = TCPSocket.new(@location.hostname, @location.port) @sock.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true) end payload = { wid: @@random_process_wid, hostname: Socket.gethostname, pid: $$, labels: Faktory.[:labels] || ["ruby-#{RUBY_VERSION}"], username: @location.user, v: 2 } hi = result if hi =~ /\AHI (.*)/ hash = JSON.parse($1) ver = hash["v"].to_i if ver > 2 puts "Warning: Faktory server protocol #{ver} in use, this worker doesn't speak that version." puts "We recommend you upgrade this gem with `bundle up faktory_worker_ruby`." end salt = hash["s"] if salt pwd = @location.password if !pwd raise ArgumentError, "Server requires password, but none has been configured" end iter = (hash["i"] || 1).to_i raise ArgumentError, "Invalid hashing" if iter < 1 payload["pwdhash"] = HASHER.call(iter, CGI.unescape(pwd), salt) end end command("HELLO", Faktory.dump_json(payload)) ok rescue Errno::ECONNRESET, Faktory::TimeoutError # A tcp client talking to a TLS server will get ECONNRESET if tls? raise else raise("Server using TLS? Use FAKTORY_URL=tcp+tls://... to enable encryption") end rescue *tlserrors # A TLS client talking to a TCP server will get OpenSSL::SSL::SSLError if tls? raise("Server not using TLS? Use FAKTORY_URL=tcp://... to disable encryption") else raise end end |
#real_push ⇒ Object
Push a hash corresponding to a job payload to Faktory. Hash must contain “jid”, “jobtype” and “args” elements at minimum. Returned value will either be the JID String if successful OR a symbol corresponding to an error. NB: aliased by faktory/testing
78 79 80 81 82 83 84 85 86 87 88 89 |
# File 'lib/faktory/testing.rb', line 78 def push(job) job = job.transform_keys(&:to_s) job["jid"] ||= SecureRandom.hex(12) job["queue"] ||= "default" raise ArgumentError, "Missing `jobtype` attribute: #{job.inspect}" unless job["jobtype"] raise ArgumentError, "Missing `args` attribute: #{job.inspect}" unless job["args"] transaction do command "PUSH", Faktory.dump_json(job) ok(job["jid"]) end end |
#reopen_batch(b) ⇒ Object
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 |
# File 'lib/faktory/client.rb', line 109 def reopen_batch(b) transaction do command "BATCH OPEN", b.bid ok end old = Thread.current[:faktory_batch] begin Thread.current[:faktory_batch] = b # any jobs pushed in this block will implicitly have # their `bid` attribute set so they are associated # with the current batch. yield b ensure Thread.current[:faktory_batch] = old end transaction do command "BATCH COMMIT", b.bid ok end end |
#resume_queues(queues) ⇒ Object
154 155 156 157 158 159 160 |
# File 'lib/faktory/client.rb', line 154 def resume_queues(queues) qs = Array(queues) transaction do command "QUEUE RESUME", qs.join(" ") ok end end |
#set_track(hash) ⇒ Object
hash must include a ‘jid’ element
139 140 141 142 143 144 |
# File 'lib/faktory/client.rb', line 139 def set_track(hash) transaction do command("TRACK SET", Faktory.dump_json(hash)) ok end end |