aws / aws/chalice

`app.websocket_api.send()` raises `WebsocketDisconnectedError` if called from within the function decorated with `@app.on_ws_connect()`

Open
#1,772 0 comments 1 reaction 0 assignees View on GitHub
Dominant language
Python
Stars
11.1k
Forks
1k
Avg merge
1d 22h
Merged PRs (30d)
2

Description

Currently it is not possible to send response over WebSocket to a client once connection to a server is established. Consider the following code:
```
from boto3.session import Session
from chalice import Chalice

app = Chalice(app_name='ws-service')
app.experimental_feature_flags.update(['WEBSOCKETS'])
app.websocket_api.session = Session()

app.debug = True

@app.on_ws_connect()
def ws_connect(event):
app.log.debug(f"New connection established: {event.connection_id}")
app.websocket_api.send(event.connection_id, "some response here")
```
When client tries to establish a connection with WebSocket service it receives "502 Bad Gateway" error. In logs I observe the following traceback:
```
[ERROR] WebsocketDisconnectedError: DFh2Ffc4oAMCIzw=
Traceback (most recent call last):
File "/var/task/chalice/app.py", line 1583, in __call__
super(WebsocketEventSourceHandler, self).__call__(event, context)
File "/var/task/chalice/app.py", line 1564, in __call__
return self.handler(event_obj)
File "/var/task/app.py", line 14, in ws_connect
app.websocket_api.send(event.connection_id, "some response here")
File "/var/task/chalice/app.py", line 665, in send
raise WebsocketDisconnectedError(connection_id)
```
Though in [official documentation](https://aws.github.io/chalice/topics/websockets.html#sending-a-message-over-a-websocket) it is stated that sending message should work in all WS-decorated functions.

Contributor guide

Open the contributing guide

Research direction

Start in chalice/app.py, particularly the WebSocket event handling and send path shown in the traceback, and compare it with the official WebSocket sending documentation. Reproduce the provided @app.on_ws_connect() example and verify that sending immediately after connection succeeds without WebsocketDisconnectedError or a 502 response.

Written by the indexing model from the issue text.

Assessment

Tech stack
aws, python
Domain
api, backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.