Skip to content

feat(email): route SendGrid sends through EU data residency#619

Merged
spashii merged 2 commits into
mainfrom
fix/sendgrid-eu-residency
Jun 5, 2026
Merged

feat(email): route SendGrid sends through EU data residency#619
spashii merged 2 commits into
mainfrom
fix/sendgrid-eu-residency

Conversation

@spashii

@spashii spashii commented Jun 4, 2026

Copy link
Copy Markdown
Member

What

Routes the app's transactional email through SendGrid's EU data residency region so recipient PII and email content stay in EU data centers (GDPR).

  • Adds SENDGRID_REGION setting (EmailSettings), default "eu".
  • email.py calls set_sendgrid_data_residency(region) before sending, switching the client host to api.eu.sendgrid.com when region != global.
  • Documents SENDGRID_REGION in server/.env.sample.

Why

dembrane is moving email to EU residency. An EU regional subuser (sameer-eu, EU IP 159.183.46.124) and the dembrane.com domain authentication (EU CNAMEs in Cloudflare) are already set up. This wires the app sender (email.py → SendGrid HTTP API) to use it.

Verified: a live test send via api.eu.sendgrid.com with the EU subuser key returns 202, and the residency call flips the client host correctly.

Requires (infra, not in this PR)

  1. SENDGRID_API_KEY must be set to the EU regional subuser key (restricted Mail Send) in the echo-api + echo-worker sealed secrets. A global-account key won't be EU-resident even on the EU host.
  2. Separate path: the echo-directus container sends its own emails via SMTP. To make those EU-resident too, set EMAIL_SMTP_HOST=smtp.eu.sendgrid.net and EMAIL_SMTP_PASSWORD=<EU subuser key> on that deployment.

Scope note

This is backend/infra email routing. It is not related to the email-template mobile-layout work in #608 / ECHO-832, despite both touching "email".

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Chores
    • Added SendGrid data residency region configuration option to enable EU-compliant email delivery, with EU region set as the default.
    • Introduced environment variable support for customizing the configured email routing region.
    • Enhanced configuration documentation with EU data residency requirements and guidance on how regional routing affects recipient data handling.

Add SENDGRID_REGION (default "eu") and call set_sendgrid_data_residency()
so the app's transactional email (email.py -> SendGrid HTTP API) routes
through api.eu.sendgrid.com, keeping recipient PII and content in EU data
centers. Requires SENDGRID_API_KEY to belong to an EU regional subuser.

Note: the echo-directus container sends its own emails via SMTP and must
separately move to smtp.eu.sendgrid.net with the EU subuser key (infra).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@spashii, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 56 minutes and 27 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 153d97a4-6059-4bc2-b95f-574e6b8fc776

📥 Commits

Reviewing files that changed from the base of the PR and between 8f51871 and bb1548e.

📒 Files selected for processing (1)
  • echo/server/AGENTS.md

Walkthrough

SendGrid data residency region is now configurable. The EmailSettings schema gains a sendgrid_region field with default "eu", supporting both flat and namespaced env vars. During email transmission, send_email_sync conditionally applies the region via SendGrid's data residency API. Environment setup docs clarify regional subuser requirements.

Changes

SendGrid Data Residency Region Configuration

Layer / File(s) Summary
Settings configuration and environment aliases
echo/server/dembrane/settings.py
EmailSettings adds sendgrid_region field with default "eu" and dual env var aliases (SENDGRID_REGION and EMAIL__SENDGRID_REGION) for configuration flexibility.
Email transmission with region routing
echo/server/dembrane/email.py
send_email_sync reads the configured region and calls sg.set_sendgrid_data_residency(region) when set and not "global", routing delivery through the appropriate regional endpoint.
Configuration documentation
echo/server/.env.sample
Environment sample documents the new SENDGRID_REGION setting with guidance on EU vs global routing and its effect on recipient PII and content handling.

🎯 2 (Simple) | ⏱️ ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and concisely captures the main change: enabling EU data residency routing for SendGrid sends, which aligns perfectly with the PR's core objective.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/sendgrid-eu-residency

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Note that email.py (SendGrid HTTP API) and the echo-directus container
(SendGrid SMTP) are separate paths with separate keys/config, and that EU
data residency must be set on each independently.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@echo/server/dembrane/settings.py`:
- Around line 330-334: The sendgrid_region Field currently accepts arbitrary
strings; add normalization and validation so only allowed regions are used:
define a SendGridRegion enum (e.g., values 'eu' and 'us') or add a Pydantic
validator named normalize_sendgrid_region for the sendgrid_region field that
strips whitespace, lowercases the input, maps common synonyms if desired, and
raises a ValueError for invalid values; update the sendgrid_region Field
declaration (the sendgrid_region symbol and its Field/AliasChoices usage) to use
the enum or validated value so typos/casing like "EU " or "euu" are
rejected/normalized at config load.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 1208c7ba-c46b-4f19-82f6-3bc68095e190

📥 Commits

Reviewing files that changed from the base of the PR and between 5635cab and 8f51871.

📒 Files selected for processing (3)
  • echo/server/.env.sample
  • echo/server/dembrane/email.py
  • echo/server/dembrane/settings.py

Comment on lines +330 to +334
sendgrid_region: str = Field(
default="eu",
alias="SENDGRID_REGION",
validation_alias=AliasChoices("SENDGRID_REGION", "EMAIL__SENDGRID_REGION"),
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Constrain and normalize sendgrid_region at config load.

Line 330 currently accepts arbitrary strings; typos/casing like EU or euu will flow into the SendGrid routing call and can break all sends (downstream queue jobs then retry/fail noisily).

💡 Suggested fix
 class EmailSettings(BaseSettings):
@@
-    sendgrid_region: str = Field(
+    sendgrid_region: Literal["eu", "global"] = Field(
         default="eu",
         alias="SENDGRID_REGION",
         validation_alias=AliasChoices("SENDGRID_REGION", "EMAIL__SENDGRID_REGION"),
     )
+
+    `@field_validator`("sendgrid_region", mode="before")
+    `@classmethod`
+    def normalize_sendgrid_region(cls, value: Any) -> str:
+        region = str(value or "eu").strip().lower()
+        if region not in {"eu", "global"}:
+            raise ValueError("SENDGRID_REGION must be 'eu' or 'global'")
+        return region
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@echo/server/dembrane/settings.py` around lines 330 - 334, The sendgrid_region
Field currently accepts arbitrary strings; add normalization and validation so
only allowed regions are used: define a SendGridRegion enum (e.g., values 'eu'
and 'us') or add a Pydantic validator named normalize_sendgrid_region for the
sendgrid_region field that strips whitespace, lowercases the input, maps common
synonyms if desired, and raises a ValueError for invalid values; update the
sendgrid_region Field declaration (the sendgrid_region symbol and its
Field/AliasChoices usage) to use the enum or validated value so typos/casing
like "EU " or "euu" are rejected/normalized at config load.

@spashii spashii merged commit 384c0da into main Jun 5, 2026
11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant