Class: Dbwatcher::Storage::SessionStorage

Inherits:
BaseStorage
  • Object
show all
Includes:
Concerns::DataNormalizer, Concerns::Validatable
Defined in:
lib/dbwatcher/storage/session_storage.rb

Overview

Handles persistence and retrieval of database monitoring sessions

This class manages the storage of session data including metadata, timestamps, and associated database changes. Sessions are stored as individual JSON files with an index for efficient querying. Follows Ruby style guide patterns for storage class organization.

Examples:

Basic usage

storage = SessionStorage.new
session = Session.new(id: "123", name: "Test Session")
storage.save(session)
loaded_session = storage.find("123")

See Also:

Constant Summary collapse

DEFAULT_INDEX_FILENAME =

Configuration constants

"index.json"
SESSIONS_DIRECTORY =
"sessions"

Constants inherited from BaseStorage

BaseStorage::DEFAULT_PERMISSIONS, BaseStorage::JSON_FILE_EXTENSION

Instance Attribute Summary collapse

Attributes inherited from BaseStorage

#file_manager, #storage_path

Instance Method Summary collapse

Methods included from Concerns::DataNormalizer

#extract_value, #normalize_change, #normalize_hash_keys, #normalize_operation, #normalize_record_id, #normalize_session_data, #normalize_table_name, #normalize_timestamp

Methods included from Concerns::Validatable

included, #valid_id?, #valid_name?, #validate_id!, #validate_name!, #validate_presence!

Methods included from Concerns::Timestampable

#age, included, #initialize_timestamps, #recently_created?, #recently_updated?, #touch_updated_at

Methods included from Concerns::ErrorHandler

#safe_operation, #with_error_handling

Constructor Details

#initialize(storage_path = nil) ⇒ SessionStorage

Initializes a new SessionStorage instance

Sets up the necessary directories and index files for session storage. Creates the sessions directory and index file if they don’t exist. Includes thread safety for concurrent operations.

Parameters:

  • storage_path (String, nil) (defaults to: nil)

    custom storage path (optional)



56
57
58
59
60
61
62
63
64
# File 'lib/dbwatcher/storage/session_storage.rb', line 56

def initialize(storage_path = nil)
  super
  @sessions_path = File.join(self.storage_path, SESSIONS_DIRECTORY)
  @index_file = File.join(self.storage_path, DEFAULT_INDEX_FILENAME)
  @operations = SessionOperations.new(@sessions_path, @index_file)
  @mutex = Mutex.new

  setup_directories
end

Instance Attribute Details

#index_fileString (readonly)

Returns path to index file.

Returns:

  • (String)

    path to index file



41
42
43
# File 'lib/dbwatcher/storage/session_storage.rb', line 41

def index_file
  @index_file
end

#mutexMutex (readonly)

Returns thread safety mutex.

Returns:

  • (Mutex)

    thread safety mutex



47
48
49
# File 'lib/dbwatcher/storage/session_storage.rb', line 47

def mutex
  @mutex
end

#operationsSessionOperations (readonly)

Returns operations helper.

Returns:



44
45
46
# File 'lib/dbwatcher/storage/session_storage.rb', line 44

def operations
  @operations
end

#sessions_pathString (readonly)

Returns path to sessions directory.

Returns:

  • (String)

    path to sessions directory



38
39
40
# File 'lib/dbwatcher/storage/session_storage.rb', line 38

def sessions_path
  @sessions_path
end

Instance Method Details

#allArray<Hash>

Returns all session summaries from the index

Returns:

  • (Array<Hash>)

    array of session summary hashes



147
148
149
# File 'lib/dbwatcher/storage/session_storage.rb', line 147

def all
  safe_read_json(index_file)
end

#cleanup_old_sessionsvoid

This method returns an undefined value.

Removes old session files based on configuration

Automatically called after each save operation to maintain storage size within configured limits.



195
196
197
198
199
200
# File 'lib/dbwatcher/storage/session_storage.rb', line 195

def cleanup_old_sessions
  return unless cleanup_enabled?

  cutoff_date = calculate_cleanup_cutoff
  remove_old_session_files(cutoff_date)
end

#clear_allInteger

Clears all session storage

Removes all session files and reinitializes the storage structure. This operation cannot be undone.

Returns:

  • (Integer)

    number of files removed



175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/dbwatcher/storage/session_storage.rb', line 175

def clear_all
  with_error_handling("clear all sessions") do
    # Count files before deleting
    file_count = count_session_files

    safe_delete_directory(sessions_path)
    safe_write_json(index_file, [])
    setup_directories
    touch_updated_at

    file_count
  end
end

#countInteger

Counts total number of sessions

Returns:

  • (Integer)

    number of sessions



165
166
167
# File 'lib/dbwatcher/storage/session_storage.rb', line 165

def count
  all.size
end

#exists?(id) ⇒ Boolean

Checks if a session exists

Parameters:

  • id (String, Integer)

    the session ID to check

Returns:

  • (Boolean)

    true if session exists



155
156
157
158
159
160
# File 'lib/dbwatcher/storage/session_storage.rb', line 155

def exists?(id)
  return false unless valid_id?(id)

  session_file = operations.session_file_path(id)
  file_manager.file_exists?(session_file)
end

#find(id) ⇒ Session?

Finds a session by ID

Retrieves session data from storage and constructs a Session object. Returns nil if the session is not found.

Examples:

session = storage.find("123")
puts session.name if session

Parameters:

  • id (String, Integer)

    the session ID to find

Returns:

  • (Session, nil)

    the loaded session or nil if not found



117
118
119
120
121
122
123
124
# File 'lib/dbwatcher/storage/session_storage.rb', line 117

def find(id)
  return nil unless valid_id?(id)

  session_data = load_session_data(id)
  return nil if session_data.empty?

  build_session_from_data(session_data)
end

#find!(id) ⇒ Session

Finds a session by ID or raises an exception

Parameters:

  • id (String, Integer)

    the session ID to find

Returns:

Raises:



131
132
133
# File 'lib/dbwatcher/storage/session_storage.rb', line 131

def find!(id)
  find(id) or raise SessionNotFoundError, "Session with id '#{id}' not found"
end

#load(id) ⇒ Session, NullSession

Deprecated.

Use #find instead

Loads a session by ID (legacy method, use find instead)

Parameters:

  • id (String, Integer)

    the session ID to load

Returns:



140
141
142
# File 'lib/dbwatcher/storage/session_storage.rb', line 140

def load(id)
  find(id) || NullSession.instance
end

#save(session) ⇒ Boolean

Persists a session to storage

Saves the session data to a JSON file and updates the session index. Automatically triggers cleanup of old sessions after successful save. Uses thread safety to prevent concurrent write conflicts.

rubocop:disable Naming/PredicateMethod

Examples:

session = Session.new(id: "123", name: "Test")
storage.save(session) # => true

Parameters:

  • session (Session, Hash)

    the session object or hash to save

Returns:

  • (Boolean)

    true if saved successfully, false otherwise

Raises:



80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/dbwatcher/storage/session_storage.rb', line 80

def save(session)
  session_data = normalize_session_data(session)
  validate_session_data!(session_data)

  mutex.synchronize do
    persist_session_file(session_data)
    update_session_index(session_data)
    trigger_cleanup
  end

  true
end

#save!(session) ⇒ Boolean

Alternative save method that raises on failure

Parameters:

  • session (Session, Hash)

    the session object or hash to save

Returns:

  • (Boolean)

    true if saved successfully

Raises:



100
101
102
103
104
# File 'lib/dbwatcher/storage/session_storage.rb', line 100

def save!(session)
  with_error_handling("save session") do
    save(session) or raise StorageError, "Failed to save session"
  end
end