# Sessions

The sessions module include utilities to enhanced CherryPy session management.

## How it Works

### `FileSession` Class

`FileSession` extends CherryPy's `FileSession` with two key improvements:

1. **Improved Lock Acquisition**: Uses `zc.lockfile` for more reliable file locking with a shorter polling interval (1ms instead of CherryPy's default), reducing lock contention and improving performance in concurrent scenarios.

2. **Orphaned Lock Cleanup**: Automatically detects and removes orphaned lock files (lock files that exist without corresponding session files) during the cleanup process, preventing lock file accumulation over time.

### `session_lock` Context Manager

The `session_lock()` context manager provides a convenient way to acquire session locks when using explicit session locking. It features:

- **Re-entrant Support**: Can be called multiple times without deadlocking
- **Automatic Lock Management**: Acquires locks only when needed (explicit locking mode)
- **Automatic Save**: Saves session data and releases locks on context exit
- **Backward Compatible**: Works seamlessly with both implicit and explicit locking modes

## Usage

### Using `FileSession`

Configure CherryPy to use `FileSession`:

```python
import cherrypy
from cherrypy_foundation.sessions import FileSession

cherrypy.config.update({
    'tools.sessions.on': True,
    'tools.sessions.storage_class': FileSession,
    'tools.sessions.storage_path': '/path/to/sessions',
    'tools.sessions.locking': 'explicit',  # Optional: use explicit locking
})
```

### Using `session_lock` with explicit Locking

When using explicit locking mode, you may use `session_lock()` context manager to safely access session data:

This is particularly useful when implementing tools or plugins that required access to user's session.

```python
import cherrypy
from cherrypy_foundation.sessions import session_lock

class MyApp:
    @cherrypy.expose
    def index(self):
        with session_lock() as session:
            # Session is locked here
            session['user_id'] = 123
            session['last_visit'] = time.time()
        # Session is automatically saved and unlocked
        return "Session updated"
```
