Class: Joblin::Batching::Batch

Inherits:
Object
  • Object
show all
Includes:
RediConn::RedisModel
Defined in:
lib/joblin/batching/batch.rb,
lib/joblin/batching/status.rb,
lib/joblin/batching/callback.rb

Defined Under Namespace

Modules: Callback Classes: NoBlockGivenError, Status

Constant Summary collapse

BID_EXPIRE_TTL =
90.days.to_i
INDEX_ALL_BATCHES =
false
SCHEDULE_CALLBACK =
RediConn::RedisScript.new(Pathname.new(__FILE__) + "../schedule_callback.lua")
BID_HIERARCHY =
RediConn::RedisScript.new(Pathname.new(__FILE__) + "../hier_batch_ids.lua")

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(existing_bid = nil) ⇒ Batch

Returns a new instance of Batch.



37
38
39
40
41
42
43
# File 'lib/joblin/batching/batch.rb', line 37

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.



27
28
29
# File 'lib/joblin/batching/batch.rb', line 27

def bid
  @bid
end

Class Method Details

.apply_apm_tags!Object



261
262
263
264
265
266
267
268
269
# File 'lib/joblin/batching/batch.rb', line 261

def apply_apm_tags!
  if defined?(Sentry)
    scope = Sentry.get_current_scope
    scope&.set_tags({
      "joblin.batch_id" => current&.bid,
    })
  end
rescue => e
end

.bid_hierarchy(bid, depth: 4, per_depth: 5, slice: nil) ⇒ Object



563
564
565
566
567
568
569
# File 'lib/joblin/batching/batch.rb', line 563

def bid_hierarchy(bid, depth: 4, per_depth: 5, slice: nil)
  args = [bid, depth, per_depth]
  args << slice if slice
  redis do |r|
    BID_HIERARCHY.call(r, [], args)
  end
end

.cleanup_redis(bid) ⇒ Object



482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
# File 'lib/joblin/batching/batch.rb', line 482

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

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

.cleanup_redis_index!Object

Administrative/console method to cleanup expired batches from the WebUI



536
537
538
539
540
541
542
543
544
545
546
547
548
549
# File 'lib/joblin/batching/batch.rb', line 536

def cleanup_redis_index!
  suffixes = ["", "-callbacks-complete", "-callbacks-success", "-failed", "-dead", "-batches-success", "-batches-complete", "-batches-failed", "-bids", "-jids", "-pending_callbacks"]

  redis do |r|
    cleanup_index = ->(index) {
      r.zrangebyscore(index, "0", BID_EXPIRE_TTL.seconds.ago.to_i).each do |bid|
        r.zrem(index, bid) if cleanup_redis_index_for("BID-#{bid}", suffixes)
      end
    }

    cleanup_index.("BID-ROOT-bids")
    cleanup_index.("batches")
  end
end

.cleanup_redis_index_for(key, suffixes = [""]) ⇒ Object

Internal method to cleanup a Redis Hash and related keys



515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
# File 'lib/joblin/batching/batch.rb', line 515

def cleanup_redis_index_for(key, suffixes = [""])
  redis do |r|
    if r.hget(key, "created_at").present?
      r.multi do |r|
        suffixes.each do |suffix|
          r.expire(key + suffix, BID_EXPIRE_TTL)
        end
      end
      false
    else
      r.multi do |r|
        suffixes.each do |suffix|
          r.unlink(key + suffix)
        end
      end
      true
    end
  end
end

.currentObject



29
30
31
# File 'lib/joblin/batching/batch.rb', line 29

def self.current
  Thread.current[CURRENT_BATCH_THREAD_KEY]
end

.current_contextObject



33
34
35
# File 'lib/joblin/batching/batch.rb', line 33

def self.current_context
  self.current&.context
end

.delete_prematurely!(bid) ⇒ Object



504
505
506
507
508
509
510
511
512
# File 'lib/joblin/batching/batch.rb', line 504

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



411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'lib/joblin/batching/batch.rb', line 411

def enqueue_callbacks(event, bid)
  batch_key = "BID-#{bid}"
  callback_key = "#{batch_key}-callbacks-#{event}"

  exists, callbacks, queue, parent_bid, callback_params = redis do |r|
    r.multi do |r|
      r.exists?(batch_key)

      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 unless exists

  queue ||= "default"
  parent_bid = !parent_bid || parent_bid.empty? ? nil : parent_bid # Basically parent_bid.blank?

  # Internal callback params. If this is present, we're trying to enqueue callbacks for a callback, which is a special case that
  # indicates that the callback completed and we need to close the triggering batch (which is in a done-but-not-cleaned state)
  callback_params = JSON.parse(callback_params) if callback_params.present?

  # User-configured parameters/arguments to pass to the callback
  callback_args = callbacks.reduce([]) do |memo, jcb|
    cb = JSON.parse(jcb)
    memo << [cb['callback'], event.to_s, cb['opts'], bid, parent_bid]
  end

  opts = {"bid" => bid, "event" => event}
  should_schedule_batch = callback_args.present? && !callback_params.present?
  already_processed = redis do |r|
    SCHEDULE_CALLBACK.call(r, [batch_key], [event.to_s, should_schedule_batch.to_s, BID_EXPIRE_TTL])
  end

  return if already_processed == 'true'

  if should_schedule_batch
    logger.debug {"Enqueue callback bid: #{bid} event: #{event} args: #{callback_args.inspect}"}

    # Create a new Batch to handle the callbacks and add it to the _parent_ batch
    #   (this ensures that the parent's lifecycle status can't change until the child's callbacks are done)
    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?
    # This is a callback for a callback. Passing `origin` to the Finalizer allows it to also cleanup the original/callback-triggering batch
    opts['origin'] = callback_params
  end

  # The Finalizer marks this batch as complete, bumps any necessary counters, cleans up this Batch _if_ no callbacks were scheduled,
  #   and enqueues parent-Batch callbacks if needed.
  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



555
556
557
# File 'lib/joblin/batching/batch.rb', line 555

def logger
  ::Joblin.logger
end

.process_dead_job(bid, jid) ⇒ Object

Dead jobs are a Sidekiq feature. If this is called for a job, process_failed_job was also called



393
394
395
396
397
398
399
400
# File 'lib/joblin/batching/batch.rb', line 393

def process_dead_job(bid, jid)
  enqueue_callbacks(:death, bid)

  with_callback_check(bid) do |r|
    r.sadd("BID-#{bid}-dead", jid)
    r.expire("BID-#{bid}-dead", BID_EXPIRE_TTL)
  end
end

.process_failed_job(bid, jid) ⇒ Object



384
385
386
387
388
389
# File 'lib/joblin/batching/batch.rb', line 384

def process_failed_job(bid, jid)
  with_callback_check(bid, except: [:success]) do |r|
    r.sadd("BID-#{bid}-failed", jid)
    r.expire("BID-#{bid}-failed", BID_EXPIRE_TTL)
  end
end

.process_successful_job(bid, jid) ⇒ Object



402
403
404
405
406
407
408
409
# File 'lib/joblin/batching/batch.rb', line 402

def process_successful_job(bid, jid)
  with_callback_check(bid) do |r|
    r.srem("BID-#{bid}-failed", jid)
    r.hincrby("BID-#{bid}", "pending", -1)
    r.hincrby("BID-#{bid}", "successful-jobs", 1)
    r.zrem("BID-#{bid}-jids", jid)
  end
end

.push_callbacks(args, queue) ⇒ Object



559
560
561
# File 'lib/joblin/batching/batch.rb', line 559

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

.redis(&blk) ⇒ Object



551
552
553
# File 'lib/joblin/batching/batch.rb', line 551

def redis(&blk)
  ::Joblin.redis(&blk)
end

.with_batch(batch) ⇒ Object



178
179
180
181
182
183
184
185
# File 'lib/joblin/batching/batch.rb', line 178

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

.with_callback_check(bid, except: [], only: Callback::VALID_CALLBACKS, &blk) ⇒ Object

Perform a success/failure/complete/etc transaction against Redis, checking if any callbacks should be triggered



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
333
334
335
336
337
338
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
378
379
380
381
382
# File 'lib/joblin/batching/batch.rb', line 273

def with_callback_check(bid, except: [], only: Callback::VALID_CALLBACKS, &blk)
  except = Array(except).map(&:to_sym)
  only = Array(only).map(&:to_sym)

  precount = 0

  # WATCH the batch hash so this transaction (the caller's mutations *and*
  # the state reads/expirations, some of which — e.g. hincrby "pending" —
  # would otherwise recreate the hash) aborts if a concurrent cleanup_redis
  # deletes the batch after we've checked it exists. An aborted EXEC applies
  # nothing, so re-running the block on retry is safe (no double-apply).
  # Concurrent mutations of the *same* bid can also abort us; we retry a
  # bounded number of times and give up loudly rather than spin forever.
  max_attempts = 50
  all_results =
    redis do |r|
      attempts = 0
      loop do
        attempts += 1
        result = r.watch("BID-#{bid}") do |rc|
          if rc.exists?("BID-#{bid}")
            rc.multi do |r|
              blk.call(r)
              futures = r.instance_variable_get(:@futures) || r.instance_variable_get(:@pipeline)&.futures || r.instance_variable_get(:@client)&.futures
              precount = futures.size

              # Misc
              r.hget("BID-#{bid}", "parent_bid")
              r.hget("BID-#{bid}", "keep_open")
              r.scard("BID-#{bid}-holds")

              # Jobs
              r.hincrby("BID-#{bid}", "pending", 0)
              r.scard("BID-#{bid}-failed")
              r.scard("BID-#{bid}-dead")

              # Batches
              r.hincrby("BID-#{bid}", "children", 0)
              r.scard("BID-#{bid}-batches-complete")
              r.scard("BID-#{bid}-batches-success")
              r.scard("BID-#{bid}-batches-failed")
              r.scard("BID-#{bid}-batches-stagnated")

              # Touch Expirations
              r.expire("BID-#{bid}", BID_EXPIRE_TTL)
              r.expire("BID-#{bid}-batches-success", BID_EXPIRE_TTL)
            end
          else
            # Batch was cleaned up; nothing to process.
            rc.unwatch
            :missing
          end
        end

        # :missing => batch gone; Array => committed; nil => EXEC aborted (retry).
        break result unless result.nil?

        if attempts >= max_attempts
          raise "with_callback_check: gave up after #{attempts} attempts due to contention on BID-#{bid}"
        end
      end
    end

  return if all_results == :missing

  # Exclude return values from the passed block
  actual_results = all_results[precount..-1]

  # "pending" = not successful (yet)
  # "failed" = dead or retrying
  # "complete" = successful or failed

  parent_bid, keep_open, holds, \
    pending_jobs, failed_jobs, dead_jobs, \
    child_batches, complete_batches, success_batches, failed_batches, stagnated_batches \
    = actual_results

  pending_batches = child_batches - success_batches

  if keep_open == 'true' || (holds && holds > 0)
    except << :complete
    except << :success
  end

  trigger_callback = ->(callback) {
    next if except.include?(callback.to_sym)
    next unless only.include?(callback.to_sym)

    Batch.logger.debug {"Finalize #{callback} bid: #{parent_bid}"}
    enqueue_callbacks(callback, bid)
  }

  # Handling all of these cases in one method may be a little less performant than in more specialized methods, but
  #   I was dealing with duplicate Redis queries and checks being made in up to 4 places and it was getting out of
  #   hand - this combined method should be easier to maintain and reason about

  all_successful = pending_jobs.zero? && child_batches == success_batches

  if all_successful || (pending_jobs == failed_jobs && child_batches == complete_batches) # All Complete
    trigger_callback.call(:complete)
  end

  if all_successful # All Successful
    trigger_callback.call(:success)
  elsif pending_jobs == dead_jobs && pending_batches == stagnated_batches # Stagnated
    trigger_callback.call(:stagnated)
  end

  all_results[0...precount]
end

.without_batch(&blk) ⇒ Object

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



188
189
190
# File 'lib/joblin/batching/batch.rb', line 188

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

Instance Method Details

#append_jobs(jids) ⇒ Object



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/joblin/batching/batch.rb', line 192

def append_jobs(jids)
  jids = Array(jids)
  jids = jids.uniq
  return unless jids.size > 0

  redis do |r|
    tme = Time.now.utc.to_f
    added = r.zadd(@bidkey + "-jids", jids.map{|jid| [tme, jid] }, nx: true)
    r.multi do |r|
      r.hincrby(@bidkey, "pending", added)
      r.hincrby(@bidkey, "job_count", added)
      r.expire(@bidkey, BID_EXPIRE_TTL)
      r.expire(@bidkey + "-jids", BID_EXPIRE_TTL)
    end
  end
end

#contextObject



51
52
53
54
55
56
57
58
59
# File 'lib/joblin/batching/batch.rb', line 51

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

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

#context=(value) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/joblin/batching/batch.rb', line 61

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

#invalidate_allObject



126
127
128
# File 'lib/joblin/batching/batch.rb', line 126

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

#jobsObject

Raises:



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# File 'lib/joblin/batching/batch.rb', line 96

def jobs
  raise NoBlockGivenError unless block_given?

  persist!

  # TODO This keep_open! block is probably desired, but it has some caveats:
  #  - Old logic didn't auto-clean empty batches
  #  - Could be an issue if the Thread crashes at a bad moment (do we even need to plan for this?)
  #  - Technically there could be a race condition without it, but such hasn't been observed

  # keep_open! do
  begin
    parent = Thread.current[CURRENT_BATCH_THREAD_KEY]
    Thread.current[CURRENT_BATCH_THREAD_KEY] = self
    yield
  ensure
    Thread.current[CURRENT_BATCH_THREAD_KEY] = parent
  end
  # end

  nil
end

#keep_open!(token = SecureRandom.urlsafe_base64(10)) ⇒ Object



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/joblin/batching/batch.rb', line 145

def keep_open!(token = SecureRandom.urlsafe_base64(10))
  if block_given?
    begin
      token = keep_open!(token)
      yield
    ensure
      let_close!(token)
    end
  else
    persist!

    redis.multi do |r|
      r.sadd("#{@bidkey}-holds", token)
      r.expire("#{@bidkey}-holds", BID_EXPIRE_TTL)
    end

    assert_batch_is_open

    token
  end
end

#let_close!(token = :unset) ⇒ Object



167
168
169
170
171
172
173
174
175
176
# File 'lib/joblin/batching/batch.rb', line 167

def let_close!(token = :unset)
  self.class.with_callback_check(bid, only: %i[complete success]) do |r|
    if token == :unset # Legacy
      r.del("#{@bidkey}-holds")
      r.hset(@bidkey, 'keep_open', "false")
    else
      r.srem("#{@bidkey}-holds", token)
    end
  end
end

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

Events: :complete - triggered once all jobs have been executed, regardless of success or failure. :success - triggered once all jobs haves successfully executed. :death - triggered after any job enters the dead state. :stagnated - triggered when a job dies and no other jobs/batches are active.



83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/joblin/batching/batch.rb', line 83

def on(event, callback, options = {})
  return unless Callback::VALID_CALLBACKS.include?(event.to_sym)

  callback_key = "#{@bidkey}-callbacks-#{event}"
  redis.multi do |r|
    r.sadd(callback_key, JSON.unparse({
      callback: callback,
      opts: options
    }))
    r.expire(callback_key, BID_EXPIRE_TTL)
  end
end

#parentObject



134
135
136
137
138
# File 'lib/joblin/batching/batch.rb', line 134

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

#parent_bidObject



130
131
132
# File 'lib/joblin/batching/batch.rb', line 130

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

#placeholder!Object

Mark this Batch as a placeholder. It will be persisted to Redis, but no jobs will be added. From here, you can either use .jobs on the batch to add jobs as usual, or call .let_close! to allow cleanup to occur.



121
122
123
124
# File 'lib/joblin/batching/batch.rb', line 121

def placeholder!
  # TODO Provide a stable `let_close!` token?
  persist!
end

#save_context_changesObject



74
75
76
# File 'lib/joblin/batching/batch.rb', line 74

def save_context_changes
  @context&.save!
end

#valid?(batch = self) ⇒ Boolean

Returns:

  • (Boolean)


140
141
142
143
# File 'lib/joblin/batching/batch.rb', line 140

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