Skip to content

Commit 418b3d0

Browse files
authored
fix: cross-runtime consistency fixes (#179)
* fix(approvals_service): Remove unused imports and replace InternalServerError - Remove unused datetime import and current_date variable calculation - Replace InternalServerError with EnvironmentError for environment variable validation - Simplify error handling for SERVICE_NAMESPACE and CONTRACT_STATUS_TABLE checks - InternalServerError is not appropriate for environment configuration issues that occur at module initialization * fix(publication_manager_service): Add evaluation result validation and remove unused metric - Add validation for evaluation_result to ensure only "APPROVED" or "DECLINED" values are processed - Return early with skip message when unknown evaluation result is encountered - Log warning when evaluation result is invalid for debugging purposes - Remove unused PropertiesAdded metric that was not being utilized - Improve robustness by preventing invalid data from being written to DynamoDB * fix(contracts_service): Improve datetime handling and add contract metrics - Import timezone from datetime module for UTC timestamp generation - Import MetricUnit from aws_lambda_powertools.metrics for proper metric typing - Replace strftime formatting with isoformat() for ISO 8601 compliant timestamps in create_contract and update_contract functions - Add metric tracking for successful contract creation events - Rename UpdateExpression attribute from modified_date to contract_last_modified_on for consistency - Ensures timestamps are timezone-aware and use UTC for consistency across distributed systems * chore(deps): bump dependencies to latest versions * ci: Add explicit permissions to workflow jobs - Add actions: read permission for workflow execution access - Add contents: read permission for repository content access - Scope down GitHub Token permissions following security best practices
1 parent fcd82b1 commit 418b3d0

5 files changed

Lines changed: 21 additions & 20 deletions

File tree

.github/workflows/on_merged_pr.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ on:
77
- completed
88

99
permissions:
10+
actions: read
11+
contents: read
1012
issues: write
1113

1214
jobs:

unicorn_approvals/src/approvals_service/contract_status_changed_event_handler.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,20 +2,18 @@
22
# SPDX-License-Identifier: MIT-0
33

44
import os
5-
from datetime import datetime
65

76
import boto3
87
from aws_lambda_powertools.logging import Logger
98
from aws_lambda_powertools.metrics import Metrics
109
from aws_lambda_powertools.tracing import Tracer
11-
from aws_lambda_powertools.event_handler.exceptions import InternalServerError
1210
from schema.unicorn_contracts.contractstatuschanged import AWSEvent, ContractStatusChanged, Marshaller
1311

1412
# Initialise Environment variables
1513
if (SERVICE_NAMESPACE := os.environ.get("SERVICE_NAMESPACE")) is None:
16-
raise InternalServerError("SERVICE_NAMESPACE environment variable is undefined")
14+
raise EnvironmentError("SERVICE_NAMESPACE environment variable is undefined")
1715
if (CONTRACT_STATUS_TABLE := os.environ.get("CONTRACT_STATUS_TABLE")) is None:
18-
raise InternalServerError("CONTRACT_STATUS_TABLE environment variable is undefined")
16+
raise EnvironmentError("CONTRACT_STATUS_TABLE environment variable is undefined")
1917

2018
# Initialise PowerTools
2119
logger: Logger = Logger()
@@ -26,10 +24,6 @@
2624
dynamodb = boto3.resource("dynamodb")
2725
table = dynamodb.Table(CONTRACT_STATUS_TABLE) # type: ignore
2826

29-
# Get current date
30-
now = datetime.now()
31-
current_date = now.strftime("%d/%m/%Y %H:%M:%S")
32-
3327

3428
@logger.inject_lambda_context(log_event=True) # type: ignore
3529
@metrics.log_metrics(capture_cold_start_metric=True) # type: ignore

unicorn_contracts/src/contracts_service/contract_event_handler.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,14 @@
33

44
import os
55
import uuid
6-
from datetime import datetime
6+
from datetime import datetime, timezone
77

88
import boto3
99
from boto3.dynamodb.conditions import Attr
1010
from botocore.exceptions import ClientError
1111

1212
from aws_lambda_powertools.logging import Logger
13-
from aws_lambda_powertools.metrics import Metrics
13+
from aws_lambda_powertools.metrics import Metrics, MetricUnit
1414
from aws_lambda_powertools.tracing import Tracer
1515
from aws_lambda_powertools.utilities.data_classes import event_source, SQSEvent
1616
from aws_lambda_powertools.utilities.typing import LambdaContext
@@ -76,7 +76,7 @@ def create_contract(event: dict) -> None:
7676
DynamoDB put Item response
7777
"""
7878

79-
current_date = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
79+
current_date = datetime.now(timezone.utc).isoformat()
8080
contract = {
8181
"property_id": event["property_id"], # PK
8282
"address": event["address"],
@@ -105,6 +105,7 @@ def create_contract(event: dict) -> None:
105105

106106
# Annotate trace with contract status
107107
tracer.put_annotation(key="ContractStatus", value=contract["contract_status"])
108+
metrics.add_metric(name="ContractCreated", unit=MetricUnit.Count, value=1)
108109

109110
except ClientError as e:
110111
code = e.response["Error"]["Code"]
@@ -147,13 +148,13 @@ def update_contract(contract: dict) -> None:
147148

148149
try:
149150
contract["contract_status"] = ContractStatus.APPROVED.name
150-
current_date = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
151+
current_date = datetime.now(timezone.utc).isoformat()
151152

152153
response = table.update_item(
153154
Key={
154155
"property_id": contract["property_id"],
155156
},
156-
UpdateExpression="set contract_status=:t, modified_date=:m",
157+
UpdateExpression="set contract_status=:t, contract_last_modified_on=:m",
157158
ConditionExpression=Attr("property_id").exists()
158159
& Attr("contract_status").is_in([ContractStatus.DRAFT.name]),
159160
ExpressionAttributeValues={

unicorn_contracts/uv.lock

Lines changed: 5 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

unicorn_web/src/publication_manager_service/publication_evaluation_event_handler.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,14 +74,18 @@ def publication_approved(event_detail, errors):
7474

7575
property_id = event_detail.property_id
7676
evaluation_result = event_detail.evaluation_result
77+
78+
valid_results = {"APPROVED", "DECLINED"}
79+
if evaluation_result.upper() not in valid_results:
80+
logger.warning(f"Unknown evaluation_result '{evaluation_result}'; skipping DynamoDB update")
81+
return {"result": "Skipped — unknown evaluation result"}
82+
7783
country, city, street, number = property_id.split("/")
7884

7985
pk_details = f"{country}#{city}".replace(" ", "-").lower()
8086
pk = f"PROPERTY#{pk_details}"
8187
sk = f"{street}#{str(number)}".replace(" ", "-").lower()
8288

83-
metrics.add_metric(name="PropertiesAdded", unit=MetricUnit.Count, value=1)
84-
8589
logger.info(f"Storing new property in DynamoDB with PK {pk} and SK {sk}")
8690
dynamodb_response = table.update_item(
8791
Key={

0 commit comments

Comments
 (0)