Class: Heimdall::Database

Inherits:
Object show all
Defined in:
lib/heimdall/heimdall_database.rb

Instance Method Summary collapse

Instance Method Details

#add(job_class, opts = {}) ⇒ Object



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
# File 'lib/heimdall/heimdall_database.rb', line 16

def add job_class, opts = {}
  opts = opts.dup
  uid  = nil

  job_cattr = job_class.cattr

  # job unique ID, unique accross all jobs. Genareate complicated SHA1 on many keys?
  # used to define UID on jobs that last long
  # example: PDF generation that last a long time. user hits page refresh multiple times, only one job is added
  # [@uique_id_string, @time_to_be_valid_in_seconds or 0 for inf]
  if (ttl_seconds = (opts.delete(:_unique_for) || job_cattr.unique_for))
    unless ttl_seconds.is_numeric?
      raise ArgumentError, '_ttl argument is not numneric'
    end

    uid = Digest::SHA1.hexdigest((job_class.to_s + opts.to_s).chars.sort.join)

    if db[:tasks].where(uid: uid).where(Sequel.lit('created_at > ?', Time.now - ttl_seconds.to_i.seconds)).first
      Heimdall.logger.info '%s skipped add by TTL check' % job_class
    end
  end

  batch   = opts.delete :_batch
  retries = job_class.cattr.retries.to_i
  retries = 1 if retries < 1

  scheduled_at = opts.delete(:_scheduled_at).to_i

  task = Task.create({
    created_at: Time.now,
    scheduled_at: Time.at(scheduled_at),
    job: job_class.to_s,
    opts: opts.to_json,
    uid: uid,
    batch: batch,
    remaining_runs: retries,
    total_runs: 0,
    status_sid: 'a'
  })

  task.logger 'ADDED - %s' % opts.to_json

  task
end

#available_idsObject



76
77
78
# File 'lib/heimdall/heimdall_database.rb', line 76

def available_ids
  available_base.select(:id).to_a.map{|el| el[:id] }
end

#dbObject



12
13
14
# File 'lib/heimdall/heimdall_database.rb', line 12

def db
  CONFIG[:db]
end

#popObject



61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/heimdall/heimdall_database.rb', line 61

def pop
  if (task = available_base.first)
    task.total_runs     += 1
    task.update({
      status_sid: 'r',
      started_at: Time.now,
      restart_at: Time.now + task.job_class.cattr.timeout.to_i.seconds,
      finished_at: nil,
      total_runs: task.total_runs
    })

    task
  end
end