Skip to content
This repository has been archived by the owner on Jul 18, 2024. It is now read-only.

Commit

Permalink
feat: add archives to EventBridge
Browse files Browse the repository at this point in the history
  • Loading branch information
nmoutschen committed May 26, 2021
1 parent b60d153 commit 4c2e071
Show file tree
Hide file tree
Showing 9 changed files with 746 additions and 219 deletions.
727 changes: 722 additions & 5 deletions payment-3p/package-lock.json

Large diffs are not rendered by default.

51 changes: 0 additions & 51 deletions platform/src/on_connect/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,40 +25,6 @@
tracer = Tracer() # pylint: disable=invalid-name


@tracer.capture_method
def create_waiter(evb_client):
waiter_name = "EvbRuleEnabled"
waiter_config = {
"version": 2,
"waiters": {
"EvbRuleEnabled": {
"operation": "DescribeRule",
"delay": WAITER_DELAY,
"maxAttempts": WAITER_MAX_ATTEMPTS,
"acceptors": [
{
"matcher": "path",
"expected": "ENABLED",
"state": "success",
"argument": "State",
},
{
"matcher": "path",
"expected": "DISABLED",
"state": "retry",
"argument": "State",
},
],
}
},
}
waiter_model = WaiterModel(waiter_config)
return create_waiter_with_client(waiter_name, waiter_model, evb_client)


evb_rule_waiter = create_waiter(evb_client=eventbridge)


@tracer.capture_method
def store_id(connection_id: str):
"""
Expand All @@ -73,22 +39,6 @@ def store_id(connection_id: str):
})


@tracer.capture_method
def enable_rule():
"""
Enable the EventBridge rule
"""

eventbridge.enable_rule(
Name=EVENT_RULE_NAME,
EventBusName=EVENT_BUS_NAME
)
evb_rule_waiter.wait(
Name=EVENT_RULE_NAME,
EventBusName=EVENT_BUS_NAME
)


@logger.inject_lambda_context
@tracer.capture_lambda_handler
def handler(event, _):
Expand All @@ -111,6 +61,5 @@ def handler(event, _):
})

store_id(connection_id)
enable_rule()

return response("Connected")
25 changes: 0 additions & 25 deletions platform/src/on_disconnect/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,28 +33,6 @@ def delete_id(connection_id: str):
})


@tracer.capture_method
def disable_rule():
"""
Disable EventBridge rule
"""

# Check for active connextions
res = table.scan(Limit=1, ConsistentRead=True)
if res.get("Items"):
# Active connections, skipping
logger.info({
"message": "Keeping rule enabled due to active connections"
})
return

# Disable the rule
eventbridge.disable_rule(
Name=EVENT_RULE_NAME,
EventBusName=EVENT_BUS_NAME
)


@logger.inject_lambda_context
@tracer.capture_lambda_handler
def handler(event, _):
Expand All @@ -76,9 +54,6 @@ def handler(event, _):
"event": event
})

# disable_rule must happen after delete_id, as it checks if there are
# active connections before deleting the rule.
delete_id(connection_id)
disable_rule()

return response("Disconnected")
20 changes: 7 additions & 13 deletions platform/template.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Parameters:
RetentionInDays:
Type: Number
Default: 30
Description: CloudWatch Logs retention period for Lambda functions
Description: CloudWatch Logs retention period for Lambda functions and EventBridge event bus


Globals:
Expand Down Expand Up @@ -50,6 +50,12 @@ Resources:
Type: String
Value: !Ref EventBus

EventBusArchive:
Type: AWS::Events::Archive
Properties:
SourceArn: !GetAtt EventBus.Arn
RetentionDays: !Ref RetentionInDays

##################
# LISTENER TABLE #
##################
Expand Down Expand Up @@ -151,12 +157,6 @@ Resources:
- dynamodb:PutItem
Resource:
- !GetAtt ListenerTable.Arn
- Effect: Allow
Action:
- events:EnableRule
- events:DescribeRule
Resource:
- !GetAtt OnEventsFunctionEvent.Arn

OnConnectPermission:
Type: AWS::Lambda::Permission
Expand Down Expand Up @@ -206,14 +206,8 @@ Resources:
- Effect: Allow
Action:
- dynamodb:DeleteItem
- dynamodb:Scan
Resource:
- !GetAtt ListenerTable.Arn
- Effect: Allow
Action:
- events:DisableRule
Resource:
- !GetAtt OnEventsFunctionEvent.Arn

OnDisconnectPermission:
Type: AWS::Lambda::Permission
Expand Down
46 changes: 3 additions & 43 deletions platform/tests/unit/test_on_connect.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,34 +38,6 @@ def test_store_id(lambda_module):
table.deactivate()


def test_enable_rule(lambda_module):
"""
Test enable_rule()
"""

eventbridge = stub.Stubber(lambda_module.eventbridge)
eventbridge.add_response("enable_rule", {}, {
"Name": "EVENT_RULE_NAME",
"EventBusName": "EVENT_BUS_NAME"
})
eventbridge.add_response(
"describe_rule",
{
"Name": "EVENT_RULE_NAME",
"State": "ENABLED",
"EventBusName": "EVENT_BUS_NAME"
},
{"Name": "EVENT_RULE_NAME", "EventBusName": "EVENT_BUS_NAME"},
)
eventbridge.activate()

lambda_module.enable_rule()

eventbridge.assert_no_pending_responses()

eventbridge.deactivate()


def test_handler(monkeypatch, lambda_module, context, apigateway_event):
"""
Test handler()
Expand All @@ -77,24 +49,18 @@ def test_handler(monkeypatch, lambda_module, context, apigateway_event):
event["requestContext"] = {"connectionId": connection_id}

calls = {
"store_id": 0,
"enable_rule": 0
"store_id": 0
}

def store_id(connection_id_req: str):
calls["store_id"] += 1
assert connection_id_req == connection_id
monkeypatch.setattr(lambda_module, "store_id", store_id)

def enable_rule():
calls["enable_rule"] += 1
monkeypatch.setattr(lambda_module, "enable_rule", enable_rule)

result = lambda_module.handler(event, context)

assert result["statusCode"] == 200
assert calls["store_id"] == 1
assert calls["enable_rule"] == 1


def test_handler_no_id(monkeypatch, lambda_module, context, apigateway_event):
Expand All @@ -107,21 +73,15 @@ def test_handler_no_id(monkeypatch, lambda_module, context, apigateway_event):
event = apigateway_event()

calls = {
"store_id": 0,
"enable_rule": 0
"store_id": 0
}

def store_id(connection_id_req: str):
calls["store_id"] += 1
assert connection_id_req == connection_id
monkeypatch.setattr(lambda_module, "store_id", store_id)

def enable_rule():
calls["enable_rule"] += 1
monkeypatch.setattr(lambda_module, "enable_rule", enable_rule)

result = lambda_module.handler(event, context)

assert result["statusCode"] == 400
assert calls["store_id"] == 0
assert calls["enable_rule"] == 0
assert calls["store_id"] == 0
77 changes: 3 additions & 74 deletions platform/tests/unit/test_on_disconnect.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,65 +35,6 @@ def test_delete_id(lambda_module):
table.deactivate()


def test_disable_rule(lambda_module):
"""
Test disable_rule()
"""

table = stub.Stubber(lambda_module.table.meta.client)
table.add_response("scan", {},{
"TableName": "TABLE_NAME",
"Limit": 1,
"ConsistentRead": True
})
table.activate()

eventbridge = stub.Stubber(lambda_module.eventbridge)
eventbridge.add_response("disable_rule", {}, {
"Name": "EVENT_RULE_NAME",
"EventBusName": "EVENT_BUS_NAME"
})
eventbridge.activate()

lambda_module.disable_rule()

table.assert_no_pending_responses()
eventbridge.assert_no_pending_responses()

table.deactivate()
eventbridge.deactivate()


def test_disable_rule_active_connections(lambda_module):
"""
Test disable_rule() with active connections
"""

table = stub.Stubber(lambda_module.table.meta.client)
table.add_response("scan", {
"Items": [{
"id": {"S": str(uuid.uuid4())},
"service": {"S": "ecommerce.test"}
}]
}, {
"TableName": "TABLE_NAME",
"Limit": 1,
"ConsistentRead": True
})
table.activate()

eventbridge = stub.Stubber(lambda_module.eventbridge)
eventbridge.activate()

lambda_module.disable_rule()

table.assert_no_pending_responses()
eventbridge.assert_no_pending_responses()

table.deactivate()
eventbridge.deactivate()


def test_handler(monkeypatch, lambda_module, context, apigateway_event):
"""
Test handler()
Expand All @@ -105,24 +46,18 @@ def test_handler(monkeypatch, lambda_module, context, apigateway_event):
event["requestContext"] = {"connectionId": connection_id}

calls = {
"delete_id": 0,
"disable_rule": 0
"delete_id": 0
}

def delete_id(connection_id_req: str):
calls["delete_id"] += 1
assert connection_id_req == connection_id
monkeypatch.setattr(lambda_module, "delete_id", delete_id)

def disable_rule():
calls["disable_rule"] += 1
monkeypatch.setattr(lambda_module, "disable_rule", disable_rule)

result = lambda_module.handler(event, context)

assert result["statusCode"] == 200
assert calls["delete_id"] == 1
assert calls["disable_rule"] == 1


def test_handler_no_id(monkeypatch, lambda_module, context, apigateway_event):
Expand All @@ -135,21 +70,15 @@ def test_handler_no_id(monkeypatch, lambda_module, context, apigateway_event):
event = apigateway_event()

calls = {
"delete_id": 0,
"disable_rule": 0
"delete_id": 0
}

def delete_id(connection_id_req: str):
calls["delete_id"] += 1
assert connection_id_req == connection_id
monkeypatch.setattr(lambda_module, "delete_id", delete_id)

def disable_rule():
calls["disable_rule"] += 1
monkeypatch.setattr(lambda_module, "disable_rule", disable_rule)

result = lambda_module.handler(event, context)

assert result["statusCode"] == 400
assert calls["delete_id"] == 0
assert calls["disable_rule"] == 0
assert calls["delete_id"] == 0
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
awscli>=1.18.211
aws-requests-auth==0.4.2
cfn-lint==0.28.2
cfn-lint==0.49.2
jsonschema==3.2.0
locust==1.0.3
pylint==2.4.4
Expand Down
6 changes: 6 additions & 0 deletions shared/src/ecom/ecom/eventbridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

from datetime import datetime
import json
import os
from boto3.dynamodb.types import TypeDeserializer
from .helpers import Encoder

Expand Down Expand Up @@ -36,6 +37,11 @@ def ddb_to_event(
"EventBusName": event_bus_name
}

# Inject X-Ray trace ID
trace_id = os.environ.get("_X_AMZN_TRACE_ID", None)
if trace_id:
event["TraceHeader"] = trace_id

# Created event
if ddb_record["eventName"].upper() == "INSERT":
event["DetailType"] = "{}Created".format(object_type)
Expand Down
Loading

0 comments on commit 4c2e071

Please sign in to comment.