Metadata-Version: 2.4
Name: vcti-session
Version: 1.1.0
Summary: Session lifecycle, working directories, and logging configuration for Python applications
Author: Visual Collaboration Technologies Inc.
License-Expression: LicenseRef-Proprietary
Project-URL: Repository, https://github.com/vcollab/vcti-python-session
Project-URL: Changelog, https://github.com/vcollab/vcti-python-session/blob/main/CHANGELOG.md
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: <3.15,>=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pydantic>=2.7
Requires-Dist: python-dotenv
Requires-Dist: vcti-logging>=1.1.0
Requires-Dist: vcti-config>=5.0.1
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Provides-Extra: lint
Requires-Dist: ruff; extra == "lint"
Provides-Extra: typecheck
Requires-Dist: mypy; extra == "typecheck"
Dynamic: license-file

# Session Management

Session lifecycle, working directories, and logging configuration for Python applications

## Overview

A script that runs unattended needs somewhere to work, a log of what it
did, and a way to keep old runs from piling up. `vcti-session` gives each
run a working directory, configures logging into it, and cleans up
afterwards. `SessionDir` creates a uniquely named directory per run and
prunes old ones by count and age; `WorkDir` uses a directory you name and
leaves it alone. `SessionHandler` ties a `SessionDir` and a `LogConfig`
into one context manager with hooks at each point of the lifecycle. Every
setting resolves in the same order: constructor argument, then environment
variable, then default.

## Installation

```bash
pip install vcti-session
```

### In `requirements.txt`

```
vcti-session>=1.1.0
```

### In `pyproject.toml` dependencies

```toml
dependencies = [
    "vcti-session>=1.1.0",
]
```

---

## Quick Start

### A new directory for each run

```python
from vcti.session import LogConfig, SessionDir, SessionHandler

session_dir = SessionDir(
    base_directory="sessions",
    max_session_dirs=10,
    max_age_days=7,
)
log_config = LogConfig(file_path="logs/app.log", level="info")

handler = SessionHandler(session_dir, log_config)
with handler.session_context() as session:
    # The working directory is now a new, uniquely named session directory,
    # and logging goes to <session>/logs/app.log.
    print(f"Working in: {session.path}")
# The log file is closed, the working directory restored, and sessions
# beyond the limits pruned.
```

### A directory you choose

```python
from vcti.session import LogConfig, WorkDir

work_dir = WorkDir(
    directory="my-work",
    log_config=LogConfig(file_path="app.log"),
    create_if_missing=True,
)
with work_dir.work_context():
    print(f"Working in: {work_dir.path}")
```

`WorkDir` never renames, prunes or deletes anything.

### Configuration from the environment

```python
from vcti.session import LogConfig, SessionDir

# Reads MYAPP_SESSION_DIR_PREFIX, MYAPP_SESSION_DIR_MAX_SESSION_DIRS, ...
session_dir = SessionDir(
    base_directory="sessions",
    env_prefix="MYAPP_",
    env_file=".env",  # loaded into the process environment first
)

# Reads MYAPP_SESSION_LOG_FILE_PATH, MYAPP_SESSION_LOG_LEVEL, ...
log_config = LogConfig(
    env_prefix="MYAPP_",
    default_file_path="logs/app.log",
    default_level="info",
)
```

A value passed to the constructor wins over the environment, which wins
over the `default_*` argument.

### Lifecycle hooks

```python
from pathlib import Path

from vcti.session import SessionDir, SessionHandler


def on_created(path: Path) -> None:
    print(f"Session started: {path.name}")


def on_exit(path: Path, error: Exception | None) -> None:
    print(f"Session ended: {path.name}, error={error!r}")


def before_prune(dirs: list[Path]) -> None:
    print(f"About to delete {len(dirs)} old session(s)")


handler = SessionHandler(
    SessionDir(base_directory="sessions", max_session_dirs=1),
    on_session_created=on_created,
    on_session_exit=on_exit,
    on_before_prune=before_prune,
    on_session_error=lambda error: print(f"Session failed: {error}"),
)
with handler.session_context():
    pass
```

---

## Key Classes

| Class | Purpose |
|-------|---------|
| `SessionDir` | Creates uniquely named session directories and prunes old ones by count and age |
| `WorkDir` | Context manager for a user-specified directory, with no naming or cleanup |
| `SessionHandler` | Context manager combining a `SessionDir` and a `LogConfig` into a session lifecycle with hooks |
| `LogConfig` | Logging settings: file path, level, console and color output, message format |

---

## Reference

### Hooks

| Hook | Signature | When |
|------|-----------|------|
| `on_session_created` | `(path: Path) -> None` | After the directory is created and logging is set up |
| `on_session_error` | `(error: Exception) -> None` | When an exception leaves the context |
| `on_session_exit` | `(path: Path, error: Exception \| None) -> None` | When the context exits, before logging is closed |
| `on_before_prune` | `(dirs: list[Path]) -> None` | Before old sessions are deleted, when there are any |

All hooks are optional. A hook that raises is logged as a warning and does
not interrupt the session.

### `SessionDir` settings

| Argument | Environment variable | Default | Description |
|----------|----------------------|---------|-------------|
| `prefix` | `SESSION_DIR_PREFIX` | `session_` | Prefix of session directory names; must not be empty |
| `timestamp_format` | `SESSION_DIR_TIMESTAMP_FORMAT` | `%Y-%m-%d-%H-%M-%S` | `strftime` format of the timestamp in the name |
| `max_session_dirs` | `SESSION_DIR_MAX_SESSION_DIRS` | `20` | Session directories to keep (`-1` = unlimited) |
| `max_age_days` | `SESSION_DIR_MAX_AGE_DAYS` | `10` | Age in days after which a session is deleted (`-1` = unlimited) |

### `LogConfig` settings

| Argument | Environment variable | Default | Description |
|----------|----------------------|---------|-------------|
| `file_path` | `SESSION_LOG_FILE_PATH` | `None` | Log file; a relative path is inside the session or work directory. `None` disables file logging |
| `level` | `SESSION_LOG_LEVEL` | `info` | `notset`, `trace`, `debug`, `verbose`, `info`, `warning`, `error` or `fatal` |
| `console_enabled` | `SESSION_LOG_CONSOLE_ENABLED` | `false` | Also log to the console |
| `color_enabled` | `SESSION_LOG_COLOR_ENABLED` | `false` | ANSI colors in console output |
| `message_format` | `SESSION_LOG_MESSAGE_FORMAT` | *(none)* | A preset name or a format string |

With `env_prefix="MYAPP_"` the variables become `MYAPP_SESSION_DIR_PREFIX`,
`MYAPP_SESSION_LOG_LEVEL`, and so on.

### Working directory

`SessionHandler` and `WorkDir` change the process working directory inside
the context and restore it on exit. Pass `change_directory=False` to leave
it alone and use `.path` instead; a multi-threaded or async application
should.

---

## Dependencies

- [pydantic](https://pypi.org/project/pydantic/) — validation of `SessionDir` and `LogConfig`
- [python-dotenv](https://pypi.org/project/python-dotenv/) — loading `env_file`
- [vcti-logging](https://pypi.org/project/vcti-logging/) — the logger and its handlers
- [vcti-config](https://pypi.org/project/vcti-config/) — decoding environment values and priority resolution

---

## Documentation

| If you want to… | Read |
|---|---|
| Get started using the package | Quick Start above |
| Choose a logging setup, run in threads, archive sessions before they are pruned | [docs/patterns.md](docs/patterns.md) |
| Understand the two directory strategies and the session lifecycle | [docs/design.md](docs/design.md) |
| Navigate and understand the source | [docs/source-guide.md](docs/source-guide.md) |
