Class: Kaal::Backend::Adapter

Inherits:
Object
  • Object
show all
Defined in:
lib/kaal/backend/adapter.rb

Overview

Abstract base class for distributed backend adapters.

Backend adapters are responsible for distributed coordination (acquire/release) and may also expose cron definition and dispatch registries for persistence.

Examples:

Implementing a backend adapter

class MyBackendAdapter < Kaal::Backend::Adapter
  def acquire(key, ttl)
    # Try to acquire a lock with key and TTL
    # Return true if acquired, false otherwise
  end

  def release(key)
    # Release the lock for key
  end
end

Instance Method Summary collapse

Instance Method Details

#acquire(_key, _ttl) ⇒ Boolean

Attempt to acquire a distributed lock.

Examples:

adapter = MyBackendAdapter.new
acquired = adapter.acquire("kaal:job1:1234567890", 60)
if acquired
  # Do work...
end

Parameters:

  • key (String)

    the lock key (e.g., “namespace:cron:key:timestamp”)

  • ttl (Integer)

    time-to-live in seconds before the lock auto-expires

Returns:

  • (Boolean)

    true if lock was acquired, false if already held by another process

Raises:

  • (NotImplementedError)

    if not implemented by subclass



42
43
44
# File 'lib/kaal/backend/adapter.rb', line 42

def acquire(_key, _ttl)
  raise NotImplementedError, 'Subclasses must implement #acquire'
end

#definition_registryKaal::Definition::Registry?

Optional definition registry for persistent cron definitions.

Backends may override this to provide a concrete implementation.

Returns:



94
95
96
# File 'lib/kaal/backend/adapter.rb', line 94

def definition_registry
  nil
end

#release(_key) ⇒ Boolean

Release a previously acquired lock.

Examples:

adapter.release("kaal:job1:1234567890")

Parameters:

  • key (String)

    the lock key to release

Returns:

  • (Boolean)

    true if released, false if not held

Raises:

  • (NotImplementedError)

    if not implemented by subclass



56
57
58
# File 'lib/kaal/backend/adapter.rb', line 56

def release(_key)
  raise NotImplementedError, 'Subclasses must implement #release'
end

#with_lock(key, ttl:) { ... } ⇒ Object

Acquire a lock, execute the block, then release the lock.

This is a convenience method that ensures the lock is properly released even if the block raises an exception. If the lock cannot be acquired, returns nil without executing the block.

Examples:

result = adapter.with_lock("kaal:job1:1234567890", ttl: 60) do
  # Do protected work
  42
end
# result is 42 if lock acquired, nil otherwise

Parameters:

  • key (String)

    the lock key

  • ttl (Integer)

    time-to-live in seconds

Yields:

  • executes the block if lock is acquired

Returns:

  • (Object)

    the result of the block if executed, nil if lock not acquired



78
79
80
81
82
83
84
85
86
# File 'lib/kaal/backend/adapter.rb', line 78

def with_lock(key, ttl:)
  return nil unless acquire(key, ttl)

  begin
    yield
  ensure
    release(key)
  end
end