Skip to content

Conversation

@codegen-sh
Copy link

@codegen-sh codegen-sh bot commented May 17, 2025

User description

Overview

This PR enhances the Modal deployment infrastructure in the codegen-examples repository with improved robustness, better error handling, and updates to the latest Modal version (1.0.0).

Key Improvements

Main Deployer.sh Script

  • Added colorized output for better readability
  • Added Python version check to ensure compatibility
  • Improved error handling and user feedback
  • Added deployment verification
  • Added post-deployment options to view logs and status
  • Added sorting of examples for consistent display
  • Added ability to extract app names from deploy.sh scripts

Documentation

  • Created a comprehensive README.md for the examples directory
  • Added detailed documentation about the Deployer.sh script
  • Listed all deployable examples with descriptions

Individual deploy.sh Scripts

  • Updated to use Modal 1.0.0
  • Added colorized output for better readability
  • Added environment variable validation
  • Added deployment verification
  • Added webhook URL extraction and display
  • Improved error handling and user feedback

Template and Examples

  • Created a deploy.sh.template file as a reference for new examples
  • Updated slack_chatbot and linear_webhooks examples to use the latest Modal API
  • Added persistent volume support for better data management
  • Updated environment templates with all required variables

Testing

The deployment infrastructure has been tested with the following examples:

  • slack_chatbot
  • linear_webhooks

All examples deploy successfully and run as expected with the latest Modal version.

Next Steps

Future improvements could include:

  • Adding automated tests for deployment scripts
  • Implementing a CI/CD pipeline for automated deployment
  • Adding more detailed logging and monitoring capabilities
  • Creating a web dashboard for deployment status

💻 View my workAbout Codegen

Summary by Sourcery

Enhance and standardize the Modal-based deployment infrastructure across codegen-examples by updating to Modal 1.0.0, refactoring webhook handlers into ASGI FastAPI services, enriching deploy scripts with colorized output, version checks, environment validation, deployment verification, and post-deployment options, and by adding user-friendly documentation.

New Features:

  • Introduce an interactive, menu-driven Deployer.sh supporting concurrent deployments and post-deploy options to view logs and status.
  • Refactor Linear and Slack webhook handlers into ASGI FastAPI applications with signature verification, structured event models, and persistent logging via Modal volumes.

Enhancements:

  • Upgrade all deploy scripts and example code to Modal 1.0.0 with Python and Modal version checks, colorized output, and environment variable validation.
  • Add persistent volume support for FastAPI services and consolidate modal image builds for consistency.
  • Extract and sort example list in Deployer.sh for a consistent user experience.

Documentation:

  • Add a comprehensive README.md for the examples directory explaining prerequisites, usage, and available examples.
  • Provide a deploy.sh.template reference for creating new example deploy scripts.

PR Type

Enhancement, Documentation


Description

  • Major refactor of Modal deployment scripts for robustness and UX

    • Colorized output, version checks, error handling, and post-deploy options
    • Deployment verification and log/status viewing features
    • Environment variable validation and template improvements
  • Upgrade Modal-based examples to Modal 1.0.0 and FastAPI ASGI services

    • Refactor linear_webhooks to FastAPI ASGI app with signature verification
    • Add persistent volume support for data storage
    • Update slack_chatbot deployment and API for new Modal version
  • Add comprehensive documentation and deployment templates

    • New README.md for examples and deployment guide
    • Add deploy.sh.template for new Modal examples
  • Improve user feedback and error messages across all scripts


Changes walkthrough 📝

Relevant files
Enhancement
6 files
Deployer.sh
Robust, interactive deployer with color, checks, and post-deploy
options
+141/-29
deploy.sh
Improved deployment script with validation and feedback   
+42/-10 
deploy.sh
Enhanced deployment script with env checks and feedback   
+46/-11 
webhooks.py
Refactor to FastAPI ASGI app, add signature verification, Modal 1.0.0
+153/-98
api.py
Update Modal app name, add persistent volume, deploy entrypoint
+13/-2   
.env.template
Standardize env template formatting and variable names     
+6/-5     
Documentation
2 files
README.md
Add comprehensive documentation for examples and deployment
+78/-0   
deploy.sh.template
Add template for new Modal deploy scripts with best practices
+97/-0   

Need help?
  • Type /help how to ... in the comments thread for any questions about Qodo Merge usage.
  • Check out the documentation for more information.
  • @sourcery-ai
    Copy link

    sourcery-ai bot commented May 17, 2025

    Reviewer's Guide

    Refactors the deployment tool by extending the main Deployer.sh with ANSI colorization, version and environment validation, deployment verification and interactive post-deploy options; adds comprehensive documentation and templates; and updates individual example scripts and apps to Modal 1.0.0—including refactoring the Linear webhooks service into a FastAPI ASGI app with Pydantic models, HMAC signature checks, file-based logging, persistent volumes, and improved Slack chatbot support.

    Sequence Diagram for Linear Webhook Processing in Modal

    sequenceDiagram
        participant Linear as Linear Service
        participant ModalEndpoint as Modal Endpoint (/webhook)
        participant FastAPIApp as FastAPI App (linear-webhooks)
        participant Logger as log_event()
        participant EventHandler as Event Handler (issue/comment)
        participant Volume as Persistent Volume (linear-data)
    
        Linear->>ModalEndpoint: POST /webhook (event data, signature)
        ModalEndpoint->>FastAPIApp: Forward request
        activate FastAPIApp
        FastAPIApp->>FastAPIApp: Verify signature (HMAC SHA256)
        FastAPIApp->>FastAPIApp: Parse request to LinearEvent model
        FastAPIApp->>Logger: log_event(LinearEvent)
        activate Logger
        Logger->>Volume: Write event to JSONL file (/data/linear_events_...)
        deactivate Logger
        alt Event type is "Issue"
            FastAPIApp->>EventHandler: handle_issue_event(LinearEvent)
        else Event type is "Comment"
            FastAPIApp->>EventHandler: handle_comment_event(LinearEvent)
        else Other event type
            FastAPIApp->>FastAPIApp: Prepare "ignored" response
        end
        activate EventHandler
        EventHandler-->>FastAPIApp: Processed event response
        deactivate EventHandler
        FastAPIApp-->>ModalEndpoint: HTTP Response
        ModalEndpoint-->>Linear: HTTP Response
        deactivate FastAPIApp
    
    Loading

    File-Level Changes

    Change Details Files
    Enhanced main Deployer.sh with robust checks, colorized feedback, and interactive features
    • Added ANSI color codes for banners, prompts and status messages
    • Implemented Python and Modal version detection with warnings
    • Introduced example sorting for consistent menus
    • Added deployment verification function
    • Provided post-deployment options to view logs or deployment status
    • Enabled automated app name extraction for log/status commands
    codegen-examples/examples/Deployer.sh
    Added documentation and a deploy script template
    • Created README.md outlining example categories and deployer usage
    • Listed all deployable examples with descriptions
    • Introduced deploy.sh.template as a reference for new examples
    codegen-examples/examples/README.md
    codegen-examples/examples/deploy.sh.template
    Updated individual deploy.sh scripts with standardized deployment flow
    • Pinned Modal to version 1.0.0 and checked CLI installation
    • Added ANSI color output and environment variable validation
    • Verified deployment success and displayed webhook URLs
    • Enforced .env template creation and validation before deploy
    codegen-examples/examples/slack_chatbot/deploy.sh
    codegen-examples/examples/linear_webhooks/deploy.sh
    Refactored Linear webhooks handler into a FastAPI ASGI service
    • Replaced CodegenApp with FastAPI app decorated as Modal ASGI function
    • Defined Pydantic model for incoming events
    • Implemented HMAC signature verification
    • Logged events to persistent volume in JSONL format
    • Modularized issue and comment handlers with typed responses
    codegen-examples/examples/linear_webhooks/webhooks.py
    Enhanced Slack chatbot application with persistent storage and correct context formatting
    • Corrected code context block formatting in answer_question
    • Renamed Modal app and added persistent volume for vector index
    • Initialized deploy entrypoint in main for direct runs
    • Updated FastAPI ASGI decorator and volume mounting
    codegen-examples/examples/slack_chatbot/api.py

    Tips and commands

    Interacting with Sourcery

    • Trigger a new review: Comment @sourcery-ai review on the pull request.
    • Continue discussions: Reply directly to Sourcery's review comments.
    • Generate a GitHub issue from a review comment: Ask Sourcery to create an
      issue from a review comment by replying to it. You can also reply to a
      review comment with @sourcery-ai issue to create an issue from it.
    • Generate a pull request title: Write @sourcery-ai anywhere in the pull
      request title to generate a title at any time. You can also comment
      @sourcery-ai title on the pull request to (re-)generate the title at any time.
    • Generate a pull request summary: Write @sourcery-ai summary anywhere in
      the pull request body to generate a PR summary at any time exactly where you
      want it. You can also comment @sourcery-ai summary on the pull request to
      (re-)generate the summary at any time.
    • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
      request to (re-)generate the reviewer's guide at any time.
    • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
      pull request to resolve all Sourcery comments. Useful if you've already
      addressed all the comments and don't want to see them anymore.
    • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
      request to dismiss all existing Sourcery reviews. Especially useful if you
      want to start fresh with a new review - don't forget to comment
      @sourcery-ai review to trigger a new review!

    Customizing Your Experience

    Access your dashboard to:

    • Enable or disable review features such as the Sourcery-generated pull request
      summary, the reviewer's guide, and others.
    • Change the review language.
    • Add, remove or edit custom review instructions.
    • Adjust other review settings.

    Getting Help

    @korbit-ai
    Copy link

    korbit-ai bot commented May 17, 2025

    By default, I don't review pull requests opened by bots. If you would like me to review this pull request anyway, you can request a review via the /korbit-review command in a comment.

    @coderabbitai
    Copy link

    coderabbitai bot commented May 17, 2025

    Important

    Review skipped

    Bot user detected.

    To trigger a single review, invoke the @coderabbitai review command.

    You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


    🪧 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? Join our Discord community 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 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.

    @codegen-sh
    Copy link
    Author

    codegen-sh bot commented May 17, 2025

    I see a check failed - I'm on it! 🫡

    💻 View my work

    @Zeeeepa Zeeeepa marked this pull request as ready for review May 17, 2025 15:30
    @Zeeeepa Zeeeepa merged commit 67d323c into develop May 17, 2025
    11 of 15 checks passed
    @korbit-ai
    Copy link

    korbit-ai bot commented May 17, 2025

    By default, I don't review pull requests opened by bots. If you would like me to review this pull request anyway, you can request a review via the /korbit-review command in a comment.

    @codiumai-pr-agent-free
    Copy link

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 3 🔵🔵🔵⚪⚪
    🧪 No relevant tests
    🔒 No security concerns identified
    ⚡ Recommended focus areas for review

    Error Handling

    The exception handling in the webhook endpoint could be improved. The current implementation catches all exceptions generically, which might mask specific issues. Consider handling different exception types separately.

    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Invalid event data: {str(e)}")
    Missing Backtick

    The code block in the context string is missing a closing backtick which could cause formatting issues when displaying code in responses.

    context += f"File: {file.filepath}\n```\n{file.content}```\n\n"
    App Name Extraction

    The app name extraction from deploy.sh scripts uses a simple grep pattern that might be fragile. It could fail to extract app names if the deploy.sh files have different formatting.

    app_name=$(grep -o "modal app [a-zA-Z0-9_-]*" "$SCRIPT_DIR/$example/deploy.sh" | head -1 | awk '{print $3}')
    if [ -z "$app_name" ]; then

    @codiumai-pr-agent-free
    Copy link

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Impact
    Possible issue
    Fix request body consumption

    The webhook handler needs to read the request body twice - once for signature
    verification and once for JSON parsing. Since FastAPI's request.body() can only
    be read once, you should store the body content in a variable to reuse it for
    both operations.

    codegen-examples/examples/linear_webhooks/webhooks.py [63-77]

     # Verify signature if provided
     if x_linear_signature:
         signing_secret = os.environ.get("LINEAR_SIGNING_SECRET")
         if not signing_secret:
             raise HTTPException(status_code=500, detail="LINEAR_SIGNING_SECRET not configured")
     
         body = await request.body()
         signature = hmac.new(
             signing_secret.encode("utf-8"),
             body,
             hashlib.sha256,
         ).hexdigest()
     
         if not hmac.compare_digest(signature, x_linear_signature):
             raise HTTPException(status_code=401, detail="Invalid signature")
    +        
    +    # Parse event data
    +    try:
    +        data = json.loads(body)
    +        event = LinearEvent(**data)
    +    except Exception as e:
    +        raise HTTPException(status_code=400, detail=f"Invalid event data: {str(e)}")
    +else:
    +    # Parse event data
    +    try:
    +        data = await request.json()
    +        event = LinearEvent(**data)
    +    except Exception as e:
    +        raise HTTPException(status_code=400, detail=f"Invalid event data: {str(e)}")
    • Apply / Chat
    Suggestion importance[1-10]: 9

    __

    Why: The current code attempts to read the request body twice (once via await request.body() for signature verification and again via await request.json() for parsing) if x_linear_signature is present. This will cause an error during JSON parsing as the body stream would have already been consumed. The suggested change correctly reuses the body read for signature verification, fixing a critical functional bug.

    High
    General
    Update Pydantic serialization

    The dict() method is deprecated in newer versions of Pydantic. Use model_dump()
    instead for Pydantic v2 compatibility, which is more future-proof and provides
    better serialization.

    codegen-examples/examples/linear_webhooks/webhooks.py [100-105]

     def log_event(event: LinearEvent):
         """Log Linear event to file."""
         log_file = f"/data/linear_events_{datetime.now().strftime('%Y%m%d')}.jsonl"
         with open(log_file, "a") as f:
    -        f.write(json.dumps(event.dict()) + "\n")
    +        try:
    +            # Try Pydantic v2 method first
    +            event_dict = event.model_dump()
    +        except AttributeError:
    +            # Fall back to Pydantic v1 method
    +            event_dict = event.dict()
    +        f.write(json.dumps(event_dict) + "\n")
         print(f"Logged {event.type} {event.action} event")
    • Apply / Chat
    Suggestion importance[1-10]: 6

    __

    Why: The suggestion correctly points out that event.dict() is deprecated in Pydantic V2. The improved_code offers a robust solution by trying event.model_dump() (for V2) and falling back to event.dict() (for V1), enhancing compatibility and maintainability.

    Low
    • More

    @codegen-sh
    Copy link
    Author

    codegen-sh bot commented May 17, 2025

    I've fixed the failing pre-commit checks in PR #141. The issue was related to formatting in some of the Modal deployment infrastructure files. I've committed and pushed the fixes to the same branch.

    The changes include:

    • Fixed formatting in .env.template files
    • Adjusted line endings and whitespace in deployment scripts
    • Made other minor formatting adjustments to comply with the pre-commit hooks

    The PR should now pass the checks and be ready for review.

    💻 View my work • React 👍 or 👎

    Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

    Projects

    None yet

    Development

    Successfully merging this pull request may close these issues.

    2 participants