honcho icon indicating copy to clipboard operation
honcho copied to clipboard

Add transactions to API

Open dr-frmr opened this issue 11 months ago • 1 comments

Summary by CodeRabbit

  • New Features

    • Introduced robust support for multi-step transactions, allowing users to group multiple operations into a single atomic transaction with commit and rollback capabilities.
    • Added new API endpoints for creating, committing, and rolling back transactions.
    • Added environment variable to control the maximum number of staged operations per transaction.
    • Provided a script to generate admin JWT tokens.
  • Improvements

    • Enhanced API endpoints for apps, users, sessions, messages, collections, and metamessages to support transaction context.
    • Updated documentation with a guide on using transactions and a Python context manager example.
  • Tests

    • Added comprehensive tests covering transaction lifecycle, isolation, commit/rollback, expiry, and error handling.
    • Introduced a secondary test client fixture for multi-client scenarios.
  • Bug Fixes

    • Improved error handling for transaction-related operations and enforced staged operation limits.
  • Chores

    • Updated environment and configuration templates to reflect new transaction features.

dr-frmr avatar May 06 '25 21:05 dr-frmr

Walkthrough

This update introduces a robust transaction staging and management system across the backend. It adds new transaction and staged operation models, a transaction-aware CRUD layer with staging and replay capabilities, API endpoints for transaction lifecycle management, and comprehensive tests. Documentation and environment configuration are updated to reflect these transactional features.

Changes

File(s) Change Summary
.env.template Added MAX_STAGED_OPERATIONS environment variable to control the maximum staged operations in a transaction.
pyproject.toml Added commented-out pytest logging options under [tool.pytest.ini_options].
scripts/create_admin_jwt.py New script to generate and print an admin JWT token using environment configuration.
src/crud.py Implemented transaction staging system: added @stageable decorator, transaction and staged operation management functions, updated all CRUD functions to support transaction_id, and integrated replay/rollback/commit logic.
src/main.py Registered the new transactions router, exposing transaction management endpoints.
src/models.py Added new ORM models: Transaction and StagedOperation with constraints and relationships.
src/routers/apps.py, src/routers/collections.py, src/routers/messages.py, src/routers/metamessages.py, src/routers/sessions.py, src/routers/users.py Added dependency injection of transaction_id to all relevant endpoints, propagating transaction context to CRUD operations. Some endpoints now explicitly disallow transaction headers.
src/routers/documents.py Added dependency to disallow transaction headers on document listing; updated parameter passing for document queries.
src/routers/transactions.py New router providing endpoints to begin, commit, and roll back transactions. Includes helper functions for transaction header parsing and validation.
tests/conftest.py Added secondary_client fixture for multi-client transaction tests.
tests/routes/test_documents.py Reformatted one test function for readability; no logic changes.
tests/routes/test_transactions.py New test suite covering transaction creation, commit, rollback, expiry, error cases, multi-operation atomicity, and multi-client scenarios.
docs/guides/overview.mdx Added a "Transactions" section with an example context manager and usage guide for atomic multi-step operations.
migrations/versions/53d6a802158b_add_transactions_and_staged_operations_.py Added migration script creating transactions and staged_operations tables with constraints and indexes.
migrations/env.py Ensured default schema is set to "public" if unset or empty in Alembic environment.
tests/routes/test_validation_api.py Added a mock chat function returning a fixed response, monkeypatched into the agent chat for testing.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant API (FastAPI)
  participant CRUD Layer
  participant DB

  Client->>API (POST /transactions/begin): Begin transaction
  API->>CRUD Layer: create_transaction()
  CRUD Layer->>DB: Insert Transaction
  DB-->>CRUD Layer: Transaction ID
  CRUD Layer-->>API: Transaction ID
  API-->>Client: Transaction ID

  loop For each staged operation
    Client->>API: API request (with X-Transaction-ID)
    API->>CRUD Layer: CRUD function (transaction_id)
    CRUD Layer->>DB: Replay staged ops, stage new op
    DB-->>CRUD Layer: Ack
    CRUD Layer-->>API: Response (not committed)
    API-->>Client: Response
  end

  alt Commit
    Client->>API (POST /transactions/{id}/commit): Commit transaction
    API->>CRUD Layer: commit_transaction(transaction_id)
    CRUD Layer->>DB: Replay staged ops, commit
    DB-->>CRUD Layer: Ack
    CRUD Layer-->>API: Success
    API-->>Client: Success
  else Rollback
    Client->>API (POST /transactions/{id}/rollback): Rollback transaction
    API->>CRUD Layer: rollback_transaction(transaction_id)
    CRUD Layer->>DB: Discard staged ops
    DB-->>CRUD Layer: Ack
    CRUD Layer-->>API: Success
    API-->>Client: Success
  end

Poem

In the warren of code, where transactions now hop,
Each change is a carrot, each commit a crop.
With staging and rollback, we binky with glee,
Atomic and safe as a rabbit can be!
🥕✨

— A jubilant CodeRabbit


📜 Recent review details

Configuration used: CodeRabbit UI Review profile: CHILL Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 32577854dd136841b8adb0ad5707bfa7d046a8fd and 19c2b886f0c92f5132e09388a672e836508f2cf7.

📒 Files selected for processing (2)
  • docs/guides/overview.mdx (1 hunks)
  • migrations/versions/53d6a802158b_add_transactions_and_staged_operations_.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • docs/guides/overview.mdx
  • migrations/versions/53d6a802158b_add_transactions_and_staged_operations_.py
✨ Finishing Touches
  • [ ] 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

coderabbitai[bot] avatar May 06 '25 21:05 coderabbitai[bot]