Loading...
Loading...
Loading...
Anders & A-Cube S.r.l. / 1 mars 2024 • 4 min read
A3-Shared-Notifier est un service de notifications serverless production-grade construit avec AWS Lambda et Python 3.12. Il fournit un envoi email fiable et scalable via AWS SES avec activation flexible via SQS, SNS et invocation directe Lambda, supportant contenus HTML et texte simple.
L'architecture prévoit trois sources de trigger (AWS SQS, AWS SNS, invocation directe) qui activent la fonction AWS Lambda (Python 3.12) pour le traitement email et validation. Le Lambda interagit avec AWS SES pour envoi email, suivi bounces et gestion plaintes, et avec CloudWatch pour logs, métriques et alarmes.
Le handler principal gère les événements de SQS, SNS et invocation directe. Exécute le parsing de l'événement selon la source, traite chaque message avec validation et envoi, gère les erreurs avec logging détaillé.
Validation Message:
Construction Email:
def build_email(sender, recipients, subject, text_content='',
html_content='', bucket_name=''):
msg = MIMEMultipart('alternative')
msg['From'] = sender
msg['To'] = ', '.join(recipients)
msg['Subject'] = subject
if text_content:
msg.attach(MIMEText(text_content, 'plain'))
if html_content:
msg.attach(MIMEText(html_content, 'html'))
return msgFormat Message SQS:
{
"sender": "noreply@acubeapi.com",
"recipients": ["user@example.com"],
"subject": "Votre facture est prête",
"text_content": "La facture #12345 est disponible pour téléchargement.",
"html_content": "<h1>Facture Prête</h1><p>Facture #12345 disponible.</p>",
"bucket_name": "acube-invoices"
}Intégration Topic SNS: Publication notifications email sur topic SNS avec gestion abonnements multiples et filtres messages basés sur attributs.
Traitement File SQS: Envoi messages à file SQS avec batch processing jusqu'à 10 messages par invocation, visibility timeout configurable et gestion retry automatique.
Template SAM: Définition complète de la fonction Lambda avec configuration runtime Python 3.12, timeout 30s, mémoire 256MB. Policies SES pour envoi email. Événements SQS et SNS configurés. CloudWatch Log Group avec retention 30 jours.
Invocation Locale:
# Build fonction Lambda
sam build
# Invocation locale avec événement test
sam local invoke NotifierFunction \
--env-vars local/env.json \
--event tests/events/sqs-email-event.json
# Démarrage API Gateway local
sam local start-api
# Debug local
sam local invoke NotifierFunction \
--debug-port 5858 \
--env-vars local/env.json \
--event tests/events/sqs-email-event.jsonTests Unitaires:
Tests d'Intégration:
Exemple Test:
@patch('src.handler.ses_client')
def test_lambda_handler_success(self, mock_ses):
mock_ses.send_raw_email.return_value = {
'MessageId': 'test-message-id-123'
}
event = {
'sender': 'test@example.com',
'recipients': ['user@example.com'],
'subject': 'Test Email',
'text_content': 'Test content'
}
response = lambda_handler(event, None)
assert response['statusCode'] == 200Makefile pour gestion simplifiée:
make init: Initialisation environnementmake build: Build container Dockermake test: Exécution tests completsmake tests.unit: Seulement tests unitairesmake tests.integration: Seulement tests intégrationmake lint: Validation CloudFormationmake invoke.local: Invocation locale fonctionDéploiement sur Dev:
sam build -u
sam deploy --profile acube-dev --config-env dev --no-confirm-changesetDéploiement sur Production:
sam build -u --use-container
sam deploy --profile acube-prod --config-env production \
--no-confirm-changeset \
--parameter-overrides Environment=production LogRetentionDays=90Configuration SAM (samconfig.toml): Configuration séparée pour environnements dev et production avec stack name, region, capabilities IAM et parameter overrides spécifiques par environnement.
Logging Structuré:
def log_event(event_type: str, data: Dict[str, Any]) -> None:
log_entry = {
'timestamp': datetime.utcnow().isoformat(),
'event_type': event_type,
'data': data
}
logger.info(json.dumps(log_entry))Configuration alarmes pour:
A3-Shared-Notifier démontre une architecture serverless production-ready avec AWS Lambda, fournissant notifications email fiables et scalables avec capacités complètes de testing et monitoring.
Licence: Propriétaire (A-Cube S.r.l.)