aws / aws-lambda-java-libs

Official mirror for interface definitions and helper classes for Java code running on the AWS Lambda platform.
https://aws.amazon.com/lambda/
Apache License 2.0
520 stars 231 forks source link

Force disconnecting an API Gateway WebSocket through Lambda #377

Open villain-bryan opened 1 year ago

villain-bryan commented 1 year ago

I'm using the WebSocket Protocol for API Gateway to route Client requests to specific Lambda invocations. How can I use Lambda to close a WebSocket?

Example:

public APIGatewayV2ProxyResponseEvent handle(APIGatewayV2WebSocketEvent input) {
    // Print this WebSocket's connectionId
    System.out.println("connectionId: " + input.getRequestContext().getConnectionId());
    // Great, I have the connectionId .. but how can I close it from here?
}
villain-bryan commented 1 year ago

Likewise, how can I send a packet to a specific WebSocket if I store that connectionId in DynamoDB? I'm basically wondering what the object is to create/recreate a WebSocket into a usable form from any Lambda given a connectionId, and haven't found any obvious way to do that.

All I've found is this reference https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-how-to-call-websocket-api-connections.html for accessing the connections, but it doesn't look convenient to work with.

msailes commented 1 year ago

Amazon API Gateway's WebSocket support is event driven in design. It will send events on Connect, Disconnect and Message.

You must manage the connections and who it is connected to the other end. When you implement the Connect handler you will probably save a business id with the connection id. Then when you want to send a message to a specific entity, you can find the connection id from that id. You then invoke the API Gateway management API to send a message to a specific connection id.

This is an example you might find helpful.

https://github.com/aws-samples/simple-websockets-chat-app

villain-bryan commented 1 year ago

Amazon API Gateway's WebSocket support is event driven in design. It will send events on Connect, Disconnect and Message.

You must manage the connections and who it is connected to the other end. When you implement the Connect handler you will probably save a business id with the connection id. Then when you want to send a message to a specific entity, you can find the connection id from that id. You then invoke the API Gateway management API to send a message to a specific connection id.

This is an example you might find helpful.

https://github.com/aws-samples/simple-websockets-chat-app

That reference is helpful, but I'm looking for a Java solution to manage the API Gateway WebSockets. Not sure how to do that - I was able to find some help via AmazonApiGatewayManagementApi, but seems to have an issue with Quarkus GraalVM build-native.