Class: Familia::Lock

Inherits:
String show all
Defined in:
lib/familia/data_type/types/lock.rb

Instance Method Summary collapse

Methods inherited from String

#in_seconds

Constructor Details

#initialize(*args) ⇒ Lock

Returns a new instance of Lock.



5
6
7
8
# File 'lib/familia/data_type/types/lock.rb', line 5

def initialize(*args)
  super
  @opts[:default] = nil
end

Instance Method Details

#acquire(token = SecureRandom.uuid, ttl: 10) ⇒ String, false

Acquire a lock with optional TTL

Parameters:

  • token (String) (defaults to: SecureRandom.uuid)

    Unique token to identify lock holder (auto-generated if nil)

  • ttl (Integer, nil) (defaults to: 10)

    Time-to-live in seconds. nil = no expiration, <=0 rejected

Returns:

  • (String, false)

    Returns token if acquired successfully, false otherwise



14
15
16
17
18
19
20
21
# File 'lib/familia/data_type/types/lock.rb', line 14

def acquire(token = SecureRandom.uuid, ttl: 10)
  success = setnx(token)
  # Handle both integer (1/0) and boolean (true/false) return values
  return false unless success == 1 || success == true
  return del && false if ttl&.<=(0)
  return del && false if ttl&.positive? && !expire(ttl)
  token
end

#force_unlock!Object



37
38
39
# File 'lib/familia/data_type/types/lock.rb', line 37

def force_unlock!
  del
end

#held_by?(token) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/familia/data_type/types/lock.rb', line 33

def held_by?(token)
  value == token
end

#locked?Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/familia/data_type/types/lock.rb', line 29

def locked?
  !value.nil?
end

#release(token) ⇒ Object



23
24
25
26
27
# File 'lib/familia/data_type/types/lock.rb', line 23

def release(token)
  # Lua script to atomically check token and delete
  script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"
  dbclient.eval(script, [dbkey], [token]) == 1
end