Module: OllamaChat::Database::SessionLocking

Included in:
Models::Session
Defined in:
lib/ollama_chat/database/session_locking.rb

Overview

The SessionLocking module provides a mechanism for exclusive session access, similar to the swap-file locking used by Vim.

It prevents multiple concurrent instances of the application from modifying the same session, thereby avoiding race conditions and context collision. The lock is based on the Process ID (PID) and is validated by checking if the owning process is still active on the system.

This module is intended to be mixed into models that persist session state, such as OllamaChat::Database::Models::Session.

Instance Method Summary collapse

Instance Method Details

#lockBoolean

Sets the lock for the current process.

Returns:

  • (Boolean)

    true if the update was successful.



41
42
43
# File 'lib/ollama_chat/database/session_locking.rb', line 41

def lock
  update(locked_by_pid: $$)
end

#lock?Boolean

Attempts to acquire a lock on the session.

Returns:

  • (Boolean)

    true if the lock was successfully acquired, false if already locked.



29
30
31
32
33
34
35
36
# File 'lib/ollama_chat/database/session_locking.rb', line 29

def lock?
  if running_pid = locked?
    STDERR.puts "session #{id} locked by running process #{running_pid}"
    false
  else
    lock
  end
end

#locked?Integer?

Checks if the session is currently locked by an active process.

Returns:

  • (Integer, nil)

    the PID of the locking process if active, or nil if unlocked/stale.



15
16
17
18
19
20
21
22
23
24
# File 'lib/ollama_chat/database/session_locking.rb', line 15

def locked?
  locked_pid = locked_by_pid
  locked_pid.nil? and return
  begin
    Process.kill(0, locked_pid)
    locked_pid
  rescue Errno::ESRCH
    nil
  end
end

#unlockBoolean

Releases the lock on the session.

Returns:

  • (Boolean)

    true if the update was successful.



48
49
50
# File 'lib/ollama_chat/database/session_locking.rb', line 48

def unlock
  update(locked_by_pid: nil)
end