strawberry-graphql / strawberry

A GraphQL library for Python that leverages type annotations 🍓
https://strawberry.rocks
MIT License
3.85k stars 511 forks source link

Subscriptions fail to create WebSocket connections #3514

Open amoghjalan opened 1 month ago

amoghjalan commented 1 month ago

Describe the Bug

I have a FastAPI server with Strawberry. It requires to have a WebSocket system for chat functionality and hence it uses the Subscriptions. While the server is up the WebSocket connection gets created in the playground of one window and doesn't in another window.

The developer tools console gives the following error:

WebSocket connection to 'wss://my_url.com/api/graphql' failed:

In the network tab, except the request URL everything is empty. Further, there are no errors visible in the server logs

The setup is as below:

@strawberry.type
class Subscription:

    @strawberry.subscription
    async def test(self, data: str) -> AsyncGenerator[str, None]:
        print("Test Subscription")
        yield "Hello World"
schema = strawberry.Schema(query=Query, subscription=Subscription, mutation=Mutation)

graphql_app = GraphQLRouter(schema, graphiql=None)

app = FastAPI(docs_url="/docs", redoc_url=None)

audio_router = APIRouter()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allows all origins
    allow_credentials=True,
    allow_methods=["*"],  # Allows all methods
    allow_headers=["*"],  # Allows all headers
)

app.include_router(graphql_app, prefix="/api/graphql")

In the graphql playground i get:

{
  "errors": [
    {
      "isTrusted": true
    }
  ]
}

Now, I have tried it in multiple browsers, their windows on multiple operating systems as well.

The problem doesn't occur on Windows Chrome browsers and Mac Safari

Though it is intermittently faced on MacOS chrome browser. The weird part is that it on the chrome browser, it works fine in one window while doesn't in another.

I faced this initially on the deployed server which has TLS but it is reproducible locally as well (again happens 50% of times).

System Information

Additional Context

Upvote & Fund

Fund with Polar

DoctorJohn commented 4 days ago

Just to confirm: did you test the websockets using GraphiQL in all these cases or does the issue also happen when you use a graphql client library (like Apollo for example)?