Loading...
Loading...
Loading...
Anders & A-Cube S.r.l. / 1 marzo 2024 • 4 min read
A3-Shared-Notifier è un servizio di notifiche serverless production-grade costruito con AWS Lambda e Python 3.12. Fornisce invio email affidabile e scalabile tramite AWS SES con attivazione flessibile via SQS, SNS e invocazione diretta Lambda, supportando contenuti HTML e testo semplice.
L'architettura prevede tre sorgenti di trigger (AWS SQS, AWS SNS, invocazione diretta) che attivano la funzione AWS Lambda (Python 3.12) per l'elaborazione email e validazione. La Lambda interagisce con AWS SES per invio email, tracciamento bounce e gestione reclami, e con CloudWatch per logs, metriche e allarmi.
L'handler principale gestisce eventi da SQS, SNS e invocazione diretta. Esegue parsing dell'evento in base alla sorgente, processa ogni messaggio con validazione e invio, gestisce errori con logging dettagliato.
Validazione Messaggio:
Costruzione 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 msgFormato Messaggio SQS:
{
"sender": "noreply@acubeapi.com",
"recipients": ["user@example.com"],
"subject": "La tua fattura è pronta",
"text_content": "La fattura #12345 è disponibile per il download.",
"html_content": "<h1>Fattura Pronta</h1><p>Fattura #12345 disponibile.</p>",
"bucket_name": "acube-invoices"
}Integrazione Topic SNS: Pubblicazione notifiche email su topic SNS con gestione sottoscrizioni multiple e filtri messaggi basati su attributi.
Elaborazione Code SQS: Invio messaggi a coda SQS con batch processing fino a 10 messaggi per invocazione, visibility timeout configurabile e gestione retry automatica.
Template SAM: Definizione completa della funzione Lambda con configurazione runtime Python 3.12, timeout 30s, memoria 256MB. Policies SES per invio email. Eventi SQS e SNS configurati. CloudWatch Log Group con retention 30 giorni.
Invocazione Locale:
# Build funzione Lambda
sam build
# Invocazione locale con evento test
sam local invoke NotifierFunction \
--env-vars local/env.json \
--event tests/events/sqs-email-event.json
# Avvio API Gateway locale
sam local start-api
# Debug locale
sam local invoke NotifierFunction \
--debug-port 5858 \
--env-vars local/env.json \
--event tests/events/sqs-email-event.jsonTest Unitari:
Test di Integrazione:
Esempio 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 per gestione semplificata:
make init: Inizializzazione ambientemake build: Build container Dockermake test: Esecuzione test completimake tests.unit: Solo test unitarimake tests.integration: Solo test integrazionemake lint: Validazione CloudFormationmake invoke.local: Invocazione locale funzioneDeploy su Dev:
sam build -u
sam deploy --profile acube-dev --config-env dev --no-confirm-changesetDeploy su Production:
sam build -u --use-container
sam deploy --profile acube-prod --config-env production \
--no-confirm-changeset \
--parameter-overrides Environment=production LogRetentionDays=90Configurazione SAM (samconfig.toml): Configurazione separata per ambienti dev e production con stack name, region, capabilities IAM e parameter overrides specifici per ambiente.
Logging Strutturato:
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))Configurazione allarmi per:
A3-Shared-Notifier dimostra un'architettura serverless production-ready con AWS Lambda, fornendo notifiche email affidabili e scalabili con capacità complete di testing e monitoring.
Licenza: Proprietaria (A-Cube S.r.l.)