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

Strict graphql ws typed dicts #3689

Merged

Conversation

DoctorJohn
Copy link
Member

@DoctorJohn DoctorJohn commented Nov 7, 2024

Description

This PR refactors all types of the legacy graphql-ws protocol. I continued using typed dicts (vs dataclasses) for performance reasons, simplicity, and the ability to model null vs undefined easily. In the linked issue I complained about them, but now that we have NotRequired and Required available for typing, they're fun to work with and enable the modelling of super precise types.

Pylance is now pretty happy when I open the protocol implementation, some type casts were removed, and some minor type errors in tests surfaced and were fixed.

Types of Changes

  • Core
  • Bugfix
  • New feature
  • Enhancement/optimization
  • Documentation

Issues Fixed or Closed by This PR

Summary by Sourcery

Refactor the graphql-ws protocol types to use stricter typed dicts, enhancing type safety and clarity. Update tests to reflect these changes and add a release note to document the improvements.

Enhancements:

  • Refactor all types of the legacy graphql-ws protocol to use stricter typed dicts, improving type safety and clarity.

Documentation:

  • Add a release note detailing the refactoring of the graphql-ws protocol types and the improvements in type strictness.

Tests:

  • Update tests to align with the new strict typing of the graphql-ws protocol, ensuring compatibility and correctness.

Copy link
Contributor

sourcery-ai bot commented Nov 7, 2024

Reviewer's Guide by Sourcery

This PR refactors the GraphQL WebSocket protocol types to be more strictly typed using TypedDict with Literal and NotRequired types. The changes improve type safety and make the distinction between null and undefined values clearer while maintaining performance.

Updated class diagram for GraphQL WebSocket protocol types

classDiagram
    class ConnectionInitMessage {
        +Literal["connection_init"] type
        +NotRequired[Dict[str, object]] payload
    }

    class StartMessagePayload {
        +str query
        +NotRequired[Dict[str, object]] variables
        +NotRequired[str] operationName
    }

    class StartMessage {
        +Literal["start"] type
        +str id
        +StartMessagePayload payload
    }

    class StopMessage {
        +Literal["stop"] type
        +str id
    }

    class ConnectionTerminateMessage {
        +Literal["connection_terminate"] type
    }

    class ConnectionErrorMessage {
        +Literal["connection_error"] type
        +NotRequired[Dict[str, object]] payload
    }

    class ConnectionAckMessage {
        +Literal["connection_ack"] type
    }

    class DataMessagePayload {
        +object data
        +NotRequired[List[GraphQLFormattedError]] errors
        +NotRequired[Dict[str, object]] extensions
    }

    class DataMessage {
        +Literal["data"] type
        +str id
        +DataMessagePayload payload
    }

    class ErrorMessage {
        +Literal["error"] type
        +str id
        +GraphQLFormattedError payload
    }

    class CompleteMessage {
        +Literal["complete"] type
        +str id
    }

    class ConnectionKeepAliveMessage {
        +Literal["ka"] type
    }

    class OperationMessage {
        +ConnectionInitMessage
        +StartMessage
        +StopMessage
        +ConnectionTerminateMessage
        +ConnectionErrorMessage
        +ConnectionAckMessage
        +DataMessage
        +ErrorMessage
        +CompleteMessage
    }
Loading

File-Level Changes

Change Details Files
Replaced string constants for message types with strictly typed message interfaces
  • Removed GQL_* string constants
  • Created TypedDict classes for each message type with Literal type values
  • Added NotRequired fields to handle optional parameters
strawberry/subscriptions/protocols/graphql_ws/types.py
strawberry/subscriptions/protocols/graphql_ws/__init__.py
Updated message handling to use new typed message interfaces
  • Replaced generic OperationMessage with specific message type handlers
  • Updated type assertions to use new message interfaces
  • Simplified message construction with direct TypedDict usage
strawberry/subscriptions/protocols/graphql_ws/handlers.py
Refactored tests to use new typed message interfaces
  • Updated test assertions to use specific message types
  • Added type annotations for received messages
  • Replaced string constant usage with literal type values
tests/websockets/test_graphql_ws.py
tests/fastapi/test_context.py
tests/http/clients/base.py

Assessment against linked issues

Issue Objective Addressed Explanation
#1669 Refactor the legacy graphql-ws protocol message definitions to use stricter typing

Possibly linked issues


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.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a 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. You can also use
    this command to specify where the summary should be inserted.

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

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @DoctorJohn - I've reviewed your changes and found some issues that need to be addressed.

Blocking issues:

  • Add runtime validation for required payload fields (link)
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🔴 Security: 1 blocking issue
  • 🟡 Testing: 1 issue found
  • 🟡 Complexity: 2 issues found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@botberry
Copy link
Member

botberry commented Nov 7, 2024

Thanks for adding the RELEASE.md file!

Here's a preview of the changelog:


In this release, all types of the legacy graphql-ws protocol were refactored.
The types are now much stricter and precisely model the difference between null and undefined fields.
As a result, our protocol implementation and related tests are now more robust and easier to maintain.

Here's the tweet text:

🆕 Release (next) is out! Thanks to @NucleonJohn for the PR 👏

Get it here 👉 https://strawberry.rocks/release/(next)

Copy link

codecov bot commented Nov 7, 2024

Codecov Report

Attention: Patch coverage is 99.24528% with 2 lines in your changes missing coverage. Please review.

Project coverage is 97.01%. Comparing base (74ad18c) to head (7e29c65).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3689      +/-   ##
==========================================
- Coverage   97.01%   97.01%   -0.01%     
==========================================
  Files         503      502       -1     
  Lines       33550    33570      +20     
  Branches     5634     5634              
==========================================
+ Hits        32548    32567      +19     
  Misses        796      796              
- Partials      206      207       +1     

Copy link

codspeed-hq bot commented Nov 7, 2024

CodSpeed Performance Report

Merging #3689 will not alter performance

Comparing DoctorJohn:strict-graphql-ws-typed-dicts (7e29c65) with main (74ad18c)

Summary

✅ 15 untouched benchmarks

@DoctorJohn DoctorJohn merged commit ac52f2f into strawberry-graphql:main Nov 7, 2024
108 of 109 checks passed
@DoctorJohn DoctorJohn deleted the strict-graphql-ws-typed-dicts branch November 20, 2024 15:57
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.

Refactor graphql-ws message types
3 participants