Class: EMJack::Connection

Inherits:
Object
  • Object
show all
Includes:
EM::Deferrable
Defined in:
lib/em-jack/connection.rb

Constant Summary collapse

RETRY_COUNT =
5
@@handlers =
[]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Connection

Returns a new instance of Connection.



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
# File 'lib/em-jack/connection.rb', line 24

def initialize(opts = {})
  case opts
  when Hash
    @host = opts[:host] || 'localhost'
    @port = opts[:port] || 11300
    @tube = opts[:tube]
  when String
    uri = URI.parse(opts)
    @host = uri.host || 'localhost'
    @port = uri.port || 11300
    @tube = uri.path.gsub(/^\//, '') # Kill the leading /
  end

  reset_tube_state

  @data = ""
  @retries = 0
  @in_reserve = false
  @fiberized = false

  @conn = EM::connect(host, port, EMJack::BeanstalkConnection) do |conn|
    conn.client = self
  end

  unless @tube.nil?
    use(@tube)
    watch(@tube)
  end
end

Instance Attribute Details

#hostObject

Returns the value of attribute host.



13
14
15
# File 'lib/em-jack/connection.rb', line 13

def host
  @host
end

#portObject

Returns the value of attribute port.



13
14
15
# File 'lib/em-jack/connection.rb', line 13

def port
  @port
end

Class Method Details

.handlersObject



20
21
22
# File 'lib/em-jack/connection.rb', line 20

def self.handlers
  @@handlers
end

.register_handler(handler) ⇒ Object



15
16
17
18
# File 'lib/em-jack/connection.rb', line 15

def self.register_handler(handler)
  @@handlers ||= []
  @@handlers << handler
end

Instance Method Details

#add_deferrable(&blk) ⇒ Object



311
312
313
314
315
316
317
318
319
320
321
# File 'lib/em-jack/connection.rb', line 311

def add_deferrable(&blk)
  df = EM::DefaultDeferrable.new
  if @error_callback
    df.errback { |err| @error_callback.call(err) }
  end

  df.callback &blk if block_given?

  @deferrables.push(df)
  df
end

#bury(job, pri, &blk) ⇒ Object



181
182
183
184
185
# File 'lib/em-jack/connection.rb', line 181

def bury(job, pri, &blk)
  callback { @conn.send(:bury, job.jobid, pri) }

  add_deferrable(&blk)
end

#connectedObject



254
255
256
257
258
259
260
# File 'lib/em-jack/connection.rb', line 254

def connected
  @reconnect_proc = nil
  @retries = 0
  succeed
  @connected = true
  @connected_callback.call if @connected_callback
end

#connected?Boolean

Returns:

  • (Boolean)


335
336
337
# File 'lib/em-jack/connection.rb', line 335

def connected?
  @connected
end

#delete(job, &blk) ⇒ Object



165
166
167
168
169
170
171
# File 'lib/em-jack/connection.rb', line 165

def delete(job, &blk)
  return if job.nil?

  callback { @conn.send(:delete, job.jobid) }

  add_deferrable(&blk)
end

#disconnectedObject



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
# File 'lib/em-jack/connection.rb', line 262

def disconnected
  @connected = false
  d = @deferrables.dup

  ## if reconnecting, need to fail ourself to remove any callbacks
  fail

  set_deferred_status(nil)
  d.each { |df| df.fail(:disconnected) }

  if @retries >= RETRY_COUNT
    if @disconnected_callback
      @disconnected_callback.call
    else
      raise EMJack::Disconnected
    end
  end

  prev_used, prev_watched = reset_tube_state
  unless @reconnect_proc
    recon = Proc.new { reconnect(prev_used, prev_watched) }
    if @fiberized
      @reconnect_proc = Proc.new { Fiber.new { recon.call }.resume }
    else
      @reconnect_proc = recon
    end
  end

  @retries += 1
  EM.add_timer(5) { @reconnect_proc.call }
end

#each_job(timeout = nil, &blk) ⇒ Object



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/em-jack/connection.rb', line 230

def each_job(timeout = nil, &blk)
  if (@fiberized)
    work = Proc.new do
      Fiber.new do
        job = reserve(timeout)
        blk.call(job)
      end.resume
      EM.next_tick { work.call }          
    end
  else
    work = Proc.new do
      r = reserve(timeout)
      r.callback do |job|
        blk.call(job)
        EM.next_tick { work.call }
      end
      r.errback do
        EM.next_tick { work.call }
      end
    end
  end      
  work.call
end

#extract_body!(bytes, data) ⇒ Object



379
380
381
382
383
384
385
386
387
388
# File 'lib/em-jack/connection.rb', line 379

def extract_body!(bytes, data)
  rem = data[(data.index(/\r\n/) + 2)..-1]
  return [nil, data] if rem.bytesize < bytes

  body = rem[0..(bytes - 1)]
  data = rem[(bytes + 2)..-1]
  data = "" if data.nil?

  [body, data]
end

#fiber!Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/em-jack/connection.rb', line 65

def fiber!
  @fiberized = true

  eigen = (class << self; self; end)
  eigen.instance_eval do
    %w(use reserve ignore watch peek stats list delete touch bury kick pause release put).each do |meth|
      alias_method :"a#{meth}", meth.to_sym
      define_method(meth.to_sym) do |*args|
        fib = Fiber.current
        ameth = :"a#{meth}"
        proc = lambda { |*result| fib.resume(*result) }
        send(ameth, *args, &proc)
        Fiber.yield
      end
    end
  end
end

#ignore(tube, &blk) ⇒ Object



104
105
106
107
108
109
110
111
112
# File 'lib/em-jack/connection.rb', line 104

def ignore(tube, &blk)
  return unless @watched_tubes.include?(tube)

  callback { @conn.send(:ignore, tube) }

  df = add_deferrable(&blk)
  df.callback { @watched_tubes.delete(tube) }
  df
end

#kick(count = 1, &blk) ⇒ Object



187
188
189
190
191
# File 'lib/em-jack/connection.rb', line 187

def kick(count = 1, &blk)
  callback { @conn.send(:kick, count) }

  add_deferrable(&blk)
end

#list(type = nil, &blk) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
# File 'lib/em-jack/connection.rb', line 153

def list(type = nil, &blk)
  callback {
    case(type)
    when nil then @conn.send(:'list-tubes')
    when :used then @conn.send(:'list-tube-used')
    when :watched then @conn.send(:'list-tubes-watched')
    else raise EMJack::InvalidCommand.new
    end
  }
  add_deferrable(&blk)
end

#on_connect(&blk) ⇒ Object



331
332
333
# File 'lib/em-jack/connection.rb', line 331

def on_connect(&blk)
  @connected_callback = blk
end

#on_disconnect(&blk) ⇒ Object



327
328
329
# File 'lib/em-jack/connection.rb', line 327

def on_disconnect(&blk)
  @disconnected_callback = blk
end

#on_error(&blk) ⇒ Object



323
324
325
# File 'lib/em-jack/connection.rb', line 323

def on_error(&blk)
  @error_callback = blk
end

#pause(tube, delay, &blk) ⇒ Object



193
194
195
196
197
# File 'lib/em-jack/connection.rb', line 193

def pause(tube, delay, &blk)
  callback { @conn.send(:'pause-tube', delay) }

  add_deferrable(&blk)
end

#peek(type = nil, &blk) ⇒ Object



126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/em-jack/connection.rb', line 126

def peek(type = nil, &blk)
  callback {
    case(type.to_s)
    when /^\d+$/ then @conn.send(:peek, type)
    when "ready" then @conn.send(:'peek-ready')
    when "delayed" then @conn.send(:'peek-delayed')
    when "buried" then @conn.send(:'peek-buried')
    else raise EMJack::InvalidCommand.new
    end
  }

  add_deferrable(&blk)
end

#put(msg, opts = nil, &blk) ⇒ Object



210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/em-jack/connection.rb', line 210

def put(msg, opts = nil, &blk)
  opts = {} if opts.nil?

  pri = (opts[:priority] || 65536).to_i
  pri = 65536 if pri< 0
  pri = 2 ** 32 if pri > (2 ** 32)

  delay = (opts[:delay] || 0).to_i
  delay = 0 if delay < 0

  ttr = (opts[:ttr] || 300).to_i
  ttr = 300 if ttr < 0

  m = msg.to_s

  callback { @conn.send_with_data(:put, m, pri, delay, ttr, m.bytesize) }

  add_deferrable(&blk)
end

#received(data) ⇒ Object



339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/em-jack/connection.rb', line 339

def received(data)
  @data << data

  until @data.empty?
    idx = @data.index(/\r\n/)
    break if idx.nil?

    first = @data[0..(idx + 1)]
    df = @deferrables.shift
    handled, skip = false, false
    EMJack::Connection.handlers.each do |h|
      handles, bytes = h.handles?(first)

      next unless handles
      bytes = bytes.to_i

      if bytes > 0
        # if this handler requires us to receive a body make sure we can get
        # the full length of body. If not, we'll go around and wait for more
        # data to be received
        body, @data = extract_body!(bytes, @data) unless bytes <= 0
        break if body.nil?
      else
        @data = @data[(@data.index(/\r\n/) + 2)..-1]
      end

      handled = h.handle(df, first, body, self)
      break if handled
    end

    @deferrables.unshift(df) unless handled

    # not handled means there wasn't enough data to process a complete response
    break unless handled
    next unless @data.index(/\r\n/)

    @data = "" if @data.nil?
  end
end

#reconnect(prev_used, prev_watched) ⇒ Object



294
295
296
297
298
299
300
301
302
# File 'lib/em-jack/connection.rb', line 294

def reconnect(prev_used, prev_watched)
  @conn.reconnect(@host, @port)

  use(prev_used) if prev_used

  [prev_watched].flatten.compact.each do |tube|
    @fiberized ? awatch(tube) : watch(tube)
  end
end

#reconnect!Object



304
305
306
307
308
309
# File 'lib/em-jack/connection.rb', line 304

def reconnect!
  @retries = 0

  prev_used, prev_watched = reset_tube_state
  EM.next_tick { reconnect(prev_used, prev_watched) }
end

#release(job, opts = {}, &blk) ⇒ Object



199
200
201
202
203
204
205
206
207
208
# File 'lib/em-jack/connection.rb', line 199

def release(job, opts = {}, &blk)
  return if job.nil?

  pri = (opts[:priority] || 65536).to_i
  delay = (opts[:delay] || 0).to_i

  callback { @conn.send(:release, job.jobid, pri, delay) }

  add_deferrable(&blk)
end

#reserve(timeout = nil, &blk) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
# File 'lib/em-jack/connection.rb', line 114

def reserve(timeout = nil, &blk)
  callback {
    if timeout
      @conn.send(:'reserve-with-timeout', timeout)
    else
      @conn.send(:reserve)
    end
  }

  add_deferrable(&blk)
end

#reset_tube_stateObject



54
55
56
57
58
59
60
61
62
63
# File 'lib/em-jack/connection.rb', line 54

def reset_tube_state
  prev_used = @used_tube
  prev_watched = @watched_tubes.dup if @watched_tubes

  @used_tube = 'default'
  @watched_tubes = ['default']
  @deferrables = []

  return [prev_used, prev_watched]
end

#stats(type = nil, val = nil, &blk) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/em-jack/connection.rb', line 140

def stats(type = nil, val = nil, &blk)
  callback {
    case(type)
    when nil then @conn.send(:stats)
    when :tube then @conn.send(:'stats-tube', val)
    when :job then @conn.send(:'stats-job', val.jobid)
    else raise EMJack::InvalidCommand.new
    end
  }

  add_deferrable(&blk)
end

#touch(job, &blk) ⇒ Object



173
174
175
176
177
178
179
# File 'lib/em-jack/connection.rb', line 173

def touch(job, &blk)
  return if job.nil?

  callback { @conn.send(:touch, job.jobid) }

  add_deferrable(&blk)
end

#use(tube, &blk) ⇒ Object



83
84
85
86
87
88
89
90
91
92
# File 'lib/em-jack/connection.rb', line 83

def use(tube, &blk)
  return if @used_tube == tube

  callback {
    @used_tube = tube
    @conn.send(:use, tube)
  }

  add_deferrable(&blk)
end

#watch(tube, &blk) ⇒ Object



94
95
96
97
98
99
100
101
102
# File 'lib/em-jack/connection.rb', line 94

def watch(tube, &blk)
  return if @watched_tubes.include?(tube)

  callback { @conn.send(:watch, tube) }

  df = add_deferrable(&blk)
  df.callback { @watched_tubes.push(tube) }
  df
end