Class: CanvasSync::JobBatches::Batch

Inherits:
Object
  • Object
show all
Includes:
RedisModel
Defined in:
lib/canvas_sync/job_batches/batch.rb,
lib/canvas_sync/job_batches/status.rb,
lib/canvas_sync/job_batches/callback.rb

Defined Under Namespace

Modules: Callback Classes: NoBlockGivenError, Status

Constant Summary collapse

BID_EXPIRE_TTL =
2_592_000

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from RedisModel

#persist_bid_attr, #read_bid_attr

Constructor Details

#initialize(existing_bid = nil) ⇒ Batch

Returns a new instance of Batch.



33
34
35
36
37
38
39
# File 'lib/canvas_sync/job_batches/batch.rb', line 33

def initialize(existing_bid = nil)
  @bid = existing_bid || SecureRandom.urlsafe_base64(10)
  @existing = !(!existing_bid || existing_bid.empty?)  # Basically existing_bid.present?
  @initialized = false
  @bidkey = "BID-" + @bid.to_s
  self.created_at = Time.now.utc.to_f unless @existing
end

Instance Attribute Details

#bidObject (readonly)

Returns the value of attribute bid.



31
32
33
# File 'lib/canvas_sync/job_batches/batch.rb', line 31

def bid
  @bid
end

Class Method Details

.cleanup_redis(bid) ⇒ Object



347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/canvas_sync/job_batches/batch.rb', line 347

def cleanup_redis(bid)
  logger.debug {"Cleaning redis of batch #{bid}"}
  redis do |r|
    r.zrem("batches", bid)
    r.unlink(
      "BID-#{bid}",
      "BID-#{bid}-callbacks-complete",
      "BID-#{bid}-callbacks-success",
      "BID-#{bid}-failed",

      "BID-#{bid}-batches-success",
      "BID-#{bid}-batches-complete",
      "BID-#{bid}-batches-failed",
      "BID-#{bid}-bids",
      "BID-#{bid}-jids",
      "BID-#{bid}-pending_callbacks",
    )
  end
end

.delete_prematurely!(bid) ⇒ Object



367
368
369
370
371
372
373
374
375
# File 'lib/canvas_sync/job_batches/batch.rb', line 367

def delete_prematurely!(bid)
  child_bids = redis do |r|
    r.zrange("BID-#{bid}-bids", 0, -1)
  end
  child_bids.each do |cbid|
    delete_prematurely!(cbid)
  end
  cleanup_redis(bid)
end

.enqueue_callbacks(event, bid) ⇒ Object



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
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/canvas_sync/job_batches/batch.rb', line 287

def enqueue_callbacks(event, bid)
  batch_key = "BID-#{bid}"
  callback_key = "#{batch_key}-callbacks-#{event}"
  already_processed, _, callbacks, queue, parent_bid, callback_params = redis do |r|
    return unless r.exists?(batch_key)
    r.multi do
      r.hget(batch_key, event)
      r.hset(batch_key, event, true)
      r.smembers(callback_key)
      r.hget(batch_key, "callback_queue")
      r.hget(batch_key, "parent_bid")
      r.hget(batch_key, "callback_params")
    end
  end

  return if already_processed == 'true'

  queue ||= "default"
  parent_bid = !parent_bid || parent_bid.empty? ? nil : parent_bid    # Basically parent_bid.blank?
  callback_params = JSON.parse(callback_params) if callback_params.present?
  callback_args = callbacks.reduce([]) do |memo, jcb|
    cb = JSON.load(jcb)
    memo << [cb['callback'], event.to_s, cb['opts'], bid, parent_bid]
  end

  opts = {"bid" => bid, "event" => event}

  if callback_args.present? && !callback_params.present?
    logger.debug {"Enqueue callback bid: #{bid} event: #{event} args: #{callback_args.inspect}"}

    redis do |r|
      r.sadd("#{batch_key}-pending_callbacks", event)
      r.expire("#{batch_key}-pending_callbacks", BID_EXPIRE_TTL)
    end

    with_batch(parent_bid) do
      cb_batch = self.new
      cb_batch.callback_params = {
        for_bid: bid,
        event: event,
      }
      opts['callback_bid'] = cb_batch.bid

      logger.debug {"Adding callback batch: #{cb_batch.bid} for batch: #{bid}"}
      cb_batch.jobs do
        push_callbacks callback_args, queue
      end
    end
  end

  if callback_params.present?
    opts['origin'] = callback_params
  end

  logger.debug {"Run batch finalizer bid: #{bid} event: #{event} args: #{callback_args.inspect}"}
  finalizer = Batch::Callback::Finalize.new
  status = Status.new bid
  finalizer.dispatch(status, opts)
end

.loggerObject



381
382
383
# File 'lib/canvas_sync/job_batches/batch.rb', line 381

def logger
  defined?(::Sidekiq) ? ::Sidekiq.logger : Rails.logger
end

.process_dead_job(bid, jid) ⇒ Object



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/canvas_sync/job_batches/batch.rb', line 231

def process_dead_job(bid, jid)
  _, failed, children, complete, parent_bid = redis do |r|
    return unless r.exists?("BID-#{bid}")

    r.multi do
      r.sadd("BID-#{bid}-dead", jid)

      r.scard("BID-#{bid}-dead")
      r.hincrby("BID-#{bid}", "children", 0)
      r.scard("BID-#{bid}-batches-complete")
      r.hget("BID-#{bid}", "parent_bid")

      r.expire("BID-#{bid}-dead", BID_EXPIRE_TTL)
    end
  end

  if parent_bid
    redis do |r|
      r.multi do
        r.sadd("BID-#{parent_bid}-dead", jid)
        r.expire("BID-#{parent_bid}-dead", BID_EXPIRE_TTL)
      end
    end
  end

  enqueue_callbacks(:dead, bid)
end

.process_failed_job(bid, jid) ⇒ Object



209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/canvas_sync/job_batches/batch.rb', line 209

def process_failed_job(bid, jid)
  _, pending, failed, children, complete, parent_bid = redis do |r|
    return unless r.exists?("BID-#{bid}")

    r.multi do
      r.sadd("BID-#{bid}-failed", jid)

      r.hincrby("BID-#{bid}", "pending", 0)
      r.scard("BID-#{bid}-failed")
      r.hincrby("BID-#{bid}", "children", 0)
      r.scard("BID-#{bid}-batches-complete")
      r.hget("BID-#{bid}", "parent_bid")

      r.expire("BID-#{bid}-failed", BID_EXPIRE_TTL)
    end
  end

  if pending.to_i == failed.to_i && children == complete
    enqueue_callbacks(:complete, bid)
  end
end

.process_successful_job(bid, jid) ⇒ Object



259
260
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
# File 'lib/canvas_sync/job_batches/batch.rb', line 259

def process_successful_job(bid, jid)
  _, failed, pending, children, complete, success, parent_bid = redis do |r|
    return unless r.exists?("BID-#{bid}")

    r.multi do
      r.srem("BID-#{bid}-failed", jid)

      r.scard("BID-#{bid}-failed")
      r.hincrby("BID-#{bid}", "pending", -1)
      r.hincrby("BID-#{bid}", "children", 0)
      r.scard("BID-#{bid}-batches-complete")
      r.scard("BID-#{bid}-batches-success")
      r.hget("BID-#{bid}", "parent_bid")

      r.hincrby("BID-#{bid}", "successful-jobs", 1)
      r.zrem("BID-#{bid}-jids", jid)
      r.expire("BID-#{bid}", BID_EXPIRE_TTL)
    end
  end

  all_success = pending.to_i.zero? && children == success
  # if complete or successfull call complete callback (the complete callback may then call successful)
  if (pending.to_i == failed.to_i && children == complete) || all_success
    enqueue_callbacks(:complete, bid)
    enqueue_callbacks(:success, bid) if all_success
  end
end

.push_callbacks(args, queue) ⇒ Object



385
386
387
# File 'lib/canvas_sync/job_batches/batch.rb', line 385

def push_callbacks(args, queue)
  Batch::Callback::worker_class.enqueue_all(args, queue)
end

.redis(*args, &blk) ⇒ Object



377
378
379
# File 'lib/canvas_sync/job_batches/batch.rb', line 377

def redis(*args, &blk)
  defined?(::Sidekiq) ? ::Sidekiq.redis(*args, &blk) : nil # TODO
end

.with_batch(batch) ⇒ Object



154
155
156
157
158
159
160
161
# File 'lib/canvas_sync/job_batches/batch.rb', line 154

def self.with_batch(batch)
  batch = self.new(batch) if batch.is_a?(String)
  parent = Thread.current[:batch]
  Thread.current[:batch] = batch
  yield
ensure
  Thread.current[:batch] = parent
end

.without_batch(&blk) ⇒ Object

Any Batches or Jobs created in the given block won’t be assocaiated to the current batch



164
165
166
# File 'lib/canvas_sync/job_batches/batch.rb', line 164

def self.without_batch(&blk)
  with_batch(nil, &blk)
end

Instance Method Details

#contextObject



47
48
49
50
51
52
53
54
55
# File 'lib/canvas_sync/job_batches/batch.rb', line 47

def context
  return @context if defined?(@context)

  if (@initialized || @existing)
    @context = ContextHash.new(bid)
  else
    @context = ContextHash.new(bid, {})
  end
end

#context=(value) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/canvas_sync/job_batches/batch.rb', line 57

def context=(value)
  raise "context is read-only once the batch has been started" if (@initialized || @existing) # && !allow_context_changes
  raise "context must be a Hash" unless value.is_a?(Hash) || value.nil?
  return nil if value.nil? && @context.nil?

  value = {} if value.nil?
  value = value.local if value.is_a?(ContextHash)

  @context ||= ContextHash.new(bid, {})
  @context.set_local(value)
  # persist_bid_attr('context', JSON.unparse(@context.local))
end

#increment_job_queue(jid) ⇒ Object



126
127
128
129
# File 'lib/canvas_sync/job_batches/batch.rb', line 126

def increment_job_queue(jid)
  assert_batch_is_open
  append_jobs([jid])
end

#invalidate_allObject



131
132
133
134
135
# File 'lib/canvas_sync/job_batches/batch.rb', line 131

def invalidate_all
  redis do |r|
    r.setex("invalidated-bid-#{bid}", BID_EXPIRE_TTL, 1)
  end
end

#jobsObject

Raises:



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
# File 'lib/canvas_sync/job_batches/batch.rb', line 88

def jobs
  raise NoBlockGivenError unless block_given?

  if !@existing && !@initialized
    parent_bid = Thread.current[:batch]&.bid

    redis do |r|
      r.multi do
        r.hset(@bidkey, "parent_bid", parent_bid.to_s) if parent_bid
        r.expire(@bidkey, BID_EXPIRE_TTL)

        if parent_bid
          r.hincrby("BID-#{parent_bid}", "children", 1)
          r.expire("BID-#{parent_bid}", BID_EXPIRE_TTL)
          r.zadd("BID-#{parent_bid}-bids", created_at, bid)
        end
      end
    end

    flush_pending_attrs
    @context&.save!

    @initialized = true
  else
    assert_batch_is_open
  end

  begin
    parent = Thread.current[:batch]
    Thread.current[:batch] = self
    yield
  ensure
    Thread.current[:batch] = parent
  end

  nil
end

#on(event, callback, options = {}) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/canvas_sync/job_batches/batch.rb', line 74

def on(event, callback, options = {})
  return unless Callback::VALID_CALLBACKS.include?(event.to_s)
  callback_key = "#{@bidkey}-callbacks-#{event}"
  redis do |r|
    r.multi do
      r.sadd(callback_key, JSON.unparse({
        callback: callback,
        opts: options
      }))
      r.expire(callback_key, BID_EXPIRE_TTL)
    end
  end
end

#parentObject



143
144
145
146
147
# File 'lib/canvas_sync/job_batches/batch.rb', line 143

def parent
  if parent_bid
    Batch.new(parent_bid)
  end
end

#parent_bidObject



137
138
139
140
141
# File 'lib/canvas_sync/job_batches/batch.rb', line 137

def parent_bid
  redis do |r|
    r.hget(@bidkey, "parent_bid")
  end
end

#save_context_changesObject



70
71
72
# File 'lib/canvas_sync/job_batches/batch.rb', line 70

def save_context_changes
  @context&.save!
end

#valid?(batch = self) ⇒ Boolean

Returns:

  • (Boolean)


149
150
151
152
# File 'lib/canvas_sync/job_batches/batch.rb', line 149

def valid?(batch = self)
  valid = !redis { |r| r.exists?("invalidated-bid-#{batch.bid}") }
  batch.parent ? valid && valid?(batch.parent) : valid
end