Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 8 additions & 3 deletions lambda/src/services/channel_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,10 +204,15 @@ def _post_to_connection(self, event, connection_id, data):
self._handle_disconnect(connection_id)

def _get_apigw_client(self, event):
"""Lazy API Gateway Management API client, cached by endpoint."""
domain = event["requestContext"]["domainName"]
"""Lazy API Gateway Management API client, cached by endpoint.

Uses the execute-api domain (not the custom domain) because the
Management API and its IAM policy are scoped to the execute-api ARN.
"""
api_id = event["requestContext"]["apiId"]
stage = event["requestContext"]["stage"]
endpoint = f"https://{domain}/{stage}"
region = self._session.region_name
endpoint = f"https://{api_id}.execute-api.{region}.amazonaws.com/{stage}"

if endpoint not in self._apigw_clients:
self._apigw_clients[endpoint] = self._session.client(
Expand Down
12 changes: 8 additions & 4 deletions lambda/tests/services/test_channel_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ def _ws_event(route_key="$default", connection_id="conn-1", body=None, query_par
"requestContext": {
"routeKey": route_key,
"connectionId": connection_id,
"apiId": "testapi123",
"domainName": "ws.example.com",
"stage": "prod",
},
Expand All @@ -48,8 +49,10 @@ def service(self, channel_table, boto_session, apigw_client, apigw_stubber):
svc = ChannelService(table=channel_table, session=boto_session)
# Pre-populate the APIGW client cache with the shared stubbed client.
# The key must match what _get_apigw_client computes from _ws_event():
# f"https://{domainName}/{stage}" => "https://ws.example.com/prod"
svc._apigw_clients["https://ws.example.com/prod"] = apigw_client
# f"https://{apiId}.execute-api.{region}.amazonaws.com/{stage}"
svc._apigw_clients["https://testapi123.execute-api.us-east-1.amazonaws.com/prod"] = (
apigw_client
)
return svc

# -- Constants ------------------------------------------------------------
Expand Down Expand Up @@ -703,8 +706,9 @@ def test_lazy_apigw_client_init(

event = _ws_event()
client1 = svc._get_apigw_client(event)
assert "https://ws.example.com/prod" in svc._apigw_clients
assert client1 is svc._apigw_clients["https://ws.example.com/prod"]
expected_key = "https://testapi123.execute-api.us-east-1.amazonaws.com/prod"
assert expected_key in svc._apigw_clients
assert client1 is svc._apigw_clients[expected_key]

# Second call returns the same cached client
client2 = svc._get_apigw_client(event)
Expand Down
Loading