:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(deployments): add real CloudflarePagesAdapter (#58572)
Richard Solomouf9569ccd9d99
diff --git a/products/deployments/backend/adapters/__init__.py b/products/deployments/backend/adapters/__init__.pyindex 4eb3cec2055e..217b7d71f610 100644--- a/products/deployments/backend/adapters/__init__.py+++ b/products/deployments/backend/adapters/__init__.py@@ -12,7 +12,13 @@ GitHub integration by default, while deployment commit resolution remainsstubbed until the build stream owns that contract."""-from .cloudflare import CloudflareAdapter, CloudflareError, NullCloudflareAdapter, get_cloudflare_adapter+from .cloudflare import (+ CloudflareAdapter,+ CloudflareError,+ CloudflarePagesAdapter,+ NullCloudflareAdapter,+ get_cloudflare_adapter,+)from .github import GitHubAdapter, GitHubBranch, GitHubError, GitHubRepository, NullGitHubAdapter, get_github_adapterfrom .microlink import NullScreenshotAdapter, ScreenshotAdapter, get_screenshot_adapterfrom .temporal import NullWorkflowAdapter, WorkflowAdapter, WorkflowError, get_workflow_adapter@@ -20,6 +26,7 @@ from .temporal import NullWorkflowAdapter, WorkflowAdapter, WorkflowError, get_w__all__ = ["CloudflareAdapter","CloudflareError",+ "CloudflarePagesAdapter","GitHubAdapter","GitHubBranch","GitHubError",diff --git a/products/deployments/backend/adapters/cloudflare.py b/products/deployments/backend/adapters/cloudflare.pyindex ed74b66e1587..ff72d087e8dc 100644--- a/products/deployments/backend/adapters/cloudflare.py+++ b/products/deployments/backend/adapters/cloudflare.py@@ -1,18 +1,33 @@"""Cloudflare Pages adapter boundary.-The Build/Infra stream owns the real implementation (a thin wrapper around-the Cloudflare Pages REST API). We declare the Protocol they implement-against and a Null stub for tests.+Declares the Protocol the rest of the product depends on, a Null stub+for tests and dev, and `CloudflarePagesAdapter` — the real implementation+that calls the Cloudflare Pages REST API. The resolver+`get_cloudflare_adapter()` returns the Null stub unless+`DEPLOYMENTS_CLOUDFLARE_ADAPTER` is wired to point at the real class,+which happens via chart values once the API token is in place."""from __future__ import annotationsfrom dataclasses import dataclassfrom importlib import import_module-from typing import Protocol+from typing import Any, Protocolfrom django.conf import settings+import requests+import structlog++# Tight timeout — `create_project` runs synchronously on the public POST+# /deployment_projects/ request path. Anything longer hurts user-visible+# latency more than it helps a flaky CF response.+CLOUDFLARE_API_TIMEOUT_SECONDS = 10+CLOUDFLARE_API_BASE = "https://api.cloudflare.com/client/v4"+HOG_DEV_ZONE = "hog.dev"++logger = structlog.get_logger(__name__)+@dataclass(frozen=True)class CFProject:@@ -66,12 +81,143 @@ class NullCloudflareAdapter:return CFDeployment(id=deployment_id, url=f"https://{project_name}.pages.dev")+class CloudflarePagesAdapter:+ """Cloudflare Pages adapter backed by the real REST API.++ Resolves settings lazily (at call time, not import time) so missing+ env vars only blow up when the adapter is actually exercised. This+ keeps test environments and the Null path unaffected by the real+ adapter's deployment-dependent config.++ `create_project` creates the Pages project and attaches a custom+ domain under `hog.dev` in a single call sequence. The custom domain+ attachment relies on the `hog.dev` zone living in the same CF+ account as the project — Cloudflare then auto-creates the CNAME+ record in the zone, so DNS records aren't managed from this side.+ """++ def _config(self) -> tuple[str, str, str]:+ account_id = getattr(settings, "DEPLOYMENTS_CLOUDFLARE_ACCOUNT_ID", "")+ api_token = getattr(settings, "DEPLOYMENTS_CLOUDFLARE_API_TOKEN", "")+ project_prefix = getattr(settings, "DEPLOYMENTS_CLOUDFLARE_PROJECT_PREFIX", "")+ if not account_id or not api_token:+ raise CloudflareError(+ "CloudflarePagesAdapter is missing required settings: "+ "DEPLOYMENTS_CLOUDFLARE_ACCOUNT_ID and DEPLOYMENTS_CLOUDFLARE_API_TOKEN."+ )+ return account_id, api_token, project_prefix++ def _request(self, method: str, path: str, *, api_token: str, json: dict[str, Any] | None = None) -> dict[str, Any]:+ url = f"{CLOUDFLARE_API_BASE}{path}"+ headers = {"Authorization": f"Bearer {api_token}", "Content-Type": "application/json"}+ try:+ response = requests.request(method, url, headers=headers, json=json, timeout=CLOUDFLARE_API_TIMEOUT_SECONDS)+ except requests.RequestException as err:+ # Path contains the CF account ID and is logged internally+ # for ops, but is intentionally kept out of the exception+ # message — `CloudflareError` is rendered into the public+ # 502 response body by the viewset.+ logger.warning("cloudflare_api_network_error", method=method, path=path, error=str(err))+ raise CloudflareError(f"Cloudflare API request failed: {err}") from err++ try:+ body = response.json()+ except ValueError as err:+ logger.warning("cloudflare_api_non_json_response", method=method, path=path, status=response.status_code)+ raise CloudflareError(+ f"Cloudflare API returned non-JSON response (status {response.status_code})."+ ) from err++ if not response.ok or not body.get("success", False):+ errors = body.get("errors") or []+ # Fall back to "Unknown error" rather than letting `None` slip+ # into the user-facing message when the error dict is missing+ # `"message"` (or `response.reason` is None for a malformed+ # response).+ message = (+ errors[0].get("message", "Unknown error")+ if errors and isinstance(errors[0], dict)+ else (response.reason or "Unknown error")+ )+ logger.warning(+ "cloudflare_api_call_failed",+ method=method,+ path=path,+ status=response.status_code,+ message=message,+ )+ raise CloudflareError(f"Cloudflare API call failed: {message} (status {response.status_code})")++ result = body.get("result")+ if not isinstance(result, dict):+ logger.warning("cloudflare_api_unexpected_result_shape", method=method, path=path)+ raise CloudflareError("Cloudflare API returned an unexpected result shape.")+ return result++ def create_project(self, *, name: str, production_branch: str) -> CFProject:+ account_id, api_token, project_prefix = self._config()+ cf_project_name = f"{project_prefix}{name}"+ create_path = f"/accounts/{account_id}/pages/projects"+ project_path = f"{create_path}/{cf_project_name}"++ self._request(+ "POST",+ create_path,+ api_token=api_token,+ json={"name": cf_project_name, "production_branch": production_branch},+ )++ # Attach the customer-facing `<name>.hog.dev` custom domain. CF+ # creates the CNAME in the hog.dev zone automatically because the+ # zone and the project live in the same account. The CF Pages+ # project's own `*.pages.dev` URL still works, but `subdomain`+ # below is what the product surfaces to the user.+ custom_domain = f"{name}.{HOG_DEV_ZONE}"+ try:+ self._request("POST", f"{project_path}/domains", api_token=api_token, json={"name": custom_domain})+ except CloudflareError:+ # The project create succeeded but the domain attach failed.+ # The CF project name is deterministic (`{prefix}{team_id}-{slug}`),+ # so leaving the orphan would block the user's next retry with+ # "Project name already taken". Best-effort cleanup; if the+ # delete itself fails we still surface the original error.+ try:+ self._request("DELETE", project_path, api_token=api_token)+ except CloudflareError as cleanup_err:+ logger.warning(+ "cloudflare_orphan_cleanup_failed",+ project=cf_project_name,+ error=str(cleanup_err),+ )+ raise++ return CFProject(name=cf_project_name, subdomain=custom_domain)++ def rollback(self, *, project_name: str, deployment_id: str) -> CFDeployment:+ account_id, api_token, _ = self._config()+ result = self._request(+ "POST",+ f"/accounts/{account_id}/pages/projects/{project_name}/deployments/{deployment_id}/rollback",+ api_token=api_token,+ )+ # The rollback endpoint returns a deployment object. `url` is the+ # public URL of the deployment that's now serving production.+ url = result.get("url")+ if not isinstance(url, str) or not url:+ raise CloudflareError("Cloudflare rollback succeeded but returned no deployment URL.")+ new_deployment_id = result.get("id")+ if not isinstance(new_deployment_id, str) or not new_deployment_id:+ raise CloudflareError("Cloudflare rollback succeeded but returned no deployment id.")+ return CFDeployment(id=new_deployment_id, url=url)++def get_cloudflare_adapter() -> CloudflareAdapter:"""Resolve the adapter implementation from settings.Reads `settings.DEPLOYMENTS_CLOUDFLARE_ADAPTER` as a `"module.path:ClassName"`- string; if unset, returns `NullCloudflareAdapter`. Build/Infra wires the- real implementation by setting this env var.+ string; if unset, returns `NullCloudflareAdapter`. Wire the real+ implementation in by setting this env var to+ `products.deployments.backend.adapters.cloudflare:CloudflarePagesAdapter`."""path = getattr(settings, "DEPLOYMENTS_CLOUDFLARE_ADAPTER", None)if not path:diff --git a/products/deployments/backend/test/test_cloudflare_adapter.py b/products/deployments/backend/test/test_cloudflare_adapter.pynew file mode 100644index 000000000000..c3bf97f54b61--- /dev/null+++ b/products/deployments/backend/test/test_cloudflare_adapter.py@@ -0,0 +1,264 @@+from __future__ import annotations++from django.test import SimpleTestCase, override_settings++import requests+import responses+from parameterized import parameterized++from products.deployments.backend.adapters.cloudflare import (+ CLOUDFLARE_API_BASE,+ CLOUDFLARE_API_TIMEOUT_SECONDS,+ CFProject,+ CloudflareError,+ CloudflarePagesAdapter,+)++ACCOUNT_ID = "test-account-id"+PROJECT_PREFIX = "hogdev-"+++@override_settings(+ DEPLOYMENTS_CLOUDFLARE_ACCOUNT_ID=ACCOUNT_ID,+ DEPLOYMENTS_CLOUDFLARE_API_TOKEN="test-token",+ DEPLOYMENTS_CLOUDFLARE_PROJECT_PREFIX=PROJECT_PREFIX,+)+class TestCloudflarePagesAdapter(SimpleTestCase):+ @responses.activate+ def test_create_project_posts_prefixed_name_and_attaches_hog_dev_domain(self) -> None:+ create_url = f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects"+ domain_url = f"{create_url}/{PROJECT_PREFIX}1-myapp/domains"+ responses.add(+ responses.POST,+ create_url,+ json={"success": True, "errors": [], "messages": [], "result": {"name": f"{PROJECT_PREFIX}1-myapp"}},+ status=200,+ )+ responses.add(+ responses.POST,+ domain_url,+ json={"success": True, "errors": [], "messages": [], "result": {"name": "1-myapp.hog.dev"}},+ status=200,+ )++ project = CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")++ self.assertEqual(project, CFProject(name=f"{PROJECT_PREFIX}1-myapp", subdomain="1-myapp.hog.dev"))+ self.assertEqual(len(responses.calls), 2)+ self.assertEqual(+ responses.calls[0].request.body,+ b'{"name": "hogdev-1-myapp", "production_branch": "main"}',+ )+ self.assertEqual(responses.calls[1].request.body, b'{"name": "1-myapp.hog.dev"}')+ # Bearer auth + request-path timeout.+ self.assertEqual(responses.calls[0].request.headers["Authorization"], "Bearer test-token")++ @responses.activate+ def test_create_project_raises_when_cloudflare_returns_success_false(self) -> None:+ responses.add(+ responses.POST,+ f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects",+ json={+ "success": False,+ "errors": [{"code": 1009, "message": "Project name already taken"}],+ "result": None,+ },+ status=200,+ )++ with self.assertRaises(CloudflareError) as cm:+ CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")+ self.assertIn("Project name already taken", str(cm.exception))++ @responses.activate+ def test_create_project_falls_back_when_cf_error_lacks_message_key(self) -> None:+ # Some CF responses come back with an `errors` array of dicts+ # that lack a `"message"` key — without a fallback, the user+ # would see `"Cloudflare API call failed: None (status 500)"`.+ responses.add(+ responses.POST,+ f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects",+ json={"success": False, "errors": [{"code": 9001}], "result": None},+ status=500,+ )++ with self.assertRaises(CloudflareError) as cm:+ CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")+ self.assertIn("Unknown error", str(cm.exception))+ self.assertNotIn("None", str(cm.exception))++ @responses.activate+ def test_create_project_error_does_not_leak_account_id(self) -> None:+ # CloudflareError is rendered into a public 502 response body by+ # the viewset, so the account ID (which appears in the API path)+ # must never end up in the exception message.+ responses.add(+ responses.POST,+ f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects",+ json={"success": False, "errors": [{"message": "boom"}], "result": None},+ status=500,+ )++ with self.assertRaises(CloudflareError) as cm:+ CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")+ self.assertNotIn(ACCOUNT_ID, str(cm.exception))++ @responses.activate+ def test_create_project_raises_on_http_error(self) -> None:+ responses.add(+ responses.POST,+ f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects",+ json={"success": False, "errors": [{"message": "Unauthorized"}], "result": None},+ status=401,+ )++ with self.assertRaises(CloudflareError) as cm:+ CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")+ self.assertIn("Unauthorized", str(cm.exception))+ self.assertIn("401", str(cm.exception))++ @responses.activate+ def test_create_project_raises_on_network_error(self) -> None:+ responses.add(+ responses.POST,+ f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects",+ body=requests.ConnectionError("connection refused"),+ )++ with self.assertRaises(CloudflareError) as cm:+ CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")+ self.assertIn("connection refused", str(cm.exception))++ @parameterized.expand(+ [+ ("missing_account_id", "", "test-token"),+ ("missing_api_token", ACCOUNT_ID, ""),+ ("both_missing", "", ""),+ ]+ )+ def test_create_project_raises_when_settings_missing(self, _name: str, account_id: str, api_token: str) -> None:+ with override_settings(+ DEPLOYMENTS_CLOUDFLARE_ACCOUNT_ID=account_id,+ DEPLOYMENTS_CLOUDFLARE_API_TOKEN=api_token,+ ):+ with self.assertRaises(CloudflareError) as cm:+ CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")+ self.assertIn("missing required settings", str(cm.exception))++ @responses.activate+ def test_create_project_does_not_attach_domain_if_create_call_fails(self) -> None:+ responses.add(+ responses.POST,+ f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects",+ json={"success": False, "errors": [{"message": "bad request"}], "result": None},+ status=400,+ )++ with self.assertRaises(CloudflareError):+ CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")+ # Only the create call should have been attempted.+ self.assertEqual(len(responses.calls), 1)++ @responses.activate+ def test_create_project_deletes_orphan_when_domain_attach_fails(self) -> None:+ # Create succeeds.+ create_url = f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects"+ project_url = f"{create_url}/{PROJECT_PREFIX}1-myapp"+ responses.add(+ responses.POST,+ create_url,+ json={"success": True, "errors": [], "messages": [], "result": {"name": f"{PROJECT_PREFIX}1-myapp"}},+ status=200,+ )+ # Domain attach fails.+ responses.add(+ responses.POST,+ f"{project_url}/domains",+ json={"success": False, "errors": [{"message": "domain conflict"}], "result": None},+ status=409,+ )+ # Cleanup DELETE succeeds.+ responses.add(+ responses.DELETE,+ project_url,+ json={"success": True, "errors": [], "messages": [], "result": {"id": f"{PROJECT_PREFIX}1-myapp"}},+ status=200,+ )++ with self.assertRaises(CloudflareError) as cm:+ CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")+ # The error surfaced is the domain-attach failure, not a delete-cleanup error.+ self.assertIn("domain conflict", str(cm.exception))+ # All three calls happened: create, attach, delete (cleanup).+ self.assertEqual(len(responses.calls), 3)+ self.assertEqual(responses.calls[2].request.method, "DELETE")++ @responses.activate+ def test_create_project_still_raises_original_error_if_cleanup_also_fails(self) -> None:+ create_url = f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects"+ project_url = f"{create_url}/{PROJECT_PREFIX}1-myapp"+ responses.add(+ responses.POST,+ create_url,+ json={"success": True, "errors": [], "messages": [], "result": {"name": f"{PROJECT_PREFIX}1-myapp"}},+ status=200,+ )+ responses.add(+ responses.POST,+ f"{project_url}/domains",+ json={"success": False, "errors": [{"message": "domain attach failed"}], "result": None},+ status=500,+ )+ responses.add(+ responses.DELETE,+ project_url,+ json={"success": False, "errors": [{"message": "cleanup also failed"}], "result": None},+ status=500,+ )++ with self.assertRaises(CloudflareError) as cm:+ CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")+ # User-facing error is still the attach failure — cleanup error is logged, not raised.+ self.assertIn("domain attach failed", str(cm.exception))+ self.assertNotIn("cleanup also failed", str(cm.exception))++ @responses.activate+ def test_rollback_returns_deployment_from_response(self) -> None:+ url = f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects/hogdev-1-myapp/deployments/dep-old/rollback"+ responses.add(+ responses.POST,+ url,+ json={+ "success": True,+ "errors": [],+ "messages": [],+ "result": {"id": "dep-new", "url": "https://hogdev-1-myapp.pages.dev"},+ },+ status=200,+ )++ deployment = CloudflarePagesAdapter().rollback(project_name="hogdev-1-myapp", deployment_id="dep-old")++ self.assertEqual(deployment.id, "dep-new")+ self.assertEqual(deployment.url, "https://hogdev-1-myapp.pages.dev")++ @responses.activate+ def test_rollback_raises_when_response_missing_url(self) -> None:+ responses.add(+ responses.POST,+ f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects/p/deployments/d/rollback",+ json={"success": True, "errors": [], "messages": [], "result": {"id": "dep-new"}},+ status=200,+ )++ with self.assertRaises(CloudflareError) as cm:+ CloudflarePagesAdapter().rollback(project_name="p", deployment_id="d")+ self.assertIn("no deployment URL", str(cm.exception))+++class TestCloudflareApiConstants(SimpleTestCase):+ def test_timeout_is_short_enough_for_request_path(self) -> None:+ # Sanity: the timeout exists for a reason — keep it small enough+ # that a hanging CF API doesn't drag the user-facing POST handler+ # past typical browser timeouts.+ self.assertLessEqual(CLOUDFLARE_API_TIMEOUT_SECONDS, 15)