Class: Kindly::DB

Inherits:
Object
  • Object
show all
Defined in:
lib/kindly/db.rb

Constant Summary collapse

DEFAULTS =
{
  :table_names => {
    :ping => 'user-ping',
    :data => 'job-data',
    :pending => 'job-pending',
    :running => 'job-running',
    :completed => 'job-completed',
    :failed => 'job-failed'
  }
}

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ DB

Returns a new instance of DB.



18
19
20
21
# File 'lib/kindly/db.rb', line 18

def initialize(options = {})
  @config = DEFAULTS.merge(options)
  @db = Aws::DynamoDB::Client.new(region: 'us-west-2')
end

Instance Method Details

#fetch_job(job_name, job_id) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/kindly/db.rb', line 65

def fetch_job(job_name, job_id)
  job = Registry.find(job_name)
  fields = fetch_job_fields(job_id)
  add_fields_to_job(job, fields)

  if job.fields.has_key?('InputDataId')
    input = fetch_job_data(job.fields['InputDataId'])
    job.input = input
  elsif job.fields.has_key?('Input')
    job.input = job.fields['Input']
  end
  job
end

#insert_job(job_name, input) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/kindly/db.rb', line 38

def insert_job(job_name, input)
  item = {
    'JobId' => SecureRandom.uuid,
    'JobName' => job_name,
    'RequestedAt' => Time.now.to_s,
    'RequestedBy' => user.user_name
  }

  unless input.empty?
    data = insert_job_data(input)
    item['InputDataId'] = data['JobDataId']
  end

  @db.put_item({ table_name: 'job-pending', item: item })
  item
end

#insert_job_data(data) ⇒ Object



55
56
57
58
59
60
61
62
63
# File 'lib/kindly/db.rb', line 55

def insert_job_data(data)
  item = {
    'JobDataId' => SecureRandom.uuid,
    'Data' => data,
    'CreatedAt' => Time.now.to_s
  }
  @db.put_item({ table_name: 'job-data', item: item })
  item
end

#pingObject



27
28
29
30
31
32
33
34
35
36
# File 'lib/kindly/db.rb', line 27

def ping
  item = {
    'PingId' => SecureRandom.uuid,
    'PingBy' => user.user_name,
    'PingAt' => Time.now.to_s
  }

  @db.put_item({ table_name: @config[:table_names][:ping], item: item })
  item
end

#update_job_status(job, job_status) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
# File 'lib/kindly/db.rb', line 79

def update_job_status(job, job_status)
  case job_status
  when :running
    delete_job_status(job, :pending)
  when :completed, :failed
    delete_job_status(job, :running)
  else
    raise "#{new_status} is invalid for job #{job.fields['JobId']}."
  end
  insert_job_status(job, job_status)
end

#userObject



23
24
25
# File 'lib/kindly/db.rb', line 23

def user
  @user ||= Aws::IAM::CurrentUser.new(region: 'us-west-2')
end