Class: PerfectQueue::Backend::RDBCompatBackend

Inherits:
Object
  • Object
show all
Includes:
PerfectQueue::BackendHelper
Defined in:
lib/perfectqueue/backend/rdb_compat.rb

Defined Under Namespace

Classes: Token

Constant Summary collapse

MAX_RETRY =

KEEPALIVE = 10

10
DEFAULT_DELETE_INTERVAL =
20

Instance Attribute Summary collapse

Attributes included from PerfectQueue::BackendHelper

#client

Instance Method Summary collapse

Methods included from PerfectQueue::BackendHelper

#close

Constructor Details

#initialize(client, config) ⇒ RDBCompatBackend

Returns a new instance of RDBCompatBackend.



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
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 27

def initialize(client, config)
  super

  require 'sequel'
  url = config[:url]
  @table = config[:table]
  unless @table
    raise ConfigError, ":table option is required"
  end

  #password = config[:password]
  #user = config[:user]
  @db = Sequel.connect(url, :max_connections=>1)
  @mutex = Mutex.new

  connect {
    # connection test
  }

  if config[:disable_resource_limit]
    @sql = "SELECT id, timeout, data, created_at, resource\nFROM `\#{@table}`\nWHERE timeout <= ? AND timeout <= ? AND created_at IS NOT NULL\nORDER BY timeout ASC\nLIMIT ?\n"
  else
    @sql = "SELECT id, timeout, data, created_at, resource, max_running, max_running/running AS weight\nFROM `\#{@table}`\nLEFT JOIN (\n  SELECT resource AS res, COUNT(1) AS running\n  FROM `\#{@table}` AS T\n  WHERE timeout > ? AND created_at IS NOT NULL AND resource IS NOT NULL\n  GROUP BY resource\n) AS R ON resource = res\nWHERE timeout <= ? AND created_at IS NOT NULL AND (max_running-running IS NULL OR max_running-running > 0)\nORDER BY weight IS NOT NULL, weight DESC, timeout ASC\nLIMIT ?\n"
  end

  case url.split('//',2)[0].to_s
  when /sqlite/i
    # sqlite always locks tables on BEGIN
    @table_lock = nil
  when /mysql/i
    if config[:disable_resource_limit]
      @table_lock = "LOCK TABLES `#{@table}` WRITE"
    else
      @table_lock = "LOCK TABLES `#{@table}` WRITE, `#{@table}` AS T WRITE"
    end
  else
    @table_lock = "LOCK TABLE `#{@table}`"
  end

  @prefetch_break_types = config[:prefetch_break_types] || []

  @cleanup_interval = config[:cleanup_interval] || DEFAULT_DELETE_INTERVAL
  @cleanup_interval_count = 0
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



90
91
92
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 90

def db
  @db
end

Instance Method Details

#acquire(alive_time, max_acquire, options) ⇒ Object

> [AcquiredTask]



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
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 187

def acquire(alive_time, max_acquire, options)
  now = (options[:now] || Time.now).to_i
  next_timeout = now + alive_time

  tasks = []

  connect {
    if @cleanup_interval_count <= 0
      @db["DELETE FROM `#{@table}` WHERE timeout <= ? AND created_at IS NULL", now].delete
      @cleanup_interval_count = @cleanup_interval
    end

    @db.transaction do
      if @table_lock
        @db[@table_lock].update
      end

      tasks = []
      @db.fetch(@sql, now, now, max_acquire) {|row|
        attributes = create_attributes(nil, row)
        task_token = Token.new(row[:id])
        task = AcquiredTask.new(@client, row[:id], attributes, task_token)
        tasks.push task

        if @prefetch_break_types.include?(attributes[:type])
          break
        end
      }

      if tasks.empty?
        return nil
      end

      sql = "UPDATE `#{@table}` SET timeout=? WHERE id IN ("
      params = [sql, next_timeout]
      tasks.each {|t| params << t.key }
      sql << (1..tasks.size).map { '?' }.join(',')
      sql << ") AND created_at IS NOT NULL"

      n = @db[*params].update
      if n != tasks.size
        # TODO table lock doesn't work. error?
      end

      @cleanup_interval_count -= 1
    end
    return tasks
  }
end

#cancel_request(key, options) ⇒ Object

> nil



238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 238

def cancel_request(key, options)
  now = (options[:now] || Time.now).to_i

  # created_at=0 means cancel_requested
  connect {
    n = @db["UPDATE `#{@table}` SET created_at=0 WHERE id=? AND created_at IS NOT NULL", key].update
    if n <= 0
      raise AlreadyFinishedError, "task key=#{key} does not exist or already finished."
    end
  }
  nil
end

#finish(task_token, retention_time, options) ⇒ Object

> nil



256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 256

def finish(task_token, retention_time, options)
  now = (options[:now] || Time.now).to_i
  delete_timeout = now + retention_time
  key = task_token.key

  connect {
    n = @db["UPDATE `#{@table}` SET timeout=?, created_at=NULL, resource=NULL WHERE id=? AND created_at IS NOT NULL", delete_timeout, key].update
    if n <= 0
      raise IdempotentAlreadyFinishedError, "task key=#{key} does not exist or already finished."
    end
  }
  nil
end

#force_finish(key, retention_time, options) ⇒ Object



251
252
253
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 251

def force_finish(key, retention_time, options)
  finish(Token.new(key), retention_time, options)
end

#get_task_metadata(key, options) ⇒ Object

> TaskStatus



113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 113

def (key, options)
  now = (options[:now] || Time.now).to_i

  connect {
    row = @db.fetch("SELECT timeout, data, created_at, resource, max_running FROM `#{@table}` WHERE id=? LIMIT 1", key).first
    unless row
      raise NotFoundError, "task key=#{key} does no exist"
    end
    attributes = create_attributes(now, row)
    return .new(@client, key, attributes)
  }
end

#heartbeat(task_token, alive_time, options) ⇒ Object

> nil



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
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 271

def heartbeat(task_token, alive_time, options)
  now = (options[:now] || Time.now).to_i
  next_timeout = now + alive_time
  key = task_token.key
  data = options[:data]

  sql = "UPDATE `#{@table}` SET timeout=?"
  params = [sql, next_timeout]
  if data
    sql << ", data=?"
    params << data.to_json
  end
  sql << " WHERE id=? AND created_at IS NOT NULL"
  params << key

  connect {
    n = @db[*params].update
    if n <= 0
      row = @db.fetch("SELECT id, timeout, created_at FROM `#{@table}` WHERE id=? LIMIT 1", key).first
      if row == nil
        raise PreemptedError, "task key=#{key} does not exist or preempted."
      elsif row[:created_at] == nil
        raise PreemptedError, "task key=#{key} preempted."
      elsif row[:created_at] <= 0
        raise CancelRequestedError, "task key=#{key} is cancel requested."
      else # row[:timeout] == next_timeout
        # ok
      end
    end
  }
  nil
end

#init_database(options) ⇒ Object



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 96

def init_database(options)
  sql = %[
      CREATE TABLE IF NOT EXISTS `#{@table}` (
        id VARCHAR(256) NOT NULL,
        timeout INT NOT NULL,
        data BLOB NOT NULL,
        created_at INT,
        resource VARCHAR(256),
        max_running INT,
        PRIMARY KEY (id)
      );]
  connect {
    @db.run sql
  }
end

#list(options, &block) ⇒ Object

yield [TaskWithMetadata]



132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 132

def list(options, &block)
  now = (options[:now] || Time.now).to_i

  connect {
    #@db.fetch("SELECT id, timeout, data, created_at, resource FROM `#{@table}` WHERE !(created_at IS NULL AND timeout <= ?) ORDER BY timeout ASC;", now) {|row|
    @db.fetch("SELECT id, timeout, data, created_at, resource, max_running FROM `#{@table}` ORDER BY timeout ASC", now) {|row|
      attributes = create_attributes(now, row)
      task = .new(@client, row[:id], attributes)
      yield task
    }
  }
end

#preempt(key, alive_time, options) ⇒ Object

> AcquiredTask

Raises:



127
128
129
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 127

def preempt(key, alive_time, options)
  raise NotSupportedError.new("preempt is not supported by rdb_compat backend")
end

#release(task_token, alive_time, options) ⇒ Object



304
305
306
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 304

def release(task_token, alive_time, options)
  heartbeat(task_token, alive_time, options)
end

#submit(key, type, data, options) ⇒ Object

> Task



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
# File 'lib/perfectqueue/backend/rdb_compat.rb', line 146

def submit(key, type, data, options)
  now = (options[:now] || Time.now).to_i
  now = 1 if now < 1  # 0 means cancel requested
  run_at = (options[:run_at] || now).to_i
  user = options[:user]
  user = user.to_s if user
  max_running = options[:max_running]
  data = data ? data.dup : {}
  data['type'] = type

  d = data.to_json

  if options[:compression] == 'gzip'
    require 'zlib'
    require 'stringio'
    io = StringIO.new
    gz = Zlib::GzipWriter.new(io)
    begin
      gz.write(d)
    ensure
      gz.close
    end
    d = io.string
    d.force_encoding('ASCII-8BIT') if d.respond_to?(:force_encoding)
    d = Sequel::SQL::Blob.new(d)
  end

  connect {
    begin
      n = @db[
        "INSERT INTO `#{@table}` (id, timeout, data, created_at, resource, max_running) VALUES (?, ?, ?, ?, ?, ?)",
        key, run_at, d, now, user, max_running
      ].insert
      return Task.new(@client, key)
    rescue Sequel::DatabaseError
      raise IdempotentAlreadyExistsError, "task key=#{key} already exists"
    end
  }
end