/
qless.rb
243 lines (200 loc) · 6.08 KB
/
qless.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
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# Encoding: utf-8
require 'socket'
require 'redis'
require 'json'
require 'securerandom'
# The top level container for all things qless
module Qless
# Define our error base class before requiring the other files so they can
# define subclasses.
Error = Class.new(StandardError)
# to maintain backwards compatibility with v2.x of that gem we need this
# constant because:
# - (lua.rb) the #evalsha method signature changed between v2.x and v3.x of
# the redis ruby gem
# - (worker.rb) in v3.x you have to reconnect to the redis server after
# forking the process
USING_LEGACY_REDIS_VERSION = ::Redis::VERSION.to_f < 3.0
end
require 'qless/version'
require 'qless/config'
require 'qless/queue'
require 'qless/job'
require 'qless/lua_script'
require 'qless/failure_formatter'
# The top level container for all things qless
module Qless
UnsupportedRedisVersionError = Class.new(Error)
def generate_jid
SecureRandom.uuid.gsub('-', '')
end
def stringify_hash_keys(hash)
hash.each_with_object({}) do |(key, value), result|
result[key.to_s] = value
end
end
# This is a unique identifier for the worker
def worker_name
@worker_name ||= [Socket.gethostname, Process.pid.to_s].join('-')
end
def failure_formatter
@failure_formatter ||= FailureFormatter.new
end
module_function(
:generate_jid, :stringify_hash_keys, :worker_name, :failure_formatter)
# A class for interacting with jobs. Not meant to be instantiated directly,
# it's accessed through Client#jobs
class ClientJobs
def initialize(client)
@client = client
end
def complete(offset = 0, count = 25)
@client.call('jobs', 'complete', offset, count)
end
def tracked
results = JSON.parse(@client.call('track'))
results['jobs'] = results['jobs'].map { |j| Job.new(@client, j) }
results
end
def tagged(tag, offset = 0, count = 25)
JSON.parse(@client.call('tag', 'get', tag, offset, count))
end
def failed(t = nil, start = 0, limit = 25)
if !t
return JSON.parse(@client.call('failed'))
else
results = JSON.parse(@client.call('failed', t, start, limit))
results['jobs'] = multiget(*results['jobs'])
results
end
end
def [](id)
get(id)
end
def get(jid)
results = @client.call('get', jid)
if results.nil?
results = @client.call('recur.get', jid)
return nil if results.nil?
return RecurringJob.new(@client, JSON.parse(results))
end
Job.new(@client, JSON.parse(results))
end
def multiget(*jids)
results = JSON.parse(@client.call('multiget', *jids))
results.map do |data|
Job.new(@client, data)
end
end
end
# A class for interacting with workers. Not meant to be instantiated
# directly, it's accessed through Client#workers
class ClientWorkers
def initialize(client)
@client = client
end
def counts
JSON.parse(@client.call('workers'))
end
def [](name)
JSON.parse(@client.call('workers', name))
end
end
# A class for interacting with queues. Not meant to be instantiated directly,
# it's accessed through Client#queues
class ClientQueues
def initialize(client)
@client = client
end
def counts
JSON.parse(@client.call('queues'))
end
def [](name)
Queue.new(name, @client)
end
end
# A class for interacting with events. Not meant to be instantiated directly,
# it's accessed through Client#events
class ClientEvents
EVENTS = %w{canceled completed failed popped stalled put track untrack}
EVENTS.each do |method|
define_method(method.to_sym) do |&block|
@actions[method.to_sym] = block
end
end
def initialize(redis)
@redis = redis
@actions = {}
end
def listen
yield(self) if block_given?
channels = EVENTS.map { |event| "ql:#{event}" }
@redis.subscribe(channels) do |on|
on.message do |channel, message|
callback = @actions[channel.sub('ql:', '').to_sym]
callback.call(message) unless callback.nil?
end
end
end
def stop
@redis.unsubscribe
end
end
# The client for interacting with Qless
class Client
# Lua script
attr_reader :_qless
# A real object
attr_reader :config, :redis, :jobs, :queues, :workers
def initialize(options = {})
# This is the redis instance we're connected to. Use connect so REDIS_URL
# will be honored
@redis = options[:redis] || Redis.connect(options)
@options = options
assert_minimum_redis_version('2.5.5')
@config = Config.new(self)
@_qless = Qless::LuaScript.new('qless', @redis)
@jobs = ClientJobs.new(self)
@queues = ClientQueues.new(self)
@workers = ClientWorkers.new(self)
end
def inspect
"<Qless::Client #{@options} >"
end
def events
# Events needs its own redis instance of the same configuration, because
# once it's subscribed, we can only use pub-sub-like commands. This way,
# we still have access to the client in the normal case
@events ||= ClientEvents.new(Redis.connect(@options))
end
def call(command, *argv)
@_qless.call(command, Time.now.to_f, *argv)
end
def track(jid)
call('track', 'track', jid)
end
def untrack(jid)
call('track', 'untrack', jid)
end
def tags(offset = 0, count = 100)
JSON.parse(call('tag', 'top', offset, count))
end
def deregister_workers(*worker_names)
call('worker.deregister', *worker_names)
end
def bulk_cancel(jids)
call('cancel', jids)
end
def new_redis_connection
::Redis.new(url: redis.id)
end
private
def assert_minimum_redis_version(version)
# remove the "-pre2" from "2.6.8-pre2"
redis_version = @redis.info.fetch('redis_version').split('-').first
return if Gem::Version.new(redis_version) >= Gem::Version.new(version)
raise UnsupportedRedisVersionError,
"Qless requires #{version} or better, not #{redis_version}"
end
end
end