Module: OllamaChat::Database::RowLocking

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

Overview

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

It prevents multiple concurrent instances of the application from modifying the same database row, thereby avoiding race conditions and state 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 any Sequel model that has a locked_by_pid column.

Instance Method Summary collapse

Instance Method Details

#lock ⇒ Boolean

Sets the lock for the current process.

Returns:

  • (Boolean) —

    true if the update was successful.



37
38
39
# File 'lib/ollama_chat/database/row_locking.rb', line 37

def lock
  update(locked_by_pid: $$)
end

#lock? ⇒ Boolean

Attempts to acquire a lock on the row.

Returns:

  • (Boolean) —

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



29
30
31
32
# File 'lib/ollama_chat/database/row_locking.rb', line 29

def lock?
  return false if locked?
  !!lock
end

#locked? ⇒ Integer?

Checks if the row 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/row_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

#unlock ⇒ Boolean

Releases the lock on the row.

Returns:

  • (Boolean) —

    true if the update was successful.



44
45
46
# File 'lib/ollama_chat/database/row_locking.rb', line 44

def unlock
  update(locked_by_pid: nil)
end