-
Notifications
You must be signed in to change notification settings - Fork 7
Feat/enhance encumbrance notifications #1179
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
isabeleliassen
merged 18 commits into
csg-org:development
from
InspiringApps:feat/enhance-encumbrance-notifications
Nov 11, 2025
Merged
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
c8c61f4
Add test case for managing encumbrance notifications
landonshumway-ia c25a468
Add event state stack for tracking system event information
landonshumway-ia 762a8c1
WIP - integrate notification tracker with encumbrance events
landonshumway-ia 5572e1c
Add enums for known values, simplify interface
landonshumway-ia cb62db3
Add logging, error handling
landonshumway-ia 6f2d2c9
Add isolated tests for notification tracker
landonshumway-ia 43b993d
Make sqs message id passing backwards compatible
landonshumway-ia 30dbd1b
Fix GSI syntax in CDK stack
landonshumway-ia c765f76
Add alarm for email notification failures
landonshumway-ia 9707e97
remove unused import
landonshumway-ia 93239b7
Make the notification tracker more generic
landonshumway-ia 7ef2c1b
Removed unused sqs decorator
landonshumway-ia ec050fd
PR feedback
landonshumway-ia ab6117f
PR feedback
landonshumway-ia d4b1874
PR feedback
landonshumway-ia acf47a4
PR feedback - explicitly pass state event stack
landonshumway-ia 4b08d4d
formatting
landonshumway-ia 145900e
PR feedback - fix comment
landonshumway-ia File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
237 changes: 237 additions & 0 deletions
237
backend/compact-connect/lambdas/python/common/cc_common/event_state_client.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,237 @@ | ||
| import time | ||
| from datetime import timedelta | ||
| from enum import StrEnum | ||
| from uuid import UUID | ||
|
|
||
| from cc_common.config import _Config, logger | ||
|
|
||
|
|
||
| class RecipientType(StrEnum): | ||
| """Enum for notification recipient types.""" | ||
|
|
||
| PROVIDER = 'provider' | ||
| STATE = 'state' | ||
|
|
||
|
|
||
| class NotificationStatus(StrEnum): | ||
| """Enum for notification delivery status.""" | ||
|
|
||
| SUCCESS = 'SUCCESS' | ||
| FAILED = 'FAILED' | ||
|
|
||
|
|
||
| class EventType(StrEnum): | ||
| """Enum for encumbrance event types.""" | ||
|
|
||
| LICENSE_ENCUMBRANCE = 'license.encumbrance' | ||
| LICENSE_ENCUMBRANCE_LIFTED = 'license.encumbranceLifted' | ||
| PRIVILEGE_ENCUMBRANCE = 'privilege.encumbrance' | ||
| PRIVILEGE_ENCUMBRANCE_LIFTED = 'privilege.encumbranceLifted' | ||
|
|
||
|
|
||
| class EventStateClient: | ||
| """Client interface for event state table operations to track notification delivery state.""" | ||
|
|
||
| def __init__(self, config: _Config): | ||
| self.config = config | ||
|
|
||
| def record_notification_attempt( | ||
| self, | ||
| *, | ||
| compact: str, | ||
| message_id: str, | ||
| recipient_type: RecipientType, | ||
| status: NotificationStatus, | ||
| provider_id: UUID, | ||
| event_type: EventType, | ||
| event_time: str, | ||
| jurisdiction: str | None = None, | ||
| error_message: str | None = None, | ||
| ttl_weeks: int = 4, | ||
| ) -> None: | ||
| """ | ||
| Record a notification attempt to the event state table. | ||
|
|
||
| :param compact: The compact identifier | ||
| :param message_id: SQS message ID | ||
| :param recipient_type: RecipientType enum or string ('provider' or 'state') | ||
| :param status: NotificationStatus enum or string ('SUCCESS' or 'FAILED') | ||
| :param provider_id: Provider ID | ||
| :param event_type: EventType enum or string (e.g., 'license.encumbrance') | ||
| :param event_time: Event timestamp | ||
| :param jurisdiction: Jurisdiction code (for state notifications) | ||
| :param error_message: Error message if failed | ||
| :param ttl_weeks: TTL in weeks (default 4 weeks) | ||
| """ | ||
| # Build partition and sort keys | ||
| pk = f'COMPACT#{compact}#SQS_MESSAGE#{message_id}' | ||
|
|
||
| sk = f'NOTIFICATION#{recipient_type}#{jurisdiction or ""}' | ||
|
|
||
| # Calculate TTL | ||
| ttl = int(time.time()) + int(timedelta(weeks=ttl_weeks).total_seconds()) | ||
|
|
||
| # Build item (ensure all values are DynamoDB-compatible types) | ||
| item = { | ||
| 'pk': pk, | ||
| 'sk': sk, | ||
| 'status': status, | ||
| 'providerId': str(provider_id), # Convert UUID to string for DynamoDB | ||
| 'eventType': event_type, | ||
| 'eventTime': str(event_time), # Ensure string format for DynamoDB | ||
| 'ttl': ttl, | ||
| } | ||
|
|
||
| # Add optional fields | ||
| if jurisdiction: | ||
| item['jurisdiction'] = jurisdiction | ||
|
|
||
| if error_message: | ||
| item['errorMessage'] = error_message | ||
|
|
||
| # Write to table | ||
| self.config.event_state_table.put_item(Item=item) | ||
| logger.debug('Recorded notification attempt', pk=pk, sk=sk, status=status) | ||
|
|
||
| def _get_notification_attempts(self, *, compact: str, message_id: str) -> dict[str, dict]: | ||
| """ | ||
| Query all notification attempts for a message. | ||
|
|
||
| :param compact: The compact identifier | ||
| :param message_id: SQS message ID | ||
| :return: Dict mapping SK to item data | ||
| """ | ||
| pk = f'COMPACT#{compact}#SQS_MESSAGE#{message_id}' | ||
|
|
||
| response = self.config.event_state_table.query( | ||
| KeyConditionExpression='pk = :pk', | ||
| ExpressionAttributeValues={':pk': pk}, | ||
| ConsistentRead=True, | ||
| ) | ||
|
|
||
| return {item['sk']: item for item in response.get('Items', [])} | ||
|
|
||
|
|
||
| class NotificationTracker: | ||
| """ | ||
| Helper class to track which notifications have been sent for an SQS message. | ||
| Provides convenient methods to check status and determine what needs to be sent. | ||
| Encapsulates the EventStateClient to simplify handler interfaces. | ||
| """ | ||
|
|
||
| def __init__(self, *, compact: str, message_id: str): | ||
| from cc_common.config import config | ||
|
|
||
| self.compact = compact | ||
| self.message_id = message_id | ||
| self.event_state_client = config.event_state_client | ||
| self._attempts = self.event_state_client._get_notification_attempts( # noqa: SLF001 meant for use within the notification tracker | ||
| compact=compact, message_id=message_id | ||
| ) | ||
|
|
||
| def should_send_provider_notification(self) -> bool: | ||
| """ | ||
| Check if provider notification needs to be sent. | ||
|
|
||
| :return: True if notification should be sent, False otherwise | ||
| """ | ||
| sk = f'NOTIFICATION#{RecipientType.PROVIDER}#' | ||
| return self._attempts.get(sk, {}).get('status') != 'SUCCESS' | ||
|
|
||
| def should_send_state_notification(self, jurisdiction: str) -> bool: | ||
| """ | ||
| Check if state notification needs to be sent. | ||
|
|
||
| :param jurisdiction: Jurisdiction code | ||
| :return: True if notification should be sent, False otherwise | ||
| """ | ||
| sk = f'NOTIFICATION#{RecipientType.STATE}#{jurisdiction}' | ||
| return self._attempts.get(sk, {}).get('status') != 'SUCCESS' | ||
|
|
||
| def record_success( | ||
| self, | ||
| *, | ||
| recipient_type: RecipientType, | ||
| provider_id: UUID, | ||
| event_type: EventType, | ||
| event_time: str, | ||
| jurisdiction: str | None = None, | ||
| ) -> None: | ||
| """ | ||
| Record a successful notification. | ||
|
|
||
| :param recipient_type: RecipientType enum or string ('provider' or 'state') | ||
| :param provider_id: Provider ID | ||
| :param event_type: EventType enum or string | ||
| :param event_time: Event timestamp | ||
| :param jurisdiction: Jurisdiction code (for state notifications) | ||
| """ | ||
| try: | ||
| self.event_state_client.record_notification_attempt( | ||
| compact=self.compact, | ||
| message_id=self.message_id, | ||
| recipient_type=recipient_type, | ||
| status=NotificationStatus.SUCCESS, | ||
| provider_id=provider_id, | ||
| event_type=event_type, | ||
| event_time=event_time, | ||
| jurisdiction=jurisdiction, | ||
| ) | ||
| except Exception as e: # noqa: BLE001 | ||
| # If this cannot be written for whatever reason, we swallow the error since the notification itself was | ||
| # sent, and this step is just another layer of system redundancy, not business critical. Just log the error | ||
| # and move on. | ||
| logger.error( | ||
| 'Unable to record notification success.', | ||
| compact=self.compact, | ||
| recipient_type=recipient_type, | ||
| provider_id=provider_id, | ||
| event_type=event_type, | ||
| jurisdiction=jurisdiction or 'None', | ||
| error=str(e), | ||
| ) | ||
|
|
||
| def record_failure( | ||
| self, | ||
| *, | ||
| recipient_type: RecipientType, | ||
| provider_id: UUID, | ||
| event_type: EventType, | ||
| event_time: str, | ||
| error_message: str, | ||
| jurisdiction: str | None = None, | ||
| ) -> None: | ||
| """ | ||
| Record a failed notification. | ||
|
|
||
| :param recipient_type: RecipientType enum or string ('provider' or 'state') | ||
| :param provider_id: Provider ID | ||
| :param event_type: EventType enum or string | ||
| :param event_time: Event timestamp | ||
| :param error_message: Error message describing the failure | ||
| :param jurisdiction: Jurisdiction code (for state notifications) | ||
| """ | ||
| try: | ||
| self.event_state_client.record_notification_attempt( | ||
| compact=self.compact, | ||
| message_id=self.message_id, | ||
| recipient_type=recipient_type, | ||
| status=NotificationStatus.FAILED, | ||
| provider_id=provider_id, | ||
| event_type=event_type, | ||
| event_time=event_time, | ||
| jurisdiction=jurisdiction, | ||
| error_message=error_message, | ||
| ) | ||
| except Exception as e: # noqa: BLE001 | ||
| # If this cannot be written, we swallow the error as the lambda will automatically retry and | ||
| # attempt to send out the notification again. Just log the error and move on. | ||
| logger.error( | ||
| 'Unable to record notification failure.', | ||
| compact=self.compact, | ||
| recipient_type=recipient_type, | ||
| provider_id=provider_id, | ||
| event_type=event_type, | ||
| jurisdiction=jurisdiction or 'None', | ||
| error=str(e), | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.