diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 00000000..205c127c --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,71 @@ +name: Docs + +on: + pull_request: + push: + branches: [ main ] + +permissions: + contents: read + +jobs: + check: + runs-on: ubuntu-24.04 + steps: + - name: Check out the repository + uses: actions/checkout@v6 + + - name: Install uv + uses: astral-sh/setup-uv@v7 + + - name: Install Node + uses: actions/setup-node@v6 + with: + node-version: 22 + + # Ubuntu 24.04 blocks the Chrome sandbox for unprivileged users. + - name: Write the puppeteer config + run: echo '{"args":["--no-sandbox"]}' > "$RUNNER_TEMP/puppeteer.json" + + - name: Run the docs check + env: + PUPPETEER_CONFIG: ${{ runner.temp }}/puppeteer.json + run: bash scripts/docs/check.sh + + deploy: + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + needs: check + runs-on: ubuntu-24.04 + permissions: + contents: read + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + concurrency: + group: pages + cancel-in-progress: false + steps: + - name: Check out the repository + uses: actions/checkout@v6 + + - name: Install uv + uses: astral-sh/setup-uv@v7 + + - name: Configure Pages + uses: actions/configure-pages@v6 + + - name: Build the site + env: + NO_MKDOCS_2_WARNING: "1" + run: uvx --with mkdocs-material mkdocs build --strict -d site + + - name: Upload the site + uses: actions/upload-pages-artifact@v5 + with: + path: site + + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v5 diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 00000000..d749cf4e --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,54 @@ +# vCon Server + +Open source pipeline for vCon conversation records: a FastAPI service, a worker that runs chains of links, and plain Redis between them. Human docs start at `docs/index.md`. Developer setup is in `docs/contributing.md`. + +## Layout + +- `api/api.py`: the REST API +- `conserver/main.py`: the worker. `conserver/links/` holds links, `conserver/tracers/` holds tracers +- `common/`: shared code. `vcon.py`, `lib/`, `storage/`, `settings.py`, `config.py` +- `tests/`, `common/tests/`, `conserver/tests/`, and tests inside each link folder +- `docker/`: `Dockerfile` for dev and CI, `Dockerfile.api` and `Dockerfile.conserver` for production +- `scripts/docs/`: doc generators and `check.sh` + +## Commands + +The toolchain is uv with `uv.lock`, never Poetry. + +```bash +uv sync --group conserver --group api --group storage-milvus # plain uv sync cannot import the services +uv lock # after a dependency change +uv run pytest conserver/links/tag # host, tests that mock Redis +docker compose run --rm conserver pytest # everything, as CI does +uv run black path/to/changed_file.py # line length 120, changed files only +``` + +Many tests need Redis, and `-m "not integration"` does not exclude them. `docker compose` needs `.env`, `config.yml` and the `conserver` network: see `docs/getting-started/quick-start.md`. + +## Docs check + +```bash +bash scripts/docs/check.sh +``` + +It runs the generators, renders the diagrams and runs `mkdocs build --strict`. Never hand edit `docs/reference/environment.md`, `ports.md`, `api-routes.md` or `metrics.md`. + +## Import path trap + +The path holds the repo root, `common`, `conserver` and `api` (`pytest.ini`, `docker/Dockerfile`). So: + +- `import vcon` resolves to `common/vcon.py`, not the `vcon` package in `pyproject.toml`. Check that file before you call a method. +- Import shared code as `lib.*`: `from lib.vcon_redis import VconRedis`. Use `lib.queue.VconQueue` for queue work. +- Links live in `conserver/links`, not `server/links`, and load as `links.`. +- Vendor transcribe modules are deprecated. Use `links.transcribe`. +- Redis is plain Redis. RedisJSON and Redis Stack appear only in the migration path. + +## Consent boundary + +Active consent management is outside this repo. The server carries and preserves `lawful_basis` attachments. It never creates, validates, enforces or manages consent, and it does not make a deployment compliant. A missing consent feature here is by design and not a bug. Do not add one, and do not document one. See `docs/concepts/lawful-basis.md`. + +## Rules + +- Example vCons use `"vcon": "0.4.0"`. +- Keep personal and company names out of issues, commits and pull requests. +- There is no product version. `pyproject.toml` holds a placeholder. diff --git a/README.md b/README.md index 176b9017..7e7e0f0f 100644 --- a/README.md +++ b/README.md @@ -1,44 +1,42 @@ # vCon Server (Conserver) -vCon Server is a pipeline-based conversation processing and storage system. It ingests [vCon](https://datatracker.ietf.org/doc/draft-ietf-vcon-vcon-container/) (Voice Conversation) records, routes them through configurable processing chains — transcription, AI analysis, tagging, webhooks — and writes results to one or more storage backends. +vCon Server is a pipeline for [vCon](https://datatracker.ietf.org/doc/draft-ietf-vcon-vcon-core/) conversation records. It takes them in, runs them through configurable chains of links (transcription, AI analysis, tagging, routing, webhooks) and writes the results to one or more storage backends. -**Full documentation:** https://vcon-dev.github.io/vcon-server/ +**Documentation:** start at [docs/index.md](docs/index.md). The `Docs` workflow publishes the same pages to https://vcon-dev.github.io/vcon-server/. -## Quick Start +## Start the server -```bash -git clone https://github.com/vcon-dev/vcon-server.git -cd vcon-server -cp example_docker-compose.yml docker-compose.yml -cp .env.example .env # edit CONSERVER_API_TOKEN at minimum -docker network create conserver -docker compose up -d --build -curl http://localhost:8000/api/health -``` +You need Docker with the Compose plugin. The [quick start](docs/getting-started/quick-start.md) takes you from a fresh clone to a processed vCon. It sets three values in `.env`, writes a small `config.yml`, and starts the stack. -## Documentation by Audience +## Find the docs for your role | Audience | Start here | |----------|-----------| -| **New users** | [Getting Started](https://vcon-dev.github.io/vcon-server/getting-started/) | -| **Operators / DevOps** | [Installation](https://vcon-dev.github.io/vcon-server/installation/) · [Configuration](https://vcon-dev.github.io/vcon-server/configuration/) · [Operations](https://vcon-dev.github.io/vcon-server/operations/) | -| **Developers** | [Contributing](https://vcon-dev.github.io/vcon-server/contributing/) · [Extending](https://vcon-dev.github.io/vcon-server/extending/) · [Reference](https://vcon-dev.github.io/vcon-server/reference/) | +| **New users** | [Getting Started](docs/getting-started/index.md) | +| **Operators** | [Installation](docs/installation/index.md), [Configuration](docs/configuration/index.md), [Operations](docs/operations/index.md) | +| **Developers** | [Contributing](docs/contributing.md), [Extending](docs/extending/index.md), [Reference](docs/reference/index.md) | + +## Check the main features -## Key Features +- **Chain-based processing:** compose reusable links into pipelines driven by Redis queues +- **Processing links:** [transcription, AI analysis, tagging, routing, webhooks, SCITT and DataTrails records](docs/reference/links/index.md) +- **Storage backends:** [PostgreSQL, MongoDB, S3, Elasticsearch, Milvus, Redis, SFTP and more](docs/reference/storage-adapters/index.md) +- **Multi-worker scaling:** parallel workers, per-worker concurrency and parallel storage writes +- **External ingress:** scoped API keys let third-party systems submit vCons to specific queues +- **OpenTelemetry:** built-in tracing and metrics export -- **Chain-based processing** — compose reusable links into pipelines driven by Redis queues -- **20+ processing links** — transcription (Deepgram, Whisper), AI analysis (OpenAI, Groq), tagging, routing, webhooks, compliance (SCITT, DataTrails) -- **10+ storage backends** — PostgreSQL, MongoDB, S3, Elasticsearch, Milvus, Redis, SFTP, and more -- **Multi-worker scaling** — parallel workers with configurable process count and parallel storage writes -- **External ingress** — scoped API keys let third-party systems submit vCons to specific queues -- **OpenTelemetry** — built-in tracing and metrics export +The server carries `lawful_basis` attachments through the pipeline. It does not create, validate or enforce consent. See [lawful basis](docs/concepts/lawful-basis.md). -## Running Tests +## Run the tests + +With the stack running: ```bash -docker compose run --rm conserver pytest conserver/links/analyze/tests/ -v +docker compose run --rm conserver pytest ``` -## License +[Contributing](docs/contributing.md) covers local setup with uv. + +## Read the license -See [LICENSE](LICENSE). +MIT. See [LICENSE](LICENSE). diff --git a/common/README_CORE.md b/common/README_CORE.md index 72aa0aa3..db6d494f 100644 --- a/common/README_CORE.md +++ b/common/README_CORE.md @@ -2,11 +2,11 @@ ## Overview -The vCon Server is a robust processing pipeline designed to handle vCon objects through configurable processing chains. It implements a Redis-based queue system for managing the flow of vCons through various processing stages. +The vCon Server is a processing pipeline that runs vCon objects through configurable chains. Redis lists carry the vCons between stages. The operator manual in `docs/` covers each topic in more depth. ## Core Components -### 1. Main Processing Pipeline (`main.py`) +### 1. Main Processing Pipeline (`conserver/main.py`) The main processing pipeline is the heart of the vCon server, responsible for: - Managing processing chains @@ -38,7 +38,7 @@ The system uses a `ChainConfig` TypedDict to define processing chains with: - Processing timeout - Enable/disable status -### 2. Configuration Management (`config.py`) +### 2. Configuration Management (`common/config.py`) The configuration system provides: - YAML-based configuration loading @@ -48,7 +48,7 @@ The configuration system provides: - Import configuration management - Ingress authentication configuration for external API access -### 3. API Layer (`api.py`) +### 3. API Layer (`api/api.py`) The API layer provides HTTP endpoints for vCon submission and management: - RESTful API endpoints using FastAPI @@ -62,17 +62,27 @@ The API layer provides HTTP endpoints for vCon submission and management: - **Multi-tier Authentication**: Different API keys for internal vs external access - **Scoped Authorization**: External API keys limited to specific ingress lists - **Input Validation**: Automatic vCon schema validation -- **Error Handling**: Comprehensive HTTP error responses +- **Error Handling**: HTTP error responses - **Logging**: Detailed request and processing logging -### 4. Redis Queue Management (`redis_mgr.py`) +### 4. Redis Connection Factory (`common/redis_mgr.py`) -The Redis management system provides: -- Connection pool management -- Synchronous and asynchronous client support -- JSON-based key-value operations -- Pattern-based key searching -- Connection lifecycle management +`redis_mgr.py` creates Redis clients and reads and writes JSON documents. It does no queue work. + +- `redis`: the shared synchronous client, created from `REDIS_URL` at import. `get_client()` returns it +- `get_async_client()`: returns a new asynchronous client. The API calls it at startup, so the client binds to the running event loop +- `json_set`, `json_get`, `json_set_async`, `json_get_async`, `json_mget_async`: store whole documents as JSON strings in plain Redis keys +- `set_key`, `get_key`, `delete_key`, `show_keys`: key helpers on the shared client + +### 5. Queue Management (`common/lib/queue.py`) + +`VconQueue` is the entry point for moving vCon ids between lists. Redis stays the implementation, and this is not a pluggable backend. + +- `enqueue` appends with RPUSH and `dequeue` pops with BLPOP, which gives FIFO order +- `enqueue_front` prepends with LPUSH, for a worker that must hand back a vCon it popped +- `enqueue_dlq` and `enqueue_storage_dlq` write to the dead letter queues +- `queue_length` and `set_vcon_ttl` read a list length and set a vCon's expiry +- Methods suffixed `_async` take the async client as their first argument ## Processing Flow @@ -123,7 +133,7 @@ The system implements multi-tier authentication and authorization: ## Error Handling -The system implements comprehensive error handling: +The system handles errors at these points: - Link-level error tracking - Storage operation error handling - API authentication and authorization errors diff --git a/conserver/links/README.md b/conserver/links/README.md index 7b162a31..f03cd917 100644 --- a/conserver/links/README.md +++ b/conserver/links/README.md @@ -23,13 +23,13 @@ A specialized link that helps reduce the size and content of vCon objects by sel A simple but effective link that sets an expiration time for vCon objects in Redis, enabling automatic cleanup after a specified period. Useful for data retention policy enforcement and storage optimization. ### @groq_whisper -A specialized link that performs speech-to-text transcription on audio recordings in vCon dialogs using Groq's implementation of the Whisper ASR service, with support for various audio formats and robust error handling. +A specialized link that performs speech-to-text transcription on audio recordings in vCon dialogs using Groq's implementation of the Whisper ASR service, with support for various audio formats and error handling. ### @hugging_face_whisper -A specialized link that performs speech-to-text transcription on audio recordings in vCon dialogs using Hugging Face's implementation of the Whisper ASR service, with support for various audio formats and robust error handling. +A specialized link that performs speech-to-text transcription on audio recordings in vCon dialogs using Hugging Face's implementation of the Whisper ASR service, with support for various audio formats and error handling. ### @hugging_llm_link -A specialized link that performs AI-powered analysis on vCon transcripts using Hugging Face's language models, supporting both API-based and local model inference with configurable parameters and robust error handling. +A specialized link that performs AI-powered analysis on vCon transcripts using Hugging Face's language models, supporting both API-based and local model inference with configurable parameters and error handling. ### @jq_link A specialized link that filters vCon objects using jq expressions, allowing for complex content-based filtering with configurable forwarding rules for matching or non-matching vCons. diff --git a/conserver/links/analyze/README.md b/conserver/links/analyze/README.md index 6b7d17b7..d4fd1d82 100644 --- a/conserver/links/analyze/README.md +++ b/conserver/links/analyze/README.md @@ -1,5 +1,7 @@ # Analyze Link +Reference: [`links.analyze`](../../../docs/reference/links/analyze.md) + The Analyze link is a powerful plugin that performs AI-powered analysis on vCon transcripts using OpenAI's GPT models. It can generate various types of analysis, such as summaries, sentiment analysis, or any custom analysis based on the provided prompt. ## Features diff --git a/conserver/links/analyze_and_label/README.md b/conserver/links/analyze_and_label/README.md index 97fc98e6..05885eaf 100644 --- a/conserver/links/analyze_and_label/README.md +++ b/conserver/links/analyze_and_label/README.md @@ -1,5 +1,7 @@ # Analyze and Label Link +Reference: [`links.analyze_and_label`](../../../docs/reference/links/analyze-and-label.md) + ## Overview The `analyze_and_label` link is a powerful component of the vCon server that automatically analyzes dialog content and generates relevant labels/tags for categorization. It uses OpenAI's language models to process various dialog formats (transcripts, messages, chats, emails) and extract meaningful labels that are then applied as tags to the vCon. @@ -44,7 +46,7 @@ The link accepts the following configuration options: ## Usage Example ```python -from server.links.analyze_and_label import run +from links.analyze_and_label import run # Run with default options (requires OPENAI_API_KEY in the options) run( @@ -71,7 +73,7 @@ Example specialized prompts: ## Error Handling -The link includes robust error handling: +The link handles errors as follows: - Exponential backoff retry mechanism for API calls - JSON parsing error handling @@ -79,7 +81,7 @@ The link includes robust error handling: ## Testing -The link includes comprehensive tests for all functionality. To run the tests with actual OpenAI API calls (optional): +The link has tests for all functionality. To run the tests with actual OpenAI API calls (optional): ```bash # Set environment variables @@ -87,7 +89,7 @@ export OPENAI_API_KEY="your-api-key" export RUN_OPENAI_ANALYZE_LABEL_TESTS=1 # Run the tests -pytest server/links/analyze_and_label/tests/test_analyze_and_label.py +pytest conserver/links/analyze_and_label/tests/test_analyze_and_label.py ``` Without setting `RUN_OPENAI_ANALYZE_LABEL_TESTS=1`, tests will run with mocked API responses. diff --git a/conserver/links/analyze_vcon/README.md b/conserver/links/analyze_vcon/README.md index 1133819e..f07654c6 100644 --- a/conserver/links/analyze_vcon/README.md +++ b/conserver/links/analyze_vcon/README.md @@ -1,5 +1,7 @@ # Analyze vCon Link +Reference: [`links.analyze_vcon`](../../../docs/reference/links/analyze-vcon.md) + The Analyze vCon link is a specialized plugin that performs AI-powered analysis on entire vCon objects using OpenAI's GPT models. Unlike the standard analyze link that processes individual dialogs, this link analyzes the complete vCon structure and returns structured JSON output. ## Features diff --git a/conserver/links/check_and_tag/README.md b/conserver/links/check_and_tag/README.md index edb068bc..7a4ea40d 100644 --- a/conserver/links/check_and_tag/README.md +++ b/conserver/links/check_and_tag/README.md @@ -1,5 +1,7 @@ # Check and Tag Link +Reference: [`links.check_and_tag`](../../../docs/reference/links/check-and-tag.md) + ## Overview The `check_and_tag` link is a specialized component of the vCon server that evaluates dialog content against a specific question to determine if a particular tag should be applied. It uses OpenAI's language models to process various dialog formats (transcripts, messages, chats, emails) and makes a binary decision about whether a specific tag applies based on an evaluation question. @@ -45,7 +47,7 @@ The link accepts the following configuration options: ## Usage Example ```python -from server.links.check_and_tag import run +from links.check_and_tag import run # Run with required tag_name and evaluation_question run( @@ -73,7 +75,7 @@ Example evaluation questions: ## Error Handling -The link includes robust error handling: +The link handles errors as follows: - Exponential backoff retry mechanism for API calls - JSON parsing error handling for evaluation responses @@ -82,7 +84,7 @@ The link includes robust error handling: ## Testing -The link includes comprehensive tests for all functionality. To run the tests with actual OpenAI API calls (optional): +The link has tests for all functionality. To run the tests with actual OpenAI API calls (optional): ```bash # Set environment variables @@ -90,7 +92,7 @@ export OPENAI_API_KEY="your-api-key" export RUN_OPENAI_CHECK_TAG_TESTS=1 # Run the tests -pytest server/links/check_and_tag/tests/test_check_and_tag.py +pytest conserver/links/check_and_tag/tests/test_check_and_tag.py ``` Without setting `RUN_OPENAI_CHECK_TAG_TESTS=1`, tests will run with mocked API responses. diff --git a/conserver/links/datatrails/readme.md b/conserver/links/datatrails/readme.md index 469841a7..544f213f 100644 --- a/conserver/links/datatrails/readme.md +++ b/conserver/links/datatrails/readme.md @@ -1,5 +1,7 @@ # DataTrails Link +Reference: [`links.datatrails`](../../../docs/reference/links/datatrails.md) + The DataTrails link is a specialized plugin that integrates vCon data with the DataTrails platform, creating a verifiable audit trail for vCon operations. It supports both asset-based and asset-free event recording, with plans to transition fully to asset-free events in the future. ## Features @@ -110,7 +112,7 @@ With the SCITT capabilities of DataTrails, the integrity and inclusion of all vC If you're in possession of a vCon that's not recorded on a SCITT ledger, how do you know it's a valid vCon, or the latest version of that vCon? The DataTrails Link is a conserver link designed to integrate vCon (virtual conversation) data with the [DataTrails Events API][datatrails-events]. -The DataTrails Link allows for the creation of DataTrails Events based on vCon information, enabling seamless tracking and management of conversation-related assets. +The DataTrails Link allows for the creation of DataTrails Events based on vCon information, for tracking and managing conversation-related assets. Setting the `vcon_operation` chain configuration, log different types of Events, based on which chain is executed. ## Prerequisites @@ -168,11 +170,11 @@ links: token_endpoint: "https://app.datatrails.ai/archivist/iam/v1/appidp/token" client_id: "" client_secret: "" - datatrails_consent_revoked: + datatrails_updated: module: links.datatrails options: api_url: "https://app.datatrails.ai/archivist" - vcon_operation: "vcon_consent_revoked" + vcon_operation: "vcon_updated" auth: type: "OIDC-client-credentials" token_endpoint: "https://app.datatrails.ai/archivist/iam/v1/appidp/token" @@ -188,11 +190,11 @@ chains: egress_lists: - default_egress enabled: 1 - consent_revoked_chain: + update_chain: links: - - datatrails_consent_revoked + - datatrails_updated ingress_lists: - - consent_ingress + - update_ingress egress_lists: - default_egress enabled: 1 @@ -233,7 +235,7 @@ To run the tests for the DataTrails Link: 1. Run the tests: ```bash - pytest server/links/datatrails/ + pytest conserver/links/datatrails/ ``` ## Contributing @@ -282,6 +284,6 @@ The [DataTrails Asset Link is open-sourced under the MIT license](./LICENSE). [datatrails-tokens]: https://docs.datatrails.ai/developers/developer-patterns/getting-access-tokens-using-app-registrations/ [datatrails-events]: https://docs.datatrails.ai/developers/api-reference/events-api/ [scitt-scrapi]: https://datatracker.ietf.org/doc/draft-ietf-scitt-scrapi/ -[scitt-link]: https://github.com/vcon-dev/vcon-server/tree/main/server/links/scitt +[scitt-link]: https://github.com/vcon-dev/vcon-server/tree/main/conserver/links/scitt [scitt-architecture]: https://datatracker.ietf.org/wg/scitt/about/ [datatrails-vcon-template]: https://docs.datatrails.ai/developers/templates/vcons/ \ No newline at end of file diff --git a/conserver/links/deepgram_link/README.md b/conserver/links/deepgram_link/README.md index 872d8990..1b760c94 100644 --- a/conserver/links/deepgram_link/README.md +++ b/conserver/links/deepgram_link/README.md @@ -1,5 +1,7 @@ # Deepgram Link +Reference: [`links.deepgram_link`](../../../docs/reference/links/deepgram.md) + The Deepgram link is a specialized plugin that performs speech-to-text transcription on audio recordings in vCon dialogs using the Deepgram API. It supports automatic language detection and confidence scoring for transcription quality. ## Features @@ -11,7 +13,7 @@ The Deepgram link is a specialized plugin that performs speech-to-text transcrip - Automatic retry mechanism with exponential backoff - Metrics tracking for transcription time and failures - Support for URL-based audio sources -- **Comprehensive logging and code comments for observability and maintainability** +- **Logging and code comments for observability and maintainability** ## Configuration Options @@ -87,7 +89,7 @@ The link tracks the following metrics: ## Logging and Observability -This link now features **comprehensive logging** at multiple levels (INFO, WARNING, ERROR, DEBUG) to provide: +This link logs at multiple levels (INFO, WARNING, ERROR, DEBUG) to provide: - Start and end of processing for each vCon - Option merging and configuration details - Dialog filtering decisions (type, URL, duration) diff --git a/conserver/links/delay/README.md b/conserver/links/delay/README.md index e8bbb582..84f35388 100644 --- a/conserver/links/delay/README.md +++ b/conserver/links/delay/README.md @@ -1,11 +1,13 @@ # Delay Link +Reference: [`links.delay`](../../../docs/reference/links/delay.md) + The Delay link is a lightweight **testing fixture**. It sleeps for a configurable number of seconds and then passes the vCon through the chain unchanged. It does not read or modify the vCon. Its purpose is to make a chain take a predictable amount of wall-clock time so -that concurrent processing behaviour can be observed during QA — for example, +that concurrent processing behaviour can be observed during QA, for example verifying that per-worker in-flight concurrency (`CONSERVER_VCON_CONCURRENCY`) actually processes multiple vCons in parallel rather than serially. diff --git a/conserver/links/detect_engagement/README.md b/conserver/links/detect_engagement/README.md index f338562a..7358f323 100644 --- a/conserver/links/detect_engagement/README.md +++ b/conserver/links/detect_engagement/README.md @@ -1,5 +1,7 @@ # Engagement Detection Link +Reference: [`links.detect_engagement`](../../../docs/reference/links/detect-engagement.md) + This link analyzes conversations to determine if both the customer and agent are engaged in the dialogue. It uses OpenAI's GPT-4.1 model to analyze transcripts and determine engagement status. ## Features @@ -81,7 +83,7 @@ Make sure the `detect_engagement` link is included in your server's link configu ```yaml links: - name: detect_engagement - module: server.links.detect_engagement + module: links.detect_engagement options: # Optional: override any default options here # prompt: "Custom prompt here" diff --git a/conserver/links/diet/README.md b/conserver/links/diet/README.md index b37e4ad9..2b8bbb88 100644 --- a/conserver/links/diet/README.md +++ b/conserver/links/diet/README.md @@ -1,5 +1,7 @@ # Diet Link +Reference: [`links.diet`](../../../docs/reference/links/diet.md) + The Diet link is a specialized plugin that helps reduce the size and content of vCon objects by selectively removing or modifying specific elements. It's particularly useful for data minimization, privacy protection, and optimizing storage. ## Features diff --git a/conserver/links/expire_vcon/README.md b/conserver/links/expire_vcon/README.md index 16027353..40689e44 100644 --- a/conserver/links/expire_vcon/README.md +++ b/conserver/links/expire_vcon/README.md @@ -1,5 +1,7 @@ # Expire vCon Link +Reference: [`links.expire_vcon`](../../../docs/reference/links/expire-vcon.md) + The Expire vCon link is a simple but effective plugin that sets an expiration time for vCon objects in Redis. This helps manage storage by automatically removing vCons after a specified period. ## Features diff --git a/conserver/links/groq_whisper/README.md b/conserver/links/groq_whisper/README.md index 9a051021..1edc83c5 100644 --- a/conserver/links/groq_whisper/README.md +++ b/conserver/links/groq_whisper/README.md @@ -1,5 +1,7 @@ # Groq Whisper Link +Reference: [`links.groq_whisper`](../../../docs/reference/links/groq-whisper.md) + A vCon-server link that provides automatic transcription of audio content using Groq's implementation of Whisper ASR. ## Overview @@ -17,7 +19,7 @@ This link processes vCon objects containing audio recordings and transcribes the 1. Install the required dependencies: ```bash -poetry add groq +uv sync --group conserver ``` 2. Set your Groq API key in the environment: @@ -46,7 +48,7 @@ The link accepts the following configuration options: To use this link in a vCon processing chain: ```python -from server.links.groq_whisper import run +from links.groq_whisper import run result = run( vcon_uuid="your-vcon-uuid", @@ -77,7 +79,7 @@ To run the unit tests (with mocked API): export GROQ_API_KEY=test_api_key_for_testing # Run the tests -poetry run pytest server/links/groq_whisper/test_groq_whisper.py -v +uv run --group conserver --group dev pytest conserver/links/groq_whisper/test_groq_whisper.py -v ``` ### Integration Testing @@ -91,10 +93,10 @@ To run the integration tests: export GROQ_API_KEY=your_actual_groq_api_key # Run just the integration tests -poetry run python -m server.links.groq_whisper.test_groq_whisper +uv run --group conserver --group dev pytest conserver/links/groq_whisper/test_groq_whisper.py -v -m integration # Or run all tests including integration tests -poetry run pytest server/links/groq_whisper/test_groq_whisper.py -v +uv run --group conserver --group dev pytest conserver/links/groq_whisper/test_groq_whisper.py -v ``` **Important Notes:** diff --git a/conserver/links/hugging_face_whisper/README.md b/conserver/links/hugging_face_whisper/README.md index fd5ce9b9..106d1d5b 100644 --- a/conserver/links/hugging_face_whisper/README.md +++ b/conserver/links/hugging_face_whisper/README.md @@ -1,6 +1,8 @@ # Hugging Face Whisper Link -The Hugging Face Whisper link is a specialized plugin that performs speech-to-text transcription on audio recordings in vCon dialogs using Hugging Face's implementation of the Whisper ASR service. It provides high-quality transcription with support for various audio formats and robust error handling. +Reference: [`links.hugging_face_whisper`](../../../docs/reference/links/huggingface-whisper.md) + +The Hugging Face Whisper link is a specialized plugin that performs speech-to-text transcription on audio recordings in vCon dialogs using Hugging Face's implementation of the Whisper ASR service. It provides high-quality transcription with support for various audio formats and error handling. ## Features diff --git a/conserver/links/hugging_llm_link/README.md b/conserver/links/hugging_llm_link/README.md index 4a21d00c..e0eb9d17 100644 --- a/conserver/links/hugging_llm_link/README.md +++ b/conserver/links/hugging_llm_link/README.md @@ -1,10 +1,12 @@ # HuggingFace LLM Link -A vCon Link component that processes conversation data using HuggingFace's language models. This link extracts transcripts from vCon documents and leverages LLMs to generate conversation analysis including summaries, sentiment analysis, and key discussion points. +Reference: [`links.hugging_llm_link`](../../../docs/reference/links/hugging-llm.md) + +A vCon Link component that processes conversation data using HuggingFace's language models. This link extracts transcripts from vCon documents and uses LLMs to generate conversation analysis including summaries, sentiment analysis, and key discussion points. ## Overview -This link is part of the vCon processing pipeline and works alongside other links to provide comprehensive conversation analysis. It integrates with HuggingFace's models to provide: +This link is part of the vCon processing pipeline and works alongside other links to provide conversation analysis. It integrates with HuggingFace's models to provide: - Conversation summaries - Sentiment analysis diff --git a/conserver/links/jq_link/README.md b/conserver/links/jq_link/README.md index f9265b49..693e3f6f 100644 --- a/conserver/links/jq_link/README.md +++ b/conserver/links/jq_link/README.md @@ -1,5 +1,7 @@ # JQ Link +Reference: [`links.jq_link`](../../../docs/reference/links/jq.md) + The JQ link is a specialized plugin that filters vCon objects using jq expressions. It provides a powerful way to selectively process vCons based on their content, allowing for complex filtering conditions and flexible forwarding rules. ## Features diff --git a/conserver/links/post_analysis_to_slack/README.md b/conserver/links/post_analysis_to_slack/README.md index b99253b8..7c6578da 100644 --- a/conserver/links/post_analysis_to_slack/README.md +++ b/conserver/links/post_analysis_to_slack/README.md @@ -1,5 +1,7 @@ # Post Analysis to Slack Link +Reference: [`links.post_analysis_to_slack`](../../../docs/reference/links/slack.md) + The Post Analysis to Slack link is a specialized plugin that posts vCon analysis results to Slack channels. It provides a way to notify teams about important analysis findings, with support for team-specific channels and customizable posting conditions. ## Features @@ -40,15 +42,15 @@ default_options = { ### URL templating The `url` option is a template. If it contains `{vcon_id}`, the vCon uuid -is substituted at that exact position — the template owns the quoting and +is substituted at that exact position. The template owns the quoting and placement. This lets the same link work with destinations that embed the id in different shapes: ```yaml -# Hex sheet — uuid must be wrapped in double quotes inside a query param. +# Hex sheet: uuid must be wrapped in double quotes inside a query param. url: 'https://app.hex.tech//app//latest?_vcon_id="{vcon_id}"' -# Path-based destination — uuid embedded raw in the path. +# Path-based destination: uuid embedded raw in the path. url: "https://app.example.com/conversations/{vcon_id}" ``` diff --git a/conserver/links/sampler/README.md b/conserver/links/sampler/README.md index abacb83c..f9286e06 100644 --- a/conserver/links/sampler/README.md +++ b/conserver/links/sampler/README.md @@ -1,5 +1,7 @@ # Sampler Link +Reference: [`links.sampler`](../../../docs/reference/links/sampler.md) + The Sampler link is a specialized plugin that selectively processes vCons based on various sampling methods. It provides a way to reduce the volume of vCons being processed in a chain, enabling efficient resource utilization and focused analysis. ## Features diff --git a/conserver/links/scitt/readme.md b/conserver/links/scitt/readme.md index 487aeb48..3f3740c7 100644 --- a/conserver/links/scitt/readme.md +++ b/conserver/links/scitt/readme.md @@ -1,5 +1,7 @@ # SCITT Link +Reference: [`links.scitt`](../../../docs/reference/links/scitt.md) + The SCITT (Supply Chain Integrity, Transparency, and Trust) link is a specialized plugin that provides integrity and inclusion protection for vCon objects by creating and registering signed statements on a SCITT Transparency Service. It ensures that vCons can be verified as authentic and complete, protecting against tampering and deletion. ## Features @@ -103,7 +105,7 @@ With the SCITT capabilities, the integrity and inclusion of all vCons are record If you're in possession of a vCon that's not recorded on a SCITT ledger, how do you know it's a valid vCon, or the latest version of that vCon? The SCITT Conserver Link is designed to integrate vCon (virtual conversation) data with a SCITT Reference API (SCRAPI) implementation. -The SCITT Link creates Signed Statements based on vCon information, enabling seamless tracking and management of conversation-related assets. +The SCITT Link creates Signed Statements based on vCon information, for tracking and managing conversation-related assets. Setting the `vcon_operation` chain configuration, log different types of Events, based on which chain is executed. ## Prerequisites diff --git a/conserver/links/tag/README.md b/conserver/links/tag/README.md index 5463d2dc..4d4174e3 100644 --- a/conserver/links/tag/README.md +++ b/conserver/links/tag/README.md @@ -1,5 +1,7 @@ # Tag Link +Reference: [`links.tag`](../../../docs/reference/links/tag.md) + The Tag link is a specialized plugin that adds tags to vCon objects. It provides a simple way to categorize and organize vCons with custom tags, enabling better filtering, searching, and organization of conversation data. ## Features @@ -9,7 +11,7 @@ The Tag link is a specialized plugin that adds tags to vCon objects. It provides - In-place modification of vCon objects - Efficient tag management - Minimal dependencies -- Seamless integration with vCon processing chains +- Integrates with vCon processing chains ## Configuration Options diff --git a/conserver/links/tag_router/README.md b/conserver/links/tag_router/README.md index 6a56252a..a10f37da 100644 --- a/conserver/links/tag_router/README.md +++ b/conserver/links/tag_router/README.md @@ -1,5 +1,7 @@ # Tag Router Link +Reference: [`links.tag_router`](../../../docs/reference/links/tag-router.md) + The Tag Router link is a specialized plugin that routes vCon objects to different Redis lists based on their tags. It provides a flexible way to organize and distribute vCons to different processing queues or storage locations based on their tag content. ## Features @@ -9,7 +11,7 @@ The Tag Router link is a specialized plugin that routes vCon objects to differen - Configurable forwarding behavior - Flexible tag-based routing rules - Efficient Redis list management -- Seamless integration with vCon processing chains +- Integrates with vCon processing chains ## Configuration Options diff --git a/conserver/links/webhook/README.md b/conserver/links/webhook/README.md index 44b9dc23..58abcd27 100644 --- a/conserver/links/webhook/README.md +++ b/conserver/links/webhook/README.md @@ -1,5 +1,7 @@ # Webhook Link +Reference: [`links.webhook`](../../../docs/reference/links/webhook.md) + The Webhook link is a specialized plugin that sends vCon objects to configured webhook URLs. It provides a flexible way to integrate vCon processing with external systems by forwarding vCon data to specified endpoints. ## Features @@ -9,7 +11,7 @@ The Webhook link is a specialized plugin that sends vCon objects to configured w - API token support - JSON payload formatting - Response logging -- Seamless integration with vCon processing chains +- Integrates with vCon processing chains ## Configuration Options diff --git a/conserver/links/wtf_transcribe/README.md b/conserver/links/wtf_transcribe/README.md index 6b22fdce..abce35b6 100644 --- a/conserver/links/wtf_transcribe/README.md +++ b/conserver/links/wtf_transcribe/README.md @@ -1,5 +1,7 @@ # WTF Transcription Link (vfun Integration) +Reference: [`links.wtf_transcribe`](../../../docs/reference/links/wtf-transcribe.md) + A link that sends vCon audio dialogs to a vfun transcription server and adds the results as WTF (World Transcription Format) analysis entries. ## Overview @@ -136,5 +138,5 @@ curl -X POST http://localhost:8443/transcribe \ ## Related -- [vfun](https://github.com/strolid/vfun) - GPU-accelerated transcription server +- vfun, the GPU-accelerated transcription server this link calls - [draft-howe-vcon-wtf-extension](https://datatracker.ietf.org/doc/html/draft-howe-vcon-wtf-extension) - IETF WTF specification diff --git a/README_REDIS_CACHING.md b/docs/archive/README_REDIS_CACHING.md similarity index 92% rename from README_REDIS_CACHING.md rename to docs/archive/README_REDIS_CACHING.md index c24a5ff7..9ad9bd73 100644 --- a/README_REDIS_CACHING.md +++ b/docs/archive/README_REDIS_CACHING.md @@ -1,5 +1,7 @@ # Redis Caching for vCon API +> **Historical file.** Archived on 2026-11-03 and no longer maintained. It does not describe the current code. See the [archive index](index.md). + ## Overview The vCon API uses Redis as a primary storage and caching layer. When a vCon is not found in Redis but exists in a configured storage backend (like PostgreSQL, MongoDB, etc.), the API will automatically store it back in Redis with a configurable expiration time. This improves performance for subsequent requests for the same vCon, as they'll be served from Redis instead of having to query the storage backend again. diff --git a/docs/archive/index.md b/docs/archive/index.md new file mode 100644 index 00000000..bb81aa79 --- /dev/null +++ b/docs/archive/index.md @@ -0,0 +1,38 @@ +# Archived documents + +These pages keep older product notes on record. Use the live manual for anything you plan to run or configure. + +!!! warning "These files are historical" + The files in this archive are historical and no longer maintained. They were last edited on or before 2026-04-08 and do not describe the current code. Routes, options, image names, version numbers, Redis keys and roadmap dates in them can be wrong or never have existed. + + Statements about compliance, consent or data rights in these files are not claims about the open source server. The server carries `lawful_basis` attachments and does not manage consent. It does not make a deployment compliant. See [lawful basis](../concepts/lawful-basis.md) and [editions](../concepts/editions.md). + +## Browse the archived files + +| File | Live page to use instead | +|---|---| +| [Product docs index](prod_mgt/README.md) | [Documentation home](../index.md) | +| [Product overview](prod_mgt/01_PRODUCT_OVERVIEW.md) | [Server architecture](../concepts/architecture.md) | +| [Core functionality](prod_mgt/02_CORE_FUNCTIONALITY.md) | [Chains, links and storage](../concepts/chains-links-storage.md), [vCon lifecycle](../concepts/vcon-lifecycle.md) | +| [Storage adapters](prod_mgt/03_STORAGE_ADAPTERS.md) | [Storage adapters](../reference/storage-adapters/index.md) | +| [Link processors](prod_mgt/04_LINK_PROCESSORS.md) | [Links](../reference/links/index.md), [JLINC tracer](../reference/tracers/jlinc.md) | +| [External integrations](prod_mgt/05_EXTERNAL_INTEGRATIONS.md) | [Links](../reference/links/index.md), [JLINC tracer](../reference/tracers/jlinc.md) | +| [Deployment and operations](prod_mgt/06_DEPLOYMENT_OPERATIONS.md) | [Installation](../installation/index.md), [Operations](../operations/index.md), [Workers](../configuration/workers.md) | +| [Use cases and examples](prod_mgt/07_USE_CASES_EXAMPLES.md) | [Chains and pipelines](../configuration/chains-and-pipelines.md) | +| [API reference](prod_mgt/08_API_REFERENCE.md) | [API reference](../reference/api.md) | +| [Architecture and design](prod_mgt/09_ARCHITECTURE_DESIGN.md) | [Server architecture](../concepts/architecture.md) | +| [Roadmap](prod_mgt/10_ROADMAP_FUTURE.md) | None. The dates have passed and no live roadmap replaces it | +| [Redis caching](README_REDIS_CACHING.md) | [Read a stored vCon](../concepts/vcon-lifecycle.md#read-a-stored-vcon) | + +## Track the merged content + +Content that was unique and still true moved to the live pages below before these files were archived. + +| Source | Content | Live page | +|---|---|---| +| Redis caching | Reads served from Redis after a recache, and the `VCON_REDIS_EXPIRY` trade-off | [vCon lifecycle](../concepts/vcon-lifecycle.md#read-a-stored-vcon) | +| Storage adapters | Multi-storage patterns, corrected to say a list makes copies and not tiers | [Storage adapters](../reference/storage-adapters/index.md#combine-backends-on-a-chain) | +| Link processors | Filter links go early in a chain | [Chains and pipelines](../configuration/chains-and-pipelines.md#halt-a-vcon-in-a-chain) | +| Link processors | Links must be safe to repeat | [Create a processing link](../extending/creating-links.md#follow-these-practices) | + +The rest was already covered by the live pages or no longer matches the code. The chain examples in the use cases file, for instance, set options the links do not read. diff --git a/prod_mgt/01_PRODUCT_OVERVIEW.md b/docs/archive/prod_mgt/01_PRODUCT_OVERVIEW.md similarity index 95% rename from prod_mgt/01_PRODUCT_OVERVIEW.md rename to docs/archive/prod_mgt/01_PRODUCT_OVERVIEW.md index 2227d463..018a0c84 100644 --- a/prod_mgt/01_PRODUCT_OVERVIEW.md +++ b/docs/archive/prod_mgt/01_PRODUCT_OVERVIEW.md @@ -1,5 +1,7 @@ # vCon Server Product Overview +> **Historical file.** Archived on 2026-11-03 and no longer maintained. It does not describe the current code. See the [archive index](../index.md). + ## Executive Summary vCon Server is an enterprise-grade conversation processing and storage system that provides a complete platform for managing Voice Conversation (vCon) records. It implements a flexible, modular pipeline architecture for processing, analyzing, storing, and retrieving conversation data through various specialized modules and integrations. diff --git a/prod_mgt/02_CORE_FUNCTIONALITY.md b/docs/archive/prod_mgt/02_CORE_FUNCTIONALITY.md similarity index 97% rename from prod_mgt/02_CORE_FUNCTIONALITY.md rename to docs/archive/prod_mgt/02_CORE_FUNCTIONALITY.md index ac20f19b..e0dc18e2 100644 --- a/prod_mgt/02_CORE_FUNCTIONALITY.md +++ b/docs/archive/prod_mgt/02_CORE_FUNCTIONALITY.md @@ -1,5 +1,7 @@ # Core Functionality +> **Historical file.** Archived on 2026-11-03 and no longer maintained. It does not describe the current code. See the [archive index](../index.md). + ## vCon Data Model ### Structure diff --git a/prod_mgt/03_STORAGE_ADAPTERS.md b/docs/archive/prod_mgt/03_STORAGE_ADAPTERS.md similarity index 97% rename from prod_mgt/03_STORAGE_ADAPTERS.md rename to docs/archive/prod_mgt/03_STORAGE_ADAPTERS.md index 83d015dc..a1ff487b 100644 --- a/prod_mgt/03_STORAGE_ADAPTERS.md +++ b/docs/archive/prod_mgt/03_STORAGE_ADAPTERS.md @@ -1,5 +1,7 @@ # Storage Adapters +> **Historical file.** Archived on 2026-11-03 and no longer maintained. It does not describe the current code. See the [archive index](../index.md). + ## Overview vCon Server supports multiple storage backends through a modular adapter system. Each storage adapter implements a common interface while providing backend-specific optimizations and features. diff --git a/prod_mgt/04_LINK_PROCESSORS.md b/docs/archive/prod_mgt/04_LINK_PROCESSORS.md similarity index 90% rename from prod_mgt/04_LINK_PROCESSORS.md rename to docs/archive/prod_mgt/04_LINK_PROCESSORS.md index d42a2302..eda9fedd 100644 --- a/prod_mgt/04_LINK_PROCESSORS.md +++ b/docs/archive/prod_mgt/04_LINK_PROCESSORS.md @@ -1,5 +1,7 @@ # Link Processors +> **Historical file.** Archived on 2026-11-03 and no longer maintained. It does not describe the current code. See the [archive index](../index.md). + ## Overview Link processors are modular components that perform specific operations on vCons as they flow through processing chains. Each link implements a focused functionality, allowing flexible pipeline construction. @@ -122,6 +124,9 @@ webhook: - Thread support #### JLINC Link + +> **Correction, 2026-11-03.** This section does not match the code. JLINC is a tracer in `conserver/tracers/jlinc`, not a link. It reports each link step to a JLINC API server as an audit event. It has no consent logic, and neither does the rest of the open source server: nothing here creates, checks, enforces or tracks consent, agreements or data rights. See the [JLINC tracer](../../reference/tracers/jlinc.md) and [lawful basis](../../concepts/lawful-basis.md). + **Purpose**: Data sovereignty and consent management **Features**: diff --git a/prod_mgt/05_EXTERNAL_INTEGRATIONS.md b/docs/archive/prod_mgt/05_EXTERNAL_INTEGRATIONS.md similarity index 89% rename from prod_mgt/05_EXTERNAL_INTEGRATIONS.md rename to docs/archive/prod_mgt/05_EXTERNAL_INTEGRATIONS.md index 1e834ebd..6b040704 100644 --- a/prod_mgt/05_EXTERNAL_INTEGRATIONS.md +++ b/docs/archive/prod_mgt/05_EXTERNAL_INTEGRATIONS.md @@ -1,5 +1,7 @@ # External Integrations +> **Historical file.** Archived on 2026-11-03 and no longer maintained. It does not describe the current code. See the [archive index](../index.md). + ## Overview vCon Server integrates with numerous external services for transcription, analysis, storage, and workflow automation. These integrations enable powerful capabilities while maintaining flexibility through the modular architecture. @@ -142,6 +144,9 @@ temperature: 0 - Verifiable claims ### JLINC + +> **Correction, 2026-11-03.** This section does not match the code. JLINC is a tracer in `conserver/tracers/jlinc`, not a link. It reports each link step to a JLINC API server as an audit event. It has no consent logic, and neither does the rest of the open source server: nothing here creates, checks, enforces or tracks consent, agreements or data rights. See the [JLINC tracer](../../reference/tracers/jlinc.md) and [lawful basis](../../concepts/lawful-basis.md). + **Service**: Data sovereignty protocol **Features**: diff --git a/prod_mgt/06_DEPLOYMENT_OPERATIONS.md b/docs/archive/prod_mgt/06_DEPLOYMENT_OPERATIONS.md similarity index 98% rename from prod_mgt/06_DEPLOYMENT_OPERATIONS.md rename to docs/archive/prod_mgt/06_DEPLOYMENT_OPERATIONS.md index 66935770..125dad76 100644 --- a/prod_mgt/06_DEPLOYMENT_OPERATIONS.md +++ b/docs/archive/prod_mgt/06_DEPLOYMENT_OPERATIONS.md @@ -1,5 +1,7 @@ # Deployment & Operations +> **Historical file.** Archived on 2026-11-03 and no longer maintained. It does not describe the current code. See the [archive index](../index.md). + ## Deployment Models ### 1. Docker Deployment (Recommended) diff --git a/prod_mgt/07_USE_CASES_EXAMPLES.md b/docs/archive/prod_mgt/07_USE_CASES_EXAMPLES.md similarity index 98% rename from prod_mgt/07_USE_CASES_EXAMPLES.md rename to docs/archive/prod_mgt/07_USE_CASES_EXAMPLES.md index 25fba627..2e466df3 100644 --- a/prod_mgt/07_USE_CASES_EXAMPLES.md +++ b/docs/archive/prod_mgt/07_USE_CASES_EXAMPLES.md @@ -1,5 +1,7 @@ # Use Cases & Examples +> **Historical file.** Archived on 2026-11-03 and no longer maintained. It does not describe the current code. See the [archive index](../index.md). + ## Industry Use Cases ### 1. Call Center Operations diff --git a/prod_mgt/08_API_REFERENCE.md b/docs/archive/prod_mgt/08_API_REFERENCE.md similarity index 97% rename from prod_mgt/08_API_REFERENCE.md rename to docs/archive/prod_mgt/08_API_REFERENCE.md index d354b9ac..384f0abc 100644 --- a/prod_mgt/08_API_REFERENCE.md +++ b/docs/archive/prod_mgt/08_API_REFERENCE.md @@ -1,5 +1,7 @@ # API Reference +> **Historical file.** Archived on 2026-11-03 and no longer maintained. It does not describe the current code. See the [archive index](../index.md). + ## Base URL ``` https://your-domain.com/api diff --git a/prod_mgt/09_ARCHITECTURE_DESIGN.md b/docs/archive/prod_mgt/09_ARCHITECTURE_DESIGN.md similarity index 99% rename from prod_mgt/09_ARCHITECTURE_DESIGN.md rename to docs/archive/prod_mgt/09_ARCHITECTURE_DESIGN.md index c6e254a8..f05229b5 100644 --- a/prod_mgt/09_ARCHITECTURE_DESIGN.md +++ b/docs/archive/prod_mgt/09_ARCHITECTURE_DESIGN.md @@ -1,5 +1,7 @@ # Architecture & Design +> **Historical file.** Archived on 2026-11-03 and no longer maintained. It does not describe the current code. See the [archive index](../index.md). + ## System Architecture ### High-Level Architecture diff --git a/prod_mgt/10_ROADMAP_FUTURE.md b/docs/archive/prod_mgt/10_ROADMAP_FUTURE.md similarity index 97% rename from prod_mgt/10_ROADMAP_FUTURE.md rename to docs/archive/prod_mgt/10_ROADMAP_FUTURE.md index fd99c202..cc61e65e 100644 --- a/prod_mgt/10_ROADMAP_FUTURE.md +++ b/docs/archive/prod_mgt/10_ROADMAP_FUTURE.md @@ -1,5 +1,7 @@ # Roadmap & Future Development +> **Historical file.** Archived on 2026-11-03 and no longer maintained. It does not describe the current code. See the [archive index](../index.md). + ## Current State (v1.1) ### Established Features diff --git a/prod_mgt/README.md b/docs/archive/prod_mgt/README.md similarity index 97% rename from prod_mgt/README.md rename to docs/archive/prod_mgt/README.md index 72f8d96f..621a5558 100644 --- a/prod_mgt/README.md +++ b/docs/archive/prod_mgt/README.md @@ -1,5 +1,7 @@ # vCon Server Product Management Documentation +> **Historical file.** Archived on 2026-11-03 and no longer maintained. It does not describe the current code. See the [archive index](../index.md). + This directory contains comprehensive product documentation for the vCon Server project, organized to provide clear insights into functionality, architecture, and deployment strategies. ## Documentation Structure diff --git a/docs/concepts/architecture.md b/docs/concepts/architecture.md new file mode 100644 index 00000000..63f06c56 --- /dev/null +++ b/docs/concepts/architecture.md @@ -0,0 +1,98 @@ +# Server architecture + +This page shows which process does what, so you can place a config change or a fault in the right service before you open the reference pages. + +vCon Server is two Python services around one Redis instance. The `api` service takes vCons in and serves them back. The `conserver` service runs them through chains. The services never call each other. They share Redis, the YAML config file and the storage backends. + +## See the system context + +```mermaid +--8<-- "docs/diagrams/D01-system-context.mmd" +``` + +Dashed edges exist only when the config asks for them. Storage and link edges are solid, but the config still picks each system. [Open the diagram as an SVG](../diagrams/D01-system-context.svg). + +| Part | Code | Job | +|---|---|---| +| `api` service | `api/api.py` | FastAPI app. Accepts vCons, pushes UUIDs to lists, reads and deletes vCons, replays dead letter queues | +| `conserver` service | `conserver/main.py` | Runs the workers and any followers. Workers pop UUIDs and run chains | +| Redis | `common/redis_mgr.py`, `common/lib/queue.py` | Holds working vCons, lists and indexes. Plain Redis, with no modules | +| Config file | `common/config.py` | YAML file named by `CONSERVER_CONFIG_FILE`. Defines chains, links, storages, tracers and followers | +| Storage backends | `common/storage/` | Keep vCons after a chain finishes. Chosen per chain | + +[Ports and services](../reference/ports.md) lists the Compose services and published ports. [Authentication](../configuration/authentication.md) covers the API keys. + +## Trace the ingress paths + +Every path ends the same way. A vCon UUID lands on a Redis list and a worker pops it. The list carries only the UUID. The vCon body sits in its own Redis key. + +```mermaid +--8<-- "docs/diagrams/D04-ingress-paths.mmd" +``` + +[Open the diagram as an SVG](../diagrams/D04-ingress-paths.svg). + +| Path | Takes | Behaviour to expect | +|---|---|---| +| `POST /vcon` | A full vCon | Stores and indexes it. Queues it only when the request names `ingress_lists` | +| `POST /vcon/external-ingress` | A full vCon | Stores and indexes it, then queues it on the one `ingress_list` its key allows | +| `POST /vcon/ingress` | A list of UUIDs | Queues vCons that already exist. Loads a missing body from storage, and logs and skips a UUID found nowhere | +| Follower | UUIDs from another server | Pops the upstream egress list, copies each body into Redis, with no TTL on a new key and any existing TTL kept, then queues it. It adds no sorted set or party index entry | +| Internal re-entry | A UUID | A chain's `egress_lists`, the `tag_router` link and `POST /dlq/reprocess` all push to lists a chain may read | + +A worker reads only the lists named in some chain's `ingress_lists`. The API does not check this, so a push to any other list waits there unread. + +The follower pop is destructive on the upstream side. If the upstream then returns 404 for a UUID, the follower logs the error and drops it. + +The [API reference](../reference/api.md) has the request shapes. [Pull from another server](../configuration/yaml-configuration.md#pull-from-another-server) has the follower keys. + +## Keep working state in Redis + +Redis is the working copy. Links read a vCon from it and write it back, and the storage backends are where it stays once Redis lets it go. + +| Key | Type | Holds | +|---|---|---| +| `vcon:` | String | The vCon as JSON, written with `SET` | +| Each ingress or egress list | List | vCon UUIDs waiting for a chain or a follower | +| `DLQ:` | List | UUIDs that failed in a link | +| `DLQ:storage:` | List | UUIDs whose write to one backend failed | +| `VCON_SORTED_SET_NAME`, default `vcons` | Sorted set | vCons by creation time, for listing | +| `tel:`, `mailto:`, `name:` | Set | Party search index, kept for `VCON_INDEX_EXPIRY` seconds | +| `context::` | List | Trace context passed from the producer to the worker | + +On a Redis miss, the server tries every backend under `storages:` in config order and re-caches the first hit. On the API path, a backend that fails to load or raises from `get` fails the request with a 500 and later backends are not tried. `VconRedis` logs the error and moves to the next backend. This covers all configured backends, not only the ones in the current chain. A backend with no `get` never answers. `VCON_STORAGE_FALLBACK_ENABLED` switches this off for `VconRedis`, the class links use. The API read path has its own lookup and ignores that setting. + +[vCon lifecycle](vcon-lifecycle.md) follows a vCon through these keys and its expiry times. + +## Run the conserver processes + +At startup the main process starts any followers, then runs the workers. With `CONSERVER_WORKERS` at its default of 1, the single worker runs in the main process. With more, the main process spawns one process per worker, checks them every 5 seconds and restarts any that die. + +Each worker blocks on `BLPOP` across all ingress lists, with a 15 second timeout. Redis gives each UUID to one worker. `CONSERVER_VCON_CONCURRENCY` lets a worker run several chains at once on threads. + +On `SIGTERM` or `SIGINT`, a worker stops taking work. A UUID popped just as the signal arrived goes back to the head of its list. + +[Worker configuration](../configuration/workers.md) covers sizing and start methods. + +## Read the configuration file + +The two services read the YAML file separately. A worker re-reads it on each loop, so most edits apply without a restart. Environment variables do not: each process reads them when it starts. `POST /config` overwrites the whole file. + +[Plan for reloads](../configuration/yaml-configuration.md#plan-for-reloads) says which sections reload. [Environment variables](../reference/environment.md) lists every setting. + +## Separate the two failure paths + +A link failure and a storage failure take different routes, because they need different repairs. + +| Failure | Where the UUID goes | What a replay does | +|---|---|---| +| A link raises an exception | `DLQ:` | Runs the whole chain again | +| One storage write fails | `DLQ:storage:` | Repeats that write alone. The chain itself does not fail | + +Both paths use `VCON_DLQ_EXPIRY` to keep the vCon body in Redis long enough to replay. See [Dead Letter Queue](../operations/dead-letter-queue.md) and [storage recovery](../operations/storage-recovery.md). + +## Continue with related pages + +- [Chains, links and storage](chains-links-storage.md) explains what happens inside a worker. +- [vCon lifecycle](vcon-lifecycle.md) tracks one vCon from ingress to expiry. +- [Monitoring](../operations/monitoring.md) covers metrics and traces, and [the metric list](../reference/metrics.md) names them. diff --git a/docs/concepts/chains-links-storage.md b/docs/concepts/chains-links-storage.md new file mode 100644 index 00000000..3d834ca4 --- /dev/null +++ b/docs/concepts/chains-links-storage.md @@ -0,0 +1,132 @@ +# Chains, links and storage + +This page gives you the model behind the `chains`, `links` and `storages` sections of the config file, so you can predict what a chain does to a vCon before you run it. + +A chain is a named route. It reads UUIDs from ingress lists, passes each vCon through links in order, then hands it to egress lists and storage backends. Links change or filter the vCon. Storage backends keep it. + +## Define a chain + +Define each link and storage once at the top level, then name it in a chain. + +```yaml +links: + label: + module: links.tag + options: + tags: + - reviewed + +storages: + archive: + module: storage.file + options: + path: /data/vcons + +chains: + main: + links: + - label + storages: + - archive + ingress_lists: + - default +``` + +An ingress list feeds one chain. If two chains name the same list, the chain defined last takes it. + +[Build processing chains](../configuration/yaml-configuration.md#build-processing-chains) lists every key and the older keys the server ignores. [Chains and pipelines](../configuration/chains-and-pipelines.md) covers chain design. + +## Follow one chain run + +A worker takes these steps for each UUID it pops: + +1. It retrieves any trace context stored for that list and UUID. +2. It calls `hook.before_processing`. A falsy result skips the vCon, with no error and no dead letter entry. +3. It runs each link in order. +4. If no link halted the chain, it pushes the UUID to every egress list, then writes to every storage backend. +5. It calls `hook.after_processing`, whether or not the run succeeded. + +Egress comes before storage, so a downstream chain can start before the storage writes finish. + +[Chains and pipelines](../configuration/chains-and-pipelines.md) draws this flow. [Creating links](../extending/creating-links.md) has the sequence diagram for a single link. + +## Learn the link contract + +A link is a Python module with a `run` function. The worker calls `run(vcon_uuid, link_name, options)` and acts on the result. + +| The link | The chain | +|---|---| +| Returns the same UUID | Continues to the next link | +| Returns a different UUID | Continues. Later links, egress and storage use the new UUID. If a later link raises, the DLQ entry and its TTL still use the UUID the worker popped | +| Returns a falsy value | Stops. The vCon skips egress and storage, and this does not count as an error | +| Raises an exception | Stops. The UUID goes to `DLQ:` | + +A filter link therefore keeps a vCon out of storage as well as out of later links. The vCon stays in Redis until it expires. Put storage in an earlier chain if you need to keep what a filter removes. + +The worker passes the `options` value from the config as it stands. A link with no `options` key receives `None`, not its `default_options`, so [write `options: {}`](../configuration/yaml-configuration.md#add-processing-links) even when you set nothing. A bare `options:` key also loads as `None`. + +Bundled links live in `conserver/links/` and load as `links.`. They read and write the vCon through `lib.vcon_redis.VconRedis` and do queue work through `lib.queue.VconQueue`. Under the image `PYTHONPATH`, `import vcon` gives the `Vcon` class in `common/vcon.py`. + +| Family | Links | +|---|---| +| Transcription | [transcribe](../reference/links/transcribe.md), [wtf_transcribe](../reference/links/wtf-transcribe.md) | +| Analysis | [analyze](../reference/links/analyze.md), [analyze_vcon](../reference/links/analyze-vcon.md), [analyze_and_label](../reference/links/analyze-and-label.md), [check_and_tag](../reference/links/check-and-tag.md), [detect_engagement](../reference/links/detect-engagement.md) | +| Tags and routing | [tag](../reference/links/tag.md), [tag_router](../reference/links/tag-router.md) | +| Filters | [jq_link](../reference/links/jq.md), [sampler](../reference/links/sampler.md) | +| Delivery | [webhook](../reference/links/webhook.md), [post_analysis_to_slack](../reference/links/slack.md) | +| Content and expiry | [diet](../reference/links/diet.md), [expire_vcon](../reference/links/expire-vcon.md) | +| External records | [datatrails](../reference/links/datatrails.md), [scitt](../reference/links/scitt.md) | + +The [link reference](../reference/links/index.md) has the full list, including deprecated modules. The vendor transcription modules are deprecated: the worker reroutes `links.openai_transcribe`, `links.groq_whisper`, `links.hugging_face_whisper` and `links.deepgram_link` through `links.transcribe` and logs a warning. New chains should use `links.transcribe` with a `vendor` option. + +To write your own, see [Creating Links](../extending/creating-links.md). [Dynamic Modules](../extending/dynamic-modules.md) covers modules installed from outside the repo. + +## Save to storage backends + +A storage adapter copies a vCon out of Redis when a chain finishes. Each adapter is a module in `common/storage/`, loaded as `storage.` by the `Storage` class. `save` is required. `get` and `delete` are optional. + +With more than one backend on a chain, writes run in parallel threads unless `CONSERVER_PARALLEL_STORAGE` is off. Otherwise they run in the order listed. + +A failed write does not stop the other backends or fail the chain. That backend gets a `DLQ:storage:` entry, and [storage recovery](../operations/storage-recovery.md) replays the write alone. + +Backends also serve reads. On a Redis miss the server looks through the configured backends, as [Server architecture](architecture.md#keep-working-state-in-redis) explains. A backend that cannot answer `get` adds nothing to that lookup, so keep at least one that can. + +The [adapter comparison](../reference/storage-adapters/index.md#compare-the-adapters) shows what each adapter supports. A few adapters convert the vCon to an older format when `EGRESS_FORMAT_VERSION` is set. See [Egress format compatibility](../configuration/egress-compatibility.md). + +## Connect chains with lists + +Chains have no direct link to each other. One chain's egress list becomes another chain's ingress list. This example assumes links named `transcribe` and `label`. + +```yaml +chains: + transcribe: + links: + - transcribe + ingress_lists: + - calls + egress_lists: + - transcribed + review: + links: + - label + ingress_lists: + - transcribed +``` + +An egress list that no chain reads still has a use. A [follower](../configuration/yaml-configuration.md#pull-from-another-server) on another server or a client calling `GET /vcon/egress` can drain it. Otherwise it just grows. + +Naming several egress lists sends the same UUID to each. The vCon body is still one Redis key, and a link writes the whole document back, so two chains working on one vCon at the same time can overwrite each other's changes. The [tag_router](../reference/links/tag-router.md) link routes by tag from inside a chain. + +## Add tracers and hooks + +Tracers and hooks run around links without being part of a chain. + +Tracers are defined under the top-level `tracers` key and apply to every chain. Each one runs once before the first link and again after every link that returns. A tracer error is logged and the chain carries on, unless the tracer's `dlq_vcon_on_error` option is true. A failing tracer with no `options` key also stops the chain and sends the vCon to the DLQ, so always set `options`, even as `options: {}`. See [Creating Tracers](../extending/creating-tracers.md) and the [JLINC tracer](../reference/tracers/jlinc.md). + +Hooks are plain functions in `conserver/hook.py`, `conserver/after_link_hook.py` and `api/vcon_hook.py`. All of them do nothing by default. + +## Continue with related pages + +- [Server architecture](architecture.md) places chains inside the running services. +- [vCon lifecycle](vcon-lifecycle.md) shows how a vCon changes state across a chain. +- [Lawful basis](lawful-basis.md) says what the server does with a `lawful_basis` attachment. diff --git a/docs/concepts/editions.md b/docs/concepts/editions.md new file mode 100644 index 00000000..aa3a6bb7 --- /dev/null +++ b/docs/concepts/editions.md @@ -0,0 +1,9 @@ +# Editions + +This page tells you what these docs cover, so you know which behaviour you can expect from the open source server. + +These docs describe the open source vCon Server and nothing else. + +A commercial edition also exists. It is built on the published open source image and adds active consent management. It is a separate product with separate documentation. + +The open source server carries `lawful_basis` attachments through the pipeline. It does not create, validate, enforce or manage consent. That is by design, and running it does not make a deployment compliant with any law. [Lawful basis](lawful-basis.md) gives the detail. diff --git a/docs/concepts/lawful-basis.md b/docs/concepts/lawful-basis.md new file mode 100644 index 00000000..30abbb92 --- /dev/null +++ b/docs/concepts/lawful-basis.md @@ -0,0 +1,77 @@ +# Carry a lawful basis + +The open source server carries a `lawful_basis` attachment and leaves its content alone. It does not manage consent. A vCon has a lawful basis in this server only if the system that built the vCon put one there. + +## Compare the server capabilities + +| Capability | Open source server | +|---|---| +| Carry a `lawful_basis` attachment through the pipeline, storage and egress | Yes. Preserved on read, write and legacy downgrade | +| Show an existing basis in rendered output | Yes, in the `utopia` adapter | +| Skip an upload when no basis grants `analysis` | Yes, opt-in, in the `utopia` adapter only. See [`require_analysis_grant`](../reference/storage-adapters/utopia.md#require-an-analysis-grant) | +| Create a lawful basis record | No | +| Validate, enforce or gate on consent in a chain | No | +| Manage consent over time, including revocation, policy and proof | No | + +This is the intended scope of the open source server. A commercial edition adds active consent management. See [editions](editions.md). + +The server makes no claim about whether a deployment meets any law or policy. Carrying an attachment says nothing about whether its content is true, current or sufficient. + +## Locate the attachment in a vCon + +![Class diagram of a vCon showing the lawful basis attachment as carried by the server and never created by it](../diagrams/D10-vcon-assembly.svg) + +## Read the attachment shape + +The attachment is an entry in the `attachments` array of a vCon with `vcon` set to `0.4.0`. This sample shows the shape only, and its values are placeholders. Attachments like this come from a producer outside the server. + +```json +{ + "purpose": "lawful_basis", + "start": "2026-01-02T12:15:30Z", + "party": 0, + "dialog": 0, + "mediatype": "application/json", + "encoding": "json", + "body": { + "lawful_basis": "consent", + "expiration": "2027-01-02T12:00:00Z", + "purpose_grants": [ + {"purpose": "recording", "granted": true, "granted_at": "2026-01-02T12:15:30Z"}, + {"purpose": "analysis", "granted": true, "granted_at": "2026-01-02T12:15:30Z"} + ], + "proof_mechanisms": [ + { + "mechanism_type": "audio_recording", + "dialog_index": 0, + "description": "Verbal consent at the start of the recording" + } + ] + } +} +``` + +With `encoding: json`, `body` is the JSON value itself. A body stored as a JSON string by an older producer still reads correctly. A vCon can also name the extension in its top-level `extensions` and `critical` arrays. + +The server checks none of this. It stores what it receives, and unknown top-level fields pass through. + +## Follow the attachment through the server + +| Stage | What happens to the attachment | +|---|---| +| Intake | The entry is stored as sent. `POST /vcon` and `POST /vcon/external-ingress` accept any dict in `attachments` | +| Read through `VconRedis` | An entry with `type: lawful_basis` and no `purpose` gets `purpose: lawful_basis`. An entry with both keeps both. The body is not touched | +| Write through `VconRedis` | The same rename. A dict or list body with another `encoding` is marked `json`, and the value stays the same | +| Links | No link reads it. Links run whether or not one is present, including links that send content to an outside vendor. See [links and lawful basis](../reference/links/index.md#carry-lawful-basis-attachments) | +| Storage | Adapters that store the whole vCon keep it. An adapter that stores a derived form does not hold the attachment itself. See [adapters and lawful basis](../reference/storage-adapters/index.md#carry-lawful-basis-attachments) | +| Legacy egress | Converted like any other attachment, with its content kept. See [egress format compatibility](../configuration/egress-compatibility.md#carry-lawful-basis-attachments) | + +The `lawful_basis` name appears in non-test code in three places only, `common/lib/vcon_compat.py`, `common/lib/vcon_egress_compat.py` and `common/storage/utopia/__init__.py`. The first two mention it in comments, and the adapter reads it. + +The attachment shares the lifetime of the vCon body. See [the vCon lifecycle](vcon-lifecycle.md). + +## Review the remaining limits + +The server does not act on `expiration` or on a `granted: false` grant. A vCon with an expired basis stays where it is and keeps running through chains. Only the `utopia` adapter reads those fields, when it renders and when `require_analysis_grant` is on. + +The [`diet`](../reference/links/diet.md) link can remove attachments. Its `remove_attachment_types` filter compares the `mime_type` key and has no exception for `lawful_basis`. An attachment in the shape above uses `mediatype`, so the filter does not match it. An entry that carries `mime_type` with a listed value is removed whatever its purpose. diff --git a/docs/concepts/vcon-lifecycle.md b/docs/concepts/vcon-lifecycle.md new file mode 100644 index 00000000..db12c444 --- /dev/null +++ b/docs/concepts/vcon-lifecycle.md @@ -0,0 +1,100 @@ +# Trace the vCon lifecycle + +A vCon lives in the server as two separate things. The body is a JSON document in Redis at the key `vcon:`. The id is a string that moves between Redis lists. Queues never hold the body, so an id and its body can outlive each other. + +![States of a vCon from intake through chains, storage, dead letter queues and expiry](../diagrams/D07-vcon-lifecycle.svg) + +The states combine where the id sits and where the body sits. Wrapping up pushes to egress lists and saves to storage in one pass, so a vCon can take an egress edge and a storage edge together. + +## Enter the server + +| Path | Body written to Redis | Body TTL | Id placed on | +|---|---|---|---| +| `POST /vcon` | Yes | `VCON_REDIS_EXPIRY` | Each list in `ingress_lists`, or none | +| `POST /vcon/external-ingress` | Yes | `VCON_REDIS_EXPIRY` | The one `ingress_list` the API key allows | +| `POST /vcon/ingress` | Only when recached from storage | Unchanged, or `VCON_REDIS_EXPIRY` if recached | The named `ingress_list` | +| Follower pull | Yes | None on a new key, an existing TTL stays | `follower_ingress_list` | + +`POST /vcon/ingress` takes ids only. An id found neither in Redis nor in storage is logged and skipped. See the [API reference](../reference/api.md) for the requests and [authentication](../configuration/authentication.md) for the keys. + +The API validates some party and dialog fields, such as `tel`, `url` and `mimetype`, and checks that dialog party indexes exist. It does not inspect `analysis` or `attachments`. Unknown top-level fields stay. The model adds defaults for `subject`, `redacted`, `appended`, `group` and the four arrays, sets `tel` to null on each party, and sets `duration`, `start`, `parties`, `url`, `mimetype` and `alg` to null on each dialog when they are absent. It also rewrites `created_at` in ISO form. Attachment and analysis entries stay as sent. + +The intake and follower writes skip the spec pass described below, so the stored body keeps the `vcon` value and field names the producer sent until a `VconRedis` write replaces them. + +## Change the vCon in a chain + +A worker pops the id and runs the chain for that list. [Chains and pipelines](../configuration/chains-and-pipelines.md) describes the run order, and [workers](../configuration/workers.md) describes who does the popping. + +Links load the body through `lib.vcon_redis.VconRedis`, which returns the `Vcon` class in `common/vcon.py`. They add to it with `add_analysis` and `add_tag`, then store it again. [Lawful basis](lawful-basis.md) has a diagram of the object and what touches each part. + +Each read through `VconRedis` runs `normalize_legacy_fields`, which renames older fields. Each write runs `_enforce_spec_on_write`, which also does the following: + +- Sets `vcon` to `0.4.0`. +- Drops an empty `group` and an empty `redacted`. +- Sets `encoding` to `json` on an analysis or attachment entry with a dict or list `body`. + +The write pass adds no missing attachment fields. An attachment from `add_tag` has no `party`, `dialog` or `start`, and stays that way. `add_tag` also writes its list as a JSON string with `encoding: json`, the older shape. Readers in the server accept both forms. + +## Track the body TTL + +Redis expiry decides how long the body stays in the cache. Nothing removes the key after a storage save, so a saved vCon stays in Redis until its TTL ends. + +| Event | Effect on the TTL of `vcon:` | +|---|---| +| `POST /vcon`, `POST /vcon/external-ingress` | Set to `VCON_REDIS_EXPIRY` | +| Follower write | Kept. A new key gets no TTL | +| A link stores the vCon | Kept | +| [`expire_vcon`](../reference/links/expire-vcon.md) link | Set to its `seconds` option | +| Storage save | No change | +| Move to the ingress DLQ | Set to `VCON_DLQ_EXPIRY` unless that is `0`. This can shorten a longer TTL and adds one to a key that had none | +| Move to a storage DLQ | Raised to `VCON_DLQ_EXPIRY` if lower. A key with no TTL stays that way | +| Recached from storage | Set to `VCON_REDIS_EXPIRY` | + +[Environment variables](../reference/environment.md) lists the defaults. + +!!! warning "The TTL keeps running while the id waits" + A backlog longer than `VCON_REDIS_EXPIRY` can leave ids on a list after their bodies expire. Links then get `None` from `get_vcon`, unless a storage copy exists. What happens next depends on the link. `tag`, for one, halts the chain. Replaying a DLQ does not reset the TTL. + +## Leave the chain + +| Outcome | Id | Body | +|---|---|---| +| `before_processing` returns a falsy value, or a link returns a falsy value | Dropped. No egress push | Stays in Redis until its TTL ends. No storage save | +| Last link returns an id | Pushed to each egress list | Saved to each storage in the chain | +| Chain has no `storages` | Pushed to each egress list | Stays in Redis until its TTL ends | +| Chain has no `egress_lists` | Dropped after the saves | Saved to each storage in the chain | +| A link raises | Pushed to `DLQ:` | Stays in Redis under the DLQ TTL | +| A storage save raises | Pushed to `DLQ:storage:` | Stays in Redis under the DLQ TTL | + +An egress list holds the id only. A chain reads it when the list name matches one of its ingress lists. Otherwise a client or a remote follower takes ids with `GET /vcon/egress`. + +## Recover a failed vCon + +The two dead letter queues replay different work. `POST /dlq/reprocess` puts ids back on the ingress list, so the whole chain runs again. `POST /dlq/storage/reprocess` repeats the save and runs no links. An id stays on a storage DLQ until its save succeeds. + +If the body is already gone when a save fails, the id is not queued and the worker logs an error for manual recovery. An id on a storage DLQ can also outlive its body. The replay save then fails and the id stays put. + +See the [dead letter queue guide](../operations/dead-letter-queue.md) and [storage recovery](../operations/storage-recovery.md). + +## Read a stored vCon + +A read checks Redis first. On a miss it tries every backend under the top-level `storages` key in order, then caches the first hit in Redis with `VCON_REDIS_EXPIRY` and adds it back to the sorted set. On the API path, a backend that fails to load or raises from `get` fails the request with a 500 and later backends are not tried. `VconRedis` logs the error and moves to the next backend. The copy goes through the write pass above, so a legacy row loaded from storage returns to the current spec. + +Reads inside that window come from Redis and skip the backends. A read does not extend the TTL. Raise `VCON_REDIS_EXPIRY` to cut backend reads, at the cost of Redis memory. + +`VCON_STORAGE_FALLBACK_ENABLED` turns this off for `VconRedis` reads, which is what links use. The API read routes do not check it. A backend with no `get` function is skipped, as the [adapter comparison](../reference/storage-adapters/index.md#compare-the-adapters) shows. + +!!! warning "A recached vCon can break the id listing" + `POST /vcon` adds `vcon:` to the sorted set, and the recache paths add the bare ``. `GET /vcon` strips the prefix with `split(":")[1]`, which raises on a bare id. A recached vCon inside the requested page can therefore fail that route. + +When `EGRESS_FORMAT_VERSION` is set, API reads, the webhook link and the `postgres`, `s3` and `elasticsearch` adapters convert a copy to the legacy format. Other adapters write the current spec. The Redis copy stays on the current spec. See [egress format compatibility](../configuration/egress-compatibility.md). + +## Delete a vCon + +`DELETE /vcon/{uuid}` removes the Redis key and calls `delete` on every configured storage. A failure on one backend is logged and the others still run, and the route returns 204 either way. It does not touch queues, the sorted set or the party index keys, which expire after `VCON_INDEX_EXPIRY`. + +Without a delete, a body in Redis ends with its TTL. If no storage holds a copy, the vCon is gone at that point. + +## Carry attachments through every state + +Attachments travel inside the body, so they share its lifetime. A `lawful_basis` attachment goes through these states like any other. No state creates or checks one. See [lawful basis](lawful-basis.md). diff --git a/docs/configuration/authentication.md b/docs/configuration/authentication.md index ed686332..c0d84a5d 100644 --- a/docs/configuration/authentication.md +++ b/docs/configuration/authentication.md @@ -1,305 +1,139 @@ # Authentication -vCon Server supports multiple authentication mechanisms for securing API access. - -## Authentication Overview - -```mermaid -flowchart TB - subgraph clients [Clients] - INTERNAL[Internal Systems] - EXTERNAL[External Partners] - end - - subgraph auth [Authentication Layer] - GLOBAL[Global API Token] - INGRESS[Ingress-Specific Keys] - end - - subgraph endpoints [API Endpoints] - STANDARD[Standard Endpoints
/vcon, /vcons, etc.] - EXT_INGRESS[External Ingress
/vcon/external-ingress] - end - - INTERNAL --> GLOBAL - EXTERNAL --> INGRESS - GLOBAL --> STANDARD - GLOBAL --> EXT_INGRESS - INGRESS --> EXT_INGRESS -``` +The API checks a key on most routes. This page shows how to set those keys, how to give an outside system a key for one ingress list, and what stays public. -## Global API Token +![Sequence of the three authentication paths: public routes, main API routes and external ingress](../diagrams/D13-authentication-paths.svg) -The global API token provides full access to all endpoints. +## Know the three paths -### Configuration +| Path | Routes | Check | +|---|---|---| +| Public | `GET /version`, `GET /health`, `GET /stats/queue`, `/docs`, `/redoc`, `/openapi.json` | None | +| Main API | Every other route | The key must be in the global list | +| External ingress | `POST /vcon/external-ingress` | The key must be listed for that ingress list. Global keys do not work here | -**Environment Variable:** +The [API routes](../reference/api-routes.md) page gives the rule for each route. -```bash -CONSERVER_API_TOKEN=your-secure-token-here -``` +## Set the global API keys -**Token File (multiple tokens):** +Set one key with an environment variable, several with a file, or both. The API joins them into one list. ```bash +CONSERVER_API_TOKEN=your-secure-token-here CONSERVER_API_TOKEN_FILE=/etc/vcon/api_tokens.txt ``` -Token file format (one token per line): +The file holds one key per line: ``` -admin-token-abc123 service-token-def456 -readonly-token-ghi789 +admin-token-abc123 ``` -### Usage +The API reads both when it starts, so a change needs a restart. If the file cannot be opened, the API does not start. Keep blank lines out of the file: each line becomes a key, and a file of blank lines leaves the list non-empty, so every request fails. -Include the token in requests: +!!! warning "No keys means no check" + With neither setting in place, or with an empty file, every main API route is open. The API logs `No API keys found, skipping authentication`. External ingress stays closed. -```bash -curl http://api/vcon \ - -H "x-conserver-api-token: your-secure-token-here" -``` +## Send the key -### Custom Header Name - -Change the header name if needed: +Put the key in the `x-conserver-api-token` header: ```bash -CONSERVER_HEADER_NAME=Authorization -``` - -Then use: - -```bash -curl http://api/vcon \ - -H "Authorization: Bearer your-token" +curl http://localhost:8000/api/vcon \ + -H "x-conserver-api-token: your-secure-token-here" ``` -## Ingress-Specific Authentication +`CONSERVER_HEADER_NAME` changes the header name. The API compares the whole header value with each key and does not strip a scheme, so with `Authorization` as the header, a `Bearer ` prefix must also be part of the stored key. -For external integrations, use scoped API keys that only allow access to specific ingress lists. +A missing or wrong key returns `403` with `Invalid API Key`. -### Configuration +## Scope a key to an ingress list -In `config.yml`: +Give each outside system its own key under `ingress_auth` in `config.yml`. A key works for its listed ingress lists, on `POST /vcon/external-ingress`, and nowhere else. With no main API keys set, the main routes are open to everyone, so the scoping protects nothing there. ```yaml ingress_auth: - # Single key for an ingress list - partner_a_input: "partner-a-api-key-12345" - - # Multiple keys for an ingress list - partner_b_input: - - "partner-b-primary-key" - - "partner-b-backup-key" - - "partner-b-dev-key" -``` - -### Usage - -External partners use the `/vcon/external-ingress` endpoint: + # One key + customer_data: "customer-api-key-12345" -```bash -curl -X POST "http://api/vcon/external-ingress?ingress_list=partner_a_input" \ - -H "x-conserver-api-token: partner-a-api-key-12345" \ - -H "Content-Type: application/json" \ - -d '{"vcon": "0.0.1", "uuid": "...", ...}' + # Several keys for one list + support_calls: + - "support-api-key-67890" + - "support-vendor-key-xyz" ``` -### Security Benefits - -- Partners can only submit to their assigned ingress list -- Key compromise affects only that partner's access -- Easy to rotate individual keys without affecting others -- Audit trail per partner +The API reads this section on every request, so changes need no restart. -## Authentication Flow - -### Standard Endpoints - -```mermaid -sequenceDiagram - participant C as Client - participant A as API Server - participant R as Redis - - C->>A: Request with token - A->>A: Validate against global token(s) - alt Valid token - A->>R: Process request - R->>A: Response - A->>C: 200 OK - else Invalid token - A->>C: 403 Forbidden - end -``` - -### External Ingress - -```mermaid -sequenceDiagram - participant P as Partner - participant A as API Server - participant C as Config - participant R as Redis - - P->>A: POST /external-ingress?ingress_list=partner_a - A->>C: Check ingress_auth[partner_a] - alt Key matches - A->>R: Push to ingress list - A->>P: 200 OK - else Key mismatch - A->>P: 403 Forbidden - end -``` - -## Token Management - -### Generating Secure Tokens - -```bash -# Generate a 32-byte (256-bit) hex token -openssl rand -hex 32 - -# Generate a base64 token -openssl rand -base64 32 - -# Generate using Python -python -c "import secrets; print(secrets.token_hex(32))" -``` - -### Token Rotation - -**Step 1: Add New Token** - -Add the new token to the token file: - -```bash -echo "new-token-xyz789" >> /etc/vcon/api_tokens.txt -``` - -Or add to environment: +The caller sends the key in the same header and names the list in the query: ```bash -# In .env, you can only have one token via env var -# Use CONSERVER_API_TOKEN_FILE for multiple tokens +curl -X POST "http://localhost:8000/api/vcon/external-ingress?ingress_list=customer_data" \ + -H "x-conserver-api-token: customer-api-key-12345" \ + -H "Content-Type: application/json" \ + -d '{"vcon": "0.4.0", "uuid": "018f0f2e-6c1a-8e3b-9a6d-2f4d1c7b9e10", "created_at": "2026-01-15T10:30:00Z", "parties": [], "dialog": []}' ``` -**Step 2: Update Clients** - -Update clients to use the new token. +Success returns `204`. The API validates the query and body first, so bad input returns `422` before any key check. After that, these errors apply: -**Step 3: Remove Old Token** +| Status | Detail | Cause | +|---|---|---| +| 403 | `API Key required` | No header value | +| 403 | `No ingress authentication configured` | `ingress_auth` is empty or missing | +| 403 | `Ingress list '' not configured` | The list is not in `ingress_auth` | +| 403 | `Invalid configuration for ingress list ''` | The value is neither a string nor a list | +| 403 | `Invalid API Key for ingress list ''` | The key is not allowed for this list | +| 500 | `Failed to store vCon` | The API could not store or enqueue the vCon | +| 500 | `Internal Server Error` | The configuration file cannot be read. The body is plain text | -Remove the old token from the file: +Giving each system its own key means you can rotate or revoke one without touching the others. -```bash -# Edit the file and remove the old token -nano /etc/vcon/api_tokens.txt -``` +## Rotate the keys -**Step 4: Restart (if using env var)** +### Rotate a global key -If using `CONSERVER_API_TOKEN`, restart the service: +1. Add the new key to the token file. +2. Restart the API. Both keys now work. +3. Move your clients to the new key. +4. Remove the old key from the file and restart the API again. -```bash -docker compose restart api -``` +With Compose, `docker compose restart api` rereads a token file. A change to `CONSERVER_API_TOKEN` in `.env` needs `docker compose up -d api`. `CONSERVER_API_TOKEN` holds only one key, so a change to it has no overlap period. -### Key Rotation for Ingress Auth +### Rotate an ingress key -Update `config.yml`: +List both keys, wait for the client to move, then remove the old one. Neither step needs a restart. ```yaml ingress_auth: - partner_a_input: - - "new-partner-a-key" # New key - - "old-partner-a-key" # Keep old key temporarily + customer_data: + - "new-customer-key" + - "old-customer-key" ``` -After partner updates: - -```yaml -ingress_auth: - partner_a_input: "new-partner-a-key" # Remove old key -``` - -## Security Best Practices - -### 1. Use Strong Tokens +## Generate strong tokens ```bash -# Minimum 32 bytes (256 bits) openssl rand -hex 32 ``` -### 2. Separate Environments - -```bash -# Development -CONSERVER_API_TOKEN=dev-token-not-secure - -# Production -CONSERVER_API_TOKEN=prod-token-very-secure-random-string -``` - -### 3. Use Token Files in Production - -```bash -# Better than environment variables -CONSERVER_API_TOKEN_FILE=/etc/vcon/api_tokens.txt - -# Secure the file -chmod 600 /etc/vcon/api_tokens.txt -chown vcon:vcon /etc/vcon/api_tokens.txt -``` - -### 4. Use Ingress Auth for Partners - -```yaml -# Give each partner their own key -ingress_auth: - acme_corp: "acme-unique-key" - globex: "globex-unique-key" -``` - -### 5. Monitor Authentication Failures - -Check logs for failed authentication attempts: +## Protect the keys -```bash -docker compose logs api | grep -i "403\|forbidden\|unauthorized" -``` +- Use different keys in each environment. +- Prefer a token file, readable only by the API's user, to a key in `.env`. In a container, mount the file and set the path. +- `ingress_auth` keys sit in plain text in `config.yml`, and `GET /config` returns them to anyone with a global key. Treat a global key as an admin key. +- Keep `/stats/queue` and the generated API pages behind your proxy if you do not want them public. +- `CORSMiddleware` allows every origin. Restrict origins at your proxy if browsers reach the API. -### 6. Use HTTPS +Serve the API over TLS. The API has no TLS or rate limiting of its own, so add both at a reverse proxy: -Always use HTTPS in production: +```nginx +limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s; -```yaml -# nginx.conf server { listen 443 ssl; ssl_certificate /etc/ssl/certs/vcon.crt; ssl_certificate_key /etc/ssl/private/vcon.key; - - location /api { - proxy_pass http://api:8000; - } -} -``` - -### 7. Rate Limiting - -Add rate limiting at the reverse proxy level: - -```yaml -# nginx rate limiting -limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s; -server { location /api { limit_req zone=api burst=20 nodelay; proxy_pass http://api:8000; @@ -307,62 +141,39 @@ server { } ``` -## Troubleshooting - -### 403 Forbidden - -**Check token is set:** +To watch for failures, look for 403 responses in the API log: ```bash -# In container -docker compose exec api env | grep CONSERVER_API_TOKEN +docker compose logs api | grep " 403" ``` -**Check header name:** - -```bash -# Default header -curl -H "x-conserver-api-token: $TOKEN" ... +## Troubleshoot a rejected request -# Custom header -curl -H "$CUSTOM_HEADER: $TOKEN" ... -``` +### The main API returns 403 -**Check ingress auth:** +Check that the running API has the key you expect. The API reads keys only at startup. ```bash -# View current config -curl http://api/config -H "x-conserver-api-token: $ADMIN_TOKEN" | jq .ingress_auth +docker compose exec api env | grep CONSERVER_ ``` -### Token File Not Loading +Then check the header name, and check that the value matches the stored key in full. -**Check file exists and readable:** +### Diagnose a token file failure ```bash ls -la /etc/vcon/api_tokens.txt -cat /etc/vcon/api_tokens.txt ``` -**Check file format:** - -- One token per line -- No trailing spaces -- No empty lines +The path must exist inside the container, not only on the host. A bad path stops the API, so read its log first. -### External Ingress Rejected +### External ingress returns 403 -**Verify ingress list name matches:** +Read the detail in the response and match it to the table in [Scope a key to an ingress list](#scope-a-key-to-an-ingress-list). To see the loaded section: ```bash -# Request must match config exactly -curl "...?ingress_list=partner_a_input" # Must match key in ingress_auth +curl -s http://localhost:8000/api/config \ + -H "x-conserver-api-token: $ADMIN_TOKEN" | jq .ingress_auth ``` -**Check key is in list:** - -```yaml -ingress_auth: - partner_a_input: - - "the-key-you-are-using" # Must be in this list -``` +A global key returns `Invalid API Key for ingress list`, because this route does not read the global list. diff --git a/docs/configuration/chains-and-pipelines.md b/docs/configuration/chains-and-pipelines.md index 04d863b0..8e00dd8d 100644 --- a/docs/configuration/chains-and-pipelines.md +++ b/docs/configuration/chains-and-pipelines.md @@ -1,491 +1,299 @@ -# Chains and Pipelines - -Chains are the core processing unit in vCon Server. They define how vCons flow through the system. - -## Chain Anatomy - -```mermaid -flowchart LR - subgraph chain [Processing Chain] - direction TB - INGRESS[Ingress Lists] --> LINKS - subgraph LINKS[Links] - L1[Link 1] --> L2[Link 2] - L2 --> L3[Link N] - end - LINKS --> STORAGE[Storages] - STORAGE --> EGRESS[Egress Lists] - end - - INPUT[Incoming vCon] --> INGRESS - EGRESS --> OUTPUT[Downstream Systems] -``` +# Build chains and pipelines + +A chain is a named pipeline that a worker runs for each vCon id it pops from an ingress list. Several chains joined by lists make a pipeline. This page covers how to design them. [YAML configuration](yaml-configuration.md#build-processing-chains) lists every chain key, and the [link reference](../reference/links/index.md) lists every link. + +![Flow of one vCon id through hooks, links, egress lists and storage, with the halted and failed paths](../diagrams/D05-chain-pipeline.svg) -## Chain Configuration +## Declare a chain -### Basic Structure +Define links and storages once at the top level, then refer to them by name. ```yaml +links: + transcribe_openai: + module: links.transcribe + options: + vendor: openai + vendor_options: + OPENAI_API_KEY: your-openai-key + model: gpt-4o-transcribe + label_sales: + module: links.tag + options: + tags: + - department:sales + +storages: + archive: + module: storage.s3 + options: + aws_access_key_id: example-key + aws_secret_access_key: example-secret + aws_bucket: vcon-archive + chains: - chain_name: + sales_calls: links: - - link1 - - link2 + - transcribe_openai + - label_sales storages: - - storage1 + - archive ingress_lists: - - input_queue + - sales_ingress egress_lists: - - output_queue - tracers: - - tracer1 - enabled: 1 -``` - -### Required Fields - -| Field | Description | -|-------|-------------| -| `links` | List of processing links (can be empty) | -| `storages` | List of storage backends | -| `ingress_lists` | List of input queue names | -| `enabled` | `1` to enable, `0` to disable | - -### Optional Fields - -| Field | Description | -|-------|-------------| -| `egress_lists` | Output queues for downstream processing | -| `tracers` | Audit trail tracers | - -## Processing Flow - -### 1. Ingress - -vCons enter the chain through ingress lists: - -```yaml -ingress_lists: - - main_input - - partner_input - - api_input + - sales_done ``` -Multiple chains can share ingress lists, but each vCon is processed by only one chain (first match). - -### 2. Link Execution - -Links execute sequentially in order: +A chain lists names only. An entry such as `- analyze: {model: gpt-4}` raises `TypeError`, and the same goes for a mapping under `storages`. To run one module with different options, define two named links. ```yaml links: - - transcribe # Step 1: Transcribe audio - - analyze # Step 2: AI analysis - - tag # Step 3: Apply tags - - tag_router # Step 4: Route based on tags -``` - -Each link: - -1. Receives the vCon UUID -2. Retrieves the vCon from Redis -3. Processes/transforms the vCon -4. Stores the updated vCon -5. Returns the UUID (or `None` to filter) - -### 3. Storage - -After all links complete, the vCon is saved to all configured storages: - -```yaml -storages: - - postgres # Primary storage - - s3 # Archive - - elasticsearch # Search index + summarize: + module: links.analyze + options: + OPENAI_API_KEY: your-openai-key + analysis_type: summary + prompt: Summarize this conversation in two sentences. + source: + analysis_type: transcript + text_location: body.text + find_actions: + module: links.analyze + options: + OPENAI_API_KEY: your-openai-key + analysis_type: action_items + prompt: List the action items in this conversation. + source: + analysis_type: transcript + text_location: body.text ``` -With `CONSERVER_PARALLEL_STORAGE=true`, writes happen concurrently. +Give each link the `options` it needs. A link with no `options` key receives `None` instead of its defaults, and [most modules then raise](../reference/links/index.md#declare-a-link-in-a-chain). -### 4. Egress +## Follow the run order -Finally, the vCon UUID is pushed to egress lists: +For each id, the worker does this: -```yaml -egress_lists: - - processed_queue - - analytics_queue -``` +1. Finds the chain that owns the ingress list. +2. Calls `hook.before_processing`. A falsy return skips the vCon. +3. Runs each link in order, passing the id. The [link contract](../reference/links/index.md#follow-the-link-contract) sets out the return values. +4. Pushes the id to each egress list. +5. Saves to each storage, in parallel when [parallel storage](workers.md#run-parallel-storage-writes) is on and the chain has two or more backends. +6. Calls `hook.after_processing`, on every path. -## Link Configuration +Egress comes before storage. A chain that reads the egress list can start while the save is still running, and a failed save does not take the id back. -### Static Configuration +The hooks in this repo do nothing. [Creating links](../extending/creating-links.md) covers the execution contract. -Define link options in the `links` section: +## Assign ingress lists -```yaml -links: - my_link: - module: links.analyze - options: - model: gpt-4 - temperature: 0.3 -``` +Each ingress list belongs to one chain. If two chains name the same list, the chain defined last in the file owns it and the other never sees that list. -Reference in chains: +To run two chains on the same vCon, put its id on two lists. `POST /vcon` accepts `ingress_lists` more than once, or a chain can push to two egress lists. -```yaml -chains: - my_chain: - links: - - my_link -``` +When several lists hold ids, a worker takes from the list that comes first in chain order. A busy early list can hold back a later one. See [the worker loop](workers.md#follow-the-worker-loop). -### Inline Configuration +The worker ignores `enabled` on a chain. To stop a chain, remove its `ingress_lists`. -Override options inline in the chain: +## Halt a vCon in a chain -```yaml -chains: - my_chain: - links: - - analyze: - model: gpt-3.5-turbo - temperature: 0.7 -``` +A link stops the chain by returning a falsy value. The vCon then skips every later link, all egress lists and all storages. Its Redis copy stays until the TTL ends, and the server still counts it as processed. -### Mixed Configuration +These links can stop a chain on purpose: -Combine predefined links with inline overrides: +| Link | Stops the chain when | +|---|---| +| [`sampler`](../reference/links/sampler.md) | The vCon falls outside the sample | +| [`jq_link`](../reference/links/jq.md) | The filter rejects the vCon | +| [`tag_router`](../reference/links/tag-router.md) | `forward_original` is false | -```yaml -links: - base_transcribe: - module: links.deepgram_link - options: - model: nova-2 +A link can also halt because the body is missing. Each link's reference page gives its return values. -chains: - english_chain: - links: - - base_transcribe: - language: en - - spanish_chain: - links: - - base_transcribe: - language: es -``` +Put `sampler` and `jq_link` ahead of transcription and analysis. A vCon they stop never reaches the later links, so it costs no vendor calls. -## Filtering +## Route vCons by tag -Links can filter vCons from the pipeline by returning `None`: +`tag_router` pushes the id to other lists and takes `tag_routes`, a map of tag name to list name. It reads tags that an earlier link wrote, so place it after them. ```yaml links: - sampler: - module: links.sampler + label_urgent: + module: links.tag options: - rate: 0.1 # Only process 10% of vCons -``` - -When a link returns `None`: - -1. Processing stops for that vCon -2. No storage operations occur -3. No egress push happens -4. The vCon remains in Redis - -## Routing - -Use `tag_router` to route vCons to different queues: - -```yaml -links: - tag_router: + tags: + - urgent + route_urgent: module: links.tag_router options: - rules: - - tag: urgent - queue: urgent_processing - - tag: routine - queue: routine_processing - - tag: archive - queue: archive_only + tag_routes: + urgent: urgent_review + forward_original: true ``` -The router: - -1. Checks vCon tags against rules -2. Pushes to matching queues -3. Multiple rules can match +The push happens during the link, before this chain's storage. With `forward_original: false` the vCon stops here whether or not a route matched, so it skips this chain's storage. See the [`tag_router` reference](../reference/links/tag-router.md) for the exact cases. -## Common Patterns +## Join chains into a pipeline -### Transcription Pipeline +An egress list feeds the next chain when its name matches that chain's ingress list. Only the id moves. Each stage works on the same Redis body. ```yaml chains: - transcription: + stage_transcribe: links: - - deepgram_link: - model: nova-2 - diarize: true - storages: - - postgres + - transcribe_openai ingress_lists: - - audio_input + - raw_audio egress_lists: - transcribed - enabled: 1 -``` - -### Analysis Pipeline -```yaml -chains: - analysis: + stage_analyze: links: - - analyze: - model: gpt-4 - prompt: | - Analyze this conversation and provide: - 1. Summary - 2. Key topics - 3. Action items - 4. Sentiment + - summarize + - label_sales storages: - - postgres - - elasticsearch + - archive ingress_lists: - transcribed - egress_lists: - - analyzed - enabled: 1 ``` -### Multi-Stage Pipeline +The first stage has no storage, so the vCon exists only in Redis until the second stage saves it. The TTL set at intake covers the whole pipeline. See [body TTLs](../concepts/vcon-lifecycle.md#track-the-body-ttl). -```yaml -chains: - stage1_transcribe: - links: - - deepgram_link - storages: - - redis_storage - ingress_lists: - - raw_audio - egress_lists: - - stage2_input - enabled: 1 - - stage2_analyze: - links: - - analyze - - detect_engagement - storages: - - redis_storage - ingress_lists: - - stage2_input - egress_lists: - - stage3_input - enabled: 1 - - stage3_store: - links: - - tag - storages: - - postgres - - s3 - ingress_lists: - - stage3_input - enabled: 1 -``` - -### Conditional Processing +An egress list that no chain reads waits for `GET /vcon/egress`, which pops from the tail, so the newest ids come out first. A remote server can pull the same list with a [follower](yaml-configuration.md#pull-from-another-server). -```yaml -chains: - triage: - links: - - check_and_tag: - rules: - - condition: duration > 300 - tag: long_call - - condition: has_escalation - tag: escalated - - tag_router: - rules: - - tag: escalated - queue: urgent_review - - tag: long_call - queue: detailed_analysis - storages: - - redis_storage - ingress_lists: - - incoming - enabled: 1 -``` +## Store a vCon with no links -### Archive-Only +Use an empty `links` list to save or forward without running links. The key must be present. A chain with no `links` key sends every vCon to the dead letter queue. ```yaml chains: - archive: - links: [] # No processing + archive_only: + links: [] storages: - - s3: - s3_path: archive/ + - archive ingress_lists: - archive_input - enabled: 1 -``` - -### Sampling for QA - -```yaml -chains: - qa_sample: - links: - - sampler: - rate: 0.05 # 5% sample - - tag: - tags: [qa_review] - storages: - - postgres - ingress_lists: - - all_calls - egress_lists: - - qa_queue - enabled: 1 -``` - -## Error Handling - -### Dead Letter Queue - -When processing fails, vCons go to the Dead Letter Queue: - -``` -DLQ:{ingress_list_name} ``` -Monitor and reprocess: +## Transcribe a recording -```bash -# View DLQ contents -curl "http://api/dlq?ingress_list=main_input" \ - -H "x-conserver-api-token: $TOKEN" +`transcribe` acts only on dialogs with `type` of `recording`. The text dialog in the [quick start](../getting-started/quick-start.md) passes through unchanged and counts as a success. This walkthrough needs an OpenAI key and an audio file at a URL. -# Reprocess DLQ -curl -X POST "http://api/dlq/reprocess?ingress_list=main_input" \ - -H "x-conserver-api-token: $TOKEN" -``` +Write this `config.yml`: -### Tracer Integration +```yaml +links: + transcribe: + module: links.transcribe + options: + vendor: openai + vendor_options: + OPENAI_API_KEY: your-openai-key -Use tracers to track processing: +storages: + file: + module: storage.file + options: + path: /data/vcons -```yaml chains: - audited_chain: + transcribe_chain: links: - transcribe - - analyze storages: - - postgres - tracers: - - jlinc # Audit trail + - file ingress_lists: - - regulated_input + - transcribe_input enabled: 1 ``` -## Best Practices +Set the audio URL and its hash. The worker downloads the file, so the URL must be reachable from inside the `conserver` container, where `localhost` means the container. A vCon that refers to external media carries both `url` and `content_hash`. -### 1. Keep Chains Focused +```bash +export AUDIO_URL=https://your-host/recordings/call.wav +export CONTENT_HASH=sha512-$(curl -fsS "$AUDIO_URL" | openssl dgst -sha512 -binary \ + | openssl base64 -A | tr '+/' '-_' | tr -d '=') +export VCON_UUID=$(uuidgen | tr 'A-Z' 'a-z') +export NOW=$(date -u +%Y-%m-%dT%H:%M:%SZ) +``` -Each chain should have a clear purpose: +Post a vCon with a recording dialog. Set `duration` to the real length in seconds. A dialog below the vendor's `minimum_duration` is skipped with no error. -```yaml -# Good: Single responsibility -chains: - transcription: - links: [deepgram_link] - ... - - analysis: - links: [analyze, tag] - ... - -# Avoid: Too many responsibilities -chains: - everything: - links: [transcribe, analyze, tag, webhook, email, archive] - ... +```bash +curl -X POST "http://localhost:8000/api/vcon?ingress_lists=transcribe_input" \ + -H "Content-Type: application/json" \ + -H "x-conserver-api-token: $TOKEN" \ + -d '{ + "vcon": "0.4.0", + "uuid": "'"$VCON_UUID"'", + "created_at": "'"$NOW"'", + "parties": [ + {"tel": "+15551234567", "name": "Caller"}, + {"tel": "+15559876543", "name": "Agent"} + ], + "dialog": [ + { + "type": "recording", + "start": "'"$NOW"'", + "duration": 60, + "parties": [0, 1], + "mediatype": "audio/wav", + "url": "'"$AUDIO_URL"'", + "content_hash": "'"$CONTENT_HASH"'" + } + ] + }' ``` -### 2. Use Meaningful Names +This vCon has no `lawful_basis` attachment, and the server does not add one. See [lawful basis](../concepts/lawful-basis.md). -```yaml -# Good -chains: - customer_support_transcription: - ingress_lists: [support_calls] - ... +Read the transcript once the chain has run: -# Avoid -chains: - chain1: - ingress_lists: [list1] - ... +```bash +curl -s "http://localhost:8000/api/vcon/$VCON_UUID" \ + -H "x-conserver-api-token: $TOKEN" \ + | jq -r '.analysis[] | select(.type == "transcript") | .body.text' ``` -### 3. Plan Storage Strategy +No output means no transcript yet. A failed download takes about a minute to reach `DLQ:transcribe_input`. See the [dead letter queue](../operations/dead-letter-queue.md). -```yaml -# Hot data: Fast access -storages: - - postgres # Queries - - elasticsearch # Search +Vendors differ in how they find the audio and where they put the text: -# Cold data: Archive -storages: - - s3 # Long-term storage -``` +| Vendor | Reads the audio from | Text in the analysis body | +|---|---|---| +| `openai` | `url` only | `body.text` | +| `deepgram` | `url` only | `body.transcript` | +| `groq` | `url` or an inline `body` | `body.text` | +| `hugging_face` | `url` or an inline `body` | Depends on the endpoint. See [transcript text](../reference/links/index.md#point-analysis-at-the-transcript-text) | -### 4. Test Chains Individually +## Move to the current transcribe link -```yaml -# Development chain for testing -chains: - test_chain: - links: - - my_new_link - storages: - - redis_storage - ingress_lists: - - test_input - enabled: 1 -``` +The vendor modules `links.deepgram_link`, `links.groq_whisper`, `links.hugging_face_whisper` and `links.openai_transcribe` are deprecated. The worker redirects them to `links.transcribe` and logs one warning per module. New chains should name `links.transcribe` with a `vendor`. See the [transcribe reference](../reference/links/transcribe.md). + +## Handle a failure -## Troubleshooting +| Failure | Result | Recovery | +|---|---|---| +| A link or `before_processing` raises | Id goes to `DLQ:`. No egress or storage | `POST /dlq/reprocess` reruns the whole chain | +| Chain names a link missing from `links` | Same as above, with `KeyError` | Fix the config, then replay | +| A storage save raises | Id goes to `DLQ:storage:`. Other backends and egress are unaffected | `POST /dlq/storage/reprocess` repeats the save only | +| A tracer raises | Logged, and the chain continues, unless the tracer sets `dlq_vcon_on_error` | As for a link | -### Chain Not Processing +The [dead letter queue guide](../operations/dead-letter-queue.md) and [storage recovery](../operations/storage-recovery.md) give the steps. -1. Check `enabled: 1` -2. Verify ingress list matches submission -3. Check for DLQ entries -4. Review worker logs +## Add tracers -### Slow Processing +Tracers run for every link in every chain, from the top-level `tracers` key. A `tracers` list inside a chain has no effect. See [tracers in YAML](yaml-configuration.md#add-tracers) and the [JLINC tracer](../reference/tracers/jlinc.md). -1. Review link complexity -2. Check external API latency -3. Enable parallel storage -4. Scale workers +!!! warning "Remove an empty tracers key" + A `tracers:` key with nothing under it loads as `None`. The worker then raises `TypeError` before the first link, and each vCon on a chain with links goes to the dead letter queue. `example_config.yml` ships in this state, with its entries commented out. Delete the key or give it an entry. -### Missing Output +## Troubleshoot a chain -1. Check link isn't filtering (`return None`) -2. Verify storage configuration -3. Check egress list names +| Symptom | Check | +|---|---| +| Nothing runs | The list name matches the submission. Another chain defined later may own the list. Worker logs may show `No ingress lists configured` | +| Every vCon reaches the DLQ | An empty `tracers` key, a missing `links` key, a link with no `options`, or a name missing from `links` | +| No storage or egress output | A link halted the chain. Look for `halted chain processing` in the logs | +| A change has no effect | [Reload timing](yaml-configuration.md#plan-for-reloads) differs by section | +| Links report a missing vCon | The body expired while the id waited | +| Chains run slowly | See [workers](workers.md) for concurrency and queue depth | diff --git a/docs/configuration/egress-compatibility.md b/docs/configuration/egress-compatibility.md index c6039a9d..df9d3010 100644 --- a/docs/configuration/egress-compatibility.md +++ b/docs/configuration/egress-compatibility.md @@ -1,78 +1,79 @@ -# Egress Format Compatibility +# Egress format compatibility -The conserver normalizes every vCon to the current spec version (`vcon: "0.4.0"`) -internally. Some deployments have downstream consumers (analytics pipelines, -indexes, BI tooling) that were built against an older vCon schema and cannot yet -be migrated. The **egress format compatibility** setting lets a deployment emit a -legacy vCon format to its external consumers, without changing the canonical -representation used inside the pipeline. +The server keeps every vCon on the current spec, `vcon: "0.4.0"`. Some downstream consumers still expect an older schema. `EGRESS_FORMAT_VERSION` lets a deployment send those consumers the old format while the pipeline stays on the current one. -## How it works +![Flow from the canonical vCon in Redis through the egress points and the to_legacy steps](../diagrams/D11-egress-compatibility.svg) -A single converter (`lib.vcon_egress_compat.to_legacy`) downgrades an outgoing -payload to a target legacy version. It is the inverse of the read/write -normalization the conserver applies to bring legacy producers up to the current -spec, so a downgraded payload that is later re-ingested normalizes back up -cleanly. +## Turn on the legacy format -The behavior is controlled by one deployment-wide setting, -`EGRESS_FORMAT_VERSION`. Every **egress point** consults it: +Set the variable for both `api` and `conserver`, then restart them: -- the `webhook` link -- the `postgres`, `s3`, and `elasticsearch` storage backends -- the API read endpoints (`GET /vcon/{uuid}`, `GET /vcons`) +```bash +EGRESS_FORMAT_VERSION=0.0.1 +``` -The **canonical in-pipeline representation is never affected**: the Redis cache -and everything links read during processing always stay on the current spec. -Only the data that leaves the system is converted. +`0.0.1` is the only supported value. Leave the variable unset or empty to emit the current spec. -## Enabling it +The setting covers the whole deployment. There is no per-link or per-adapter option, and no way to serve one API caller the current format and another the legacy format. Use it only when every consumer of an egress point expects the legacy schema. -Set the `EGRESS_FORMAT_VERSION` environment variable to a supported legacy -version string. Leave it unset for the default behavior (current spec emitted -everywhere, byte-identical to a deployment without this feature). +## Check the egress points -```bash -EGRESS_FORMAT_VERSION=0.0.1 -``` +`lib.vcon_egress_compat.to_configured_legacy` does the conversion. These callers use it: + +| Egress point | Process | +|---|---| +| `webhook` link | `conserver` | +| `postgres`, `s3` and `elasticsearch` storage adapters | `conserver` | +| `GET /vcon/{uuid}` and `GET /vcons` | `api` | + +Everything else keeps the current spec: + +- Redis and all link processing. +- The other storage adapters, including `mongo`, `file` and the `webhook` storage adapter. Only the `webhook` link converts. +- Egress lists, which carry vCon UUIDs and no vCon body. + +## Review the field changes + +For `0.0.1`, `to_legacy` works on a deep copy and makes these changes: + +| Current spec | Legacy `0.0.1` | Scope | +|---|---|---| +| `vcon: "0.4.0"` | `vcon: "0.0.1"` | Top level | +| `amended` | `appended` | Top level | +| `critical` | `must_support` | Top level, dialog, analysis, attachments | +| `schema` | `schema_version` | Dialog, analysis, attachments | +| `mediatype` | `mimetype` | Dialog, analysis, attachments | +| `purpose` | `type` | Attachments, only when `type` is absent | +| `encoding: "json"` | `encoding: "none"`, with the body as a native value | Analysis, attachments | +| Keys absent | `group: []`, `redacted: {}`, `appended: null` | Top level, added only when missing | + +A few rules decide the edge cases: + +- When an entry carries both the current and the legacy name, the legacy value stays and the current name goes. Attachments differ for `purpose` and `type`: an attachment with both keeps both. +- A body under `encoding: "json"` is usually already a JSON value, so only `encoding` changes. A string body is parsed first. A string that is not valid JSON stays as it is, with `encoding: "json"`. +- Dialog bodies are not touched. +- Other fields, such as extension keys, pass through unchanged. + +## Carry lawful basis attachments + +A `lawful_basis` attachment goes through the same conversion as any other attachment. Its `purpose` becomes `type` when `type` is absent, its body keeps its content, and a JSON body changes `encoding` as above. + +The conversion carries the attachment and does nothing else with it. It does not read, check or create a lawful basis. See [lawful basis](../concepts/lawful-basis.md). + +## Handle an unsupported version + +`to_legacy` raises `ValueError` for any other version string, at the moment of egress and not at startup. The result depends on the egress point: + +| Egress point | Result | +|---|---| +| `webhook` link | The link fails and the vCon moves to the ingress dead letter queue | +| Storage adapter | The write fails and the vCon moves to `DLQ:storage:` | +| API read | HTTP 500 | + +See the [dead letter queue](../operations/dead-letter-queue.md). + +## Read legacy data from storage + +A converted copy returns to the current spec when the server reads it back. On a Redis miss, `VconRedis.get_vcon` and the API read path both load from storage, rename the fields up, stamp `vcon: "0.4.0"` and cache the result. The canonical copy in Redis stays on the current spec. -An unsupported version string raises an error at egress time rather than -emitting a wrong payload. - -## Supported version mappings - -| Target | Status | -| --- | --- | -| `0.0.1` | Supported | - -### Field deltas applied for `0.0.1` - -| Current spec (0.4.0) | Legacy (0.0.1) | Scope | -| --- | --- | --- | -| `vcon: "0.4.0"` | `vcon: "0.0.1"` | top level | -| `amended` | `appended` | top level | -| `critical` | `must_support` | top level + dialog / analysis entries | -| `purpose` | `type` | attachments (only when `type` is absent) | -| `mediatype` | `mimetype` | dialog + attachments | -| `schema` | `schema_version` | dialog + analysis | -| `body` as JSON string + `encoding: "json"` | native object/array + `encoding: "none"` | analysis + attachments | -| empty `group` / `redacted` omitted | re-added as `group: []`, `redacted: {}`, `appended: null` | top level | - -The JSON-body conversion re-inflates analysis and attachment bodies that the -spec write-path serializes to strings. Dialog bodies are not serialized on -write and are left unchanged. - -## Known gaps and notes - -- **Deployment-wide:** every egress point emits the same configured version. -- **API consumers:** while the setting is on, the API read endpoints return the - legacy format to all callers. Use it only when every API consumer expects the - legacy schema. -- **Attachment `type` vs. `purpose`:** for attachments that already carry a - `type` value (e.g. the `lawful_basis` extension, which uses `type` as its - value), the value is preserved rather than overwritten. -- **Custom/extension fields** (e.g. application-specific top-level keys or - `vendor_schema`) are passed through unchanged in both directions. -- **Coverage:** the supported delta set reflects the differences between the - current spec and `0.0.1`. New downstream requirements should be validated - against the target schema and added here before relying on them. +A [follower](yaml-configuration.md#pull-from-another-server) that pulls from a server with this setting on receives the legacy format and writes it to Redis as it arrives. `VconRedis.get_vcon` renames the fields on read. diff --git a/docs/configuration/environment-variables.md b/docs/configuration/environment-variables.md index 617e2d31..2ae688c9 100644 --- a/docs/configuration/environment-variables.md +++ b/docs/configuration/environment-variables.md @@ -1,544 +1,162 @@ -# Environment Variables +# Configure the server with environment variables -Complete reference for all environment variables used by vCon Server. +Environment variables set how the server connects, scales and reports. The [YAML file](yaml-configuration.md) sets what it does to each vCon. -## Core Settings +This page groups the variables by task. The [environment reference](../reference/environment.md) is generated from the code and lists every variable, with its default, type and the file that reads it. -### REDIS_URL +## Load variables from a .env file -Redis connection URL for queues and caching. +`common/settings.py` calls `dotenv.load_dotenv()` on import, so a `.env` file works the same as exported variables. Docker Compose passes the same file to `api` and `conserver` through `env_file`. -| Property | Value | -|----------|-------| -| **Required** | Yes | -| **Default** | `redis://localhost` | -| **Format** | `redis://[user:password@]host[:port][/database]` | +Start from the example: ```bash -# Local Redis -REDIS_URL=redis://localhost:6379 - -# Docker Redis -REDIS_URL=redis://redis:6379 - -# Redis with authentication -REDIS_URL=redis://user:password@redis-host:6379/0 - -# Redis Cluster -REDIS_URL=redis://redis-cluster:6379 -``` - -### HOSTNAME - -Server hostname used for generating URLs. - -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `http://localhost:8000` | - -```bash -HOSTNAME=https://api.example.com -``` - -### ENV - -Environment identifier for logging and behavior. - -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `dev` | -| **Options** | `dev`, `staging`, `production` | - -```bash -ENV=production -``` - -### LOG_LEVEL - -Logging verbosity level. - -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `DEBUG` | -| **Options** | `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL` | - -```bash -LOG_LEVEL=INFO -``` - -### LOGGING_CONFIG_FILE - -Path to logging configuration file. - -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `server/logging.conf` | - -```bash -# Production (JSON logging) -LOGGING_CONFIG_FILE=server/logging.conf - -# Development (simple logging) -LOGGING_CONFIG_FILE=server/logging_dev.conf -``` - -### CONSERVER_CONFIG_FILE - -Path to YAML configuration file. - -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `./example_config.yml` | - -```bash -CONSERVER_CONFIG_FILE=/etc/vcon/config.yml -``` - -### API_ROOT_PATH - -Root path prefix for API endpoints. - -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `/api` | - -```bash -API_ROOT_PATH=/api/v1 -``` - -### TICK_INTERVAL - -Processing tick interval in milliseconds. - -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `5000` | - -```bash -TICK_INTERVAL=1000 # Check queues every second -``` - -## Authentication - -### CONSERVER_API_TOKEN - -API authentication token for all endpoints. - -| Property | Value | -|----------|-------| -| **Required** | Yes (for production) | -| **Default** | None | - -```bash -# Single token -CONSERVER_API_TOKEN=your-secure-token-here - -# Generate secure token -openssl rand -hex 32 -``` - -### CONSERVER_API_TOKEN_FILE - -Path to file containing API tokens (one per line). - -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | None | - -```bash -CONSERVER_API_TOKEN_FILE=/etc/vcon/api_tokens.txt -``` - -File format: -``` -token-one-here -token-two-here -admin-token-here -``` - -### CONSERVER_HEADER_NAME - -HTTP header name for API token. - -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `x-conserver-api-token` | - -```bash -CONSERVER_HEADER_NAME=Authorization -``` - -## Worker Configuration - -### CONSERVER_WORKERS - -Number of worker **processes** to spawn. Each worker is a separate OS process that polls Redis with BLPOP and processes vCons independently. - -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `1` | -| **Minimum** | `1` | - -```bash -# Single worker (default) -CONSERVER_WORKERS=1 - -# Multi-worker mode -CONSERVER_WORKERS=4 -``` - -!!! tip "Sizing Workers" - Scale `CONSERVER_WORKERS` based on CPU cores for CPU-bound workloads. - For I/O-bound workloads, prefer raising `CONSERVER_VCON_CONCURRENCY` first — - it gives you parallelism without the per-process memory cost. - -### CONSERVER_VCON_CONCURRENCY - -Maximum number of in-flight vCons **per worker process**. When > 1, each worker dispatches popped vCons to an internal `ThreadPoolExecutor` of this size, so multiple chains run in parallel inside a single worker. - -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `1` (strict serial — original behaviour) | -| **Minimum** | `1` | - -```bash -# Strict serial (default) -CONSERVER_VCON_CONCURRENCY=1 - -# Up to 8 vCons running in parallel inside each worker -CONSERVER_VCON_CONCURRENCY=8 +cp .env.example .env ``` -!!! info "Total parallelism" - `CONSERVER_WORKERS` and `CONSERVER_VCON_CONCURRENCY` multiply: - - ``` - max parallel vCons = CONSERVER_WORKERS × CONSERVER_VCON_CONCURRENCY - ``` - - For example, `CONSERVER_WORKERS=4` with `CONSERVER_VCON_CONCURRENCY=8` allows up to **32 vCons** in flight simultaneously. See [Worker Configuration](workers.md) for sizing guidance. - -!!! warning "Thread safety" - Concurrency > 1 runs chain links in threads. Link code must be thread-safe and should release the GIL during I/O (standard HTTP/DB clients do). Modules that hold the GIL across long CPU work will block other in-flight vCons in the same worker. - -### CONSERVER_PARALLEL_STORAGE - -Enable parallel writes to storage backends. - -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `true` | -| **Options** | `true`, `false`, `1`, `0`, `yes`, `no` | +This set is enough for the Compose stack: ```bash -# Enable parallel storage (default) -CONSERVER_PARALLEL_STORAGE=true - -# Disable for sequential writes -CONSERVER_PARALLEL_STORAGE=false +REDIS_URL=redis://redis +CONSERVER_CONFIG_FILE=/app/config.yml +LOGGING_CONFIG_FILE=common/logging_dev.conf +CONSERVER_API_TOKEN=replace-with-a-long-random-value ``` -### CONSERVER_START_METHOD +Watch for these behaviours: -Multiprocessing start method for workers. +- Each process reads its variables at startup. After a change, run `docker compose up -d api conserver`. `docker compose restart` does not reread `.env`. +- An empty value is not the same as unset. `CONSERVER_CONFIG_FILE=` gives an empty path, not the default, and the server fails when it opens the file. `.env.example` ships that line empty, so fill it in. +- An empty value on an integer variable, such as `CONSERVER_WORKERS=`, raises `ValueError` on import. +- `.env.example` sets `LOGGING_CONFIG_FILE=server/logging_dev.conf`, and the repo has no `server/` folder. Use `common/logging_dev.conf`, or remove the line to use `common/logging.conf`. -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | Platform default | -| **Options** | `fork`, `spawn`, `forkserver` | +## Connect the server to Redis -```bash -# Memory-efficient (Unix only) -CONSERVER_START_METHOD=fork - -# Safer, cross-platform -CONSERVER_START_METHOD=spawn - -# Hybrid approach -CONSERVER_START_METHOD=forkserver -``` - -| Method | Memory | Startup | Safety | Platform | -|--------|--------|---------|--------|----------| -| `fork` | Low (COW) | Fast | Lower | Unix only | -| `spawn` | Higher | Slower | Higher | All | -| `forkserver` | Medium | Medium | Medium | Unix | - -## AI Service Keys - -### DEEPGRAM_KEY - -Deepgram API key for transcription. - -| Property | Value | -|----------|-------| -| **Required** | If using Deepgram | -| **Default** | None | +`REDIS_URL` is the one connection every process needs. The default is `redis://localhost`. ```bash -DEEPGRAM_KEY=your-deepgram-api-key -``` +# Service on the Compose network +REDIS_URL=redis://redis -### OPENAI_API_KEY - -OpenAI API key for analysis and transcription. - -| Property | Value | -|----------|-------| -| **Required** | If using OpenAI | -| **Default** | None | - -```bash -OPENAI_API_KEY=sk-your-openai-api-key +# External Redis with a password and a database number +REDIS_URL=redis://:password@redis-host:6379/0 ``` -### GROQ_API_KEY +The Docker entrypoint, `docker/wait_for_redis.sh`, pings this URL before it starts the service. With `REDIS_URL` unset or empty it skips the wait. -Groq API key for Whisper transcription. +## Point the server at its files -| Property | Value | -|----------|-------| -| **Required** | If using Groq | -| **Default** | None | +| Variable | Use | +|---|---| +| `CONSERVER_CONFIG_FILE` | Path to the [YAML configuration](yaml-configuration.md). Compose mounts `./config.yml` at `/app/config.yml`, so use that path there. `POST /config` needs this variable set, because it does not use the `./example_config.yml` default | +| `LOGGING_CONFIG_FILE` | Path to a Python logging config. See [logging](../operations/logging.md) | -```bash -GROQ_API_KEY=gsk-your-groq-api-key -``` +`LOG_LEVEL` has no effect. Set levels in the logging config file. -## Cache Settings +## Protect the API with keys -### VCON_REDIS_EXPIRY +| Variable | Use | +|---|---| +| `CONSERVER_API_TOKEN` | One API key | +| `CONSERVER_API_TOKEN_FILE` | Path to a file of keys, one per line, added to the key above. The API reads it once at startup | +| `CONSERVER_HEADER_NAME` | Header that carries the key. The default is `x-conserver-api-token` | -Default TTL (Time-To-Live) for vCons stored in Redis (seconds). +With no key set, the main API routes are open. Keys for `POST /vcon/external-ingress` live in the `ingress_auth` section of the YAML file. See [authentication](authentication.md). -This expiry applies to: +## Run the API behind a proxy -- **vCons created via POST `/vcon`**: New vCons are stored with this TTL -- **vCons created via POST `/vcon/external-ingress`**: External submissions use this TTL -- **vCons synced from storage backends**: When a vCon is fetched from storage and cached in Redis +`API_ROOT_PATH` sets the FastAPI `root_path`, default `/api`, for a proxy that strips that prefix. It does not add the prefix to routes, so the app still serves `/vcon` and `/health`. -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `3600` (1 hour) | +`CONSERVER_EXTERNAL_PORT` sets the host port Compose publishes for the `api` service, default `8000`. See [ports and services](../reference/ports.md). -```bash -VCON_REDIS_EXPIRY=7200 # 2 hours -``` +## Tune worker throughput -!!! warning "Cache Expiry Behavior" - vCons will be automatically removed from Redis after this TTL expires. - To ensure long-term retention, configure storage backends (S3, PostgreSQL, etc.) - in your processing chains to persist vCons before they expire from Redis. +| Variable | Default | Use | +|---|---|---| +| `CONSERVER_WORKERS` | `1` | Worker processes. Suits CPU-bound chains | +| `CONSERVER_VCON_CONCURRENCY` | `1` | vCons in flight per worker, in a thread pool. Suits chains that wait on the network | +| `CONSERVER_PARALLEL_STORAGE` | `true` | Writes to a chain's storage backends at the same time when it has more than one | +| `CONSERVER_START_METHOD` | platform default | `fork`, `spawn` or `forkserver`. Used only when `CONSERVER_WORKERS` is above 1 | -### VCON_INDEX_EXPIRY +At most `CONSERVER_WORKERS` times `CONSERVER_VCON_CONCURRENCY` vCons run at once. [Workers](workers.md) covers sizing. -Index expiration time in seconds. +## Set Redis retention -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `86400` (24 hours) | +| Variable | Default | Controls | +|---|---|---| +| `VCON_REDIS_EXPIRY` | `3600` | TTL on vCons written by `POST /vcon` and `POST /vcon/external-ingress`, and on vCons cached back from storage | +| `VCON_DLQ_EXPIRY` | `604800` | TTL once a vCon reaches a dead letter queue | +| `VCON_CONTEXT_EXPIRY` | `86400` | TTL on the ingress context stored beside a queue entry | +| `VCON_INDEX_EXPIRY` | `86400` | TTL on the party search keys the API writes | +| `VCON_STORAGE_FALLBACK_ENABLED` | `true` | Whether a Redis miss in `VconRedis.get_vcon` tries the storage backends | +| `VCON_SORTED_SET_NAME` | `vcons` | Redis sorted set that orders vCons by time | -```bash -VCON_INDEX_EXPIRY=172800 # 48 hours -``` +Set `VCON_REDIS_EXPIRY` above your longest queue wait. A vCon that expires in the queue, with no copy in a storage backend, comes back as `None` from `VconRedis.get_vcon`. -### VCON_CONTEXT_EXPIRY +`VCON_DLQ_EXPIRY` works differently on the two dead letter queues. The ingress DLQ sets the TTL to this value. The storage DLQ only raises a lower TTL. `0` leaves the TTL as it is on both. See the [dead letter queue](../operations/dead-letter-queue.md). -Context data expiration for ingress operations (seconds). +## Give links their vendor keys -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `86400` (24 hours) | +Most vendor keys belong in link options in the YAML file, not in the environment. The YAML loader does not expand `${VAR}`, so write the value itself. See [links](yaml-configuration.md#add-processing-links). -```bash -VCON_CONTEXT_EXPIRY=43200 # 12 hours -``` +Two variables act as defaults for a link option: -### VCON_DLQ_EXPIRY +| Variable | Link | Option it fills | +|---|---|---| +| `GROQ_API_KEY` | `groq_whisper`, also through `links.transcribe` with `vendor: groq` | `API_KEY` | +| `OPENAI_API_KEY` | `detect_engagement` | `OPENAI_API_KEY` | -TTL for vCons moved to the Dead Letter Queue (seconds). +The link reads the variable when its module loads. Other links that use OpenAI take the key from their own options. `DEEPGRAM_KEY` in the environment has no effect, so set `DEEPGRAM_KEY` in the link options. -When a vCon fails processing and is moved to the DLQ, its TTL is extended to this value to ensure operators have sufficient time to investigate failures. This prevents vCons from expiring before they can be reviewed and reprocessed. +## Emit a legacy vCon format -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `604800` (7 days) | +Set `EGRESS_FORMAT_VERSION=0.0.1` for downstream consumers that still need the old schema. Set it on both `api` and `conserver`. See [egress format compatibility](egress-compatibility.md). -```bash -# Extend DLQ retention to 14 days -VCON_DLQ_EXPIRY=1209600 +## Export metrics and traces -# Disable DLQ expiry (vCons persist indefinitely) -VCON_DLQ_EXPIRY=0 -``` +| Variable | Use | +|---|---| +| `OTEL_EXPORTER_OTLP_ENDPOINT` | OTLP endpoint. Unset or empty, the metric helpers do nothing | +| `OTEL_SERVICE_NAME` | `service.name` on metrics. Compose sets `api` and `conserver` | +| `OTEL_METRIC_EXPORT_INTERVAL` | Metric export interval in milliseconds, default `5000` | -!!! tip "DLQ Retention Strategy" - The default 7-day retention gives operators time to investigate and reprocess failed vCons. Set to `0` if you want DLQ vCons to persist indefinitely (useful when using persistent storage backends). +The `api` and `conserver` Compose commands run under `opentelemetry-instrument`, which also takes `OTEL_EXPORTER_OTLP_PROTOCOL`, `OTEL_EXPORTER_OTLP_INSECURE` and `OTEL_EXPORTER_OTLP_HEADERS`. -### VCON_SORTED_SET_NAME +The server's own metrics always use the OTLP gRPC exporter, and `OTEL_EXPORTER_OTLP_PROTOCOL` does not change that. An endpoint that accepts only `http/protobuf`, such as the Langfuse examples in `.env.example`, suits the auto-instrumented traces and not those metrics. -Redis sorted set name for vCon indexing. +The [metrics reference](../reference/metrics.md) lists the metric names. [Monitoring](../operations/monitoring.md) covers the setup. -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `vcons` | +## Report errors to Sentry -```bash -VCON_SORTED_SET_NAME=vcon_index -``` +Set `SENTRY_DSN` to turn on Sentry. `ENV` must then be set too, because `common/lib/error_tracking.py` reads it directly and raises `KeyError` without it. The `dev` default in `settings` does not apply there. -### VCON_SORTED_FORCE_RESET +`VCON_SERVER_GIT_COMMIT`, when set, becomes the Sentry release. -Force reset sorted set on startup. +## Configure the Space and Time adapter -| Property | Value | -|----------|-------| -| **Required** | No | -| **Default** | `true` | +The `spaceandtime` storage adapter reads its settings from the environment, not from YAML options. -```bash -VCON_SORTED_FORCE_RESET=false -``` +| Variable | Use | +|---|---| +| `SXT_API_KEY` | API key | +| `SXT_VCON_TABLENAME` | Table name | +| `SXT_VCON_TABLE_WRITE_BISCUI` | Write biscuit. The code reads this exact name, with no final `T` | -## Vector Database +## Read the build information -### WEVIATE_HOST +`VCON_SERVER_VERSION`, `VCON_SERVER_GIT_COMMIT` and `VCON_SERVER_BUILD_TIME` are Docker build arguments that the images keep as variables. `GET /version` returns them. Without them the values are `dev` and `unknown`. -Weaviate vector database host. +## Skip the variables with no effect -| Property | Value | -|----------|-------| -| **Required** | If using Weaviate | -| **Default** | `localhost:8000` | +The code reads these variables and then never uses the value. Older guides mention some of them. -```bash -WEVIATE_HOST=weaviate:8080 -``` - -### WEVIATE_API_KEY - -Weaviate API key. - -| Property | Value | -|----------|-------| -| **Required** | If using Weaviate with auth | -| **Default** | None | - -```bash -WEVIATE_API_KEY=your-weaviate-key -``` - -## Build Information - -These are typically set at build time: - -### VCON_SERVER_VERSION - -Server version in CalVer format. - -```bash -VCON_SERVER_VERSION=2024.01.15 -``` - -### VCON_SERVER_GIT_COMMIT - -Git commit hash of the build. - -```bash -VCON_SERVER_GIT_COMMIT=a1b2c3d -``` - -### VCON_SERVER_BUILD_TIME - -ISO timestamp of the build. - -```bash -VCON_SERVER_BUILD_TIME=2024-01-15T10:30:00Z -``` - -## Complete Example - -```bash -# ============================================================================= -# vCon Server Environment Configuration -# ============================================================================= - -# Core Settings -REDIS_URL=redis://redis:6379 -HOSTNAME=https://api.example.com -ENV=production -LOG_LEVEL=INFO -CONSERVER_CONFIG_FILE=/etc/vcon/config.yml - -# Authentication -CONSERVER_API_TOKEN=your-secure-production-token -CONSERVER_HEADER_NAME=x-conserver-api-token - -# Worker Configuration -CONSERVER_WORKERS=4 -CONSERVER_PARALLEL_STORAGE=true -CONSERVER_START_METHOD=fork - -# AI Services -DEEPGRAM_KEY=your-deepgram-key -OPENAI_API_KEY=your-openai-key -GROQ_API_KEY=your-groq-key - -# Cache Settings -VCON_REDIS_EXPIRY=3600 -VCON_INDEX_EXPIRY=86400 -VCON_CONTEXT_EXPIRY=86400 - -# Processing -TICK_INTERVAL=5000 -``` - -## Environment-Specific Configurations - -### Development - -```bash -ENV=dev -LOG_LEVEL=DEBUG -LOGGING_CONFIG_FILE=server/logging_dev.conf -CONSERVER_WORKERS=1 -CONSERVER_API_TOKEN=dev-token -``` - -### Staging - -```bash -ENV=staging -LOG_LEVEL=INFO -CONSERVER_WORKERS=2 -CONSERVER_API_TOKEN=staging-token -``` - -### Production - -```bash -ENV=production -LOG_LEVEL=INFO -LOGGING_CONFIG_FILE=server/logging.conf -CONSERVER_WORKERS=8 -CONSERVER_PARALLEL_STORAGE=true -CONSERVER_START_METHOD=fork -``` +| Variable | Note | +|---|---| +| `DEEPGRAM_KEY` | Set the key in link options | +| `HOSTNAME` | | +| `LOG_LEVEL` | Set levels in the logging config file | +| `TICK_INTERVAL` | | +| `UUID8_DOMAIN_NAME` | | +| `VCON_SORTED_FORCE_RESET` | | +| `VCON_STORAGE` | The API defines a Peewee model on it, and nothing uses the model | +| `WEVIATE_API_KEY`, `WEVIATE_HOST` | Spelled this way in the code | diff --git a/docs/configuration/index.md b/docs/configuration/index.md index 29fcbd99..f63e0bce 100644 --- a/docs/configuration/index.md +++ b/docs/configuration/index.md @@ -1,47 +1,31 @@ -# Configuration Guide +# Configuration guide -vCon Server uses a two-tier configuration system: +vCon Server reads two kinds of settings: -1. **Environment Variables**: Server-level settings, API keys, worker configuration -2. **YAML Configuration**: Processing pipelines, storage backends, chains, and links +| Source | Holds | Reference | +|---|---|---| +| Environment variables, usually in `.env` | Redis, API keys, workers, logging, telemetry | [Environment reference](../reference/environment.md) and [environment guide](environment-variables.md) | +| YAML file, usually `config.yml` | Links, storages, tracers, chains, ingress keys, followers | [YAML configuration](yaml-configuration.md) | -## Configuration Overview +Credentials for links and storage backends go in the YAML file as `options`. The server does not expand `${VAR}` in that file. -```mermaid -flowchart TB - subgraph env [Environment Variables] - REDIS[REDIS_URL] - TOKEN[CONSERVER_API_TOKEN] - WORKERS[CONSERVER_WORKERS] - KEYS[API Keys] - end - - subgraph yaml [YAML Configuration] - CHAINS[Chains] - LINKS[Links] - STORAGE[Storages] - AUTH[Ingress Auth] - end - - ENV_FILE[.env file] --> env - CONFIG_FILE[config.yml] --> yaml - - env --> SERVER[vCon Server] - yaml --> SERVER -``` - -## Quick Configuration - -### Minimal Setup +## Start with a minimal setup **.env**: + ```bash REDIS_URL=redis://localhost:6379 CONSERVER_API_TOKEN=your-secure-token +CONSERVER_CONFIG_FILE=./config.yml ``` **config.yml**: + ```yaml +storages: + redis_storage: + module: storage.redis_storage + chains: simple_chain: links: [] @@ -49,226 +33,229 @@ chains: - redis_storage ingress_lists: - default - enabled: 1 - -storages: - redis_storage: - module: storage.redis_storage ``` -### Production Setup +## Grow into a production setup **.env**: + ```bash -# Core Settings REDIS_URL=redis://redis:6379 CONSERVER_API_TOKEN=your-production-token +CONSERVER_CONFIG_FILE=./config.yml ENV=production -LOG_LEVEL=INFO +LOGGING_CONFIG_FILE=common/logging.conf -# Worker Configuration CONSERVER_WORKERS=4 CONSERVER_PARALLEL_STORAGE=true -CONSERVER_START_METHOD=fork - -# AI Services -DEEPGRAM_KEY=your-deepgram-key -OPENAI_API_KEY=your-openai-key ``` +The logging file sets log levels. See [logging](../operations/logging.md). + **config.yml**: -```yaml -chains: - production_chain: - links: - - transcribe - - analyze - - tag - storages: - - postgres - - s3 - ingress_lists: - - production - egress_lists: - - processed - enabled: 1 +```yaml links: transcribe: - module: links.deepgram_link + module: links.transcribe options: - model: nova-2 + vendor: deepgram + vendor_options: + DEEPGRAM_KEY: your-deepgram-key + api: + model: nova-3 analyze: module: links.analyze options: + OPENAI_API_KEY: your-openai-key + analysis_type: summary model: gpt-4 - tag: + prompt: Summarize this conversation. + source: + analysis_type: transcript + text_location: body.transcript + tag_processed: module: links.tag options: - tags: [processed] + tags: + - processed storages: postgres: module: storage.postgres options: host: postgres + port: 5432 database: vcon_server + user: postgres + password: your-password s3: module: storage.s3 options: - bucket: vcon-archive -``` + aws_access_key_id: your-key-id + aws_secret_access_key: your-secret + aws_bucket: vcon-archive -## Configuration Sections - -| Section | Documentation | -|---------|---------------| -| [Environment Variables](environment-variables.md) | All environment variables with defaults | -| [YAML Configuration](yaml-configuration.md) | Complete YAML structure reference | -| [Chains and Pipelines](chains-and-pipelines.md) | How to build processing pipelines | -| [Authentication](authentication.md) | API tokens and ingress authentication | -| [Workers](workers.md) | Multi-worker and parallel storage configuration | +chains: + production_chain: + links: + - transcribe + - analyze + - tag_processed + storages: + - postgres + - s3 + ingress_lists: + - production + egress_lists: + - processed +``` -## Configuration Loading +The [link reference](../reference/links/index.md) and the [storage adapter reference](../reference/storage-adapters/index.md) list every option. -### Environment Variables +## Find the right page -Environment variables are loaded at startup from: +| Page | Covers | +|---|---| +| [Environment variables](environment-variables.md) | Choosing values | +| [YAML configuration](yaml-configuration.md) | The file structure and reload rules | +| [Chains and pipelines](chains-and-pipelines.md) | Building pipelines | +| [Egress format compatibility](egress-compatibility.md) | Sending the legacy vCon format | +| [Authentication](authentication.md) | API keys and ingress keys | +| [Workers](workers.md) | Worker processes, concurrency and parallel storage | -1. System environment -2. `.env` file in the working directory -3. Docker Compose `env_file` directive +## Understand the loading order -Priority: System environment > `.env` file +### Load order for the environment -### YAML Configuration +`common/settings.py` loads a `.env` file when it is imported. A variable already set in the process wins over the same variable in `.env`. Compose passes `.env` through `env_file`. Each process reads these values once at startup. -The YAML configuration file location is specified by: +### Location of the YAML file -```bash -CONSERVER_CONFIG_FILE=./config.yml -``` +`CONSERVER_CONFIG_FILE` gives the path. The default is `./example_config.yml`, which is a catalogue of syntax and stops the worker if you run it unchanged, so always set your own. -Default: `./example_config.yml` +The server reads the file again as it runs, so most edits need no restart. See [the reload table](yaml-configuration.md#plan-for-reloads). -### Configuration Validation +### Checks on your configuration -The server validates configuration at startup: +The server does not validate the file at startup. A link with a bad module name fails when a vCon first reaches it. To see what the server loads, run this in the conserver container: ```bash -# Check configuration -poetry run python -c "from server.config import get_config; import json; print(json.dumps(get_config(), indent=2))" +python -c "from config import get_config; import json; print(json.dumps(get_config(), indent=2))" ``` -## Configuration Best Practices - -### Security +For a manual install, prefix it with `uv run` and set `PYTHONPATH` as in [Install from source](../installation/manual-installation.md#set-the-environment). -1. **Never commit secrets** to version control -2. **Use environment variables** for sensitive data -3. **Rotate API tokens** regularly -4. **Use ingress-specific authentication** for external integrations +## Follow these practices -### Organization +- Keep `.env` and `config.yml` out of version control, because both hold secrets. +- Use a separate file for each environment. +- Name chains for what they do. +- Set `options` on every link, even as `options: {}`. +- Use [ingress keys](authentication.md#scope-a-key-to-an-ingress-list) for outside systems. +- Size workers with the [workers guide](workers.md). -1. **Separate environments** with different config files -2. **Use meaningful chain names** that describe their purpose -3. **Document custom links** with comments in YAML +## Copy a common configuration -### Performance +These fragments show the `chains` section only. Each name must match an entry you define under `links` or `storages`. -1. **Match workers to CPU cores** for I/O-bound workloads -2. **Enable parallel storage** when using multiple backends -3. **Use appropriate storage backends** for your access patterns - -## Common Configurations - -### Call Center Analytics +### Call analytics ```yaml chains: call_analytics: links: - - deepgram_link # Transcribe - - analyze # Extract insights - - detect_engagement # Measure customer engagement - - tag_router # Route by outcome + - transcribe # links.transcribe + - analyze # links.analyze + - detect_engagement # links.detect_engagement + - tag_router # links.tag_router storages: - - postgres # Queryable storage - - elasticsearch # Full-text search + - postgres + - elasticsearch ingress_lists: - call_recordings - enabled: 1 ``` -### Compliance Archive +### Long-term archive with a trace + +Tracers sit at the top level and run for every chain. A `tracers` key inside a chain is not read. See [Add tracers](yaml-configuration.md#add-tracers). ```yaml +tracers: + jlinc: + module: tracers.jlinc + options: + data_store_api_url: http://jlinc-server:9090 + data_store_api_key: replace-with-a-key + archive_api_url: http://jlinc-server:9090 + archive_api_key: replace-with-a-key + system_prefix: VCONProd + agreement_id: 00000000-0000-0000-0000-000000000000 + chains: - compliance_archive: + archive: links: - - transcribe - - check_and_tag # Apply compliance tags + - transcribe # links.transcribe + - check_and_tag # links.check_and_tag storages: - - s3 # Long-term archive - - postgres # Audit queries - tracers: - - jlinc # Audit trail + - s3 + - postgres ingress_lists: - - regulated_calls - enabled: 1 + - archive_calls ``` -### AI Knowledge Base +The tracer reports processing steps. It reads no `lawful_basis` attachment and makes no deployment compliant. See [Lawful basis](../concepts/lawful-basis.md). + +### Searchable knowledge base + +`storage.milvus` needs the `storage-milvus` dependency group, which the published images leave out. ```yaml chains: knowledge_base: links: - - transcribe - - analyze_and_label # Extract topics and entities + - transcribe # links.transcribe + - analyze_and_label # links.analyze_and_label storages: - - milvus # Vector search - - mongo # Document storage + - milvus + - mongo ingress_lists: - knowledge_ingress - enabled: 1 ``` -## Troubleshooting Configuration +## Troubleshoot a configuration -### Configuration Not Loading +### Check the file path and syntax ```bash -# Check file exists -ls -la $CONSERVER_CONFIG_FILE - -# Validate YAML syntax +ls -la "$CONSERVER_CONFIG_FILE" python -c "import yaml; yaml.safe_load(open('config.yml'))" ``` -### Environment Variables Not Set +### Check a suspect variable + +Run this where the process runs, with `PYTHONPATH` set: ```bash -# Check current values env | grep CONSERVER - -# Debug in Python -python -c "from server import settings; print(settings.REDIS_URL)" +python -c "import settings; print(settings.REDIS_URL)" ``` -### Chain Not Processing +### Trace a silent chain + +Check that the list you submit to appears in the chain's `ingress_lists`: ```yaml chains: my_chain: - enabled: 1 # Must be 1, not "true" ingress_lists: - my_list # Must match where vCons are submitted ``` -## Next Steps +The worker never reads `enabled`. Setting `enabled: 0` does not stop a chain, so remove its `ingress_lists` instead. + +## Continue with these guides -- [Environment Variables](environment-variables.md) - Complete reference -- [YAML Configuration](yaml-configuration.md) - All configuration options -- [Chains and Pipelines](chains-and-pipelines.md) - Build processing workflows +- [Environment variables](environment-variables.md) +- [YAML configuration](yaml-configuration.md) +- [Chains and pipelines](chains-and-pipelines.md) diff --git a/docs/configuration/workers.md b/docs/configuration/workers.md index 5d5b05db..42e9d10d 100644 --- a/docs/configuration/workers.md +++ b/docs/configuration/workers.md @@ -1,550 +1,125 @@ -# Worker Configuration +# Configure the workers -vCon Server supports multi-worker processing for improved throughput and parallel storage writes for faster persistence. +Workers pop vCon ids from Redis and run chains. Three environment variables shape them: -Two environment variables together determine how many vCons can be processed in parallel: - -``` -max parallel vCons = CONSERVER_WORKERS × CONSERVER_VCON_CONCURRENCY -``` - -- **`CONSERVER_WORKERS`** — number of worker **processes** (separate OS processes, each polling Redis independently). Scales CPU-bound work. -- **`CONSERVER_VCON_CONCURRENCY`** — number of in-flight vCons **per worker** (a `ThreadPoolExecutor` inside each worker). Scales I/O-bound work (LLM, transcription, webhooks, storage writes) without paying the per-process memory cost. - -A third variable, **`CONSERVER_PARALLEL_STORAGE`**, controls a separate thread pool used only for writing to multiple storage backends concurrently — it is independent of the two above. - -## Architecture Overview - -```mermaid -flowchart TB - subgraph main [Main Process] - MAIN[Main Process
Spawns and monitors workers] - end - - subgraph workers [Worker Processes] - W1[Worker 1] - W2[Worker 2] - W3[Worker 3] - WN[Worker N] - end - - subgraph redis [Redis] - Q1[Ingress Queue 1] - Q2[Ingress Queue 2] - end - - subgraph storage [Storage Layer] - S1[PostgreSQL] - S2[S3] - S3[Elasticsearch] - end - - MAIN --> W1 - MAIN --> W2 - MAIN --> W3 - MAIN --> WN - - Q1 --> |BLPOP| W1 - Q1 --> |BLPOP| W2 - Q2 --> |BLPOP| W3 - Q2 --> |BLPOP| WN - - W1 --> |Parallel Write| S1 - W1 --> |Parallel Write| S2 - W1 --> |Parallel Write| S3 -``` - -## Worker Configuration - -### CONSERVER_WORKERS - -Controls the number of worker processes. - -```bash -# Single worker (default) -CONSERVER_WORKERS=1 - -# Multi-worker mode -CONSERVER_WORKERS=4 -``` - -| Value | Mode | Use Case | -|-------|------|----------| -| `1` | Single worker | Development, low volume | -| `2-4` | Light parallel | Medium volume, limited resources | -| `4-8` | Standard parallel | Production workloads | -| `8-16` | High parallel | High-throughput systems | - -### Sizing Guidelines - -**I/O-Bound Workloads** (transcription, API calls): - -```bash -# Match CPU cores -CONSERVER_WORKERS=$(nproc) -``` - -**CPU-Bound Workloads** (local processing): - -```bash -# Leave 1 core for system -CONSERVER_WORKERS=$(($(nproc) - 1)) -``` - -**Memory-Constrained Systems**: - -```bash -# Each worker uses ~200-500MB -# For 8GB system with other services: -CONSERVER_WORKERS=4 -``` - -### CONSERVER_VCON_CONCURRENCY - -Controls how many vCons each worker process keeps in flight at once. When set above `1`, the worker dispatches each popped vCon to an internal `ThreadPoolExecutor` and back-pressures (waits before the next BLPOP) when the pool is full. - -```bash -# Strict serial — one vCon at a time per worker (default) -CONSERVER_VCON_CONCURRENCY=1 - -# Up to 8 vCons running in parallel inside each worker -CONSERVER_VCON_CONCURRENCY=8 -``` - -| Value | Behaviour | Best For | -|-------|-----------|----------| -| `1` | Strict serial — original behaviour | CPU-bound chains, debugging | -| `2-4` | Light in-process parallelism | Mixed workloads | -| `4-16` | High in-process parallelism | I/O-bound chains (LLM, transcription, webhooks) | - -#### How it combines with CONSERVER_WORKERS - -The two settings multiply: - -``` -max parallel vCons = CONSERVER_WORKERS × CONSERVER_VCON_CONCURRENCY -``` - -| Workers | Concurrency | Max parallel vCons | Notes | -|---------|-------------|--------------------|----| -| `1` | `1` | 1 | Original single-threaded behaviour | -| `4` | `1` | 4 | Multi-process only — good for CPU-bound work | -| `1` | `8` | 8 | Single-process, threaded — good for I/O-bound chains | -| `4` | `8` | 32 | Combined — high-throughput I/O-bound workloads | - -#### When to raise concurrency vs. workers - -- **Raise `CONSERVER_WORKERS`** when chains are CPU-bound (heavy local compute, audio processing without GPU offload) — more processes sidestep the Python GIL. -- **Raise `CONSERVER_VCON_CONCURRENCY`** when chains are I/O-bound (waiting on LLM/transcription APIs, external webhooks, S3/Postgres writes) — threads share memory and avoid the cost of extra processes. -- **Combine both** for mixed workloads. Start by saturating concurrency within a single worker, then add workers if CPU is still underused. - -!!! warning "GIL & thread safety" - Concurrency > 1 runs chain links in threads. Chain link code must be thread-safe and should release the GIL during I/O (most HTTP/DB clients do). Modules that hold the GIL across long CPU work will block other in-flight vCons in the same worker. - -## Parallel Storage - -### CONSERVER_PARALLEL_STORAGE - -Enables concurrent writes to multiple storage backends. - -```bash -# Enable parallel storage (default) -CONSERVER_PARALLEL_STORAGE=true - -# Disable for sequential writes -CONSERVER_PARALLEL_STORAGE=false -``` - -### Performance Impact - -``` -Without parallel storage (sequential): - PostgreSQL: 100ms - S3: 150ms - Elasticsearch: 100ms - Total: 350ms - -With parallel storage (concurrent): - All backends: ~150ms (max of individual times) - Speedup: 2.3x -``` - -### When to Disable - -Disable parallel storage if: - -- Storage backends have interdependencies -- Debugging storage issues -- Resource constraints prevent concurrent connections - -## Start Method - -### CONSERVER_START_METHOD - -Controls how worker processes are created. - -```bash -# Memory-efficient (Unix only) -CONSERVER_START_METHOD=fork - -# Safer, cross-platform -CONSERVER_START_METHOD=spawn - -# Hybrid approach -CONSERVER_START_METHOD=forkserver - -# Platform default -CONSERVER_START_METHOD= -``` - -### Comparison - -| Method | Memory | Startup | Safety | Platform | -|--------|--------|---------|--------|----------| -| `fork` | Low (COW) | Fast | Lower | Unix only | -| `spawn` | Higher | Slower | Higher | All | -| `forkserver` | Medium | Medium | Medium | Unix | - -### fork (Default on Unix) - -```bash -CONSERVER_START_METHOD=fork -``` - -**How it works:** - -- Creates worker by copying parent process (copy-on-write) -- Shares memory pages until modified -- Fast startup, low memory overhead - -**Considerations:** - -- Not safe with threads before fork -- Can cause issues with some libraries (OpenSSL, CUDA) -- Not available on Windows - -**Best for:** - -- Unix servers with stable libraries -- Memory-constrained environments -- Simple deployments - -### spawn - -```bash -CONSERVER_START_METHOD=spawn -``` - -**How it works:** - -- Starts fresh Python interpreter for each worker -- No shared memory from parent -- All modules re-imported - -**Considerations:** - -- Higher memory usage -- Slower startup time -- Most compatible option - -**Best for:** - -- macOS deployments -- Windows systems -- When using CUDA, OpenSSL, or other sensitive libraries -- Maximum stability - -### forkserver - -```bash -CONSERVER_START_METHOD=forkserver -``` - -**How it works:** - -- Spawns a clean "server" process at startup -- Workers are forked from the server -- Avoids issues with parent process state - -**Considerations:** - -- Middle ground between fork and spawn -- Only available on Unix -- Requires extra process - -**Best for:** - -- Balance of memory efficiency and safety -- When fork causes issues but spawn is too slow - -## Worker Behavior - -### Atomic Work Distribution - -Workers use Redis BLPOP for atomic work distribution: - -``` -Worker 1: BLPOP queue1 queue2 ... -Worker 2: BLPOP queue1 queue2 ... -Worker N: BLPOP queue1 queue2 ... -``` - -Each vCon is processed by exactly one worker. - -### Graceful Shutdown - -On SIGTERM or SIGINT: - -1. Main process signals all workers -2. Workers complete current vCon -3. Workers exit cleanly -4. Main process exits - -```bash -# Graceful stop -docker compose stop # Sends SIGTERM - -# Force stop (after timeout) -docker compose kill # Sends SIGKILL -``` - -### Auto-Restart - -If a worker crashes: - -1. Main process detects exit -2. New worker is spawned -3. Processing continues - -```bash -# Check worker status -docker compose logs conserver | grep -i "worker" -``` - -## Configuration Examples - -### Development - -```bash -# Single worker, single in-flight vCon, verbose logging -CONSERVER_WORKERS=1 -CONSERVER_VCON_CONCURRENCY=1 -CONSERVER_PARALLEL_STORAGE=true -LOG_LEVEL=DEBUG -``` - -### Production (Linux) - -```bash -# Multi-worker, memory-efficient -# 8 workers × 4 in-flight = up to 32 vCons in parallel -CONSERVER_WORKERS=8 -CONSERVER_VCON_CONCURRENCY=4 -CONSERVER_PARALLEL_STORAGE=true -CONSERVER_START_METHOD=fork -LOG_LEVEL=INFO -``` - -### Production (macOS/Container) - -```bash -# Multi-worker, safer start method -# 4 workers × 4 in-flight = up to 16 vCons in parallel -CONSERVER_WORKERS=4 -CONSERVER_VCON_CONCURRENCY=4 -CONSERVER_PARALLEL_STORAGE=true -CONSERVER_START_METHOD=spawn -LOG_LEVEL=INFO ``` - -### High-Throughput (I/O-Bound) - -```bash -# Saturate I/O without exploding process count -# 4 workers × 16 in-flight = up to 64 vCons in parallel -CONSERVER_WORKERS=4 -CONSERVER_VCON_CONCURRENCY=16 -CONSERVER_PARALLEL_STORAGE=true -CONSERVER_START_METHOD=fork -TICK_INTERVAL=1000 # Check queues more frequently +max parallel vCons = CONSERVER_WORKERS x CONSERVER_VCON_CONCURRENCY ``` -### High-Throughput (CPU-Bound) +`CONSERVER_PARALLEL_STORAGE` adds a separate pool for storage writes. [Environment variables](../reference/environment.md) lists the defaults and accepted values. -```bash -# Maximise process count, keep per-worker concurrency low -CONSERVER_WORKERS=16 -CONSERVER_VCON_CONCURRENCY=1 -CONSERVER_PARALLEL_STORAGE=true -CONSERVER_START_METHOD=fork -``` +![Producers, ingress lists, the worker processes and their thread pools, egress lists and dead letter queues](../diagrams/D06-worker-queue-topology.svg) -### Memory-Constrained +## Set the process count -```bash -# Few processes, lean on in-process threading for parallelism -CONSERVER_WORKERS=2 -CONSERVER_VCON_CONCURRENCY=8 -CONSERVER_PARALLEL_STORAGE=true -CONSERVER_START_METHOD=fork # Use COW memory -``` +`CONSERVER_WORKERS` sets the number of worker processes. With `1`, the main process runs the worker loop itself. Above `1`, the main process spawns the workers and watches them. -## Monitoring Workers +More processes suit CPU-bound chains, since each has its own interpreter. Each process also loads its own copy of the code and modules, so memory grows with the count. -### Logs +## Size the thread pool -```bash -# View worker startup -docker compose logs conserver | grep -i "worker" +`CONSERVER_VCON_CONCURRENCY` sets how many vCons one worker keeps in flight. At `1` the worker runs each vCon itself, one at a time. Above `1` it hands each vCon to a thread pool of that size, and it stops popping while the pool is full. -# Watch for processing -docker compose logs -f conserver -``` +Threads suit I/O-bound chains that wait on LLM, transcription, webhook or storage calls, and they share the memory of their process. -### Metrics +!!! warning "Thread safety" + Above `1`, links and hooks run in threads. Custom link code must be thread-safe. A link that holds the GIL through long CPU work slows the other vCons in that worker. -Monitor these metrics: +## Combine the two settings -- **Queue depth**: `redis-cli LLEN {ingress_list}` -- **Processing rate**: vCons processed per minute -- **Worker health**: Process count, restarts +| `CONSERVER_WORKERS` | `CONSERVER_VCON_CONCURRENCY` | Max parallel vCons | Fits | +|---|---|---|---| +| `1` | `1` | 1 | Development and debugging | +| `4` | `1` | 4 | CPU-bound chains | +| `1` | `8` | 8 | I/O-bound chains on a small host | +| `4` | `8` | 32 | I/O-bound chains at higher volume | -### Health Check +For a mixed workload, raise concurrency in one worker first, then add workers if the CPU has room. Measure against your own chains, since link cost varies widely. -```bash -# Check all workers are running -docker compose exec conserver ps aux | grep python +## Run parallel storage writes -# Check queue processing -docker compose exec redis redis-cli LLEN default -``` +With `CONSERVER_PARALLEL_STORAGE` on, a chain with two or more storages writes to them at once, with one thread per backend. A chain with one backend writes directly. This pool starts per vCon, so peak thread use is workers times concurrency times backends. -## Troubleshooting +Turn it off to write backends one at a time in chain order, for example while debugging a storage problem. A failed save goes to the storage DLQ in both modes. See [chains and pipelines](chains-and-pipelines.md#handle-a-failure). -### Workers Not Starting +## Choose a start method -**Check logs:** +`CONSERVER_START_METHOD` applies only when `CONSERVER_WORKERS` is above `1`. Left empty, Python's platform default applies, which is `fork` on Linux for the Python versions this project supports and `spawn` on macOS. -```bash -docker compose logs conserver -``` +| Method | How a worker starts | Trade-off | +|---|---|---| +| `fork` | Copies the parent process | Lowest memory and fastest start. Can cause problems with threads and some libraries, such as OpenSSL and CUDA. See the shutdown warning below | +| `spawn` | Starts a fresh interpreter | Higher memory and slower start, and the safest with those libraries | +| `forkserver` | Forks from a clean server process | Between the two. Unix only | -**Common causes:** +Modules listed under `imports` load inside each worker, not in the main process. Followers run in the main process only, so with followers configured the parent already has timer threads when it forks. See [importing modules](yaml-configuration.md#import-extra-modules). -- Invalid start method for platform -- Insufficient memory -- Redis connection issues +## Follow the worker loop -### High Memory Usage +Each pass of the loop does this: -**Reduce workers:** +1. Rereads the config file and rebuilds the map of ingress lists to chains. +2. Calls BLPOP on all ingress lists with a 15 second timeout. +3. Runs the chain for the popped id, directly or in the pool. -```bash -CONSERVER_WORKERS=2 -``` +BLPOP gives each id to exactly one worker. It checks lists in the order they appear across chains, so an earlier list that always has work can starve a later one. -**Use fork start method:** +Link and chain edits apply on the next pass, and `imports` apply only when a worker starts. See [reload timing](yaml-configuration.md#plan-for-reloads). -```bash -CONSERVER_START_METHOD=fork -``` +A popped id has no in-flight record. If a worker dies during a chain, that queue entry is lost. The body stays in Redis until its TTL ends, and `POST /vcon/ingress` can queue the id again. -### Slow Processing +## Stop the workers -**Increase workers:** +On SIGTERM or SIGINT, the main process signals each live worker. With one worker, the main process is the worker. Each worker then: -```bash -CONSERVER_WORKERS=8 -``` +1. Stops popping after the current wait, which can take up to 15 seconds. +2. Returns an id it popped during shutdown to the head of its list. +3. Finishes its current vCon, and waits for its thread pool to drain. -**Enable parallel storage:** +The main process waits up to 30 seconds for each worker, then terminates any that remain. A terminated worker loses its in-flight vCons as described above. -```bash -CONSERVER_PARALLEL_STORAGE=true -``` +!!! warning "Set a stop timeout that fits your chains" + `docker-compose.yml` sets `stop_grace_period: 5s` on the `conserver` service, so Docker kills the container before those waits end. Raise it if your chains run longer than that. -**Check external API latency:** +!!! warning "Shutdown under fork" + With `fork`, each worker after the first inherits the parent's list of earlier workers. The signal handler then calls `is_alive()` on a process that is not its child, which raises `AssertionError` in that worker. The shutdown flag is already set by then, but the error lands in whatever the worker was doing. It can end the worker or fail the current vCon. `spawn` and `forkserver` do not inherit the list. -```bash -# Time transcription API -time curl -X POST https://api.deepgram.com/... -``` +Under `docker-compose.yml`, `watchmedo` is the container's main process. It receives the `SIGTERM` from `docker compose stop` and sends `SIGINT` to the server's process group, and the server handles both signals the same way. -### Worker Crashes +## Restart a failed worker -**Check for library compatibility:** +With more than one worker, the main process checks every 5 seconds and replaces any worker that died, logging `died unexpectedly, restarting`. With one worker there is no supervisor inside the process, so rely on your container or service manager. -```bash -# If using fork and seeing crashes -CONSERVER_START_METHOD=spawn -``` +## Scale past one process -**Check resource limits:** +Conservers that share a Redis server share the work, since BLPOP is atomic across them. ```bash -# Docker resource constraints -docker stats +docker compose up -d --scale conserver=4 ``` -### Inconsistent Processing +Total parallelism is then instances times workers times concurrency. Each instance also starts its own followers. For Kubernetes, see [the deployment guide](../installation/kubernetes.md). -**Ensure atomic operations:** +## Watch the workers -- Workers use BLPOP (atomic pop) -- Each vCon processed once +| Signal | Source | +|---|---| +| Startup settings | Log line `Worker configuration: workers=...` | +| Queue depth | `GET /stats/queue?list_name=`, or the gauge `conserver.ingress_list.length` | +| In-flight vCons per chain | `conserver.vcons.inflight` | +| Throughput and time per vCon, halted vCons included | `conserver.main_loop.count_vcons_processed`, `conserver.main_loop.vcon_processing_time` | +| Redis memory | `conserver.redis.memory_used_bytes` | -**Check for duplicate processing:** +The [metrics reference](../reference/metrics.md) has the full list, and [monitoring](../operations/monitoring.md) shows how to collect it. -```bash -# Review logs for same UUID -docker compose logs conserver | grep "UUID" -``` - -## Scaling Strategies - -### Vertical Scaling - -Increase workers within single instance: - -```bash -# Start with CPU cores -CONSERVER_WORKERS=$(nproc) +## Troubleshoot the workers -# Monitor and adjust -docker stats -``` - -### Horizontal Scaling - -Run multiple instances: - -```bash -# Docker Compose -docker compose up -d --scale conserver=4 - -# Each instance can have multiple workers -CONSERVER_WORKERS=2 # 4 instances x 2 workers = 8 total -``` - -### Auto-Scaling (Kubernetes) - -```yaml -apiVersion: autoscaling/v2 -kind: HorizontalPodAutoscaler -metadata: - name: worker-hpa -spec: - scaleTargetRef: - apiVersion: apps/v1 - kind: Deployment - name: worker - minReplicas: 2 - maxReplicas: 10 - metrics: - - type: Resource - resource: - name: cpu - target: - type: Utilization - averageUtilization: 70 -``` +| Symptom | Check | +|---|---| +| Server exits at startup | An invalid `CONSERVER_START_METHOD` raises `ValueError`. An empty integer variable fails on import | +| A worker fails at startup | A module under `imports` failed to load. Worker logs show `Failed to import module` | +| Workers crash under `fork` | Try `spawn`, since some libraries do not survive a fork | +| Memory grows too high | Use fewer processes and more concurrency | +| Queue depth keeps rising | Raise concurrency for I/O-bound chains and workers for CPU-bound ones, and check the latency of outside services | +| A later list never drains | An earlier list is taking every pop. See [the worker loop](#follow-the-worker-loop) | +| Workers idle with work queued | The list name matches no chain, or a later chain took the list | diff --git a/docs/configuration/yaml-configuration.md b/docs/configuration/yaml-configuration.md index 4dd9cd4c..9fbc90bb 100644 --- a/docs/configuration/yaml-configuration.md +++ b/docs/configuration/yaml-configuration.md @@ -1,286 +1,168 @@ -# YAML Configuration +# Write the YAML configuration -Complete reference for the vCon Server YAML configuration file. +One YAML file defines what the server does to each vCon: which links run, where results go, and who may submit. `CONSERVER_CONFIG_FILE` names the file. Server-level settings live in [environment variables](environment-variables.md). -## File Structure +Start from the small file in [the Docker guide](../installation/docker.md#write-the-chain-configuration). -```yaml -# API key authentication for ingress lists -ingress_auth: - ... +`example_config.yml` is a syntax catalogue to read, not to run. It names modules that are not in this repo, and its empty `tracers` key sends every vCon to the dead letter queue. -# Dynamic module imports -imports: - ... +## Learn the file rules -# Processing link definitions -links: - ... +The server loads the file with `yaml.safe_load`, with no further processing: -# Storage backend definitions -storages: - ... +- `${VAR}` is not expanded. A value such as `${OPENAI_API_KEY}` reaches the link as that literal text. Write the real value, and render the file in your deployment tooling if you keep secrets elsewhere. +- Nothing validates the file on load. An unknown key is ignored and a wrong one fails when the code reaches it. +- `GET /config` returns the parsed file, secrets included, to any caller with an API key. `POST /config` replaces the whole file, and comments are lost. -# Tracer definitions -tracers: - ... +## Know the top-level keys -# Processing chain definitions -chains: - ... +| Key | Read by | Holds | +|---|---|---| +| `ingress_auth` | API | API keys per ingress list | +| `imports` | Conserver | Modules to load when a worker starts | +| `links` | Conserver | Named processing links | +| `storages` | Conserver and API | Named storage backends | +| `tracers` | Conserver | Named tracers | +| `chains` | Conserver and queue metrics | Pipelines that join the above | +| `followers` | Conserver | Remote servers to pull from | -# Follower configurations (distributed mode) -followers: - ... -``` +Every key is optional. With no `chains`, the workers log a warning and retry every 15 seconds. -## Ingress Authentication +## Plan for reloads -Map API keys to specific ingress lists for external integrations. +The server reads the file again at these points, so most edits need no restart: -### Single Key +| Section | Takes effect | +|---|---| +| `chains`, `links`, `tracers` | On each worker loop, after a vCon is popped or the 15 second wait ends | +| `storages` | On the next write or read | +| `ingress_auth` | On the next request | +| `imports` | When a worker starts | +| `followers` | When the conserver process starts | -```yaml -ingress_auth: - customer_data: "customer-api-key-12345" -``` +A YAML syntax error stops a worker at its next reload, so check a change before you save it over the live file. -### Multiple Keys +## Authorize external ingress + +`ingress_auth` maps an ingress list to one key or a list of keys: ```yaml ingress_auth: + customer_data: "replace-with-a-key" support_calls: - - "support-api-key-67890" - - "support-client-2-key" - - "support-vendor-key-xyz" + - "replace-with-a-key-for-client-1" + - "replace-with-a-key-for-client-2" ``` -### Usage - -External systems use the `/vcon/external-ingress` endpoint with their assigned key: +A caller sends the key to `POST /vcon/external-ingress`: ```bash -curl -X POST "http://api/vcon/external-ingress?ingress_list=customer_data" \ - -H "x-conserver-api-token: customer-api-key-12345" \ +curl -X POST "http://localhost:8000/vcon/external-ingress?ingress_list=customer_data" \ + -H "x-conserver-api-token: replace-with-a-key" \ -H "Content-Type: application/json" \ - -d '{"vcon": "0.0.1", ...}' + -d @vcon.json ``` -## Imports +A key works only for its own list. With `ingress_auth` empty, or the list missing from it, the API returns 403. See [authentication](authentication.md). -Define modules to import dynamically from PyPI or GitHub. +## Import extra modules -### From PyPI +`imports` loads modules when each worker starts. A module that is missing is installed with `pip`, and an import that still fails stops the worker. ```yaml imports: custom_utility: module: custom_utils pip_name: custom-utils-package -``` - -### From GitHub - -```yaml -imports: github_helper: module: github_helper pip_name: git+https://github.com/username/helper-repo.git -``` - -### Direct Module - -```yaml -imports: - # Module name matches pip package requests_import: module: requests + legacy_module: some.legacy.module ``` -## Links +`pip_name` defaults to the module name. A plain string is the older form and names the module alone. See [dynamic modules](../extending/dynamic-modules.md). -Define processing links that transform vCons. +## Add processing links -### Basic Link +A link entry has a name of your choice and these keys: -```yaml -links: - transcribe: - module: links.transcribe -``` - -### Link with Options +| Key | Required | Use | +|---|---|---| +| `module` | Yes | Python module with a `run` function, such as `links.tag` | +| `options` | In practice | Mapping passed to the link | +| `pip_name` | No | Package to install when the module is missing | ```yaml links: - deepgram_link: - module: links.deepgram_link + tag_processed: + module: links.tag options: - model: nova-2 - language: en - punctuate: true - diarize: true + tags: + - processed ``` -### External Link +Always write `options`, even as `options: {}`. Without the key the link receives `None`, not its `default_options`, and most bundled links then raise an error. A bare `options:` key also loads as `None`. A missing block does not break `delay`, `hugging_llm_link` or the four deprecated transcription modules. `transcribe` then falls to `whisper_builtin` and raises, and `wtf_transcribe` halts the chain because it has no `vfun-server-url`. -```yaml -links: - custom_analyzer: - module: custom_analyzer_module - pip_name: custom-analyzer-package - options: - api_key: your-key - endpoint: https://api.example.com -``` +`options.after_link` goes to the after-link hook, which does nothing unless a build replaces it. See [creating links](../extending/creating-links.md). -### Available Links - -| Link | Module | Description | -|------|--------|-------------| -| `deepgram_link` | `links.deepgram_link` | Deepgram transcription | -| `groq_whisper` | `links.groq_whisper` | Groq Whisper transcription | -| `hugging_face_whisper` | `links.hugging_face_whisper` | HuggingFace Whisper | -| `openai_transcribe` | `links.openai_transcribe` | OpenAI Whisper | -| `analyze` | `links.analyze` | AI analysis | -| `analyze_and_label` | `links.analyze_and_label` | Analysis with labeling | -| `analyze_vcon` | `links.analyze_vcon` | vCon-specific analysis | -| `detect_engagement` | `links.detect_engagement` | Engagement detection | -| `tag` | `links.tag` | Add static tags | -| `check_and_tag` | `links.check_and_tag` | Conditional tagging | -| `tag_router` | `links.tag_router` | Route by tags | -| `sampler` | `links.sampler` | Random sampling | -| `webhook` | `links.webhook` | HTTP webhook delivery | -| `post_analysis_to_slack` | `links.post_analysis_to_slack` | Slack notifications | -| `diet` | `links.diet` | Reduce vCon size | -| `expire_vcon` | `links.expire_vcon` | Set expiration | -| `jq_link` | `links.jq_link` | jq transformations | - -## Storages - -Define storage backends for persisting vCons. - -### Redis Storage +The [link reference](../reference/links/index.md) lists each bundled link and its options. -```yaml -storages: - redis_storage: - module: storage.redis_storage -``` +### Transcribe with one link -### PostgreSQL +`links.transcribe` is the transcription link. `vendor` picks the service and `vendor_options` goes to it unchanged. ```yaml -storages: - postgres: - module: storage.postgres +links: + transcribe: + module: links.transcribe options: - user: vcon - password: vcon_password - host: postgres - port: "5432" - database: vcon_server + vendor: deepgram + vendor_options: + DEEPGRAM_KEY: replace-with-a-key + api: + model: nova-3 ``` -### MongoDB - -```yaml -storages: - mongo: - module: storage.mongo - options: - url: mongodb://root:example@mongo:27017/ - database: conserver - collection: vcons -``` +Always set `vendor`. The default, `whisper_builtin`, calls `Vcon.transcribe`, which the `Vcon` class in `common/vcon.py` does not have, so the link raises an error. -### Amazon S3 +The per-vendor modules are deprecated. A chain that names one still runs: the server routes it through `links.transcribe`, treats its `options` as `vendor_options` and logs a warning. -```yaml -storages: - s3: - module: storage.s3 - options: - aws_access_key_id: your-access-key - aws_secret_access_key: your-secret-key - aws_bucket: vcon-archive - aws_region: us-east-1 - s3_path: vcons/ # Optional prefix -``` +| Deprecated module | `vendor` | +|---|---| +| `links.deepgram_link` | `deepgram` | +| `links.groq_whisper` | `groq` | +| `links.hugging_face_whisper` | `hugging_face` | +| `links.openai_transcribe` | `openai` | -### S3-Compatible Storage +`links.wtf_transcribe` is a separate link and does not go through this dispatcher. -```yaml -storages: - minio: - module: storage.s3 - options: - aws_access_key_id: minioadmin - aws_secret_access_key: minioadmin - aws_bucket: vcons - endpoint_url: http://minio:9000 -``` +## Add storage backends -### Elasticsearch +A storage entry has a name, a `module` and `options`: ```yaml storages: - elasticsearch: - module: storage.elasticsearch - options: - hosts: - - http://elasticsearch:9200 - index: vcons -``` - -### Milvus (Vector Database) - -```yaml -storages: - milvus: - module: storage.milvus - options: - host: milvus - port: "19530" - collection_name: vcons - embedding_model: text-embedding-3-small - embedding_dim: 1536 - api_key: your-openai-key # For embeddings - create_collection_if_missing: true - index_type: IVF_FLAT - metric_type: L2 -``` - -### File Storage - -```yaml -storages: - file: - module: storage.file + postgres: + module: storage.postgres options: - path: /data/vcons - organize_by_date: true - compression: false + user: vcon + password: replace-with-a-password + host: postgres + port: "5432" + database: vcon_server ``` -### SFTP +With no `options` key, the adapter gets its `default_options`. With the key, it gets exactly that mapping, and the server does not merge in the defaults. Check the adapter's reference page for the options it requires. -```yaml -storages: - sftp: - module: storage.sftp - options: - host: sftp.example.com - username: vcon - private_key_path: /etc/vcon/sftp_key - remote_path: /uploads/vcons -``` +Storage modules load with a plain import, so `pip_name` has no effect here. List a storage package under `imports`, or install it in the image. The API process does not run `imports`, and it loads the same adapters to read vCons, so an image install covers both. -## Tracers +The [storage adapter reference](../reference/storage-adapters/index.md) lists each adapter. -Define tracers for audit trails and monitoring. +## Add tracers -### JLINC Tracer +Tracers run around links and report each step to an outside system. Every tracer under the top-level `tracers` key runs for every chain. ```yaml tracers: @@ -288,210 +170,159 @@ tracers: module: tracers.jlinc options: data_store_api_url: http://jlinc-server:9090 - data_store_api_key: your-key + data_store_api_key: replace-with-a-key archive_api_url: http://jlinc-server:9090 - archive_api_key: your-key + archive_api_key: replace-with-a-key system_prefix: VCONProd agreement_id: 00000000-0000-0000-0000-000000000000 hash_event_data: true dlq_vcon_on_error: true ``` -## Chains +Keep the `options` key. Without it the tracer receives `None`, and the error handling in `conserver/main.py` raises a second error when the tracer fails. -Define processing chains that combine links, storage, and routing. +A tracer error is logged and processing continues, unless `dlq_vcon_on_error` is true. Then the vCon moves to the dead letter queue. A chain with no links runs no tracers. See [creating tracers](../extending/creating-tracers.md). -### Basic Chain +## Build processing chains -```yaml -chains: - simple_chain: - links: - - transcribe - storages: - - redis_storage - ingress_lists: - - default - enabled: 1 -``` - -### Full Chain +A chain ties links and storage to ingress lists: ```yaml chains: - production_chain: + main_chain: links: - - deepgram_link - - analyze - - tag - - tag_router + - transcribe + - tag_processed storages: - postgres - - s3 - - elasticsearch - tracers: - - jlinc ingress_lists: - - production_ingress + - main_ingress egress_lists: - - processed_vcons - - analytics_queue - enabled: 1 + - processed ``` -### Chain with Link Options +| Key | Required | Use | +|---|---|---| +| `links` | Yes | Link names, run in order. Use `[]` for none. A chain without the key fails each vCon with `KeyError` | +| `ingress_lists` | To run at all | Redis lists the workers read for this chain | +| `storages` | No | Storage names to write when the links finish | +| `egress_lists` | No | Redis lists that receive the vCon UUID when the links finish | -```yaml -chains: - custom_chain: - links: - - deepgram_link: - model: nova-2 - diarize: true - - analyze: - model: gpt-4 - prompt: "Summarize this call" - - sampler: - rate: 0.1 # Sample 10% - storages: - - postgres - ingress_lists: - - sample_input - enabled: 1 -``` +These rules follow from the code: -### Disabled Chain +- Each entry under `links` must be a plain name. An inline mapping such as `- analyze: {model: gpt-4}` raises `TypeError` and sends the vCon to the dead letter queue. To vary options, define a second link. +- If two chains name the same ingress list, the chain defined last takes it. +- A link that returns nothing halts the chain. The vCon then skips egress lists and storage. +- Egress lists fill before storage runs. A storage failure does not fail the chain: that vCon goes to `DLQ:storage:`. -```yaml -chains: - disabled_chain: - links: - - transcribe - storages: - - redis_storage - ingress_lists: - - unused - enabled: 0 # Chain is disabled -``` +Three keys that appear in older examples do nothing: -## Followers +| Key | What the code does | +|---|---| +| `enabled` | Never reads it. `enabled: 0` does not stop a chain. To stop one, remove its `ingress_lists` | +| `timeout` | Writes it to a debug log and enforces nothing | +| `tracers` | Never reads it on a chain. See [tracers](#add-tracers) | -Configure follower processes for distributed deployments. +The `ingress-lists` and `egress-lists` keys on a link, seen in `example_config.yml`, are ignored too. + +[Chains and pipelines](chains-and-pipelines.md) covers chain design. + +## Pull from another server + +A follower polls the egress list of another server and copies each vCon into a local ingress list. Followers start with the conserver process. ```yaml followers: upstream_server: url: http://upstream-vcon-server:8000 - egress_list: processed_vcons + egress_list: processed follower_ingress_list: incoming_from_upstream - auth_token: upstream-api-token - pulling_interval: 60 # seconds + auth_token: replace-with-the-upstream-key + pulling_interval: 60 fetch_vcon_limit: 10 ``` -## Complete Example +| Key | Use | +|---|---| +| `url` | Base URL of the other server's API, with no trailing slash | +| `egress_list` | Egress list to pop UUIDs from | +| `follower_ingress_list` | Local list that receives each vCon | +| `auth_token` | API key for the other server, sent in the header named by the local `CONSERVER_HEADER_NAME` | +| `pulling_interval` | Seconds between polls | +| `fetch_vcon_limit` | UUIDs to pop on each poll | -```yaml ---- -# ============================================================================= -# vCon Server Configuration -# ============================================================================= +All six keys are required. Popping removes the UUID from the other server's list, so give each follower its own egress list. -# Ingress-specific authentication +## See a complete example + +This file joins the sections above into one working shape. Replace the placeholders before you use it. + +```yaml ingress_auth: - partner_a: "partner-a-secure-key" - partner_b: - - "partner-b-key-1" - - "partner-b-key-2" + partner_a: "replace-with-a-key" -# Processing links links: - deepgram_link: - module: links.deepgram_link + transcribe: + module: links.transcribe options: - model: nova-2 - language: en - punctuate: true - diarize: true - - analyze: + vendor: deepgram + vendor_options: + DEEPGRAM_KEY: replace-with-a-key + api: + model: nova-3 + summarize: module: links.analyze options: - model: gpt-4 - temperature: 0.3 - - tag: + OPENAI_API_KEY: replace-with-a-key + analysis_type: summary + prompt: "Summarize this conversation." + source: + analysis_type: transcript + text_location: body.transcript + tag_processed: module: links.tag options: tags: - processed - - v1 - - tag_router: + route_urgent: module: links.tag_router options: - rules: - - tag: urgent - queue: urgent_queue - - tag: routine - queue: routine_queue + tag_routes: + urgent: urgent_queue + forward_original: true -# Storage backends storages: postgres: module: storage.postgres options: user: vcon - password: vcon_password + password: replace-with-a-password host: postgres port: "5432" database: vcon_server - s3: module: storage.s3 options: - aws_access_key_id: ${AWS_ACCESS_KEY_ID} - aws_secret_access_key: ${AWS_SECRET_ACCESS_KEY} + aws_access_key_id: replace-with-a-key-id + aws_secret_access_key: replace-with-a-secret aws_bucket: vcon-archive aws_region: us-east-1 - elasticsearch: - module: storage.elasticsearch - options: - hosts: - - http://elasticsearch:9200 - index: vcons - -# Tracers -tracers: - jlinc: - module: tracers.jlinc - options: - data_store_api_url: http://jlinc:9090 - data_store_api_key: jlinc-key - system_prefix: PROD - -# Processing chains chains: main_pipeline: links: - - deepgram_link - - analyze - - tag - - tag_router + - transcribe + - summarize + - tag_processed + - route_urgent storages: - postgres - s3 - - elasticsearch - tracers: - - jlinc ingress_lists: - main_ingress - partner_a - - partner_b egress_lists: - processed - enabled: 1 archive_only: links: [] @@ -499,5 +330,4 @@ chains: - s3 ingress_lists: - archive_ingress - enabled: 1 ``` diff --git a/docs/contributing.md b/docs/contributing.md new file mode 100644 index 00000000..b3d8a8d5 --- /dev/null +++ b/docs/contributing.md @@ -0,0 +1,141 @@ +# Contributing + +This page gets you from a fresh clone to a passing test run and a clean docs check, so your change reaches review without a CI surprise. + +Report bugs and propose changes through [GitHub issues](https://github.com/vcon-dev/vcon-server/issues) and pull requests against `main`. + +## Learn the repository layout + +| Path | Contents | +|---|---| +| `api/` | The FastAPI service | +| `conserver/` | The worker: `main.py`, `links/`, `tracers/`, hooks and the follower | +| `common/` | Code both services import: `vcon.py`, `lib/`, `storage/`, `settings.py`, `config.py` | +| `tests/` | Core and storage tests. `common/tests/`, `conserver/tests/` and each link folder hold more | +| `docker/` | `Dockerfile` for development and CI, plus `Dockerfile.api` and `Dockerfile.conserver` for production images | +| `docs/` | This site. `scripts/docs/` holds the generators and the docs check | + +## Set up with uv + +The project uses [uv](https://docs.astral.sh/uv/) and `uv.lock`. It needs Python `>=3.12,<3.14`. + +Dependencies sit in groups, and a plain `uv sync` installs only the core and `dev` groups. Those are not enough to import the services, so name the groups: + +```bash +uv sync --group conserver --group api --group storage-milvus +``` + +| Group | Adds | +|---|---| +| `dev` | pytest, black and test tools. Installed by default | +| `storage` | Storage backend clients. Pulled in by `api` and `conserver` | +| `api` | FastAPI, uvicorn and `storage` | +| `conserver` | Link dependencies, watchdog and `storage` | +| `storage-milvus` | The Milvus client. Kept out of the production images | +| `conserver-local` | transformers, for the local model path in [hugging_llm_link](reference/links/hugging-llm.md) | + +Change dependencies with `uv add` or by editing `pyproject.toml` and running `uv lock`. Commit `uv.lock` with the change. The Dockerfiles install with `--frozen`, so a dependency missing from the lock file never reaches the image. + +## Mind the import paths + +Four directories go on the Python path: the repo root, `common`, `conserver` and `api`. `pytest.ini` sets them for tests and `docker/Dockerfile` sets `PYTHONPATH` for the image. + +- Shared code imports from `lib`, for example `from lib.vcon_redis import VconRedis`. +- Queue work goes through `VconQueue` in `lib.queue`. +- Links live in `conserver/links/` and load as `links.`. Storage adapters load as `storage.`. +- `import vcon` finds `common/vcon.py` first, not the `vcon` package from `pyproject.toml`. Links run on the local class, so read that file to see which methods exist. + +To run a script outside pytest, set the path yourself: + +```bash +PYTHONPATH=.:common:conserver:api uv run python your_script.py +``` + +## Run the tests + +Run the suite in the container, as CI does. Many tests need Redis, and the container has it. Start the stack first, as the [quick start](getting-started/quick-start.md) shows. + +```bash +docker compose run --rm conserver pytest +``` + +Pick a path to run part of it: + +```bash +docker compose run --rm conserver pytest conserver/links/analyze/tests/ -v +``` + +CI also adds coverage: + +```bash +docker compose run --rm conserver pytest --maxfail=5 --disable-warnings --cov --cov-report=term-missing:skip-covered +``` + +Tests that mock Redis also run on the host, which is quicker for a link you are working on: + +```bash +uv run pytest conserver/links/tag +``` + +On the host, tests that need Redis error out unless one is listening at `REDIS_URL`, default `redis://localhost`. The `integration` marker does not separate them, so `-m "not integration"` does not avoid this. + +If your `.env` was copied from `.env.example`, fix `LOGGING_CONFIG_FILE` first, as the [quick start](getting-started/quick-start.md#set-the-environment) describes. Collection fails otherwise. + +### Enable the vendor tests + +Tests that call Deepgram, OpenAI or Groq skip without credentials. To run them, copy the template and fill it in: + +```bash +cp .env.test.example .env.test +``` + +`pytest.ini` loads `.env.test` before collection. Git ignores that file. Never commit real keys. + +## Format your code + +`pyproject.toml` configures black with a line length of 120 and no string normalization. Format the code you change, and leave the rest of the file alone to keep the diff small. Not every file in the repo is black clean. + +```bash +uv run black path/to/changed_file.py +``` + +## Change the docs + +The site uses MkDocs Material. Run the same check as CI, which needs uv and Node: + +```bash +bash scripts/docs/check.sh +``` + +It runs the generators, renders every diagram and builds the site with `--strict`. To build the site alone: + +```bash +NO_MKDOCS_2_WARNING=1 uvx --with mkdocs-material mkdocs build --strict -d /tmp/vcon-site +``` + +Follow these rules: + +- Take every claim from the code. Old docs drift. +- Never hand edit a generated page: [environment](reference/environment.md), [ports](reference/ports.md), [API routes](reference/api-routes.md) and [metrics](reference/metrics.md). Edit the code, or `scripts/docs/descriptions.yml` for the prose, then rerun the check. +- Change a diagram in its `.mmd` source and commit the SVG. See `docs/diagrams/README.md`. +- Example vCons use `"vcon": "0.4.0"`. +- Link to reference pages. Do not copy them. + +## Add a link, adapter or tracer + +Start from the guides: [creating links](extending/creating-links.md), [creating storage adapters](extending/creating-storage-adapters.md) and [creating tracers](extending/creating-tracers.md). Add tests next to the code and a page under `docs/reference/`. + +## Keep the consent boundary + +Active consent management is outside this repository. The server carries `lawful_basis` attachments and never creates, validates or enforces them. See [lawful basis](concepts/lawful-basis.md) and [editions](concepts/editions.md). Keep contributions and docs within that boundary, and never describe the server as making a deployment compliant. + +## Open a pull request + +- Branch from `main` and keep each pull request to one change. +- Keep `.env`, `.env.test`, `config.yml` and any scratch folders out of commits. +- Leave personal and company names out of issues, commits and pull requests. This repo is public, so write "a partner" or "the customer". +- CI runs the tests and the docs check on every pull request. + +## Understand releases + +Pushing to `main` builds and publishes the images tagged `main-` and `latest`. Pushing a `v*` tag publishes semver tags such as `1.2.3`, `1.2` and `1`. The tag push is the release. See [upgrading](installation/upgrading.md). diff --git a/docs/diagrams/D01-system-context.mmd b/docs/diagrams/D01-system-context.mmd new file mode 100644 index 00000000..35341612 --- /dev/null +++ b/docs/diagrams/D01-system-context.mmd @@ -0,0 +1,41 @@ +%%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, Helvetica, Arial, sans-serif','fontSize':'14px','background':'#FFFFFF','primaryColor':'#F3F4F6','primaryTextColor':'#292929','primaryBorderColor':'#0A7D18','secondaryColor':'#FFFFFF','secondaryTextColor':'#33363B','secondaryBorderColor':'#8A8A8D','tertiaryColor':'#FFFFFF','tertiaryTextColor':'#33363B','tertiaryBorderColor':'#8A8A8D','lineColor':'#33363B','textColor':'#33363B','mainBkg':'#F3F4F6','nodeBorder':'#0A7D18','clusterBkg':'#FFFFFF','clusterBorder':'#8A8A8D','edgeLabelBackground':'#FFFFFF','actorBkg':'#F3F4F6','actorBorder':'#0A7D18','actorTextColor':'#292929','signalColor':'#33363B','signalTextColor':'#292929','labelBoxBkgColor':'#F3F4F6','labelBoxBorderColor':'#0A7D18','noteBkgColor':'#F3F4F6','noteBorderColor':'#8A8A8D','noteTextColor':'#292929'}}}%% +%%{init: {'fontFamily':'Inter, Helvetica, Arial, sans-serif'}}%% +flowchart TB + subgraph callers["Callers"] + clients["API clients"] + partners["Third-party senders"] + end + + subgraph server["vCon Server"] + api["api service
FastAPI, port 8000"] + config[/"YAML config file
CONSERVER_CONFIG_FILE"/] + redis[("Redis
vCon cache, lists, indexes")] + conserver["conserver service
workers run chains"] + end + + subgraph external["External systems, each set by config"] + storage[("Storage backends
15 adapters")] + linksvc["Link services
speech to text, LLM APIs,
webhooks, Slack, DataTrails, SCITT"] + tracer["JLINC tracer service"] + upstream["Upstream conserver
same API on another host"] + otel["OTLP endpoint"] + sentry["Sentry"] + end + + clients -->|"REST, global API key"| api + partners -->|"POST /vcon/external-ingress
per-list API key"| api + api -->|"store vCons,
RPUSH ingress lists"| redis + conserver <-->|"BLPOP ingress lists, read and write vCons,
RPUSH egress lists and DLQs"| redis + config -->|"read on each use"| conserver + api <-->|"read, POST /config rewrites"| config + conserver -->|"save, read on Redis miss"| storage + api -->|"read, delete, DLQ replay"| storage + conserver -->|"links call out"| linksvc + conserver -.->|"tracers run per link"| tracer + conserver -.->|"follower polls egress"| upstream + conserver -.->|"traces, metrics"| otel + api -.->|"traces, metrics"| otel + conserver -.->|"errors"| sentry + + classDef accent stroke:#0BB81E,stroke-width:3px + class conserver accent diff --git a/docs/diagrams/D01-system-context.svg b/docs/diagrams/D01-system-context.svg new file mode 100644 index 00000000..61976c62 --- /dev/null +++ b/docs/diagrams/D01-system-context.svg @@ -0,0 +1 @@ +

External systems, each set by config

vCon Server

Callers

REST, global API key

POST /vcon/external-ingress
per-list API key

store vCons,
RPUSH ingress lists

BLPOP ingress lists, read and write vCons,
RPUSH egress lists and DLQs

read on each use

read, POST /config rewrites

save, read on Redis miss

read, delete, DLQ replay

links call out

tracers run per link

follower polls egress

traces, metrics

traces, metrics

errors

API clients

Third-party senders

api service
FastAPI, port 8000

YAML config file
CONSERVER_CONFIG_FILE

Redis
vCon cache, lists, indexes

conserver service
workers run chains

Storage backends
15 adapters

Link services
speech to text, LLM APIs,
webhooks, Slack, DataTrails, SCITT

JLINC tracer service

Upstream conserver
same API on another host

OTLP endpoint

Sentry

\ No newline at end of file diff --git a/docs/diagrams/D01.sources.md b/docs/diagrams/D01.sources.md new file mode 100644 index 00000000..b7906de8 --- /dev/null +++ b/docs/diagrams/D01.sources.md @@ -0,0 +1,44 @@ +# D01 sources + +System context. Drawn from the code at base commit `323109a`. Paths are relative to the repo root. + +## Nodes + +| Node | Source | +|---|---| +| API clients | `api/api.py:1371` mounts `api_router` behind `get_api_key` | +| Third-party senders | `api/api.py:824`, `api/api.py:1377` mounts `external_router` without the global key | +| api service | `api/api.py:85`, `docker-compose.yml:45`, `docker-compose.yml:49` | +| YAML config file | `common/settings.py:58`, `common/config.py:7` | +| Redis | `common/redis_mgr.py:22`, `api/api.py:447` sorted set, `api/api.py:1312` party index, `common/lib/queue.py:64` lists | +| conserver service | `conserver/main.py:925`, `conserver/main.py:774`, `docker-compose.yml:16` | +| Storage backends, 15 adapters | The 15 packages in `common/storage/`: `chatgpt_files`, `dataverse`, `elasticsearch`, `file`, `milvus`, `mongo`, `postgres`, `redis_storage`, `s3`, `scitt`, `sftp`, `spaceandtime`, `utopia`, `vcon_mcp`, `webhook`. Loaded by `common/storage/base.py:50` | +| Link services | Speech to text: `conserver/links/transcribe/__init__.py:59`, `conserver/links/groq_whisper/__init__.py:240`, `conserver/links/hugging_face_whisper/__init__.py:52`, `conserver/links/deepgram_link/__init__.py:15`, `conserver/links/wtf_transcribe/__init__.py:256`. LLM APIs: `common/lib/openai_client.py:21`, `conserver/links/hugging_llm_link/__init__.py:110`. Others: `conserver/links/webhook/__init__.py:63`, `conserver/links/post_analysis_to_slack/__init__.py:92`, `conserver/links/datatrails/__init__.py:28`, `conserver/links/scitt/__init__.py:30` | +| JLINC tracer service | `conserver/tracers/jlinc/__init__.py:11`, `conserver/tracers/jlinc/__init__.py:38`, `example_config.yml:102` | +| Upstream conserver | `conserver/follower.py:22`, `conserver/follower.py:41` | +| OTLP endpoint | `common/lib/metrics.py:12`, `common/lib/metrics.py:84`, `docker-compose.yml:21`, `docker-compose.yml:49` | +| Sentry | `common/lib/error_tracking.py:9`, `common/lib/error_tracking.py:27` | + +## Edges + +| Edge | Source | +|---|---| +| API clients to api, global key | `api/api.py:105`, `api/api.py:1371`. With no key configured the check is skipped, `api/api.py:118`. `/version`, `/health` and `/stats/queue` are on `app` directly and need no key, `api/api.py:235`, `api/api.py:257`, `api/api.py:275` | +| Third-party senders to api, per-list key | `api/api.py:824`, `api/api.py:127`, `api/api.py:877` | +| api to Redis | `api/api.py:452`, `api/api.py:447`, `common/lib/queue.py:149` | +| conserver and Redis | `common/lib/queue.py:81` BLPOP, `conserver/main.py:875`, `conserver/main.py:587` read, `common/lib/vcon_redis.py:98` write, `conserver/main.py:366` egress, `conserver/main.py:761` and `conserver/main.py:447` DLQs | +| Config to conserver, read on each use | `common/config.py:10`, `conserver/main.py:862` | +| api and config | `common/config.py:60`, `api/api.py:1109`, `api/api.py:1135` | +| conserver to Storage backends | `conserver/main.py:410` save, `common/lib/vcon_redis.py:127` read on a Redis miss, gated by `common/lib/vcon_redis.py:120` | +| api to Storage backends | `api/api.py:492` read, `api/api.py:965` delete, `api/api.py:1233` storage DLQ replay | +| conserver to Link services | `conserver/main.py:603` runs the module. The calls are in the link files listed under Nodes | +| conserver to JLINC tracer | `conserver/main.py:508`, `conserver/main.py:522`, called at `conserver/main.py:601`, `conserver/main.py:642`, `conserver/main.py:644` | +| conserver to Upstream conserver | `conserver/main.py:989`, `conserver/follower.py:33`, `conserver/follower.py:42`. No poll runs unless `followers` is in the config, `common/config.py:69` | +| conserver and api to OTLP endpoint | `docker-compose.yml:21`, `docker-compose.yml:49`, `common/lib/metrics.py:67` skips export when the endpoint is unset | +| conserver to Sentry | `conserver/main.py:148`, `conserver/main.py:790`, `conserver/follower.py:13`, active only with `SENTRY_DSN`, `common/lib/error_tracking.py:28`. `api/api.py` never calls `init_error_tracker`, so no api edge is drawn | + +## Notes + +The dashed edges depend on config. Storage and link edges are solid because a chain needs them to do useful work, though each named system still comes from config. + +Line 2 of the `.mmd` sets the top-level `fontFamily`. See the font note in `D02.sources.md`. diff --git a/docs/diagrams/D02-container-port-map.mmd b/docs/diagrams/D02-container-port-map.mmd new file mode 100644 index 00000000..148ad111 --- /dev/null +++ b/docs/diagrams/D02-container-port-map.mmd @@ -0,0 +1,63 @@ +%%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, Helvetica, Arial, sans-serif','fontSize':'14px','background':'#FFFFFF','primaryColor':'#F3F4F6','primaryTextColor':'#292929','primaryBorderColor':'#0A7D18','secondaryColor':'#FFFFFF','secondaryTextColor':'#33363B','secondaryBorderColor':'#8A8A8D','tertiaryColor':'#FFFFFF','tertiaryTextColor':'#33363B','tertiaryBorderColor':'#8A8A8D','lineColor':'#33363B','textColor':'#33363B','mainBkg':'#F3F4F6','nodeBorder':'#0A7D18','clusterBkg':'#FFFFFF','clusterBorder':'#8A8A8D','edgeLabelBackground':'#FFFFFF','actorBkg':'#F3F4F6','actorBorder':'#0A7D18','actorTextColor':'#292929','signalColor':'#33363B','signalTextColor':'#292929','labelBoxBkgColor':'#F3F4F6','labelBoxBorderColor':'#0A7D18','noteBkgColor':'#F3F4F6','noteBorderColor':'#8A8A8D','noteTextColor':'#292929'}}}%% +%%{init: {'fontFamily':'Inter, Helvetica, Arial, sans-serif'}}%% +flowchart LR + subgraph host["Docker host, published ports"] + p8000["8000
CONSERVER_EXTERNAL_PORT"] + p5432["5432"] + p9200["9200"] + p9300["9300"] + p3000["3000"] + end + + subgraph net["Docker network conserver, external, create it first"] + subgraph always["Always started"] + subgraph app["Built from docker/Dockerfile"] + api["api
container port 8000"] + conserver["conserver
no port"] + end + redis[("redis
6379, network only")] + end + subgraph stores["Local storage profiles"] + subgraph profpg["Profile postgres"] + postgres[("postgres
5432")] + end + subgraph profes["Profile elasticsearch"] + elastic[("elasticsearch
9200, 9300")] + end + end + subgraph proflf["Profile langfuse"] + subgraph lfapp["Langfuse services"] + lfserver["langfuse-server
3000"] + lfworker["langfuse-worker
no port"] + end + lfpg[("langfuse-postgres
5432, network only")] + lfch[("langfuse-clickhouse
8123, 9000, network only")] + lfminio[("langfuse-minio
9000, 9001, network only")] + end + end + + subgraph proxy["nginx.conf, no Compose service loads it"] + n443["listen 443 ssl"] + admin["admin:8501
not in docker-compose.yml"] + end + + p8000 --> api + p5432 --> postgres + p9200 --> elastic + p9300 --> elastic + p3000 --> lfserver + + app -->|"REDIS_URL"| redis + lfapp -->|"REDIS_HOST"| redis + app -.->|"if set as a storage"| stores + app -.->|"OTLP, if set in .env"| lfserver + lfapp --> lfpg + lfapp --> lfch + lfapp --> lfminio + n443 -.->|"/ to api:8000"| api + n443 -.->|"/admin"| admin + + classDef accent stroke:#0BB81E,stroke-width:3px + classDef absent fill:#FFFFFF,stroke:#8A8A8D,stroke-dasharray:4 3 + class p8000 accent + class n443,admin absent diff --git a/docs/diagrams/D02-container-port-map.svg b/docs/diagrams/D02-container-port-map.svg new file mode 100644 index 00000000..4b0af4e4 --- /dev/null +++ b/docs/diagrams/D02-container-port-map.svg @@ -0,0 +1 @@ +

nginx.conf, no Compose service loads it

Docker network conserver, external, create it first

Docker host, published ports

Profile langfuse

Local storage profiles

Always started

Langfuse services

Profile elasticsearch

Profile postgres

Built from docker/Dockerfile

REDIS_URL

REDIS_HOST

if set as a storage

OTLP, if set in .env

/ to api:8000

/admin

8000
CONSERVER_EXTERNAL_PORT

5432

9200

9300

3000

api
container port 8000

conserver
no port

redis
6379, network only

postgres
5432

elasticsearch
9200, 9300

langfuse-server
3000

langfuse-worker
no port

langfuse-postgres
5432, network only

langfuse-clickhouse
8123, 9000, network only

langfuse-minio
9000, 9001, network only

listen 443 ssl

admin:8501
not in docker-compose.yml

\ No newline at end of file diff --git a/docs/diagrams/D02.sources.md b/docs/diagrams/D02.sources.md new file mode 100644 index 00000000..193b6bfc --- /dev/null +++ b/docs/diagrams/D02.sources.md @@ -0,0 +1,52 @@ +# D02 sources + +Container and port map. Drawn from the code at base commit `323109a`. Paths are relative to the repo root. + +## Nodes + +| Node | Source | +|---|---| +| Host port 8000, `CONSERVER_EXTERNAL_PORT` | `docker-compose.yml:53` | +| Host port 5432 | `docker-compose.yml:102` | +| Host ports 9200, 9300 | `docker-compose.yml:130`, `docker-compose.yml:131` | +| Host port 3000 | `docker-compose.yml:278` | +| Docker network `conserver`, external | `docker-compose.yml:1`, every service joins it, for example `docker-compose.yml:38` | +| Built from `docker/Dockerfile` | `docker-compose.yml:18`, `docker-compose.yml:47` | +| api, container port 8000 | `docker-compose.yml:45`, `docker-compose.yml:49` | +| conserver, no port | `docker-compose.yml:16`, no `ports` key in `docker-compose.yml:16` to `docker-compose.yml:43` | +| redis, 6379, network only | `docker-compose.yml:79`, `docker-compose.yml:81`, no `ports` key, port in `docker-compose.yml:96` | +| Profile postgres, postgres | `docker-compose.yml:98`, `docker-compose.yml:99` | +| Profile elasticsearch, elasticsearch | `docker-compose.yml:118`, `docker-compose.yml:119` | +| langfuse-server, 3000 | `docker-compose.yml:274`, `docker-compose.yml:275` | +| langfuse-worker, no port | `docker-compose.yml:318`, `docker-compose.yml:319` | +| langfuse-postgres, 5432 | `docker-compose.yml:386`, `docker-compose.yml:287` | +| langfuse-clickhouse, 8123 and 9000 | `docker-compose.yml:367`, `docker-compose.yml:288`, `docker-compose.yml:289` | +| langfuse-minio, 9000 and 9001 | `docker-compose.yml:349`, `docker-compose.yml:303`, `docker-compose.yml:353` | +| nginx.conf, listen 443 ssl | `nginx.conf:12`. No service in `docker-compose.yml` mounts it, and `scripts/install_conserver.sh` never mentions nginx | +| admin:8501 | `nginx.conf:18`. No `admin` service exists in `docker-compose.yml` | + +## Edges + +| Edge | Source | +|---|---| +| 8000 to api | `docker-compose.yml:53` | +| 5432 to postgres | `docker-compose.yml:102` | +| 9200 and 9300 to elasticsearch | `docker-compose.yml:130`, `docker-compose.yml:131` | +| 3000 to langfuse-server | `docker-compose.yml:278` | +| api and conserver to redis, `REDIS_URL` | `common/settings.py:11`, `.env.example:10`, `docker-compose.yml:25`, `docker-compose.yml:54` | +| Langfuse services to redis, `REDIS_HOST` | `docker-compose.yml:292`, `docker-compose.yml:334`. Langfuse shares the conserver Redis | +| api and conserver to the local storage profiles | `common/storage/postgres/__init__.py:18`, `common/storage/elasticsearch/__init__.py:5`, `common/storage/base.py:50`. Compose wires nothing here; a `storages` entry in the config does | +| api and conserver to langfuse-server, OTLP | `docker-compose.yml:270`, `.env.example:52`, `docker-compose.yml:32`, `docker-compose.yml:61` | +| Langfuse services to langfuse-postgres | `docker-compose.yml:287`, `docker-compose.yml:329` | +| Langfuse services to langfuse-clickhouse | `docker-compose.yml:289`, `docker-compose.yml:331` | +| Langfuse services to langfuse-minio | `docker-compose.yml:303`, `docker-compose.yml:343` | +| nginx `/` to api:8000 | `nginx.conf:26`, `nginx.conf:27` | +| nginx `/admin` to admin:8501 | `nginx.conf:17`, `nginx.conf:18` | + +## Notes + +`scripts/docs/descriptions.yml` and `docs/reference/ports.md` carry the same port facts in table form. + +The commented `jlinc-server`, `jlinc-db`, `fedid-*` services and Traefik labels in `docker-compose.yml` are off, so they are not drawn. + +Line 2 of each `.mmd` here sets the top-level `fontFamily`. `fontFamily` under `themeVariables` in `_init.txt` and `vconic-theme.json` does not reach the root of the SVG with mermaid-cli 12.2.0: the SVG then paints in the browser default serif and clips labels measured at a different width. Line 1 stays the exact `_init.txt` line. diff --git a/docs/diagrams/D03-deploy-map.mmd b/docs/diagrams/D03-deploy-map.mmd new file mode 100644 index 00000000..ad081fcc --- /dev/null +++ b/docs/diagrams/D03-deploy-map.mmd @@ -0,0 +1,58 @@ +%%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, Helvetica, Arial, sans-serif','fontSize':'14px','background':'#FFFFFF','primaryColor':'#F3F4F6','primaryTextColor':'#292929','primaryBorderColor':'#0A7D18','secondaryColor':'#FFFFFF','secondaryTextColor':'#33363B','secondaryBorderColor':'#8A8A8D','tertiaryColor':'#FFFFFF','tertiaryTextColor':'#33363B','tertiaryBorderColor':'#8A8A8D','lineColor':'#33363B','textColor':'#33363B','mainBkg':'#F3F4F6','nodeBorder':'#0A7D18','clusterBkg':'#FFFFFF','clusterBorder':'#8A8A8D','edgeLabelBackground':'#FFFFFF','actorBkg':'#F3F4F6','actorBorder':'#0A7D18','actorTextColor':'#292929','signalColor':'#33363B','signalTextColor':'#292929','labelBoxBkgColor':'#F3F4F6','labelBoxBorderColor':'#0A7D18','noteBkgColor':'#F3F4F6','noteBorderColor':'#8A8A8D','noteTextColor':'#292929'}}}%% +%%{init: {'fontFamily':'Inter, Helvetica, Arial, sans-serif'}}%% +flowchart TB + subgraph compose["Docker Compose, one host"] + cimg["docker/Dockerfile
all dependency groups, for dev and tests"] + cstack["api, conserver, redis
plus COMPOSE_PROFILES services"] + cimg --> cstack + end + + subgraph script["Automated script, Ubuntu"] + inst["scripts/install_conserver.sh
installs Docker, creates network conserver"] + sadmin["/opt/vcon-admin
clone, then docker compose up"] + sserver["/opt/vcon-server
clone, write .env and config.yml,
then docker compose up"] + inst --> sadmin + inst --> sserver + end + + subgraph manual["Manual, no containers"] + uvsync["uv sync --group api --group conserver"] + procs["uvicorn api:app
python conserver/main.py"] + localredis[("Redis you run
REDIS_URL")] + uvsync --> procs + procs --> localredis + end + + subgraph published["Published images"] + dapi["docker/Dockerfile.api"] + dcon["docker/Dockerfile.conserver"] + wf["docker-publish.yml
push to main or v* tag"] + ecrapi["ECR vcon-server-api"] + ecrcon["ECR vcon-server-conserver"] + dapi --> wf + dcon --> wf + wf --> ecrapi + wf --> ecrcon + end + + subgraph k8s["Kubernetes, example manifests in the docs, none in the repo"] + ing["Ingress
path /api"] + apidep["api Deployment
2 replicas, port 8000"] + workerdep["worker Deployment
4 replicas, CONSERVER_WORKERS=2"] + hpa["worker HPA
2 to 10 on CPU"] + rsts[("redis StatefulSet
1 replica, 10Gi claim")] + cfg[/"ConfigMap, Secret"/] + ing --> apidep + hpa --> workerdep + apidep --> rsts + workerdep --> rsts + cfg --> apidep + cfg --> workerdep + end + + sserver -->|"same compose file"| cstack + ecrapi -.->|"image to set"| apidep + ecrcon -.->|"image to set"| workerdep + + classDef accent stroke:#0BB81E,stroke-width:3px + class cstack accent diff --git a/docs/diagrams/D03-deploy-map.svg b/docs/diagrams/D03-deploy-map.svg new file mode 100644 index 00000000..b314ca00 --- /dev/null +++ b/docs/diagrams/D03-deploy-map.svg @@ -0,0 +1 @@ +

Kubernetes, example manifests in the docs, none in the repo

Published images

Manual, no containers

Automated script, Ubuntu

Docker Compose, one host

same compose file

image to set

image to set

docker/Dockerfile
all dependency groups, for dev and tests

api, conserver, redis
plus COMPOSE_PROFILES services

scripts/install_conserver.sh
installs Docker, creates network conserver

/opt/vcon-admin
clone, then docker compose up

/opt/vcon-server
clone, write .env and config.yml,
then docker compose up

uv sync --group api --group conserver

uvicorn api:app
python conserver/main.py

Redis you run
REDIS_URL

docker/Dockerfile.api

docker/Dockerfile.conserver

docker-publish.yml
push to main or v* tag

ECR vcon-server-api

ECR vcon-server-conserver

Ingress
path /api

api Deployment
2 replicas, port 8000

worker Deployment
4 replicas, CONSERVER_WORKERS=2

worker HPA
2 to 10 on CPU

redis StatefulSet
1 replica, 10Gi claim

ConfigMap, Secret

\ No newline at end of file diff --git a/docs/diagrams/D03.sources.md b/docs/diagrams/D03.sources.md new file mode 100644 index 00000000..7832e1ec --- /dev/null +++ b/docs/diagrams/D03.sources.md @@ -0,0 +1,51 @@ +# D03 sources + +Deploy map. Drawn from the code at base commit `323109a`. Paths are relative to the repo root. + +## Nodes + +| Node | Source | +|---|---| +| `docker/Dockerfile`, all dependency groups | `docker/Dockerfile:1`, `docker/Dockerfile:37` | +| api, conserver, redis plus profile services | `docker-compose.yml:16`, `docker-compose.yml:45`, `docker-compose.yml:79`, profile note at `docker-compose.yml:5` | +| `scripts/install_conserver.sh` | `scripts/install_conserver.sh:134` Docker, `scripts/install_conserver.sh:165` network | +| `/opt/vcon-admin` | `scripts/install_conserver.sh:178`, `scripts/install_conserver.sh:241` | +| `/opt/vcon-server` | `scripts/install_conserver.sh:257`, `scripts/install_conserver.sh:279`, `scripts/install_conserver.sh:297`, `scripts/install_conserver.sh:328` | +| `uv sync --group api --group conserver` | `pyproject.toml:56`, `pyproject.toml:66`, same groups as `docker/Dockerfile:37` | +| `uvicorn api:app`, `python conserver/main.py` | `docker/Dockerfile.api:46`, `docker/Dockerfile.conserver:52`. Both need the paths in `docker/Dockerfile:47` or `pytest.ini:2` on `PYTHONPATH` | +| Redis you run | `common/settings.py:11` | +| `docker/Dockerfile.api` | `docker/Dockerfile.api:1`, `docker/Dockerfile.api:31` | +| `docker/Dockerfile.conserver` | `docker/Dockerfile.conserver:1`, `docker/Dockerfile.conserver:37` | +| `docker-publish.yml` | `.github/workflows/docker-publish.yml:12` | +| ECR `vcon-server-api`, `vcon-server-conserver` | `.github/workflows/docker-publish.yml:5`, `.github/workflows/docker-publish.yml:6` | +| Ingress, path `/api` | `docs/installation/kubernetes.md:344`, `docs/installation/kubernetes.md:360`. `/api` paths reach the app: `api/api.py:85` sets `root_path`, and with the pinned FastAPI 0.115.6 and Starlette 0.41.3 both `/health` and `/api/health` return 200 (tested 2026-11-03) | +| api Deployment, 2 replicas, port 8000 | `docs/installation/kubernetes.md:207`, `docs/installation/kubernetes.md:212`, `docs/installation/kubernetes.md:232` | +| worker Deployment, 4 replicas, `CONSERVER_WORKERS=2` | `docs/installation/kubernetes.md:275`, `docs/installation/kubernetes.md:281`, `docs/installation/kubernetes.md:306` | +| worker HPA, 2 to 10 on CPU | `docs/installation/kubernetes.md:374`, `docs/installation/kubernetes.md:383`, `docs/installation/kubernetes.md:384` | +| redis StatefulSet, 1 replica, 10Gi claim | `docs/installation/kubernetes.md:150`, `docs/installation/kubernetes.md:156`, `docs/installation/kubernetes.md:187` | +| ConfigMap, Secret | `docs/installation/kubernetes.md:78`, `docs/installation/kubernetes.md:114` | + +## Edges + +| Edge | Source | +|---|---| +| `docker/Dockerfile` to Compose stack | `docker-compose.yml:18`, `docker-compose.yml:47` | +| Script to `/opt/vcon-admin` and `/opt/vcon-server` | `scripts/install_conserver.sh:178`, `scripts/install_conserver.sh:257` | +| `/opt/vcon-server` to Compose stack | `scripts/install_conserver.sh:328` runs the repo `docker-compose.yml` | +| `uv sync` to the processes | `docker/Dockerfile:37` to `docker/Dockerfile:50` show the same order | +| Processes to Redis | `common/redis_mgr.py:22` | +| Dockerfiles to `docker-publish.yml` | `.github/workflows/docker-publish.yml:52`, `.github/workflows/docker-publish.yml:64` | +| `docker-publish.yml` to ECR | `.github/workflows/docker-publish.yml:96`, `.github/workflows/docker-publish.yml:139` | +| ECR images to the Deployments, dashed | Drawn from the workflow, not from the docs page. `docs/installation/kubernetes.md:223` and `docs/installation/kubernetes.md:292` name `vcon-server:latest`, which the workflow does not build | +| Ingress to api Deployment | `docs/installation/kubernetes.md:362` to `docs/installation/kubernetes.md:366` | +| HPA to worker Deployment | `docs/installation/kubernetes.md:379` | +| api and worker Deployments to redis | `docs/installation/kubernetes.md:234`, `docs/installation/kubernetes.md:297` | +| ConfigMap and Secret to the Deployments | `docs/installation/kubernetes.md:236`, `docs/installation/kubernetes.md:243`, `docs/installation/kubernetes.md:299`, `docs/installation/kubernetes.md:322` | + +## Notes + +No Kubernetes manifest ships in this repo. The Kubernetes group shows the example in the docs page, not a tested deployment. + +The manifests in that page set no command, so each image's own `CMD` applies (`docker/Dockerfile.api:46`, `docker/Dockerfile.conserver:52`). + +TODO(verify): `scripts/install_conserver.sh:234` and `scripts/install_conserver.sh:340` expect HTTPS on `/api`, and no file in this repo sets that up. The proxy probably comes from the `vcon-admin` Compose project, which is outside this repo. diff --git a/docs/diagrams/D04-ingress-paths.mmd b/docs/diagrams/D04-ingress-paths.mmd new file mode 100644 index 00000000..d9fb9dff --- /dev/null +++ b/docs/diagrams/D04-ingress-paths.mmd @@ -0,0 +1,47 @@ +%%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, Helvetica, Arial, sans-serif','fontSize':'14px','background':'#FFFFFF','primaryColor':'#F3F4F6','primaryTextColor':'#292929','primaryBorderColor':'#0A7D18','secondaryColor':'#FFFFFF','secondaryTextColor':'#33363B','secondaryBorderColor':'#8A8A8D','tertiaryColor':'#FFFFFF','tertiaryTextColor':'#33363B','tertiaryBorderColor':'#8A8A8D','lineColor':'#33363B','textColor':'#33363B','mainBkg':'#F3F4F6','nodeBorder':'#0A7D18','clusterBkg':'#FFFFFF','clusterBorder':'#8A8A8D','edgeLabelBackground':'#FFFFFF','actorBkg':'#F3F4F6','actorBorder':'#0A7D18','actorTextColor':'#292929','signalColor':'#33363B','signalTextColor':'#292929','labelBoxBkgColor':'#F3F4F6','labelBoxBorderColor':'#0A7D18','noteBkgColor':'#F3F4F6','noteBorderColor':'#8A8A8D','noteTextColor':'#292929'}}}%% +%%{init: {'fontFamily':'Inter, Helvetica, Arial, sans-serif'}}%% +flowchart LR + client["API client"] + partner["Third-party sender"] + upstream["Upstream conserver"] + + subgraph apisvc["api service"] + postvcon["POST /vcon
global API key, full vCon"] + external["POST /vcon/external-ingress
per-list key from ingress_auth, full vCon"] + ingress["POST /vcon/ingress
global API key, list of UUIDs"] + store["Cache vcon:uuid for VCON_REDIS_EXPIRY
add to sorted set, index parties"] + verify["MGET bodies from Redis
on a miss, load from storage
if still missing, warn and skip"] + end + + subgraph follow["conserver main process"] + follower["follower.py timer
every pulling_interval"] + fset["SET vcon:uuid, keeps any TTL, none on a new key
no sorted set, no party index"] + end + + subgraph reentry["Internal re-entry"] + egress["Chain egress_lists
when another chain reads that list"] + router["tag_router link
tag_routes target lists"] + dlq["POST /dlq/reprocess
LPOP DLQ, up to count items"] + end + + list[("Redis ingress list
RPUSH vCon UUID")] + worker["worker_loop
BLPOP every chain ingress list"] + + client --> postvcon + client --> ingress + partner --> external + postvcon --> store + external --> store + ingress --> verify + store -->|"POST /vcon: only with ingress_lists
external: always, one list"| list + verify -->|"found UUIDs, one RPUSH"| list + follower -->|"GET /vcon/egress pops UUIDs,
then GET /vcon/{uuid} for each"| upstream + follower --> fset + fset -->|"follower_ingress_list"| list + egress -.-> list + router -.-> list + dlq -.-> list + list -->|"BLPOP, 15 s timeout"| worker + + classDef accent stroke:#0BB81E,stroke-width:3px + class list accent diff --git a/docs/diagrams/D04-ingress-paths.svg b/docs/diagrams/D04-ingress-paths.svg new file mode 100644 index 00000000..38211338 --- /dev/null +++ b/docs/diagrams/D04-ingress-paths.svg @@ -0,0 +1 @@ +

Internal re-entry

conserver main process

api service

POST /vcon: only with ingress_lists
external: always, one list

found UUIDs, one RPUSH

GET /vcon/egress pops UUIDs,
then GET /vcon/{uuid} for each

follower_ingress_list

BLPOP, 15 s timeout

API client

Third-party sender

Upstream conserver

POST /vcon
global API key, full vCon

POST /vcon/external-ingress
per-list key from ingress_auth, full vCon

POST /vcon/ingress
global API key, list of UUIDs

Cache vcon:uuid for VCON_REDIS_EXPIRY
add to sorted set, index parties

MGET bodies from Redis
on a miss, load from storage
if still missing, warn and skip

follower.py timer
every pulling_interval

SET vcon:uuid, keeps any TTL, none on a new key
no sorted set, no party index

Chain egress_lists
when another chain reads that list

tag_router link
tag_routes target lists

POST /dlq/reprocess
LPOP DLQ, up to count items

Redis ingress list
RPUSH vCon UUID

worker_loop
BLPOP every chain ingress list

\ No newline at end of file diff --git a/docs/diagrams/D04.sources.md b/docs/diagrams/D04.sources.md new file mode 100644 index 00000000..55b96875 --- /dev/null +++ b/docs/diagrams/D04.sources.md @@ -0,0 +1,49 @@ +# D04 sources + +Ingress paths. Drawn from the code at base commit `323109a`. Paths are relative to the repo root. + +## Nodes + +| Node | Source | +|---|---| +| API client | `api/api.py:1371` | +| Third-party sender | `api/api.py:824` | +| Upstream conserver | `conserver/follower.py:23`, the `url` key of a `followers` entry | +| `POST /vcon` | `api/api.py:750`, `api/api.py:758`, body type `Vcon` | +| `POST /vcon/external-ingress` | `api/api.py:824`, `api/api.py:877`, `api/api.py:878`, keys from `common/config.py:79` | +| `POST /vcon/ingress` | `api/api.py:992`, `api/api.py:1000`, body is `List[UUID]` | +| Cache, sorted set, party index | `api/api.py:789`, `api/api.py:792`, `api/api.py:795` for `POST /vcon`; `api/api.py:893`, `api/api.py:896`, `api/api.py:899` for external ingress. TTL at `api/api.py:452`, default at `common/settings.py:38` | +| MGET, storage load, warn and skip | `api/api.py:1023`, `api/api.py:1031`, `api/api.py:1037` | +| `follower.py` timer | `conserver/follower.py:53`, `conserver/follower.py:55`, `conserver/follower.py:67` | +| SET, keeps any TTL, none on a new key, no sorted set, no party index | `conserver/follower.py:49`, `common/redis_mgr.py:29`, `common/redis_mgr.py:57`. `follower.py` makes no other write | +| Chain `egress_lists` | `conserver/main.py:352`, `conserver/main.py:366`. A chain reads that list only if it names it, `conserver/main.py:682` | +| `tag_router` link | `conserver/links/tag_router/__init__.py:84`, `conserver/links/tag_router/__init__.py:88` | +| `POST /dlq/reprocess` | `api/api.py:1142`, `api/api.py:1168`, `api/api.py:1171`, count limit at `api/api.py:1155` | +| Redis ingress list | `common/lib/queue.py:64`, `common/lib/queue.py:149`, both RPUSH | +| `worker_loop` | `conserver/main.py:774`, `conserver/main.py:865`, `conserver/main.py:866` | + +## Edges + +| Edge | Source | +|---|---| +| API client to `POST /vcon` and `POST /vcon/ingress` | `api/api.py:1371` applies `get_api_key` to both | +| Third-party sender to external ingress | `api/api.py:1377` skips the global key; `api/api.py:127` checks the per-list key | +| `POST /vcon` and external ingress to cache | `api/api.py:789`, `api/api.py:893` | +| `POST /vcon/ingress` to MGET | `api/api.py:1023` | +| Cache to ingress list, conditions | `api/api.py:798` only when `ingress_lists` is set, one RPUSH per list at `api/api.py:806`. External ingress always pushes to its one list, `api/api.py:908` | +| MGET to ingress list, one RPUSH | `api/api.py:1046` | +| Follower to Upstream conserver | `conserver/follower.py:22` to `conserver/follower.py:33` pop, `conserver/follower.py:41` and `conserver/follower.py:42` fetch. The pop is the upstream `RPOP`, `api/api.py:591` | +| Follower to SET | `conserver/follower.py:49` | +| SET to ingress list, `follower_ingress_list` | `conserver/follower.py:50` | +| Chain `egress_lists` to ingress list | `conserver/main.py:366` | +| `tag_router` to ingress list | `conserver/links/tag_router/__init__.py:88` | +| `POST /dlq/reprocess` to ingress list | `api/api.py:1168`, `api/api.py:1171`, `common/lib/queue.py:163` | +| Ingress list to `worker_loop`, BLPOP with 15 s timeout | `conserver/main.py:875`, `common/lib/queue.py:90` | + +## Notes + +A list with no chain behind it is never read: workers only watch lists named in a chain's `ingress_lists`, `conserver/main.py:679`. The API does not check this on push. + +The follower pop is destructive on the upstream side. A vCon that then returns 404 is logged and dropped, `conserver/follower.py:43`. + +`conserver/main.py:898` returns a popped vCon to the head of its list on shutdown. That belongs to the worker topology and is drawn in D06. diff --git a/docs/diagrams/D05-chain-pipeline.mmd b/docs/diagrams/D05-chain-pipeline.mmd new file mode 100644 index 00000000..ef0ed65d --- /dev/null +++ b/docs/diagrams/D05-chain-pipeline.mmd @@ -0,0 +1,49 @@ +%%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, Helvetica, Arial, sans-serif','fontSize':'14px','background':'#FFFFFF','primaryColor':'#F3F4F6','primaryTextColor':'#292929','primaryBorderColor':'#0A7D18','secondaryColor':'#FFFFFF','secondaryTextColor':'#33363B','secondaryBorderColor':'#8A8A8D','tertiaryColor':'#FFFFFF','tertiaryTextColor':'#33363B','tertiaryBorderColor':'#8A8A8D','lineColor':'#33363B','textColor':'#33363B','mainBkg':'#F3F4F6','nodeBorder':'#0A7D18','clusterBkg':'#FFFFFF','clusterBorder':'#8A8A8D','edgeLabelBackground':'#FFFFFF','actorBkg':'#F3F4F6','actorBorder':'#0A7D18','actorTextColor':'#292929','signalColor':'#33363B','signalTextColor':'#292929','labelBoxBkgColor':'#F3F4F6','labelBoxBorderColor':'#0A7D18','noteBkgColor':'#F3F4F6','noteBorderColor':'#8A8A8D','noteTextColor':'#292929'}}}%% +%%{init: {'fontFamily':'Inter, Helvetica, Arial, sans-serif'}}%% +flowchart TD + ingress[("Ingress list
Redis list of vCon ids")] + pop["worker_loop pops one id
and finds the chain for that list"] + before{"hook.before_processing
returns truthy?"} + link["Next link runs
module.run(vcon_id, link_name, options)"] + result{"What did the
link return?"} + swap["Chain carries the
new id forward"] + more{"More links
in the chain?"} + routed[("Another Redis list")] + skipped(["vCon skipped
no links, storage or egress"]) + halted(["Chain halted
no storage or egress"]) + dlq[("DLQ:ingress_list
TTL set to VCON_DLQ_EXPIRY")] + after["hook.after_processing
runs on every path"] + + subgraph wrap["_wrap_up, in this order"] + egress["Push id to each egress list
trace context stored first"] + mode{"Parallel storage on
and 2 or more backends?"} + seq["One backend at a time"] + par["One thread per backend"] + save["Storage(name).save(vcon_id)"] + sdlq[("DLQ:storage:backend
body TTL extended")] + end + + ingress --> pop --> before + before -- "falsy" --> skipped + before -- "truthy" --> link + before -- "raises" --> dlq + link --> result + link -. "tag_router only" .-> routed + result -- "same id" --> more + result -- "new id" --> swap --> more + result -- "falsy" --> halted + result -- "raises" --> dlq + more -- "yes" --> link + more -- "no" --> egress + egress --> mode + mode -- "yes" --> par --> save + mode -- "no" --> seq --> save + save -- "raises" --> sdlq + save -- "ok" --> after + sdlq --> after + skipped --> after + halted --> after + dlq --> after + + classDef key stroke:#0BB81E,stroke-width:3px + class link key diff --git a/docs/diagrams/D05-chain-pipeline.svg b/docs/diagrams/D05-chain-pipeline.svg new file mode 100644 index 00000000..c13065e4 --- /dev/null +++ b/docs/diagrams/D05-chain-pipeline.svg @@ -0,0 +1 @@ +

_wrap_up, in this order

falsy

truthy

raises

tag_router only

same id

new id

falsy

raises

yes

no

yes

no

raises

ok

Ingress list
Redis list of vCon ids

worker_loop pops one id
and finds the chain for that list

hook.before_processing
returns truthy?

Next link runs
module.run(vcon_id, link_name, options)

What did the
link return?

Chain carries the
new id forward

More links
in the chain?

Another Redis list

vCon skipped
no links, storage or egress

Chain halted
no storage or egress

DLQ:ingress_list
TTL set to VCON_DLQ_EXPIRY

hook.after_processing
runs on every path

Push id to each egress list
trace context stored first

Parallel storage on
and 2 or more backends?

One backend at a time

One thread per backend

Storage(name).save(vcon_id)

DLQ:storage:backend
body TTL extended

\ No newline at end of file diff --git a/docs/diagrams/D05.sources.md b/docs/diagrams/D05.sources.md new file mode 100644 index 00000000..91fc7639 --- /dev/null +++ b/docs/diagrams/D05.sources.md @@ -0,0 +1,55 @@ +# D05 traces the chain pipeline + +Diagram: `D05-chain-pipeline.mmd`. Line numbers refer to the worktree at the time of drawing. + +## Each node maps to code + +| Node | Code | +|---|---| +| Ingress list | `common/lib/queue.py:81`, `conserver/main.py:875` | +| worker_loop pops one id and finds the chain | `conserver/main.py:875`, `conserver/main.py:883`, `conserver/main.py:901`, map built at `conserver/main.py:673` | +| hook.before_processing returns truthy | `conserver/main.py:747`, `conserver/hook.py:11` | +| Next link runs | `conserver/main.py:255`, `conserver/main.py:256`, `conserver/main.py:603` | +| What did the link return | `conserver/main.py:257`, `conserver/main.py:264` | +| Chain carries the new id forward | `conserver/main.py:271` | +| More links in the chain | `conserver/main.py:255` | +| Another Redis list | `conserver/links/tag_router/__init__.py:88` | +| vCon skipped | `conserver/main.py:747`, `conserver/main.py:752` | +| Chain halted | `conserver/main.py:257`, `conserver/main.py:263`, `conserver/main.py:273` | +| DLQ:ingress_list, TTL set | `conserver/main.py:761`, `conserver/main.py:762`, `conserver/main.py:763`, `common/lib/queue.py:92`, `common/dlq_utils.py:3`, `common/settings.py:56` | +| _wrap_up, in this order | `conserver/main.py:273`, `conserver/main.py:345` | +| Push id to each egress list, context first | `conserver/main.py:352`, `conserver/main.py:360`, `conserver/main.py:365`, `conserver/main.py:366` | +| Parallel storage on and 2 or more backends | `conserver/main.py:376`, `common/config.py:24`, `common/settings.py:66` | +| One backend at a time | `conserver/main.py:381` | +| One thread per backend | `conserver/main.py:475` | +| Storage(name).save(vcon_id) | `conserver/main.py:410`, `common/storage/base.py:64` | +| DLQ:storage:backend, body TTL extended | `conserver/main.py:429`, `conserver/main.py:447`, `common/lib/queue.py:111`, `common/dlq_utils.py:7` | +| hook.after_processing | `conserver/main.py:764`, `conserver/main.py:766`, `conserver/hook.py:31` | + +## Each edge maps to code + +| Edge | Code | +|---|---| +| Ingress list to worker_loop to before_processing | `conserver/main.py:875`, `conserver/main.py:905`, `conserver/main.py:747` | +| before_processing falsy to skipped | `conserver/main.py:747`, `conserver/main.py:752` | +| before_processing truthy to first link | `conserver/main.py:753`, `conserver/main.py:255` | +| before_processing raises to DLQ | the call sits in the `try` at `conserver/main.py:744`, caught at `conserver/main.py:754` | +| Link to tag_router list, dashed | `conserver/links/tag_router/__init__.py:88` | +| Result same id to more links | `conserver/main.py:255`, `conserver/main.py:264` | +| Result new id to carry forward | `conserver/main.py:264`, `conserver/main.py:271` | +| Result falsy to halted | `conserver/main.py:257`, `conserver/main.py:263` | +| Result raises to DLQ | `conserver/main.py:670`, `conserver/main.py:754`, `conserver/main.py:761` | +| More links no to egress | `conserver/main.py:273`, `conserver/main.py:274` | +| Egress to storage decision | `conserver/main.py:368`, `conserver/main.py:376` | +| Save raises to storage DLQ | `conserver/main.py:411`, `conserver/main.py:429` | +| Skipped, halted, DLQ and saved paths to after_processing | `finally` at `conserver/main.py:764` | + +## Notes cover the unusual paths + +- Egress runs before storage (`conserver/main.py:352` then `conserver/main.py:368`). A downstream chain can start before the save ends. +- A failed save goes to the storage DLQ and does not fail the chain (`conserver/main.py:425`). +- `links: []` skips the loop and goes straight to `_wrap_up`. A chain with no `links` key raises `KeyError` at `conserver/main.py:255` and lands on the ingress DLQ. +- No `egress_lists` or no `storages` skips that step (`conserver/main.py:353`, `conserver/main.py:369`). +- A halted chain still counts in `conserver.main_loop.count_vcons_processed` (`conserver/main.py:288`). +- A chain `timeout` is only logged (`conserver/main.py:732`) and `enabled` is never read by the worker (`conserver/main.py:679`), so the diagram shows neither. +- Two chains that share an ingress list collapse to the later chain (`conserver/main.py:683`). diff --git a/docs/diagrams/D06-worker-queue-topology.mmd b/docs/diagrams/D06-worker-queue-topology.mmd new file mode 100644 index 00000000..059e3564 --- /dev/null +++ b/docs/diagrams/D06-worker-queue-topology.mmd @@ -0,0 +1,47 @@ +%%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, Helvetica, Arial, sans-serif','fontSize':'14px','background':'#FFFFFF','primaryColor':'#F3F4F6','primaryTextColor':'#292929','primaryBorderColor':'#0A7D18','secondaryColor':'#FFFFFF','secondaryTextColor':'#33363B','secondaryBorderColor':'#8A8A8D','tertiaryColor':'#FFFFFF','tertiaryTextColor':'#33363B','tertiaryBorderColor':'#8A8A8D','lineColor':'#33363B','textColor':'#33363B','mainBkg':'#F3F4F6','nodeBorder':'#0A7D18','clusterBkg':'#FFFFFF','clusterBorder':'#8A8A8D','edgeLabelBackground':'#FFFFFF','actorBkg':'#F3F4F6','actorBorder':'#0A7D18','actorTextColor':'#292929','signalColor':'#33363B','signalTextColor':'#292929','labelBoxBkgColor':'#F3F4F6','labelBoxBorderColor':'#0A7D18','noteBkgColor':'#F3F4F6','noteBorderColor':'#8A8A8D','noteTextColor':'#292929'}}}%% +%%{init: {'fontFamily':'Inter, Helvetica, Arial, sans-serif'}}%% +flowchart TD + subgraph sources["Producers"] + apiin["API ingress routes
POST /vcon with ingress_lists
POST /vcon/external-ingress
POST /vcon/ingress"] + fol["Follower timers
in the main process"] + dlqapi["API replay route
POST /dlq/reprocess"] + end + + ingress[("Ingress lists")] + + subgraph conserver["Conserver"] + main["Main process
spawns CONSERVER_WORKERS processes
restarts dead ones, checks every 5 s
runs worker_loop itself when the count is 1"] + subgraph worker["Each worker process"] + loop["worker_loop
rereads config on each pass
BLPOP with a 15 s timeout"] + pool["Thread pool, only when
CONSERVER_VCON_CONCURRENCY
is above 1"] + handle["_handle_vcon
runs one chain"] + end + end + + dlq[("DLQ:ingress_list")] + egress[("Egress lists")] + sdlq[("DLQ:storage:backend")] + backends[("Storage backends")] + egressapi["GET /vcon/egress
client or remote follower"] + sdlqapi["POST /dlq/storage/reprocess"] + + apiin -- "RPUSH" --> ingress + fol -- "RPUSH" --> ingress + dlqapi -- "RPUSH" --> ingress + main -- "spawns" --> loop + ingress -- "BLPOP" --> loop + loop -. "LPUSH popped id on shutdown" .-> ingress + loop -- "concurrency 1" --> handle + loop -- "above 1" --> pool --> handle + handle -- "RPUSH on exception" --> dlq + handle -- "RPUSH after links" --> egress + handle -- "save" --> backends + handle -- "RPUSH on failed save" --> sdlq + dlq -- "LPOP" --> dlqapi + egress -- "RPOP" --> egressapi + egress -. "same name as an ingress list" .-> ingress + sdlq -- "LRANGE, LREM on success" --> sdlqapi + sdlqapi -- "save" --> backends + + classDef key stroke:#0BB81E,stroke-width:3px + class loop key diff --git a/docs/diagrams/D06-worker-queue-topology.svg b/docs/diagrams/D06-worker-queue-topology.svg new file mode 100644 index 00000000..92ff4d92 --- /dev/null +++ b/docs/diagrams/D06-worker-queue-topology.svg @@ -0,0 +1 @@ +

Conserver

Producers

Each worker process

RPUSH

RPUSH

RPUSH

spawns

BLPOP

LPUSH popped id on shutdown

concurrency 1

above 1

RPUSH on exception

RPUSH after links

save

RPUSH on failed save

LPOP

RPOP

same name as an ingress list

LRANGE, LREM on success

save

API ingress routes
POST /vcon with ingress_lists
POST /vcon/external-ingress
POST /vcon/ingress

Follower timers
in the main process

API replay route
POST /dlq/reprocess

Ingress lists

Main process
spawns CONSERVER_WORKERS processes
restarts dead ones, checks every 5 s
runs worker_loop itself when the count is 1

worker_loop
rereads config on each pass
BLPOP with a 15 s timeout

Thread pool, only when
CONSERVER_VCON_CONCURRENCY
is above 1

_handle_vcon
runs one chain

DLQ:ingress_list

Egress lists

DLQ:storage:backend

Storage backends

GET /vcon/egress
client or remote follower

POST /dlq/storage/reprocess

\ No newline at end of file diff --git a/docs/diagrams/D06.sources.md b/docs/diagrams/D06.sources.md new file mode 100644 index 00000000..3e50abff --- /dev/null +++ b/docs/diagrams/D06.sources.md @@ -0,0 +1,55 @@ +# D06 traces the worker and queue topology + +Diagram: `D06-worker-queue-topology.mmd`. Line numbers refer to the worktree at the time of drawing. + +## Each node maps to code + +| Node | Code | +|---|---| +| API ingress routes | `api/api.py:750`, `api/api.py:824`, `api/api.py:992` | +| Follower timers in the main process | `conserver/main.py:989`, `conserver/follower.py:53`, `conserver/follower.py:58` | +| POST /dlq/reprocess | `api/api.py:1142` | +| Ingress lists | `conserver/main.py:673`, `conserver/main.py:866` | +| Main process | `conserver/main.py:925`, spawn at `conserver/main.py:995`, 5 s check at `conserver/main.py:1012`, restart at `conserver/main.py:1023`, single worker at `conserver/main.py:1048` | +| CONSERVER_WORKERS | `common/settings.py:63`, `common/config.py:15` | +| worker_loop | `conserver/main.py:774`, config reread at `conserver/main.py:862`, BLPOP at `conserver/main.py:875`, `common/lib/queue.py:90` | +| Thread pool | `conserver/main.py:850`, `conserver/main.py:851`, `conserver/main.py:908`, back-pressure at `conserver/main.py:914`, `common/settings.py:81` | +| _handle_vcon | `conserver/main.py:702` | +| DLQ:ingress_list | `common/dlq_utils.py:3` | +| Egress lists | `conserver/main.py:352` | +| DLQ:storage:backend | `common/dlq_utils.py:7` | +| Storage backends | `common/storage/base.py:44` | +| GET /vcon/egress | `api/api.py:565`, remote caller at `conserver/follower.py:22` | +| POST /dlq/storage/reprocess | `api/api.py:1185` | + +## Each edge maps to code + +| Edge | Code | +|---|---| +| API ingress routes RPUSH | `api/api.py:806`, `api/api.py:908`, `api/api.py:1046`, `common/lib/queue.py:158` | +| Follower RPUSH | `conserver/follower.py:50`, `common/lib/queue.py:69` | +| /dlq/reprocess RPUSH | `api/api.py:1171` | +| Main spawns worker_loop | `conserver/main.py:997`, `conserver/main.py:998` | +| Ingress BLPOP to worker_loop | `conserver/main.py:875`, `common/lib/queue.py:90` | +| LPUSH popped id on shutdown | `conserver/main.py:890`, `conserver/main.py:898`, `common/lib/queue.py:79` | +| Concurrency 1 to _handle_vcon | `conserver/main.py:903`, `conserver/main.py:905` | +| Above 1 through the pool | `conserver/main.py:908` | +| RPUSH on exception | `conserver/main.py:761`, `common/lib/queue.py:107` | +| RPUSH after links | `conserver/main.py:366` | +| save | `conserver/main.py:410` | +| RPUSH on failed save | `conserver/main.py:447`, `common/lib/queue.py:121` | +| DLQ LPOP to /dlq/reprocess | `api/api.py:1168`, `common/lib/queue.py:173` | +| Egress RPOP | `api/api.py:591` | +| Egress name equals an ingress name, dashed | `conserver/main.py:366` writes the list that `conserver/main.py:875` reads when the names match | +| Storage DLQ LRANGE, LREM | `api/api.py:1230`, `api/api.py:1239` | +| /dlq/storage/reprocess save | `api/api.py:1233` | + +## Notes cover what the picture leaves out + +- BLPOP scans lists in order, and that order follows chain order in the config (`conserver/main.py:866`, `common/lib/queue.py:86`). Earlier lists win when several hold items. +- A popped id has no in-flight record. A worker that dies mid-chain loses that queue entry, and the main process only restarts the worker (`conserver/main.py:1015`). +- `imports` load once at worker start (`conserver/main.py:821`), while chains reload on every pass (`conserver/main.py:862`). +- Shutdown: the main process sends SIGTERM to live workers (`conserver/main.py:98`), then waits 30 s per worker before `terminate` (`conserver/main.py:1038`, `conserver/main.py:1041`). Thread pools drain first (`conserver/main.py:920`). +- The `tag_router` link can RPUSH to any named list (`conserver/links/tag_router/__init__.py:88`). D05 shows that edge. +- Trace context rides in `context::` beside the queue (`common/lib/context_utils.py:32`). Producers write it first and `_handle_vcon` reads it (`conserver/main.py:713`). `/dlq/reprocess` writes none. +- Followers run in the main process only, and the first poll runs inline at startup (`conserver/follower.py:54`). diff --git a/docs/diagrams/D07-vcon-lifecycle.mmd b/docs/diagrams/D07-vcon-lifecycle.mmd new file mode 100644 index 00000000..8341af44 --- /dev/null +++ b/docs/diagrams/D07-vcon-lifecycle.mmd @@ -0,0 +1,40 @@ +%%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, Helvetica, Arial, sans-serif','fontSize':'14px','background':'#FFFFFF','primaryColor':'#F3F4F6','primaryTextColor':'#292929','primaryBorderColor':'#0A7D18','secondaryColor':'#FFFFFF','secondaryTextColor':'#33363B','secondaryBorderColor':'#8A8A8D','tertiaryColor':'#FFFFFF','tertiaryTextColor':'#33363B','tertiaryBorderColor':'#8A8A8D','lineColor':'#33363B','textColor':'#33363B','mainBkg':'#F3F4F6','nodeBorder':'#0A7D18','clusterBkg':'#FFFFFF','clusterBorder':'#8A8A8D','edgeLabelBackground':'#FFFFFF','actorBkg':'#F3F4F6','actorBorder':'#0A7D18','actorTextColor':'#292929','signalColor':'#33363B','signalTextColor':'#292929','labelBoxBkgColor':'#F3F4F6','labelBoxBorderColor':'#0A7D18','noteBkgColor':'#F3F4F6','noteBorderColor':'#8A8A8D','noteTextColor':'#292929'}}}%% +%%{init: {'fontFamily':'Inter, Helvetica, Arial, sans-serif'}}%% +stateDiagram-v2 + direction TB + state "Cached in Redis, no queue" as Cached + state "Id on an ingress list" as Queued + state "Running a chain" as Running + state "Wrapping up" as WrapUp + state "Saved, body still in Redis" as Stored + state "Body in storage only" as Archived + state "Id on DLQ for its ingress list" as IngressDLQ + state "Id on DLQ for a backend" as StorageDLQ + state "Gone" as Gone + + [*] --> Cached: POST /vcon, no ingress_lists + [*] --> Queued: POST /vcon with ingress_lists, external ingress, follower + Cached --> Queued: POST /vcon/ingress + Archived --> Queued: POST /vcon/ingress recaches first + Queued --> Running: worker pops id + Running --> Running: link stores changes, TTL kept, expire_vcon sets TTL + Running --> Cached: before_processing falsy or link halts chain + Running --> IngressDLQ: exception, TTL set to VCON_DLQ_EXPIRY + IngressDLQ --> Queued: POST /dlq/reprocess + Running --> WrapUp: last link returns an id + WrapUp --> Queued: egress list feeds another chain + WrapUp --> Stored: every save succeeds + WrapUp --> StorageDLQ: a save raises, TTL extended + WrapUp --> Cached: chain has no storages + StorageDLQ --> Stored: POST /dlq/storage/reprocess succeeds + Stored --> Archived: Redis TTL reached + Archived --> Cached: read misses Redis, recached with VCON_REDIS_EXPIRY + Cached --> Gone: Redis TTL reached, no storage copy + IngressDLQ --> Gone: Redis TTL reached, no storage copy + Cached --> Gone: DELETE vCon + Stored --> Gone: DELETE vCon + Archived --> Gone: DELETE vCon + Gone --> [*] + + classDef key stroke:#0BB81E,stroke-width:3px + class Running key diff --git a/docs/diagrams/D07-vcon-lifecycle.svg b/docs/diagrams/D07-vcon-lifecycle.svg new file mode 100644 index 00000000..de6aa9e7 --- /dev/null +++ b/docs/diagrams/D07-vcon-lifecycle.svg @@ -0,0 +1 @@ +

POST /vcon, no ingress_lists

POST /vcon with ingress_lists, external ingress, follower

POST /vcon/ingress

POST /vcon/ingress recaches first

worker pops id

link stores changes, TTL kept, expire_vcon sets TTL

before_processing falsy or link halts chain

exception, TTL set to VCON_DLQ_EXPIRY

POST /dlq/reprocess

last link returns an id

egress list feeds another chain

every save succeeds

a save raises, TTL extended

chain has no storages

POST /dlq/storage/reprocess succeeds

Redis TTL reached

read misses Redis, recached with VCON_REDIS_EXPIRY

Redis TTL reached, no storage copy

Redis TTL reached, no storage copy

DELETE vCon

DELETE vCon

DELETE vCon

Cached in Redis, no queue

Id on an ingress list

Running a chain

Wrapping up

Saved, body still in Redis

Body in storage only

Id on DLQ for its ingress list

Id on DLQ for a backend

Gone

\ No newline at end of file diff --git a/docs/diagrams/D07.sources.md b/docs/diagrams/D07.sources.md new file mode 100644 index 00000000..36cfe38d --- /dev/null +++ b/docs/diagrams/D07.sources.md @@ -0,0 +1,56 @@ +# D07 traces the vCon lifecycle + +Diagram: `D07-vcon-lifecycle.mmd`. Line numbers refer to the worktree at the time of drawing. + +The states combine two facts: where the id sits in a queue, and where the body sits. Wrapping up pushes egress and saves to storage in the same pass, so one vCon can take the egress edge and a storage edge together. + +## Each state maps to code + +| State | Code | +|---|---| +| Cached in Redis, no queue | key `vcon:`, `api/api.py:450`, `common/redis_mgr.py:53` | +| Id on an ingress list | `common/lib/queue.py:64`, `common/lib/queue.py:149` | +| Running a chain | `conserver/main.py:232` | +| Wrapping up | `conserver/main.py:345` | +| Saved, body still in Redis | `conserver/main.py:410`. Nothing removes the Redis key after a save | +| Body in storage only | `common/lib/vcon_redis.py:113`, `api/api.py:477` | +| Id on DLQ for its ingress list | `common/lib/queue.py:92` | +| Id on DLQ for a backend | `common/lib/queue.py:111` | +| Gone | `api/api.py:956`, `api/api.py:965`, or Redis expiry with no storage copy | + +## Each transition maps to code + +| Transition | Code | +|---|---| +| POST /vcon, no ingress_lists | `api/api.py:789`, `api/api.py:798`, TTL from `api/api.py:452`, `common/settings.py:38` | +| POST /vcon with ingress_lists | `api/api.py:806` | +| External ingress | `api/api.py:893`, `api/api.py:908` | +| Follower | `conserver/follower.py:49`, `conserver/follower.py:50`. No TTL argument, so a new key has no expiry (`common/redis_mgr.py:29`, `common/redis_mgr.py:57`) | +| Cached to queued by POST /vcon/ingress | `api/api.py:1046` | +| Storage to queued by POST /vcon/ingress | `api/api.py:1031`, `api/api.py:501`, `api/api.py:1046` | +| Worker pops id | `conserver/main.py:875` | +| Link stores changes, TTL kept | `conserver/links/tag/__init__.py:40`, `common/lib/vcon_redis.py:107`, `common/redis_mgr.py:57` | +| expire_vcon sets TTL | `conserver/links/expire_vcon/__init__.py:20`, default at `conserver/links/expire_vcon/__init__.py:15`, `common/lib/queue.py:145` | +| before_processing falsy | `conserver/main.py:747` | +| Link halts chain | `conserver/main.py:257`, `conserver/main.py:273` | +| Exception to ingress DLQ, TTL set | `conserver/main.py:761`, `conserver/main.py:762`, `conserver/main.py:763` | +| POST /dlq/reprocess | `api/api.py:1168`, `api/api.py:1171` | +| Last link returns an id | `conserver/main.py:273`, `conserver/main.py:274` | +| Egress list feeds another chain | `conserver/main.py:366`, `conserver/main.py:683` | +| Every save succeeds | `conserver/main.py:410` | +| A save raises, TTL extended | `conserver/main.py:429`, `common/lib/queue.py:126`, `common/lib/queue.py:127` | +| Chain has no storages | `conserver/main.py:368`, `conserver/main.py:369` | +| POST /dlq/storage/reprocess succeeds | `api/api.py:1233`, `api/api.py:1239` | +| Redis TTL reached | Redis expiry of the TTL set by the rows above | +| Read misses Redis, recached | `common/lib/vcon_redis.py:217`, `common/lib/vcon_redis.py:222`, `common/lib/vcon_redis.py:152`, `api/api.py:474`, `api/api.py:501` | +| DELETE vCon | `api/api.py:932`, `api/api.py:956`, `api/api.py:965` | + +## Notes cover timing and carried data + +- Default TTLs: `VCON_REDIS_EXPIRY` 3600 s (`common/settings.py:38`), `VCON_DLQ_EXPIRY` 604800 s (`common/settings.py:56`), `expire_vcon` 86400 s. +- Setting `VCON_DLQ_EXPIRY` to 0 leaves the TTL alone on both DLQ paths (`conserver/main.py:762`, `common/lib/queue.py:126`). +- The TTL keeps running while the id waits. If it lapses, the id stays on its list and links get `None` from `get_vcon` unless a storage copy exists (`common/lib/vcon_redis.py:178`). The `tag` link then halts (`conserver/links/tag/__init__.py:19`). +- An id on a backend DLQ can outlive its body in the same way. The replay save then fails and the id stays put (`api/api.py:1234`). +- `VconRedis` writes pass through `_enforce_spec_on_write` (`common/lib/vcon_redis.py:61`). The API intake path (`api/api.py:789`) and the follower (`conserver/follower.py:49`) write without it. Reads normalise legacy fields (`common/lib/vcon_redis.py:223`). +- `VCON_STORAGE_FALLBACK_ENABLED` gates the `VconRedis` read path only (`common/lib/vcon_redis.py:120`). The API path at `api/api.py:491` does not check it. +- Any `lawful_basis` attachment travels with the body through every state. No state creates or checks one. diff --git a/docs/diagrams/D08-dead-letter-flow.mmd b/docs/diagrams/D08-dead-letter-flow.mmd new file mode 100644 index 00000000..3751b357 --- /dev/null +++ b/docs/diagrams/D08-dead-letter-flow.mmd @@ -0,0 +1,51 @@ +%%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, Helvetica, Arial, sans-serif','fontSize':'14px','background':'#FFFFFF','primaryColor':'#F3F4F6','primaryTextColor':'#292929','primaryBorderColor':'#0A7D18','secondaryColor':'#FFFFFF','secondaryTextColor':'#33363B','secondaryBorderColor':'#8A8A8D','tertiaryColor':'#FFFFFF','tertiaryTextColor':'#33363B','tertiaryBorderColor':'#8A8A8D','lineColor':'#33363B','textColor':'#33363B','mainBkg':'#F3F4F6','nodeBorder':'#0A7D18','clusterBkg':'#FFFFFF','clusterBorder':'#8A8A8D','edgeLabelBackground':'#FFFFFF','actorBkg':'#F3F4F6','actorBorder':'#0A7D18','actorTextColor':'#292929','signalColor':'#33363B','signalTextColor':'#292929','labelBoxBkgColor':'#F3F4F6','labelBoxBorderColor':'#0A7D18','noteBkgColor':'#F3F4F6','noteBorderColor':'#8A8A8D','noteTextColor':'#292929'}}}%% +%%{init: {'fontFamily':'Inter, Helvetica, Arial, sans-serif'}}%% +stateDiagram-v2 + direction TB + + state "Ingress list" as Ingress + state "Popped by a worker" as Popped + state "Links running" as Links + state "Wrap-up, egress then storage" as WrapUp + state "Ingress DLQ, DLQ:#lt;ingress_list#gt;" as IngressDLQ + state "Storage DLQ, DLQ:storage:#lt;backend#gt;" as StorageDLQ + state "Skipped by hook" as Skipped + state "Halted by a link" as Halted + state "Saved to the backend" as Saved + state "Manual recovery, error logged" as Manual + + [*] --> Ingress : RPUSH from API or follower + Ingress --> Popped : BLPOP by a worker + Popped --> Ingress : shutdown requested, LPUSH to head + Popped --> Skipped : before_processing returns falsy + Popped --> IngressDLQ : before_processing raises + Popped --> Links : chain starts + Links --> Halted : a link returns falsy + Links --> WrapUp : every link returns an id + Links --> IngressDLQ : exception in a link, hook or tracer + WrapUp --> IngressDLQ : egress enqueue raises + WrapUp --> Saved : backend save returns + WrapUp --> StorageDLQ : backend save raises + WrapUp --> Manual : dead-letter fails, body missing or Redis error + IngressDLQ --> Ingress : POST /dlq/reprocess, LPOP then RPUSH, whole chain runs again + StorageDLQ --> Saved : POST /dlq/storage/reprocess, write only, see D09 + StorageDLQ --> StorageDLQ : retry fails, entry stays + Skipped --> [*] + Halted --> [*] + Saved --> [*] + + note right of IngressDLQ + EXPIRE resets the + body TTL to the + DLQ expiry setting + unless that is 0. + GET /dlq only reads. + end note + + note right of StorageDLQ + One entry per + failed backend. + A longer TTL or a + persistent body + stays as it is. + end note diff --git a/docs/diagrams/D08-dead-letter-flow.svg b/docs/diagrams/D08-dead-letter-flow.svg new file mode 100644 index 00000000..14e7d2be --- /dev/null +++ b/docs/diagrams/D08-dead-letter-flow.svg @@ -0,0 +1 @@ +

RPUSH from API or follower

BLPOP by a worker

shutdown requested, LPUSH to head

before_processing returns falsy

before_processing raises

chain starts

a link returns falsy

every link returns an id

exception in a link, hook or tracer

egress enqueue raises

backend save returns

backend save raises

dead-letter fails, body missing or Redis error

POST /dlq/reprocess, LPOP then RPUSH, whole chain runs again

POST /dlq/storage/reprocess, write only, see D09

retry fails, entry stays

Ingress list

Popped by a worker

Links running

Wrap-up, egress then storage

Ingress DLQ, DLQ:<ingress_list>

Storage DLQ, DLQ:storage:<backend>

Skipped by hook

Halted by a link

Saved to the backend

Manual recovery, error logged

EXPIRE resets the
body TTL to the
DLQ expiry setting
unless that is 0.
GET /dlq only reads.

One entry per
failed backend.
A longer TTL or a
persistent body
stays as it is.

\ No newline at end of file diff --git a/docs/diagrams/D08.sources.md b/docs/diagrams/D08.sources.md new file mode 100644 index 00000000..76c39bc6 --- /dev/null +++ b/docs/diagrams/D08.sources.md @@ -0,0 +1,57 @@ +# D08 code sources + +Diagram: `D08-dead-letter-flow.mmd`. Drawn from the code at the worktree base, not from older docs. + +## States map to these lines + +| State | Code | +|---|---| +| Ingress list | `conserver/main.py:673` `get_ingress_chain_map`, `conserver/main.py:875` | +| Popped by a worker | `conserver/main.py:883` | +| Links running | `conserver/main.py:255-263`, `conserver/main.py:548` `_process_link` | +| Wrap-up, egress then storage | `conserver/main.py:345-388` `_wrap_up` | +| Ingress DLQ name | `common/dlq_utils.py:3-4` | +| Storage DLQ name | `common/dlq_utils.py:7-15` | +| Skipped by hook | `conserver/main.py:747-752`, `conserver/hook.py:23-26` | +| Halted by a link | `conserver/main.py:257-263`, `conserver/main.py:273` | +| Saved to the backend | `conserver/main.py:410` | +| Manual recovery, error logged | `conserver/main.py:450-456` | + +## Transitions map to these lines + +| Transition | Code | +|---|---| +| RPUSH from API or follower | `common/lib/queue.py:64-69`, `common/lib/queue.py:149-158`, `api/api.py:806`, `api/api.py:908`, `api/api.py:1046`, `conserver/follower.py:50` | +| BLPOP by a worker | `common/lib/queue.py:81-90`, `conserver/main.py:875` | +| Shutdown requested, LPUSH to head | `conserver/main.py:890-899`, `common/lib/queue.py:71-79` | +| `before_processing` returns falsy | `conserver/main.py:747-752` | +| Chain starts | `conserver/main.py:753` | +| A link returns falsy | `conserver/main.py:256-263` | +| Every link returns an id | `conserver/main.py:273-274` | +| Exception in a link, hook or tracer | `conserver/main.py:646-670`, `conserver/main.py:754-761`. Also an unknown link name, a failed import and a chain with no `links` key (`conserver/main.py:255`, `conserver/main.py:561`, `conserver/main.py:581`) | +| `before_processing` raises | `conserver/main.py:747`, inside the `try` that ends at `conserver/main.py:754` | +| Tracer with `dlq_vcon_on_error` raises, or a failing tracer with no `options` key | `conserver/main.py:536-546` | +| Egress enqueue raises | `conserver/main.py:361-366`, nothing in `_wrap_up` catches it, so it reaches `conserver/main.py:754` | +| Backend save returns | `conserver/main.py:410` | +| Backend save raises | `conserver/main.py:411-429`, `common/lib/queue.py:111-136` | +| Dead-letter fails | `common/lib/queue.py:133-134`, `conserver/main.py:446-456` | +| POST /dlq/reprocess | `api/api.py:1142-1182`, `common/lib/queue.py:163-173` | +| POST /dlq/storage/reprocess | `api/api.py:1185-1246` | +| Retry fails, entry stays | `api/api.py:1232-1238` | + +## Notes map to these lines + +| Note | Code | +|---|---| +| EXPIRE resets the body TTL unless the setting is 0 | `conserver/main.py:762-763`, `common/lib/queue.py:143-145`, `common/settings.py:56` (`VCON_DLQ_EXPIRY`, default 604800) | +| GET /dlq only reads | `api/api.py:1269-1296` | +| One entry per failed backend | `conserver/main.py:381-382`, `conserver/main.py:429`, `common/dlq_utils.py:15` | +| A longer TTL or persistent body stays | `common/lib/queue.py:123-128` | + +## Limits apply to this drawing + +- The ingress path calls plain EXPIRE, so it can shorten a longer TTL or put a TTL on a persistent body. The storage path does neither (`common/lib/queue.py:126`). +- `enqueue_dlq` does not check that the body exists. An id can sit on the ingress DLQ after its body has expired. +- A worker holds a popped id only in memory. No in-flight list exists, so a killed worker loses that id. This is not drawn because no code handles it. +- A saved vCon and a storage DLQ entry can exist together when one backend succeeds and another fails. +- The `POST /dlq/reprocess` move is two Redis commands, not one atomic step (`api/api.py:1168-1171`). diff --git a/docs/diagrams/D09-storage-write-recovery.mmd b/docs/diagrams/D09-storage-write-recovery.mmd new file mode 100644 index 00000000..49975334 --- /dev/null +++ b/docs/diagrams/D09-storage-write-recovery.mmd @@ -0,0 +1,67 @@ +%%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, Helvetica, Arial, sans-serif','fontSize':'14px','background':'#FFFFFF','primaryColor':'#F3F4F6','primaryTextColor':'#292929','primaryBorderColor':'#0A7D18','secondaryColor':'#FFFFFF','secondaryTextColor':'#33363B','secondaryBorderColor':'#8A8A8D','tertiaryColor':'#FFFFFF','tertiaryTextColor':'#33363B','tertiaryBorderColor':'#8A8A8D','lineColor':'#33363B','textColor':'#33363B','mainBkg':'#F3F4F6','nodeBorder':'#0A7D18','clusterBkg':'#FFFFFF','clusterBorder':'#8A8A8D','edgeLabelBackground':'#FFFFFF','actorBkg':'#F3F4F6','actorBorder':'#0A7D18','actorTextColor':'#292929','signalColor':'#33363B','signalTextColor':'#292929','labelBoxBkgColor':'#F3F4F6','labelBoxBorderColor':'#0A7D18','noteBkgColor':'#F3F4F6','noteBorderColor':'#8A8A8D','noteTextColor':'#292929'}}}%% +%%{init: {'fontFamily':'Inter, Helvetica, Arial, sans-serif'}}%% +sequenceDiagram + autonumber + actor Op as Operator + participant W as Worker wrap-up + participant S as Storage + participant A as Adapter module + participant B as Backend + participant Q as VconQueue + participant R as Redis + participant API as API + + Note over W,R: Write path after the last link + W->>R: RPUSH to each egress list, before any storage write + loop Each backend, threads when CONSERVER_PARALLEL_STORAGE is on and there are two or more + W->>S: Storage(name).save(vcon_id) + S->>A: module.save(vcon_id, options) + A->>R: VconRedis.get_vcon(vcon_id) + R-->>A: vCon body + A->>B: write + alt Write succeeds + A-->>W: returns, conserver.storage.count outcome=success + else Adapter raises + A-->>W: exception, outcome=error + W->>Q: enqueue_storage_dlq(name, vcon_id, VCON_DLQ_EXPIRY) + Q->>R: EVAL, one atomic script + alt Body exists + Note over R: Raise a shorter TTL to the retention value, then RPUSH DLQ:storage:#lt;name#gt; + R-->>Q: list length + Q-->>W: conserver.dlq.count incremented + else Body missing + R-->>Q: -1 + Q-->>W: ValueError + Note over W: Logged as manual recovery required, never re-raised + end + end + end + Note over W: A failed backend does not stop the other backends or re-run the chain + + Note over Op,API: Recovery path, driven by the operator + Op->>API: GET /dlq/storage?storage_name=#lt;name#gt; + API->>R: LRANGE 0 -1 + R-->>API: pending vCon ids + API-->>Op: JSON list of ids + Op->>API: POST /dlq/storage/reprocess?storage_name=#lt;name#gt;#amp;count=N + alt Backend not configured or adapter fails to load + API-->>Op: 404 + else Replay lock is already held + API->>R: acquire DLQ:storage:#lt;name#gt;:replay-lock, non-blocking, no expiry + API-->>Op: 409 + else Lock acquired + API->>R: LRANGE 0 count-1, a snapshot that removes nothing + loop Each id in the snapshot + API->>S: save(vcon_id) in the threadpool + S->>A: module.save(vcon_id, options) + A->>R: VconRedis.get_vcon(vcon_id) + A->>B: write + alt Write succeeds + API->>R: LREM one entry + else Adapter raises + Note over API: Warning logged, entry stays, batch stops + end + end + API->>R: release the lock + API-->>Op: 200 with the number written + end diff --git a/docs/diagrams/D09-storage-write-recovery.svg b/docs/diagrams/D09-storage-write-recovery.svg new file mode 100644 index 00000000..839dc33f --- /dev/null +++ b/docs/diagrams/D09-storage-write-recovery.svg @@ -0,0 +1 @@ +APIRedisVconQueueBackendAdapter moduleStorageWorker wrap-upAPIRedisVconQueueBackendAdapter moduleStorageWorker wrap-upWrite path after the last linkRaise a shorter TTL to the retention value, then RPUSH DLQ:storage:<name>Logged as manual recovery required, never re-raisedalt[Body exists][Body missing]alt[Write succeeds][Adapter raises]loop[Each backend, threads when CONSERVER_PARALLEL_STORAGE is on and there are two or more]A failed backend does not stop the other backends or re-run the chainRecovery path, driven by the operatorWarning logged, entry stays, batch stopsalt[Write succeeds][Adapter raises]loop[Each id in the snapshot]alt[Backend not configured or adapter fails to load][Replay lock is already held][Lock acquired]OperatorRPUSH to each egress list, before any storage write1Storage(name).save(vcon_id)2module.save(vcon_id, options)3VconRedis.get_vcon(vcon_id)4vCon body5write6returns, conserver.storage.count outcome=success7exception, outcome=error8enqueue_storage_dlq(name, vcon_id, VCON_DLQ_EXPIRY)9EVAL, one atomic script10list length11conserver.dlq.count incremented12-113ValueError14GET /dlq/storage?storage_name=<name>15LRANGE 0 -116pending vCon ids17JSON list of ids18POST /dlq/storage/reprocess?storage_name=<name>&count=N1940420acquire DLQ:storage:<name>:replay-lock, non-blocking, no expiry2140922LRANGE 0 count-1, a snapshot that removes nothing23save(vcon_id) in the threadpool24module.save(vcon_id, options)25VconRedis.get_vcon(vcon_id)26write27LREM one entry28release the lock29200 with the number written30Operator \ No newline at end of file diff --git a/docs/diagrams/D09.sources.md b/docs/diagrams/D09.sources.md new file mode 100644 index 00000000..bb3a5453 --- /dev/null +++ b/docs/diagrams/D09.sources.md @@ -0,0 +1,59 @@ +# D09 code sources + +Diagram: `D09-storage-write-recovery.mmd`. Step numbers match the `autonumber` output. + +## Participants map to these lines + +| Participant | Code | +|---|---| +| Operator | Caller of the API routes below | +| Worker wrap-up | `conserver/main.py:345` `_wrap_up` | +| Storage | `common/storage/base.py:44-77` | +| Adapter module | `common/storage//__init__.py`, loaded at `common/storage/base.py:56-60` | +| Backend | The system each adapter writes to | +| VconQueue | `common/lib/queue.py:45` | +| Redis | `common/lib/vcon_redis.py:197-224`, `common/lib/queue.py:121-132` | +| API | `api/api.py:1185-1266` | + +## Write path steps map to these lines + +| Step | Message | Code | +|---|---|---| +| 1 | RPUSH to each egress list before storage | `conserver/main.py:352-366`, storage starts at `conserver/main.py:368` | +| Loop | Threads when parallel storage is on and two or more backends exist | `conserver/main.py:376-382`, `conserver/main.py:475-494`, `common/settings.py:66` (default true) | +| 2 | `Storage(name).save` | `conserver/main.py:410` | +| 3 | `module.save` | `common/storage/base.py:63-65` | +| 4, 5 | Adapter reads the body | For example `common/storage/s3/__init__.py:85-86`, `common/lib/vcon_redis.py:168-181` | +| 6 | Adapter writes | For example `common/storage/s3/__init__.py:97-99` | +| 7 | Success metric | `conserver/main.py:407`, `conserver/main.py:430-434` | +| 8 | Exception, error outcome | `conserver/main.py:411-424`, `conserver/main.py:430-434` | +| 9 | `enqueue_storage_dlq` | `conserver/main.py:429`, `conserver/main.py:446-449` | +| 10 | EVAL script | `common/lib/queue.py:121-132` | +| Note | TTL raised, then RPUSH | `common/lib/queue.py:125-129` | +| 11, 12 | List length, `conserver.dlq.count` | `common/lib/queue.py:129`, `common/lib/queue.py:135-136` | +| 13, 14 | Body missing, ValueError | `common/lib/queue.py:124`, `common/lib/queue.py:133-134` | +| Note | Manual recovery logged, never re-raised | `conserver/main.py:450-456` | +| Note | Other backends continue, chain does not re-run | `conserver/main.py:425-429`, `conserver/main.py:381-382` | + +## Recovery path steps map to these lines + +| Step | Message | Code | +|---|---|---| +| 15 to 18 | GET /dlq/storage | `api/api.py:1249-1266` | +| 19 | POST /dlq/storage/reprocess, count from 1 to 100000, default 1000 | `api/api.py:1185-1202` | +| 20 | 404 for an unknown backend | `api/api.py:1212-1216` | +| 21, 22 | Lock with no expiry, 409 when held | `api/api.py:1218-1223` | +| 23 | Snapshot with LRANGE | `api/api.py:1230` | +| 24 to 27 | Save in the threadpool | `api/api.py:1233`, `common/storage/base.py:63-65` | +| 28 | LREM one entry | `api/api.py:1239-1240` | +| Note | Warning, entry stays, batch stops | `api/api.py:1234-1238` | +| 29 | Lock released | `api/api.py:1245-1246` | +| 30 | 200 with the count | `api/api.py:1241` | + +## Limits apply to this drawing + +- The HTTP 500 branch is not drawn. A Redis error during replay returns it and still releases the lock (`api/api.py:1242-1246`). +- A crash leaves the lock in place because it has no expiry (`api/api.py:1219-1221`). +- Replay is at-least-once, so a backend can see the same UUID twice (`api/api.py:1227-1229`). +- `get_vcon` falls back to the configured storages on a Redis miss, so steps 4 and 26 can succeed after the body expires (`common/lib/vcon_redis.py:214-222`). +- The diagram shows adapters that raise. Two adapters differ: `spaceandtime` catches and logs (`common/storage/spaceandtime/__init__.py:70-71`), and `scitt` returns when the vCon is missing (`common/storage/scitt/__init__.py:37-39`). Both count as a success here. diff --git a/docs/diagrams/D10-vcon-assembly.mmd b/docs/diagrams/D10-vcon-assembly.mmd new file mode 100644 index 00000000..ccf31d98 --- /dev/null +++ b/docs/diagrams/D10-vcon-assembly.mmd @@ -0,0 +1,114 @@ +%%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, Helvetica, Arial, sans-serif','fontSize':'14px','background':'#FFFFFF','primaryColor':'#F3F4F6','primaryTextColor':'#292929','primaryBorderColor':'#0A7D18','secondaryColor':'#FFFFFF','secondaryTextColor':'#33363B','secondaryBorderColor':'#8A8A8D','tertiaryColor':'#FFFFFF','tertiaryTextColor':'#33363B','tertiaryBorderColor':'#8A8A8D','lineColor':'#33363B','textColor':'#33363B','mainBkg':'#F3F4F6','nodeBorder':'#0A7D18','clusterBkg':'#FFFFFF','clusterBorder':'#8A8A8D','edgeLabelBackground':'#FFFFFF','actorBkg':'#F3F4F6','actorBorder':'#0A7D18','actorTextColor':'#292929','signalColor':'#33363B','signalTextColor':'#292929','labelBoxBkgColor':'#F3F4F6','labelBoxBorderColor':'#0A7D18','noteBkgColor':'#F3F4F6','noteBorderColor':'#8A8A8D','noteTextColor':'#292929'}}}%% +%%{init: {'fontFamily':'Inter, Helvetica, Arial, sans-serif'}}%% +classDiagram + direction LR + + class UpstreamProducer { + <> + builds the vCon it sends + } + class IngressPaths { + <> + POST /vcon + POST /vcon/external-ingress + follower pull + } + class Vcon { + <> + +uuid + +vcon + +created_at + +add_analysis() + +add_tag() + +add_attachment() + +find_attachment_by_purpose() + +to_dict() + } + class Party { + <> + tel + mailto + } + class Dialog { + <> + type + start + parties + body + } + class Analysis { + <> + type + dialog + vendor + body + encoding + } + class Attachment { + <> + purpose + body + encoding + } + class TagsAttachment { + <> + purpose = tags + body = name:value list + encoding = json + } + class LawfulBasisAttachment { + <> + purpose = lawful_basis + body.lawful_basis + body.purpose_grants + body.expiration + } + class Links { + <> + run(vcon_uuid, link_name, opts) + } + class DietLink { + <> + remove_attachment_types + } + class VconRedis { + <> + +get_vcon() + +store_vcon() + -_enforce_spec_on_write() + } + class LegacyNormalizer { + <> + normalize_legacy_fields() + } + class EgressDowngrade { + <> + to_legacy() + } + class UtopiaAdapter { + <> + render() + require_analysis_grant = false + } + + UpstreamProducer ..> IngressPaths : sends the vCon + UpstreamProducer ..> LawfulBasisAttachment : may include + IngressPaths ..> Vcon : stores after model validation + Vcon "1" *-- "0..*" Party : parties + Vcon "1" *-- "0..*" Dialog : dialog + Vcon "1" *-- "0..*" Analysis : analysis + Vcon "1" *-- "0..*" Attachment : attachments + Attachment <|-- TagsAttachment + Attachment <|-- LawfulBasisAttachment + Links ..> Analysis : add_analysis + Links ..> TagsAttachment : add_tag + DietLink ..> Attachment : drops entries by mime_type when configured + VconRedis ..> Vcon : loads and stores + VconRedis ..> LegacyNormalizer : calls on read and write + LegacyNormalizer ..> LawfulBasisAttachment : renames type to purpose, keeps body + EgressDowngrade ..> LawfulBasisAttachment : renames purpose to type, keeps body + UtopiaAdapter ..> LawfulBasisAttachment : reads and renders + + note for LawfulBasisAttachment "No server code creates this record. The server does not validate, enforce or manage consent." + + style LawfulBasisAttachment fill:#FFFFFF,stroke:#0BB81E,stroke-width:3px diff --git a/docs/diagrams/D10-vcon-assembly.svg b/docs/diagrams/D10-vcon-assembly.svg new file mode 100644 index 00000000..55488a60 --- /dev/null +++ b/docs/diagrams/D10-vcon-assembly.svg @@ -0,0 +1 @@ +

sends the vCon

may include

stores after model validation

parties

1

0..*

dialog

1

0..*

analysis

1

0..*

attachments

1

0..*

add_analysis

add_tag

drops entries by mime_type when configured

loads and stores

calls on read and write

renames type to purpose, keeps body

renames purpose to type, keeps body

reads and renders

«outside this server»

UpstreamProducer

builds the vCon it sends

«server»

IngressPaths

POST /vcon

POST /vcon/external-ingress

follower pull

«common/vcon.py»

Vcon

+uuid

+vcon

+created_at

+add_analysis()

+add_tag()

+add_attachment()

+find_attachment_by_purpose()

+to_dict()

«dict»

Party

tel

mailto

«dict»

Dialog

type

start

parties

body

«dict»

Analysis

type

dialog

vendor

body

encoding

«dict»

Attachment

purpose

body

encoding

«written by add_tag»

TagsAttachment

purpose = tags

body = name:value list

encoding = json

«carried, never created»

LawfulBasisAttachment

purpose = lawful_basis

body.lawful_basis

body.purpose_grants

body.expiration

«conserver/links»

Links

run(vcon_uuid, link_name, opts)

«conserver/links/diet»

DietLink

remove_attachment_types

«common/lib/vcon_redis.py»

VconRedis

+get_vcon()

+store_vcon()

-_enforce_spec_on_write()

«common/lib/vcon_compat.py»

LegacyNormalizer

normalize_legacy_fields()

«common/lib/vcon_egress_compat.py»

EgressDowngrade

to_legacy()

«common/storage/utopia»

UtopiaAdapter

require_analysis_grant = false

render()

No server code creates this record. The server does not validate, enforce or manage consent.

\ No newline at end of file diff --git a/docs/diagrams/D10.sources.md b/docs/diagrams/D10.sources.md new file mode 100644 index 00000000..ca2ed69e --- /dev/null +++ b/docs/diagrams/D10.sources.md @@ -0,0 +1,53 @@ +# D10 code sources + +Diagram: `D10-vcon-assembly.mmd`. `Vcon` is the class in `common/vcon.py`, which `import vcon` resolves to under the image `PYTHONPATH`. Party, dialog, analysis and attachment entries are plain dicts, not classes. The diagram draws them as classes to show their fields. + +## Classes map to these lines + +| Class | Code | +|---|---| +| UpstreamProducer | No code here. It stands for whatever sends a vCon to the server. `common/tests/test_api.py:106-138` posts a vCon that already holds a `lawful_basis` attachment | +| IngressPaths | `api/api.py:750-821`, `api/api.py:824-929`, `conserver/follower.py:46-50` | +| Vcon | `common/vcon.py:20`, `common/vcon.py:124`, `common/vcon.py:148`, `common/vcon.py:177`, `common/vcon.py:209`, `common/vcon.py:267`, `common/vcon.py:311-337` | +| Party | `common/vcon.py:241`, fields read at `conserver/main.py:589-590` | +| Dialog | `common/vcon.py:260`, `api/api.py:309-315` | +| Analysis | `common/vcon.py:232-239` | +| Attachment | `common/vcon.py:200-204`, `api/api.py:395` | +| TagsAttachment | `common/vcon.py:124-146` | +| LawfulBasisAttachment | Fields read at `common/storage/utopia/__init__.py:156-184`. Names in code: `common/lib/vcon_compat.py:18-21`, `common/lib/vcon_egress_compat.py:103-107` | +| Links | `conserver/main.py:603` | +| DietLink | `conserver/links/diet/__init__.py:39`, `conserver/links/diet/__init__.py:203-208` | +| VconRedis | `common/lib/vcon_redis.py:19`, `common/lib/vcon_redis.py:61-96`, `common/lib/vcon_redis.py:98-108`, `common/lib/vcon_redis.py:168-181` | +| LegacyNormalizer | `common/lib/vcon_compat.py:78-99` | +| EgressDowngrade | `common/lib/vcon_egress_compat.py:110-149` | +| UtopiaAdapter | `common/storage/utopia/__init__.py:52`, `common/storage/utopia/__init__.py:251-252`, `common/storage/utopia/__init__.py:325-330` | + +## Relationships map to these lines + +| Relationship | Code | +|---|---| +| Producer sends the vCon | `api/api.py:759`, `api/api.py:781` | +| Producer may include a basis | `common/tests/test_api.py:113-138` | +| Ingress stores after model validation | `api/api.py:781-789`, `api/api.py:893`, `api/api.py:395` (`List[Dict]`, no attachment validation), `api/api.py:450-452` (no spec pass on this write) | +| Vcon holds the four arrays | `common/vcon.py:279-308` | +| Links call `add_analysis` | For example `conserver/links/analyze/__init__.py:181`, `conserver/links/deepgram_link/__init__.py:303` | +| Links call `add_tag` | For example `conserver/links/tag/__init__.py:39`, `conserver/links/check_and_tag/__init__.py:195` | +| Diet drops entries by `mime_type` | `conserver/links/diet/__init__.py:205-208` | +| VconRedis loads and stores | `common/lib/vcon_redis.py:178-181`, `common/lib/vcon_redis.py:106-108` | +| VconRedis calls the normalizer | `common/lib/vcon_redis.py:75`, `common/lib/vcon_redis.py:223` | +| Normalizer renames `type` to `purpose` | `common/lib/vcon_compat.py:63-75`. Test: `common/tests/test_vcon_compat.py:62-80` | +| Downgrade renames `purpose` to `type` | `common/lib/vcon_egress_compat.py:99-107`. Test: `common/tests/test_vcon_egress_compat.py:77-80` | +| Utopia reads and renders | `common/storage/utopia/__init__.py:156-184`, `common/storage/utopia/__init__.py:251-252` | + +## The never created claim rests on these searches + +- `lawful_basis` appears in non-test Python only in `common/lib/vcon_compat.py`, `common/lib/vcon_egress_compat.py` and `common/storage/utopia/__init__.py`. The first two mention it in comments, and the adapter only reads it. +- `add_attachment` has no caller outside tests. `add_party` and `add_dialog` have none either, so parties and dialogs arrive from the producer. +- `build_new` has no caller outside tests. +- Diet is the only link that assigns to `attachments`. The filter reads `mime_type`, a key that `normalize_legacy_fields` does not touch. + +## Limits apply to this drawing + +- `add_attachment` writes `type` and `add_tag` writes no `party`, `dialog` or `start` (`common/vcon.py:129`, `common/vcon.py:200-204`). `_enforce_spec_on_write` renames `type` to `purpose` but does not add those three fields. +- `add_tag` writes a stringified body (`common/vcon.py:145`). `_normalize_json_body_encoding` leaves a string body alone (`common/lib/vcon_redis.py:50-58`), so tags stay in the older shape. +- `require_analysis_grant` defaults to false and exists only in the `utopia` adapter. It reads a basis and skips one upload. It manages nothing. diff --git a/docs/diagrams/D11-egress-compatibility.mmd b/docs/diagrams/D11-egress-compatibility.mmd new file mode 100644 index 00000000..b42bee7c --- /dev/null +++ b/docs/diagrams/D11-egress-compatibility.mmd @@ -0,0 +1,43 @@ +%%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, Helvetica, Arial, sans-serif','fontSize':'14px','background':'#FFFFFF','primaryColor':'#F3F4F6','primaryTextColor':'#292929','primaryBorderColor':'#0A7D18','secondaryColor':'#FFFFFF','secondaryTextColor':'#33363B','secondaryBorderColor':'#8A8A8D','tertiaryColor':'#FFFFFF','tertiaryTextColor':'#33363B','tertiaryBorderColor':'#8A8A8D','lineColor':'#33363B','textColor':'#33363B','mainBkg':'#F3F4F6','nodeBorder':'#0A7D18','clusterBkg':'#FFFFFF','clusterBorder':'#8A8A8D','edgeLabelBackground':'#FFFFFF','actorBkg':'#F3F4F6','actorBorder':'#0A7D18','actorTextColor':'#292929','signalColor':'#33363B','signalTextColor':'#292929','labelBoxBkgColor':'#F3F4F6','labelBoxBorderColor':'#0A7D18','noteBkgColor':'#F3F4F6','noteBorderColor':'#8A8A8D','noteTextColor':'#292929'}}}%% +%%{init: {'fontFamily':'Inter, Helvetica, Arial, sans-serif'}}%% +flowchart TB + canon["Canonical vCon in Redis
vcon 0.4.0, never changed by egress"] + + subgraph points["Egress points that call to_configured_legacy"] + direction LR + hook["webhook link"] + stores["postgres, s3 and
elasticsearch adapters"] + reads["GET /vcon/{uuid}
GET /vcons"] + end + + other["Other storage adapters
skip the conversion"] + + canon --> points + canon --> other + + points -- "reads EGRESS_FORMAT_VERSION" --> setting{"Format
version set?"} + setting -- "no" --> same["Payload unchanged, current spec"] + setting -- "yes, checks SUPPORTED_VERSIONS" --> known{"Version
supported?"} + known -- "no" --> bad["ValueError at egress time"] + bad --> fail["webhook link: ingress DLQ
adapter: storage DLQ
API read: HTTP 500"] + known -- "yes, 0.0.1" --> copy["Deep copy the dict"] + + subgraph convert["to_legacy steps"] + direction TB + top["Top level
amended to appended
critical to must_support"] + ent["Dialog, analysis, attachments
schema to schema_version
mediatype to mimetype
critical to must_support"] + att["Attachments
purpose to type when type is absent"] + body["Analysis and attachments
encoding json becomes none
string body parsed to a native value"] + fill["Defaults group [], redacted {}, appended null
Stamp vcon 0.0.1"] + top --> ent --> att --> body --> fill + end + + copy --> convert + convert --> legacy["Legacy 0.0.1 payload to the consumer or store"] + lb["lawful_basis attachment keeps its body
Only field names and encoding change"] + convert -.-> lb + + legacy -. "read back from storage" .-> up["Renamed up to the current spec
vcon stamped 0.4.0, cached in Redis"] + + classDef pick stroke:#0BB81E,stroke-width:3px,fill:#FFFFFF + class lb pick diff --git a/docs/diagrams/D11-egress-compatibility.svg b/docs/diagrams/D11-egress-compatibility.svg new file mode 100644 index 00000000..b3568304 --- /dev/null +++ b/docs/diagrams/D11-egress-compatibility.svg @@ -0,0 +1 @@ +

to_legacy steps

Egress points that call to_configured_legacy

reads EGRESS_FORMAT_VERSION

no

yes, checks SUPPORTED_VERSIONS

no

yes, 0.0.1

read back from storage

Canonical vCon in Redis
vcon 0.4.0, never changed by egress

webhook link

postgres, s3 and
elasticsearch adapters

GET /vcon/{uuid}
GET /vcons

Other storage adapters
skip the conversion

Format
version set?

Payload unchanged, current spec

Version
supported?

ValueError at egress time

webhook link: ingress DLQ
adapter: storage DLQ
API read: HTTP 500

Deep copy the dict

Top level
amended to appended
critical to must_support

Dialog, analysis, attachments
schema to schema_version
mediatype to mimetype
critical to must_support

Attachments
purpose to type when type is absent

Analysis and attachments
encoding json becomes none
string body parsed to a native value

Defaults group [], redacted {}, appended null
Stamp vcon 0.0.1

Legacy 0.0.1 payload to the consumer or store

lawful_basis attachment keeps its body
Only field names and encoding change

Renamed up to the current spec
vcon stamped 0.4.0, cached in Redis

\ No newline at end of file diff --git a/docs/diagrams/D11.sources.md b/docs/diagrams/D11.sources.md new file mode 100644 index 00000000..c35297f2 --- /dev/null +++ b/docs/diagrams/D11.sources.md @@ -0,0 +1,44 @@ +# D11 code sources + +Diagram: `D11-egress-compatibility.mmd`. + +## Nodes map to these lines + +| Node | Code | +|---|---| +| Canonical vCon in Redis | `common/lib/vcon_redis.py:82`, `common/lib/vcon_egress_compat.py:128` (the conversion works on a copy) | +| webhook link | `conserver/links/webhook/__init__.py:42` | +| postgres adapter | `common/storage/postgres/__init__.py:126` | +| s3 adapter | `common/storage/s3/__init__.py:92` | +| elasticsearch adapter | `common/storage/elasticsearch/__init__.py:73` | +| GET /vcon/{uuid} | `api/api.py:631` | +| GET /vcons | `api/api.py:668` | +| Other storage adapters skip the conversion | A search for `to_configured_legacy` finds only the callers above | +| Format version set? | `common/lib/vcon_egress_compat.py:162-166`, `common/settings.py:74` | +| Payload unchanged | `common/lib/vcon_egress_compat.py:166` | +| Version supported? | `common/lib/vcon_egress_compat.py:48`, `common/lib/vcon_egress_compat.py:120-124` | +| ValueError at egress time | `common/lib/vcon_egress_compat.py:121-124` | +| Deep copy the dict | `common/lib/vcon_egress_compat.py:128` | +| Top level renames | `common/lib/vcon_egress_compat.py:34-37`, `common/lib/vcon_egress_compat.py:130-131` | +| Entry renames | `common/lib/vcon_egress_compat.py:41-45`, `common/lib/vcon_egress_compat.py:65-69`, `common/lib/vcon_egress_compat.py:133-139` | +| Attachment `purpose` to `type` | `common/lib/vcon_egress_compat.py:99-107` | +| Body and encoding | `common/lib/vcon_egress_compat.py:72-96`, `common/lib/vcon_egress_compat.py:137`, `common/lib/vcon_egress_compat.py:140` | +| Defaults and version stamp | `common/lib/vcon_egress_compat.py:144-148` | +| Legacy 0.0.1 payload | `common/lib/vcon_egress_compat.py:149` | +| `lawful_basis` keeps its body | `common/lib/vcon_egress_compat.py:99-107`. Test: `common/tests/test_vcon_egress_compat.py:77-80` | +| Renamed up, stamped, cached | `common/lib/vcon_redis.py:142-152`, `common/lib/vcon_redis.py:75-82`, `api/api.py:492-501` | + +## Failure edges map to these lines + +| Failure | Code | +|---|---| +| webhook link reaches the ingress DLQ | No catch around `conserver/links/webhook/__init__.py:42`, then `conserver/main.py:646-670`, `conserver/main.py:754-761` | +| Adapter reaches the storage DLQ | Re-raised at `common/storage/postgres/__init__.py:156-160`, `common/storage/s3/__init__.py:106-110`, `common/storage/elasticsearch/__init__.py` (`raise e` at line 150), then `conserver/main.py:411-429` | +| API read returns HTTP 500 | No catch around `api/api.py:631` or `api/api.py:668`, and `api/api.py` registers no exception handler. This is the FastAPI default | + +## Limits apply to this drawing + +- `to_legacy` loops dialog, analysis, then attachments. The diagram groups the steps by what they do, so the boxes are not a strict call order. +- A non-dict input returns as it came (`common/lib/vcon_egress_compat.py:125-126`). This is not drawn. +- `_body_to_legacy` leaves an invalid JSON string, or a scalar body, on `encoding: "json"` (`common/lib/vcon_egress_compat.py:88-95`). +- `settings.py` does not validate the value at start-up, so a bad version fails on the first egress. diff --git a/docs/diagrams/D12-link-execution-contract.mmd b/docs/diagrams/D12-link-execution-contract.mmd new file mode 100644 index 00000000..c2be5d61 --- /dev/null +++ b/docs/diagrams/D12-link-execution-contract.mmd @@ -0,0 +1,46 @@ +%%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, Helvetica, Arial, sans-serif','fontSize':'14px','background':'#FFFFFF','primaryColor':'#F3F4F6','primaryTextColor':'#292929','primaryBorderColor':'#0A7D18','secondaryColor':'#FFFFFF','secondaryTextColor':'#33363B','secondaryBorderColor':'#8A8A8D','tertiaryColor':'#FFFFFF','tertiaryTextColor':'#33363B','tertiaryBorderColor':'#8A8A8D','lineColor':'#33363B','textColor':'#33363B','mainBkg':'#F3F4F6','nodeBorder':'#0A7D18','clusterBkg':'#FFFFFF','clusterBorder':'#8A8A8D','edgeLabelBackground':'#FFFFFF','actorBkg':'#F3F4F6','actorBorder':'#0A7D18','actorTextColor':'#292929','signalColor':'#33363B','signalTextColor':'#292929','labelBoxBkgColor':'#F3F4F6','labelBoxBorderColor':'#0A7D18','noteBkgColor':'#F3F4F6','noteBorderColor':'#8A8A8D','noteTextColor':'#292929'}}}%% +%%{init: {'fontFamily':'Inter, Helvetica, Arial, sans-serif'}}%% +sequenceDiagram + autonumber + participant W as _handle_vcon + participant H as hook + participant C as VconChainRequest + participant T as Tracers + participant L as Link module + participant A as after_link_hook + participant R as Redis + + W->>H: before_processing(vcon_id, chain_details, context) + alt Hook returns a falsy value + H-->>W: None, False or empty string + Note over W: Skip the chain, no DLQ + else Hook returns a truthy value + H-->>W: truthy value, used only as a yes + W->>C: process() + loop Each link in chain_details links + C->>C: Resolve module and options, import once + C->>R: get_vcon for parties, errors ignored + opt First link only + C->>T: run(id, id, name, links, -1, options) + end + C->>L: run(vcon_id, link_name, options) + L->>R: get_vcon, returns None when missing + L->>R: store_vcon when the link changes the vCon + alt Link returns + L-->>C: same id, new id, or falsy to halt + C->>A: after_link(..., "success", None, parties) + C->>T: run(..., link_index, options) + Note over C: Falsy ends the loop, new id replaces vcon_id + else Link raises + L--xC: exception + C->>A: after_link(..., "error", exception, parties) + Note over C,A: Hook errors ignored on this path + C--xW: exception raised again + W->>R: RPUSH DLQ:ingress_list, EXPIRE VCON_DLQ_EXPIRY + end + end + opt No link halted or raised + C->>C: _wrap_up runs egress, then storage + end + end + W->>H: after_processing(vcon_id, chain_details, context, error) diff --git a/docs/diagrams/D12-link-execution-contract.svg b/docs/diagrams/D12-link-execution-contract.svg new file mode 100644 index 00000000..a6d924db --- /dev/null +++ b/docs/diagrams/D12-link-execution-contract.svg @@ -0,0 +1 @@ +Redisafter_link_hookLink moduleTracersVconChainRequesthook_handle_vconRedisafter_link_hookLink moduleTracersVconChainRequesthook_handle_vconSkip the chain, no DLQopt[First link only]Falsy ends the loop, new id replaces vcon_idHook errors ignored on this pathalt[Link returns][Link raises]loop[Each link in chain_details links]opt[No link halted or raised]alt[Hook returns a falsy value][Hook returns a truthy value]before_processing(vcon_id, chain_details, context)1None, False or empty string2truthy value, used only as a yes3process()4Resolve module and options, import once5get_vcon for parties, errors ignored6run(id, id, name, links, -1, options)7run(vcon_id, link_name, options)8get_vcon, returns None when missing9store_vcon when the link changes the vCon10same id, new id, or falsy to halt11after_link(..., "success", None, parties)12run(..., link_index, options)13exception14after_link(..., "error", exception, parties)15exception raised again16RPUSH DLQ:ingress_list, EXPIRE VCON_DLQ_EXPIRY17_wrap_up runs egress, then storage18after_processing(vcon_id, chain_details, context, error)19 \ No newline at end of file diff --git a/docs/diagrams/D12.sources.md b/docs/diagrams/D12.sources.md new file mode 100644 index 00000000..10887bc0 --- /dev/null +++ b/docs/diagrams/D12.sources.md @@ -0,0 +1,53 @@ +# D12 traces the link execution contract + +Diagram: `D12-link-execution-contract.mmd`. Line numbers refer to the worktree at the time of drawing. Step numbers match the rendered diagram. + +## Each participant maps to code + +| Participant | Code | +|---|---| +| _handle_vcon | `conserver/main.py:702` | +| hook | `conserver/hook.py:11`, `conserver/hook.py:31` | +| VconChainRequest | `conserver/main.py:206` | +| Tracers | `conserver/main.py:508`, example `conserver/tracers/jlinc/__init__.py:28` | +| Link module | `conserver/main.py:582`, example `conserver/links/tag/__init__.py:10` | +| after_link_hook | `conserver/after_link_hook.py:11` | +| Redis | `common/lib/vcon_redis.py:19`, `common/lib/queue.py:45` | + +## Each step maps to code + +| Step | Message | Code | +|---|---|---| +| 1 | before_processing | `conserver/main.py:747`, `conserver/hook.py:11` | +| 2 | Falsy return, skip | `conserver/main.py:747`, `conserver/main.py:752`, `conserver/hook.py:24` | +| 3 | Truthy return | `conserver/main.py:747`. The value is tested and not kept | +| 4 | process() | `conserver/main.py:753` | +| Loop | Each link | `conserver/main.py:255` | +| 5 | Resolve module and options, import once | `conserver/main.py:575`, `conserver/main.py:578`, `conserver/main.py:581`, aliases at `conserver/main.py:158` | +| 6 | get_vcon for parties | `conserver/main.py:587`, `conserver/main.py:595` | +| 7 | Tracers before the first link | `conserver/main.py:600`, `conserver/main.py:601`, `conserver/main.py:522` | +| 8 | run(vcon_id, link_name, options) | `conserver/main.py:603` | +| 9 | Link reads the vCon | `conserver/links/tag/__init__.py:18`, `common/lib/vcon_redis.py:168`, `common/lib/vcon_redis.py:176` | +| 10 | Link stores changes | `conserver/links/tag/__init__.py:40`, `common/lib/vcon_redis.py:98` | +| 11 | Link returns | `conserver/main.py:603`, `conserver/main.py:645` | +| 12 | after_link, success | `conserver/main.py:604`, `conserver/after_link_hook.py:11` | +| 13 | Tracers after the link | `conserver/main.py:641`, `conserver/main.py:642`, `conserver/main.py:644` | +| Note | Falsy ends the loop, new id replaces vcon_id | `conserver/main.py:257`, `conserver/main.py:263`, `conserver/main.py:271` | +| 14 | Link raises | `conserver/main.py:646` | +| 15 | after_link, error | `conserver/main.py:651`, `conserver/main.py:652`, `conserver/main.py:655` | +| 16 | Exception raised again | `conserver/main.py:670`, `conserver/main.py:754` | +| 17 | DLQ push and TTL | `conserver/main.py:761`, `conserver/main.py:763` | +| 18 | _wrap_up | `conserver/main.py:273`, `conserver/main.py:274`, `conserver/main.py:345` | +| 19 | after_processing | `conserver/main.py:766` | + +## Notes state the contract for link authors + +- Signature: `run(vcon_uuid, link_name, opts)`. The server always passes the third argument (`conserver/main.py:603`), and it is `None` when the config has no `options` key (`conserver/main.py:574`). A link's `default_options` default does not apply in that case. +- Return the id to continue, a different id to swap the vCon, or a falsy value to halt. +- `status` is `"success"` for a halt too. Only the `conserver.link.count` metric separates them, with `outcome` of `halt` (`conserver/main.py:626`). +- If `after_link` raises on the success path, the `except` at `conserver/main.py:646` treats it as a link failure: a second `after_link` call with `"error"`, then the DLQ. +- A tracer error only stops the chain when its options set `dlq_vcon_on_error` (`conserver/main.py:545`). A failing tracer with no `options` key also stops the chain and sends the vCon to the DLQ, so always set `options`, even as `options: {}`. +- An unknown link name or failed import raises before the `try` at `conserver/main.py:599`, so `after_link` does not run and the vCon reaches the DLQ. +- `after_link` config comes from `options.after_link` (`conserver/main.py:598`). +- `hook.py` and `after_link_hook.py` ship as no-ops and are meant to be replaced at image build time (`conserver/hook.py:4`, `conserver/after_link_hook.py:4`). +- `after_processing` also runs after a skip (`conserver/main.py:764`) and gets the current id (`conserver/main.py:767`). An exception from it is not caught. diff --git a/docs/diagrams/D13-authentication-paths.mmd b/docs/diagrams/D13-authentication-paths.mmd new file mode 100644 index 00000000..5112fa70 --- /dev/null +++ b/docs/diagrams/D13-authentication-paths.mmd @@ -0,0 +1,61 @@ +%%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, Helvetica, Arial, sans-serif','fontSize':'14px','background':'#FFFFFF','primaryColor':'#F3F4F6','primaryTextColor':'#292929','primaryBorderColor':'#0A7D18','secondaryColor':'#FFFFFF','secondaryTextColor':'#33363B','secondaryBorderColor':'#8A8A8D','tertiaryColor':'#FFFFFF','tertiaryTextColor':'#33363B','tertiaryBorderColor':'#8A8A8D','lineColor':'#33363B','textColor':'#33363B','mainBkg':'#F3F4F6','nodeBorder':'#0A7D18','clusterBkg':'#FFFFFF','clusterBorder':'#8A8A8D','edgeLabelBackground':'#FFFFFF','actorBkg':'#F3F4F6','actorBorder':'#0A7D18','actorTextColor':'#292929','signalColor':'#33363B','signalTextColor':'#292929','labelBoxBkgColor':'#F3F4F6','labelBoxBorderColor':'#0A7D18','noteBkgColor':'#F3F4F6','noteBorderColor':'#8A8A8D','noteTextColor':'#292929'}}}%% +%%{init: {'fontFamily':'Inter, Helvetica, Arial, sans-serif'}}%% +sequenceDiagram + autonumber + participant S as Environment and token file + participant C as Client + participant F as FastAPI app + participant G as get_api_key + participant H as Route handler + participant V as validate_ingress_api_key + participant Y as Config file + + Note over S,F: Startup loads the main API keys once + S->>F: CONSERVER_API_TOKEN, one key + S->>F: CONSERVER_API_TOKEN_FILE, one key per line + F->>F: Build the api_keys list + + Note over C,H: Public routes sit on app and check no key + C->>F: GET /version, /health or /stats/queue + F->>H: Call the handler + H-->>C: Route response + + Note over C,H: Main API routes sit on api_router + C->>F: Request with key in CONSERVER_HEADER_NAME + F->>G: Run the Security dependency + alt api_keys is empty + G-->>F: Skip the check, return None + else Header value is in api_keys + G-->>F: Return the key + else Key missing or not in api_keys + G-->>C: 403 Invalid API Key + end + F->>H: Call the handler after a pass + H-->>C: Route response + + Note over C,Y: External ingress sits on external_router and ignores api_keys + C->>F: POST /vcon/external-ingress?ingress_list=name + F->>F: Validate the query and the Vcon body + opt Query or body is invalid + F-->>C: 422 before any key check + end + F->>H: Call external_ingress_vcon + H->>V: Pass ingress_list and the header value + alt No header value + V-->>C: 403 API Key required + else Header value present + V->>Y: Read ingress_auth on every request + Y-->>V: Map of ingress list to allowed keys + alt ingress_auth is empty + V-->>C: 403 No ingress authentication configured + else ingress_list is not in the map + V-->>C: 403 Ingress list not configured + else Map value is neither string nor list + V-->>C: 403 Invalid configuration + else Key is not allowed for this list + V-->>C: 403 Invalid API Key for ingress list + else Key is allowed for this list + V-->>H: Return the key + H-->>C: 204 after store and enqueue, 500 on failure + end + end diff --git a/docs/diagrams/D13-authentication-paths.svg b/docs/diagrams/D13-authentication-paths.svg new file mode 100644 index 00000000..30525203 --- /dev/null +++ b/docs/diagrams/D13-authentication-paths.svg @@ -0,0 +1 @@ +Config filevalidate_ingress_api_keyRoute handlerget_api_keyFastAPI appClientEnvironment and token fileConfig filevalidate_ingress_api_keyRoute handlerget_api_keyFastAPI appClientEnvironment and token fileStartup loads the main API keys oncePublic routes sit on app and check no keyMain API routes sit on api_routeralt[api_keys is empty][Header value is in api_keys][Key missing or not in api_keys]External ingress sits on external_router and ignores api_keysopt[Query or body is invalid]alt[ingress_auth is empty][ingress_list is not in the map][Map value is neither string nor list][Key is not allowed for this list][Key is allowed for this list]alt[No header value][Header value present]CONSERVER_API_TOKEN, one key1CONSERVER_API_TOKEN_FILE, one key per line2Build the api_keys list3GET /version, /health or /stats/queue4Call the handler5Route response6Request with key in CONSERVER_HEADER_NAME7Run the Security dependency8Skip the check, return None9Return the key10403 Invalid API Key11Call the handler after a pass12Route response13POST /vcon/external-ingress?ingress_list=name14Validate the query and the Vcon body15422 before any key check16Call external_ingress_vcon17Pass ingress_list and the header value18403 API Key required19Read ingress_auth on every request20Map of ingress list to allowed keys21403 No ingress authentication configured22403 Ingress list not configured23403 Invalid configuration24403 Invalid API Key for ingress list25Return the key26204 after store and enqueue, 500 on failure27 \ No newline at end of file diff --git a/docs/diagrams/D13.sources.md b/docs/diagrams/D13.sources.md new file mode 100644 index 00000000..13b2ebda --- /dev/null +++ b/docs/diagrams/D13.sources.md @@ -0,0 +1,85 @@ +# D13 sources + +Diagram: `D13-authentication-paths.mmd`, a sequence diagram. Owner page: `configuration/authentication.md`. + +Paths are relative to the repo root. Step numbers match the numbers in the rendered diagram. + +## Participants + +| Participant | Source | +|---|---| +| Environment and token file | `common/settings.py:17-19` | +| Client | Any HTTP caller | +| FastAPI app | `api/api.py:85` | +| `get_api_key` | `api/api.py:105-124` | +| Route handler | Functions under `@app.*`, `@api_router.*` and `@external_router.*` in `api/api.py` | +| `validate_ingress_api_key` | `api/api.py:127-185` | +| Config file | `common/settings.py:58`, `common/config.py:7-12` | + +## Startup + +| Step | Behaviour | Source | +|---|---|---| +| 1 | `CONSERVER_API_TOKEN` adds one key when set and not empty | `common/settings.py:17`, `api/api.py:90-92` | +| 2 | `CONSERVER_API_TOKEN_FILE` adds each line, stripped. The file opens at import, so a bad path stops the API from starting | `common/settings.py:18`, `api/api.py:94-99` | +| 3 | `api_keys` is a module list built at import. The API logs when it is empty. Changing keys needs a restart | `api/api.py:89`, `api/api.py:101-102` | + +## Public routes + +| Step | Behaviour | Source | +|---|---|---| +| 4 | `/version`, `/health` and `/stats/queue` are declared on `app`, not on a router | `api/api.py:235-236`, `api/api.py:257-258`, `api/api.py:275-276` | +| 5 | `app` carries no global dependency, so no key is read | `api/api.py:85`, `api/api.py:284` | +| 6 | The handlers respond. `/stats/queue` returns 500 if Redis fails | `api/api.py:254`, `api/api.py:269-272`, `api/api.py:285-290` | + +## Main API routes + +| Step | Behaviour | Source | +|---|---|---| +| 7 | The key travels in the header named by `CONSERVER_HEADER_NAME`, default `x-conserver-api-token`. `api_router` holds 16 routes | `common/settings.py:19`, `api/api.py:86`, `api/api.py:230` | +| 8 | `include_router` attaches `get_api_key` to every `api_router` route | `api/api.py:1371-1374` | +| 9 | With an empty `api_keys`, the check is skipped and any request passes | `api/api.py:118-120` | +| 10 | A header value in `api_keys` passes. The whole header value is compared | `api/api.py:122`, `api/api.py:124` | +| 11 | A missing or wrong key gets 403 with detail `Invalid API Key` | `api/api.py:122-123` | +| 12 | The handler runs only after a pass | `api/api.py:1371-1374` | +| 13 | The handler responds | `api/api.py:511-1369` | + +## External ingress + +| Step | Behaviour | Source | +|---|---|---| +| 14 | `/vcon/external-ingress` sits on `external_router`, included with no dependency, so `get_api_key` and `api_keys` play no part | `api/api.py:231`, `api/api.py:824-825`, `api/api.py:1376-1377` | +| 15 | FastAPI validates the `ingress_list` query and the `Vcon` body before the handler runs | `api/api.py:837-840` | +| 16 | Invalid input gets 422 with no key check. See the test note below | `api/api.py:876-878`, `uv.lock:579-580` | +| 17 | `external_ingress_vcon` starts | `api/api.py:835` | +| 18 | The handler reads the same header and calls the validator, outside the `try` block, so a 403 stays a 403 | `api/api.py:877-878`, `api/api.py:880` | +| 19 | No header value gets 403 with detail `API Key required` | `api/api.py:142-143` | +| 20 | `get_ingress_auth` calls `get_config`, which opens the YAML file on every call, so `ingress_auth` changes apply with no restart | `api/api.py:146`, `common/config.py:7-12`, `common/config.py:60-61`, `common/config.py:79-88` | +| 21 | The map holds a string or a list of strings per ingress list | `common/config.py:80-88`, `example_config.yml:16-32` | +| 22 | An empty or missing `ingress_auth` gets 403, whatever `api_keys` holds | `api/api.py:148-152` | +| 23 | An unlisted `ingress_list` gets 403. Full detail: `Ingress list '' not configured` | `api/api.py:155-159` | +| 24 | A map value of any other type gets 403. Full detail: `Invalid configuration for ingress list ''` | `api/api.py:162-174` | +| 25 | A key outside the allowed set gets 403. Full detail: `Invalid API Key for ingress list ''` | `api/api.py:177-182` | +| 26 | An allowed key returns to the handler | `api/api.py:184-185` | +| 27 | The handler stores, indexes and enqueues, then returns 204. Any failure returns 500 with detail `Failed to store vCon` | `api/api.py:826`, `api/api.py:880-923`, `api/api.py:925-929` | + +## Test note + +Steps 11, 15 and 16 depend on FastAPI ordering, not on repo code. A small app with the same dependency shape on the pinned FastAPI 0.115.6 gave these results: + +| Request | Status | +|---|---| +| `api_router` route, wrong key, valid JSON that fails the body model | 403 | +| `api_router` route, wrong key, malformed JSON | 422 | +| External ingress, no key, body fails the model | 422 | +| External ingress, no `ingress_list`, no key | 422 | +| External ingress, no key, valid input | 403 | +| `/docs`, `/redoc`, `/openapi.json`, no key | 200 | + +The test used a stand-in app, not `api/api.py` itself. + +## Left out of the drawing + +- `/docs`, `/redoc` and `/openapi.json` are public through FastAPI defaults, because `api/api.py:85` does not turn them off. +- `CORSMiddleware` allows all origins (`api/api.py:204-206`). It checks no key. +- `VersionHeaderMiddleware` adds version headers (`api/api.py:210-228`). It checks no key. diff --git a/docs/diagrams/D14-observability.mmd b/docs/diagrams/D14-observability.mmd new file mode 100644 index 00000000..e2578b4c --- /dev/null +++ b/docs/diagrams/D14-observability.mmd @@ -0,0 +1,75 @@ +%%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, Helvetica, Arial, sans-serif','fontSize':'14px','background':'#FFFFFF','primaryColor':'#F3F4F6','primaryTextColor':'#292929','primaryBorderColor':'#0A7D18','secondaryColor':'#FFFFFF','secondaryTextColor':'#33363B','secondaryBorderColor':'#8A8A8D','tertiaryColor':'#FFFFFF','tertiaryTextColor':'#33363B','tertiaryBorderColor':'#8A8A8D','lineColor':'#33363B','textColor':'#33363B','mainBkg':'#F3F4F6','nodeBorder':'#0A7D18','clusterBkg':'#FFFFFF','clusterBorder':'#8A8A8D','edgeLabelBackground':'#FFFFFF','actorBkg':'#F3F4F6','actorBorder':'#0A7D18','actorTextColor':'#292929','signalColor':'#33363B','signalTextColor':'#292929','labelBoxBkgColor':'#F3F4F6','labelBoxBorderColor':'#0A7D18','noteBkgColor':'#F3F4F6','noteBorderColor':'#8A8A8D','noteTextColor':'#292929'}}}%% +%%{init: {'fontFamily':'Inter, Helvetica, Arial, sans-serif'}}%% +flowchart TB + MON["Monitoring client"] + + subgraph procs ["Server processes"] + API["API process
opentelemetry-instrument uvicorn"] + WRK["Conserver worker process
opentelemetry-instrument python"] + end + + REDIS[("Redis")] + + subgraph metrics ["Metrics path, common/lib"] + HELP["lib.metrics helpers
increment_counter, record_histogram,
add_updown_counter"] + GAUGE["lib.queue_metrics gauges
ingress_list.length,
redis.memory_used_bytes"] + GATE{"OTEL_EXPORTER_
OTLP_ENDPOINT
set?"} + NOOP["No metrics published"] + PROV["MeterProvider per process
service.instance.id is host-pid-pid"] + READ["PeriodicExportingMetricReader
tick is OTEL_METRIC_
EXPORT_INTERVAL,
default 5000 ms"] + GRPC["OTLPMetricExporter, gRPC only"] + end + + subgraph traces ["Trace path"] + CTX["Redis key
context:{list}:{uuid}"] + SPANS["Worker spans
vcon_processing.{chain},
link.{name}, storage.{name}"] + LLM["init_tracing
OpenAI LLM spans"] + AUTO["Auto-instrumentation
global OTel pipeline"] + end + + subgraph errors ["Error path"] + ERR["init_error_tracker
runs when SENTRY_DSN is set,
conserver side only"] + end + + subgraph chain ["Chain tracers, separate from OTel"] + TRC["_process_tracers
every entry in config tracers,
before link 0 and after each link"] + JL["tracers.jlinc"] + end + + OTLP["OTLP endpoint
usually an OTel Collector"]:::focus + SENTRY["Sentry"] + JAPI["JLINC API"] + + MON -->|"GET /health, /version, /stats/queue, no key"| API + API -->|"/stats/queue reads list length"| REDIS + + API -->|"counters"| HELP + WRK -->|"counters, histograms, inflight"| HELP + WRK -->|"registers at worker start"| GAUGE + GAUGE -->|"LLEN and INFO memory each tick"| REDIS + HELP --> GATE + GAUGE --> GATE + GATE -->|"no"| NOOP + GATE -->|"yes, first call in each pid"| PROV + PROV --> READ + READ --> GRPC + GRPC -->|"metrics"| OTLP + + API -->|"store_context_async before enqueue"| CTX + WRK -->|"store_context_sync for egress lists"| CTX + CTX -->|"retrieve_context, becomes a span link"| SPANS + WRK -->|"opens per vCon"| SPANS + WRK -->|"calls at startup"| LLM + API -->|"request spans"| AUTO + SPANS --> AUTO + LLM --> AUTO + AUTO -->|"traces and auto metrics"| OTLP + + WRK --> ERR + ERR -->|"logger.error events"| SENTRY + + WRK --> TRC + TRC --> JL + JL -->|"HTTP POST to the data store API"| JAPI + + classDef focus fill:#0BB81E,stroke:#0A7D18,color:#292929 diff --git a/docs/diagrams/D14-observability.svg b/docs/diagrams/D14-observability.svg new file mode 100644 index 00000000..f887c64a --- /dev/null +++ b/docs/diagrams/D14-observability.svg @@ -0,0 +1 @@ +

Chain tracers, separate from OTel

Error path

Trace path

Metrics path, common/lib

Server processes

GET /health, /version, /stats/queue, no key

/stats/queue reads list length

counters

counters, histograms, inflight

registers at worker start

LLEN and INFO memory each tick

no

yes, first call in each pid

metrics

store_context_async before enqueue

store_context_sync for egress lists

retrieve_context, becomes a span link

opens per vCon

calls at startup

request spans

traces and auto metrics

logger.error events

HTTP POST to the data store API

Monitoring client

API process
opentelemetry-instrument uvicorn

Conserver worker process
opentelemetry-instrument python

Redis

lib.metrics helpers
increment_counter, record_histogram,
add_updown_counter

lib.queue_metrics gauges
ingress_list.length,
redis.memory_used_bytes

OTEL_EXPORTER_
OTLP_ENDPOINT
set?

No metrics published

MeterProvider per process
service.instance.id is host-pid-pid

PeriodicExportingMetricReader
tick is OTEL_METRIC_
EXPORT_INTERVAL,
default 5000 ms

OTLPMetricExporter, gRPC only

Redis key
context:{list}:{uuid}

Worker spans
vcon_processing.{chain},
link.{name}, storage.{name}

init_tracing
OpenAI LLM spans

Auto-instrumentation
global OTel pipeline

init_error_tracker
runs when SENTRY_DSN is set,
conserver side only

_process_tracers
every entry in config tracers,
before link 0 and after each link

tracers.jlinc

OTLP endpoint
usually an OTel Collector

Sentry

JLINC API

\ No newline at end of file diff --git a/docs/diagrams/D14.sources.md b/docs/diagrams/D14.sources.md new file mode 100644 index 00000000..c2b0c9f2 --- /dev/null +++ b/docs/diagrams/D14.sources.md @@ -0,0 +1,75 @@ +# D14 sources + +Diagram: `D14-observability.mmd`, a flowchart. Owner page: `operations/monitoring.md`. + +Paths are relative to the repo root. Metric names live in `docs/reference/metrics.md`, so the diagram does not list them. + +## Nodes + +| Node | Source | +|---|---| +| Monitoring client | `api/api.py:284` names monitoring and backpressure as the purpose of `/stats/queue` | +| API process | `docker/Dockerfile.api:46`, `docker-compose.yml:49` | +| Conserver worker process | `docker/Dockerfile.conserver:52`, `docker-compose.yml:21`, `conserver/main.py:774-815` | +| Redis | `conserver/main.py:800`, `api/api.py:188-191` | +| `lib.metrics` helpers | `common/lib/metrics.py:153`, `common/lib/metrics.py:190`, `common/lib/metrics.py:264` | +| `lib.queue_metrics` gauges | `common/lib/queue_metrics.py:86-106`, `common/lib/queue_metrics.py:140-157` | +| `OTEL_EXPORTER_OTLP_ENDPOINT` decision | `common/lib/metrics.py:12`, `common/lib/metrics.py:67-70` | +| No metrics published | `common/lib/metrics.py:167-168`, `common/lib/metrics.py:207-208`, `common/lib/metrics.py:247-248`, `common/lib/metrics.py:278-279` | +| MeterProvider per process | `common/lib/metrics.py:21-26`, `common/lib/metrics.py:61-65`, `common/lib/metrics.py:76-82`, `common/lib/metrics.py:93-96`, `common/lib/metrics.py:118` | +| PeriodicExportingMetricReader | `common/lib/metrics.py:14`, `common/lib/metrics.py:88-91` | +| OTLPMetricExporter, gRPC only | `common/lib/metrics.py:7`, `common/lib/metrics.py:84-86` | +| Redis key `context:{list}:{uuid}` | `common/lib/context_utils.py:22-32` | +| Worker spans | `conserver/main.py:335-343`, `conserver/main.py:398-405`, `conserver/main.py:564-572` | +| `init_tracing` | `common/lib/tracing.py:6-25` | +| Auto-instrumentation | `docker/Dockerfile.api:37`, `docker/Dockerfile.api:46`, `docker/Dockerfile.conserver:43`, `docker/Dockerfile.conserver:52`, `common/lib/metrics.py:113-117` | +| `init_error_tracker` | `common/lib/error_tracking.py:27-30` | +| `_process_tracers` | `conserver/main.py:508-546` | +| `tracers.jlinc` | `conserver/tracers/jlinc/__init__.py:28-122`, `example_config.yml:102-115` | +| OTLP endpoint | `common/lib/metrics.py:84-86`, `docker-compose.yml:32`, `common/lib/tracing.py:10-12` names the collector | +| Sentry | `common/lib/error_tracking.py:9-24` | +| JLINC API | `conserver/tracers/jlinc/__init__.py:37-43` | + +## Edges + +| Edge | Behaviour | Source | +|---|---|---| +| Monitoring client to API process | Three routes need no key. See D13 | `api/api.py:235-236`, `api/api.py:257-258`, `api/api.py:275-276` | +| API process to Redis | `/stats/queue` asks the queue helper for a list length | `api/api.py:286` | +| API process to helpers | The API imports only `increment_counter` | `api/api.py:50`, `api/api.py:807`, `api/api.py:909`, `api/api.py:1047`, `api/api.py:1174` | +| Worker to helpers | Chain, link and storage metrics, plus the in-flight count. Links call the helpers too | `conserver/main.py:41`, `conserver/main.py:287-288`, `conserver/main.py:433-434`, `conserver/main.py:614`, `conserver/main.py:622`, `conserver/main.py:743`, `conserver/main.py:765`, `conserver/main.py:885` | +| Worker to gauges | Each worker process registers both gauges at start. The API never does | `conserver/main.py:807-809` | +| Gauges to Redis | Callbacks run on each export tick. `LLEN` per ingress list and DLQ, `INFO memory` for memory. Chain config is read on each tick | `common/lib/queue_metrics.py:60-81`, `common/lib/queue_metrics.py:118-135`, `common/lib/queue_metrics.py:27-47`, `common/lib/metrics.py:230-231` | +| Helpers to decision | Each helper calls the lazy init first | `common/lib/metrics.py:165`, `common/lib/metrics.py:205`, `common/lib/metrics.py:276` | +| Gauges to decision | Gauge registration calls the same lazy init | `common/lib/metrics.py:245` | +| Decision, no | The init remembers the pid and the helper returns | `common/lib/metrics.py:67-70` | +| Decision, yes | The first call in each pid builds a provider. A forked child rebuilds its own. An init error logs a warning and leaves metrics off | `common/lib/metrics.py:60-65`, `common/lib/metrics.py:72-96`, `common/lib/metrics.py:133-150` | +| Provider to reader | The reader is passed to the provider | `common/lib/metrics.py:93-96` | +| Reader to exporter | The exporter is passed to the reader | `common/lib/metrics.py:88-91` | +| Exporter to OTLP endpoint | The endpoint comes from the environment. `atexit` flushes on clean exit | `common/lib/metrics.py:84-86`, `common/lib/metrics.py:131` | +| API process to context key | Runs before enqueue and only when a valid span exists | `api/api.py:779`, `api/api.py:805`, `api/api.py:881`, `api/api.py:906-907`, `api/api.py:1019`, `api/api.py:1045`, `common/lib/context_utils.py:35-69`, `common/lib/context_utils.py:156-192` | +| Worker to context key | Forwarding to egress lists stores the current context first | `conserver/main.py:360-366`, `common/lib/context_utils.py:72-106` | +| Context key to worker spans | `retrieve_context` pops the oldest entry and `_create_span_from_context` adds a span link, not a parent | `conserver/main.py:713`, `conserver/main.py:736`, `conserver/main.py:318-333`, `common/lib/context_utils.py:129-143` | +| Worker to spans | One root span per vCon, with `link.*` and `storage.*` children. Errors are recorded on the span | `conserver/main.py:244-245`, `conserver/main.py:414-417`, `conserver/main.py:658-661` | +| Worker to `init_tracing` | Called in `main` and again in each worker process | `conserver/main.py:797`, `conserver/main.py:954` | +| API process to auto-instrumentation | The API has no span code of its own. `extract_otel_trace_context` reads the current span | `docker/Dockerfile.api:46`, `common/lib/context_utils.py:165-172` | +| Spans to auto-instrumentation | `trace.get_tracer` uses the global provider, which `opentelemetry-instrument` sets up | `conserver/main.py:316`, `conserver/main.py:397`, `conserver/main.py:563` | +| LLM spans to auto-instrumentation | `OpenAIInstrumentor` adds spans to the configured exporter | `common/lib/tracing.py:7-17` | +| Auto-instrumentation to OTLP endpoint | Separate from the metrics pipeline in `lib.metrics`. Both reach the collector | `common/lib/metrics.py:113-117`, `docker-compose.yml:32-35` | +| Worker to `init_error_tracker` | Called at import of `conserver/main.py`, in each worker, in `conserver/follower.py` and in six link modules. `api/api.py` never calls it | `conserver/main.py:148`, `conserver/main.py:790`, `conserver/follower.py:13`, `conserver/links/deepgram_link/__init__.py:33`, `conserver/links/groq_whisper/__init__.py:94`, `conserver/links/hugging_face_whisper/__init__.py:37`, `conserver/links/hugging_llm_link/__init__.py:45`, `conserver/links/openai_transcribe/__init__.py:35`, `conserver/links/wtf_transcribe/__init__.py:38` | +| `init_error_tracker` to Sentry | Logging at `ERROR` becomes an event and `INFO` and above become breadcrumbs. Trace sampling is 0. `capture_exception` has no caller in the repo | `common/lib/error_tracking.py:17-23`, `common/lib/error_tracking.py:49-51` | +| Worker to `_process_tracers` | Runs before the first link with index -1, then after each link | `conserver/main.py:600-601`, `conserver/main.py:641-644` | +| `_process_tracers` to `tracers.jlinc` | Every entry in top-level `tracers` runs for every chain. A tracer error is logged and re-raised only with `dlq_vcon_on_error` | `conserver/main.py:509-522`, `conserver/main.py:536-546` | +| `tracers.jlinc` to JLINC API | POSTs entity calls and `event/produce`. The event data is a SHA-256 hash of the vCon only when the configured options set `hash_event_data`, and otherwise the whole vCon. `default_options` do not apply, because `_process_tracers` always passes the configured options | `conserver/tracers/jlinc/__init__.py:37-43`, `conserver/tracers/jlinc/__init__.py:60-77`, `conserver/tracers/jlinc/__init__.py:110-115`, `conserver/main.py:522` | + +## TODO(verify) + +- TODO(verify): the auto-instrumentation exporter settings belong to the OpenTelemetry SDK, not this repo. This repo only passes `OTEL_EXPORTER_OTLP_*` through (`docker-compose.yml:32-35`). `.env.example:49` says a blank endpoint disables tracing, and no code here confirms that. +- TODO(verify): which instrumentation packages are present depends on `opentelemetry-bootstrap -a install || true` at image build (`docker/Dockerfile.api:37`), so the API request spans depend on that step succeeding. + +## Left out of the drawing + +- Plain logging. `common/logging.conf:39` writes everything to stdout. The stderr handler at line 45 is defined but no logger uses it. +- `X-Vcon-Server-Version` and `X-Vcon-Server-Commit` response headers (`api/api.py:210-228`). +- `log_llen` debug logging (`conserver/main.py:687`). +- The deprecated no-op functions `init_metrics`, `stats_gauge` and `stats_count` (`common/lib/metrics.py:34-43`). diff --git a/docs/diagrams/README.md b/docs/diagrams/README.md new file mode 100644 index 00000000..189b16d1 --- /dev/null +++ b/docs/diagrams/README.md @@ -0,0 +1,41 @@ +# Diagram sources + +This folder holds the Mermaid sources for the docs and the SVGs built from them. + +The [visuals index](../visuals/index.md) lists D01 to D14 with their SVGs, owner pages and motion scenes. + +## File names + +Each diagram has three files: + +- `Dnn-name.mmd`, the source +- `Dnn-name.svg`, the rendered output +- `Dnn.sources.md`, the code paths the diagram was drawn from + +## Brand theme + +The first line of every `.mmd` file must be the `%%{init}%%` line from `_init.txt`, copied exactly. `render_diagrams.sh` fails a diagram that does not start with it. + +`vconic-theme.json` holds the same colours as a Mermaid config file. Change both files together. + +| Role | Colour | +|---|---| +| Node border | `#0A7D18` | +| Node fill | `#F3F4F6` | +| Heading text | `#292929` | +| Body text and lines | `#33363B` | +| Secondary borders | `#8A8A8D` | + +Use `#0BB81E` to pick out one element with a `classDef`. Diagram text uses Inter. + +## Rendering + +From the repo root: + +```bash +scripts/docs/render_diagrams.sh +``` + +The script uses `$MMDC` when set and otherwise runs mermaid-cli through `npx`. Set `PUPPETEER_CONFIG` to pass a puppeteer config file, for example to name a local Chrome. Pass a folder as the first argument to render somewhere else. + +`scripts/docs/check.sh` renders every diagram to a temp folder to catch syntax errors. It does not compare SVG bytes, so commit the SVG whenever you change a source. diff --git a/docs/diagrams/_init.txt b/docs/diagrams/_init.txt new file mode 100644 index 00000000..96400656 --- /dev/null +++ b/docs/diagrams/_init.txt @@ -0,0 +1 @@ +%%{init: {'theme':'base','themeVariables':{'fontFamily':'Inter, Helvetica, Arial, sans-serif','fontSize':'14px','background':'#FFFFFF','primaryColor':'#F3F4F6','primaryTextColor':'#292929','primaryBorderColor':'#0A7D18','secondaryColor':'#FFFFFF','secondaryTextColor':'#33363B','secondaryBorderColor':'#8A8A8D','tertiaryColor':'#FFFFFF','tertiaryTextColor':'#33363B','tertiaryBorderColor':'#8A8A8D','lineColor':'#33363B','textColor':'#33363B','mainBkg':'#F3F4F6','nodeBorder':'#0A7D18','clusterBkg':'#FFFFFF','clusterBorder':'#8A8A8D','edgeLabelBackground':'#FFFFFF','actorBkg':'#F3F4F6','actorBorder':'#0A7D18','actorTextColor':'#292929','signalColor':'#33363B','signalTextColor':'#292929','labelBoxBkgColor':'#F3F4F6','labelBoxBorderColor':'#0A7D18','noteBkgColor':'#F3F4F6','noteBorderColor':'#8A8A8D','noteTextColor':'#292929'}}}%% diff --git a/docs/diagrams/vconic-theme.json b/docs/diagrams/vconic-theme.json new file mode 100644 index 00000000..3423eb0b --- /dev/null +++ b/docs/diagrams/vconic-theme.json @@ -0,0 +1,34 @@ +{ + "theme": "base", + "themeVariables": { + "fontFamily": "Inter, Helvetica, Arial, sans-serif", + "fontSize": "14px", + "background": "#FFFFFF", + "primaryColor": "#F3F4F6", + "primaryTextColor": "#292929", + "primaryBorderColor": "#0A7D18", + "secondaryColor": "#FFFFFF", + "secondaryTextColor": "#33363B", + "secondaryBorderColor": "#8A8A8D", + "tertiaryColor": "#FFFFFF", + "tertiaryTextColor": "#33363B", + "tertiaryBorderColor": "#8A8A8D", + "lineColor": "#33363B", + "textColor": "#33363B", + "mainBkg": "#F3F4F6", + "nodeBorder": "#0A7D18", + "clusterBkg": "#FFFFFF", + "clusterBorder": "#8A8A8D", + "edgeLabelBackground": "#FFFFFF", + "actorBkg": "#F3F4F6", + "actorBorder": "#0A7D18", + "actorTextColor": "#292929", + "signalColor": "#33363B", + "signalTextColor": "#292929", + "labelBoxBkgColor": "#F3F4F6", + "labelBoxBorderColor": "#0A7D18", + "noteBkgColor": "#F3F4F6", + "noteBorderColor": "#8A8A8D", + "noteTextColor": "#292929" + } +} diff --git a/docs/extending/creating-links.md b/docs/extending/creating-links.md index 48493e63..7c77303f 100644 --- a/docs/extending/creating-links.md +++ b/docs/extending/creating-links.md @@ -1,85 +1,85 @@ -# Creating Processing Links +# Create a processing link -Links are the building blocks of vCon processing pipelines. This guide covers creating custom links. +A link is one step in a chain. This page shows how to write one that the server can run, test and recover from failure. The [link reference](../reference/links/index.md) documents the links that ship with the server. -## Link Interface +## Follow the link contract -Every link must implement the `run` function: +Every link is a module with a `run` function: ```python def run(vcon_uuid: str, link_name: str, opts: dict = default_options) -> str | None: - """ - Process a vCon. - - Args: - vcon_uuid: UUID of the vCon to process - link_name: Name of this link instance (from config) - opts: Configuration options dictionary - - Returns: - str: Return the vcon_uuid to continue the chain - None: Return None to filter/stop the vCon - """ + ... ``` -## Directory Structure +| Argument | Value | +|---|---| +| `vcon_uuid` | The id of the vCon. Load the vCon yourself | +| `link_name` | The name of this entry in `config.yml` | +| `opts` | The entry's `options`. `None` when the entry has no `options` key, because the server always passes this argument | + +The sequence below shows one vCon passing through a link. + +![Sequence of a worker running hooks, tracers and a link module for one vCon, with success and failure branches](../diagrams/D12-link-execution-contract.svg) + +What you return decides what happens next: + +| Result | Effect | +|---|---| +| The same id | The next link runs. After the last link, the vCon goes to the egress lists and then storage | +| A different id | The chain continues with that vCon. It must exist in Redis | +| `None` or another falsy value | The chain stops. No later link, egress list or storage runs for this vCon | +| An exception | The vCon moves to `DLQ:`, and no later step runs | + +So a link that halts also keeps the vCon out of storage. To skip your own work and let the vCon carry on, return the id. + +Other points to plan for: + +- A vCon can be missing, because `get_vcon` returns `None` once it has expired from Redis and no storage holds it. Return `None` in that case. +- `after_link` receives `status="success"` for a halt as well. Only the `conserver.link.count` metric separates them, with its `outcome` attribute. +- An unknown link name or a failed import raises before the `after_link` hook is set up, and the vCon reaches the dead letter queue. +- A tracer error stops the chain only when that tracer sets `dlq_vcon_on_error`. A failing tracer with no `options` key also stops the chain and sends the vCon to the DLQ, so always set `options`, even as `options: {}`. + +## Lay out the module ``` -server/links/ - my_link/ - __init__.py # Required: contains run() and default_options - README.md # Optional: documentation - tests/ - __init__.py - test_my_link.py +conserver/links/my_link/ + __init__.py # run() and default_options + README.md # Short description and a link to the reference page + test_my_link.py # Tests sit beside the code ``` -## Basic Link Example +## Write a basic link ```python -# server/links/my_link/__init__.py +# conserver/links/my_link/__init__.py from lib.logging_utils import init_logger -from server.lib.vcon_redis import VconRedis +from lib.vcon_redis import VconRedis logger = init_logger(__name__) default_options = { "tag_name": "processed", - "tag_value": "true" + "tag_value": "true", } + def run(vcon_uuid, link_name, opts=default_options): - """Add a tag to the vCon.""" - logger.debug(f"Starting {link_name}::run for {vcon_uuid}") - - # Merge default options with provided options - options = {**default_options, **opts} - - # Get vCon from Redis + options = {**default_options, **(opts or {})} + vcon_redis = VconRedis() vcon = vcon_redis.get_vcon(vcon_uuid) - if vcon is None: - logger.error(f"vCon not found: {vcon_uuid}") + logger.warning("vCon %s not found, halting chain", vcon_uuid) return None - - # Process the vCon - vcon.add_tag( - tag_name=options["tag_name"], - tag_value=options["tag_value"] - ) - - # Save changes back to Redis + + vcon.add_tag(options["tag_name"], options["tag_value"]) vcon_redis.store_vcon(vcon) - - logger.info(f"Completed {link_name}::run for {vcon_uuid}") + return vcon_uuid ``` -## Configuration - -Register the link in `config.yml`: +## Register the link ```yaml links: @@ -94,122 +94,128 @@ chains: links: - my_link storages: - - redis_storage + - file ingress_lists: - - default - enabled: 1 + - my_list ``` -## Common Patterns +This sample uses the `file` backend from the [quick start](../getting-started/quick-start.md#write-the-configuration). A name under `storages` must exist in the top-level `storages` section, or every save lands in `DLQ:storage:`. + +Give the chain its own list. A later chain on the same list silently replaces the earlier one. See [assign ingress lists](../configuration/chains-and-pipelines.md#assign-ingress-lists). + +## Load the link -### Working with vCon Data +Under Compose the repository is bind mounted at `/app`, so a new module needs no build. A worker imports it on the first vCon that reaches it. `watchmedo` restarts the conserver on any `.py` save, so there is nothing to do. The restart stops the process with `SIGINT` and kills it after 10 seconds, and a killed worker loses the id it held. + +Without `watchmedo`, an edit needs a restart, because a worker keeps an imported module for the life of the process. + +The published images copy `conserver/` at build time, so a link added to a clone does not reach them. Build your own image. See [Bake modules into an image](dynamic-modules.md#bake-modules-into-an-image). + +## Work with vCon data + +`get_vcon` returns a `Vcon` object from `common/vcon.py`. `store_vcon` writes it back and keeps any existing expiry. + +### Read the fields ```python -def run(vcon_uuid, link_name, opts=default_options): - vcon_redis = VconRedis() - vcon = vcon_redis.get_vcon(vcon_uuid) - - # Access basic properties - uuid = vcon.uuid - created_at = vcon.created_at - - # Access parties - for party in vcon.parties: - tel = party.get("tel") - email = party.get("mailto") - name = party.get("name") - - # Access dialog - for dialog in vcon.dialog: - dialog_type = dialog.get("type") # "recording", "text", etc. - start_time = dialog.get("start") - parties = dialog.get("parties") - body = dialog.get("body") # Text content - url = dialog.get("url") # Audio/video URL - - # Access analysis - for analysis in vcon.analysis: - analysis_type = analysis.get("type") - body = analysis.get("body") - vendor = analysis.get("vendor") - - # Access attachments - for attachment in vcon.attachments: - filename = attachment.get("filename") - content = attachment.get("body") - - return vcon_uuid +vcon.uuid +vcon.created_at +vcon.subject + +for party in vcon.parties: + tel = party.get("tel") + email = party.get("mailto") + +for dialog in vcon.dialog: + dialog_type = dialog.get("type") # "recording", "text", "transfer" + body = dialog.get("body") + url = dialog.get("url") + +transcript = vcon.find_analysis_by_type("transcript") +tags = vcon.find_attachment_by_purpose("tags") +department = vcon.get_tag("department") ``` -### Adding Analysis +An attachment or analysis `body` with `encoding: "json"` may be a JSON value or a JSON string. `add_analysis` stores a dict or list as the value. `add_tag` writes its list as a JSON string today, and older records may hold strings too. `Vcon.decoded_body(entry)` handles both. + +`find_attachment_by_purpose`, `get_tag`, `add_tag` and `add_analysis` need the `attachments` and `analysis` keys, and raise `KeyError` without them. `POST /vcon` always fills both. For a vCon from another producer, call `vcon.vcon_dict.setdefault("attachments", [])` and `vcon.vcon_dict.setdefault("analysis", [])` first. + +### Add analysis + +`add_analysis` takes keyword arguments only, and `vendor` is required. Pass other fields through `extra`. ```python -def run(vcon_uuid, link_name, opts=default_options): - vcon_redis = VconRedis() - vcon = vcon_redis.get_vcon(vcon_uuid) - - # Perform analysis - result = analyze_vcon(vcon) - - # Add analysis to vCon - vcon.add_analysis( - type="custom_analysis", - body=result, - vendor="my_company", - dialog=0, # Optional: index of dialog this applies to - encoding="json" - ) - - vcon_redis.store_vcon(vcon) - return vcon_uuid +vcon.add_analysis( + type="custom_analysis", + dialog=0, + vendor="my_vendor", + body={"score": 0.9}, + extra={"schema": "my-schema-v1", "product": "my-product"}, +) +``` + +A dict or list `body` is stored as is, with `encoding` set to `json`. Use `schema`, not `schema_version`. + +### Add tags + +```python +vcon.add_tag("status", "processed") ``` -### Adding Tags +Tags live in one attachment with `purpose: "tags"`, as `name:value` strings. The `body` is a JSON string with `encoding: "json"`, not an array, so decode it with `Vcon.decoded_body` or, in `jq`, with `fromjson`. + +### Add an attachment + +`Vcon.add_attachment` writes only `type`, `body` and `encoding`. `store_vcon` renames `type` to `purpose`, but it does not add the other required fields. Append the entry yourself to get all of them: + +```python +vcon.vcon_dict.setdefault("attachments", []).append({ + "purpose": "my_metadata", + "start": vcon.created_at, + "party": 0, + "dialog": 0, + "mediatype": "application/json", + "encoding": "json", + "body": {"source": "my_link"}, +}) +``` + +## Apply these patterns + +### Filter vCons ```python def run(vcon_uuid, link_name, opts=default_options): - vcon_redis = VconRedis() - vcon = vcon_redis.get_vcon(vcon_uuid) - - # Add single tag - vcon.add_tag("status", "processed") - - # Add multiple tags - for tag in opts.get("tags", []): - vcon.add_tag(tag["name"], tag["value"]) - - vcon_redis.store_vcon(vcon) + options = {**default_options, **(opts or {})} + + vcon = VconRedis().get_vcon(vcon_uuid) + if vcon is None: + return None + + required_domain = options.get("required_domain") + if required_domain and not any( + required_domain in party.get("mailto", "") for party in vcon.parties + ): + logger.info("Halting %s: no party in %s", vcon_uuid, required_domain) + return None + return vcon_uuid ``` -### Filtering vCons +To offer the `only_if` and `sampling_rate` options that other links have, use `lib.links.filters`: ```python -def run(vcon_uuid, link_name, opts=default_options): - vcon_redis = VconRedis() - vcon = vcon_redis.get_vcon(vcon_uuid) - - # Filter by duration - min_duration = opts.get("min_duration", 60) - if get_duration(vcon) < min_duration: - logger.info(f"Filtering {vcon_uuid}: duration too short") - return None # Stop processing - - # Filter by party - required_domain = opts.get("required_domain") - if required_domain: - has_domain = any( - required_domain in p.get("mailto", "") - for p in vcon.parties - ) - if not has_domain: - logger.info(f"Filtering {vcon_uuid}: missing required domain") - return None - - return vcon_uuid # Continue processing +from lib.links.filters import is_included, randomly_execute_with_sampling + +if not is_included(options, vcon) or not randomly_execute_with_sampling(options): + return vcon_uuid ``` -### Calling External APIs +The [shared filter options](../reference/links/index.md#set-the-shared-filter-options) describe what they accept. + +### Call an external API + +Retry inside the link, then let the last error raise so the vCon reaches the dead letter queue. ```python import requests @@ -218,279 +224,157 @@ from tenacity import retry, stop_after_attempt, wait_exponential default_options = { "api_url": "https://api.example.com/analyze", "api_key": "", - "timeout": 30 + "timeout": 30, } -@retry( - stop=stop_after_attempt(3), - wait=wait_exponential(multiplier=1, max=10) -) + +@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, max=10), reraise=True) def call_api(url, api_key, data, timeout): - """Call external API with retry logic.""" response = requests.post( url, headers={"Authorization": f"Bearer {api_key}"}, json=data, - timeout=timeout + timeout=timeout, ) response.raise_for_status() return response.json() + def run(vcon_uuid, link_name, opts=default_options): - options = {**default_options, **opts} - + options = {**default_options, **(opts or {})} + vcon_redis = VconRedis() vcon = vcon_redis.get_vcon(vcon_uuid) - - # Call external API - try: - result = call_api( - options["api_url"], - options["api_key"], - vcon.to_dict(), - options["timeout"] - ) - except requests.RequestException as e: - logger.error(f"API call failed: {e}") - raise # Will send to DLQ - - # Add result to vCon - vcon.add_analysis(type="external_analysis", body=result) + if vcon is None: + return None + + result = call_api(options["api_url"], options["api_key"], vcon.to_dict(), options["timeout"]) + + vcon.add_analysis(type="external_analysis", dialog=0, vendor="example", body=result) vcon_redis.store_vcon(vcon) - return vcon_uuid ``` -### Routing to Different Queues +To send a vCon to an outside system unchanged, the bundled [webhook link](../reference/links/webhook.md) may already do what you need. A link that sends vCons out should apply `lib.vcon_egress_compat.to_configured_legacy`. See [egress compatibility](../configuration/egress-compatibility.md). + +### Route to another queue + +Use `VconQueue`. `enqueue` appends to the list, and a worker pops from the other end, so order holds. ```python +from lib.queue import VconQueue + + def run(vcon_uuid, link_name, opts=default_options): - vcon_redis = VconRedis() - vcon = vcon_redis.get_vcon(vcon_uuid) - - # Determine destination based on vCon properties - destination = determine_destination(vcon, opts.get("rules", [])) - + options = {**default_options, **(opts or {})} + + vcon = VconRedis().get_vcon(vcon_uuid) + if vcon is None: + return None + + destination = options["routes"].get(vcon.get_tag("department")) if destination: - # Push to destination queue - redis_client = vcon_redis.get_redis() - redis_client.lpush(destination, vcon_uuid) - logger.info(f"Routed {vcon_uuid} to {destination}") - + VconQueue().enqueue(destination, vcon_uuid) + logger.info("Routed %s to %s", vcon_uuid, destination) + return vcon_uuid ``` -## Error Handling +The bundled [tag_router](../reference/links/tag-router.md) routes by tag. -### Graceful Degradation +### Record metrics ```python -def run(vcon_uuid, link_name, opts=default_options): - vcon_redis = VconRedis() - vcon = vcon_redis.get_vcon(vcon_uuid) - - try: - # Try primary processing - result = primary_process(vcon) - except PrimaryServiceError: - logger.warning(f"Primary service failed, using fallback") - try: - # Try fallback - result = fallback_process(vcon) - except FallbackServiceError: - logger.warning(f"Fallback failed, skipping processing") - # Continue chain without this processing - return vcon_uuid - - vcon.add_analysis(type="process_result", body=result) - vcon_redis.store_vcon(vcon) - return vcon_uuid +from lib.metrics import increment_counter, record_histogram + +increment_counter("conserver.link.my_link.count", attributes={"link.name": link_name}) ``` -### DLQ vs Skip +Keep ids out of the attributes on histograms, because each new value creates a separate time series. + +## Decide how to handle errors + +| You want | Do this | +|---|---| +| Keep going without this link's result | Log it and return the id | +| Stop, with no storage and no replay | Return `None` | +| Stop, and keep the vCon for inspection and replay | Raise | + +Raise when in doubt. A halted vCon leaves no queue entry, while a raised one waits in the [dead letter queue](../operations/dead-letter-queue.md) for replay. ```python def run(vcon_uuid, link_name, opts=default_options): vcon_redis = VconRedis() vcon = vcon_redis.get_vcon(vcon_uuid) - + if vcon is None: + return None + try: - process(vcon) - except TemporaryError as e: - # Temporary issue - skip this vCon - logger.warning(f"Temporary error, skipping: {e}") - return None # Filter out, don't DLQ - except PermanentError as e: - # Permanent issue - needs investigation - logger.error(f"Permanent error: {e}") - raise # Will go to DLQ - except Exception as e: - # Unknown error - DLQ for safety - logger.error(f"Unknown error: {e}") - raise - + result = primary_process(vcon) + except PrimaryServiceError: + logger.warning("Primary service failed for %s, using fallback", vcon_uuid) + result = fallback_process(vcon) # An error here reaches the DLQ + + vcon.add_analysis(type="process_result", dialog=0, vendor="my_vendor", body=result) + vcon_redis.store_vcon(vcon) return vcon_uuid ``` -## Testing Links +## Test the link -### Unit Tests +Patch `VconRedis` where your module imports it. `pytest.ini` sets the import paths. ```python -# server/links/my_link/tests/test_my_link.py - -import pytest -from unittest.mock import MagicMock, patch - -class TestMyLink: - def test_run_adds_tag(self): - """Test that run adds the expected tag.""" - with patch('server.links.my_link.VconRedis') as mock_redis_class: - # Setup mock - mock_vcon = MagicMock() - mock_redis = MagicMock() - mock_redis.get_vcon.return_value = mock_vcon - mock_redis_class.return_value = mock_redis - - # Import and run - from server.links.my_link import run - result = run("test-uuid", "my_link", {"tag_name": "test", "tag_value": "value"}) - - # Verify - assert result == "test-uuid" - mock_vcon.add_tag.assert_called_once_with("test", "value") - mock_redis.store_vcon.assert_called_once_with(mock_vcon) - - def test_run_returns_none_when_vcon_not_found(self): - """Test that run returns None when vCon doesn't exist.""" - with patch('server.links.my_link.VconRedis') as mock_redis_class: - mock_redis = MagicMock() - mock_redis.get_vcon.return_value = None - mock_redis_class.return_value = mock_redis - - from server.links.my_link import run - result = run("nonexistent-uuid", "my_link", {}) - - assert result is None - - def test_run_uses_default_options(self): - """Test that default options are used when not provided.""" - with patch('server.links.my_link.VconRedis') as mock_redis_class: - mock_vcon = MagicMock() - mock_redis = MagicMock() - mock_redis.get_vcon.return_value = mock_vcon - mock_redis_class.return_value = mock_redis - - from server.links.my_link import run, default_options - run("test-uuid", "my_link", {}) - - mock_vcon.add_tag.assert_called_once_with( - default_options["tag_name"], - default_options["tag_value"] - ) -``` +# conserver/links/my_link/test_my_link.py -### Integration Tests +from unittest.mock import patch -```python -# server/links/my_link/tests/test_my_link_integration.py - -import pytest - -@pytest.mark.integration -class TestMyLinkIntegration: - def test_full_processing(self, redis_client, sample_vcon): - """Test full processing with real Redis.""" - from server.lib.vcon_redis import VconRedis - from server.links.my_link import run - - # Setup - vcon_redis = VconRedis() - vcon_redis.store_vcon(sample_vcon) - - # Run - result = run(sample_vcon.uuid, "my_link", {"tag_name": "test"}) - - # Verify - assert result == sample_vcon.uuid - updated_vcon = vcon_redis.get_vcon(sample_vcon.uuid) - assert any(t.get("name") == "test" for t in updated_vcon.tags) -``` +from vcon import Vcon -## Best Practices +from links.my_link import default_options, run -### 1. Always Use Default Options -```python -default_options = { - "option1": "default_value", - "option2": 100 -} +@patch("links.my_link.VconRedis") +def test_run_adds_tag_and_stores(mock_vcon_redis): + vcon = Vcon.build_new() + instance = mock_vcon_redis.return_value + instance.get_vcon.return_value = vcon -def run(vcon_uuid, link_name, opts=default_options): - options = {**default_options, **opts} # Merge with provided -``` - -### 2. Use Logging Appropriately + result = run("test-uuid", "my_link", {"tag_name": "test", "tag_value": "value"}) -```python -logger.debug("Detailed info for debugging") -logger.info("Normal operations") -logger.warning("Unexpected but handled") -logger.error("Failures", exc_info=True) # Include traceback -``` + assert result == "test-uuid" + assert vcon.get_tag("test") == "value" + instance.store_vcon.assert_called_once_with(vcon) -### 3. Handle Missing Data Gracefully -```python -def run(vcon_uuid, link_name, opts=default_options): - vcon = VconRedis().get_vcon(vcon_uuid) - - # Check for required data - if not vcon.dialog: - logger.info(f"No dialog in {vcon_uuid}, skipping") - return vcon_uuid # Continue but skip processing -``` +@patch("links.my_link.VconRedis") +def test_run_halts_when_vcon_missing(mock_vcon_redis): + mock_vcon_redis.return_value.get_vcon.return_value = None -### 4. Document Your Link + assert run("missing-uuid", "my_link", {}) is None -Create a README.md: -```markdown -# My Link +@patch("links.my_link.VconRedis") +def test_run_uses_defaults_when_options_are_none(mock_vcon_redis): + vcon = Vcon.build_new() + mock_vcon_redis.return_value.get_vcon.return_value = vcon -Processes vCons by adding custom tags. + run("test-uuid", "my_link", None) -## Options - -| Option | Type | Default | Description | -|--------|------|---------|-------------| -| tag_name | string | "processed" | Name of tag to add | -| tag_value | string | "true" | Value of tag | - -## Example Configuration - - links: - my_link: - module: links.my_link - options: - tag_name: custom - tag_value: value + assert vcon.get_tag(default_options["tag_name"]) == default_options["tag_value"] ``` -### 5. Keep Links Focused +Run them with `uv run pytest conserver/links/my_link`. -Each link should do one thing well: +For a test against real Redis, mark it with `@pytest.mark.integration` so that `pytest -m "not integration"` skips it. -```python -# Good: Single responsibility -def run_transcribe(vcon_uuid, link_name, opts): - # Only handles transcription - -def run_analyze(vcon_uuid, link_name, opts): - # Only handles analysis - -# Bad: Multiple responsibilities -def run_do_everything(vcon_uuid, link_name, opts): - # Transcribes AND analyzes AND routes AND stores -``` +## Follow these practices + +- Handle `opts` being `None`, and merge it over `default_options`. +- Check for a missing vCon before you use it. +- Keep each link to one job, so that chains stay easy to rearrange. +- Make `run` safe to repeat. A DLQ replay runs the whole chain again, so your link can see a vCon it already processed. +- Log the id, and never log credentials. `lib.redaction.safe_opts` strips credential-shaped options before you log or record them. +- Store once, at the end of `run`. +- Leave entries you did not write unchanged. +- Add a README with the options, and a page under `docs/reference/links/`. diff --git a/docs/extending/creating-storage-adapters.md b/docs/extending/creating-storage-adapters.md index ec5d0160..bcfb7054 100644 --- a/docs/extending/creating-storage-adapters.md +++ b/docs/extending/creating-storage-adapters.md @@ -1,118 +1,98 @@ -# Creating Storage Adapters +# Create a storage adapter -Storage adapters persist vCons to external systems. This guide covers creating custom storage adapters. +A storage adapter keeps vCons in a backend. This page shows how to write one that the server can call, retry and read back from. The [storage adapter reference](../reference/storage-adapters/index.md) documents the adapters that ship with the server, including [how a write runs](../reference/storage-adapters/index.md#follow-a-write-through-the-server). -## Storage Interface +## Implement the interface -Storage adapters implement these functions: +An adapter is a module with `default_options` and a `save` function. `get` and `delete` are optional. ```python +default_options = {} + def save(vcon_uuid: str, opts: dict = default_options) -> None: - """Save a vCon to storage.""" + """Write the vCon. Raise on failure.""" def get(vcon_uuid: str, opts: dict = default_options) -> dict | None: - """Retrieve a vCon from storage. Returns None if not found.""" + """Return the vCon as a dict, or None if it is not here.""" def delete(vcon_uuid: str, opts: dict = default_options) -> bool: - """Delete a vCon from storage. Returns True if deleted.""" + """Delete the vCon. Return True if it was deleted.""" ``` -Only `save` is required. `get` and `delete` are optional. +| Function | Called by | When it is missing | +|---|---|---| +| `save` | The conserver, at the end of a chain | Required | +| `get` | `VconRedis` and the API, when Redis misses | The server treats the vCon as absent here | +| `delete` | `DELETE /vcon/{vcon_uuid}` | The server skips this backend | + +`default_options` is required even if you always set `options`, because the server reads the attribute either way. -## Directory Structure +The server passes the id, so `save` loads the vCon itself with `VconRedis`. Adapters can run in the API image as well as the conserver image, so keep imports to `common/`. + +## Lay out the module ``` -server/storage/ - my_storage/ - __init__.py # Required: contains save(), get(), delete() - README.md # Optional: documentation - tests/ - __init__.py - test_my_storage.py +common/storage/my_storage/ + __init__.py # save(), get(), delete() and default_options + README.md + test_my_storage.py # Tests sit beside the code ``` -## Basic Storage Example +## Write a basic adapter ```python -# server/storage/my_storage/__init__.py +# common/storage/my_storage/__init__.py import json -import os +from pathlib import Path + from lib.logging_utils import init_logger -from server.lib.vcon_redis import VconRedis +from lib.vcon_egress_compat import to_configured_legacy +from lib.vcon_redis import VconRedis logger = init_logger(__name__) default_options = { "path": "/data/vcons", - "file_extension": ".json" } + +def _file_path(vcon_uuid, opts): + options = {**default_options, **(opts or {})} + return Path(options["path"]) / f"{vcon_uuid}.json" + + def save(vcon_uuid, opts=default_options): - """Save vCon to file system.""" - options = {**default_options, **opts} - - # Get vCon from Redis - vcon_redis = VconRedis() - vcon = vcon_redis.get_vcon(vcon_uuid) - + vcon = VconRedis().get_vcon(vcon_uuid) if vcon is None: - logger.error(f"vCon not found: {vcon_uuid}") raise ValueError(f"vCon not found: {vcon_uuid}") - - # Ensure directory exists - os.makedirs(options["path"], exist_ok=True) - - # Write to file - file_path = os.path.join( - options["path"], - f"{vcon_uuid}{options['file_extension']}" - ) - - with open(file_path, 'w') as f: - json.dump(vcon.to_dict(), f, indent=2) - - logger.info(f"Saved {vcon_uuid} to {file_path}") + + file_path = _file_path(vcon_uuid, opts) + file_path.parent.mkdir(parents=True, exist_ok=True) + file_path.write_text(json.dumps(to_configured_legacy(vcon.to_dict()))) + logger.info("Saved %s to %s", vcon_uuid, file_path) + def get(vcon_uuid, opts=default_options): - """Retrieve vCon from file system.""" - options = {**default_options, **opts} - - file_path = os.path.join( - options["path"], - f"{vcon_uuid}{options['file_extension']}" - ) - - if not os.path.exists(file_path): - logger.debug(f"vCon not found: {file_path}") + file_path = _file_path(vcon_uuid, opts) + if not file_path.exists(): return None - - with open(file_path, 'r') as f: - data = json.load(f) - - logger.debug(f"Retrieved {vcon_uuid} from {file_path}") - return data + return json.loads(file_path.read_text()) + def delete(vcon_uuid, opts=default_options): - """Delete vCon from file system.""" - options = {**default_options, **opts} - - file_path = os.path.join( - options["path"], - f"{vcon_uuid}{options['file_extension']}" - ) - - if os.path.exists(file_path): - os.remove(file_path) - logger.info(f"Deleted {vcon_uuid} from {file_path}") - return True - - return False + file_path = _file_path(vcon_uuid, opts) + if not file_path.exists(): + return False + file_path.unlink() + return True ``` -## Configuration +`to_configured_legacy` applies `EGRESS_FORMAT_VERSION`, and returns the vCon unchanged when that is unset. See [egress compatibility](../configuration/egress-compatibility.md). + +An `options` block replaces `default_options` and does not merge with it, so merge them yourself, as `_file_path` does. See [the rule for option defaults](../reference/storage-adapters/index.md#learn-the-rule-for-option-defaults). -Register the storage in `config.yml`: +## Register the adapter ```yaml storages: @@ -120,492 +100,193 @@ storages: module: storage.my_storage options: path: /data/custom_vcons - file_extension: .vcon.json chains: my_chain: links: - - transcribe + - my_link storages: - my_storage ingress_lists: - default - enabled: 1 ``` -## Common Patterns +The server imports the module by name and does not read `pip_name` for storages, so an adapter's package must already be installed. Add it to the `storage` group in `pyproject.toml` and run `uv lock`. If it is heavy, give it its own group, as `storage-milvus` does. -### Database Storage +## Handle a failed write + +Let `save` raise. The server catches the error, pushes the vCon onto `DLQ:storage:`, extends its Redis expiry to `VCON_DLQ_EXPIRY` and moves on, so other backends are not affected and the chain is not rerun. `POST /dlq/storage/reprocess` then retries the write alone. The [storage adapter reference](../reference/storage-adapters/index.md#handle-a-failed-write) covers this in full. + +If `save` catches an error and returns, the server records success, so nothing retries that write. + +A replay runs `save` again, so make it safe to repeat: + +- Use an upsert, or overwrite by id. +- Write to a temporary name and rename, if a half-written file would do harm. +- Use `tenacity` for short retries, and raise when they run out. + +## Apply these patterns + +### Write to a database + +Open connections with a context manager, and upsert by id. ```python -# server/storage/my_database/__init__.py +from contextlib import contextmanager import psycopg2 -from contextlib import contextmanager -from lib.logging_utils import init_logger -from server.lib.vcon_redis import VconRedis -logger = init_logger(__name__) +from lib.vcon_redis import VconRedis default_options = { "host": "localhost", "port": 5432, "database": "vcons", "user": "vcon", - "password": "" + "password": "", } + @contextmanager -def get_connection(opts): - """Context manager for database connections.""" +def get_connection(options): conn = psycopg2.connect( - host=opts["host"], - port=opts["port"], - database=opts["database"], - user=opts["user"], - password=opts["password"] + host=options["host"], + port=options["port"], + database=options["database"], + user=options["user"], + password=options["password"], ) try: yield conn finally: conn.close() + def save(vcon_uuid, opts=default_options): - """Save vCon to database.""" - options = {**default_options, **opts} - - vcon_redis = VconRedis() - vcon = vcon_redis.get_vcon(vcon_uuid) - + options = {**default_options, **(opts or {})} + + vcon = VconRedis().get_vcon(vcon_uuid) + if vcon is None: + raise ValueError(f"vCon not found: {vcon_uuid}") + with get_connection(options) as conn: with conn.cursor() as cur: cur.execute( """ INSERT INTO vcons (uuid, data, created_at) VALUES (%s, %s, %s) - ON CONFLICT (uuid) DO UPDATE SET data = %s + ON CONFLICT (uuid) DO UPDATE SET data = EXCLUDED.data """, - (vcon_uuid, vcon.dumps(), vcon.created_at, vcon.dumps()) - ) - conn.commit() - - logger.info(f"Saved {vcon_uuid} to database") - -def get(vcon_uuid, opts=default_options): - """Retrieve vCon from database.""" - options = {**default_options, **opts} - - with get_connection(options) as conn: - with conn.cursor() as cur: - cur.execute( - "SELECT data FROM vcons WHERE uuid = %s", - (vcon_uuid,) - ) - row = cur.fetchone() - - if row: - import json - return json.loads(row[0]) - return None - -def delete(vcon_uuid, opts=default_options): - """Delete vCon from database.""" - options = {**default_options, **opts} - - with get_connection(options) as conn: - with conn.cursor() as cur: - cur.execute( - "DELETE FROM vcons WHERE uuid = %s", - (vcon_uuid,) + (vcon_uuid, vcon.dumps(), vcon.created_at), ) - deleted = cur.rowcount > 0 conn.commit() - - return deleted ``` -### API Storage +### Write to an HTTP API ```python -# server/storage/api_storage/__init__.py - import requests from tenacity import retry, stop_after_attempt, wait_exponential -from lib.logging_utils import init_logger -from server.lib.vcon_redis import VconRedis -logger = init_logger(__name__) +from lib.vcon_redis import VconRedis default_options = { "base_url": "https://api.example.com", "api_key": "", - "timeout": 30 + "timeout": 30, } -@retry( - stop=stop_after_attempt(3), - wait=wait_exponential(multiplier=1, max=10) -) -def _make_request(method, url, **kwargs): - """Make HTTP request with retry.""" - response = requests.request(method, url, **kwargs) - response.raise_for_status() - return response - -def save(vcon_uuid, opts=default_options): - """Save vCon via API.""" - options = {**default_options, **opts} - - vcon_redis = VconRedis() - vcon = vcon_redis.get_vcon(vcon_uuid) - - _make_request( - "POST", - f"{options['base_url']}/vcons", - headers={ - "Authorization": f"Bearer {options['api_key']}", - "Content-Type": "application/json" - }, - json=vcon.to_dict(), - timeout=options["timeout"] - ) - - logger.info(f"Saved {vcon_uuid} via API") - -def get(vcon_uuid, opts=default_options): - """Retrieve vCon via API.""" - options = {**default_options, **opts} - - try: - response = _make_request( - "GET", - f"{options['base_url']}/vcons/{vcon_uuid}", - headers={"Authorization": f"Bearer {options['api_key']}"}, - timeout=options["timeout"] - ) - return response.json() - except requests.HTTPError as e: - if e.response.status_code == 404: - return None - raise - -def delete(vcon_uuid, opts=default_options): - """Delete vCon via API.""" - options = {**default_options, **opts} - - try: - _make_request( - "DELETE", - f"{options['base_url']}/vcons/{vcon_uuid}", - headers={"Authorization": f"Bearer {options['api_key']}"}, - timeout=options["timeout"] - ) - return True - except requests.HTTPError as e: - if e.response.status_code == 404: - return False - raise -``` - -### Cloud Storage (S3-Compatible) - -```python -# server/storage/cloud_storage/__init__.py - -import boto3 -import json -from botocore.exceptions import ClientError -from lib.logging_utils import init_logger -from server.lib.vcon_redis import VconRedis - -logger = init_logger(__name__) - -default_options = { - "bucket": "vcons", - "prefix": "", - "region": "us-east-1", - "access_key": "", - "secret_key": "", - "endpoint_url": None # For S3-compatible services -} -def _get_client(opts): - """Get S3 client.""" - return boto3.client( - 's3', - region_name=opts["region"], - aws_access_key_id=opts["access_key"], - aws_secret_access_key=opts["secret_key"], - endpoint_url=opts.get("endpoint_url") +@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, max=10), reraise=True) +def _post(url, api_key, payload, timeout): + response = requests.post( + url, + headers={"Authorization": f"Bearer {api_key}"}, + json=payload, + timeout=timeout, ) + response.raise_for_status() -def _get_key(vcon_uuid, opts): - """Get S3 key for vCon.""" - prefix = opts.get("prefix", "") - if prefix and not prefix.endswith("/"): - prefix += "/" - return f"{prefix}{vcon_uuid}.json" def save(vcon_uuid, opts=default_options): - """Save vCon to S3.""" - options = {**default_options, **opts} - - vcon_redis = VconRedis() - vcon = vcon_redis.get_vcon(vcon_uuid) - - client = _get_client(options) - key = _get_key(vcon_uuid, options) - - client.put_object( - Bucket=options["bucket"], - Key=key, - Body=json.dumps(vcon.to_dict()), - ContentType="application/json" - ) - - logger.info(f"Saved {vcon_uuid} to s3://{options['bucket']}/{key}") + options = {**default_options, **(opts or {})} -def get(vcon_uuid, opts=default_options): - """Retrieve vCon from S3.""" - options = {**default_options, **opts} - - client = _get_client(options) - key = _get_key(vcon_uuid, options) - - try: - response = client.get_object( - Bucket=options["bucket"], - Key=key - ) - return json.loads(response['Body'].read()) - except ClientError as e: - if e.response['Error']['Code'] == 'NoSuchKey': - return None - raise + vcon = VconRedis().get_vcon(vcon_uuid) + if vcon is None: + raise ValueError(f"vCon not found: {vcon_uuid}") -def delete(vcon_uuid, opts=default_options): - """Delete vCon from S3.""" - options = {**default_options, **opts} - - client = _get_client(options) - key = _get_key(vcon_uuid, options) - - try: - client.delete_object( - Bucket=options["bucket"], - Key=key - ) - return True - except ClientError: - return False + _post(f"{options['base_url']}/vcons", options["api_key"], vcon.to_dict(), options["timeout"]) ``` -## Error Handling +The bundled [webhook adapter](../reference/storage-adapters/webhook.md) already posts vCons to a URL. For S3-compatible object stores, see [`storage.s3`](../reference/storage-adapters/s3.md), which takes an `endpoint_url`. -### Connection Errors +### Share a connection -```python -def save(vcon_uuid, opts=default_options): - options = {**default_options, **opts} - - try: - # Attempt to save - _save_to_backend(vcon_uuid, options) - except ConnectionError as e: - logger.error(f"Connection failed: {e}") - raise # Will cause retry or DLQ - except TimeoutError as e: - logger.error(f"Timeout: {e}") - raise -``` - -### Partial Failures - -When using multiple storages with parallel writes, handle individual failures: +With parallel storage on, `save` runs in a thread pool, and `get` can run in the API at the same time. A client kept at module level must be safe across threads. Create it once and reuse it: ```python -def save(vcon_uuid, opts=default_options): - options = {**default_options, **opts} - - try: - _save_to_backend(vcon_uuid, options) - except Exception as e: - # Log but don't raise - other storages can continue - logger.error(f"Storage failed for {vcon_uuid}: {e}") - # Optionally: record failure for later retry - _record_failure(vcon_uuid, str(e)) -``` +import threading -## Testing Storage Adapters +_client = None +_client_lock = threading.Lock() -### Unit Tests -```python -# server/storage/my_storage/tests/test_my_storage.py - -import pytest -from unittest.mock import MagicMock, patch, mock_open -import json - -class TestMyStorage: - def test_save_creates_file(self): - """Test save creates file with correct content.""" - mock_vcon = MagicMock() - mock_vcon.to_dict.return_value = {"uuid": "test-123"} - - with patch('server.storage.my_storage.VconRedis') as mock_redis_class: - mock_redis = MagicMock() - mock_redis.get_vcon.return_value = mock_vcon - mock_redis_class.return_value = mock_redis - - with patch('builtins.open', mock_open()) as mock_file: - with patch('os.makedirs'): - from server.storage.my_storage import save - save("test-123", {"path": "/tmp/test"}) - - # Verify file was written - mock_file.assert_called_once() - handle = mock_file() - written_data = ''.join( - call.args[0] for call in handle.write.call_args_list - ) - assert "test-123" in written_data - - def test_get_returns_none_for_missing_file(self): - """Test get returns None when file doesn't exist.""" - with patch('os.path.exists', return_value=False): - from server.storage.my_storage import get - result = get("nonexistent", {"path": "/tmp/test"}) - assert result is None - - def test_delete_removes_file(self): - """Test delete removes existing file.""" - with patch('os.path.exists', return_value=True): - with patch('os.remove') as mock_remove: - from server.storage.my_storage import delete - result = delete("test-123", {"path": "/tmp/test"}) - - assert result is True - mock_remove.assert_called_once() -``` - -### Integration Tests - -```python -@pytest.mark.integration -class TestMyStorageIntegration: - def test_save_and_get(self, temp_directory): - """Test full save and get cycle.""" - from server.storage.my_storage import save, get - - # Setup test vCon in Redis - # ... (requires running Redis) - - opts = {"path": temp_directory} - - # Save - save("test-uuid", opts) - - # Verify file exists - import os - assert os.path.exists(f"{temp_directory}/test-uuid.json") - - # Get - result = get("test-uuid", opts) - assert result is not None - assert result["uuid"] == "test-uuid" +def _get_client(options): + global _client + with _client_lock: + if _client is None: + _client = make_client(options) + return _client ``` -## Best Practices +A client created before a worker forks is shared with that worker, so create it inside the function, as above. -### 1. Use Connection Pooling +## Test the adapter ```python -from contextlib import contextmanager -from some_db import ConnectionPool - -_pool = None +# common/storage/my_storage/test_my_storage.py -def _get_pool(opts): - global _pool - if _pool is None: - _pool = ConnectionPool( - host=opts["host"], - max_connections=10 - ) - return _pool +from unittest.mock import patch -@contextmanager -def get_connection(opts): - pool = _get_pool(opts) - conn = pool.get() - try: - yield conn - finally: - pool.release(conn) -``` +import pytest +from vcon import Vcon -### 2. Implement Idempotent Saves +from storage.my_storage import delete, get, save -```python -def save(vcon_uuid, opts=default_options): - # Use upsert pattern - # If vCon exists, update it - # If not, insert it -``` -### 3. Handle Large vCons +@patch("storage.my_storage.VconRedis") +def test_save_and_get_round_trip(mock_vcon_redis, tmp_path): + vcon = Vcon.build_new() + mock_vcon_redis.return_value.get_vcon.return_value = vcon + opts = {"path": str(tmp_path)} -```python -def save(vcon_uuid, opts=default_options): - vcon = VconRedis().get_vcon(vcon_uuid) - - # Check size - data = vcon.dumps() - if len(data) > opts.get("max_size", 10_000_000): - logger.warning(f"vCon {vcon_uuid} exceeds max size") - # Handle: compress, split, or reject -``` + save(vcon.uuid, opts) -### 4. Add Metadata + assert get(vcon.uuid, opts)["uuid"] == vcon.uuid -```python -def save(vcon_uuid, opts=default_options): - vcon = VconRedis().get_vcon(vcon_uuid) - - metadata = { - "uuid": vcon_uuid, - "created_at": vcon.created_at, - "stored_at": datetime.utcnow().isoformat(), - "storage_version": "1.0" - } - - # Store with metadata -``` -### 5. Document Your Storage +@patch("storage.my_storage.VconRedis") +def test_save_raises_when_vcon_missing(mock_vcon_redis, tmp_path): + mock_vcon_redis.return_value.get_vcon.return_value = None -```markdown -# My Storage Adapter + with pytest.raises(ValueError): + save("missing-uuid", {"path": str(tmp_path)}) -Stores vCons in a custom backend. -## Options +def test_get_returns_none_for_missing_file(tmp_path): + assert get("missing-uuid", {"path": str(tmp_path)}) is None -| Option | Type | Default | Description | -|--------|------|---------|-------------| -| path | string | /data/vcons | Storage path | -## Setup +def test_delete_returns_false_for_missing_file(tmp_path): + assert delete("missing-uuid", {"path": str(tmp_path)}) is False +``` -1. Create directory: `mkdir -p /data/vcons` -2. Set permissions: `chmod 755 /data/vcons` +Run them with `uv run pytest common/storage/my_storage`. -## Example +## Follow these practices - storages: - my_storage: - module: storage.my_storage - options: - path: /data/custom -``` +- Raise on failure, so that the storage dead letter queue can do its job. +- Make `save` safe to repeat. +- Store the whole vCon, attachments included. Do not drop entries you do not recognise. +- Keep credentials out of logs, and out of your `default_options` values. +- Add a README with the options, and a page under `docs/reference/storage-adapters/`. diff --git a/docs/extending/creating-tracers.md b/docs/extending/creating-tracers.md index 090d7746..6c2f7532 100644 --- a/docs/extending/creating-tracers.md +++ b/docs/extending/creating-tracers.md @@ -1,458 +1,219 @@ -# Creating Tracers +# Create a tracer -Tracers provide audit trails and event logging for vCon processing. This guide covers creating custom tracers. +A tracer reports each step of a chain to somewhere else, such as a log or an audit service. This page shows how to write one. The [JLINC tracer](../reference/tracers/jlinc.md) is the one that ships with the server. -## Tracer Interface +## Implement the interface -Tracers are called at key points during vCon processing: +A tracer is a module with a `run` function. It has no event names: the server calls it at two kinds of point, and `link_index` tells you which. ```python -def trace(vcon_uuid: str, event: str, opts: dict = default_options) -> None: - """ - Record a trace event. - - Args: - vcon_uuid: UUID of the vCon being processed - event: Event type (e.g., "chain_start", "chain_complete", "error") - opts: Configuration options - """ +def run( + in_vcon_uuid: str, + out_vcon_uuid: str, + tracer_name: str, + links: list[str], + link_index: int, + opts: dict = default_options, +) -> None: + ... ``` -## Events +| Argument | Value | +|---|---| +| `in_vcon_uuid` | Before the first link, the vCon id. After a link, the id the link returned, or the current id if the link halted | +| `out_vcon_uuid` | The vCon id the chain held when the link ran | +| `tracer_name` | The name of this entry in `config.yml` | +| `links` | The chain's link names | +| `link_index` | `-1` before the first link. After that, the index in `links` of the link that just finished | +| `opts` | The entry's `options`. `None` when the entry has no `options` key | -Tracers receive these events: +The two ids differ only when a link swaps the vCon for another. -| Event | Description | -|-------|-------------| -| `chain_start` | vCon entered a processing chain | -| `link_start` | Processing link started | -| `link_complete` | Processing link completed | -| `link_error` | Processing link failed | -| `storage_start` | Storage operation started | -| `storage_complete` | Storage operation completed | -| `storage_error` | Storage operation failed | -| `chain_complete` | Chain processing completed | -| `chain_error` | Chain processing failed | +## Learn the tracer schedule -## Directory Structure +- Every tracer under the top-level `tracers` key runs for every chain. A `tracers` key inside a chain is not read. +- Each runs once before the first link, then once after each link that returns, including one that halts. +- A tracer does not run after a link that raises. +- A chain with no links runs no tracers. Tracers do not run around storage or egress. +- The return value is ignored. + +Tracers run inline, so the chain waits for them. See [the link contract](creating-links.md#follow-the-link-contract) for the full sequence. + +## Lay out the module ``` -server/tracers/ - my_tracer/ - __init__.py # Required: contains trace() - README.md # Optional: documentation - tests/ - __init__.py - test_my_tracer.py +conserver/tracers/my_tracer/ + __init__.py # run() and default_options + README.md + test_my_tracer.py # Tests sit beside the code ``` -## Basic Tracer Example +## Write a basic tracer ```python -# server/tracers/my_tracer/__init__.py +# conserver/tracers/my_tracer/__init__.py import json -from datetime import datetime +from datetime import UTC, datetime + from lib.logging_utils import init_logger logger = init_logger(__name__) default_options = { - "log_file": "/var/log/vcon/audit.log", - "include_vcon_data": False + "log_file": "/var/log/vcon/trace.log", } -def trace(vcon_uuid, event, opts=default_options): - """Log trace event to file.""" - options = {**default_options, **opts} - + +def run(in_vcon_uuid, out_vcon_uuid, tracer_name, links, link_index, opts=default_options): + options = {**default_options, **(opts or {})} + record = { - "timestamp": datetime.utcnow().isoformat(), - "vcon_uuid": vcon_uuid, - "event": event + "timestamp": datetime.now(UTC).isoformat(), + "tracer": tracer_name, + "in_vcon_uuid": in_vcon_uuid, + "out_vcon_uuid": out_vcon_uuid, + "link": links[link_index] if link_index >= 0 else None, + "link_index": link_index, } - - if options.get("include_vcon_data"): - from server.lib.vcon_redis import VconRedis - vcon = VconRedis().get_vcon(vcon_uuid) - if vcon: - record["vcon_summary"] = { - "parties": len(vcon.parties), - "dialog_count": len(vcon.dialog) - } - + with open(options["log_file"], "a") as f: f.write(json.dumps(record) + "\n") - - logger.debug(f"Traced {event} for {vcon_uuid}") ``` -## Configuration - -Register the tracer in `config.yml`: +## Register the tracer ```yaml tracers: my_tracer: module: tracers.my_tracer options: - log_file: /var/log/vcon/audit.log - include_vcon_data: true - -chains: - audited_chain: - links: - - transcribe - storages: - - postgres - tracers: - - my_tracer - ingress_lists: - - default - enabled: 1 + log_file: /var/log/vcon/trace.log ``` -## Common Patterns +Always write `options`, even as `options: {}`. The error handler in `conserver/main.py` reads it, so a failing tracer with no options raises a second error that stops the chain. -### Database Audit Trail +`pip_name` works here as it does for links. See [Dynamic modules](dynamic-modules.md). -```python -# server/tracers/db_audit/__init__.py +## Handle a tracer failure -import psycopg2 -from datetime import datetime -from lib.logging_utils import init_logger +The server catches an exception from a tracer and logs it, and the chain continues. If the tracer's options set `dlq_vcon_on_error: true`, the exception stops the chain and the vCon moves to the dead letter queue. A failing tracer with no `options` key also stops the chain and sends the vCon to the DLQ, so always set `options`, even as `options: {}`. -logger = init_logger(__name__) +So raise when something goes wrong and let the operator choose with that option. A tracer needs no `try` block of its own for this. -default_options = { - "host": "localhost", - "database": "audit", - "user": "audit", - "password": "", - "table": "vcon_events" -} +## Apply these patterns -def trace(vcon_uuid, event, opts=default_options): - """Record event to audit database.""" - options = {**default_options, **opts} - - conn = psycopg2.connect( - host=options["host"], - database=options["database"], - user=options["user"], - password=options["password"] - ) - - try: - with conn.cursor() as cur: - cur.execute( - f""" - INSERT INTO {options['table']} - (vcon_uuid, event, timestamp, metadata) - VALUES (%s, %s, %s, %s) - """, - ( - vcon_uuid, - event, - datetime.utcnow(), - json.dumps({"source": "vcon-server"}) - ) - ) - conn.commit() - finally: - conn.close() - - logger.debug(f"Recorded {event} for {vcon_uuid}") -``` +### Send events to an HTTP service -### External Audit Service +Always set a timeout, because the chain waits for the call. ```python -# server/tracers/external_audit/__init__.py +from datetime import UTC, datetime import requests -from datetime import datetime -from lib.logging_utils import init_logger - -logger = init_logger(__name__) default_options = { "api_url": "https://audit.example.com/events", "api_key": "", - "system_id": "vcon-server" + "system_id": "vcon-server", + "timeout": 5, } -def trace(vcon_uuid, event, opts=default_options): - """Send event to external audit service.""" - options = {**default_options, **opts} - - payload = { - "system_id": options["system_id"], - "entity_id": vcon_uuid, - "entity_type": "vcon", - "event_type": event, - "timestamp": datetime.utcnow().isoformat(), - } - - try: - response = requests.post( - options["api_url"], - headers={ - "Authorization": f"Bearer {options['api_key']}", - "Content-Type": "application/json" - }, - json=payload, - timeout=5 - ) - response.raise_for_status() - except requests.RequestException as e: - logger.error(f"Failed to send audit event: {e}") - if options.get("dlq_vcon_on_error", False): - raise -``` -### Compliance Tracer +def run(in_vcon_uuid, out_vcon_uuid, tracer_name, links, link_index, opts=default_options): + options = {**default_options, **(opts or {})} -```python -# server/tracers/compliance/__init__.py - -import hashlib -import json -from datetime import datetime -from lib.logging_utils import init_logger -from server.lib.vcon_redis import VconRedis - -logger = init_logger(__name__) - -default_options = { - "hash_algorithm": "sha256", - "include_content_hash": True, - "retention_policy": "7_years" -} - -def trace(vcon_uuid, event, opts=default_options): - """Create compliance-grade audit record.""" - options = {**default_options, **opts} - - record = { - "record_id": f"{vcon_uuid}_{event}_{datetime.utcnow().timestamp()}", - "vcon_uuid": vcon_uuid, - "event": event, - "timestamp": datetime.utcnow().isoformat(), - "retention_policy": options["retention_policy"] - } - - # Add content hash for integrity verification - if options.get("include_content_hash") and event in ["chain_complete", "storage_complete"]: - vcon = VconRedis().get_vcon(vcon_uuid) - if vcon: - content = vcon.dumps() - hash_algo = hashlib.new(options["hash_algorithm"]) - hash_algo.update(content.encode()) - record["content_hash"] = hash_algo.hexdigest() - record["hash_algorithm"] = options["hash_algorithm"] - - # Store record (implement based on your compliance requirements) - _store_compliance_record(record, options) - -def _store_compliance_record(record, options): - """Store compliance record - implement based on requirements.""" - # Could be: immutable storage, blockchain, WORM storage, etc. - logger.info(f"Compliance record: {json.dumps(record)}") + response = requests.post( + options["api_url"], + headers={"Authorization": f"Bearer {options['api_key']}"}, + json={ + "system_id": options["system_id"], + "entity_id": out_vcon_uuid, + "step": links[link_index] if link_index >= 0 else "start", + "timestamp": datetime.now(UTC).isoformat(), + }, + timeout=options["timeout"], + ) + response.raise_for_status() ``` -### Metrics Tracer +### Record a content hash + +A tracer can read the vCon. Use `out_vcon_uuid`, as the JLINC tracer does, and allow for a missing vCon. ```python -# server/tracers/metrics/__init__.py +import hashlib -import time -from lib.logging_utils import init_logger +from lib.vcon_redis import VconRedis -logger = init_logger(__name__) -# Track timing -_start_times = {} +def run(in_vcon_uuid, out_vcon_uuid, tracer_name, links, link_index, opts=default_options): + vcon = VconRedis().get_vcon(out_vcon_uuid) + if vcon is None: + return -default_options = { - "statsd_host": "localhost", - "statsd_port": 8125, - "prefix": "vcon" -} - -def trace(vcon_uuid, event, opts=default_options): - """Record metrics to StatsD.""" - options = {**default_options, **opts} - - import statsd - client = statsd.StatsClient( - options["statsd_host"], - options["statsd_port"], - prefix=options["prefix"] - ) - - # Count events - client.incr(f"events.{event}") - - # Track timing for paired events - if event.endswith("_start"): - _start_times[vcon_uuid] = time.time() - elif event.endswith("_complete") or event.endswith("_error"): - start_time = _start_times.pop(vcon_uuid, None) - if start_time: - duration_ms = (time.time() - start_time) * 1000 - base_event = event.rsplit("_", 1)[0] - client.timing(f"duration.{base_event}", duration_ms) - - # Track errors - if event.endswith("_error"): - client.incr("errors.total") + digest = hashlib.sha256(vcon.dumps().encode()).hexdigest() + logger.info("vCon %s at step %s has hash %s", out_vcon_uuid, link_index, digest) ``` -## Error Handling +`Vcon.hash` gives the same value. -### Fail-Safe Tracing +### Hand work to a background thread -```python -def trace(vcon_uuid, event, opts=default_options): - """Trace with fail-safe behavior.""" - options = {**default_options, **opts} - - try: - _send_trace(vcon_uuid, event, options) - except Exception as e: - logger.error(f"Tracing failed: {e}") - - # Optionally send to DLQ - if options.get("dlq_vcon_on_error", False): - raise - - # Otherwise, log and continue - # Processing continues even if tracing fails -``` - -### Async Tracing +To keep a slow call out of the chain, submit it to a pool. A failure then never reaches the server, so `dlq_vcon_on_error` has no effect. ```python -import asyncio from concurrent.futures import ThreadPoolExecutor _executor = ThreadPoolExecutor(max_workers=5) -def trace(vcon_uuid, event, opts=default_options): - """Non-blocking trace.""" - # Submit to thread pool, don't wait - _executor.submit(_do_trace, vcon_uuid, event, opts) -def _do_trace(vcon_uuid, event, opts): - """Actual tracing logic.""" +def run(in_vcon_uuid, out_vcon_uuid, tracer_name, links, link_index, opts=default_options): + _executor.submit(_send, out_vcon_uuid, link_index, opts) + + +def _send(vcon_uuid, link_index, opts): try: - # ... tracing implementation ... - pass - except Exception as e: - logger.error(f"Async trace failed: {e}") + ... + except Exception: + logger.exception("Trace failed for %s", vcon_uuid) ``` -## Testing Tracers +For timing and counts, you may not need a tracer. The server already emits [metrics](../reference/metrics.md) and OpenTelemetry spans for each link and storage write. -### Unit Tests +## Test the tracer ```python -# server/tracers/my_tracer/tests/test_my_tracer.py +# conserver/tracers/my_tracer/test_my_tracer.py -import pytest -from unittest.mock import patch, mock_open import json -class TestMyTracer: - def test_trace_writes_to_file(self): - """Test trace writes correct format.""" - with patch('builtins.open', mock_open()) as mock_file: - from server.tracers.my_tracer import trace - trace("test-uuid", "chain_start", {"log_file": "/tmp/test.log"}) - - # Verify write was called - mock_file.assert_called_with("/tmp/test.log", "a") - - # Verify content - handle = mock_file() - written = handle.write.call_args[0][0] - record = json.loads(written.strip()) - - assert record["vcon_uuid"] == "test-uuid" - assert record["event"] == "chain_start" - assert "timestamp" in record - - def test_trace_handles_errors(self): - """Test trace handles write errors gracefully.""" - with patch('builtins.open', side_effect=IOError("Write failed")): - from server.tracers.my_tracer import trace - - # Should not raise - trace("test-uuid", "chain_start", {"log_file": "/invalid/path"}) -``` - -## Best Practices +from tracers.my_tracer import run -### 1. Keep Tracing Fast -```python -def trace(vcon_uuid, event, opts=default_options): - # Avoid heavy processing in trace - # Use async/background processing for heavy operations -``` +def test_run_records_the_step(tmp_path): + log_file = tmp_path / "trace.log" -### 2. Handle Failures Gracefully + run("id-1", "id-1", "my_tracer", ["first", "second"], 1, {"log_file": str(log_file)}) -```python -def trace(vcon_uuid, event, opts=default_options): - try: - _trace_impl(vcon_uuid, event, opts) - except Exception as e: - logger.error(f"Trace failed: {e}") - # Don't let tracing failures break processing -``` + record = json.loads(log_file.read_text()) + assert record["link"] == "second" + assert record["link_index"] == 1 -### 3. Use Structured Data -```python -record = { - "timestamp": datetime.utcnow().isoformat(), - "vcon_uuid": vcon_uuid, - "event": event, - "metadata": { - "chain": chain_name, - "link": link_name - } -} -``` +def test_run_handles_the_start_of_a_chain(tmp_path): + log_file = tmp_path / "trace.log" -### 4. Consider Retention + run("id-1", "id-1", "my_tracer", ["first"], -1, {"log_file": str(log_file)}) -```python -default_options = { - "retention_days": 90, - "archive_after_days": 30 -} + assert json.loads(log_file.read_text())["link"] is None ``` -### 5. Document Requirements - -```markdown -# My Tracer +Run them with `uv run pytest conserver/tracers/my_tracer`. -Records audit events to external system. +## Follow these practices -## Requirements - -- Network access to audit service -- API key with write permissions - -## Options - -| Option | Type | Default | Description | -|--------|------|---------|-------------| -| api_url | string | Required | Audit service URL | -| api_key | string | Required | Authentication key | -``` +- Keep `run` fast, since it runs on every link of every chain. +- Handle `link_index` of `-1` before you index into `links`. +- Keep vCon content and credentials out of trace records unless the destination is meant to hold them. +- Add a README with the options, and a page under `docs/reference/tracers/`. diff --git a/docs/extending/dynamic-modules.md b/docs/extending/dynamic-modules.md index 24295770..b1084575 100644 --- a/docs/extending/dynamic-modules.md +++ b/docs/extending/dynamic-modules.md @@ -1,117 +1,91 @@ -# Dynamic Modules +# Load dynamic modules -vCon Server can dynamically install and load modules from PyPI or GitHub at runtime. +The conserver can import a link or tracer from outside the repo, and install it with `pip` if it is missing. This page shows how to configure that and when to avoid it. -## Overview +## Add a module to the configuration -Dynamic modules allow you to: - -- Use external processing links without modifying the codebase -- Share custom modules across deployments -- Install dependencies automatically - -## Configuration - -### From PyPI +Give a link or tracer a `module` to import and a `pip_name` to install. ```yaml links: - custom_link: + pypi_link: module: custom_link_package.main - pip_name: custom-link-package + pip_name: custom-link-package==1.2.3 options: - api_key: your-key -``` - -### From GitHub + setting: value -```yaml -links: - github_link: - module: github_link.processor - pip_name: git+https://github.com/username/repo.git + git_link: + module: git_link.processor + pip_name: git+https://github.com/username/repo.git@v1.2.3 options: setting: value ``` -### From GitHub Branch/Tag +`pip_name` defaults to `module`. It accepts any single requirement that `pip install` accepts, including a branch or tag after `@`. + +Use the `imports` section to load a module when each worker starts, rather than when a vCon first reaches it: ```yaml -links: - dev_link: - module: dev_link.main - pip_name: git+https://github.com/username/repo.git@develop - - versioned_link: - module: versioned_link.main - pip_name: git+https://github.com/username/repo.git@v1.2.3 +imports: + custom_utility: + module: custom_utils + pip_name: custom-utils-package + requests_import: + module: requests + legacy_module: some.legacy.module # Older form: the module name alone ``` -### From Private GitHub +See [YAML configuration](../configuration/yaml-configuration.md#import-extra-modules) for the section itself. -```yaml -links: - private_link: - module: private_link.main - pip_name: git+https://${GITHUB_TOKEN}@github.com/org/private-repo.git -``` +Storage adapters do not use this. The server imports them by name and ignores `pip_name`, so their packages must already be installed. -## Import Configuration +## Learn the loading rules -Use the `imports` section to pre-load modules: +1. The conserver tries to import `module`. +2. If that raises `ModuleNotFoundError`, it runs `python -m pip install ` and imports again. +3. It keeps the module for the life of the process. -```yaml -imports: - # Simple import - requests_lib: - module: requests - - # PyPI package - custom_utils: - module: custom_utils - pip_name: custom-utils-package - - # GitHub repository - shared_lib: - module: shared_library - pip_name: git+https://github.com/org/shared-lib.git -``` +Each worker process does this for itself. + +| Fact | Effect | +|---|---| +| `pip` runs only when the import fails | Changing a pinned version does not upgrade a module that is already installed | +| The install lands in the running environment | A new container starts without it and installs it again | +| A failure in `imports` raises | The worker stops at startup | +| A failure for a link raises when a vCon reaches it | That vCon moves to the dead letter queue | +| `pip_name` is passed as one argument, with no shell | `${VAR}` is not expanded, and extra flags such as `--index-url` do not work | + +`pip` must exist in the environment. The published images include it. For a manual install, create the environment with `uv venv --seed`, as in [Install from source](../installation/manual-installation.md#install-the-dependencies). + +## Bake modules into an image -## How It Works +For production, install modules at build time. A deployment then needs no network access to a package index at runtime, and every worker has the same version. -```mermaid -flowchart TB - CONFIG[Load Configuration] --> CHECK{Module
Installed?} - CHECK -->|Yes| IMPORT[Import Module] - CHECK -->|No| INSTALL[pip install] - INSTALL --> IMPORT - IMPORT --> CACHE[Cache Module] - CACHE --> USE[Use Module] +```dockerfile +FROM public.ecr.aws/r4g1k2s3/vcon-dev/vcon-server-conserver: +RUN pip install custom-link-package==1.2.3 ``` -1. Server reads configuration -2. For each module with `pip_name`: - - Check if module is already installed - - If not, run `pip install {pip_name}` -3. Import the module -4. Cache for subsequent use +Keep `module` in the configuration and leave out `pip_name`. -## Creating Distributable Modules +## Reach a private package -### Package Structure +The server does not expand environment variables in `config.yml` or in `pip_name`. Give `pip` its credentials through its own channels: + +- For a private index, set `PIP_INDEX_URL` in the conserver's environment. +- For a private Git repo, use `git+ssh://git@github.com/org/repo.git` with a key in the container, or a Git credential helper. +- A token written into `pip_name` works, but it sits in plain text in `config.yml` and comes back from `GET /config`. + +## Package a module ``` my-vcon-link/ - setup.py pyproject.toml + README.md my_link/ __init__.py - processor.py - README.md ``` -### pyproject.toml - ```toml [build-system] requires = ["setuptools>=61.0"] @@ -123,251 +97,73 @@ version = "1.0.0" description = "Custom vCon processing link" requires-python = ">=3.12" dependencies = [ - "requests>=2.28.0", -] - -[project.optional-dependencies] -dev = [ - "pytest>=7.0.0", + "requests>=2.31.0", ] ``` -### Module Implementation +The module follows the [link contract](creating-links.md#follow-the-link-contract). It imports server code such as `lib.vcon_redis` from the running server, so do not list those as dependencies. Tests outside the repo need the server's `common/` on the path, or a stub. ```python # my_link/__init__.py from lib.logging_utils import init_logger -from server.lib.vcon_redis import VconRedis +from lib.vcon_redis import VconRedis logger = init_logger(__name__) default_options = { - "setting": "default" + "setting": "default", } + def run(vcon_uuid, link_name, opts=default_options): - """Process vCon.""" - options = {**default_options, **opts} - + options = {**default_options, **(opts or {})} + vcon_redis = VconRedis() vcon = vcon_redis.get_vcon(vcon_uuid) - + if vcon is None: + return None + # Your processing logic - + vcon_redis.store_vcon(vcon) return vcon_uuid ``` -### Publishing to PyPI - -```bash -# Build -python -m build - -# Upload to PyPI -python -m twine upload dist/* - -# Or upload to private PyPI -python -m twine upload --repository-url https://pypi.example.com dist/* -``` - -### Publishing to GitHub - -```bash -# Tag release -git tag v1.0.0 -git push origin v1.0.0 -``` - -## Environment Variables in pip_name - -Use environment variables for secrets: - -```yaml -links: - private_link: - module: private_link - pip_name: git+https://${GITHUB_TOKEN}@github.com/org/repo.git -``` - -Set the environment variable: +Publish the package the way your project publishes everything else, ideally from CI on a tag push, and state which server image you tested against. -```bash -export GITHUB_TOKEN=ghp_xxxxxxxxxxxx -``` +## Keep third-party code safe -## Version Pinning - -Pin versions for reproducibility: - -```yaml -# PyPI with version -links: - stable_link: - module: stable_link - pip_name: stable-link-package==1.2.3 - -# GitHub with tag -links: - tagged_link: - module: tagged_link - pip_name: git+https://github.com/org/repo.git@v1.2.3 -``` +Dynamic modules run with the same access as the conserver. That covers Redis, every vCon and all credentials in `config.yml`. -## Troubleshooting +- Pin every `pip_name` to a version or tag. +- Read the code of a module before you add it, and scan its dependencies in your own CI. +- Install from sources you trust, and prefer [an image you built](#bake-modules-into-an-image). +- Protect global API keys. `POST /config` rewrites the configuration, and a worker that rereads it can then install what a new `pip_name` names. -### Module Not Found +## Handle a missing dependency -**Check pip installation:** - -```bash -docker compose exec conserver pip list | grep my-package -``` - -**Manual install:** - -```bash -docker compose exec conserver pip install my-package -``` - -### Import Errors - -**Check module path:** - -```python -# Verify module can be imported -docker compose exec conserver python -c "import my_module; print(my_module)" -``` - -**Check dependencies:** - -```bash -docker compose exec conserver pip check -``` - -### GitHub Authentication - -**For private repos:** - -```bash -# Use personal access token -pip_name: git+https://TOKEN@github.com/org/repo.git - -# Or use SSH (requires key setup) -pip_name: git+ssh://git@github.com/org/repo.git -``` - -### Version Conflicts - -**Check for conflicts:** - -```bash -docker compose exec conserver pip check -``` - -**Force reinstall:** - -```bash -docker compose exec conserver pip install --force-reinstall my-package -``` - -## Best Practices - -### 1. Pin Versions in Production - -```yaml -# Good: Pinned version -pip_name: my-package==1.2.3 - -# Avoid: Unpinned (may break) -pip_name: my-package -``` - -### 2. Use Trusted Sources - -```yaml -# Good: Official PyPI -pip_name: official-package - -# Good: Verified GitHub -pip_name: git+https://github.com/trusted-org/repo.git@v1.0.0 - -# Avoid: Unverified sources -pip_name: git+https://github.com/random-user/suspicious-repo.git -``` - -### 3. Test Before Deployment - -```bash -# Test installation -pip install my-package - -# Test import -python -c "from my_package import run; print(run)" - -# Test functionality -pytest tests/ -``` - -### 4. Document Dependencies - -Include in your module's README: - -```markdown -## Requirements - -- Python 3.12+ -- vCon Server 1.1+ - -## Dependencies - -- requests >= 2.28.0 -- pydantic >= 2.0.0 -``` - -### 5. Handle Missing Dependencies +Import optional packages inside `run`, and raise a clear error so the vCon reaches the dead letter queue: ```python def run(vcon_uuid, link_name, opts=default_options): try: import optional_dependency - except ImportError: - logger.error("Optional dependency not installed") - raise ImportError("Please install: pip install optional-dependency") + except ImportError as e: + raise ImportError("Install optional-dependency to use this link") from e ``` -## Security Considerations - -### 1. Verify Package Sources - -Only use packages from trusted sources: - -- Official PyPI packages -- Verified GitHub repositories -- Internal/private repositories +## Troubleshoot a dynamic module -### 2. Review Code +Run these in the conserver container. -Before using external modules: +| Check | Command | +|---|---| +| Is it installed | `pip list \| grep my-package` | +| Does it import | `python -c "import my_module; print(my_module)"` | +| Are there conflicts | `pip check` | +| Reinstall it | `pip install --force-reinstall my-package` | -- Review the source code -- Check for security issues -- Verify maintainer reputation +The conserver log shows `Module not found, attempting to install `, then either success or the `pip` error. -### 3. Use Private PyPI - -For enterprise deployments: - -```yaml -# Configure private PyPI -pip_name: my-package --index-url https://pypi.internal.example.com/simple/ -``` - -### 4. Scan Dependencies - -```bash -# Use safety to scan for vulnerabilities -pip install safety -safety check -``` +`No module named pip` means the environment was created without `--seed`. diff --git a/docs/extending/index.md b/docs/extending/index.md index db636da8..325f25a5 100644 --- a/docs/extending/index.md +++ b/docs/extending/index.md @@ -1,355 +1,125 @@ -# Extending vCon Server - -vCon Server is designed to be extended with custom processing links, storage adapters, and tracers. - -## Extension Points - -```mermaid -flowchart TB - subgraph chain [Processing Chain] - INGRESS[Ingress] --> LINKS - subgraph LINKS[Custom Links] - L1[Your Link] - end - LINKS --> STORAGE - subgraph STORAGE[Custom Storage] - S1[Your Adapter] - end - STORAGE --> TRACERS - subgraph TRACERS[Custom Tracers] - T1[Your Tracer] - end - end -``` - -| Extension Type | Purpose | Interface | -|---------------|---------|-----------| -| [Links](creating-links.md) | Process/transform vCons | `run(vcon_uuid, link_name, opts)` | -| [Storage Adapters](creating-storage-adapters.md) | Persist vCons | `save(vcon_uuid, opts)`, `get(vcon_uuid, opts)` | -| [Tracers](creating-tracers.md) | Audit trails | `trace(vcon_uuid, event, opts)` | - -## Quick Start - -### Create a Custom Link - -```python -# server/links/my_link/__init__.py - -from lib.logging_utils import init_logger -from server.lib.vcon_redis import VconRedis - -logger = init_logger(__name__) - -default_options = { - "my_option": "default_value" -} - -def run(vcon_uuid, link_name, opts=default_options): - """Process a vCon.""" - logger.info(f"Processing {vcon_uuid}") - - # Get vCon from Redis - vcon_redis = VconRedis() - vcon = vcon_redis.get_vcon(vcon_uuid) - - # Your processing logic here - vcon.add_tag("processed_by", "my_link") - - # Save changes - vcon_redis.store_vcon(vcon) - - return vcon_uuid # Return UUID to continue chain -``` - -Register in `config.yml`: - -```yaml -links: - my_link: - module: links.my_link - -chains: - my_chain: - links: - - my_link - storages: - - redis_storage - ingress_lists: - - default - enabled: 1 -``` - -### Create a Custom Storage Adapter - -```python -# server/storage/my_storage/__init__.py +# Extend vCon Server -from lib.logging_utils import init_logger -from server.lib.vcon_redis import VconRedis +You extend the server by writing Python modules and naming them in `config.yml`. There is no base class. A module works if it has the expected functions. -logger = init_logger(__name__) +## Choose an extension point -default_options = { - "connection_string": "localhost:1234" -} +| Extension | Purpose | Interface | Lives in | Guide | +|---|---|---|---|---| +| Link | Change, filter or route a vCon in a chain | `run(vcon_uuid, link_name, opts)` | `conserver/links//` | [Creating links](creating-links.md) | +| Storage adapter | Keep vCons in a backend | `save(vcon_uuid, opts)`, with optional `get` and `delete` | `common/storage//` | [Creating storage adapters](creating-storage-adapters.md) | +| Tracer | Report each chain step elsewhere | `run(in_vcon_uuid, out_vcon_uuid, tracer_name, links, link_index, opts)` | `conserver/tracers//` | [Creating tracers](creating-tracers.md) | +| External package | Ship a link or tracer outside the repo | As above, plus `pip_name` | PyPI or Git | [Dynamic modules](dynamic-modules.md) | -def save(vcon_uuid, opts=default_options): - """Save vCon to storage.""" - vcon_redis = VconRedis() - vcon = vcon_redis.get_vcon(vcon_uuid) - - # Your storage logic here - # e.g., write to database, file, API - - logger.info(f"Saved {vcon_uuid} to my_storage") - -def get(vcon_uuid, opts=default_options): - """Retrieve vCon from storage.""" - # Your retrieval logic here - # Return dict or None if not found - return None - -def delete(vcon_uuid, opts=default_options): - """Delete vCon from storage.""" - # Your deletion logic here - return True -``` +[Chains, links and storage](../concepts/chains-links-storage.md) explains how these fit into a run. -Register in `config.yml`: +## Follow the shared rules -```yaml -storages: - my_storage: - module: storage.my_storage - options: - connection_string: "mydb://localhost:5432" - -chains: - my_chain: - storages: - - my_storage -``` +**Import from the top level.** The development image and `pytest.ini` put `common/`, `conserver/` and `api/` on the path. The published API image leaves out `conserver/`, and the published conserver image leaves out `api/`. Write `from lib.vcon_redis import VconRedis`, not a path through `common`. -## Architecture Principles +**Use the local `Vcon` class.** On that path, `import vcon` loads `common/vcon.py`, not the `vcon` package named in `pyproject.toml`. Every link runs on the local class. -### 1. Duck Typing +**Go through the helpers.** Read and write vCons with `lib.vcon_redis.VconRedis`, and queues with `lib.queue.VconQueue`. Do not import the Redis client. -No base classes required. Implement the expected interface: +**Read options defensively.** A link or tracer with no `options` key receives `None`, not its `default_options`. An `options` block replaces `default_options` and does not merge with it. Merge them yourself: ```python -# Links: run(vcon_uuid, link_name, opts) -> str | None -# Storage: save(vcon_uuid, opts), get(vcon_uuid, opts), delete(vcon_uuid, opts) -# Tracers: trace(vcon_uuid, event, opts) +options = {**default_options, **(opts or {})} ``` -### 2. Configuration-Driven +**Expect concurrency.** `CONSERVER_WORKERS` runs several processes. `CONSERVER_VCON_CONCURRENCY` and parallel storage run your code in several threads in one process. Keep module-level state safe for both. -Extensions are registered via YAML configuration: +**Check the image.** Links and tracers load only in the conserver. Storage adapters load in both the API and the conserver, so a new package for an adapter goes in the `storage` group of `pyproject.toml`, followed by `uv lock`. -```yaml -links: - my_link: - module: links.my_link # Python module path - options: # Passed to run() - key: value -``` - -### 3. Dynamic Loading - -Modules are imported at runtime: +## Build an extension -1. Configuration specifies module path -2. Server imports module on first use -3. Module is cached for subsequent calls +1. Create the folder and its `__init__.py`: -### 4. External Packages + ```bash + mkdir -p conserver/links/my_link + touch conserver/links/my_link/__init__.py + ``` -Install from PyPI or GitHub: - -```yaml -links: - external_link: - module: external_module - pip_name: external-package # Auto-installed - -imports: - custom_utils: - module: custom_utils - pip_name: git+https://github.com/user/repo.git -``` +2. Write the interface from the guide for your extension type. -## Development Workflow +3. Add tests beside the code, for example `conserver/links/my_link/test_my_link.py`, and run them: -### 1. Create Module + ```bash + uv run pytest conserver/links/my_link + ``` -```bash -mkdir -p server/links/my_link -touch server/links/my_link/__init__.py -``` - -### 2. Implement Interface - -```python -# server/links/my_link/__init__.py -default_options = {} - -def run(vcon_uuid, link_name, opts=default_options): - # Implementation - return vcon_uuid -``` - -### 3. Add Tests - -```python -# server/links/my_link/test_my_link.py -import pytest -from server.links.my_link import run +4. Register the module in `config.yml`, with `options` set: -def test_run_returns_uuid(): - result = run("test-uuid", "my_link", {}) - assert result == "test-uuid" -``` - -### 4. Register in Config - -```yaml -links: - my_link: - module: links.my_link -``` - -### 5. Test End-to-End - -```bash -# Start services -docker compose up -d - -# Submit test vCon -curl -X POST "http://localhost:8000/api/vcon?ingress_lists=default" \ - -H "x-conserver-api-token: $TOKEN" \ - -d '{"vcon": "0.0.1", "uuid": "test-123", ...}' - -# Check logs -docker compose logs -f conserver -``` - -## Common Patterns - -### Accessing vCon Data - -```python -from server.lib.vcon_redis import VconRedis - -vcon_redis = VconRedis() -vcon = vcon_redis.get_vcon(vcon_uuid) - -# Access properties -uuid = vcon.uuid -parties = vcon.parties -dialog = vcon.dialog -analysis = vcon.analysis - -# Modify vCon -vcon.add_tag("key", "value") -vcon.add_analysis(analysis_data) - -# Save changes -vcon_redis.store_vcon(vcon) -``` - -### Filtering vCons - -Return `None` to stop processing: - -```python -def run(vcon_uuid, link_name, opts): - vcon = VconRedis().get_vcon(vcon_uuid) - - # Filter based on criteria - if should_filter(vcon): - logger.info(f"Filtering {vcon_uuid}") - return None # Stop chain - - return vcon_uuid # Continue chain -``` - -### Error Handling - -```python -def run(vcon_uuid, link_name, opts): - try: - # Processing logic - return vcon_uuid - except TemporaryError as e: - logger.warning(f"Temporary error: {e}") - return None # Skip, don't DLQ - except Exception as e: - logger.error(f"Error processing {vcon_uuid}: {e}") - raise # Send to DLQ -``` - -### External API Calls - -```python -import requests -from tenacity import retry, stop_after_attempt, wait_exponential - -@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, max=10)) -def call_external_api(data): - response = requests.post("https://api.example.com", json=data) - response.raise_for_status() - return response.json() - -def run(vcon_uuid, link_name, opts): - vcon = VconRedis().get_vcon(vcon_uuid) - result = call_external_api(vcon.to_dict()) - # Process result - return vcon_uuid + ```yaml + links: + my_link: + module: links.my_link + options: {} + + chains: + my_chain: + links: + - my_link + storages: + - file + ingress_lists: + - my_list + ``` + + The `file` backend is the one from the [quick start](../getting-started/quick-start.md#write-the-configuration). See [Register the link](creating-links.md#register-the-link) for why the chain has its own list. + +5. Start the stack and submit a vCon: + + ```bash + docker compose up -d + + curl -X POST "http://localhost:8000/api/vcon?ingress_lists=my_list" \ + -H "x-conserver-api-token: $TOKEN" \ + -H "Content-Type: application/json" \ + -d @vcon.json + + docker compose logs -f conserver + ``` + +Use this sample for `vcon.json`. Change the `uuid` for each run. + +```json +{ + "vcon": "0.4.0", + "uuid": "018f0f2e-6c1a-8e3b-9a6d-2f4d1c7b9e10", + "created_at": "2026-01-15T10:30:00Z", + "parties": [ + {"tel": "+15551230100", "name": "Agent"}, + {"tel": "+15551230101", "name": "Caller"} + ], + "dialog": [ + { + "type": "text", + "start": "2026-01-15T10:30:00Z", + "parties": [0, 1], + "mediatype": "text/plain", + "encoding": "none", + "body": "Hello, I would like to check my order." + } + ] +} ``` -## Testing Extensions +## Replace a lifecycle hook -### Unit Tests +Three modules ship as no-ops. They are not configured in YAML: you replace the file when you build your image. -```python -import pytest -from unittest.mock import MagicMock, patch - -def test_my_link(): - with patch('server.lib.vcon_redis.VconRedis') as mock_redis: - mock_vcon = MagicMock() - mock_redis.return_value.get_vcon.return_value = mock_vcon - - from server.links.my_link import run - result = run("test-uuid", "my_link", {}) - - assert result == "test-uuid" - mock_vcon.add_tag.assert_called() -``` - -### Integration Tests +| File | Functions | Runs | +|---|---|---| +| `conserver/hook.py` | `before_processing`, `after_processing` | Around each chain run. A falsy return from `before_processing` skips the vCon with no dead letter entry | +| `conserver/after_link_hook.py` | `after_link` | After each link, on success or error | +| `api/vcon_hook.py` | `on_vcon_created`, `on_vcon_deleted` | When the REST API creates or deletes a vCon | -```python -@pytest.mark.integration -def test_my_link_integration(): - # Requires running Redis - from server.lib.vcon_redis import VconRedis - from server.links.my_link import run - - # Create test vCon - vcon_redis = VconRedis() - # ... setup test data ... - - result = run("test-uuid", "my_link", {}) - - # Verify results - vcon = vcon_redis.get_vcon("test-uuid") - assert "my_tag" in vcon.tags -``` +The code comments suggest audit logging, metrics and notifications. [Creating links](creating-links.md#follow-the-link-contract) shows where the conserver hooks fall in a run. -## Next Steps +## Continue with these guides -- [Creating Links](creating-links.md) - Detailed link development guide -- [Creating Storage Adapters](creating-storage-adapters.md) - Storage adapter guide -- [Creating Tracers](creating-tracers.md) - Tracer development guide -- [Dynamic Modules](dynamic-modules.md) - External module installation +- [Creating links](creating-links.md) +- [Creating storage adapters](creating-storage-adapters.md) +- [Creating tracers](creating-tracers.md) +- [Dynamic modules](dynamic-modules.md) diff --git a/docs/getting-started/index.md b/docs/getting-started/index.md index 5e634852..c1522aab 100644 --- a/docs/getting-started/index.md +++ b/docs/getting-started/index.md @@ -1,106 +1,52 @@ -# Getting Started +# Getting started -Welcome to vCon Server! This section will help you understand what vCon Server does and get you up and running quickly. +This section takes you from no knowledge of the server to a running stack that has processed its first vCon. -## What is vCon Server? +## Learn what a vCon holds -vCon Server (also called "Conserver") is a processing pipeline for voice conversation data. It receives vCon (Voice Conversation) documents, processes them through configurable chains of operations, and stores them in one or more backends. +A vCon is a JSON container for one conversation, defined in an [IETF draft](https://datatracker.ietf.org/doc/draft-ietf-vcon-vcon-core/). The server works with these parts: -### The vCon Standard +| Part | Contents | +|---|---| +| `parties` | The participants: phone numbers, email addresses, names | +| `dialog` | The conversation itself: recordings, text, or references to them | +| `analysis` | Output from models and services, such as transcripts and summaries | +| `attachments` | Related material, including tags and any `lawful_basis` record | -A vCon is a standardized JSON format for representing voice conversations. It includes: +## Follow a vCon through the server -- **Parties**: Information about participants (phone numbers, emails, names) -- **Dialog**: The conversation content (audio files, transcripts) -- **Analysis**: AI-generated insights (summaries, sentiment, topics) -- **Attachments**: Related documents and files -- **Metadata**: Timestamps, UUIDs, and custom tags +1. Your system posts a vCon to the API, which stores it in Redis and adds its uuid to one or more ingress lists. +2. A worker pops the uuid and finds the chain that reads from that list. +3. The chain runs its links in order. A link can add to the vCon, stop the chain, or send the vCon elsewhere. +4. The worker pushes the uuid to the chain's egress lists and writes the vCon to the chain's storage backends. +5. A vCon that fails goes to a dead letter queue, where you can inspect and replay it. -### What vCon Server Does +![Flow from an ingress list through the links to egress lists and storage, with the dead letter paths](../diagrams/D05-chain-pipeline.svg) -```mermaid -flowchart LR - IN[Incoming vCon] --> INGEST[Ingress Queue] - INGEST --> CHAIN[Processing Chain] - - subgraph CHAIN[Processing Chain] - direction TB - L1[Transcribe] --> L2[Analyze] - L2 --> L3[Tag] - L3 --> L4[Route] - end - - CHAIN --> STORE[Storage Backends] - CHAIN --> OUT[Egress Queue] -``` +[vCon lifecycle](../concepts/vcon-lifecycle.md) gives the full story, and [architecture](../concepts/architecture.md) shows the services. -1. **Receives vCons** via REST API or external integrations -2. **Queues them** in Redis for processing -3. **Processes them** through configurable chains of "links" -4. **Stores them** in one or more storage backends -5. **Routes them** to egress queues for downstream systems +## Learn three terms -## Key Concepts +- A **chain** is one pipeline: ingress lists, links, storage backends and egress lists. See [chains and pipelines](../configuration/chains-and-pipelines.md). +- A **link** is one processing step, such as [transcribe](../reference/links/transcribe.md), [analyze](../reference/links/analyze.md) or [tag](../reference/links/tag.md). See the [link catalogue](../reference/links/index.md). +- A **storage adapter** copies a finished vCon to another system. See the [adapter catalogue](../reference/storage-adapters/index.md). -### Chains +[Chains, links and storage](../concepts/chains-links-storage.md) explains how they fit together. -A **chain** is a complete processing pipeline that defines: +## Match a goal to its building blocks -- **Ingress Lists**: Where vCons enter the chain -- **Links**: Processing steps executed in order -- **Storages**: Where processed vCons are persisted -- **Egress Lists**: Where vCons go after processing +| Goal | Building blocks | +|---|---| +| Analyse customer calls | [transcribe](../reference/links/transcribe.md), [analyze](../reference/links/analyze.md), [detect_engagement](../reference/links/detect-engagement.md), [tag_router](../reference/links/tag-router.md) | +| Keep a searchable archive | [S3](../reference/storage-adapters/s3.md) for the records, [Elasticsearch](../reference/storage-adapters/elasticsearch.md) for search | +| Search by meaning | [Milvus](../reference/storage-adapters/milvus.md) for vector similarity | +| Feed other systems | [webhook](../reference/links/webhook.md), egress lists | +| Record a tamper-evident trail | [scitt](../reference/links/scitt.md), [datatrails](../reference/links/datatrails.md), the [JLINC tracer](../reference/tracers/jlinc.md) | -### Links +The server alone does not make a deployment compliant with any regulation, and it does not manage consent. See [lawful basis](../concepts/lawful-basis.md). -**Links** are modular processors that transform or analyze vCons: +## Take the next step -| Link Type | Examples | -|-----------|----------| -| Transcription | `deepgram_link`, `groq_whisper`, `hugging_face_whisper` | -| Analysis | `analyze`, `analyze_and_label`, `detect_engagement` | -| Tagging | `tag`, `check_and_tag` | -| Routing | `tag_router`, `sampler` | -| Integration | `webhook`, `post_analysis_to_slack` | - -### Storage Adapters - -**Storage adapters** persist vCons to various backends: - -- **Databases**: PostgreSQL, MongoDB, Elasticsearch -- **Object Storage**: S3, local filesystem -- **Vector Databases**: Milvus (for similarity search) -- **Specialized**: SFTP, Dataverse, ChatGPT Files - -## Use Cases - -### Call Center Analytics - -Process customer service calls to: - -- Transcribe audio recordings -- Analyze sentiment and topics -- Detect customer engagement levels -- Route based on call outcome - -### Compliance Recording - -Archive voice communications with: - -- Immutable storage in S3 -- Full-text search in Elasticsearch -- Audit trails via tracers - -### AI-Powered Insights - -Extract value from conversations: - -- Generate summaries and action items -- Classify calls by intent -- Build searchable knowledge bases - -## Next Steps - -1. **[System Requirements](requirements.md)**: Check what you need to run vCon Server -2. **[Quick Start](quick-start.md)**: Get running in 5 minutes with Docker -3. **[Installation Guide](../installation/index.md)**: Detailed installation options +1. [Check the system requirements](requirements.md). +2. [Run the quick start](quick-start.md). +3. [Pick an installation method](../installation/index.md) for a real deployment. diff --git a/docs/getting-started/quick-start.md b/docs/getting-started/quick-start.md index ea45adc1..d1b359b7 100644 --- a/docs/getting-started/quick-start.md +++ b/docs/getting-started/quick-start.md @@ -1,285 +1,235 @@ -# Quick Start +# Quick start -Get vCon Server running in 5 minutes using Docker Compose. +This page takes you from a fresh clone to a processed vCon with Docker Compose. It needs no vendor keys, and the first build takes a few minutes. -## Prerequisites +You need Docker with the Compose plugin and Git. See [system requirements](requirements.md). -- Docker and Docker Compose installed ([verify](requirements.md#verifying-requirements)) -- Git installed -- Terminal access - -## Step 1: Clone the Repository +## Clone the repository ```bash git clone https://github.com/vcon-dev/vcon-server.git cd vcon-server ``` -## Step 2: Configure Environment +The repository ships a ready `docker-compose.yml`, so there is no Compose file to copy. -Copy the example environment file and configure it: +## Set the environment ```bash cp .env.example .env +openssl rand -hex 32 ``` -Edit `.env` with your settings: +Edit `.env` and set these four values. Use the `openssl` output as your token. ```bash -# Required: Redis connection -REDIS_URL=redis://redis:6379 +CONSERVER_API_TOKEN=your-generated-token +CONSERVER_CONFIG_FILE=./config.yml +LOGGING_CONFIG_FILE=common/logging_dev.conf +COMPOSE_PROFILES= +``` + +Each one matters: + +| Variable | Without this change | +|---|---| +| `CONSERVER_API_TOKEN` | A blank token turns API authentication off | +| `CONSERVER_CONFIG_FILE` | `.env.example` leaves it blank. A blank value overrides the built-in default, and the services cannot open a config file | +| `LOGGING_CONFIG_FILE` | `.env.example` names a path that does not exist, and both services stop at startup | +| `COMPOSE_PROFILES` | `.env.example` sets `postgres`, which starts PostgreSQL on host port 5432. This walkthrough does not use it | + +`common/logging_dev.conf` writes plain text, which the samples on this page show. `common/logging.conf` writes JSON for production. -# Required: API authentication token -CONSERVER_API_TOKEN=your-secret-token-here +## Write the configuration -# Optional: AI service keys (for transcription/analysis) -DEEPGRAM_KEY=your-deepgram-key -OPENAI_API_KEY=your-openai-key +Create `config.yml` in the repository root: + +```yaml +links: + tag: + module: links.tag + options: + tags: + - quick_start + +storages: + file: + module: storage.file + options: + path: /data/vcons + +chains: + quick_start: + links: + - tag + storages: + - file + ingress_lists: + - default + egress_lists: + - quick_start_output + enabled: 1 ``` -!!! tip "Generate a Secure Token" - Generate a secure API token: - ```bash - openssl rand -hex 32 - ``` +This chain reads the `default` list, tags each vCon, writes it to a file inside the `conserver` container and pushes its uuid to `quick_start_output`. -## Step 3: Start Services +Create this file before you start the stack. Compose mounts `./config.yml` into the `conserver` container, and Docker creates a directory of that name if no file exists. -```bash -# Create the Docker network -docker network create conserver +Do not start from `example_config.yml`. It is a syntax sample, and it names placeholder packages, modules and backends that a fresh stack does not have. The worker tries to install those packages and stops. -# Copy and customize the Docker Compose file -cp example_docker-compose.yml docker-compose.yml +## Start the stack -# Build and start all services +```bash +docker network create conserver docker compose up -d --build ``` -## Step 4: Verify Installation +`docker-compose.yml` declares the `conserver` network as external, so it must exist first. If it already exists, the first command reports that and you can carry on. -Check that services are running: +Check the services: ```bash docker compose ps ``` -Expected output: +You should see `api`, `conserver` and `redis` running. The `conserver` container can show `Up` after its process has failed, because a file watcher wraps it in the Compose setup. Read its logs to be sure: +```bash +docker compose logs conserver | tail ``` -NAME SERVICE STATUS -vcon-server-api-1 api running -vcon-server-conserver-1 conserver running -vcon-server-redis-1 redis running -``` -Check the API health: +A healthy worker logs `Worker-1 started`. + +Check the API: ```bash curl http://localhost:8000/api/health ``` -Expected response: - ```json -{"status": "healthy"} +{"status":"healthy","version":{"version":"dev","git_commit":"unknown","build_time":"unknown"}} ``` -Check the version: +A local build reports `dev`, because Compose passes no version at build time. This endpoint does not touch Redis, so it shows only that the API answers. + +## Submit a vCon + +Set the token and a uuid. The API rejects a `uuid` that is not a real UUID. ```bash -curl http://localhost:8000/api/version +export TOKEN=your-generated-token +export VCON_UUID=$(uuidgen | tr 'A-Z' 'a-z') +export NOW=$(date -u +%Y-%m-%dT%H:%M:%SZ) ``` -## Step 5: Submit a Test vCon - -Create a simple test vCon: +Post a vCon to the `default` list: ```bash -curl -X POST http://localhost:8000/api/vcon \ +curl -X POST "http://localhost:8000/api/vcon?ingress_lists=default" \ -H "Content-Type: application/json" \ - -H "x-conserver-api-token: your-secret-token-here" \ + -H "x-conserver-api-token: $TOKEN" \ -d '{ - "vcon": "0.0.1", - "uuid": "test-vcon-001", - "created_at": "2024-01-15T10:30:00Z", + "vcon": "0.4.0", + "uuid": "'"$VCON_UUID"'", + "created_at": "'"$NOW"'", "parties": [ - {"tel": "+15551234567", "name": "John Doe"}, - {"tel": "+15559876543", "name": "Jane Smith"} + {"tel": "+15551234567", "name": "Caller"}, + {"tel": "+15559876543", "name": "Agent"} ], - "dialog": [] + "dialog": [ + { + "type": "text", + "start": "'"$NOW"'", + "parties": [0, 1], + "originator": 0, + "mediatype": "text/plain", + "encoding": "none", + "body": "Hello, I have a question about my order." + } + ] }' ``` -Retrieve the vCon: - -```bash -curl http://localhost:8000/api/vcon/test-vcon-001 \ - -H "x-conserver-api-token: your-secret-token-here" -``` - -## Step 6: View Logs - -Monitor the processing: - -```bash -# View all logs -docker compose logs -f - -# View only conserver logs -docker compose logs -f conserver - -# View only API logs -docker compose logs -f api -``` - -## Basic Configuration +The API returns `201` and the stored vCon. The `ingress_lists` parameter is what starts processing. Without it the API stores the vCon and no chain runs. -The default configuration in `example_config.yml` includes a sample processing chain: +This test vCon has no `lawful_basis` attachment, and the server does not add one. See [lawful basis](../concepts/lawful-basis.md). -```yaml -chains: - sample_chain: - links: - - transcribe - - analyze - - tag - storages: - - redis_storage - ingress_lists: - - default - enabled: 1 -``` +## Read the result -This chain: - -1. Transcribes audio using the configured transcription service -2. Analyzes the transcript for insights -3. Applies tags based on analysis -4. Stores the result in Redis - -## Common Operations - -### Stop Services +Fetch the vCon: ```bash -docker compose down +curl "http://localhost:8000/api/vcon/$VCON_UUID" \ + -H "x-conserver-api-token: $TOKEN" ``` -### Restart Services +The `attachments` array now holds an entry the chain added: -```bash -docker compose restart +```json +{"purpose": "tags", "body": "[\"quick_start:quick_start\"]", "encoding": "json"} ``` -### View Configuration +The `body` is a JSON string, not an array. Decode it with `fromjson` in `jq`: ```bash -curl http://localhost:8000/api/config \ - -H "x-conserver-api-token: your-secret-token-here" +curl -s "http://localhost:8000/api/vcon/$VCON_UUID" \ + -H "x-conserver-api-token: $TOKEN" \ + | jq '.attachments[] | select(.purpose == "tags") | .body | fromjson' ``` -### Check Queue Status +Check the two other results of the chain: ```bash -# Connect to Redis and check queue lengths -docker compose exec redis redis-cli LLEN default +curl "http://localhost:8000/api/stats/queue?list_name=quick_start_output" +docker compose exec conserver find /data/vcons -type f ``` -## Troubleshooting +The first shows `"depth":1`. The second lists the stored file, under a date folder. That folder is inside the container, so recreating the container removes it. A real deployment uses a [storage adapter](../reference/storage-adapters/index.md) with durable storage. -### Services Won't Start +The API answers for one hour from Redis. After that, this setup returns `404`, because the file backend is visible only to the `conserver` container. See [read a stored vCon](../concepts/vcon-lifecycle.md#read-a-stored-vcon). -Check Docker logs: +The logs show the same run: ```bash -docker compose logs +docker compose logs conserver | grep "Completed processing" ``` -Common issues: +## Change the chain -- Port 8000 already in use -- Redis connection failed -- Invalid API token format +An idle worker rereads `config.yml` within 15 seconds, so chain changes need no restart. Compose mounts the file on its own, and on a Linux host an editor that saves by replacing the file leaves the container on the old copy. If an edit has no effect, run `docker compose up -d --force-recreate conserver`. -### API Returns 403 Forbidden +To go further: -Verify your API token: +- Add speech to text with [transcribe a recording](../configuration/chains-and-pipelines.md#transcribe-a-recording). The text dialog on this page has no audio, so `transcribe` skips it. Follow with an [analyze](../reference/links/analyze.md) step. +- Build your own chain from [chains and pipelines](../configuration/chains-and-pipelines.md). +- Browse the [API reference](../reference/api.md). -```bash -# Check if token is set -echo $CONSERVER_API_TOKEN - -# Ensure header matches -curl -H "x-conserver-api-token: $CONSERVER_API_TOKEN" ... -``` - -### vCon Not Processing - -Check the conserver logs: +## Stop the stack ```bash -docker compose logs conserver -``` - -Verify the ingress list is configured in a chain: - -```yaml -chains: - my_chain: - ingress_lists: - - default # Must match where you're sending vCons +docker compose down ``` -## Next Steps - -Now that you have vCon Server running: - -1. **[Docker Installation](../installation/docker.md)**: Learn about all Docker options -2. **[Configuration Guide](../configuration/index.md)**: Customize your setup -3. **[API Reference](../operations/api-reference.md)**: Explore all API endpoints -4. **[Creating Chains](../configuration/chains-and-pipelines.md)**: Build custom processing pipelines +Add `-v` to delete the Redis volume as well. -## Example: Complete Workflow +## Fix common problems -Here's a complete example that demonstrates the full workflow: - -```bash -#!/bin/bash -# complete-workflow.sh +| Symptom | Cause | Fix | +|---|---|---| +| `api` exits with code 1, logs show `server/logging_dev.conf doesn't exist` | `.env` still holds the value from `.env.example` | Set `LOGGING_CONFIG_FILE=common/logging_dev.conf` | +| `FileNotFoundError` naming an empty path, or `500` from `/config` | `CONSERVER_CONFIG_FILE` is blank | Set `CONSERVER_CONFIG_FILE=./config.yml` | +| `IsADirectoryError` naming `./config.yml` | The stack started before the file existed | Stop the stack, delete the `config.yml` directory, then create the file | +| `CalledProcessError` from `pip install` | `config.yml` names a package that cannot be installed, as `example_config.yml` does | Use the configuration on this page | +| `network conserver declared as external, but could not be found` | The network does not exist | `docker network create conserver` | +| Host port 8000 in use | Another process holds it | Set `CONSERVER_EXTERNAL_PORT` in `.env` | +| `403` with `Invalid API Key` | Wrong or missing header | Send `x-conserver-api-token` with the value in `.env`. After you change `.env`, run `docker compose up -d api` | +| `422` on `POST /vcon` | The body failed validation, often a `uuid` that is not a UUID | Read the `detail` field in the response | +| vCon stays unprocessed | No `ingress_lists` parameter, or the list is not in a chain | Post with `?ingress_lists=default` and check `ingress_lists` in `config.yml` | -API_URL="http://localhost:8000/api" -TOKEN="your-secret-token-here" +For anything else, see [troubleshooting](../operations/troubleshooting.md). Failed vCons go to the [dead letter queue](../operations/dead-letter-queue.md). -# 1. Check health -echo "Checking health..." -curl -s "$API_URL/health" -echo +## Take the next step -# 2. Create a vCon with audio reference -echo "Creating vCon..." -VCON_UUID=$(uuidgen) -curl -s -X POST "$API_URL/vcon?ingress_lists=default" \ - -H "Content-Type: application/json" \ - -H "x-conserver-api-token: $TOKEN" \ - -d "{ - \"vcon\": \"0.0.1\", - \"uuid\": \"$VCON_UUID\", - \"created_at\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\", - \"parties\": [ - {\"tel\": \"+15551234567\", \"name\": \"Customer\"}, - {\"tel\": \"+15559876543\", \"name\": \"Agent\"} - ], - \"dialog\": [] - }" -echo - -# 3. Wait for processing -echo "Waiting for processing..." -sleep 5 - -# 4. Retrieve processed vCon -echo "Retrieving processed vCon..." -curl -s "$API_URL/vcon/$VCON_UUID" \ - -H "x-conserver-api-token: $TOKEN" | jq . -``` +- [Docker installation](../installation/docker.md) covers more Docker options. +- [Configuration](../configuration/index.md) covers the environment and YAML settings. +- [Authentication](../configuration/authentication.md) covers API keys and scoped ingress keys. diff --git a/docs/getting-started/requirements.md b/docs/getting-started/requirements.md index 3e35595e..141fb946 100644 --- a/docs/getting-started/requirements.md +++ b/docs/getting-started/requirements.md @@ -1,193 +1,90 @@ -# System Requirements +# System requirements -This page describes the hardware and software requirements for running vCon Server. +This page lists what you need before you start the server, so the [quick start](quick-start.md) runs first time. -## Software Requirements +## Install the required software -### Required Components +| Software | Version | Purpose | +|---|---|---| +| Docker Engine | Current release | Runs the services | +| Docker Compose | v2 plugin (`docker compose`) | Starts the stack from `docker-compose.yml` | +| Git | Any | Clones the repository | -| Component | Version | Purpose | -|-----------|---------|---------| -| Docker | 20.10+ | Container runtime | -| Docker Compose | 2.0+ | Multi-container orchestration | -| Redis | 7.0+ | Queue management and caching | +Compose starts Redis for you, pinned to `redis:7.4-alpine`. Plain Redis is enough. If you run your own, you do not need RedisJSON or Redis Stack, and data from an older Redis Stack deployment needs the [Redis migration](../installation/redis-migration.md). -### Optional Components +CI runs the test suite on Ubuntu 24.04 under Docker. Published images cover `linux/amd64` and `linux/arm64`. -| Component | Version | Purpose | -|-----------|---------|---------| -| Python | 3.12+ | Local development without Docker | -| Poetry | 2.0+ | Python dependency management | -| PostgreSQL | 14+ | Relational storage backend | -| MongoDB | 6.0+ | Document storage backend | -| Elasticsearch | 8.0+ | Search storage backend | +## Add tools for local development -## Hardware Requirements +You need these only to run the code outside Docker. -### Minimum (Development/Testing) +| Software | Version | Purpose | +|---|---|---| +| Python | 3.12 or 3.13 (`>=3.12,<3.14`) | Runtime. The images use 3.12 | +| [uv](https://docs.astral.sh/uv/) | The images pin 0.10.9 | Dependency management, from `uv.lock` | +| Redis | Plain Redis. Compose uses 7.4 | Queues and vCon cache | +| ffmpeg, sox | Any | Audio handling in some links. The images install them | -| Resource | Requirement | -|----------|-------------| -| CPU | 2 cores | -| RAM | 4 GB | -| Storage | 20 GB SSD | -| Network | Stable internet connection | +See [Contributing](../contributing.md) for the setup. -### Recommended (Production) +## Choose optional backends -| Resource | Small | Medium | Large | -|----------|-------|--------|-------| -| CPU | 4 cores | 8 cores | 16+ cores | -| RAM | 8 GB | 16 GB | 32+ GB | -| Storage | 100 GB SSD | 500 GB SSD | 1+ TB SSD | -| Workers | 2-4 | 4-8 | 8-16 | +The default stack needs none of these. Each adapter page lists its options and credentials. -### Scaling Considerations +| Backend | Compose profile | Reference | +|---|---|---| +| PostgreSQL | `postgres` (`postgres:alpine`) | [PostgreSQL adapter](../reference/storage-adapters/postgres.md) | +| Elasticsearch | `elasticsearch` (8.13.4) | [Elasticsearch adapter](../reference/storage-adapters/elasticsearch.md) | +| MongoDB | None, bring your own | [MongoDB adapter](../reference/storage-adapters/mongo.md) | +| S3 | None, bring your own | [S3 adapter](../reference/storage-adapters/s3.md) | +| Anything else | None | [Storage adapters](../reference/storage-adapters/index.md) | -**CPU**: Each worker process uses approximately 1 CPU core during active processing. Set `CONSERVER_WORKERS` based on available cores. +The `langfuse` profile adds a local Langfuse stack for trace inspection. See [monitoring](../operations/monitoring.md). -**Memory**: Base memory usage is approximately 500MB. Each worker adds 200-500MB depending on: +## Gather vendor credentials -- Processing link complexity -- Audio file sizes being processed -- Caching configuration +Transcription and AI analysis links call outside services, so they need an API key and outbound HTTPS. A chain with only local links needs neither. Each [link page](../reference/links/index.md) names its option or environment variable, and [transcribe](../reference/links/transcribe.md) covers the speech to text vendors. -**Storage**: Storage requirements depend on: +## Plan capacity -- Number of vCons processed -- Audio file retention policy -- Storage backends used +Size for your chains, since the work happens there. An I/O-bound chain, such as one waiting on an LLM or a transcription service, needs little CPU. Two settings control how many vCons run at once: -**Network**: Consider bandwidth for: - -- Audio file ingestion -- External API calls (transcription, AI services) -- Storage backend communication - -## Operating System Support - -### Fully Supported - -- **Linux**: Ubuntu 20.04+, Debian 11+, RHEL 8+, Amazon Linux 2 -- **macOS**: 12.0+ (Monterey and later) - -### Container Support - -- Docker Desktop (Windows, macOS) -- Kubernetes 1.24+ -- AWS ECS/Fargate -- Google Cloud Run -- Azure Container Instances - -### Windows - -Windows is supported via: - -- Docker Desktop with WSL2 -- Windows Subsystem for Linux (WSL2) - -!!! note "Windows Native" - Native Windows installation is not recommended due to: - - - `fork` multiprocessing not available (must use `spawn`) - - Path handling differences - - Limited testing coverage - -## Network Requirements - -### Inbound Ports - -| Port | Service | Required | -|------|---------|----------| -| 8000 | API Server | Yes | -| 6379 | Redis (if external) | Optional | - -### Outbound Connections - -| Service | URL | Required | -|---------|-----|----------| -| Deepgram | api.deepgram.com | If using Deepgram transcription | -| OpenAI | api.openai.com | If using OpenAI analysis/transcription | -| Groq | api.groq.com | If using Groq Whisper | -| Hugging Face | huggingface.co | If using HF models | - -### Firewall Rules - -For production deployments, ensure: - -1. API server port (8000) accessible to clients -2. Redis port (6379) accessible only internally -3. Outbound HTTPS (443) for external AI services -4. Storage backend ports accessible from workers +```text +maximum parallel vCons = CONSERVER_WORKERS x CONSERVER_VCON_CONCURRENCY +``` -## External Service Requirements +Each worker is a separate OS process. See [workers](../configuration/workers.md). -### AI Services (Optional) +Compose caps the Redis container at 1 GB with `mem_limit`. Raise it if your queues and cached vCons need more. -To use transcription and analysis features, you need API keys for: + -| Service | Environment Variable | Free Tier | -|---------|---------------------|-----------| -| Deepgram | `DEEPGRAM_KEY` | Yes (limited) | -| OpenAI | `OPENAI_API_KEY` | No | -| Groq | `GROQ_API_KEY` | Yes (limited) | +## Open the network ports -### Storage Services (Optional) +The API listens on port 8000. Redis stays on the private `conserver` Docker network unless you publish it. See [ports](../reference/ports.md) for every service. -| Service | Credentials Needed | -|---------|-------------------| -| AWS S3 | Access Key ID, Secret Access Key | -| MongoDB Atlas | Connection string | -| Elasticsearch Cloud | API key or credentials | +## Run on macOS or Windows -## Verifying Requirements +The containers run Linux, so nothing changes under Docker. Outside Docker, Python defaults to the `spawn` start method on macOS and Windows, against `fork` on Linux. Set `CONSERVER_START_METHOD` to override it. See [workers](../configuration/workers.md). -### Check Docker +## Check your tools ```bash -# Check Docker version docker --version -# Expected: Docker version 20.10.0 or higher - -# Check Docker Compose version docker compose version -# Expected: Docker Compose version 2.0.0 or higher - -# Verify Docker is running docker info +git --version ``` -### Check Python (for local development) - -```bash -# Check Python version -python3 --version -# Expected: Python 3.12.0 or higher - -# Check Poetry version -poetry --version -# Expected: Poetry version 2.0.0 or higher -``` - -### Check System Resources +For local development: ```bash -# Linux/macOS - Check available memory -free -h # Linux -vm_stat # macOS - -# Check available disk space -df -h - -# Check CPU cores -nproc # Linux -sysctl -n hw.ncpu # macOS +uv --version +uv python list ``` -## Next Steps - -Once you have verified your system meets the requirements: +## Pick your next page -1. **[Quick Start](quick-start.md)**: Get running in 5 minutes -2. **[Docker Installation](../installation/docker.md)**: Detailed Docker setup -3. **[Manual Installation](../installation/manual-installation.md)**: Development setup with Poetry +- [Quick start](quick-start.md) runs the stack with Docker Compose. +- [Docker installation](../installation/docker.md) covers more Docker options. +- [Manual installation](../installation/manual-installation.md) runs the services without Docker. diff --git a/docs/index.md b/docs/index.md index 5baf1887..9b32101c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,145 +1,48 @@ -# vCon Server Documentation +# vCon Server documentation -Welcome to the official documentation for **vCon Server** (Conserver), a high-performance server for processing, storing, and managing vCon (Voice Conversation) data. +vCon Server, also called the Conserver, takes in [vCon](https://datatracker.ietf.org/doc/draft-ietf-vcon-vcon-core/) conversation records, runs them through configurable chains of processing steps and writes the results to the storage backends you choose. -## What is vCon Server? +These pages cover the open source server and match the code in this repository. -vCon Server is a pipeline-based processing system designed to handle voice conversation data at scale. It provides: +![API and conserver services around Redis, with storage backends and link services outside](diagrams/D01-system-context.svg) -- **Flexible Processing Pipelines**: Chain-based architecture with modular processing links -- **Multi-Storage Support**: 10+ backend storage options with parallel write support -- **AI Integration**: Built-in transcription (Deepgram, Whisper) and analysis (OpenAI, Groq) -- **Scalable Architecture**: Multi-worker processing with configurable parallelism -- **Enterprise Ready**: Authentication, monitoring, and dead letter queue handling +## See the main functions -## Quick Links +- **Takes in vCons.** The REST API accepts them from your systems, and scoped API keys let third parties post to one ingress list. +- **Queues work in Redis.** Plain Redis holds the vCons, the ingress and egress lists, and the dead letter queues. +- **Runs chains.** A chain names its ingress lists, its links, its storage backends and its egress lists. +- **Runs links.** A link is one step: transcription, AI analysis, tagging, routing, a webhook. Returning nothing stops the chain for that vCon. +- **Stores results.** Writes go to every backend in the chain, in parallel by default. +- **Scales by worker.** Set worker processes and per-worker concurrency with environment variables. +- **Reports on itself.** OpenTelemetry tracing and metrics, plus dead letter queues for failed vCons and failed storage writes. -
+The server carries `lawful_basis` attachments through the pipeline. It does not create, validate or enforce consent. See [lawful basis](concepts/lawful-basis.md) and [editions](concepts/editions.md). -- :material-rocket-launch:{ .lg .middle } **Getting Started** +## Choose a starting point - --- +| You want to | Read | +|---|---| +| Run the server for the first time | [Quick start](getting-started/quick-start.md) | +| Learn the moving parts | [Architecture](concepts/architecture.md), [chains, links and storage](concepts/chains-links-storage.md) | +| Follow one vCon from start to finish | [vCon lifecycle](concepts/vcon-lifecycle.md) | +| Deploy it | [Installation](installation/index.md) | +| Set it up | [Configuration](configuration/index.md) | +| Run it day to day | [Operations](operations/index.md) | +| Write a link, adapter or tracer | [Extending](extending/index.md) | +| Look up a name | [Reference](reference/index.md) | +| Change the code or the docs | [Contributing](contributing.md) | - New to vCon Server? Start here for system requirements and a 5-minute quick start guide. +## Find the catalogues - [:octicons-arrow-right-24: Getting Started](getting-started/index.md) +- [Links](reference/links/index.md) lists every link module and its status. +- [Storage adapters](reference/storage-adapters/index.md) lists every backend. +- [API reference](reference/api.md) describes every REST endpoint. +- [Environment variables](reference/environment.md), [ports](reference/ports.md) and [metrics](reference/metrics.md) are generated from the code. -- :material-download:{ .lg .middle } **Installation** +## Check the running version - --- +The repository has no product version: `pyproject.toml` holds a placeholder. Each image carries the version it was built with, and `GET /version` reports it. See the [API reference](reference/api.md). - Multiple installation options: Docker, automated scripts, manual setup, or Kubernetes. +## Report a problem - [:octicons-arrow-right-24: Installation Guide](installation/index.md) - -- :material-cog:{ .lg .middle } **Configuration** - - --- - - Configure environment variables, YAML settings, processing chains, and authentication. - - [:octicons-arrow-right-24: Configuration](configuration/index.md) - -- :material-tools:{ .lg .middle } **Operations** - - --- - - API reference, monitoring, logging, troubleshooting, and maintenance procedures. - - [:octicons-arrow-right-24: Operations](operations/index.md) - -- :material-puzzle:{ .lg .middle } **Extending** - - --- - - Create custom processing links, storage adapters, and tracers. - - [:octicons-arrow-right-24: Extending](extending/index.md) - -- :material-book-open-variant:{ .lg .middle } **Reference** - - --- - - Complete reference for all links, storage adapters, and CLI options. - - [:octicons-arrow-right-24: Reference](reference/index.md) - -
- -## Architecture Overview - -```mermaid -flowchart TB - subgraph ingress [Ingress Layer] - API[REST API] - EXT[External Ingress] - end - - subgraph processing [Processing Pipeline] - QUEUE[Redis Queues] - W1[Worker 1] - W2[Worker 2] - WN[Worker N] - LINKS[Processing Links] - end - - subgraph storage [Storage Layer] - PG[PostgreSQL] - S3[S3] - MONGO[MongoDB] - MILVUS[Milvus] - end - - API --> QUEUE - EXT --> QUEUE - QUEUE --> W1 - QUEUE --> W2 - QUEUE --> WN - W1 --> LINKS - W2 --> LINKS - WN --> LINKS - LINKS --> PG - LINKS --> S3 - LINKS --> MONGO - LINKS --> MILVUS -``` - -## Key Features - -### Processing Pipeline - -- **Chains**: Define processing workflows with ingress lists, links, storage, and egress -- **Links**: Modular processors for transcription, analysis, tagging, routing, and more -- **Filtering**: Links can filter vCons from the pipeline by returning `None` -- **Parallel Execution**: Multiple workers process vCons concurrently - -### Storage Options - -| Storage | Use Case | -|---------|----------| -| PostgreSQL | Relational queries, ACID compliance | -| MongoDB | Document storage, flexible schema | -| S3 | Archive storage, cost-effective | -| Elasticsearch | Full-text search | -| Milvus | Vector similarity search | -| File | Local development, simple deployments | - -### AI Integrations - -- **Transcription**: Deepgram, OpenAI Whisper, Groq Whisper, Hugging Face -- **Analysis**: OpenAI GPT models, custom analysis links -- **Embeddings**: OpenAI embeddings for vector storage - -## Version Information - -This documentation covers vCon Server v1.1, which includes: - -- Multi-worker support with configurable worker processes -- Parallel storage writes for improved throughput -- Graceful shutdown handling -- Worker auto-restart capabilities - -## Support - -- **GitHub Issues**: [Report bugs or request features](https://github.com/vcon-dev/vcon-server/issues) -- **GitHub Discussions**: [Ask questions and share ideas](https://github.com/vcon-dev/vcon-server/discussions) +Report bugs and request features in [GitHub issues](https://github.com/vcon-dev/vcon-server/issues). diff --git a/docs/installation/automated-script.md b/docs/installation/automated-script.md index 8c98ba95..02055494 100644 --- a/docs/installation/automated-script.md +++ b/docs/installation/automated-script.md @@ -1,304 +1,171 @@ -# Automated Installation Script +# Install with the automated script -The automated installation script provides a one-command setup for production deployments on Ubuntu Linux. +`scripts/install_conserver.sh` sets up an Ubuntu host with vcon-admin and vcon-server. It runs both as Docker Compose projects. -## Overview +!!! danger "Set the API token yourself" + The script does not write your domain, email or token into the files it creates. `CONSERVER_API_TOKEN` ends up empty in `/opt/vcon-server/.env`, which turns off the API key check, even though the script prints a token. Port 8000 is published on the host. Follow [Repair the generated files](#repair-the-generated-files) straight after the install. -The `install_conserver.sh` script: +## See the script steps -- Installs Docker and Docker Compose if needed -- Creates a dedicated `vcon` user -- Sets up directory structure -- Clones both vcon-server and vcon-admin repositories -- Configures SSL with Let's Encrypt -- Starts all services +In order, the script: -## Requirements +1. Asks you to confirm the domain, email and token. +2. Creates a `vcon` user with a Bash shell, and the folders `/opt/vcon-admin`, `/opt/vcon-server` and `/opt/vcon-data/redis`. +3. Installs Docker, with the Compose plugin, if the `docker` command is missing, and adds `vcon` to the `docker` group. A host that has Docker needs the plugin already. +4. Creates the `conserver` Docker network. +5. Clones `vcon-dev/vcon-admin` to `/opt/vcon-admin`, writes its `.env` and `.streamlit/secrets.toml`, and starts it. +6. Clones `vcon-dev/vcon-server` to `/opt/vcon-server`, writes `.env` and a `config.yml` with one `demo_chain`, and starts it. -- **Operating System**: Ubuntu 20.04 or later (recommended) -- **Access**: Root or sudo privileges -- **Network**: Public IP address with DNS record -- **Resources**: Minimum 4GB RAM, 20GB disk +Running the script again removes nothing in the two clones but pulls them and overwrites `.env` and `config.yml`, so keep your own copies. -## Usage +The server project is the repo's `docker-compose.yml`, which is built for development. See [Install with Docker](docker.md) for what that means. -### Basic Installation +## Prepare the host -```bash -sudo ./scripts/install_conserver.sh \ - --domain your-domain.com \ - --email admin@your-domain.com -``` +- Ubuntu. The script uses `apt-get` and Docker's Ubuntu repository. +- Root access. +- A domain name, and a DNS record pointing at the host. + +See the [system requirements](../getting-started/requirements.md) for sizing. -### With Custom API Token +## Run the script + +The script is in the repo, so clone it first: ```bash +git clone https://github.com/vcon-dev/vcon-server.git +cd vcon-server sudo ./scripts/install_conserver.sh \ --domain your-domain.com \ - --email admin@your-domain.com \ - --token your-custom-api-token + --email admin@your-domain.com ``` -## Command Line Options - | Option | Required | Description | -|--------|----------|-------------| -| `--domain` | Yes | Domain name pointing to this server | -| `--email` | Yes | Email for SSL certificate registration | -| `--token` | No | Custom API token (auto-generated if not provided) | - -## What Gets Installed - -### Directory Structure - -``` -/opt/vcon-admin/ # Admin portal -/opt/vcon-server/ # vCon Server -/opt/vcon-data/ # Persistent data - ├── redis/ # Redis data - ├── mongo/ # MongoDB data - └── uploads/ # Uploaded files -``` - -### Services - -| Service | Port | Description | -|---------|------|-------------| -| API | 8000 | vCon Server REST API | -| Admin | 3000 | Admin portal web UI | -| Redis | 6379 | Queue and cache | -| MongoDB | 27017 | Document storage | -| nginx | 80, 443 | Reverse proxy with SSL | - -### User Account - -A dedicated `vcon` user is created with: - -- No login shell (security) -- Ownership of `/opt/vcon-*` directories -- Docker group membership - -## Post-Installation - -### Access Points - -After installation, access your services at: +|---|---|---| +| `-d`, `--domain` | Yes | Domain name for the installation | +| `-e`, `--email` | Yes | Email for DNS registration | +| `-t`, `--token` | No | API token. A random 16-character hex value when left out. See the warning above | +| `-h`, `--help` | No | Print the options | -| Service | URL | -|---------|-----| -| Admin Portal | `https://your-domain.com/admin/` | -| API Documentation | `https://your-domain.com/api/docs` | -| API Health | `https://your-domain.com/api/health` | -| MongoDB Express | `https://your-domain.com/mongo-express` | -| Redis Insight | `http://your-server:8001` | +## Repair the generated files -### API Token - -If you didn't specify a token, find it in: - -```bash -cat /opt/vcon-server/.env | grep CONSERVER_API_TOKEN -``` - -### Service Management +Set a token in the server's `.env` and apply it: ```bash -# View service status +TOKEN=$(openssl rand -hex 32) +sudo sed -i "s/^CONSERVER_API_TOKEN=.*/CONSERVER_API_TOKEN=$TOKEN/" /opt/vcon-server/.env cd /opt/vcon-server -docker compose ps - -# View logs -docker compose logs -f - -# Restart services -docker compose restart - -# Stop services -docker compose down - -# Start services -docker compose up -d +sudo -u vcon docker compose up -d ``` -## Configuration +Then fill in the values the script left blank: -### Environment Variables +| File | Values to set | +|---|---| +| `/opt/vcon-server/.env` | `DNS_HOST`, `DNS_REGISTRATION_EMAIL` | +| `/opt/vcon-admin/.env` | `DNS_HOST`, `DNS_REGISTRATION_EMAIL` | +| `/opt/vcon-admin/.streamlit/secrets.toml` | `api_url` under `[conserver]`, which needs your domain, and `auth_token`, which needs the token | -Edit `/opt/vcon-server/.env`: +Restart vcon-admin after you edit its files: ```bash -sudo -u vcon nano /opt/vcon-server/.env +cd /opt/vcon-admin +sudo -u vcon docker compose up -d ``` -After changes, restart services: +Check that the key is on: ```bash -cd /opt/vcon-server -docker compose restart +curl -i http://localhost:8000/api/vcon ``` -### Processing Chains +A `403` means the check is on. -Edit `/opt/vcon-server/config.yml`: +## Find the installed services -```bash -sudo -u vcon nano /opt/vcon-server/config.yml -``` +This repo's Compose project starts `api`, `conserver` and `redis`. `.env` sets no `COMPOSE_PROFILES`, so no optional service starts. [Ports and services](../reference/ports.md) lists them. -### SSL Certificates +The generated `config.yml` writes to `mongodb://root:example@mongo:27017/`, a host this repo's Compose file does not define. -Certificates are managed by Certbot and auto-renewed. Manual renewal: + -```bash -certbot renew -``` +The script's closing summary names these addresses. All but the last depend on vcon-admin, so check them against that project: -## Upgrading +| Service | Address | +|---|---| +| Admin portal | `https://your-domain.com/admin/` | +| API docs | `https://your-domain.com/api/docs` | +| Mongo Express | `https://your-domain.com/mongo-express` | +| Redis Stack | `http://localhost:8001`. Out of date: the server now uses plain Redis with no Redis Insight, so nothing in this repo serves this port | -### Update vCon Server +On the host itself, the API answers on `http://localhost:8000/api/health`. -```bash -cd /opt/vcon-server -sudo -u vcon git pull -docker compose build --no-cache -docker compose up -d -``` +The script opens no firewall ports and sets up no certificates of its own. Restrict port 8000 with your own firewall rules. -### Update Admin Portal +## Change the configuration ```bash -cd /opt/vcon-admin -sudo -u vcon git pull -docker compose build --no-cache -docker compose up -d +sudo -u vcon nano /opt/vcon-server/.env +sudo -u vcon nano /opt/vcon-server/config.yml ``` -## Uninstallation - -Use the uninstall script: +Apply a change to `.env` with: ```bash -sudo ./scripts/uninstall_conserver.sh -``` - -This removes: - -- Docker containers and images -- Configuration files -- The `vcon` user - -!!! warning "Data Preservation" - By default, data in `/opt/vcon-data` is preserved. Add `--remove-data` to delete everything. - -## Troubleshooting - -### Installation Failed - -Check the installation log: - -```bash -cat /var/log/conserver-install.log +cd /opt/vcon-server +sudo -u vcon docker compose up -d ``` -Common issues: +Most changes to `config.yml` need no restart. See [the reload table](../configuration/yaml-configuration.md#plan-for-reloads). -1. **DNS not configured**: Ensure your domain points to the server IP -2. **Port 80/443 in use**: Stop any existing web servers -3. **Insufficient disk space**: Need at least 20GB free -4. **Docker installation failed**: Try installing Docker manually first - -### Services Not Starting - -Check Docker logs: +## Update the install ```bash cd /opt/vcon-server -docker compose logs -``` - -Check system resources: - -```bash -free -h -df -h +sudo -u vcon git pull +sudo -u vcon docker compose up -d --build ``` -### SSL Certificate Issues +Do the same in `/opt/vcon-admin`. See [Upgrading](upgrading.md) first. An install that predates plain Redis needs the [Redis migration](redis-migration.md). -Verify DNS: +## Remove the install ```bash -dig your-domain.com +sudo ./scripts/uninstall_conserver.sh ``` -Check Certbot logs: +The script asks for confirmation, then removes: -```bash -cat /var/log/letsencrypt/letsencrypt.log -``` +- The vcon-server containers and volumes, and the `conserver` network +- Images named `vcon-server` or `vcon-admin` +- `/opt/vcon-data`, `/opt/vcon-server` and `/opt/vcon-admin` +- The `vcon` user, unless that user is logged in -### Cannot Access Admin Portal +!!! warning "Data is deleted" + The script has no option to keep data. Back up first. See [Backup and restore](../operations/backup-restore.md). -Check nginx configuration: +The script runs `docker compose down` for vcon-server only. Stop vcon-admin first with `docker compose down` in `/opt/vcon-admin`, or its containers keep running. While they run, the `conserver` network stays too, because its removal fails without stopping the script. -```bash -nginx -t -systemctl status nginx -``` - -Verify the admin service is running: +## Troubleshoot the install -```bash -cd /opt/vcon-admin -docker compose ps -``` +The script logs to the terminal and keeps no log file. `set -e` stops it at the first failed command, so read the last lines it printed. -## Security Considerations +| Symptom | Fix | +|---|---| +| `ERROR: This script must be run as root` | Run it with `sudo` | +| Docker install fails | Install Docker yourself, then run the script again | +| Services do not start | Run `docker compose logs` in `/opt/vcon-server` | +| vCons fail at storage | Check that the `mongo` host resolves on the `conserver` network, or change `storages` in `config.yml` | -### Firewall Configuration - -The script configures UFW. Required ports: +To see what is running on the shared network: ```bash -# View current rules -ufw status - -# Required ports -ufw allow 22/tcp # SSH -ufw allow 80/tcp # HTTP (redirect to HTTPS) -ufw allow 443/tcp # HTTPS +docker ps +docker network inspect conserver ``` -### Changing the API Token - -1. Generate new token: - ```bash - openssl rand -hex 32 - ``` - -2. Update `.env`: - ```bash - sudo -u vcon nano /opt/vcon-server/.env - ``` - -3. Restart services: - ```bash - cd /opt/vcon-server - docker compose restart - ``` - -4. Update any clients using the old token - -### Database Security - -MongoDB is configured with authentication. Default credentials are in `.env`. Change them for production: - -1. Update `.env` with new credentials -2. Connect to MongoDB and update users -3. Restart services - -## Next Steps +## Continue with these guides -- [Configuration Guide](../configuration/index.md) - Customize settings -- [API Reference](../operations/api-reference.md) - Explore the API -- [Monitoring](../operations/monitoring.md) - Set up observability +- [Configuration guide](../configuration/index.md) +- [API reference](../reference/api.md) +- [Monitoring](../operations/monitoring.md) diff --git a/docs/installation/docker.md b/docs/installation/docker.md index 74ce2da8..764d2000 100644 --- a/docs/installation/docker.md +++ b/docs/installation/docker.md @@ -1,223 +1,116 @@ -# Docker Installation +# Install with Docker -This guide covers installing vCon Server using Docker and Docker Compose. +This page starts the API, the conserver and Redis on one host with Docker Compose. -## Prerequisites +The Compose file suits development and small deployments. It builds `docker/Dockerfile`, bind-mounts the repo into each container and restarts the conserver when a Python file changes. For production, see [Run the published images](#run-the-published-images). -- Docker 20.10 or later -- Docker Compose 2.0 or later -- Git -- 4GB RAM minimum (8GB recommended) -- 20GB disk space minimum +## Prepare the host -## Quick Installation +You need Git and Docker with the Compose plugin. See the [system requirements](../getting-started/requirements.md) for sizing. -```bash -# Clone the repository -git clone https://github.com/vcon-dev/vcon-server.git -cd vcon-server +If you already run Redis Stack, finish the [Redis migration](redis-migration.md) first. RedisJSON persistence files cannot be reused with the plain Redis image. -# Create Docker network -docker network create conserver - -# Copy configuration files -cp .env.example .env -cp example_docker-compose.yml docker-compose.yml - -# Edit .env with your settings -nano .env - -# Build and start services -docker compose up -d --build -``` - -## Detailed Steps - -### Step 1: Clone Repository +## Clone the repository ```bash git clone https://github.com/vcon-dev/vcon-server.git cd vcon-server ``` -### Step 2: Create Docker Network +## Create the network -The `conserver` network allows containers to communicate: +The Compose file declares the `conserver` network as external, so create it once: ```bash docker network create conserver ``` -### Step 3: Configure Environment - -Copy the example environment file: +## Set the environment ```bash cp .env.example .env ``` -Edit `.env` with required settings: +Change these lines in `.env` before you start anything: ```bash -# Required Settings -REDIS_URL=redis://redis:6379 -CONSERVER_API_TOKEN=your-secure-token-here +# The sample value points at a path that no longer exists and stops both services. +LOGGING_CONFIG_FILE=common/logging.conf -# Optional: AI Services -DEEPGRAM_KEY=your-deepgram-api-key -OPENAI_API_KEY=your-openai-api-key -GROQ_API_KEY=your-groq-api-key +# The sample value is empty, which the services cannot open. +CONSERVER_CONFIG_FILE=./config.yml -# Optional: Worker Configuration -CONSERVER_WORKERS=4 -CONSERVER_PARALLEL_STORAGE=true -CONSERVER_START_METHOD=fork +# Blank means no API key check on the main routes. +CONSERVER_API_TOKEN=your-secure-token-here -# Optional: Logging -LOG_LEVEL=INFO -ENV=production +# Optional services to start. Blank starts only api, conserver and redis. +COMPOSE_PROFILES= ``` -!!! tip "Secure Token Generation" - Generate a secure API token: - ```bash - openssl rand -hex 32 - ``` - -### Step 4: Configure Docker Compose - -Copy and customize the Docker Compose file: +`common/logging.conf` writes JSON for production. `common/logging_dev.conf` writes plain text, as the [quick start](../getting-started/quick-start.md) does, so log lines here look different from its samples. -```bash -cp example_docker-compose.yml docker-compose.yml -``` - -For existing Redis Stack installations, complete the [Redis migration](redis-migration.md) before upgrading. RedisJSON persistence files cannot be reused with the ordinary Redis image. +Generate a token with `openssl rand -hex 32`. Every variable is listed in the [environment reference](../reference/environment.md), and the [environment guide](../configuration/environment-variables.md) helps you choose values. -Redis listens on port 6379 inside the Docker network. The default configuration publishes no Redis port and does not include Redis Insight. The previous `REDIS_EXTERNAL_PORT` setting no longer applies. For local debugging, use `docker compose exec redis redis-cli`. +## Write the chain configuration -The default configuration includes: +The Compose file mounts `./config.yml` into the conserver, so the file must exist before the first start. Start with a small one: ```yaml -services: - redis: - image: redis:7.4-alpine@sha256:520775a41a63e77e06c73e35d2fd9cc15921a609516818796b4ecbb813078bc7 - command: ["redis-server", "--save", "20", "1", "--notify-keyspace-events", "Ex", "--dir", "/data", "--appendonly", "yes"] - volumes: - - redis_data:/data - networks: - - conserver +links: + tag_processed: + module: links.tag + options: + tags: + - processed - api: - build: - context: . - dockerfile: docker/Dockerfile - command: > - opentelemetry-instrument - uvicorn server.api:app - --host 0.0.0.0 - --port 8000 - ports: - - "8000:8000" - env_file: - - .env - depends_on: - - redis - networks: - - conserver - - conserver: - build: - context: . - dockerfile: docker/Dockerfile - command: opentelemetry-instrument python ./server/main.py - env_file: - - .env - depends_on: - - redis - networks: - - conserver - -volumes: - redis_data: +storages: + redis_storage: + module: storage.redis_storage -networks: - conserver: - external: true +chains: + main_chain: + links: + - tag_processed + storages: + - redis_storage + ingress_lists: + - default ``` -### Step 5: Build and Start +`example_config.yml` is a catalogue of syntax, not a working configuration. Its `imports` section names packages that do not exist, so a worker that loads it fails at startup. Copy from it, but do not run it as it stands. -Build the Docker images: +See [YAML configuration](../configuration/yaml-configuration.md) to build your own. -```bash -docker compose build -``` - -Start all services: +## Start the services ```bash -docker compose up -d +docker compose up -d --build ``` -### Step 6: Verify Installation - -Check service status: +## Check the installation ```bash docker compose ps -``` - -Check API health: - -```bash curl http://localhost:8000/api/health +curl http://localhost:8000/api/version +docker compose logs -f conserver ``` -View logs: +The API listens on host port 8000, or on `CONSERVER_EXTERNAL_PORT` if you set it. To send a first vCon, follow the [quick start](../getting-started/quick-start.md). -```bash -docker compose logs -f -``` - -## Configuration Options - -### Adding Storage Backends - -#### PostgreSQL - -Add to `docker-compose.yml`: - -```yaml -services: - postgres: - image: postgres:15 - environment: - POSTGRES_USER: vcon - POSTGRES_PASSWORD: vcon_password - POSTGRES_DB: vcon_server - volumes: - - postgres_data:/var/lib/postgresql/data - networks: - - conserver +Redis listens on port 6379 inside the Docker network and publishes no host port. The old `REDIS_EXTERNAL_PORT` setting no longer applies, and the file no longer includes Redis Insight. To reach Redis, run `docker compose exec redis redis-cli`. -volumes: - postgres_data: -``` +## Add storage backends -Add to `.env`: +PostgreSQL and Elasticsearch are Compose profiles. Add a profile to `.env`, then run `docker compose up -d`: ```bash -POSTGRES_USER=vcon -POSTGRES_PASSWORD=vcon_password -POSTGRES_HOST=postgres -POSTGRES_PORT=5432 -POSTGRES_DB=vcon_server +COMPOSE_PROFILES=postgres,elasticsearch ``` -#### MongoDB +The credentials in the Compose file are for development only. Point the adapter at the service in `config.yml`. The [PostgreSQL](../reference/storage-adapters/postgres.md) and [Elasticsearch](../reference/storage-adapters/elasticsearch.md) reference pages list the options. -Add to `docker-compose.yml`: +The Compose file has no MongoDB service. Add one, or point [`storage.mongo`](../reference/storage-adapters/mongo.md) at a server you run. For a local service, put this in a `docker-compose.override.yml` file: ```yaml services: @@ -235,45 +128,19 @@ volumes: mongo_data: ``` -#### Elasticsearch +The `langfuse` profile adds local LLM tracing. See [Ports and services](../reference/ports.md). -Add to `docker-compose.yml`: - -```yaml -services: - elasticsearch: - image: docker.elastic.co/elasticsearch/elasticsearch:8.11.0 - environment: - - discovery.type=single-node - - xpack.security.enabled=false - - "ES_JAVA_OPTS=-Xms512m -Xmx512m" - volumes: - - es_data:/usr/share/elasticsearch/data - networks: - - conserver - -volumes: - es_data: -``` +## Scale the workers -### Scaling Workers - -Scale the conserver service for more throughput: +Run more conserver containers: ```bash -# Run 4 conserver instances docker compose up -d --scale conserver=4 ``` -Or use the `CONSERVER_WORKERS` environment variable for multi-worker mode within a single container: - -```bash -CONSERVER_WORKERS=4 -``` - -### Resource Limits +Or run more worker processes in one container with `CONSERVER_WORKERS` in `.env`. [Workers](../configuration/workers.md) compares the two. -Add resource constraints in `docker-compose.yml`: +Set resource limits in `docker-compose.override.yml`: ```yaml services: @@ -283,173 +150,96 @@ services: limits: cpus: '2' memory: 2G - reservations: - cpus: '1' - memory: 1G -``` - -## Docker Commands Reference - -### Service Management - -```bash -# Start services -docker compose up -d - -# Stop services -docker compose down - -# Restart a specific service -docker compose restart conserver - -# View logs -docker compose logs -f [service] - -# Check status -docker compose ps -``` - -### Maintenance - -```bash -# Update to latest code -git pull -docker compose build --no-cache -docker compose up -d - -# Clean up unused images -docker image prune -f - -# View resource usage -docker stats ``` -### Debugging +## Run the published images -```bash -# Execute shell in container -docker compose exec conserver bash +CI publishes two multi-arch images, each smaller than the Compose image: -# View container logs -docker compose logs conserver --tail=100 +| Image | Built from | Holds | +|---|---|---| +| `public.ecr.aws/r4g1k2s3/vcon-dev/vcon-server-api` | `docker/Dockerfile.api` | `api/`, `common/` and the `api` dependency group | +| `public.ecr.aws/r4g1k2s3/vcon-dev/vcon-server-conserver` | `docker/Dockerfile.conserver` | `conserver/`, `common/` and the `conserver` dependency group | -# Check container health -docker inspect --format='{{.State.Health.Status}}' vcon-server-conserver-1 -``` +A push to `main` publishes `latest` and `main-`. A `v1.2.3` tag publishes `1.2.3`, `1.2` and `1`. Each image starts its own process, so it needs no `command` override. Each waits for `REDIS_URL` to answer before it starts. -## Production Considerations +Neither image holds `storage-milvus`, and the [storage adapter reference](../reference/storage-adapters/index.md#install-the-adapter-packages) shows which adapters each image can load. -### Security +## Prepare for production -1. **Use secrets management** instead of environment variables for sensitive data -2. **Enable TLS** with a reverse proxy (nginx, Traefik) -3. **Restrict network access** to Redis and database ports -4. **Use non-root users** in containers (already configured in Dockerfile) - -### Reverse Proxy with nginx - -Add nginx for TLS termination: +- Set API keys and use a [token file](../configuration/authentication.md#set-the-global-api-keys) for more than one key. +- Terminate TLS at a reverse proxy, and send it to `api:8000`. The `nginx.conf` in the repo is a sample with fixed certificate paths, so write your own. +- Keep Redis and databases off public networks. The `postgres` and `elasticsearch` profiles publish their ports on the host. +- The images define no `USER`, so containers run as root. Set a user in your runtime if your policy needs one. +- Rotate container logs: ```yaml services: - nginx: - image: nginx:alpine - ports: - - "80:80" - - "443:443" - volumes: - - ./nginx.conf:/etc/nginx/nginx.conf:ro - - ./certs:/etc/nginx/certs:ro - depends_on: - - api - networks: - - conserver + conserver: + logging: + driver: "json-file" + options: + max-size: "10m" + max-file: "3" ``` -### Health Checks - -Add health checks to ensure service reliability: +The images do not include `curl`, so write a health check in Python: ```yaml services: api: healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:8000/api/health"] + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"] interval: 30s timeout: 10s retries: 3 start_period: 40s ``` -### Logging - -Configure centralized logging: - -```yaml -services: - conserver: - logging: - driver: "json-file" - options: - max-size: "10m" - max-file: "3" -``` - -## Troubleshooting - -### Container Won't Start - -Check logs for errors: - -```bash -docker compose logs conserver -``` - -Common issues: - -- Redis not reachable (check network) -- Invalid configuration file -- Insufficient memory - -### Redis Connection Failed - -Verify Redis is running: +## Manage the services ```bash -docker compose exec redis redis-cli ping +docker compose up -d # Start, or apply changes to .env +docker compose down # Stop and remove the containers +docker compose restart conserver # Restart one service +docker compose logs -f conserver # Follow logs +docker compose exec conserver bash +docker stats ``` -Check network connectivity: +`docker compose restart` does not reread `.env`. Use `docker compose up -d` after you change it. -```bash -docker compose exec conserver ping redis -``` +To update the code, see [Upgrading](upgrading.md). -### Out of Memory +## Troubleshoot a failed start -Increase Docker memory limit or reduce worker count: +Start with the logs: ```bash -CONSERVER_WORKERS=2 +docker compose logs conserver --tail=100 ``` -### Port Already in Use +| Symptom | Cause | Fix | +|---|---|---| +| `FileNotFoundError: server/logging_dev.conf` | `LOGGING_CONFIG_FILE` still holds the sample value | [Set the environment](#set-the-environment) | +| `FileNotFoundError` on an empty path | `CONSERVER_CONFIG_FILE` is empty | [Set the environment](#set-the-environment) | +| `IsADirectoryError` on `config.yml` | Docker created a folder because the file was missing | Remove the folder and [write the file](#write-the-chain-configuration) | +| Worker exits with `No matching distribution found` | The `imports` section of `example_config.yml` | [Write your own file](#write-the-chain-configuration) | +| `network conserver declared as external, but could not be found` | The network is missing | [Create the network](#create-the-network) | +| `Redis not ready yet. Retrying...` repeats | Wrong `REDIS_URL`, or Redis is down | Use `redis://redis` and check `docker compose exec redis redis-cli ping` | +| Port 8000 already in use | Another process holds it | Set `CONSERVER_EXTERNAL_PORT` in `.env` | +| Containers are killed for memory | Too many workers | Lower `CONSERVER_WORKERS` or raise Docker's memory limit | -Check what's using the port: +To test Redis from the conserver container: ```bash -lsof -i :8000 +docker compose exec conserver redis-cli -h redis ping ``` -Change the port mapping in `docker-compose.yml`: - -```yaml -ports: - - "8080:8000" # Map to different host port -``` +See [Troubleshooting](../operations/troubleshooting.md) for faults after startup. -## Next Steps +## Continue with these guides -- [Configuration Guide](../configuration/index.md) - Customize your installation -- [Multi-Worker Configuration](../configuration/workers.md) - Scale processing -- [Monitoring](../operations/monitoring.md) - Set up observability +- [Configuration guide](../configuration/index.md) +- [Workers](../configuration/workers.md) +- [Monitoring](../operations/monitoring.md) diff --git a/docs/installation/index.md b/docs/installation/index.md index b0ed568b..e9459251 100644 --- a/docs/installation/index.md +++ b/docs/installation/index.md @@ -1,168 +1,44 @@ -# Installation Guide +# Install vCon Server -This section covers all methods for installing and deploying vCon Server. +Pick the path that fits how you will run the server. Every path ends with the same three processes: the API, the conserver workers and Redis. -## Installation Methods +![Five deployment paths: Docker Compose, the automated script, manual install, published images and the example Kubernetes manifests](../diagrams/D03-deploy-map.svg) -Choose the installation method that best fits your needs: +## Choose a method -| Method | Best For | Complexity | -|--------|----------|------------| -| [Docker](docker.md) | Production, most users | Low | -| [Automated Script](automated-script.md) | Quick production setup on Ubuntu | Low | -| [Manual Installation](manual-installation.md) | Development, customization | Medium | -| [Kubernetes](kubernetes.md) | Large scale, cloud native | High | +| Method | Runs on | Use it for | +|---|---|---| +| [Docker Compose](docker.md) | One host with Docker | Local work and small single-host deployments | +| [Automated script](automated-script.md) | One Ubuntu host | A demo host with the vcon-admin portal alongside the server | +| [Manual install](manual-installation.md) | Any host with Python and Redis | Development and debugging without containers | +| [Kubernetes](kubernetes.md) | A cluster | Scaled deployments from the published images | -## Quick Comparison +The Compose file builds `docker/Dockerfile`, which holds every dependency group, bind-mounts the source and restarts the conserver on file changes. It is built for development. For production, run the published images from `docker/Dockerfile.api` and `docker/Dockerfile.conserver`. The [Docker page](docker.md#run-the-published-images) gives the image names. -### Docker (Recommended) +The repo ships no Kubernetes manifests. The [Kubernetes page](kubernetes.md) gives an untested example to adapt. -```bash -git clone https://github.com/vcon-dev/vcon-server.git -cd vcon-server -cp .env.example .env -cp example_docker-compose.yml docker-compose.yml -docker network create conserver -docker compose up -d --build -``` +## Know the components -**Pros:** +| Component | Required | Role | +|---|---|---| +| API | Yes | FastAPI app on port 8000. Accepts vCons, serves reads and manages the queues | +| Conserver | Yes | Worker processes that run each vCon through its chain | +| Redis | Yes | Queues and the hot copy of each vCon. Plain Redis, no modules | +| Storage backends | No | Long-term copies. See the [storage adapter reference](../reference/storage-adapters/index.md) | -- Consistent environment across systems -- Easy to scale with `docker compose up --scale` -- All dependencies included -- Simple upgrades +[Architecture](../concepts/architecture.md) explains how they fit together. [Ports and services](../reference/ports.md) lists every port and Compose service. -**Cons:** +If you run an older deployment on Redis Stack, read [Migrate RedisJSON data](redis-migration.md) before you upgrade. -- Requires Docker knowledge -- Container overhead +## Gather the prerequisites -### Automated Script +- Read the [system requirements](../getting-started/requirements.md). +- Collect the API keys your links need. Most links take them as [options in the YAML file](../reference/links/index.md). A few fall back to an environment variable, and each link page names it. +- Choose your [storage backends](../reference/storage-adapters/index.md). -```bash -sudo ./scripts/install_conserver.sh \ - --domain your-domain.com \ - --email admin@your-domain.com -``` +## Complete the follow-up steps -**Pros:** - -- One-command installation -- Sets up SSL, reverse proxy, and all services -- Production-ready configuration - -**Cons:** - -- Ubuntu Linux only -- Requires root access -- Less flexibility - -### Manual Installation - -```bash -poetry install -poetry run python ./server/main.py -``` - -**Pros:** - -- Full control over configuration -- Best for development -- Easy debugging - -**Cons:** - -- More setup steps -- Must manage dependencies -- External Redis required - -### Kubernetes - -```bash -kubectl apply -f k8s/ -``` - -**Pros:** - -- Horizontal scaling -- Self-healing -- Cloud-native integration - -**Cons:** - -- Kubernetes expertise required -- More complex setup -- Higher resource overhead - -## Architecture Overview - -Regardless of installation method, vCon Server consists of these components: - -```mermaid -flowchart TB - subgraph required [Required Components] - API[API Server
FastAPI on port 8000] - WORKER[Conserver Workers
vCon Processing] - REDIS[Redis
Queues and Cache] - end - - subgraph optional [Optional Components] - PG[PostgreSQL] - MONGO[MongoDB] - ES[Elasticsearch] - S3[S3 Storage] - end - - API <--> REDIS - WORKER <--> REDIS - WORKER --> PG - WORKER --> MONGO - WORKER --> ES - WORKER --> S3 -``` - -### Required Components - -1. **API Server**: FastAPI application serving the REST API -2. **Conserver Workers**: Background processes that execute chains -3. **Redis**: Message queue and caching layer - -### Optional Components - -Storage backends are optional and can be added based on your needs: - -- **PostgreSQL**: Relational storage with full query support -- **MongoDB**: Document storage for flexible schemas -- **Elasticsearch**: Full-text search capabilities -- **S3**: Object storage for archival -- **Milvus**: Vector similarity search - -## Pre-Installation Checklist - -Before installing, ensure you have: - -- [ ] Reviewed [System Requirements](../getting-started/requirements.md) -- [ ] Chosen an installation method -- [ ] Obtained any necessary API keys (Deepgram, OpenAI, etc.) -- [ ] Planned your storage backend strategy -- [ ] Allocated sufficient system resources - -## Post-Installation Steps - -After installation, you should: - -1. **Verify the installation** by checking the health endpoint -2. **Configure authentication** with secure API tokens -3. **Set up monitoring** for production environments -4. **Configure backups** for your storage backends -5. **Review security settings** and firewall rules - -## Next Steps - -Choose your installation method: - -- [Docker Installation](docker.md) - Recommended for most users -- [Automated Script](automated-script.md) - Quick Ubuntu production setup -- [Manual Installation](manual-installation.md) - Development and customization -- [Kubernetes](kubernetes.md) - Large scale deployments +1. Check `GET /api/health`. +2. Set API keys. See [Authentication](../configuration/authentication.md). With no key set, the main API routes are open. +3. Build your [chains](../configuration/chains-and-pipelines.md). +4. Set up [monitoring](../operations/monitoring.md) and [backups](../operations/backup-restore.md). diff --git a/docs/installation/kubernetes.md b/docs/installation/kubernetes.md index 7d5ac2e5..d83fe51f 100644 --- a/docs/installation/kubernetes.md +++ b/docs/installation/kubernetes.md @@ -1,64 +1,20 @@ -# Kubernetes Deployment - -This guide covers deploying vCon Server on Kubernetes for scalable, production-grade deployments. - -## Overview - -Kubernetes deployment provides: - -- Horizontal scaling with multiple replicas -- Self-healing with automatic restarts -- Rolling updates with zero downtime -- Resource management and limits -- Integration with cloud-native services - -## Architecture - -```mermaid -flowchart TB - subgraph ingress [Ingress] - ING[Ingress Controller] - end - - subgraph services [Services] - API_SVC[API Service] - REDIS_SVC[Redis Service] - end - - subgraph workloads [Workloads] - API[API Deployment
replicas: 2] - WORKER[Worker Deployment
replicas: 4] - REDIS[Redis StatefulSet
replicas: 1] - end - - subgraph storage [Storage] - PVC[PersistentVolumeClaim] - SECRET[Secrets] - CM[ConfigMap] - end - - ING --> API_SVC - API_SVC --> API - API --> REDIS_SVC - WORKER --> REDIS_SVC - REDIS_SVC --> REDIS - REDIS --> PVC - API --> SECRET - WORKER --> SECRET - API --> CM - WORKER --> CM -``` +# Deploy on Kubernetes + +This page gives example manifests for the API, the workers and Redis. The repo ships no manifests and CI does not test these, so treat them as a starting point. The Kubernetes group in the [deploy map](index.md) shows how the pieces connect. + +## Prepare the cluster -## Prerequisites +You need: -- Kubernetes cluster 1.24+ -- kubectl configured -- Container registry access -- Persistent volume provisioner +- A cluster with a persistent volume provisioner +- `kubectl` configured for that cluster +- Pull access to `public.ecr.aws` -## Deployment Files +Use the two published images. `api` runs `vcon-server-api` and `worker` runs `vcon-server-conserver`. See [Run the published images](docker.md#run-the-published-images) for the tags, and pin a version in production. Each image starts its own process and waits for `REDIS_URL`, so the manifests set no `command`. -Create a `k8s/` directory with the following manifests: +## Write the manifests + +Create a `k8s/` folder with these files. ### Namespace @@ -81,31 +37,31 @@ metadata: namespace: vcon-server data: config.yml: | + links: + tag_processed: + module: links.tag + options: + tags: + - processed + + storages: + redis_storage: + module: storage.redis_storage + chains: main_chain: links: - - transcribe - - analyze - - tag + - tag_processed storages: - redis_storage ingress_lists: - default - enabled: 1 - - links: - transcribe: - module: links.transcribe - analyze: - module: links.analyze - tag: - module: links.tag - - storages: - redis_storage: - module: storage.redis_storage ``` +Build your own chains with [YAML configuration](../configuration/yaml-configuration.md). + +The server does not expand `${VAR}` in this file, so link and storage credentials sit in it as plain values. Once they do, move `config.yml` from the ConfigMap to a Secret. `POST /config` writes to this file, so it fails on a read-only mount. + ### Secrets ```yaml @@ -118,19 +74,13 @@ metadata: type: Opaque stringData: api-token: "your-secure-api-token" - deepgram-key: "your-deepgram-key" - openai-key: "your-openai-key" ``` -!!! warning "Secret Management" - In production, use a secrets management solution like: - - - HashiCorp Vault - - AWS Secrets Manager - - Azure Key Vault - - Sealed Secrets +In production, fill this Secret from a secrets manager rather than a file in Git. + +### Redis -### Redis StatefulSet +The arguments match the `redis` service in `docker-compose.yml`. ```yaml # k8s/redis.yaml @@ -164,7 +114,8 @@ spec: spec: containers: - name: redis - image: redis:7-alpine + image: redis:7.4-alpine + args: ["redis-server", "--save", "20", "1", "--notify-keyspace-events", "Ex", "--dir", "/data", "--appendonly", "yes"] ports: - containerPort: 6379 resources: @@ -187,7 +138,7 @@ spec: storage: 10Gi ``` -### API Deployment +### API ```yaml # k8s/api.yaml @@ -220,14 +171,7 @@ spec: spec: containers: - name: api - image: public.ecr.aws/r4g1k2s3/vcon-dev/vcon-server:latest - command: - - uvicorn - - server.api:app - - --host - - "0.0.0.0" - - --port - - "8000" + image: public.ecr.aws/r4g1k2s3/vcon-dev/vcon-server-api:latest ports: - containerPort: 8000 env: @@ -268,7 +212,7 @@ spec: name: vcon-config ``` -### Worker Deployment +### Workers ```yaml # k8s/worker.yaml @@ -289,10 +233,7 @@ spec: spec: containers: - name: worker - image: public.ecr.aws/r4g1k2s3/vcon-dev/vcon-server:latest - command: - - python - - ./server/main.py + image: public.ecr.aws/r4g1k2s3/vcon-dev/vcon-server-conserver:latest env: - name: REDIS_URL value: "redis://redis:6379" @@ -307,18 +248,6 @@ spec: value: "2" - name: CONSERVER_PARALLEL_STORAGE value: "true" - - name: DEEPGRAM_KEY - valueFrom: - secretKeyRef: - name: vcon-secrets - key: deepgram-key - optional: true - - name: OPENAI_API_KEY - valueFrom: - secretKeyRef: - name: vcon-secrets - key: openai-key - optional: true volumeMounts: - name: config mountPath: /config @@ -366,7 +295,7 @@ spec: number: 8000 ``` -### Horizontal Pod Autoscaler +### Autoscaler ```yaml # k8s/hpa.yaml @@ -391,9 +320,7 @@ spec: averageUtilization: 70 ``` -## Deployment Steps - -### Step 1: Apply Manifests +## Apply the manifests ```bash # Create namespace @@ -415,7 +342,7 @@ kubectl apply -f k8s/ingress.yaml kubectl apply -f k8s/hpa.yaml ``` -### Step 2: Verify Deployment +## Check the deployment ```bash # Check pod status @@ -432,66 +359,28 @@ kubectl port-forward svc/api 8000:8000 -n vcon-server curl http://localhost:8000/api/health ``` -## Scaling - -### Manual Scaling +## Scale the deployments ```bash -# Scale workers kubectl scale deployment/worker --replicas=8 -n vcon-server - -# Scale API kubectl scale deployment/api --replicas=4 -n vcon-server ``` -### Automatic Scaling - -The HPA automatically scales based on CPU utilization. Customize thresholds: - -```yaml -metrics: - - type: Resource - resource: - name: cpu - target: - type: Utilization - averageUtilization: 70 - - type: Resource - resource: - name: memory - target: - type: Utilization - averageUtilization: 80 -``` - -## Monitoring +The example autoscaler scales workers on CPU. The `conserver.ingress_list.length` metric reports queue depth if you prefer to scale on that. See [Workers](../configuration/workers.md) to balance replicas against `CONSERVER_WORKERS` and `CONSERVER_VCON_CONCURRENCY`. -### Prometheus Metrics +## Connect monitoring -Add annotations for Prometheus scraping: +The server exposes no Prometheus endpoint. It pushes metrics and traces over OTLP when `OTEL_EXPORTER_OTLP_ENDPOINT` is set, so add that variable to both Deployments and point it at your collector: ```yaml -metadata: - annotations: - prometheus.io/scrape: "true" - prometheus.io/port: "8000" - prometheus.io/path: "/metrics" +env: + - name: OTEL_EXPORTER_OTLP_ENDPOINT + value: "http://otel-collector:4317" ``` -### Logging - -Configure centralized logging: +See [Monitoring](../operations/monitoring.md) and the [metric list](../reference/metrics.md). [Logging](../operations/logging.md) covers log format, which `LOGGING_CONFIG_FILE` sets. -```yaml -spec: - containers: - - name: worker - env: - - name: LOG_FORMAT - value: "json" -``` - -## Cloud-Specific Configurations +## Adapt the Ingress to your cloud ### AWS EKS @@ -523,9 +412,9 @@ metadata: kubernetes.io/ingress.class: azure/application-gateway ``` -## Troubleshooting +## Troubleshoot the cluster -### Pods Not Starting +### Diagnose a stuck pod ```bash # Check pod status @@ -535,7 +424,9 @@ kubectl describe pod -n vcon-server kubectl get events -n vcon-server --sort-by='.lastTimestamp' ``` -### Connection Issues +A pod that logs `Redis not ready yet. Retrying...` cannot reach `REDIS_URL`. + +### Diagnose a failed connection ```bash # Test Redis connectivity @@ -545,7 +436,7 @@ kubectl exec -it deployment/api -n vcon-server -- redis-cli -h redis ping kubectl get endpoints -n vcon-server ``` -### Resource Issues +### Check resource usage ```bash # Check resource usage @@ -555,8 +446,8 @@ kubectl top pods -n vcon-server kubectl describe nodes ``` -## Next Steps +## Continue with these guides -- [Configuration Guide](../configuration/index.md) - Customize settings -- [Monitoring](../operations/monitoring.md) - Set up observability -- [Scaling](../configuration/workers.md) - Optimize performance +- [Configuration guide](../configuration/index.md) +- [Monitoring](../operations/monitoring.md) +- [Workers](../configuration/workers.md) diff --git a/docs/installation/manual-installation.md b/docs/installation/manual-installation.md index 5dda1651..8d547a75 100644 --- a/docs/installation/manual-installation.md +++ b/docs/installation/manual-installation.md @@ -1,411 +1,199 @@ -# Manual Installation +# Install from source -This guide covers installing vCon Server manually for development or customized deployments. +This page runs the server from a checkout with [uv](https://docs.astral.sh/uv/), with no containers. Use it for development and debugging. The Dockerfiles use the same tool and the same `uv.lock`. -## Prerequisites +## Prepare the tools -- Python 3.12 or later -- Poetry 2.0 or later -- Redis 7.0 or later -- Git - -## Installation Steps - -### Step 1: Install Python 3.12 +You need Git, uv and Redis. `pyproject.toml` needs Python 3.12 or 3.13, and uv downloads a suitable Python if the host has none. === "Ubuntu/Debian" ```bash - sudo apt update - sudo apt install python3.12 python3.12-venv python3.12-dev + curl -LsSf https://astral.sh/uv/install.sh | sh + sudo apt install redis-server + sudo systemctl enable --now redis-server ``` === "macOS" ```bash - brew install python@3.12 - ``` - -=== "Windows" - - Download from [python.org](https://www.python.org/downloads/) or use: - ```powershell - winget install Python.Python.3.12 + brew install uv redis + brew services start redis ``` -### Step 2: Install Poetry +You can run Redis in Docker instead: ```bash -curl -sSL https://install.python-poetry.org | python3 - +docker run -d --name redis -p 6379:6379 redis:7.4-alpine +``` -# Add to PATH (add to ~/.bashrc or ~/.zshrc) -export PATH="$HOME/.local/bin:$PATH" +The server needs plain Redis and no modules. Check it with: -# Verify installation -poetry --version +```bash +redis-cli ping ``` -### Step 3: Install Redis +Links that process audio need FFmpeg and SoX, which the conserver image installs: === "Ubuntu/Debian" ```bash - sudo apt install redis-server - sudo systemctl enable redis-server - sudo systemctl start redis-server + sudo apt install ffmpeg sox libsox-fmt-all ``` === "macOS" ```bash - brew install redis - brew services start redis - ``` - -=== "Docker" - - ```bash - docker run -d --name redis -p 6379:6379 redis:7 + brew install ffmpeg sox ``` -Verify Redis is running: - -```bash -redis-cli ping -# Should return: PONG -``` - -### Step 4: Clone Repository +## Install the dependencies ```bash git clone https://github.com/vcon-dev/vcon-server.git cd vcon-server +uv venv --seed --python 3.12 +uv sync --group api --group conserver ``` -### Step 5: Install Dependencies - -```bash -poetry install -``` +`--seed` keeps `pip` in the environment. The server calls `pip` to install [dynamic modules](../extending/dynamic-modules.md), and `uv venv` leaves it out otherwise. -This installs all required Python packages in a virtual environment. +`uv sync` includes the `dev` group by default, which holds pytest. Add `--no-dev` to leave it out. The other groups in `pyproject.toml` are: -### Step 6: Configure Environment +| Group | Adds | +|---|---| +| `api` | FastAPI, uvicorn and the `storage` group | +| `conserver` | Link packages, `watchdog` and the `storage` group | +| `storage` | Clients for the common storage backends | +| `storage-milvus` | The Milvus client, for `storage.milvus` | +| `conserver-local` | `transformers`, for local models in `hugging_llm_link` | -Create a `.env` file: +## Set the environment ```bash cp .env.example .env ``` -Edit with your settings: +Change these lines in `.env`: ```bash -# Required REDIS_URL=redis://localhost:6379 CONSERVER_API_TOKEN=your-development-token - -# Optional: AI services -DEEPGRAM_KEY=your-key -OPENAI_API_KEY=your-key - -# Development settings -ENV=dev -LOG_LEVEL=DEBUG +CONSERVER_CONFIG_FILE=./config.yml +LOGGING_CONFIG_FILE=common/logging_dev.conf ``` -### Step 7: Configure Processing +The sample `LOGGING_CONFIG_FILE` points at a path that no longer exists, and the sample `CONSERVER_CONFIG_FILE` is empty. Either one stops the server. See the [environment reference](../reference/environment.md) for the rest. -Copy the example configuration: +The code imports from `common/`, `conserver/` and `api/` as top-level paths, so set `PYTHONPATH` in each shell. With these paths, `import vcon` loads `common/vcon.py`. ```bash -cp example_config.yml config.yml +export PYTHONPATH=.:common:conserver:api ``` -Point to it in your environment: +## Write the chain configuration -```bash -export CONSERVER_CONFIG_FILE=./config.yml -``` +Create `config.yml` with the small file on the [Docker page](docker.md#write-the-chain-configuration). Do not run `example_config.yml` unchanged, because its `imports` section stops the worker. -### Step 8: Run the Server +## Start the server -Start the conserver (processing worker): +Start the conserver: ```bash -poetry run python ./server/main.py +uv run python conserver/main.py ``` -In a separate terminal, start the API server: +In a second shell, with `PYTHONPATH` set, start the API: ```bash -poetry run uvicorn server.api:app --reload --host 0.0.0.0 --port 8000 +uv run uvicorn api:app --reload --host 0.0.0.0 --port 8000 ``` -### Step 9: Verify Installation +Check it: ```bash -# Check health curl http://localhost:8000/api/health - -# Check version curl http://localhost:8000/api/version ``` -## Development Mode +To send a first vCon, follow the [quick start](../getting-started/quick-start.md), and use `localhost` for the host. -### Auto-Reload +## Work on the code -For development, use watchdog for auto-reload on code changes: +Restart the conserver on code changes, as the Compose file does: ```bash -# Install watchdog -poetry add watchdog --group dev - -# Run with auto-reload -poetry run watchmedo auto-restart \ - --directory=./server \ - --pattern="*.py" \ - --recursive \ - -- python ./server/main.py +uv run watchmedo auto-restart -p '*.py' -R -- python conserver/main.py ``` -### Debug Logging - -Enable debug logging: +Run the tests from the repo root. `pytest.ini` sets the import paths, and it loads `.env.test` if you create one from `.env.test.example`. ```bash -export LOG_LEVEL=DEBUG -export LOGGING_CONFIG_FILE=./server/logging_dev.conf +uv run pytest # All tests +uv run pytest -m "not integration" # Skip integration tests +uv run pytest tests/core/test_vcon_redis.py # One file +uv run pytest conserver/links/tag # One link +uv run pytest --cov --cov-report=html # With coverage ``` -### Running Tests - -```bash -# Run all tests -poetry run pytest +Some tests need Redis at `REDIS_URL`, and some need provider keys. CI runs them in the Compose stack, and the [contributing guide](../contributing.md) covers that path. -# Run with verbose output -poetry run pytest -v - -# Run specific test file -poetry run pytest server/tests/test_api.py - -# Fast path: skip integration tests -poetry run pytest -m "not integration" - -# Run with coverage -poetry run pytest --cov --cov-report=html -``` - -## Installing Optional Dependencies - -### FFmpeg (for audio processing) - -=== "Ubuntu/Debian" - - ```bash - sudo apt install ffmpeg - ``` - -=== "macOS" - - ```bash - brew install ffmpeg - ``` - -### SoX (for audio manipulation) - -=== "Ubuntu/Debian" - - ```bash - sudo apt install sox libsox-fmt-all - ``` - -=== "macOS" - - ```bash - brew install sox - ``` - -## Storage Backend Setup - -### PostgreSQL - -=== "Ubuntu/Debian" - - ```bash - sudo apt install postgresql postgresql-contrib - sudo systemctl start postgresql - - # Create database - sudo -u postgres createuser vcon - sudo -u postgres createdb -O vcon vcon_server - ``` - -=== "macOS" - - ```bash - brew install postgresql@15 - brew services start postgresql@15 - - createuser vcon - createdb -O vcon vcon_server - ``` - -=== "Docker" - - ```bash - docker run -d --name postgres \ - -e POSTGRES_USER=vcon \ - -e POSTGRES_PASSWORD=vcon \ - -e POSTGRES_DB=vcon_server \ - -p 5432:5432 \ - postgres:15 - ``` - -### MongoDB - -=== "Ubuntu/Debian" - - ```bash - # Follow MongoDB installation guide for your Ubuntu version - # https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/ - ``` - -=== "macOS" - - ```bash - brew tap mongodb/brew - brew install mongodb-community - brew services start mongodb-community - ``` - -=== "Docker" - - ```bash - docker run -d --name mongo \ - -e MONGO_INITDB_ROOT_USERNAME=root \ - -e MONGO_INITDB_ROOT_PASSWORD=example \ - -p 27017:27017 \ - mongo:6 - ``` - -## Project Structure - -Understanding the project structure helps with development: +## Find your way around the repo ``` vcon-server/ -├── server/ -│ ├── __init__.py -│ ├── api.py # FastAPI application -│ ├── main.py # Worker entry point -│ ├── config.py # Configuration loading +├── api/ +│ └── api.py # FastAPI app +├── common/ # Shared by the API and the conserver +│ ├── config.py # YAML loading │ ├── settings.py # Environment settings -│ ├── vcon.py # vCon data model -│ ├── lib/ # Shared utilities -│ │ ├── vcon_redis.py # Redis operations -│ │ ├── logging_utils.py -│ │ └── ... +│ ├── vcon.py # The Vcon class that links use +│ ├── lib/ # VconRedis, VconQueue, metrics and helpers +│ └── storage/ # Storage adapters +├── conserver/ +│ ├── main.py # Worker entry point │ ├── links/ # Processing links -│ │ ├── analyze/ -│ │ ├── deepgram_link/ -│ │ ├── tag/ -│ │ └── ... -│ ├── storage/ # Storage adapters -│ │ ├── postgres/ -│ │ ├── mongo/ -│ │ ├── s3/ -│ │ └── ... -│ └── tests/ # Test files -├── docker/ -│ └── Dockerfile -├── scripts/ -│ └── install_conserver.sh -├── pyproject.toml # Poetry configuration -├── example_config.yml # Example configuration -└── .env.example # Example environment +│ └── tracers/ # Tracers +├── docker/ # Dockerfiles and the Redis wait script +├── scripts/ # Install scripts and the Redis migration tool +├── tests/ # Core and storage tests +├── docker-compose.yml +├── example_config.yml # Syntax catalogue, not a working configuration +├── pyproject.toml +└── uv.lock ``` -## IDE Setup +Each link and adapter keeps its tests beside its code. -### VS Code +## Set up your editor -Recommended extensions: +Point the editor at `.venv/bin/python` and add the same import paths. -- Python (Microsoft) -- Pylance -- Python Test Explorer - -Settings (`.vscode/settings.json`): +For VS Code, in `.vscode/settings.json`: ```json { "python.defaultInterpreterPath": "${workspaceFolder}/.venv/bin/python", - "python.testing.pytestEnabled": true, - "python.testing.pytestArgs": ["server/tests"], - "python.linting.enabled": true, - "python.linting.flake8Enabled": true + "python.analysis.extraPaths": ["common", "conserver", "api"], + "python.testing.pytestEnabled": true } ``` -### PyCharm - -1. Open the project folder -2. Configure Poetry interpreter: Settings > Project > Python Interpreter > Add > Poetry Environment -3. Mark `server` as Sources Root - -## Troubleshooting - -### Poetry Install Fails - -Clear cache and retry: - -```bash -poetry cache clear . --all -poetry install -``` - -### Redis Connection Refused - -Check Redis is running: - -```bash -redis-cli ping -``` +For PyCharm, select the `.venv` interpreter and mark `common`, `conserver` and `api` as Sources Root. -Check the URL in `.env`: +## Troubleshoot a manual install -```bash -REDIS_URL=redis://localhost:6379 -``` - -### Import Errors - -Ensure you're in the Poetry environment: - -```bash -poetry shell -python ./server/main.py -``` - -Or prefix commands with `poetry run`: - -```bash -poetry run python ./server/main.py -``` - -### Module Not Found - -Install missing dependencies: - -```bash -poetry install --all-extras -``` +| Symptom | Cause | Fix | +|---|---|---| +| `ModuleNotFoundError: No module named 'lib'` or `'settings'` | `PYTHONPATH` is not set | [Set the environment](#set-the-environment) | +| `ModuleNotFoundError: No module named 'fastapi'` | The `api` group is missing | Run `uv sync --group api --group conserver` | +| `FileNotFoundError: server/logging_dev.conf doesn't exist` | Sample `LOGGING_CONFIG_FILE` | [Set the environment](#set-the-environment) | +| `No module named pip` when a module installs | The environment was made without `--seed` | Remove `.venv` and repeat [the install](#install-the-dependencies) | +| `Connection refused` on Redis | Redis is down, or the URL is wrong | Run `redis-cli ping` and check `REDIS_URL` | +| An adapter fails to import | Its package group is missing | See the [storage adapter reference](../reference/storage-adapters/index.md#install-the-adapter-packages) | -## Next Steps +## Continue with these guides -- [Configuration Guide](../configuration/index.md) - Customize your setup -- [Creating Links](../extending/creating-links.md) - Develop custom processors -- [Running Tests](../operations/troubleshooting.md) - Test your changes +- [Configuration guide](../configuration/index.md) +- [Creating links](../extending/creating-links.md) +- [Contributing](../contributing.md) diff --git a/docs/installation/redis-migration.md b/docs/installation/redis-migration.md index 2598370d..d9897b21 100644 --- a/docs/installation/redis-migration.md +++ b/docs/installation/redis-migration.md @@ -33,13 +33,13 @@ volume, remove that volume, or flush the source database to make startup succeed ## Copy the owned data -Install this repository's Python dependencies. Set `REDIS_MIGRATION_SOURCE_URL` -and `REDIS_MIGRATION_TARGET_URL` using the deployment's secret-management method. -Do not put credential-bearing URLs on the command line or in a committed file. -Then, from the repository root: +Install this repository's Python dependencies with `uv sync`. Set +`REDIS_MIGRATION_SOURCE_URL` and `REDIS_MIGRATION_TARGET_URL` using the +deployment's secret-management method. Do not put credential-bearing URLs on the +command line or in a committed file. Then, from the repository root: ```sh -python scripts/migrate_redis_json.py --writers-stopped --match 'vcon:*' --match 'config:*' +uv run python scripts/migrate_redis_json.py --writers-stopped --match 'vcon:*' --match 'config:*' ``` Those patterns are examples, **not a complete application inventory**. Include the @@ -95,8 +95,8 @@ The existing API/TTL integration tests use REDIS_URL, which must point to a disposable test instance. They now fail if that service is unavailable. ```sh -pytest tests/core/test_plain_redis.py tests/core/test_redis_json_migration.py -pytest tests/core/test_vcon_redis.py tests/core/test_vcon_redis_ttl.py common/tests/test_api.py +uv run pytest tests/core/test_plain_redis.py tests/core/test_redis_json_migration.py +uv run pytest tests/core/test_vcon_redis.py tests/core/test_vcon_redis_ttl.py common/tests/test_api.py ``` JSON syntax errors remain visible errors. Missing keys still return None and batch diff --git a/docs/installation/upgrading.md b/docs/installation/upgrading.md index de355f8a..98e11440 100644 --- a/docs/installation/upgrading.md +++ b/docs/installation/upgrading.md @@ -1,340 +1,141 @@ -# Upgrading vCon Server +# Upgrade vCon Server -This guide covers upgrading vCon Server to newer versions safely. +This page moves a running server to newer code without losing queued work. -## Before You Upgrade +## Prepare for the upgrade -### 1. Check Release Notes +### Read the release notes -Review the release notes for your target version: +Check [GitHub Releases](https://github.com/vcon-dev/vcon-server/releases) for your target tag. Image tags follow Git tags, so `v2.0.9` publishes image tag `2.0.9`. List tags with `git tag --list`. -- [GitHub Releases](https://github.com/vcon-dev/vcon-server/releases) -- Breaking changes -- New features -- Deprecations - -### 2. Backup Your Data - -=== "Docker" - - ```bash - # Backup Redis data - docker compose exec redis redis-cli BGSAVE - docker cp vcon-server-redis-1:/data/dump.rdb ./backup/redis-dump.rdb - - # Backup configuration - cp .env ./backup/.env.bak - cp config.yml ./backup/config.yml.bak - - # Backup storage volumes - docker compose exec postgres pg_dump -U vcon vcon_server > ./backup/postgres.sql - ``` - -=== "Kubernetes" - - ```bash - # Backup ConfigMap - kubectl get configmap vcon-config -n vcon-server -o yaml > backup/configmap.yaml - - # Backup Secrets - kubectl get secret vcon-secrets -n vcon-server -o yaml > backup/secrets.yaml - - # Backup Redis data - kubectl exec -n vcon-server redis-0 -- redis-cli BGSAVE - kubectl cp vcon-server/redis-0:/data/dump.rdb ./backup/redis-dump.rdb - ``` - -### 3. Test in Staging - -Always test upgrades in a staging environment first: +To see what you run now: ```bash -# Clone production config to staging -cp .env .env.staging -# Edit .env.staging with staging settings - -# Run staging environment -docker compose -f docker-compose.staging.yml up -d +curl http://localhost:8000/api/version ``` -## Version Compatibility - -### vCon Format Compatibility - -| Server Version | vCon Format | -|---------------|-------------| -| 1.0.x | 0.0.1 | -| 1.1.x | 0.0.1 | - -### Breaking Changes by Version - -#### v1.0 to v1.1 - -**New Features:** +A local build reports `dev` unless you pass `VCON_SERVER_VERSION` at image build. -- Multi-worker support (`CONSERVER_WORKERS`) -- Parallel storage writes (`CONSERVER_PARALLEL_STORAGE`) -- Configurable start method (`CONSERVER_START_METHOD`) +### Check these breaking changes -**Breaking Changes:** +| Your deployment | Before you upgrade | +|---|---| +| Runs Redis Stack, or stores vCons as RedisJSON | Complete the [Redis migration](redis-migration.md). Old and new workers cannot share keys, and the plain Redis image cannot read a Stack volume | +| Sets `REDIS_EXTERNAL_PORT` or uses Redis Insight | Remove them. Compose publishes no Redis port now | +| Installs Python dependencies with another tool | Move to [uv](manual-installation.md#install-the-dependencies). `uv.lock` is the only lock file | +| Runs code from `server/` | Update paths: `api/api.py`, `conserver/main.py`, `common/` and `conserver/links/`. Custom modules import `lib.*` and `vcon`, as in [Creating links](../extending/creating-links.md) | +| Names a vendor transcription module | It still works through a redirect, with a warning in the log. Move to [`links.transcribe`](../reference/links/transcribe.md) | +| Has consumers that expect `vcon: "0.0.1"` | The server now writes `0.4.0`. Set [`EGRESS_FORMAT_VERSION`](../configuration/egress-compatibility.md) for them | -- None +The server normalizes legacy field names when it reads a vCon, so stored records keep working. -**Configuration Changes:** +### Back up your data -```bash -# New environment variables (optional) -CONSERVER_WORKERS=4 # Default: 1 -CONSERVER_PARALLEL_STORAGE=true # Default: true -CONSERVER_START_METHOD=fork # Default: platform default -``` +Follow [Backup and restore](../operations/backup-restore.md) for Redis, your storage backends, `.env` and `config.yml`. -## Upgrade Procedures +### Test on a second copy -### Docker Compose +Clone the repo to another folder, give it its own `.env` and `config.yml`, and run the upgrade there first. Use a different `CONSERVER_EXTERNAL_PORT`. Compose services share the `conserver` network by name, so run the test on another host if you can, and never point it at your production `REDIS_URL`. -#### Rolling Update (Zero Downtime) +## Upgrade a Compose deployment ```bash -# Pull latest code -git fetch origin -git checkout v1.1.0 # or desired version - -# Pull new images -docker compose pull +git fetch origin --tags +git checkout -# Rebuild if using local Dockerfile docker compose build --no-cache - -# Rolling restart (one at a time) docker compose up -d --no-deps api docker compose up -d --no-deps conserver ``` -#### Full Restart - -```bash -# Stop services -docker compose down - -# Pull latest code -git pull origin main - -# Rebuild and start -docker compose up -d --build -``` - -### Kubernetes +`up -d` recreates each service in turn, so the API drops requests for a moment and queued vCons wait in Redis. A worker that receives `SIGTERM` finishes its current vCon. The Compose file gives it `stop_grace_period: 5s`, so raise that if your chains run longer. -#### Rolling Update +## Upgrade a Kubernetes deployment ```bash -# Update image tag in deployment kubectl set image deployment/api \ - api=public.ecr.aws/r4g1k2s3/vcon-dev/vcon-server:v1.1.0 \ + api=public.ecr.aws/r4g1k2s3/vcon-dev/vcon-server-api: \ -n vcon-server kubectl set image deployment/worker \ - worker=public.ecr.aws/r4g1k2s3/vcon-dev/vcon-server:v1.1.0 \ + worker=public.ecr.aws/r4g1k2s3/vcon-dev/vcon-server-conserver: \ -n vcon-server -# Monitor rollout kubectl rollout status deployment/api -n vcon-server kubectl rollout status deployment/worker -n vcon-server ``` -#### Rollback +## Upgrade a manual install -```bash -# Rollback to previous version -kubectl rollout undo deployment/api -n vcon-server -kubectl rollout undo deployment/worker -n vcon-server - -# Rollback to specific revision -kubectl rollout undo deployment/api --to-revision=2 -n vcon-server -``` - -### Manual Installation +Stop the processes, then: ```bash -# Stop services -pkill -f "python ./server/main.py" -pkill -f "uvicorn server.api" - -# Backup current version -cp -r server server.bak - -# Pull latest code -git fetch origin -git checkout v1.1.0 - -# Update dependencies -poetry install - -# Start services -poetry run python ./server/main.py & -poetry run uvicorn server.api:app --host 0.0.0.0 --port 8000 & +git fetch origin --tags +git checkout +uv sync --group api --group conserver ``` -## Post-Upgrade Steps +Start them again as in [Start the server](manual-installation.md#start-the-server). -### 1. Verify Health +## Check the upgrade ```bash -# Check API health curl http://localhost:8000/api/health - -# Check version curl http://localhost:8000/api/version -``` - -### 2. Check Logs - -```bash -# Docker docker compose logs -f --tail=100 - -# Kubernetes -kubectl logs -f deployment/worker -n vcon-server -``` - -### 3. Verify Processing - -Submit a test vCon and verify it processes correctly: - -```bash -curl -X POST http://localhost:8000/api/vcon?ingress_lists=default \ - -H "Content-Type: application/json" \ - -H "x-conserver-api-token: $TOKEN" \ - -d '{"vcon": "0.0.1", "uuid": "upgrade-test-001", ...}' ``` -### 4. Update Configuration +Send a test vCon to a chain and confirm that it reaches storage. The [quick start](../getting-started/quick-start.md) has a sample body. -Review and update configuration for new features: +Then compare your configuration with the samples: ```bash -# Check for new configuration options -diff example_config.yml config.yml - -# Update .env for new environment variables diff .env.example .env ``` -## Rollback Procedures - -### Docker Compose - -```bash -# Stop current version -docker compose down - -# Checkout previous version -git checkout v1.0.0 - -# Start previous version -docker compose up -d --build -``` - -### Restore from Backup - -```bash -# Restore configuration -cp ./backup/.env.bak .env -cp ./backup/config.yml.bak config.yml - -# Restore Redis data -docker compose stop redis -docker cp ./backup/redis-dump.rdb vcon-server-redis-1:/data/dump.rdb -docker compose start redis +The [environment reference](../reference/environment.md) lists every variable the code reads. -# Restore PostgreSQL -docker compose exec -T postgres psql -U vcon vcon_server < ./backup/postgres.sql -``` +## Roll back an upgrade -## Database Migrations +=== "Compose" -Some upgrades may include database schema changes. - -### Check for Migrations + ```bash + docker compose down + git checkout + docker compose up -d --build + ``` -```bash -# View migration status (if using Alembic) -poetry run alembic current +=== "Kubernetes" -# Run pending migrations -poetry run alembic upgrade head -``` + ```bash + kubectl rollout undo deployment/api -n vcon-server + kubectl rollout undo deployment/worker -n vcon-server + ``` -### Manual Schema Updates +Restore data only if the upgrade changed it. See [Backup and restore](../operations/backup-restore.md). -If migrations aren't automated, apply changes manually: +After a Redis migration, the rollback rules are stricter. Read the end of [Verify and switch the application](redis-migration.md#verify-and-switch-the-application). -```sql --- Example: Add new column -ALTER TABLE vcons ADD COLUMN processed_at TIMESTAMP; -``` +## Change database schemas -## Troubleshooting Upgrades +The repo ships no migration tool. If the release notes name a schema change, apply it to your database by hand. -### Service Won't Start +## Troubleshoot an upgrade -Check for configuration errors: +Print the configuration the server loads: ```bash -# Validate configuration -poetry run python -c "from server.config import get_config; print(get_config())" - -# Check for missing environment variables -poetry run python -c "from server import settings; print(dir(settings))" +docker compose exec conserver python -c "from config import get_config; import json; print(json.dumps(get_config(), indent=2))" ``` -### Processing Stopped - -Check worker status: +Check a queue: ```bash -# Docker -docker compose logs conserver --tail=100 - -# Check Redis queues -docker compose exec redis redis-cli LLEN default +docker compose exec redis redis-cli LLEN ``` -### API Errors +Read the API's own schema at `http://localhost:8000/api/docs`, or the [API reference](../reference/api.md). See [Troubleshooting](../operations/troubleshooting.md) for other faults. -Check for breaking API changes: - -```bash -# View API docs -curl http://localhost:8000/api/docs - -# Check for deprecation warnings in logs -docker compose logs api | grep -i deprecat -``` +## Get help -## Upgrade Checklist - -- [ ] Review release notes for target version -- [ ] Backup all data (Redis, databases, configuration) -- [ ] Test upgrade in staging environment -- [ ] Schedule maintenance window (if needed) -- [ ] Notify users of planned downtime (if any) -- [ ] Perform upgrade -- [ ] Verify health endpoints -- [ ] Check logs for errors -- [ ] Test processing pipeline -- [ ] Update monitoring/alerting thresholds -- [ ] Document any issues encountered - -## Getting Help - -If you encounter issues during upgrade: - -1. Check [GitHub Issues](https://github.com/vcon-dev/vcon-server/issues) -2. Review [Troubleshooting Guide](../operations/troubleshooting.md) -3. Open a new issue with: - - Current version - - Target version - - Error messages - - Configuration (redacted) +Search [GitHub Issues](https://github.com/vcon-dev/vcon-server/issues). If you open a new issue, give your current and target versions, the error messages and your configuration with secrets removed. diff --git a/docs/operations/api-reference.md b/docs/operations/api-reference.md deleted file mode 100644 index b38d8b67..00000000 --- a/docs/operations/api-reference.md +++ /dev/null @@ -1,716 +0,0 @@ -# API Reference - -Complete reference for all vCon Server REST API endpoints. - -## Base URL - -``` -http://localhost:8000/api -``` - -The base path can be configured with `API_ROOT_PATH` environment variable. - -## Authentication - -All endpoints (except health) require authentication via header: - -```bash -curl -H "x-conserver-api-token: your-token" ... -``` - -Header name configurable via `CONSERVER_HEADER_NAME`. - -## System Endpoints - -### Health Check - -Check if the API server is healthy. - -```http -GET /health -``` - -**Authentication:** Not required - -**Response:** - -```json -{ - "status": "healthy" -} -``` - -**Example:** - -```bash -curl http://localhost:8000/api/health -``` - -### Version - -Get server version information. - -```http -GET /version -``` - -**Authentication:** Not required - -**Response:** - -```json -{ - "version": "2024.01.15", - "git_commit": "a1b2c3d", - "build_time": "2024-01-15T10:30:00Z" -} -``` - -**Example:** - -```bash -curl http://localhost:8000/api/version -``` - -## vCon Endpoints - -### List vCons - -Get a paginated list of vCon UUIDs. - -```http -GET /vcon -``` - -**Query Parameters:** - -| Parameter | Type | Default | Description | -|-----------|------|---------|-------------| -| `page` | int | 1 | Page number | -| `size` | int | 100 | Items per page | -| `since` | datetime | - | Filter by created_at >= | -| `until` | datetime | - | Filter by created_at <= | - -**Response:** - -```json -{ - "vcons": ["uuid-1", "uuid-2", "uuid-3"], - "page": 1, - "size": 100, - "total": 250 -} -``` - -**Example:** - -```bash -curl "http://localhost:8000/api/vcon?page=1&size=50" \ - -H "x-conserver-api-token: $TOKEN" -``` - -### Get vCon - -Retrieve a specific vCon by UUID. - -```http -GET /vcon/{vcon_uuid} -``` - -**Path Parameters:** - -| Parameter | Description | -|-----------|-------------| -| `vcon_uuid` | vCon UUID | - -**Response:** Full vCon JSON object - -**Example:** - -```bash -curl http://localhost:8000/api/vcon/abc-123-def \ - -H "x-conserver-api-token: $TOKEN" -``` - -**Notes:** - -- If not in Redis cache, syncs from storage backends -- Returns 404 if not found in any storage - -### Create vCon - -Create or update a vCon. - -```http -POST /vcon -``` - -**Query Parameters:** - -| Parameter | Type | Description | -|-----------|------|-------------| -| `ingress_lists` | string | Comma-separated list of ingress queues | - -**Request Body:** vCon JSON object - -**Response:** - -```json -{ - "uuid": "abc-123-def", - "status": "created" -} -``` - -**Cache Expiry:** - -Created vCons are stored in Redis with a default TTL of `VCON_REDIS_EXPIRY` seconds (default: 3600 seconds / 1 hour). After this time, the vCon will be automatically removed from Redis cache. - -!!! tip "Persisting vCons" - To retain vCons beyond the cache expiry, configure a storage backend (S3, PostgreSQL, etc.) in your processing chain. Use the `ingress_lists` parameter to add vCons to a chain that includes storage. - -**Example:** - -```bash -curl -X POST "http://localhost:8000/api/vcon?ingress_lists=default" \ - -H "Content-Type: application/json" \ - -H "x-conserver-api-token: $TOKEN" \ - -d '{ - "vcon": "0.0.1", - "uuid": "abc-123-def", - "created_at": "2024-01-15T10:30:00Z", - "parties": [ - {"tel": "+15551234567"} - ], - "dialog": [] - }' -``` - -### Batch Get vCons - -Retrieve multiple vCons by UUID. - -```http -GET /vcons -``` - -**Query Parameters:** - -| Parameter | Type | Description | -|-----------|------|-------------| -| `uuids` | string | Comma-separated UUIDs | - -**Response:** Array of vCon objects - -**Example:** - -```bash -curl "http://localhost:8000/api/vcons?uuids=uuid-1,uuid-2,uuid-3" \ - -H "x-conserver-api-token: $TOKEN" -``` - -### Delete vCon - -Delete a vCon from Redis and all storage backends. - -```http -DELETE /vcon/{vcon_uuid} -``` - -**Path Parameters:** - -| Parameter | Description | -|-----------|-------------| -| `vcon_uuid` | vCon UUID | - -**Response:** - -```json -{ - "uuid": "abc-123-def", - "status": "deleted" -} -``` - -**Example:** - -```bash -curl -X DELETE http://localhost:8000/api/vcon/abc-123-def \ - -H "x-conserver-api-token: $TOKEN" -``` - -## Search Endpoints - -### Search vCons - -Search vCons by metadata. - -```http -GET /vcons/search -``` - -**Query Parameters:** - -| Parameter | Type | Description | -|-----------|------|-------------| -| `tel` | string | Phone number (partial match) | -| `mailto` | string | Email address (partial match) | -| `name` | string | Party name (partial match) | - -**Response:** - -```json -{ - "vcons": ["uuid-1", "uuid-2"], - "count": 2 -} -``` - -**Example:** - -```bash -# Search by phone -curl "http://localhost:8000/api/vcons/search?tel=+1555" \ - -H "x-conserver-api-token: $TOKEN" - -# Search by email -curl "http://localhost:8000/api/vcons/search?mailto=@example.com" \ - -H "x-conserver-api-token: $TOKEN" - -# Combined search (AND logic) -curl "http://localhost:8000/api/vcons/search?tel=+1555&name=John" \ - -H "x-conserver-api-token: $TOKEN" -``` - -## Chain Processing Endpoints - -### Ingress - -Add vCon UUIDs to a processing chain. - -```http -POST /vcon/ingress -``` - -**Query Parameters:** - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `ingress_list` | string | Yes | Ingress queue name | - -**Request Body:** - -```json -{ - "uuids": ["uuid-1", "uuid-2"] -} -``` - -**Response:** - -```json -{ - "queued": 2, - "ingress_list": "default" -} -``` - -**Example:** - -```bash -curl -X POST "http://localhost:8000/api/vcon/ingress?ingress_list=default" \ - -H "Content-Type: application/json" \ - -H "x-conserver-api-token: $TOKEN" \ - -d '{"uuids": ["uuid-1", "uuid-2"]}' -``` - -### Egress - -Remove vCon UUIDs from a chain's output. - -```http -GET /vcon/egress -``` - -**Query Parameters:** - -| Parameter | Type | Default | Description | -|-----------|------|---------|-------------| -| `egress_list` | string | Required | Egress queue name | -| `limit` | int | 10 | Maximum items to return | - -**Response:** - -```json -{ - "uuids": ["uuid-1", "uuid-2"], - "count": 2, - "egress_list": "processed" -} -``` - -**Example:** - -```bash -curl "http://localhost:8000/api/vcon/egress?egress_list=processed&limit=5" \ - -H "x-conserver-api-token: $TOKEN" -``` - -### Count - -Count vCons in an egress list. - -```http -GET /vcon/count -``` - -**Query Parameters:** - -| Parameter | Type | Description | -|-----------|------|-------------| -| `egress_list` | string | Egress queue name | - -**Response:** - -```json -{ - "count": 42, - "egress_list": "processed" -} -``` - -**Example:** - -```bash -curl "http://localhost:8000/api/vcon/count?egress_list=processed" \ - -H "x-conserver-api-token: $TOKEN" -``` - -## External Ingress - -### External Ingress - -Submit vCons from external partners with scoped authentication. - -```http -POST /vcon/external-ingress -``` - -**Query Parameters:** - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `ingress_list` | string | Yes | Ingress queue (must match ingress_auth config) | - -**Authentication:** Ingress-specific API key (configured in `ingress_auth`) - -**Request Body:** vCon JSON object - -**Response:** - -```json -{ - "uuid": "abc-123-def", - "status": "queued", - "ingress_list": "partner_input" -} -``` - -**Cache Expiry:** - -Submitted vCons are stored in Redis with a default TTL of `VCON_REDIS_EXPIRY` seconds (default: 3600 seconds / 1 hour). The vCon is automatically queued in the specified ingress list for processing, which should include a storage step if long-term retention is required. - -**Example:** - -```bash -curl -X POST "http://localhost:8000/api/vcon/external-ingress?ingress_list=partner_input" \ - -H "Content-Type: application/json" \ - -H "x-conserver-api-token: partner-specific-key" \ - -d '{"vcon": "0.0.1", "uuid": "...", ...}' -``` - -## Dead Letter Queue Endpoints - -### List DLQ - -Get vCons in the dead letter queue. - -```http -GET /dlq -``` - -**Query Parameters:** - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `ingress_list` | string | Yes | Original ingress list | - -**Response:** - -```json -{ - "uuids": ["uuid-1", "uuid-2"], - "count": 2, - "dlq_name": "DLQ:default" -} -``` - -**Example:** - -```bash -curl "http://localhost:8000/api/dlq?ingress_list=default" \ - -H "x-conserver-api-token: $TOKEN" -``` - -### Reprocess DLQ - -Move items from DLQ back to ingress for retry. - -```http -POST /dlq/reprocess -``` - -**Query Parameters:** - -| Parameter | Type | Required | Description | -|-----------|------|----------|-------------| -| `ingress_list` | string | Yes | Original ingress list | - -**Response:** - -```json -{ - "reprocessed": 5, - "ingress_list": "default" -} -``` - -**Example:** - -```bash -curl -X POST "http://localhost:8000/api/dlq/reprocess?ingress_list=default" \ - -H "x-conserver-api-token: $TOKEN" -``` - -## Configuration Endpoints - -### Get Configuration - -Retrieve current server configuration. - -```http -GET /config -``` - -**Response:** Full configuration object - -**Example:** - -```bash -curl http://localhost:8000/api/config \ - -H "x-conserver-api-token: $TOKEN" | jq . -``` - -### Update Configuration - -Update server configuration. - -```http -POST /config -``` - -**Request Body:** Configuration object (partial updates supported) - -**Example:** - -```bash -curl -X POST http://localhost:8000/api/config \ - -H "Content-Type: application/json" \ - -H "x-conserver-api-token: $TOKEN" \ - -d '{"chains": {...}}' -``` - -!!! warning "Configuration Updates" - Configuration updates may require service restart to take full effect. - -### Rebuild Index - -Rebuild the vCon search index. - -```http -GET /index_vcons -``` - -**Response:** - -```json -{ - "status": "indexing", - "count": 1000 -} -``` - -**Example:** - -```bash -curl http://localhost:8000/api/index_vcons \ - -H "x-conserver-api-token: $TOKEN" -``` - -## Error Responses - -### 400 Bad Request - -Invalid request format or parameters. - -```json -{ - "detail": "Invalid UUID format" -} -``` - -### 403 Forbidden - -Authentication failed. - -```json -{ - "detail": "Invalid or missing API token" -} -``` - -### 404 Not Found - -Resource not found. - -```json -{ - "detail": "vCon not found: abc-123" -} -``` - -### 500 Internal Server Error - -Server error. - -```json -{ - "detail": "Internal server error" -} -``` - -## Rate Limiting - -Rate limiting should be configured at the reverse proxy level: - -```nginx -# nginx.conf -limit_req_zone $binary_remote_addr zone=api:10m rate=100r/s; - -server { - location /api { - limit_req zone=api burst=200 nodelay; - proxy_pass http://api:8000; - } -} -``` - -## SDK Examples - -### Python - -```python -import requests - -class VconClient: - def __init__(self, base_url, token): - self.base_url = base_url - self.headers = {"x-conserver-api-token": token} - - def get_vcon(self, uuid): - response = requests.get( - f"{self.base_url}/vcon/{uuid}", - headers=self.headers - ) - response.raise_for_status() - return response.json() - - def create_vcon(self, vcon, ingress_list=None): - params = {"ingress_lists": ingress_list} if ingress_list else {} - response = requests.post( - f"{self.base_url}/vcon", - headers=self.headers, - params=params, - json=vcon - ) - response.raise_for_status() - return response.json() - - def search(self, tel=None, mailto=None, name=None): - params = {k: v for k, v in { - "tel": tel, "mailto": mailto, "name": name - }.items() if v} - response = requests.get( - f"{self.base_url}/vcons/search", - headers=self.headers, - params=params - ) - response.raise_for_status() - return response.json() - -# Usage -client = VconClient("http://localhost:8000/api", "your-token") -vcon = client.get_vcon("abc-123") -results = client.search(tel="+1555") -``` - -### JavaScript - -```javascript -class VconClient { - constructor(baseUrl, token) { - this.baseUrl = baseUrl; - this.headers = { - 'x-conserver-api-token': token, - 'Content-Type': 'application/json' - }; - } - - async getVcon(uuid) { - const response = await fetch(`${this.baseUrl}/vcon/${uuid}`, { - headers: this.headers - }); - if (!response.ok) throw new Error(`HTTP ${response.status}`); - return response.json(); - } - - async createVcon(vcon, ingressList = null) { - const url = new URL(`${this.baseUrl}/vcon`); - if (ingressList) url.searchParams.set('ingress_lists', ingressList); - - const response = await fetch(url, { - method: 'POST', - headers: this.headers, - body: JSON.stringify(vcon) - }); - if (!response.ok) throw new Error(`HTTP ${response.status}`); - return response.json(); - } - - async search({ tel, mailto, name } = {}) { - const url = new URL(`${this.baseUrl}/vcons/search`); - if (tel) url.searchParams.set('tel', tel); - if (mailto) url.searchParams.set('mailto', mailto); - if (name) url.searchParams.set('name', name); - - const response = await fetch(url, { headers: this.headers }); - if (!response.ok) throw new Error(`HTTP ${response.status}`); - return response.json(); - } -} - -// Usage -const client = new VconClient('http://localhost:8000/api', 'your-token'); -const vcon = await client.getVcon('abc-123'); -const results = await client.search({ tel: '+1555' }); -``` diff --git a/docs/operations/backup-restore.md b/docs/operations/backup-restore.md index fe149410..2f0d73a1 100644 --- a/docs/operations/backup-restore.md +++ b/docs/operations/backup-restore.md @@ -1,38 +1,20 @@ -# Backup and Restore +# Back up and restore data -This guide covers backup strategies and recovery procedures for vCon Server. +This page covers what to back up and how to restore it, using the services in `docker-compose.yml`. -## What to Backup +## Decide what to back up -| Component | Priority | Frequency | Method | -|-----------|----------|-----------|--------| -| Configuration | Critical | On change | File copy | -| Redis data | High | Daily | RDB/AOF | -| Storage backends | High | Daily | Native tools | -| vCon data | High | Continuous | Storage replication | +| Component | Holds | Priority | Method | +|-----------|-------|----------|--------| +| Configuration | `.env`, `config.yml`, `docker-compose.yml` | Critical | File copy on each change | +| Storage backends | Your durable vCons | High | The backend's own tools | +| Redis | Queues, DLQs, search indexes and vCon bodies still inside their TTL | High | Archive of the data directory | -## Configuration Backup +Redis is a working store. A vCon body stays there for a limited time, so the storage backends named in your chains hold the long-term copy. A vCon in a queue or a DLQ may exist only in Redis, which is why Redis still needs a backup. -### Environment Files +Backups hold conversation data, and `.env` holds secrets. [Encrypt them](#protect-the-backups). -```bash -# Backup -cp .env ./backups/.env.$(date +%Y%m%d) -cp config.yml ./backups/config.yml.$(date +%Y%m%d) - -# Restore -cp ./backups/.env.20240115 .env -cp ./backups/config.yml.20240115 config.yml -``` - -### Docker Compose - -```bash -# Backup -cp docker-compose.yml ./backups/docker-compose.yml.$(date +%Y%m%d) -``` - -### Automated Config Backup +## Back up the configuration ```bash #!/bin/bash @@ -46,184 +28,115 @@ cp .env "$BACKUP_DIR/.env.$DATE" cp config.yml "$BACKUP_DIR/config.yml.$DATE" cp docker-compose.yml "$BACKUP_DIR/docker-compose.yml.$DATE" -# Keep last 30 days +# Keep the last 30 days find "$BACKUP_DIR" -type f -mtime +30 -delete - -echo "Configuration backed up to $BACKUP_DIR" ``` -## Redis Backup +To restore, copy the files back and run `docker compose up -d`. `POST /config` also rewrites the config file, so take a copy after any change made that way. -### RDB Snapshot +## Back up Redis -```bash -# Trigger snapshot -docker compose exec redis redis-cli BGSAVE - -# Wait for completion -docker compose exec redis redis-cli LASTSAVE - -# Copy snapshot -docker cp vcon-server-redis-1:/data/dump.rdb ./backups/redis-dump.$(date +%Y%m%d).rdb -``` +The `redis` service runs with `--appendonly yes`, so its data lives in `/data/appendonlydir/` on the `redis_data` volume, beside a `dump.rdb` snapshot. Back up the whole directory. -### AOF Backup - -If using AOF persistence: +!!! warning "A dump.rdb alone does not restore this service" + With `appendonly yes`, Redis loads the AOF files at startup and ignores `dump.rdb`. Copying a dump into place leaves the old data in Redis. If the AOF directory is missing too, Redis starts empty. ```bash -# Rewrite AOF -docker compose exec redis redis-cli BGREWRITEAOF - -# Copy AOF file -docker cp vcon-server-redis-1:/data/appendonly.aof ./backups/ -``` +# Compact the AOF files +docker compose exec -T redis redis-cli BGREWRITEAOF -### Automated Redis Backup +# Wait until this prints aof_rewrite_in_progress:0 +docker compose exec -T redis redis-cli INFO persistence | grep aof_rewrite_in_progress -```bash -#!/bin/bash -# backup-redis.sh -BACKUP_DIR="./backups/redis" -DATE=$(date +%Y%m%d_%H%M%S) - -mkdir -p "$BACKUP_DIR" - -# Trigger background save -docker compose exec -T redis redis-cli BGSAVE - -# Wait for save to complete (max 60 seconds) -for i in {1..60}; do - if docker compose exec -T redis redis-cli LASTSAVE | grep -q "$(date +%s)"; then - break - fi - sleep 1 -done - -# Copy snapshot -docker cp vcon-server-redis-1:/data/dump.rdb "$BACKUP_DIR/dump.$DATE.rdb" - -# Compress -gzip "$BACKUP_DIR/dump.$DATE.rdb" - -# Keep last 7 days -find "$BACKUP_DIR" -name "*.rdb.gz" -mtime +7 -delete - -echo "Redis backed up to $BACKUP_DIR/dump.$DATE.rdb.gz" +# Archive the data directory +docker compose exec -T redis tar -czf - -C /data . > ./backups/redis-data.$(date +%Y%m%d).tar.gz ``` ### Restore Redis ```bash -# Stop services -docker compose stop conserver api +# Stop everything that uses Redis, then Redis itself +docker compose stop conserver api redis + +# Replace the data directory +docker compose run --rm --no-deps -T -v "$PWD/backups:/backup:ro" --entrypoint sh redis \ + -c 'rm -rf /data/* && tar -xzf /backup/redis-data.20260115.tar.gz -C /data' -# Replace dump file -docker cp ./backups/redis-dump.20240115.rdb vcon-server-redis-1:/data/dump.rdb +# Start Redis and check it +docker compose start redis +docker compose exec -T redis redis-cli DBSIZE -# Restart Redis -docker compose restart redis +# List any replay lock captured in the backup +docker compose exec -T redis redis-cli --scan --pattern 'DLQ:storage:*:replay-lock' +# After confirming no replay can be running, delete each one: redis-cli DEL -# Start services docker compose start conserver api ``` -## PostgreSQL Backup +These commands were tested on the `redis:7.4-alpine` image with the same server flags as `docker-compose.yml`. + +A restore brings back the queues as they stood at backup time. vCons that finished after the backup may run through their chains again, and TTLs carry on from their stored expiry times. A replay lock in the archive blocks that backend's replay until you delete it. See [Recover the replay lock](storage-recovery.md#recover-the-replay-lock). + +## Back up PostgreSQL -### pg_dump +Use the user and database from your `postgres` storage options. The adapter defaults to database `vcon_db`, and the Compose `postgres` service creates user `postgres` and database `postgres`. See the [PostgreSQL adapter reference](../reference/storage-adapters/postgres.md). ```bash -# Backup -docker compose exec postgres pg_dump -U vcon vcon_server > ./backups/postgres-$(date +%Y%m%d).sql +PG_USER=postgres +PG_DB=vcon_db -# Compressed backup -docker compose exec postgres pg_dump -U vcon vcon_server | gzip > ./backups/postgres-$(date +%Y%m%d).sql.gz +docker compose exec -T postgres pg_dump -U "$PG_USER" "$PG_DB" | gzip > ./backups/postgres-$(date +%Y%m%d).sql.gz ``` ### Restore PostgreSQL +Stop the workers and the API first, so nothing holds a connection. + ```bash -# Drop and recreate database -docker compose exec postgres psql -U vcon -c "DROP DATABASE IF EXISTS vcon_server;" -docker compose exec postgres psql -U vcon -c "CREATE DATABASE vcon_server;" +docker compose stop conserver api + +docker compose exec -T postgres psql -U "$PG_USER" -d template1 -c "DROP DATABASE IF EXISTS $PG_DB;" +docker compose exec -T postgres psql -U "$PG_USER" -d template1 -c "CREATE DATABASE $PG_DB;" -# Restore -docker compose exec -T postgres psql -U vcon vcon_server < ./backups/postgres-20240115.sql +gunzip -c ./backups/postgres-20260115.sql.gz | docker compose exec -T postgres psql -U "$PG_USER" "$PG_DB" -# Or from compressed -gunzip -c ./backups/postgres-20240115.sql.gz | docker compose exec -T postgres psql -U vcon vcon_server +docker compose start conserver api ``` -## MongoDB Backup +## Back up MongoDB -### mongodump +`docker-compose.yml` has no MongoDB service, so run these where the tools can reach your server. The adapter defaults to database `conserver`. See the [MongoDB adapter reference](../reference/storage-adapters/mongo.md). ```bash -# Backup -docker compose exec mongo mongodump \ - --username root \ - --password example \ - --authenticationDatabase admin \ - --db conserver \ - --out /tmp/backup - -# Copy from container -docker cp vcon-server-mongo-1:/tmp/backup ./backups/mongo-$(date +%Y%m%d) +mongodump --uri "$MONGO_URL" --db conserver --out ./backups/mongo-$(date +%Y%m%d) ``` ### Restore MongoDB ```bash -# Copy to container -docker cp ./backups/mongo-20240115 vcon-server-mongo-1:/tmp/restore - -# Restore -docker compose exec mongo mongorestore \ - --username root \ - --password example \ - --authenticationDatabase admin \ - --db conserver \ - /tmp/restore/conserver +mongorestore --uri "$MONGO_URL" --db conserver ./backups/mongo-20260115/conserver ``` -## S3 Backup - -### Cross-Region Replication - -Configure S3 bucket replication for disaster recovery: - -```json -{ - "Rules": [ - { - "ID": "BackupRule", - "Status": "Enabled", - "Destination": { - "Bucket": "arn:aws:s3:::backup-bucket", - "StorageClass": "STANDARD_IA" - } - } - ] -} -``` - -### S3 Sync +## Back up S3 ```bash -# Backup to another bucket +# Copy to another bucket aws s3 sync s3://vcon-bucket s3://vcon-backup-bucket -# Backup to local +# Copy to local disk aws s3 sync s3://vcon-bucket ./backups/s3-$(date +%Y%m%d) ``` -## Elasticsearch Backup +For disaster recovery, configure bucket replication in AWS. + +## Back up Elasticsearch -### Snapshot Repository +A filesystem snapshot repository needs `path.repo` set on the Elasticsearch node, and the Compose service does not set it. That service also has security on, so pass credentials. Its values are for development only. ```bash -# Create repository -curl -X PUT "localhost:9200/_snapshot/backup" -H 'Content-Type: application/json' -d' +# Create the repository +curl -u "elastic:$ELASTIC_PASSWORD" -X PUT "localhost:9200/_snapshot/backup" \ + -H 'Content-Type: application/json' -d' { "type": "fs", "settings": { @@ -231,21 +144,27 @@ curl -X PUT "localhost:9200/_snapshot/backup" -H 'Content-Type: application/json } }' -# Create snapshot -curl -X PUT "localhost:9200/_snapshot/backup/snapshot_$(date +%Y%m%d)" +# Create a snapshot +curl -u "elastic:$ELASTIC_PASSWORD" -X PUT "localhost:9200/_snapshot/backup/snapshot_$(date +%Y%m%d)" ``` -### Restore Snapshot +### Restore a snapshot ```bash -# List snapshots -curl "localhost:9200/_snapshot/backup/_all" +# List the snapshots +curl -u "elastic:$ELASTIC_PASSWORD" "localhost:9200/_snapshot/backup/_all" -# Restore -curl -X POST "localhost:9200/_snapshot/backup/snapshot_20240115/_restore" +# Restore one +curl -u "elastic:$ELASTIC_PASSWORD" -X POST "localhost:9200/_snapshot/backup/snapshot_20260115/_restore" ``` -## Complete Backup Script +## Back up the other backends + +Use each system's own tools. The [storage adapter reference](../reference/storage-adapters/index.md) shows where each adapter writes. + +## Script a full backup + +This script covers the configuration, Redis and a Compose PostgreSQL. Add your other backends. ```bash #!/bin/bash @@ -256,51 +175,37 @@ set -e BACKUP_BASE="./backups" DATE=$(date +%Y%m%d_%H%M%S) BACKUP_DIR="$BACKUP_BASE/$DATE" +PG_USER="${PG_USER:-postgres}" +PG_DB="${PG_DB:-vcon_db}" -echo "Starting full backup to $BACKUP_DIR" mkdir -p "$BACKUP_DIR" -# 1. Configuration echo "Backing up configuration..." -cp .env "$BACKUP_DIR/" -cp config.yml "$BACKUP_DIR/" -cp docker-compose.yml "$BACKUP_DIR/" +cp .env config.yml docker-compose.yml "$BACKUP_DIR/" -# 2. Redis echo "Backing up Redis..." -docker compose exec -T redis redis-cli BGSAVE -sleep 5 # Wait for save -docker cp vcon-server-redis-1:/data/dump.rdb "$BACKUP_DIR/redis-dump.rdb" +docker compose exec -T redis redis-cli BGREWRITEAOF +until docker compose exec -T redis redis-cli INFO persistence | grep -q "aof_rewrite_in_progress:0"; do + sleep 1 +done +docker compose exec -T redis tar -czf - -C /data . > "$BACKUP_DIR/redis-data.tar.gz" -# 3. PostgreSQL (if used) -if docker compose ps postgres | grep -q "running"; then +if [ -n "$(docker compose ps -q postgres)" ]; then echo "Backing up PostgreSQL..." - docker compose exec -T postgres pg_dump -U vcon vcon_server > "$BACKUP_DIR/postgres.sql" + docker compose exec -T postgres pg_dump -U "$PG_USER" "$PG_DB" > "$BACKUP_DIR/postgres.sql" fi -# 4. MongoDB (if used) -if docker compose ps mongo | grep -q "running"; then - echo "Backing up MongoDB..." - docker compose exec -T mongo mongodump \ - --username root --password example \ - --authenticationDatabase admin \ - --db conserver --out /tmp/mongodump - docker cp vcon-server-mongo-1:/tmp/mongodump "$BACKUP_DIR/mongo" -fi +echo "Compressing..." +tar -czf "$BACKUP_BASE/$DATE.tar.gz" -C "$BACKUP_BASE" "$DATE" +rm -rf "$BACKUP_DIR" -# 5. Compress -echo "Compressing backup..." -cd "$BACKUP_BASE" -tar -czf "$DATE.tar.gz" "$DATE" -rm -rf "$DATE" - -# 6. Cleanup old backups (keep 7 days) -find "$BACKUP_BASE" -name "*.tar.gz" -mtime +7 -delete +# Keep the last 7 days +find "$BACKUP_BASE" -maxdepth 1 -name "*.tar.gz" -mtime +7 -delete echo "Backup complete: $BACKUP_BASE/$DATE.tar.gz" ``` -## Complete Restore Script +## Script a full restore ```bash #!/bin/bash @@ -309,139 +214,98 @@ echo "Backup complete: $BACKUP_BASE/$DATE.tar.gz" set -e BACKUP_FILE="${1:?Usage: $0 }" +PG_USER="${PG_USER:-postgres}" +PG_DB="${PG_DB:-vcon_db}" -if [ ! -f "$BACKUP_FILE" ]; then - echo "Backup file not found: $BACKUP_FILE" - exit 1 -fi - -echo "Restoring from $BACKUP_FILE" - -# Extract backup RESTORE_DIR=$(mktemp -d) tar -xzf "$BACKUP_FILE" -C "$RESTORE_DIR" -BACKUP_DIR=$(ls "$RESTORE_DIR") +BACKUP_DIR="$RESTORE_DIR/$(ls "$RESTORE_DIR")" -# Stop services echo "Stopping services..." -docker compose stop conserver api +docker compose stop conserver api redis -# 1. Configuration echo "Restoring configuration..." -cp "$RESTORE_DIR/$BACKUP_DIR/.env" .env -cp "$RESTORE_DIR/$BACKUP_DIR/config.yml" config.yml +cp "$BACKUP_DIR/.env" .env +cp "$BACKUP_DIR/config.yml" config.yml -# 2. Redis echo "Restoring Redis..." -docker cp "$RESTORE_DIR/$BACKUP_DIR/redis-dump.rdb" vcon-server-redis-1:/data/dump.rdb -docker compose restart redis +docker compose run --rm --no-deps -T -v "$BACKUP_DIR:/backup:ro" --entrypoint sh redis \ + -c 'rm -rf /data/* && tar -xzf /backup/redis-data.tar.gz -C /data' +docker compose start redis -# 3. PostgreSQL -if [ -f "$RESTORE_DIR/$BACKUP_DIR/postgres.sql" ]; then +if [ -f "$BACKUP_DIR/postgres.sql" ]; then echo "Restoring PostgreSQL..." - docker compose exec -T postgres psql -U vcon -c "DROP DATABASE IF EXISTS vcon_server;" - docker compose exec -T postgres psql -U vcon -c "CREATE DATABASE vcon_server;" - docker compose exec -T postgres psql -U vcon vcon_server < "$RESTORE_DIR/$BACKUP_DIR/postgres.sql" -fi - -# 4. MongoDB -if [ -d "$RESTORE_DIR/$BACKUP_DIR/mongo" ]; then - echo "Restoring MongoDB..." - docker cp "$RESTORE_DIR/$BACKUP_DIR/mongo" vcon-server-mongo-1:/tmp/mongorestore - docker compose exec -T mongo mongorestore \ - --username root --password example \ - --authenticationDatabase admin \ - --db conserver /tmp/mongorestore/conserver + docker compose exec -T postgres psql -U "$PG_USER" -d template1 -c "DROP DATABASE IF EXISTS $PG_DB;" + docker compose exec -T postgres psql -U "$PG_USER" -d template1 -c "CREATE DATABASE $PG_DB;" + docker compose exec -T postgres psql -U "$PG_USER" "$PG_DB" < "$BACKUP_DIR/postgres.sql" fi -# Cleanup rm -rf "$RESTORE_DIR" -# Start services echo "Starting services..." docker compose start conserver api echo "Restore complete. Verify with: curl http://localhost:8000/api/health" ``` -## Disaster Recovery +## Recover from a disaster -### Recovery Time Objectives +Set your own targets. These rows show what usually drives each one. -| Scenario | RTO | RPO | -|----------|-----|-----| -| Configuration loss | Minutes | On change | -| Redis failure | Minutes | Last backup | -| Database failure | Hours | Last backup | -| Complete failure | Hours | Last full backup | +| Scenario | Recovery time depends on | Data loss back to | +|----------|--------------------------|-------------------| +| Configuration loss | Copying files | The last change you saved | +| Redis failure | Restoring the archive | The last Redis backup | +| Database failure | The size of the database | The last database backup | +| Complete failure | Rebuilding hosts and restoring everything | The last full backup | -### Recovery Procedure +1. **Assess the damage.** -1. **Assess damage** - ```bash - docker compose ps - docker compose logs --tail=100 - ``` + ```bash + docker compose ps + docker compose logs --tail=100 + ``` -2. **Restore infrastructure** - ```bash - docker compose up -d redis postgres mongo - ``` +2. **Restore the infrastructure.** The network is external, and `COMPOSE_PROFILES` in `.env` starts the optional services. -3. **Restore data** - ```bash - ./full-restore.sh ./backups/latest.tar.gz - ``` + ```bash + docker network create conserver + docker compose up -d redis postgres + ``` -4. **Verify health** - ```bash - curl http://localhost:8000/api/health - curl http://localhost:8000/api/version - ``` +3. **Restore the data.** -5. **Test functionality** - ```bash - # Submit test vCon - # Verify processing - # Check storage backends - ``` + ```bash + ./full-restore.sh ./backups/.tar.gz + ``` -## Best Practices +4. **Verify the health.** -### 1. Test Restores Regularly + ```bash + curl http://localhost:8000/api/health + docker compose exec -T redis redis-cli ping + ``` -```bash -# Monthly restore test to staging -./full-restore.sh ./backups/latest.tar.gz -# Verify everything works -``` +5. **Test the pipeline.** [Submit a test vCon](index.md#submit-a-test-vcon), confirm it runs, and check that it reaches your storage backends. -### 2. Offsite Backups +## Test the restores -```bash -# Sync to cloud storage -aws s3 sync ./backups s3://vcon-backups/ -``` +Run a restore in a staging environment every month. A backup you have never restored is not proven. -### 3. Encrypt Sensitive Backups +## Protect the backups ```bash # Encrypt before upload gpg --symmetric --cipher-algo AES256 backup.tar.gz + +# Sync to offsite storage +aws s3 sync ./backups s3://vcon-backups/ ``` -### 4. Monitor Backup Jobs +Add the backup to cron with a notification, so a failed run gets noticed: ```bash -# Add to cron with notification 0 2 * * * /path/to/full-backup.sh && echo "Backup OK" | mail -s "vCon Backup" admin@example.com ``` -### 5. Document Recovery Procedures - -Keep runbooks updated with: - -- Contact information -- Access credentials (securely stored) -- Step-by-step procedures -- Verification checklists +Keep your runbooks current, with contacts, where credentials are stored, the steps above and a verification checklist. diff --git a/docs/operations/dead-letter-queue.md b/docs/operations/dead-letter-queue.md index 49588cc4..4cf66388 100644 --- a/docs/operations/dead-letter-queue.md +++ b/docs/operations/dead-letter-queue.md @@ -1,334 +1,223 @@ -# Dead Letter Queue +# Manage dead letter queues -The Dead Letter Queue (DLQ) captures vCons that fail processing, allowing for analysis and retry. +A dead letter queue (DLQ) holds the ids of vCons that failed, so you can find the cause and replay them. This page covers the ingress DLQ. A failed write to one backend goes to a separate storage DLQ, covered in [Recover failed storage writes](storage-recovery.md). -## How DLQ Works +The [API reference](../reference/api.md#work-with-dead-letter-queues) gives the parameters, responses and status codes for every route used here. In the examples, `default` stands for your ingress list and `$API` is your base URL, such as `http://localhost:8000/api`. -```mermaid -flowchart LR - subgraph normal [Normal Flow] - INGRESS[Ingress Queue] --> PROCESS[Processing] - PROCESS --> STORAGE[Storage] - STORAGE --> EGRESS[Egress Queue] - end +![States of a vCon id from an ingress list through the links and wrap-up to the ingress and storage dead letter queues](../diagrams/D08-dead-letter-flow.svg) - subgraph error [Error Flow] - PROCESS --> |Error| DLQ[Dead Letter Queue] - end -``` - -When processing fails: - -1. Error is logged with full traceback -2. vCon UUID is moved to DLQ -3. vCon TTL is extended to `VCON_DLQ_EXPIRY` (default 7 days) to ensure retention -4. Original ingress list is recorded -5. Processing continues with next vCon - -## DLQ Retention - -When a vCon is moved to the DLQ, its TTL is automatically extended to ensure it persists long enough for investigation and reprocessing. +## Follow a failed vCon -| Setting | Default | Description | -|---------|---------|-------------| -| `VCON_DLQ_EXPIRY` | `604800` (7 days) | TTL for vCons in the DLQ | +A vCon reaches the ingress DLQ on any exception before wrap-up finishes its egress pushes. That covers a link that raises or cannot be imported, an unknown link name, a chain with no `links` key, the `before_processing` or `after_link` hook raising, a tracer with `dlq_vcon_on_error`, a failing tracer with no `options` key, and a failed egress enqueue. The worker then: -```bash -# Extend DLQ retention to 14 days -VCON_DLQ_EXPIRY=1209600 +1. Logs the error with its traceback. +2. Pushes the id onto the DLQ for the ingress list it came from. +3. Sets the body's TTL to `VCON_DLQ_EXPIRY`, unless that is 0. +4. Moves on to the next vCon. -# Disable DLQ expiry (vCons persist indefinitely) -VCON_DLQ_EXPIRY=0 -``` +Two outcomes never reach a DLQ. A link that returns a falsy value halts the chain, and a `before_processing` hook that returns falsy skips the vCon. Neither path writes to egress or storage. -!!! note "Why DLQ Expiry Matters" - vCons created via the API have a default TTL of 1 hour (`VCON_REDIS_EXPIRY`). Without DLQ expiry extension, a failed vCon could expire from Redis before operators can investigate, leaving only the UUID in the DLQ with no data to review. +A killed worker also loses the id it was processing, since a popped id is held only in memory. See [plan maintenance](index.md#plan-maintenance). -## DLQ Naming +## Name the queues -Each ingress list has its own DLQ: - -``` -DLQ:{ingress_list_name} -``` +Each ingress list has its own DLQ, named `DLQ:`. For example, `transcribe` fails into `DLQ:transcribe`. Each storage backend has its own queue, named `DLQ:storage:`. -Examples: +## Keep the vCon body -- `default` -> `DLQ:default` -- `production` -> `DLQ:production` -- `partner_input` -> `DLQ:partner_input` +The queue holds only the id. The body stays in Redis under `vcon:` until its TTL runs out. vCons created through the API start with a TTL of `VCON_REDIS_EXPIRY`, so without a longer retention a failed vCon could expire before you look at it. See the [environment reference](../reference/environment.md) for both defaults. -## Managing the DLQ +| `VCON_DLQ_EXPIRY` | Ingress DLQ | Storage DLQ | +|---|---|---| +| Above 0 | Sets the TTL to this value. This can shorten a longer TTL, and it puts a TTL on a persistent body | Raises a shorter TTL to this value. A longer TTL or a persistent body stays as it is | +| 0 | Leaves the TTL unchanged | Leaves the TTL unchanged | -### View DLQ Contents +!!! warning "Zero does not keep a body forever" + With `VCON_DLQ_EXPIRY=0` the body keeps the TTL it already had, so it can expire while its id waits in the DLQ. ```bash -# Via API -curl "http://localhost:8000/api/dlq?ingress_list=default" \ - -H "x-conserver-api-token: $TOKEN" +# Keep bodies for 14 days after a failure +VCON_DLQ_EXPIRY=1209600 ``` -Response: - -```json -{ - "uuids": ["uuid-1", "uuid-2", "uuid-3"], - "count": 3, - "dlq_name": "DLQ:default" -} -``` +The ingress path does not check that the body exists, so an id can sit in the DLQ after its body has gone. On replay, the read falls back to the configured storages. If no backend has the vCon, the result depends on the first link in the chain. -### Check DLQ Depth +## Inspect the queue ```bash -# Via Redis -docker compose exec redis redis-cli LLEN DLQ:default -``` - -### View DLQ Items Directly +# List ids. The response is a JSON array. +curl "$API/dlq?ingress_list=default" -H "x-conserver-api-token: $TOKEN" -```bash -# List all items (0 to -1 = all) -docker compose exec redis redis-cli LRANGE DLQ:default 0 -1 -``` +# Read the depth. This route needs no token. +curl "$API/stats/queue?list_name=DLQ:default" -### Reprocess DLQ - -Move items back to the ingress queue for retry: +# Read the depth in Redis +docker compose exec redis redis-cli LLEN DLQ:default -```bash -curl -X POST "http://localhost:8000/api/dlq/reprocess?ingress_list=default" \ - -H "x-conserver-api-token: $TOKEN" +# Find every DLQ, including storage DLQs and any replay locks +docker compose exec redis redis-cli --scan --pattern 'DLQ:*' ``` -Response: - -```json -{ - "reprocessed": 3, - "ingress_list": "default" -} -``` +`GET /dlq` only reads. It removes nothing. An unknown list name returns an empty array with `200`, not an error, so a typo looks like an empty queue. -### Remove Single Item +## Find the cause ```bash -# Remove specific UUID from DLQ -docker compose exec redis redis-cli LREM DLQ:default 1 "uuid-to-remove" -``` +# Find the log lines for one vCon +docker compose logs conserver | grep "" -### Clear Entire DLQ +# Find every move to a DLQ +docker compose logs conserver | grep "Moving to DLQ" -```bash -# Delete the DLQ list -docker compose exec redis redis-cli DEL DLQ:default +# Read the vCon +curl "$API/vcon/" -H "x-conserver-api-token: $TOKEN" | jq . ``` -!!! warning "Data Loss" - Clearing the DLQ permanently removes failed vCons. Ensure you've investigated the failures first. - -## Analyzing Failures - -### 1. Check Processing Logs - -```bash -# Find errors for specific UUID -docker compose logs conserver | grep "uuid-from-dlq" - -# Find all errors -docker compose logs conserver | grep -i "error\|exception\|failed" -``` - -### 2. Inspect the vCon - -```bash -# Get the vCon data -curl "http://localhost:8000/api/vcon/uuid-from-dlq" \ - -H "x-conserver-api-token: $TOKEN" | jq . -``` +See [Logging](logging.md#search-the-logs) for more search patterns. -### 3. Common Failure Patterns +A failure can arrive late. A transcription link that keeps failing takes about a minute to reach the DLQ, and that worker handles nothing else meanwhile unless `CONSERVER_VCON_CONCURRENCY` is above 1. See [openai_transcribe](../reference/links/openai-transcribe.md#follow-the-processing-steps). | Error | Cause | Solution | -|-------|-------|----------| -| Connection refused | External service down | Check service, retry | -| Invalid API key | Wrong or expired key | Update credentials | -| Timeout | Slow external service | Increase timeout, retry | -| JSON decode error | Malformed vCon | Fix vCon data | -| Module not found | Missing dependency | Install module | +|---|---|---| +| Connection refused | External service down | Check the service, then replay | +| Invalid API key | Wrong or expired key | Update the credentials | +| Timeout | Slow external service | Fix the service or raise the link's timeout, if it has one | +| JSON decode error | Malformed vCon | Fix the vCon data | +| Module not found | Missing dependency | Install the module | -## Preventing DLQ Items +## Replay the queue -### 1. Validate Input +Fix the cause first, because an unfixed failure sends the vCon straight back to the DLQ. -Check vCons before submission: +A replay runs every link again. Transcribe vendors skip a dialog that already has a transcript, so a transcript saved before a later link failed is not repeated. Other links repeat their work: `tag` adds a duplicate. Check each [link page](../reference/links/index.md) for its repeat behaviour. -```python -import json - -def validate_vcon(vcon): - required = ['vcon', 'uuid', 'created_at', 'parties', 'dialog'] - for field in required: - if field not in vcon: - raise ValueError(f"Missing required field: {field}") - return True -``` - -### 2. Use Appropriate Timeouts - -Configure timeouts in links: - -```yaml -links: - deepgram_link: - module: links.deepgram_link - options: - timeout: 120 # seconds -``` +Try one item, then the rest. `count=1` takes the oldest entry, which may not be the vCon you diagnosed: -### 3. Handle Partial Failures +```bash +# Move one item back to the ingress list +curl -X POST "$API/dlq/reprocess?ingress_list=default&count=1" \ + -H "x-conserver-api-token: $TOKEN" -Use try/except in custom links: +# Watch it run +docker compose logs -f conserver -```python -def run(vcon_uuid, link_name, opts): - try: - # Processing logic - return vcon_uuid - except TemporaryError: - # Log and return None (skip, don't DLQ) - logger.warning(f"Temporary error for {vcon_uuid}, skipping") - return None - except PermanentError: - # Re-raise to send to DLQ - raise +# Move up to 1000 items. The response is the number moved. +curl -X POST "$API/dlq/reprocess?ingress_list=default&count=1000" \ + -H "x-conserver-api-token: $TOKEN" ``` -### 4. Monitor DLQ Depth +Each call moves a bounded number of items, oldest failure first. To drain a large queue, repeat the call until the response is 0. -Set up alerts for DLQ growth: +The move is two Redis commands per item, not one atomic step. The server keeps no retry count, so a vCon that keeps failing returns to the DLQ each time, until you remove it. -```yaml -# prometheus-alerts.yml -- alert: DLQNotEmpty - expr: redis_list_length{list=~"DLQ:.*"} > 0 - for: 5m - labels: - severity: warning -``` +### Replay one chosen vCon -## DLQ Workflow +Take its id off the DLQ, then push it back with `POST /vcon/ingress`. The route returns `204`. It logs and skips an id found neither in Redis nor in storage, so [read the vCon](#find-the-cause) first. -### Standard Recovery Process +```bash +docker compose exec redis redis-cli LREM DLQ:default 1 "" -```mermaid -flowchart TB - DETECT[Detect DLQ Items] --> ANALYZE[Analyze Failures] - ANALYZE --> FIX[Fix Root Cause] - FIX --> TEST[Test Fix] - TEST --> REPROCESS[Reprocess DLQ] - REPROCESS --> VERIFY[Verify Success] - VERIFY --> |Success| DONE[Done] - VERIFY --> |Failure| ANALYZE +curl -X POST "$API/vcon/ingress?ingress_list=default" \ + -H "Content-Type: application/json" \ + -H "x-conserver-api-token: $TOKEN" \ + -d '[""]' ``` -### Step-by-Step - -1. **Detect**: Alert on DLQ depth > 0 -2. **Analyze**: Review logs, identify pattern -3. **Fix**: Address root cause (config, code, external service) -4. **Test**: Submit test vCon, verify processing -5. **Reprocess**: Move DLQ items back to ingress -6. **Verify**: Ensure items process successfully - -### Scripted Recovery +### Script the recovery ```bash #!/bin/bash # dlq-recovery.sh +set -e + INGRESS_LIST="${1:-default}" -API_URL="http://localhost:8000/api" -TOKEN="${CONSERVER_API_TOKEN}" +API="${API:-http://localhost:8000/api}" +TOKEN="${TOKEN:-$CONSERVER_API_TOKEN}" + +if [ -z "$TOKEN" ]; then + echo "Set TOKEN or CONSERVER_API_TOKEN" >&2 + exit 1 +fi -# Check DLQ depth -echo "Checking DLQ for $INGRESS_LIST..." -DEPTH=$(docker compose exec -T redis redis-cli LLEN "DLQ:$INGRESS_LIST") -echo "DLQ depth: $DEPTH" +DEPTH=$(curl -fsS "$API/stats/queue?list_name=DLQ:$INGRESS_LIST" | jq -r .depth) +echo "DLQ:$INGRESS_LIST depth: $DEPTH" if [ "$DEPTH" -eq 0 ]; then - echo "DLQ is empty" exit 0 fi -# Get sample of failed UUIDs -echo "Sample failed UUIDs:" +echo "Oldest failed ids:" docker compose exec -T redis redis-cli LRANGE "DLQ:$INGRESS_LIST" 0 4 -# Prompt for action -read -p "Reprocess DLQ? (y/n) " -n 1 -r +read -p "Reprocess? (y/n) " -n 1 -r echo if [[ $REPLY =~ ^[Yy]$ ]]; then - echo "Reprocessing..." - curl -X POST "$API_URL/dlq/reprocess?ingress_list=$INGRESS_LIST" \ + curl -fsS -X POST "$API/dlq/reprocess?ingress_list=$INGRESS_LIST" \ -H "x-conserver-api-token: $TOKEN" echo - echo "Done. Monitor processing with: docker compose logs -f conserver" + echo "Monitor processing with: docker compose logs -f conserver" fi ``` -## Tracer Integration +## Remove items -When using tracers with DLQ handling: +```bash +# Remove one id +docker compose exec redis redis-cli LREM DLQ:default 1 "" -```yaml -tracers: - jlinc: - module: tracers.jlinc - options: - dlq_vcon_on_error: true # Send to DLQ on tracer error +# Delete the whole queue +docker compose exec redis redis-cli DEL DLQ:default ``` -## Best Practices +!!! warning "Data loss" + These commands remove ids, not bodies. A body stays until its TTL runs out, but with no id left nothing will replay it. Investigate first. -### 1. Don't Ignore the DLQ +To set an item aside instead, move its id to a list of your own. No server code reads that list, and the body still expires on its TTL. `LMOVE` moves the oldest entry, so use `LREM` and `RPUSH` for a chosen id. -- Monitor DLQ depth continuously -- Investigate failures promptly -- Don't let items accumulate +```bash +# Set aside the oldest entry +docker compose exec redis redis-cli LMOVE DLQ:default ARCHIVE:default LEFT RIGHT -### 2. Fix Root Causes +# Set aside a chosen id +docker compose exec redis redis-cli LREM DLQ:default 1 "" +docker compose exec redis redis-cli RPUSH ARCHIVE:default "" +``` -- Don't just reprocess blindly -- Understand why failures occurred -- Prevent recurrence +## Prevent failures -### 3. Test Before Bulk Reprocess +**Validate input.** `POST /vcon` and `POST /vcon/external-ingress` reject a malformed body with HTTP 422 before it reaches a chain. See the [body rules](../reference/api.md#meet-the-vcon-body-rules). -```bash -# Move one item for testing -docker compose exec redis redis-cli RPOPLPUSH DLQ:default default +**Check link timeouts.** Each link has its own options, and many have no timeout setting. See the [link reference](../reference/links/index.md). -# Check processing -docker compose logs -f conserver +**Decide how a custom link fails.** Raise to send the vCon to the DLQ. Return `None` only when the chain should stop, because that skips egress and storage too. -# If successful, reprocess rest -curl -X POST ".../dlq/reprocess?ingress_list=default" ... +```python +def run(vcon_uuid, link_name, opts=default_options): + try: + # Processing logic + return vcon_uuid + except NotWorthProcessing: + # Halts the chain. No DLQ entry, no egress, no storage. + logger.warning("Halting chain for %s", vcon_uuid) + return None + except ServiceError: + # Sends the vCon to the DLQ + raise ``` -### 4. Consider Retry Limits +See [Creating links](../extending/creating-links.md). -For persistent failures: +**Choose the tracer failure mode.** With `dlq_vcon_on_error: true`, a tracer error sends the vCon to the DLQ. The [JLINC tracer](../reference/tracers/jlinc.md#handle-a-failure) describes which failures that covers. -```bash -# Check how many times an item has been reprocessed -# (Implement custom tracking if needed) -``` +**Alert on depth.** See [the alert rules](monitoring.md#write-the-alert-rules). -### 5. Archive Unrecoverable Items +## Work through a recovery -```bash -# Move to archive queue instead of deleting -docker compose exec redis redis-cli RPOPLPUSH DLQ:default ARCHIVE:default -``` +1. **Detect.** Alert on a depth above 0. +2. **Analyze.** Read the logs and identify the pattern. +3. **Fix.** Address the cause in the config, the code or the external service. +4. **Test.** Replay one item and watch it run. +5. **Replay.** Move the remaining items back to the ingress list. +6. **Verify.** Confirm the depth stays at 0. If items return, go back to step 2. diff --git a/docs/operations/index.md b/docs/operations/index.md index 5c0e4017..eaa8d51f 100644 --- a/docs/operations/index.md +++ b/docs/operations/index.md @@ -1,33 +1,28 @@ -# Operations Guide +# Run the server -This section covers day-to-day operations, monitoring, troubleshooting, and maintenance of vCon Server. - -## Operations Overview +This section covers day-to-day operation of vCon Server: checking it, recovering from failure and planning capacity. | Topic | Description | |-------|-------------| -| [API Reference](api-reference.md) | Complete API endpoint documentation | -| [Monitoring](monitoring.md) | Metrics, observability, and health checks | +| [Monitoring](monitoring.md) | Health checks, OpenTelemetry export and alerts | | [Logging](logging.md) | Log configuration and analysis | | [Troubleshooting](troubleshooting.md) | Common issues and solutions | -| [Dead Letter Queue](dead-letter-queue.md) | Managing failed processing | -| [Backup and Restore](backup-restore.md) | Data protection procedures | +| [Dead letter queues](dead-letter-queue.md) | Failed chains and how to replay them | +| [Storage recovery](storage-recovery.md) | Failed backend writes and how to replay them | +| [Backup and restore](backup-restore.md) | Data protection procedures | +| [API reference](../reference/api.md) | Every REST endpoint | -## Quick Reference +In the examples, `default` stands for your own ingress list and `$TOKEN` for your API token. The API listens on port 8000. See [API reference](../reference/api.md#set-the-base-url) for the base URL. -### Health Check +## Check the service status ```bash +# Health and version need no token curl http://localhost:8000/api/health -``` - -### Version Information - -```bash curl http://localhost:8000/api/version ``` -### Service Status +`/health` confirms only that the API process answers. It does not check Redis or the workers. See [Monitoring](monitoring.md#check-the-server-health). === "Docker" @@ -43,25 +38,21 @@ curl http://localhost:8000/api/version kubectl logs -f deployment/worker -n vcon-server ``` -=== "Systemd" - - ```bash - systemctl status vcon-server - journalctl -u vcon-server -f - ``` - -## Common Operations +## Run the common tasks -### Restart Services +### Restart the services === "Docker" ```bash # Restart all docker compose restart - - # Restart specific service + + # Restart one service docker compose restart conserver + + # Recreate a service after changing .env + docker compose up -d conserver ``` === "Kubernetes" @@ -70,18 +61,15 @@ curl http://localhost:8000/api/version kubectl rollout restart deployment/worker -n vcon-server ``` -### View Logs +`docker compose restart` keeps the old environment. After editing `.env`, use `docker compose up -d`. + +### Read the logs === "Docker" ```bash - # All logs docker compose logs -f - - # Last 100 lines docker compose logs --tail=100 conserver - - # Filter by time docker compose logs --since="1h" conserver ``` @@ -92,207 +80,175 @@ curl http://localhost:8000/api/version kubectl logs --tail=100 -l app=worker -n vcon-server ``` -### Check Queue Status +### Check the queue status ```bash -# Get queue lengths +# Queue depth through the API, no token needed +curl "http://localhost:8000/api/stats/queue?list_name=default" +curl "http://localhost:8000/api/stats/queue?list_name=DLQ:default" + +# Queue depth in Redis docker compose exec redis redis-cli LLEN default -docker compose exec redis redis-cli LLEN DLQ:default -# List all queues -docker compose exec redis redis-cli KEYS "*" +# List every dead letter queue, without blocking Redis as KEYS would +docker compose exec redis redis-cli --scan --pattern 'DLQ:*' ``` -### Submit Test vCon +### Submit a test vCon + +The `uuid` must be a valid UUID, or the API returns 422. ```bash curl -X POST "http://localhost:8000/api/vcon?ingress_lists=default" \ -H "Content-Type: application/json" \ -H "x-conserver-api-token: $TOKEN" \ -d '{ - "vcon": "0.0.1", - "uuid": "test-'$(date +%s)'", + "vcon": "0.4.0", + "uuid": "'$(uuidgen | tr 'A-Z' 'a-z')'", "created_at": "'$(date -u +%Y-%m-%dT%H:%M:%SZ)'", - "parties": [], + "parties": [{"tel": "+15551234567"}], "dialog": [] }' ``` -### View Configuration +The API accepts any list name, even one no chain reads. An id pushed to such a list waits there and nothing processes it. + +### Read the configuration ```bash curl http://localhost:8000/api/config \ -H "x-conserver-api-token: $TOKEN" | jq . ``` -## Operational Metrics +## Watch the key signals -### Key Metrics to Monitor +Publish metrics through OpenTelemetry, then watch these signals. [Monitoring](monitoring.md#watch-the-key-signals) maps each one to a metric, and the [metrics reference](../reference/metrics.md) lists every name. -| Metric | Description | Alert Threshold | -|--------|-------------|-----------------| -| Queue Depth | Items waiting in ingress queues | > 1000 | -| DLQ Depth | Items in dead letter queue | > 0 | -| Processing Latency | Time to process one vCon | > 30s | -| Error Rate | Percentage of failed processing | > 5% | -| Worker Count | Active worker processes | < expected | -| Memory Usage | Container/process memory | > 80% | -| CPU Usage | Container/process CPU | > 80% | +- Ingress queue depth +- Ingress and storage DLQ depth +- Chain processing time +- Link and storage errors +- Redis memory, and container CPU and memory -### Quick Health Assessment +Set thresholds from your own baseline, since load depends on the chains you run. + +### Script a quick health assessment ```bash #!/bin/bash # health-check.sh API_URL="http://localhost:8000/api" -TOKEN="your-token" - -echo "=== vCon Server Health Check ===" +QUEUES="default" -# API Health -echo -n "API Health: " +echo -n "API health: " curl -s "$API_URL/health" | jq -r .status -# Version echo -n "Version: " curl -s "$API_URL/version" | jq -r .version -# Queue Status -echo "Queue Depths:" -for queue in default production test; do - depth=$(docker compose exec -T redis redis-cli LLEN $queue 2>/dev/null || echo "N/A") - echo " $queue: $depth" +for queue in $QUEUES; do + for list in "$queue" "DLQ:$queue"; do + echo -n "$list: " + curl -s "$API_URL/stats/queue?list_name=$list" | jq -r .depth + done done -# DLQ Status -echo "DLQ Depths:" -for queue in default production test; do - depth=$(docker compose exec -T redis redis-cli LLEN "DLQ:$queue" 2>/dev/null || echo "N/A") - echo " DLQ:$queue: $depth" -done +echo -n "Redis: " +docker compose exec -T redis redis-cli ping -# Container Status -echo "Container Status:" docker compose ps --format "table {{.Name}}\t{{.Status}}" ``` -## Maintenance Windows +## Plan maintenance -### Planned Maintenance +No switch stops ingress on the server, so stop your producers first. Then drain the queues before stopping the workers. -1. **Announce maintenance** to users -2. **Stop ingress** (stop accepting new vCons) -3. **Drain queues** (wait for processing to complete) -4. **Perform maintenance** -5. **Verify health** -6. **Resume operations** +1. Announce the maintenance to users. +2. Stop the systems that submit vCons. +3. Wait until the ingress lists reach 0 and `conserver.vcons.inflight` falls to 0. +4. Stop the workers and carry out the maintenance. +5. Start the workers and verify health. +6. Resume the producers. ```bash -# Graceful shutdown (allows current processing to complete) docker compose stop conserver -# Perform maintenance... +# Perform the maintenance -# Restart docker compose start conserver - -# Verify curl http://localhost:8000/api/health ``` -### Emergency Procedures +!!! warning "Shutdown has a short grace period" + A worker finishes the vCons it holds before it exits, but `docker-compose.yml` sets `stop_grace_period: 5s`. After that Docker kills the process. A popped id lives only in memory, so a vCon still running at that moment is lost from the queue. Drain first, or raise the grace period above your longest chain. -**Service Unresponsive:** +## Respond to an emergency + +**Service unresponsive:** ```bash -# Force restart docker compose restart -# If still unresponsive +# If it still does not respond docker compose down docker compose up -d ``` -**Queue Backup:** +**Queue backing up:** ```bash -# Check queue depth -docker compose exec redis redis-cli LLEN default +curl "http://localhost:8000/api/stats/queue?list_name=default" -# Scale workers +# Add worker containers docker compose up -d --scale conserver=4 ``` -**DLQ Growing:** +[Configure the workers](../configuration/workers.md) covers the other ways to add capacity. -```bash -# Check DLQ -curl "http://localhost:8000/api/dlq?ingress_list=default" \ - -H "x-conserver-api-token: $TOKEN" +**DLQ growing:** find the cause, then replay. See [Manage dead letter queues](dead-letter-queue.md). -# Fix issues, then reprocess -curl -X POST "http://localhost:8000/api/dlq/reprocess?ingress_list=default" \ - -H "x-conserver-api-token: $TOKEN" -``` +**Storage DLQ growing:** fix the backend, then replay. See [Recover failed storage writes](storage-recovery.md). -## Capacity Planning +## Plan the capacity -### Resource Requirements by Scale +Treat these figures as starting points, not measurements. Throughput depends on your chains, and a chain that calls external transcription or analysis services behaves very differently from one that only tags and stores. Load test with your own chains. + + | Scale | vCons/day | Workers | Memory | CPU | |-------|-----------|---------|--------|-----| | Small | < 1,000 | 1-2 | 2 GB | 2 cores | | Medium | 1,000-10,000 | 4 | 4 GB | 4 cores | | Large | 10,000-100,000 | 8 | 8 GB | 8 cores | -| Enterprise | > 100,000 | 16+ | 16+ GB | 16+ cores | - -### Scaling Triggers +| Very large | > 100,000 | 16+ | 16+ GB | 16+ cores | -**Scale Up When:** +Scale up when the queue depth stays high, chain processing time climbs, or CPU stays high. Scale down when the queue stays empty and CPU stays low. Maximum parallel vCons per host is `CONSERVER_WORKERS` times `CONSERVER_VCON_CONCURRENCY`. See [Configure the workers](../configuration/workers.md). -- Queue depth consistently > 100 -- Processing latency > 10s -- CPU usage > 70% +The `redis` service in `docker-compose.yml` has `mem_limit: 1gb`. Bodies held for a DLQ stay in Redis for days, so raise the limit if a queue may grow large. -**Scale Down When:** - -- Queue depth consistently 0 -- CPU usage < 30% -- Cost optimization needed - -## Security Operations - -### Regular Tasks +## Maintain the security | Task | Frequency | Procedure | |------|-----------|-----------| -| Rotate API tokens | Monthly | [Authentication Guide](../configuration/authentication.md) | -| Review access logs | Weekly | Check for unauthorized access | -| Update dependencies | Monthly | `poetry update && docker compose build` | -| Security patches | As released | Apply and test | -| Backup verification | Weekly | Test restore procedure | - -### Audit Logging - -Enable audit logging for compliance: - -```bash -LOG_LEVEL=INFO -``` +| Rotate API tokens | Monthly | [Authentication](../configuration/authentication.md). The API reads its tokens at startup, so restart it | +| Review access logs | Weekly | See below | +| Update dependencies | Monthly | `uv lock --upgrade && docker compose build` | +| Apply security patches | As released | Apply and test | +| Verify backups | Weekly | [Test a restore](backup-restore.md#test-the-restores) | -Review access patterns: +The server has no dedicated audit log. To review access, search the API process output: ```bash -# Failed auth attempts -docker compose logs api | grep -i "403" +# Rejected requests +docker compose logs api | grep '" 403' -# Successful operations -docker compose logs api | grep "200" +# Rejected keys on external ingress +docker compose logs api | grep "Invalid API key for ingress list" ``` -## Next Steps +## Read the next pages -- [API Reference](api-reference.md) - Complete endpoint documentation -- [Monitoring](monitoring.md) - Set up observability -- [Troubleshooting](troubleshooting.md) - Solve common issues +- [Monitoring](monitoring.md) sets up observability +- [Troubleshooting](troubleshooting.md) solves common issues +- [API reference](../reference/api.md) documents every endpoint diff --git a/docs/operations/logging.md b/docs/operations/logging.md index 67083674..53eeb155 100644 --- a/docs/operations/logging.md +++ b/docs/operations/logging.md @@ -1,235 +1,170 @@ -# Logging +# Read and configure logs -This guide covers logging configuration, log analysis, and debugging with logs. +This page covers the logging configuration, how to search the logs and how to turn on debug output. -## Logging Configuration +## Choose the log format -### Configuration Files +Python's `logging.config.fileConfig` loads one file at import, named by `LOGGING_CONFIG_FILE`. Two files ship in the repo: -vCon Server includes two logging configurations: - -| File | Format | Use Case | -|------|--------|----------| -| `server/logging.conf` | JSON | Production | -| `server/logging_dev.conf` | Simple text | Development | - -### Selecting Configuration +| File | Format | Use | +|------|--------|-----| +| `common/logging.conf` | JSON | The default | +| `common/logging_dev.conf` | Plain text | Development | ```bash -# Production (default) -LOGGING_CONFIG_FILE=server/logging.conf - -# Development -LOGGING_CONFIG_FILE=server/logging_dev.conf +# Plain text in a container +LOGGING_CONFIG_FILE=/app/common/logging_dev.conf ``` -### Log Level +Apply a change with `docker compose up -d conserver api`, since `docker compose restart` keeps the old environment. -```bash -# Options: DEBUG, INFO, WARNING, ERROR, CRITICAL -LOG_LEVEL=INFO -``` - -## Production Logging (JSON) +!!! warning "The example path does not exist" + `.env.example` sets `LOGGING_CONFIG_FILE=server/logging_dev.conf`, and the repo has no `server/` folder. A process with that value fails at import. Use the path above, or remove the line to use the default. -Production logging outputs structured JSON for easy parsing. +Both files write everything to stdout. A `custom_error` handler for stderr is defined, but no logger uses it. -### Configuration +## Set the log level -```ini -# server/logging.conf -[loggers] -keys=root,vcon,uvicorn,main,api - -[handlers] -keys=custom_info,custom_error - -[formatters] -keys=json - -[logger_root] -level=INFO -handlers=custom_info,custom_error - -[logger_vcon] -level=INFO -handlers=custom_info,custom_error -qualname=vcon -propagate=0 - -[handler_custom_info] -class=StreamHandler -level=INFO -formatter=json -args=(sys.stdout,) - -[handler_custom_error] -class=StreamHandler -level=WARNING -formatter=json -args=(sys.stderr,) - -[formatter_json] -format={"timestamp": "%(asctime)s", "level": "%(levelname)s", "logger": "%(name)s", "message": "%(message)s"} -``` - -### Sample Output - -```json -{"timestamp": "2024-01-15 10:30:00,123", "level": "INFO", "logger": "vcon", "message": "Processing vCon abc-123"} -{"timestamp": "2024-01-15 10:30:01,456", "level": "INFO", "logger": "vcon", "message": "Completed processing abc-123"} -``` +Levels live in the config file. `LOG_LEVEL` is read into `settings`, but no code uses it, so setting it changes nothing. -## Development Logging (Text) +Both shipped files stop at `INFO`, including `logging_dev.conf`, because the root logger and the `custom_info` handler are both at `INFO`. Its `DEBUG` loggers have no handler that passes `DEBUG`. To see debug output, see [Turn on debug output](#turn-on-debug-output). -Development logging uses human-readable format. +## Read the JSON output -### Configuration +The JSON formatter is `pythonjsonlogger`. Fields passed through `extra` become top-level keys. -```ini -# server/logging_dev.conf -[loggers] -keys=root,vcon,uvicorn,main,api - -[handlers] -keys=console - -[formatters] -keys=simple - -[logger_root] -level=DEBUG -handlers=console - -[logger_vcon] -level=DEBUG -handlers=console -qualname=vcon -propagate=0 - -[handler_console] -class=StreamHandler -level=DEBUG -formatter=simple -args=(sys.stdout,) - -[formatter_simple] -format=%(asctime)s - %(name)s - %(levelname)s - %(message)s +```json +{"asctime": "2026-11-03 17:46:27,793", "levelname": "INFO", "name": "storage.base", "message": "Finished storage postgres module storage.postgres save for vCon: 018f0000-0000-8000-8000-000000000001 in 0.12 seconds.", "taskName": null, "storage_processing_time": 0.12} ``` -### Sample Output +The plain text format is `%(asctime)s - %(name)s - %(levelname)s - %(message)s`. ``` -2024-01-15 10:30:00,123 - vcon - DEBUG - Processing vCon abc-123 -2024-01-15 10:30:00,456 - vcon - DEBUG - Running link: transcribe -2024-01-15 10:30:01,789 - vcon - INFO - Completed processing abc-123 +2026-11-03 17:46:27 - main - INFO - Worker-1 started (PID 12) ``` -## Logger Hierarchy +## Identify the loggers -| Logger | Purpose | -|--------|---------| -| `root` | Catch-all for unhandled loggers | -| `vcon` | Core vCon processing | -| `api` | API endpoint handling | -| `main` | Main worker process | -| `uvicorn` | Web server | +| Logger | Source | +|--------|--------| +| `main` | `conserver/main.py` | +| `api` | `api/api.py` | +| `vcon` | `common/vcon.py` | +| `uvicorn` | The web server | +| `root` | Everything else. Modules log under their own names, such as `links.tag`, `storage.base` and `lib.vcon_redis`, and pass up to `root` | -### Using Loggers in Code +Use the helper in your own code: ```python from lib.logging_utils import init_logger logger = init_logger(__name__) - -def process(): - logger.debug("Starting process") - logger.info("Process completed") - logger.warning("Something unusual") - logger.error("Something failed", exc_info=True) ``` -## Viewing Logs +## View the logs -### Docker Compose +### Use Docker Compose ```bash -# All logs -docker compose logs - -# Follow logs docker compose logs -f - -# Specific service -docker compose logs conserver - -# Last N lines docker compose logs --tail=100 conserver - -# Since time docker compose logs --since="1h" conserver - -# Filter by time range -docker compose logs --since="2024-01-15T10:00:00" --until="2024-01-15T11:00:00" +docker compose logs --since="2026-01-15T10:00:00" --until="2026-01-15T11:00:00" ``` -### Kubernetes +### Use Kubernetes ```bash -# Pod logs kubectl logs -f deployment/worker -n vcon-server - -# All pods with label kubectl logs -f -l app=worker -n vcon-server -# Previous container (after crash) +# The previous container, after a crash kubectl logs --previous deployment/worker -n vcon-server ``` -### Container Logs +## Search the logs + +These lines mark the events you will look for most. + +| Search for | Meaning | +|---|---| +| `Completed processing vCon` | A chain finished | +| `halted chain processing` | A link returned a falsy value, so egress and storage were skipped | +| `Moving to DLQ` | A chain failed and the vCon went to the ingress DLQ | +| `Moving to storage DLQ` | A write to one backend failed | +| `manual recovery required` | A failed write could not reach the storage DLQ | +| `Deprecated link module` | A chain uses a legacy transcribe module | ```bash -# Docker logs -docker logs -f vcon-server-conserver-1 +# Find one vCon +docker compose logs conserver | grep "" + +# Count the log levels +docker compose logs conserver | grep -oE '"levelname": "[A-Z]+"' | sort | uniq -c -# With timestamps -docker logs -t vcon-server-conserver-1 +# Parse JSON and skip any line that is not JSON +docker compose logs conserver --no-log-prefix | jq -R 'fromjson? | select(.levelname == "ERROR")' ``` -## Log Analysis +Some output, such as library messages, is not JSON. The `fromjson?` filter skips those lines. -### Common Patterns +## Turn on debug output -**Find errors:** +Make your own copy of a config file and lower two levels. `docker-compose.yml` mounts the repo at `/app`, so a file in the repo root is visible in the containers. ```bash -docker compose logs conserver | grep -i error +cp common/logging_dev.conf logging_debug.conf ``` -**Find specific vCon:** +In `logging_debug.conf`, set `level = DEBUG` under `[logger_root]` and under `[handler_custom_info]`. The `main` and `api` loggers are already at `DEBUG`. ```bash -docker compose logs conserver | grep "abc-123" +# In .env +LOGGING_CONFIG_FILE=/app/logging_debug.conf ``` -**Count log levels:** - ```bash -docker compose logs conserver | grep -oE '"level": "[A-Z]+"' | sort | uniq -c +docker compose up -d conserver api ``` -**Parse JSON logs with jq:** +To debug one area, keep `[handler_custom_info]` at `DEBUG`, put `[logger_root]` back to `INFO` and add a logger. Add its name to `keys` under `[loggers]` first. -```bash -docker compose logs conserver --no-log-prefix | jq -r 'select(.level == "ERROR")' +```ini +[loggers] +keys = root, vcon, uvicorn, main, api, links + +[logger_links] +level = DEBUG +handlers = custom_info +propagate = 0 +qualname = links +``` + +Debug output is heavy. The worker logs each link of each vCon at `DEBUG`, so turn it off when you finish. + +## Limit the log size + +`docker-compose.yml` sets no log limits, so the default driver can fill a disk. Add a limit for each service: + +```yaml +services: + conserver: + logging: + driver: "json-file" + options: + max-size: "10m" + max-file: "5" ``` -### Log Aggregation +The server writes no log files of its own, so there is nothing to rotate inside the containers. + +## Forward logs to an aggregator -#### Fluentd +The server logs to stdout, so forwarding is a Docker or platform setting. In Kubernetes, use your cluster's log agent. + +### Use Fluentd ```yaml -# docker-compose.yml services: fluentd: image: fluent/fluentd:v1.16 @@ -246,7 +181,7 @@ services: tag: vcon.conserver ``` -#### Loki +### Use Loki ```yaml services: @@ -262,170 +197,62 @@ services: - ./promtail.yml:/etc/promtail/promtail.yml ``` -### Elasticsearch/Kibana - -```yaml -services: - elasticsearch: - image: docker.elastic.co/elasticsearch/elasticsearch:8.11.0 - environment: - - discovery.type=single-node - - kibana: - image: docker.elastic.co/kibana/kibana:8.11.0 - ports: - - "5601:5601" - - filebeat: - image: docker.elastic.co/beats/filebeat:8.11.0 - volumes: - - /var/lib/docker/containers:/var/lib/docker/containers:ro -``` - -## Debugging with Logs - -### Enable Debug Logging - -```bash -# Environment variable -LOG_LEVEL=DEBUG -LOGGING_CONFIG_FILE=server/logging_dev.conf - -# Restart services -docker compose restart conserver -``` - -### Debug Specific Components - -In `logging_dev.conf`: - -```ini -[logger_links] -level=DEBUG -handlers=console -qualname=links -propagate=0 - -[logger_storage] -level=DEBUG -handlers=console -qualname=storage -propagate=0 -``` - -### Trace Processing - -```bash -# Watch for specific vCon -docker compose logs -f conserver | grep "uuid-to-trace" - -# Watch processing steps -docker compose logs -f conserver | grep -E "(Starting|Completed|Error)" -``` - -## Log Rotation - -### Docker Log Rotation +### Use CloudWatch ```yaml -# docker-compose.yml services: conserver: logging: - driver: "json-file" + driver: "awslogs" options: - max-size: "10m" - max-file: "5" + awslogs-region: us-east-1 + awslogs-group: vcon-server + awslogs-stream: "{{.Name}}" ``` -### Logrotate (Manual Installation) +### Use Elasticsearch and Kibana -``` -# /etc/logrotate.d/vcon-server -/var/log/vcon-server/*.log { - daily - rotate 7 - compress - delaycompress - missingok - notifempty - create 644 vcon vcon - postrotate - systemctl reload vcon-server - endscript -} -``` +Run Filebeat against `/var/lib/docker/containers`, read-only, and send to your Elasticsearch cluster. The JSON format needs no parsing rules. -## Structured Logging Best Practices +## Write good log lines -### Include Context +Pass context through `extra`, so it reaches the JSON output as fields: ```python -logger.info("Processing vCon", extra={ - "vcon_uuid": uuid, - "chain": chain_name, - "link": link_name -}) +logger.info("Saved vCon", extra={"chain": chain_name, "link": link_name}) ``` -### Use Appropriate Levels - -| Level | Use For | +| Level | Use for | |-------|---------| -| DEBUG | Detailed diagnostic info | +| DEBUG | Detailed diagnostic information | | INFO | General operational events | | WARNING | Unexpected but handled situations | -| ERROR | Failures requiring attention | +| ERROR | Failures that need attention. With Sentry on, these become events | | CRITICAL | System-wide failures | -### Avoid Sensitive Data +Never log secrets or conversation content. Log the vCon UUID instead. ```python # Bad logger.info(f"Processing vCon with API key {api_key}") # Good -logger.info(f"Processing vCon {uuid}") +logger.info("Processing vCon %s", vcon_uuid) ``` -## Troubleshooting - -### No Logs Appearing +## Fix the common logging problems -Check logging configuration: +**A process exits at import with a logging error.** Check the path in `LOGGING_CONFIG_FILE`: ```bash -# Verify environment -docker compose exec conserver env | grep LOG - -# Check file exists -docker compose exec conserver cat /app/server/logging.conf -``` - -### Too Many Logs - -Increase log level: - -```bash -LOG_LEVEL=WARNING +docker compose exec conserver env | grep LOGGING_CONFIG_FILE +docker compose exec conserver ls /app/common/logging.conf ``` -### JSON Parse Errors +If the container exits too fast for `exec`, read `docker compose logs conserver` and check `.env`. -Some logs may not be JSON (e.g., library output): +**Too many logs.** Raise a level in your config file. `LOG_LEVEL` does nothing. -```bash -# Filter valid JSON only -docker compose logs conserver --no-log-prefix 2>/dev/null | while read line; do - echo "$line" | jq . 2>/dev/null || true -done -``` - -### Logs Missing Timestamps +**No debug lines appear.** Lower both the logger and the handler. See [Turn on debug output](#turn-on-debug-output). -Ensure formatter includes timestamps: - -```ini -[formatter_json] -format={"timestamp": "%(asctime)s", ...} -``` +**jq fails on some lines.** Use `jq -R 'fromjson?'` as shown in [Search the logs](#search-the-logs). diff --git a/docs/operations/monitoring.md b/docs/operations/monitoring.md index de907357..f6856343 100644 --- a/docs/operations/monitoring.md +++ b/docs/operations/monitoring.md @@ -1,110 +1,100 @@ -# Monitoring +# Monitor the server -This guide covers monitoring, observability, and alerting for vCon Server. +This page shows how to check the server, publish its telemetry and alert on the failures that matter. The [metrics reference](../reference/metrics.md) lists every metric name, and the [environment reference](../reference/environment.md) lists every variable. -## Health Endpoints +![Metrics, traces, errors and chain tracers leaving the API and worker processes, with the Redis reads behind them](../diagrams/D14-observability.svg) -### API Health +## Check the server health -```bash -curl http://localhost:8000/api/health -``` - -Response: - -```json -{"status": "healthy"} -``` - -### Version Information +Three monitoring routes need no API token. The FastAPI `/docs`, `/redoc` and `/openapi.json` pages are also open. See the [API reference](../reference/api.md#monitor-the-server) for the responses. ```bash +curl http://localhost:8000/api/health curl http://localhost:8000/api/version +curl "http://localhost:8000/api/stats/queue?list_name=default" ``` -Response: +`/health` returns a fixed `healthy` status with the version details. It proves that the API process answers and nothing more. It does not touch Redis or the workers, so pair it with a queue depth check and a Redis check. -```json -{ - "version": "2024.01.15", - "git_commit": "a1b2c3d", - "build_time": "2024-01-15T10:30:00Z" -} -``` - -## Key Metrics +The version fields come from the image build. Outside a built image they read `dev` and `unknown`. Every API response also carries `X-Vcon-Server-Version` and `X-Vcon-Server-Commit` headers. -### Queue Metrics +## Read the queue depth -| Metric | Command | Description | -|--------|---------|-------------| -| Ingress Depth | `LLEN {ingress_list}` | Items waiting to process | -| Egress Depth | `LLEN {egress_list}` | Processed items awaiting pickup | -| DLQ Depth | `LLEN DLQ:{ingress_list}` | Failed items | +| Queue | Redis list | Holds | +|---|---|---| +| Ingress | `` | Ids waiting for a worker | +| Egress | `` | Processed ids awaiting pickup | +| Ingress DLQ | `DLQ:` | Ids whose chain failed | +| Storage DLQ | `DLQ:storage:` | Ids whose write to one backend failed | ```bash -# Check queue depths +# Through the API, for any Redis list +curl "http://localhost:8000/api/stats/queue?list_name=DLQ:default" + +# In Redis docker compose exec redis redis-cli LLEN default -docker compose exec redis redis-cli LLEN DLQ:default -# Watch queue depth over time +# Watch the depth over time watch -n 5 'docker compose exec -T redis redis-cli LLEN default' ``` -### Processing Metrics +## Watch the key signals -| Metric | Description | Target | -|--------|-------------|--------| -| Processing Rate | vCons/minute | Depends on volume | -| Processing Latency | Time per vCon | < 30s typical | -| Error Rate | Failed/Total | < 5% | -| DLQ Growth | New DLQ items/hour | 0 | +Set thresholds from your own baseline. The [metrics reference](../reference/metrics.md) gives each metric's type and attributes. -### Resource Metrics +| Signal | Metric | Watch for | +|---|---|---| +| Ingress depth | `conserver.ingress_list.length` with `kind="ingress"` | Sustained growth | +| Ingress DLQ depth | `conserver.ingress_list.length` with `kind="dlq"` | Anything above 0 | +| Storage DLQ growth | `conserver.dlq.count` with a `DLQ:storage:` queue name | Any increase | +| Chain time | `conserver.main_loop.vcon_processing_time` | A rising upper percentile | +| Throughput | `conserver.main_loop.count_vcons_processed` | A drop against the ingress rate | +| Link errors | `conserver.link.count` with `outcome="error"` | Any sustained rate | +| Storage errors | `conserver.storage.count` with `outcome="error"` | Any sustained rate | +| In-flight work | `conserver.vcons.inflight` | Stuck at the concurrency limit | +| Redis memory | `conserver.redis.memory_used_bytes` | Nearing the limit | -| Metric | Description | Alert Threshold | -|--------|-------------|-----------------| -| CPU Usage | Container CPU % | > 80% | -| Memory Usage | Container memory | > 80% | -| Disk Usage | Storage volume | > 80% | -| Network I/O | Bytes in/out | Baseline + 50% | +The depth gauge covers configured ingress lists and their DLQs. It does not sample storage DLQs, so read those through `/stats/queue` or with `LLEN`. -## OpenTelemetry Integration +Take CPU, memory, disk and network figures from your container platform. The server does not publish them. -vCon Server includes OpenTelemetry instrumentation. +## Publish the telemetry -### Enable Tracing +The server has two separate OpenTelemetry pipelines. + +**Metrics** go through `common/lib/metrics.py`. They publish only when `OTEL_EXPORTER_OTLP_ENDPOINT` is set, and always over OTLP gRPC, whatever `OTEL_EXPORTER_OTLP_PROTOCOL` says. Each process exports with its own `service.instance.id`, so sum across instances for a total. + +**Traces** come from `opentelemetry-instrument`, which wraps both processes in `docker-compose.yml`. Workers open one span per vCon, with `link.*` and `storage.*` children, and `init_tracing` adds OpenAI LLM spans. The API has only auto-instrumented request spans. + +Set the endpoint in `.env`. `docker-compose.yml` passes the `OTEL_EXPORTER_OTLP_*` variables through. ```bash -# Environment variables -OTEL_SERVICE_NAME=vcon-server OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317 -OTEL_TRACES_EXPORTER=otlp -OTEL_METRICS_EXPORTER=otlp +OTEL_EXPORTER_OTLP_PROTOCOL=grpc ``` -### Docker Compose with Collector +`docker-compose.yml` sets `OTEL_SERVICE_NAME` to `conserver` and `api`, so a value in `.env` has no effect on those services. Outside Compose the metrics default is `vcon-server`. + +### Run a collector + +Add the collector to `docker-compose.yml`: ```yaml services: otel-collector: - image: otel/opentelemetry-collector:latest + image: otel/opentelemetry-collector-contrib:latest command: ["--config=/etc/otel-collector-config.yaml"] volumes: - ./otel-collector-config.yaml:/etc/otel-collector-config.yaml ports: - "4317:4317" # OTLP gRPC - "4318:4318" # OTLP HTTP + - "8889:8889" # Prometheus scrape networks: - conserver - - conserver: - environment: - - OTEL_SERVICE_NAME=vcon-server - - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317 ``` -### Collector Configuration +Then configure it. This example sends traces to Jaeger and exposes metrics for Prometheus. ```yaml # otel-collector-config.yaml @@ -120,16 +110,13 @@ processors: batch: exporters: - logging: - loglevel: debug - - # Jaeger for traces - jaeger: - endpoint: jaeger:14250 + debug: + + otlp/jaeger: + endpoint: jaeger:4317 tls: insecure: true - - # Prometheus for metrics + prometheus: endpoint: "0.0.0.0:8889" @@ -138,91 +125,42 @@ service: traces: receivers: [otlp] processors: [batch] - exporters: [jaeger, logging] + exporters: [otlp/jaeger, debug] metrics: receivers: [otlp] processors: [batch] exporters: [prometheus] ``` -### Langfuse Integration - -Langfuse accepts traces via the standard OTLP HTTP endpoint — no separate collector needed. +### Send traces to Langfuse -#### Step 1 — Generate your auth header +Langfuse accepts traces over OTLP HTTP. Metrics cannot follow, since the metrics exporter is gRPC only. If you want metrics too, use [a collector to fan out](#fan-out-to-several-backends). -In Langfuse, go to **Settings → API Keys** and copy your Public Key and Secret Key. Then run: +In Langfuse, open the API keys page in its settings and copy your public and secret keys. Then build the auth header: ```bash echo -n "pk-lf-YOUR_PUBLIC_KEY:sk-lf-YOUR_SECRET_KEY" | base64 ``` -Copy the output for the next step. - -#### Step 2 — Set environment variables - -Add the following to your `.env` file: +Add these to `.env`: ```bash OTEL_EXPORTER_OTLP_ENDPOINT=http://:3000/api/public/otel OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf -OTEL_EXPORTER_OTLP_HEADERS=Authorization=Basic -``` - -For Langfuse Cloud use: - -```bash -OTEL_EXPORTER_OTLP_ENDPOINT=https://cloud.langfuse.com/api/public/otel +OTEL_EXPORTER_OTLP_HEADERS=Authorization=Basic ``` -Traces will appear in Langfuse under the service names `conserver` and `api`. - -### Sending to Multiple Backends (Fan-out via OTel Collector) - -vCon Server can only point to one OTLP endpoint via environment variables. To fan out to multiple backends simultaneously, use the OTel Collector as a proxy. The example below uses SigNoz and Langfuse, but the same pattern works with any two OTLP-compatible backends. - -``` -vcon-server ──OTLP──▶ OTel Collector ──▶ Backend A (gRPC :4317) - └──▶ Backend B (HTTP) -``` - -#### Step 1 — Point vCon Server at the collector - -In your `.env`: - -```bash -OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317 -OTEL_EXPORTER_OTLP_PROTOCOL=grpc -``` - -No auth header needed here — the collector handles authentication to each backend separately. - -#### Step 2 — Add the collector to docker-compose.yml - -```yaml -services: - otel-collector: - image: otel/opentelemetry-collector-contrib:latest - command: ["--config=/etc/otel-collector-config.yaml"] - volumes: - - ./otel-collector-config.yaml:/etc/otel-collector-config.yaml - ports: - - "4317:4317" - networks: - - conserver -``` +For Langfuse Cloud, use `https://cloud.langfuse.com/api/public/otel` as the endpoint. -> Use `otel/opentelemetry-collector-contrib` (not the slim `otel/opentelemetry-collector`) — it includes the `otlphttp` exporter needed for Langfuse. +Traces appear under the service names `conserver` and `api`. -#### Step 3 — Configure the collector (otel-collector-config.yaml) +For local testing, `docker-compose.yml` has a `langfuse` profile with development credentials. Its comments give the `.env` values. Never use those credentials in production. -Generate your Langfuse Basic auth token first: +### Fan out to several backends -```bash -echo -n "pk-lf-YOUR_PUBLIC_KEY:sk-lf-YOUR_SECRET_KEY" | base64 -``` +The server points at one OTLP endpoint. To reach several backends, send everything to a collector and let it fan out. This example uses SigNoz over gRPC and Langfuse over HTTP, and the same pattern works with any two OTLP backends. -Then create `otel-collector-config.yaml`: +Point the server at the collector as shown in [Publish the telemetry](#publish-the-telemetry), with no auth header. The collector authenticates to each backend itself. Then configure the collector: ```yaml receivers: @@ -235,13 +173,11 @@ processors: batch: exporters: - # SigNoz — receives OTLP gRPC otlp/signoz: endpoint: :4317 tls: insecure: true - # Langfuse — receives OTLP HTTP otlphttp/langfuse: endpoint: http://:3000/api/public/otel headers: @@ -259,23 +195,15 @@ service: exporters: [otlp/signoz] ``` -> Langfuse only ingests **traces** (LLM spans). Metrics go to SigNoz only. - -Traces will appear in both backends. In Langfuse, look under service names `conserver` and `api`. +Langfuse ingests only traces, so metrics go to SigNoz alone. ---- +### Send telemetry to Datadog -## Prometheus Integration +The server has no Datadog library, so `DD_*` application settings do nothing. Send OTLP to a collector or to a Datadog Agent with OTLP intake enabled, and follow the Datadog documentation for that side. -### Metrics Endpoint - -If using OpenTelemetry with Prometheus exporter: - -```bash -curl http://localhost:8889/metrics -``` +## Scrape the metrics with Prometheus -### Prometheus Configuration +The server exposes no metrics port of its own. Prometheus scrapes the collector. ```yaml # prometheus.yml @@ -283,71 +211,29 @@ scrape_configs: - job_name: 'vcon-server' static_configs: - targets: ['otel-collector:8889'] - - - job_name: 'redis' - static_configs: - - targets: ['redis-exporter:9121'] ``` -### Key Prometheus Queries - -```promql -# Processing rate (vCons per minute) -rate(vcon_processed_total[5m]) * 60 - -# Error rate -rate(vcon_processing_errors_total[5m]) / rate(vcon_processed_total[5m]) - -# Average processing duration -histogram_quantile(0.95, rate(vcon_processing_duration_seconds_bucket[5m])) - -# Queue depth -redis_list_length{list="default"} -``` +The collector's Prometheus exporter rewrites names. Dots become underscores and counters gain `_total`, so `conserver.dlq.count` becomes `conserver_dlq_count_total`. Attribute dots change too, so `chain.name` becomes `chain_name`. Check the names at `http://localhost:8889/metrics`, since exporter settings can change them. -## Datadog Integration + -### Agent Configuration +```promql +# vCons finished per minute +sum(rate(conserver_main_loop_count_vcons_processed_total[5m])) * 60 -```yaml -# docker-compose.yml -services: - datadog-agent: - image: datadog/agent:latest - environment: - - DD_API_KEY=${DD_API_KEY} - - DD_SITE=datadoghq.com - - DD_APM_ENABLED=true - - DD_LOGS_ENABLED=true - volumes: - - /var/run/docker.sock:/var/run/docker.sock:ro - - /proc/:/host/proc/:ro - - /sys/fs/cgroup/:/host/sys/fs/cgroup:ro - networks: - - conserver -``` +# Share of link runs that failed +sum(rate(conserver_link_count_total{outcome="error"}[5m])) + / sum(rate(conserver_link_count_total[5m])) -### Application Configuration +# 95th percentile chain time in seconds +histogram_quantile(0.95, + sum by (le) (rate(conserver_main_loop_vcon_processing_time_bucket[5m]))) -```bash -# Enable Datadog APM -DD_AGENT_HOST=datadog-agent -DD_TRACE_ENABLED=true -DD_PROFILING_ENABLED=true +# Ingress depth. Each worker process reports the gauge, so take the maximum. +max by (ingress_list) (conserver_ingress_list_length{kind="ingress"}) ``` -### Datadog Dashboards - -Create dashboards for: - -1. **Overview**: Health, version, uptime -2. **Processing**: Queue depths, throughput, latency -3. **Errors**: DLQ depth, error rates, error types -4. **Resources**: CPU, memory, network, disk - -## Grafana Dashboards - -### Sample Dashboard JSON +## Build a Grafana dashboard ```json { @@ -355,30 +241,30 @@ Create dashboards for: "title": "vCon Server", "panels": [ { - "title": "Queue Depth", - "type": "graph", + "title": "Queue depth", + "type": "timeseries", "targets": [ { - "expr": "redis_list_length{list=~\"default|production\"}", - "legendFormat": "{{list}}" + "expr": "max by (ingress_list) (conserver_ingress_list_length{kind=\"ingress\"})", + "legendFormat": "{{ingress_list}}" } ] }, { - "title": "Processing Rate", + "title": "vCons per minute", "type": "stat", "targets": [ { - "expr": "rate(vcon_processed_total[5m]) * 60" + "expr": "sum(rate(conserver_main_loop_count_vcons_processed_total[5m])) * 60" } ] }, { - "title": "DLQ Items", + "title": "DLQ items", "type": "stat", "targets": [ { - "expr": "redis_list_length{list=~\"DLQ:.*\"}" + "expr": "sum(max by (ingress_list) (conserver_ingress_list_length{kind=\"dlq\"}))" } ] } @@ -387,9 +273,7 @@ Create dashboards for: } ``` -## Alerting - -### Alert Rules +## Write the alert rules ```yaml # prometheus-alerts.yml @@ -397,42 +281,46 @@ groups: - name: vcon-server rules: - alert: HighQueueDepth - expr: redis_list_length{list="default"} > 1000 + expr: max by (ingress_list) (conserver_ingress_list_length{kind="ingress"}) > 1000 for: 5m labels: severity: warning annotations: summary: "Queue depth is high" - description: "Queue {{ $labels.list }} has {{ $value }} items" + description: "Queue {{ $labels.ingress_list }} has {{ $value }} items" - - alert: DLQNotEmpty - expr: redis_list_length{list=~"DLQ:.*"} > 0 + - alert: IngressDLQNotEmpty + expr: max by (ingress_list) (conserver_ingress_list_length{kind="dlq"}) > 0 for: 5m labels: severity: warning annotations: - summary: "DLQ has items" - description: "DLQ {{ $labels.list }} has {{ $value }} items" + summary: "An ingress DLQ has items" + description: "DLQ for {{ $labels.ingress_list }} has {{ $value }} items" - - alert: HighErrorRate - expr: rate(vcon_processing_errors_total[5m]) / rate(vcon_processed_total[5m]) > 0.05 - for: 5m + - alert: StorageDLQGrowing + expr: sum by (queue_name) (increase(conserver_dlq_count_total{queue_name=~"DLQ:storage:.*"}[15m])) > 0 labels: - severity: critical + severity: warning annotations: - summary: "High error rate" - description: "Error rate is {{ $value | humanizePercentage }}" + summary: "Storage writes are failing" + description: "{{ $labels.queue_name }} gained entries" - - alert: ServiceDown - expr: up{job="vcon-server"} == 0 - for: 1m + - alert: HighLinkErrorRate + expr: | + sum(rate(conserver_link_count_total{outcome="error"}[5m])) + / sum(rate(conserver_link_count_total[5m])) > 0.05 + for: 5m labels: severity: critical annotations: - summary: "vCon Server is down" + summary: "High link error rate" + description: "Error rate is {{ $value | humanizePercentage }}" ``` -### PagerDuty Integration +Treat 1000 items and 5% as examples. The `up` metric for this scrape job describes the collector, not the server, so probe `/health` with a blackbox check to catch a dead API. A stalled worker shows up as rising ingress depth. + +### Route alerts to PagerDuty ```yaml # alertmanager.yml @@ -450,95 +338,57 @@ route: receiver: 'pagerduty' ``` -## Custom Monitoring Script +## Report errors to Sentry + +Set `SENTRY_DSN` and `ENV` to turn on Sentry for the conserver side. Logging at `ERROR` becomes an event, and `INFO` and above become breadcrumbs. The API process does not initialize Sentry. See the [environment reference](../reference/environment.md). + +## Record chain events with a tracer + +Tracers are separate from OpenTelemetry. Every entry under `tracers` in the config runs before the first link and after each link. The repo ships one, described in the [JLINC tracer reference](../reference/tracers/jlinc.md). + +## Script a monitoring check ```bash #!/bin/bash -# monitor.sh - Custom monitoring script +# monitor.sh API_URL="${API_URL:-http://localhost:8000/api}" -TOKEN="${CONSERVER_API_TOKEN}" +QUEUE="${QUEUE:-default}" THRESHOLD_QUEUE=100 -THRESHOLD_DLQ=0 -# Check API health health=$(curl -s "$API_URL/health" | jq -r .status) if [ "$health" != "healthy" ]; then echo "CRITICAL: API health check failed" exit 2 fi -# Check queue depth -queue_depth=$(docker compose exec -T redis redis-cli LLEN default) +redis_ping=$(docker compose exec -T redis redis-cli ping) +if [ "$redis_ping" != "PONG" ]; then + echo "CRITICAL: Redis did not answer" + exit 2 +fi + +queue_depth=$(curl -s "$API_URL/stats/queue?list_name=$QUEUE" | jq -r .depth) if [ "$queue_depth" -gt "$THRESHOLD_QUEUE" ]; then echo "WARNING: Queue depth is $queue_depth (threshold: $THRESHOLD_QUEUE)" exit 1 fi -# Check DLQ -dlq_depth=$(docker compose exec -T redis redis-cli LLEN DLQ:default) -if [ "$dlq_depth" -gt "$THRESHOLD_DLQ" ]; then +dlq_depth=$(curl -s "$API_URL/stats/queue?list_name=DLQ:$QUEUE" | jq -r .depth) +if [ "$dlq_depth" -gt 0 ]; then echo "WARNING: DLQ has $dlq_depth items" exit 1 fi echo "OK: All checks passed" -exit 0 ``` -## Logging Integration - -### Ship Logs to ELK - -```yaml -# docker-compose.yml -services: - conserver: - logging: - driver: "fluentd" - options: - fluentd-address: localhost:24224 - tag: vcon.server -``` - -### Ship Logs to CloudWatch - -```yaml -services: - conserver: - logging: - driver: "awslogs" - options: - awslogs-region: us-east-1 - awslogs-group: vcon-server - awslogs-stream: "{{.Name}}" -``` - -## Best Practices - -### 1. Monitor All Layers - -- Application (processing rate, errors) -- Infrastructure (CPU, memory, disk) -- Dependencies (Redis, databases) -- External services (Deepgram, OpenAI) - -### 2. Set Meaningful Alerts - -- Alert on symptoms, not causes -- Use appropriate thresholds -- Include runbook links in alerts -- Avoid alert fatigue - -### 3. Visualize Trends +## Ship the logs -- Historical processing rates -- Queue depth over time -- Error patterns -- Resource usage trends +See [Forward logs to an aggregator](logging.md#forward-logs-to-an-aggregator). -### 4. Regular Review +## Review the coverage -- Weekly review of dashboards -- Monthly alert threshold review -- Quarterly capacity planning +- Monitor each layer: the application, the host, Redis and your storage backends, and external services such as Deepgram and OpenAI. +- Alert on symptoms, and link a runbook from each alert. [Dead letter queues](dead-letter-queue.md) and [storage recovery](storage-recovery.md) are good targets. +- Review dashboards and thresholds on a regular schedule, and revisit capacity as volume changes. diff --git a/docs/operations/storage-recovery.md b/docs/operations/storage-recovery.md new file mode 100644 index 00000000..299f28e8 --- /dev/null +++ b/docs/operations/storage-recovery.md @@ -0,0 +1,104 @@ +# Recover failed storage writes + +This page shows how to find a failed backend write and replay it without running the chain again, so recovery never repeats transcription or analysis. + +![Sequence of a storage write after the last link, the storage DLQ path and the operator replay](../diagrams/D09-storage-write-recovery.svg) + +## Follow a failed write + +A failed backend write enters `DLQ:storage:`. It does not re-enter the processing chain. Other backends and egress continue, because the worker pushes to egress lists before it writes to storage. Each failed backend gets its own entry, so a vCon can sit in one storage DLQ after another backend saved it. + +Watch two metrics, both described in the [metrics reference](../reference/metrics.md): + +- `conserver.storage.count` with `outcome="error"` +- `conserver.dlq.count` with `queue_name="DLQ:storage:"` + +The `conserver.ingress_list.length` gauge samples ingress DLQs only. To read the depth of a storage DLQ, use [`GET /stats/queue`](../reference/api.md#read-queue-depth) with `list_name=DLQ:storage:`, or `LLEN` in Redis. + +## Keep the vCon body + +The queue holds an id, and the body stays in Redis under `vcon:`. One Redis script extends the body's retention and adds the entry, so the two steps happen together. + +`VCON_DLQ_EXPIRY` sets the retention. See the [environment reference](../reference/environment.md) for its default. A shorter TTL rises to that value. A longer TTL or a persistent body stays as it is. Zero leaves the TTL unchanged, so the body can still expire on its old schedule. + +If the body is missing or Redis fails, no entry is written. The worker logs `Could not durably dead-letter vCon for storage ; manual recovery required` and carries on. Replay cannot reach that write. Take the UUID from the log. Once Redis is healthy and the body exists, add the entry by hand with `RPUSH DLQ:storage: `, or resubmit the vCon from its source. + +Redis durability and capacity remain prerequisites. This is not a second durable store, so recover before the body expires. + +## Replay the failed writes + +Use the API's root path and normal authentication. In the examples, `$API` is your base URL, such as `http://localhost:8000/api`. The [API reference](../reference/api.md#work-with-dead-letter-queues) gives the parameters and status codes. + +```bash +# List pending UUIDs +curl "$API/dlq/storage?storage_name=" -H "x-conserver-api-token: $TOKEN" + +# Retry a bounded snapshot. The response is the number written. +curl -X POST "$API/dlq/storage/reprocess?storage_name=&count=10" \ + -H "x-conserver-api-token: $TOKEN" +``` + +Start with a small count, because the default is large. The API process runs the save itself, in its threadpool, so it needs the same configuration, credentials and network reach to the backend as the workers. A `file` backend must be a volume shared by `api` and `conserver`, or the replayed file lands in a different container and the replay still counts it as written. See [the file adapter](../reference/storage-adapters/file.md). + +A `404` with `Unknown storage backend` means the backend is not configured or its adapter fails to load in the API process. + +Entries leave the queue only after a successful write. A failed write stops the batch and leaves its entry queued. A stopped API process or a failed acknowledgement also leaves entries replayable. + +This is at-least-once delivery. An interrupted replay can repeat a successful save, so check that the backend tolerates repeated writes of the same UUID. + +## Clear a blocked entry + +Replay reads from the head of the list and stops at the first failure. An entry that can never succeed therefore blocks every entry behind it, on each replay. + +The usual cause is a body that has expired. `get_vcon` falls back to the configured storages on a Redis miss, unless `VCON_STORAGE_FALLBACK_ENABLED` is off, so the write can still succeed if another backend holds the vCon. If nothing holds it, most adapters raise. + +```bash +# Check the first entry +docker compose exec redis redis-cli LINDEX DLQ:storage: 0 +docker compose exec redis redis-cli EXISTS vcon: + +# With no replay running, move that entry to the tail so the rest can drain +docker compose exec redis redis-cli LMOVE DLQ:storage: DLQ:storage: LEFT RIGHT +``` + +## Recover the replay lock + +A Redis lock serializes replay per backend across API processes. A concurrent replay returns HTTP 409. + +The lock deliberately has no expiry, so a slow backend cannot let a second replay acknowledge entries from an earlier snapshot. Normal completion and errors release it. A process crash leaves it in place, and every later replay then returns 409. + +To recover after a crash: + +1. Stop or confirm the termination of every replay for that backend. +2. Delete only `DLQ:storage::replay-lock`. +3. Retry the replay. + +Never clear a lock while a replay might still be running. Preserve the DLQ list and the vCon bodies. + +## Check the adapter behaviour + +An adapter reaches the storage DLQ only by raising. The [storage adapter reference](../reference/storage-adapters/index.md) describes each one. Three cases matter most for recovery. + +`vcon_mcp` retries transient failures itself before it raises, and respects `Retry-After`. Permanent 4xx responses are not retried. POST retries rely on the backend's UUID-based upsert. See [its options](../reference/storage-adapters/vcon_mcp.md). + +`webhook` propagates HTTP 4xx and 5xx responses and transport failures to the storage DLQ. It does not retry arbitrary POST receivers, because their idempotency is unknown. With several URLs, an earlier URL may have succeeded before a later one failed, so every receiver must tolerate duplicate writes. See [its options](../reference/storage-adapters/webhook.md). + +`spaceandtime` logs a failed write and returns, and `scitt` returns when the vCon is missing. Both count as a success, so neither produces a DLQ entry for those cases. + +The same applies to replay: an entry for one of these adapters leaves the DLQ and counts as written even though nothing was stored. Check the body exists before you replay them, and read the log after a `spaceandtime` replay, since any error there is swallowed. `chatgpt_files` reads Redis without the `vcon:` prefix, so it uploads `null` and also counts a success. + +## Validate the path before production rollout + +Use an isolated Redis instance and a disposable HTTP receiver, and never create a production backend outage for this test. + +1. Make the receiver return 503. +2. With `vcon_mcp`, confirm bounded retries. With `webhook`, confirm a single attempt. Then confirm a per-backend DLQ entry and a retained body. +3. Restore successful responses and replay. +4. Verify the receiver stored one UUID and no processing link ran. +5. Stop a replay during a write and confirm its UUID stays queued. + +## Release the images together + +Release the conserver and API images together. Deployments that build on these images must update both base images. Updating only the workers queues failures with no recovery endpoint to drain them. + +Keep the previous images for rollback. A rollback must not clear `DLQ:storage:*`, and images without these routes cannot replay those queues. After rollout, verify versions, health, storage error alerts and queue depth before a small replay. diff --git a/docs/operations/troubleshooting.md b/docs/operations/troubleshooting.md index cb99dc54..c1f57e38 100644 --- a/docs/operations/troubleshooting.md +++ b/docs/operations/troubleshooting.md @@ -1,13 +1,11 @@ -# Troubleshooting +# Fix common problems -Common issues and solutions for vCon Server. +This page lists common issues and their solutions. In the examples, `default` stands for your ingress list. -## Diagnostic Commands - -### Quick Health Check +## Run the diagnostics ```bash -# API health +# API health. This shows only that the API process answers. curl -s http://localhost:8000/api/health | jq . # Service status @@ -17,401 +15,333 @@ docker compose ps docker compose logs --tail=50 conserver # Queue status -docker compose exec redis redis-cli LLEN default -docker compose exec redis redis-cli LLEN DLQ:default +curl -s "http://localhost:8000/api/stats/queue?list_name=default" +curl -s "http://localhost:8000/api/stats/queue?list_name=DLQ:default" ``` -### Comprehensive Diagnostic Script +### Script the diagnostics ```bash #!/bin/bash # diagnose.sh -echo "=== vCon Server Diagnostics ===" -echo - -echo "1. Service Status:" +echo "1. Service status:" docker compose ps echo -echo "2. API Health:" +echo "2. API health:" curl -s http://localhost:8000/api/health 2>/dev/null || echo "API unreachable" echo -echo "3. Version:" -curl -s http://localhost:8000/api/version 2>/dev/null || echo "Cannot get version" +echo "3. Redis:" +docker compose exec -T redis redis-cli ping 2>/dev/null || echo "Redis unreachable" echo -echo "4. Queue Depths:" +echo "4. Queue depths:" echo " default: $(docker compose exec -T redis redis-cli LLEN default 2>/dev/null || echo 'N/A')" echo " DLQ:default: $(docker compose exec -T redis redis-cli LLEN DLQ:default 2>/dev/null || echo 'N/A')" echo -echo "5. Recent Errors:" -docker compose logs --tail=20 conserver 2>&1 | grep -i error || echo " No recent errors" +echo "5. Recent errors:" +docker compose logs --tail=200 conserver 2>&1 | grep -i error || echo " No recent errors" echo -echo "6. Resource Usage:" +echo "6. Resource usage:" docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}" 2>/dev/null || echo " Cannot get stats" ``` -## Startup Issues - -### Services Won't Start +## Fix the startup problems -**Symptoms:** -- `docker compose up` fails -- Containers exit immediately +### Services fail to start -**Check:** +**Symptoms:** `docker compose up` fails, or containers exit immediately. ```bash -# View exit codes docker compose ps -a - -# Check logs for errors docker compose logs ``` -**Common Causes:** - -1. **Port already in use** - ```bash - # Find what's using port 8000 - lsof -i :8000 - - # Change port in docker-compose.yml - ports: - - "8080:8000" - ``` - -2. **Missing environment variables** - ```bash - # Check .env file exists - ls -la .env - - # Verify required variables - grep REDIS_URL .env - grep CONSERVER_API_TOKEN .env - ``` - -3. **Invalid configuration** - ```bash - # Validate YAML - python -c "import yaml; yaml.safe_load(open('config.yml'))" - ``` - -4. **Network not created** - ```bash - docker network create conserver - ``` - -### Redis Connection Failed - -**Symptoms:** -- `Connection refused` errors -- Workers not processing - -**Check:** +**Common causes:** + +1. **Port already in use.** Find what holds the port, then set `CONSERVER_EXTERNAL_PORT` in `.env` to publish the API elsewhere. + + ```bash + lsof -i :8000 + ``` + +2. **Missing environment variables.** See the [environment reference](../reference/environment.md). + + ```bash + ls -la .env + grep REDIS_URL .env + grep CONSERVER_API_TOKEN .env + ``` + +3. **Bad logging path.** `.env.example` sets `LOGGING_CONFIG_FILE=server/logging_dev.conf`, and that path does not exist. Remove the line or use `/app/common/logging_dev.conf`. See [Choose the log format](logging.md#choose-the-log-format). + +4. **Invalid configuration.** + + ```bash + python -c "import yaml; yaml.safe_load(open('config.yml'))" + ``` + +5. **Network not created.** The `conserver` network is external. + + ```bash + docker network create conserver + ``` + +### Redis connection fails + +**Symptoms:** `Connection refused` errors, or workers not processing. ```bash -# Redis running? docker compose ps redis - -# Can connect? docker compose exec redis redis-cli ping ``` **Solutions:** -1. **Redis not started** - ```bash - docker compose up -d redis - ``` +1. **Redis not started.** -2. **Wrong URL** - ```bash - # Should match docker-compose service name - REDIS_URL=redis://redis:6379 - ``` + ```bash + docker compose up -d redis + ``` -3. **Network issue** - ```bash - # Recreate network - docker compose down - docker network rm conserver - docker network create conserver - docker compose up -d - ``` +2. **Wrong URL.** The host must match the Compose service name. -## Processing Issues + ```bash + REDIS_URL=redis://redis:6379 + ``` -### vCons Not Processing +3. **Network problem.** -**Symptoms:** -- Queue depth increasing -- No processing logs + ```bash + docker compose down + docker network rm conserver + docker network create conserver + docker compose up -d + ``` -**Check:** +4. **Data from an older Redis image.** Persistence files from an older image may not load. See the [Redis migration](../installation/redis-migration.md). -```bash -# Workers running? -docker compose ps conserver +## Fix the processing problems + +### vCons wait in the queue -# Processing logs? -docker compose logs --tail=50 conserver | grep -i "processing" +**Symptoms:** queue depth rises and the logs show no processing. -# Queue has items? -docker compose exec redis redis-cli LLEN default +```bash +docker compose ps conserver +docker compose logs --tail=50 conserver +curl -s "http://localhost:8000/api/stats/queue?list_name=default" ``` **Solutions:** -1. **Chain not enabled** - ```yaml - chains: - my_chain: - enabled: 1 # Must be 1 - ``` +1. **No chain reads the list.** The API accepts any list name. The name you submit to must appear under a chain's `ingress_lists`: + + ```yaml + chains: + my_chain: + ingress_lists: + - default + ``` + +2. **No ingress lists at all.** The worker logs `No ingress lists configured, retrying in 15s`. Check `CONSERVER_CONFIG_FILE`, which defaults to `./example_config.yml`. + +3. **Workers crashed.** + + ```bash + docker compose restart conserver + ``` + +A chain's `enabled` key does not help here, because the worker does not read it. A chain runs if it lists an ingress list. To stop a chain, remove its `ingress_lists`. -2. **Ingress list mismatch** - ```yaml - # Submission ingress_list must match chain - chains: - my_chain: - ingress_lists: - - default # Must match submission - ``` +### vCons finish but never reach storage -3. **Workers crashed** - ```bash - # Restart workers - docker compose restart conserver - ``` +**Symptoms:** the log shows `halted chain processing`, and no egress or storage follows. -### Slow Processing +A link returned a falsy value, which stops the chain with no error and no DLQ entry. Filter links do this on purpose. Check the link's [reference page](../reference/links/index.md). -**Symptoms:** -- High queue depth -- Long processing times +### Processing runs slowly -**Check:** +**Symptoms:** high queue depth and long processing times. ```bash -# Queue depth trend watch -n 5 'docker compose exec -T redis redis-cli LLEN default' - -# Processing logs docker compose logs -f conserver ``` **Solutions:** -1. **Scale workers** - ```bash - CONSERVER_WORKERS=4 - docker compose restart conserver - ``` +1. **Add worker capacity.** Set the values in `.env`, then recreate the service, since `docker compose restart` keeps the old environment. See [Configure the workers](../configuration/workers.md). + + ```bash + CONSERVER_WORKERS=4 + CONSERVER_VCON_CONCURRENCY=4 + ``` -2. **Enable parallel storage** - ```bash - CONSERVER_PARALLEL_STORAGE=true - ``` + ```bash + docker compose up -d conserver + ``` -3. **Check external API latency** - ```bash - # If using transcription - time curl -X POST https://api.deepgram.com/... - ``` +2. **Check parallel storage.** `CONSERVER_PARALLEL_STORAGE` is on by default, and helps only with two or more backends. -### DLQ Growing +3. **Check external services.** `conserver.link.execution_time` shows which link takes the time. See the [metrics reference](../reference/metrics.md). -**Symptoms:** -- Items appearing in DLQ -- Processing failures +### The DLQ grows -**Check:** +**Symptoms:** items appear in a DLQ. ```bash -# View DLQ contents curl "http://localhost:8000/api/dlq?ingress_list=default" \ -H "x-conserver-api-token: $TOKEN" -# Check logs for errors -docker compose logs conserver | grep -i error +docker compose logs conserver | grep "Moving to DLQ" ``` -**Solutions:** - -1. **Fix the root cause** (check error logs) +Fix the cause, then replay. See [Manage dead letter queues](dead-letter-queue.md). -2. **Reprocess after fix** - ```bash - curl -X POST "http://localhost:8000/api/dlq/reprocess?ingress_list=default" \ - -H "x-conserver-api-token: $TOKEN" - ``` +## Fix the API problems -## API Issues +### The API returns 403 -### 403 Forbidden - -**Symptoms:** -- API returns 403 -- "Invalid or missing API token" - -**Check:** +**Symptoms:** the response body is `{"detail":"Invalid API Key"}`, or `Invalid API Key for ingress list ''` on external ingress. ```bash -# Token set? echo $CONSERVER_API_TOKEN - -# Correct header? curl -v -H "x-conserver-api-token: $TOKEN" http://localhost:8000/api/vcon ``` **Solutions:** -1. **Set token in environment** - ```bash - export CONSERVER_API_TOKEN=your-token - ``` +1. **Set the token.** Set it in `.env`, then run `docker compose up -d api`. The API reads tokens only at startup. -2. **Check header name** - ```bash - # Default header - -H "x-conserver-api-token: $TOKEN" - - # Custom header (check CONSERVER_HEADER_NAME) - -H "$CUSTOM_HEADER: $TOKEN" - ``` +2. **Check the header name.** The default is `x-conserver-api-token`. `CONSERVER_HEADER_NAME` changes it. -3. **For external ingress, check ingress_auth** - ```yaml - ingress_auth: - partner_input: "partner-key" # Key must match - ``` +3. **Check `ingress_auth` for external ingress.** The key must match the list you submit to. -### 404 Not Found + ```yaml + ingress_auth: + customer_data: "customer-api-key-12345" + ``` -**Symptoms:** -- vCon not found -- Endpoint not found +See [Authentication](../configuration/authentication.md). + +### The API returns 404 + +**Symptoms:** vCon not found, or endpoint not found. **Solutions:** -1. **Check UUID exists** - ```bash - docker compose exec redis redis-cli EXISTS vcon:abc-123 - ``` +1. **Check the UUID in Redis.** + + ```bash + docker compose exec redis redis-cli EXISTS vcon: + ``` + +2. **Fetch it.** A GET looks in the configured storages when Redis has no copy. -2. **Sync from storage** - ```bash - # GET will sync from storage if not in Redis - curl http://localhost:8000/api/vcon/abc-123 -H "x-conserver-api-token: $TOKEN" - ``` + ```bash + curl http://localhost:8000/api/vcon/ -H "x-conserver-api-token: $TOKEN" + ``` -3. **Check API path** - ```bash - # Include /api prefix - curl http://localhost:8000/api/vcon # Correct - curl http://localhost:8000/vcon # Wrong - ``` +3. **Check the expiry.** A vCon that never reached a storage backend is gone once its Redis TTL ends. -### 500 Internal Server Error +4. **Check the route.** See the [generated route list](../reference/api-routes.md). -**Symptoms:** -- Server errors -- Unexpected failures +### The API returns 422 -**Check:** +The vCon body failed validation. A common cause is a `uuid` that is not a valid UUID. See the [body rules](../reference/api.md#meet-the-vcon-body-rules). + +### The API returns 500 ```bash -# API logs docker compose logs api | grep -i error ``` **Solutions:** -1. **Check configuration** - ```bash - curl http://localhost:8000/api/config -H "x-conserver-api-token: $TOKEN" - ``` +1. **Check the configuration.** + + ```bash + curl http://localhost:8000/api/config -H "x-conserver-api-token: $TOKEN" + ``` -2. **Restart API** - ```bash - docker compose restart api - ``` +2. **Restart the API.** -## Storage Issues + ```bash + docker compose restart api + ``` -### Storage Write Failures +## Fix the storage problems -**Symptoms:** -- Processing completes but data not persisted -- Storage-related errors in logs +### Storage writes fail -**Check:** +**Symptoms:** chains finish but data does not persist. The log shows `Moving to storage DLQ`. ```bash -# Check storage logs -docker compose logs conserver | grep -i storage +docker compose logs conserver | grep "storage DLQ" -# Test storage connectivity +# Test a backend. Use a name from your storages config. docker compose exec conserver python -c " -from storage import Storage +from storage.base import Storage s = Storage('postgres') -print(s.get('test-uuid')) +print(s.get('')) +" + +# Test the network path +docker compose exec conserver python -c " +import socket +socket.create_connection(('postgres', 5432), 3) +print('ok') " ``` **Solutions:** -1. **Check credentials** - ```yaml - storages: - postgres: - options: - user: correct_user - password: correct_password - ``` +1. **Check the credentials.** See the backend's page in the [adapter reference](../reference/storage-adapters/index.md). -2. **Check connectivity** - ```bash - docker compose exec conserver ping postgres - ``` +2. **Check the backend service.** -3. **Check storage service running** - ```bash - docker compose ps postgres - ``` + ```bash + docker compose ps postgres + ``` -### Storage Sync Issues +3. **Replay after the fix.** See [Recover failed storage writes](storage-recovery.md). -**Symptoms:** -- vCon in storage but not found via API +### Storage replay returns 409 -**Solutions:** +Another replay is running, or a crash left the lock behind. See [Recover the replay lock](storage-recovery.md#recover-the-replay-lock). + +### Storage replay stops early + +The batch stops at the first failed write. If the count stays at 0 with a healthy backend, an entry is blocking the queue. See [Clear a blocked entry](storage-recovery.md#clear-a-blocked-entry). + +### A stored vCon does not appear in the API + +**Symptoms:** a vCon is in storage but missing from list or search results. -1. **Force sync** - ```bash - # GET syncs from storage - curl http://localhost:8000/api/vcon/abc-123 -H "x-conserver-api-token: $TOKEN" - ``` +1. **Fetch it by UUID.** A GET finds it in storage and caches it back in Redis. It also adds a bare id to the sorted set, which can make `GET /vcon` return 500 for any page that holds it, as [the lifecycle page](../concepts/vcon-lifecycle.md#read-a-stored-vcon) warns. To clear that, remove the bare member with `ZREM vcons `. The fetch does not restore the party index. -2. **Rebuild index** - ```bash - curl http://localhost:8000/api/index_vcons -H "x-conserver-api-token: $TOKEN" - ``` + ```bash + curl http://localhost:8000/api/vcon/ -H "x-conserver-api-token: $TOKEN" + ``` -## Resource Issues +2. **Check the fallback.** `VCON_STORAGE_FALLBACK_ENABLED=false` turns the worker's read fallback off. -### High Memory Usage +3. **Rebuild the index for what Redis holds.** This route walks `vcon:*` keys in Redis only, so it cannot find a vCon that exists only in storage. A vCon that step 1 cached is in Redis, so this adds its prefixed key back to the list. See [the route](../reference/api.md#rebuild-the-search-index). -**Symptoms:** -- OOM kills -- Slow performance + ```bash + curl http://localhost:8000/api/index_vcons -H "x-conserver-api-token: $TOKEN" + ``` -**Check:** +## Fix the resource problems + +### Memory use runs high + +**Symptoms:** OOM kills or slow performance. ```bash docker stats @@ -419,51 +349,38 @@ docker stats **Solutions:** -1. **Reduce workers** - ```bash - CONSERVER_WORKERS=2 - ``` +1. **Reduce the workers.** Set `CONSERVER_WORKERS=2` in `.env`, then run `docker compose up -d conserver`. -2. **Use fork start method** - ```bash - CONSERVER_START_METHOD=fork - ``` +2. **Review the start method.** `CONSERVER_START_METHOD` affects memory, and `fork` has a shutdown caveat. See [Configure the workers](../configuration/workers.md). -3. **Add memory limits** - ```yaml - services: - conserver: - deploy: - resources: - limits: - memory: 2G - ``` +3. **Add memory limits.** -### High CPU Usage + ```yaml + services: + conserver: + deploy: + resources: + limits: + memory: 2G + ``` -**Symptoms:** -- CPU at 100% -- Slow response +4. **Check Redis.** The Compose service has `mem_limit: 1gb`. A large DLQ keeps bodies in Redis for days. -**Solutions:** +### CPU use runs high + +**Symptoms:** CPU at 100% and slow responses. -1. **Check for processing loops** - ```bash - docker compose logs conserver | tail -100 - ``` +1. **Look for repeated failures.** -2. **Reduce workers** - ```bash - CONSERVER_WORKERS=2 - ``` + ```bash + docker compose logs --tail=100 conserver + ``` -### Disk Full +2. **Reduce the workers.** Set `CONSERVER_WORKERS=2` in `.env`, then run `docker compose up -d conserver`. -**Symptoms:** -- Write failures -- Service crashes +### The disk fills up -**Check:** +**Symptoms:** write failures or service crashes. ```bash df -h @@ -472,41 +389,40 @@ docker system df **Solutions:** -1. **Clean Docker** - ```bash - docker system prune -f - docker volume prune -f - ``` +1. **Clean Docker.** -2. **Clean old logs** - ```bash - docker compose logs --tail=0 # Truncate logs - ``` + ```bash + docker system prune -f + ``` -## Getting Help + !!! warning "Keep your volumes" + Do not run `docker volume prune` as routine cleanup. A stopped stack's `redis_data` and `postgres_data` volumes count as unused, and pruning can remove them. -### Collect Diagnostics +2. **Limit the container logs.** Compose sets no limit by default. See [Limit the log size](logging.md#limit-the-log-size). + +## Get help + +### Collect the diagnostics ```bash -# Create diagnostic bundle mkdir -p /tmp/vcon-diag docker compose ps > /tmp/vcon-diag/services.txt docker compose logs --tail=1000 > /tmp/vcon-diag/logs.txt docker stats --no-stream > /tmp/vcon-diag/stats.txt -cp .env /tmp/vcon-diag/env.txt.redacted -# Remove secrets from env file -sed -i 's/=.*/=REDACTED/' /tmp/vcon-diag/env.txt.redacted -tar -czf vcon-diagnostics.tar.gz /tmp/vcon-diag +sed 's/=.*/=REDACTED/' .env > /tmp/vcon-diag/env.txt.redacted +tar -czf vcon-diagnostics.tar.gz -C /tmp vcon-diag ``` -### Report Issues +Read the logs before you share them, since they can hold phone numbers and other conversation details. + +### Report the issue -When reporting issues, include: +Include: -1. vCon Server version (`/api/version`) -2. Error messages from logs +1. The version from `/api/version` +2. Error messages from the logs 3. Steps to reproduce -4. Configuration (redacted secrets) -5. Diagnostic bundle +4. The configuration, with secrets removed +5. The diagnostic bundle -Open issues at: [GitHub Issues](https://github.com/vcon-dev/vcon-server/issues) +Open issues at [GitHub Issues](https://github.com/vcon-dev/vcon-server/issues). diff --git a/docs/plans/2026-11-03-documentation-plan.md b/docs/plans/2026-11-03-documentation-plan.md new file mode 100644 index 00000000..088f3c1a --- /dev/null +++ b/docs/plans/2026-11-03-documentation-plan.md @@ -0,0 +1,161 @@ +# vCon Server documentation plan + +Status: approved 2026-11-03. Base commit `323109a` on `origin/main`, branch `docs/vconic-docs-set`. + +This plan gives operators and link authors one set of docs that matches the open source code, states plainly what that code does and does not do for consent, and gives maintainers a CI check that keeps it that way. + +## Current state + +`docs/` holds 42 Markdown pages, about 12,700 lines, built with MkDocs Material. `mkdocs build --strict` passes. + +Well covered: installation paths, YAML configuration, chains, workers, authentication, dead letter queue, logging, the three extension guides. + +Thin or wrong: + +| Area | Finding | +|---|---| +| Publishing | `https://vcon-dev.github.io/vcon-server/` returns 404. GitHub Pages is not enabled and no workflow deploys the site, yet `README.md` sends every reader there | +| Dead link | `README.md` links `/contributing/`, and no such page exists | +| Links | 23 link modules, 5 reference pages. `datatrails`, `delay`, `hugging_llm_link`, `scitt` and `wtf_transcribe` appear nowhere in `docs/` | +| Storage | 15 adapters, 3 reference pages. `scitt`, `spaceandtime`, `utopia` and `vcon_mcp` appear nowhere in `docs/` | +| Environment | 42 variables read directly in code by a first grep; 13 missing from the environment page, 8 of them from all of `docs/` | +| API | `/dlq/storage`, `/dlq/storage/reprocess` and `/stats/queue` are missing from the API reference | +| Metrics | About 38 metric names in code, no generated list | +| Orphans | `docs/storage-recovery.md` and `docs/installation/redis-migration.md` are outside the nav | +| Tooling | 51 Poetry references in docs; zero `uv sync` or `uv run`. The Dockerfiles and `uv.lock` use uv | +| Spec examples | 11 or more examples show `vcon: "0.0.1"`; the current syntax value is `0.4.0` | +| Redis | `docs/installation/docker.md` and `docs/storage-recovery.md` mention RedisJSON or Redis Stack after the move to plain Redis (#203). Each needs review; `redis-migration.md` mentions them on purpose | +| Lawful basis | No page says what the open source server does with a `lawful_basis` attachment, or that it does not manage consent | +| Edition language | `docs/index.md:13` says "Enterprise Ready" and `docs/operations/index.md:248` labels a sizing tier "Enterprise". Both read as product editions | +| Consent claims | `prod_mgt/04_LINK_PROCESSORS.md:125` and `prod_mgt/05_EXTERNAL_INTEGRATIONS.md:148` credit JLINC with consent management. The JLINC code here is a tracer and has no consent logic | +| Older drift | `server/links` module paths, the old Redis queue pattern and deprecated vendor transcribe modules in `docs/extending/` and `docs/configuration/`; `docs/index.md:135` claims a version that `pyproject.toml` does not | +| Agent context | No `CLAUDE.md`, `AGENTS.md` or `CONTRIBUTING.md` in the repo | +| Overlap | `prod_mgt/` (11 files, 3,067 lines, last touched 2026-04-08), `README_REDIS_CACHING.md`, `common/README_CORE.md` and per-link READMEs overlap `docs/` | + +Diagrams: 14 Mermaid blocks across 11 pages, unbranded. No SVGs, decks or animations in this repo. `vcon-dev/vcon-docs` holds `conserver/figures/vcon-day-stations.svg` and a conveyor infographic page. + +## Edition boundary + +These docs cover the open source server only. A commercial edition builds on the published open source image and adds its own files; it is a separate product with separate docs. + +Active consent management is a commercial feature. Its absence here is by design and is not a gap to fix. + +| Capability | Open source server | Docs treatment | +|---|---|---| +| Carry a `lawful_basis` attachment through the pipeline, storage and egress | Yes. Preserved on read, write and legacy downgrade (`common/lib/vcon_compat.py`, `common/lib/vcon_egress_compat.py`, storage round-trip tests) | Document | +| Show an existing basis in rendered output | Yes, in the `utopia` adapter (`common/storage/utopia/__init__.py:156`) | Document | +| Opt-in skip when no basis grants `analysis` | Yes, `require_analysis_grant`, default false, `utopia` adapter only | Document as adapter behaviour; see decision 10 | +| Create a lawful basis record | No | State the absence | +| Validate, enforce or gate on consent in a chain | No | State the absence | +| Manage consent over time: revocation, policy, proof | No | State the absence | + +Rules for every agent in this run: + +- Write only about behaviour in this repo. Never present consent management as an open source capability, and never imply the server makes a deployment compliant. +- Never name private modules, private repos, customers or commercial pricing. A name list kept outside this repo feeds the Verify check, so the list itself stays private. +- Do not read private repos for content. The boundary above is the only input from them. +- Do not write instructions for rebuilding commercial features. `extending/creating-links.md` stays generic. +- Treat a missing commercial feature as expected. It goes in no contradiction list and no Linear issue. + +## Target structure + +| Section | Page | State | +|---|---|---| +| Start | `index.md`, `getting-started/*` | Existing, revise | +| Start | `README.md` | Existing, fix links | +| Concepts | `concepts/architecture.md` | New | +| Concepts | `concepts/vcon-lifecycle.md` | New | +| Concepts | `concepts/chains-links-storage.md` | New | +| Concepts | `concepts/lawful-basis.md` | New, covers what the server carries and what it leaves out | +| Concepts | `concepts/editions.md` | New, per decision 8 | +| Guides | `installation/*`, `configuration/*`, `extending/*` | Existing, revise; Poetry to uv | +| Guides | `contributing.md` | New | +| Reference | `reference/links/*` | 5 existing, 18 new, one per module | +| Reference | `reference/storage-adapters/*` | 3 existing, 12 new, one per adapter | +| Reference | `reference/tracers/jlinc.md` | New | +| Reference | `reference/api.md` | Moved from `operations/api-reference.md`, gaps closed | +| Reference | `reference/environment.md`, `ports.md`, `metrics.md` | Generated | +| Reference | `reference/cli-reference.md` | Existing, verify | +| Operations | `operations/*` | Existing, revise | +| Operations | `operations/storage-recovery.md` | Moved into the nav | +| Operations | `installation/redis-migration.md` | Added to the nav | +| Visuals | `visuals/index.md`, `diagrams/`, `motion/` | New | +| Archive | `archive/` | New, per decision 4 | + +## Core diagram set + +| ID | Diagram | Kind | Code source of truth | Owner page | Exists | Motion | +|---|---|---|---|---|---|---| +| D01 | System context | flowchart | `api/api.py`, `conserver/main.py`, `common/storage/` | `concepts/architecture.md` | Partial | M1 | +| D02 | Container and port map | flowchart | `docker-compose.yml`, `docker/`, `nginx.conf` | `reference/ports.md` | No | | +| D03 | Deploy map | flowchart | `docker-compose.yml`, `docs/installation/kubernetes.md` | `installation/index.md` | Partial | | +| D04 | Ingress paths | flowchart | `api/api.py` (`/vcon`, `/vcon/ingress`, `/vcon/external-ingress`), `conserver/follower.py` | `concepts/architecture.md` | No | | +| D05 | Chain pipeline | flowchart | `conserver/main.py` (`VconChainRequest`, `worker_loop`) | `configuration/chains-and-pipelines.md` | Partial | M1 | +| D06 | Worker and queue topology | flowchart | `conserver/main.py`, `common/lib/queue.py` | `configuration/workers.md` | Partial | M2 | +| D07 | vCon lifecycle | state | `conserver/main.py`, `common/lib/vcon_redis.py`, `conserver/links/expire_vcon` | `concepts/vcon-lifecycle.md` | No | M3 | +| D08 | Dead letter flow | state | `common/lib/queue.py`, `common/dlq_utils.py`, `api/api.py` | `operations/dead-letter-queue.md` | Partial | M4 | +| D09 | Storage write and recovery | sequence | `common/storage/base.py`, `common/dlq_utils.py` | `operations/storage-recovery.md` | No | M4 | +| D10 | vCon assembly, lawful basis shown as carried and never created | class | `common/vcon.py`, `common/lib/vcon_compat.py`, link modules | `concepts/lawful-basis.md` | No | M3 | +| D11 | Egress compatibility | flowchart | `common/lib/vcon_egress_compat.py` | `configuration/egress-compatibility.md` | No | | +| D12 | Link execution contract | sequence | `conserver/main.py`, `conserver/hook.py`, `conserver/after_link_hook.py` | `extending/creating-links.md` | Partial | | +| D13 | Authentication paths | sequence | `api/api.py`, `common/settings.py` | `configuration/authentication.md` | Partial | | +| D14 | Observability | flowchart | `common/lib/metrics.py`, `common/lib/tracing.py`, `common/lib/queue_metrics.py`, `conserver/tracers/` | `operations/monitoring.md` | No | | + +The event bus and media path items from the standard list do not apply: this repo has Redis lists, covered by D06, and handles no live media. It has no agent loops. + +## Motion scenes + +No scenes exist, so numbering starts at M1. Every scene has a static Mermaid twin. + +| ID | Scene | Twin | +|---|---|---| +| M1 | A vCon runs a chain | D01, D05 | +| M2 | Workers drain the ingress queues | D06 | +| M3 | A vCon gains analysis, tags and attachments | D07, D10 | +| M4 | A failed vCon reaches the DLQ and returns | D08, D09 | + +## Generated reference + +`scripts/docs/` emits environment variables, ports, API routes and metric names from code. The environment script must parse `common/settings.py`, direct `os.getenv` reads and per-module reads. `scripts/docs/check.sh` runs the generators, renders the diagrams, runs `mkdocs build --strict` and fails on a git diff. A new CI job runs it, with SVG byte diffs skipped. + +## Orchestration + +Agents write to this worktree and never commit. About 25 agents in total. The first run on another repo used 29 agents, 85 minutes and 5.4M subagent tokens on 2 CPUs. + +| Phase | Agents | Work | Gate | +|---|---|---|---| +| Inventory | 1 | Generators, theme, render and check scripts, CI job, README extract | Scripts run clean | +| Diagrams | 4 | D01 to D14, split by source file | `mmdc` renders | +| Reference | 4 | Links; storage and tracers; API and CLI; config, ports, metrics | Every name in code appears in the docs and the reverse | +| Guides | 6 | Start and README; concepts; lifecycle and lawful basis; install and uv; ops; merges, archive, nav | Pages link to reference and copy nothing | +| Motions | 1, 4, then 1 | Scene shell and brand; one agent per scene; integrator with Playwright | Every tab runs over `file://` | +| Verify | 3, then 1 | Code audit, cold reader, mechanical checks including the private name list and the edition rules; fixer changes docs only | `check.sh` passes, zero private names | + +Reference then Guides runs alongside Motions after Diagrams. + +## Decisions taken 2026-11-03 + +All ten recommendations below were accepted as written. + +1. **Docs home and publishing.** Keep `docs/` as the canonical operator manual, add a deploy workflow, enable GitHub Pages, and have conserver.io link to it. +2. **Branding scope.** Vconic colours and type in diagrams, motion scenes and the MkDocs theme, with no Vconic logo or product claims, since this is a community repo under `vcon-dev`. +3. **README.** Keep it at its current short size and fix the links. +4. **Merges.** Fold `README_REDIS_CACHING.md` into `docs/`, leave per-link READMEs as the short form with a link to the reference page, and move `prod_mgt/` into `docs/archive/` with its unique content merged. +5. **Agent context file.** Add a short `CLAUDE.md`. +6. **Linear home.** No project matches this repo by name. File under the existing conserver hardening project. +7. **Plan file.** Keep this file in `docs/plans/`, outside the nav. +8. **Edition mention.** One short `concepts/editions.md` saying a commercial edition exists and adds active consent management, with no module names or pricing, and a link from the lawful basis page. +9. **Commercial docs.** Keep them out of this run and do a second run in the private repo, reusing these diagrams. +10. **`require_analysis_grant`.** This small consent gate already sits in open source. Leave it and document it as an adapter option, since it reads a basis and manages nothing. Moving it would be a code change. + +## Flags found while planning + +- **Lawful basis:** no open source path creates a `lawful_basis` attachment, by design. See the edition boundary. This is recorded for the audit and is not a code problem. +- **Two `Vcon` classes:** with the `PYTHONPATH` set in `docker/Dockerfile*` and `pytest.ini`, `import vcon` resolves to `common/vcon.py`, not the pinned `vcon>=0.9.2` library. Tested on 2026-11-03. Every link therefore runs on the local class, and docs must describe that one. +- **Legacy shape in the live class:** `add_attachment` (`common/vcon.py:177`) writes `type`, not `purpose`, and omits the required `party`, `dialog` and `start`. `build_new` (line 51) emits `vcon: "0.0.1"`, `redacted` and the reserved `group`, though nothing outside tests calls it. Whether `VconRedis._enforce_spec_on_write` repairs these needs checking. +- **Hard-coded company domain:** `common/vcon.py:15` defaults `UUID8_DOMAIN_NAME` to a company domain in public code, and `build_new` at line 53 passes the same literal, bypassing the setting. +- **Commercial reference:** `docker-compose.yml:20` carries a commented commercial image name. +- **Storage stub:** `common/storage/spaceandtime/__init__.py:41` writes `"vcon": "test"`, and needs review. +- **Version:** `pyproject.toml` still says `0.1.0`. +- **Toolchain end of life:** Material for MkDocs reaches end of life on 2027-05-05. No action in this run. +- **Open branch:** PR #226 changes link metrics and may touch the metrics page. diff --git a/docs/reference/api-routes.md b/docs/reference/api-routes.md new file mode 100644 index 00000000..501f2f08 --- /dev/null +++ b/docs/reference/api-routes.md @@ -0,0 +1,41 @@ + + +# API routes + +!!! note "Generated page" + `scripts/docs/gen_routes.py` builds this page from the code. Text that needs a person lives in `scripts/docs/descriptions.yml`. Edit that file, not this page. + +Paths are relative to the app. `API_ROOT_PATH`, default `/api`, sets the FastAPI root path. + +The Auth column uses three values: + +- `API key` routes pass through `get_api_key`, which compares the header named by `CONSERVER_HEADER_NAME` with the keys from `CONSERVER_API_TOKEN` and `CONSERVER_API_TOKEN_FILE`. With no keys configured, the check is skipped and the route is open. +- `ingress API key` routes call `validate_ingress_api_key`, which checks the same header against the `ingress_auth` section of the configuration for the named ingress list. With no match the API returns 403, including when `ingress_auth` is empty. +- `none` routes have no check. + +`api/api.py` defines 20 routes. + +| Method | Path | Auth | Success status | Tag | Summary | Notes | +|---|---|---|---|---|---|---| +| GET | `/config` | API key | 200 | config | Get system config | | +| POST | `/config` | API key | 204 | config | Update system config | | +| GET | `/dlq` | API key | 200 | dlq | Get DLQ contents | | +| POST | `/dlq/reprocess` | API key | 200 | dlq | Reprocess DLQ | | +| GET | `/dlq/storage` | API key | 200 | dlq | Get storage DLQ contents | | +| POST | `/dlq/storage/reprocess` | API key | 200 | dlq | Retry failed storage writes | | +| GET | `/health` | none | 200 | system | Health check | | +| GET | `/index_vcons` | API key | 200 | config | Rebuild search index | | +| GET | `/stats/queue` | none | 200 | system | Get queue depth | | +| GET | `/vcon` | API key | 200 | vcon | Gets a list of vCon UUIDs | | +| POST | `/vcon` | API key | 201 | vcon | Create a new vCon | | +| GET | `/vcon/count` | API key | 200 | chain | Count vCons in chain | Unreachable. `GET /vcon/{vcon_uuid}` captures the path and returns 422. | +| GET | `/vcon/egress` | API key | 204 | chain | Removes vCon UUIDs from a chain output | Declared 204. The handler returns a JSON array with 200. | +| POST | `/vcon/external-ingress` | ingress API key | 204 | external | Submit external vCon from 3rd party systems | | +| POST | `/vcon/ingress` | API key | 204 | chain | Add vCons to a chain | | +| DELETE | `/vcon/{vcon_uuid}` | API key | 204 | vcon | Delete a vCon | | +| GET | `/vcon/{vcon_uuid}` | API key | 200 | vcon | Gets a vCon by UUID | | +| GET | `/vcons` | API key | 200 | vcon | Gets multiple vCons by UUIDs | | +| GET | `/vcons/search` | API key | 200 | vcon | Search vCons by metadata | | +| GET | `/version` | none | 200 | system | Get server version | | + +`FastAPI` is created without turning off its default pages, so `/docs`, `/redoc` and `/openapi.json` are served too, with no check. diff --git a/docs/reference/api.md b/docs/reference/api.md new file mode 100644 index 00000000..9027d0b5 --- /dev/null +++ b/docs/reference/api.md @@ -0,0 +1,799 @@ +# API reference + +This page gives each REST endpoint's parameters, responses and status codes, so you can write a client without reading `api/api.py`. For a one-line index of every route, see the generated [API routes](api-routes.md) page. + +## Set the base URL + +The API listens on port 8000. The Compose file publishes it on `CONSERVER_EXTERNAL_PORT`, default `8000`. + +```bash +export API=http://localhost:8000/api +export TOKEN=your-token +``` + +`API_ROOT_PATH`, default `/api`, sets the FastAPI `root_path`. It does not move the routes. With the versions in `uv.lock`, `/health` and `/api/health` reach the same handler, and the OpenAPI document lists `/api` as its server URL. Examples on this page use the `/api` form. + +## Authenticate a request + +Each route follows one rule. See [Authentication](../configuration/authentication.md) to configure them. + +| Rule | Routes | Check | +|---|---|---| +| API key | All routes not listed below | The header named by `CONSERVER_HEADER_NAME`, default `x-conserver-api-token`, must hold a key from `CONSERVER_API_TOKEN` or `CONSERVER_API_TOKEN_FILE` | +| Ingress API key | `POST /vcon/external-ingress` | The same header must hold a key listed for that ingress list under `ingress_auth` in the configuration | +| None | `GET /version`, `GET /health`, `GET /stats/queue`, and the [generated API pages](#read-the-generated-api-pages) | No check | + +```bash +curl -H "x-conserver-api-token: $TOKEN" "$API/vcon" +``` + +A missing or wrong key on an API key route returns `403` with `{"detail": "Invalid API Key"}`. + +!!! warning "No keys means no check" + With neither `CONSERVER_API_TOKEN` nor `CONSERVER_API_TOKEN_FILE` set, or with an empty token file, every API key route is open. The ingress rule still applies. + +The API reads both settings once at startup, so a new key needs a restart. A token file that cannot be opened stops the API from starting. + +`GET /stats/queue` has no check and accepts any Redis key name. Anyone who can reach the API can read list depths, so restrict it at your proxy if that matters. + +## Read the response headers + +The API adds two headers to each response from a handler. An unhandled `500` does not carry them. + +| Header | Value | +|---|---| +| `X-Vcon-Server-Version` | `VCON_SERVER_VERSION`, set at image build. `dev` when unset | +| `X-Vcon-Server-Commit` | `VCON_SERVER_GIT_COMMIT`, set at image build. `unknown` when unset | + +CORS is open. `CORSMiddleware` allows any origin, method and header, with credentials. + +## Monitor the server + +### Check server health + +```http +GET /health +``` + +Returns a fixed status plus the version fields. The handler does not touch Redis, so `200` only shows that the API process answers. It still returns `healthy` with Redis down. + +```json +{ + "status": "healthy", + "version": { + "version": "dev", + "git_commit": "unknown", + "build_time": "unknown" + } +} +``` + +**Status:** `200` + +### Read the server version + +```http +GET /version +``` + +Returns the same three fields, from `VCON_SERVER_VERSION`, `VCON_SERVER_GIT_COMMIT` and `VCON_SERVER_BUILD_TIME`. Images take these as build arguments. Outside an image they read `dev` and `unknown`. + +```json +{ + "version": "dev", + "git_commit": "unknown", + "build_time": "unknown" +} +``` + +**Status:** `200` + +### Read queue depth + +```http +GET /stats/queue +``` + +Returns the length of a Redis list. Use it for monitoring and backpressure. It works on ingress lists, egress lists and dead letter queues. + +| Query parameter | Type | Required | Description | +|---|---|---|---| +| `list_name` | string | Yes | Redis list to measure, such as `test_list` or `DLQ:test_list` | + +```bash +curl "$API/stats/queue?list_name=test_list" +``` + +```json +{"list_name": "test_list", "depth": 3} +``` + +A list that does not exist reports depth `0`. + +| Status | Meaning | +|---|---| +| `200` | Depth returned | +| `422` | `list_name` missing | +| `500` | `Failed to get queue depth`: Redis is unreachable, or the key is not a list | + +### Read the generated API pages + +FastAPI serves its default pages with no check. + +| Route | Content | +|---|---| +| `GET /docs` | Swagger UI | +| `GET /docs/oauth2-redirect` | Swagger UI OAuth helper page | +| `GET /redoc` | ReDoc | +| `GET /openapi.json` | OpenAPI document | + +The OpenAPI document comes from the route decorators, so it repeats the two mismatches noted under [Pop UUIDs from an egress list](#pop-uuids-from-an-egress-list) and [Count an egress list](#count-an-egress-list). This page describes what the server returns. + +## Manage vCons + +### List vCon UUIDs + +```http +GET /vcon +``` + +Returns UUIDs from the sorted set named by `VCON_SORTED_SET_NAME`, default `vcons`, newest `created_at` first. + +| Query parameter | Type | Default | Description | +|---|---|---|---| +| `page` | int | `1` | Page number, from 1 | +| `size` | int | `50` | Items per page | +| `since` | datetime | none | Keep vCons created at or after this time | +| `until` | datetime | none | Keep vCons created at or before this time | + +```bash +curl "$API/vcon?page=1&size=50&since=2026-01-01" \ + -H "x-conserver-api-token: $TOKEN" +``` + +The response is a plain JSON array, with no total count. + +```json +["018f0000-0000-8000-8000-000000000001"] +``` + +The sorted set has no expiry and no code removes entries from it. A UUID stays listed after its Redis body expires or after [Delete a vCon](#delete-a-vcon). + +!!! warning "A storage read-back can break this route" + When a vCon is restored from a storage backend, the code adds a bare UUID to the sorted set, while `POST /vcon` adds `vcon:`. This route then fails with an unhandled `500` on any page that includes the bare member. `GET /index_vcons` does not remove it. To clear it, run `ZREM vcons ` in Redis. + +| Status | Meaning | +|---|---| +| `200` | UUID array, empty past the last page | +| `403` | Bad API key | +| `422` | Bad `page`, `size`, `since` or `until` | +| `500` | See the warning above | + +### Fetch one vCon + +```http +GET /vcon/{vcon_uuid} +``` + +Returns the full vCon. On a Redis miss the API tries each configured storage backend in order. A hit is normalized to the current spec, cached in Redis for `VCON_REDIS_EXPIRY` seconds and added to the sorted set. This path does not read `VCON_STORAGE_FALLBACK_ENABLED`, so it always tries storage. + +With `EGRESS_FORMAT_VERSION` set, the response uses that legacy format and Redis stays on the current spec. See [Egress compatibility](../configuration/egress-compatibility.md). + +```bash +curl "$API/vcon/018f0000-0000-8000-8000-000000000001" \ + -H "x-conserver-api-token: $TOKEN" +``` + +| Status | Meaning | +|---|---| +| `200` | vCon returned | +| `403` | Bad API key | +| `404` | `vCon not found` in Redis or any storage backend | +| `422` | `vcon_uuid` is not a UUID | +| `500` | A storage backend raised an error, the configuration file cannot be read, or `EGRESS_FORMAT_VERSION` holds an unsupported value | + +### Fetch several vCons + +```http +GET /vcons +``` + +| Query parameter | Type | Required | Description | +|---|---|---|---| +| `vcon_uuids` | UUID, repeatable | Yes in practice | Repeat the parameter once per UUID | + +```bash +curl "$API/vcons?vcon_uuids=018f0000-0000-8000-8000-000000000001&vcon_uuids=018f0000-0000-8000-8000-000000000002" \ + -H "x-conserver-api-token: $TOKEN" +``` + +The response is an array in request order. A UUID found nowhere gives `null` in its position. Lookup and egress format follow [Fetch one vCon](#fetch-one-vcon). + +| Status | Meaning | +|---|---| +| `200` | Array returned | +| `403` | Bad API key | +| `422` | A value is not a UUID | +| `500` | `vcon_uuids` left out, which the code does not guard against, or a storage error | + +### Create a vCon + +```http +POST /vcon +``` + +Stores a vCon in Redis, adds it to the sorted set, indexes its parties for search and optionally queues it. + +| Query parameter | Type | Required | Description | +|---|---|---|---| +| `ingress_lists` | string, repeatable | No | Repeat once per list: `?ingress_lists=a&ingress_lists=b`. A comma is part of the name | + +```bash +curl -X POST "$API/vcon?ingress_lists=test_list" \ + -H "Content-Type: application/json" \ + -H "x-conserver-api-token: $TOKEN" \ + -d '{ + "vcon": "0.4.0", + "uuid": "018f0000-0000-8000-8000-000000000001", + "created_at": "2026-01-15T10:30:00Z", + "parties": [{"tel": "+15551234567"}], + "dialog": [] + }' +``` + +The response is the stored vCon, with the model's defaults filled in. + +```json +{ + "vcon": "0.4.0", + "uuid": "018f0000-0000-8000-8000-000000000001", + "created_at": "2026-01-15T10:30:00+00:00", + "subject": null, + "redacted": {}, + "appended": null, + "group": [], + "parties": [{"tel": "+15551234567"}], + "dialog": [], + "analysis": [], + "attachments": [] +} +``` + +| Status | Meaning | +|---|---| +| `201` | Stored | +| `403` | Bad API key | +| `422` | Body failed [validation](#meet-the-vcon-body-rules) | +| `500` | `Failed to store vCon` | + +Behaviour to plan around: + +- This route writes to Redis only. The body expires after `VCON_REDIS_EXPIRY` seconds, default 3600. To keep it, queue it on a chain with a storage step. +- A UUID that already exists is overwritten with no conflict error, and its expiry restarts. +- The route does not normalize the body. Empty `redacted` and `group` and the legacy `appended` key stay in Redis until a worker writes the vCon, or a read restores it from storage. Those writes drop the empty keys and rename `appended` to `amended`. +- `api/vcon_hook.py` runs after a create and a delete. The default does nothing, and the API ignores any error it raises. + +### Meet the vCon body rules + +`POST /vcon` and `POST /vcon/external-ingress` validate the body with the same model. Unknown fields pass through. + +| Field | Rule | +|---|---| +| `vcon` | Required string. The model requires it even though the spec marks it optional. Use `"0.4.0"` | +| `uuid` | Required UUID | +| `created_at` | Required datetime | +| `parties[].tel` | Must look like a phone number. An empty string counts as absent. `Anonymous` fails | +| `dialog[].parties` | List of integers, each a valid index into `parties`. A bare integer fails | +| `dialog[].duration` | Zero or more | +| `dialog[].url` | Must have a URL scheme. An empty string counts as absent | +| `dialog[].mimetype` | Must look like a media type. The check does not cover `mediatype`, which passes through | +| `dialog[].alg` | One of `SHA-256`, `SHA-384`, `SHA-512`, or `HS`, `RS`, `ES` or `PS` followed by `256`, `384` or `512` | +| `analysis`, `attachments` | Lists of objects, stored as sent | + +The model also fills absent keys with `null` on each party and dialog entry it validates: `tel` on parties, and `duration`, `start`, `parties`, `url`, `mimetype` and `alg` on dialog entries. + +The API stores `attachments` entries as sent. That includes a `lawful_basis` attachment, which it carries and does not create, validate or act on. See [Lawful basis](../concepts/lawful-basis.md). + +### Delete a vCon + +```http +DELETE /vcon/{vcon_uuid} +``` + +Deletes the Redis body, then calls `delete` on every configured storage backend. A failure on one backend does not stop the others. + +```bash +curl -X DELETE "$API/vcon/018f0000-0000-8000-8000-000000000001" \ + -H "x-conserver-api-token: $TOKEN" +``` + +The route leaves the sorted set entry and the party search indexes in place, so [List vCon UUIDs](#list-vcon-uuids) and [Search vCons by party](#search-vcons-by-party) can still return the UUID. Search entries expire with `VCON_INDEX_EXPIRY`. Sorted set entries do not expire. + +| Status | Meaning | +|---|---| +| `204` | Finished. Also returned when the vCon did not exist or a backend failed, so check the logs for failures | +| `403` | Bad API key | +| `422` | `vcon_uuid` is not a UUID | +| `500` | The configuration file cannot be read | + +### Search vCons by party + +```http +GET /vcons/search +``` + +| Query parameter | Type | Description | +|---|---|---| +| `tel` | string | Exact phone number | +| `mailto` | string | Exact email address | +| `name` | string | Exact party name | + +Supply at least one. Matching is exact: `tel=+1555` does not find `+15551234567`. Encode `+` as `%2B` in a query string. + +```bash +curl "$API/vcons/search?tel=%2B15551234567" \ + -H "x-conserver-api-token: $TOKEN" +``` + +The response is an array of UUIDs in no set order. + +```json +["018f0000-0000-8000-8000-000000000001"] +``` + +Search reads the Redis sets `tel:`, `mailto:` and `name:`. `POST /vcon`, `POST /vcon/external-ingress` and `GET /index_vcons` write them. Each set expires `VCON_INDEX_EXPIRY` seconds after its last write, default 86400. A vCon older than that, or one read back from storage, is not found until you rebuild the index. + +With more than one term, the result is not a strict AND: + +| Terms | Result | +|---|---| +| Every term has matches | vCons that match all terms | +| Some terms have matches | The terms with no matches are ignored, and the rest are intersected | +| No term has matches | `500` | + +A single term with no matches returns `[]`. A term with an empty value, such as `tel=`, does not count as a term, so on its own it also returns `[]`. + +| Status | Meaning | +|---|---| +| `200` | Array returned | +| `400` | `At least one search parameter must be provided` | +| `403` | Bad API key | +| `500` | `An error occurred during the search`, including the case above | + +## Move vCons through chains + +The ingress routes append to the tail of a Redis list. When a trace is active they also store its context for the worker under `context::`, for `VCON_CONTEXT_EXPIRY` seconds. The count of queued vCons appears as `conserver.api.count_vcons_enqueued`. See [Metrics](metrics.md). + +### Add vCons to an ingress list + +```http +POST /vcon/ingress +``` + +| Query parameter | Type | Required | Description | +|---|---|---|---| +| `ingress_list` | string | Yes | Ingress list to add to | + +The body is a JSON array of UUIDs. It is not an object. + +```bash +curl -X POST "$API/vcon/ingress?ingress_list=test_list" \ + -H "Content-Type: application/json" \ + -H "x-conserver-api-token: $TOKEN" \ + -d '["018f0000-0000-8000-8000-000000000001"]' +``` + +The API looks up each vCon in Redis, then in storage. It queues the ones it finds, and logs and skips the rest. The response has no body, so it does not show what was skipped. + +| Status | Meaning | +|---|---| +| `204` | Finished, including when every UUID was skipped | +| `403` | Bad API key | +| `422` | `ingress_list` missing, or the body is not an array of UUIDs | +| `500` | `Failed to add to ingress list` | + +### Pop UUIDs from an egress list + +```http +GET /vcon/egress +``` + +Removes up to `limit` UUIDs from an egress list and returns them. This is a `GET` that changes state, so do not retry it blindly. + +| Query parameter | Type | Default | Description | +|---|---|---|---| +| `egress_list` | string | Required | Egress list to pop from | +| `limit` | int | `1` | Maximum UUIDs to remove | + +```bash +curl "$API/vcon/egress?egress_list=processed&limit=5" \ + -H "x-conserver-api-token: $TOKEN" +``` + +```json +["018f0000-0000-8000-8000-000000000001"] +``` + +Workers append to the tail and this route pops from the tail, so the newest UUID comes first. + +The decorator declares `204`, but the handler returns a JSON body with `200`. Clients receive `200`. + +| Status | Meaning | +|---|---| +| `200` | Array returned, empty when the list is empty | +| `403` | Bad API key | +| `422` | `egress_list` missing | +| `500` | `Failed to pop from egress list` | + +### Count an egress list + +```http +GET /vcon/count +``` + +| Query parameter | Type | Required | Description | +|---|---|---|---| +| `egress_list` | string | Yes | List to count | + +!!! warning "This route cannot be reached" + `GET /vcon/{vcon_uuid}` is registered first and captures this path, so the request fails UUID validation and returns `422`, with or without `egress_list`. Use [Read queue depth](#read-queue-depth) until the code changes. + +The handler is written to return the count as a bare integer, or `500` with `Failed to count egress list`. Neither happens today. + +### Submit a vCon from an external system + +```http +POST /vcon/external-ingress +``` + +Lets a third party submit vCons to one ingress list with a key that opens nothing else. The route stores and indexes the vCon as `POST /vcon` does, then always queues it. + +| Query parameter | Type | Required | Description | +|---|---|---|---| +| `ingress_list` | string | Yes | Target list. Must appear under `ingress_auth` | + +Keys live in the configuration file. A list takes one key or several. + +```yaml +ingress_auth: + third_party_input: third-party-key + shared_input: + - first-key + - second-key +``` + +```bash +curl -X POST "$API/vcon/external-ingress?ingress_list=third_party_input" \ + -H "Content-Type: application/json" \ + -H "x-conserver-api-token: third-party-key" \ + -d '{ + "vcon": "0.4.0", + "uuid": "018f0000-0000-8000-8000-000000000001", + "created_at": "2026-01-15T10:30:00Z", + "parties": [{"tel": "+15551234567"}], + "dialog": [] + }' +``` + +An ingress key fails on every other route, unless the same value is also a main API key. With no main API keys set, the main routes are open to everyone, so the scoping protects nothing there. A main API key fails here unless it is listed for that ingress list. The check runs even when the main API has no keys. The API re-reads `ingress_auth` on each request, so key changes need no restart. + +Body and query validation run before the key check, so an invalid body returns `422` even with a bad key. + +The [body rules](#meet-the-vcon-body-rules) and the Redis expiry from [Create a vCon](#create-a-vcon) apply here too. + +| Status | Detail | Meaning | +|---|---|---| +| `204` | | Stored and queued. No body | +| `403` | `API Key required` | No key in the header | +| `403` | `No ingress authentication configured` | `ingress_auth` is missing or empty | +| `403` | `Ingress list '' not configured` | The list is not under `ingress_auth` | +| `403` | `Invalid configuration for ingress list ''` | The value is neither a string nor a list | +| `403` | `Invalid API Key for ingress list ''` | The key is not listed for this ingress list | +| `422` | | `ingress_list` missing or body invalid | +| `500` | `Failed to store vCon` | Redis or queue failure | +| `500` | `Internal Server Error` | The configuration file cannot be read. The body is plain text | + +## Work with dead letter queues + +Each ingress list and each storage backend has its own queue. See [Dead letter queue](../operations/dead-letter-queue.md) for how to work with them. + +| Queue | Redis list | Holds | Replay runs | +|---|---|---|---| +| Ingress DLQ | `DLQ:` | vCons whose chain failed | The whole chain | +| Storage DLQ | `DLQ:storage:` | vCons whose write to one backend failed | Only that storage write | + +### Read an ingress DLQ + +```http +GET /dlq +``` + +| Query parameter | Type | Required | Description | +|---|---|---|---| +| `ingress_list` | string | Yes | Ingress list that owns the DLQ | + +```bash +curl "$API/dlq?ingress_list=test_list" \ + -H "x-conserver-api-token: $TOKEN" +``` + +The response is the whole list as a JSON array of UUIDs, oldest failure first. + +| Status | Meaning | +|---|---| +| `200` | Array returned | +| `403` | Bad API key | +| `422` | `ingress_list` missing | +| `500` | `Failed to read DLQ` | + +### Replay an ingress DLQ + +```http +POST /dlq/reprocess +``` + +Moves items from `DLQ:` to the tail of the ingress list, oldest first. + +| Query parameter | Type | Default | Description | +|---|---|---|---| +| `ingress_list` | string | Required | Ingress list to replay to | +| `count` | int | `1000` | Maximum items to move, from 1 to 100000 | + +```bash +curl -X POST "$API/dlq/reprocess?ingress_list=test_list&count=1000" \ + -H "x-conserver-api-token: $TOKEN" +``` + +The response is the number of items moved, as a bare integer. To drain a large DLQ, call the route until it returns `0`. + +| Status | Meaning | +|---|---| +| `200` | Count returned | +| `403` | Bad API key | +| `422` | `ingress_list` missing or `count` out of range | +| `500` | `Failed to reprocess DLQ` | + +### Read a storage DLQ + +```http +GET /dlq/storage +``` + +| Query parameter | Type | Required | Description | +|---|---|---|---| +| `storage_name` | string | Yes | Storage backend name from the configuration | + +```bash +curl "$API/dlq/storage?storage_name=s3" \ + -H "x-conserver-api-token: $TOKEN" +``` + +The response is a JSON array of UUIDs. The route does not check the name, so an unknown backend returns `[]`. + +| Status | Meaning | +|---|---| +| `200` | Array returned | +| `403` | Bad API key | +| `422` | `storage_name` missing | +| `500` | `Failed to read storage DLQ` | + +### Replay a storage DLQ + +```http +POST /dlq/storage/reprocess +``` + +Retries the storage write for vCons in `DLQ:storage:`, oldest first. The chain does not run again. + +| Query parameter | Type | Default | Description | +|---|---|---|---| +| `storage_name` | string | Required | Storage backend to retry | +| `count` | int | `1000` | Maximum items to retry, from 1 to 100000 | + +```bash +curl -X POST "$API/dlq/storage/reprocess?storage_name=s3&count=1000" \ + -H "x-conserver-api-token: $TOKEN" +``` + +The response is the number of successful writes, as a bare integer. + +- An item leaves the DLQ only after its write succeeds. +- The first failed write ends the call. The response is still `200` with the count so far, and `0` does not prove the DLQ is empty. Check with [Read a storage DLQ](#read-a-storage-dlq). +- Recovery is at least once. A backend can see the same UUID twice. +- The write reads the vCon through `VconRedis`, so it needs the body in Redis or in another configured backend. Most adapters then fail and the item stays. `scitt` logs a warning and counts a success, so the item leaves the DLQ with nothing registered. + +One replay runs per backend, under the Redis lock `DLQ:storage::replay-lock`. The lock has no expiry. If a process dies during a replay, the lock stays and each later call returns `409`. Confirm that no replay is running, then delete that key. + +| Status | Meaning | +|---|---| +| `200` | Count returned | +| `403` | Bad API key | +| `404` | `Unknown storage backend: `. Any failure to load the backend gives this, not only an unknown name | +| `409` | `Storage replay already running or requires lock recovery` | +| `422` | `storage_name` missing or `count` out of range | +| `500` | `Failed to reprocess storage DLQ` | + +## Manage the configuration + +### Read the configuration + +```http +GET /config +``` + +Returns the configuration file as JSON. The API reads the file on each call. + +```bash +curl "$API/config" -H "x-conserver-api-token: $TOKEN" | jq . +``` + +!!! warning "Secrets in the response" + The response holds the whole file, including `ingress_auth` keys and any credentials in link or storage options. + +| Status | Meaning | +|---|---| +| `200` | Configuration returned | +| `403` | Bad API key | +| `500` | `Failed to read configuration` | + +### Replace the configuration + +```http +POST /config +``` + +Writes the JSON body to the file named by `CONSERVER_CONFIG_FILE`, as YAML. This replaces the whole file. It is not a partial update. + +```bash +curl -X POST "$API/config" \ + -H "Content-Type: application/json" \ + -H "x-conserver-api-token: $TOKEN" \ + -d @config.json +``` + +- The API checks only that the body is a JSON object. A bad configuration is written as sent. +- Comments and key order in the file are lost. +- The route reads the variable directly. If `CONSERVER_CONFIG_FILE` is unset, it returns `500`, even though reads fall back to `./example_config.yml`. +- Most sections need no restart: the API re-reads the file on each use and workers re-read it on each pass of their loop, as long as they share the file. `imports` apply only when a worker starts, and `followers` only when the conserver process starts. See [reload timing](../configuration/yaml-configuration.md#plan-for-reloads). Environment variables still need a restart. + +| Status | Meaning | +|---|---| +| `204` | Written. No body | +| `403` | Bad API key | +| `422` | Body is not a JSON object | +| `500` | `Failed to update configuration` | + +### Rebuild the search index + +```http +GET /index_vcons +``` + +Runs Redis `KEYS vcon:*`, then for each key adds the vCon to the sorted set and rewrites its party search entries. This is a `GET` that changes state. `KEYS` blocks Redis while it runs, so take care on a large database. + +Only vCons in Redis are indexed, and the rebuild removes nothing. + +```bash +curl "$API/index_vcons" -H "x-conserver-api-token: $TOKEN" +``` + +The response is the number of keys found, as a bare integer. + +| Status | Meaning | +|---|---| +| `200` | Count returned | +| `403` | Bad API key | +| `500` | Body `{"detail": "Internal Server Error"}` | + +## Handle error responses + +Errors raised by a handler have a string `detail`. + +```json +{"detail": "vCon not found"} +``` + +A `422` from request validation has a list instead. + +```json +{ + "detail": [ + { + "type": "missing", + "loc": ["query", "list_name"], + "msg": "Field required", + "input": null + } + ] +} +``` + +An unhandled error, such as Redis being down on a route with no error handling, returns `500` with the plain text body `Internal Server Error`. + +## Limit the request rate + +The API has no rate limiting, and neither does the `nginx.conf` in this repo. Add it at your reverse proxy. + +```nginx +limit_req_zone $binary_remote_addr zone=api:10m rate=100r/s; + +server { + location /api { + limit_req zone=api burst=200 nodelay; + proxy_pass http://api:8000; + } +} +``` + +## Write a client + +This repo ships no client library. These short classes show the request shapes. + +### Python + +```python +import requests + + +class VconClient: + def __init__(self, base_url, token): + self.base_url = base_url + self.headers = {"x-conserver-api-token": token} + + def get_vcon(self, vcon_uuid): + response = requests.get(f"{self.base_url}/vcon/{vcon_uuid}", headers=self.headers) + response.raise_for_status() + return response.json() + + def create_vcon(self, vcon, ingress_lists=None): + response = requests.post( + f"{self.base_url}/vcon", + headers=self.headers, + params={"ingress_lists": ingress_lists or []}, + json=vcon, + ) + response.raise_for_status() + return response.json() + + def search(self, **terms): + response = requests.get(f"{self.base_url}/vcons/search", headers=self.headers, params=terms) + response.raise_for_status() + return response.json() + + +client = VconClient("http://localhost:8000/api", "your-token") +uuids = client.search(tel="+15551234567") +``` + +### JavaScript + +```javascript +class VconClient { + constructor(baseUrl, token) { + this.baseUrl = baseUrl; + this.headers = { 'x-conserver-api-token': token, 'Content-Type': 'application/json' }; + } + + async request(path, options = {}) { + const response = await fetch(`${this.baseUrl}${path}`, { headers: this.headers, ...options }); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + return response.json(); + } + + getVcon(uuid) { + return this.request(`/vcon/${uuid}`); + } + + createVcon(vcon, ingressLists = []) { + const query = new URLSearchParams(ingressLists.map((name) => ['ingress_lists', name])); + return this.request(`/vcon?${query}`, { method: 'POST', body: JSON.stringify(vcon) }); + } + + search(terms) { + return this.request(`/vcons/search?${new URLSearchParams(terms)}`); + } +} + +const client = new VconClient('http://localhost:8000/api', 'your-token'); +const uuids = await client.search({ tel: '+15551234567' }); +``` diff --git a/docs/reference/cli-reference.md b/docs/reference/cli-reference.md index c037fd05..e7c83765 100644 --- a/docs/reference/cli-reference.md +++ b/docs/reference/cli-reference.md @@ -1,459 +1,268 @@ -# CLI Reference +# CLI reference -Command-line options and usage for vCon Server components. +This page lists the commands that run, test and inspect the server, so you can find the right one without reading the Dockerfiles. -## Worker Process +The repo installs no command of its own: `pyproject.toml` defines no scripts. The worker and the API take no flags. Configure them with environment variables, listed on the generated [Environment variables](environment.md) page. -The main worker process that executes processing chains. +## Set up a local environment -### Basic Usage +The project uses uv with `uv.lock`, and needs Python 3.12 or 3.13. ```bash -python ./server/main.py +uv sync --frozen --group conserver --group api --group dev +export PYTHONPATH=.:common:conserver:api ``` -### With OpenTelemetry +Run these from the repo root. The code imports from `common/`, `conserver/` and `api/` as top-level paths, so it needs `PYTHONPATH`. `pytest.ini` and the `docker/Dockerfile` image set the same paths. `Dockerfile.conserver` leaves out `api`, and `Dockerfile.api` leaves out `conserver`. `common/settings.py` also loads a `.env` file, and `.env.example` shows the format. + +| Group | Adds | +|---|---| +| `storage` | Storage backend clients | +| `storage-milvus` | Milvus backend. Kept out of `storage` for its size | +| `api` | `storage`, plus FastAPI, uvicorn and gunicorn | +| `conserver` | `storage`, plus the packages links use, and `watchdog` | +| `conserver-local` | `transformers` for local Hugging Face inference | +| `dev` | pytest, black and test helpers. `uv sync` includes it by default | + +### Manage dependencies ```bash -opentelemetry-instrument python ./server/main.py +# Add a runtime dependency +uv add package-name + +# Add to a group +uv add --group dev package-name + +# Upgrade the lock file +uv lock --upgrade + +# Show outdated packages +uv tree --outdated ``` -### Environment Configuration +## Run the worker -The worker is configured entirely through environment variables: +The worker runs the chains. Its entry point is `conserver/main.py`. ```bash -# Required -export REDIS_URL=redis://localhost:6379 -export CONSERVER_API_TOKEN=your-token -export CONSERVER_CONFIG_FILE=./config.yml - -# Optional -export CONSERVER_WORKERS=4 -export CONSERVER_PARALLEL_STORAGE=true -export CONSERVER_START_METHOD=fork -export LOG_LEVEL=INFO - -# Run -python ./server/main.py +uv run python conserver/main.py ``` -### Docker Usage +With OpenTelemetry, as the Docker images run it: ```bash -docker compose exec conserver python ./server/main.py +uv run opentelemetry-instrument python conserver/main.py ``` -## API Server +`SIGTERM` or `SIGINT` starts a graceful shutdown: each worker finishes its current vCon and exits. See [Workers](../configuration/workers.md) for `CONSERVER_WORKERS` and related settings. -The FastAPI server providing the REST API. +## Run the API server -### Basic Usage +The FastAPI app is `app` in `api/api.py`, loaded as `api:app`. ```bash -uvicorn server.api:app --host 0.0.0.0 --port 8000 -``` +# Basic +uv run uvicorn api:app --host 0.0.0.0 --port 8000 -### Development Mode +# Development, with reload +uv run uvicorn api:app --reload --host 0.0.0.0 --port 8000 -```bash -uvicorn server.api:app --reload --host 0.0.0.0 --port 8000 -``` - -### Production Mode +# With OpenTelemetry, as the Docker images run it +uv run opentelemetry-instrument uvicorn api:app --host 0.0.0.0 --port 8000 -```bash -gunicorn server.api:app \ +# Several workers under gunicorn +uv run gunicorn api:app \ --worker-class uvicorn.workers.UvicornWorker \ --workers 4 \ --bind 0.0.0.0:8000 ``` -### With OpenTelemetry - -```bash -opentelemetry-instrument uvicorn server.api:app --host 0.0.0.0 --port 8000 -``` - -### Uvicorn Options +### Set uvicorn options | Option | Description | -|--------|-------------| -| `--host` | Bind address (default: 127.0.0.1) | -| `--port` | Bind port (default: 8000) | -| `--reload` | Auto-reload on code changes | +|---|---| +| `--host` | Bind address. Default `127.0.0.1` | +| `--port` | Bind port. Default `8000` | +| `--reload` | Restart on code changes. Cannot combine with `--workers` | | `--workers` | Number of worker processes | -| `--log-level` | Log level (debug, info, warning, error) | -| `--access-log` | Enable/disable access log | +| `--log-level` | One of `critical`, `error`, `warning`, `info`, `debug`, `trace` | +| `--access-log`, `--no-access-log` | Turn the access log on or off | -## Poetry Commands +## Run with Docker Compose -### Install Dependencies +Compose needs the external network, a `.env` file and a `config.yml` before it starts. See [Docker installation](../installation/docker.md). ```bash -# Install all dependencies -poetry install - -# Install with dev dependencies -poetry install --with dev - -# Install only main dependencies -poetry install --only main -``` - -### Run Commands - -```bash -# Run worker -poetry run python ./server/main.py - -# Run API server -poetry run uvicorn server.api:app --reload - -# Run tests -poetry run pytest - -# Run linting -poetry run black server/ -poetry run flake8 server/ +docker network create conserver ``` -### Manage Dependencies +`redis`, `conserver` and `api` always start. `postgres`, `elasticsearch` and `langfuse` start only through `COMPOSE_PROFILES` in `.env`. See [Ports](ports.md) for what each one publishes. ```bash -# Add dependency -poetry add package-name - -# Add dev dependency -poetry add --group dev package-name - -# Update dependencies -poetry update - -# Show outdated -poetry show --outdated -``` - -## Docker Commands - -### Build - -```bash -# Build image +# Build docker compose build - -# Build without cache docker compose build --no-cache - -# Build specific service docker compose build conserver -``` -### Run - -```bash -# Start all services +# Start docker compose up -d - -# Start with logs -docker compose up - -# Start specific service docker compose up -d conserver -# Scale workers +# Run more worker containers docker compose up -d --scale conserver=4 -``` - -### Logs -```bash -# All logs -docker compose logs - -# Follow logs +# Read logs docker compose logs -f - -# Specific service -docker compose logs conserver - -# Last N lines docker compose logs --tail=100 conserver +docker compose logs --since=1h conserver -# Since time -docker compose logs --since="1h" conserver -``` - -### Management - -```bash -# Stop services +# Stop and remove docker compose stop - -# Restart services docker compose restart - -# Remove containers docker compose down -# Remove with volumes -docker compose down -v - -# Execute command +# Open a shell docker compose exec conserver bash ``` -## Testing Commands +!!! danger "Data loss" + `docker compose down -v` also deletes the named volumes, including Redis data. -### Run All Tests +Compose runs the worker under `watchmedo auto-restart`, so it restarts when a `.py` file changes in the mounted repo. `stop_grace_period` is 5 seconds. A worker still busy after that is killed. -```bash -poetry run pytest -``` +## Run the tests -### Run with Options +The API and Redis tests need Redis at `REDIS_URL`. `pytest.ini` sets the import paths and loads `.env.test`, and `.env.test.example` shows the format. ```bash -# Verbose output -poetry run pytest -v - -# Stop on first failure -poetry run pytest -x - -# Max failures -poetry run pytest --maxfail=5 - -# Disable warnings -poetry run pytest --disable-warnings +# All tests +uv run pytest -# Run specific file -poetry run pytest server/tests/test_api.py +# Common options +uv run pytest -v +uv run pytest -x +uv run pytest --maxfail=5 --disable-warnings -# Run specific test -poetry run pytest server/tests/test_api.py::test_health +# One file or one test +uv run pytest common/tests/test_api.py +uv run pytest common/tests/test_api.py::test_api_vcon_lifecycle -# Run by marker -poetry run pytest -m integration - -# Fast path: skip integration tests -poetry run pytest -m "not integration" +# By marker +uv run pytest -m integration +uv run pytest -m "not integration" # With coverage -poetry run pytest --cov --cov-report=html -``` - -### Test Configuration - -```ini -# pytest.ini -[pytest] -pythonpath = ., server -log_cli = 1 -log_cli_level = INFO -markers = - integration: mark a test as an integration test. +uv run pytest --cov --cov-report=html ``` -## Redis CLI - -### Connect +CI runs the tests in the conserver container, whose dev image includes every group the tests need: ```bash -# Local -redis-cli - -# Docker -docker compose exec redis redis-cli - -# Remote -redis-cli -h hostname -p 6379 -a password +docker compose run --rm conserver pytest --maxfail=5 --disable-warnings --cov ``` -### Common Commands +Format code with black, which reads its settings from `pyproject.toml`: ```bash -# Check connection -redis-cli ping - -# List keys -redis-cli KEYS "*" - -# Get queue length -redis-cli LLEN default - -# Get queue items -redis-cli LRANGE default 0 -1 - -# Get vCon -redis-cli GET vcon:uuid-here - -# Delete key -redis-cli DEL key-name - -# Monitor commands -redis-cli MONITOR - -# Server info -redis-cli INFO +uv run black api common conserver ``` -## Utility Scripts +## Inspect Redis -### Health Check Script +In Compose, prefix these with `docker compose exec redis`. vCons are plain JSON strings, so `GET` reads them. -```bash -#!/bin/bash -# health-check.sh - -API_URL="${API_URL:-http://localhost:8000/api}" -TOKEN="${CONSERVER_API_TOKEN}" - -# Check API -response=$(curl -s -o /dev/null -w "%{http_code}" "$API_URL/health") -if [ "$response" = "200" ]; then - echo "API: OK" -else - echo "API: FAILED ($response)" - exit 1 -fi - -# Check Redis -if docker compose exec -T redis redis-cli ping | grep -q "PONG"; then - echo "Redis: OK" -else - echo "Redis: FAILED" - exit 1 -fi - -echo "All checks passed" -``` +| Purpose | Command | +|---|---| +| Check the connection | `redis-cli ping` | +| Read a vCon | `redis-cli GET vcon:` | +| See a vCon's remaining lifetime | `redis-cli TTL vcon:` | +| Measure a queue | `redis-cli LLEN ` | +| Read a queue | `redis-cli LRANGE 0 -1` | +| Read an ingress DLQ | `redis-cli LRANGE DLQ: 0 -1` | +| Read a storage DLQ | `redis-cli LRANGE DLQ:storage: 0 -1` | +| List recent vCons | `redis-cli ZREVRANGE vcons 0 9` | +| Read a party search entry | `redis-cli SMEMBERS tel:` | +| Find keys without blocking | `redis-cli --scan --pattern 'vcon:*'` | +| Show server details | `redis-cli INFO` | -### Queue Monitor Script +The API exposes most of this over HTTP, which suits scripts: ```bash -#!/bin/bash -# queue-monitor.sh - -while true; do - clear - echo "=== Queue Status $(date) ===" - echo - for queue in default production test; do - depth=$(docker compose exec -T redis redis-cli LLEN $queue 2>/dev/null || echo "N/A") - dlq=$(docker compose exec -T redis redis-cli LLEN "DLQ:$queue" 2>/dev/null || echo "N/A") - echo "$queue: $depth (DLQ: $dlq)" - done - sleep 5 -done +API=http://localhost:8000/api +curl -s "$API/health" +curl -s "$API/stats/queue?list_name=test_list" +curl -s "$API/stats/queue?list_name=DLQ:test_list" ``` -### Backup Script +`/health` does not check Redis. `/stats/queue` does, and returns `500` when Redis is down. See the [API reference](api.md). -```bash -#!/bin/bash -# backup.sh +For backups, see [Backup and restore](../operations/backup-restore.md). -BACKUP_DIR="${1:-./backups}" -DATE=$(date +%Y%m%d_%H%M%S) +## Use the repository scripts -mkdir -p "$BACKUP_DIR" +### Install and remove a server -echo "Backing up to $BACKUP_DIR..." +`scripts/install_conserver.sh` sets up a server on Ubuntu. See [Automated script](../installation/automated-script.md). -# Redis -docker compose exec -T redis redis-cli BGSAVE -sleep 2 -docker cp vcon-server-redis-1:/data/dump.rdb "$BACKUP_DIR/redis-$DATE.rdb" +| Option | Required | Description | +|---|---|---| +| `-d`, `--domain DOMAIN` | Yes | Domain name for the installation | +| `-e`, `--email EMAIL` | Yes | Email for DNS registration | +| `-t`, `--token TOKEN` | No | API token. Default is a random value | +| `-h`, `--help` | No | Show help | -# Config -cp .env "$BACKUP_DIR/env-$DATE" -cp config.yml "$BACKUP_DIR/config-$DATE.yml" +`scripts/uninstall_conserver.sh` takes no options. It must run as root and asks for confirmation. -echo "Backup complete: $BACKUP_DIR" -``` +!!! danger "Data loss" + The uninstall script removes containers, images, volumes, networks, data and the `vcon` user. It cannot be undone. -## Environment Variables Reference +### Migrate Redis data -### Core Variables +`scripts/migrate_redis_json.py` copies a stopped Redis database to an empty target and converts RedisJSON values. See [Redis migration](../installation/redis-migration.md). ```bash -# Redis connection -REDIS_URL=redis://localhost:6379 - -# API token -CONSERVER_API_TOKEN=your-token - -# Config file -CONSERVER_CONFIG_FILE=./config.yml - -# API path prefix -API_ROOT_PATH=/api - -# Hostname -HOSTNAME=http://localhost:8000 - -# Environment -ENV=production +REDIS_MIGRATION_SOURCE_URL=redis://old:6379 \ +REDIS_MIGRATION_TARGET_URL=redis://new:6379 \ +uv run python scripts/migrate_redis_json.py --match '*' --writers-stopped ``` -### Worker Variables - -```bash -# Number of workers -CONSERVER_WORKERS=4 - -# Parallel storage -CONSERVER_PARALLEL_STORAGE=true +| Option | Required | Description | +|---|---|---| +| `--match PATTERN` | Yes | Key pattern to copy. Repeatable | +| `--writers-stopped` | Yes | Confirms that writers on both ends are stopped and the source is backed up | -# Start method -CONSERVER_START_METHOD=fork +It prints a JSON object with `selected`, `copied` and `expired` counts. Use `*` only on a database the server owns alone. -# Tick interval (ms) -TICK_INTERVAL=5000 -``` +### Check the docs -### Logging Variables +`scripts/docs/check.sh` runs the page generators, renders the diagrams and builds the site with `mkdocs build --strict`. CI runs the same script. ```bash -# Log level -LOG_LEVEL=INFO - -# Logging config file -LOGGING_CONFIG_FILE=server/logging.conf +bash scripts/docs/check.sh ``` -### Cache Variables +Each generated page has its own script in `scripts/docs/`: `gen_env.py`, `gen_ports.py`, `gen_routes.py` and `gen_metrics.py`. Edit `scripts/docs/descriptions.yml` for their text. ```bash -# Redis cache expiry (seconds) -VCON_REDIS_EXPIRY=3600 - -# Index expiry (seconds) -VCON_INDEX_EXPIRY=86400 - -# Context expiry (seconds) -VCON_CONTEXT_EXPIRY=86400 +uv run -q --no-project --python 3.12 --with pyyaml python scripts/docs/gen_routes.py ``` -### External Services +### Use the other helpers -```bash -# Deepgram -DEEPGRAM_KEY=your-key +| Script | Purpose | +|---|---| +| `docker/wait_for_redis.sh` | Entry point of each image. Waits until `REDIS_URL` answers, then runs the given command. Skips the wait when `REDIS_URL` is unset | +| `common/tests/load_test_vcons.py [count]` | Posts generated test vCons to `http://localhost:8000/vcon`, one by default. Sends no API key, so it works only on an API with no keys set | +| `conserver/links/scitt/dump_cbor.py --input FILE` | Prints a COSE Sign1 statement from a CBOR file. The default file is `transparent-statement.cbor` | +| `conserver/links/scitt/create_hashed_signed_statement.py` | Creates a signed statement over a hashed payload. Run it with `--help` for its options. See the [`scitt` link](links/scitt.md) | -# OpenAI -OPENAI_API_KEY=your-key - -# Groq -GROQ_API_KEY=your-key -``` +## Read the exit codes -## Exit Codes +| Process | Code | Meaning | +|---|---|---| +| Worker | `0` | Clean stop, including after `SIGTERM` or `SIGINT` | +| Worker | `1` | Unhandled startup error, such as a missing configuration file | +| `migrate_redis_json.py` | `2` | Missing or invalid arguments | +| `install_conserver.sh` | `0` | Also returned for a missing or unknown option, because the help function exits first | -| Code | Meaning | -|------|---------| -| 0 | Success | -| 1 | General error | -| 2 | Configuration error | -| 130 | Interrupted (Ctrl+C) | -| 143 | Terminated (SIGTERM) | +The worker sets no exit codes of its own, so these come from Python and the signal handlers. diff --git a/docs/reference/environment.md b/docs/reference/environment.md new file mode 100644 index 00000000..68fece05 --- /dev/null +++ b/docs/reference/environment.md @@ -0,0 +1,82 @@ + + +# Environment variables + +!!! note "Generated page" + `scripts/docs/gen_env.py` builds this page from the code. Text that needs a person lives in `scripts/docs/descriptions.yml`. Edit that file, not this page. + +`common/settings.py` loads a `.env` file with `dotenv.load_dotenv()` when it is imported, so values in `.env` count as environment variables. Every read below sits under `api/`, `common/` or `conserver/`. Tests are left out. + +A default of `none` means the read returns nothing when the variable is unset. `required` means the code raises `KeyError` when it is unset. A variable set to an empty value counts as set, so its default does not apply. + +Each process reads these values when it starts, so restart it after a change. For help choosing values, see the [environment guide](../configuration/environment-variables.md). + +The code reads 40 variables. + +| Variable | Default | Type | Read in | Description | +|---|---|---|---|---| +| `API_ROOT_PATH` | `/api` | string | `common/settings.py` | FastAPI `root_path` for the API app, for a proxy that strips this prefix. Route paths do not change. | +| `CONSERVER_API_TOKEN` | none | string | `common/settings.py` | One API key for the main API routes. With neither this nor `CONSERVER_API_TOKEN_FILE` set, the API skips authentication on those routes. | +| `CONSERVER_API_TOKEN_FILE` | none | string | `common/settings.py` | Path to a file of API keys, one per line, read once when the API starts. Added to the keys from `CONSERVER_API_TOKEN`. | +| `CONSERVER_CONFIG_FILE` | `./example_config.yml` in `common/settings.py`
none in `api/api.py` | string | `api/api.py`
`common/settings.py` | Path to the YAML configuration. `common/config.py` reads it through the setting and its default. The `POST /config` handler reads the variable directly, with no default, to write the file. An empty value fails when the file is opened. | +| `CONSERVER_HEADER_NAME` | `x-conserver-api-token` | string | `common/settings.py` | HTTP header that carries the API key. The follower also sends its auth token in this header. | +| `CONSERVER_PARALLEL_STORAGE` | `true` | boolean | `common/settings.py` | When true, and a chain has more than one storage backend, writes run in parallel. `true`, `1` and `yes` count as true, in any case. | +| `CONSERVER_START_METHOD` | `""` | string | `common/settings.py` | Multiprocessing start method, one of `fork`, `spawn` or `forkserver`. Used only when `CONSERVER_WORKERS` is above 1. Empty or unset uses the Python platform default. Any other value raises `ValueError` at startup. | +| `CONSERVER_VCON_CONCURRENCY` | `1` | integer | `common/settings.py` | In-flight vCons per worker process. Values under 1 become 1, which processes vCons serially. | +| `CONSERVER_WORKERS` | `1` | integer | `common/settings.py` | Number of worker processes. Values under 1 become 1. | +| `DEEPGRAM_KEY` | none | string | `common/settings.py` | Read into `settings`, but no code uses that setting. The `deepgram_link` link takes its key from link options. | +| `EGRESS_FORMAT_VERSION` | none | string | `common/settings.py` | Legacy vCon version string emitted by the `webhook` link, the `postgres`, `s3` and `elasticsearch` storage adapters and the `GET /vcon/{uuid}` and `GET /vcons` reads. `0.0.1` is the only supported value. Empty or unset emits the current spec. Redis and link processing stay on the current spec either way. | +| `ENV` | `dev` in `common/settings.py`
required in `common/lib/error_tracking.py` | string | `common/lib/error_tracking.py`
`common/settings.py` | Sentry environment name. The `settings` value is unused. `common/lib/error_tracking.py` reads the variable directly when `SENTRY_DSN` is set, and has no default. | +| `GROQ_API_KEY` | `YOUR_GROQ_API_KEY` | string | `conserver/links/groq_whisper/__init__.py` | Default `API_KEY` option for the `groq_whisper` link. | +| `HOSTNAME` | `http://localhost:8000` | string | `common/settings.py` | Read into `settings`, but no code uses that setting. | +| `LOGGING_CONFIG_FILE` | `logging.conf` beside `common/settings.py` | string | `common/settings.py` | Path passed to `logging.config.fileConfig`. The repo also ships `common/logging_dev.conf`. | +| `LOG_LEVEL` | `DEBUG` | string | `common/settings.py` | Read into `settings`, but no code uses that setting. The logging config file sets log levels. | +| `OPENAI_API_KEY` | `""` in `conserver/links/detect_engagement/__init__.py`
none in `common/settings.py` | string | `common/settings.py`
`conserver/links/detect_engagement/__init__.py` | Default `OPENAI_API_KEY` option for the `detect_engagement` link. The `settings` value is unused. Other links take the key from link options. | +| `OTEL_EXPORTER_OTLP_ENDPOINT` | none | string | `common/lib/metrics.py` | OTLP endpoint for metrics, passed to the gRPC exporter in `common/lib/metrics.py`. Unset or empty, the metric helpers do nothing. | +| `OTEL_METRIC_EXPORT_INTERVAL` | `5000` | integer | `common/lib/metrics.py` | Metric export interval in milliseconds. | +| `OTEL_SERVICE_NAME` | `vcon-server` | string | `common/lib/metrics.py` | Value of the `service.name` resource attribute on metrics. The Compose file sets `conserver` and `api`. | +| `REDIS_URL` | `redis://localhost` | string | `common/settings.py` | Redis connection URL. `docker/wait_for_redis.sh` reads it too, and skips its wait when it is unset or empty. | +| `SENTRY_DSN` | none | string | `common/lib/error_tracking.py` | Sentry DSN. Unset, Sentry stays off. Set, `ENV` must be in the process environment too. | +| `SXT_API_KEY` | none | string | `common/storage/spaceandtime/__init__.py` | Space and Time API key for the `spaceandtime` storage adapter. | +| `SXT_VCON_TABLENAME` | none | string | `common/storage/spaceandtime/__init__.py` | Table name for the `spaceandtime` storage adapter. | +| `SXT_VCON_TABLE_WRITE_BISCUI` | none | string | `common/storage/spaceandtime/__init__.py` | Write biscuit for the `spaceandtime` storage adapter. The code reads this exact name, which lacks the final `T` of the Python constant `SXT_VCON_TABLE_WRITE_BISCUIT`. | +| `TICK_INTERVAL` | `5000` | integer | `common/settings.py` | Read into `settings`, but no code uses that setting. | +| `UUID8_DOMAIN_NAME` | a domain set in code | string | `common/vcon.py` | Read into a constant in `common/vcon.py`, but no code uses that constant. | +| `VCON_CONTEXT_EXPIRY` | `86400` | integer | `common/settings.py` | Seconds before ingress context data expires in Redis. | +| `VCON_DLQ_EXPIRY` | `604800` | integer | `common/settings.py` | TTL in seconds for a vCon in a dead letter queue. The ingress DLQ sets the TTL to this value. The storage DLQ only raises a lower TTL. `0` leaves the existing TTL alone. | +| `VCON_INDEX_EXPIRY` | `86400` | integer | `common/settings.py` | Seconds before the search index keys written by the API expire. | +| `VCON_REDIS_EXPIRY` | `3600` | integer | `common/settings.py` | TTL in seconds on vCon keys written by `POST /vcon` and `POST /vcon/external-ingress`, and on a vCon cached back from a storage backend. | +| `VCON_SERVER_BUILD_TIME` | `unknown` | string | `common/version.py` | Image build time. The Dockerfiles set it from a build argument. | +| `VCON_SERVER_GIT_COMMIT` | `unknown` in `common/version.py`
none in `common/lib/error_tracking.py` | string | `common/lib/error_tracking.py`
`common/version.py` | Git commit of the build. The Dockerfiles set it from a build argument. Sentry uses it as the release. | +| `VCON_SERVER_VERSION` | `dev` | string | `common/version.py` | Server version string. The Dockerfiles set it from a build argument. | +| `VCON_SORTED_FORCE_RESET` | `true` | string | `common/settings.py` | Read into `settings`, but no code uses that setting. | +| `VCON_SORTED_SET_NAME` | `vcons` | string | `common/settings.py` | Name of the Redis sorted set that orders vCons by timestamp. | +| `VCON_STORAGE` | `""` | string | `common/settings.py` | PostgreSQL connection string. When set, `api/api.py` defines a Peewee model on it, but no code uses that model. | +| `VCON_STORAGE_FALLBACK_ENABLED` | `true` | boolean | `common/settings.py` | When true, a Redis miss in `VconRedis.get_vcon` tries the configured storage backends and caches the first hit back in Redis. `true`, `1` and `yes` count as true, in any case. | +| `WEVIATE_API_KEY` | none | string | `common/settings.py` | Read into `settings`, but no code uses that setting. The spelling is the one in the code. | +| `WEVIATE_HOST` | `localhost:8000` | string | `common/settings.py` | Read into `settings`, but no code uses that setting. The spelling is the one in the code. | + +## Dynamic reads + +These reads compute the variable name at run time, so the table cannot list them. + +| File | Expression | +|---|---| +| `conserver/links/groq_whisper/__init__.py` | `var in os.environ` | + +The dynamic read in `groq_whisper` does not configure anything. When that link module loads, it deletes `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` and their lowercase forms from the process environment. + +## Variables outside the server code + +Scripts, Docker Compose and the OpenTelemetry tools read these. The table above leaves them out because no code under `api/`, `common/` or `conserver/` reads them. + +| Variable | Read by | Default | Description | +|---|---|---|---| +| `COMPOSE_PROFILES` | Docker Compose | none | Comma-separated profiles to start: `postgres`, `elasticsearch`, `langfuse`. | +| `CONSERVER_EXTERNAL_PORT` | `docker-compose.yml` | `8000` | Host port published for the `api` service. | +| `OTEL_EXPORTER_OTLP_HEADERS` | `opentelemetry-instrument` | empty | Headers for OTLP export. Compose passes it to `api` and `conserver`. | +| `OTEL_EXPORTER_OTLP_INSECURE` | `opentelemetry-instrument` | `false` in Compose | Turns off TLS for OTLP export. Compose passes it to `api` and `conserver`. | +| `OTEL_EXPORTER_OTLP_PROTOCOL` | `opentelemetry-instrument` | `grpc` in Compose | OTLP protocol. The custom metrics in `common/lib/metrics.py` always use the gRPC exporter, whatever this says. | +| `OTEL_RESOURCE_ATTRIBUTES` | `opentelemetry-instrument` | `deployment.environment=dev` in Compose | Resource attributes. The Compose file fixes this value for `api` and `conserver`. | +| `REDIS_MIGRATION_SOURCE_URL` | `scripts/migrate_redis_json.py` | required | Redis URL to copy from. See the [Redis migration](../installation/redis-migration.md). | +| `REDIS_MIGRATION_TARGET_URL` | `scripts/migrate_redis_json.py` | required | Redis URL to copy to. | diff --git a/docs/reference/index.md b/docs/reference/index.md index 2473916e..d3a9ce41 100644 --- a/docs/reference/index.md +++ b/docs/reference/index.md @@ -1,140 +1,35 @@ # Reference -Complete reference documentation for vCon Server components. +These pages state what the code does: every option, variable, route and metric, for lookup rather than reading in order. For task-led help, start with [configuration](../configuration/index.md). -## Available Links +## Find the page for a name -Processing links transform and analyze vCons. +| Looking for | Page | +|---|---| +| A link and its options | [Links](links/index.md) | +| A storage adapter and its options | [Storage adapters](storage-adapters/index.md) | +| A tracer and its options | [JLINC tracer](tracers/jlinc.md) | +| An API route, its parameters and responses | [API](api.md) | +| A route, its auth and its status code, in one table | [API routes](api-routes.md) | +| An environment variable, its default and where it is read | [Environment variables](environment.md) | +| A container, port or Compose profile | [Ports and services](ports.md) | +| A metric name, its type and where it is emitted | [Metrics](metrics.md) | +| A command-line option | [CLI](cli-reference.md) | -| Link | Module | Description | -|------|--------|-------------| -| [deepgram_link](links/deepgram.md) | `links.deepgram_link` | Deepgram transcription | -| [groq_whisper](links/groq-whisper.md) | `links.groq_whisper` | Groq Whisper transcription | -| [hugging_face_whisper](links/huggingface-whisper.md) | `links.hugging_face_whisper` | HuggingFace Whisper | -| [openai_transcribe](links/openai-transcribe.md) | `links.openai_transcribe` | OpenAI Whisper | -| [analyze](links/analyze.md) | `links.analyze` | AI analysis | -| [analyze_and_label](links/analyze-and-label.md) | `links.analyze_and_label` | Analysis with labeling | -| [analyze_vcon](links/analyze-vcon.md) | `links.analyze_vcon` | vCon-specific analysis | -| [detect_engagement](links/detect-engagement.md) | `links.detect_engagement` | Engagement detection | -| [tag](links/tag.md) | `links.tag` | Add static tags | -| [check_and_tag](links/check-and-tag.md) | `links.check_and_tag` | Conditional tagging | -| [tag_router](links/tag-router.md) | `links.tag_router` | Route by tags | -| [sampler](links/sampler.md) | `links.sampler` | Random sampling | -| [webhook](links/webhook.md) | `links.webhook` | HTTP webhook delivery | -| [post_analysis_to_slack](links/slack.md) | `links.post_analysis_to_slack` | Slack notifications | -| [diet](links/diet.md) | `links.diet` | Reduce vCon size | -| [expire_vcon](links/expire-vcon.md) | `links.expire_vcon` | Set expiration | -| [jq_link](links/jq.md) | `links.jq_link` | jq transformations | +## Trust the generated pages -## Available Storage Adapters +`scripts/docs/` builds four of these pages from the code, so their names, defaults and types come straight from it: [environment variables](environment.md), [ports and services](ports.md), [API routes](api-routes.md) and [metrics](metrics.md). Each generator fails if `scripts/docs/descriptions.yml` names something the code no longer has. -Storage adapters persist vCons to various backends. +To change text on one of these pages, edit `scripts/docs/descriptions.yml` and run `scripts/docs/check.sh`. Do not edit the page. -| Storage | Module | Description | -|---------|--------|-------------| -| [redis_storage](storage-adapters/redis.md) | `storage.redis_storage` | Redis storage | -| [postgres](storage-adapters/postgres.md) | `storage.postgres` | PostgreSQL | -| [mongo](storage-adapters/mongo.md) | `storage.mongo` | MongoDB | -| [elasticsearch](storage-adapters/elasticsearch.md) | `storage.elasticsearch` | Elasticsearch | -| [s3](storage-adapters/s3.md) | `storage.s3` | Amazon S3 / S3-compatible | -| [milvus](storage-adapters/milvus.md) | `storage.milvus` | Milvus vector database | -| [file](storage-adapters/file.md) | `storage.file` | Local filesystem | -| [sftp](storage-adapters/sftp.md) | `storage.sftp` | SFTP server | -| [dataverse](storage-adapters/dataverse.md) | `storage.dataverse` | Microsoft Dataverse | -| [chatgpt_files](storage-adapters/chatgpt-files.md) | `storage.chatgpt_files` | ChatGPT Files | +## Name modules in the YAML file -## Available Tracers +The `module` value in the [YAML configuration](../configuration/yaml-configuration.md) is a Python module path: -Tracers provide audit trails for processing. +| Kind | Form | Example | +|---|---|---| +| Link | `links.` | `links.tag` | +| Storage adapter | `storage.` | `storage.postgres` | +| Tracer | `tracers.` | `tracers.jlinc` | -| Tracer | Module | Description | -|--------|--------|-------------| -| jlinc | `tracers.jlinc` | JLINC audit trail | - -## CLI Reference - -See [CLI Reference](cli-reference.md) for command-line options. - -## Quick Reference - -### Common Link Options - -```yaml -links: - my_link: - module: links.my_link - options: - timeout: 30 # Request timeout in seconds - retry_count: 3 # Number of retries on failure - retry_delay: 1 # Delay between retries -``` - -### Common Storage Options - -```yaml -storages: - my_storage: - module: storage.my_storage - options: - timeout: 30 # Connection timeout - batch_size: 100 # Items per batch operation -``` - -### Chain Configuration - -```yaml -chains: - chain_name: - links: - - link1 - - link2: - option: value - storages: - - storage1 - - storage2 - tracers: - - tracer1 - ingress_lists: - - input_queue - egress_lists: - - output_queue - enabled: 1 -``` - -## Environment Variables Quick Reference - -| Variable | Default | Description | -|----------|---------|-------------| -| `REDIS_URL` | `redis://localhost` | Redis connection | -| `CONSERVER_API_TOKEN` | - | API authentication | -| `CONSERVER_CONFIG_FILE` | `./example_config.yml` | Config file path | -| `CONSERVER_WORKERS` | `1` | Worker processes (multiplies with `CONSERVER_VCON_CONCURRENCY`) | -| `CONSERVER_VCON_CONCURRENCY` | `1` | In-flight vCons per worker (thread pool size) | -| `CONSERVER_PARALLEL_STORAGE` | `true` | Parallel storage writes | -| `CONSERVER_START_METHOD` | Platform default | Multiprocessing method | -| `LOG_LEVEL` | `DEBUG` | Logging level | -| `DEEPGRAM_KEY` | - | Deepgram API key | -| `OPENAI_API_KEY` | - | OpenAI API key | -| `GROQ_API_KEY` | - | Groq API key | - -See [Environment Variables](../configuration/environment-variables.md) for complete list. - -## API Endpoints Quick Reference - -| Method | Endpoint | Description | -|--------|----------|-------------| -| `GET` | `/health` | Health check | -| `GET` | `/version` | Version info | -| `GET` | `/vcon` | List vCons | -| `GET` | `/vcon/{uuid}` | Get vCon | -| `POST` | `/vcon` | Create vCon | -| `DELETE` | `/vcon/{uuid}` | Delete vCon | -| `GET` | `/vcons/search` | Search vCons | -| `POST` | `/vcon/ingress` | Queue for processing | -| `GET` | `/vcon/egress` | Get processed vCons | -| `POST` | `/vcon/external-ingress` | External submission | -| `GET` | `/dlq` | View DLQ | -| `POST` | `/dlq/reprocess` | Reprocess DLQ | -| `GET` | `/config` | Get configuration | - -See [API Reference](../operations/api-reference.md) for complete documentation. +The folders are `conserver/links/`, `common/storage/` and `conserver/tracers/`. A link or tracer can also come from an installed package. See [dynamic modules](../extending/dynamic-modules.md). diff --git a/docs/reference/links/analyze-and-label.md b/docs/reference/links/analyze-and-label.md new file mode 100644 index 00000000..ee91e99c --- /dev/null +++ b/docs/reference/links/analyze-and-label.md @@ -0,0 +1,68 @@ +# analyze_and_label + +Asks an LLM for a list of labels per dialog, stores the reply as analysis and applies each label as a tag. + +Module: `links.analyze_and_label` + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `prompt` | string | `Analyze this transcript and provide a list of relevant labels for categorization. Return your response as a JSON object with a single key 'labels' containing an array of strings.` | Placed before the transcript | +| `analysis_type` | string | `labeled_analysis` | The `type` of the analysis entry | +| `model` | string | `gpt-4-turbo` | Model name | +| `sampling_rate` | float | `1` | See [filter options](index.md#set-the-shared-filter-options) | +| `temperature` | float | `0.2` | Sampling temperature | +| `source.analysis_type` | string | `transcript` | Analysis entry to read | +| `source.text_location` | string | `body.paragraphs.transcript` | Path to the text. See [transcript text](index.md#point-analysis-at-the-transcript-text) | +| `response_format` | dict | `{"type": "json_object"}` | Passed to the model call | +| `only_if` | dict | none | See [filter options](index.md#set-the-shared-filter-options) | + +The link also takes the [LLM client options](index.md#set-the-llm-client-options). One of those groups is required. The system message is fixed in the code. + +## Follow the processing steps + +1. Merge the options, load the vCon, and apply `only_if` and `sampling_rate`. +2. For each dialog, read the source text. Skip the dialog if the text is missing or if it already has an entry of this `analysis_type`. +3. Call the model, with up to 6 attempts, and parse the reply as JSON. +4. Add the analysis, then add one tag for each item in `labels`. +5. Save the vCon after the last dialog. + +If the reply is not valid JSON, the link stores the raw text, adds no tags, and counts `conserver.link.openai.json_parse_failures`. The chain continues. + +## Read the return value + +Returns the uuid, including when the vCon is skipped. A model failure after all retries raises, and the vCon goes to the dead letter queue. A missing vCon raises `AttributeError`, unless `only_if` is set, which then skips it and returns the uuid. + +## Inspect the vCon changes + +One analysis entry per processed dialog. + +| Field | Value | +|---|---| +| `type` | `analysis_type` | +| `dialog` | Dialog index | +| `vendor` | `openai`, whichever client group is in use | +| `body` | The model's reply as a string | +| `encoding` | `json`, or `none` when the reply did not parse | +| `vendor_schema` | `model` and `prompt`, plus `parse_error` when the reply did not parse | + +A label `billing` becomes the tag `billing:billing`. See [tag](tag.md#inspect-the-vcon-changes) for how tags are stored. + +## Copy a configuration example + +```yaml +links: + label_calls: + module: links.analyze_and_label + options: + OPENAI_API_KEY: your-openai-key + model: gpt-4.1 + source: + analysis_type: transcript + text_location: body.text +``` + +## Track the metrics + +`conserver.link.openai.analysis_time`, `conserver.link.openai.analysis_failures`, `conserver.link.openai.labels_added` and `conserver.link.openai.json_parse_failures`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/analyze-vcon.md b/docs/reference/links/analyze-vcon.md new file mode 100644 index 00000000..3501c6cf --- /dev/null +++ b/docs/reference/links/analyze-vcon.md @@ -0,0 +1,66 @@ +# analyze_vcon + +Sends the whole vCon to an LLM and stores the JSON reply as one analysis entry. + +Module: `links.analyze_vcon` + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `prompt` | string | `Analyze this vCon and return a JSON object with your analysis.` | Placed before the vCon JSON | +| `analysis_type` | string | `json_analysis` | The `type` of the analysis entry | +| `model` | string | `gpt-3.5-turbo-16k` | Model name | +| `sampling_rate` | float | `1` | See [filter options](index.md#set-the-shared-filter-options) | +| `temperature` | float | `0` | Sampling temperature | +| `system_prompt` | string | `You are a helpful assistant that analyzes conversation data and returns structured JSON output.` | System message | +| `remove_body_properties` | bool | `true` | Drops each dialog's `body` from the copy sent to the model | +| `only_if` | dict | none | See [filter options](index.md#set-the-shared-filter-options) | + +The link also takes the [LLM client options](index.md#set-the-llm-client-options). One of those groups is required. + +## Follow the processing steps + +1. Merge the options, load the vCon, and apply `only_if` and `sampling_rate`. +2. Stop if the vCon already has an entry of this `analysis_type`. +3. Copy the vCon and, by default, drop the dialog bodies from the copy. Parties, attachments and analysis go to the model as they are. +4. Call the model in JSON mode, with up to 6 attempts. +5. Check that the reply parses as JSON, then add the analysis and save. + +## Check the known issues + +If the text of `system_prompt` appears anywhere in the vCon, the call fails with a `NameError` and the link raises after its retries. This happens when an earlier `analyze_vcon` link with the same `system_prompt` and a different `analysis_type` ran on the vCon, since `vendor_schema` records the prompt. Give each link its own `system_prompt`, or run [`diet`](diet.md) with `remove_system_prompts` between them. + +## Read the return value + +Returns the uuid, including when the vCon is skipped. A model failure or a reply that is not JSON raises, and the vCon goes to the dead letter queue. A missing vCon raises `AttributeError`, unless `only_if` is set, which then skips it and returns the uuid. + +## Inspect the vCon changes + +One analysis entry. + +| Field | Value | +|---|---| +| `type` | `analysis_type` | +| `dialog` | `0`, though the entry covers the whole vCon | +| `vendor` | `openai`, whichever client group is in use | +| `body` | The parsed JSON value | +| `encoding` | `json` | +| `vendor_schema` | `model`, `prompt` and `system_prompt` | + +## Copy a configuration example + +```yaml +links: + call_review: + module: links.analyze_vcon + options: + OPENAI_API_KEY: your-openai-key + model: gpt-4.1 + analysis_type: call_review + prompt: Return a JSON object with keys outcome and next_step. +``` + +## Track the metrics + +`conserver.link.openai.analysis_time`, `conserver.link.openai.analysis_failures` and `conserver.link.openai.invalid_json`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/analyze.md b/docs/reference/links/analyze.md index f4536939..e9360af4 100644 --- a/docs/reference/links/analyze.md +++ b/docs/reference/links/analyze.md @@ -1,71 +1,70 @@ # analyze -Analyzes vCon content using AI (OpenAI GPT models). +Sends each dialog's transcript to an LLM and stores the reply as analysis. -## Configuration +Module: `links.analyze` -```yaml -links: - analyze: - module: links.analyze - options: - model: gpt-4 - temperature: 0.3 - prompt: "Analyze this conversation..." -``` - -## Options +## Set the options | Option | Type | Default | Description | -|--------|------|---------|-------------| -| `model` | string | `gpt-4` | OpenAI model | -| `temperature` | float | `0.3` | Response randomness (0-1) | -| `prompt` | string | Default | Analysis prompt | -| `max_tokens` | int | `1000` | Maximum response tokens | -| `timeout` | int | `60` | Request timeout in seconds | +|---|---|---|---| +| `prompt` | string | `""` | Placed before the transcript in the user message | +| `analysis_type` | string | `summary` | The `type` of the analysis entry | +| `model` | string | `gpt-3.5-turbo-16k` | Model name | +| `sampling_rate` | float | `1` | See [filter options](index.md#set-the-shared-filter-options) | +| `temperature` | float | `0` | Sampling temperature | +| `system_prompt` | string | `You are a helpful assistant.` | System message | +| `source.analysis_type` | string | `transcript` | Analysis entry to read | +| `source.text_location` | string | `body.paragraphs.transcript` | Path to the text. See [transcript text](index.md#point-analysis-at-the-transcript-text) | +| `only_if` | dict | none | See [filter options](index.md#set-the-shared-filter-options) | +| `send_ai_usage_data_to_url` | string | `""` | See [AI usage](index.md#report-ai-usage-to-an-endpoint) | +| `ai_usage_api_token` | string | `""` | See [AI usage](index.md#report-ai-usage-to-an-endpoint) | + +The link also takes the [LLM client options](index.md#set-the-llm-client-options). One of those groups is required. + +## Follow the processing steps + +1. Merge the options over `default_options` and load the vCon. +2. Apply `only_if` and `sampling_rate`. +3. For each dialog, read the source text. Skip the dialog if the text is missing or if it already has an entry of this `analysis_type`. +4. Call the model, with up to 6 attempts. +5. Save the vCon after the last dialog. -## Requirements +A second `analyze` link needs its own `analysis_type`. With the same value it skips every dialog. -- `OPENAI_API_KEY` environment variable +## Read the return value -## Example +Returns the uuid, including when the vCon is skipped. A model failure after all retries raises, and the vCon goes to the dead letter queue. A missing vCon raises `AttributeError`, unless `only_if` is set, which then skips it and returns the uuid. + +## Inspect the vCon changes + +One analysis entry per processed dialog. + +| Field | Value | +|---|---| +| `type` | `analysis_type` | +| `dialog` | Dialog index | +| `vendor` | Derived from the client options: `openai`, `azure`, or with LiteLLM the provider inferred from the model name | +| `body` | The model's reply as a string | +| `encoding` | `none` | +| `vendor_schema` | `model` and `prompt` | + +## Copy a configuration example ```yaml -chains: - analysis: - links: - - analyze: - model: gpt-4 - prompt: | - Analyze this conversation and provide: - 1. Summary (2-3 sentences) - 2. Key topics discussed - 3. Action items - 4. Overall sentiment - storages: - - postgres - ingress_lists: - - transcribed - enabled: 1 +links: + summarize: + module: links.analyze + options: + OPENAI_API_KEY: your-openai-key + model: gpt-4.1 + analysis_type: summary + prompt: Summarize this conversation in two sentences. + source: + analysis_type: transcript + text_location: body.text ``` -## Output - -Adds analysis to vCon: - -```json -{ - "analysis": [ - { - "type": "summary", - "vendor": "openai", - "body": { - "summary": "Customer called about billing issue...", - "topics": ["billing", "refund"], - "action_items": ["Process refund"], - "sentiment": "negative" - } - } - ] -} -``` +## Track the metrics + +`conserver.link.openai.analysis_time` and `conserver.link.openai.analysis_failures`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/check-and-tag.md b/docs/reference/links/check-and-tag.md new file mode 100644 index 00000000..7d69749b --- /dev/null +++ b/docs/reference/links/check-and-tag.md @@ -0,0 +1,77 @@ +# check_and_tag + +Asks an LLM a yes or no question about each dialog and adds a tag when the answer is yes. + +Module: `links.check_and_tag` + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `tag_name` | string | required | Name of the tag to add | +| `tag_value` | string | required | Value of the tag to add | +| `evaluation_question` | string | required | The question put to the model | +| `analysis_type` | string | `tag_evaluation` | The `type` of the analysis entry | +| `model` | string | `gpt-5` | Model name | +| `sampling_rate` | float | `1` | See [filter options](index.md#set-the-shared-filter-options) | +| `source.analysis_type` | string | `transcript` | Analysis entry to read | +| `source.text_location` | string | `body` | Path to the text. See [transcript text](index.md#point-analysis-at-the-transcript-text) | +| `response_format` | dict | `{"type": "json_object"}` | Passed to the model call | +| `verbosity` | string | `low` | In `default_options`, but no code reads it | +| `minimal_reasoning` | bool | `true` | In `default_options`, but no code reads it | +| `only_if` | dict | none | See [filter options](index.md#set-the-shared-filter-options) | + +The link also takes the [LLM client options](index.md#set-the-llm-client-options). One of those groups is required. The call sets no temperature. + +With the default `text_location` of `body`, a transcript whose body is an object reaches the model as the text form of that whole object. Set a narrower path such as `body.text`. + +## Follow the processing steps + +1. Raise `ValueError` if `tag_name`, `tag_value` or `evaluation_question` is empty. +2. Load the vCon and apply `only_if` and `sampling_rate`. +3. For each dialog, read the source text. Skip the dialog if the text is missing or if it already has an entry of this `analysis_type`. +4. Call the model, with up to 6 attempts. The link asks for a JSON object with a boolean `applies`. +5. Add the analysis, and add the tag when `applies` is true. +6. Save the vCon after the last dialog. + +Several `check_and_tag` links in one chain each need their own `analysis_type`. With the same value, the second link skips every dialog. + +## Read the return value + +Returns the uuid, including when the vCon is skipped or missing. A model failure or a reply that is not JSON raises, and the vCon goes to the dead letter queue. + +## Inspect the vCon changes + +One analysis entry per processed dialog, whatever the answer. + +| Field | Value | +|---|---| +| `type` | `analysis_type` | +| `dialog` | Dialog index | +| `vendor` | `openai`, whichever client group is in use | +| `body` | Object with `link_name`, `tag` as `name:value`, and `applies` | +| `encoding` | `json` | +| `vendor_schema` | `model` and `evaluation_question` | + +When the answer is yes, the link adds the tag `tag_name:tag_value`. See [tag](tag.md#inspect-the-vcon-changes) for how tags are stored. + +## Copy a configuration example + +```yaml +links: + check_refund: + module: links.check_and_tag + options: + OPENAI_API_KEY: your-openai-key + analysis_type: refund_check + tag_name: refund + tag_value: requested + evaluation_question: Did the customer ask for a refund? + source: + analysis_type: transcript + text_location: body.text +``` + +## Track the metrics + +`conserver.link.openai.evaluation_time`, `conserver.link.openai.evaluation_failures` and `conserver.link.openai.tags_applied`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/datatrails.md b/docs/reference/links/datatrails.md new file mode 100644 index 00000000..a2d137e2 --- /dev/null +++ b/docs/reference/links/datatrails.md @@ -0,0 +1,59 @@ +# datatrails + +Records an event for the vCon on the DataTrails service, so a vCon's hash can be checked later. + +Module: `links.datatrails` + +Imports `fastapi`, which the `conserver` dependency group does not include. The link fails to import in the `docker/Dockerfile.conserver` image, and each vCon then goes to the dead letter queue. It imports in the `docker/Dockerfile` image. + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `api_url` | string | `https://app.datatrails.ai/archivist` | Base API URL | +| `auth_url` | string | `https://app.datatrails.ai/archivist/iam/v1/appidp/token` | In `default_options`, but no code reads it. The token URL comes from `auth.token_endpoint` | +| `partner_id` | string | `not-set` | Sent as the `DataTrails-Partner-ID` header | +| `asset_attributes` | dict | `{"arc_display_type": "vcon_droid", "conserver_link_version": "0.3.0"}` | Attributes used to find or create the asset | +| `auth.type` | string | required | Must be `oidc-client-credentials`, in any case | +| `auth.token_endpoint` | string | required | Token URL | +| `auth.client_id` | string | required | Client ID | +| `auth.client_secret` | string | required | Client secret | +| `vcon_operation` | string | required | Operation name. Absent from `default_options`, so leaving the key out raises `KeyError`. An empty value becomes `vcon` | + +The event name is `vcon_` plus `vcon_operation` in lowercase, after any leading `vcon_` or `vcon-` is removed. + +## Follow the processing steps + +1. Merge the options and build the authenticator. +2. Load the vCon. +3. Find the day's asset by `asset_attributes` plus a `droid_id` of today's UTC date, or create it. +4. Create an event on that asset. Its attributes include the vCon's SHA-256 hash as `payload`, `vcon://` as `subject`, and the operation. +5. Create an asset-free event with the same attributes and a trail of the subject. A failure here is counted and logged, and the link continues. + +## Read the return value + +Returns the uuid. Bad `auth` raises `HTTPException` with status 501, and a missing vCon raises it with status 404. A failed token, asset or asset event request raises as well. In each case the vCon goes to the dead letter queue. + +## Inspect the vCon changes + +None. The link does not save the vCon or store a receipt. + +## Copy a configuration example + +```yaml +links: + datatrails_created: + module: links.datatrails + options: + partner_id: your-partner-id + vcon_operation: vcon_created + auth: + type: oidc-client-credentials + token_endpoint: https://app.datatrails.ai/archivist/iam/v1/appidp/token + client_id: your-client-id + client_secret: your-client-secret +``` + +## Track the metrics + +`conserver.link.datatrails.event_creation_failures`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/deepgram.md b/docs/reference/links/deepgram.md index 443c8e61..c2e37eec 100644 --- a/docs/reference/links/deepgram.md +++ b/docs/reference/links/deepgram.md @@ -1,69 +1,74 @@ # deepgram_link -Transcribes audio using the Deepgram API. +Transcribes recordings with the Deepgram API, or through a LiteLLM proxy. -## Configuration +Module: `links.deepgram_link` -```yaml -links: - deepgram_link: - module: links.deepgram_link - options: - model: nova-2 - language: en - punctuate: true - diarize: true -``` +!!! warning "Deprecated" + Use [`links.transcribe`](transcribe.md) with `vendor: deepgram`. The worker reroutes `module: links.deepgram_link` there and logs a warning. This module remains the implementation, and the options below go under `vendor_options`. -## Options +## Set the options | Option | Type | Default | Description | -|--------|------|---------|-------------| -| `model` | string | `nova-2` | Deepgram model (nova-2, nova, enhanced, base) | -| `language` | string | `en` | Language code | -| `punctuate` | bool | `true` | Add punctuation | -| `diarize` | bool | `false` | Speaker diarization | -| `smart_format` | bool | `true` | Smart formatting | -| `utterances` | bool | `false` | Split by utterance | -| `timeout` | int | `300` | Request timeout in seconds | +|---|---|---|---| +| `minimum_duration` | number | `60` | Skips recordings shorter than this many seconds | +| `DEEPGRAM_KEY` | string | `None` | Deepgram API key. Required unless the LiteLLM pair is set | +| `minimum_confidence` | float | `0.5` | Discards transcripts below this confidence | +| `api` | dict | none | Keyword arguments for Deepgram's `PrerecordedOptions`. Required on the direct path, and has no default | +| `LITELLM_PROXY_URL` | string | none | With `LITELLM_MASTER_KEY`, routes through LiteLLM | +| `LITELLM_MASTER_KEY` | string | none | See `LITELLM_PROXY_URL` | +| `model` | string | none | LiteLLM path only. Falls back to `api.model`, then `nova-3` | +| `send_ai_usage_data_to_url` | string | `""` | See [AI usage](index.md#report-ai-usage-to-an-endpoint). Direct path only | +| `ai_usage_api_token` | string | `""` | See [AI usage](index.md#report-ai-usage-to-an-endpoint) | + +## Follow the processing steps + +For each dialog: + +1. Skip it unless its `type` is `recording` and it has a `url`. A dialog with no `url` key raises `KeyError`. +2. If `duration` is missing and the URL ends in `.wav`, fetch the file to measure it and store the value on the dialog. +3. Skip it if it is shorter than `minimum_duration`. If the duration is still unknown, go on with a warning. +4. Skip it if it already has a `transcript` analysis. +5. Transcribe it, with up to 6 attempts. +6. On the direct path, discard the result if confidence is below `minimum_confidence`, count a failure, and go on to the next dialog. The LiteLLM path returns no confidence, so it skips this check. +7. Add the analysis. + +An empty result stops the loop. The vCon is saved after the loop. -## Requirements +## Read the return value -- `DEEPGRAM_KEY` environment variable +Returns the uuid, or `None` when the vCon is missing. A transcription failure after all retries raises, and the vCon goes to the dead letter queue. Missing credentials or a missing `api` raise the same way. -## Example +## Inspect the vCon changes + +One analysis entry per transcribed dialog. The direct path can also set `duration` on a dialog. + +| Field | Value | +|---|---| +| `type` | `transcript` | +| `dialog` | Dialog index | +| `vendor` | `deepgram` | +| `body` | Direct path: Deepgram's first alternative, with `detected_language` added. LiteLLM path: an object with `transcript` | +| `encoding` | `json` | +| `vendor_schema` | `opts`, with credential-like option names removed | + +## Copy a configuration example ```yaml -chains: - transcription: - links: - - deepgram_link: - model: nova-2 - language: en - diarize: true - storages: - - postgres - ingress_lists: - - audio_input - enabled: 1 +links: + transcribe_deepgram: + module: links.transcribe + options: + vendor: deepgram + vendor_options: + DEEPGRAM_KEY: your-deepgram-key + minimum_duration: 30 + minimum_confidence: 0.5 + api: + model: nova-3 + smart_format: true ``` -## Output - -Adds transcription to vCon analysis: - -```json -{ - "analysis": [ - { - "type": "transcript", - "vendor": "deepgram", - "body": { - "transcript": "Hello, how can I help you today?", - "words": [...], - "confidence": 0.95 - } - } - ] -} -``` +## Track the metrics + +`conserver.link.deepgram.transcription_time`, `conserver.link.deepgram.transcription_failures` and `conserver.link.deepgram.confidence`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/delay.md b/docs/reference/links/delay.md new file mode 100644 index 00000000..62e3d371 --- /dev/null +++ b/docs/reference/links/delay.md @@ -0,0 +1,33 @@ +# delay + +Sleeps for a set time and passes the vCon on. It is a test aid for watching concurrent workers, and has no use in production chains. + +Module: `links.delay` + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `seconds` | number | `5` | Time to sleep. A negative value logs a warning and counts as 0 | + +## Follow the processing steps + +The link sleeps, blocking its worker for that time. It never reads the vCon. See [Workers](../../configuration/workers.md) for `CONSERVER_VCON_CONCURRENCY`. + +## Read the return value + +Always returns the uuid. + +## Inspect the vCon changes + +None. + +## Copy a configuration example + +```yaml +links: + slow_down: + module: links.delay + options: + seconds: 5 +``` diff --git a/docs/reference/links/detect-engagement.md b/docs/reference/links/detect-engagement.md new file mode 100644 index 00000000..3d6f31a8 --- /dev/null +++ b/docs/reference/links/detect-engagement.md @@ -0,0 +1,66 @@ +# detect_engagement + +Asks an LLM whether both the customer and the agent spoke, then records the answer as analysis and a tag. + +Module: `links.detect_engagement` + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `prompt` | string | `Did both the customer and the agent speak? Respond with 'true' if yes, 'false' if not. Respond with only 'true' or 'false'.` | Placed before the transcript | +| `analysis_type` | string | `engagement_analysis` | The `type` of the analysis entry | +| `model` | string | `gpt-4.1` | Model name | +| `sampling_rate` | float | `1` | See [filter options](index.md#set-the-shared-filter-options) | +| `temperature` | float | `0.2` | Sampling temperature | +| `source.analysis_type` | string | `transcript` | Analysis entry to read | +| `source.text_location` | string | `body.paragraphs.transcript` | Path to the text. See [transcript text](index.md#point-analysis-at-the-transcript-text) | +| `OPENAI_API_KEY` | string | `OPENAI_API_KEY` from the environment at import, or `""` | OpenAI key | +| `only_if` | dict | none | See [filter options](index.md#set-the-shared-filter-options) | + +The link also takes the other [LLM client options](index.md#set-the-llm-client-options). This is the one LLM link that falls back to the environment for its key. + +## Follow the processing steps + +1. Merge the options, load the vCon, and apply `only_if` and `sampling_rate`. +2. Build the client. With no credentials the link logs a warning and skips the vCon. +3. For each dialog, read the source text. Skip the dialog if the text is missing or if it already has an entry of this `analysis_type`. +4. Call the model through the Responses API (`client.responses.create`), with up to 6 attempts. Only a reply equal to `true`, ignoring case and surrounding space, counts as engaged. +5. Add the analysis and the tag. +6. Save the vCon after the last dialog. + +## Read the return value + +Returns the uuid, including when the vCon is skipped. A model failure after all retries raises, and the vCon goes to the dead letter queue. A missing vCon raises `AttributeError`, unless `only_if` is set, which then skips it and returns the uuid. + +## Inspect the vCon changes + +One analysis entry per processed dialog. + +| Field | Value | +|---|---| +| `type` | `analysis_type` | +| `dialog` | Dialog index | +| `vendor` | `openai`, whichever client group is in use | +| `body` | The string `true` or `false` | +| `encoding` | `none` | +| `vendor_schema` | `model`, `prompt` and `is_engaged` | + +The link also adds the tag `engagement:true` or `engagement:false`. See [tag](tag.md#inspect-the-vcon-changes) for how tags are stored. + +## Copy a configuration example + +```yaml +links: + engagement: + module: links.detect_engagement + options: + OPENAI_API_KEY: your-openai-key + source: + analysis_type: transcript + text_location: body.text +``` + +## Track the metrics + +`conserver.link.openai.engagement_analysis_time`, `conserver.link.openai.engagement_analysis_failures` and `conserver.link.openai.engagement_detected`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/diet.md b/docs/reference/links/diet.md new file mode 100644 index 00000000..c13e6e88 --- /dev/null +++ b/docs/reference/links/diet.md @@ -0,0 +1,71 @@ +# diet + +Removes content from a vCon, or moves dialog bodies out to S3 or an HTTP endpoint. + +Module: `links.diet` + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `remove_dialog_body` | bool | `false` | Empties each dialog's `body`, after moving it if a target is set | +| `post_media_to_url` | string | `""` | URL that receives each body. Used when `s3_bucket` is empty | +| `remove_analysis` | bool | `false` | Deletes the whole `analysis` array | +| `remove_attachment_types` | list | `[]` | Removes attachments whose `mime_type` is in this list | +| `remove_system_prompts` | bool | `false` | Deletes every `system_prompt` key, at any depth | +| `s3_bucket` | string | `""` | Bucket for dialog bodies. Takes priority over `post_media_to_url` | +| `s3_path` | string | `""` | Key prefix | +| `aws_access_key_id` | string | `""` | AWS access key ID | +| `aws_secret_access_key` | string | `""` | AWS secret key | +| `aws_region` | string | `us-east-1` | AWS region | +| `presigned_url_expiration` | number | `None` | Lifetime of the stored URL in seconds. `None` means 3600 | + +## Follow the processing steps + +1. Load the vCon. If it is missing, log an error and pass the uuid on. +2. If `remove_dialog_body` is true, handle each dialog that has a `body`: + - With `s3_bucket`, upload the body to `[s3_path/]/[_].txt` and store a presigned URL. + - With `post_media_to_url`, POST JSON with `content`, `vcon_uuid` and `dialog_id`. A 200 reply with a `url` key sets that URL. + - With neither, set `body` to `""`. +3. Delete `analysis` if `remove_analysis` is true. +4. Filter attachments if `remove_attachment_types` is set. +5. Delete `system_prompt` keys if `remove_system_prompts` is true. +6. Save the vCon. + +## Check the limits + +- A failed upload or POST sets `body` to `""`. The content is gone from the vCon and the link continues. Only the POST path counts `conserver.link.diet.media_post_failures`. +- A presigned URL stops working when it expires, and the link keeps no other reference to the object. +- `remove_analysis` deletes the key itself. A later link that adds analysis then raises `KeyError`, so place `diet` after them. +- `remove_attachment_types` compares the literal field `mime_type`. Attachments that use `mediatype`, as spec-current vCons do, never match. +- The attachment filter has no exception for `lawful_basis`. An attachment with a listed `mime_type` is removed whatever its purpose. +- The link does not read `only_if` or `sampling_rate`. + +## Read the return value + +Returns the uuid, also when the vCon is missing. + +## Inspect the vCon changes + +The link only removes or replaces content. A moved dialog has its `body` set to the URL and gains `body_type: "url"`, and its `encoding` stays as it was. + +## Copy a configuration example + +```yaml +links: + slim_down: + module: links.diet + options: + remove_dialog_body: true + s3_bucket: vcon-media + s3_path: dialogs + aws_access_key_id: your-access-key-id + aws_secret_access_key: your-secret-key + aws_region: us-east-1 + presigned_url_expiration: 86400 + remove_system_prompts: true +``` + +## Track the metrics + +`conserver.link.diet.media_post_failures`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/expire-vcon.md b/docs/reference/links/expire-vcon.md new file mode 100644 index 00000000..7d469e65 --- /dev/null +++ b/docs/reference/links/expire-vcon.md @@ -0,0 +1,37 @@ +# expire_vcon + +Sets a time to live on the vCon's Redis key. + +Module: `links.expire_vcon` + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `seconds` | int | `86400` | Time to live in seconds | + +The link does not merge `default_options`. Set `seconds` in `options`, or the link raises `KeyError`. + +## Follow the processing steps + +The link calls `VconQueue().set_vcon_ttl`, which runs Redis `EXPIRE` on `vcon:`. Later saves in the chain keep that expiry. + +Only the Redis copy expires. Copies in storage backends stay, and when `VCON_STORAGE_FALLBACK_ENABLED` is on, a later read loads the vCon back from storage into Redis. + +## Read the return value + +Returns the uuid, also when the key does not exist. + +## Inspect the vCon changes + +None. The vCon content does not change. + +## Copy a configuration example + +```yaml +links: + expire_in_a_day: + module: links.expire_vcon + options: + seconds: 86400 +``` diff --git a/docs/reference/links/groq-whisper.md b/docs/reference/links/groq-whisper.md new file mode 100644 index 00000000..c3fb78d7 --- /dev/null +++ b/docs/reference/links/groq-whisper.md @@ -0,0 +1,69 @@ +# groq_whisper + +Transcribes recordings with Groq's hosted Whisper model. + +Module: `links.groq_whisper` + +!!! warning "Deprecated" + Use [`links.transcribe`](transcribe.md) with `vendor: groq`. The worker reroutes `module: links.groq_whisper` there and logs a warning. This module remains the implementation, and the options below go under `vendor_options`. + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `minimum_duration` | number | `30` | Skips recordings shorter than this many seconds | +| `API_KEY` | string | `GROQ_API_KEY` from the environment at import, or `YOUR_GROQ_API_KEY` | Groq API key | +| `Content-Type` | string | `audio/flac` | In `default_options`, but no code reads it | + +The model is fixed in the code as `whisper-large-v3-turbo`. + +## Follow the processing steps + +For each dialog: + +1. Skip it unless its `type` is `recording`. +2. Skip it if `duration` is below `minimum_duration`. A dialog with no `duration` raises, and the vCon goes to the dead letter queue: `KeyError` when the key is absent, `TypeError` when it is null, as on any vCon sent through `POST /vcon` without one. +3. Skip it if it already has a `transcript` analysis. +4. Get the audio. An inline `body` is decoded by its `encoding`. Otherwise the link downloads `url` and, if the dialog has `alg` of `SHA-512` and a `signature`, verifies it. +5. Send the audio to Groq, with up to 6 attempts. +6. Add the analysis. + +Any transcription failure stops the loop. The link counts the failure and logs it, saves the vCon, and the chain continues with no transcript for that dialog. + +## Check the side effects + +Importing this module changes the whole worker process. It removes `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` and their lowercase forms from the environment, and it replaces `httpx.Client` with a version that drops proxy arguments. Other links in that worker lose their proxy settings from that point on. + +## Read the return value + +Returns the uuid, also after a transcription failure. A missing vCon raises `AttributeError`. + +## Inspect the vCon changes + +One analysis entry per transcribed dialog. + +| Field | Value | +|---|---| +| `type` | `transcript` | +| `dialog` | Dialog index | +| `vendor` | `groq_whisper` | +| `body` | The Groq response as an object, with the text in `text` | +| `encoding` | `json` | +| `vendor_schema` | `opts`, with credential-like option names removed | + +## Copy a configuration example + +```yaml +links: + transcribe_groq: + module: links.transcribe + options: + vendor: groq + vendor_options: + API_KEY: your-groq-key + minimum_duration: 30 +``` + +## Track the metrics + +`conserver.link.groq_whisper.transcription_time` and `conserver.link.groq_whisper.transcription_failures`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/hugging-llm.md b/docs/reference/links/hugging-llm.md new file mode 100644 index 00000000..21e22380 --- /dev/null +++ b/docs/reference/links/hugging-llm.md @@ -0,0 +1,66 @@ +# hugging_llm_link + +Sends a vCon's transcripts to a Hugging Face language model, through the hosted API or a local model. + +Module: `links.hugging_llm_link` + +!!! danger "Known issue" + The link does not work as written. See [the known issues](#check-the-known-issues) before adding it to a chain. Its tests in the repo are commented out. + +## Set the options + +The module has no `default_options`. Its defaults come from the `LLMConfig` dataclass. + +| Option | Type | Default | Description | +|---|---|---|---| +| `HUGGINGFACE_API_KEY` | string | none | Bearer token for the hosted API | +| `model` | string | `meta-llama/Llama-2-70b-chat-hf` | Model name | +| `use_local_model` | bool | `false` | Runs the model in the worker through `transformers`, on CPU | +| `max_length` | int | `1000` | Generation length | +| `temperature` | float | `0.7` | Sampling temperature | + +The local path needs an optional dependency group and a model backend such as torch: + +```bash +uv sync --group conserver --group conserver-local +``` + +## Follow the processing steps + +1. Load the vCon. Stop if it already has an `llm_analysis` entry. +2. Join the `body.transcript` text of every `transcript` analysis. Stop if there is none, so transcripts that keep their text in `body.text` count as missing. +3. Call the model with a fixed prompt that asks for a summary, sentiment and key points. +4. Add the analysis and save the vCon. + +## Check the known issues + +Step 4 raises `TypeError`, because `_add_analysis_to_vcon` calls `add_analysis` with no `dialog`, which `common/vcon.py` requires. Any vCon that reaches that step goes to the dead letter queue. + +On the hosted API path the code also calls the async `analyze` method without awaiting it, so no request is made. + +`conserver/links/hugging_llm_link/main.py` defines a separate `HuggingLLMLink` class. It has no `run` function and the worker does not use it. + +## Read the return value + +Returns the uuid when the vCon already has the analysis, has no transcript, or the model call fails. The failure in step 4 raises. + +## Inspect the vCon changes + +None as the code stands. The code is written to add an entry of type `llm_analysis` with vendor `huggingface`, a `body` holding `analysis`, `model` and `parameters`, and a `vendor_schema` holding the options. + +## Copy a configuration example + +```yaml +links: + hf_analysis: + module: links.hugging_llm_link + options: + HUGGINGFACE_API_KEY: your-hugging-face-token + model: meta-llama/Llama-2-70b-chat-hf + max_length: 1000 + temperature: 0.7 +``` + +## Track the metrics + +`conserver.link.huggingface.llm_time` and `conserver.link.huggingface.llm_failures`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/huggingface-whisper.md b/docs/reference/links/huggingface-whisper.md new file mode 100644 index 00000000..d6f181df --- /dev/null +++ b/docs/reference/links/huggingface-whisper.md @@ -0,0 +1,68 @@ +# hugging_face_whisper + +Transcribes recordings with a Whisper model on a Hugging Face inference endpoint. + +Module: `links.hugging_face_whisper` + +!!! warning "Deprecated" + Use [`links.transcribe`](transcribe.md) with `vendor: hugging_face`. The worker reroutes `module: links.hugging_face_whisper` there and logs a warning. This module remains the implementation, and the options below go under `vendor_options`. + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `minimum_duration` | number | `30` | Skips recordings shorter than this many seconds | +| `API_URL` | string | `https://xxxxxx.us-east-1.aws.endpoints.huggingface.cloud` | Placeholder. Set your endpoint URL | +| `API_KEY` | string | `Bearer hf_XXXXX` | Placeholder. Set the bare token: the code adds `Bearer ` itself | +| `Content-Type` | string | `audio/flac` | Request content type. Match it to your audio | + +## Follow the processing steps + +For each dialog: + +1. Skip it unless its `type` is `recording`. +2. Skip it if `duration` is below `minimum_duration`. A dialog with no `duration` raises, and the vCon goes to the dead letter queue: `KeyError` when the key is absent, `TypeError` when it is null, as on any vCon sent through `POST /vcon` without one. +3. Skip it if it already has a `transcript` analysis. +4. Get the audio. An inline `body` is decoded by its `encoding`. Otherwise the link downloads `url` and, if the dialog has `alg` of `SHA-512` and a `signature`, verifies it. +5. Post the audio to `API_URL`, with up to 6 attempts. +6. Add the analysis. + +The link does not check the HTTP status. Any JSON reply, including an error object from the endpoint, is stored as the transcript. + +An exception or an empty reply stops the loop. The link counts the failure and logs it, saves the vCon, and the chain continues. + +## Read the return value + +Returns the uuid, also after a transcription failure. A missing vCon raises `AttributeError`. + +## Inspect the vCon changes + +One analysis entry per transcribed dialog. + +| Field | Value | +|---|---| +| `type` | `transcript` | +| `dialog` | Dialog index | +| `vendor` | `hugging_face_whisper` | +| `body` | The endpoint's JSON reply | +| `encoding` | `json` when the reply is an object or list | +| `vendor_schema` | `opts`, with credential-like option names removed | + +## Copy a configuration example + +```yaml +links: + transcribe_hf: + module: links.transcribe + options: + vendor: hugging_face + vendor_options: + API_URL: https://your-endpoint.endpoints.huggingface.cloud + API_KEY: your-hugging-face-token + Content-Type: audio/flac + minimum_duration: 30 +``` + +## Track the metrics + +`conserver.link.hugging_face_whisper.transcription_time` and `conserver.link.hugging_face_whisper.transcription_failures`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/index.md b/docs/reference/links/index.md new file mode 100644 index 00000000..2c692314 --- /dev/null +++ b/docs/reference/links/index.md @@ -0,0 +1,144 @@ +# Links + +A link is one processing step in a chain. Each module lives in `conserver/links//` and loads as `links.`. This section has one page per module, with options and defaults taken from the code. + +## Browse the link modules + +| Page | Module | Status | Effect on the vCon | +|---|---|---|---| +| [transcribe](transcribe.md) | `links.transcribe` | Current | Depends on the vendor. Adds `transcript` analysis | +| [wtf_transcribe](wtf-transcribe.md) | `links.wtf_transcribe` | Current | Adds `wtf_transcription` analysis | +| [deepgram_link](deepgram.md) | `links.deepgram_link` | Deprecated | Adds `transcript` analysis | +| [groq_whisper](groq-whisper.md) | `links.groq_whisper` | Deprecated | Adds `transcript` analysis | +| [hugging_face_whisper](huggingface-whisper.md) | `links.hugging_face_whisper` | Deprecated | Adds `transcript` analysis | +| [openai_transcribe](openai-transcribe.md) | `links.openai_transcribe` | Deprecated | Adds `transcript` analysis | +| [analyze](analyze.md) | `links.analyze` | Current | Adds analysis per dialog | +| [analyze_and_label](analyze-and-label.md) | `links.analyze_and_label` | Current | Adds analysis per dialog and one tag per label | +| [analyze_vcon](analyze-vcon.md) | `links.analyze_vcon` | Current | Adds one analysis for the whole vCon | +| [check_and_tag](check-and-tag.md) | `links.check_and_tag` | Current | Adds analysis per dialog and a tag when the answer is yes | +| [detect_engagement](detect-engagement.md) | `links.detect_engagement` | Current | Adds analysis per dialog and an `engagement` tag | +| [hugging_llm_link](hugging-llm.md) | `links.hugging_llm_link` | Known issue | Fails when it reaches a transcript | +| [tag](tag.md) | `links.tag` | Current | Adds tags | +| [tag_router](tag-router.md) | `links.tag_router` | Current | None. Pushes the uuid to other lists | +| [jq_link](jq.md) | `links.jq_link` | Current | None. Filters the chain | +| [sampler](sampler.md) | `links.sampler` | Current | None. Filters the chain | +| [webhook](webhook.md) | `links.webhook` | Current | None. Posts the vCon out | +| [post_analysis_to_slack](slack.md) | `links.post_analysis_to_slack` | Current | Marks posted analysis entries | +| [diet](diet.md) | `links.diet` | Current | Removes or moves content | +| [expire_vcon](expire-vcon.md) | `links.expire_vcon` | Current | None. Sets a Redis TTL | +| [datatrails](datatrails.md) | `links.datatrails` | Current. Imports `fastapi`, so it fails to import in the `docker/Dockerfile.conserver` image and each vCon goes to the dead letter queue. It imports in the `docker/Dockerfile` image | None. Records events externally | +| [scitt](scitt.md) | `links.scitt` | Current. Imports `fastapi`, so it fails to import in the `docker/Dockerfile.conserver` image and each vCon goes to the dead letter queue. It imports in the `docker/Dockerfile` image | Adds `scitt_receipt` analysis | +| [delay](delay.md) | `links.delay` | Test aid | None. Sleeps | + +## Declare a link in a chain + +Define each link once under `links`, then list its name in a chain. A chain holds names only. + +```yaml +links: + summarize: + module: links.analyze + options: + OPENAI_API_KEY: your-openai-key + prompt: Summarize this conversation in two sentences. + source: + analysis_type: transcript + text_location: body.text + +chains: + main: + links: + - summarize + storages: + - postgres + ingress_lists: + - default + enabled: 1 +``` + +Set `options` on every link, even if it is only `options: {}`. `conserver/main.py` passes the value of `options` straight to `run`, so a link with no `options` key receives `None` in place of its `default_options`, and most modules then raise. A missing block does not break `delay`, `hugging_llm_link` or the four deprecated transcription modules. `transcribe` then falls to `whisper_builtin` and raises, and `wtf_transcribe` halts the chain because it has no `vfun-server-url`. + +The config loader reads YAML with `yaml.safe_load` and does not expand `${VAR}`. A value such as `${OPENAI_API_KEY}` reaches the link as that literal text. See [YAML configuration](../../configuration/yaml-configuration.md) for the rest of the file. + +## Follow the link contract + +The worker calls `run(vcon_uuid, link_name, opts)` for each link in order. + +| Result | Effect | +|---|---| +| Returns the uuid | The next link runs. After the last link the vCon goes to egress lists and then storages | +| Returns a different uuid | The chain continues with that uuid | +| Returns `None` | The chain stops. Storages and egress lists do not run for this vCon | +| Raises | The worker moves the vCon to the [dead letter queue](../../operations/dead-letter-queue.md) of its ingress list | + +So a filter that drops a vCon also keeps it out of the chain's storages. Its copy in Redis stays, subject to any expiry on the key. + +After each run the worker calls `conserver/after_link_hook.py` and passes it the `after_link` key from `options`, if there is one. The hook in this repo does nothing. + +## Set the shared filter options + +`analyze`, `analyze_and_label`, `analyze_vcon`, `check_and_tag` and `detect_engagement` read these two options through `lib.links.filters`. In both cases a skipped vCon continues down the chain unchanged. The other links ignore them, and `post_analysis_to_slack` has its own [`only_if`](slack.md) with a different shape. + +| Option | Type | Default | Description | +|---|---|---|---| +| `only_if` | dict | none | Runs the link only when the vCon has a matching entry. Omit it to include every vCon | +| `only_if.section` | string | required | `attachments` or `analysis` | +| `only_if.type` | string | none | Entry to match. Alias of `only_if.purpose`; give one of the two | +| `only_if.purpose` | string | none | Entry to match. Takes priority over `only_if.type` | +| `only_if.includes` | string | required | Value to look for in the entry's `body` | +| `sampling_rate` | float | `1` in each module's `default_options` | Chance of running, from 0 to 1. A value of `0` or an unset option means always run | + +For `attachments`, an entry matches on either its `purpose` or its legacy `type`. For `analysis` it matches on `type`. When the target is `tags`, `includes` must equal a whole `name:value` tag. For any other target it is a substring of the body, or of the JSON text of a dict or list body. + +```yaml +options: + only_if: + section: attachments + purpose: tags + includes: department:sales + sampling_rate: 0.25 +``` + +## Set the LLM client options + +`analyze`, `analyze_and_label`, `analyze_vcon`, `check_and_tag`, `detect_engagement` and `openai_transcribe` build their client with `lib.openai_client.get_openai_client`, as does the LiteLLM path of `deepgram_link`. The client reads these keys from the link options, not from the environment. The first complete group wins, in this order. + +| Option | Description | +|---|---| +| `LITELLM_PROXY_URL`, `LITELLM_MASTER_KEY` | Use a LiteLLM proxy. Both are required | +| `AZURE_OPENAI_ENDPOINT`, `AZURE_OPENAI_API_KEY` | Use Azure OpenAI. Both are required | +| `AZURE_OPENAI_API_VERSION` | Azure API version. Defaults to `2024-10-21` | +| `OPENAI_API_KEY`, `openai_api_key`, `api_key` | Use OpenAI. The first one set is used | +| `organization`, `organization_key` | Optional, for OpenAI and LiteLLM | +| `project`, `project_key` | Optional, for OpenAI and LiteLLM | + +With none of these set the client raises `ValueError`. Only `detect_engagement` catches that and skips the vCon. + +Calls to the model make up to 6 attempts with exponential backoff. After the last attempt the error reaches the link. + +## Point analysis at the transcript text + +`analyze`, `analyze_and_label`, `check_and_tag` and `detect_engagement` find their input with a `source` option. The link looks up the analysis entry of type `source.analysis_type` on each dialog, decodes its body, then reads the dotted path `source.text_location`. A dialog with no entry or no text at that path logs a warning and is skipped. + +The default path must fit the transcription link in the chain. + +| Transcript written by | `text_location` to use | +|---|---| +| `transcribe` with vendor `openai` or `groq` | `body.text` | +| `transcribe` with vendor `deepgram` | `body.transcript`. `body.paragraphs.transcript` works only when the Deepgram response has paragraphs. TODO(verify) which `api` options produce them | +| `transcribe` with vendor `hugging_face` | Depends on the endpoint. Usually `body.text`. TODO(verify) | + +## Report AI usage to an endpoint + +`analyze`, `deepgram_link` and `openai_transcribe` can post usage records. Nothing is sent unless `send_ai_usage_data_to_url` is set. + +| Option | Type | Default | Description | +|---|---|---|---| +| `send_ai_usage_data_to_url` | string | `""` | URL that receives one JSON record per model call | +| `ai_usage_api_token` | string | `""` | Sent as a bearer token | + +## Carry lawful basis attachments + +No link creates, reads or checks a `lawful_basis` attachment, and no link gates on consent. A transcription or analysis link runs whether or not one is present. + +Links leave the attachment in place as they load and save the vCon. The only link that removes attachments is [`diet`](diet.md), which filters on `mime_type` and has no exception for `lawful_basis`. diff --git a/docs/reference/links/jq.md b/docs/reference/links/jq.md index 0e012b23..3d4694ff 100644 --- a/docs/reference/links/jq.md +++ b/docs/reference/links/jq.md @@ -1,69 +1,52 @@ # jq_link -Filters vCons with jq expressions. +Passes or stops a vCon according to a jq expression. -## Configuration +Module: `links.jq_link` -```yaml -links: - jq_filter: - module: links.jq_link - options: - filter: '.attachments | length > 0' - forward_matches: true -``` - -## Options +## Set the options | Option | Type | Default | Description | -|--------|------|---------|-------------| -| `filter` | string | `"."` | jq expression evaluated against the vCon | -| `forward_matches` | boolean | `true` | Forward matches when `true`, or forward non-matches when `false` | +|---|---|---|---| +| `filter` | string | `.` | jq expression run against the vCon | +| `forward_matches` | bool | `true` | When true, matching vCons continue. When false, non-matching vCons continue | -## Examples +## Follow the processing steps -```yaml -links: - has_analysis: - module: links.jq_link - options: - filter: '.analysis | length > 0' - forward_matches: true +1. Load the vCon and run the expression on its dict form. +2. Treat the vCon as a match if the first result is truthy. Later results are ignored, and no result means no match. +3. Forward the vCon if the match agrees with `forward_matches`. - skip_empty_analysis: - module: links.jq_link - options: - filter: '.analysis | length == 0' - forward_matches: false +Truthiness here is Python's, not jq's. A first result of `0`, `""`, `[]` or `{}` is not a match. + +Some legacy vCons hold mixed values in `body` arrays, and jq string functions such as `startswith()` raise on the non-strings. When jq reports `requires string inputs`, the link retries once with those arrays reduced to their strings. For new filters, guard explicitly: + +```jq +.attachments[0] +| select(any(.body[]; type == "string" and startswith("call_type:") and . != "call_type:2")) ``` -## Mixed-Type `body` Arrays +## Read the return value -Some legacy vCons contain mixed values inside attachment or analysis `body` -arrays. For example, a tags-like array may contain strings plus integers or -objects. Raw jq string functions such as `startswith()` fail on non-string -inputs. +Returns the uuid to forward, or `None` to stop the chain. An invalid filter or any other jq error is logged and also returns `None`, so a broken expression drops every vCon and raises nothing. A missing vCon returns `None`. -`jq_link` now retries once with string-only `body` arrays when jq raises a -string-input type error. That hardens common filters that scan `body[]` values -for tag prefixes. +A stopped chain skips its storages and egress lists. -For new filters, prefer explicit string guards: +## Inspect the vCon changes -```jq -.attachments[0] -| select(.body[] | strings | startswith("call_type:") and . != "call_type:2") -``` +None. -or: +## Copy a configuration example -```jq -.attachments[0] -| select(any(.body[]; type == "string" and startswith("call_type:") and . != "call_type:2")) +```yaml +links: + has_analysis: + module: links.jq_link + options: + filter: '.analysis | length > 0' + forward_matches: true ``` -## Behavior +## Track the metrics -If the jq expression returns a truthy first result, the link treats the vCon as -a match. Invalid filters or runtime jq failures are logged and the vCon is -filtered out. +`conserver.link.jq.vcon_filtered_out`, `conserver.link.jq.filter_errors` and `conserver.link.jq.string_body_array_retries`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/openai-transcribe.md b/docs/reference/links/openai-transcribe.md new file mode 100644 index 00000000..adbc6a43 --- /dev/null +++ b/docs/reference/links/openai-transcribe.md @@ -0,0 +1,77 @@ +# openai_transcribe + +Transcribes recordings with an OpenAI-compatible transcription API, splitting long audio into chunks. + +Module: `links.openai_transcribe` + +!!! warning "Deprecated" + Use [`links.transcribe`](transcribe.md) with `vendor: openai`. The worker reroutes `module: links.openai_transcribe` there and logs a warning. This module remains the implementation, and the options below go under `vendor_options`. + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `OPENAI_API_KEY` | string | `None` | See [LLM client options](index.md#set-the-llm-client-options) | +| `AZURE_OPENAI_API_KEY` | string | `None` | See [LLM client options](index.md#set-the-llm-client-options) | +| `AZURE_OPENAI_ENDPOINT` | string | `None` | See [LLM client options](index.md#set-the-llm-client-options) | +| `AZURE_OPENAI_API_VERSION` | string | `2024-10-21` | See [LLM client options](index.md#set-the-llm-client-options) | +| `model` | string | `gpt-4o-transcribe` | Transcription model | +| `language` | string | `en` | In `default_options`, but no code reads it, so it never reaches the API | +| `minimum_duration` | number | `3` | Skips recordings shorter than this many seconds | +| `max_chunk_duration` | number | `480` | Longest chunk in seconds | +| `use_silence_chunking` | bool | `true` | Splits at silences near each chunk boundary | +| `silence_thresh` | number | `-40` | Silence threshold in dBFS | +| `silence_len` | number | `2000` | Shortest silence in milliseconds | +| `send_ai_usage_data_to_url` | string | `""` | See [AI usage](index.md#report-ai-usage-to-an-endpoint) | +| `ai_usage_api_token` | string | `""` | See [AI usage](index.md#report-ai-usage-to-an-endpoint) | + +## Follow the processing steps + +For each dialog: + +1. Skip it unless its `type` is `recording` and it has a `url`. Inline `body` audio is not read. +2. Skip it if `duration` is below `minimum_duration`. If `duration` is missing, go on with a warning. +3. Skip it if it already has a `transcript` analysis. +4. Download the audio and split it if it runs past `max_chunk_duration`. With silence chunking on, each split goes to the silence nearest the boundary, within a quarter of `max_chunk_duration`. Otherwise it falls on the boundary. Chunks are exported as mono 16 kHz MP3. +5. Transcribe each chunk in turn, with up to 6 attempts for the whole download and transcription. Join the chunk texts with spaces. +6. Add the analysis. + +The link uses ffmpeg, which the server images install. An empty result stops the loop. + +A failing dialog takes about a minute to reach the dead letter queue, because the waits between attempts add up to 62 seconds. That worker handles nothing else meanwhile unless `CONSERVER_VCON_CONCURRENCY` is above 1. + +## Read the return value + +Returns the uuid. A transcription failure after all retries raises, and the vCon goes to the dead letter queue. A missing vCon raises `AttributeError`. + +## Inspect the vCon changes + +One analysis entry per transcribed dialog. + +| Field | Value | +|---|---| +| `type` | `transcript` | +| `dialog` | Dialog index | +| `vendor` | `openai` | +| `body` | The API response as an object, with the text in `text`. A chunked result also has `chunked_transcription` with `total_chunks` and `chunk_results` | +| `encoding` | `json` | +| `vendor_schema` | `opts`, with credential-like option names removed | + +## Copy a configuration example + +```yaml +links: + transcribe_openai: + module: links.transcribe + options: + vendor: openai + vendor_options: + OPENAI_API_KEY: your-openai-key + model: gpt-4o-transcribe + minimum_duration: 3 + max_chunk_duration: 480 +``` + +## Track the metrics + +`conserver.link.openai.transcription_time` and `conserver.link.openai.transcription_failures`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/sampler.md b/docs/reference/links/sampler.md new file mode 100644 index 00000000..bc275c47 --- /dev/null +++ b/docs/reference/links/sampler.md @@ -0,0 +1,53 @@ +# sampler + +Keeps a share of vCons and stops the chain for the rest. + +Module: `links.sampler` + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `method` | string | `percentage` | `percentage`, `rate`, `modulo` or `time_based` | +| `value` | number | `50` | Meaning depends on `method` | +| `seed` | any | `None` | Reseeds Python's `random` on every run when set | + +| `method` | `value` | Keeps a vCon when | +|---|---|---| +| `percentage` | Percent, 0 to 100 | A random number from 0 to 100 is at or below `value` | +| `rate` | Positive number | An exponential draw with mean `value` is at most 1. Each vCon is an independent draw, with chance 1 - e^(-1/`value`). No timing state is kept | +| `modulo` | Positive integer | The first 8 hex digits of the uuid's SHA-256, as an integer, divide evenly by `value`. The result is stable for a given uuid and keeps about one in `value` | +| `time_based` | Positive integer, seconds | The current Unix time in whole seconds divides evenly by `value` | + +Avoid `seed` with `percentage` or `rate`. The link reseeds on every run, so every vCon gets the same draw and they are all kept or all dropped. The call also reseeds the shared generator for the worker process, which affects `sampling_rate` in other links. `modulo` and `time_based` do not use the generator. + +## Follow the processing steps + +1. Merge the options and reseed if `seed` is set. +2. Run the method. An unknown `method` raises `ValueError`. +3. Count the outcome. + +The link does not load the vCon. + +## Read the return value + +Returns the uuid to keep the vCon, or `None` to stop the chain. A dropped vCon skips this chain's storages and egress lists. + +## Inspect the vCon changes + +None. + +## Copy a configuration example + +```yaml +links: + sample_ten_percent: + module: links.sampler + options: + method: percentage + value: 10 +``` + +## Track the metrics + +`conserver.link.sampler.sampled_in` and `conserver.link.sampler.sampled_out`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/scitt.md b/docs/reference/links/scitt.md new file mode 100644 index 00000000..4b1e14ea --- /dev/null +++ b/docs/reference/links/scitt.md @@ -0,0 +1,72 @@ +# scitt + +Registers a signed statement of the vCon's hash on a SCRAPI-compatible SCITT transparency service, and stores the verified receipt. + +Module: `links.scitt` + +Imports `fastapi`, which the `conserver` dependency group does not include. The link fails to import in the `docker/Dockerfile.conserver` image, and each vCon then goes to the dead letter queue. It imports in the `docker/Dockerfile` image. + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `scrapi_url` | string | `http://scittles:8000` | Base URL of the transparency service | +| `signing_key_pem` | string | `None` | Base64-encoded P-256 PEM key. Used first when set | +| `signing_key_path` | string | `/etc/scitt/signing-key.pem` | Path to a P-256 PEM key | +| `issuer` | string | `conserver` | Issuer of the statement | +| `key_id` | string | `conserver-key-1` | Key ID in the statement | +| `vcon_operation` | string | `vcon_created` | Lifecycle event, such as `vcon_created` or `vcon_enhanced` | +| `store_receipt` | bool | `true` | Adds the receipts to the vCon | + +## Follow the processing steps + +1. Load the vCon and its SHA-256 hash, then load the signing key. +2. Collect the `tel` of each party. With none, use a single statement for the vCon. +3. For each entry, build a COSE Sign1 statement. + + | Case | Subject | Signed payload | + |---|---|---| + | Party with `tel` | `tel:` | `::` | + | No party has `tel` | `vcon://` | `:` | + +4. Register the statement at `/entries`, polling if the service replies 303. +5. Verify the receipt: recompute the Merkle root from its inclusion proof, fetch the service's public key from its JWKS, and check the signature. +6. If `store_receipt` is true, add the analysis and save the vCon. + +To record two points in a chain, add this link twice with different `vcon_operation` values. The second hash covers the first receipt, since the receipt is part of the vCon. + +## Read the return value + +Returns the uuid. A missing vCon raises `HTTPException` with status 404. A failure to sign, register or verify raises. In each case the vCon goes to the dead letter queue. + +## Inspect the vCon changes + +One analysis entry when `store_receipt` is true. Otherwise none. + +| Field | Value | +|---|---| +| `type` | `scitt_receipt` | +| `dialog` | `0` | +| `vendor` | `scittles` | +| `body` | One receipt object, or a list when there are several | +| `encoding` | `json` | + +Each receipt has `entry_id`, `cose_receipt` in Base64, `vcon_operation`, `subject`, `vcon_hash` and `scrapi_url`. The `subject` can hold a party's phone number. + +## Copy a configuration example + +```yaml +links: + scitt_created: + module: links.scitt + options: + scrapi_url: http://scittles:8000 + signing_key_path: /etc/scitt/signing-key.pem + issuer: conserver + key_id: conserver-key-1 + vcon_operation: vcon_created +``` + +## Track the metrics + +`conserver.link.scitt.statement_creation_failures` and `conserver.link.scitt.registration_failures`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/slack.md b/docs/reference/links/slack.md new file mode 100644 index 00000000..adf121ce --- /dev/null +++ b/docs/reference/links/slack.md @@ -0,0 +1,58 @@ +# post_analysis_to_slack + +Posts a summary to Slack when a chosen analysis entry contains a given string. + +Module: `links.post_analysis_to_slack` + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `token` | string | `None` | Slack bot token. Required | +| `default_channel_name` | string | none | Channel for every post. Required, and absent from `default_options`, so leaving it out raises `KeyError` at the first post | +| `url` | string | `Url to link to the details page` | Target of the Details button. Replaces `{vcon_id}` with the uuid, or adds `?_vcon_id=""` when there is no placeholder | +| `only_if.analysis_type` | string | `customer_frustration` | Analysis `type` to check | +| `only_if.includes` | string | `NEEDS REVIEW` | Substring to look for in that entry's body | +| `channel_name` | string | `None` | In `default_options`, but no code reads it | +| `analysis_to_post` | string | `summary` | In `default_options`, but no code reads it. The posted text always comes from the `summary` entry | + +This `only_if` differs from the [shared filter](index.md#set-the-shared-filter-options): it has no `section` and works per analysis entry. + +## Follow the processing steps + +For each analysis entry: + +1. Skip it unless its `type` is `only_if.analysis_type`, its body contains `only_if.includes`, and it has no `was_posted_to_slack` flag. +2. Find the `summary` entry for the same dialog. If there is none the link raises `TypeError`. +3. If a deployment-specific team attachment names a team, also post to `team--alerts`, with the first word of the team name in lowercase. See `get_team` and `get_dealer` in the source. The attachment purpose and an excluded team name are hard-coded there, so this step does not apply to other deployments. +4. Post to `default_channel_name`. +5. Set `was_posted_to_slack` on the entry. + +The vCon is saved after the loop. If a post fails, the link sends a short notice to `default_channel_name`, then raises. + +## Read the return value + +Returns the uuid. A failed post raises, and the vCon goes to the dead letter queue. A missing vCon raises `AttributeError`. + +## Inspect the vCon changes + +Sets `was_posted_to_slack: true` on each posted analysis entry. This flag stops a second post when the vCon runs again. + +## Copy a configuration example + +```yaml +links: + slack_alerts: + module: links.post_analysis_to_slack + options: + token: your-slack-bot-token + default_channel_name: call-alerts + url: https://portal.example.com/vcons/{vcon_id} + only_if: + analysis_type: customer_frustration + includes: NEEDS REVIEW +``` + +## Track the metrics + +`conserver.link.slack.post_failures` and `conserver.link.slack.fallback_channel_used`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/tag-router.md b/docs/reference/links/tag-router.md new file mode 100644 index 00000000..f0aece26 --- /dev/null +++ b/docs/reference/links/tag-router.md @@ -0,0 +1,54 @@ +# tag_router + +Pushes the vCon's uuid to other Redis lists according to its tags. + +Module: `links.tag_router` + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `tag_routes` | dict | `{}` | Tag name to target Redis list | +| `forward_original` | bool | `true` | Continues the current chain after routing | + +## Follow the processing steps + +1. Load the vCon. If `tag_routes` is empty, log a warning and pass the vCon on. +2. Collect tag names from every attachment with `purpose` or legacy `type` of `tags`. In a list body, the name is the part before the first colon. A string with no colon is ignored. In a dict body, the keys are the names. +3. For each tag name with a route, push the uuid to the target list. + +Routing matches on the tag name only. A vCon with `department:sales` and `department:support` pushes twice to the `department` route. + +The target list receives the uuid only, through `VconQueue` in `lib.queue`. To process the vCon there, make the list an `ingress_lists` entry of a chain. + +## Read the return value + +| Case | Returns | +|---|---| +| vCon missing | `None` | +| `tag_routes` empty | The uuid, whatever `forward_original` says | +| Otherwise, `forward_original` true | The uuid | +| Otherwise, `forward_original` false | `None`, even if no route matched | + +With `forward_original: false`, the chain stops here, so this chain's storages and egress lists do not run. + +## Inspect the vCon changes + +None. + +## Copy a configuration example + +```yaml +links: + route_by_tag: + module: links.tag_router + options: + tag_routes: + urgent: urgent_vcons + department: department_vcons + forward_original: false +``` + +## Track the metrics + +`conserver.link.tag_router.routes_matched` and `conserver.link.tag_router.routed_count`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/tag.md b/docs/reference/links/tag.md index 471f2e7b..b1902ca5 100644 --- a/docs/reference/links/tag.md +++ b/docs/reference/links/tag.md @@ -1,59 +1,49 @@ # tag -Adds static tags to vCons. +Adds fixed tags to a vCon. -## Configuration +Module: `links.tag` -```yaml -links: - tag: - module: links.tag - options: - tags: - - processed - - v1 -``` - -## Options +## Set the options | Option | Type | Default | Description | -|--------|------|---------|-------------| -| `tags` | list | `[]` | List of tags to add | +|---|---|---|---| +| `tags` | list or dict | `["iron", "maiden"]` | Tags to add. See below for the forms | -## Example +The link does not merge `default_options`. If `options` omits `tags`, the link adds nothing. It never uses the default list. -```yaml -chains: - tagging: - links: - - tag: - tags: - - processed - - team_a - - priority_normal - storages: - - redis_storage - ingress_lists: - - default - enabled: 1 -``` +`tags` takes three forms. -## Alternative Format +| Form | Example | Result | +|---|---|---| +| List of `name:value` strings | `- department:sales` | `department:sales` | +| List of bare names | `- processed` | `processed:processed` | +| Dict of name to value | `department: sales` | `department:sales` | -Tags can be key-value pairs: +## Follow the processing steps + +1. Load the vCon. +2. Turn `tags` into name and value pairs and add each one. +3. Save the vCon. + +## Read the return value + +Returns the uuid, or `None` when the vCon is missing. + +## Inspect the vCon changes + +Tags go in the `tags` attachment. `Vcon.add_tag` creates the attachment if needed and appends `name:value` to its list. Tags are not deduplicated. + +The attachment has `purpose: "tags"` and `encoding: "json"`. `add_tag` writes the list as a JSON string in `body`, and readers in this repo decode it. It does not set `start`, `party`, `dialog` or `mediatype`. + +## Copy a configuration example ```yaml links: - tag: + label_sales: module: links.tag options: tags: - - name: status - value: processed - - name: version - value: "1.0" + - department:sales + - processed ``` - -## Output - -Adds tags to vCon metadata. diff --git a/docs/reference/links/transcribe.md b/docs/reference/links/transcribe.md new file mode 100644 index 00000000..ace53ffe --- /dev/null +++ b/docs/reference/links/transcribe.md @@ -0,0 +1,67 @@ +# transcribe + +The single entry point for speech to text. It hands the vCon to the vendor named in its options. + +Module: `links.transcribe` + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `vendor` | string | `whisper_builtin` | `openai`, `groq`, `hugging_face`, `deepgram` or `whisper_builtin` | +| `vendor_options` | dict | `{"model_size": "base", "output_options": ["vendor"]}` | Passed unchanged to the vendor. The default suits `whisper_builtin` only | +| `transcribe_options` | dict | none | Legacy name for `vendor_options`, used when `vendor_options` is absent | + +Each vendor reads its own options inside `vendor_options`. + +| `vendor` | Implementation | Options | +|---|---|---| +| `openai` | `links.openai_transcribe` | [openai_transcribe](openai-transcribe.md#set-the-options) | +| `groq` | `links.groq_whisper` | [groq_whisper](groq-whisper.md#set-the-options) | +| `hugging_face` | `links.hugging_face_whisper` | [hugging_face_whisper](huggingface-whisper.md#set-the-options) | +| `deepgram` | `links.deepgram_link` | [deepgram_link](deepgram.md#set-the-options) | +| `whisper_builtin` | `Vcon.transcribe()` | See the known issue below | + +Always set `vendor_options` when you name a vendor. Without it the vendor receives the `whisper_builtin` defaults and no credentials. + +WTF transcripts have their own link, [wtf_transcribe](wtf-transcribe.md), because they use a different analysis schema. + +## Follow the processing steps + +1. Merge the options and resolve the vendor. An empty `vendor` means `whisper_builtin`. +2. Pick `vendor_options`, then `transcribe_options`, then the default. +3. Import the vendor module and call its `run` with those options. An unknown vendor raises `ValueError`. + +Vendors act only on dialogs with `type` of `recording`. A vCon with none passes through unchanged and counts as a success. See [transcribe a recording](../../configuration/chains-and-pipelines.md#transcribe-a-recording). + +The worker also sends the deprecated modules here. A chain entry of `module: links.groq_whisper` becomes `links.transcribe` with `vendor: groq` and logs one deprecation warning per module. Its existing options block becomes `vendor_options`. + +## Check the known issues + +`whisper_builtin` is the default vendor and does not work in the server image. It calls `vCon.transcribe()`, and the `Vcon` class in `common/vcon.py`, which is the class the worker imports, has no such method. The link raises `AttributeError` and the vCon goes to the dead letter queue. Always set `vendor` to one of the other four. + +## Read the return value + +The vendor's return value. With `whisper_builtin`, `None` when the vCon is missing. + +## Inspect the vCon changes + +See the vendor's page. Each one adds analysis of type `transcript`. The body differs by vendor, which matters for [the links that read it](index.md#point-analysis-at-the-transcript-text). + +## Copy a configuration example + +```yaml +links: + transcribe_openai: + module: links.transcribe + options: + vendor: openai + vendor_options: + OPENAI_API_KEY: your-openai-key + model: gpt-4o-transcribe + minimum_duration: 3 +``` + +## Track the metrics + +The dispatcher emits none of its own. See the vendor's page. diff --git a/docs/reference/links/webhook.md b/docs/reference/links/webhook.md index 93a74f50..339e5ef7 100644 --- a/docs/reference/links/webhook.md +++ b/docs/reference/links/webhook.md @@ -1,63 +1,46 @@ # webhook -Sends vCon data to external HTTP endpoints. +Posts the vCon as JSON to one or more URLs. -## Configuration +Module: `links.webhook` -```yaml -links: - webhook: - module: links.webhook - options: - url: https://api.example.com/webhook - method: POST - headers: - Authorization: Bearer token -``` - -## Options +## Set the options | Option | Type | Default | Description | -|--------|------|---------|-------------| -| `url` | string | Required | Webhook URL | -| `method` | string | `POST` | HTTP method | +|---|---|---|---| +| `webhook-urls` | list | `[]` | URLs to post to | | `headers` | dict | `{}` | Request headers | -| `timeout` | int | `30` | Request timeout | -| `include_vcon` | bool | `true` | Include full vCon | -| `retry_count` | int | `3` | Retry attempts | -## Example +## Follow the processing steps + +1. Load the vCon. A missing vCon raises `AttributeError`. +2. Convert the payload to a legacy format if `EGRESS_FORMAT_VERSION` is set. See [Egress format compatibility](../../configuration/egress-compatibility.md). The stored vCon does not change. +3. If `webhook-urls` is empty, log a warning, count it and pass the vCon on. +4. POST the payload to each URL in order. + +The body is the vCon object itself, with no wrapper. The link logs the response but does not check its status, so a 4xx or 5xx counts as delivered. No request timeout is set, and there are no retries. + +## Read the return value + +Returns the uuid. A connection error raises, the remaining URLs are not tried, and the vCon goes to the dead letter queue. Reprocessing posts again to the URLs that already succeeded. + +## Inspect the vCon changes + +None. + +## Copy a configuration example ```yaml -chains: +links: notify: - links: - - analyze - - webhook: - url: https://api.example.com/vcon-processed - method: POST - headers: - Authorization: Bearer ${WEBHOOK_TOKEN} - Content-Type: application/json - storages: - - postgres - ingress_lists: - - default - enabled: 1 + module: links.webhook + options: + webhook-urls: + - https://api.example.com/vcon-processed + headers: + Authorization: Bearer your-token ``` -## Payload +## Track the metrics -Default payload includes full vCon: - -```json -{ - "vcon": { - "uuid": "...", - "created_at": "...", - "parties": [...], - "dialog": [...], - "analysis": [...] - } -} -``` +`conserver.link.webhook.no_urls_configured` and `conserver.link.webhook.post_failures`. See [Metrics](../metrics.md). diff --git a/docs/reference/links/wtf-transcribe.md b/docs/reference/links/wtf-transcribe.md new file mode 100644 index 00000000..fa958fb1 --- /dev/null +++ b/docs/reference/links/wtf-transcribe.md @@ -0,0 +1,63 @@ +# wtf_transcribe + +Sends each recording to a vfun server and stores the World Transcription Format (WTF) result. + +Module: `links.wtf_transcribe` + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `vfun-server-url` | string | `None` | URL of the vfun server. Required | +| `language` | string | `None` | Language override, sent to vfun and written to `body.transcript.language`. When unset, vfun detects the language | +| `diarize` | bool | `false` | Asks for speaker diarization. The module marks this as work in progress | +| `vfun-timeout` | number | `300` | Timeout in seconds for the vfun request | +| `url-timeout` | number | `60` | Timeout in seconds for fetching a dialog's `url` | +| `api-key` | string | `None` | Sent as a bearer token when set | + +## Follow the processing steps + +1. Stop if `vfun-server-url` is empty or the vCon is missing. +2. For each dialog of type `recording` that has no `wtf_transcription` analysis, get the audio. A `url` comes first: `file://` reads a local path, anything else is fetched. Otherwise the link decodes the inline `body`. +3. Post the audio to vfun as the multipart field `file-binary`. +4. Add the analysis, then save the vCon after the last dialog. + +There is no minimum duration. A failure on one dialog, including a timeout, is logged and the link moves to the next dialog. There are no retries. + +The media type sent to vfun comes from the dialog's `mediatype`, then its filename extension, then defaults to `audio/wav`. + +## Read the return value + +Returns the uuid, also when some dialogs failed. Returns `None`, which stops the chain, when `vfun-server-url` is missing or the vCon is not found. + +## Inspect the vCon changes + +One analysis entry per transcribed dialog. + +| Field | Value | +|---|---| +| `type` | `wtf_transcription` | +| `dialog` | Dialog index | +| `vendor` | `vfun` | +| `schema` | `wtf-1.0` | +| `mediatype` | `application/json` | +| `body` | The vfun reply as a JSON value | +| `encoding` | `json` | + +## Copy a configuration example + +```yaml +links: + wtf: + module: links.wtf_transcribe + options: + vfun-server-url: http://localhost:4380/wtf + language: en + vfun-timeout: 300 + url-timeout: 60 + api-key: your-vfun-key +``` + +## Track the metrics + +The link emits no metrics of its own. diff --git a/docs/reference/metrics.md b/docs/reference/metrics.md new file mode 100644 index 00000000..fb57256a --- /dev/null +++ b/docs/reference/metrics.md @@ -0,0 +1,71 @@ + + +# Metrics + +!!! note "Generated page" + `scripts/docs/gen_metrics.py` builds this page from the code. Text that needs a person lives in `scripts/docs/descriptions.yml`. Edit that file, not this page. + +All metrics go through the helpers in `common/lib/metrics.py`. They publish only when `OTEL_EXPORTER_OTLP_ENDPOINT` is set, and always through the OTLP gRPC exporter. `OTEL_METRIC_EXPORT_INTERVAL` sets the export interval. Metrics from OpenTelemetry auto-instrumentation are not listed. + +The code emits 58 metric names. + +| Metric | Type | Emitted in | Description | +|---|---|---|---| +| `conserver.api.count_vcons_enqueued` | counter | `api/api.py` | vCons the API added to an ingress list. Attributes are `ingress_list` and `source`, which is `new`, `external`, `reingress` or `dlq_reprocess`. | +| `conserver.dlq.count` | counter | `common/lib/queue.py` | vCons moved to a dead letter queue, ingress or storage. Attribute is `queue_name`. | +| `conserver.ingress_list.length` | observable gauge | `common/lib/queue_metrics.py` | Current `LLEN` of each configured ingress list and its dead letter queue. Attributes are `ingress_list` and `kind`, which is `ingress` or `dlq`. | +| `conserver.lib.vcon_redis.get_vcon_not_found` | counter | `common/lib/vcon_redis.py` | A `VconRedis.get_vcon` call found the vCon in neither Redis nor storage. | +| `conserver.lib.vcon_redis.get_vcon_redis_miss` | counter | `common/lib/vcon_redis.py` | A `VconRedis.get_vcon` call missed Redis. | +| `conserver.lib.vcon_redis.get_vcon_storage_hit` | counter | `common/lib/vcon_redis.py` | A `VconRedis.get_vcon` call missed Redis and found the vCon in storage. | +| `conserver.link.count` | counter | `conserver/main.py` | Link runs. Attributes are `link_name` and `outcome`, which is `success`, `halt` or `error`. | +| `conserver.link.datatrails.event_creation_failures` | counter | `conserver/links/datatrails/__init__.py` | Failed DataTrails event creation. | +| `conserver.link.deepgram.confidence` | histogram | `conserver/links/deepgram_link/__init__.py` | Deepgram transcript confidence. Not recorded when the link goes through a LiteLLM proxy. | +| `conserver.link.deepgram.transcription_failures` | counter | `conserver/links/deepgram_link/__init__.py` | Failed Deepgram transcriptions, including results below `minimum_confidence`. | +| `conserver.link.deepgram.transcription_time` | histogram | `conserver/links/deepgram_link/__init__.py` | Deepgram transcription time in seconds. | +| `conserver.link.diet.media_post_failures` | counter | `conserver/links/diet/__init__.py` | Failed media posts from the `diet` link. | +| `conserver.link.execution_time` | histogram | `conserver/main.py` | Link execution time in seconds. Attributes are `link.name` and `chain.name`. | +| `conserver.link.groq_whisper.transcription_failures` | counter | `conserver/links/groq_whisper/__init__.py` | Failed Groq Whisper transcriptions. | +| `conserver.link.groq_whisper.transcription_time` | histogram | `conserver/links/groq_whisper/__init__.py` | Groq Whisper transcription time in seconds. | +| `conserver.link.hugging_face_whisper.transcription_failures` | counter | `conserver/links/hugging_face_whisper/__init__.py` | Failed Hugging Face Whisper transcriptions. | +| `conserver.link.hugging_face_whisper.transcription_time` | histogram | `conserver/links/hugging_face_whisper/__init__.py` | Hugging Face Whisper transcription time in seconds. | +| `conserver.link.huggingface.llm_failures` | counter | `conserver/links/hugging_llm_link/__init__.py` | Failed Hugging Face LLM calls. | +| `conserver.link.huggingface.llm_time` | histogram | `conserver/links/hugging_llm_link/__init__.py` | Hugging Face LLM call time in seconds. | +| `conserver.link.jq.filter_errors` | counter | `conserver/links/jq_link/__init__.py` | Errors applying the `jq_link` filter. | +| `conserver.link.jq.string_body_array_retries` | counter | `conserver/links/jq_link/__init__.py` | Filter retries with string-only body arrays after a type error. | +| `conserver.link.jq.vcon_filtered_out` | counter | `conserver/links/jq_link/__init__.py` | vCons the `jq_link` filter stopped. | +| `conserver.link.openai.analysis_failures` | counter | `conserver/links/analyze/__init__.py`
`conserver/links/analyze_and_label/__init__.py`
`conserver/links/analyze_vcon/__init__.py` | Failed analysis calls in the `analyze`, `analyze_and_label` and `analyze_vcon` links. | +| `conserver.link.openai.analysis_time` | histogram | `conserver/links/analyze/__init__.py`
`conserver/links/analyze_and_label/__init__.py`
`conserver/links/analyze_vcon/__init__.py` | Analysis call time in seconds in the `analyze`, `analyze_and_label` and `analyze_vcon` links. | +| `conserver.link.openai.engagement_analysis_failures` | counter | `conserver/links/detect_engagement/__init__.py` | Failed `detect_engagement` analysis calls. | +| `conserver.link.openai.engagement_analysis_time` | histogram | `conserver/links/detect_engagement/__init__.py` | `detect_engagement` analysis time in seconds. | +| `conserver.link.openai.engagement_detected` | counter | `conserver/links/detect_engagement/__init__.py` | Conversations `detect_engagement` found engaged. Other results add 0. | +| `conserver.link.openai.evaluation_failures` | counter | `conserver/links/check_and_tag/__init__.py` | Failed `check_and_tag` evaluations. | +| `conserver.link.openai.evaluation_time` | histogram | `conserver/links/check_and_tag/__init__.py` | `check_and_tag` evaluation time in seconds. | +| `conserver.link.openai.invalid_json` | counter | `conserver/links/analyze_vcon/__init__.py` | Invalid JSON responses in `analyze_vcon`. | +| `conserver.link.openai.json_parse_failures` | counter | `conserver/links/analyze_and_label/__init__.py` | Responses `analyze_and_label` could not parse as JSON. | +| `conserver.link.openai.labels_added` | counter | `conserver/links/analyze_and_label/__init__.py` | Labels `analyze_and_label` added as tags. | +| `conserver.link.openai.tags_applied` | counter | `conserver/links/check_and_tag/__init__.py` | Tags `check_and_tag` applied. | +| `conserver.link.openai.transcription_failures` | counter | `conserver/links/openai_transcribe/__init__.py` | Failed `openai_transcribe` transcriptions. | +| `conserver.link.openai.transcription_time` | histogram | `conserver/links/openai_transcribe/__init__.py` | `openai_transcribe` transcription time in seconds. | +| `conserver.link.sampler.sampled_in` | counter | `conserver/links/sampler/__init__.py` | vCons the `sampler` link kept. | +| `conserver.link.sampler.sampled_out` | counter | `conserver/links/sampler/__init__.py` | vCons the `sampler` link dropped. | +| `conserver.link.scitt.registration_failures` | counter | `conserver/links/scitt/__init__.py` | Failed SCITT statement registrations. | +| `conserver.link.scitt.statement_creation_failures` | counter | `conserver/links/scitt/__init__.py` | Failed SCITT signed statement creation. | +| `conserver.link.slack.fallback_channel_used` | counter | `conserver/links/post_analysis_to_slack/__init__.py` | Posts that failed on the target channel. The link then sends a notice to `default_channel_name` and raises. | +| `conserver.link.slack.post_failures` | counter | `conserver/links/post_analysis_to_slack/__init__.py` | Failed Slack posts. | +| `conserver.link.tag_router.routed_count` | counter | `conserver/links/tag_router/__init__.py` | vCons routed to at least one list. | +| `conserver.link.tag_router.routes_matched` | counter | `conserver/links/tag_router/__init__.py` | Tag matches, one per target list. The `route` attribute names the list. | +| `conserver.link.webhook.no_urls_configured` | counter | `conserver/links/webhook/__init__.py` | Webhook link runs with no URLs configured. | +| `conserver.link.webhook.post_failures` | counter | `conserver/links/webhook/__init__.py` | Webhook link posts that raised an exception. | +| `conserver.main_loop.count_vcons_processed` | counter | `conserver/main.py` | vCons that left a chain without an exception, including those a link halted. Attribute is `chain.name`. | +| `conserver.main_loop.count_vcons_received` | counter | `conserver/main.py` | vCons popped from an ingress list. Attribute is `ingress_list`. | +| `conserver.main_loop.vcon_processing_time` | histogram | `conserver/main.py` | Chain processing time in seconds, per vCon that left a chain without an exception, including those a link halted. Attribute is `chain.name`. | +| `conserver.redis.memory_used_bytes` | observable gauge | `common/lib/queue_metrics.py` | Redis `used_memory` from `INFO memory`, in bytes. | +| `conserver.storage.count` | counter | `conserver/main.py` | Storage writes. Attributes are `backend` and `outcome`, which is `success` or `error`. | +| `conserver.storage.duration_ms` | histogram | `conserver/main.py` | Storage write time in milliseconds. Attributes are `backend` and `outcome`. | +| `conserver.storage.milvus.embedding_failures` | counter | `common/storage/milvus/__init__.py` | Failed embedding calls in the `milvus` adapter. | +| `conserver.storage.milvus.embedding_time` | histogram | `common/storage/milvus/__init__.py` | Embedding call time in seconds in the `milvus` adapter. | +| `conserver.storage.milvus.storage_failures` | counter | `common/storage/milvus/__init__.py` | Failed `milvus` writes. | +| `conserver.storage.milvus.text_extraction_time` | histogram | `common/storage/milvus/__init__.py` | Text extraction time in seconds in the `milvus` adapter. | +| `conserver.storage.milvus.vcons_stored` | counter | `common/storage/milvus/__init__.py` | vCons written to Milvus. | +| `conserver.vcons.inflight` | up-down counter | `conserver/main.py` | vCons in progress. Attribute is `chain.name`. | +| `conserver.webhook.duration` | histogram | `common/storage/webhook/__init__.py` | Webhook storage adapter post time in seconds. Attribute is `status_code`. | diff --git a/docs/reference/ports.md b/docs/reference/ports.md new file mode 100644 index 00000000..fb02726d --- /dev/null +++ b/docs/reference/ports.md @@ -0,0 +1,37 @@ + + +# Ports and services + +!!! note "Generated page" + `scripts/docs/gen_ports.py` builds this page from the code. Text that needs a person lives in `scripts/docs/descriptions.yml`. Edit that file, not this page. + +`docker-compose.yml` joins every service to the `conserver` network, which is declared external, so create it before the first `docker compose up`. Set `COMPOSE_PROFILES` in `.env` to start optional services. A service with no published port is reachable only on that network. + +## Published ports + +| Service | Host port | Container port | Protocol | Host port set by | +|---|---|---|---|---| +| `api` | `8000` | `8000` | tcp | `CONSERVER_EXTERNAL_PORT` | +| `elasticsearch` | `9200` | `9200` | tcp | fixed | +| `elasticsearch` | `9300` | `9300` | tcp | fixed | +| `langfuse-server` | `3000` | `3000` | tcp | fixed | +| `postgres` | `5432` | `5432` | tcp | fixed | + +## Compose services + +| Service | Image | Profile | Depends on | Description | +|---|---|---|---|---| +| `api` | built from `docker/Dockerfile` | always | `redis` | FastAPI app, run by uvicorn on port 8000. | +| `conserver` | built from `docker/Dockerfile` | always | `redis` | Runs `conserver/main.py`, restarted by `watchmedo` when a Python file changes. Publishes no port. | +| `elasticsearch` | `docker.elastic.co/elasticsearch/elasticsearch:8.13.4` | `elasticsearch` | none | Single-node Elasticsearch with security on. The credentials in the Compose file are for development only. | +| `langfuse-clickhouse` | `clickhouse/clickhouse-server:24.12` | `langfuse` | none | ClickHouse store for Langfuse. Uses 8123 and 9000 on the network. | +| `langfuse-minio` | `minio/minio` | `langfuse` | none | MinIO object store for Langfuse. Uses 9000 on the network, with its console on 9001. | +| `langfuse-postgres` | `postgres:alpine` | `langfuse` | none | PostgreSQL database for Langfuse. Uses 5432 on the network. | +| `langfuse-server` | `langfuse/langfuse:latest` | `langfuse` | `langfuse-clickhouse`, `langfuse-minio`, `langfuse-postgres` | Langfuse web app for local tracing. The credentials in the Compose file are for development only. | +| `langfuse-worker` | `langfuse/langfuse-worker:latest` | `langfuse` | `langfuse-clickhouse`, `langfuse-minio`, `langfuse-postgres` | Langfuse background worker. | +| `postgres` | `postgres:alpine` | `postgres` | none | Local PostgreSQL. The credentials in the Compose file are for development only. | +| `redis` | `redis:7.4-alpine` | always | none | Plain Redis with append-only persistence and a 1 GB memory limit. Uses 6379 on the network. | + +## Container and port map + +![Docker host ports, the conserver network and the Compose services by profile](../diagrams/D02-container-port-map.svg) diff --git a/docs/reference/storage-adapters/chatgpt_files.md b/docs/reference/storage-adapters/chatgpt_files.md new file mode 100644 index 00000000..9d6e1e6d --- /dev/null +++ b/docs/reference/storage-adapters/chatgpt_files.md @@ -0,0 +1,56 @@ +# ChatGPT files storage adapter + +Uploads a vCon as a JSON file to OpenAI and attaches it to a vector store. + +!!! warning "This adapter does not work as written" + With the locked dependencies, `save` cannot finish. See [Check the known problems](#check-the-known-problems). + +Module: `storage.chatgpt_files`. Needs the `openai` package, from the `conserver` dependency group. + +## Configure the adapter + +```yaml +storages: + chatgpt: + module: storage.chatgpt_files + options: + api_key: sk-example + organization_key: org-example + project_key: proj_example + vector_store_id: vs_example + purpose: assistants +``` + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `organization_key` | string | `org-xxxxx` | OpenAI organization. Optional for the client | +| `project_key` | string | `proj_xxxxxxx` | OpenAI project. Optional for the client | +| `api_key` | string | `sk-proj-xxxxxx` | OpenAI API key | +| `vector_store_id` | string | `xxxxxx` | Vector store that receives the file. Required in practice | +| `purpose` | string | `assistants` | Purpose sent with the file upload. Required in practice | + +The defaults are placeholders. The adapter builds its client with `get_openai_client` in `common/lib/openai_client.py`, so that function's other keys work here too: `LITELLM_PROXY_URL` with `LITELLM_MASTER_KEY`, `AZURE_OPENAI_ENDPOINT` with `AZURE_OPENAI_API_KEY` and `AZURE_OPENAI_API_VERSION`, `OPENAI_API_KEY` or `openai_api_key` in place of `api_key`, and `organization` or `project`. + +## Save a vCon + +1. Read the key `` from Redis with `redis_mgr.get_key`. +2. Write the value to `.vcon.json` in the process working directory. +3. Upload the file with `client.files.create`. +4. Delete the local file. +5. Add the uploaded file to the vector store. + +## Read or delete a vCon + +The adapter has no `get` and no `delete`. A file stays in OpenAI after `DELETE /vcon/{uuid}`. + +## Handle a failed write + +Any exception is re-raised, so the server moves the vCon to the [storage DLQ](index.md#handle-a-failed-write). The client runs with `max_retries=0`. A replay after step 3 uploads a second file. A failed upload leaves the local file in the working directory, because the delete in step 4 does not run. + +## Check the known problems + +- The adapter reads the Redis key ``, and the server stores vCons under `vcon:`. The read finds nothing, so the file holds `null`. +- Step 5 calls `client.beta.vector_stores`. `uv.lock` pins `openai` 2.24.0, where that attribute does not exist and the vector store API sits at `client.vector_stores`. The call raises `AttributeError` after the file has been uploaded. +- The only test, in `common/storage/chatgpt_files/test_init.py`, is marked skip. diff --git a/docs/reference/storage-adapters/dataverse.md b/docs/reference/storage-adapters/dataverse.md new file mode 100644 index 00000000..a58da004 --- /dev/null +++ b/docs/reference/storage-adapters/dataverse.md @@ -0,0 +1,70 @@ +# Dataverse storage adapter + +Stores a vCon as a row in a Microsoft Dataverse table through the Web API, with Azure AD client credentials from MSAL. + +Module: `storage.dataverse`. Needs `msal`, from the `storage` dependency group. + +## Configure the adapter + +```yaml +storages: + dataverse: + module: storage.dataverse + options: + url: https://example.crm.dynamics.com + api_version: "9.2" + tenant_id: 00000000-0000-0000-0000-000000000000 + client_id: 00000000-0000-0000-0000-000000000000 + client_secret: example-secret + entity_name: vcon_storage + uuid_field: vcon_uuid + data_field: vcon_data + subject_field: vcon_subject + created_at_field: vcon_created_at +``` + +## Set the options + +The adapter reads every key directly, so all of them except `name` are required in an `options` block. + +| Option | Type | Default | Description | +|---|---|---|---| +| `name` | string | `dataverse` | Not read by the adapter | +| `url` | string | `https://org.crm.dynamics.com` | Environment URL. Also forms the token scope `/.default` | +| `api_version` | string | `9.2` | Web API version in the request path | +| `tenant_id` | string | `""` | Azure AD tenant | +| `client_id` | string | `""` | Azure AD application id | +| `client_secret` | string | `""` | Azure AD client secret | +| `entity_name` | string | `vcon_storage` | Entity set name in the request path | +| `uuid_field` | string | `vcon_uuid` | Column for the vCon UUID | +| `data_field` | string | `vcon_data` | Column for the vCon JSON string | +| `subject_field` | string | `vcon_subject` | Column for the subject | +| `created_at_field` | string | `vcon_created_at` | Column for the creation time | + +## Save a vCon + +1. Read the vCon through `VconRedis`. +2. Acquire a new token and open a session. Each `save` and `get` does this. +3. Query for an existing row by UUID. An error in this query is logged at debug level and treated as no match. +4. Send a `PATCH` to `()` when a row was found, otherwise a `POST` to ``. + +`created_at` falls back to the current time when the vCon has none. The adapter does not apply `EGRESS_FORMAT_VERSION`. + +## Read a vCon + +`get` runs the same query and parses `data_field` from the first row. It returns `None` when no row matches, the field is empty or holds bad JSON, or any error occurs. + +## Delete a vCon + +The adapter has no `delete`. A row stays in Dataverse after `DELETE /vcon/{uuid}`. + +## Handle a failed write + +A token failure or HTTP error raises, so the server moves the vCon to the [storage DLQ](index.md#handle-a-failed-write). The adapter has no retry of its own. + +A repeated `save` updates the row only if the lookup in step 3 works. Otherwise it creates another row. + +## Check the known problems + +- TODO(verify): the filter is built as `$vcon_uuid eq ''`, with a leading `$` on the column name. If Dataverse rejects that, `get` always returns `None` and every `save` creates a row. No test covers the query. +- TODO(verify): the lookup takes the row key from a field called `id`. If the table's key column has another name, the update branch never runs. diff --git a/docs/reference/storage-adapters/elasticsearch.md b/docs/reference/storage-adapters/elasticsearch.md new file mode 100644 index 00000000..d0fd8ccd --- /dev/null +++ b/docs/reference/storage-adapters/elasticsearch.md @@ -0,0 +1,77 @@ +# Elasticsearch storage adapter + +Indexes the parts of a vCon as separate documents. Parties, attachments, analysis and dialog each go to their own indices. The adapter does not store the vCon as one document and cannot read it back. + +Module: `storage.elasticsearch`. Needs `elasticsearch`, from the `storage` dependency group. The group pins it below version 9. + +## Configure the adapter + +Self-managed cluster: + +```yaml +storages: + elasticsearch: + module: storage.elasticsearch + options: + url: https://elasticsearch:9200 + username: elastic + password: example-password + ca_certs: /etc/ssl/es/ca.crt + index_prefix: prod_ +``` + +Elastic Cloud: + +```yaml +storages: + elasticsearch: + module: storage.elasticsearch + options: + cloud_id: example:ZXhhbXBsZQ== + api_key: example-key +``` + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `name` | string | `elasticsearch` | Not read by the adapter | +| `cloud_id` | string | `""` | Elastic Cloud id. If `cloud_id` or `api_key` is set, the adapter takes the cloud path, which reads both | +| `api_key` | string | `""` | Elastic Cloud API key | +| `index` | string | `vcon_index` | Not read by the adapter. Index names come from `index_prefix` | +| `ca_certs` | string | none | Path to a CA bundle. If it is unset or the path does not exist, the client runs with `verify_certs=False` | +| `url` | string | none | Cluster URL. Required on the non-cloud path | +| `username` | string | none | Basic auth user. Required on the non-cloud path | +| `password` | string | none | Basic auth password. Required on the non-cloud path | +| `index_prefix` | string | `""` | Prepended to every index name, after trimming whitespace | + +## Save a vCon + +`save` reads the vCon through `VconRedis`, applies `EGRESS_FORMAT_VERSION`, then writes these documents: + +| Part | Index | Document id | +|---|---|---| +| Party | `vcon_parties_`, or `vcon_parties` when the party has no role | `_` | +| Attachment | `vcon_attachments_`, or `..._unknown` | `_` | +| Analysis | `vcon_analysis_` | `_` | +| Dialog | `vcon_dialog` | `_` | + +Each index name starts with `index_prefix`. Every document also gets `vcon_id` and `started_at`, the `start` of the first dialog. When the vCon has an attachment with purpose `tenant`, every document gets `tenant_id` from the `id` in its body. A JSON string body on an attachment or analysis entry is parsed before indexing. + +A vCon with an empty dialog list is skipped without an error. + +## Read a vCon + +The adapter has no `get`. + +## Delete a vCon + +`delete` lists indices matching `vcon*` and runs one `delete_by_query` on `vcon_id` with `refresh=True`. It returns `True` when at least one document went, `False` otherwise, and raises on a query error. + +## Handle a failed write + +Failures to connect, to read the vCon or to prepare a part raise, so the server moves the vCon to the [storage DLQ](index.md#handle-a-failed-write). An analysis entry with no `encoding` key raises `KeyError` here. + +A failure on one document is different. `do_vcon_parts_indexing` logs it and carries on, so the vCon counts as stored with that document missing, and nothing reaches the DLQ. Watch the logs for `failed to insert`. + +A repeated `save` overwrites documents with the same ids. If a vCon lost a part between saves, the old document stays. diff --git a/docs/reference/storage-adapters/file.md b/docs/reference/storage-adapters/file.md new file mode 100644 index 00000000..b4c039ee --- /dev/null +++ b/docs/reference/storage-adapters/file.md @@ -0,0 +1,65 @@ +# File storage adapter + +Writes each vCon to the local file system as JSON, with optional gzip compression and date folders. + +Module: `storage.file`. Needs no extra packages. + +## Configure the adapter + +```yaml +storages: + file: + module: storage.file + options: + path: /data/vcons + organize_by_date: true + compression: false + max_file_size: 10485760 + file_permissions: 0644 + dir_permissions: 0755 +``` + +!!! warning "Write permissions in a form YAML reads as a number" + PyYAML reads `0644` as the integer 420, and reads `0o644` as the string `"0o644"`. A string in `file_permissions` makes `os.chmod` raise `TypeError`, which the adapter does not catch, so every save goes to the storage DLQ although the file was written. `example_config.yml` has this value. Use `0644` or `420`. + +!!! warning "Share the path between containers" + The API process also runs this adapter, for reads on a Redis miss and for [storage replay](../../operations/storage-recovery.md). `docker-compose.yml` mounts no volume at `/data` on `api` or `conserver`, so each container has its own folder. A read then finds nothing, and a replayed file lands in the `api` container. Mount one volume at `path` on both services. + +## Set the options + +Each key falls back to its default, so all of them are optional. + +| Option | Type | Default | Description | +|---|---|---|---| +| `path` | string | `/data/vcons` | Base directory | +| `organize_by_date` | boolean | `true` | Write under `YYYY/MM/DD` from the vCon's `created_at` | +| `compression` | boolean | `false` | Gzip the file and use the `.json.gz` extension | +| `max_file_size` | integer | `10485760` | Largest allowed size in bytes, measured on the uncompressed JSON | +| `file_permissions` | integer | `0o644` | Mode set on the file. An `OSError` here is ignored | +| `dir_permissions` | integer | `0o755` | Mode set on directories. Any error here is ignored | + +## Save a vCon + +`save` reads the vCon through `VconRedis`, checks the size limit, and writes `.json` or `.json.gz`. With `organize_by_date` on, the path is `/YYYY/MM/DD/.`. When `created_at` is missing or will not parse, the file goes straight under ``. + +The adapter does not apply `EGRESS_FORMAT_VERSION`. + +`_ensure_directory` applies `dir_permissions` to every ancestor of the file up to the file system root, not only to directories under `path`. As a non-root user it stops at the first directory it cannot change. As root it changes them all. + +## Read a vCon + +`get` looks for the file directly under `path`, then searches recursively. It tries the extension that matches `compression` first and then the other, so files survive a change to that option. It returns `None` when the file is missing or on any error. + +## Delete a vCon + +`delete` finds the file the same way, removes it, and removes any parent directories left empty, stopping at `path`. It returns `False` when nothing was found or on any error. + +The module also has `exists` and `list_vcons`. `Storage` does not call them. + +## Handle a failed write + +Any exception in `save` raises, so the server moves the vCon to the [storage DLQ](index.md#handle-a-failed-write). The adapter has no retry. + +A vCon over `max_file_size` raises `ValueError` on each attempt. It will block a replay until you raise the limit, because draining stops at the first failure. + +A repeated `save` overwrites the same path. If `compression` changed in between, both files remain. diff --git a/docs/reference/storage-adapters/index.md b/docs/reference/storage-adapters/index.md new file mode 100644 index 00000000..c1c4bcff --- /dev/null +++ b/docs/reference/storage-adapters/index.md @@ -0,0 +1,179 @@ +# Storage adapters + +A storage adapter copies a vCon from Redis to another system when a chain finishes. Each adapter is a module in `common/storage/`, loaded by the `Storage` class in `common/storage/base.py`. A module must expose `save` and `default_options`. `get` and `delete` are optional. + +## Configure an adapter + +Define each backend under `storages:` and name it in a chain. The name under `storages:` is yours to choose. The `module` value selects the adapter. + +```yaml +storages: + archive: + module: storage.s3 + options: + aws_access_key_id: example-key + aws_secret_access_key: example-secret + aws_bucket: vcon-archive + +chains: + main: + links: + - tag + storages: + - archive + ingress_lists: + - default + enabled: 1 +``` + +`Storage` reads only `module` and `options`. It imports the module with `importlib` and does not install packages, so the `pip_name` key that links and tracers accept has no effect here. + +The config file is parsed with `yaml.safe_load`. The server does not expand `${VAR}` references, so a value written that way reaches the adapter as literal text. Write the real value, or render the file before the server reads it. + +## Compare the adapters + +| Adapter | Module | `save` | `get` | `delete` | Failed `save` | +|---|---|---|---|---|---| +| [chatgpt_files](chatgpt_files.md) | `storage.chatgpt_files` | Yes, see page | No | No | Storage DLQ | +| [dataverse](dataverse.md) | `storage.dataverse` | Yes | Yes | No | Storage DLQ | +| [elasticsearch](elasticsearch.md) | `storage.elasticsearch` | Yes | No | Yes | Storage DLQ, except per-document errors | +| [file](file.md) | `storage.file` | Yes | Yes | Yes | Storage DLQ | +| [milvus](milvus.md) | `storage.milvus` | Yes | Partial record | No | Storage DLQ | +| [mongo](mongo.md) | `storage.mongo` | Yes | Yes | No | Storage DLQ | +| [postgres](postgres.md) | `storage.postgres` | Yes | Yes | Yes | Storage DLQ | +| [redis_storage](redis_storage.md) | `storage.redis_storage` | Yes | Yes | No | Storage DLQ | +| [s3](s3.md) | `storage.s3` | Yes | Yes | Yes | Storage DLQ | +| [scitt](scitt.md) | `storage.scitt` | Yes | No | No | Storage DLQ | +| [sftp](sftp.md) | `storage.sftp` | Fails, see page | Wrong vCon possible, see page | No | Storage DLQ | +| [spaceandtime](spaceandtime.md) | `storage.spaceandtime` | Fails, see page | Yes | No | Logged only | +| [utopia](utopia.md) | `storage.utopia` | Yes | No | Yes | Storage DLQ | +| [vcon_mcp](vcon_mcp.md) | `storage.vcon_mcp` | Yes | Yes | Yes | Storage DLQ | +| [webhook](webhook.md) | `storage.webhook` | Yes | No | No | Storage DLQ | + +When a module has no `get`, `Storage.get` returns `None`. When it has no `delete`, `Storage.delete` returns `False`. + +## Install the adapter packages + +| Adapter | Python package | `pyproject.toml` group | +|---|---|---| +| `dataverse` | `msal` | `storage` | +| `elasticsearch` | `elasticsearch` | `storage` | +| `mongo` | `pymongo` | `storage` | +| `postgres` | `peewee`, `psycopg2-binary` | `storage` | +| `s3` | `boto3` | `storage` | +| `milvus` | `pymilvus`, `openai` | `storage-milvus` | +| `chatgpt_files` | `openai` | `conserver` | +| `scitt` | `ecdsa`, `pycose` from the core set, plus `fastapi` through `links.scitt` | Core and `api` | +| `file`, `redis_storage`, `vcon_mcp`, `utopia`, `webhook` | None beyond the core set | Core | +| `sftp` | `paramiko` | None. Not in `uv.lock` | +| `spaceandtime` | `spaceandtime` | None. Not in `uv.lock` | + +Each image installs different groups: + +| Image | Groups | Effect on adapters | +|---|---|---| +| `docker/Dockerfile`, used by `docker-compose.yml` | `conserver`, `api`, `dev`, `storage-milvus` | All adapters import except `sftp` and `spaceandtime` | +| `docker/Dockerfile.conserver` | `conserver` | No `milvus`. No `scitt`, because `fastapi` is absent. No `sftp` or `spaceandtime` | +| `docker/Dockerfile.api` | `api` | No `milvus` or `chatgpt_files`, because `openai` is absent. No `scitt`, because `conserver/` is not on `PYTHONPATH`. No `sftp` or `spaceandtime` | + +The API imports adapters too. On a Redis miss it walks every entry under `storages:`, so a module that will not import in the API image affects reads as well as writes. See [Read a vCon back from storage](#read-a-vcon-back-from-storage). + +## Learn the rule for option defaults + +`Storage.__init__` runs `storage.get("options", module.default_options)`. An `options` block replaces `default_options`. It does not merge with it. A key you leave out of the block keeps its default only when the adapter handles that itself. + +| Adapters | What happens to a key left out of `options` | +|---|---| +| `milvus`, `scitt`, `utopia` | The adapter merges your options over `default_options`, so every default applies | +| `file` | Each key falls back to its default | +| `vcon_mcp` | `base_url`, `timeout`, `transient_retries` and `transient_backoff_base_s` fall back to their defaults | +| `webhook` | `timeout` and `pool-size` fall back to their defaults. `headers` and `webhook-urls` fall back to empty | +| `elasticsearch` | `cloud_id`, `api_key`, `ca_certs` and `index_prefix` are read safely. `url`, `username` and `password` raise `KeyError` on the non-cloud path | +| `postgres` | `table_name` falls back to `vcons`. All other keys raise `KeyError` | +| `s3` | `aws_region`, `endpoint_url` and `s3_path` are optional. The rest raise `KeyError`. `default_options` is empty | +| `chatgpt_files`, `dataverse`, `mongo`, `redis_storage`, `sftp` | The adapter reads the key directly, so a missing key raises `KeyError`. A missing `dataverse` auth key surfaces as `Failed to create Dataverse session with valid token` | + +The option tables on each page give the `default_options` value. Where that value applies only when the whole `options` block is absent, the page marks the option as required in practice. + +## Combine backends on a chain + +Every name in a chain's `storages` list gets the same write. The list is a set of copies and not a set of tiers, and the server never moves a vCon between backends later. + +| Goal | `storages` list | Note | +|---|---|---| +| Primary store plus search | `postgres`, `elasticsearch` | `elasticsearch` has no `get`, so reads come from `postgres` | +| Primary store plus object archive | `postgres`, `s3` | Both have `get`. The first one under the top-level `storages:` key answers reads | +| Two targets on one adapter | `postgres_us`, `postgres_eu` | Each name is its own entry under `storages:`, with its own `module` and `options` | + +## Follow a write through the server + +1. A chain finishes its links. `VconChainRequest._wrap_up` in `conserver/main.py` pushes the vCon to the chain's egress lists first. +2. It then calls `Storage(name).save(vcon_id)` for each name in the chain's `storages` list. +3. With `CONSERVER_PARALLEL_STORAGE` on, the default, and more than one backend, the writes run in a thread pool. Otherwise they run in list order. +4. Each adapter reads the vCon through `VconRedis`, which itself falls back to storage on a Redis miss. `chatgpt_files` is the exception and reads Redis directly. + +Each write is timed and counted in `conserver.storage.count` and `conserver.storage.duration_ms`, with `backend` and `outcome` attributes. See the [metrics reference](../metrics.md). + +`elasticsearch`, `postgres` and `s3` apply `EGRESS_FORMAT_VERSION` before they write. The others write the canonical form. See [egress compatibility](../../configuration/egress-compatibility.md). + +## Handle a failed write + +An exception from `save`, or from loading the module, is caught per backend in `_process_storage`. It does not stop the other backends and does not send the vCon to the ingress DLQ. The server pushes the vCon id to `DLQ:storage:`, where `` is the key under `storages:`, and records `outcome: error`. + +The push runs as one Redis script. It extends the vCon's TTL to `VCON_DLQ_EXPIRY` when the current TTL is shorter, and leaves a longer TTL or a persistent key alone. If the vCon body is already gone from Redis, nothing is pushed and the server logs that manual recovery is required. + +The server does not retry a failed write by itself. Replay is an operator action: + +```bash +curl -X POST "$API/dlq/storage/reprocess?storage_name=archive&count=100" \ + -H "x-conserver-api-token: $TOKEN" +``` + +`GET /dlq/storage?storage_name=archive` lists the ids. The header name comes from `CONSERVER_HEADER_NAME`. See the [API routes](../api-routes.md) and [storage recovery](../../operations/storage-recovery.md). + +Replay behaves as follows: + +- It repeats the storage write only. The chain does not run again. +- It takes a Redis lock with no expiry on `DLQ:storage::replay-lock`. A second caller gets `409`. A crash during replay leaves the lock in place for an operator to clear. +- An id leaves the list only after its write succeeds. +- Draining stops at the first failure. An item that always fails stays at the head and holds back every item behind it. +- Recovery is at-least-once, so a backend can see the same vCon twice. Each adapter page says what a repeated `save` does. +- An unknown `storage_name`, or a module that fails to import, returns `404`. + +### Find the writes that never reach the DLQ + +`save` can return without writing and without raising. The server then counts a success. + +| Adapter | Condition | +|---|---| +| `elasticsearch` | The vCon has no dialog. A single document that fails to index is also logged and skipped | +| `milvus` | `skip_if_exists` finds the vCon, or no text can be extracted. A failed embedding stores a zero vector | +| `scitt` | The vCon cannot be found | +| `spaceandtime` | Any error. The adapter logs and returns | +| `utopia` | `require_analysis_grant` is on and no basis grants `analysis` | +| `webhook` | `webhook-urls` is empty | + +## Read a vCon back from storage + +A vCon missing from Redis is read from adapters on the paths below. Both walk `Configuration.get_storages()`, which is every entry under `storages:` in file order, whether or not a chain uses it. The first truthy result wins and is cached back to Redis with `VCON_REDIS_EXPIRY`. + +| Path | Caller | Adapter errors | `VCON_STORAGE_FALLBACK_ENABLED` | +|---|---|---|---| +| `VconRedis._load_from_storage` | Links, adapters, tracers | Logged, next backend tried | Honoured | +| `sync_vcon_from_storage` in `api/api.py` | API read routes and `POST /vcon/ingress` | Not caught in the function. The read routes return a plain `500`, and `POST /vcon/ingress` returns `Failed to add to ingress list` | Not read | + +Order matters. `milvus` returns a partial record and `sftp` can return a different vCon, and neither path can tell. Put adapters that hold the full vCon first under `storages:`. + +## Delete a vCon from storage + +`DELETE /vcon/{uuid}` removes the Redis key and calls `Storage.delete` on every entry under `storages:`. An adapter with no `delete` returns `False`, the API logs a warning, and the stored copy stays. The route still answers with success when a backend fails, so check the logs. + +## Carry lawful basis attachments + +Adapters that store the whole vCon keep every attachment, including `lawful_basis`. `tests/storage/` covers the round trip for `mongo`, `postgres`, `s3` and `vcon_mcp`. `to_legacy` keeps the attachment too when `EGRESS_FORMAT_VERSION` is set. + +No adapter creates, validates or manages a lawful basis. Only `utopia` reads one. It writes a sentence about the basis into its rendering and offers the opt-in [`require_analysis_grant`](utopia.md#require-an-analysis-grant) option, which affects that adapter alone. Storing a vCon does not make a deployment compliant with anything. + +## Write a new adapter + +See [creating storage adapters](../../extending/creating-storage-adapters.md). diff --git a/docs/reference/storage-adapters/milvus.md b/docs/reference/storage-adapters/milvus.md new file mode 100644 index 00000000..757dd20f --- /dev/null +++ b/docs/reference/storage-adapters/milvus.md @@ -0,0 +1,105 @@ +# Milvus storage adapter + +Stores an embedding of a vCon's text in a Milvus collection for similarity search. It does not store the vCon. + +Module: `storage.milvus`. Needs `pymilvus` and `openai`, from the `storage-milvus` dependency group. Only `docker/Dockerfile` installs that group. See [the image table](index.md#install-the-adapter-packages). + +## Configure the adapter + +```yaml +storages: + milvus: + module: storage.milvus + options: + host: milvus + port: "19530" + collection_name: vcons + embedding_model: text-embedding-3-small + embedding_dim: 1536 + api_key: sk-example + create_collection_if_missing: true +``` + +## Set the options + +The adapter merges your options over the defaults. + +| Option | Type | Default | Description | +|---|---|---|---| +| `host` | string | `localhost` | Milvus host | +| `port` | string | `19530` | Milvus port | +| `collection_name` | string | `vcons` | Collection to use | +| `embedding_model` | string | `text-embedding-3-small` | Model for the embedding call | +| `embedding_dim` | integer | `1536` | Expected vector size. `save` raises `ValueError` on a mismatch | +| `api_key` | string | none | OpenAI API key | +| `organization` | string | none | OpenAI organization | +| `create_collection_if_missing` | boolean | `false` | Create the collection and its index on first use. When false, a missing collection raises `ValueError` | +| `skip_if_exists` | boolean | `true` | Skip a vCon already in the collection | +| `index_type` | string | `IVF_FLAT` | `IVF_FLAT`, `IVF_SQ8`, `IVF_PQ`, `HNSW`, `ANNOY` or `FLAT`. Anything else logs a warning and uses `IVF_FLAT` | +| `metric_type` | string | `L2` | Distance metric, passed to Milvus | +| `nlist` | integer | `128` | Cluster count for IVF indexes | +| `m` | integer | `16` | Edges per node for `HNSW` | +| `ef_construction` | integer | `200` | `efConstruction` for `HNSW` | + +The adapter also reads these keys when it creates the collection. They are not in `default_options`: + +| Option | Type | Fallback | Description | +|---|---|---|---| +| `pq_m` | integer | `8` | `m` for `IVF_PQ` | +| `pq_nbits` | integer | `8` | `nbits` for `IVF_PQ` | +| `n_trees` | integer | `50` | Tree count for `ANNOY` | + +Index options apply only when the adapter creates the collection. The client comes from `get_openai_client`, so the LiteLLM and Azure keys in `common/lib/openai_client.py` work here too. + +## Save a vCon + +1. Connect to Milvus and check the collection. +2. Read the vCon through `VconRedis`. A missing vCon raises `ValueError`. +3. With `skip_if_exists` on, return if a row has this `vcon_uuid`. +4. Build the text from `transcript`, analysis of type `transcript` and `summary`, party details, `metadata` and text dialogs. If the text is empty, log a warning and return. +5. Pick a party identifier and get the embedding. +6. Insert one row and flush. + +The collection has these fields: + +| Field | Type | Source | +|---|---|---| +| `id` | INT64, primary key, auto | Milvus | +| `vcon_uuid` | VARCHAR(100) | vCon UUID | +| `party_id` | VARCHAR(100) | First usable party identifier | +| `text` | VARCHAR(65535) | Extracted text. The adapter does not truncate it | +| `embedding` | FLOAT_VECTOR | Embedding | +| `created_at`, `updated_at` | VARCHAR(30) | `metadata.created_at` and `metadata.updated_at`, not the top-level `created_at` | +| `subject` | VARCHAR(255) | vCon subject | +| `metadata_title` | VARCHAR(255) | `metadata.title` | +| `has_transcript`, `has_summary` | BOOL | Content flags | +| `party_count` | INT16 | Party count | +| `embedding_model` | VARCHAR(50) | `embedding_model` option | +| `embedding_version` | VARCHAR(20) | Always `1.0` | + +The insert is not an upsert. With `skip_if_exists` off, each `save` adds a row. With it on, a changed vCon keeps its first embedding. + +## Read a vCon + +`get` returns a partial record, not a vCon: + +```json +{"uuid": "...", "text": "...", "embedding": [0.1], "party_id": "..."} +``` + +It returns `None` when the row or collection is missing, or on an error. + +!!! warning "Keep milvus behind adapters that hold the full vCon" + The storage fallback treats any truthy result as the vCon. If `milvus` answers first, this partial record is cached in Redis as `vcon:`, and the API read path then fails on the missing `created_at`. See [Read a vCon back from storage](index.md#read-a-vcon-back-from-storage). + +## Delete a vCon + +The adapter has no `delete`. Rows stay in Milvus after `DELETE /vcon/{uuid}`. + +## Handle a failed write + +Connection, collection, dimension and insert failures raise, so the server moves the vCon to the [storage DLQ](index.md#handle-a-failed-write). Failures inside the main block also increment `conserver.storage.milvus.storage_failures`. + +The embedding client retries transient errors with `max_retries=3`. If the embedding call still fails, `get_embedding` logs it, increments `conserver.storage.milvus.embedding_failures` and returns a zero vector of the default 1536 dimensions. With `embedding_dim` at 1536 the row is stored with that zero vector and `save` succeeds. With another size the dimension check raises. + +A replay is safe with `skip_if_exists` on. See the [metrics reference](../metrics.md) for the adapter's other metrics. diff --git a/docs/reference/storage-adapters/mongo.md b/docs/reference/storage-adapters/mongo.md index 1ace8ea4..19e190c1 100644 --- a/docs/reference/storage-adapters/mongo.md +++ b/docs/reference/storage-adapters/mongo.md @@ -1,8 +1,10 @@ -# mongo +# MongoDB storage adapter -Stores vCons in MongoDB. +Stores each vCon as one document in a MongoDB collection, keyed by UUID. -## Configuration +Module: `storage.mongo`. Needs `pymongo`, from the `storage` dependency group. + +## Configure the adapter ```yaml storages: @@ -14,83 +16,60 @@ storages: collection: vcons ``` -## Options +Any URL that `pymongo.MongoClient` accepts works, including `mongodb+srv://` and replica set URLs. + +## Set the options + +The adapter reads `url`, `database` and `collection` directly, so all three are required in an `options` block. | Option | Type | Default | Description | -|--------|------|---------|-------------| -| `url` | string | Required | MongoDB connection URL | +|---|---|---|---| +| `name` | string | `mongo` | Not read by the adapter | +| `url` | string | `mongodb://localhost:27017/` | Connection URL. A missing key raises `ValueError` | | `database` | string | `conserver` | Database name | | `collection` | string | `vcons` | Collection name | -## Example +The adapter logs the whole options dictionary at INFO on each `save`, and the URL at DEBUG. A password in `url` reaches the logs. -### Local MongoDB +## Save a vCon -```yaml -storages: - mongo: - module: storage.mongo - options: - url: mongodb://localhost:27017/ - database: vcon_server - collection: vcons -``` +`save` reads the vCon through `VconRedis`, then runs `update_one` with `$set` and `upsert=True` on `_id`, which holds the UUID. -### MongoDB Atlas +The stored document is the vCon with these changes: -```yaml -storages: - mongo_atlas: - module: storage.mongo - options: - url: mongodb+srv://user:password@cluster.mongodb.net/ - database: production - collection: vcons -``` +- `_id` is added. +- Top-level `created_at` becomes a BSON date. +- `start` on each dialog becomes a BSON date. -### With Replica Set +Attachment and analysis bodies stay as they are. The adapter does not apply `EGRESS_FORMAT_VERSION`. -```yaml -storages: - mongo: - module: storage.mongo - options: - url: mongodb://mongo1:27017,mongo2:27017,mongo3:27017/?replicaSet=rs0 - database: vcon_server - collection: vcons -``` +`$set` writes the keys in the new document and leaves others alone, so a top-level key removed from the vCon stays in MongoDB. -## Document Structure - -```json -{ - "_id": "abc-123-def", - "vcon": "0.0.1", - "uuid": "abc-123-def", - "created_at": "2024-01-15T10:30:00Z", - "parties": [...], - "dialog": [...], - "analysis": [...], - "_metadata": { - "stored_at": "2024-01-15T10:31:00Z", - "version": "1.0" - } -} -``` +## Read a vCon -## Queries +`get` calls `fetch`, turns dates back into ISO strings, and returns the vCon dictionary. The result still contains `_id`. It returns `None` when the document is missing or on any error. + +The module also has `fetch` and `exists`, which raise on errors. `Storage` does not call them directly. + +## Delete a vCon + +The adapter has no `delete`. A document stays in MongoDB after `DELETE /vcon/{uuid}`. + +## Handle a failed write + +Any exception raises, so the server moves the vCon to the [storage DLQ](index.md#handle-a-failed-write). That covers a vCon missing from Redis, a missing `created_at`, a dialog with no `start`, and a date that will not parse. The adapter sets no retry of its own. + +A repeated `save` is safe, because it upserts on `_id`. + +## Query the collection ```javascript // Find by UUID -db.vcons.findOne({ uuid: "abc-123-def" }) +db.vcons.findOne({ _id: "018f4a2e-7b1c-8000-9000-000000000001" }) // Search by party -db.vcons.find({ "parties.tel": "+15551234567" }) +db.vcons.find({ "parties.tel": "+15555550100" }) // Recent vCons db.vcons.find().sort({ created_at: -1 }).limit(10) - -// Text search (requires index) -db.vcons.createIndex({ "analysis.body": "text" }) -db.vcons.find({ $text: { $search: "billing issue" } }) ``` diff --git a/docs/reference/storage-adapters/postgres.md b/docs/reference/storage-adapters/postgres.md index e3daffe8..6d0cb715 100644 --- a/docs/reference/storage-adapters/postgres.md +++ b/docs/reference/storage-adapters/postgres.md @@ -1,84 +1,97 @@ -# postgres +# PostgreSQL storage adapter -Stores vCons in PostgreSQL database. +Stores each vCon as one row in a PostgreSQL table, with the full vCon in a JSONB column. -## Configuration +Module: `storage.postgres`. Needs `peewee` and `psycopg2-binary`, from the `storage` dependency group. + +## Configure the adapter ```yaml storages: postgres: module: storage.postgres options: - user: vcon - password: vcon_password host: postgres - port: "5432" - database: vcon_server + port: 5432 + database: vcon_db + user: postgres + password: example-password + table_name: vcons ``` -## Options +The `postgres` service in `docker-compose.yml`, started by the `postgres` profile, creates no `vcon_db`. Match its development values instead: + +```yaml +storages: + postgres: + module: storage.postgres + options: + host: postgres + port: 5432 + database: postgres + user: postgres + password: postgres +``` + +## Set the options + +The adapter reads the connection keys directly, so `database`, `user`, `password`, `host` and `port` are required in an `options` block. | Option | Type | Default | Description | -|--------|------|---------|-------------| +|---|---|---|---| +| `name` | string | `postgres` | Not read by the adapter | +| `database` | string | `vcon_db` | Database name | +| `user` | string | `postgres` | Database user | +| `password` | string | `""` | Database password | | `host` | string | `localhost` | Database host | -| `port` | string | `5432` | Database port | -| `database` | string | Required | Database name | -| `user` | string | Required | Database user | -| `password` | string | Required | Database password | -| `table` | string | `vcons` | Table name | +| `port` | integer | `5432` | Database port | +| `table_name` | string | `vcons` | Table name. Falls back to `vcons` when left out | -## Schema +## Check the table -The storage creates this table if it doesn't exist: +`save` creates the table if it does not exist. `get` and `delete` do not. -```sql -CREATE TABLE vcons ( - uuid VARCHAR(255) PRIMARY KEY, - data JSONB NOT NULL, - created_at TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -); - -CREATE INDEX idx_vcons_created_at ON vcons(created_at); -``` +| Column | Type | Content | +|---|---|---| +| `id` | UUID, primary key | vCon UUID | +| `vcon` | TEXT | The vCon's syntax version, such as `0.4.0`. This column does not hold the vCon | +| `uuid` | UUID | vCon UUID again | +| `created_at` | TIMESTAMP | vCon `created_at` | +| `updated_at` | TIMESTAMP, nullable | Time of the last write | +| `subject` | TEXT, nullable | vCon subject | +| `vcon_json` | JSONB, nullable | The full vCon | -## Example +## Save a vCon -```yaml -storages: - postgres: - module: storage.postgres - options: - host: postgres.example.com - port: "5432" - database: vcon_production - user: vcon_app - password: ${POSTGRES_PASSWORD} - -chains: - main: - links: - - transcribe - storages: - - postgres - ingress_lists: - - default - enabled: 1 -``` +`save` reads the vCon through `VconRedis`, applies `EGRESS_FORMAT_VERSION`, opens a connection, creates the table if needed, and inserts the row. On a conflict on `id` it updates all columns. It closes the connection afterwards. + +With `EGRESS_FORMAT_VERSION` set, `vcon_json` and the `vcon` column hold the legacy form. The server normalises the vCon up to the current form when it reads it back. + +## Read a vCon + +`get` returns `vcon_json`. It returns `None` when the row is missing or on any error, including a missing table. + +## Delete a vCon + +`delete` removes the row and returns `True`, or `False` when no row matched. It raises on a database error. + +## Handle a failed write + +Any exception raises, so the server moves the vCon to the [storage DLQ](index.md#handle-a-failed-write). The adapter has no retry. -## Queries +A repeated `save` is safe, because it upserts on `id`. -Query vCons directly: +## Query the table ```sql --- Get vCon by UUID -SELECT data FROM vcons WHERE uuid = 'abc-123'; +-- Get a vCon by UUID +SELECT vcon_json FROM vcons WHERE id = '018f4a2e-7b1c-8000-9000-000000000001'; -- Search by party phone -SELECT * FROM vcons -WHERE data->'parties' @> '[{"tel": "+15551234567"}]'; +SELECT id FROM vcons +WHERE vcon_json->'parties' @> '[{"tel": "+15555550100"}]'; -- Find recent vCons -SELECT uuid, created_at FROM vcons +SELECT id, created_at FROM vcons ORDER BY created_at DESC LIMIT 10; ``` diff --git a/docs/reference/storage-adapters/redis_storage.md b/docs/reference/storage-adapters/redis_storage.md new file mode 100644 index 00000000..47bd2470 --- /dev/null +++ b/docs/reference/storage-adapters/redis_storage.md @@ -0,0 +1,46 @@ +# Redis storage adapter + +Copies a vCon to a second key in the server's own Redis, with a separate expiry. Use it to keep a vCon longer than `VCON_REDIS_EXPIRY` allows. + +Module: `storage.redis_storage`. Needs no extra packages. + +## Configure the adapter + +```yaml +storages: + redis_copy: + module: storage.redis_storage + options: + prefix: vcon_storage + expires: 604800 +``` + +## Set the options + +The adapter reads `prefix` and `expires` directly, so both are required in an `options` block. + +| Option | Type | Default | Description | +|---|---|---|---| +| `redis_url` | string | `redis://:localhost:6379` | Not read by the adapter. It always uses the `redis_mgr` client, which connects to `REDIS_URL` | +| `prefix` | string | `vcon_storage` | Key prefix | +| `expires` | integer | `604800` | Key expiry in seconds. The default is seven days | + +Because `redis_url` has no effect, this adapter cannot write to a different Redis. + +## Save a vCon + +`save` reads the vCon through `VconRedis` and sets `:` to its JSON, with `expires` as the TTL. The adapter does not apply `EGRESS_FORMAT_VERSION`. + +## Read a vCon + +`get` reads `:` and parses it. It returns `None` when the key is missing or on any error. + +## Delete a vCon + +The adapter has no `delete`. After `DELETE /vcon/{uuid}` the copy stays until its TTL runs out, and a later Redis miss can bring the vCon back through the [storage fallback](index.md#read-a-vcon-back-from-storage). + +## Handle a failed write + +Any exception raises, so the server moves the vCon to the [storage DLQ](index.md#handle-a-failed-write). A failure here usually means Redis itself is down, and in that case the DLQ push fails too. The server then logs that manual recovery is required. + +A repeated `save` overwrites the key and resets its TTL. diff --git a/docs/reference/storage-adapters/s3.md b/docs/reference/storage-adapters/s3.md index 35513f74..f9591971 100644 --- a/docs/reference/storage-adapters/s3.md +++ b/docs/reference/storage-adapters/s3.md @@ -1,48 +1,26 @@ -# s3 +# S3 storage adapter -Stores vCons in Amazon S3 or S3-compatible storage. +Stores each vCon as a JSON object in Amazon S3 or an S3-compatible service, under a date prefix, with a small pointer object for lookups by UUID. -## Configuration +Module: `storage.s3`. Needs `boto3`, from the `storage` dependency group. -```yaml -storages: - s3: - module: storage.s3 - options: - aws_access_key_id: your-access-key - aws_secret_access_key: your-secret-key - aws_bucket: vcon-archive - aws_region: us-east-1 -``` +## Configure the adapter -## Options - -| Option | Type | Default | Description | -|--------|------|---------|-------------| -| `aws_access_key_id` | string | Required | AWS access key | -| `aws_secret_access_key` | string | Required | AWS secret key | -| `aws_bucket` | string | Required | S3 bucket name | -| `aws_region` | string | `us-east-1` | AWS region | -| `s3_path` | string | `""` | Key prefix | -| `endpoint_url` | string | None | Custom endpoint (for S3-compatible) | - -## Example - -### Amazon S3 +Amazon S3: ```yaml storages: s3: module: storage.s3 options: - aws_access_key_id: ${AWS_ACCESS_KEY_ID} - aws_secret_access_key: ${AWS_SECRET_ACCESS_KEY} - aws_bucket: company-vcon-archive + aws_access_key_id: example-key + aws_secret_access_key: example-secret + aws_bucket: vcon-archive aws_region: us-west-2 - s3_path: vcons/production/ + s3_path: vcons/production ``` -### MinIO (S3-Compatible) +MinIO or another S3-compatible service: ```yaml storages: @@ -55,35 +33,42 @@ storages: endpoint_url: http://minio:9000 ``` -### DigitalOcean Spaces +## Set the options -```yaml -storages: - spaces: - module: storage.s3 - options: - aws_access_key_id: ${DO_SPACES_KEY} - aws_secret_access_key: ${DO_SPACES_SECRET} - aws_bucket: my-space - aws_region: nyc3 - endpoint_url: https://nyc3.digitaloceanspaces.com -``` +`default_options` is empty, so a storage entry with no `options` block fails on every write. -## Object Structure +| Option | Type | Default | Description | +|---|---|---|---| +| `aws_access_key_id` | string | none | Access key. Required | +| `aws_secret_access_key` | string | none | Secret key. Required | +| `aws_bucket` | string | none | Bucket name. Required | +| `aws_region` | string | none | Region. Passed to the client only when set | +| `endpoint_url` | string | none | Custom endpoint for S3-compatible services | +| `s3_path` | string | none | Key prefix. A trailing slash is removed | -vCons are stored as JSON files: +## Check the object layout -``` -s3://bucket/vcons/production/abc-123-def.json -``` +`save` writes two objects: -Content: +| Object | Key | Content | +|---|---|---| +| vCon | `[s3_path/]YYYY/MM/DD/.vcon` | The vCon as JSON. The date comes from `created_at` | +| Lookup pointer | `[s3_path/]lookup/.txt` | The `YYYY/MM/DD` string | -```json -{ - "vcon": "0.0.1", - "uuid": "abc-123-def", - "created_at": "2024-01-15T10:30:00Z", - ... -} -``` +## Save a vCon + +`save` reads the vCon through `VconRedis`, applies `EGRESS_FORMAT_VERSION`, puts the vCon object, then puts the pointer. + +## Read a vCon + +`get` reads the pointer to find the date, then reads the vCon object. It returns `None` on any error, including a missing pointer. An object with no pointer cannot be read through this adapter. + +## Delete a vCon + +`delete` reads the pointer, then deletes the vCon object and the pointer. It returns `True` on success. It returns `False` on any error, including a missing pointer, and does not raise. + +## Handle a failed write + +Any exception raises, so the server moves the vCon to the [storage DLQ](index.md#handle-a-failed-write). A vCon with no `created_at` fails here, because the date prefix cannot be built. The adapter sets no retry of its own. + +A repeated `save` overwrites both objects with the same keys. If the first put succeeds and the pointer put fails, the replay repairs the pointer. diff --git a/docs/reference/storage-adapters/scitt.md b/docs/reference/storage-adapters/scitt.md new file mode 100644 index 00000000..bdf50fcf --- /dev/null +++ b/docs/reference/storage-adapters/scitt.md @@ -0,0 +1,60 @@ +# SCITT storage adapter + +Registers signed statements about a vCon on a SCRAPI-compatible transparency service. The service receives a hash-based statement. It does not receive the vCon, and the adapter cannot read one back. + +Module: `storage.scitt`. It imports `links.scitt`, so it needs `conserver/` on `PYTHONPATH` and the `fastapi` package. Only the `docker/Dockerfile` image has both. See [the image table](index.md#install-the-adapter-packages). + +## Configure the adapter + +```yaml +storages: + scitt: + module: storage.scitt + options: + scrapi_url: http://scittles:8000 + signing_key_path: /etc/scitt/signing-key.pem + issuer: conserver + key_id: conserver-key-1 + operations: + - vcon_enhanced +``` + +## Set the options + +The adapter merges your options over the defaults. + +| Option | Type | Default | Description | +|---|---|---|---| +| `scrapi_url` | string | `http://scittles:8000` | Base URL of the transparency service | +| `signing_key_pem` | string | none | Base64-encoded PEM signing key. Takes priority over `signing_key_path` | +| `signing_key_path` | string | `/etc/scitt/signing-key.pem` | Path to a PEM signing key | +| `issuer` | string | `conserver` | Issuer in the signed statement | +| `key_id` | string | `conserver-key-1` | Key id in the signed statement | +| `operations` | list | `["vcon_enhanced"]` | Operation labels. Each label produces its own statements | + +The key loader in `links.scitt` expects a P-256 ECDSA key. + +## Save a vCon + +`save` reads the vCon through `VconRedis` and takes its SHA-256 hash. It then registers one statement for each operation and each party with a `tel`: + +| Case | Subject | Payload | Metadata | +|---|---|---|---| +| Party has `tel` | `tel:` | `::` | `vcon_operation`, `party_tel` | +| No party has `tel` | `vcon://` | `:` | `vcon_operation` | + +A party with no `tel` is skipped with a warning when another party has one. + +The adapter never writes receipts back to the vCon, which avoids races with other storage writers running in parallel. The transparency service holds the receipts. + +Registration posts to `/entries`. A `201` is complete. A `303` starts polling, every 10 seconds for up to 60 seconds. Each HTTP request has a 30 second timeout. + +## Read or delete a vCon + +The adapter has no `get` and no `delete`. Entries stay on the transparency service after `DELETE /vcon/{uuid}`. + +## Handle a failed write + +A signing key problem, an HTTP error or a polling timeout raises, so the server moves the vCon to the [storage DLQ](index.md#handle-a-failed-write). A vCon that cannot be found logs a warning and returns, so the write counts as a success. + +The adapter has no retry. A replay registers every statement again, including those that succeeded before the failure. The vCon hash is the same if the vCon has not changed. TODO(verify): whether the transparency service treats a repeated statement as a new entry. diff --git a/docs/reference/storage-adapters/sftp.md b/docs/reference/storage-adapters/sftp.md new file mode 100644 index 00000000..3cc10f0f --- /dev/null +++ b/docs/reference/storage-adapters/sftp.md @@ -0,0 +1,63 @@ +# SFTP storage adapter + +Intended to upload each vCon as a file to an SFTP server. + +!!! warning "This adapter does not work as written" + `save` fails on every upload, and `paramiko` is not in any dependency group. See [Check the known problems](#check-the-known-problems). + +Module: `storage.sftp`. Needs `paramiko`, which `pyproject.toml` and `uv.lock` do not include, so the module will not import in any image. + +## Configure the adapter + +```yaml +storages: + sftp: + module: storage.sftp + options: + url: sftp.example.com + port: 22 + username: example-user + password: example-password + path: /uploads + add_timestamp_to_filename: true + filename: vcon + extension: json +``` + +## Set the options + +The adapter reads every key directly, so all of them except `name` are required in an `options` block. + +| Option | Type | Default | Description | +|---|---|---|---| +| `name` | string | `sftp` | Not read by the adapter | +| `url` | string | `sftp://localhost` | Passed to `paramiko.Transport` as the host name, so use a bare host. The default value has a scheme and will not resolve | +| `port` | integer | `22` | SSH port | +| `username` | string | `username` | SSH user | +| `password` | string | `password` | SSH password | +| `path` | string | `.` | Remote directory | +| `add_timestamp_to_filename` | boolean | `true` | Append `_` to the file name | +| `filename` | string | `vcon` | File name stem. The vCon UUID is not part of the name | +| `extension` | string | `json` | File extension | + +## Save a vCon + +`save` opens a transport, reads the vCon through `VconRedis`, builds `/[_].`, and calls `putfo`. The connection closes afterwards. + +## Read a vCon + +`get` ignores the requested UUID. It lists `path`, keeps files that start with `filename` and end with the extension, and returns the one with the greatest name. It returns `None` when nothing matches or on any error. + +## Delete a vCon + +The adapter has no `delete`. + +## Handle a failed write + +Any exception raises, so the server moves the vCon to the [storage DLQ](index.md#handle-a-failed-write). The adapter has no retry. + +## Check the known problems + +- The local `SFTPClient` subclass overrides `putfo` with a method that calls itself, so each upload ends in `RecursionError`. The value passed is also a string, where paramiko expects a file object. +- `get` can return a different vCon from the one requested. Under the [storage fallback](index.md#read-a-vcon-back-from-storage) that record would be served as the requested vCon. +- With `add_timestamp_to_filename` off, every vCon writes to the same file name. diff --git a/docs/reference/storage-adapters/spaceandtime.md b/docs/reference/storage-adapters/spaceandtime.md new file mode 100644 index 00000000..441988a0 --- /dev/null +++ b/docs/reference/storage-adapters/spaceandtime.md @@ -0,0 +1,60 @@ +# Space and Time storage adapter + +Intended to insert each vCon as a row in a Space and Time table. + +!!! warning "This adapter does not work as written" + `save` fails for real vCons and hides the failure, and the `spaceandtime` package is not in any dependency group. See [Check the known problems](#check-the-known-problems). + +Module: `storage.spaceandtime`. Needs `spaceandtime`, which `pyproject.toml` and `uv.lock` do not include, so the module will not import in any image. + +## Configure the adapter + +```yaml +storages: + spaceandtime: + module: storage.spaceandtime +``` + +Connection settings come from the environment, not from `options`. The module also calls `load_dotenv()`. + +| Variable | Use | +|---|---| +| `SXT_API_KEY` | API key | +| `SXT_VCON_TABLENAME` | Table name | +| `SXT_VCON_TABLE_WRITE_BISCUI` | Write biscuit, used for reads as well. The code reads this exact name, with no final `T` | + +See the [environment reference](../environment.md). + +The module authenticates at import time, so a bad key fails when `Storage` first loads it. + +## Set the options + +| Option | Type | Default | Description | +|---|---|---|---| +| `name` | string | `spaceandtime` | Not read by the adapter | + +`save` and `get` use no other option. + +## Save a vCon + +`save` reads the vCon through `VconRedis`, refreshes the session if it has expired, checks each vCon key against the table columns, and inserts one row. + +`save` has a self-test branch. When the UUID is the literal string `test`, it builds a stub record with `"vcon": "test"` and writes that. The `__main__` block in the module uses it. Real vCons do not reach this branch. + +## Read a vCon + +`get` selects on `uuid` and returns the parsed `VCON_JSON` column. It returns `None` when no row matches or on any error. Those errors are logged with the text `Postgres storage plugin`. + +## Delete a vCon + +The adapter has no `delete`. + +## Handle a failed write + +`save` catches every exception, logs it and returns. The server counts a success and nothing reaches the [storage DLQ](index.md#handle-a-failed-write), so a failed write can only be found in the logs. Search for `spaceandtime storage plugin: failed to insert`. + +## Check the known problems + +- `VconRedis.get_vcon` returns a `Vcon` object, and `save` then calls `vcon.keys()`. `Vcon` has no such method, so each real save logs `AttributeError` and writes nothing. +- `get` builds its SQL by string formatting. The API validates the UUID path parameter. Other callers pass the id as given. +- `common/storage/spaceandtime/README.md` lists options and variables the code does not read. diff --git a/docs/reference/storage-adapters/utopia.md b/docs/reference/storage-adapters/utopia.md new file mode 100644 index 00000000..d02003d6 --- /dev/null +++ b/docs/reference/storage-adapters/utopia.md @@ -0,0 +1,142 @@ +# Utopia storage adapter + +Sends each vCon to a [Utopia](https://github.com/deeplethe/utopia) knowledge base. Utopia reads dated prose, so the adapter renders the vCon as Markdown sentences and uploads `.md`. Utopia holds that rendering and not the vCon, so the adapter offers no `get`. + +Module: `storage.utopia`. Needs no extra packages. + +## Configure the adapter + +```yaml +storages: + utopia: + module: storage.utopia + options: + base_url: http://utopia:1516/api/v1 + kb_id: 00000000-0000-0000-0000-000000000000 + email: conserver@example.com + password: example-password +``` + +## Set the options + +The adapter merges your options over the defaults. A missing `kb_id`, `email` or `password` raises `ValueError` on every `save` and `delete`. + +| Option | Type | Default | Description | +|---|---|---|---| +| `base_url` | string | `http://127.0.0.1:1516/api/v1` | Utopia REST API root | +| `kb_id` | string | `""` | Knowledge base UUID. Required | +| `email` | string | `""` | Service account with the Editor role on the knowledge base. Required | +| `password` | string | `""` | Service account password. Required | +| `timeout` | integer | `30` | Request timeout in seconds | +| `transient_retries` | integer | `3` | Retries for transient failures | +| `transient_backoff_base_s` | number | `0.5` | Backoff factor in seconds | +| `require_analysis_grant` | boolean | `false` | Skip a vCon when no lawful basis grants `analysis`. See [Require an analysis grant](#require-an-analysis-grant) | + +## Check the rendering + +The first line is a `YYYY-MM-DD` date, because Utopia dates a document from that line. The date comes from `created_at`, or else the first dialog `start`. + +```text +2026-09-18 + +# Conversation 018f4a2e-7b1c-8000-9000-000000000001 + ++15555550100 took part. +On 2026-09-18 at 14:02, +15555550100 and Support had a recorded call lasting 240 seconds. + +On 2026-09-18, the conversation was summarised: ... + +Transcript of the conversation on 2026-09-18 at 14:02: + +On 2026-09-18, Speaker 0: ... + +Lawful basis: none recorded. +Source: vCon 018f4a2e-7b1c-8000-9000-000000000001, created 2026-09-18T14:02:00Z. +``` + +The rendering includes: + +- Party names, phone numbers, email addresses and roles. +- One sentence per dialog. +- `summary` analysis. +- `transcript` and `wtf_transcription` analysis. +- `tags` attachments. +- One lawful basis sentence. +- A source line with `amended` or `redacted` references. + +This content leaves the server, so treat the knowledge base as a store of conversation data. + +The lawful basis sentence reports what the vCon carries. It reads `Lawful basis: none recorded.` when no usable attachment exists. When one exists it gives the `lawful_basis` value, the purposes granted, and any expiry, for example `Lawful basis: consent, granted for recording, analysis, expires 2027-01-01.` The adapter fills no gaps and adds no basis to the vCon. + +## Require an analysis grant + +`require_analysis_grant` is an adapter option. It reads a `lawful_basis` attachment that is already on the vCon and decides whether this one adapter uploads. It manages nothing. + +With the option at its default of `false`, a vCon with no grant still uploads, and the adapter logs that at INFO. With `true`, that vCon is skipped. + +The adapter treats `analysis` as granted only when all of these hold: + +1. An attachment has `purpose` `lawful_basis`, or the legacy `type` with that value, and its decoded body is an object. The first such attachment is used and later ones are ignored. +2. `purpose_grants` in that body has an entry with `purpose` `analysis` and `granted` exactly `true`. +3. `expiration` is absent or in the future. An expiry that will not parse counts as expired. An expiry with no timezone is read as UTC. + +The attachment shape it reads looks like this. The values are illustrative: + +```json +{ + "purpose": "lawful_basis", + "start": "2026-09-18T14:02:00Z", + "party": 0, + "dialog": 0, + "mediatype": "application/json", + "encoding": "json", + "body": { + "lawful_basis": "consent", + "expiration": "2027-01-01T00:00:00Z", + "purpose_grants": [ + {"purpose": "analysis", "granted": true, "granted_at": "2026-09-18T14:02:00Z"} + ] + } +} +``` + +A skip works like this: + +- The adapter logs a warning and returns before it contacts Utopia. +- The write counts as a success and nothing reaches the DLQ. +- A rendering uploaded earlier stays in Utopia. + +The limits of the option: + +- It checks the fields above and nothing else. It does not examine `proof_mechanisms`, the `lawful_basis` value or `granted_at`, and it consults no outside source. +- It applies to `utopia` only. Other backends and links in the same chain do not read it. +- It creates, changes and removes no lawful basis attachment. +- It does not make a deployment compliant. + +## Save a vCon + +1. Read the vCon through `VconRedis`. A missing vCon raises `ValueError`. +2. Render it and apply `require_analysis_grant`. +3. Log in with `POST auth/login` if this process has no token for this `base_url` and `email`. Tokens are cached per process. A `401` clears the token and logs in once more. +4. List documents with `GET kbs/{kb_id}/documents`, querying by UUID with a limit of 200, and keep those named `.md`. +5. Upload with `POST kbs/{kb_id}/documents`. +6. If Utopia reports nothing created, the content is unchanged and `save` returns. +7. Otherwise delete the older documents with `DELETE documents/{id}`. + +The upload comes first, so a failed upload loses nothing. The adapter does not apply `EGRESS_FORMAT_VERSION`. + +## Read a vCon + +The adapter has no `get`. + +## Delete a vCon + +`delete` finds every live `.md` and deletes it, then returns `True` if there was at least one. A Utopia delete is a tombstone and can be reversed. Purging for redaction needs the KB Admin role, and the adapter does not do it. + +## Handle a failed write + +HTTP errors and missing options raise, so the server moves the vCon to the [storage DLQ](index.md#handle-a-failed-write). + +Before that, the session retries transient failures with exponential backoff. It shares its retry policy with [`vcon_mcp`](vcon_mcp.md#handle-a-failed-write): connection errors, read timeouts, and `429`, `502`, `503` and `504` responses, for `GET`, `POST` and `DELETE`. + +A repeated `save` is safe. Utopia skips an upload whose sha256 is already in the knowledge base. diff --git a/docs/reference/storage-adapters/vcon_mcp.md b/docs/reference/storage-adapters/vcon_mcp.md new file mode 100644 index 00000000..46ae4890 --- /dev/null +++ b/docs/reference/storage-adapters/vcon_mcp.md @@ -0,0 +1,59 @@ +# vCon MCP storage adapter + +Stores vCons in a vcon-mcp service through its REST API. + +Module: `storage.vcon_mcp`. Needs no extra packages. + +## Configure the adapter + +```yaml +storages: + vcon_mcp: + module: storage.vcon_mcp + options: + base_url: http://vcon-mcp:3000/api/v1 + api_key: example-key + timeout: 30 + transient_retries: 3 + transient_backoff_base_s: 0.5 +``` + +## Set the options + +Each key falls back to its default, so all of them are optional. + +| Option | Type | Default | Description | +|---|---|---|---| +| `base_url` | string | `http://127.0.0.1:3000/api/v1` | REST API root | +| `api_key` | string | `""` | Sent as `Authorization: Bearer ` when set | +| `timeout` | integer | `30` | Request timeout in seconds | +| `transient_retries` | integer | `3` | Retries for transient failures | +| `transient_backoff_base_s` | number | `0.5` | Backoff factor in seconds | + +## Save a vCon + +`save` reads the vCon through `VconRedis` and sends it to `POST {base_url}/vcons`. A vCon missing from Redis raises `ValueError`. The adapter does not apply `EGRESS_FORMAT_VERSION`. + +## Read a vCon + +`get` calls `GET {base_url}/vcons/{uuid}` and returns the `vcon` key of the JSON response. It returns `None` on `404`, when that key is absent, and on any request error. + +## Delete a vCon + +`delete` calls `DELETE {base_url}/vcons/{uuid}`. It returns `True` on success and `False` on `404`, and raises on any other request error. + +## Handle a failed write + +Each call uses a session that retries before any failure reaches the server. + +| Setting | Value | +|---|---| +| Retried failures | Connection errors, read timeouts, and `429`, `502`, `503` and `504` responses | +| Methods | `GET`, `POST`, `DELETE` | +| Attempts | `transient_retries` retries after the first request | +| Backoff | Exponential, with `transient_backoff_base_s` as the factor | +| `Retry-After` | Honoured on `429` and `503` | + +Other statuses such as `400`, `401` and `404` are not retried. When retries run out, or on any other error, `save` raises and the server moves the vCon to the [storage DLQ](index.md#handle-a-failed-write). + +Retrying `POST` and replaying from the DLQ are both safe, because vcon-mcp upserts on the vCon UUID. diff --git a/docs/reference/storage-adapters/webhook.md b/docs/reference/storage-adapters/webhook.md new file mode 100644 index 00000000..418bd65c --- /dev/null +++ b/docs/reference/storage-adapters/webhook.md @@ -0,0 +1,51 @@ +# Webhook storage adapter + +Posts the vCon as JSON to one or more URLs when a chain finishes. It differs from the [webhook link](../links/webhook.md), which runs as a step inside a chain. + +Module: `storage.webhook`. Needs no extra packages. + +## Configure the adapter + +```yaml +storages: + webhook: + module: storage.webhook + options: + webhook-urls: + - https://example.com/vcon-hook + headers: + Authorization: Bearer example-token + timeout: 30 + pool-size: 16 +``` + +The option names `webhook-urls` and `pool-size` use hyphens. + +## Set the options + +Each key falls back to its default, so all of them are optional. + +| Option | Type | Default | Description | +|---|---|---|---| +| `webhook-urls` | list | `[]` | Target URLs. When empty, `save` logs a warning and returns | +| `headers` | map | `{}` | Headers sent with each post | +| `timeout` | integer | `30` | Request timeout in seconds | +| `pool-size` | integer | `16` | Keep-alive connections kept per worker process | + +Size `pool-size` to `CONSERVER_VCON_CONCURRENCY`. Extra connections still work but close after use. The HTTP session is built once per process, so the first call's `pool-size` applies to all webhook storages in that process. + +## Save a vCon + +`save` reads the vCon through `VconRedis` and posts it to each URL in turn. It records the response time in `conserver.webhook.duration`, with a `status_code` attribute. + +If the payload's `vcon` is `0.0.1` or absent, the adapter sets it to `0.3.0` in the posted copy. The adapter does not apply `EGRESS_FORMAT_VERSION`. The webhook link does. + +## Read or delete a vCon + +The adapter has no `get` and no `delete`. + +## Handle a failed write + +A connection error, a timeout or a `4xx` or `5xx` response raises, so the server moves the vCon to the [storage DLQ](index.md#handle-a-failed-write). The adapter has no retry. + +The first failure stops the loop, so later URLs are not called. A replay posts to every URL again from the start, and URLs that already succeeded receive the vCon a second time. Receivers should tolerate duplicates. For independent delivery, define one storage entry per URL. diff --git a/docs/reference/tracers/jlinc.md b/docs/reference/tracers/jlinc.md new file mode 100644 index 00000000..795e8a1d --- /dev/null +++ b/docs/reference/tracers/jlinc.md @@ -0,0 +1,99 @@ +# JLINC tracer + +Reports each link step to a JLINC API server as an audit event. A tracer runs alongside the links in a chain. This one does not change the vCon. + +Module: `tracers.jlinc`, in `conserver/tracers/jlinc/`. Needs no extra packages. + +The tracer records events and does nothing else. It has no consent logic. It does not read `lawful_basis` attachments, and it does not create, check or enforce an agreement. `agreement_id` is a value it forwards. + +## Configure the tracer + +```yaml +tracers: + jlinc: + module: tracers.jlinc + options: + data_store_api_url: http://jlinc-server:9090 + data_store_api_key: example-key + archive_api_url: http://jlinc-server:9090 + archive_api_key: example-key + system_prefix: VCONTest + agreement_id: 00000000-0000-0000-0000-000000000000 + hash_event_data: true + dlq_vcon_on_error: false +``` + +The server runs every entry under the top-level `tracers:` key for every chain. A `tracers:` list inside a chain, as the comments in `example_config.yml` suggest, is not read. + +The `options` block is required. The conserver passes `tracer.get("options")` straight to `run`, so `default_options` never applies and a tracer with no options raises `TypeError`. `pip_name` is accepted here, as for links. + +## Set the options + +| Option | Type | `default_options` value | Description | +|---|---|---|---| +| `data_store_api_url` | string | `http://jlinc-server:9090` | Base URL for all API calls. Required | +| `data_store_api_key` | string | `""` | Sent as `Authorization: Bearer `. Required | +| `archive_api_url` | string | `http://jlinc-server:9090` | Sent as `archive.url` in each event body. Required | +| `archive_api_key` | string | `""` | Sent as `archive.key` in each event body. Required | +| `system_prefix` | string | `VCONTest` | Prefix for entity names. Required | +| `agreement_id` | string | `00000000-0000-0000-0000-000000000000` | Sent as `agreementId` in each event body. Required | +| `hash_event_data` | boolean | `true` | When true, send a SHA-256 hash in place of the vCon | +| `dlq_vcon_on_error` | boolean | `false` | Read by the conserver. See [Handle a failure](#handle-a-failure) | + +!!! warning "Set hash_event_data explicitly" + The default of `true` does not apply to a key left out of `options`. Without the key, hashing is off and the full vCon goes to the JLINC server. + +## Follow an event + +The conserver calls the tracer once before the first link and once after each link, whether or not the link halted the chain. Each call does this: + +1. Read the vCon through `VconRedis`. +2. On first use in a process, fetch the domain from `entity/domains/get` and take the first one. +3. Work out sender and recipient entities, creating any that are missing. +4. Build the payload. +5. Post the event to `event/produce`. + +All calls are `POST {data_store_api_url}/api/v1/data/`. + +Entities are named `-system@` and `-@`. The prefix and link name are lowercased, and any character outside `a-z`, `0-9`, `.`, `_` and `-` becomes `_`. An entity is fetched with `entity/get`, created with `entity/create` if the reply has no `didDoc`, and remembered in process memory. + +Sender and recipient depend on the position in the chain, where `links` is the chain's link list: + +| Call | Sender | Recipient | +|---|---|---| +| Before the first link | system | `links[0]` | +| After the first link | `links[-1]`, the last link in the list | `links[1]`, or system for a one-link chain | +| After link `i` | `links[i-1]` | `links[i+1]` | +| After the last link | `links[n-2]` | system | + +The link that just ran is not the sender. + +The event body has this shape: + +```json +{ + "type": "data", + "senderShortName": "vcontest-tag@example.com", + "recipientShortName": "vcontest-system@example.com", + "agreementId": "00000000-0000-0000-0000-000000000000", + "data": {"hash": ""}, + "meta": {"in_vcon_uuid": "", "out_vcon_uuid": ""}, + "archive": {"url": "http://jlinc-server:9090", "key": ""} +} +``` + +With hashing off, `data` is the full vCon, including any attachments. The archive key travels in every event body. + +## Handle a failure + +| Failure | Result | +|---|---| +| vCon not found | Logs an error and returns `False`. The conserver ignores the return value | +| API call fails or returns an unexpected body | Logs a warning, then logs success and returns `True`. No event is recorded and the chain continues | +| Any exception that leaves `run` | The conserver logs it, then re-raises only if `dlq_vcon_on_error` is true | + +A re-raised exception takes the link failure path in `_process_link`, which sends the vCon to the [dead letter queue](../../operations/dead-letter-queue.md) for its ingress list. + +Connection errors and API errors sit inside the tracer's own `try` block and never leave `run`, so `dlq_vcon_on_error` does not cover them. It covers failures outside that block, such as a Redis error on read. A failed JLINC call shows up only as a warning in the logs, and the tracer does not retry it. + +API calls set no request timeout, so a server that accepts a connection and never answers holds the chain at that step. diff --git a/docs/storage-recovery.md b/docs/storage-recovery.md deleted file mode 100644 index 716232f5..00000000 --- a/docs/storage-recovery.md +++ /dev/null @@ -1,61 +0,0 @@ -# Recover failed storage writes - -A failed backend write enters `DLQ:storage:`. It does not -re-enter the processing chain, so recovery does not repeat transcription. Other -backends and egress continue. Monitor `conserver.storage.count{outcome="error"}` -and `conserver.dlq.count{queue_name="DLQ:storage:"}`. - -The Redis body retention extension and enqueue happen atomically. -`VCON_DLQ_EXPIRY` defaults to seven days; longer TTLs and persistent bodies are -preserved. Zero disables the extension. A missing body or Redis failure is logged -as requiring manual recovery. Redis durability and available capacity remain -prerequisites; this is not a second durable store. Recover before the body expires. - -The vcon-mcp HTTP backend retries connection failures, read timeouts, and -429/502/503/504 responses. Options are `transient_retries` (default 3), -`transient_backoff_base_s` (default 0.5), and `timeout` (default 30 seconds per -request). Retry-After is respected. Permanent 4xx responses are not retried. -POST retries require the backend's UUID-based upsert contract. - -Using the API's configured root path and normal authentication: - -- `GET /dlq/storage?storage_name=` lists pending UUIDs. -- `POST /dlq/storage/reprocess?storage_name=&count=10` retries a bounded - snapshot, returning the number successfully written. Start with a small count. - -Entries are removed only after successful writes. A failed write stops the batch -and leaves its entry queued. A stopped API process or failed acknowledgement also -leaves entries replayable. This is at-least-once delivery: interrupted replays may -repeat a successful save. Verify that the selected backend tolerates repeated -writes of the same UUID. Storage I/O runs in the threadpool rather than blocking -the API event loop. - -A Redis lock serializes replay per backend across API processes. Concurrent replay -returns HTTP 409. The lock deliberately has no expiry: a slow backend must not let -a second replay acknowledge entries belonging to an earlier snapshot. Normal -completion and errors release it. After a process crash, stop or verify the -termination of every replay for that backend before manually deleting only -`DLQ:storage::replay-lock`, then retry. Never clear a lock while replay might -still be running; preserve the DLQ list and vCon bodies. - -## Validate before production rollout - -Use an isolated RedisJSON instance and a disposable HTTP receiver. Make the receiver -return 503, confirm bounded retries followed by a per-backend DLQ entry and retained -body, restore successful responses, replay, and verify the receiver stored one UUID -without invoking processing links. Stop replay during a write and confirm its UUID -remains queued. Never create a production backend outage for this test. - -Release the upstream conserver and API images together. Overlay deployments must -update both base images; updating only workers queues failures without providing -the recovery endpoint. Preserve the previous images for rollback. Rolling back -must not clear `DLQ:storage:*`; old images cannot replay these queues. After rollout, -verify versions, health, storage-error alerts, and queue depth before a small replay. - -## Generic webhook backends - -`storage.webhook` propagates HTTP 4xx/5xx and transport failures to the same storage -DLQ. Its `timeout` option defaults to 30 seconds per request. It does not automatically -retry arbitrary POST receivers because their idempotency contracts are unknown. -Before replaying a backend with multiple webhook URLs, confirm every receiver can -tolerate duplicate writes: an earlier URL may have succeeded before a later one failed. diff --git a/docs/stylesheets/vconic.css b/docs/stylesheets/vconic.css new file mode 100644 index 00000000..1359fc81 --- /dev/null +++ b/docs/stylesheets/vconic.css @@ -0,0 +1,105 @@ +/* Brand colours and type for the MkDocs Material theme. */ +@import url("https://fonts.googleapis.com/css2?family=Anton&display=swap"); + +:root { + --vconic-green: #0BB81E; + --vconic-deep-green: #0A7D18; + --vconic-ink: #292929; + --vconic-body: #33363B; + --vconic-muted: #8A8A8D; + --vconic-surface: #F3F4F6; + --vconic-display: "Anton", "Inter", Helvetica, Arial, sans-serif; +} + +/* White text on #0BB81E fails contrast, so primary uses the deep green. */ +[data-md-color-scheme="default"][data-md-color-primary="custom"], +[data-md-color-scheme="slate"][data-md-color-primary="custom"] { + --md-primary-fg-color: var(--vconic-deep-green); + --md-primary-fg-color--light: var(--vconic-green); + --md-primary-fg-color--dark: var(--vconic-deep-green); + --md-primary-bg-color: #FFFFFF; + --md-primary-bg-color--light: #FFFFFFB3; +} + +[data-md-color-scheme="default"][data-md-color-accent="custom"], +[data-md-color-scheme="slate"][data-md-color-accent="custom"] { + --md-accent-fg-color: var(--vconic-green); + --md-accent-fg-color--transparent: #0BB81E1A; + --md-accent-bg-color: #FFFFFF; + --md-accent-bg-color--light: #FFFFFFB3; +} + +[data-md-color-scheme="default"] { + --md-default-fg-color: var(--vconic-ink); + --md-default-fg-color--light: var(--vconic-body); + --md-typeset-color: var(--vconic-body); + --md-typeset-a-color: var(--vconic-deep-green); + --md-code-bg-color: var(--vconic-surface); + --md-code-fg-color: var(--vconic-ink); +} + +/* Deep green is too dark on the slate background, so links use the bright green. */ +[data-md-color-scheme="slate"] { + --md-typeset-a-color: var(--vconic-green); +} + +.md-header, +.md-tabs { + background-color: var(--vconic-ink); +} + +.md-header__button.md-logo { + display: none; +} + +.md-header__title, +.md-typeset h1 { + font-family: var(--vconic-display); + font-weight: 400; + letter-spacing: 0.01em; +} + +.md-typeset h1 { + color: var(--md-default-fg-color); +} + +.md-typeset h2, +.md-typeset h3 { + color: var(--md-default-fg-color); + font-weight: 600; +} + +.md-typeset table:not([class]) th { + background-color: var(--md-code-bg-color); +} + +/* Rendered diagrams have a white background, so give them an edge in dark mode. */ +.md-typeset img[src$=".svg"] { + border-radius: 0.2rem; +} + +/* Inline Mermaid blocks follow the same palette as the rendered SVGs. */ +:root > * { + --md-mermaid-font-family: "Inter", Helvetica, Arial, sans-serif; + --md-mermaid-node-fg-color: var(--vconic-deep-green); +} + +/* A green rule under the header and on notes carries the brand colour. */ +.md-tabs { + border-bottom: 0.1rem solid var(--vconic-green); +} + +.md-typeset .admonition.note, +.md-typeset details.note { + border-color: var(--vconic-deep-green); +} + +.md-typeset .note > .admonition-title, +.md-typeset .note > summary { + background-color: var(--md-accent-fg-color--transparent); +} + +.md-typeset .note > .admonition-title::before, +.md-typeset .note > summary::before { + background-color: var(--vconic-deep-green); +} diff --git a/docs/visuals/index.md b/docs/visuals/index.md new file mode 100644 index 00000000..af38f0ec --- /dev/null +++ b/docs/visuals/index.md @@ -0,0 +1,99 @@ +# Diagrams and motion scenes + +Use these pictures to see how the open source server fits together before you read the detail. Each diagram lists the page that explains it. + +Four [motion scenes](motion/index.html) animate the same flows. The Mermaid sources sit in the [diagram folder](../diagrams/README.md). + +## Browse the diagram list + +| ID | Diagram | SVG | Owner page | Motion | +|---|---|---|---|---| +| D01 | System context | [SVG](../diagrams/D01-system-context.svg) | [Server architecture](../concepts/architecture.md) | [M1](motion/index.html#m1) | +| D02 | Container and port map | [SVG](../diagrams/D02-container-port-map.svg) | [Ports and services](../reference/ports.md) | | +| D03 | Deploy map | [SVG](../diagrams/D03-deploy-map.svg) | [Install vCon Server](../installation/index.md) | | +| D04 | Ingress paths | [SVG](../diagrams/D04-ingress-paths.svg) | [Server architecture](../concepts/architecture.md) | | +| D05 | Chain pipeline | [SVG](../diagrams/D05-chain-pipeline.svg) | [Chains and pipelines](../configuration/chains-and-pipelines.md) | [M1](motion/index.html#m1) | +| D06 | Worker and queue topology | [SVG](../diagrams/D06-worker-queue-topology.svg) | [Workers](../configuration/workers.md) | [M2](motion/index.html#m2) | +| D07 | vCon lifecycle | [SVG](../diagrams/D07-vcon-lifecycle.svg) | [vCon lifecycle](../concepts/vcon-lifecycle.md) | [M3](motion/index.html#m3) | +| D08 | Dead letter flow | [SVG](../diagrams/D08-dead-letter-flow.svg) | [Dead letter queues](../operations/dead-letter-queue.md) | [M4](motion/index.html#m4) | +| D09 | Storage write and recovery | [SVG](../diagrams/D09-storage-write-recovery.svg) | [Storage recovery](../operations/storage-recovery.md) | [M4](motion/index.html#m4) | +| D10 | vCon assembly | [SVG](../diagrams/D10-vcon-assembly.svg) | [Lawful basis](../concepts/lawful-basis.md) | [M3](motion/index.html#m3) | +| D11 | Egress compatibility | [SVG](../diagrams/D11-egress-compatibility.svg) | [Egress format compatibility](../configuration/egress-compatibility.md) | | +| D12 | Link execution contract | [SVG](../diagrams/D12-link-execution-contract.svg) | [Create a processing link](../extending/creating-links.md) | | +| D13 | Authentication paths | [SVG](../diagrams/D13-authentication-paths.svg) | [Authentication](../configuration/authentication.md) | | +| D14 | Observability | [SVG](../diagrams/D14-observability.svg) | [Monitor the server](../operations/monitoring.md) | | + +## Watch the motion scenes + +Each scene has a static twin among the diagrams above. + +| ID | Scene | Twin | +|---|---|---| +| [M1](motion/index.html#m1) | A vCon runs a chain | D01, D05 | +| [M2](motion/index.html#m2) | Workers drain the ingress queues | D06 | +| [M3](motion/index.html#m3) | A vCon gains analysis, tags and attachments | D07, D10 | +| [M4](motion/index.html#m4) | A failed vCon reaches the DLQ and returns | D08, D09 | + +## See the system shape + +**D01 System context** + +![API and conserver services around Redis, with storage backends and link services outside](../diagrams/D01-system-context.svg) + +**D02 Container and port map** + +![Docker host ports, the conserver network and the Compose services by profile](../diagrams/D02-container-port-map.svg) + +**D03 Deploy map** + +![Five deployment paths: Docker Compose, the automated script, manual install, published images and the example Kubernetes manifests](../diagrams/D03-deploy-map.svg) + +**D04 Ingress paths** + +![The routes and the follower that bring a vCon into the server](../diagrams/D04-ingress-paths.svg) + +## Follow the vCon path + +**D05 Chain pipeline** + +![Flow of one vCon id through hooks, links, egress lists and storage, with the halted and failed paths](../diagrams/D05-chain-pipeline.svg) + +**D06 Worker and queue topology** + +![Producers, ingress lists, the worker processes and their thread pools, egress lists and dead letter queues](../diagrams/D06-worker-queue-topology.svg) + +**D07 vCon lifecycle** + +![States of a vCon from intake through chains, storage, dead letter queues and expiry](../diagrams/D07-vcon-lifecycle.svg) + +**D10 vCon assembly** + +![Class diagram of a vCon showing the lawful basis attachment as carried by the server and never created by it](../diagrams/D10-vcon-assembly.svg) + +## Recover a failed vCon + +**D08 Dead letter flow** + +![States of a vCon id from an ingress list through the links and wrap-up to the ingress and storage dead letter queues](../diagrams/D08-dead-letter-flow.svg) + +**D09 Storage write and recovery** + +![Sequence of a storage write after the last link, the storage DLQ path and the operator replay](../diagrams/D09-storage-write-recovery.svg) + +## Read the interface contracts + +**D11 Egress compatibility** + +![Flow from the canonical vCon in Redis through the egress points and the to_legacy steps](../diagrams/D11-egress-compatibility.svg) + +**D12 Link execution contract** + +![Sequence of a worker running hooks, tracers and a link module for one vCon, with success and failure branches](../diagrams/D12-link-execution-contract.svg) + +**D13 Authentication paths** + +![Sequence of the three authentication paths: public routes, main API routes and external ingress](../diagrams/D13-authentication-paths.svg) + +**D14 Observability** + +![Metrics, traces, errors and chain tracers leaving the API and worker processes, with the Redis reads behind them](../diagrams/D14-observability.svg) diff --git a/docs/visuals/motion/fonts/Anton-Regular.ttf b/docs/visuals/motion/fonts/Anton-Regular.ttf new file mode 100644 index 00000000..3eb0e15b Binary files /dev/null and b/docs/visuals/motion/fonts/Anton-Regular.ttf differ diff --git a/docs/visuals/motion/fonts/Inter-VariableFont_opsz_wght.ttf b/docs/visuals/motion/fonts/Inter-VariableFont_opsz_wght.ttf new file mode 100644 index 00000000..e31b51e3 Binary files /dev/null and b/docs/visuals/motion/fonts/Inter-VariableFont_opsz_wght.ttf differ diff --git a/docs/visuals/motion/index.html b/docs/visuals/motion/index.html new file mode 100644 index 00000000..68629488 --- /dev/null +++ b/docs/visuals/motion/index.html @@ -0,0 +1,57 @@ + + + + + + vCon Server motion scenes + + + + +
+

vCon Server documentation

+

Four scenes follow a vCon through the server.

+
+ +
+
+ + + + +
+ +
+
+

+

+
+

Scroll the stage sideways to see the whole scene.

+ +
+ + + + + +
+

+ +
+ +
+ +
+ + + + + + + + diff --git a/docs/visuals/motion/scene-authoring.md b/docs/visuals/motion/scene-authoring.md new file mode 100644 index 00000000..dc7c35d0 --- /dev/null +++ b/docs/visuals/motion/scene-authoring.md @@ -0,0 +1,131 @@ +# Motion scene player + +This folder holds four animated scenes of the open source server. Each scene has a static Mermaid twin in `docs/diagrams/`. + +Open `index.html` in a browser. It runs over `file://` with no build step, no server and no network. A hash picks the scene: `index.html#m3`. + +| Tab | Scene | File | Twins | +|---|---|---|---| +| M1 | A vCon runs a chain | `scenes/m1-chain-run.js` | D01, D05 | +| M2 | Workers drain the ingress queues | `scenes/m2-workers.js` | D06 | +| M3 | A vCon gains analysis, tags and attachments | `scenes/m3-vcon-assembly.js` | D07, D10 | +| M4 | A failed vCon reaches the DLQ and returns | `scenes/m4-dlq-recovery.js` | D08, D09 | + +## Keep these file rules + +- Scene files are classic scripts. Browsers block ES modules, `fetch` and XHR over `file://`, so use none of them. +- Load nothing from a CDN. Fonts sit in `fonts/` and styles in `shell.css`. +- Use vanilla JavaScript and SVG, with no libraries. +- A scene changes only its own file. Add a shared style or helper in `shell.css` or `shell.js`, not in a scene. + +## Register a scene + +Each scene file makes one call to `VconMotion.register`. A malformed scene throws a `TypeError` at load. Its tab then shows an error and the other tabs keep working. + +```js +VconMotion.register({ + id: 'm1', // matches the tab in index.html + title: 'A vCon runs a chain', // shown above the stage + summary: 'One sentence on what the viewer sees.', + twins: ['D01-system-context', 'D05-chain-pipeline'], // file names in docs/diagrams, no extension + viewBox: [960, 540], // optional, this is the default + + setup: function (ctx) { + // Build the SVG once, in the state before step 1. Keep handles in ctx.state. + var a = ctx.node({ x: 100, y: 238, label: 'Source' }); + var b = ctx.node({ x: 405, y: 238, label: 'Target' }); + ctx.state.path = ctx.edge({ from: a.right, to: b.left }); + ctx.state.token = ctx.token({ x: a.cx, y: a.y - 24 }); + }, + + steps: [ + { + id: 'move', // stable name, used by tests + label: 'The token moves', // short heading in the step list + caption: 'One or two plain sentences. Screen readers announce this.', + duration: 1200, // ms of animation + hold: 700, // optional ms pause after the step, default 700 + draw: function (p, ctx) { // p runs from 0 to 1, linear + ctx.state.token.follow(ctx.state.path, ctx.ease(p)); + } + } + ] +}); +``` + +## Follow the drawing contract + +The shell rebuilds the stage on every jump: it runs `setup`, then calls `draw(1, ctx)` on each finished step in order. So Back, Step, Reset and the step list all work with no scene code, as long as these rules hold. + +- `draw` depends only on `p`, `ctx` and what earlier steps left at `p = 1`. Set values. Never add to them. +- `draw(1, ctx)` alone must produce the full end state of the step. The shell may skip every smaller `p`. +- Do all motion inside `draw`. Use no timers, `requestAnimationFrame`, CSS transitions or SMIL, since the shell could not pause or skip them. +- Put meaning in the captions as well as the picture. Reduced motion viewers and screen readers rely on them. +- Never signal a state by colour alone. The `fail` state uses a dark fill and a dashed line for this reason. +- Every caption must come from the code, like any other page in these docs. Mark what you cannot confirm with `TODO(verify)` in a code comment, not in a caption. + +## Build with the stage helpers + +`setup` and `draw` receive the same `ctx`. It is rebuilt on each mount, so `ctx.state` starts empty. + +| Member | Purpose | +|---|---| +| `ctx.svg`, `ctx.width`, `ctx.height` | Root SVG element and its viewBox size | +| `ctx.layers` | SVG groups from back to front: `back`, `edges`, `nodes`, `tokens`, `notes` | +| `ctx.tokens` | Brand colours: `green`, `greenDeep`, `ink`, `body`, `muted`, `surface`, `white` | +| `ctx.state` | Scratch object for the scene | +| `ctx.reducedMotion` | True when the viewer asks for reduced motion | +| `ctx.el(tag, attrs, parent)` | Creates an SVG element. The parent defaults to `layers.notes` | +| `ctx.text({ x, y, text, kind, anchor, parent })` | Adds text. `\n` splits lines. `kind` is `label`, `title` or `small` | +| `ctx.setText(textEl, value)` | Replaces the text of an element made by `ctx.text` | +| `ctx.node({ x, y, w, h, label, sub, state })` | Adds a box. Defaults to 150 by 64 | +| `ctx.edge({ from, to, via, label, dashed, state })` | Adds an arrow through `[x, y]` points | +| `ctx.token({ x, y, label, w, h, state, hidden })` | Adds a moving card, centred on `x, y`. The label defaults to `vCon` | +| `ctx.show(item, visible)`, `ctx.fade(item, opacity)` | Work on an element or on anything a helper returned | +| `ctx.ease(p)` | Brand easing, `cubic-bezier(.2, .7, .2, 1)` | +| `ctx.lerp(a, b, p)`, `ctx.clamp(v, lo, hi)` | Interpolate and limit. `clamp` defaults to 0 and 1 | +| `ctx.seg(p, a, b)` | Maps the window `a` to `b` of a step onto 0 to 1 | + +Helper return values: + +- A node has `g`, `x`, `y`, `w`, `h`, `cx`, `cy`, the `[x, y]` ports `left`, `right`, `top` and `bottom`, plus `setLabel(label, sub)` and `setState(state)`. +- An edge has `g`, `points`, `pointAt(p)` and `setState(state)`. +- A token has `g`, `at(x, y)`, `follow(edge, p)`, `setLabel(text)` and `setState(state)`. + +States are `idle`, `active`, `done`, `fail` and `muted`. Edges have no `done` style, and tokens show `active` as `idle`. Node labels do not wrap, so size boxes to fit. Keep SVG text at 12px or larger in the 960 wide viewBox. The stage stops shrinking at 640px and scrolls inside its frame on phones. + +## Drive the player + +`window.VconMotion` carries the whole API. + +| Call | Effect | +|---|---| +| `register(scene)` | Adds a scene. Call it from a scene file | +| `select(id)` | Shows a scene at its start and stops playback | +| `play()` | Plays from the current position. At the end it restarts | +| `pause()` | Stops playback and keeps the frame | +| `step()` | Stops playback and finishes the current step | +| `step(-1)` | Stops playback and returns to the start of the step, or of the step before when already on a boundary | +| `seek(cursor, p)` | Jumps to a position, for tests and screenshots. `cursor` counts finished steps | +| `reset()` | Returns to the start | +| `state()` | Returns `{ scene, title, cursor, progress, stepCount, activeStep, playing, done, reducedMotion, error }` | +| `scenes()` | Lists registered ids | + +Nothing plays until the viewer presses Play. Switching tabs stops playback and resets the new scene. Arrow keys, Home and End move between tabs. The controls are ordinary buttons, so the keyboard reaches them with no extra shortcuts. + +## Respect reduced motion + +Under `prefers-reduced-motion: reduce` the player never tweens. Play calls `draw(1, ctx)` once per step and holds each result for at least 2.5 seconds. Step, Back and the step list work as usual, and a notice explains the behaviour. Scenes need no code for this, provided they follow the drawing contract. + +## Test a scene + +Load `file://.../docs/visuals/motion/index.html` in Playwright. For each tab, check these points: + +- `VconMotion.scenes()` lists the id and `VconMotion.state().error` stays `null`. +- `VconMotion.seek(stepCount)` reaches `done`, and the frame matches the frame after a full `play()`. +- No request leaves `file://`, and the console stays free of errors. +- With `reducedMotion: 'reduce'` set on the browser context, `play()` still reaches `done`. + +## Keep the font licences + +`fonts/` holds byte copies of Anton and the Inter variable font. Both use the SIL Open Font License 1.1, and each file carries its copyright and licence in its name table. Keep the files unmodified. Inter Italic is left out because nothing here sets italic text. diff --git a/docs/visuals/motion/scenes/m1-chain-run.js b/docs/visuals/motion/scenes/m1-chain-run.js new file mode 100644 index 00000000..3005e5f8 --- /dev/null +++ b/docs/visuals/motion/scenes/m1-chain-run.js @@ -0,0 +1,444 @@ +/* M1: a vCon runs a chain. Twin of D01-system-context and D05-chain-pipeline. + Paths and line numbers point at the code each step draws, in this worktree. + Every draw paints the whole frame through paint(), so draw(1, ctx) alone + gives the full end state of a step, as the scene-authoring.md contract requires. */ +(function () { + 'use strict'; + + var COL = [25, 265, 505, 745]; // four columns of 190 wide boxes + var W = 190; + var ROW = { a: 30, b: 140, c: 276, d: 410 }; + + var MAIN_NODES = ['api', 'ingress', 'worker', 'before', 'link1', 'link2', 'egress', 'mode', 'save', 'after']; + var EXIT_NODES = ['skipped', 'halted', 'routed', 'dlq', 'sdlq']; + var MAIN_EDGES = ['apiIngress', 'ingressWorker', 'workerBefore', 'beforeLink', 'linkLink', 'linkEgress', 'egressMode', 'modeSave', 'saveAfter']; + var EXIT_EDGES = ['beforeSkipped', 'skippedAfter', 'linkHalted', 'haltedAfter', 'linkRouted', 'linkDlq', 'beforeDlq', 'dlqAfter', 'saveSdlq', 'sdlqAfter']; + + var LINK_LABELS = { + link1: ['Link 1', 'module.run(...)'], + link2: ['Link 2', 'module.run(...)'] + }; + + function has(list, name) { return (list || []).indexOf(name) !== -1; } + + // Sets every node and edge from one spec. base is the state of main path + // items the spec does not name. Exit nodes rest as muted, exit edges hidden. + function paint(ctx, spec) { + var s = ctx.state; + var base = spec.base || 'idle'; + + function nodeState(name, fallback) { + if (has(spec.fail, name)) { return 'fail'; } + if (has(spec.active, name)) { return 'active'; } + if (has(spec.done, name)) { return 'done'; } + return fallback; + } + + MAIN_NODES.forEach(function (name) { s.n[name].setState(nodeState(name, base)); }); + EXIT_NODES.forEach(function (name) { s.n[name].setState(nodeState(name, 'muted')); }); + + MAIN_EDGES.forEach(function (name) { + s.e[name].setState(has(spec.edges, name) ? 'active' : base); + }); + EXIT_EDGES.forEach(function (name) { + var failed = has(spec.failEdges, name); + ctx.show(s.e[name], failed || has(spec.edges, name)); + s.e[name].setState(failed ? 'fail' : 'active'); + }); + + Object.keys(LINK_LABELS).forEach(function (name) { + var label = (spec.labels && spec.labels[name]) || LINK_LABELS[name]; + s.n[name].setLabel(label[0], label[1]); + }); + + s.token.setLabel(spec.tokenLabel || 'vCon id'); + s.token.setState(spec.tokenState || 'idle'); + ctx.show(s.copy, false); + } + + // A hidden polyline for the token to follow. Tokens rest on the top edge of + // a box, so the route leaves and rejoins that spot and the label stays clear. + function route(ctx, points) { + var line = ctx.edge({ + from: points[0], + to: points[points.length - 1], + via: points.slice(1, -1) + }); + ctx.show(line, false); + return line; + } + + VconMotion.register({ + id: 'm1', + title: 'A vCon runs a chain', + summary: 'A vCon id leaves the API, passes through a worker, two links, egress and storage, and then takes each of the other exits a chain can reach.', + twins: ['D01-system-context', 'D05-chain-pipeline'], + + setup: function (ctx) { + var s = ctx.state; + + // Back panels, matching the _wrap_up subgraph in D05. + var panel = { rx: 6, fill: ctx.tokens.white, stroke: ctx.tokens.muted, 'stroke-width': 1 }; + ctx.el('rect', Object.assign({ x: 14, y: 128, width: 452, height: 108 }, panel), ctx.layers.back); + ctx.el('rect', Object.assign({ x: 14, y: 264, width: 930, height: 108 }, panel), ctx.layers.back); + ctx.text({ x: 26, y: 226, text: 'Links, in order', kind: 'small', parent: ctx.layers.back }); + ctx.text({ x: 26, y: 362, text: '_wrap_up, in this order', kind: 'small', parent: ctx.layers.back }); + + function box(col, row, label, sub) { + return ctx.node({ x: COL[col], y: ROW[row], w: W, h: 64, label: label, sub: sub }); + } + + var n = s.n = { + api: box(0, 'a', 'api service', 'FastAPI, port 8000'), + ingress: box(1, 'a', 'Ingress list', 'Redis list of vCon ids'), + worker: box(2, 'a', 'worker_loop', 'pops one id, finds the chain'), + before: box(3, 'a', 'hook.before_processing', 'returns truthy?'), + link1: box(0, 'b', LINK_LABELS.link1[0], LINK_LABELS.link1[1]), + link2: box(1, 'b', LINK_LABELS.link2[0], LINK_LABELS.link2[1]), + halted: box(2, 'b', 'Chain halted', 'no storage or egress'), + skipped: box(3, 'b', 'vCon skipped', 'no links, storage or egress'), + egress: box(0, 'c', 'Egress lists', 'trace context stored first'), + mode: box(1, 'c', 'Parallel storage?', 'on, and 2 or more backends'), + save: box(2, 'c', 'Storage(name).save', 'one call per backend'), + sdlq: box(3, 'c', 'DLQ:storage:backend', 'body TTL extended'), + routed: box(0, 'd', 'Another Redis list', 'tag_router only'), + dlq: box(2, 'd', 'DLQ:ingress_list', 'TTL set to VCON_DLQ_EXPIRY'), + after: box(3, 'd', 'hook.after_processing', 'runs on every path') + }; + + function rest(node) { return [node.cx, node.y]; } + + var bottomA = ROW.a + 64; + var linkY = n.link1.cy; + var d = n.dlq.cy; + + var P = { + truthyOut: [800, bottomA], + falsyOut: [880, bottomA], + skippedIn: [880, n.skipped.y], + raiseOut: [770, bottomA], + linkRaise: [n.link2.x + W, linkY + 18], + haltedIn: [n.after.x, d - 14], + dlqIn: [n.dlq.x + W, d - 14], + dlqOut: [n.dlq.x + W, d + 14], + afterDlq: [n.after.x, d + 14], + saveIn: [800, n.after.y], + sdlqOut: [880, n.sdlq.y + 64], + sdlqIn: [880, n.after.y] + }; + var V = { + truthy: [[800, 116], [120, 116]], + wrapUp: [[n.link2.cx, 255], [n.egress.cx, 255]], + saved: [[n.save.cx, 392], [800, 392]], + skip: [[951, linkY], [951, d]], + halt: [[720, linkY], [720, d - 14]], + tag: [[9, linkY], [9, d]], + linkRaise: [[480, linkY + 18], [480, d]], + hookRaise: [[770, 106], [732, 106], [732, d - 14]] + }; + + s.e = { + apiIngress: ctx.edge({ from: n.api.right, to: n.ingress.left }), + ingressWorker: ctx.edge({ from: n.ingress.right, to: n.worker.left }), + workerBefore: ctx.edge({ from: n.worker.right, to: n.before.left }), + beforeLink: ctx.edge({ from: P.truthyOut, via: V.truthy, to: n.link1.top, label: 'truthy' }), + linkLink: ctx.edge({ from: n.link1.right, to: n.link2.left, label: 'same id' }), + linkEgress: ctx.edge({ from: n.link2.bottom, via: V.wrapUp, to: n.egress.top, label: 'no more links' }), + egressMode: ctx.edge({ from: n.egress.right, to: n.mode.left }), + modeSave: ctx.edge({ from: n.mode.right, to: n.save.left }), + saveAfter: ctx.edge({ from: n.save.bottom, via: V.saved, to: P.saveIn, label: 'ok' }), + + beforeSkipped: ctx.edge({ from: P.falsyOut, to: P.skippedIn }), + skippedAfter: ctx.edge({ from: n.skipped.right, via: V.skip, to: n.after.right }), + linkHalted: ctx.edge({ from: n.link2.right, to: n.halted.left, label: 'falsy' }), + haltedAfter: ctx.edge({ from: n.halted.right, via: V.halt, to: P.haltedIn }), + linkRouted: ctx.edge({ from: n.link1.left, via: V.tag, to: n.routed.left, dashed: true }), + linkDlq: ctx.edge({ from: P.linkRaise, via: V.linkRaise, to: n.dlq.left }), + beforeDlq: ctx.edge({ from: P.raiseOut, via: V.hookRaise, to: P.dlqIn }), + dlqAfter: ctx.edge({ from: P.dlqOut, to: P.afterDlq }), + saveSdlq: ctx.edge({ from: n.save.right, to: n.sdlq.left, label: 'raises' }), + sdlqAfter: ctx.edge({ from: P.sdlqOut, to: P.sdlqIn }) + }; + + // Edge labels that the midpoint rule would place badly. Kept inside the + // edge group so they hide and show with the edge. + ctx.text({ x: 888, y: 122, text: 'falsy', parent: s.e.beforeSkipped.g }); + ctx.text({ x: 474, y: 392, text: 'raises', anchor: 'end', parent: s.e.linkDlq.g }); + ctx.text({ x: 726, y: 250, text: 'raises', anchor: 'end', parent: s.e.beforeDlq.g }); + + function trip(from, points, to) { + return route(ctx, [rest(from)].concat(points, [rest(to)])); + } + + s.r = { + toIngress: trip(n.api, [n.api.right, n.ingress.left], n.ingress), + toWorker: trip(n.ingress, [n.ingress.right, n.worker.left], n.worker), + toBefore: trip(n.worker, [n.worker.right, n.before.left], n.before), + toLink1: trip(n.before, [P.truthyOut].concat(V.truthy), n.link1), + toLink2: trip(n.link1, [n.link1.right, n.link2.left], n.link2), + toEgress: trip(n.link2, [n.link2.bottom].concat(V.wrapUp), n.egress), + toSave: trip(n.egress, [n.egress.right, n.mode.left, n.mode.right, n.save.left], n.save), + toAfter: trip(n.save, [n.save.bottom].concat(V.saved), n.after), + tag: trip(n.link1, [n.link1.left].concat(V.tag, [n.routed.left]), n.routed), + skip: trip(n.before, [P.falsyOut, P.skippedIn, n.skipped.right].concat(V.skip, [n.after.right]), n.after), + halt: trip(n.link2, [n.link2.right, n.halted.left, n.halted.right].concat(V.halt, [P.haltedIn]), n.after), + raise: trip(n.link2, [P.linkRaise].concat(V.linkRaise, [n.dlq.left, n.dlq.right, P.dlqOut, P.afterDlq]), n.after), + storeFail: trip(n.save, [n.save.right, n.sdlq.left, P.sdlqOut, P.sdlqIn], n.after) + }; + + s.token = ctx.token({ x: n.api.cx, y: n.api.y, label: 'vCon id', w: 74 }); + s.copy = ctx.token({ x: n.link1.cx, y: n.link1.y, label: 'vCon id', w: 74, hidden: true }); + + ctx.text({ + x: 25, + y: 508, + kind: 'small', + text: 'The token carries the id. The vCon body stays in Redis under vcon:, where links read and write it.' + }); + + paint(ctx, { active: ['api'] }); + }, + + steps: [ + { + // api/api.py:758 post_vcon, :789 cache_vcon_in_redis, :806 queue.enqueue_async + // common/lib/queue.py VconQueue. D01 edge "store vCons, RPUSH ingress lists". + id: 'enqueue', + label: 'The API queues the id', + caption: 'POST /vcon stores the vCon in Redis. When the request names ingress lists, the API pushes the id onto each one.', + duration: 1300, + hold: 2000, + draw: function (p, ctx) { + paint(ctx, { done: ['api'], active: ['ingress'], edges: ['apiIngress'] }); + ctx.state.token.follow(ctx.state.r.toIngress, ctx.ease(p)); + } + }, + { + // conserver/main.py:862 get_config, :865 get_ingress_chain_map, + // :875 queue.dequeue (common/lib/queue.py:81 BLPOP), :901 chain lookup, + // :905 _handle_vcon. + id: 'pop', + label: 'A worker pops the id', + caption: 'worker_loop reloads the config, then waits on every ingress list with BLPOP. It finds the chain mapped to the list that gave it the id.', + duration: 1300, + hold: 2200, + draw: function (p, ctx) { + paint(ctx, { done: ['api', 'ingress'], active: ['worker'], edges: ['ingressWorker'] }); + ctx.state.token.follow(ctx.state.r.toWorker, ctx.ease(p)); + } + }, + { + // conserver/main.py:747 inside _handle_vcon. conserver/hook.py:11, the + // default returns the id. The docstring there says a Docker build may + // replace hook.py. + id: 'before-hook', + label: 'The before hook passes the vCon', + caption: 'hook.before_processing runs first. The default hook returns the id, and a truthy return lets the chain start.', + duration: 1200, + hold: 2000, + draw: function (p, ctx) { + paint(ctx, { done: ['api', 'ingress', 'worker'], active: ['before'], edges: ['workerBefore'] }); + ctx.state.token.follow(ctx.state.r.toBefore, ctx.ease(p)); + } + }, + { + // conserver/main.py:255 loop, :256 _process_link, :603 module.run, + // :264 same id leaves self.vcon_id alone. D01 edge "links call out". + id: 'link-same-id', + label: 'Link 1 returns the same id', + caption: 'VconChainRequest.process calls module.run(vcon_id, link_name, options) for each link in turn. A link may call an outside service. The same id comes back, so the chain moves on.', + duration: 1500, + hold: 2600, + draw: function (p, ctx) { + paint(ctx, { + done: ['api', 'ingress', 'worker', 'before'], + active: ['link1'], + edges: ['beforeLink'], + labels: { link1: ['Link 1', 'returns the same id'] } + }); + ctx.state.token.follow(ctx.state.r.toLink1, ctx.ease(p)); + } + }, + { + // conserver/main.py:264 to :271, self.vcon_id takes the returned value. + // A search of the run() returns in conserver/links found no bundled link + // that returns a different id, so the caption states the contract only. + id: 'link-new-id', + label: 'Link 2 returns a new id', + caption: 'A link may return a different id. The chain then carries that id forward through later links, egress and storage. A later exception still dead-letters the id the worker popped.', + duration: 1300, + hold: 2200, + draw: function (p, ctx) { + paint(ctx, { + done: ['api', 'ingress', 'worker', 'before', 'link1'], + active: ['link2'], + edges: ['linkLink'], + labels: { + link1: ['Link 1', 'returns the same id'], + link2: ['Link 2', 'returns a new id'] + }, + tokenLabel: p >= 1 ? 'new id' : 'vCon id' + }); + ctx.state.token.follow(ctx.state.r.toLink2, ctx.ease(p)); + } + }, + { + // conserver/main.py:273 _wrap_up, :352 egress_lists, :365 store_context_sync + // when a context exists, :366 queue.enqueue. Egress runs before storage. + id: 'egress', + label: '_wrap_up pushes the egress lists', + caption: 'With no links left, _wrap_up runs. It pushes the id onto each egress list before any storage write, so a downstream chain can start before the save ends. Trace context, when present, is stored before each push.', + duration: 1400, + hold: 2800, + draw: function (p, ctx) { + paint(ctx, { + done: ['api', 'ingress', 'worker', 'before', 'link1', 'link2'], + active: ['egress'], + edges: ['linkEgress'], + tokenLabel: 'new id' + }); + ctx.state.token.follow(ctx.state.r.toEgress, ctx.ease(p)); + } + }, + { + // conserver/main.py:376 mode check (common/settings.py:66 default true), + // :378 and :475 thread per backend, :381 one at a time, + // :410 Storage(name).save, common/storage/base.py:64. + id: 'storage', + label: '_wrap_up saves to each backend', + caption: 'With CONSERVER_PARALLEL_STORAGE on, the default, and 2 or more backends, each backend gets its own thread. Otherwise writes run one at a time. Storage(name).save(vcon_id) calls the adapter.', + duration: 1600, + hold: 2800, + draw: function (p, ctx) { + paint(ctx, { + done: ['api', 'ingress', 'worker', 'before', 'link1', 'link2', 'egress', 'mode'], + active: ['save'], + edges: ['egressMode', 'modeSave'], + tokenLabel: 'new id' + }); + ctx.state.token.follow(ctx.state.r.toSave, ctx.ease(p)); + } + }, + { + // conserver/main.py:764 finally, :766 hook.after_processing with the + // chain's current id. conserver/hook.py:31, the default does nothing. + id: 'after-hook', + label: 'The after hook closes the run', + caption: 'hook.after_processing sits in a finally block and gets the current id. The default hook does nothing. The next steps show the other exits, and each one ends here too.', + duration: 1300, + hold: 2600, + draw: function (p, ctx) { + paint(ctx, { + done: MAIN_NODES, + edges: ['saveAfter'], + tokenLabel: 'new id', + tokenState: p >= 1 ? 'done' : 'idle' + }); + ctx.state.token.follow(ctx.state.r.toAfter, ctx.ease(p)); + } + }, + { + // conserver/links/tag_router/__init__.py:88 queue.enqueue, :14 default + // forward_original True, final return. It is the only link module that + // pushes to a list, by grep for enqueue, rpush and lpush in conserver/links. + id: 'tag-router', + label: 'tag_router copies the id to another list', + caption: 'tag_router pushes the id onto a list chosen by the tags on the vCon. With forward_original on, the default, it also returns the id and the chain goes on. With it off, the chain halts.', + duration: 1400, + hold: 2800, + draw: function (p, ctx) { + var s = ctx.state; + paint(ctx, { + base: 'muted', + active: ['link1', 'routed'], + edges: ['linkRouted'], + labels: { link1: ['tag_router', 'queue.enqueue(list, id)'] } + }); + s.token.at(s.n.link1.cx, s.n.link1.y); + ctx.show(s.copy, true); + s.copy.follow(s.r.tag, ctx.ease(p)); + } + }, + { + // conserver/main.py:747 to :752, return with no chain run. :764 finally. + // conserver/hook.py docstring: falsy skips without the DLQ. + id: 'exit-skip', + label: 'A falsy before hook skips the vCon', + caption: 'A falsy return from hook.before_processing skips this vCon. No links, storage or egress run, and it goes to no DLQ.', + duration: 1500, + hold: 2200, + draw: function (p, ctx) { + paint(ctx, { + base: 'muted', + active: ['before', 'skipped', 'after'], + edges: ['beforeSkipped', 'skippedAfter'], + labels: {}, + tokenState: p >= 1 ? 'done' : 'idle' + }); + ctx.state.token.follow(ctx.state.r.skip, ctx.ease(p)); + } + }, + { + // conserver/main.py:257 to :263 break, :273 _wrap_up is skipped. + // :288 a halted vCon still counts as processed. + id: 'exit-halt', + label: 'A falsy link return halts the chain', + caption: 'A falsy return stops the loop and _wrap_up never runs, so this vCon gets no egress and no storage write. It is not an error and no DLQ is involved.', + duration: 1500, + hold: 2400, + draw: function (p, ctx) { + paint(ctx, { + base: 'muted', + active: ['link2', 'halted', 'after'], + edges: ['linkHalted', 'haltedAfter'], + labels: { link2: ['Link 2', 'returns falsy'] }, + tokenState: p >= 1 ? 'done' : 'idle' + }); + ctx.state.token.follow(ctx.state.r.halt, ctx.ease(p)); + } + }, + { + // conserver/main.py:670 re-raise, :754 except, :761 queue.enqueue_dlq, + // :762 and :763 TTL when VCON_DLQ_EXPIRY is above 0, :770 error argument. + // common/dlq_utils.py:3 builds DLQ:. M4 follows the replay. + id: 'exit-raise', + label: 'An exception reaches the ingress DLQ', + caption: 'An exception from a link or the before hook lands in _handle_vcon. It pushes the id onto DLQ: and sets the body TTL to VCON_DLQ_EXPIRY when that is above 0. hook.after_processing receives the error.', + duration: 1600, + hold: 2800, + draw: function (p, ctx) { + paint(ctx, { + base: 'muted', + active: ['after'], + fail: ['link2', 'dlq'], + failEdges: ['linkDlq', 'beforeDlq', 'dlqAfter'], + labels: { link2: ['Link 2', 'raises'] }, + tokenState: 'fail' + }); + ctx.state.token.follow(ctx.state.r.raise, ctx.ease(p)); + } + }, + { + // conserver/main.py:411 except, :425 comment, :429 _dead_letter_storage, + // :447 queue.enqueue_storage_dlq, common/lib/queue.py:111, + // common/dlq_utils.py:7 builds DLQ:storage:. + id: 'exit-storage', + label: 'A failed save reaches the storage DLQ', + caption: 'A failed save does not fail the chain. _process_storage pushes the id onto DLQ:storage: and extends the body TTL, so a replay repeats only that write. Other backends still run, and hook.after_processing receives no error.', + duration: 1600, + hold: 2800, + draw: function (p, ctx) { + paint(ctx, { + base: 'muted', + active: ['after'], + fail: ['save', 'sdlq'], + failEdges: ['saveSdlq', 'sdlqAfter'], + labels: {}, + tokenState: 'fail' + }); + ctx.state.token.follow(ctx.state.r.storeFail, ctx.ease(p)); + } + } + ] + }); +}()); diff --git a/docs/visuals/motion/scenes/m2-workers.js b/docs/visuals/motion/scenes/m2-workers.js new file mode 100644 index 00000000..7f6c4f17 --- /dev/null +++ b/docs/visuals/motion/scenes/m2-workers.js @@ -0,0 +1,558 @@ +/* M2. Workers drain the ingress queues. Static twin: D06-worker-queue-topology. + Every step comment names the code the step draws. Line numbers refer to the + worktree at the time of writing. The ids and the two lists are a made-up run; + only their behaviour comes from the code. + + Layout follows D06: producers on the left, ingress lists next, the main process + and two worker processes in the middle, and the output lists on the right. The + scene shows two workers. CONSERVER_WORKERS sets the real count. */ +VconMotion.register({ + id: 'm2', + title: 'Workers drain the ingress queues', + summary: 'Worker processes pop vCon ids from Redis ingress lists with BLPOP, run one chain per id, and send each id to egress, storage or a dead letter list.', + twins: ['D06-worker-queue-topology'], + + setup: function (ctx) { + var s = ctx.state; + s.nodes = []; + s.wires = []; + + function box(opts) { + var n = ctx.node(opts); + s.nodes.push(n); + return n; + } + + // A wire is a grey edge plus a lit copy on top, so a lit path stays visible + // where several wires share the rail on the right. + function wire(opts) { + var base = ctx.edge(opts); + var over = ctx.edge({ from: opts.from, to: opts.to, via: opts.via, dashed: opts.dashed, state: 'active' }); + ctx.show(over, false); + var w = { + points: base.points, + pointAt: base.pointAt, + over: over, + on: function (state) { + over.setState(state || 'active'); + ctx.show(over, true); + }, + off: function () { ctx.show(over, false); } + }; + s.wires.push(w); + return w; + } + + // An invisible path for a token to follow. + function route(points) { + var e = ctx.edge({ from: points[0], to: points[points.length - 1], via: points.slice(1, -1) }); + ctx.show(e, false); + return e; + } + + function frame(x, y, w, h) { + return ctx.el('rect', { + x: x, y: y, width: w, height: h, rx: 2, + fill: ctx.tokens.white, stroke: ctx.tokens.muted, 'stroke-width': 1.5 + }, ctx.layers.back); + } + + /* ---------- Producers ---------- */ + ctx.text({ x: 14, y: 116, text: 'Producers', kind: 'title' }); + s.api = box({ x: 14, y: 130, w: 160, h: 56, label: 'API ingress routes', sub: 'three POST routes' }); + s.follower = box({ x: 14, y: 212, w: 160, h: 56, label: 'Follower timers', sub: 'in the main process' }); + s.replay = box({ x: 14, y: 452, w: 180, h: 56, label: 'POST /dlq/reprocess', sub: 'API replay route' }); + + /* ---------- Ingress lists, head on the right ---------- */ + frame(196, 120, 154, 226); + ctx.text({ x: 273, y: 142, text: 'Ingress lists', kind: 'label', anchor: 'middle' }); + ctx.text({ x: 206, y: 168, text: 'List A, scanned first', kind: 'small' }); + ctx.text({ x: 206, y: 256, text: 'List B, scanned next', kind: 'small' }); + [176, 264].forEach(function (y) { + ctx.el('rect', { + x: 206, y: y, width: 134, height: 38, + fill: ctx.tokens.surface, stroke: ctx.tokens.muted, 'stroke-width': 1 + }, ctx.layers.back); + ctx.text({ x: 206, y: y + 52, text: 'tail', kind: 'small' }); + ctx.text({ x: 340, y: y + 52, text: 'head', kind: 'small', anchor: 'end' }); + }); + s.timer = ctx.text({ x: 273, y: 366, text: '', kind: 'small', anchor: 'middle' }); + + /* ---------- Conserver ---------- */ + frame(392, 32, 344, 394); + ctx.text({ x: 402, y: 48, text: 'Conserver', kind: 'title' }); + s.main = box({ + x: 420, y: 54, w: 298, h: 46, + label: 'Main process', sub: 'spawns CONSERVER_WORKERS processes' + }); + + s.workers = [108, 266].map(function (top, i) { + var w = { + top: top, + hy: top + 53, // height of the worker_loop and _handle_vcon centres + rest: top + 14, // height where a token sits above a box + frame: frame(412, top, 314, 150) + }; + w.title = ctx.text({ x: 568, y: top + 18, text: 'Worker-' + (i + 1), kind: 'small', anchor: 'middle' }); + w.loop = box({ x: 420, y: top + 28, w: 104, h: 50, label: 'worker_loop', sub: 'BLPOP, 15 s' }); + w.handle = box({ x: 610, y: top + 28, w: 108, h: 50, label: '_handle_vcon', sub: 'runs one chain' }); + w.pool = box({ x: 505, y: top + 94, w: 126, h: 46, label: 'Thread pool', sub: 'only above 1' }); + return w; + }); + + /* ---------- Output lists and their readers ---------- */ + var rx = 762; + var rw = 180; + s.reader = box({ x: rx, y: 14, w: rw, h: 50, label: 'GET /vcon/egress', sub: 'client or remote follower' }); + s.egress = box({ x: rx, y: 92, w: rw, h: 50, label: 'Egress lists', sub: 'RPUSH after links' }); + s.storage = box({ x: rx, y: 176, w: rw, h: 50, label: 'Storage backends', sub: 'save' }); + s.sdlq = box({ x: rx, y: 260, w: rw, h: 50, label: 'DLQ:storage:backend', sub: 'RPUSH on failed save' }); + s.sreplay = box({ x: rx, y: 344, w: rw, h: 50, label: 'Storage replay', sub: 'POST /dlq/storage/reprocess' }); + s.dlq = box({ x: rx, y: 452, w: rw, h: 56, label: 'DLQ:ingress_list', sub: 'RPUSH on exception' }); + + /* ---------- Wires ---------- */ + s.wApi = wire({ from: s.api.right, to: [196, 158] }); + s.wFollower = wire({ from: s.follower.right, to: [196, 240] }); + s.wReplay = wire({ from: [185, 452], to: [196, 320], via: [[185, 320]] }); + s.wDlqOut = wire({ from: [rx, 494], to: [194, 494] }); + ctx.text({ x: 478, y: 486, text: 'LPOP', kind: 'small', anchor: 'middle' }); + + var railX = 748; + s.workers.forEach(function (w) { + w.wSpawn = wire({ from: s.main.left, to: [412, w.top + 25], via: [[402, 77], [402, w.top + 25]] }); + w.wPop = wire({ from: [350, w.hy], to: w.loop.left }); + w.wPush = wire({ from: [420, w.hy + 14], to: [350, w.hy + 14], dashed: true }); + ctx.text({ x: 371, y: w.hy - 6, text: 'BLPOP', kind: 'small', anchor: 'middle' }); + ctx.text({ x: 371, y: w.hy + 29, text: 'LPUSH', kind: 'small', anchor: 'middle' }); + w.wSerial = wire({ from: w.loop.right, to: w.handle.left, label: 'concurrency 1' }); + w.wPoolIn = wire({ from: w.loop.bottom, to: w.pool.left, via: [[w.loop.cx, w.pool.cy]] }); + w.wPoolOut = wire({ from: w.pool.right, to: w.handle.bottom, via: [[w.handle.cx, w.pool.cy]] }); + + function out(y) { + return wire({ from: w.handle.right, to: [rx, y], via: [[railX, w.hy], [railX, y]] }); + } + w.wEgress = out(s.egress.cy); + w.wSave = out(s.storage.cy); + w.wSdlq = out(s.sdlq.cy); + w.wDlq = out(470); + }); + + s.wRead = wire({ from: s.egress.top, to: s.reader.bottom }); + ctx.text({ x: 860, y: 82, text: 'RPOP', kind: 'small' }); + s.wSdlqOut = wire({ from: s.sdlq.bottom, to: s.sreplay.top }); + ctx.text({ x: 860, y: 331, text: 'LRANGE, LREM', kind: 'small' }); + s.wResave = wire({ from: s.sreplay.right, to: s.storage.right, via: [[953, s.sreplay.cy], [953, s.storage.cy]] }); + s.wLoopback = wire({ + from: [rx, 103], to: [273, 120], + via: [[755, 103], [755, 10], [273, 10]], dashed: true + }); + ctx.text({ x: 284, y: 26, text: 'same name as an ingress list', kind: 'small' }); + + // Lit copies go last so they sit above every grey wire. + s.wires.forEach(function (w) { ctx.layers.edges.appendChild(w.over.g); }); + + /* ---------- Token paths ---------- */ + var W1 = s.workers[0]; + var W2 = s.workers[1]; + var laneA = 195; + var laneB = 283; + var head = 318; + var next = 273; + var loopX = W1.loop.cx; + var handleX = W1.handle.cx; + var shelfX = rx + rw - 22; + + function popPath(lane, w) { + return route([[head, lane], [371, lane], [371, w.hy], [loopX, w.hy], [loopX, w.rest]]); + } + function dispatchPath(w) { + return route([[loopX, w.rest], [loopX, w.hy], [handleX, w.hy], [handleX, w.rest]]); + } + function outPath(w, y, shelfY) { + return route([ + [handleX, w.rest], [handleX, w.hy], [railX, w.hy], [railX, y], + [shelfX, y], [shelfX, shelfY] + ]); + } + + s.paths = { + apiIn: route([[174, 158], [190, 158], [190, laneA], [head, laneA]]), + followerIn: route([[174, 240], [190, 240], [190, laneA], [next, laneA]]), + replayIn: route([[185, 452], [185, laneB], [head, laneB]]), + shiftA: route([[next, laneA], [head, laneA]]), + popA1: popPath(laneA, W1), + popA2: popPath(laneA, W2), + popB1: popPath(laneB, W1), + dispatch1: dispatchPath(W1), + dispatch2: dispatchPath(W2), + toEgress: outPath(W1, s.egress.cy, s.egress.y - 5), + toSave: outPath(W1, s.storage.cy, s.storage.y - 5), + toDlq: outPath(W2, 470, s.dlq.y - 5), + toSdlq: outPath(W1, s.sdlq.cy, s.sdlq.y - 5), + read: route([[shelfX, s.egress.y - 5], [s.egress.cx, s.egress.y - 5], [s.egress.cx, s.reader.cy]]), + resave: route([ + [shelfX, s.sdlq.y - 5], [s.sdlq.cx, s.sdlq.y - 5], [s.sdlq.cx, s.sreplay.cy], + [953, s.sreplay.cy], [953, s.storage.cy], [shelfX + 20, s.storage.cy], [shelfX, s.storage.y - 5] + ]), + replayOut: route([ + [shelfX, s.dlq.y - 5], [shelfX, 494], [185, 494], [185, 320], [190, 320], [190, laneA], [head, laneA] + ]), + giveBack: route([ + [loopX, W1.rest], [loopX, W1.hy + 14], [350, W1.hy + 14], [340, laneA], [head, laneA] + ]) + }; + + /* ---------- Tokens ---------- */ + s.id1 = ctx.token({ x: 174, y: 158, label: 'id 1', w: 40, hidden: true }); + s.id2 = ctx.token({ x: 174, y: 240, label: 'id 2', w: 40, hidden: true }); + s.id3 = ctx.token({ x: 185, y: 452, label: 'id 3', w: 40, hidden: true }); + s.id4 = ctx.token({ x: 174, y: 158, label: 'id 4', w: 40, hidden: true }); + s.body = ctx.token({ x: handleX, y: W1.rest, label: 'vCon', w: 44, hidden: true }); + + // Workers do not exist until step 2 runs. + s.setWorkers = function (opacity) { + s.workers.forEach(function (w) { + ctx.fade(w.frame, opacity); + ctx.fade(w.title, opacity); + ctx.fade(w.loop, opacity); + ctx.fade(w.handle, opacity); + ctx.fade(w.pool, opacity); + }); + }; + s.setWorkers(0.3); + + // Clears the highlights of the step before. Tokens keep their place. + s.calm = function () { + s.nodes.forEach(function (n) { n.setState('idle'); }); + s.wires.forEach(function (w) { w.off(); }); + }; + + // Moves a token along a path. A window that has not opened leaves it alone. + s.ride = function (token, path, q) { + if (q <= 0) { return; } + ctx.show(token, true); + token.follow(path, ctx.ease(q)); + }; + }, + + steps: [ + { + // API: api/api.py:806 (POST /vcon), :908 (external-ingress), :1046 (ingress), + // through VconQueue.enqueue_async at common/lib/queue.py:158. + // Follower: conserver/follower.py:50, VconQueue.enqueue at common/lib/queue.py:64. + // Replay: api/api.py:1171. Body key: _vcon_key at common/lib/queue.py:41. + id: 'producers-push', + label: 'Producers push vCon ids', + caption: 'The API ingress routes, the follower timers and POST /dlq/reprocess RPUSH vCon ids onto the tail of an ingress list. The list holds ids only, and each vCon body sits under its own Redis key.', + duration: 2000, + draw: function (p, ctx) { + var s = ctx.state; + s.calm(); + s.api.setState('active'); + s.follower.setState('active'); + s.replay.setState('active'); + s.wApi.on(); + s.wFollower.on(); + s.wReplay.on(); + s.ride(s.id1, s.paths.apiIn, ctx.seg(p, 0, 0.6)); + s.ride(s.id2, s.paths.followerIn, ctx.seg(p, 0.2, 0.8)); + s.ride(s.id3, s.paths.replayIn, ctx.seg(p, 0.4, 1)); + } + }, + { + // Spawn loop: conserver/main.py:993 to :1004. Count: get_worker_count at + // common/config.py:15, from common/settings.py:63. Single worker: main.py:1048. + id: 'main-spawns-workers', + label: 'The main process spawns workers', + caption: 'With CONSERVER_WORKERS above 1, main() starts that many processes and each one runs worker_loop. With a count of 1, the main process runs worker_loop itself.', + duration: 1400, + draw: function (p, ctx) { + var s = ctx.state; + s.calm(); + s.main.setState('active'); + s.workers.forEach(function (w) { w.wSpawn.on(); }); + s.setWorkers(ctx.lerp(0.3, 1, ctx.ease(p))); + } + }, + { + // Config reread: conserver/main.py:862. Ingress map: main.py:673, :865, :866. + // BLPOP: main.py:875, VconQueue.dequeue at common/lib/queue.py:81 to :90. + // Atomic hand-out: worker_loop docstring, main.py:777. + id: 'blpop-pops-heads', + label: 'BLPOP gives each worker one id', + caption: 'Each pass rereads the config, then BLPOP watches every ingress list with a 15 s timeout. It pops the head of the first non-empty list in chain order, so each id reaches one worker and id 3 waits on list B.', + duration: 2000, + draw: function (p, ctx) { + var s = ctx.state; + var a = s.workers[0]; + var b = s.workers[1]; + s.calm(); + a.loop.setState('active'); + b.loop.setState('active'); + a.wPop.on(); + b.wPop.on(); + s.ride(s.id1, s.paths.popA1, ctx.seg(p, 0, 0.5)); + s.ride(s.id2, s.paths.shiftA, ctx.seg(p, 0.3, 0.5)); + s.ride(s.id2, s.paths.popA2, ctx.seg(p, 0.5, 1)); + } + }, + { + // Serial path: conserver/main.py:903 to :905. _handle_vcon: main.py:702. + // The next BLPOP comes only after _handle_vcon returns. + id: 'serial-dispatch', + label: 'Each worker runs one chain', + caption: 'At concurrency 1, worker_loop calls _handle_vcon directly. It pops nothing more until that chain ends.', + duration: 1400, + draw: function (p, ctx) { + var s = ctx.state; + s.calm(); + s.workers.forEach(function (w) { + w.wSerial.on(); + w.handle.setState('active'); + }); + s.ride(s.id1, s.paths.dispatch1, p); + s.ride(s.id2, s.paths.dispatch2, p); + } + }, + { + // Pool: conserver/main.py:850 to :851, submit at :908, back-pressure at :914. + // Setting: common/settings.py:81, get_vcon_concurrency at common/config.py:33. + id: 'thread-pool', + label: 'A thread pool adds in-flight vCons', + caption: 'Above 1, each worker submits _handle_vcon to a pool of CONSERVER_VCON_CONCURRENCY threads. worker_loop stops popping while the pool is full.', + duration: 1000, + hold: 1200, + draw: function (p, ctx) { + var s = ctx.state; + s.calm(); + s.workers.forEach(function (w) { + w.wPoolIn.on(); + w.wPoolOut.on(); + w.pool.setState('active'); + }); + } + }, + { + // _wrap_up: conserver/main.py:345, called at :273. Egress first: :352 to :366. + // Storage next: :368 to :382, Storage(name).save at :410. + id: 'wrap-up', + label: 'The chain ends in egress and storage', + caption: 'When the links finish, _wrap_up pushes the id onto each egress list of the chain, then saves the vCon to each storage backend.', + duration: 1800, + draw: function (p, ctx) { + var s = ctx.state; + var a = s.workers[0]; + var first = ctx.seg(p, 0, 0.5); + var second = ctx.seg(p, 0.5, 1); + s.calm(); + a.handle.setState('active'); + if (first > 0) { a.wEgress.on(); s.egress.setState('active'); } + if (second > 0) { + a.wEgress.off(); + a.wSave.on(); + s.egress.setState('done'); + s.storage.setState('active'); + } + s.ride(s.id1, s.paths.toEgress, first); + s.ride(s.body, s.paths.toSave, second); + if (p >= 1) { + a.handle.setState('done'); + s.storage.setState('done'); + s.body.setState('done'); + } + } + }, + { + // except branch: conserver/main.py:754 to :763. enqueue_dlq: common/lib/queue.py:92. + // Name: get_ingress_list_dlq_name at common/dlq_utils.py:3. + // VCON_DLQ_EXPIRY: common/settings.py:56. + id: 'exception-to-dlq', + label: 'An exception fills the ingress DLQ', + caption: 'An exception in the chain pushes the id onto the DLQ named for its ingress list. When VCON_DLQ_EXPIRY is above 0, the vCon also gets that TTL.', + duration: 1500, + draw: function (p, ctx) { + var s = ctx.state; + var b = s.workers[1]; + s.calm(); + b.handle.setState('fail'); + b.wDlq.on('fail'); + s.dlq.setState('active'); + s.id2.setState('fail'); + s.ride(s.id2, s.paths.toDlq, p); + if (p >= 1) { + b.handle.setState('idle'); + s.dlq.setState('done'); + } + } + }, + { + // BLPOP reaches the next list: conserver/main.py:875. Failed save: main.py:411 + // to :429, which logs and does not re-raise. _dead_letter_storage: main.py:436, + // enqueue_storage_dlq at common/lib/queue.py:111, name at common/dlq_utils.py:7. + id: 'failed-save-to-storage-dlq', + label: 'A failed save fills the storage DLQ', + caption: 'List A is empty, so the next BLPOP takes id 3 from list B. A failed save pushes the id onto the DLQ of that backend and raises nothing, so the id stays out of the ingress DLQ.', + duration: 2400, + draw: function (p, ctx) { + var s = ctx.state; + var a = s.workers[0]; + var pop = ctx.seg(p, 0, 0.3); + var run = ctx.seg(p, 0.3, 0.45); + var save = ctx.seg(p, 0.45, 0.7); + var dead = ctx.seg(p, 0.7, 1); + s.calm(); + ctx.show(s.body, false); + if (pop > 0 && run <= 0) { a.wPop.on(); a.loop.setState('active'); } + if (run > 0) { a.wSerial.on(); a.handle.setState('active'); } + if (save > 0) { + a.wSerial.off(); + a.wSave.on('fail'); + s.storage.setState('fail'); + s.body.setState('fail'); + s.body.setLabel('vCon'); + s.ride(s.body, s.paths.toSave, save); + } + if (dead > 0) { + ctx.show(s.body, false); + a.wSave.off(); + a.wSdlq.on('fail'); + s.sdlq.setState('active'); + s.id3.setState('fail'); + } + s.ride(s.id3, s.paths.popB1, pop); + s.ride(s.id3, s.paths.dispatch1, run); + s.ride(s.id3, s.paths.toSdlq, dead); + if (p >= 1) { s.sdlq.setState('done'); } + } + }, + { + // Timeout: conserver/main.py:875 to :881. VconQueue.dequeue returns None on + // timeout, common/lib/queue.py:88. The next pass rereads config at main.py:862. + id: 'blpop-timeout', + label: 'Empty lists time out the BLPOP', + caption: 'With every list empty, BLPOP returns nothing after 15 s. The worker starts another pass and rereads the config.', + duration: 1800, + draw: function (p, ctx) { + var s = ctx.state; + s.calm(); + s.workers.forEach(function (w) { + w.loop.setState('active'); + w.wPop.on(); + }); + ctx.setText(s.timer, p >= 1 + ? 'BLPOP returned nothing,\nnext pass' + : 'BLPOP timeout\nin ' + Math.ceil(15 * (1 - p)) + ' s'); + } + }, + { + // RPOP: api/api.py:591. Replay: api/api.py:1168 (LPOP through + // dequeue_dlq_async, common/lib/queue.py:163) and :1171 (RPUSH). + // Storage replay: api/api.py:1230 (LRANGE), :1233 (save), :1239 (LREM). + // Same list name: conserver/main.py:366 writes what main.py:875 reads. + id: 'readers-drain-outputs', + label: 'Readers drain the output lists', + caption: 'GET /vcon/egress takes ids with RPOP, POST /dlq/reprocess moves ids back to their ingress list, and POST /dlq/storage/reprocess retries the save. An egress list named like an ingress list feeds that chain directly.', + duration: 2600, + draw: function (p, ctx) { + var s = ctx.state; + s.calm(); + ctx.setText(s.timer, ''); + s.reader.setState('active'); + s.replay.setState('active'); + s.sreplay.setState('active'); + s.wRead.on(); + s.wDlqOut.on(); + s.wReplay.on(); + s.wSdlqOut.on(); + s.wResave.on(); + s.wLoopback.on(); + s.id1.setState('done'); + s.id2.setState('idle'); + s.id3.setState('done'); + s.ride(s.id1, s.paths.read, ctx.seg(p, 0, 0.4)); + s.ride(s.id3, s.paths.resave, ctx.seg(p, 0, 0.8)); + s.ride(s.id2, s.paths.replayOut, p); + if (p >= 1) { + ctx.show(s.id1, false); + s.storage.setState('done'); + } + } + }, + { + // Health check: conserver/main.py:1012 (5 s sleep), :1015, restart at :1023 to + // :1030 with the same worker_id. No in-flight record: BLPOP at :875 removes + // the entry and nothing else records it. + id: 'dead-worker-restart', + label: 'The main process replaces a dead worker', + caption: 'The main process checks every 5 s and restarts a dead worker under the same number. A popped id has no in-flight record, so the queue entry that worker held is gone.', + duration: 2400, + draw: function (p, ctx) { + var s = ctx.state; + var b = s.workers[1]; + var pop = ctx.seg(p, 0, 0.3); + var dead = p >= 0.35; + var back = p >= 0.75; + s.calm(); + ctx.show(s.id3, false); + b.frame.removeAttribute('stroke-dasharray'); + if (pop > 0 && !dead) { b.wPop.on(); b.loop.setState('active'); } + s.ride(s.id2, s.paths.popA2, pop); + if (dead) { + s.id2.setState('fail'); + s.id2.setLabel('lost'); + } + if (dead && !back) { + b.loop.setState('fail'); + b.handle.setState('fail'); + b.pool.setState('fail'); + b.frame.setAttribute('stroke-dasharray', '6 4'); + } + if (back) { + s.main.setState('active'); + b.wSpawn.on(); + ctx.setText(b.title, 'Worker-2, new PID'); + } + } + }, + { + // SIGTERM: conserver/main.py:98 to :102. LPUSH on a late pop: :890 to :899, + // VconQueue.enqueue_front at common/lib/queue.py:71. Pool drain: :918 to :920. + // Join and terminate: :1037 to :1042. + id: 'shutdown-returns-id', + label: 'Shutdown returns the popped id', + caption: 'SIGTERM reaches every live worker. A worker that pops an id after the signal puts it back at the head with LPUSH, so the next worker sees it first. Thread pools drain, and the main process waits up to 30 s per worker before terminate.', + duration: 2600, + hold: 1200, + draw: function (p, ctx) { + var s = ctx.state; + var a = s.workers[0]; + var push = ctx.seg(p, 0, 0.3); + var pop = ctx.seg(p, 0.3, 0.55); + var back = ctx.seg(p, 0.6, 0.95); + s.calm(); + ctx.show(s.id2, false); + s.main.setState('active'); + if (push > 0 && pop <= 0) { s.api.setState('active'); s.wApi.on(); } + if (pop > 0 && back <= 0) { a.wPop.on(); a.loop.setState('active'); } + if (back > 0) { + a.wPush.on(); + s.workers.forEach(function (w) { + w.wSpawn.on(); + if (w !== a) { w.loop.setState('muted'); } + w.handle.setState('muted'); + w.pool.setState('muted'); + }); + a.loop.setState('active'); + } + s.ride(s.id4, s.paths.apiIn, push); + s.ride(s.id4, s.paths.popA1, pop); + s.ride(s.id4, s.paths.giveBack, back); + if (p >= 1) { + s.wires.forEach(function (w) { w.off(); }); + s.main.setState('done'); + a.loop.setState('muted'); + } + } + } + ] +}); diff --git a/docs/visuals/motion/scenes/m3-vcon-assembly.js b/docs/visuals/motion/scenes/m3-vcon-assembly.js new file mode 100644 index 00000000..0c5ff21d --- /dev/null +++ b/docs/visuals/motion/scenes/m3-vcon-assembly.js @@ -0,0 +1,382 @@ +/* M3: a vCon gains analysis, tags and attachments. Twins D07 and D10. + + The lane across the top uses the D07 states on the path a vCon takes through + a successful chain. The card below uses the D10 parts of the Vcon class in + common/vcon.py. Halts and DLQ paths belong to M1 and M4. + + The chain is an example: links.transcribe with vendor openai, links.analyze + with default options, links.tag with tags [department:sales], links.diet. + Line numbers refer to the worktree at the time of drawing. + + Attachments: add_tag (common/vcon.py:124) is the only writer a link calls. + add_attachment (common/vcon.py:177) has no caller outside tests, and neither + have add_party and add_dialog, so parties, dialog and any other attachment + come from the producer. + + Lawful basis: no step here creates one. lawful_basis appears in non-test + Python only in common/lib/vcon_compat.py, common/lib/vcon_egress_compat.py + (comments) and common/storage/utopia/__init__.py (reads it). The entry drawn + here is what a producer may send. Its dashed ring means it can be absent. */ +(function () { + 'use strict'; + + var LANE_TOKEN_Y = 22; + var COLUMNS = { parties: 34, dialog: 164, analysis: 294, attachments: 464 }; + var ROWS = [186, 248, 310]; + var ENTRY_H = 54; + + /* ---------- Scene helpers, all safe to call on every frame ---------- */ + + // Lane nodes before index are done, the node at index is active. + function focusLane(ctx, index) { + ctx.state.lane.forEach(function (node, i) { + node.setState(i < index ? 'done' : (i === index ? 'active' : 'idle')); + }); + ctx.state.laneEdges.forEach(function (edge) { edge.setState('idle'); }); + } + + // Moves the vCon token from above one lane node to above the next. + function moveToken(ctx, from, to, p) { + var lane = ctx.state.lane; + var e = ctx.ease(p); + ctx.state.token.at(ctx.lerp(lane[from].cx, lane[to].cx, e), LANE_TOKEN_Y); + if (p < 1) { ctx.state.laneEdges[from].setState('active'); } + } + + // Chain items before index are done, the item at index is active. + function focusChain(ctx, index) { + ctx.state.chain.forEach(function (item, i) { + item.setState(i < index ? 'done' : (i === index ? 'active' : 'idle')); + }); + } + + // Highlights the named entries in the card and clears the others. + function highlight(ctx, names) { + Object.keys(ctx.state.entries).forEach(function (name) { + ctx.state.entries[name].setState(names.indexOf(name) >= 0 ? 'active' : 'idle'); + }); + } + + function detail(ctx, heading, body) { + ctx.setText(ctx.state.detailHeading, heading); + ctx.setText(ctx.state.detailBody, body); + } + + // Flies a small card from a chain item into an entry slot, then fades it in. + function deliver(ctx, p, itemIndex, entryName, label) { + var s = ctx.state; + var item = s.chain[itemIndex]; + var entry = s.entries[entryName]; + var t = ctx.ease(ctx.seg(p, 0, 0.7)); + s.fly.setLabel(label); + s.fly.at( + ctx.lerp(item.left[0], entry.cx, t), + ctx.lerp(item.left[1], entry.cy, t) + ); + ctx.show(s.fly, p < 0.75); + ctx.fade(entry, ctx.seg(p, 0.6, 1)); + } + + function entry(ctx, column, row, width, label, sub) { + return ctx.node({ + x: COLUMNS[column], y: ROWS[row], w: width, h: ENTRY_H, label: label, sub: sub + }); + } + + VconMotion.register({ + id: 'm3', + title: 'A vCon gains analysis, tags and attachments', + summary: 'A vCon built by a producer runs a chain. Links add analysis and a tags attachment. Any lawful_basis attachment stays on the vCon with its body unchanged, and no step creates one.', + twins: ['D07-vcon-lifecycle', 'D10-vcon-assembly'], + + setup: function (ctx) { + var s = ctx.state; + + // D07 states on this path. + s.lane = [ + { label: 'Producer', sub: 'outside this server' }, + { label: 'Id on an ingress list', sub: 'body cached in Redis' }, + { label: 'Running a chain', sub: 'one link at a time' }, + { label: 'Wrapping up', sub: 'egress, then storage' }, + { label: 'Saved', sub: 'body still in Redis' } + ].map(function (item, i) { + return ctx.node({ x: 20 + i * 189, y: 42, w: 164, h: 60, label: item.label, sub: item.sub }); + }); + s.laneEdges = [0, 1, 2, 3].map(function (i) { + return ctx.edge({ from: s.lane[i].right, to: s.lane[i + 1].left }); + }); + + // The vCon card, drawn behind the entries. + ctx.el('rect', { + x: 20, y: 118, width: 640, height: 392, rx: 6, + fill: ctx.tokens.surface, stroke: ctx.tokens.muted, 'stroke-width': 1 + }, ctx.layers.back); + ctx.el('line', { + x1: 34, y1: 376, x2: 646, y2: 376, stroke: ctx.tokens.muted, 'stroke-width': 1 + }, ctx.layers.back); + s.cardKey = ctx.text({ x: 34, y: 145, text: 'The vCon', kind: 'label' }); + s.version = ctx.text({ x: 646, y: 145, text: '', anchor: 'end' }); + Object.keys(COLUMNS).forEach(function (name) { + ctx.text({ x: COLUMNS[name], y: 174, text: name, kind: 'title' }); + }); + + // Entries start invisible and fade in on the step that adds them. + s.entries = { + party0: entry(ctx, 'parties', 0, 120, 'party 0', 'tel'), + party1: entry(ctx, 'parties', 1, 120, 'party 1', 'mailto'), + dialog0: entry(ctx, 'dialog', 0, 120, 'dialog 0', 'recording'), + transcript: entry(ctx, 'analysis', 0, 160, 'transcript', 'dialog 0, vendor openai'), + summary: entry(ctx, 'analysis', 1, 160, 'summary', 'dialog 0, from opts'), + lawful: entry(ctx, 'attachments', 0, 182, 'lawful_basis', 'carried, never created'), + tags: entry(ctx, 'attachments', 1, 182, 'tags', 'department:sales') + }; + Object.keys(s.entries).forEach(function (name) { ctx.fade(s.entries[name], 0); }); + + // Dashed ring: this entry is present only when the producer sent one. + var lawful = s.entries.lawful; + ctx.el('rect', { + x: lawful.x - 5, y: lawful.y - 5, width: lawful.w + 10, height: lawful.h + 10, + style: 'fill: none; stroke: ' + ctx.tokens.greenDeep + '; stroke-width: 1.5; stroke-dasharray: 6 4;' + }, lawful.g); + + // A dashed box for the method no link calls. + s.unused = entry(ctx, 'attachments', 2, 182, 'add_attachment()', 'no caller outside tests'); + s.unused.g.querySelector('rect').style.strokeDasharray = '6 4'; + ctx.fade(s.unused, 0); + + s.detailHeading = ctx.text({ x: 34, y: 402, text: '', kind: 'label' }); + s.detailBody = ctx.text({ x: 34, y: 428, text: '' }); + + // Example chain and the storage call that follows it. + ctx.text({ x: 680, y: 133, text: 'Example chain', kind: 'title' }); + s.chain = [ + { label: 'links.transcribe', sub: 'add_analysis()' }, + { label: 'links.analyze', sub: 'add_analysis()' }, + { label: 'links.tag', sub: 'add_tag()' }, + { label: 'links.diet', sub: 'optional filter' }, + { label: 'Storage.save(id)', sub: 'each chain storage' } + ].map(function (item, i) { + return ctx.node({ x: 680, y: 144 + i * 54, w: 260, h: 46, label: item.label, sub: item.sub }); + }); + + ctx.el('rect', { x: 680, y: 430, width: 4, height: 72, fill: ctx.tokens.green }, ctx.layers.back); + ctx.text({ + x: 696, y: 452, kind: 'label', + text: 'No step here creates a lawful\nbasis or gates a chain on one.' + }); + + s.token = ctx.token({ x: s.lane[0].cx, y: LANE_TOKEN_Y, hidden: true }); + s.fly = ctx.token({ label: 'analysis', w: 92, hidden: true }); + }, + + steps: [ + { + // D10 UpstreamProducer to IngressPaths. api/api.py:750 post_vcon, + // api/api.py:824 external_ingress_vcon, conserver/follower.py:46-50. + // test: common/tests/test_api.py:113-138 posts a vCon holding a basis. + id: 'producer-sends', + label: 'A producer sends the vCon', + caption: 'A producer outside the server builds the vCon and sends it. Parties and dialog come from the producer. It may also include a lawful_basis attachment. No server code creates one.', + duration: 1400, + draw: function (p, ctx) { + var s = ctx.state; + focusLane(ctx, 0); + ctx.show(s.token, true); + ctx.fade(s.token, ctx.seg(p, 0, 0.3)); + ['party0', 'party1', 'dialog0'].forEach(function (name) { + ctx.fade(s.entries[name], ctx.seg(p, 0.1, 0.6)); + }); + ctx.fade(s.entries.lawful, ctx.seg(p, 0.5, 1)); + highlight(ctx, ['lawful']); + ctx.setText(s.version, 'vcon: as sent'); + detail(ctx, 'What the producer sends', + 'parties, dialog and any attachments of its own.\nThe dashed ring marks an entry that may be absent.'); + } + }, + { + // D07 [*] to Queued, POST /vcon with ingress_lists. + // api/api.py:789 cache_vcon_in_redis, api/api.py:450-452 sets + // VCON_REDIS_EXPIRY with no _enforce_spec_on_write pass. + // api/api.py:395 attachments is List[Dict], so entries get no check. + // api/api.py:806 enqueue_async. conserver/follower.py:49-50 also writes + // and enqueues, with no TTL on a new key. Without ingress_lists the id stays off any + // queue: that is the D07 Cached state, left out of this path. + id: 'server-caches', + label: 'The server caches the body', + caption: 'The API writes the body to Redis after model validation and pushes the id onto an ingress list. Attachments are plain dicts here, so nothing checks a lawful_basis body.', + duration: 1300, + draw: function (p, ctx) { + var s = ctx.state; + focusLane(ctx, p >= 1 ? 1 : 0); + moveToken(ctx, 0, 1, p); + highlight(ctx, []); + ctx.setText(s.cardKey, 'vcon: in Redis'); + detail(ctx, 'What the API checks', + 'Parties and dialog pass through their API models.\nThe API sets the key to expire after VCON_REDIS_EXPIRY.'); + } + }, + { + // D07 Queued to Running. conserver/main.py:875 queue.dequeue, + // conserver/main.py:232 VconChainRequest.process, + // conserver/main.py:603 module.run(vcon_id, link_name, options). + // Read path: common/lib/vcon_redis.py:168 get_vcon, + // common/lib/vcon_redis.py:223 normalize_legacy_fields, + // common/lib/vcon_compat.py:63-75 renames type only if purpose is absent. + id: 'worker-starts', + label: 'A worker starts the chain', + caption: 'A worker pops the id and runs the chain. Each link gets the id and loads the body through VconRedis. That read renames a legacy attachment type to purpose and keeps the body.', + duration: 1300, + draw: function (p, ctx) { + focusLane(ctx, p >= 1 ? 2 : 1); + moveToken(ctx, 1, 2, p); + highlight(ctx, ['lawful']); + detail(ctx, 'What a read changes', + 'normalize_legacy_fields renames legacy field names.\nIt leaves an attachment body alone.'); + } + }, + { + // conserver/links/transcribe/__init__.py:146-150 hands off to the vendor + // module. conserver/links/openai_transcribe/__init__.py:582 add_analysis + // with type transcript, vendor openai. common/vcon.py:209 add_analysis. + // Write path: common/lib/vcon_redis.py:98 store_vcon, + // common/lib/vcon_redis.py:61 _enforce_spec_on_write stamps 0.4.0, + // common/redis_mgr.py:53-57 json_set with keepttl=True when ttl is None. + id: 'transcribe-adds', + label: 'Transcribe adds a transcript', + caption: 'With vendor openai, the transcribe link hands off to its vendor module. That module calls add_analysis for each dialog and then store_vcon. The write stamps vcon 0.4.0 and keeps the TTL.', + duration: 1500, + draw: function (p, ctx) { + var s = ctx.state; + focusLane(ctx, 2); + focusChain(ctx, 0); + deliver(ctx, p, 0, 'transcript', 'analysis'); + highlight(ctx, ['transcript']); + ctx.setText(s.version, p >= 0.6 ? 'vcon: "0.4.0"' : 'vcon: as sent'); + detail(ctx, 'What add_analysis appends', + 'type: "transcript", dialog: 0, vendor: "openai", body, encoding'); + } + }, + { + // conserver/links/analyze/__init__.py:32 analysis_type default summary, + // conserver/links/analyze/__init__.py:37-38 source transcript, + // conserver/links/analyze/__init__.py:181-190 add_analysis, + // conserver/links/analyze/__init__.py:191 store_vcon. + id: 'analyze-adds', + label: 'Analyze adds a summary', + caption: 'The analyze link reads the transcript of each dialog and sends it to a model. It adds the answer with add_analysis, then calls store_vcon. The analysis_type option defaults to summary.', + duration: 1500, + draw: function (p, ctx) { + focusLane(ctx, 2); + focusChain(ctx, 1); + deliver(ctx, p, 1, 'summary', 'analysis'); + highlight(ctx, ['summary']); + detail(ctx, 'What add_analysis appends', + 'type: "summary", dialog: 0, vendor from options, body, encoding: "none"'); + } + }, + { + // conserver/links/tag/__init__.py:39 add_tag, :40 store_vcon. + // common/vcon.py:124-146 add_tag. common/vcon.py:129 builds the entry + // with no party, dialog or start, and common/vcon.py:145 stores the list + // as a JSON string. common/lib/vcon_redis.py:50-58 leaves a string body + // alone. common/vcon.py:177 add_attachment has no caller outside tests. + id: 'tag-writes', + label: 'The tag link writes the tags attachment', + caption: 'add_tag creates one attachment with purpose tags, or extends the one already there. This is the only attachment a link adds. Vcon also has add_attachment, but no code outside tests calls it.', + duration: 1500, + draw: function (p, ctx) { + var s = ctx.state; + focusLane(ctx, 2); + focusChain(ctx, 2); + deliver(ctx, p, 2, 'tags', 'tag'); + ctx.fade(s.unused, ctx.seg(p, 0.7, 1)); + highlight(ctx, ['tags']); + detail(ctx, 'What add_tag writes', + 'purpose: "tags", encoding: "json", body: "[\\"department:sales\\"]"\nThe body is a JSON string, and readers decode it.'); + } + }, + { + // conserver/links/diet/__init__.py:39 remove_attachment_types default [], + // conserver/links/diet/__init__.py:203-208 filter on mime_type, + // conserver/links/diet/__init__.py:199-200 remove_analysis, default false. + // Diet is the only link that assigns to attachments. + id: 'diet-filters', + label: 'Diet filters the listed attachments', + caption: 'An optional diet link drops attachments whose mime_type is in remove_attachment_types. The list is empty by default. A lawful_basis entry stays unless it carries a listed mime_type.', + duration: 1200, + draw: function (p, ctx) { + var s = ctx.state; + focusLane(ctx, 2); + focusChain(ctx, 3); + ctx.show(s.fly, false); + highlight(ctx, p < 1 ? ['lawful', 'tags'] : ['lawful']); + detail(ctx, 'What diet removes here', + 'Nothing in this run. Its options default to removing nothing.'); + } + }, + { + // D07 Running to WrapUp. conserver/main.py:273-274 the last link returned + // an id, conserver/main.py:345 _wrap_up, conserver/main.py:366 egress + // lists first, conserver/main.py:368-382 storages next. + id: 'chain-wraps-up', + label: 'The chain reaches its wrap up', + caption: 'The last link returns the id, so the chain wraps up. The id goes to any egress lists first, where it can feed another chain. The chain storages run next.', + duration: 1200, + draw: function (p, ctx) { + focusLane(ctx, p >= 1 ? 3 : 2); + focusChain(ctx, p >= 1 ? 4 : 3); + moveToken(ctx, 2, 3, p); + highlight(ctx, []); + detail(ctx, 'What stays on the vCon', + 'Each entry added above, and any lawful_basis entry the producer sent.'); + } + }, + { + // D07 WrapUp to Stored. conserver/main.py:410 Storage(name).save(id), + // common/storage/base.py:64-65. A save that raises goes to + // conserver/main.py:429 _dead_letter_storage, shown in M4. + // Egress: common/lib/vcon_egress_compat.py:152 to_configured_legacy, + // common/lib/vcon_egress_compat.py:99-107 renames purpose to type, + // common/lib/vcon_egress_compat.py:72-96 flips encoding json to none, + // common/settings.py:74 EGRESS_FORMAT_VERSION. Callers: + // common/storage/postgres/__init__.py:126, common/storage/s3/__init__.py:92, + // common/storage/elasticsearch/__init__.py:73, + // conserver/links/webhook/__init__.py:42, api/api.py:631, api/api.py:668. + id: 'storage-saves', + label: 'Each storage saves the vCon', + caption: 'Each storage in the chain gets the id through Storage.save. With EGRESS_FORMAT_VERSION set, postgres, s3, elasticsearch, the webhook link and API reads send a 0.0.1 copy. The copy renames purpose to type and keeps the body value.', + duration: 1400, + draw: function (p, ctx) { + focusLane(ctx, p >= 1 ? 4 : 3); + focusChain(ctx, 4); + moveToken(ctx, 3, 4, p); + highlight(ctx, ['lawful']); + detail(ctx, 'What a 0.0.1 egress copy holds', + 'type: "lawful_basis", the same body value, encoding: "none"\nThe copy in Redis stays at 0.4.0 with purpose.'); + } + }, + { + // common/storage/utopia/__init__.py:156-184 _lawful_basis reads the entry, + // :184 returns the none recorded sentence, :251-252 adds it to the text, + // :52 require_analysis_grant defaults to False, :327-329 skips the upload. + // Edition boundary: the adapter option reads a basis and manages nothing. + id: 'utopia-renders', + label: 'Utopia renders an existing basis', + caption: 'If the chain uses the utopia adapter, it reads the attachment and prints one sentence about it, or "Lawful basis: none recorded." With require_analysis_grant set, it skips the upload when no basis grants analysis. That option defaults to false. The server creates no basis and manages no consent.', + duration: 1000, + hold: 1500, + draw: function (p, ctx) { + var s = ctx.state; + focusLane(ctx, 4); + s.lane[4].setState('done'); + focusChain(ctx, 4); + s.chain[4].setLabel('utopia adapter', 'reads and renders'); + highlight(ctx, ['lawful']); + s.token.setState('done'); + detail(ctx, 'What the server leaves out', + 'It does not create a basis, or validate, enforce or manage consent.\nThat holds whether or not a basis arrived.'); + } + } + ] + }); +}()); diff --git a/docs/visuals/motion/scenes/m4-dlq-recovery.js b/docs/visuals/motion/scenes/m4-dlq-recovery.js new file mode 100644 index 00000000..674f7018 --- /dev/null +++ b/docs/visuals/motion/scenes/m4-dlq-recovery.js @@ -0,0 +1,424 @@ +/* M4. A failed vCon reaches the DLQ and returns. Twins: D08, D09. + + One vCon id walks both dead letter paths. Each step comment names the code + it draws. Line numbers are from this worktree, base commit 323109a. + + Left out on purpose, as in the twins or to keep one storyline: + - Skipped by hook, halted by a link, shutdown LPUSH (D08 only). + - A tracer with dlq_vcon_on_error, or an egress enqueue, can also raise into + the ingress DLQ: conserver/main.py:545-546, conserver/main.py:361-366. + - POST /dlq/storage/reprocess returns 404 for an unknown backend and 409 when + the lock is held: api/api.py:1212-1216, api/api.py:1222-1223. D09 draws both. + - HTTP 500 on a Redis error during replay: api/api.py:1242-1246. + + No vCon is built here. The tokens carry an id and nothing else. */ +(function () { + 'use strict'; + + var ROW = 110; // top of the worker row + var HOLD = 1500; // reading time after a step + var PARK = { + ingress: [89, ROW], + worker: [250, ROW], + links: [406, ROW], + wrap: [562, ROW], + dlq: [466, 290], + storageDlq: [800, 290], + backendA: [880, 44], + backendB: [880, 144] + }; + + // Moves a token from one parking spot, along an edge, to the next spot. + function travel(ctx, token, edge, from, to, p) { + var start = edge.pointAt(0); + var end = edge.pointAt(1); + if (p <= 0.12) { + var a = ctx.seg(p, 0, 0.12); + token.at(ctx.lerp(from[0], start[0], a), ctx.lerp(from[1], start[1], a)); + } else if (p < 0.85) { + token.follow(edge, ctx.ease(ctx.seg(p, 0.12, 0.85))); + } else { + var c = ctx.seg(p, 0.85, 1); + token.at(ctx.lerp(end[0], to[0], c), ctx.lerp(end[1], to[1], c)); + } + } + + // Sets the panel that lists where this one id sits. + function redis(ctx, values) { + var r = ctx.state.redis; + ['ingress', 'dlq', 'storageDlq', 'ttl'].forEach(function (key) { + if (values[key] !== undefined) { ctx.setText(r[key], values[key]); } + }); + } + + function exchange(ctx, request, response) { + ctx.setText(ctx.state.request, request ? 'Request: ' + request : ''); + ctx.setText(ctx.state.response, response ? 'Response: ' + response : ''); + } + + // Runs the request card from the operator, through the API, to a target list. + function call(ctx, label, target, p) { + var s = ctx.state; + var going = p < 1; + s.t.request.setLabel(label); + ctx.show(s.t.request, going); + s.e.operatorApi.setState(going ? 'active' : 'idle'); + target.setState(going ? 'active' : 'idle'); + s.n.operator.setState('active'); + s.n.api.setState('active'); + if (p < 0.5) { + s.t.request.follow(s.e.operatorApi, ctx.ease(ctx.seg(p, 0, 0.5))); + } else { + s.t.request.follow(target, ctx.ease(ctx.seg(p, 0.5, 1))); + } + } + + function operatorIdle(ctx) { + ctx.state.n.operator.setState('idle'); + ctx.state.n.api.setState('idle'); + } + + VconMotion.register({ + id: 'm4', + title: 'A failed vCon reaches the DLQ and returns', + summary: 'One vCon id fails in a link and returns through the ingress DLQ, then fails a storage write and returns through the storage DLQ.', + twins: ['D08-dead-letter-flow', 'D09-storage-write-recovery'], + + setup: function (ctx) { + var s = ctx.state; + var n = { + ingress: ctx.node({ x: 24, y: ROW, w: 130, label: 'Ingress list', sub: '' }), + worker: ctx.node({ x: 190, y: ROW, w: 120, label: 'Worker', sub: 'BLPOP' }), + links: ctx.node({ x: 346, y: ROW, w: 120, label: 'Links', sub: 'run in order' }), + wrap: ctx.node({ x: 502, y: ROW, w: 120, label: 'Wrap-up', sub: 'egress, storage' }), + egress: ctx.node({ x: 482, y: 16, w: 160, h: 52, label: 'Egress lists', sub: 'if the chain has any' }), + backendA: ctx.node({ x: 770, y: 50, w: 160, h: 60, label: 'Backend A', sub: 'storage adapter' }), + backendB: ctx.node({ x: 770, y: 150, w: 160, h: 60, label: 'Backend B', sub: 'storage adapter' }), + dlq: ctx.node({ x: 306, y: 290, w: 200, label: 'Ingress DLQ', sub: 'DLQ:' }), + storageDlq: ctx.node({ x: 640, y: 290, w: 220, label: 'Storage DLQ', sub: 'DLQ:storage:' }), + operator: ctx.node({ x: 24, y: 420, w: 130, label: 'Operator' }), + api: ctx.node({ x: 326, y: 420, w: 160, label: 'API', sub: '/dlq routes' }) + }; + s.n = n; + + s.e = { + ingressWorker: ctx.edge({ from: n.ingress.right, to: n.worker.left }), + workerLinks: ctx.edge({ from: n.worker.right, to: n.links.left }), + linksWrap: ctx.edge({ from: n.links.right, to: n.wrap.left }), + wrapEgress: ctx.edge({ from: n.wrap.top, to: n.egress.bottom }), + wrapA: ctx.edge({ from: [622, 130], via: [[700, 130], [700, 80]], to: n.backendA.left }), + wrapB: ctx.edge({ from: [622, 154], via: [[700, 154], [700, 180]], to: n.backendB.left }), + linksDlq: ctx.edge({ from: n.links.bottom, to: n.dlq.top }), + wrapStorageDlq: ctx.edge({ from: n.wrap.bottom, via: [[562, 308]], to: [640, 308] }), + dlqIngress: ctx.edge({ from: n.dlq.left, via: [[89, 322]], to: n.ingress.bottom, dashed: true }), + storageDlqB: ctx.edge({ from: [850, 290], to: [850, 210], dashed: true }), + operatorApi: ctx.edge({ from: n.operator.right, to: n.api.left }), + apiDlq: ctx.edge({ from: n.api.top, to: n.dlq.bottom, dashed: true }), + apiStorageDlq: ctx.edge({ from: n.api.right, via: [[600, 452], [600, 338]], to: [640, 338], dashed: true }) + }; + + function edgeNote(x, y, text, anchor) { + ctx.text({ x: x, y: y, text: text, kind: 'small', anchor: anchor, parent: ctx.layers.edges }); + } + edgeNote(414, 236, 'link raises'); + edgeNote(570, 250, 'backend save raises'); + edgeNote(858, 254, 'write only'); + edgeNote(197, 314, 'POST /dlq/reprocess', 'middle'); + edgeNote(197, 340, 'LPOP, RPUSH, chain reruns', 'middle'); + + // Panel with the position of this id, so state never rests on colour. + ctx.el('rect', { + x: 640, y: 392, width: 296, height: 128, rx: 4, + fill: ctx.tokens.surface, stroke: ctx.tokens.muted + }, ctx.layers.back); + ctx.text({ x: 654, y: 416, text: 'Redis state for this id', kind: 'label' }); + function row(y, name, value) { + ctx.text({ x: 654, y: y, text: name, kind: 'small' }); + return ctx.text({ x: 922, y: y, text: value, kind: 'small', anchor: 'end' }); + } + s.redis = { + ingress: row(442, 'Ingress list', '1 id'), + dlq: row(464, 'DLQ:', 'empty'), + storageDlq: row(486, 'DLQ:storage:', 'empty'), + // api/api.py:789 and :893 cache the body with this TTL, api/api.py:450-452. + // Link writes keep the TTL: common/lib/vcon_redis.py:108, common/redis_mgr.py:56-57. + ttl: row(508, 'Body TTL', 'VCON_REDIS_EXPIRY') + }; + + s.lock = ctx.text({ x: 750, y: 372, text: '', kind: 'small', anchor: 'middle' }); + s.request = ctx.text({ x: 24, y: 508, text: '' }); + s.response = ctx.text({ x: 24, y: 528, text: '' }); + + s.t = { + id: ctx.token({ x: PARK.ingress[0], y: PARK.ingress[1], label: 'vCon id' }), + egress: ctx.token({ label: 'vCon id', hidden: true }), + backendA: ctx.token({ label: 'vCon id', hidden: true }), + retry: ctx.token({ label: 'vCon id', hidden: true }), + request: ctx.token({ label: 'POST', w: 56, hidden: true }) + }; + + n.ingress.setState('active'); + }, + + steps: [ + { + // conserver/main.py:875 queue.dequeue, common/lib/queue.py:81-90 BLPOP. + // common/lib/queue.py:41-42 builds the body key vcon:. + id: 'pop', + label: 'A worker pops the id', + caption: 'A worker takes the vCon id from the head of the ingress list with BLPOP. Lists hold ids only, and the body stays at vcon:.', + duration: 1400, + hold: HOLD, + draw: function (p, ctx) { + var s = ctx.state; + s.e.ingressWorker.setState(p < 1 ? 'active' : 'idle'); + travel(ctx, s.t.id, s.e.ingressWorker, PARK.ingress, PARK.worker, p); + if (p >= 1) { + s.n.ingress.setState('idle'); + s.n.worker.setState('active'); + redis(ctx, { ingress: 'empty' }); + } + } + }, + { + // conserver/main.py:255-263 runs the links in order. + // conserver/main.py:646-670 _process_link logs and re-raises. + // conserver/main.py:754 _handle_vcon catches it. + id: 'link-raises', + label: 'A link raises an exception', + caption: 'A link raises, so the chain stops and the later links never run. The worker catches the exception in _handle_vcon.', + duration: 1400, + hold: HOLD, + draw: function (p, ctx) { + var s = ctx.state; + s.e.workerLinks.setState(p < 1 ? 'active' : 'idle'); + travel(ctx, s.t.id, s.e.workerLinks, PARK.worker, PARK.links, p); + if (p >= 1) { + s.n.worker.setState('idle'); + s.n.links.setState('fail'); + s.n.links.setLabel('Links', 'link raised'); + s.t.id.setState('fail'); + } + } + }, + { + // conserver/main.py:761 enqueue_dlq, common/lib/queue.py:92-109 RPUSH and + // conserver.dlq.count, common/dlq_utils.py:3-4 the name. + // conserver/main.py:762-763 EXPIRE when VCON_DLQ_EXPIRY > 0, plain EXPIRE + // at common/lib/queue.py:143-145, default at common/settings.py:56. + id: 'ingress-dlq', + label: 'The id lands on the ingress DLQ', + caption: 'The worker pushes the id onto DLQ: with RPUSH. It then resets the body TTL to VCON_DLQ_EXPIRY, 604800 seconds by default, unless that setting is 0.', + duration: 1400, + hold: HOLD, + draw: function (p, ctx) { + var s = ctx.state; + s.e.linksDlq.setState(p < 1 ? 'fail' : 'idle'); + travel(ctx, s.t.id, s.e.linksDlq, PARK.links, PARK.dlq, p); + if (p >= 1) { + s.n.links.setState('idle'); + s.n.links.setLabel('Links', 'run in order'); + s.n.dlq.setState('active'); + redis(ctx, { dlq: '1 id', ttl: 'VCON_DLQ_EXPIRY' }); + } + } + }, + { + // api/api.py:1269-1296 GET /dlq, LRANGE 0 -1, no write. + id: 'ingress-read', + label: 'The operator reads the ingress DLQ', + caption: 'GET /dlq returns the waiting ids with LRANGE. The call only reads, so the list keeps every id.', + duration: 1200, + hold: HOLD, + draw: function (p, ctx) { + call(ctx, 'GET', ctx.state.e.apiDlq, p); + exchange(ctx, 'GET /dlq?ingress_list=', p >= 1 ? '200, JSON list of ids' : ''); + } + }, + { + // api/api.py:1142-1182 POST /dlq/reprocess, count from 1 to 100000, default + // 1000. api/api.py:1168 dequeue_dlq_async is LPOP, common/lib/queue.py:163-173. + // api/api.py:1171 enqueue_async is RPUSH, common/lib/queue.py:149-158. + // These are two commands per id, not one atomic step. Returns the count moved. + id: 'ingress-replay', + label: 'The operator replays the ingress DLQ', + caption: 'POST /dlq/reprocess moves up to count ids, 1000 by default, with LPOP then RPUSH. The id joins the tail of its ingress list.', + duration: 2000, + hold: HOLD, + draw: function (p, ctx) { + var s = ctx.state; + call(ctx, 'POST', s.e.apiDlq, ctx.seg(p, 0, 0.45)); + exchange(ctx, 'POST /dlq/reprocess?ingress_list=&count=N', p >= 1 ? '200 with the number moved, 1' : ''); + s.e.dlqIngress.setState(p > 0.45 && p < 1 ? 'active' : 'idle'); + if (p > 0.45) { + s.t.id.setState('idle'); + travel(ctx, s.t.id, s.e.dlqIngress, PARK.dlq, PARK.ingress, ctx.seg(p, 0.45, 1)); + } + if (p >= 1) { + s.n.dlq.setState('idle'); + s.n.ingress.setState('active'); + redis(ctx, { ingress: '1 id', dlq: 'empty' }); + } + } + }, + { + // conserver/main.py:875 pops again. conserver/main.py:255 loops from link 0. + // conserver/main.py:273-274 reaches _wrap_up when every link returned an id. + // A link that still raises sends the id back to the ingress DLQ. + id: 'chain-reruns', + label: 'A worker reruns the whole chain', + caption: 'A worker pops the id again and every link runs from the first one. Each link returns the id this time, so the worker reaches wrap-up.', + duration: 2400, + hold: HOLD, + draw: function (p, ctx) { + var s = ctx.state; + operatorIdle(ctx); + exchange(ctx, '', ''); + s.n.ingress.setState(p < 0.33 ? 'active' : 'idle'); + s.n.worker.setState(p >= 0.33 && p < 0.66 ? 'active' : 'idle'); + s.n.links.setState(p >= 0.66 && p < 1 ? 'active' : 'idle'); + s.e.ingressWorker.setState(p < 0.33 ? 'active' : 'idle'); + s.e.workerLinks.setState(p >= 0.33 && p < 0.66 ? 'active' : 'idle'); + s.e.linksWrap.setState(p >= 0.66 && p < 1 ? 'active' : 'idle'); + if (p < 0.33) { + travel(ctx, s.t.id, s.e.ingressWorker, PARK.ingress, PARK.worker, ctx.seg(p, 0, 0.33)); + } else if (p < 0.66) { + travel(ctx, s.t.id, s.e.workerLinks, PARK.worker, PARK.links, ctx.seg(p, 0.33, 0.66)); + } else { + travel(ctx, s.t.id, s.e.linksWrap, PARK.links, PARK.wrap, ctx.seg(p, 0.66, 1)); + } + if (p >= 0.33) { redis(ctx, { ingress: 'empty' }); } + if (p >= 1) { s.n.wrap.setState('active'); } + } + }, + { + // conserver/main.py:352-366 egress RPUSH, storage starts at conserver/main.py:368. + id: 'egress', + label: 'Wrap-up feeds the egress lists', + caption: 'Wrap-up pushes the id onto any egress lists in the chain first. Storage writes start only after that.', + duration: 1100, + hold: HOLD, + draw: function (p, ctx) { + var s = ctx.state; + s.e.wrapEgress.setState(p < 1 ? 'active' : 'idle'); + ctx.show(s.t.egress, p < 1); + s.t.egress.follow(s.e.wrapEgress, ctx.ease(p)); + if (p >= 1) { + s.n.egress.setState('done'); + s.n.egress.setLabel('Egress lists', 'id pushed'); + } + } + }, + { + // conserver/main.py:376-382 threads when parallel storage is on and there + // are two or more backends, common/config.py:24, default at common/settings.py:66. + // conserver/main.py:410 Storage(name).save, common/storage/base.py:63-65. + // conserver/main.py:411 catches the exception, outcome=error at :412. + id: 'backends', + label: 'One backend rejects the write', + caption: 'Each backend gets its own save, in parallel by default when the chain has two or more. Backend A returns and Backend B raises.', + duration: 1800, + hold: HOLD, + draw: function (p, ctx) { + var s = ctx.state; + var out = ctx.seg(p, 0, 0.6); + var bounce = ctx.seg(p, 0.6, 1); + ctx.show(s.t.backendA, true); + s.e.wrapA.setState(p < 0.6 ? 'active' : 'idle'); + s.e.wrapB.setState(p < 0.6 ? 'active' : (p < 1 ? 'fail' : 'idle')); + travel(ctx, s.t.backendA, s.e.wrapA, PARK.wrap, PARK.backendA, out); + if (p < 0.6) { + s.t.id.follow(s.e.wrapB, ctx.ease(out)); + } else { + s.t.id.follow(s.e.wrapB, 1 - ctx.ease(bounce)); + } + if (p >= 0.6) { + s.t.backendA.setState('done'); + s.n.backendA.setState('done'); + s.n.backendA.setLabel('Backend A', 'saved'); + s.n.backendB.setState('fail'); + s.n.backendB.setLabel('Backend B', 'write raised'); + s.t.id.setState('fail'); + } + if (p >= 1) { s.t.id.at(PARK.wrap[0], PARK.wrap[1]); } + } + }, + { + // conserver/main.py:429 _dead_letter_storage, conserver/main.py:446-449. + // common/lib/queue.py:121-132 one EVAL: TTL -2 returns -1, else EXPIRE only + // when retention > 0 and 0 <= ttl < retention, then RPUSH. The TTL row stays + // VCON_DLQ_EXPIRY because this id already carries that setting. + // common/lib/queue.py:133-134 ValueError on -1, conserver/main.py:450-456 + // logs manual recovery and never re-raises. + // conserver/main.py:425-429 is why the ingress DLQ stays out of this. + id: 'storage-dlq', + label: 'The id lands on the storage DLQ', + caption: 'One atomic script raises a TTL below VCON_DLQ_EXPIRY and pushes the id onto DLQ:storage:, or the worker logs for manual recovery when the body is gone. Nothing re-raises, so the chain does not rerun.', + duration: 1500, + hold: HOLD, + draw: function (p, ctx) { + var s = ctx.state; + s.e.wrapStorageDlq.setState(p < 1 ? 'fail' : 'idle'); + travel(ctx, s.t.id, s.e.wrapStorageDlq, PARK.wrap, PARK.storageDlq, p); + if (p >= 1) { + s.n.wrap.setState('idle'); + s.n.storageDlq.setState('active'); + redis(ctx, { storageDlq: '1 id' }); + } + } + }, + { + // api/api.py:1185-1202 POST /dlq/storage/reprocess, api/api.py:1221 lock with + // no expiry, api/api.py:1230 LRANGE snapshot, api/api.py:1233 save in the + // threadpool, api/api.py:1234-1238 warning then break, api/api.py:1241 returns + // the count, api/api.py:1245-1246 releases the lock. + id: 'retry-fails', + label: 'The backend refuses the first retry', + caption: 'POST /dlq/storage/reprocess takes the replay lock, snapshots ids with LRANGE and calls save. The save raises, so the batch stops, the id stays on the list and the response is 200 with 0.', + duration: 2400, + hold: HOLD, + draw: function (p, ctx) { + var s = ctx.state; + var out = ctx.seg(p, 0.4, 0.75); + call(ctx, 'POST', s.e.apiStorageDlq, ctx.seg(p, 0, 0.4)); + exchange(ctx, 'POST /dlq/storage/reprocess?storage_name=&count=N', p >= 1 ? '200 with the number written, 0' : ''); + if (p >= 0.4) { ctx.setText(s.lock, p >= 1 ? 'Replay lock released' : 'Replay lock held'); } + s.e.storageDlqB.setState(p > 0.4 && p < 0.75 ? 'active' : (p >= 0.75 && p < 1 ? 'fail' : 'idle')); + ctx.show(s.t.retry, p > 0.4 && p < 1); + s.t.retry.setState(p >= 0.75 ? 'fail' : 'idle'); + s.t.retry.follow(s.e.storageDlqB, p < 0.75 ? ctx.ease(out) : 1 - ctx.ease(ctx.seg(p, 0.75, 1))); + s.n.backendB.setLabel('Backend B', p >= 0.75 ? 'retry raised' : 'write raised'); + } + }, + { + // Same route as the step before. api/api.py:1233 save returns, + // api/api.py:1239-1240 LREM one entry, api/api.py:1241 returns the count. + // Replay is at-least-once, api/api.py:1227-1229. + id: 'retry-succeeds', + label: 'A second retry clears the entry', + caption: 'The backend is healthy again, so save returns and LREM removes the id. Only the write ran, not the chain, and the response is 200 with 1.', + duration: 2200, + hold: HOLD, + draw: function (p, ctx) { + var s = ctx.state; + call(ctx, 'POST', s.e.apiStorageDlq, ctx.seg(p, 0, 0.4)); + exchange(ctx, 'POST /dlq/storage/reprocess?storage_name=&count=N', p >= 1 ? '200 with the number written, 1' : ''); + if (p >= 0.4) { ctx.setText(s.lock, p >= 1 ? 'Replay lock released' : 'Replay lock held'); } + s.e.storageDlqB.setState(p > 0.4 && p < 1 ? 'active' : 'idle'); + if (p > 0.4) { + s.t.id.setState('idle'); + travel(ctx, s.t.id, s.e.storageDlqB, PARK.storageDlq, PARK.backendB, ctx.seg(p, 0.4, 1)); + } + if (p >= 1) { + operatorIdle(ctx); + s.t.id.setState('done'); + s.n.storageDlq.setState('idle'); + s.n.backendB.setState('done'); + s.n.backendB.setLabel('Backend B', 'saved'); + redis(ctx, { storageDlq: 'empty' }); + } + } + } + ] + }); +}()); diff --git a/docs/visuals/motion/screenshots/m1-chain-run.png b/docs/visuals/motion/screenshots/m1-chain-run.png new file mode 100644 index 00000000..b7409e40 Binary files /dev/null and b/docs/visuals/motion/screenshots/m1-chain-run.png differ diff --git a/docs/visuals/motion/screenshots/m2-workers.png b/docs/visuals/motion/screenshots/m2-workers.png new file mode 100644 index 00000000..b7513b24 Binary files /dev/null and b/docs/visuals/motion/screenshots/m2-workers.png differ diff --git a/docs/visuals/motion/screenshots/m3-vcon-assembly.png b/docs/visuals/motion/screenshots/m3-vcon-assembly.png new file mode 100644 index 00000000..c1f74d9e Binary files /dev/null and b/docs/visuals/motion/screenshots/m3-vcon-assembly.png differ diff --git a/docs/visuals/motion/screenshots/m4-dlq-recovery.png b/docs/visuals/motion/screenshots/m4-dlq-recovery.png new file mode 100644 index 00000000..539e053b Binary files /dev/null and b/docs/visuals/motion/screenshots/m4-dlq-recovery.png differ diff --git a/docs/visuals/motion/shell.css b/docs/visuals/motion/shell.css new file mode 100644 index 00000000..be0b74a6 --- /dev/null +++ b/docs/visuals/motion/shell.css @@ -0,0 +1,349 @@ +/* Motion player styles. Brand tokens, page layout and the SVG classes used by + the ctx helpers in shell.js. Everything loads from this folder, so the page + works over file:// with no network. */ + +@font-face { + font-family: "Anton"; + src: url("fonts/Anton-Regular.ttf") format("truetype"); + font-weight: 400 800; + font-style: normal; + font-display: swap; +} + +@font-face { + font-family: "Inter"; + src: url("fonts/Inter-VariableFont_opsz_wght.ttf") format("truetype"); + font-weight: 100 900; + font-style: normal; + font-display: swap; +} + +:root { + color-scheme: light; + + --mo-green: #0BB81E; + --mo-green-deep: #0A7D18; + --mo-ink: #292929; + --mo-body: #33363B; + --mo-muted: #8A8A8D; + --mo-surface: #F3F4F6; + --mo-white: #FFFFFF; + --mo-green-tint: rgba(11, 184, 30, 0.14); + --mo-rule: rgba(17, 17, 17, 0.10); + + --mo-font-display: "Anton", Impact, "Helvetica Neue", sans-serif; + --mo-font-body: "Inter", Helvetica, Arial, sans-serif; + + --mo-ease: cubic-bezier(.2, .7, .2, 1); + --mo-fast: 0.25s; +} + +*, *::before, *::after { box-sizing: border-box; } + +body { + margin: 0; + background: var(--mo-white); + color: var(--mo-body); + font-family: var(--mo-font-body); + font-size: 16px; + line-height: 1.6; +} + +/* ---------- Page ---------- */ + +.mo-header, .mo-main { + max-width: 1280px; + margin: 0 auto; + padding: 0 32px; +} + +.mo-header { padding-top: 48px; padding-bottom: 28px; } + +.mo-eyebrow, .mo-label { + margin: 0 0 14px; + font-size: 13px; + font-weight: 700; + line-height: 1.35; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.mo-eyebrow { color: var(--mo-green-deep); } +.mo-label { color: var(--mo-body); } + +/* Signature bar above the display heading. Anton stays at 40px or larger. */ +.mo-display { + position: relative; + margin: 0; + padding-top: 26px; + color: var(--mo-ink); + font-family: var(--mo-font-display); + font-size: clamp(40px, 4.2vw, 60px); + font-weight: 800; + line-height: 1.05; + letter-spacing: -0.01em; + text-transform: uppercase; + text-wrap: balance; +} + +.mo-display::before { + content: ""; + position: absolute; + top: 0; + left: 0; + width: 64px; + height: 4px; + background: var(--mo-green); +} + +.mo-accent { color: var(--mo-green-deep); } + +/* ---------- Tabs ---------- */ + +.mo-tabs { + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + gap: 8px; + margin-bottom: 28px; +} + +.mo-tab { + padding: 12px 14px; + border: 0; + border-top: 4px solid var(--mo-rule); + background: var(--mo-surface); + color: var(--mo-body); + font: inherit; + font-size: 14px; + line-height: 1.35; + text-align: left; + cursor: pointer; + transition: border-color var(--mo-fast) var(--mo-ease); +} + +.mo-tab:hover { border-top-color: var(--mo-green); } + +.mo-tab[aria-selected="true"] { + border-top-color: var(--mo-green-deep); + background: var(--mo-white); + color: var(--mo-ink); + font-weight: 600; +} + +.mo-tab-id { + display: block; + color: var(--mo-green-deep); + font-size: 13px; + font-weight: 700; + letter-spacing: 0.08em; +} + +/* ---------- Player ---------- */ + +.mo-player { + display: grid; + grid-template-columns: minmax(0, 1fr) 320px; + gap: 40px; + padding-bottom: 64px; +} + +.mo-primary { min-width: 0; } + +.mo-title { + margin: 0 0 6px; + color: var(--mo-ink); + font-size: 24px; + font-weight: 800; + line-height: 1.2; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.mo-summary { margin: 0 0 18px; } + +/* The stage keeps a readable size on phones and scrolls inside its own frame, + so the page itself never scrolls sideways. */ +.mo-stage { + overflow-x: auto; + background: var(--mo-surface); +} + +.mo-stage svg { + display: block; + width: 100%; + min-width: 640px; + height: auto; +} + +/* Shown only where the stage is narrower than its 640px minimum. */ +.mo-hint { display: none; margin: 6px 0; font-size: 13px; } + +.mo-progress { height: 4px; background: var(--mo-rule); } +.mo-progress-bar { width: 0; height: 100%; background: var(--mo-green); } + +.mo-controls { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + margin-top: 16px; +} + +.mo-btn { + min-height: 44px; + padding: 10px 22px; + border: 2px solid var(--mo-ink); + border-radius: 999px; + background: var(--mo-white); + color: var(--mo-ink); + font-family: var(--mo-font-body); + font-size: 13px; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; + cursor: pointer; + transition: transform var(--mo-fast) var(--mo-ease), + background var(--mo-fast) var(--mo-ease); +} + +.mo-btn:hover:not(:disabled) { transform: translateY(-2px); } +.mo-btn:active:not(:disabled) { transform: translateY(0); } +.mo-btn:disabled { border-color: var(--mo-muted); color: var(--mo-muted); cursor: default; } + +/* White on the vivid green fails contrast, so the filled button uses deep green. */ +.mo-btn--primary { + min-width: 104px; + border-color: var(--mo-green-deep); + background: var(--mo-green-deep); + color: var(--mo-white); +} + +.mo-btn--primary:disabled { background: var(--mo-muted); color: var(--mo-white); } + +.mo-status { + margin-left: auto; + font-size: 13px; + font-variant-numeric: tabular-nums; +} + +.mo-caption { + min-height: 3.2em; + margin: 16px 0 0; + color: var(--mo-ink); + font-size: 18px; + line-height: 1.5; +} + +.mo-notice { + margin: 12px 0 0; + padding-left: 12px; + border-left: 4px solid var(--mo-green); + font-size: 14px; +} + +.mo-error { + margin: 0; + padding: 48px 32px; + color: var(--mo-ink); +} + +/* ---------- Side rail ---------- */ + +.mo-steps { + margin: 0 0 28px; + padding: 0; + list-style: none; +} + +.mo-step { + display: block; + width: 100%; + padding: 10px 12px; + border: 0; + border-left: 4px solid var(--mo-rule); + background: none; + color: var(--mo-body); + font: inherit; + font-size: 14px; + line-height: 1.45; + text-align: left; + cursor: pointer; +} + +.mo-step strong { display: block; color: var(--mo-ink); font-weight: 600; } +.mo-step:hover { border-left-color: var(--mo-green); } + +.mo-step[aria-current="step"] { + border-left-color: var(--mo-green-deep); + background: var(--mo-surface); +} + +.mo-twins { margin: 0; font-size: 14px; } +.mo-twins a { margin-right: 14px; color: var(--mo-green-deep); font-weight: 600; } + +:focus-visible { + outline: 3px solid var(--mo-green-deep); + outline-offset: 2px; +} + +/* ---------- SVG classes used by the ctx helpers ---------- */ + +.mo-svg-text { fill: var(--mo-body); font-family: var(--mo-font-body); font-size: 14px; } +.mo-svg-text--label { fill: var(--mo-ink); font-size: 15px; font-weight: 600; } +.mo-svg-text--title { + fill: var(--mo-ink); + font-size: 13px; + font-weight: 700; + letter-spacing: 0.08em; + text-transform: uppercase; +} +.mo-svg-text--small { font-size: 12px; } + +.mo-node rect { fill: var(--mo-white); stroke: var(--mo-ink); stroke-width: 1.5; } +.mo-node .mo-node-label { fill: var(--mo-ink); font-family: var(--mo-font-body); font-size: 15px; font-weight: 600; } +.mo-node .mo-node-sub { fill: var(--mo-body); font-family: var(--mo-font-body); font-size: 12px; } +.mo-node--active rect { fill: #E2F6E4; stroke: var(--mo-green-deep); stroke-width: 3; } +.mo-node--done rect { stroke: var(--mo-green-deep); stroke-width: 2; } +.mo-node--fail rect { fill: var(--mo-ink); stroke: var(--mo-ink); stroke-dasharray: 6 4; } +.mo-node--fail .mo-node-label, .mo-node--fail .mo-node-sub { fill: var(--mo-white); } +.mo-node--muted { opacity: 0.45; } + +.mo-edge path { fill: none; stroke: var(--mo-muted); stroke-width: 2; } +.mo-edge polygon { fill: var(--mo-muted); } +.mo-edge text { fill: var(--mo-body); font-family: var(--mo-font-body); font-size: 12px; } +.mo-edge--dashed path { stroke-dasharray: 6 5; } +.mo-edge--active path { stroke: var(--mo-green-deep); stroke-width: 3; } +.mo-edge--active polygon { fill: var(--mo-green-deep); } +.mo-edge--fail path { stroke: var(--mo-ink); stroke-width: 3; stroke-dasharray: 6 4; } +.mo-edge--fail polygon { fill: var(--mo-ink); } +.mo-edge--muted { opacity: 0.45; } + +.mo-token rect { fill: var(--mo-green-deep); } +.mo-token text { fill: var(--mo-white); font-family: var(--mo-font-body); font-size: 12px; font-weight: 700; } +.mo-token--done rect { fill: var(--mo-white); stroke: var(--mo-green-deep); stroke-width: 2; } +.mo-token--done text { fill: var(--mo-green-deep); } +.mo-token--fail rect { fill: var(--mo-ink); } +.mo-token--muted { opacity: 0.45; } + +/* ---------- Responsive ---------- */ + +@media (max-width: 980px) { + .mo-player { grid-template-columns: minmax(0, 1fr); gap: 28px; } + .mo-tabs { grid-template-columns: repeat(2, minmax(0, 1fr)); } +} + +@media (max-width: 704px) { + .mo-hint { display: block; } +} + +@media (max-width: 540px) { + .mo-header, .mo-main { padding-left: 16px; padding-right: 16px; } + .mo-header { padding-top: 32px; } + .mo-status { flex-basis: 100%; margin-left: 0; } + .mo-btn { padding: 10px 16px; } +} + +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { animation: none !important; transition: none !important; } + .mo-btn:hover:not(:disabled) { transform: none; } +} diff --git a/docs/visuals/motion/shell.js b/docs/visuals/motion/shell.js new file mode 100644 index 00000000..e8ce29c1 --- /dev/null +++ b/docs/visuals/motion/shell.js @@ -0,0 +1,632 @@ +/* Motion player shell. Plain script, no modules, so it runs over file://. + Exposes window.VconMotion. scene-authoring.md in this folder defines the scene API. */ +(function (global) { + 'use strict'; + + var SVG_NS = 'http://www.w3.org/2000/svg'; + var DEFAULT_HOLD = 700; // ms pause after a step while playing + var REDUCED_MIN_HOLD = 2500; // ms a step stays up when motion is reduced + var MAX_FRAME = 100; // ms, so a stalled tab does not jump a step + + var TOKENS = Object.freeze({ + green: '#0BB81E', + greenDeep: '#0A7D18', + ink: '#292929', + body: '#33363B', + muted: '#8A8A8D', + surface: '#F3F4F6', + white: '#FFFFFF' + }); + + var scenes = {}; + var dom = {}; + var motionQuery = global.matchMedia + ? global.matchMedia('(prefers-reduced-motion: reduce)') + : { matches: false }; + + // Player state. cursor counts finished steps, from 0 to steps.length. + var scene = null; + var sceneId = null; + var ctx = null; + var cursor = 0; + var progress = 0; + var elapsed = 0; + var holdLeft = 0; + var playing = false; + var rafId = null; + var lastTs = null; + var errorText = null; + + /* ---------- Maths ---------- */ + + function clamp(v, lo, hi) { + if (lo === undefined) { lo = 0; } + if (hi === undefined) { hi = 1; } + return Math.min(hi, Math.max(lo, v)); + } + + function lerp(a, b, p) { return a + (b - a) * p; } + + // Maps p to 0..1 across the window a..b of a step. + function seg(p, a, b) { return clamp((p - a) / (b - a)); } + + function bezier(a, b, t) { + var u = 1 - t; + return 3 * u * u * t * a + 3 * u * t * t * b + t * t * t; + } + + // Brand easing, cubic-bezier(.2, .7, .2, 1). + function ease(p) { + if (p <= 0) { return 0; } + if (p >= 1) { return 1; } + var lo = 0; + var hi = 1; + for (var i = 0; i < 24; i++) { + var mid = (lo + hi) / 2; + if (bezier(0.2, 0.2, mid) < p) { lo = mid; } else { hi = mid; } + } + return bezier(0.7, 1, (lo + hi) / 2); + } + + /* ---------- Stage helpers handed to scenes as ctx ---------- */ + + function setAttrs(node, attrs) { + Object.keys(attrs || {}).forEach(function (key) { + node.setAttribute(key, attrs[key]); + }); + return node; + } + + function createCtx(svg, width, height) { + function layer(name) { + var g = document.createElementNS(SVG_NS, 'g'); + g.setAttribute('data-layer', name); + svg.appendChild(g); + return g; + } + + var layers = { + back: layer('back'), + edges: layer('edges'), + nodes: layer('nodes'), + tokens: layer('tokens'), + notes: layer('notes') + }; + + function el(tag, attrs, parent) { + var node = setAttrs(document.createElementNS(SVG_NS, tag), attrs); + (parent || layers.notes).appendChild(node); + return node; + } + + function setText(node, value) { + var x = node.getAttribute('x') || 0; + while (node.firstChild) { node.removeChild(node.firstChild); } + String(value).split('\n').forEach(function (line, i) { + var span = el('tspan', { x: x, dy: i === 0 ? 0 : '1.3em' }, node); + span.textContent = line; + }); + return node; + } + + function text(opts) { + var cls = 'mo-svg-text' + (opts.kind ? ' mo-svg-text--' + opts.kind : ''); + var node = el('text', { + x: opts.x, + y: opts.y, + 'class': cls, + 'text-anchor': opts.anchor || 'start' + }, opts.parent); + return setText(node, opts.text); + } + + function stateSetter(target, base) { + return function (state) { + var cls = base + (state && state !== 'idle' ? ' ' + base + '--' + state : ''); + target.setAttribute('class', cls + (target.__moExtra || '')); + }; + } + + function show(node, visible) { + var target = node.g || node; + target.setAttribute('visibility', visible === false ? 'hidden' : 'visible'); + } + + function fade(node, opacity) { + (node.g || node).setAttribute('opacity', clamp(opacity)); + } + + function node(opts) { + var w = opts.w || 150; + var h = opts.h || 64; + var x = opts.x; + var y = opts.y; + var cx = x + w / 2; + var cy = y + h / 2; + var g = el('g', { 'class': 'mo-node' }, layers.nodes); + el('rect', { x: x, y: y, width: w, height: h }, g); + var label = el('text', { + x: cx, + 'class': 'mo-node-label', + 'text-anchor': 'middle', + 'dominant-baseline': 'central' + }, g); + var sub = el('text', { + x: cx, + 'class': 'mo-node-sub', + 'text-anchor': 'middle', + 'dominant-baseline': 'central' + }, g); + + function setLabel(main, detail) { + label.setAttribute('y', detail ? cy - 9 : cy); + sub.setAttribute('y', cy + 12); + label.textContent = main; + sub.textContent = detail || ''; + } + + setLabel(opts.label || '', opts.sub); + var api = { + g: g, x: x, y: y, w: w, h: h, cx: cx, cy: cy, + left: [x, cy], right: [x + w, cy], top: [cx, y], bottom: [cx, y + h], + setLabel: setLabel, + setState: stateSetter(g, 'mo-node') + }; + if (opts.state) { api.setState(opts.state); } + return api; + } + + function edge(opts) { + var points = [opts.from].concat(opts.via || [], [opts.to]); + var lengths = [0]; + for (var i = 1; i < points.length; i++) { + lengths.push(lengths[i - 1] + Math.hypot( + points[i][0] - points[i - 1][0], + points[i][1] - points[i - 1][1] + )); + } + var total = lengths[lengths.length - 1]; + + function pointAt(p) { + var target = clamp(p) * total; + for (var j = 1; j < points.length; j++) { + if (target <= lengths[j] || j === points.length - 1) { + var span = (lengths[j] - lengths[j - 1]) || 1; + var t = (target - lengths[j - 1]) / span; + return [ + lerp(points[j - 1][0], points[j][0], t), + lerp(points[j - 1][1], points[j][1], t) + ]; + } + } + return points[0]; + } + + var g = el('g', {}, layers.edges); + g.__moExtra = opts.dashed ? ' mo-edge--dashed' : ''; + var setState = stateSetter(g, 'mo-edge'); + setState(opts.state || 'idle'); + + el('path', { + d: points.map(function (pt, k) { + return (k === 0 ? 'M' : 'L') + pt[0] + ' ' + pt[1]; + }).join(' ') + }, g); + + var tip = points[points.length - 1]; + var prev = points[points.length - 2]; + var angle = Math.atan2(tip[1] - prev[1], tip[0] - prev[0]) * 180 / Math.PI; + el('polygon', { + points: '0,0 -10,-5 -10,5', + transform: 'translate(' + tip[0] + ' ' + tip[1] + ') rotate(' + angle + ')' + }, g); + + if (opts.label) { + var mid = pointAt(0.5); + text({ x: mid[0], y: mid[1] - 8, text: opts.label, anchor: 'middle', parent: g }); + } + + return { g: g, points: points, pointAt: pointAt, setState: setState }; + } + + function token(opts) { + var label = opts.label || 'vCon'; + var w = opts.w || label.length * 8 + 20; + var h = opts.h || 26; + var g = el('g', { 'class': 'mo-token' }, layers.tokens); + el('rect', { x: -w / 2, y: -h / 2, width: w, height: h }, g); + var caption = el('text', { 'text-anchor': 'middle', 'dominant-baseline': 'central' }, g); + caption.textContent = label; + + var api = { + g: g, + at: function (x, y) { + g.setAttribute('transform', 'translate(' + x + ' ' + y + ')'); + }, + follow: function (path, p) { + var pt = path.pointAt(p); + api.at(pt[0], pt[1]); + }, + setLabel: function (value) { caption.textContent = value; }, + setState: stateSetter(g, 'mo-token') + }; + api.at(opts.x || 0, opts.y || 0); + if (opts.state) { api.setState(opts.state); } + if (opts.hidden) { show(g, false); } + return api; + } + + return { + svg: svg, + width: width, + height: height, + layers: layers, + tokens: TOKENS, + state: {}, + reducedMotion: motionQuery.matches, + el: el, + text: text, + setText: setText, + node: node, + edge: edge, + token: token, + show: show, + fade: fade, + ease: ease, + lerp: lerp, + clamp: clamp, + seg: seg + }; + } + + /* ---------- Rendering ---------- */ + + function fail(message, err) { + errorText = message; + stopLoop(); + if (err) { global.console.error(message, err); } else { global.console.error(message); } + dom.stage.textContent = ''; + var p = document.createElement('p'); + p.className = 'mo-error'; + p.textContent = message; + dom.stage.appendChild(p); + sync(); + } + + function mount() { + var box = scene.viewBox || [960, 540]; + var svg = setAttrs(document.createElementNS(SVG_NS, 'svg'), { + viewBox: '0 0 ' + box[0] + ' ' + box[1], + role: 'img', + 'aria-label': scene.title + '. ' + (scene.summary || '') + }); + dom.stage.textContent = ''; + dom.stage.appendChild(svg); + ctx = createCtx(svg, box[0], box[1]); + try { + scene.setup(ctx); + return true; + } catch (err) { + fail('Scene ' + sceneId + ' failed in setup: ' + err.message, err); + return false; + } + } + + function draw(step, p) { + try { + step.draw(p, ctx); + return true; + } catch (err) { + fail('Scene ' + sceneId + ' failed in step ' + step.id + ': ' + err.message, err); + return false; + } + } + + // Every jump rebuilds the stage and replays finished steps at p = 1, so a + // frame depends only on the position and never on how the viewer got there. + function renderAt(nextCursor, p) { + if (!mount()) { return; } + for (var i = 0; i < nextCursor; i++) { + if (!draw(scene.steps[i], 1)) { return; } + } + cursor = nextCursor; + progress = cursor < scene.steps.length ? p : 0; + elapsed = progress * (cursor < scene.steps.length ? scene.steps[cursor].duration : 0); + holdLeft = 0; + if (progress > 0 && !draw(scene.steps[cursor], progress)) { return; } + sync(); + } + + function activeIndex() { + return progress > 0 ? cursor : cursor - 1; + } + + function sync() { + var count = scene ? scene.steps.length : 0; + var usable = count > 0 && errorText === null; + var done = usable && cursor >= count; + var active = activeIndex(); + var caption = ''; + if (usable) { + caption = active >= 0 ? scene.steps[active].caption : 'Press Play or Step to start.'; + } + + dom.play.textContent = playing ? 'Pause' : (done ? 'Replay' : 'Play'); + dom.play.disabled = !usable; + dom.back.disabled = !usable || (cursor === 0 && progress === 0); + dom.step.disabled = !usable || done; + dom.reset.disabled = !usable; + dom.progress.style.width = count ? ((cursor + progress) / count * 100) + '%' : '0'; + dom.status.textContent = usable ? 'Step ' + Math.max(active + 1, 0) + ' of ' + count : ''; + if (dom.caption.textContent !== caption) { dom.caption.textContent = caption; } + dom.reducedNote.hidden = !motionQuery.matches; + + Array.prototype.forEach.call(dom.steps.querySelectorAll('.mo-step'), function (button, i) { + if (i === active) { + button.setAttribute('aria-current', 'step'); + } else { + button.removeAttribute('aria-current'); + } + }); + } + + /* ---------- Playback ---------- */ + + function stopLoop() { + playing = false; + lastTs = null; + if (rafId !== null) { + global.cancelAnimationFrame(rafId); + rafId = null; + } + } + + function holdAfter(step) { + var hold = step.hold === undefined ? DEFAULT_HOLD : step.hold; + return motionQuery.matches ? Math.max(step.duration + hold, REDUCED_MIN_HOLD) : hold; + } + + function tick(ts) { + rafId = null; + if (!playing) { return; } + var dt = lastTs === null ? 0 : Math.min(ts - lastTs, MAX_FRAME); + lastTs = ts; + + if (holdLeft > 0) { + holdLeft -= dt; + if (holdLeft > 0) { + rafId = global.requestAnimationFrame(tick); + return; + } + holdLeft = 0; + } + + var step = scene.steps[cursor]; + elapsed += dt; + var instant = motionQuery.matches || step.duration === 0; + var p = instant ? 1 : Math.min(elapsed / step.duration, 1); + if (!draw(step, p)) { return; } + progress = p; + + if (p >= 1) { + cursor += 1; + progress = 0; + elapsed = 0; + holdLeft = cursor < scene.steps.length ? holdAfter(step) : 0; + } + + if (cursor >= scene.steps.length) { + stopLoop(); + } else { + rafId = global.requestAnimationFrame(tick); + } + sync(); + } + + function play() { + if (!scene || errorText !== null || playing) { return; } + if (cursor >= scene.steps.length) { renderAt(0, 0); } + playing = true; + lastTs = null; + rafId = global.requestAnimationFrame(tick); + sync(); + } + + function pause() { + if (!playing) { return; } + stopLoop(); + holdLeft = 0; + sync(); + } + + function seek(nextCursor, p) { + if (!scene || errorText !== null) { return; } + stopLoop(); + renderAt(clamp(Math.round(nextCursor), 0, scene.steps.length), clamp(p || 0)); + } + + // step() finishes the current step. step(-1) returns to the start of the + // current step, or to the start of the one before if already at a boundary. + function step(delta) { + if (!scene) { return; } + if (delta !== undefined && delta < 0) { + seek(progress > 0 ? cursor : cursor - 1); + } else { + seek(cursor + 1); + } + } + + function reset() { seek(0); } + + /* ---------- Scene selection ---------- */ + + function fillSceneChrome() { + var tab = document.getElementById('tab-' + sceneId); + var fallback = tab ? tab.textContent.replace(/^M\d+/, '') : sceneId; + dom.title.textContent = scene ? scene.title : fallback; + dom.summary.textContent = scene ? (scene.summary || '') : ''; + + dom.steps.textContent = ''; + (scene ? scene.steps : []).forEach(function (item, i) { + var li = document.createElement('li'); + var button = document.createElement('button'); + var strong = document.createElement('strong'); + button.type = 'button'; + button.className = 'mo-step'; + strong.textContent = (i + 1) + '. ' + item.label; + button.appendChild(strong); + button.appendChild(document.createTextNode(item.caption)); + button.addEventListener('click', function () { seek(i + 1); }); + li.appendChild(button); + dom.steps.appendChild(li); + }); + + dom.twins.textContent = ''; + (scene && scene.twins ? scene.twins : []).forEach(function (slug) { + var a = document.createElement('a'); + a.href = '../../diagrams/' + slug + '.svg'; + a.textContent = slug.split('-')[0]; + a.title = slug; + dom.twins.appendChild(a); + }); + } + + function select(id) { + var key = String(id).toLowerCase(); + var tab = document.getElementById('tab-' + key); + if (!tab || key === sceneId) { return; } + + stopLoop(); + sceneId = key; + scene = scenes[key] || null; + cursor = 0; + progress = 0; + elapsed = 0; + holdLeft = 0; + errorText = null; + + dom.tabs.forEach(function (item) { + var selected = item === tab; + item.setAttribute('aria-selected', selected ? 'true' : 'false'); + item.tabIndex = selected ? 0 : -1; + }); + dom.player.setAttribute('aria-labelledby', tab.id); + if (global.location.hash !== '#' + key) { global.location.hash = key; } + + fillSceneChrome(); + if (!scene) { + fail('Scene ' + key + ' did not register. Check its file in scenes/ and the browser console.'); + return; + } + renderAt(0, 0); + } + + function onTabKey(event) { + var index = dom.tabs.indexOf(event.currentTarget); + var last = dom.tabs.length - 1; + var next = { + ArrowRight: index === last ? 0 : index + 1, + ArrowLeft: index === 0 ? last : index - 1, + Home: 0, + End: last + }[event.key]; + if (next === undefined) { return; } + event.preventDefault(); + dom.tabs[next].focus(); + select(dom.tabs[next].dataset.scene); + } + + function boot() { + function byId(id) { return document.getElementById(id); } + dom = { + player: byId('player'), + stage: byId('stage'), + title: byId('scene-title'), + summary: byId('scene-summary'), + progress: byId('progress'), + play: byId('btn-play'), + back: byId('btn-back'), + step: byId('btn-step'), + reset: byId('btn-reset'), + status: byId('status'), + caption: byId('caption'), + reducedNote: byId('reduced-note'), + steps: byId('steps'), + twins: byId('twins'), + tabs: Array.prototype.slice.call(document.querySelectorAll('[role="tab"]')) + }; + + dom.tabs.forEach(function (tab) { + tab.addEventListener('click', function () { select(tab.dataset.scene); }); + tab.addEventListener('keydown', onTabKey); + }); + dom.play.addEventListener('click', function () { if (playing) { pause(); } else { play(); } }); + dom.back.addEventListener('click', function () { step(-1); }); + dom.step.addEventListener('click', function () { step(); }); + dom.reset.addEventListener('click', reset); + + global.addEventListener('hashchange', function () { + select(global.location.hash.slice(1)); + }); + if (motionQuery.addEventListener) { + motionQuery.addEventListener('change', function () { + if (ctx) { ctx.reducedMotion = motionQuery.matches; } + sync(); + }); + } + + var wanted = global.location.hash.slice(1).toLowerCase(); + select(document.getElementById('tab-' + wanted) ? wanted : dom.tabs[0].dataset.scene); + } + + /* ---------- Public API ---------- */ + + function register(def) { + function bad(why) { + throw new TypeError('VconMotion.register(' + (def && def.id) + '): ' + why); + } + if (!def || !/^m[0-9]+$/.test(def.id || '')) { bad('id must look like m1'); } + if (typeof def.title !== 'string' || !def.title) { bad('title is required'); } + if (typeof def.setup !== 'function') { bad('setup must be a function'); } + if (!Array.isArray(def.steps) || def.steps.length === 0) { bad('steps must not be empty'); } + def.steps.forEach(function (item, i) { + var where = 'step ' + i + ' '; + if (!item.id) { bad(where + 'needs an id'); } + if (!item.label) { bad(where + 'needs a label'); } + if (!item.caption) { bad(where + 'needs a caption'); } + if (typeof item.duration !== 'number' || item.duration < 0) { bad(where + 'needs a duration in ms'); } + if (typeof item.draw !== 'function') { bad(where + 'needs a draw function'); } + }); + scenes[def.id] = def; + } + + function state() { + var count = scene ? scene.steps.length : 0; + return { + scene: sceneId, + title: scene ? scene.title : null, + cursor: cursor, + progress: progress, + stepCount: count, + activeStep: scene && activeIndex() >= 0 ? scene.steps[activeIndex()].id : null, + playing: playing, + done: count > 0 && cursor >= count, + reducedMotion: motionQuery.matches, + error: errorText + }; + } + + global.VconMotion = { + register: register, + select: select, + play: play, + pause: pause, + step: step, + seek: seek, + reset: reset, + state: state, + scenes: function () { return Object.keys(scenes).sort(); } + }; + + document.addEventListener('DOMContentLoaded', boot); +}(window)); diff --git a/mkdocs.yml b/mkdocs.yml index c662d8ff..379e3b62 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -24,68 +24,130 @@ theme: code: JetBrains Mono palette: - scheme: default - primary: blue grey - accent: light blue + primary: custom + accent: custom toggle: icon: material/brightness-7 name: Switch to dark mode - scheme: slate - primary: blue grey - accent: light blue + primary: custom + accent: custom toggle: icon: material/brightness-4 name: Switch to light mode icon: repo: fontawesome/brands/github +extra_css: + - stylesheets/vconic.css + +exclude_docs: | + /plans/ + /diagrams/*.sources.md + /visuals/motion/scene-authoring.md + +not_in_nav: | + /archive/ + /diagrams/README.md + nav: - - Home: index.md - - Getting Started: + - Start: + - Home: index.md - getting-started/index.md - System Requirements: getting-started/requirements.md - Quick Start: getting-started/quick-start.md - - Installation: - - installation/index.md - - Docker: installation/docker.md - - Automated Script: installation/automated-script.md - - Manual Installation: installation/manual-installation.md - - Kubernetes: installation/kubernetes.md - - Upgrading: installation/upgrading.md - - Configuration: - - configuration/index.md - - Environment Variables: configuration/environment-variables.md - - YAML Configuration: configuration/yaml-configuration.md - - Chains and Pipelines: configuration/chains-and-pipelines.md - - Egress Format Compatibility: configuration/egress-compatibility.md - - Authentication: configuration/authentication.md - - Workers: configuration/workers.md - - Operations: - - operations/index.md - - API Reference: operations/api-reference.md - - Monitoring: operations/monitoring.md - - Logging: operations/logging.md - - Troubleshooting: operations/troubleshooting.md - - Dead Letter Queue: operations/dead-letter-queue.md - - Backup and Restore: operations/backup-restore.md - - Extending: - - extending/index.md - - Creating Links: extending/creating-links.md - - Creating Storage Adapters: extending/creating-storage-adapters.md - - Creating Tracers: extending/creating-tracers.md - - Dynamic Modules: extending/dynamic-modules.md + - Concepts: + - Architecture: concepts/architecture.md + - vCon Lifecycle: concepts/vcon-lifecycle.md + - Chains, Links and Storage: concepts/chains-links-storage.md + - Lawful Basis: concepts/lawful-basis.md + - Editions: concepts/editions.md + - Guides: + - Installation: + - installation/index.md + - Docker: installation/docker.md + - Automated Script: installation/automated-script.md + - Manual Installation: installation/manual-installation.md + - Kubernetes: installation/kubernetes.md + - Upgrading: installation/upgrading.md + - Configuration: + - configuration/index.md + - Environment Variables: configuration/environment-variables.md + - YAML Configuration: configuration/yaml-configuration.md + - Chains and Pipelines: configuration/chains-and-pipelines.md + - Egress Format Compatibility: configuration/egress-compatibility.md + - Authentication: configuration/authentication.md + - Workers: configuration/workers.md + - Extending: + - extending/index.md + - Creating Links: extending/creating-links.md + - Creating Storage Adapters: extending/creating-storage-adapters.md + - Creating Tracers: extending/creating-tracers.md + - Dynamic Modules: extending/dynamic-modules.md + - Contributing: contributing.md - Reference: - reference/index.md - Links: - - Deepgram: reference/links/deepgram.md - - Analyze: reference/links/analyze.md - - Tag: reference/links/tag.md - - JQ: reference/links/jq.md - - Webhook: reference/links/webhook.md + - reference/links/index.md + - analyze: reference/links/analyze.md + - analyze_and_label: reference/links/analyze-and-label.md + - analyze_vcon: reference/links/analyze-vcon.md + - check_and_tag: reference/links/check-and-tag.md + - datatrails: reference/links/datatrails.md + - deepgram_link: reference/links/deepgram.md + - delay: reference/links/delay.md + - detect_engagement: reference/links/detect-engagement.md + - diet: reference/links/diet.md + - expire_vcon: reference/links/expire-vcon.md + - groq_whisper: reference/links/groq-whisper.md + - hugging_face_whisper: reference/links/huggingface-whisper.md + - hugging_llm_link: reference/links/hugging-llm.md + - jq_link: reference/links/jq.md + - openai_transcribe: reference/links/openai-transcribe.md + - post_analysis_to_slack: reference/links/slack.md + - sampler: reference/links/sampler.md + - scitt: reference/links/scitt.md + - tag: reference/links/tag.md + - tag_router: reference/links/tag-router.md + - transcribe: reference/links/transcribe.md + - webhook: reference/links/webhook.md + - wtf_transcribe: reference/links/wtf-transcribe.md - Storage Adapters: + - reference/storage-adapters/index.md + - ChatGPT Files: reference/storage-adapters/chatgpt_files.md + - Dataverse: reference/storage-adapters/dataverse.md + - Elasticsearch: reference/storage-adapters/elasticsearch.md + - File: reference/storage-adapters/file.md + - Milvus: reference/storage-adapters/milvus.md + - MongoDB: reference/storage-adapters/mongo.md - PostgreSQL: reference/storage-adapters/postgres.md + - Redis: reference/storage-adapters/redis_storage.md - S3: reference/storage-adapters/s3.md - - MongoDB: reference/storage-adapters/mongo.md + - SCITT: reference/storage-adapters/scitt.md + - SFTP: reference/storage-adapters/sftp.md + - Space and Time: reference/storage-adapters/spaceandtime.md + - Utopia: reference/storage-adapters/utopia.md + - vCon MCP: reference/storage-adapters/vcon_mcp.md + - Webhook: reference/storage-adapters/webhook.md + - Tracers: + - JLINC: reference/tracers/jlinc.md + - API Reference: reference/api.md + - API Routes: reference/api-routes.md + - Environment Variables: reference/environment.md + - Ports and Services: reference/ports.md + - Metrics: reference/metrics.md - CLI Reference: reference/cli-reference.md + - Operations: + - operations/index.md + - Monitoring: operations/monitoring.md + - Logging: operations/logging.md + - Troubleshooting: operations/troubleshooting.md + - Dead Letter Queue: operations/dead-letter-queue.md + - Storage Recovery: operations/storage-recovery.md + - Backup and Restore: operations/backup-restore.md + - Redis Migration: installation/redis-migration.md + - Visuals: visuals/index.md + - Archive: archive/index.md plugins: - search diff --git a/scripts/docs/_docslib.py b/scripts/docs/_docslib.py new file mode 100644 index 00000000..0ceea6f5 --- /dev/null +++ b/scripts/docs/_docslib.py @@ -0,0 +1,142 @@ +"""Shared helpers for the docs generators. + +The generators parse source files with ``ast`` and YAML. They never import +the code they describe, so they run without the server's dependencies. +""" + +import ast +import sys +from pathlib import Path + +import yaml + +REPO = Path(__file__).resolve().parents[2] +DESCRIPTIONS = REPO / "scripts" / "docs" / "descriptions.yml" +CODE_ROOTS = ("api", "common", "conserver") +TODO = "TODO(verify)" + + +def rel(path): + return path.relative_to(REPO).as_posix() + + +def is_test_file(path): + parts = path.relative_to(REPO).parts + return ( + "tests" in parts + or "test" in parts + or path.name.startswith("test_") + or path.name.endswith("_test.py") + or path.name == "conftest.py" + ) + + +def iter_python_files(): + """Yield non-test Python files under the code roots in a stable order.""" + for root in CODE_ROOTS: + for path in sorted((REPO / root).rglob("*.py")): + if not is_test_file(path): + yield path + + +def parse(path): + """Parse a Python file and give every node a ``parent`` attribute.""" + tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path)) + for node in ast.walk(tree): + for child in ast.iter_child_nodes(node): + child.parent = node + return tree + + +def call_name(node): + """Return the bare function name of a Call node, or an empty string.""" + if isinstance(node.func, ast.Name): + return node.func.id + if isinstance(node.func, ast.Attribute): + return node.func.attr + return "" + + +def keyword(call, name): + for item in call.keywords: + if item.arg == name: + return item.value + return None + + +def constant(node): + """Return a node's constant value, or None when it has none.""" + return node.value if isinstance(node, ast.Constant) else None + + +def load_section(section): + """Return one top-level section of descriptions.yml.""" + data = yaml.safe_load(DESCRIPTIONS.read_text(encoding="utf-8")) or {} + block = data.get(section) or {} + block.setdefault("entries", {}) + return block + + +def check_stale(section, block, known): + """Fail when descriptions.yml names something the code no longer has.""" + stale = sorted(set(block["entries"]) - set(known)) + if stale: + sys.exit( + f"descriptions.yml section {section!r} has entries the code no " + f"longer provides: {', '.join(stale)}" + ) + + +def entry(block, key): + """Return an entry as a dict, accepting a bare string as the description.""" + value = block["entries"].get(key) + if value is None: + return {} + if isinstance(value, str): + return {"description": value} + return value + + +def description(block, key, required=True): + text = str(entry(block, key).get("description", "")).strip() + if not text and required: + print(f"warning: no description for {key}", file=sys.stderr) + return TODO + return text + + +def cell(text): + """Make text safe for a Markdown table cell.""" + return " ".join(str(text).split()).replace("|", "\\|") + + +def code(text): + return f"`{text}`" + + +def table(headers, rows): + lines = [ + "| " + " | ".join(headers) + " |", + "|" + "|".join("---" for _ in headers) + "|", + ] + lines += ["| " + " | ".join(cell(c) for c in row) + " |" for row in rows] + return "\n".join(lines) + + +def write_page(filename, title, generator, block, sections): + """Write a generated page under docs/reference/.""" + parts = [ + f"", + f"# {title}", + '!!! note "Generated page"\n' + f" `scripts/docs/{generator}` builds this page from the code. " + "Text that needs a person lives in `scripts/docs/descriptions.yml`. " + "Edit that file, not this page.", + ] + for piece in [block.get("intro"), *sections, block.get("outro")]: + if piece and str(piece).strip(): + parts.append(str(piece).strip()) + target = REPO / "docs" / "reference" / filename + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("\n\n".join(parts) + "\n", encoding="utf-8") + print(f"wrote {rel(target)}") diff --git a/scripts/docs/check.sh b/scripts/docs/check.sh new file mode 100755 index 00000000..55a1df67 --- /dev/null +++ b/scripts/docs/check.sh @@ -0,0 +1,53 @@ +#!/usr/bin/env bash +# Check the docs against the code. CI runs this, and it is safe to run locally. +# +# 1. Runs the generators and fails if a generated page differs from git. +# 2. Renders every diagram to a temp folder to catch syntax errors. It does not +# compare SVG bytes, since mermaid-cli output is not stable between runs. +# 3. Builds the site with mkdocs build --strict. +# +# A regenerated page stays on disk. Stage or commit it and the check passes. +set -euo pipefail + +repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$repo" + +generators=(gen_env.py gen_ports.py gen_routes.py gen_metrics.py) +pages=( + docs/reference/environment.md + docs/reference/ports.md + docs/reference/api-routes.md + docs/reference/metrics.md +) + +tmp="$(mktemp -d)" +trap 'rm -rf "$tmp"' EXIT + +echo "== generators" +for generator in "${generators[@]}"; do + uv run -q --no-project --python 3.12 --with pyyaml python "scripts/docs/$generator" +done + +if ! git diff --exit-code --stat -- "${pages[@]}"; then + echo "check: generated pages are out of date. Review and commit them." >&2 + exit 1 +fi + +untracked="$(git ls-files --others --exclude-standard -- "${pages[@]}")" +if [[ -n "$untracked" ]]; then + if [[ -n "${CI:-}" ]]; then + echo "check: generated pages are not committed:" >&2 + echo "$untracked" >&2 + exit 1 + fi + echo "check: note, generated pages are not in git yet, so no diff was checked:" + echo "$untracked" +fi + +echo "== diagrams" +scripts/docs/render_diagrams.sh "$tmp/diagrams" + +echo "== mkdocs" +NO_MKDOCS_2_WARNING=1 uvx --with mkdocs-material mkdocs build --strict -q -d "$tmp/site" + +echo "check: passed" diff --git a/scripts/docs/descriptions.yml b/scripts/docs/descriptions.yml new file mode 100644 index 00000000..73dcbc08 --- /dev/null +++ b/scripts/docs/descriptions.yml @@ -0,0 +1,182 @@ +# Text for the generated reference pages that needs a person. +# +# The generators merge this file into docs/reference/*.md, so edit here and +# never edit those pages. Then run scripts/docs/check.sh, or one generator: +# +# uv run -q --no-project --python 3.12 --with pyyaml python scripts/docs/gen_env.py +# +# Each section takes optional `intro` and `outro` Markdown, placed before and +# after the generated tables, and `entries` keyed by the name in the code. An +# entry is a string, or a mapping with `description` and, for environment +# variables, `default` to replace the value parsed from the code. A key the +# code no longer has fails the generator. A missing description shows as +# TODO(verify). + +environment: + intro: | + `common/settings.py` loads a `.env` file with `dotenv.load_dotenv()` when it is imported, so values in `.env` count as environment variables. Every read below sits under `api/`, `common/` or `conserver/`. Tests are left out. + + A default of `none` means the read returns nothing when the variable is unset. `required` means the code raises `KeyError` when it is unset. A variable set to an empty value counts as set, so its default does not apply. + + Each process reads these values when it starts, so restart it after a change. For help choosing values, see the [environment guide](../configuration/environment-variables.md). + outro: | + The dynamic read in `groq_whisper` does not configure anything. When that link module loads, it deletes `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` and their lowercase forms from the process environment. + + ## Variables outside the server code + + Scripts, Docker Compose and the OpenTelemetry tools read these. The table above leaves them out because no code under `api/`, `common/` or `conserver/` reads them. + + | Variable | Read by | Default | Description | + |---|---|---|---| + | `COMPOSE_PROFILES` | Docker Compose | none | Comma-separated profiles to start: `postgres`, `elasticsearch`, `langfuse`. | + | `CONSERVER_EXTERNAL_PORT` | `docker-compose.yml` | `8000` | Host port published for the `api` service. | + | `OTEL_EXPORTER_OTLP_HEADERS` | `opentelemetry-instrument` | empty | Headers for OTLP export. Compose passes it to `api` and `conserver`. | + | `OTEL_EXPORTER_OTLP_INSECURE` | `opentelemetry-instrument` | `false` in Compose | Turns off TLS for OTLP export. Compose passes it to `api` and `conserver`. | + | `OTEL_EXPORTER_OTLP_PROTOCOL` | `opentelemetry-instrument` | `grpc` in Compose | OTLP protocol. The custom metrics in `common/lib/metrics.py` always use the gRPC exporter, whatever this says. | + | `OTEL_RESOURCE_ATTRIBUTES` | `opentelemetry-instrument` | `deployment.environment=dev` in Compose | Resource attributes. The Compose file fixes this value for `api` and `conserver`. | + | `REDIS_MIGRATION_SOURCE_URL` | `scripts/migrate_redis_json.py` | required | Redis URL to copy from. See the [Redis migration](../installation/redis-migration.md). | + | `REDIS_MIGRATION_TARGET_URL` | `scripts/migrate_redis_json.py` | required | Redis URL to copy to. | + entries: + API_ROOT_PATH: FastAPI `root_path` for the API app, for a proxy that strips this prefix. Route paths do not change. + CONSERVER_API_TOKEN: One API key for the main API routes. With neither this nor `CONSERVER_API_TOKEN_FILE` set, the API skips authentication on those routes. + CONSERVER_API_TOKEN_FILE: Path to a file of API keys, one per line, read once when the API starts. Added to the keys from `CONSERVER_API_TOKEN`. + CONSERVER_CONFIG_FILE: Path to the YAML configuration. `common/config.py` reads it through the setting and its default. The `POST /config` handler reads the variable directly, with no default, to write the file. An empty value fails when the file is opened. + CONSERVER_HEADER_NAME: HTTP header that carries the API key. The follower also sends its auth token in this header. + CONSERVER_PARALLEL_STORAGE: When true, and a chain has more than one storage backend, writes run in parallel. `true`, `1` and `yes` count as true, in any case. + CONSERVER_START_METHOD: Multiprocessing start method, one of `fork`, `spawn` or `forkserver`. Used only when `CONSERVER_WORKERS` is above 1. Empty or unset uses the Python platform default. Any other value raises `ValueError` at startup. + CONSERVER_VCON_CONCURRENCY: In-flight vCons per worker process. Values under 1 become 1, which processes vCons serially. + CONSERVER_WORKERS: Number of worker processes. Values under 1 become 1. + DEEPGRAM_KEY: Read into `settings`, but no code uses that setting. The `deepgram_link` link takes its key from link options. + EGRESS_FORMAT_VERSION: Legacy vCon version string emitted by the `webhook` link, the `postgres`, `s3` and `elasticsearch` storage adapters and the `GET /vcon/{uuid}` and `GET /vcons` reads. `0.0.1` is the only supported value. Empty or unset emits the current spec. Redis and link processing stay on the current spec either way. + ENV: Sentry environment name. The `settings` value is unused. `common/lib/error_tracking.py` reads the variable directly when `SENTRY_DSN` is set, and has no default. + GROQ_API_KEY: Default `API_KEY` option for the `groq_whisper` link. + HOSTNAME: Read into `settings`, but no code uses that setting. + LOG_LEVEL: Read into `settings`, but no code uses that setting. The logging config file sets log levels. + LOGGING_CONFIG_FILE: + description: Path passed to `logging.config.fileConfig`. The repo also ships `common/logging_dev.conf`. + default: "`logging.conf` beside `common/settings.py`" + OPENAI_API_KEY: Default `OPENAI_API_KEY` option for the `detect_engagement` link. The `settings` value is unused. Other links take the key from link options. + OTEL_EXPORTER_OTLP_ENDPOINT: OTLP endpoint for metrics, passed to the gRPC exporter in `common/lib/metrics.py`. Unset or empty, the metric helpers do nothing. + OTEL_METRIC_EXPORT_INTERVAL: Metric export interval in milliseconds. + OTEL_SERVICE_NAME: Value of the `service.name` resource attribute on metrics. The Compose file sets `conserver` and `api`. + REDIS_URL: Redis connection URL. `docker/wait_for_redis.sh` reads it too, and skips its wait when it is unset or empty. + SENTRY_DSN: + description: Sentry DSN. Unset, Sentry stays off. Set, `ENV` must be in the process environment too. + default: none + SXT_API_KEY: Space and Time API key for the `spaceandtime` storage adapter. + SXT_VCON_TABLENAME: Table name for the `spaceandtime` storage adapter. + SXT_VCON_TABLE_WRITE_BISCUI: Write biscuit for the `spaceandtime` storage adapter. The code reads this exact name, which lacks the final `T` of the Python constant `SXT_VCON_TABLE_WRITE_BISCUIT`. + TICK_INTERVAL: Read into `settings`, but no code uses that setting. + UUID8_DOMAIN_NAME: + description: Read into a constant in `common/vcon.py`, but no code uses that constant. + default: a domain set in code + VCON_CONTEXT_EXPIRY: Seconds before ingress context data expires in Redis. + VCON_DLQ_EXPIRY: TTL in seconds for a vCon in a dead letter queue. The ingress DLQ sets the TTL to this value. The storage DLQ only raises a lower TTL. `0` leaves the existing TTL alone. + VCON_INDEX_EXPIRY: Seconds before the search index keys written by the API expire. + VCON_REDIS_EXPIRY: TTL in seconds on vCon keys written by `POST /vcon` and `POST /vcon/external-ingress`, and on a vCon cached back from a storage backend. + VCON_SERVER_BUILD_TIME: Image build time. The Dockerfiles set it from a build argument. + VCON_SERVER_GIT_COMMIT: Git commit of the build. The Dockerfiles set it from a build argument. Sentry uses it as the release. + VCON_SERVER_VERSION: Server version string. The Dockerfiles set it from a build argument. + VCON_SORTED_FORCE_RESET: Read into `settings`, but no code uses that setting. + VCON_SORTED_SET_NAME: Name of the Redis sorted set that orders vCons by timestamp. + VCON_STORAGE: PostgreSQL connection string. When set, `api/api.py` defines a Peewee model on it, but no code uses that model. + VCON_STORAGE_FALLBACK_ENABLED: When true, a Redis miss in `VconRedis.get_vcon` tries the configured storage backends and caches the first hit back in Redis. `true`, `1` and `yes` count as true, in any case. + WEVIATE_API_KEY: Read into `settings`, but no code uses that setting. The spelling is the one in the code. + WEVIATE_HOST: Read into `settings`, but no code uses that setting. The spelling is the one in the code. + +ports: + intro: | + `docker-compose.yml` joins every service to the `conserver` network, which is declared external, so create it before the first `docker compose up`. Set `COMPOSE_PROFILES` in `.env` to start optional services. A service with no published port is reachable only on that network. + entries: + api: FastAPI app, run by uvicorn on port 8000. + conserver: Runs `conserver/main.py`, restarted by `watchmedo` when a Python file changes. Publishes no port. + elasticsearch: Single-node Elasticsearch with security on. The credentials in the Compose file are for development only. + langfuse-clickhouse: ClickHouse store for Langfuse. Uses 8123 and 9000 on the network. + langfuse-minio: MinIO object store for Langfuse. Uses 9000 on the network, with its console on 9001. + langfuse-postgres: PostgreSQL database for Langfuse. Uses 5432 on the network. + langfuse-server: Langfuse web app for local tracing. The credentials in the Compose file are for development only. + langfuse-worker: Langfuse background worker. + postgres: Local PostgreSQL. The credentials in the Compose file are for development only. + redis: Plain Redis with append-only persistence and a 1 GB memory limit. Uses 6379 on the network. + outro: | + ## Container and port map + + ![Docker host ports, the conserver network and the Compose services by profile](../diagrams/D02-container-port-map.svg) + +routes: + intro: | + Paths are relative to the app. `API_ROOT_PATH`, default `/api`, sets the FastAPI root path. + + The Auth column uses three values: + + - `API key` routes pass through `get_api_key`, which compares the header named by `CONSERVER_HEADER_NAME` with the keys from `CONSERVER_API_TOKEN` and `CONSERVER_API_TOKEN_FILE`. With no keys configured, the check is skipped and the route is open. + - `ingress API key` routes call `validate_ingress_api_key`, which checks the same header against the `ingress_auth` section of the configuration for the named ingress list. With no match the API returns 403, including when `ingress_auth` is empty. + - `none` routes have no check. + outro: | + `FastAPI` is created without turning off its default pages, so `/docs`, `/redoc` and `/openapi.json` are served too, with no check. + entries: + "GET /vcon/egress": Declared 204. The handler returns a JSON array with 200. + "GET /vcon/count": "Unreachable. `GET /vcon/{vcon_uuid}` captures the path and returns 422." + +metrics: + intro: | + All metrics go through the helpers in `common/lib/metrics.py`. They publish only when `OTEL_EXPORTER_OTLP_ENDPOINT` is set, and always through the OTLP gRPC exporter. `OTEL_METRIC_EXPORT_INTERVAL` sets the export interval. Metrics from OpenTelemetry auto-instrumentation are not listed. + entries: + conserver.api.count_vcons_enqueued: vCons the API added to an ingress list. Attributes are `ingress_list` and `source`, which is `new`, `external`, `reingress` or `dlq_reprocess`. + conserver.dlq.count: vCons moved to a dead letter queue, ingress or storage. Attribute is `queue_name`. + conserver.ingress_list.length: Current `LLEN` of each configured ingress list and its dead letter queue. Attributes are `ingress_list` and `kind`, which is `ingress` or `dlq`. + conserver.lib.vcon_redis.get_vcon_not_found: A `VconRedis.get_vcon` call found the vCon in neither Redis nor storage. + conserver.lib.vcon_redis.get_vcon_redis_miss: A `VconRedis.get_vcon` call missed Redis. + conserver.lib.vcon_redis.get_vcon_storage_hit: A `VconRedis.get_vcon` call missed Redis and found the vCon in storage. + conserver.link.count: Link runs. Attributes are `link_name` and `outcome`, which is `success`, `halt` or `error`. + conserver.link.datatrails.event_creation_failures: Failed DataTrails event creation. + conserver.link.deepgram.confidence: Deepgram transcript confidence. Not recorded when the link goes through a LiteLLM proxy. + conserver.link.deepgram.transcription_failures: Failed Deepgram transcriptions, including results below `minimum_confidence`. + conserver.link.deepgram.transcription_time: Deepgram transcription time in seconds. + conserver.link.diet.media_post_failures: Failed media posts from the `diet` link. + conserver.link.execution_time: Link execution time in seconds. Attributes are `link.name` and `chain.name`. + conserver.link.groq_whisper.transcription_failures: Failed Groq Whisper transcriptions. + conserver.link.groq_whisper.transcription_time: Groq Whisper transcription time in seconds. + conserver.link.hugging_face_whisper.transcription_failures: Failed Hugging Face Whisper transcriptions. + conserver.link.hugging_face_whisper.transcription_time: Hugging Face Whisper transcription time in seconds. + conserver.link.huggingface.llm_failures: Failed Hugging Face LLM calls. + conserver.link.huggingface.llm_time: Hugging Face LLM call time in seconds. + conserver.link.jq.filter_errors: Errors applying the `jq_link` filter. + conserver.link.jq.string_body_array_retries: Filter retries with string-only body arrays after a type error. + conserver.link.jq.vcon_filtered_out: vCons the `jq_link` filter stopped. + conserver.link.openai.analysis_failures: Failed analysis calls in the `analyze`, `analyze_and_label` and `analyze_vcon` links. + conserver.link.openai.analysis_time: Analysis call time in seconds in the `analyze`, `analyze_and_label` and `analyze_vcon` links. + conserver.link.openai.engagement_analysis_failures: Failed `detect_engagement` analysis calls. + conserver.link.openai.engagement_analysis_time: "`detect_engagement` analysis time in seconds." + conserver.link.openai.engagement_detected: Conversations `detect_engagement` found engaged. Other results add 0. + conserver.link.openai.evaluation_failures: Failed `check_and_tag` evaluations. + conserver.link.openai.evaluation_time: "`check_and_tag` evaluation time in seconds." + conserver.link.openai.invalid_json: Invalid JSON responses in `analyze_vcon`. + conserver.link.openai.json_parse_failures: Responses `analyze_and_label` could not parse as JSON. + conserver.link.openai.labels_added: Labels `analyze_and_label` added as tags. + conserver.link.openai.tags_applied: Tags `check_and_tag` applied. + conserver.link.openai.transcription_failures: Failed `openai_transcribe` transcriptions. + conserver.link.openai.transcription_time: "`openai_transcribe` transcription time in seconds." + conserver.link.sampler.sampled_in: vCons the `sampler` link kept. + conserver.link.sampler.sampled_out: vCons the `sampler` link dropped. + conserver.link.scitt.registration_failures: Failed SCITT statement registrations. + conserver.link.scitt.statement_creation_failures: Failed SCITT signed statement creation. + conserver.link.slack.fallback_channel_used: Posts that failed on the target channel. The link then sends a notice to `default_channel_name` and raises. + conserver.link.slack.post_failures: Failed Slack posts. + conserver.link.tag_router.routed_count: vCons routed to at least one list. + conserver.link.tag_router.routes_matched: Tag matches, one per target list. The `route` attribute names the list. + conserver.link.webhook.no_urls_configured: Webhook link runs with no URLs configured. + conserver.link.webhook.post_failures: Webhook link posts that raised an exception. + conserver.main_loop.count_vcons_processed: vCons that left a chain without an exception, including those a link halted. Attribute is `chain.name`. + conserver.main_loop.count_vcons_received: vCons popped from an ingress list. Attribute is `ingress_list`. + conserver.main_loop.vcon_processing_time: Chain processing time in seconds, per vCon that left a chain without an exception, including those a link halted. Attribute is `chain.name`. + conserver.redis.memory_used_bytes: Redis `used_memory` from `INFO memory`, in bytes. + conserver.storage.count: Storage writes. Attributes are `backend` and `outcome`, which is `success` or `error`. + conserver.storage.duration_ms: Storage write time in milliseconds. Attributes are `backend` and `outcome`. + conserver.storage.milvus.embedding_failures: Failed embedding calls in the `milvus` adapter. + conserver.storage.milvus.embedding_time: Embedding call time in seconds in the `milvus` adapter. + conserver.storage.milvus.storage_failures: Failed `milvus` writes. + conserver.storage.milvus.text_extraction_time: Text extraction time in seconds in the `milvus` adapter. + conserver.storage.milvus.vcons_stored: vCons written to Milvus. + conserver.vcons.inflight: vCons in progress. Attribute is `chain.name`. + conserver.webhook.duration: Webhook storage adapter post time in seconds. Attribute is `status_code`. diff --git a/scripts/docs/gen_env.py b/scripts/docs/gen_env.py new file mode 100755 index 00000000..84d8c698 --- /dev/null +++ b/scripts/docs/gen_env.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Generate docs/reference/environment.md from environment reads in the code. + +Covers common/settings.py and every direct os.getenv, os.environ.get, +os.environ[...] and "X" in os.environ read under api, common and conserver. +""" + +import ast +import sys +from collections import defaultdict + +from _docslib import ( + call_name, + check_stale, + code, + constant, + description, + entry, + iter_python_files, + load_section, + parse, + rel, + table, + write_page, +) + +NO_DEFAULT = "none" +REQUIRED = "required" + + +def is_environ(node): + if isinstance(node, ast.Attribute): + return node.attr == "environ" + return isinstance(node, ast.Name) and node.id == "environ" + + +def is_env_call(node): + """True for os.getenv(...), getenv(...) and os.environ.get(...).""" + if not isinstance(node, ast.Call) or not node.args: + return False + if call_name(node) == "getenv": + return True + return ( + isinstance(node.func, ast.Attribute) + and node.func.attr == "get" + and is_environ(node.func.value) + ) + + +def default_text(call): + if len(call.args) < 2: + return NO_DEFAULT + node = call.args[1] + if isinstance(node, ast.Constant): + if node.value is None: + return NO_DEFAULT + return code(node.value) if node.value != "" else code('""') + return code(ast.unparse(node)) + + +def value_type(node): + """Work out how the surrounding statement treats the value.""" + child, parent = node, getattr(node, "parent", None) + while parent is not None and not isinstance(parent, ast.stmt): + if isinstance(parent, ast.Call) and call_name(parent) in ("int", "float"): + return "integer" if call_name(parent) == "int" else "float" + if ( + isinstance(parent, ast.Compare) + and parent.left is child + and isinstance(parent.ops[0], ast.In) + ): + return "boolean" + child, parent = parent, getattr(parent, "parent", None) + return "string" + + +def collect(): + reads = defaultdict(list) # variable -> [(file, default, type)] + dynamic = set() + for path in iter_python_files(): + name = rel(path) + for node in ast.walk(parse(path)): + if is_env_call(node): + variable = constant(node.args[0]) + if isinstance(variable, str): + reads[variable].append((name, default_text(node), value_type(node))) + else: + dynamic.add((name, ast.unparse(node))) + elif ( + isinstance(node, ast.Subscript) + and is_environ(node.value) + and isinstance(node.ctx, ast.Load) + ): + variable = constant(node.slice) + if isinstance(variable, str): + reads[variable].append((name, REQUIRED, "string")) + else: + dynamic.add((name, ast.unparse(node))) + elif ( + isinstance(node, ast.Compare) + and isinstance(node.ops[0], ast.In) + and is_environ(node.comparators[0]) + ): + variable = constant(node.left) + if isinstance(variable, str): + reads[variable].append((name, NO_DEFAULT, "string")) + else: + dynamic.add((name, ast.unparse(node))) + return reads, dynamic + + +def render_default(sites): + by_value = defaultdict(set) + for name, default, _ in sites: + by_value[default].add(name) + if len(by_value) == 1: + return next(iter(by_value)) + return "
".join( + f"{value} in " + ", ".join(code(f) for f in sorted(files)) + for value, files in sorted(by_value.items()) + ) + + +def main(): + block = load_section("environment") + reads, dynamic = collect() + check_stale("environment", block, reads) + + rows = [] + for variable in sorted(reads): + sites = reads[variable] + rows.append( + [ + code(variable), + entry(block, variable).get("default") or render_default(sites), + ", ".join(sorted({site[2] for site in sites})), + "
".join(code(f) for f in sorted({site[0] for site in sites})), + description(block, variable), + ] + ) + + sections = [ + f"The code reads {len(rows)} variables.", + table(["Variable", "Default", "Type", "Read in", "Description"], rows), + ] + if dynamic: + print(f"warning: {len(dynamic)} dynamic environment reads", file=sys.stderr) + sections += [ + "## Dynamic reads", + "These reads compute the variable name at run time, so the table cannot list them.", + table( + ["File", "Expression"], + [[code(f), code(expr)] for f, expr in sorted(dynamic)], + ), + ] + write_page("environment.md", "Environment variables", "gen_env.py", block, sections) + + +if __name__ == "__main__": + main() diff --git a/scripts/docs/gen_metrics.py b/scripts/docs/gen_metrics.py new file mode 100755 index 00000000..d7a18e1a --- /dev/null +++ b/scripts/docs/gen_metrics.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 +"""Generate docs/reference/metrics.md from calls to the lib.metrics helpers.""" + +import ast +import sys +from collections import defaultdict + +from _docslib import ( + call_name, + check_stale, + code, + constant, + description, + iter_python_files, + keyword, + load_section, + parse, + rel, + table, + write_page, +) + +HELPERS = { + "increment_counter": "counter", + "add_updown_counter": "up-down counter", + "record_histogram": "histogram", + "register_observable_gauge": "observable gauge", +} +# The helpers themselves take the name as a parameter. +SKIP = {"common/lib/metrics.py"} + + +def collect(): + metrics = defaultdict(lambda: {"types": set(), "files": set()}) + dynamic = set() + for path in iter_python_files(): + name = rel(path) + if name in SKIP: + continue + for node in ast.walk(parse(path)): + if not (isinstance(node, ast.Call) and call_name(node) in HELPERS): + continue + argument = node.args[0] if node.args else keyword(node, "metric_name") + metric = constant(argument) + if isinstance(metric, str): + metrics[metric]["types"].add(HELPERS[call_name(node)]) + metrics[metric]["files"].add(name) + else: + dynamic.add((name, ast.unparse(argument))) + return metrics, dynamic + + +def main(): + block = load_section("metrics") + metrics, dynamic = collect() + check_stale("metrics", block, metrics) + + rows = [ + [ + code(metric), + ", ".join(sorted(metrics[metric]["types"])), + "
".join(code(f) for f in sorted(metrics[metric]["files"])), + description(block, metric), + ] + for metric in sorted(metrics) + ] + sections = [ + f"The code emits {len(rows)} metric names.", + table(["Metric", "Type", "Emitted in", "Description"], rows), + ] + if dynamic: + print(f"warning: {len(dynamic)} dynamic metric names", file=sys.stderr) + sections += [ + "## Dynamic metric names", + "These calls compute the name at run time, so the table cannot list them.", + table( + ["File", "Expression"], + [[code(f), code(expr)] for f, expr in sorted(dynamic)], + ), + ] + write_page("metrics.md", "Metrics", "gen_metrics.py", block, sections) + + +if __name__ == "__main__": + main() diff --git a/scripts/docs/gen_ports.py b/scripts/docs/gen_ports.py new file mode 100755 index 00000000..7ccd49c8 --- /dev/null +++ b/scripts/docs/gen_ports.py @@ -0,0 +1,102 @@ +#!/usr/bin/env python3 +"""Generate docs/reference/ports.md from docker-compose.yml.""" + +import re + +import yaml + +from _docslib import ( + REPO, + check_stale, + code, + description, + load_section, + table, + write_page, +) + +VARIABLE = re.compile(r"^\$\{(?P\w+)(?::?-(?P[^}]*))?\}$") + + +def split_short_form(text): + """Split a short port mapping, keeping a ${VAR:-default} host part whole.""" + text, _, protocol = str(text).partition("/") + parts = re.findall(r"\$\{[^}]*\}|[^:]+", text) + if len(parts) == 1: + return "", parts[0], protocol or "tcp" + return parts[-2], parts[-1], protocol or "tcp" + + +def parse_port(spec): + """Return (host, host variable, container, protocol).""" + if isinstance(spec, dict): + host = str(spec.get("published", "")) + container = str(spec["target"]) + protocol = spec.get("protocol", "tcp") + else: + host, container, protocol = split_short_form(spec) + variable = "" + match = VARIABLE.match(host) + if match: + variable = match["name"] + host = match["default"] or "" + return host, variable, container, protocol + + +def image_label(service): + if "image" in service: + return code(service["image"].split("@")[0]) + build = service.get("build", {}) + dockerfile = build.get("dockerfile") if isinstance(build, dict) else None + return "built from " + code(str(dockerfile or build)).replace("./", "") + + +def dependencies(service): + depends = service.get("depends_on") or [] + return sorted(depends) + + +def main(): + block = load_section("ports") + compose = yaml.safe_load((REPO / "docker-compose.yml").read_text(encoding="utf-8")) + services = compose["services"] + check_stale("ports", block, services) + + published = [] + for name in sorted(services): + for spec in services[name].get("ports") or []: + host, variable, container, protocol = parse_port(spec) + published.append( + [ + code(name), + code(host) if host else "assigned by Docker", + code(container), + protocol, + code(variable) if variable else "fixed", + ] + ) + + rows = [] + for name in sorted(services): + service = services[name] + rows.append( + [ + code(name), + image_label(service), + ", ".join(code(p) for p in service.get("profiles") or []) or "always", + ", ".join(code(d) for d in dependencies(service)) or "none", + description(block, name), + ] + ) + + sections = [ + "## Published ports", + table(["Service", "Host port", "Container port", "Protocol", "Host port set by"], published), + "## Compose services", + table(["Service", "Image", "Profile", "Depends on", "Description"], rows), + ] + write_page("ports.md", "Ports and services", "gen_ports.py", block, sections) + + +if __name__ == "__main__": + main() diff --git a/scripts/docs/gen_routes.py b/scripts/docs/gen_routes.py new file mode 100755 index 00000000..a8897d54 --- /dev/null +++ b/scripts/docs/gen_routes.py @@ -0,0 +1,108 @@ +#!/usr/bin/env python3 +"""Generate docs/reference/api-routes.md from the decorators in api/api.py.""" + +import ast + +from _docslib import ( + REPO, + call_name, + check_stale, + code, + constant, + description, + keyword, + load_section, + parse, + table, + write_page, +) + +METHODS = {"get", "post", "put", "patch", "delete"} +AUTH_NONE = "none" +AUTH_DEPENDENCIES = {"get_api_key": "API key"} +AUTH_BODY_CALLS = {"validate_ingress_api_key": "ingress API key"} + + +def router_auth(tree): + """Map each router name to its auth label and prefix from include_router.""" + routers = {} + for node in ast.walk(tree): + if not (isinstance(node, ast.Call) and call_name(node) == "include_router"): + continue + router = node.args[0].id + label = AUTH_NONE + dependencies = keyword(node, "dependencies") + if dependencies is not None: + for dependency in ast.walk(dependencies): + if isinstance(dependency, ast.Name) and dependency.id in AUTH_DEPENDENCIES: + label = AUTH_DEPENDENCIES[dependency.id] + routers[router] = (label, constant(keyword(node, "prefix")) or "") + return routers + + +def body_auth(function): + for node in ast.walk(function): + if isinstance(node, ast.Call) and call_name(node) in AUTH_BODY_CALLS: + return AUTH_BODY_CALLS[call_name(node)] + return None + + +def collect(tree): + routers = router_auth(tree) + routes = [] + for function in ast.walk(tree): + if not isinstance(function, (ast.FunctionDef, ast.AsyncFunctionDef)): + continue + for decorator in function.decorator_list: + if not ( + isinstance(decorator, ast.Call) + and isinstance(decorator.func, ast.Attribute) + and decorator.func.attr in METHODS + and isinstance(decorator.func.value, ast.Name) + ): + continue + owner = decorator.func.value.id + if owner != "app" and owner not in routers: + continue + auth, prefix = routers.get(owner, (AUTH_NONE, "")) + tags = keyword(decorator, "tags") + routes.append( + { + "method": decorator.func.attr.upper(), + "path": prefix + constant(decorator.args[0]), + "auth": body_auth(function) or auth, + "status": constant(keyword(decorator, "status_code")) or 200, + "summary": constant(keyword(decorator, "summary")) or "", + "tags": [t.value for t in tags.elts] if tags is not None else [], + } + ) + return sorted(routes, key=lambda r: (r["path"], r["method"])) + + +def main(): + block = load_section("routes") + routes = collect(parse(REPO / "api" / "api.py")) + keys = [f"{r['method']} {r['path']}" for r in routes] + check_stale("routes", block, keys) + + rows = [ + [ + r["method"], + code(r["path"]), + r["auth"], + r["status"], + ", ".join(r["tags"]), + r["summary"], + description(block, key, required=False), + ] + for r, key in zip(routes, keys) + ] + sections = [ + f"`api/api.py` defines {len(rows)} routes.", + table(["Method", "Path", "Auth", "Success status", "Tag", "Summary", "Notes"], rows), + ] + write_page("api-routes.md", "API routes", "gen_routes.py", block, sections) + + +if __name__ == "__main__": + main() diff --git a/scripts/docs/render_diagrams.sh b/scripts/docs/render_diagrams.sh new file mode 100755 index 00000000..ee908701 --- /dev/null +++ b/scripts/docs/render_diagrams.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Render every docs/diagrams/*.mmd to SVG. +# +# Usage: render_diagrams.sh [output-dir] +# +# Output defaults to the source folder. +# MMDC path to mmdc; unset runs mermaid-cli through npx +# PUPPETEER_CONFIG optional puppeteer config file passed to mmdc with -p +# DIAGRAMS_DIR source folder, default docs/diagrams +set -euo pipefail + +repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" +cd "$repo" + +source_dir="${DIAGRAMS_DIR:-docs/diagrams}" +out_dir="${1:-$source_dir}" +theme="docs/diagrams/vconic-theme.json" +init_line="$(head -n 1 docs/diagrams/_init.txt)" + +if [[ -n "${MMDC:-}" ]]; then + mmdc=("$MMDC") +else + mmdc=(npx --yes @mermaid-js/mermaid-cli@12.2.0) +fi + +args=(--quiet -c "$theme" -b white) +if [[ -n "${PUPPETEER_CONFIG:-}" ]]; then + args+=(-p "$PUPPETEER_CONFIG") +fi + +shopt -s nullglob +sources=("$source_dir"/*.mmd) +if [[ ${#sources[@]} -eq 0 ]]; then + echo "render_diagrams: no .mmd files in $source_dir" + exit 0 +fi + +mkdir -p "$out_dir" +failed=() +for source in "${sources[@]}"; do + name="$(basename "$source" .mmd)" + if [[ "$(head -n 1 "$source")" != "$init_line" ]]; then + echo "render_diagrams: $source: first line must match docs/diagrams/_init.txt" >&2 + failed+=("$name") + continue + fi + if ! "${mmdc[@]}" "${args[@]}" -i "$source" -o "$out_dir/$name.svg"; then + failed+=("$name") + fi +done + +if [[ ${#failed[@]} -gt 0 ]]; then + echo "render_diagrams: failed: ${failed[*]}" >&2 + exit 1 +fi +echo "render_diagrams: rendered ${#sources[@]} diagrams to $out_dir"