Module: Locksmith::Dynamodb

Extended by:
Dynamodb
Included in:
Dynamodb
Defined in:
lib/locksmith/dynamodb.rb

Instance Method Summary collapse

Instance Method Details

#create(name, attempts) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/locksmith/dynamodb.rb', line 26

def create(name, attempts)
  attempts.times do |i|
    begin
      locks.put({"Name" => name, "Created" => Time.now.to_i},
        :unless_exists => "Name")
      return(true)
    rescue AWS::DynamoDB::Errors::ConditionalCheckFailedException
      return(false) if i == (attempts - 1)
    end
  end
end

#delete(name) ⇒ Object



38
39
40
# File 'lib/locksmith/dynamodb.rb', line 38

def delete(name)
  locks.at(name).delete
end

#dynamoObject



67
68
69
70
71
72
# File 'lib/locksmith/dynamodb.rb', line 67

def dynamo
  @dynamo_lock.synchronize do
    @db ||= AWS::DynamoDB.new(:access_key_id => Config.aws_id,
                              :secret_access_key => Config.aws_secret)
  end
end

#expired?(name, ttl) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
45
46
47
48
# File 'lib/locksmith/dynamodb.rb', line 42

def expired?(name, ttl)
  if l = locks.at(name).attributes.to_h(:consistent_read => true)
    if t = l["Created"]
      t < (Time.now.to_i - ttl)
    end
  end
end

#lock(name, opts = {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/locksmith/dynamodb.rb', line 12

def lock(name, opts={})
  opts[:ttl] ||= 60
  opts[:attempts] ||= 3
  # Clean up expired locks. Does not grantee that we will
  # be able to acquire the lock, just a nice thing to do for
  # the other processes attempting to lock.
  delete(name) if expired?(name, opts[:ttl])
  if create(name, opts[:attempts])
    begin Timeout::timeout(opts[:ttl]) {return(yield)}
    ensure delete(name)
    end
  end
end

#lock_tableObject



74
75
76
# File 'lib/locksmith/dynamodb.rb', line 74

def lock_table
  @lock_table
end

#lock_table=(table_name) ⇒ Object



78
79
80
# File 'lib/locksmith/dynamodb.rb', line 78

def lock_table=(table_name)
  @lock_table = table_name
end

#locksObject



50
51
52
# File 'lib/locksmith/dynamodb.rb', line 50

def locks
  table(lock_table)
end

#table(name) ⇒ Object



54
55
56
57
58
59
60
61
# File 'lib/locksmith/dynamodb.rb', line 54

def table(name)
  unless tables[name]
    @table_lock.synchronize do
      tables[name] = dynamo.tables[name].load_schema
    end
  end
  tables[name].items
end

#tablesObject



63
64
65
# File 'lib/locksmith/dynamodb.rb', line 63

def tables
  @tables ||= {}
end