🔍 Code Extractor

function load_all_sessions

Maturity: 46

Loads all chat session data from JSON files stored in a sessions directory into memory on application startup.

File:
/tf/active/vicechatdev/docchat/app.py
Lines:
149 - 160
Complexity:
moderate

Purpose

This function is designed to restore application state by reading persisted session data from disk during initialization. It iterates through all JSON files in the SESSIONS_DIR, deserializes each session, and populates the in-memory chat_sessions dictionary with thread-safe locking. This enables session persistence across application restarts and ensures users can resume their conversations.

Source Code

def load_all_sessions():
    """Load all sessions from disk on startup"""
    try:
        for session_file in SESSIONS_DIR.glob("*.json"):
            session_id = session_file.stem
            session_data = load_session_from_disk(session_id)
            if session_data:
                with session_lock:
                    chat_sessions[session_id] = session_data
        logger.info(f"Loaded {len(chat_sessions)} sessions from disk")
    except Exception as e:
        logger.error(f"Failed to load sessions: {e}")

Return Value

This function does not return any value (implicitly returns None). It performs side effects by populating the global chat_sessions dictionary and logging the operation results.

Dependencies

  • pathlib
  • logging
  • threading

Required Imports

from pathlib import Path
import logging
from threading import Lock

Usage Example

# Setup required globals and dependencies
import logging
from pathlib import Path
from threading import Lock

logger = logging.getLogger(__name__)
SESSIONS_DIR = Path('./sessions')
session_lock = Lock()
chat_sessions = {}

# Define the helper function
def load_session_from_disk(session_id):
    session_file = SESSIONS_DIR / f"{session_id}.json"
    if session_file.exists():
        with open(session_file, 'r') as f:
            return json.load(f)
    return None

# Ensure sessions directory exists
SESSIONS_DIR.mkdir(exist_ok=True)

# Call the function during application startup
load_all_sessions()

# Check loaded sessions
print(f"Loaded {len(chat_sessions)} sessions")

Best Practices

  • This function should be called only once during application startup to avoid duplicate session loading
  • Ensure SESSIONS_DIR exists and is writable before calling this function
  • The session_lock must be properly initialized as a threading.Lock before calling this function
  • The load_session_from_disk helper function must be defined and handle JSON deserialization errors gracefully
  • Consider implementing session validation after loading to ensure data integrity
  • The function catches all exceptions to prevent startup failures, but logs errors for debugging
  • For large numbers of sessions, consider implementing lazy loading or pagination to reduce startup time
  • Ensure the logger is configured before calling this function to capture load status and errors

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function load_all_chat_sessions 91.7% similar

    Loads all chat session data from JSON files stored in a designated directory and returns them as a dictionary indexed by session ID.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function load_chat_session_from_file 79.4% similar

    Loads a chat session from a JSON file stored in the CHAT_SESSIONS_DIR directory using the provided session_id as the filename.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function save_session_to_disk_v1 72.4% similar

    Persists a chat session to disk by serializing session data to a JSON file, converting datetime objects to ISO format strings for storage.

    From: /tf/active/vicechatdev/docchat/blueprint.py
  • function load_session_from_disk 71.3% similar

    Loads a session from disk storage by reading a JSON file identified by session_id, deserializing the data, and converting timestamp strings back to datetime objects.

    From: /tf/active/vicechatdev/docchat/app.py
  • function save_session_to_disk 71.1% similar

    Persists a chat session to disk by serializing session data to a JSON file, converting datetime objects to ISO format strings.

    From: /tf/active/vicechatdev/docchat/app.py
← Back to Browse