Class: Kaal::Backend::MemoryAdapter

Inherits:
Adapter
  • Object
show all
Includes:
DispatchLogging
Defined in:
lib/kaal/backend/memory_adapter.rb

Overview

In-memory backend adapter using Mutex and Hash.

This adapter stores locks in memory with TTL tracking. Locks are stored with an expiration time and automatically considered released if the TTL has passed.

IMPORTANT: This adapter is suitable only for single-node deployments (development, testing). For multi-node production systems, use Redis or PostgreSQL adapters instead.

Examples:

Using the memory adapter

Kaal.configure do |config|
  config.backend = Kaal::Backend::MemoryAdapter.new
  config.enable_log_dispatch_registry = true  # Enable dispatch logging
end

Instance Method Summary collapse

Methods included from DispatchLogging

#log_dispatch_attempt, #parse_lock_key, parse_lock_key

Methods inherited from Adapter

#with_lock

Constructor Details

#initializeMemoryAdapter

Returns a new instance of MemoryAdapter.



32
33
34
35
36
# File 'lib/kaal/backend/memory_adapter.rb', line 32

def initialize
  super
  @locks = {}
  @mutex = Mutex.new
end

Instance Method Details

#acquire(key, ttl) ⇒ Boolean

Attempt to acquire a lock in memory.

Opportunistically prunes expired locks to prevent unbounded memory growth. Since the coordinator generates unique keys per dispatch and relies on TTL expiration without calling release, this pruning is essential.

Parameters:

  • key (String)

    the lock key

  • ttl (Integer)

    time-to-live in seconds

Returns:

  • (Boolean)

    true if acquired (key was free or expired), false if held by another process



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/kaal/backend/memory_adapter.rb', line 64

def acquire(key, ttl)
  acquired = @mutex.synchronize do
    prune_expired_locks
    expiration_time = @locks[key]
    current_time = Time.current
    next false if expiration_time && expiration_time > current_time

    @locks[key] = current_time + ttl.seconds
    true
  end

  log_dispatch_attempt(key) if acquired

  acquired
end

#definition_registryKaal::Definition::MemoryEngine

Get the definition registry for in-memory definition persistence.

Returns:



50
51
52
# File 'lib/kaal/backend/memory_adapter.rb', line 50

def definition_registry
  @definition_registry ||= Kaal::Definition::MemoryEngine.new
end

#dispatch_registryKaal::Dispatch::MemoryEngine

Get the dispatch registry for in-memory logging.

Returns:



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

def dispatch_registry
  @dispatch_registry ||= Kaal::Dispatch::MemoryEngine.new
end

#release(key) ⇒ Boolean

Release a lock from memory.

Parameters:

  • key (String)

    the lock key to release

Returns:

  • (Boolean)

    true if released (key was held), false if not held



85
86
87
88
89
# File 'lib/kaal/backend/memory_adapter.rb', line 85

def release(key)
  @mutex.synchronize do
    @locks.delete(key).present?
  end
end