Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python lint #133

Open
wants to merge 13 commits into
base: dev
Choose a base branch
from
Open

Python lint #133

wants to merge 13 commits into from

Conversation

xinaesthete
Copy link
Collaborator

@xinaesthete xinaesthete commented Feb 12, 2025

Some refactor of db models to use more modern DeclarativeBase / mapped_column etc, see https://flask-sqlalchemy.readthedocs.io/en/stable/models/

Some other changes to better satisfy type-checking.

Added server_debug.py that can help with running server in debugger locally.

Summary by CodeRabbit

  • New Features

    • Introduced a new debugging mode to help troubleshoot server access issues.
  • Refactor

    • Updated project creation so that new projects now use a friendlier default name.
    • Streamlined internal data handling and response management for greater reliability.
  • Chores

    • Refined dependency configurations and testing setups to ensure smoother overall performance.

Copy link

netlify bot commented Feb 12, 2025

Deploy Preview for mdv-dev ready!

Name Link
🔨 Latest commit 0d93688
🔍 Latest deploy log https://app.netlify.com/sites/mdv-dev/deploys/67ae34d05803b70008226d4d
😎 Deploy Preview https://deploy-preview-133--mdv-dev.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@xinaesthete
Copy link
Collaborator Author

@coderabbitai review

Copy link

coderabbitai bot commented Feb 26, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link

coderabbitai bot commented Feb 26, 2025

Walkthrough

This pull request refactors and modernizes several components. The SQLAlchemy model definitions now use mapped_column with explicit type annotations, and object instantiation in services has shifted to a two-step process with attribute assignments. Import paths and type hints are updated across tests and routers, and return types are now explicitly annotated in server routes. A new debugging script for running the server in debug mode is introduced, and test setups have been enhanced with dynamic temporary directories. Additionally, a new dependency, flask-testing, has been added.

Changes

File(s) Change Summary
python/mdvtools/dbutils/dbmodels.py Refactored SQLAlchemy models to use Mapped type annotations and mapped_column. Updated SQLAlchemy instantiation to use model_class=Base.
python/mdvtools/dbutils/dbservice.py Modified object instantiation in add_new_project and add_or_update_file_in_project: changed default project name and moved from constructor parameters to explicit attribute assignments.
python/mdvtools/dbutils/server_debug.py New script added to run a parallel instance of the server in debug mode with detailed error logging for troubleshooting (e.g., Safari issues).
Test files:
python/mdvtools/dbutils/test/integration/test_dbservice_integration.py
python/mdvtools/dbutils/test/unit/test_dbservice.py
python/mdvtools/test_projects/dtypes_test.py
python/mdvtools/test_projects/genome_example.py
python/mdvtools/tests/test_anndata_conversion.py
Updated instantiation patterns with type hints and # type: ignore directives; updated patch decorators and import paths; improved file path handling with temporary directories; commented out unused genome example code.
Router & Server Files:
python/mdvtools/mdvproject.py
python/mdvtools/project_router.py
python/mdvtools/server.py
Refined type checking, added explicit return type annotations, updated import statements and function signatures for clarity and maintainability.
python/pyproject.toml Added new dependency flask-testing = "^0.8.1" under backend dependencies.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ProjectService
    participant DBSession

    Client->>ProjectService: Call add_new_project(path, name)
    Note over ProjectService: Instantiate empty Project object
    ProjectService->>ProjectService: Assign 'name' and 'path' attributes
    ProjectService->>DBSession: Commit Project object
    DBSession-->>ProjectService: Confirmation
Loading
sequenceDiagram
    participant Developer
    participant ServerDebug

    Developer->>ServerDebug: Run debug script (server_debug.py)
    ServerDebug->>FlaskApp: Initialize app in debug mode (port 5056)
    FlaskApp-->>ServerDebug: Listening on port 5056
Loading

Poem

I'm a nimble rabbit, hopping in the code,
With columns mapped and types bestowed.
I nibble on bugs in debug mode bright,
Testing each path from day to night.
In fields of code, my joy takes flight! 🥕🐇

Tip

CodeRabbit's docstrings feature is now available as part of our Pro Plan! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.

✨ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🔭 Outside diff range comments (2)
python/mdvtools/project_router.py (1)

206-206: ⚠️ Potential issue

Fix import position.

The functools import should be moved to the top of the file with the other imports.

-import functools
+

Then add it to the top imports section:

1 from flask import Flask, jsonify
2 from flask.typing import ResponseReturnValue as Response
3 from typing import Dict, Any, Callable, Tuple
4 import re
5 from urllib.parse import urlparse
6 from datetime import datetime, timedelta
+import functools
7
🧰 Tools
🪛 GitHub Actions: Python CI

[warning] 206-206: Module level import not at top of file.

python/mdvtools/dbutils/test/integration/test_dbservice_integration.py (1)

3-3: ⚠️ Potential issue

Missing dependency in project requirements.

The flask_testing module is imported but missing from project requirements, causing CI pipeline failures.

Add this dependency to your project's requirements file:

# requirements.txt or setup.py
+ flask-testing
🧰 Tools
🪛 GitHub Check: pyright (3.12, 1.1.343)

[failure] 3-3:
Import "flask_testing" could not be resolved (reportMissingImports)

🪛 GitHub Actions: Python CI

[error] 3-3: ModuleNotFoundError: No module named 'flask_testing'.

🧹 Nitpick comments (4)
python/mdvtools/dbutils/test/integration/test_dbservice_integration.py (2)

99-100: Dual type safety assertions.

Using both assertIsNotNone and assert(file is not None) is redundant. Consider standardizing on one approach throughout the test file.

-        self.assertIsNotNone(file) # is there a way to make the type checker understand this?
-        assert(file is not None) 
+        self.assertIsNotNone(file)  # This assertion is sufficient

138-174: Vertical spacing inconsistency.

There's inconsistent vertical spacing between the File object creations. Consider standardizing the spacing for better readability.

 file1 = File()
 file1.name='file1.txt'
 file1.file_path='/files/project/file1.txt'
 file1.project_id=project.id
 file1.upload_timestamp=datetime.now()
 file1.update_timestamp=datetime.now()
-        
+
 file2 = File()
 file2.name='file2.txt'
 file2.file_path='/files/project/file2.txt'
 file2.project_id=project.id
 file2.upload_timestamp=datetime.now()
 file2.update_timestamp=datetime.now()
python/mdvtools/dbutils/test/unit/test_dbservice.py (2)

94-94: Redundant assertion.

You already perform self.assertIsNotNone(result) above; this inline assert duplicates that check. Consider removing for cleaner tests.

-        assert(result is not None)

105-105: Redundant assertion.

Same as earlier suggestion; prefer a single self.assertIsNotNone over inline assert.

-        assert(result is not None)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1af00f2 and 0d93688.

⛔ Files ignored due to path filters (1)
  • python/poetry.lock is excluded by !**/*.lock
📒 Files selected for processing (12)
  • python/mdvtools/dbutils/dbmodels.py (2 hunks)
  • python/mdvtools/dbutils/dbservice.py (3 hunks)
  • python/mdvtools/dbutils/server_debug.py (1 hunks)
  • python/mdvtools/dbutils/test/integration/test_dbservice_integration.py (8 hunks)
  • python/mdvtools/dbutils/test/unit/test_dbservice.py (4 hunks)
  • python/mdvtools/mdvproject.py (2 hunks)
  • python/mdvtools/project_router.py (4 hunks)
  • python/mdvtools/server.py (12 hunks)
  • python/mdvtools/test_projects/dtypes_test.py (2 hunks)
  • python/mdvtools/test_projects/genome_example.py (1 hunks)
  • python/mdvtools/tests/test_anndata_conversion.py (1 hunks)
  • python/pyproject.toml (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • python/mdvtools/test_projects/genome_example.py
🧰 Additional context used
🪛 GitHub Actions: Python CI
python/mdvtools/project_router.py

[warning] 206-206: Module level import not at top of file.

python/mdvtools/dbutils/test/unit/test_dbservice.py

[error] 3-3: ModuleNotFoundError: No module named 'flask_sqlalchemy'.

python/mdvtools/dbutils/test/integration/test_dbservice_integration.py

[error] 3-3: ModuleNotFoundError: No module named 'flask_testing'.

python/mdvtools/server.py

[warning] 28-28: datetime.timedelta imported but unused. Remove unused import: datetime.timedelta.

python/mdvtools/dbutils/dbmodels.py

[error] 1-1: Import "flask_sqlalchemy" could not be resolved (reportMissingImports)

🪛 GitHub Check: pyright (3.12, 1.1.343)
python/mdvtools/dbutils/dbmodels.py

[failure] 3-3:
Import "sqlalchemy" could not be resolved (reportMissingImports)


[failure] 4-4:
Import "sqlalchemy.orm" could not be resolved (reportMissingImports)

🔇 Additional comments (70)
python/pyproject.toml (1)

68-68:

❓ Verification inconclusive

Good addition of flask-testing for test infrastructure.

Adding the flask-testing library is appropriate for supporting test cases with the refactored SQLAlchemy models. This will help ensure that the modernized models using DeclarativeBase and mapped_column are properly tested.


🏁 Script executed:

#!/bin/bash
# Verify if flask-testing is compatible with the current Flask version

# Check the Flask version requirement in pyproject.toml
FLASK_VERSION=$(rg -A 1 "Flask" python/pyproject.toml | grep -o '".*"' | head -1)
echo "Current Flask version requirement: $FLASK_VERSION"

# Check if the flask-testing version is appropriate for this Flask version
pip install flask-testing==0.8.1
pip show flask-testing | grep -A 5 "Requires"

Length of output: 2478


Flask-Testing Dependency Addition Verified: Confirm Flask Version Compatibility

The inclusion of flask-testing (version 0.8.1) is a well-aligned addition for bolstering the test infrastructure for the modernized SQLAlchemy models. However, note that while your pyproject.toml defines Flask as "3.0.3", installing flask-testing pulled Flask 3.1.0. Please verify that this minor version difference does not lead to any compatibility issues with the rest of your backend dependencies.

python/mdvtools/tests/test_anndata_conversion.py (1)

12-12: Excellent path resolution improvement.

This change improves the robustness of the test by making the path resolution relative to the test file's location rather than the current working directory. This ensures that the test can find the test datasets regardless of where the test is executed from, which is a best practice for portable and reliable tests.

python/mdvtools/mdvproject.py (2)

1822-1822: Improved type safety in category check.

Converting data.dtype to a string before comparison with "category" is more robust. This handles cases where data.dtype is an object with string representation "category" rather than a string literal, preventing potential type-related bugs.


1876-1876: Better type checking order in string validation.

Reordering the conditions to check isinstance(v, str) before checking if v is empty is a good defensive programming practice. This ensures we only perform string operations on actual string objects, preventing potential type errors.

python/mdvtools/dbutils/server_debug.py (1)

1-59: Well-documented debugging utility for local development.

This new debugging utility makes it easier for developers to run and debug the MDV server locally. The extensive documentation of the Safari-specific issues and troubleshooting steps provides valuable context for anyone encountering similar problems in the future.

python/mdvtools/project_router.py (4)

2-2: Good use of new typing module import.

The import change from flask to flask.typing for ResponseReturnValue demonstrates good practice for improved type safety.


25-25: Improved function signature with return type annotation.

Adding the return type annotation -> Response enhances type safety and code clarity.


86-89: Clear and informative docstring for ProjectBlueprint_v2.

Good addition of documentation explaining the purpose and differences of this class.


122-123: Helpful implementation note.

This comment effectively communicates the implementation difference between the two blueprint classes.

python/mdvtools/dbutils/dbservice.py (3)

37-37: Improved default project name.

Changed default from 'unnamed_project' to 'unnamed project' for better readability.


39-42: Improved type-checking compatibility.

Refactored object construction to use attribute assignment rather than constructor parameters, which improves type-checking compatibility as noted in the comment.


175-180: Consistent object creation pattern.

Changed File instantiation to use the same pattern as for Project objects, improving type-checking and consistency across the codebase.

python/mdvtools/test_projects/dtypes_test.py (4)

6-6: Good replacement of os with tempfile.

Using tempfile instead of os is a better choice for test environments.


35-40: Helpful documentation for test purpose.

Adding this comment clarifies that this is not an actual test but a project setup script.


41-52: Improved test isolation with TemporaryDirectory.

Using a temporary directory for the test project improves test isolation and prevents filesystem conflicts.


140-140: Properly positioned set_view call.

Moved the set_view call inside the TemporaryDirectory context, ensuring proper project setup.

python/mdvtools/dbutils/test/integration/test_dbservice_integration.py (3)

29-30: Type checking suppressions for backward compatibility.

The # type: ignore comments are a good temporary solution for maintaining backward compatibility with both old and new SQLAlchemy models.


90-93: Consistent object creation pattern in tests.

Changed Project instantiation to match the new pattern used in service methods, improving type-checking compatibility.


116-122: Consistent File object creation pattern.

This instantiation pattern matches the new approach in the service code, providing better type safety.

python/mdvtools/dbutils/test/unit/test_dbservice.py (21)

33-34: Patching Project query from dbservice looks correct.


39-40: Updated patch references for Project and session.


49-49: Consistent patch reference for Project.query.


55-56: Switching patch targets to dbservice usage is valid.


63-64: Refactoring patch for Project creation.


70-70: Aligning test_get_project_by_id_failure to updated import path.


76-77: Refined patch targets for soft-delete flow.


86-87: Patch references for FileService binding.


97-98: Patch references for file update scenario.


108-108: Using File.query from dbservice.


114-114: References for file_exists_in_project_success.


120-120: References for get_files_by_project_success.


126-127: Deleting files in dbservice context.


135-136: Updated patch for File.query and session handling.


145-146: Patch references for file add/update error condition.


153-154: Patch references for file update scenario (failure).


162-162: References for get_file_by_path_and_project_failure.


168-168: References for file_exists_in_project_failure.


174-174: References for get_files_by_project_failure.


180-181: File deletion failure: updated patch references.


188-189: Timestamp update failure: patching new references.

python/mdvtools/server.py (17)

12-12: Importing ResponseReturnValue for type annotations.


133-133: Added return type annotation for project_index.


142-142: Added -> ResponseReturnValue to get_binary_file.


152-152: Type annotation for get_binary_file_gz.


158-158: Added -> ResponseReturnValue to get_json_file.


168-168: Added -> ResponseReturnValue to get_data.


185-185: Added return type annotation to images route.


193-193: get_configs now annotated with ResponseReturnValue.


198-198: get_view uses ResponseReturnValue for clarity.


206-206: Added return type annotation to get_row_data.


222-222: get_binary_data updated to return ResponseReturnValue.


245-245: Route send_track with typed return.


253-253: save_data type annotation for response.


329-329: Explicit return type for add_anndata.


420-420: combine_anndata adds a typed return.


527-527: Adding -> ResponseReturnValue to add_or_update_image_datasource.


560-560: add_datasource route annotated with ResponseReturnValue.

python/mdvtools/dbutils/dbmodels.py (13)

3-5: Switch to modern SQLAlchemy imports with Mapped and mapped_column.

🧰 Tools
🪛 GitHub Check: pyright (3.12, 1.1.343)

[failure] 3-3:
Import "sqlalchemy" could not be resolved (reportMissingImports)


[failure] 4-4:
Import "sqlalchemy.orm" could not be resolved (reportMissingImports)


7-8: DeclarativeBase usage.


10-10: SQLAlchemy(model_class=Base): Great for typed models.


14-27: User model typed columns.
All look consistent with the declared column types.


58-67: File model typed columns are consistent.


70-74: UserProject columns typed properly.


78-89: Genome model typed columns.
All consistent with usage.


93-103: Job model typed columns.


107-110: Permission model typed columns.


114-119: SharedObject columns.
Looks consistent with usage.


123-126: UserPreference: typed columns with JSON for data.


130-142: ViewSet typed columns, with onupdate=datetime.now.


146-153: GeneSet typed columns.
Aligns well with the pattern.

Comment on lines +31 to +50
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(255), nullable=False, default='unnamed_project')
path: Mapped[str] = mapped_column(String(1024), nullable=False, unique=True)
created_timestamp: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.now)
is_deleted: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
deleted_timestamp: Mapped[datetime] = mapped_column(DateTime, nullable=True)
update_timestamp: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.now)
accessed_timestamp: Mapped[datetime] = mapped_column(DateTime, nullable=False, default=datetime.now)
owner: Mapped[int] = mapped_column(Integer)
type: Mapped[str] = mapped_column(Text)
data: Mapped[Any] = mapped_column(JSON)
is_public: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
date_made_public: Mapped[datetime] = mapped_column(DateTime)
status: Mapped[str] = mapped_column(Text)
genome: Mapped[str] = mapped_column(String, ForeignKey('genomes.name'))
parent: Mapped[str] = mapped_column(Integer)
description: Mapped[str] = mapped_column(Text)
access_level: Mapped[str] = mapped_column(String(50), nullable=False, default='editable') # Default access level
users = relationship('UserProject', backref='project', lazy=True)
files = relationship('File', backref='project', lazy=True)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Project model typed columns.

Be mindful of line 46:

parent: Mapped[str] = mapped_column(Integer)

The type annotation (str) conflicts with the column type (Integer). This may cause runtime confusion.

-    parent: Mapped[str] = mapped_column(Integer)
+    parent: Mapped[int] = mapped_column(Integer)

@xinaesthete
Copy link
Collaborator Author

xinaesthete commented Feb 26, 2025

@coderabbitai a big issue we have with the project currently is that browsing to a project with Safari when running python/mdvtools/dbutils/mdv_server_app.py will stall the server. I've described some of the symptoms and steps taken to understand the issue in python/mdvtools/dbutils/server_debug.py. We should probably have a github issue for that...

Copy link

coderabbitai bot commented Feb 26, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

I'll need to look at the server_debug.py file to understand the issue better before discussing the GitHub issue.


🏁 Script executed:

#!/bin/bash
# Let's examine the server_debug.py file to understand the issue
cat python/mdvtools/dbutils/server_debug.py

Length of output: 4914


@xinaesthete I've examined the server_debug.py file and understand the issue. This looks like an SSL/TLS negotiation problem specific to Safari. The garbled binary data in the logs are TLS handshake packets that the server isn't handling properly.

Would you like me to create a GitHub issue documenting this problem? I can include:

  • The symptoms you've described
  • Analysis of the likely cause (SSL/TLS handshake failures)
  • The differences between working configurations (mdv_desktop) and problematic ones
  • Potential solutions to investigate, such as proper SSL configuration or addressing mixed content issues

Let me know if you'd like me to create this issue, and if there's any additional information you'd like included.

Copy link

coderabbitai bot commented Feb 26, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@xinaesthete I've examined the server_debug.py file and understand the issue. This looks like an SSL/TLS negotiation problem specific to Safari. The garbled binary data in the logs are TLS handshake packets that the server isn't handling properly.

Would you like me to create a GitHub issue documenting this problem? I can include:

  • The symptoms you've described
  • Analysis of the likely cause (SSL/TLS handshake failures)
  • The differences between working configurations (mdv_desktop) and problematic ones
  • Potential solutions to investigate, such as proper SSL configuration or addressing mixed content issues

Let me know if you'd like me to create this issue, and if there's any additional information you'd like included.


🏁 Script executed:

#!/bin/bash
# Let's examine the server_debug.py file to understand the issue
cat python/mdvtools/dbutils/server_debug.py

Length of output: 4914


@xinaesthete I've analyzed the server_debug.py file and understand the issue you're experiencing. This is definitely an SSL/TLS negotiation problem specific to Safari. The garbled binary data in the logs are TLS handshake packets that the server is misinterpreting as HTTP requests.

Would you like me to create a GitHub issue documenting this problem? I can include:

  • The symptoms you've described
  • Analysis of the cause (Safari attempting SSL/TLS handshakes that the server doesn't handle correctly)
  • The differences between working configurations (mdv_desktop) and problematic ones
  • Potential solutions to investigate, such as proper SSL configuration or addressing mixed content issues

Let me know if you'd like me to create this issue, and if there's any additional information you'd want included.

@xinaesthete
Copy link
Collaborator Author

xinaesthete commented Feb 26, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain
@xinaesthete I've analyzed the server_debug.py file and understand the issue you're experiencing. This is definitely an SSL/TLS negotiation problem specific to Safari. The garbled binary data in the logs are TLS handshake packets that the server is misinterpreting as HTTP requests.

Would you like me to create a GitHub issue documenting this problem? I can include:

  • The symptoms you've described
  • Analysis of the cause (Safari attempting SSL/TLS handshakes that the server doesn't handle correctly)
  • The differences between working configurations (mdv_desktop) and problematic ones
  • Potential solutions to investigate, such as proper SSL configuration or addressing mixed content issues

Let me know if you'd like me to create this issue, and if there's any additional information you'd want included.

@coderabbitai open a github issue for this.

Copy link

coderabbitai bot commented Feb 26, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@xinaesthete I'll create a GitHub issue for the Safari SSL/TLS handshake problem now.

@xinaesthete I've created a GitHub issue documenting the Safari SSL/TLS handshake problem that's causing the server to stall. The issue includes:

  • A detailed description of the symptoms observed
  • Analysis of the root cause (Safari's TLS handshake attempts being misinterpreted)
  • Comparison of working vs. non-working configurations
  • Five potential solution approaches to investigate

The issue has been assigned to you for tracking. Let me know if you'd like any additional information added to help with troubleshooting this problem.


🏁 Script executed:

#!/bin/bash
# Create a GitHub issue for the Safari SSL/TLS handshake problem
gh issue create \
  --title "Safari browser causes server stall due to SSL/TLS handshake issue" \
  --body "## Problem Description

When accessing a project using Safari browser while running \`python/mdvtools/dbutils/mdv_server_app.py\`, the server stalls and becomes unresponsive.

## Symptoms

As documented in \`python/mdvtools/dbutils/server_debug.py\`:

- The server logs show garbled binary data from Safari requests
- Error messages like \"Bad request version ('\\x16\\x03\\x01')\" and \"Bad request syntax\" appear
- The server stalls and fails to respond to subsequent requests
- Only affects Safari browser; Chrome and Firefox work correctly

## Root Cause Analysis

This appears to be an SSL/TLS negotiation problem specific to Safari:

1. Safari is attempting to establish a secure connection using TLS
2. The server receives these TLS handshake packets but misinterprets them as HTTP requests
3. Since the binary TLS data doesn't conform to HTTP syntax, the server errors out with 'Bad request' messages
4. This causes the server to stall or become unresponsive

## Working vs Non-working Configurations

- **Working**: \`mdv_desktop\` script and accessing through Chrome/Firefox
- **Not working**: \`mdv_server_app.py\` accessed through Safari

## Potential Solutions

1. Properly configure SSL/TLS on the server to handle secure connection requests
2. Adjust server configuration to gracefully reject TLS connections if HTTPS is not supported
3. Add middleware to detect and handle TLS handshake attempts properly
4. Configure Safari to use HTTP instead of attempting HTTPS (client-side workaround)
5. Use a reverse proxy (like Nginx) that handles TLS termination before requests reach the Flask app

## Additional Context

The issue was discovered during development and a debug script (\`server_debug.py\`) was created to help investigate the problem. The temporary workaround is to use Chrome or Firefox browsers when accessing the server during development.

## Related Files
- \`python/mdvtools/dbutils/server_debug.py\` - Contains debugging information
- \`python/mdvtools/dbutils/mdv_server_app.py\` - The problematic server implementation" \
  --assignee "xinaesthete"

Length of output: 2225


@xinaesthete The GitHub issue has been successfully created! You can find it at: #139

I've documented the Safari SSL/TLS handshake problem with detailed information about:

  • The symptoms you're experiencing
  • Root cause analysis (Safari's TLS handshake attempts)
  • Comparison between working and problematic configurations
  • Five potential solutions to investigate

Would you like me to also do a follow-up review of the PR changes? If so, I can focus on any specific aspects you'd like me to evaluate.

Copy link

coderabbitai bot commented Feb 26, 2025

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@xinaesthete I've created a GitHub issue documenting the Safari SSL/TLS negotiation problem. The issue includes:

  • A detailed description of the symptoms from server_debug.py
  • Analysis identifying the cause as Safari attempting SSL/TLS handshakes that the server misinterprets
  • Comparison between working and non-working configurations
  • Several potential solutions to investigate

You'll be automatically notified of the issue since I've tagged you in it.


🏁 Script executed:

#!/bin/bash
# Create a GitHub issue for the Safari SSL/TLS negotiation problem

gh issue create \
  --title "Safari connections stall server due to TLS handshake issues" \
  --body "## Problem
When accessing the MDV server (python/mdvtools/dbutils/mdv_server_app.py) using Safari browser, the server stalls and becomes unresponsive.

## Symptoms
As documented in server_debug.py:
- Safari attempts show garbled binary data in server logs
- Server receives HTTP 400 error messages with 'Bad request version' and 'Bad Request Type'
- Exact error messages include:
  - \`RequestEntityTooLarge: 413 Request Entity Too Large: The data value transmitted exceeds the capacity limit.\`
  - \`BadRequest: 400 Bad Request: Bad request version ('\\x16\\x03\\x01')\`
  - \`BadRequest: 400 Bad Request: Bad HTTP/0.9 request type ('\\x16\\x03\\x01')\`

## Analysis
The garbled binary data in the logs (\\x16\\x03\\x01) appears to be TLS handshake packets. This suggests that Safari is attempting to establish an SSL/TLS connection, but the server is misinterpreting these as HTTP requests.

Key points:
- This issue is specific to Safari browser
- The server does not crash when using the server_debug.py script
- The issue doesn't occur with mdv_desktop script, which suggests a configuration difference
- The problem may be related to how Safari handles HTTP vs HTTPS connections differently than other browsers

## Differences between configurations
- mdv_desktop works correctly with Safari
- mdv_server_app.py stalls when accessed via Safari
- server_debug.py (identical to mdv_server_app.py except for how it's launched) shows errors but doesn't stall

## Potential Solutions
1. Properly configure SSL/TLS on the server to handle Safari's connection attempts
2. Address potential mixed content issues that may trigger Safari's security features
3. Modify how the Flask application handles invalid requests to prevent stalling
4. Add better error handling for malformed requests
5. Investigate how Gunicorn or other WSGI servers might handle these requests differently

## References
- Detailed debugging information is available in python/mdvtools/dbutils/server_debug.py
- Related issue may involve how Flask/Werkzeug handles TLS handshake packets

/cc @xinaesthete" \
  --repo "Taylor-CCB-Group/MDV"

Length of output: 2276


@xinaesthete I've successfully created a GitHub issue documenting the Safari SSL/TLS negotiation problem. The issue (#140) is now available at:

#140

The issue includes detailed information about:

  • The symptoms you're experiencing with Safari
  • Analysis of the TLS handshake packets being misinterpreted
  • Differences between working and non-working configurations
  • Potential solutions to investigate

You've been tagged in the issue and will receive notifications for any updates.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant