Skip to content

: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.

feat(deployments): main deployments api (#58460)

Matheus Batista437047f61558
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index 6bb39056d80e..f5dc98824628 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -92,6 +92,8 @@ rules:
|DataWarehouseSavedQueryFolder
|DataWarehouseTable
|Deployment
+ |DeploymentEvent
+ |DeploymentProject
|DesktopRecording
|EarlyAccessFeature
|EmailMessageMapping
@@ -310,6 +312,8 @@ rules:
|DataWarehouseSavedQueryFolder
|DataWarehouseTable
|Deployment
+ |DeploymentEvent
+ |DeploymentProject
|DesktopRecording
|EarlyAccessFeature
|EmailMessageMapping
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index b3135525cd85..baaaafee3b23 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -314,11 +314,20 @@ project_features_router = projects_router.register(
"project_early_access_feature",
["project_id"],
)
-projects_router.register(
+# Deployments: DeploymentProject is the top-level entity; Deployment nests under it.
+# Mirrors `project_tasks_router` → `runs` pattern above for the parent/child URL shape:
+# /api/projects/{team_id}/deployment_projects/{deployment_project_id}/deployments/...
+project_deployment_projects_router = projects_router.register(
+ r"deployment_projects",
+ deployments.DeploymentProjectViewSet,
+ "project_deployment_projects",
+ ["project_id"],
+)
+project_deployment_projects_router.register(
r"deployments",
deployments.DeploymentViewSet,
- "project_deployments",
- ["project_id"],
+ "project_deployment_projects_deployments",
+ ["project_id", "deployment_project_id"],
)
# Tasks endpoints
diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.py
index 6baed0bbe7c2..dd559bc5cb5b 100644
--- a/posthog/rbac/user_access_control.py
+++ b/posthog/rbac/user_access_control.py
@@ -297,6 +297,11 @@ def model_to_resource(model: Model) -> Optional[APIScopeObject]:
return "customer_journey"
if name in ("replaylens", "replayobservation"):
return "replay_lens"
+ if name == "deploymentproject":
+ # DeploymentProject + Deployment share the `deployment` scope/resource
+ # so RBAC checks (scope, queryset filter, object-level) fire for both
+ # via AccessControlViewSetMixin.
+ return "deployment"
if name not in API_SCOPE_OBJECTS or name in INTERNAL_API_SCOPE_OBJECTS:
return None
diff --git a/posthog/urls.py b/posthog/urls.py
index 7b258850c9ca..48195f1a46f1 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -48,6 +48,7 @@ from posthog.oauth2_urls import urlpatterns as oauth2_urls
from posthog.temporal.codec_server import decode_payloads
from products.data_warehouse.backend.api.public_source_configs import PublicSourceConfigViewSet
+from products.deployments.backend.api.internal import InternalDeploymentTransitionsViewSet
from products.early_access_features.backend.api import early_access_features
from products.legal_documents.backend.presentation.webhook import legal_document_pandadoc_webhook
from products.messaging.backend.api.customerio_webhook import CustomerIOWebhookView
@@ -316,6 +317,15 @@ urlpatterns = [
"api/projects/<str:team_id>/internal/signals/emit",
csrf_exempt(signals_views.InternalSignalViewSet.as_view({"post": "emit"})),
),
+ # Deployments internal endpoints — Temporal build worker posts here.
+ path(
+ "api/internal/deployments/<uuid:deployment_id>/transitions/",
+ csrf_exempt(InternalDeploymentTransitionsViewSet.as_view({"post": "transitions"})),
+ ),
+ path(
+ "api/internal/deployments/<uuid:deployment_id>/events/",
+ csrf_exempt(InternalDeploymentTransitionsViewSet.as_view({"post": "events"})),
+ ),
# Test setup endpoint (only available in TEST mode)
path("api/setup_test/<str:test_name>/", csrf_exempt(playwright_setup.setup_test)),
opt_slash_path(
diff --git a/products/deployments/backend/adapters/__init__.py b/products/deployments/backend/adapters/__init__.py
new file mode 100644
index 000000000000..922774f64107
--- /dev/null
+++ b/products/deployments/backend/adapters/__init__.py
@@ -0,0 +1,35 @@
+"""External-system boundaries for the Deployments product.
+
+Each adapter is a `typing.Protocol` that declares the surface area we need
+from an external system (Cloudflare Pages, GitHub, microlink screenshots,
+Temporal workflow control). Build/Infra and GitHub streams substitute real
+implementations via `settings.DEPLOYMENTS_*_ADAPTER` (path-string → class)
+without touching any of our files.
+
+For tests and the dev environment, a `Null*` stub is the default — it
+returns canned values so the rest of the codebase exercises real code
+paths without standing up external services.
+"""
+
+from .cloudflare import CloudflareAdapter, CloudflareError, NullCloudflareAdapter, get_cloudflare_adapter
+from .github import GitHubAdapter, GitHubError, NullGitHubAdapter, get_github_adapter
+from .microlink import NullScreenshotAdapter, ScreenshotAdapter, get_screenshot_adapter
+from .temporal import NullWorkflowAdapter, WorkflowAdapter, WorkflowError, get_workflow_adapter
+
+__all__ = [
+ "CloudflareAdapter",
+ "CloudflareError",
+ "GitHubAdapter",
+ "GitHubError",
+ "NullCloudflareAdapter",
+ "NullGitHubAdapter",
+ "NullScreenshotAdapter",
+ "NullWorkflowAdapter",
+ "ScreenshotAdapter",
+ "WorkflowAdapter",
+ "WorkflowError",
+ "get_cloudflare_adapter",
+ "get_github_adapter",
+ "get_screenshot_adapter",
+ "get_workflow_adapter",
+]
diff --git a/products/deployments/backend/adapters/cloudflare.py b/products/deployments/backend/adapters/cloudflare.py
new file mode 100644
index 000000000000..ed74b66e1587
--- /dev/null
+++ b/products/deployments/backend/adapters/cloudflare.py
@@ -0,0 +1,81 @@
+"""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.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from importlib import import_module
+from typing import Protocol
+
+from django.conf import settings
+
+
+@dataclass(frozen=True)
+class CFProject:
+ """Minimal Cloudflare Pages project descriptor we depend on."""
+
+ name: str
+ subdomain: str
+
+
+@dataclass(frozen=True)
+class CFDeployment:
+ """Minimal Cloudflare Pages deployment descriptor we depend on."""
+
+ id: str
+ url: str
+
+
+class CloudflareAdapter(Protocol):
+ """Surface we depend on from Cloudflare Pages.
+
+ `create_project` is called synchronously from the public POST
+ /deployment_projects/ handler, BEFORE the DB write — see
+ deployments.md "Provisioning flow" and CLAUDE.md ("Avoid performing
+ irreversible side effects inside an atomic block").
+
+ `rollback` is called from the build worker when a rollback-trigger
+ deployment lands; not from our process. We declare it here so the
+ Protocol mirrors the full Cloudflare surface area.
+ """
+
+ def create_project(self, *, name: str, production_branch: str) -> CFProject: ...
+
+ def rollback(self, *, project_name: str, deployment_id: str) -> CFDeployment: ...
+
+
+class CloudflareError(Exception):
+ """Raised when a Cloudflare API call fails. Surfaced as 502 by the viewset."""
+
+
+class NullCloudflareAdapter:
+ """Stub used in tests and the dev environment.
+
+ `create_project` returns a synthetic CFProject whose name matches what
+ the real API would assign. `rollback` is a no-op that echoes its input.
+ """
+
+ def create_project(self, *, name: str, production_branch: str) -> CFProject:
+ return CFProject(name=name, subdomain=f"{name}.pages.dev")
+
+ def rollback(self, *, project_name: str, deployment_id: str) -> CFDeployment:
+ return CFDeployment(id=deployment_id, url=f"https://{project_name}.pages.dev")
+
+
+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.
+ """
+ path = getattr(settings, "DEPLOYMENTS_CLOUDFLARE_ADAPTER", None)
+ if not path:
+ return NullCloudflareAdapter()
+ module_path, class_name = path.split(":")
+ module = import_module(module_path)
+ return getattr(module, class_name)()
diff --git a/products/deployments/backend/adapters/github.py b/products/deployments/backend/adapters/github.py
new file mode 100644
index 000000000000..c2e09d9da2c4
--- /dev/null
+++ b/products/deployments/backend/adapters/github.py
@@ -0,0 +1,74 @@
+"""GitHub adapter boundary.
+
+The GitHub auth stream owns the real implementation (resolves HEAD of a
+branch, fetches commit metadata, exchanges PAT/OAuth). We declare the
+Protocol they implement against and a Null stub for tests.
+"""
+
+from __future__ import annotations
+
+from importlib import import_module
+from typing import Protocol
+
+from django.conf import settings
+
+from ..domain.contracts import CommitMetadata
+
+
+class GitHubAdapter(Protocol):
+ """Surface we depend on from GitHub.
+
+ The build worker resolves a commit SHA off the request path — if the
+ API request didn't pin one — by calling `head_of_branch`. The API
+ itself rarely needs `get_commit`; we expose it because the GitHub
+ stream may want to populate commit metadata on the Deployment row at
+ create-time (cheaper than waiting for the worker to fill it in).
+
+ `access_token` is the short-lived GitHub App installation token resolved
+ by `create_deployment` from the project's `posthog.Integration` row.
+ None means unauthenticated (public repos only).
+ """
+
+ def head_of_branch(self, *, repo_url: str, branch: str, access_token: str | None) -> CommitMetadata: ...
+
+ def get_commit(self, *, repo_url: str, sha: str, access_token: str | None) -> CommitMetadata: ...
+
+
+class GitHubError(Exception):
+ """Raised when a GitHub API call fails. Translated to 502 by callers."""
+
+
+class NullGitHubAdapter:
+ """Stub used in tests and the dev environment.
+
+ Returns synthetic commit metadata that mirrors the shape of a real
+ response. The author email matches the test team's owner email pattern
+ so author-filter tests can assert against a stable value.
+ """
+
+ def head_of_branch(self, *, repo_url: str, branch: str, access_token: str | None) -> CommitMetadata:
+ return CommitMetadata(
+ sha="0" * 40,
+ message="chore: stubbed commit (NullGitHubAdapter)",
+ author_name="Test Author",
+ author_email="[email protected]",
+ branch=branch,
+ )
+
+ def get_commit(self, *, repo_url: str, sha: str, access_token: str | None) -> CommitMetadata:
+ return CommitMetadata(
+ sha=sha,
+ message="chore: stubbed commit (NullGitHubAdapter)",
+ author_name="Test Author",
+ author_email="[email protected]",
+ branch="main",
+ )
+
+
+def get_github_adapter() -> GitHubAdapter:
+ path = getattr(settings, "DEPLOYMENTS_GITHUB_ADAPTER", None)
+ if not path:
+ return NullGitHubAdapter()
+ module_path, class_name = path.split(":")
+ module = import_module(module_path)
+ return getattr(module, class_name)()
diff --git a/products/deployments/backend/adapters/microlink.py b/products/deployments/backend/adapters/microlink.py
new file mode 100644
index 000000000000..feb7420d1682
--- /dev/null
+++ b/products/deployments/backend/adapters/microlink.py
@@ -0,0 +1,43 @@
+"""Screenshot adapter boundary (microlink.io for v1).
+
+Build/Infra stream owns the real implementation. We declare the Protocol
+plus a Null stub for tests.
+
+Screenshot capture is best-effort: a failure surfaces as a
+`preview_capture_failed` DeploymentEvent row but never rolls back the
+`ready` transition.
+"""
+
+from __future__ import annotations
+
+from importlib import import_module
+from typing import Protocol
+
+from django.conf import settings
+
+
+class ScreenshotAdapter(Protocol):
+ """Capture a screenshot of the given URL.
+
+ Returns the image URL on success, or None when capture failed (rate
+ limit, timeout, page-load error). Callers must tolerate None.
+ """
+
+ def capture(self, *, url: str) -> str | None: ...
+
+
+class NullScreenshotAdapter:
+ """Stub used in tests. Returns None to mirror the failure path so
+ callers exercise the `preview_capture_failed` event-emission code."""
+
+ def capture(self, *, url: str) -> str | None:
+ return None
+
+
+def get_screenshot_adapter() -> ScreenshotAdapter:
+ path = getattr(settings, "DEPLOYMENTS_SCREENSHOT_ADAPTER", None)
+ if not path:
+ return NullScreenshotAdapter()
+ module_path, class_name = path.split(":")
+ module = import_module(module_path)
+ return getattr(module, class_name)()
diff --git a/products/deployments/backend/adapters/temporal.py b/products/deployments/backend/adapters/temporal.py
new file mode 100644
index 000000000000..fc34f5817622
--- /dev/null
+++ b/products/deployments/backend/adapters/temporal.py
@@ -0,0 +1,64 @@
+"""Temporal workflow adapter boundary.
+
+Build/Infra stream owns the real implementation (a thin wrapper around
+the Temporal Python SDK). We declare the Protocol they implement against
+and a Null stub for tests.
+
+We only ever:
+- Start a build workflow when a Deployment is created (one `start_build`
+ call per new row).
+- Signal cancellation when the user clicks Cancel on a non-terminal
+ deployment (`signal_cancel`).
+
+The workflow itself posts status transitions and events back to our
+internal API — we never poll Temporal.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from importlib import import_module
+from typing import Protocol
+
+from django.conf import settings
+
+from ..domain.contracts import BuildInput
+
+
+@dataclass(frozen=True)
+class WorkflowHandle:
+ """Reference we persist on the Deployment row so cancel() can target the run."""
+
+ workflow_id: str
+ run_id: str
+
+
+class WorkflowAdapter(Protocol):
+ def start_build(self, *, workflow_input: BuildInput) -> WorkflowHandle: ...
+
+ def signal_cancel(self, *, workflow_id: str) -> None: ...
+
+
+class WorkflowError(Exception):
+ """Raised when a Temporal start/signal call fails."""
+
+
+class NullWorkflowAdapter:
+ """Stub used in tests. Returns a deterministic WorkflowHandle so callers
+ can persist + assert on temporal_workflow_id / temporal_run_id."""
+
+ def start_build(self, *, workflow_input: BuildInput) -> WorkflowHandle:
+ wf_id = f"deployment-{workflow_input.deployment_id}"
+ return WorkflowHandle(workflow_id=wf_id, run_id=f"{wf_id}-run-0")
+
+ def signal_cancel(self, *, workflow_id: str) -> None:
+ return None
+
+
+def get_workflow_adapter() -> WorkflowAdapter:
+ path = getattr(settings, "DEPLOYMENTS_WORKFLOW_ADAPTER", None)
+ if not path:
+ return NullWorkflowAdapter()
+ module_path, class_name = path.split(":")
+ module = import_module(module_path)
+ return getattr(module, class_name)()
diff --git a/products/deployments/backend/api/__init__.py b/products/deployments/backend/api/__init__.py
index 3ba09ed6dbaa..6eb4de889acb 100644
--- a/products/deployments/backend/api/__init__.py
+++ b/products/deployments/backend/api/__init__.py
@@ -1,3 +1,10 @@
+from .deployment_projects import DeploymentProjectViewSet, DeploymentsAccessPermission
from .deployments import DeploymentViewSet
+from .internal import InternalDeploymentTransitionsViewSet
-__all__ = ["DeploymentViewSet"]
+__all__ = [
+ "DeploymentProjectViewSet",
+ "DeploymentViewSet",
+ "DeploymentsAccessPermission",
+ "InternalDeploymentTransitionsViewSet",
+]
diff --git a/products/deployments/backend/api/deployment_projects.py b/products/deployments/backend/api/deployment_projects.py
new file mode 100644
index 000000000000..43ef697248d5
--- /dev/null
+++ b/products/deployments/backend/api/deployment_projects.py
@@ -0,0 +1,137 @@
+"""DRF wiring for the DeploymentProject viewset.
+
+`DeploymentProject` is the top-level entity in the Deployments product —
+one connected repo + its Cloudflare Pages target. Deployments are nested
+under projects (see api/deployments.py).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from django.utils import timezone
+
+from drf_spectacular.utils import OpenApiResponse, extend_schema
+from rest_framework import filters, serializers, status, viewsets
+from rest_framework.permissions import BasePermission, IsAuthenticated
+from rest_framework.request import Request
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.permissions import APIScopePermission
+from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
+
+from ..access import has_deployments_access
+from ..adapters import CloudflareError, get_cloudflare_adapter
+from ..models import DeploymentProject
+from ..serializers import DeploymentProjectSerializer
+from ..services import provision_project
+
+
+class DeploymentsAccessPermission(BasePermission):
+ """Gate the whole product behind the `deployments` feature flag."""
+
+ message = "Deployments is not enabled for this team."
+
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ team_id = getattr(view, "team_id", None)
+ return has_deployments_access(request.user, team_id=team_id)
+
+
+@extend_schema(tags=["deployments"])
+class DeploymentProjectViewSet(
+ TeamAndOrgViewSetMixin,
+ AccessControlViewSetMixin,
+ viewsets.ModelViewSet,
+):
+ """CRUD for DeploymentProject (the connected-repo + hosting-target entity).
+
+ Create-time provisioning calls Cloudflare BEFORE writing the DB row
+ (see services/provision_project.py for the rationale). Delete is a
+ soft-delete; Cloudflare-side cleanup is deferred to a periodic Celery
+ task.
+ """
+
+ scope_object = "deployment"
+ authentication_classes = [
+ SessionAuthentication,
+ PersonalAPIKeyAuthentication,
+ OAuthAccessTokenAuthentication,
+ ]
+ permission_classes = [IsAuthenticated, APIScopePermission, DeploymentsAccessPermission]
+ serializer_class = DeploymentProjectSerializer
+ # all_teams is the unscoped sibling manager — `objects` is fail-closed
+ # and would raise without a team context at class-definition time.
+ queryset = DeploymentProject.all_teams.all()
+ filter_backends = [filters.SearchFilter, filters.OrderingFilter]
+ search_fields = ["name", "slug", "repo_url"]
+ ordering_fields = ["created_at", "updated_at", "name"]
+ ordering = ["-created_at"]
+ # URL parent `project_id` is the PostHog team_id (project/team alias).
+ # Rewrite to the model field so the framework's parent-lookup filter
+ # finds rows. Without this the router would try to filter `team`,
+ # which doesn't exist on ProductTeamModel.
+ filter_rewrite_rules = {"project_id": "team_id"}
+
+ def safely_get_queryset(self, queryset: Any) -> Any:
+ # Default queryset hides soft-deleted projects.
+ return queryset.filter(team_id=self.team_id).exclude(deleted=True)
+
+ @extend_schema(
+ request=DeploymentProjectSerializer,
+ responses={
+ status.HTTP_201_CREATED: DeploymentProjectSerializer,
+ status.HTTP_502_BAD_GATEWAY: OpenApiResponse(description="Cloudflare provisioning failed."),
+ },
+ )
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ serializer = self.get_serializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+ try:
+ project = provision_project.execute(
+ provision_project.ProvisionInput(
+ team_id=self.team_id,
+ created_by_id=request.user.id if request.user.is_authenticated else None,
+ name=serializer.validated_data["name"],
+ slug=serializer.validated_data["slug"],
+ repo_url=serializer.validated_data["repo_url"],
+ default_branch=serializer.validated_data.get("default_branch", "main"),
+ github_integration_id=serializer.validated_data.get("github_integration_id"),
+ build_command=serializer.validated_data.get("build_command"),
+ output_dir=serializer.validated_data.get("output_dir", "dist"),
+ framework=serializer.validated_data.get("framework"),
+ inject_posthog_snippet=serializer.validated_data.get("inject_posthog_snippet", False),
+ ),
+ cloudflare=get_cloudflare_adapter(),
+ )
+ except CloudflareError as exc:
+ return Response(
+ {"detail": f"Cloudflare provisioning failed: {exc}"},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+
+ return Response(self.get_serializer(project).data, status=status.HTTP_201_CREATED)
+
+ @extend_schema(request=DeploymentProjectSerializer, responses={status.HTTP_200_OK: DeploymentProjectSerializer})
+ def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ return super().partial_update(request, *args, **kwargs)
+
+ @extend_schema(responses={status.HTTP_204_NO_CONTENT: None})
+ def destroy(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ # Soft-delete: mark deleted=True / deleted_at=now() rather than removing
+ # the row. The slug remains reserved (the partial unique constraint
+ # excludes deleted rows so a new project can reuse the slug after
+ # soft-delete, but anyone with the old URL still gets a 404).
+ instance = self.get_object()
+ instance.deleted = True
+ instance.deleted_at = timezone.now()
+ instance.save(update_fields=["deleted", "deleted_at", "updated_at"])
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+
+class DeploymentProjectActionResponseSerializer(serializers.Serializer):
+ """Generic action response shape (e.g. for 502 on Cloudflare failure)."""
+
+ detail = serializers.CharField(help_text="Human-readable explanation of the response.")
diff --git a/products/deployments/backend/api/deployments.py b/products/deployments/backend/api/deployments.py
index 323c6d6df6c9..c16b1cfa7d9d 100644
--- a/products/deployments/backend/api/deployments.py
+++ b/products/deployments/backend/api/deployments.py
@@ -1,207 +1,95 @@
-"""DRF wiring for the Deployments product.
+"""DRF wiring for the Deployment viewset (nested under DeploymentProject).
-Scaffold only. The serializer surfaces every model field with `help_text`
-so generated TypeScript types and MCP tools have real descriptions, but
-computed fields (`is_current`, `duration_seconds`) return hardcoded
-placeholders. The viewset registers `list`, `retrieve`, and the
-501-stubbed actions (`redeploy`, `rollback`, `refresh_preview`).
+URL: `/api/projects/{team_id}/deployment_projects/{deployment_project_id}/deployments/...`
+
+list/retrieve are read-only views over the model. Mutating actions
+(create, redeploy, rollback, cancel, refresh_preview) defer all business
+logic to the services layer.
"""
from __future__ import annotations
from typing import Any
-from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field
-from rest_framework import serializers, status, viewsets
+from django.db.models import Exists, OuterRef
+
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
+from rest_framework import filters, status, viewsets
from rest_framework.decorators import action
-from rest_framework.permissions import BasePermission
+from rest_framework.exceptions import NotFound, PermissionDenied
+from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
-from rest_framework.views import APIView
from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
+from posthog.permissions import APIScopePermission
from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
-from ..access import has_deployments_access
-from ..models import Deployment
-
-
-class DeploymentsAccessPermission(BasePermission):
- """Gate the whole product behind the `deployments` feature flag.
-
- Returns 403 instead of 404 because we already have a flag-driven
- sidebar entry — there's no point pretending the URL doesn't exist
- once a request has reached this viewset.
- """
-
- message = "Deployments is not enabled for this team."
-
- def has_permission(self, request: Request, view: APIView) -> bool:
- team_id = getattr(view, "team_id", None)
- return has_deployments_access(request.user, team_id=team_id)
-
-
-class DeploymentSerializer(serializers.ModelSerializer):
- id = serializers.UUIDField(read_only=True, help_text="Unique identifier for the deployment.")
- status = serializers.ChoiceField(
- choices=Deployment.Status.choices,
- help_text=(
- "Current pipeline stage for the deployment. Valid values: "
- "queued, initializing, building, ready, error, cancelled."
+from ..adapters import GitHubError
+from ..domain.trigger import TriggerKind
+from ..models import Deployment, DeploymentEvent, DeploymentProject
+from ..serializers import DeploymentEventSerializer, DeploymentSerializer
+from ..serializers.deployment import (
+ DeploymentActionResponseSerializer,
+ DeploymentConflictResponseSerializer,
+ DeploymentCreateInputSerializer,
+)
+from ..services import cancel, create_deployment, redeploy, refresh_preview, rollback
+from .deployment_projects import DeploymentsAccessPermission
+
+
+@extend_schema(
+ tags=["deployments"],
+ parameters=[
+ OpenApiParameter(
+ name="deployment_project_id",
+ type=OpenApiTypes.UUID,
+ location=OpenApiParameter.PATH,
+ description="UUID of the parent DeploymentProject.",
),
- )
- started_at = serializers.DateTimeField(
- allow_null=True,
- required=False,
- help_text="Timestamp when the pipeline started building. Null while still queued.",
- )
- finished_at = serializers.DateTimeField(
- allow_null=True,
- required=False,
- help_text="Timestamp when the pipeline finished (regardless of outcome). Null while still running.",
- )
- created_at = serializers.DateTimeField(
- read_only=True,
- help_text="Timestamp when the deployment row was created.",
- )
-
- commit_sha = serializers.CharField(
- allow_blank=True,
- required=False,
- max_length=64,
- help_text="Git commit SHA the deployment was built from. Empty for non-git triggers.",
- )
- commit_message = serializers.CharField(
- allow_blank=True,
- required=False,
- help_text="Commit message associated with the commit SHA.",
- )
- commit_author_name = serializers.CharField(
- allow_blank=True,
- required=False,
- max_length=255,
- help_text="Display name of the commit author.",
- )
- commit_author_email = serializers.CharField(
- allow_blank=True,
- required=False,
- max_length=255,
- help_text="Email address of the commit author.",
- )
-
- repo_url = serializers.URLField(
- allow_blank=True,
- required=False,
- max_length=1024,
- help_text="HTTPS URL of the source repository this deployment came from.",
- )
- branch = serializers.CharField(
- allow_blank=True,
- required=False,
- max_length=255,
- help_text="Source branch the deployment was built from.",
- )
-
- deployment_url = serializers.URLField(
- allow_blank=True,
- required=False,
- max_length=1024,
- help_text="Public URL where the built site is served once the deployment is ready.",
- )
- preview_image_url = serializers.URLField(
- allow_blank=True,
- required=False,
- max_length=1024,
- help_text="URL of a screenshot capture of the deployed site, used in the list view.",
- )
-
- triggered_by_deployment: serializers.PrimaryKeyRelatedField = serializers.PrimaryKeyRelatedField( # ty: ignore[invalid-assignment]
- read_only=True,
- allow_null=True,
- help_text="The deployment this one was triggered from (e.g. for rollbacks/redeploys).",
- )
- trigger_kind = serializers.ChoiceField(
- choices=Deployment.TriggerKind.choices,
- help_text="What caused this deployment to start. One of: git, redeploy, rollback, seed.",
- )
-
- is_current = serializers.SerializerMethodField(
- help_text="Whether this deployment is the team's currently-serving production deployment.",
- )
- duration_seconds = serializers.SerializerMethodField(
- help_text="Build duration in seconds (finished_at - started_at). 0 while still running.",
- )
-
- class Meta:
- model = Deployment
- fields = [
- "id",
- "status",
- "started_at",
- "finished_at",
- "created_at",
- "commit_sha",
- "commit_message",
- "commit_author_name",
- "commit_author_email",
- "repo_url",
- "branch",
- "deployment_url",
- "preview_image_url",
- "triggered_by_deployment",
- "trigger_kind",
- "is_current",
- "duration_seconds",
- ]
- # SerializerMethodField is always read-only in DRF, so listing
- # is_current / duration_seconds here would be redundant.
- read_only_fields = ["id", "created_at", "triggered_by_deployment"]
-
- # TODO(deployments-v1): replace with a real `Subquery`/annotation that
- # marks the most recent `READY` deployment per team as current.
- @extend_schema_field(serializers.BooleanField())
- def get_is_current(self, obj: Deployment) -> bool:
- return False
-
- # TODO(deployments-v1): replace with `(finished_at - started_at).total_seconds()`
- # once the mock pipeline starts writing timestamps.
- @extend_schema_field(serializers.IntegerField())
- def get_duration_seconds(self, obj: Deployment) -> int:
- return 0
-
-
-class DeploymentActionResponseSerializer(serializers.Serializer):
- """Response shape for the redeploy/rollback/refresh-preview stubs."""
-
- detail = serializers.CharField(help_text="Human-readable explanation of the stub response.")
-
-
-@extend_schema(tags=["deployments"])
+ ],
+)
class DeploymentViewSet(
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
- viewsets.ReadOnlyModelViewSet,
+ viewsets.ModelViewSet,
):
- """Read-only viewset for the Deployments product.
+ """Full lifecycle viewset for Deployments.
- `list` and `retrieve` are wired against the model queryset. The
- `@action` stubs (`redeploy`, `rollback`, `refresh_preview`) intentionally
- return 501 — they exist so OpenAPI / MCP can discover the surface area
- while behavior lands in follow-up commits.
+ All deployments are scoped to a parent DeploymentProject via the URL
+ parent lookup `deployment_project_id`. The viewset enforces that
+ scoping in `safely_get_queryset` so a user can never see / mutate a
+ deployment that doesn't belong to the project in the URL.
"""
scope_object = "deployment"
- # The TeamAndOrgViewSetMixin appends class-level permission_classes to its
- # mandatory set (IsAuthenticated + APIScopePermission + AccessControlPermission
- # + TeamMemberAccessPermission), so we get the feature-flag gate on top of
- # all the standard checks without overriding get_permissions (which the mixin
- # protects via __init_subclass__).
- permission_classes = [DeploymentsAccessPermission]
+ authentication_classes = [
+ SessionAuthentication,
+ PersonalAPIKeyAuthentication,
+ OAuthAccessTokenAuthentication,
+ ]
+ permission_classes = [IsAuthenticated, APIScopePermission, DeploymentsAccessPermission]
serializer_class = DeploymentSerializer
- # Use `all_teams` (the unscoped sibling manager) at class-definition
- # time — `objects` is fail-closed and would raise without a team
- # context. `safely_get_queryset` re-applies the team filter explicitly.
+ # all_teams (unscoped sibling) at class-definition time — `objects` is
+ # fail-closed and would raise without a team context.
queryset = Deployment.all_teams.all()
+ filter_backends = [filters.SearchFilter, filters.OrderingFilter]
+ search_fields = ["commit_sha", "commit_message", "commit_author_name", "commit_author_email", "branch"]
+ ordering_fields = ["created_at", "started_at", "finished_at"]
+ ordering = ["-created_at"]
+
+ # Disable PUT/PATCH on individual deployments — they're driven by the
+ # state machine, not by direct field edits. POST creates a new row,
+ # the internal transitions endpoint moves it through states, and the
+ # action endpoints handle redeploy/rollback/cancel.
+ http_method_names = ["get", "post", "head", "options"]
+
+ @property
+ def deployment_project_id(self) -> str:
+ # DRF nested router prefixes parent kwargs with `parent_lookup_`.
+ return self.kwargs["parent_lookup_deployment_project_id"]
def _should_skip_parents_filter(self) -> bool:
# The router's default `parents_query_dict` filter assumes a `team` FK
@@ -211,44 +99,249 @@ class DeploymentViewSet(
return True
def safely_get_queryset(self, queryset: Any) -> Any:
- # TODO(deployments-v1): wire filters (status, author, search) once
- # `DeploymentsFilters` is implemented on the frontend.
- return queryset.filter(team_id=self.team_id)
+ # Annotate `is_current` via Exists so the serializer can read it
+ # in O(1) per row.
+ is_current = Exists(
+ DeploymentProject.all_teams.filter(
+ current_deployment=OuterRef("pk"),
+ team_id=self.team_id,
+ )
+ )
+ qs = queryset.filter(
+ team_id=self.team_id,
+ project_id=self.deployment_project_id,
+ ).annotate(is_current=is_current)
+
+ # The status / author filters are list-only — applying them on
+ # detail / action lookups would make `get_object()` 404 against
+ # rows the URL clearly references (e.g. redeploying a cancelled
+ # deployment, which is allowed). Matches the convention in
+ # `_filter_queryset_by_access_level` at posthog/api/routing.py.
+ if self.action != "list":
+ return qs
+
+ params = self.request.query_params if hasattr(self, "request") else {}
+
+ status_filter = params.get("status")
+ if status_filter:
+ statuses = [s.strip() for s in status_filter.split(",") if s.strip()]
+ qs = qs.filter(status__in=statuses)
+ else:
+ # Default: hide cancelled (mirrors Vercel's default filter).
+ qs = qs.exclude(status=Deployment.Status.CANCELLED)
+
+ author = params.get("author")
+ if author:
+ qs = qs.filter(commit_author_email__iexact=author.strip())
+
+ return qs
+
+ def _ensure_project_visible(self) -> None:
+ """403 if the parent project doesn't belong to this team / has been deleted."""
+ exists = (
+ DeploymentProject.all_teams.filter(
+ id=self.deployment_project_id,
+ team_id=self.team_id,
+ )
+ .exclude(deleted=True)
+ .exists()
+ )
+ if not exists:
+ raise NotFound("Deployment project not found.")
+
+ def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:
+ super().initial(request, *args, **kwargs)
+ # Enforced after auth/permission stacks run; `self.team_id` is set
+ # by TeamAndOrgViewSetMixin in initial().
+ self._ensure_project_visible()
+
+ # ---- Create -------------------------------------------------------
+
+ @extend_schema(
+ request=DeploymentCreateInputSerializer,
+ responses={
+ status.HTTP_201_CREATED: DeploymentSerializer,
+ status.HTTP_409_CONFLICT: OpenApiResponse(response=DeploymentConflictResponseSerializer),
+ status.HTTP_502_BAD_GATEWAY: OpenApiResponse(
+ description="Upstream (GitHub commit lookup or build workflow dispatch) failed."
+ ),
+ },
+ )
+ def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
+ body = DeploymentCreateInputSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+ try:
+ deployment = create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=self.deployment_project_id,
+ team_id=self.team_id,
+ triggered_by_user_id=request.user.id if request.user.is_authenticated else None,
+ trigger_kind=TriggerKind.MANUAL,
+ commit_sha=body.validated_data.get("commit_sha") or None,
+ branch=body.validated_data.get("branch") or None,
+ )
+ )
+ except create_deployment.ActiveDeploymentExists as exc:
+ return Response(
+ {
+ "detail": "A deployment is already in flight for this project.",
+ "active_deployment_id": exc.active_deployment_id,
+ },
+ status=status.HTTP_409_CONFLICT,
+ )
+ except GitHubError as exc:
+ # The github adapter's contract is to bubble GitHubError up here;
+ # we honour the docstring ("Translated to 502 by callers"). No DB
+ # row was created — the failure happened before the atomic block.
+ return Response({"detail": str(exc)}, status=status.HTTP_502_BAD_GATEWAY)
+ except create_deployment.WorkflowDispatchFailed as exc:
+ # Row has already been marked ERROR by the service; surface
+ # the orphan id so operators / clients can audit.
+ return Response(
+ {"detail": str(exc), "deployment_id": exc.deployment_id},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+ return Response(self.get_serializer(deployment).data, status=status.HTTP_201_CREATED)
+
+ # ---- Actions ------------------------------------------------------
@extend_schema(
request=None,
- responses={status.HTTP_501_NOT_IMPLEMENTED: OpenApiResponse(response=DeploymentActionResponseSerializer)},
+ responses={
+ status.HTTP_201_CREATED: DeploymentSerializer,
+ status.HTTP_409_CONFLICT: OpenApiResponse(response=DeploymentConflictResponseSerializer),
+ status.HTTP_502_BAD_GATEWAY: OpenApiResponse(
+ description="Upstream (GitHub commit lookup or build workflow dispatch) failed."
+ ),
+ },
)
@action(detail=True, methods=["post"])
def redeploy(self, request: Request, **kwargs: Any) -> Response:
- # TODO(deployments-v1): enqueue a redeploy by cloning this deployment's commit_sha.
- return Response(
- DeploymentActionResponseSerializer({"detail": "Redeploy is not implemented yet."}).data,
- status=status.HTTP_501_NOT_IMPLEMENTED,
- )
+ # get_object() runs safely_get_queryset (team + project filter)
+ # and check_object_permissions (RBAC). Without it, the URL's
+ # `deployment_project_id` is unverified — a deployment id from
+ # one project could be redeployed via another project's URL.
+ source = self.get_object()
+ try:
+ deployment = redeploy.execute(
+ deployment_id=str(source.pk),
+ team_id=self.team_id,
+ triggered_by_user_id=request.user.id if request.user.is_authenticated else None,
+ )
+ except create_deployment.ActiveDeploymentExists as exc:
+ return Response(
+ {
+ "detail": "A deployment is already in flight for this project.",
+ "active_deployment_id": exc.active_deployment_id,
+ },
+ status=status.HTTP_409_CONFLICT,
+ )
+ except GitHubError as exc:
+ return Response({"detail": str(exc)}, status=status.HTTP_502_BAD_GATEWAY)
+ except create_deployment.WorkflowDispatchFailed as exc:
+ return Response(
+ {"detail": str(exc), "deployment_id": exc.deployment_id},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+ return Response(self.get_serializer(deployment).data, status=status.HTTP_201_CREATED)
@extend_schema(
request=None,
- responses={status.HTTP_501_NOT_IMPLEMENTED: OpenApiResponse(response=DeploymentActionResponseSerializer)},
+ responses={
+ status.HTTP_201_CREATED: DeploymentSerializer,
+ status.HTTP_409_CONFLICT: OpenApiResponse(response=DeploymentConflictResponseSerializer),
+ status.HTTP_502_BAD_GATEWAY: OpenApiResponse(
+ description="Upstream (GitHub commit lookup or build workflow dispatch) failed."
+ ),
+ },
)
@action(detail=True, methods=["post"])
def rollback(self, request: Request, **kwargs: Any) -> Response:
- # TODO(deployments-v1): make this deployment the currently-serving one,
- # creating a new `rollback`-trigger deployment that points at it.
- return Response(
- DeploymentActionResponseSerializer({"detail": "Rollback is not implemented yet."}).data,
- status=status.HTTP_501_NOT_IMPLEMENTED,
- )
+ source = self.get_object()
+ try:
+ deployment = rollback.execute(
+ deployment_id=str(source.pk),
+ team_id=self.team_id,
+ triggered_by_user_id=request.user.id if request.user.is_authenticated else None,
+ )
+ except create_deployment.ActiveDeploymentExists as exc:
+ return Response(
+ {
+ "detail": "A deployment is already in flight for this project.",
+ "active_deployment_id": exc.active_deployment_id,
+ },
+ status=status.HTTP_409_CONFLICT,
+ )
+ except GitHubError as exc:
+ return Response({"detail": str(exc)}, status=status.HTTP_502_BAD_GATEWAY)
+ except create_deployment.WorkflowDispatchFailed as exc:
+ return Response(
+ {"detail": str(exc), "deployment_id": exc.deployment_id},
+ status=status.HTTP_502_BAD_GATEWAY,
+ )
+ return Response(self.get_serializer(deployment).data, status=status.HTTP_201_CREATED)
@extend_schema(
request=None,
- responses={status.HTTP_501_NOT_IMPLEMENTED: OpenApiResponse(response=DeploymentActionResponseSerializer)},
+ responses={status.HTTP_200_OK: DeploymentActionResponseSerializer},
)
- @action(detail=True, methods=["post"], url_path="refresh-preview")
+ @action(detail=True, methods=["post"])
+ def cancel(self, request: Request, **kwargs: Any) -> Response:
+ source = self.get_object()
+ try:
+ signalled = cancel.execute(deployment_id=str(source.pk), team_id=self.team_id)
+ except cancel.DeploymentNotCancellable as exc:
+ raise PermissionDenied(detail=str(exc))
+ detail = (
+ "Cancellation signal sent."
+ if signalled
+ else "No workflow to signal; deployment marked cancelled without a worker."
+ )
+ return Response({"detail": detail}, status=status.HTTP_200_OK)
+
+ @extend_schema(request=None, responses={status.HTTP_200_OK: DeploymentSerializer})
+ @action(detail=True, methods=["post"], url_path="refresh_preview")
def refresh_preview(self, request: Request, **kwargs: Any) -> Response:
- # TODO(deployments-v1): re-capture `preview_image_url` via the
- # microlink-backed `preview_capture` service.
+ source = self.get_object()
+ deployment = refresh_preview.execute(
+ deployment_id=str(source.pk),
+ team_id=self.team_id,
+ )
+ return Response(self.get_serializer(deployment).data, status=status.HTTP_200_OK)
+
+ @extend_schema(responses={status.HTTP_200_OK: DeploymentEventSerializer(many=True)})
+ @action(detail=True, methods=["get"])
+ def events(self, request: Request, **kwargs: Any) -> Response:
+ source = self.get_object()
+ qs = DeploymentEvent.all_teams.filter(
+ deployment_id=source.pk,
+ team_id=self.team_id,
+ ).order_by("-occurred_at")
+ page = self.paginate_queryset(qs)
+ if page is not None:
+ data = DeploymentEventSerializer(page, many=True).data
+ return self.get_paginated_response(data)
+ data = DeploymentEventSerializer(qs, many=True).data
+ return Response(data)
+
+ @extend_schema(responses={status.HTTP_200_OK: DeploymentActionResponseSerializer})
+ @action(detail=True, methods=["get"])
+ def logs(self, request: Request, **kwargs: Any) -> Response:
+ # Build logs land as `$log` PostHog events tagged with
+ # `properties.deployment_id`. The real Logs ingest endpoint is
+ # owned by another team; this stub returns an empty page until
+ # the HogQL bridge lands. Frontend stream can iterate against
+ # the empty shape today and we'll fill it in once the contract
+ # is final.
+ source = self.get_object()
+ # TODO(deployments-v1): swap stub for an `execute_hogql_query` call:
+ # SELECT timestamp, level, step, line, exit_code
+ # FROM events
+ # WHERE event = '$log'
+ # AND properties.deployment_id = {deployment_id}
+ # ORDER BY timestamp ASC
+ # LIMIT 1000
return Response(
- DeploymentActionResponseSerializer({"detail": "Refresh preview is not implemented yet."}).data,
- status=status.HTTP_501_NOT_IMPLEMENTED,
+ {"detail": f"Logs proxy not implemented yet (deployment_id={source.pk})."},
+ status=status.HTTP_200_OK,
)
diff --git a/products/deployments/backend/api/internal.py b/products/deployments/backend/api/internal.py
new file mode 100644
index 000000000000..97e491329c68
--- /dev/null
+++ b/products/deployments/backend/api/internal.py
@@ -0,0 +1,179 @@
+"""Service-to-service endpoints for the Deployments product.
+
+The Temporal build worker posts status transitions and lifecycle events
+to this viewset. Auth is `X-Internal-Api-Secret` against
+`settings.INTERNAL_API_SECRET`. Excluded from the OpenAPI schema —
+these endpoints are owned by infrastructure, not customer-facing.
+
+Routes (wired in `posthog/urls.py`, not via the DRF router — matching
+the precedent at `products/signals/backend/views.py:142-172`):
+
+- POST /api/internal/deployments/{deployment_id}/transitions/
+- POST /api/internal/deployments/{deployment_id}/events/
+
+The `transitions` handler is the ONLY mutator of `Deployment.status`
+(see services/update_status.py). The `events` handler is an append-only
+sink for `DeploymentEvent` rows the worker emits during build.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from uuid import UUID
+
+import structlog
+from drf_spectacular.utils import extend_schema
+from rest_framework import serializers, status, viewsets
+from rest_framework.exceptions import NotFound
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.auth import InternalAPIAuthentication
+
+from ..domain.status import InvalidStatusTransition, Status
+from ..domain.trigger import ErrorStep
+from ..models import Deployment, DeploymentEvent
+from ..serializers import DeploymentSerializer
+from ..services import update_status
+
+logger = structlog.get_logger(__name__)
+
+
+class InternalTransitionInputSerializer(serializers.Serializer):
+ """Body for POST /api/internal/deployments/{id}/transitions/.
+
+ The build worker posts this after each lifecycle activity completes
+ (dispatched → initializing → building → ready / error / cancelled).
+ """
+
+ status = serializers.ChoiceField(
+ choices=[s.value for s in Status],
+ help_text="Target deployment status. Validated against domain.status.VALID_TRANSITIONS.",
+ )
+ cloudflare_deployment_id = serializers.CharField(
+ max_length=128,
+ required=False,
+ allow_blank=True,
+ help_text="Cloudflare Pages deployment id assigned once publish succeeds.",
+ )
+ deployment_url = serializers.URLField(
+ max_length=1024,
+ required=False,
+ allow_blank=True,
+ help_text="Public URL the build was published to. Set on ready transitions.",
+ )
+ error_message = serializers.CharField(
+ required=False,
+ allow_blank=True,
+ help_text="Human-readable failure detail. Set on error transitions.",
+ )
+ error_step = serializers.ChoiceField(
+ choices=[s.value for s in ErrorStep],
+ required=False,
+ allow_blank=True,
+ help_text="Build step that failed (dispatch/clone/install/build/publish).",
+ )
+ started_at = serializers.DateTimeField(
+ required=False,
+ help_text="Optional started_at override (worker-time). If omitted, auto-stamped on INITIALIZING.",
+ )
+ finished_at = serializers.DateTimeField(
+ required=False,
+ help_text="Optional finished_at override (worker-time). If omitted, auto-stamped on terminal status.",
+ )
+
+
+class InternalEventInputSerializer(serializers.Serializer):
+ """Body for POST /api/internal/deployments/{id}/events/.
+
+ Append-only audit log entries emitted by the build worker as
+ activities run (start/finish of each step, preview-capture outcome,
+ etc.). Free-form payload by design — the timeline UI is the only
+ consumer and we want schema-flexibility.
+ """
+
+ event_type = serializers.CharField(
+ max_length=50,
+ help_text="Event category, e.g. status_changed, preview_captured, dispatched.",
+ )
+ payload = serializers.JSONField(
+ required=False,
+ help_text="Arbitrary structured payload. Shape varies by event_type.",
+ )
+
+
+class InternalDeploymentTransitionsViewSet(viewsets.ViewSet):
+ """Internal endpoints called by the Temporal build worker.
+
+ Authenticated via `X-Internal-Api-Secret` (constant-time compared
+ against `settings.INTERNAL_API_SECRET`). No team context required
+ on the URL — the deployment id resolves to a team via the row's
+ `team_id` field (ProductTeamModel; reads bypass `objects` via
+ `all_teams` because no team context is in scope).
+ """
+
+ authentication_classes = [InternalAPIAuthentication]
+
+ def _get_deployment(self, deployment_id: str | UUID) -> Deployment:
+ try:
+ return Deployment.all_teams.get(pk=deployment_id)
+ except Deployment.DoesNotExist as exc:
+ raise NotFound(f"Deployment {deployment_id} not found.") from exc
+
+ @extend_schema(exclude=True)
+ def transitions(self, request: Request, deployment_id: str, *args: Any, **kwargs: Any) -> Response:
+ body = InternalTransitionInputSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+
+ target = Status(body.validated_data["status"])
+ error_step_raw = body.validated_data.get("error_step")
+ error_step = ErrorStep(error_step_raw) if error_step_raw else None
+
+ # `update_status.execute` does its own `SELECT FOR UPDATE` on the
+ # row, so we catch the missing-row case here instead of pre-fetching
+ # (which would just be a wasted query and still race the worker that
+ # deletes the row between the two reads). `Deployment.DoesNotExist`
+ # otherwise bubbles up as a 500.
+ try:
+ deployment = update_status.execute(
+ update_status.UpdateStatusInput(
+ deployment_id=deployment_id,
+ status=target,
+ cloudflare_deployment_id=body.validated_data.get("cloudflare_deployment_id") or None,
+ deployment_url=body.validated_data.get("deployment_url") or None,
+ error_message=body.validated_data.get("error_message") or None,
+ error_step=error_step,
+ started_at=body.validated_data.get("started_at"),
+ finished_at=body.validated_data.get("finished_at"),
+ )
+ )
+ except Deployment.DoesNotExist as exc:
+ raise NotFound(f"Deployment {deployment_id} not found.") from exc
+ except InvalidStatusTransition as exc:
+ logger.warning(
+ "internal_deployments.invalid_transition",
+ deployment_id=str(deployment_id),
+ current=str(exc.current),
+ target=str(exc.target),
+ )
+ return Response({"detail": str(exc)}, status=status.HTTP_409_CONFLICT)
+
+ return Response(DeploymentSerializer(deployment).data, status=status.HTTP_200_OK)
+
+ @extend_schema(exclude=True)
+ def events(self, request: Request, deployment_id: str, *args: Any, **kwargs: Any) -> Response:
+ deployment = self._get_deployment(deployment_id)
+
+ body = InternalEventInputSerializer(data=request.data)
+ body.is_valid(raise_exception=True)
+
+ event = DeploymentEvent.objects.create(
+ deployment_id=deployment.pk,
+ team_id=deployment.team_id,
+ event_type=body.validated_data["event_type"],
+ payload=body.validated_data.get("payload") or {},
+ )
+ return Response(
+ {"id": str(event.id), "occurred_at": event.occurred_at.isoformat()},
+ status=status.HTTP_202_ACCEPTED,
+ )
diff --git a/products/deployments/backend/domain/__init__.py b/products/deployments/backend/domain/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/deployments/backend/domain/contracts.py b/products/deployments/backend/domain/contracts.py
new file mode 100644
index 000000000000..ad38a844953c
--- /dev/null
+++ b/products/deployments/backend/domain/contracts.py
@@ -0,0 +1,80 @@
+"""Frozen request / response contracts shared with the Build/Infra and GitHub streams.
+
+These are FROZEN at hour 1 of the hackathon. The Build/Infra stream consumes
+`BuildInput` as the Temporal workflow's input payload, and posts back to the
+internal API using the `TransitionRequest` / `EventRequest` shapes. The GitHub
+stream emits `CommitMetadata` after resolving a branch HEAD.
+
+Keep these as plain dataclasses with no Django imports — they cross process
+boundaries (the Temporal worker is its own pod) and must serialize cleanly
+through JSON.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+from uuid import UUID
+
+from .status import Status
+from .trigger import ErrorStep, TriggerKind
+
+
+@dataclass(frozen=True)
+class CommitMetadata:
+ """Returned by the GitHub adapter after resolving a branch HEAD or a SHA."""
+
+ sha: str
+ message: str
+ author_name: str
+ author_email: str
+ branch: str
+
+
+@dataclass(frozen=True)
+class BuildInput:
+ """Payload the API hands to the Temporal worker when starting a build.
+
+ The worker owns everything past this point — clone, install, build, publish.
+ `github_access_token` is the short-lived installation token the API resolved
+ from the project's `posthog.Integration` row (kind=github). It travels with
+ the payload (encrypted in transit by Temporal) so the worker can authenticate
+ against GitHub without a second roundtrip to the API. Tokens last ~1h —
+ sufficient for hackathon-scale builds; long-running builds would need the
+ worker to refresh through the integration framework instead.
+ """
+
+ deployment_id: UUID
+ project_id: UUID
+ team_id: int
+ repo_url: str
+ branch: str
+ commit_sha: str
+ github_access_token: str | None
+ build_command: str | None
+ output_dir: str
+ framework: str | None
+ inject_posthog_snippet: bool
+ cloudflare_project_name: str
+ trigger_kind: TriggerKind
+
+
+@dataclass(frozen=True)
+class TransitionRequest:
+ """Body of POST /api/internal/deployments/{id}/transitions/."""
+
+ status: Status
+ cloudflare_deployment_id: str | None = None
+ deployment_url: str | None = None
+ error_message: str | None = None
+ error_step: ErrorStep | None = None
+ started_at_iso: str | None = None
+ finished_at_iso: str | None = None
+
+
+@dataclass(frozen=True)
+class EventRequest:
+ """Body of POST /api/internal/deployments/{id}/events/."""
+
+ event_type: str
+ payload: dict[str, Any] = field(default_factory=dict)
diff --git a/products/deployments/backend/domain/status.py b/products/deployments/backend/domain/status.py
new file mode 100644
index 000000000000..17c89c5b3a3e
--- /dev/null
+++ b/products/deployments/backend/domain/status.py
@@ -0,0 +1,61 @@
+"""Deployment status state machine.
+
+Pure Python — no Django imports — so the state machine can be exercised
+in isolation. The model's TextChoices are mirrored here as a plain
+StrEnum so callers outside the Django model layer (Temporal activities,
+the build runner) can import this module without pulling in Django.
+"""
+
+from __future__ import annotations
+
+from enum import StrEnum
+
+
+class Status(StrEnum):
+ QUEUED = "queued"
+ INITIALIZING = "initializing"
+ BUILDING = "building"
+ READY = "ready"
+ ERROR = "error"
+ CANCELLED = "cancelled"
+
+
+NON_TERMINAL_STATUSES: frozenset[Status] = frozenset({Status.QUEUED, Status.INITIALIZING, Status.BUILDING})
+TERMINAL_STATUSES: frozenset[Status] = frozenset({Status.READY, Status.ERROR, Status.CANCELLED})
+
+
+VALID_TRANSITIONS: frozenset[tuple[Status, Status]] = frozenset(
+ {
+ (Status.QUEUED, Status.INITIALIZING),
+ (Status.QUEUED, Status.ERROR),
+ (Status.QUEUED, Status.CANCELLED),
+ (Status.INITIALIZING, Status.BUILDING),
+ (Status.INITIALIZING, Status.ERROR),
+ (Status.INITIALIZING, Status.CANCELLED),
+ (Status.BUILDING, Status.READY),
+ (Status.BUILDING, Status.ERROR),
+ (Status.BUILDING, Status.CANCELLED),
+ }
+)
+
+
+class InvalidStatusTransition(Exception):
+ def __init__(self, current: Status, target: Status) -> None:
+ self.current = current
+ self.target = target
+ super().__init__(f"Cannot transition from {current} to {target}")
+
+
+def assert_valid(current: Status, target: Status) -> None:
+ if (current, target) not in VALID_TRANSITIONS:
+ raise InvalidStatusTransition(current, target)
+
+
+def is_idempotent_noop(current: Status, target: Status) -> bool:
+ """Return True when the row is already in a terminal state matching the target.
+
+ A duplicate `ready` (or `error`/`cancelled`) callback from a racing build
+ activity is safe to no-op against. Used by the transitions handler to
+ distinguish "actually invalid transition" from "duplicate callback".
+ """
+ return current == target and current in TERMINAL_STATUSES
diff --git a/products/deployments/backend/domain/trigger.py b/products/deployments/backend/domain/trigger.py
new file mode 100644
index 000000000000..5f94dae063f1
--- /dev/null
+++ b/products/deployments/backend/domain/trigger.py
@@ -0,0 +1,25 @@
+"""Deployment trigger kinds — mirrored from the model's TextChoices.
+
+Pure Python so non-Django callers (Temporal activities, the build runner
+input contract) can import without dragging Django in.
+"""
+
+from __future__ import annotations
+
+from enum import StrEnum
+
+
+class TriggerKind(StrEnum):
+ MANUAL = "manual"
+ GIT = "git"
+ REDEPLOY = "redeploy"
+ ROLLBACK = "rollback"
+ SEED = "seed"
+
+
+class ErrorStep(StrEnum):
+ DISPATCH = "dispatch"
+ CLONE = "clone"
+ INSTALL = "install"
+ BUILD = "build"
+ PUBLISH = "publish"
diff --git a/products/deployments/backend/management/commands/seed_deployments.py b/products/deployments/backend/management/commands/seed_deployments.py
index 56110f92b79f..8bbc0a61d69c 100644
--- a/products/deployments/backend/management/commands/seed_deployments.py
+++ b/products/deployments/backend/management/commands/seed_deployments.py
@@ -1,17 +1,330 @@
-"""`manage.py seed_deployments` — placeholder for realistic dev seeds."""
+"""`manage.py seed_deployments` — generate realistic dev data.
+
+Populates the list scene with a `DeploymentProject` + ~25 mixed-status
+`Deployment` rows + 3-5 `DeploymentEvent` rows per deployment for the
+team passed via `--team-id`. Idempotent: deletes the slug's previous
+seed rows (anything with `trigger_kind=seed`) before re-creating them.
+
+Run locally with:
+
+ python manage.py seed_deployments --team-id <id>
+
+To create multiple seed projects (different repos):
+
+ python manage.py seed_deployments --team-id <id> --project-count 3
+"""
from __future__ import annotations
+import random
+from datetime import timedelta
from typing import Any
from django.core.management.base import BaseCommand
+from django.utils import timezone
+
+from posthog.models.scoping import team_scope
+from posthog.models.team import Team
+
+from ...domain.trigger import TriggerKind
+from ...models import Deployment, DeploymentEvent, DeploymentProject
+
+# Deterministic content sources for realistic-looking seed rows. The same
+# pool every run so the list view is recognisable across iterations.
+SEED_COMMIT_MESSAGES = [
+ "feat: add new pricing tile to marketing site",
+ "fix: rebroadcast on-boarding emails when SMTP recovers",
+ "chore: bump next.js to 14.2.5",
+ "feat: surface deploy logs in the new pipeline tab",
+ "fix: stop double-firing analytics event on hero CTA",
+ "refactor: extract <PreviewCard> from <DeploymentList>",
+ "feat: dark-mode polish on the docs landing page",
+ "fix: regression where /pricing showed stale data",
+ "chore: regenerate posthog-js bundle",
+ "feat: hide cancelled deploys behind the status filter",
+ "fix: typo on the changelog header",
+ "feat: support `astro` framework auto-detect",
+ "chore: upgrade tailwindcss to 3.4",
+ "fix: rollback button stuck disabled after redeploy",
+ "feat: render preview screenshot on the current-deployment card",
+]
+SEED_AUTHORS = [
+ ("Alice Chen", "[email protected]"),
+ ("Bob Patel", "[email protected]"),
+ ("Carmen Vasquez", "[email protected]"),
+ ("Dmitri Kuznetsov", "[email protected]"),
+ ("Erin O'Hara", "[email protected]"),
+]
+SEED_PROJECTS = [
+ ("Marketing site", "marketing-site", "https://github.com/example-org/marketing-site"),
+ ("Customer dashboard", "customer-dashboard", "https://github.com/example-org/customer-dashboard"),
+ ("Docs site", "docs-site", "https://github.com/example-org/docs-site"),
+]
+# Roughly Vercel-like distribution: mostly green, a handful red, the rest in-flight or cancelled.
+STATUS_DISTRIBUTION: list[tuple[Deployment.Status, int]] = [
+ (Deployment.Status.READY, 16),
+ (Deployment.Status.ERROR, 5),
+ (Deployment.Status.CANCELLED, 2),
+ (Deployment.Status.BUILDING, 1),
+ (Deployment.Status.QUEUED, 1),
+]
+ERROR_STEPS: list[Deployment.ErrorStep] = [
+ Deployment.ErrorStep.BUILD,
+ Deployment.ErrorStep.INSTALL,
+ Deployment.ErrorStep.PUBLISH,
+ Deployment.ErrorStep.CLONE,
+]
class Command(BaseCommand):
- help = "Seed mock deployments for local development. Not yet implemented."
+ help = "Seed mock deployments for local development."
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument(
+ "--team-id",
+ type=int,
+ required=True,
+ help="Team ID to attach the seed rows to.",
+ )
+ parser.add_argument(
+ "--project-count",
+ type=int,
+ default=1,
+ help=f"Number of DeploymentProject rows to create (default: 1, max: {len(SEED_PROJECTS)}).",
+ )
+ parser.add_argument(
+ "--deployments-per-project",
+ type=int,
+ default=25,
+ help="Approximate number of Deployment rows per project (default: 25).",
+ )
+ parser.add_argument(
+ "--seed",
+ type=int,
+ default=42,
+ help="Random seed for deterministic generation (default: 42).",
+ )
def handle(self, *args: Any, **options: Any) -> None:
- # TODO(deployments-v1): generate a realistic stream of deployments
- # (varied statuses, authors, branches) for the team passed via
- # --team-id, so the list scene has something to show locally.
- self.stdout.write("TODO: seed_deployments is not implemented yet.")
+ team_id: int = options["team_id"]
+ project_count: int = min(options["project_count"], len(SEED_PROJECTS))
+ deployments_per_project: int = options["deployments_per_project"]
+ rng = random.Random(options["seed"])
+
+ try:
+ team = Team.objects.get(id=team_id)
+ except Team.DoesNotExist:
+ self.stderr.write(self.style.ERROR(f"Team {team_id} not found."))
+ return
+
+ with team_scope(team.id):
+ for idx in range(project_count):
+ name, slug, repo_url = SEED_PROJECTS[idx]
+ project = self._upsert_project(team_id=team.id, name=name, slug=slug, repo_url=repo_url)
+ self._clear_seed_deployments(project)
+ deployments = self._create_deployments(
+ project=project,
+ count=deployments_per_project,
+ rng=rng,
+ )
+ self._link_current_deployment(project, deployments)
+ self.stdout.write(
+ self.style.SUCCESS(f"Seeded project '{name}' (slug={slug}) with {len(deployments)} deployments.")
+ )
+
+ def _upsert_project(self, *, team_id: int, name: str, slug: str, repo_url: str) -> DeploymentProject:
+ defaults = {
+ "name": name,
+ "repo_url": repo_url,
+ "default_branch": "main",
+ # build_command left null — the framework hint below is the
+ # canonical way to tell the worker how to build a Vite app.
+ "output_dir": "dist",
+ "framework": "vite",
+ "inject_posthog_snippet": False,
+ "cloudflare_project_name": f"{team_id}-{slug}",
+ "subdomain": f"{slug}.posthog-app.com",
+ "cloudflare_ready_at": timezone.now(),
+ }
+ project, _ = DeploymentProject.objects.update_or_create(team_id=team_id, slug=slug, defaults=defaults)
+ return project
+
+ def _clear_seed_deployments(self, project: DeploymentProject) -> None:
+ # Wipe ALL deployments on this seed-owned project. The seed mixes
+ # `SEED` and `REDEPLOY` trigger kinds (~15% of rows are REDEPLOY)
+ # so filtering on `trigger_kind=SEED` would leak REDEPLOY rows
+ # across runs. Cascade also wipes the project's DeploymentEvent
+ # rows.
+ Deployment.objects.filter(project=project).delete()
+
+ def _create_deployments(
+ self,
+ *,
+ project: DeploymentProject,
+ count: int,
+ rng: random.Random,
+ ) -> list[Deployment]:
+ plan = self._expand_status_distribution(count, rng)
+ now = timezone.now()
+ deployments: list[Deployment] = []
+
+ # Walk backwards in time so the most recent rows land at the top
+ # of the list when sorted by -created_at.
+ for offset, target_status in enumerate(plan):
+ created_at = now - timedelta(hours=offset * 3 + rng.randint(0, 90))
+ commit_msg = rng.choice(SEED_COMMIT_MESSAGES)
+ author_name, author_email = rng.choice(SEED_AUTHORS)
+ commit_sha = self._random_sha(rng)
+
+ started_at = None
+ finished_at = None
+ error_message = ""
+ error_step = ""
+ deployment_url = ""
+ cloudflare_deployment_id = ""
+
+ if target_status in (
+ Deployment.Status.READY,
+ Deployment.Status.ERROR,
+ Deployment.Status.CANCELLED,
+ Deployment.Status.BUILDING,
+ ):
+ started_at = created_at + timedelta(seconds=rng.randint(2, 8))
+ if target_status in (
+ Deployment.Status.READY,
+ Deployment.Status.ERROR,
+ Deployment.Status.CANCELLED,
+ ):
+ # Narrow `started_at`: every status that sets `finished_at` is also in
+ # the (READY|ERROR|CANCELLED|BUILDING) set above where `started_at` was set.
+ assert started_at is not None
+ finished_at = started_at + timedelta(seconds=rng.randint(45, 240))
+ if target_status == Deployment.Status.READY:
+ deployment_url = f"https://{commit_sha[:7]}.{project.subdomain}"
+ cloudflare_deployment_id = f"cf-{commit_sha[:12]}"
+ if target_status == Deployment.Status.ERROR:
+ error_step_choice = rng.choice(ERROR_STEPS)
+ error_step = error_step_choice.value
+ error_message = self._error_message_for(error_step_choice)
+
+ # Most deployments are user-triggered; sprinkle in a couple
+ # of redeploys against earlier rows to exercise the redeploy
+ # filter.
+ trigger_kind = TriggerKind.SEED.value
+ triggered_by_deployment = None
+ if offset > 0 and rng.random() < 0.15:
+ trigger_kind = TriggerKind.REDEPLOY.value
+ if deployments:
+ triggered_by_deployment = rng.choice(deployments)
+
+ deployment = Deployment.objects.create(
+ project=project,
+ team_id=project.team_id,
+ status=target_status.value,
+ started_at=started_at,
+ finished_at=finished_at,
+ commit_sha=commit_sha,
+ commit_message=commit_msg,
+ commit_author_name=author_name,
+ commit_author_email=author_email,
+ repo_url=project.repo_url,
+ branch=project.default_branch,
+ deployment_url=deployment_url,
+ error_message=error_message,
+ error_step=error_step,
+ cloudflare_deployment_id=cloudflare_deployment_id,
+ trigger_kind=trigger_kind,
+ triggered_by_deployment=triggered_by_deployment,
+ )
+ # auto_now_add overwrites created_at on insert, so fix it up
+ # with an explicit update so the list view is chronological.
+ Deployment.objects.filter(pk=deployment.pk).update(created_at=created_at)
+ deployment.created_at = created_at
+
+ self._create_events_for(deployment, rng)
+ deployments.append(deployment)
+
+ return deployments
+
+ @staticmethod
+ def _expand_status_distribution(count: int, rng: random.Random) -> list[Deployment.Status]:
+ # Scale the configured distribution to the requested row count,
+ # then shuffle so the timeline mixes statuses naturally.
+ total = sum(weight for _, weight in STATUS_DISTRIBUTION)
+ plan: list[Deployment.Status] = []
+ for s, weight in STATUS_DISTRIBUTION:
+ plan.extend([s] * max(1, round(weight * count / total)))
+ # Pad / trim to exactly `count`.
+ while len(plan) < count:
+ plan.append(Deployment.Status.READY)
+ plan = plan[:count]
+ rng.shuffle(plan)
+ return plan
+
+ @staticmethod
+ def _random_sha(rng: random.Random) -> str:
+ return "".join(rng.choice("0123456789abcdef") for _ in range(40))
+
+ @staticmethod
+ def _error_message_for(step: Deployment.ErrorStep) -> str:
+ match step:
+ case Deployment.ErrorStep.CLONE:
+ return "fatal: repository not found"
+ case Deployment.ErrorStep.INSTALL:
+ return "ERR_PNPM_FETCH_404 GET https://registry.npmjs.org/ghost-pkg: not_found"
+ case Deployment.ErrorStep.BUILD:
+ return "Error: Type 'string | undefined' is not assignable to type 'string'."
+ case Deployment.ErrorStep.PUBLISH:
+ return "wrangler: Error 1019: Request blocked by Cloudflare access policy"
+ case _:
+ return "Build failed."
+
+ def _create_events_for(self, deployment: Deployment, rng: random.Random) -> None:
+ events: list[tuple[str, dict[str, Any]]] = [
+ ("dispatched", {"trigger_kind": deployment.trigger_kind}),
+ (
+ "status_changed",
+ {"from": Deployment.Status.QUEUED.value, "to": Deployment.Status.INITIALIZING.value},
+ ),
+ ]
+ if deployment.status not in (Deployment.Status.QUEUED, Deployment.Status.CANCELLED):
+ events.append(
+ (
+ "status_changed",
+ {"from": Deployment.Status.INITIALIZING.value, "to": Deployment.Status.BUILDING.value},
+ )
+ )
+ if deployment.status == Deployment.Status.READY:
+ events.append(("status_changed", {"from": Deployment.Status.BUILDING.value, "to": "ready"}))
+ events.append(("preview_captured", {"url": deployment.deployment_url}))
+ elif deployment.status == Deployment.Status.ERROR:
+ events.append(
+ (
+ "status_changed",
+ {
+ "from": Deployment.Status.BUILDING.value,
+ "to": "error",
+ "error_step": deployment.error_step,
+ },
+ )
+ )
+ elif deployment.status == Deployment.Status.CANCELLED:
+ events.append(("status_changed", {"to": "cancelled", "by": "user"}))
+
+ for event_type, payload in events:
+ DeploymentEvent.objects.create(
+ deployment_id=deployment.pk,
+ team_id=deployment.team_id,
+ event_type=event_type,
+ payload=payload,
+ )
+
+ def _link_current_deployment(self, project: DeploymentProject, deployments: list[Deployment]) -> None:
+ # Pick the most recent READY row as the live deployment.
+ latest_ready = next(
+ (d for d in deployments if d.status == Deployment.Status.READY.value),
+ None,
+ )
+ if latest_ready is not None:
+ project.current_deployment = latest_ready
+ project.save(update_fields=["current_deployment", "updated_at"])
diff --git a/products/deployments/backend/migrations/0002_deploymentproject_deploymentevent_and_more.py b/products/deployments/backend/migrations/0002_deploymentproject_deploymentevent_and_more.py
new file mode 100644
index 000000000000..253915990833
--- /dev/null
+++ b/products/deployments/backend/migrations/0002_deploymentproject_deploymentevent_and_more.py
@@ -0,0 +1,249 @@
+"""Add DeploymentProject + DeploymentEvent + the remaining Deployment fields.
+
+This migration extends the scaffold's single-model `Deployment` to the
+three-model design from the deployments.md spec:
+
+- DeploymentProject — connected repo + Cloudflare target + build config.
+- DeploymentEvent — append-only audit log per deployment.
+- Deployment.project (FK), error_*, cloudflare_*, temporal_*, MANUAL trigger.
+- Partial unique constraint enforcing "one active deploy per project".
+
+Safety notes:
+- `Deployment.project` is added via `SeparateDatabaseAndState`: the DB
+ column lands as nullable so PG only takes a brief lock to add a
+ nullable column, while Django's state keeps it `NOT NULL` so model
+ code, serializers, and type checks treat it as required. The flag-
+ gated product has an empty `deployment` table at rollout time, and
+ every code path that creates a row (see `services/create_deployment`,
+ `management/commands/seed_deployments`) sets `project`, so no row will
+ observe the relaxed DB nullability. A follow-up migration can promote
+ the column to `NOT NULL` once we have telemetry confirming all rows
+ carry a project.
+- The index on `deployment(project, -created_at)` is added in `0003`
+ with `AddIndexConcurrently`. PostHog policy (see
+ `posthog/management/migration_analysis/policies.py`) blocks
+ CONCURRENTLY operations from being mixed with regular DDL — splitting
+ the concurrent index out lets this migration keep `atomic = True`
+ (and its rollback safety) while the index build runs without a
+ transaction.
+- The partial unique constraint validates against zero rows, so it's
+ instant; left in this migration because it would be a no-op once the
+ product is rolled out.
+- `current_deployment` on `DeploymentProject` is a circular FK to
+ `Deployment`; the string-reference + null=True lets Django resolve
+ both directions within this single migration without a separate
+ `AddField` operation.
+"""
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("deployments", "0001_initial"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="DeploymentProject",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("team_id", models.BigIntegerField(db_index=True)),
+ ("created_by_id", models.BigIntegerField(blank=True, null=True)),
+ ("name", models.CharField(max_length=200)),
+ ("slug", models.SlugField(max_length=80)),
+ ("repo_url", models.URLField(max_length=1024)),
+ ("default_branch", models.CharField(default="main", max_length=255)),
+ ("github_integration_id", models.BigIntegerField(blank=True, null=True)),
+ ("build_command", models.TextField(blank=True, default=None, null=True)),
+ ("output_dir", models.CharField(default="dist", max_length=255)),
+ ("framework", models.CharField(blank=True, max_length=50, null=True)),
+ ("inject_posthog_snippet", models.BooleanField(default=False)),
+ ("cloudflare_project_name", models.CharField(blank=True, default="", max_length=255)),
+ ("subdomain", models.CharField(blank=True, default="", max_length=255)),
+ ("cloudflare_ready_at", models.DateTimeField(blank=True, null=True)),
+ # current_deployment is set after Deployment.project FK is added below.
+ # String-ref + null=True avoids the circular-FK chicken-and-egg.
+ (
+ "current_deployment",
+ models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="+",
+ to="deployments.deployment",
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True, db_index=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ("deleted", models.BooleanField(blank=True, default=False, null=True)),
+ ("deleted_at", models.DateTimeField(blank=True, null=True)),
+ ],
+ options={
+ "abstract": False,
+ },
+ ),
+ migrations.CreateModel(
+ name="DeploymentEvent",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("team_id", models.BigIntegerField(db_index=True)),
+ (
+ "deployment",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="events",
+ to="deployments.deployment",
+ ),
+ ),
+ ("event_type", models.CharField(max_length=50)),
+ ("payload", models.JSONField(default=dict)),
+ ("occurred_at", models.DateTimeField(auto_now_add=True)),
+ ],
+ options={
+ "ordering": ("-occurred_at",),
+ },
+ ),
+ # Deployment.project — the DB column lands nullable so PG only takes
+ # a brief lock to ADD COLUMN (no full table rewrite), while Django's
+ # state keeps the FK NOT NULL so model/serializer/type code treats it
+ # as required. The `deployment` table is empty at rollout, every
+ # row-creation path (services/create_deployment, seed command) sets
+ # `project`, and a follow-up migration can promote the column to
+ # `NOT NULL` once we're sure all rows carry a project.
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AddField(
+ model_name="deployment",
+ name="project",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="deployments",
+ to="deployments.deploymentproject",
+ ),
+ ),
+ ],
+ database_operations=[
+ migrations.AddField(
+ model_name="deployment",
+ name="project",
+ field=models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="deployments",
+ to="deployments.deploymentproject",
+ ),
+ ),
+ ],
+ ),
+ migrations.AddField(
+ model_name="deployment",
+ name="triggered_by_user_id",
+ field=models.BigIntegerField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="deployment",
+ name="error_message",
+ field=models.TextField(blank=True, default=""),
+ ),
+ migrations.AddField(
+ model_name="deployment",
+ name="error_step",
+ field=models.CharField(
+ blank=True,
+ choices=[
+ ("dispatch", "Dispatch"),
+ ("clone", "Clone"),
+ ("install", "Install"),
+ ("build", "Build"),
+ ("publish", "Publish"),
+ ],
+ default="",
+ max_length=20,
+ ),
+ ),
+ migrations.AddField(
+ model_name="deployment",
+ name="cloudflare_deployment_id",
+ field=models.CharField(blank=True, default="", max_length=128),
+ ),
+ migrations.AddField(
+ model_name="deployment",
+ name="temporal_workflow_id",
+ field=models.CharField(blank=True, default="", max_length=255),
+ ),
+ migrations.AddField(
+ model_name="deployment",
+ name="temporal_run_id",
+ field=models.CharField(blank=True, default="", max_length=255),
+ ),
+ # Expand trigger_kind choices to include MANUAL and bump default
+ # to MANUAL (most common path in v1 — user-clicked Deploy).
+ migrations.AlterField(
+ model_name="deployment",
+ name="trigger_kind",
+ field=models.CharField(
+ choices=[
+ ("manual", "Manual"),
+ ("git", "Git"),
+ ("redeploy", "Redeploy"),
+ ("rollback", "Rollback"),
+ ("seed", "Seed"),
+ ],
+ default="manual",
+ max_length=16,
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="deploymentproject",
+ index=models.Index(fields=["team_id", "-created_at"], name="deployments_team_id_e8b09b_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="deploymentevent",
+ index=models.Index(fields=["deployment", "occurred_at"], name="deployments_deploym_3a8e69_idx"),
+ ),
+ # The deployment(project, -created_at) index is built in 0003 with
+ # AddIndexConcurrently — see the file header for why it lives in
+ # its own migration.
+ # Slug uniqueness scoped to live rows. The OR-isnull clause covers
+ # the bool-with-null=True pattern used by DeletedMetaFields, where
+ # `deleted` defaults to False but is nullable.
+ migrations.AddConstraint(
+ model_name="deploymentproject",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("deleted", False)) | models.Q(("deleted__isnull", True)),
+ fields=("team_id", "slug"),
+ name="unique_deploymentproject_slug_per_team",
+ ),
+ ),
+ # At-most-one non-terminal deploy per project. The 409 the API returns
+ # is the friendly surface over the resulting IntegrityError; no
+ # check-then-insert (which would race).
+ migrations.AddConstraint(
+ model_name="deployment",
+ constraint=models.UniqueConstraint(
+ condition=models.Q(("status__in", ("queued", "initializing", "building"))),
+ fields=("project",),
+ name="one_active_deployment_per_project",
+ ),
+ ),
+ ]
diff --git a/products/deployments/backend/migrations/0003_deployment_project_idx_concurrent.py b/products/deployments/backend/migrations/0003_deployment_project_idx_concurrent.py
new file mode 100644
index 000000000000..5223033236f1
--- /dev/null
+++ b/products/deployments/backend/migrations/0003_deployment_project_idx_concurrent.py
@@ -0,0 +1,32 @@
+"""Add the deployment(project, -created_at) index without locking.
+
+`AddIndex` on the existing `deployment` table would acquire a SHARE lock
+for the duration of the index build. `AddIndexConcurrently` (Postgres
+`CREATE INDEX CONCURRENTLY`) builds the index in the background without
+blocking writes — the trade-off is that the migration runs outside a
+transaction, so `atomic = False` is required and a failed run leaves an
+INVALID index that must be DROPped manually.
+
+Split from `0002` so the schema-creating migration can keep its
+`atomic = True` rollback safety. PostHog policy explicitly flags mixing
+CONCURRENTLY operations with regular DDL in one migration (see
+`posthog/management/migration_analysis/policies.py`).
+"""
+
+from django.contrib.postgres.operations import AddIndexConcurrently
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("deployments", "0002_deploymentproject_deploymentevent_and_more"),
+ ]
+
+ operations = [
+ AddIndexConcurrently(
+ model_name="deployment",
+ index=models.Index(fields=("project", "-created_at"), name="deploy_project_created_idx"),
+ ),
+ ]
diff --git a/products/deployments/backend/migrations/0004_alter_deploymentevent_managers_and_more.py b/products/deployments/backend/migrations/0004_alter_deploymentevent_managers_and_more.py
new file mode 100644
index 000000000000..e4bcd56734bb
--- /dev/null
+++ b/products/deployments/backend/migrations/0004_alter_deploymentevent_managers_and_more.py
@@ -0,0 +1,44 @@
+# Reconcile migration state with the current Django version.
+#
+# `0002` was generated under Django 4.2 and predates two changes that
+# Django 5.2's autodetector now picks up against the current model
+# definitions in `models.py`:
+#
+# 1. `ProductTeamModel` exposes a sibling `all_teams = models.Manager()`
+# alongside `objects`. `0002`'s `CreateModel` for `DeploymentEvent`
+# didn't record it, so we add the manager here via
+# `AlterModelManagers`. State-only — no SQL emitted. This mirrors
+# `products/visual_review/backend/migrations/0011_alter_artifact_managers_and_more.py`.
+#
+# 2. The auto-name hash for unnamed `Meta.indexes` entries changed
+# between Django 4.2 and 5.2. Renaming via Postgres `ALTER INDEX
+# ... RENAME TO ...` is a metadata-only operation (no table lock,
+# no rewrite), so this is safe to run inline.
+
+import django.db.models.manager
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("deployments", "0003_deployment_project_idx_concurrent"),
+ ]
+
+ operations = [
+ migrations.AlterModelManagers(
+ name="deploymentevent",
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ migrations.RenameIndex(
+ model_name="deploymentevent",
+ new_name="deployments_deploym_dd5504_idx",
+ old_name="deployments_deploym_3a8e69_idx",
+ ),
+ migrations.RenameIndex(
+ model_name="deploymentproject",
+ new_name="deployments_team_id_849b3e_idx",
+ old_name="deployments_team_id_e8b09b_idx",
+ ),
+ ]
diff --git a/products/deployments/backend/migrations/max_migration.txt b/products/deployments/backend/migrations/max_migration.txt
index cbab66dde92a..a5b64b0a0da5 100644
--- a/products/deployments/backend/migrations/max_migration.txt
+++ b/products/deployments/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0001_initial
+0004_alter_deploymentevent_managers_and_more
diff --git a/products/deployments/backend/models.py b/products/deployments/backend/models.py
index 888300a3e001..ca15a1bfbdad 100644
--- a/products/deployments/backend/models.py
+++ b/products/deployments/backend/models.py
@@ -1,8 +1,15 @@
"""Django models for the Deployments product.
-Scaffold only — fields and choices land here so other commits on
-`feat/deployments` can build behavior on top. Business logic, signals,
-and activity describers will be filled in later.
+Three models:
+- DeploymentProject — a connected repo + Cloudflare Pages target + build config.
+- Deployment — one build attempt against a project at a specific commit.
+- DeploymentEvent — append-only audit log per deployment (drives the timeline UI).
+
+All inherit ProductTeamModel: team_id is a plain BigIntegerField (no FK to Team)
+and queries are fail-closed via TeamScopedManager. DeploymentProject and
+Deployment also inherit ModelActivityMixin so create/update/delete are surfaced
+through the standard activity log. DeploymentEvent is itself the audit log —
+no second log on top.
"""
from __future__ import annotations
@@ -11,15 +18,84 @@ from django.db import models
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.scoping.product_mixin import ProductTeamModel
-from posthog.models.utils import uuid7
+from posthog.models.utils import DeletedMetaFields, uuid7
+
+
+class DeploymentProject(ModelActivityMixin, ProductTeamModel, DeletedMetaFields):
+ """A connected repo + its Cloudflare Pages hosting target.
+
+ One DeploymentProject per Cloudflare Pages project. A team may own
+ multiple projects (different repos). The `current_deployment` pointer
+ is the single source of truth for "what's serving now"; it is set
+ explicitly on a successful build or rollback rather than derived as
+ "most recent READY", because Cloudflare's rollback API can promote a
+ non-latest deployment to current.
+ """
+
+ id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
+ created_by_id = models.BigIntegerField(null=True, blank=True)
+
+ name = models.CharField(max_length=200)
+ slug = models.SlugField(max_length=80)
+
+ # Source
+ repo_url = models.URLField(max_length=1024)
+ default_branch = models.CharField(max_length=255, default="main")
+ # Pointer to the team's `posthog.Integration` row for the GitHub App that
+ # owns access to this repo. We resolve to a short-lived access token at
+ # deploy-time via `GitHubIntegration(integration).integration.sensitive_config`.
+ # BigIntegerField (no FK) keeps the ProductTeamModel cross-app boundary clean,
+ # matching the pattern used for `created_by_id`.
+ github_integration_id = models.BigIntegerField(null=True, blank=True)
+
+ # Build config
+ # Null = build worker infers the command from `framework` (or auto-detects
+ # if framework is also null). Users can pin an explicit command via PATCH.
+ build_command = models.TextField(null=True, blank=True, default=None)
+ output_dir = models.CharField(max_length=255, default="dist")
+ framework = models.CharField(max_length=50, null=True, blank=True)
+ inject_posthog_snippet = models.BooleanField(default=False)
+
+ # Hosting (Cloudflare Pages)
+ cloudflare_project_name = models.CharField(max_length=255, blank=True, default="")
+ subdomain = models.CharField(max_length=255, blank=True, default="")
+ cloudflare_ready_at = models.DateTimeField(null=True, blank=True)
+
+ # String-ref + null avoids the circular-FK chicken-and-egg with Deployment
+ # in the initial migration. Set on ready-transition or rollback.
+ current_deployment = models.ForeignKey(
+ "deployments.Deployment",
+ null=True,
+ blank=True,
+ on_delete=models.SET_NULL,
+ related_name="+",
+ )
+
+ created_at = models.DateTimeField(auto_now_add=True, db_index=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ class Meta:
+ constraints = [
+ # Slug is the user-facing subdomain handle; uniqueness scoped to live rows
+ # (matches the soft-delete pattern at posthog/models/llm_prompt.py:38-48).
+ models.UniqueConstraint(
+ fields=["team_id", "slug"],
+ condition=models.Q(deleted=False) | models.Q(deleted__isnull=True),
+ name="unique_deploymentproject_slug_per_team",
+ ),
+ ]
+ indexes = [models.Index(fields=["team_id", "-created_at"])]
+
+ def __str__(self) -> str:
+ return f"DeploymentProject {self.slug} ({self.id})"
class Deployment(ModelActivityMixin, ProductTeamModel):
"""A single deployment of a project's site.
- `team_id` is inherited from `ProductTeamModel` as a plain
- `BigIntegerField` — no cross-DB FK to `Team`. All reads go through
- the fail-closed `TeamScopedManager`.
+ `team_id` is inherited from `ProductTeamModel` as a plain `BigIntegerField`
+ — no cross-DB FK to `Team`. All reads go through the fail-closed
+ `TeamScopedManager`.
"""
class Status(models.TextChoices):
@@ -30,14 +106,33 @@ class Deployment(ModelActivityMixin, ProductTeamModel):
ERROR = "error", "Error"
CANCELLED = "cancelled", "Cancelled"
+ NON_TERMINAL_STATUSES: tuple[str, ...] = (Status.QUEUED, Status.INITIALIZING, Status.BUILDING)
+ TERMINAL_STATUSES: tuple[str, ...] = (Status.READY, Status.ERROR, Status.CANCELLED)
+
class TriggerKind(models.TextChoices):
+ MANUAL = "manual", "Manual"
GIT = "git", "Git"
REDEPLOY = "redeploy", "Redeploy"
ROLLBACK = "rollback", "Rollback"
SEED = "seed", "Seed"
+ class ErrorStep(models.TextChoices):
+ DISPATCH = "dispatch", "Dispatch"
+ CLONE = "clone", "Clone"
+ INSTALL = "install", "Install"
+ BUILD = "build", "Build"
+ PUBLISH = "publish", "Publish"
+
id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
+ # Parent project. CASCADE: hard-deleting a project wipes its deployments.
+ # In practice projects soft-delete (deleted=True), so this rarely fires.
+ project = models.ForeignKey(
+ DeploymentProject,
+ on_delete=models.CASCADE,
+ related_name="deployments",
+ )
+
status = models.CharField(
max_length=32,
choices=Status.choices,
@@ -48,17 +143,18 @@ class Deployment(ModelActivityMixin, ProductTeamModel):
finished_at = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
+ # Source — captured at deploy time so changing project.default_branch
+ # doesn't rewrite history.
commit_sha = models.CharField(max_length=64, blank=True, default="")
commit_message = models.TextField(blank=True, default="")
commit_author_name = models.CharField(max_length=255, blank=True, default="")
commit_author_email = models.CharField(max_length=255, blank=True, default="")
-
repo_url = models.URLField(max_length=1024, blank=True, default="")
branch = models.CharField(max_length=255, blank=True, default="")
- deployment_url = models.URLField(max_length=1024, blank=True, default="")
- preview_image_url = models.URLField(max_length=1024, blank=True, default="")
-
+ # Who clicked deploy. BigIntegerField (not FK) because Team / User live
+ # in the main DB and ProductTeamModel doesn't carry FK constraints across.
+ triggered_by_user_id = models.BigIntegerField(null=True, blank=True)
triggered_by_deployment = models.ForeignKey(
"self",
null=True,
@@ -69,14 +165,69 @@ class Deployment(ModelActivityMixin, ProductTeamModel):
trigger_kind = models.CharField(
max_length=16,
choices=TriggerKind.choices,
- default=TriggerKind.GIT,
+ default=TriggerKind.MANUAL,
)
+ # Result
+ deployment_url = models.URLField(max_length=1024, blank=True, default="")
+ preview_image_url = models.URLField(max_length=1024, blank=True, default="")
+
+ # Failure context
+ error_message = models.TextField(blank=True, default="")
+ error_step = models.CharField(
+ max_length=20,
+ choices=ErrorStep.choices,
+ blank=True,
+ default="",
+ )
+
+ # External references owned by other streams. Opaque to us; we just
+ # store and forward.
+ cloudflare_deployment_id = models.CharField(max_length=128, blank=True, default="")
+ temporal_workflow_id = models.CharField(max_length=255, blank=True, default="")
+ temporal_run_id = models.CharField(max_length=255, blank=True, default="")
+
class Meta:
ordering = ("-created_at",)
indexes = [
models.Index(fields=("team_id", "-created_at"), name="deploy_team_created_idx"),
+ models.Index(fields=("project", "-created_at"), name="deploy_project_created_idx"),
+ ]
+ constraints = [
+ # Enforces "at most one non-terminal deploy per project" at the DB layer.
+ # The 409 the API returns is a friendly surface over the resulting
+ # IntegrityError, not a separate check-then-insert (which would race).
+ models.UniqueConstraint(
+ fields=["project"],
+ condition=models.Q(status__in=("queued", "initializing", "building")),
+ name="one_active_deployment_per_project",
+ ),
]
def __str__(self) -> str:
return f"Deployment {self.id} ({self.status})"
+
+
+class DeploymentEvent(ProductTeamModel):
+ """Append-only event log per deployment. Drives timeline, audit, debugging.
+
+ Never updated. Every status transition and lifecycle event is a new row.
+ Intentionally NOT a ModelActivityMixin subclass — this IS the audit log.
+ """
+
+ id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
+ deployment = models.ForeignKey(
+ Deployment,
+ on_delete=models.CASCADE,
+ related_name="events",
+ )
+ event_type = models.CharField(max_length=50)
+ payload = models.JSONField(default=dict)
+ occurred_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ indexes = [models.Index(fields=["deployment", "occurred_at"])]
+ ordering = ("-occurred_at",)
+
+ def __str__(self) -> str:
+ return f"DeploymentEvent {self.event_type} on {self.deployment_id}"
diff --git a/products/deployments/backend/serializers/__init__.py b/products/deployments/backend/serializers/__init__.py
new file mode 100644
index 000000000000..57520ac769bc
--- /dev/null
+++ b/products/deployments/backend/serializers/__init__.py
@@ -0,0 +1,9 @@
+from .deployment import DeploymentSerializer
+from .event import DeploymentEventSerializer
+from .project import DeploymentProjectSerializer
+
+__all__ = [
+ "DeploymentEventSerializer",
+ "DeploymentProjectSerializer",
+ "DeploymentSerializer",
+]
diff --git a/products/deployments/backend/serializers/deployment.py b/products/deployments/backend/serializers/deployment.py
new file mode 100644
index 000000000000..d062cf7d192a
--- /dev/null
+++ b/products/deployments/backend/serializers/deployment.py
@@ -0,0 +1,220 @@
+"""Serializer for Deployment.
+
+`is_current` reads an annotated `Exists` subquery — see DeploymentViewSet
+for the queryset annotation. `duration_seconds` is a SerializerMethodField
+because it depends on two fields that may be null mid-build.
+"""
+
+from __future__ import annotations
+
+from drf_spectacular.utils import extend_schema_field
+from rest_framework import serializers
+
+from ..models import Deployment, DeploymentProject
+
+
+class DeploymentSerializer(serializers.ModelSerializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique identifier for the deployment.")
+ project: serializers.PrimaryKeyRelatedField = serializers.PrimaryKeyRelatedField( # ty: ignore[invalid-assignment]
+ read_only=True,
+ help_text="The deployment project this deployment belongs to.",
+ )
+
+ status = serializers.ChoiceField(
+ choices=Deployment.Status.choices,
+ help_text=("Current pipeline stage. Valid values: queued, initializing, building, ready, error, cancelled."),
+ )
+ started_at = serializers.DateTimeField(
+ allow_null=True,
+ required=False,
+ help_text="When the pipeline started building. Null while still queued.",
+ )
+ finished_at = serializers.DateTimeField(
+ allow_null=True,
+ required=False,
+ help_text="When the pipeline finished (regardless of outcome). Null while still running.",
+ )
+ created_at = serializers.DateTimeField(
+ read_only=True,
+ help_text="When the deployment row was created (~ queued_at).",
+ )
+
+ commit_sha = serializers.CharField(
+ allow_blank=True,
+ required=False,
+ max_length=64,
+ help_text="Git commit SHA the deployment was built from.",
+ )
+ commit_message = serializers.CharField(
+ allow_blank=True,
+ required=False,
+ help_text="Commit message associated with the commit SHA.",
+ )
+ commit_author_name = serializers.CharField(
+ allow_blank=True,
+ required=False,
+ max_length=255,
+ help_text="Display name of the commit author.",
+ )
+ commit_author_email = serializers.CharField(
+ allow_blank=True,
+ required=False,
+ max_length=255,
+ help_text="Email address of the commit author. Used by the Author filter on the list page.",
+ )
+
+ repo_url = serializers.URLField(
+ allow_blank=True,
+ required=False,
+ max_length=1024,
+ help_text="HTTPS URL of the source repository. Captured at deploy time.",
+ )
+ branch = serializers.CharField(
+ allow_blank=True,
+ required=False,
+ max_length=255,
+ help_text="Source branch the deployment was built from.",
+ )
+
+ deployment_url = serializers.URLField(
+ allow_blank=True,
+ required=False,
+ max_length=1024,
+ help_text="Public URL serving the built site once ready.",
+ )
+ preview_image_url = serializers.URLField(
+ allow_blank=True,
+ required=False,
+ max_length=1024,
+ help_text="URL of the captured site screenshot, used in the list/card view.",
+ )
+
+ triggered_by_deployment: serializers.PrimaryKeyRelatedField = serializers.PrimaryKeyRelatedField( # ty: ignore[invalid-assignment]
+ read_only=True,
+ allow_null=True,
+ help_text="The deployment this one was triggered from (for rollbacks and redeploys).",
+ )
+ triggered_by_user_id = serializers.IntegerField(
+ read_only=True,
+ allow_null=True,
+ help_text="Posthog user id of the user who clicked Deploy/Redeploy/Rollback. Null for git-triggered or seed rows.",
+ )
+ trigger_kind = serializers.ChoiceField(
+ choices=Deployment.TriggerKind.choices,
+ help_text="What caused this deployment to start: manual | git | redeploy | rollback | seed.",
+ )
+
+ error_message = serializers.CharField(
+ read_only=True,
+ help_text="Failure detail set when status=error. Empty for successful or in-flight deployments.",
+ )
+ error_step = serializers.ChoiceField(
+ choices=Deployment.ErrorStep.choices,
+ required=False,
+ allow_blank=True,
+ help_text="Build step that failed: dispatch | clone | install | build | publish. Empty when status != error.",
+ )
+
+ cloudflare_deployment_id = serializers.CharField(
+ read_only=True,
+ help_text="Cloudflare Pages deployment id, set once the publish step succeeds.",
+ )
+ temporal_workflow_id = serializers.CharField(
+ read_only=True,
+ help_text="Temporal workflow id for this build. Used for cancellation signalling.",
+ )
+
+ is_current = serializers.SerializerMethodField(
+ help_text="True if this deployment is currently serving production traffic for its project.",
+ )
+ duration_seconds = serializers.SerializerMethodField(
+ help_text="Build duration in seconds (finished_at - started_at). 0 while still running.",
+ )
+
+ class Meta:
+ model = Deployment
+ fields = [
+ "id",
+ "project",
+ "status",
+ "started_at",
+ "finished_at",
+ "created_at",
+ "commit_sha",
+ "commit_message",
+ "commit_author_name",
+ "commit_author_email",
+ "repo_url",
+ "branch",
+ "deployment_url",
+ "preview_image_url",
+ "triggered_by_deployment",
+ "triggered_by_user_id",
+ "trigger_kind",
+ "error_message",
+ "error_step",
+ "cloudflare_deployment_id",
+ "temporal_workflow_id",
+ "is_current",
+ "duration_seconds",
+ ]
+ # SerializerMethodField is implicitly read-only.
+ read_only_fields = [
+ "id",
+ "project",
+ "created_at",
+ "triggered_by_deployment",
+ "triggered_by_user_id",
+ "error_message",
+ "cloudflare_deployment_id",
+ "temporal_workflow_id",
+ ]
+
+ @extend_schema_field(serializers.BooleanField())
+ def get_is_current(self, obj: Deployment) -> bool:
+ # The list viewset annotates rows with `is_current` via Exists()
+ # for O(1) per-row reads. When the serializer is used outside that
+ # path (refresh_preview, detail actions, admin), fall back to a
+ # direct DB lookup so the field stays accurate.
+ annotated = getattr(obj, "is_current", None)
+ if annotated is not None:
+ return bool(annotated)
+ return DeploymentProject.all_teams.filter(current_deployment_id=obj.pk).exists()
+
+ @extend_schema_field(serializers.IntegerField())
+ def get_duration_seconds(self, obj: Deployment) -> int:
+ if obj.started_at is None or obj.finished_at is None:
+ return 0
+ return int((obj.finished_at - obj.started_at).total_seconds())
+
+
+class DeploymentCreateInputSerializer(serializers.Serializer):
+ """Body of POST /api/projects/{}/deployment_projects/{}/deployments/."""
+
+ commit_sha = serializers.CharField(
+ max_length=64,
+ required=False,
+ allow_blank=True,
+ help_text="Optional commit SHA. If omitted, the build worker resolves HEAD of `branch` (or the project's default_branch).",
+ )
+ branch = serializers.CharField(
+ max_length=255,
+ required=False,
+ allow_blank=True,
+ help_text="Optional branch override. If omitted, uses the project's `default_branch`.",
+ )
+
+
+class DeploymentActionResponseSerializer(serializers.Serializer):
+ """Response shape for one-off action endpoints (cancel, refresh_preview)."""
+
+ detail = serializers.CharField(help_text="Short human-readable confirmation message.")
+
+
+class DeploymentConflictResponseSerializer(serializers.Serializer):
+ """Response shape returned with HTTP 409 when an active deploy exists."""
+
+ detail = serializers.CharField(help_text="Reason for the conflict.")
+ active_deployment_id = serializers.UUIDField(
+ help_text="The deployment currently in-flight for the project. Frontend can poll this id.",
+ )
diff --git a/products/deployments/backend/serializers/event.py b/products/deployments/backend/serializers/event.py
new file mode 100644
index 000000000000..c21c8ca2250a
--- /dev/null
+++ b/products/deployments/backend/serializers/event.py
@@ -0,0 +1,31 @@
+"""Serializer for DeploymentEvent."""
+
+from __future__ import annotations
+
+from rest_framework import serializers
+
+from ..models import DeploymentEvent
+
+
+class DeploymentEventSerializer(serializers.ModelSerializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique identifier for the event row.")
+ deployment: serializers.PrimaryKeyRelatedField = serializers.PrimaryKeyRelatedField( # ty: ignore[invalid-assignment]
+ read_only=True,
+ help_text="The deployment this event belongs to.",
+ )
+ event_type = serializers.CharField(
+ max_length=50,
+ help_text="Event category, e.g. `status_changed`, `preview_captured`, `dispatched`.",
+ )
+ payload = serializers.JSONField(
+ help_text="Arbitrary structured payload for the event. Shape varies by event_type.",
+ )
+ occurred_at = serializers.DateTimeField(
+ read_only=True,
+ help_text="When the event occurred (server time).",
+ )
+
+ class Meta:
+ model = DeploymentEvent
+ fields = ["id", "deployment", "event_type", "payload", "occurred_at"]
+ read_only_fields = ["id", "deployment", "occurred_at"]
diff --git a/products/deployments/backend/serializers/project.py b/products/deployments/backend/serializers/project.py
new file mode 100644
index 000000000000..bd649c507fe2
--- /dev/null
+++ b/products/deployments/backend/serializers/project.py
@@ -0,0 +1,181 @@
+"""Serializer for DeploymentProject.
+
+`github_integration` is the id of a `posthog.Integration` row with `kind="github"`
+that belongs to the same team. The serializer validates ownership and kind at
+write time. Secrets (the access token) never travel through the serializer —
+they live on the Integration row and are resolved at deploy time.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from urllib.parse import urlparse
+
+from drf_spectacular.utils import extend_schema_field
+from rest_framework import serializers
+
+from posthog.models.integration import Integration
+
+from ..models import DeploymentProject
+
+
+class DeploymentProjectSerializer(serializers.ModelSerializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique identifier for the deployment project.")
+ name = serializers.CharField(max_length=200, help_text="Human-readable project name shown in the UI.")
+ slug = serializers.SlugField(
+ max_length=80,
+ help_text=(
+ "URL-safe handle. Combined with the team id to form the Cloudflare project name; "
+ "the actual subdomain comes from Cloudflare and is returned in the read-only "
+ "`subdomain` field. Must be unique per team."
+ ),
+ )
+ repo_url = serializers.URLField(
+ max_length=1024,
+ help_text="HTTPS URL of the source repository this project deploys from.",
+ )
+ default_branch = serializers.CharField(
+ max_length=255,
+ required=False,
+ default="main",
+ help_text="Branch the project deploys from when no commit SHA is pinned. Defaults to `main`.",
+ )
+ github_integration = serializers.IntegerField(
+ source="github_integration_id",
+ required=False,
+ allow_null=True,
+ help_text=(
+ "ID of the `posthog.Integration` row (kind=github) the project uses to read this "
+ "repository. Must belong to the same team. The actual access token lives on the "
+ "Integration row and is never exposed through this serializer."
+ ),
+ )
+
+ build_command = serializers.CharField(
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ help_text=(
+ "Optional shell command run inside the build container. Null = the build worker "
+ "infers it from `framework` (or auto-detection if framework is also null)."
+ ),
+ )
+ output_dir = serializers.CharField(
+ max_length=255,
+ required=False,
+ default="dist",
+ help_text="Directory containing the built static site, relative to the repository root.",
+ )
+ framework = serializers.CharField(
+ max_length=50,
+ required=False,
+ allow_null=True,
+ allow_blank=True,
+ help_text="Optional framework hint (e.g. `nextjs`, `vite`, `astro`). Null = auto-detect.",
+ )
+ inject_posthog_snippet = serializers.BooleanField(
+ required=False,
+ default=False,
+ help_text=(
+ "If true, the build injects a PostHog snippet into every HTML file that registers "
+ "`release = deployment_id` as a super-property — runtime exceptions are then linked "
+ "back to the deployment that introduced them."
+ ),
+ )
+
+ cloudflare_project_name = serializers.CharField(
+ read_only=True,
+ help_text="Cloudflare Pages project name, assigned during provisioning.",
+ )
+ subdomain = serializers.CharField(
+ read_only=True,
+ help_text="Public subdomain at which deployments of this project serve.",
+ )
+ cloudflare_ready_at = serializers.DateTimeField(
+ read_only=True,
+ allow_null=True,
+ help_text="Timestamp when the Cloudflare project was fully provisioned and ready to receive deploys.",
+ )
+
+ current_deployment: serializers.PrimaryKeyRelatedField = serializers.PrimaryKeyRelatedField( # ty: ignore[invalid-assignment]
+ read_only=True,
+ allow_null=True,
+ help_text="The deployment currently serving traffic for this project. Null if no deployment has ever succeeded.",
+ )
+
+ is_ready_to_deploy = serializers.SerializerMethodField(
+ help_text=(
+ "True when the project has both a provisioned Cloudflare backend and a configured "
+ "GitHub credential — meaning a deploy can be triggered right now."
+ ),
+ )
+
+ created_at = serializers.DateTimeField(
+ read_only=True,
+ help_text="Timestamp when the project was created.",
+ )
+ updated_at = serializers.DateTimeField(
+ read_only=True,
+ help_text="Timestamp when the project was last modified.",
+ )
+
+ class Meta:
+ model = DeploymentProject
+ fields = [
+ "id",
+ "name",
+ "slug",
+ "repo_url",
+ "default_branch",
+ "github_integration",
+ "build_command",
+ "output_dir",
+ "framework",
+ "inject_posthog_snippet",
+ "cloudflare_project_name",
+ "subdomain",
+ "cloudflare_ready_at",
+ "current_deployment",
+ "is_ready_to_deploy",
+ "created_at",
+ "updated_at",
+ ]
+ read_only_fields = [
+ "id",
+ "cloudflare_project_name",
+ "subdomain",
+ "cloudflare_ready_at",
+ "current_deployment",
+ "is_ready_to_deploy",
+ "created_at",
+ "updated_at",
+ ]
+
+ @extend_schema_field(serializers.BooleanField())
+ def get_is_ready_to_deploy(self, obj: DeploymentProject) -> bool:
+ return obj.cloudflare_ready_at is not None and obj.github_integration_id is not None
+
+ def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
+ # The field uses `source="github_integration_id"`, so the int lands under that key.
+ integration_id = attrs.get("github_integration_id")
+ if integration_id is None:
+ return attrs
+ team = self.context["get_team"]()
+ if not Integration.objects.filter(id=integration_id, team_id=team.id, kind="github").exists():
+ raise serializers.ValidationError(
+ {"github_integration": "Integration not found or is not a GitHub integration for this team."}
+ )
+ return attrs
+
+ def validate_repo_url(self, value: str) -> str:
+ # v1 deploys from github.com only. Without this check the field
+ # would accept any URL — including http://169.254.169.254/... or
+ # other internal/link-local hosts the build worker / GitHub
+ # adapter would then connect to (SSRF). Restricting scheme +
+ # host is the smallest fix that closes that vector.
+ parsed = urlparse(value)
+ if parsed.scheme != "https":
+ raise serializers.ValidationError("repo_url must use HTTPS.")
+ if (parsed.hostname or "").lower() != "github.com":
+ raise serializers.ValidationError("repo_url must point to github.com.")
+ return value
diff --git a/products/deployments/backend/services/cancel.py b/products/deployments/backend/services/cancel.py
new file mode 100644
index 000000000000..7ed1ae4155ac
--- /dev/null
+++ b/products/deployments/backend/services/cancel.py
@@ -0,0 +1,52 @@
+"""Cancel an in-flight deployment.
+
+Two paths:
+
+1. Normal case: `temporal_workflow_id` is set. Send a cancel signal to
+ Temporal via the adapter. The workflow's cancellation handler will
+ eventually POST `status=cancelled` back to the internal transitions
+ endpoint, which is what actually flips the DB row.
+2. Orphan case: `temporal_workflow_id` is empty. This happens when
+ `create_deployment` committed the row but `start_build` failed before
+ persisting the handle. There is no worker to signal — flip the row
+ to CANCELLED directly through `update_status` so the state machine
+ stays the single source of truth.
+
+Returns True if a signal was sent, False if the row was directly flipped.
+The caller (viewset) uses this to surface an accurate response message.
+"""
+
+from __future__ import annotations
+
+from ..adapters import WorkflowAdapter, get_workflow_adapter
+from ..domain.status import Status
+from ..models import Deployment
+
+
+class DeploymentNotCancellable(Exception):
+ """The deployment is already in a terminal state."""
+
+
+def execute(*, deployment_id: str, team_id: int, workflow: WorkflowAdapter | None = None) -> bool:
+ # Imported here to avoid a circular import with update_status, which
+ # depends on this module's domain types transitively.
+ from . import update_status
+
+ deployment = Deployment.objects.get(pk=deployment_id, team_id=team_id)
+ if deployment.status not in Deployment.NON_TERMINAL_STATUSES:
+ raise DeploymentNotCancellable(f"Deployment is already {deployment.status}.")
+
+ if deployment.temporal_workflow_id:
+ wf = workflow or get_workflow_adapter()
+ wf.signal_cancel(workflow_id=deployment.temporal_workflow_id)
+ return True
+
+ # Orphan: no workflow to signal. Drive the state machine ourselves so
+ # the row doesn't sit in QUEUED forever.
+ update_status.execute(
+ update_status.UpdateStatusInput(
+ deployment_id=str(deployment.pk),
+ status=Status.CANCELLED,
+ )
+ )
+ return False
diff --git a/products/deployments/backend/services/create_deployment.py b/products/deployments/backend/services/create_deployment.py
new file mode 100644
index 000000000000..6f74ae36342a
--- /dev/null
+++ b/products/deployments/backend/services/create_deployment.py
@@ -0,0 +1,207 @@
+"""Create a new Deployment row, dispatch its build workflow.
+
+The partial unique index `one_active_deployment_per_project` makes
+concurrent POSTs race-safe at the DB layer: the second insert raises
+IntegrityError, which the viewset translates to HTTP 409 Conflict.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from django.db import IntegrityError, transaction
+from django.utils import timezone
+
+import structlog
+
+from posthog.models.integration import Integration
+
+from ..adapters import (
+ CloudflareAdapter,
+ GitHubAdapter,
+ WorkflowAdapter,
+ get_cloudflare_adapter,
+ get_github_adapter,
+ get_workflow_adapter,
+)
+from ..domain.contracts import BuildInput
+from ..domain.trigger import ErrorStep, TriggerKind
+from ..models import Deployment, DeploymentProject
+
+logger = structlog.get_logger(__name__)
+
+
+class ActiveDeploymentExists(Exception):
+ """Raised when a project already has a non-terminal deployment in flight.
+
+ The viewset catches this and returns HTTP 409 with the in-flight
+ deployment ID.
+ """
+
+ def __init__(self, active_deployment_id: str) -> None:
+ self.active_deployment_id = active_deployment_id
+ super().__init__(f"Project already has an active deployment: {active_deployment_id}")
+
+
+class WorkflowDispatchFailed(Exception):
+ """Raised when the build workflow couldn't be dispatched.
+
+ The deployment row has already been marked ERROR at this point —
+ callers should surface a 502 to the client. The row carries
+ `error_step=dispatch` and `error_message` describing the failure so
+ operators can audit it.
+ """
+
+ def __init__(self, deployment_id: str, cause: BaseException) -> None:
+ self.deployment_id = deployment_id
+ self.__cause__ = cause
+ super().__init__(f"Failed to start build workflow for deployment {deployment_id}: {cause}")
+
+
+@dataclass(frozen=True)
+class CreateDeploymentInput:
+ project_id: str
+ team_id: int
+ triggered_by_user_id: int | None
+ trigger_kind: TriggerKind
+ commit_sha: str | None
+ branch: str | None
+ triggered_by_deployment_id: str | None = None
+
+
+def execute(
+ payload: CreateDeploymentInput,
+ *,
+ cloudflare: CloudflareAdapter | None = None,
+ github: GitHubAdapter | None = None,
+ workflow: WorkflowAdapter | None = None,
+) -> Deployment:
+ project = DeploymentProject.objects.get(id=payload.project_id, team_id=payload.team_id)
+
+ # Resolve the GitHub access token from the project's Integration row, if any.
+ # The token is short-lived (GitHub App installation tokens expire after ~1h);
+ # we read whatever's currently stored in `sensitive_config` — refreshing is
+ # owned by the integration framework, not this service. A null token means
+ # public-repo access or a Null adapter in tests.
+ access_token = _resolve_github_access_token(project.github_integration_id, project.team_id)
+
+ # Resolve commit metadata up-front when possible. The build worker will
+ # also resolve HEAD-of-branch in `resolve_commit_sha`, but pre-resolving
+ # lets the list scene render real commit messages before the worker
+ # picks up the workflow.
+ branch = payload.branch or project.default_branch
+ gh = github or get_github_adapter()
+ if payload.commit_sha:
+ commit = gh.get_commit(repo_url=project.repo_url, sha=payload.commit_sha, access_token=access_token)
+ else:
+ commit = gh.head_of_branch(repo_url=project.repo_url, branch=branch, access_token=access_token)
+
+ try:
+ with transaction.atomic():
+ deployment = Deployment.objects.create(
+ project=project,
+ team_id=payload.team_id,
+ triggered_by_user_id=payload.triggered_by_user_id,
+ triggered_by_deployment_id=payload.triggered_by_deployment_id,
+ trigger_kind=payload.trigger_kind.value,
+ status=Deployment.Status.QUEUED,
+ commit_sha=commit.sha,
+ commit_message=commit.message,
+ commit_author_name=commit.author_name,
+ commit_author_email=commit.author_email,
+ repo_url=project.repo_url,
+ branch=commit.branch,
+ )
+ except IntegrityError as exc:
+ # Race: another POST landed first. Surface the in-flight deployment
+ # so the FE can poll its detail endpoint instead of retrying.
+ if "one_active_deployment_per_project" in str(exc):
+ in_flight = (
+ Deployment.objects.filter(
+ project=project,
+ team_id=payload.team_id,
+ status__in=Deployment.NON_TERMINAL_STATUSES,
+ )
+ .values_list("id", flat=True)
+ .first()
+ )
+ raise ActiveDeploymentExists(str(in_flight) if in_flight else "")
+ raise
+
+ # Hand off to the build worker. Persist the workflow handle so cancel()
+ # can target the right run later.
+ #
+ # The row is already committed in QUEUED state by this point. If
+ # `start_build` raises (e.g. Temporal unreachable), the row would
+ # otherwise sit QUEUED forever with no workflow id — no worker to
+ # advance it and `cancel.execute` would have nothing to signal. So
+ # we flip it to ERROR(error_step=dispatch) on failure and raise a
+ # typed exception the view can map to 502.
+ wf = workflow or get_workflow_adapter()
+ cf = cloudflare or get_cloudflare_adapter() # noqa: F841 — held for future provisioning checks
+ try:
+ handle = wf.start_build(
+ workflow_input=BuildInput(
+ deployment_id=deployment.id,
+ project_id=project.id,
+ team_id=payload.team_id,
+ repo_url=project.repo_url,
+ branch=commit.branch,
+ commit_sha=commit.sha,
+ github_access_token=access_token,
+ build_command=project.build_command,
+ output_dir=project.output_dir,
+ framework=project.framework,
+ inject_posthog_snippet=project.inject_posthog_snippet,
+ cloudflare_project_name=project.cloudflare_project_name,
+ trigger_kind=payload.trigger_kind,
+ )
+ )
+ except Exception as exc:
+ logger.exception(
+ "create_deployment.workflow_dispatch_failed",
+ deployment_id=str(deployment.pk),
+ error=str(exc),
+ )
+ # Direct .update() instead of `update_status.execute` so we don't
+ # walk the state machine for a row that never got off QUEUED —
+ # `assert_valid(QUEUED, ERROR)` is valid but the side-effect
+ # scheduling in update_status (finalize_failure → $exception) is
+ # noise for a dispatch failure that never produced any build
+ # output. Operators see the ERROR row + the structlog event.
+ Deployment.objects.filter(pk=deployment.pk).update(
+ status=Deployment.Status.ERROR.value,
+ error_step=ErrorStep.DISPATCH.value,
+ error_message=f"Failed to dispatch build workflow: {exc}",
+ finished_at=timezone.now(),
+ )
+ raise WorkflowDispatchFailed(str(deployment.pk), exc) from exc
+
+ Deployment.objects.filter(pk=deployment.pk).update(
+ temporal_workflow_id=handle.workflow_id,
+ temporal_run_id=handle.run_id,
+ )
+ deployment.refresh_from_db()
+ return deployment
+
+
+def _resolve_github_access_token(integration_id: int | None, team_id: int) -> str | None:
+ if integration_id is None:
+ return None
+ try:
+ integration = Integration.objects.get(id=integration_id, kind="github", team_id=team_id)
+ except Integration.DoesNotExist:
+ # Row was deleted, never existed, or belongs to a different team. Treat
+ # as "no creds" so the adapter can still attempt unauthenticated
+ # public-repo access and surface a clean GitHubError if the repo is
+ # private. Filtering by team_id closes the IDOR window where a stale
+ # github_integration_id (e.g. left over from a moved project) could
+ # otherwise resolve to another team's GitHub App token.
+ logger.warning(
+ "create_deployment.integration_missing",
+ integration_id=integration_id,
+ team_id=team_id,
+ )
+ return None
+ token = integration.sensitive_config.get("access_token")
+ return str(token) if token else None
diff --git a/products/deployments/backend/services/finalize_failure.py b/products/deployments/backend/services/finalize_failure.py
new file mode 100644
index 000000000000..c4ec5b91d6ad
--- /dev/null
+++ b/products/deployments/backend/services/finalize_failure.py
@@ -0,0 +1,53 @@
+"""Side effects scheduled when a Deployment flips to ERROR.
+
+Emits a `$exception` PostHog event so the failure shows up in Error
+Tracking grouped by deployment_id. The `$exception_releases` property
+matches the shape Error Tracking already stores (see
+products/error_tracking/backend/api/query_utils.py).
+"""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+import structlog
+
+from posthog.ph_client import ph_scoped_capture
+
+from ..models import Deployment
+
+logger = structlog.get_logger(__name__)
+
+
+def execute(*, deployment_id: UUID | str) -> None:
+ deployment = Deployment.all_teams.select_related("project").filter(pk=deployment_id).first()
+ if deployment is None:
+ logger.warning("finalize_failure.missing_deployment", deployment_id=str(deployment_id))
+ return
+
+ distinct_id = (
+ str(deployment.triggered_by_user_id)
+ if deployment.triggered_by_user_id is not None
+ else f"team_{deployment.team_id}"
+ )
+
+ sha7 = deployment.commit_sha[:7] if deployment.commit_sha else str(deployment.id)[:7]
+
+ with ph_scoped_capture() as capture:
+ capture(
+ distinct_id=distinct_id,
+ event="$exception",
+ properties={
+ "$exception_type": "DeploymentBuildFailed",
+ "$exception_message": deployment.error_message or f"Build failed at step {deployment.error_step}",
+ "$exception_releases": {sha7: deployment.deployment_url or None},
+ "deployment_id": str(deployment.id),
+ "project_id": str(deployment.project_id),
+ "error_step": deployment.error_step,
+ "commit_sha": deployment.commit_sha,
+ "repo_url": deployment.repo_url,
+ "branch": deployment.branch,
+ "trigger_kind": deployment.trigger_kind,
+ },
+ groups={"project": str(deployment.team_id)},
+ )
diff --git a/products/deployments/backend/services/finalize_success.py b/products/deployments/backend/services/finalize_success.py
new file mode 100644
index 000000000000..11d49fab5683
--- /dev/null
+++ b/products/deployments/backend/services/finalize_success.py
@@ -0,0 +1,173 @@
+"""Side effects scheduled when a Deployment flips to READY.
+
+This is OUR responsibility — not Build/Infra's. It runs the actual Posthog-
+internal integrations (Annotation, ErrorTrackingRelease, $deployment event)
+that close the loop between deploys and the rest of the product.
+
+Called via `transaction.on_commit(lambda: execute(...))` from update_status
+so a rolled-back transition leaves nothing behind. The callback fires
+AFTER the request transaction commits — at that point the request's team
+scope (set by `TeamAndOrgViewSetMixin`) has already been torn down, and
+the internal endpoint never sets one in the first place. We re-enter
+team scope from `deployment.team_id` so the TeamScopedManager finds rows.
+"""
+
+from __future__ import annotations
+
+from uuid import UUID
+
+from django.utils import timezone
+
+import structlog
+
+from posthog.models.annotation import Annotation
+from posthog.models.scoping import team_scope
+from posthog.models.team.team import Team
+from posthog.ph_client import ph_scoped_capture
+
+from products.error_tracking.backend.models import ErrorTrackingRelease
+
+from ..adapters import ScreenshotAdapter, get_screenshot_adapter
+from ..models import Deployment, DeploymentEvent
+
+logger = structlog.get_logger(__name__)
+
+
+def execute(*, deployment_id: UUID | str, screenshot: ScreenshotAdapter | None = None) -> None:
+ # `all_teams` bypasses TeamScopedManager so we can read the row before
+ # entering scope. Once we have `team_id` from the row, we enter scope
+ # for the rest of the work so subsequent writes to scoped models
+ # (Deployment, DeploymentEvent) succeed.
+ deployment = Deployment.all_teams.select_related("project").filter(pk=deployment_id).first()
+ if deployment is None:
+ # Row was deleted between commit and callback. Drop quietly.
+ logger.warning("finalize_success.missing_deployment", deployment_id=str(deployment_id))
+ return
+
+ with team_scope(deployment.team_id, canonical=True):
+ # 1) Annotation marking the deploy on insight timelines.
+ _create_annotation(deployment)
+
+ # 2) ErrorTrackingRelease — join key the UI uses to link runtime
+ # exceptions back to the deploy that introduced them.
+ _create_error_tracking_release(deployment)
+
+ # 3) $deployment PostHog event for downstream funnels / webhooks.
+ _emit_deployment_event(deployment)
+
+ # 4) Best-effort preview screenshot. Failure surfaces as a
+ # preview_capture_failed event but does NOT roll back ready.
+ # Guard the empty-URL case explicitly with a distinct payload
+ # `reason` — otherwise the event log would record a spurious
+ # "failure" for a capture that was never attempted. Matches
+ # the shape used by `refresh_preview.execute`.
+ if not deployment.deployment_url:
+ DeploymentEvent.objects.create(
+ deployment_id=deployment.pk,
+ team_id=deployment.team_id,
+ event_type="preview_capture_failed",
+ payload={"reason": "no_deployment_url"},
+ )
+ else:
+ screenshot_adapter = screenshot or get_screenshot_adapter()
+ image_url = screenshot_adapter.capture(url=deployment.deployment_url)
+ if image_url:
+ Deployment.objects.filter(pk=deployment.pk).update(preview_image_url=image_url)
+ DeploymentEvent.objects.create(
+ deployment_id=deployment.pk,
+ team_id=deployment.team_id,
+ event_type="preview_captured",
+ payload={"url": image_url},
+ )
+ else:
+ DeploymentEvent.objects.create(
+ deployment_id=deployment.pk,
+ team_id=deployment.team_id,
+ event_type="preview_capture_failed",
+ payload={"deployment_url": deployment.deployment_url},
+ )
+
+
+def _create_annotation(deployment: Deployment) -> None:
+ """Create a PROJECT-scoped annotation with creation_type=GIT."""
+ organization_id = Team.objects.filter(id=deployment.team_id).values_list("organization_id", flat=True).first()
+ if organization_id is None:
+ # The team has been deleted between the build starting and ready.
+ logger.warning("finalize_success.no_organization", team_id=deployment.team_id)
+ return
+ content = _annotation_content(deployment)
+ Annotation.objects.create(
+ team_id=deployment.team_id,
+ organization_id=organization_id,
+ scope=Annotation.Scope.PROJECT,
+ creation_type=Annotation.CreationType.GITHUB,
+ date_marker=deployment.finished_at or timezone.now(),
+ content=content,
+ )
+
+
+def _annotation_content(deployment: Deployment) -> str:
+ sha7 = deployment.commit_sha[:7] if deployment.commit_sha else ""
+ msg = (deployment.commit_message or "").splitlines()[0] if deployment.commit_message else ""
+ msg = msg[:80]
+ if msg and sha7:
+ return f"{msg} ({sha7})"
+ if sha7:
+ return f"Deploy {sha7}"
+ return f"Deploy {deployment.id}"
+
+
+def _create_error_tracking_release(deployment: Deployment) -> None:
+ """Idempotent — the (team_id, hash_id) unique constraint silently
+ de-dupes repeated calls."""
+ try:
+ ErrorTrackingRelease.objects.get_or_create(
+ team_id=deployment.team_id,
+ hash_id=str(deployment.id),
+ defaults={
+ "version": deployment.commit_sha[:7] if deployment.commit_sha else str(deployment.id)[:7],
+ "project": deployment.project.cloudflare_project_name or deployment.project.slug,
+ "metadata": {
+ "deployment_id": str(deployment.id),
+ "commit_sha": deployment.commit_sha,
+ "commit_message": deployment.commit_message,
+ "deployment_url": deployment.deployment_url,
+ "branch": deployment.branch,
+ },
+ },
+ )
+ except Exception as exc: # noqa: BLE001 — finalize_success is best-effort
+ # Don't let a release-row failure block the deployment from being
+ # marked ready. Log and move on.
+ logger.exception("finalize_success.error_tracking_release_failed", error=str(exc))
+
+
+def _emit_deployment_event(deployment: Deployment) -> None:
+ """Emit $deployment via ph_scoped_capture — Temporal/Celery-safe."""
+ distinct_id = (
+ str(deployment.triggered_by_user_id)
+ if deployment.triggered_by_user_id is not None
+ else f"team_{deployment.team_id}"
+ )
+ duration_seconds: int | None = None
+ if deployment.finished_at and deployment.started_at:
+ duration_seconds = int((deployment.finished_at - deployment.started_at).total_seconds())
+
+ with ph_scoped_capture() as capture:
+ capture(
+ distinct_id=distinct_id,
+ event="$deployment",
+ properties={
+ "deployment_id": str(deployment.id),
+ "project_id": str(deployment.project_id),
+ "commit_sha": deployment.commit_sha,
+ "commit_message": deployment.commit_message,
+ "branch": deployment.branch,
+ "deployment_url": deployment.deployment_url,
+ "subdomain": deployment.project.subdomain,
+ "framework": deployment.project.framework,
+ "trigger_kind": deployment.trigger_kind,
+ "duration_seconds": duration_seconds,
+ },
+ groups={"project": str(deployment.team_id)},
+ )
diff --git a/products/deployments/backend/services/provision_project.py b/products/deployments/backend/services/provision_project.py
new file mode 100644
index 000000000000..5dbce399a15c
--- /dev/null
+++ b/products/deployments/backend/services/provision_project.py
@@ -0,0 +1,80 @@
+"""Provision a DeploymentProject + matching Cloudflare Pages project.
+
+The Cloudflare call happens BEFORE the atomic DB write, never inside it.
+Rationale (from CLAUDE.md): "Avoid performing irreversible side effects
+inside an atomic block: if the transaction rolls back, those side effects
+have already happened." A rolled-back DB write doesn't un-create the
+Cloudflare project. Putting the call inside `transaction.on_commit` is
+worse — the HTTP response has already been written by the time the
+callback fires, so the 502 path becomes unreachable.
+
+If the Cloudflare call fails, no local row exists; the orphaned-CF-project
+risk is zero (there isn't one). If the local insert later fails (rare;
+the partial unique constraint can't fire here), the orphaned CF project
+gets reaped by a periodic cleanup task (deferred to v2).
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from django.db import transaction
+from django.utils import timezone
+
+from ..adapters import CloudflareAdapter, get_cloudflare_adapter
+from ..models import DeploymentProject
+
+
+@dataclass(frozen=True)
+class ProvisionInput:
+ team_id: int
+ created_by_id: int | None
+ name: str
+ slug: str
+ repo_url: str
+ default_branch: str
+ github_integration_id: int | None
+ build_command: str | None
+ output_dir: str
+ framework: str | None
+ inject_posthog_snippet: bool
+
+
+def execute(
+ payload: ProvisionInput,
+ *,
+ cloudflare: CloudflareAdapter | None = None,
+) -> DeploymentProject:
+ cf = cloudflare or get_cloudflare_adapter()
+
+ # 1) Irreversible CF side effect FIRST. If it fails, no DB row exists.
+ cf_project = cf.create_project(
+ name=f"{payload.team_id}-{payload.slug}",
+ production_branch=payload.default_branch,
+ )
+
+ # 2) Narrow atomic block — local row only. Persist whatever the adapter
+ # actually published the project at, not a hardcoded pattern: the slug
+ # uniqueness constraint is per-team, so two different teams choosing
+ # slug "myapp" would collide on a hardcoded `{slug}.posthog-app.com`,
+ # and the value flows into the `$deployment` PostHog event so any
+ # divergence pollutes analytics. The real adapter (when it lands) is
+ # the source of truth for the actual subdomain.
+ with transaction.atomic():
+ project = DeploymentProject.objects.create(
+ team_id=payload.team_id,
+ created_by_id=payload.created_by_id,
+ name=payload.name,
+ slug=payload.slug,
+ repo_url=payload.repo_url,
+ default_branch=payload.default_branch,
+ github_integration_id=payload.github_integration_id,
+ build_command=payload.build_command,
+ output_dir=payload.output_dir,
+ framework=payload.framework,
+ inject_posthog_snippet=payload.inject_posthog_snippet,
+ cloudflare_project_name=cf_project.name,
+ subdomain=cf_project.subdomain,
+ cloudflare_ready_at=timezone.now(),
+ )
+ return project
diff --git a/products/deployments/backend/services/redeploy.py b/products/deployments/backend/services/redeploy.py
new file mode 100644
index 000000000000..81714db78a0f
--- /dev/null
+++ b/products/deployments/backend/services/redeploy.py
@@ -0,0 +1,34 @@
+"""Trigger a new deployment at the same commit as a prior one."""
+
+from __future__ import annotations
+
+from ..adapters import CloudflareAdapter, GitHubAdapter, WorkflowAdapter
+from ..domain.trigger import TriggerKind
+from ..models import Deployment
+from . import create_deployment
+
+
+def execute(
+ *,
+ deployment_id: str,
+ team_id: int,
+ triggered_by_user_id: int | None,
+ cloudflare: CloudflareAdapter | None = None,
+ github: GitHubAdapter | None = None,
+ workflow: WorkflowAdapter | None = None,
+) -> Deployment:
+ source = Deployment.objects.select_related("project").get(pk=deployment_id, team_id=team_id)
+ return create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=str(source.project_id),
+ team_id=team_id,
+ triggered_by_user_id=triggered_by_user_id,
+ trigger_kind=TriggerKind.REDEPLOY,
+ commit_sha=source.commit_sha or None,
+ branch=source.branch or None,
+ triggered_by_deployment_id=str(source.pk),
+ ),
+ cloudflare=cloudflare,
+ github=github,
+ workflow=workflow,
+ )
diff --git a/products/deployments/backend/services/refresh_preview.py b/products/deployments/backend/services/refresh_preview.py
new file mode 100644
index 000000000000..1fef2e23f171
--- /dev/null
+++ b/products/deployments/backend/services/refresh_preview.py
@@ -0,0 +1,44 @@
+"""Re-capture the preview screenshot for a deployment.
+
+Best-effort: a failure surfaces as a `preview_capture_failed` DeploymentEvent
+row but the call still returns a 200 to the caller. The frontend re-polls
+the detail endpoint after triggering this and reads the new
+`preview_image_url` field.
+"""
+
+from __future__ import annotations
+
+from ..adapters import ScreenshotAdapter, get_screenshot_adapter
+from ..models import Deployment, DeploymentEvent
+
+
+def execute(*, deployment_id: str, team_id: int, screenshot: ScreenshotAdapter | None = None) -> Deployment:
+ deployment = Deployment.objects.get(pk=deployment_id, team_id=team_id)
+ if not deployment.deployment_url:
+ DeploymentEvent.objects.create(
+ deployment_id=deployment.pk,
+ team_id=team_id,
+ event_type="preview_capture_failed",
+ payload={"reason": "no_deployment_url"},
+ )
+ return deployment
+
+ adapter = screenshot or get_screenshot_adapter()
+ image_url = adapter.capture(url=deployment.deployment_url)
+ if image_url:
+ Deployment.objects.filter(pk=deployment.pk).update(preview_image_url=image_url)
+ DeploymentEvent.objects.create(
+ deployment_id=deployment.pk,
+ team_id=team_id,
+ event_type="preview_captured",
+ payload={"url": image_url},
+ )
+ deployment.refresh_from_db(fields=["preview_image_url"])
+ else:
+ DeploymentEvent.objects.create(
+ deployment_id=deployment.pk,
+ team_id=team_id,
+ event_type="preview_capture_failed",
+ payload={"deployment_url": deployment.deployment_url},
+ )
+ return deployment
diff --git a/products/deployments/backend/services/rollback.py b/products/deployments/backend/services/rollback.py
new file mode 100644
index 000000000000..eb4785e72a04
--- /dev/null
+++ b/products/deployments/backend/services/rollback.py
@@ -0,0 +1,40 @@
+"""Trigger a rollback deployment: a new row pointing at the target deployment.
+
+The actual Cloudflare rollback is performed by the build worker (it calls
+the Cloudflare adapter's `rollback` from inside the workflow). When the
+worker finishes and posts `ready`, `update_status` flips
+`DeploymentProject.current_deployment` to this rollback row.
+"""
+
+from __future__ import annotations
+
+from ..adapters import CloudflareAdapter, GitHubAdapter, WorkflowAdapter
+from ..domain.trigger import TriggerKind
+from ..models import Deployment
+from . import create_deployment
+
+
+def execute(
+ *,
+ deployment_id: str,
+ team_id: int,
+ triggered_by_user_id: int | None,
+ cloudflare: CloudflareAdapter | None = None,
+ github: GitHubAdapter | None = None,
+ workflow: WorkflowAdapter | None = None,
+) -> Deployment:
+ target = Deployment.objects.select_related("project").get(pk=deployment_id, team_id=team_id)
+ return create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=str(target.project_id),
+ team_id=team_id,
+ triggered_by_user_id=triggered_by_user_id,
+ trigger_kind=TriggerKind.ROLLBACK,
+ commit_sha=target.commit_sha or None,
+ branch=target.branch or None,
+ triggered_by_deployment_id=str(target.pk),
+ ),
+ cloudflare=cloudflare,
+ github=github,
+ workflow=workflow,
+ )
diff --git a/products/deployments/backend/services/update_status.py b/products/deployments/backend/services/update_status.py
new file mode 100644
index 000000000000..e47e5699a68d
--- /dev/null
+++ b/products/deployments/backend/services/update_status.py
@@ -0,0 +1,105 @@
+"""Apply a status transition to a Deployment.
+
+The ONLY entry point that mutates `Deployment.status`. Called by the
+internal `/api/internal/deployments/{id}/transitions/` endpoint when the
+build worker posts a status update.
+
+Invariants:
+- SELECT FOR UPDATE on the row so concurrent transitions serialize.
+- Idempotent: a duplicate `ready` callback on an already-`ready` row is
+ a no-op (returns the existing instance). Detection uses
+ `domain.status.is_idempotent_noop`.
+- Side effects (annotation, ErrorTrackingRelease, $deployment event)
+ scheduled via `transaction.on_commit` so a rolled-back transition
+ leaves no orphan records.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime
+from uuid import UUID
+
+from django.db import transaction
+from django.utils import timezone
+
+from ..domain.status import Status, assert_valid, is_idempotent_noop
+from ..domain.trigger import ErrorStep
+from ..models import Deployment
+
+
+@dataclass(frozen=True)
+class UpdateStatusInput:
+ deployment_id: UUID | str
+ status: Status
+ cloudflare_deployment_id: str | None = None
+ deployment_url: str | None = None
+ error_message: str | None = None
+ error_step: ErrorStep | None = None
+ started_at: datetime | None = None
+ finished_at: datetime | None = None
+
+
+def execute(payload: UpdateStatusInput) -> Deployment:
+ # Import here to avoid a circular import with finalize_success (which
+ # depends on this module's UpdateStatusInput shape).
+ from . import finalize_failure, finalize_success
+
+ with transaction.atomic():
+ deployment = (
+ Deployment.all_teams.select_for_update(of=("self",)).select_related("project").get(pk=payload.deployment_id)
+ )
+ current = Status(deployment.status)
+ target = payload.status
+
+ if is_idempotent_noop(current, target):
+ # Duplicate callback from a racing build activity. Don't error
+ # — Temporal's at-least-once delivery makes this expected.
+ return deployment
+
+ assert_valid(current, target)
+
+ deployment.status = target.value
+ if payload.cloudflare_deployment_id is not None:
+ deployment.cloudflare_deployment_id = payload.cloudflare_deployment_id
+ if payload.deployment_url is not None:
+ deployment.deployment_url = payload.deployment_url
+ if payload.error_message is not None:
+ deployment.error_message = payload.error_message
+ if payload.error_step is not None:
+ deployment.error_step = payload.error_step.value
+ if payload.started_at is not None:
+ deployment.started_at = payload.started_at
+ if target == Status.INITIALIZING and deployment.started_at is None:
+ deployment.started_at = timezone.now()
+ if payload.finished_at is not None:
+ deployment.finished_at = payload.finished_at
+ if target in (Status.READY, Status.ERROR, Status.CANCELLED) and deployment.finished_at is None:
+ deployment.finished_at = timezone.now()
+ deployment.save(
+ update_fields=[
+ "status",
+ "cloudflare_deployment_id",
+ "deployment_url",
+ "error_message",
+ "error_step",
+ "started_at",
+ "finished_at",
+ ]
+ )
+
+ # On READY, flip the project's current_deployment pointer atomically.
+ if target == Status.READY:
+ project = deployment.project
+ project.current_deployment_id = deployment.pk
+ project.save(update_fields=["current_deployment", "updated_at"])
+
+ # Schedule side effects AFTER the commit. A rolled-back transition
+ # (e.g. an exception during save) leaves no annotations, no
+ # ErrorTrackingRelease, no $deployment events.
+ if target == Status.READY:
+ transaction.on_commit(lambda: finalize_success.execute(deployment_id=deployment.pk))
+ elif target == Status.ERROR:
+ transaction.on_commit(lambda: finalize_failure.execute(deployment_id=deployment.pk))
+
+ return deployment
diff --git a/products/deployments/backend/test/_helpers.py b/products/deployments/backend/test/_helpers.py
new file mode 100644
index 000000000000..e89eace23dd8
--- /dev/null
+++ b/products/deployments/backend/test/_helpers.py
@@ -0,0 +1,41 @@
+"""Shared test helpers for the Deployments backend.
+
+`DeploymentsTeamScopedTestMixin` wraps `setUp` / `tearDown` with a
+`team_scope` context using `self.team.id`, so queries through
+`ProductTeamModel.objects` find a team and don't raise `TeamScopeError`.
+
+Mirrors the pattern at
+`products/visual_review/backend/tests/conftest.py:57-89`.
+"""
+
+from __future__ import annotations
+
+from contextlib import AbstractContextManager
+
+from posthog.models.scoping import team_scope
+
+
+class DeploymentsTeamScopedTestMixin:
+ """Wraps setUp/tearDown with team_scope(self.team.id).
+
+ Place BEFORE `APIBaseTest` / `BaseTest` in the MRO so its setUp runs
+ first (creating `self.team`) and ours can use it. The `_cm` is
+ initialised to None up front so a partial-init failure in setUp
+ doesn't leave tearDown calling __exit__ on an unentered ctx manager.
+ """
+
+ _cm: AbstractContextManager[None] | None = None
+
+ def setUp(self) -> None:
+ super().setUp() # type: ignore[misc]
+ cm = team_scope(self.team.id) # type: ignore[attr-defined]
+ cm.__enter__()
+ self._cm = cm
+
+ def tearDown(self) -> None:
+ if self._cm is not None:
+ try:
+ self._cm.__exit__(None, None, None)
+ finally:
+ self._cm = None
+ super().tearDown() # type: ignore[misc]
diff --git a/products/deployments/backend/test/test_deployments_api.py b/products/deployments/backend/test/test_deployments_api.py
index 05c2450138aa..3ecdc5b75ae5 100644
--- a/products/deployments/backend/test/test_deployments_api.py
+++ b/products/deployments/backend/test/test_deployments_api.py
@@ -1,13 +1,318 @@
+"""End-to-end tests for the public Deployments API.
+
+Covers both top-level routes:
+- /api/projects/{team_id}/deployment_projects/...
+- /api/projects/{team_id}/deployment_projects/{pid}/deployments/...
+
+The feature flag gate (`DeploymentsAccessPermission`) is mocked via
+`posthoganalytics.feature_enabled` — see `products/deployments/backend/access.py`.
+"""
+
+from __future__ import annotations
+
from posthog.test.base import APIBaseTest
from unittest.mock import patch
+from django.utils import timezone
+
from parameterized import parameterized
from rest_framework import status
+from posthog.models.integration import Integration
from posthog.models.utils import uuid7
+from products.deployments.backend.models import Deployment, DeploymentProject
+from products.deployments.backend.test._helpers import DeploymentsTeamScopedTestMixin
+
+
+class _BaseDeploymentsAPITest(DeploymentsTeamScopedTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # Force the feature flag on for every test in this module — it's
+ # the same gate the scaffold's test_list_respects_feature_flag
+ # covered separately.
+ self._flag_patcher = patch(
+ "products.deployments.backend.access.posthoganalytics.feature_enabled",
+ return_value=True,
+ )
+ self._flag_patcher.start()
+ self.addCleanup(self._flag_patcher.stop)
+
+
+class TestDeploymentProjectsAPI(_BaseDeploymentsAPITest):
+ def test_list_returns_empty_when_no_projects(self) -> None:
+ response = self.client.get(f"/api/projects/{self.team.id}/deployment_projects/")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["results"], [])
+
+ def test_list_excludes_soft_deleted(self) -> None:
+ DeploymentProject.objects.create(
+ team_id=self.team.id,
+ name="Alive",
+ slug="alive",
+ repo_url="https://github.com/example-org/alive",
+ )
+ DeploymentProject.objects.create(
+ team_id=self.team.id,
+ name="Dead",
+ slug="dead",
+ repo_url="https://github.com/example-org/dead",
+ deleted=True,
+ deleted_at=timezone.now(),
+ )
+ response = self.client.get(f"/api/projects/{self.team.id}/deployment_projects/")
+ results = response.json()["results"]
+ slugs = [p["slug"] for p in results]
+ self.assertEqual(slugs, ["alive"])
+
+ def test_github_integration_is_persisted_and_returned(self) -> None:
+ # POST accepts a github_integration id pointing at the team's
+ # `posthog.Integration` row; the FK is returned on GETs (it's a
+ # reference, not a secret — the access token lives on Integration).
+ integration = Integration.objects.create(
+ team=self.team,
+ kind="github",
+ integration_id="42",
+ sensitive_config={"access_token": "ghs_short_lived"},
+ )
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/deployment_projects/",
+ {
+ "name": "Site",
+ "slug": "site",
+ "repo_url": "https://github.com/example-org/site",
+ "github_integration": integration.id,
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ body = response.json()
+ self.assertEqual(body["github_integration"], integration.id)
+ # Verify the FK is stored on the row.
+ project = DeploymentProject.all_teams.get(pk=body["id"])
+ self.assertEqual(project.github_integration_id, integration.id)
+ # No secrets exposed via the API surface.
+ self.assertNotIn("access_token", body)
+ self.assertNotIn("sensitive_config", body)
+
+ def test_github_integration_must_belong_to_team(self) -> None:
+ # An integration from another team is not selectable.
+ other_team = self.organization.teams.create(name="Other")
+ outsider = Integration.objects.create(
+ team=other_team,
+ kind="github",
+ integration_id="99",
+ sensitive_config={"access_token": "ghs_other"},
+ )
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/deployment_projects/",
+ {
+ "name": "Site",
+ "slug": "site",
+ "repo_url": "https://github.com/example-org/site",
+ "github_integration": outsider.id,
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
+ self.assertEqual(response.json().get("attr"), "github_integration")
+
+ def test_github_integration_kind_must_be_github(self) -> None:
+ slack = Integration.objects.create(
+ team=self.team,
+ kind="slack",
+ integration_id="T123",
+ sensitive_config={"access_token": "xoxb-not-github"},
+ )
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/deployment_projects/",
+ {
+ "name": "Site",
+ "slug": "site",
+ "repo_url": "https://github.com/example-org/site",
+ "github_integration": slack.id,
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
+ self.assertEqual(response.json().get("attr"), "github_integration")
+
+ def test_create_provisions_cloudflare_via_null_adapter(self) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/deployment_projects/",
+ {
+ "name": "Site",
+ "slug": "site",
+ "repo_url": "https://github.com/example-org/site",
+ },
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ body = response.json()
+ # Null adapter assigns a {team_id}-{slug} name; serializer surfaces
+ # the cloudflare_project_name as a read-only field. The subdomain
+ # mirrors whatever the adapter returned (Null = `{name}.pages.dev`)
+ # — provisioning persists the adapter's value rather than a
+ # hardcoded pattern so two teams with the same slug don't collide.
+ self.assertIn(f"{self.team.id}-site", body["cloudflare_project_name"])
+ self.assertEqual(body["subdomain"], f"{self.team.id}-site.pages.dev")
+ self.assertIsNotNone(body["cloudflare_ready_at"])
+
+ def test_destroy_is_soft_delete(self) -> None:
+ project = DeploymentProject.objects.create(
+ team_id=self.team.id,
+ name="Site",
+ slug="site",
+ repo_url="https://github.com/example-org/site",
+ )
+ response = self.client.delete(f"/api/projects/{self.team.id}/deployment_projects/{project.id}/")
+ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
+ # Row still exists but flagged deleted.
+ project.refresh_from_db()
+ self.assertTrue(project.deleted)
+ self.assertIsNotNone(project.deleted_at)
+
+
+class TestDeploymentsAPINested(_BaseDeploymentsAPITest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.deployment_project = DeploymentProject.objects.create(
+ team_id=self.team.id,
+ name="Site",
+ slug="site",
+ repo_url="https://github.com/example-org/site",
+ cloudflare_project_name=f"{self.team.id}-site",
+ subdomain="site.posthog-app.com",
+ cloudflare_ready_at=timezone.now(),
+ )
+
+ def test_list_returns_empty_when_no_deployments(self) -> None:
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/deployment_projects/{self.deployment_project.id}/deployments/"
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json()["results"], [])
+
+ def test_unknown_project_returns_404(self) -> None:
+ response = self.client.get(f"/api/projects/{self.team.id}/deployment_projects/{uuid7()}/deployments/")
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+
+ def test_post_creates_deployment(self) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/deployment_projects/{self.deployment_project.id}/deployments/",
+ {},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+ body = response.json()
+ self.assertEqual(body["status"], Deployment.Status.QUEUED.value)
+ self.assertEqual(body["trigger_kind"], Deployment.TriggerKind.MANUAL.value)
+
+ def test_second_concurrent_post_returns_409(self) -> None:
+ # First create: succeeds.
+ first = self.client.post(
+ f"/api/projects/{self.team.id}/deployment_projects/{self.deployment_project.id}/deployments/",
+ {},
+ format="json",
+ )
+ self.assertEqual(first.status_code, status.HTTP_201_CREATED, first.content)
+ # Second: the partial unique constraint fires.
+ second = self.client.post(
+ f"/api/projects/{self.team.id}/deployment_projects/{self.deployment_project.id}/deployments/",
+ {},
+ format="json",
+ )
+ self.assertEqual(second.status_code, status.HTTP_409_CONFLICT, second.content)
+ body = second.json()
+ self.assertEqual(body["active_deployment_id"], first.json()["id"])
+
+ def test_list_default_filter_hides_cancelled(self) -> None:
+ ready = Deployment.objects.create(
+ project=self.deployment_project,
+ team_id=self.team.id,
+ status=Deployment.Status.READY.value,
+ )
+ Deployment.objects.create(
+ project=self.deployment_project,
+ team_id=self.team.id,
+ status=Deployment.Status.CANCELLED.value,
+ )
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/deployment_projects/{self.deployment_project.id}/deployments/"
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ ids = [d["id"] for d in response.json()["results"]]
+ self.assertEqual(ids, [str(ready.id)])
+
+ def test_list_with_explicit_status_filter_reveals_cancelled(self) -> None:
+ cancelled = Deployment.objects.create(
+ project=self.deployment_project,
+ team_id=self.team.id,
+ status=Deployment.Status.CANCELLED.value,
+ )
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/deployment_projects/{self.deployment_project.id}/deployments/?status=cancelled"
+ )
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ ids = [d["id"] for d in response.json()["results"]]
+ self.assertEqual(ids, [str(cancelled.id)])
+
+ def test_is_current_annotated_against_project_pointer(self) -> None:
+ deployment = Deployment.objects.create(
+ project=self.deployment_project,
+ team_id=self.team.id,
+ status=Deployment.Status.READY.value,
+ )
+ self.deployment_project.current_deployment = deployment
+ self.deployment_project.save(update_fields=["current_deployment"])
+
+ response = self.client.get(
+ f"/api/projects/{self.team.id}/deployment_projects/{self.deployment_project.id}/deployments/"
+ )
+ body = response.json()["results"][0]
+ self.assertTrue(body["is_current"])
+
+ def test_action_endpoint_refuses_cross_project_deployment_id(self) -> None:
+ # Regression for the cross-project IDOR on action endpoints: a
+ # deployment belonging to project B must not be reachable via
+ # project A's URL, even within the same team.
+ other_project = DeploymentProject.objects.create(
+ team_id=self.team.id,
+ name="Other",
+ slug="other",
+ repo_url="https://github.com/example-org/other",
+ )
+ other_deployment = Deployment.objects.create(
+ project=other_project,
+ team_id=self.team.id,
+ status=Deployment.Status.READY.value,
+ commit_sha="abc1234",
+ )
+ # Hit the WRONG project's URL with the right deployment id.
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/deployment_projects/{self.deployment_project.id}/deployments/{other_deployment.id}/redeploy/"
+ )
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND, response.content)
+
+ def test_redeploy_of_cancelled_deployment_succeeds(self) -> None:
+ # Detail / action lookups must NOT inherit the list-only filters
+ # (status / author / hide-cancelled). Redeploying a cancelled row
+ # is a valid operation and the URL clearly references it.
+ cancelled = Deployment.objects.create(
+ project=self.deployment_project,
+ team_id=self.team.id,
+ status=Deployment.Status.CANCELLED.value,
+ commit_sha="abc1234",
+ )
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/deployment_projects/{self.deployment_project.id}/deployments/{cancelled.id}/redeploy/"
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
+
+
+class TestDeploymentsFeatureFlag(_BaseDeploymentsAPITest):
+ """Re-verifies the feature-flag gate over the new nested URL."""
-class TestDeploymentsAPI(APIBaseTest):
@parameterized.expand(
[
("flag on returns empty list", True, status.HTTP_200_OK),
@@ -15,27 +320,18 @@ class TestDeploymentsAPI(APIBaseTest):
]
)
def test_list_respects_feature_flag(self, _name: str, flag_enabled: bool, expected_status: int) -> None:
+ # Stop the module-wide patcher so this test can swap in its own
+ # return value.
+ self._flag_patcher.stop()
with patch(
"products.deployments.backend.access.posthoganalytics.feature_enabled",
return_value=flag_enabled,
):
- response = self.client.get(f"/api/projects/{self.team.id}/deployments/")
+ response = self.client.get(f"/api/projects/{self.team.id}/deployment_projects/")
self.assertEqual(response.status_code, expected_status)
if expected_status == status.HTTP_200_OK:
self.assertEqual(response.json()["results"], [])
-
- @parameterized.expand(
- [
- ("redeploy",),
- ("rollback",),
- ("refresh-preview",),
- ]
- )
- @patch("products.deployments.backend.access.posthoganalytics.feature_enabled", return_value=True)
- def test_stub_action_returns_501_when_flag_on(self, action: str, _mock_flag: object) -> None:
- # The stubs never call get_object, so the deployment id only has to be a
- # syntactically valid UUID — no row needs to exist for the URL to route.
- response = self.client.post(f"/api/projects/{self.team.id}/deployments/{uuid7()}/{action}/")
-
- self.assertEqual(response.status_code, status.HTTP_501_NOT_IMPLEMENTED)
+ # Re-start the cleanup-registered patcher so addCleanup's stop() is
+ # safe (re-stop is fine since `stop` is idempotent on already-stopped).
+ self._flag_patcher.start()
diff --git a/products/deployments/backend/test/test_finalize_success.py b/products/deployments/backend/test/test_finalize_success.py
new file mode 100644
index 000000000000..af0af86b2f23
--- /dev/null
+++ b/products/deployments/backend/test/test_finalize_success.py
@@ -0,0 +1,172 @@
+"""Integration tests for finalize_success — the on-commit side effects
+that run when a deployment flips to READY.
+
+We invoke `finalize_success.execute(...)` directly rather than going
+through `update_status.execute` because the `transaction.on_commit`
+callback doesn't fire inside Django's per-test transaction. This lets
+us assert the side effects in isolation.
+"""
+
+from __future__ import annotations
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.utils import timezone
+
+from posthog.models.annotation import Annotation
+
+from products.deployments.backend.models import Deployment, DeploymentEvent, DeploymentProject
+from products.deployments.backend.services import finalize_success
+from products.deployments.backend.test._helpers import DeploymentsTeamScopedTestMixin
+from products.error_tracking.backend.models import ErrorTrackingRelease
+
+
+class TestFinalizeSuccess(DeploymentsTeamScopedTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.deployment_project = DeploymentProject.objects.create(
+ team_id=self.team.id,
+ name="Site",
+ slug="site",
+ repo_url="https://github.com/example-org/site",
+ cloudflare_project_name=f"{self.team.id}-site",
+ subdomain="site.posthog-app.com",
+ cloudflare_ready_at=timezone.now(),
+ )
+ self.deployment = Deployment.objects.create(
+ project=self.deployment_project,
+ team_id=self.team.id,
+ status=Deployment.Status.READY.value,
+ commit_sha="abcdef1234567890abcdef1234567890abcdef12",
+ commit_message="feat: ship the new pricing page",
+ commit_author_name="Alice",
+ commit_author_email="[email protected]",
+ branch="main",
+ deployment_url="https://abcdef0.site.posthog-app.com",
+ started_at=timezone.now(),
+ finished_at=timezone.now(),
+ )
+
+ def _execute(self, *, screenshot=None) -> None:
+ # Mock ph_scoped_capture — we test that it's called with the right
+ # event/properties, but we don't want it to actually call out.
+ with patch("products.deployments.backend.services.finalize_success.ph_scoped_capture") as mock_capture_cm:
+ mock_capture = MagicMock()
+ mock_capture_cm.return_value.__enter__.return_value = mock_capture
+ finalize_success.execute(
+ deployment_id=self.deployment.pk,
+ screenshot=screenshot,
+ )
+ self._mock_capture = mock_capture
+ self._mock_capture_cm = mock_capture_cm
+
+ def test_creates_project_annotation_with_github_creation_type(self) -> None:
+ screenshot = MagicMock()
+ screenshot.capture.return_value = None
+ self._execute(screenshot=screenshot)
+
+ annotations = Annotation.objects.filter(team_id=self.team.id)
+ self.assertEqual(annotations.count(), 1)
+ annotation = annotations.first()
+ assert annotation is not None
+ self.assertEqual(annotation.scope, Annotation.Scope.PROJECT)
+ self.assertEqual(annotation.creation_type, Annotation.CreationType.GITHUB)
+ self.assertEqual(annotation.organization_id, self.organization.id)
+ # Content: first 80 chars of message + (sha7)
+ self.assertIn("feat: ship the new pricing page", annotation.content or "")
+ self.assertIn("abcdef1", annotation.content or "")
+
+ def test_creates_error_tracking_release_with_deployment_id_hash(self) -> None:
+ screenshot = MagicMock()
+ screenshot.capture.return_value = None
+ self._execute(screenshot=screenshot)
+
+ releases = ErrorTrackingRelease.objects.filter(team_id=self.team.id)
+ self.assertEqual(releases.count(), 1)
+ release = releases.first()
+ assert release is not None
+ self.assertEqual(release.hash_id, str(self.deployment.id))
+ self.assertEqual(release.version, "abcdef1")
+ self.assertEqual(release.project, self.deployment_project.cloudflare_project_name)
+
+ def test_emits_deployment_event_via_ph_scoped_capture(self) -> None:
+ screenshot = MagicMock()
+ screenshot.capture.return_value = None
+ self._execute(screenshot=screenshot)
+
+ self._mock_capture.assert_called_once()
+ call_args = self._mock_capture.call_args
+ self.assertEqual(call_args.kwargs["event"], "$deployment")
+ properties = call_args.kwargs["properties"]
+ self.assertEqual(properties["deployment_id"], str(self.deployment.id))
+ self.assertEqual(properties["commit_sha"], self.deployment.commit_sha)
+ self.assertEqual(properties["deployment_url"], self.deployment.deployment_url)
+
+ def test_screenshot_success_persists_preview_url(self) -> None:
+ screenshot = MagicMock()
+ screenshot.capture.return_value = "https://cdn.example/preview.png"
+ self._execute(screenshot=screenshot)
+
+ self.deployment.refresh_from_db(fields=["preview_image_url"])
+ self.assertEqual(self.deployment.preview_image_url, "https://cdn.example/preview.png")
+
+ events = DeploymentEvent.objects.filter(deployment_id=self.deployment.pk, event_type="preview_captured")
+ self.assertEqual(events.count(), 1)
+
+ def test_screenshot_failure_emits_failed_event_but_does_not_block(self) -> None:
+ screenshot = MagicMock()
+ screenshot.capture.return_value = None
+ self._execute(screenshot=screenshot)
+
+ # Status stayed READY — failure didn't roll back.
+ self.deployment.refresh_from_db()
+ self.assertEqual(self.deployment.status, Deployment.Status.READY.value)
+ self.assertEqual(self.deployment.preview_image_url, "")
+
+ events = DeploymentEvent.objects.filter(deployment_id=self.deployment.pk, event_type="preview_capture_failed")
+ self.assertEqual(events.count(), 1)
+
+ def test_idempotent_release_creation(self) -> None:
+ # Running finalize twice should not create a second release row —
+ # the internal endpoint must be safe against Temporal's at-least-once
+ # delivery semantics.
+ screenshot = MagicMock()
+ screenshot.capture.return_value = None
+ self._execute(screenshot=screenshot)
+ self._execute(screenshot=screenshot)
+
+ releases = ErrorTrackingRelease.objects.filter(team_id=self.team.id, hash_id=str(self.deployment.id))
+ self.assertEqual(releases.count(), 1)
+
+ def test_runs_without_outer_team_scope(self) -> None:
+ # Regression: in production the `transaction.on_commit` callback
+ # fires AFTER the request transaction commits and AFTER the
+ # request's team scope has been reset. finalize_success.execute
+ # must enter scope itself, otherwise every successful deploy
+ # crashes with TeamScopeError.
+ from posthog.models.scoping import _current_team_id
+
+ screenshot = MagicMock()
+ screenshot.capture.return_value = "https://cdn.example/preview.png"
+
+ # Reset the outer scope set by DeploymentsTeamScopedTestMixin —
+ # mimic the production on_commit path where no scope is active.
+ token = _current_team_id.set(None)
+ try:
+ with patch("products.deployments.backend.services.finalize_success.ph_scoped_capture") as cap:
+ cap.return_value.__enter__.return_value = MagicMock()
+ finalize_success.execute(
+ deployment_id=self.deployment.pk,
+ screenshot=screenshot,
+ )
+ finally:
+ _current_team_id.reset(token)
+
+ # Both scoped writes should have succeeded under the in-function scope.
+ self.deployment.refresh_from_db(fields=["preview_image_url"])
+ self.assertEqual(self.deployment.preview_image_url, "https://cdn.example/preview.png")
+ self.assertEqual(
+ DeploymentEvent.all_teams.filter(deployment_id=self.deployment.pk).count(),
+ 1,
+ )
diff --git a/products/deployments/backend/test/test_internal_auth.py b/products/deployments/backend/test/test_internal_auth.py
new file mode 100644
index 000000000000..f15ce06027bd
--- /dev/null
+++ b/products/deployments/backend/test/test_internal_auth.py
@@ -0,0 +1,147 @@
+"""End-to-end tests for the internal `/api/internal/deployments/*` endpoints.
+
+These exercise the URL → InternalAPIAuthentication →
+InternalDeploymentTransitionsViewSet → service path. Auth is verified
+both negative (missing/wrong header) and positive (correct secret).
+"""
+
+from __future__ import annotations
+
+from posthog.test.base import APIBaseTest
+
+from django.http import HttpResponse
+from django.test import override_settings
+from django.utils import timezone
+
+from rest_framework import status as drf_status
+
+from products.deployments.backend.domain.status import Status
+from products.deployments.backend.models import Deployment, DeploymentEvent, DeploymentProject
+from products.deployments.backend.test._helpers import DeploymentsTeamScopedTestMixin
+
+SECRET = "test-internal-secret-abc123"
+
+
+@override_settings(INTERNAL_API_SECRET=SECRET)
+class TestInternalDeploymentTransitions(DeploymentsTeamScopedTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.deployment_project = DeploymentProject.objects.create(
+ team_id=self.team.id,
+ name="Site",
+ slug="site",
+ repo_url="https://github.com/example-org/site",
+ cloudflare_project_name=f"{self.team.id}-site",
+ subdomain="site.posthog-app.com",
+ cloudflare_ready_at=timezone.now(),
+ )
+ self.deployment = Deployment.objects.create(
+ project=self.deployment_project,
+ team_id=self.team.id,
+ status=Deployment.Status.QUEUED.value,
+ commit_sha="abc1234",
+ )
+
+ def _post_transition(self, body: dict, *, secret: str | None = SECRET) -> HttpResponse:
+ headers: dict = {}
+ if secret is not None:
+ headers["x-internal-api-secret"] = secret
+ return self.client.post(
+ f"/api/internal/deployments/{self.deployment.id}/transitions/",
+ body,
+ format="json",
+ headers=headers,
+ )
+
+ def test_valid_secret_walks_state_machine(self) -> None:
+ response = self._post_transition({"status": Status.INITIALIZING.value})
+ self.assertEqual(response.status_code, drf_status.HTTP_200_OK)
+ self.deployment.refresh_from_db()
+ self.assertEqual(self.deployment.status, Deployment.Status.INITIALIZING.value)
+ self.assertIsNotNone(self.deployment.started_at)
+
+ def test_missing_secret_returns_401(self) -> None:
+ response = self._post_transition({"status": Status.INITIALIZING.value}, secret=None)
+ self.assertEqual(response.status_code, drf_status.HTTP_401_UNAUTHORIZED)
+
+ def test_wrong_secret_returns_401(self) -> None:
+ response = self._post_transition({"status": Status.INITIALIZING.value}, secret="wrong-secret")
+ self.assertEqual(response.status_code, drf_status.HTTP_401_UNAUTHORIZED)
+
+ def test_invalid_transition_returns_409(self) -> None:
+ # queued → ready is not a valid edge.
+ response = self._post_transition({"status": Status.READY.value})
+ self.assertEqual(response.status_code, drf_status.HTTP_409_CONFLICT)
+
+ def test_idempotent_terminal_callback_is_noop(self) -> None:
+ Deployment.objects.filter(pk=self.deployment.pk).update(status=Deployment.Status.READY.value)
+ response = self._post_transition(
+ {"status": Status.READY.value, "deployment_url": "https://site.posthog-app.com"}
+ )
+ self.assertEqual(response.status_code, drf_status.HTTP_200_OK)
+
+ def test_unknown_deployment_returns_404(self) -> None:
+ from uuid import uuid4
+
+ response = self.client.post(
+ f"/api/internal/deployments/{uuid4()}/transitions/",
+ {"status": Status.INITIALIZING.value},
+ format="json",
+ headers={"x-internal-api-secret": SECRET},
+ )
+ self.assertEqual(response.status_code, drf_status.HTTP_404_NOT_FOUND)
+
+ def test_ready_transition_flips_project_current_deployment(self) -> None:
+ # queued → initializing → building → ready
+ for s in (Status.INITIALIZING, Status.BUILDING, Status.READY):
+ response = self._post_transition({"status": s.value})
+ self.assertEqual(response.status_code, drf_status.HTTP_200_OK, response.content)
+
+ self.deployment_project.refresh_from_db(fields=["current_deployment"])
+ self.assertEqual(self.deployment_project.current_deployment_id, self.deployment.pk)
+
+ def test_unknown_status_value_returns_400(self) -> None:
+ response = self._post_transition({"status": "frobnicated"})
+ self.assertEqual(response.status_code, drf_status.HTTP_400_BAD_REQUEST)
+
+
+@override_settings(INTERNAL_API_SECRET=SECRET)
+class TestInternalDeploymentEvents(DeploymentsTeamScopedTestMixin, APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.deployment_project = DeploymentProject.objects.create(
+ team_id=self.team.id,
+ name="Site",
+ slug="site",
+ repo_url="https://github.com/example-org/site",
+ )
+ self.deployment = Deployment.objects.create(
+ project=self.deployment_project,
+ team_id=self.team.id,
+ status=Deployment.Status.BUILDING.value,
+ )
+
+ def test_creates_event_with_team_id_resolved_from_deployment(self) -> None:
+ response = self.client.post(
+ f"/api/internal/deployments/{self.deployment.id}/events/",
+ {"event_type": "step_started", "payload": {"step": "install"}},
+ format="json",
+ headers={"x-internal-api-secret": SECRET},
+ )
+ self.assertEqual(response.status_code, drf_status.HTTP_202_ACCEPTED, response.content)
+
+ events = DeploymentEvent.objects.filter(deployment_id=self.deployment.pk)
+ self.assertEqual(events.count(), 1)
+ event = events.first()
+ assert event is not None
+ self.assertEqual(event.event_type, "step_started")
+ self.assertEqual(event.payload, {"step": "install"})
+ self.assertEqual(event.team_id, self.team.id)
+
+ def test_missing_secret_returns_401(self) -> None:
+ response = self.client.post(
+ f"/api/internal/deployments/{self.deployment.id}/events/",
+ {"event_type": "step_started", "payload": {}},
+ format="json",
+ )
+ self.assertEqual(response.status_code, drf_status.HTTP_401_UNAUTHORIZED)
diff --git a/products/deployments/backend/test/test_models.py b/products/deployments/backend/test/test_models.py
new file mode 100644
index 000000000000..26fae3b10955
--- /dev/null
+++ b/products/deployments/backend/test/test_models.py
@@ -0,0 +1,133 @@
+"""DB-integration tests for the Deployments models.
+
+Focus on invariants the migration adds: the partial unique constraint
+that enforces "one active deploy per project", the soft-delete-aware
+slug uniqueness on DeploymentProject, and the `current_deployment`
+pointer's null-safety.
+"""
+
+from __future__ import annotations
+
+from posthog.test.base import BaseTest
+
+from django.db import IntegrityError, transaction
+from django.utils import timezone
+
+from products.deployments.backend.models import Deployment, DeploymentEvent, DeploymentProject
+from products.deployments.backend.test._helpers import DeploymentsTeamScopedTestMixin
+
+
+class TestDeploymentProject(DeploymentsTeamScopedTestMixin, BaseTest):
+ def _make_project(self, slug: str = "alpha") -> DeploymentProject:
+ return DeploymentProject.objects.create(
+ team_id=self.team.id,
+ name=f"Project {slug}",
+ slug=slug,
+ repo_url="https://github.com/example-org/site",
+ default_branch="main",
+ cloudflare_project_name=f"{self.team.id}-{slug}",
+ subdomain=f"{slug}.posthog-app.com",
+ cloudflare_ready_at=timezone.now(),
+ )
+
+ def test_slug_uniqueness_per_team(self) -> None:
+ self._make_project(slug="alpha")
+ with self.assertRaises(IntegrityError):
+ with transaction.atomic():
+ self._make_project(slug="alpha")
+
+ def test_soft_deleted_project_releases_slug(self) -> None:
+ original = self._make_project(slug="alpha")
+ original.deleted = True
+ original.deleted_at = timezone.now()
+ original.save(update_fields=["deleted", "deleted_at"])
+
+ # The partial unique constraint excludes soft-deleted rows so the
+ # slug can be reused.
+ reused = self._make_project(slug="alpha")
+ self.assertNotEqual(reused.pk, original.pk)
+
+ def test_current_deployment_accepts_null(self) -> None:
+ project = self._make_project()
+ self.assertIsNone(project.current_deployment_id)
+
+ def test_current_deployment_set_null_on_target_delete(self) -> None:
+ project = self._make_project()
+ deployment = Deployment.objects.create(
+ project=project,
+ team_id=self.team.id,
+ status=Deployment.Status.READY.value,
+ commit_sha="abcdef0123456789",
+ )
+ project.current_deployment = deployment
+ project.save(update_fields=["current_deployment"])
+
+ deployment.delete()
+ project.refresh_from_db(fields=["current_deployment"])
+ self.assertIsNone(project.current_deployment_id)
+
+
+class TestDeploymentActiveConstraint(DeploymentsTeamScopedTestMixin, BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.deployment_project = DeploymentProject.objects.create(
+ team_id=self.team.id,
+ name="Site",
+ slug="site",
+ repo_url="https://github.com/example-org/site",
+ cloudflare_project_name=f"{self.team.id}-site",
+ subdomain="site.posthog-app.com",
+ cloudflare_ready_at=timezone.now(),
+ )
+
+ def _make_deployment(self, status: Deployment.Status) -> Deployment:
+ return Deployment.objects.create(
+ project=self.deployment_project,
+ team_id=self.team.id,
+ status=status.value,
+ commit_sha="a" * 40,
+ )
+
+ def test_second_non_terminal_deployment_raises(self) -> None:
+ self._make_deployment(Deployment.Status.QUEUED)
+ with self.assertRaises(IntegrityError):
+ with transaction.atomic():
+ self._make_deployment(Deployment.Status.BUILDING)
+
+ def test_terminal_then_non_terminal_is_allowed(self) -> None:
+ self._make_deployment(Deployment.Status.READY)
+ # No exception expected — the terminal row doesn't count against
+ # the partial unique constraint.
+ self._make_deployment(Deployment.Status.QUEUED)
+
+ def test_multiple_terminals_allowed(self) -> None:
+ # Most projects accumulate many terminal-status deployments over
+ # their lifetime — the constraint must not block this.
+ for _ in range(5):
+ self._make_deployment(Deployment.Status.READY)
+
+
+class TestDeploymentEvent(DeploymentsTeamScopedTestMixin, BaseTest):
+ def test_event_is_team_scoped(self) -> None:
+ project = DeploymentProject.objects.create(
+ team_id=self.team.id,
+ name="P",
+ slug="p",
+ repo_url="https://github.com/example-org/p",
+ )
+ deployment = Deployment.objects.create(
+ project=project,
+ team_id=self.team.id,
+ status=Deployment.Status.READY.value,
+ )
+ event = DeploymentEvent.objects.create(
+ deployment=deployment,
+ team_id=self.team.id,
+ event_type="status_changed",
+ payload={"from": "building", "to": "ready"},
+ )
+
+ fetched = DeploymentEvent.objects.get(pk=event.pk)
+ self.assertEqual(fetched.team_id, self.team.id)
+ self.assertEqual(fetched.deployment_id, deployment.pk)
+ self.assertEqual(fetched.payload["to"], "ready")
diff --git a/products/deployments/backend/test/test_seed_command.py b/products/deployments/backend/test/test_seed_command.py
new file mode 100644
index 000000000000..ab169ea86135
--- /dev/null
+++ b/products/deployments/backend/test/test_seed_command.py
@@ -0,0 +1,45 @@
+"""Regression tests for the `seed_deployments` management command.
+
+Catches the C3 finding from CODE_REVIEW.md: the seeder mixes SEED and
+REDEPLOY trigger kinds, so a `trigger_kind=SEED`-only clear would leak
+REDEPLOY rows across runs.
+"""
+
+from __future__ import annotations
+
+from io import StringIO
+
+from posthog.test.base import APIBaseTest
+
+from django.core.management import call_command
+
+from products.deployments.backend.models import Deployment, DeploymentProject
+from products.deployments.backend.test._helpers import DeploymentsTeamScopedTestMixin
+
+
+class TestSeedDeployments(DeploymentsTeamScopedTestMixin, APIBaseTest):
+ def test_idempotent_across_runs(self) -> None:
+ out = StringIO()
+ call_command(
+ "seed_deployments",
+ team_id=self.team.id,
+ project_count=1,
+ deployments_per_project=15,
+ seed=42,
+ stdout=out,
+ )
+ project = DeploymentProject.objects.get(slug="marketing-site")
+ first_count = Deployment.objects.filter(project=project).count()
+ self.assertEqual(first_count, 15)
+
+ # Re-run with the same args — counts should not drift.
+ call_command(
+ "seed_deployments",
+ team_id=self.team.id,
+ project_count=1,
+ deployments_per_project=15,
+ seed=42,
+ stdout=out,
+ )
+ second_count = Deployment.objects.filter(project=project).count()
+ self.assertEqual(second_count, first_count)
diff --git a/products/deployments/backend/test/test_services.py b/products/deployments/backend/test/test_services.py
new file mode 100644
index 000000000000..c8104b8e9569
--- /dev/null
+++ b/products/deployments/backend/test/test_services.py
@@ -0,0 +1,448 @@
+"""Service-layer tests with stubbed adapters.
+
+Each service exposes `execute(...)` and accepts adapter overrides as
+keyword args so tests can substitute fakes without monkeypatching. We
+verify the orchestration around the ORM and the on_commit side-effect
+scheduling — finalize_success / finalize_failure themselves are tested
+separately under test_finalize_success.py.
+"""
+
+from __future__ import annotations
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock
+
+from django.utils import timezone
+
+from products.deployments.backend.adapters import NullCloudflareAdapter
+from products.deployments.backend.adapters.github import NullGitHubAdapter
+from products.deployments.backend.adapters.temporal import NullWorkflowAdapter
+from products.deployments.backend.domain.status import Status
+from products.deployments.backend.domain.trigger import ErrorStep, TriggerKind
+from products.deployments.backend.models import Deployment, DeploymentEvent, DeploymentProject
+from products.deployments.backend.services import (
+ cancel,
+ create_deployment,
+ redeploy,
+ refresh_preview,
+ rollback,
+ update_status,
+)
+from products.deployments.backend.test._helpers import DeploymentsTeamScopedTestMixin
+
+
+class _BaseServicesTest(DeploymentsTeamScopedTestMixin, BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.deployment_project = DeploymentProject.objects.create(
+ team_id=self.team.id,
+ name="Site",
+ slug="site",
+ repo_url="https://github.com/example-org/site",
+ default_branch="main",
+ cloudflare_project_name=f"{self.team.id}-site",
+ subdomain="site.posthog-app.com",
+ cloudflare_ready_at=timezone.now(),
+ )
+
+
+class TestCreateDeployment(_BaseServicesTest):
+ def test_creates_row_and_persists_workflow_handle(self) -> None:
+ deployment = create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=str(self.deployment_project.id),
+ team_id=self.team.id,
+ triggered_by_user_id=self.user.id,
+ trigger_kind=TriggerKind.MANUAL,
+ commit_sha=None,
+ branch=None,
+ ),
+ cloudflare=NullCloudflareAdapter(),
+ github=NullGitHubAdapter(),
+ workflow=NullWorkflowAdapter(),
+ )
+ self.assertEqual(deployment.status, Deployment.Status.QUEUED.value)
+ self.assertEqual(deployment.project_id, self.deployment_project.id)
+ self.assertEqual(deployment.team_id, self.team.id)
+ self.assertEqual(deployment.trigger_kind, TriggerKind.MANUAL.value)
+ # NullWorkflowAdapter assigns `deployment-{id}` as workflow_id —
+ # the row must round-trip it after the post-insert update().
+ self.assertTrue(deployment.temporal_workflow_id.startswith("deployment-"))
+ self.assertTrue(deployment.temporal_run_id)
+
+ def test_second_concurrent_create_raises_active_deployment_exists(self) -> None:
+ first = create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=str(self.deployment_project.id),
+ team_id=self.team.id,
+ triggered_by_user_id=self.user.id,
+ trigger_kind=TriggerKind.MANUAL,
+ commit_sha=None,
+ branch=None,
+ ),
+ cloudflare=NullCloudflareAdapter(),
+ github=NullGitHubAdapter(),
+ workflow=NullWorkflowAdapter(),
+ )
+ with self.assertRaises(create_deployment.ActiveDeploymentExists) as cm:
+ create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=str(self.deployment_project.id),
+ team_id=self.team.id,
+ triggered_by_user_id=self.user.id,
+ trigger_kind=TriggerKind.MANUAL,
+ commit_sha=None,
+ branch=None,
+ ),
+ cloudflare=NullCloudflareAdapter(),
+ github=NullGitHubAdapter(),
+ workflow=NullWorkflowAdapter(),
+ )
+ self.assertEqual(cm.exception.active_deployment_id, str(first.id))
+
+ def test_workflow_dispatch_failure_marks_row_error(self) -> None:
+ # Regression: if start_build raises (Temporal unreachable), the
+ # row must NOT be left in QUEUED with no workflow id — it has to
+ # be flipped to ERROR(error_step=dispatch) and the caller gets a
+ # typed WorkflowDispatchFailed they can map to 502.
+ workflow = MagicMock()
+ workflow.start_build.side_effect = RuntimeError("temporal is down")
+ with self.assertRaises(create_deployment.WorkflowDispatchFailed) as cm:
+ create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=str(self.deployment_project.id),
+ team_id=self.team.id,
+ triggered_by_user_id=self.user.id,
+ trigger_kind=TriggerKind.MANUAL,
+ commit_sha=None,
+ branch=None,
+ ),
+ cloudflare=NullCloudflareAdapter(),
+ github=NullGitHubAdapter(),
+ workflow=workflow,
+ )
+ # The orphan deployment id is surfaced for operators.
+ self.assertTrue(cm.exception.deployment_id)
+ orphan = Deployment.objects.get(pk=cm.exception.deployment_id)
+ self.assertEqual(orphan.status, Deployment.Status.ERROR.value)
+ self.assertEqual(orphan.error_step, "dispatch")
+ self.assertIn("temporal is down", orphan.error_message)
+ self.assertIsNotNone(orphan.finished_at)
+
+ def test_terminal_deployment_does_not_block_new_one(self) -> None:
+ first = create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=str(self.deployment_project.id),
+ team_id=self.team.id,
+ triggered_by_user_id=self.user.id,
+ trigger_kind=TriggerKind.MANUAL,
+ commit_sha=None,
+ branch=None,
+ ),
+ cloudflare=NullCloudflareAdapter(),
+ github=NullGitHubAdapter(),
+ workflow=NullWorkflowAdapter(),
+ )
+ # Park the first row in a terminal state.
+ Deployment.objects.filter(pk=first.pk).update(status=Deployment.Status.ERROR.value)
+ second = create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=str(self.deployment_project.id),
+ team_id=self.team.id,
+ triggered_by_user_id=self.user.id,
+ trigger_kind=TriggerKind.MANUAL,
+ commit_sha=None,
+ branch=None,
+ ),
+ cloudflare=NullCloudflareAdapter(),
+ github=NullGitHubAdapter(),
+ workflow=NullWorkflowAdapter(),
+ )
+ self.assertNotEqual(second.pk, first.pk)
+ self.assertEqual(second.status, Deployment.Status.QUEUED.value)
+
+
+class TestUpdateStatus(_BaseServicesTest):
+ def _make_queued(self) -> Deployment:
+ return create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=str(self.deployment_project.id),
+ team_id=self.team.id,
+ triggered_by_user_id=self.user.id,
+ trigger_kind=TriggerKind.MANUAL,
+ commit_sha=None,
+ branch=None,
+ ),
+ cloudflare=NullCloudflareAdapter(),
+ github=NullGitHubAdapter(),
+ workflow=NullWorkflowAdapter(),
+ )
+
+ def test_walks_the_happy_path(self) -> None:
+ deployment = self._make_queued()
+ update_status.execute(update_status.UpdateStatusInput(deployment_id=deployment.id, status=Status.INITIALIZING))
+ deployment.refresh_from_db()
+ self.assertEqual(deployment.status, Deployment.Status.INITIALIZING.value)
+ self.assertIsNotNone(deployment.started_at)
+
+ update_status.execute(update_status.UpdateStatusInput(deployment_id=deployment.id, status=Status.BUILDING))
+ deployment.refresh_from_db()
+ self.assertEqual(deployment.status, Deployment.Status.BUILDING.value)
+
+ update_status.execute(
+ update_status.UpdateStatusInput(
+ deployment_id=deployment.id,
+ status=Status.READY,
+ deployment_url="https://abcdef.site.posthog-app.com",
+ cloudflare_deployment_id="cf-abcdef",
+ )
+ )
+ deployment.refresh_from_db()
+ self.assertEqual(deployment.status, Deployment.Status.READY.value)
+ self.assertEqual(deployment.deployment_url, "https://abcdef.site.posthog-app.com")
+ self.assertEqual(deployment.cloudflare_deployment_id, "cf-abcdef")
+ self.assertIsNotNone(deployment.finished_at)
+
+ # On READY, project.current_deployment must flip to this row.
+ self.deployment_project.refresh_from_db(fields=["current_deployment"])
+ self.assertEqual(self.deployment_project.current_deployment_id, deployment.pk)
+
+ def test_duplicate_terminal_callback_is_noop(self) -> None:
+ deployment = self._make_queued()
+ update_status.execute(update_status.UpdateStatusInput(deployment_id=deployment.id, status=Status.INITIALIZING))
+ update_status.execute(update_status.UpdateStatusInput(deployment_id=deployment.id, status=Status.BUILDING))
+ update_status.execute(update_status.UpdateStatusInput(deployment_id=deployment.id, status=Status.READY))
+
+ deployment.refresh_from_db()
+ first_finished_at = deployment.finished_at
+
+ # Second `ready` callback — should be a quiet no-op, not raise.
+ update_status.execute(update_status.UpdateStatusInput(deployment_id=deployment.id, status=Status.READY))
+ deployment.refresh_from_db()
+ self.assertEqual(deployment.status, Deployment.Status.READY.value)
+ self.assertEqual(deployment.finished_at, first_finished_at)
+
+ def test_invalid_transition_raises(self) -> None:
+ from products.deployments.backend.domain.status import InvalidStatusTransition
+
+ deployment = self._make_queued()
+ # queued → ready is not a valid edge in the graph.
+ with self.assertRaises(InvalidStatusTransition):
+ update_status.execute(update_status.UpdateStatusInput(deployment_id=deployment.id, status=Status.READY))
+
+ def test_error_step_recorded(self) -> None:
+ deployment = self._make_queued()
+ update_status.execute(update_status.UpdateStatusInput(deployment_id=deployment.id, status=Status.INITIALIZING))
+ update_status.execute(
+ update_status.UpdateStatusInput(
+ deployment_id=deployment.id,
+ status=Status.ERROR,
+ error_message="Build exploded",
+ error_step=ErrorStep.BUILD,
+ )
+ )
+ deployment.refresh_from_db()
+ self.assertEqual(deployment.status, Deployment.Status.ERROR.value)
+ self.assertEqual(deployment.error_step, ErrorStep.BUILD.value)
+ self.assertEqual(deployment.error_message, "Build exploded")
+
+
+class TestRollback(_BaseServicesTest):
+ def test_creates_new_row_with_rollback_kind_and_lineage(self) -> None:
+ original = create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=str(self.deployment_project.id),
+ team_id=self.team.id,
+ triggered_by_user_id=self.user.id,
+ trigger_kind=TriggerKind.MANUAL,
+ commit_sha="abc1234567890abcdef0",
+ branch=None,
+ ),
+ cloudflare=NullCloudflareAdapter(),
+ github=NullGitHubAdapter(),
+ workflow=NullWorkflowAdapter(),
+ )
+ Deployment.objects.filter(pk=original.pk).update(status=Deployment.Status.READY.value)
+
+ rolled_back = rollback.execute(
+ deployment_id=str(original.id),
+ team_id=self.team.id,
+ triggered_by_user_id=self.user.id,
+ cloudflare=NullCloudflareAdapter(),
+ github=NullGitHubAdapter(),
+ workflow=NullWorkflowAdapter(),
+ )
+ self.assertEqual(rolled_back.trigger_kind, TriggerKind.ROLLBACK.value)
+ self.assertEqual(rolled_back.triggered_by_deployment_id, original.pk)
+ self.assertEqual(rolled_back.commit_sha, original.commit_sha)
+
+
+class TestRedeploy(_BaseServicesTest):
+ def test_redeploy_clones_commit(self) -> None:
+ original = create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=str(self.deployment_project.id),
+ team_id=self.team.id,
+ triggered_by_user_id=self.user.id,
+ trigger_kind=TriggerKind.MANUAL,
+ commit_sha="deadbeef1234567890ab",
+ branch="release",
+ ),
+ cloudflare=NullCloudflareAdapter(),
+ github=NullGitHubAdapter(),
+ workflow=NullWorkflowAdapter(),
+ )
+ Deployment.objects.filter(pk=original.pk).update(status=Deployment.Status.READY.value)
+
+ new = redeploy.execute(
+ deployment_id=str(original.id),
+ team_id=self.team.id,
+ triggered_by_user_id=self.user.id,
+ cloudflare=NullCloudflareAdapter(),
+ github=NullGitHubAdapter(),
+ workflow=NullWorkflowAdapter(),
+ )
+ self.assertEqual(new.trigger_kind, TriggerKind.REDEPLOY.value)
+ self.assertEqual(new.triggered_by_deployment_id, original.pk)
+ self.assertEqual(new.commit_sha, original.commit_sha)
+
+
+class TestCancel(_BaseServicesTest):
+ def test_cancel_signals_workflow(self) -> None:
+ deployment = create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=str(self.deployment_project.id),
+ team_id=self.team.id,
+ triggered_by_user_id=self.user.id,
+ trigger_kind=TriggerKind.MANUAL,
+ commit_sha=None,
+ branch=None,
+ ),
+ cloudflare=NullCloudflareAdapter(),
+ github=NullGitHubAdapter(),
+ workflow=NullWorkflowAdapter(),
+ )
+ workflow = MagicMock()
+ signalled = cancel.execute(
+ deployment_id=str(deployment.id),
+ team_id=self.team.id,
+ workflow=workflow,
+ )
+ workflow.signal_cancel.assert_called_once_with(workflow_id=deployment.temporal_workflow_id)
+ self.assertTrue(signalled)
+
+ def test_cancel_without_workflow_id_flips_row_directly(self) -> None:
+ # Orphan case: the row never got a temporal_workflow_id (e.g.
+ # start_build crashed mid-dispatch). cancel must NOT silently no-op
+ # — it should walk the state machine to CANCELLED so the row
+ # doesn't sit QUEUED forever.
+ deployment = create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=str(self.deployment_project.id),
+ team_id=self.team.id,
+ triggered_by_user_id=self.user.id,
+ trigger_kind=TriggerKind.MANUAL,
+ commit_sha=None,
+ branch=None,
+ ),
+ cloudflare=NullCloudflareAdapter(),
+ github=NullGitHubAdapter(),
+ workflow=NullWorkflowAdapter(),
+ )
+ Deployment.objects.filter(pk=deployment.pk).update(temporal_workflow_id="")
+ workflow = MagicMock()
+ signalled = cancel.execute(
+ deployment_id=str(deployment.id),
+ team_id=self.team.id,
+ workflow=workflow,
+ )
+ workflow.signal_cancel.assert_not_called()
+ self.assertFalse(signalled)
+ deployment.refresh_from_db()
+ self.assertEqual(deployment.status, Deployment.Status.CANCELLED.value)
+
+ def test_cancel_terminal_deployment_raises(self) -> None:
+ deployment = create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=str(self.deployment_project.id),
+ team_id=self.team.id,
+ triggered_by_user_id=self.user.id,
+ trigger_kind=TriggerKind.MANUAL,
+ commit_sha=None,
+ branch=None,
+ ),
+ cloudflare=NullCloudflareAdapter(),
+ github=NullGitHubAdapter(),
+ workflow=NullWorkflowAdapter(),
+ )
+ Deployment.objects.filter(pk=deployment.pk).update(status=Deployment.Status.READY.value)
+ with self.assertRaises(cancel.DeploymentNotCancellable):
+ cancel.execute(
+ deployment_id=str(deployment.id),
+ team_id=self.team.id,
+ workflow=MagicMock(),
+ )
+
+
+class TestRefreshPreview(_BaseServicesTest):
+ def test_capture_success_writes_image_url_and_event(self) -> None:
+ deployment = create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=str(self.deployment_project.id),
+ team_id=self.team.id,
+ triggered_by_user_id=self.user.id,
+ trigger_kind=TriggerKind.MANUAL,
+ commit_sha=None,
+ branch=None,
+ ),
+ cloudflare=NullCloudflareAdapter(),
+ github=NullGitHubAdapter(),
+ workflow=NullWorkflowAdapter(),
+ )
+ Deployment.objects.filter(pk=deployment.pk).update(
+ status=Deployment.Status.READY.value,
+ deployment_url="https://site.posthog-app.com",
+ )
+
+ screenshot = MagicMock()
+ screenshot.capture.return_value = "https://cdn.example/preview.png"
+
+ updated = refresh_preview.execute(
+ deployment_id=str(deployment.id),
+ team_id=self.team.id,
+ screenshot=screenshot,
+ )
+ self.assertEqual(updated.preview_image_url, "https://cdn.example/preview.png")
+
+ events = list(DeploymentEvent.objects.filter(deployment_id=deployment.pk).values_list("event_type", flat=True))
+ self.assertIn("preview_captured", events)
+
+ def test_capture_failure_emits_failed_event(self) -> None:
+ deployment = create_deployment.execute(
+ create_deployment.CreateDeploymentInput(
+ project_id=str(self.deployment_project.id),
+ team_id=self.team.id,
+ triggered_by_user_id=self.user.id,
+ trigger_kind=TriggerKind.MANUAL,
+ commit_sha=None,
+ branch=None,
+ ),
+ cloudflare=NullCloudflareAdapter(),
+ github=NullGitHubAdapter(),
+ workflow=NullWorkflowAdapter(),
+ )
+ Deployment.objects.filter(pk=deployment.pk).update(
+ status=Deployment.Status.READY.value,
+ deployment_url="https://site.posthog-app.com",
+ )
+
+ screenshot = MagicMock()
+ screenshot.capture.return_value = None
+
+ refresh_preview.execute(
+ deployment_id=str(deployment.id),
+ team_id=self.team.id,
+ screenshot=screenshot,
+ )
+ events = list(DeploymentEvent.objects.filter(deployment_id=deployment.pk).values_list("event_type", flat=True))
+ self.assertIn("preview_capture_failed", events)
diff --git a/products/deployments/backend/test/test_state_machine.py b/products/deployments/backend/test/test_state_machine.py
new file mode 100644
index 000000000000..5c5d23116106
--- /dev/null
+++ b/products/deployments/backend/test/test_state_machine.py
@@ -0,0 +1,94 @@
+"""Pure-unit tests for the deployment status state machine.
+
+Lives outside the DB layer — exercises domain/status.py directly. The
+transition rules are the most safety-critical thing in this product
+(the internal endpoint is the only place we mutate `Deployment.status`)
+so we want exhaustive coverage with no test infra in the way.
+"""
+
+from __future__ import annotations
+
+from itertools import product
+
+from posthog.test.base import BaseTest
+
+from parameterized import parameterized
+
+from products.deployments.backend.domain.status import (
+ NON_TERMINAL_STATUSES,
+ TERMINAL_STATUSES,
+ VALID_TRANSITIONS,
+ InvalidStatusTransition,
+ Status,
+ assert_valid,
+ is_idempotent_noop,
+)
+
+_ALL_STATUSES = tuple(Status)
+
+
+class TestStateMachine(BaseTest):
+ @parameterized.expand([(c.value, t.value) for (c, t) in VALID_TRANSITIONS])
+ def test_every_valid_transition_passes_assert_valid(self, current: str, target: str) -> None:
+ # No exception raised = pass.
+ assert_valid(Status(current), Status(target))
+
+ @parameterized.expand(
+ [
+ (c.value, t.value)
+ for (c, t) in product(_ALL_STATUSES, _ALL_STATUSES)
+ if (c, t) not in VALID_TRANSITIONS and not (c == t and c in TERMINAL_STATUSES)
+ ]
+ )
+ def test_invalid_transitions_raise(self, current: str, target: str) -> None:
+ with self.assertRaises(InvalidStatusTransition):
+ assert_valid(Status(current), Status(target))
+
+ @parameterized.expand(
+ [
+ (Status.READY.value,),
+ (Status.ERROR.value,),
+ (Status.CANCELLED.value,),
+ ]
+ )
+ def test_is_idempotent_noop_for_matching_terminal(self, status: str) -> None:
+ self.assertTrue(is_idempotent_noop(Status(status), Status(status)))
+
+ @parameterized.expand(
+ [
+ (Status.QUEUED.value,),
+ (Status.INITIALIZING.value,),
+ (Status.BUILDING.value,),
+ ]
+ )
+ def test_is_idempotent_noop_false_for_non_terminal_self_loop(self, status: str) -> None:
+ # `queued → queued` is NOT an idempotent no-op — the worker should
+ # never claim it's still queued. Detect that as a programmer error.
+ self.assertFalse(is_idempotent_noop(Status(status), Status(status)))
+
+ def test_is_idempotent_noop_false_when_statuses_differ(self) -> None:
+ self.assertFalse(is_idempotent_noop(Status.READY, Status.ERROR))
+ self.assertFalse(is_idempotent_noop(Status.BUILDING, Status.READY))
+
+ def test_non_terminal_and_terminal_partition_all_statuses(self) -> None:
+ # Together they should cover the enum exactly and not overlap.
+ self.assertSetEqual(
+ set(NON_TERMINAL_STATUSES) | set(TERMINAL_STATUSES),
+ set(_ALL_STATUSES),
+ )
+ self.assertSetEqual(
+ set(NON_TERMINAL_STATUSES) & set(TERMINAL_STATUSES),
+ set(),
+ )
+
+ def test_no_transition_from_terminal_state_is_valid(self) -> None:
+ for terminal in TERMINAL_STATUSES:
+ for target in _ALL_STATUSES:
+ if terminal == target and terminal in TERMINAL_STATUSES:
+ # idempotent_noop is handled by is_idempotent_noop, not VALID_TRANSITIONS
+ continue
+ self.assertNotIn(
+ (terminal, target),
+ VALID_TRANSITIONS,
+ f"{terminal} → {target} should not be a valid transition",
+ )
diff --git a/products/deployments/frontend/deploymentsLogic.ts b/products/deployments/frontend/deploymentsLogic.ts
index eaef56746eb9..0ce6d10fe356 100644
--- a/products/deployments/frontend/deploymentsLogic.ts
+++ b/products/deployments/frontend/deploymentsLogic.ts
@@ -2,11 +2,9 @@ import { actions, afterMount, kea, key, path, props, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import { actionToUrl, urlToAction } from 'kea-router'
-import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import type { deploymentsLogicType } from './deploymentsLogicType'
-import { deploymentsList } from './generated/api'
import type { DeploymentApi } from './generated/api.schemas'
export interface DeploymentsFilters {
@@ -38,12 +36,10 @@ export const deploymentsLogic = kea<deploymentsLogicType>([
[] as DeploymentApi[],
{
loadDeployments: async () => {
- const projectId = teamLogic.values.currentTeamId
- if (!projectId) {
- return []
- }
- const response = await deploymentsList(String(projectId))
- return response.results || []
+ // Deployments are now nested under DeploymentProject; the list scene
+ // owned by the Frontend stream will pick a project and call
+ // `deploymentProjectsDeploymentsList(projectId, deploymentProjectId)`.
+ return []
},
},
],
diff --git a/products/deployments/frontend/generated/api.schemas.ts b/products/deployments/frontend/generated/api.schemas.ts
index 48351ccf75b3..6e538bbed8dd 100644
--- a/products/deployments/frontend/generated/api.schemas.ts
+++ b/products/deployments/frontend/generated/api.schemas.ts
@@ -7,6 +7,84 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+export interface DeploymentProjectApi {
+ /** Unique identifier for the deployment project. */
+ readonly id: string
+ /**
+ * Human-readable project name shown in the UI.
+ * @maxLength 200
+ */
+ name: string
+ /**
+ * URL-safe handle. Combined with the team id to form the Cloudflare project name; the actual subdomain comes from Cloudflare and is returned in the read-only `subdomain` field. Must be unique per team.
+ * @maxLength 80
+ * @pattern ^[-a-zA-Z0-9_]+$
+ */
+ slug: string
+ /**
+ * HTTPS URL of the source repository this project deploys from.
+ * @maxLength 1024
+ */
+ repo_url: string
+ /**
+ * Branch the project deploys from when no commit SHA is pinned. Defaults to `main`.
+ * @maxLength 255
+ */
+ default_branch?: string
+ /**
+ * ID of the `posthog.Integration` row (kind=github) the project uses to read this repository. Must belong to the same team. The actual access token lives on the Integration row and is never exposed through this serializer.
+ * @nullable
+ */
+ github_integration?: number | null
+ /**
+ * Optional shell command run inside the build container. Null = the build worker infers it from `framework` (or auto-detection if framework is also null).
+ * @nullable
+ */
+ build_command?: string | null
+ /**
+ * Directory containing the built static site, relative to the repository root.
+ * @maxLength 255
+ */
+ output_dir?: string
+ /**
+ * Optional framework hint (e.g. `nextjs`, `vite`, `astro`). Null = auto-detect.
+ * @maxLength 50
+ * @nullable
+ */
+ framework?: string | null
+ /** If true, the build injects a PostHog snippet into every HTML file that registers `release = deployment_id` as a super-property — runtime exceptions are then linked back to the deployment that introduced them. */
+ inject_posthog_snippet?: boolean
+ /** Cloudflare Pages project name, assigned during provisioning. */
+ readonly cloudflare_project_name: string
+ /** Public subdomain at which deployments of this project serve. */
+ readonly subdomain: string
+ /**
+ * Timestamp when the Cloudflare project was fully provisioned and ready to receive deploys.
+ * @nullable
+ */
+ readonly cloudflare_ready_at: string | null
+ /**
+ * The deployment currently serving traffic for this project. Null if no deployment has ever succeeded.
+ * @nullable
+ */
+ readonly current_deployment: string | null
+ /** True when the project has both a provisioned Cloudflare backend and a configured GitHub credential — meaning a deploy can be triggered right now. */
+ readonly is_ready_to_deploy: boolean
+ /** Timestamp when the project was created. */
+ readonly created_at: string
+ /** Timestamp when the project was last modified. */
+ readonly updated_at: string
+}
+
+export interface PaginatedDeploymentProjectListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: DeploymentProjectApi[]
+}
+
/**
* * `queued` - Queued
* `initializing` - Initializing
@@ -27,7 +105,8 @@ export const DeploymentStatusEnumApi = {
} as const
/**
- * * `git` - Git
+ * * `manual` - Manual
+ * `git` - Git
* `redeploy` - Redeploy
* `rollback` - Rollback
* `seed` - Seed
@@ -35,16 +114,43 @@ export const DeploymentStatusEnumApi = {
export type TriggerKindEnumApi = (typeof TriggerKindEnumApi)[keyof typeof TriggerKindEnumApi]
export const TriggerKindEnumApi = {
+ Manual: 'manual',
Git: 'git',
Redeploy: 'redeploy',
Rollback: 'rollback',
Seed: 'seed',
} as const
+/**
+ * * `dispatch` - Dispatch
+ * `clone` - Clone
+ * `install` - Install
+ * `build` - Build
+ * `publish` - Publish
+ */
+export type ErrorStepEnumApi = (typeof ErrorStepEnumApi)[keyof typeof ErrorStepEnumApi]
+
+export const ErrorStepEnumApi = {
+ Dispatch: 'dispatch',
+ Clone: 'clone',
+ Install: 'install',
+ Build: 'build',
+ Publish: 'publish',
+} as const
+
+export type BlankEnumApi = (typeof BlankEnumApi)[keyof typeof BlankEnumApi]
+
+export const BlankEnumApi = {
+ '': '',
+} as const
+
+export const DeploymentApiErrorStep = { ...ErrorStepEnumApi, ...BlankEnumApi } as const
export interface DeploymentApi {
/** Unique identifier for the deployment. */
readonly id: string
- /** Current pipeline stage for the deployment. Valid values: queued, initializing, building, ready, error, cancelled.
+ /** The deployment project this deployment belongs to. */
+ readonly project: string
+ /** Current pipeline stage. Valid values: queued, initializing, building, ready, error, cancelled.
* `queued` - Queued
* `initializing` - Initializing
@@ -54,19 +160,19 @@ export interface DeploymentApi {
* `cancelled` - Cancelled */
status: DeploymentStatusEnumApi
/**
- * Timestamp when the pipeline started building. Null while still queued.
+ * When the pipeline started building. Null while still queued.
* @nullable
*/
started_at?: string | null
/**
- * Timestamp when the pipeline finished (regardless of outcome). Null while still running.
+ * When the pipeline finished (regardless of outcome). Null while still running.
* @nullable
*/
finished_at?: string | null
- /** Timestamp when the deployment row was created. */
+ /** When the deployment row was created (~ queued_at). */
readonly created_at: string
/**
- * Git commit SHA the deployment was built from. Empty for non-git triggers.
+ * Git commit SHA the deployment was built from.
* @maxLength 64
*/
commit_sha?: string
@@ -78,12 +184,12 @@ export interface DeploymentApi {
*/
commit_author_name?: string
/**
- * Email address of the commit author.
+ * Email address of the commit author. Used by the Author filter on the list page.
* @maxLength 255
*/
commit_author_email?: string
/**
- * HTTPS URL of the source repository this deployment came from.
+ * HTTPS URL of the source repository. Captured at deploy time.
* @maxLength 1024
*/
repo_url?: string
@@ -93,28 +199,48 @@ export interface DeploymentApi {
*/
branch?: string
/**
- * Public URL where the built site is served once the deployment is ready.
+ * Public URL serving the built site once ready.
* @maxLength 1024
*/
deployment_url?: string
/**
- * URL of a screenshot capture of the deployed site, used in the list view.
+ * URL of the captured site screenshot, used in the list/card view.
* @maxLength 1024
*/
preview_image_url?: string
/**
- * The deployment this one was triggered from (e.g. for rollbacks/redeploys).
+ * The deployment this one was triggered from (for rollbacks and redeploys).
* @nullable
*/
readonly triggered_by_deployment: string | null
- /** What caused this deployment to start. One of: git, redeploy, rollback, seed.
+ /**
+ * Posthog user id of the user who clicked Deploy/Redeploy/Rollback. Null for git-triggered or seed rows.
+ * @nullable
+ */
+ readonly triggered_by_user_id: number | null
+ /** What caused this deployment to start: manual | git | redeploy | rollback | seed.
+ * `manual` - Manual
* `git` - Git
* `redeploy` - Redeploy
* `rollback` - Rollback
* `seed` - Seed */
trigger_kind: TriggerKindEnumApi
- /** Whether this deployment is the team's currently-serving production deployment. */
+ /** Failure detail set when status=error. Empty for successful or in-flight deployments. */
+ readonly error_message: string
+ /** Build step that failed: dispatch | clone | install | build | publish. Empty when status != error.
+
+ * `dispatch` - Dispatch
+ * `clone` - Clone
+ * `install` - Install
+ * `build` - Build
+ * `publish` - Publish */
+ error_step?: (typeof DeploymentApiErrorStep)[keyof typeof DeploymentApiErrorStep]
+ /** Cloudflare Pages deployment id, set once the publish step succeeds. */
+ readonly cloudflare_deployment_id: string
+ /** Temporal workflow id for this build. Used for cancellation signalling. */
+ readonly temporal_workflow_id: string
+ /** True if this deployment is currently serving production traffic for its project. */
readonly is_current: boolean
/** Build duration in seconds (finished_at - started_at). 0 while still running. */
readonly duration_seconds: number
@@ -130,14 +256,153 @@ export interface PaginatedDeploymentListApi {
}
/**
- * Response shape for the redeploy/rollback/refresh-preview stubs.
+ * Body of POST /api/projects/{}/deployment_projects/{}/deployments/.
+ */
+export interface DeploymentCreateInputApi {
+ /**
+ * Optional commit SHA. If omitted, the build worker resolves HEAD of `branch` (or the project's default_branch).
+ * @maxLength 64
+ */
+ commit_sha?: string
+ /**
+ * Optional branch override. If omitted, uses the project's `default_branch`.
+ * @maxLength 255
+ */
+ branch?: string
+}
+
+/**
+ * Response shape returned with HTTP 409 when an active deploy exists.
+ */
+export interface DeploymentConflictResponseApi {
+ /** Reason for the conflict. */
+ detail: string
+ /** The deployment currently in-flight for the project. Frontend can poll this id. */
+ active_deployment_id: string
+}
+
+/**
+ * Response shape for one-off action endpoints (cancel, refresh_preview).
*/
export interface DeploymentActionResponseApi {
- /** Human-readable explanation of the stub response. */
+ /** Short human-readable confirmation message. */
detail: string
}
-export type DeploymentsListParams = {
+export interface DeploymentEventApi {
+ /** Unique identifier for the event row. */
+ readonly id: string
+ /** The deployment this event belongs to. */
+ readonly deployment: string
+ /**
+ * Event category, e.g. `status_changed`, `preview_captured`, `dispatched`.
+ * @maxLength 50
+ */
+ event_type: string
+ /** Arbitrary structured payload for the event. Shape varies by event_type. */
+ payload: unknown
+ /** When the event occurred (server time). */
+ readonly occurred_at: string
+}
+
+export interface PaginatedDeploymentEventListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: DeploymentEventApi[]
+}
+
+export interface PatchedDeploymentProjectApi {
+ /** Unique identifier for the deployment project. */
+ readonly id?: string
+ /**
+ * Human-readable project name shown in the UI.
+ * @maxLength 200
+ */
+ name?: string
+ /**
+ * URL-safe handle. Combined with the team id to form the Cloudflare project name; the actual subdomain comes from Cloudflare and is returned in the read-only `subdomain` field. Must be unique per team.
+ * @maxLength 80
+ * @pattern ^[-a-zA-Z0-9_]+$
+ */
+ slug?: string
+ /**
+ * HTTPS URL of the source repository this project deploys from.
+ * @maxLength 1024
+ */
+ repo_url?: string
+ /**
+ * Branch the project deploys from when no commit SHA is pinned. Defaults to `main`.
+ * @maxLength 255
+ */
+ default_branch?: string
+ /**
+ * ID of the `posthog.Integration` row (kind=github) the project uses to read this repository. Must belong to the same team. The actual access token lives on the Integration row and is never exposed through this serializer.
+ * @nullable
+ */
+ github_integration?: number | null
+ /**
+ * Optional shell command run inside the build container. Null = the build worker infers it from `framework` (or auto-detection if framework is also null).
+ * @nullable
+ */
+ build_command?: string | null
+ /**
+ * Directory containing the built static site, relative to the repository root.
+ * @maxLength 255
+ */
+ output_dir?: string
+ /**
+ * Optional framework hint (e.g. `nextjs`, `vite`, `astro`). Null = auto-detect.
+ * @maxLength 50
+ * @nullable
+ */
+ framework?: string | null
+ /** If true, the build injects a PostHog snippet into every HTML file that registers `release = deployment_id` as a super-property — runtime exceptions are then linked back to the deployment that introduced them. */
+ inject_posthog_snippet?: boolean
+ /** Cloudflare Pages project name, assigned during provisioning. */
+ readonly cloudflare_project_name?: string
+ /** Public subdomain at which deployments of this project serve. */
+ readonly subdomain?: string
+ /**
+ * Timestamp when the Cloudflare project was fully provisioned and ready to receive deploys.
+ * @nullable
+ */
+ readonly cloudflare_ready_at?: string | null
+ /**
+ * The deployment currently serving traffic for this project. Null if no deployment has ever succeeded.
+ * @nullable
+ */
+ readonly current_deployment?: string | null
+ /** True when the project has both a provisioned Cloudflare backend and a configured GitHub credential — meaning a deploy can be triggered right now. */
+ readonly is_ready_to_deploy?: boolean
+ /** Timestamp when the project was created. */
+ readonly created_at?: string
+ /** Timestamp when the project was last modified. */
+ readonly updated_at?: string
+}
+
+export type DeploymentProjectsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+ /**
+ * Which field to use when ordering the results.
+ */
+ ordering?: string
+ /**
+ * A search term.
+ */
+ search?: string
+}
+
+export type DeploymentProjectsDeploymentsListParams = {
/**
* Number of results to return per page.
*/
@@ -146,4 +411,31 @@ export type DeploymentsListParams = {
* The initial index from which to return the results.
*/
offset?: number
+ /**
+ * Which field to use when ordering the results.
+ */
+ ordering?: string
+ /**
+ * A search term.
+ */
+ search?: string
+}
+
+export type DeploymentProjectsDeploymentsEventsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+ /**
+ * Which field to use when ordering the results.
+ */
+ ordering?: string
+ /**
+ * A search term.
+ */
+ search?: string
}
diff --git a/products/deployments/frontend/generated/api.ts b/products/deployments/frontend/generated/api.ts
index 0d7b69fe0ab5..4dec60097e19 100644
--- a/products/deployments/frontend/generated/api.ts
+++ b/products/deployments/frontend/generated/api.ts
@@ -8,9 +8,102 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
-import type { DeploymentApi, DeploymentsListParams, PaginatedDeploymentListApi } from './api.schemas'
+import type {
+ DeploymentActionResponseApi,
+ DeploymentApi,
+ DeploymentCreateInputApi,
+ DeploymentProjectApi,
+ DeploymentProjectsDeploymentsEventsListParams,
+ DeploymentProjectsDeploymentsListParams,
+ DeploymentProjectsListParams,
+ PaginatedDeploymentEventListApi,
+ PaginatedDeploymentListApi,
+ PaginatedDeploymentProjectListApi,
+ PatchedDeploymentProjectApi,
+} from './api.schemas'
-export const getDeploymentsListUrl = (projectId: string, params?: DeploymentsListParams) => {
+// https://stackoverflow.com/questions/49579094/typescript-conditional-types-filter-out-readonly-properties-pick-only-requir/49579497#49579497
+type IfEquals<X, Y, A = X, B = never> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2 ? A : B
+
+type WritableKeys<T> = {
+ [P in keyof T]-?: IfEquals<{ [Q in P]: T[P] }, { -readonly [Q in P]: T[P] }, P>
+}[keyof T]
+
+type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never
+type DistributeReadOnlyOverUnions<T> = T extends any ? NonReadonly<T> : never
+
+type Writable<T> = Pick<T, WritableKeys<T>>
+type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
+ ? {
+ [P in keyof Writable<T>]: T[P] extends object ? NonReadonly<NonNullable<T[P]>> : T[P]
+ }
+ : DistributeReadOnlyOverUnions<T>
+
+export const getDeploymentProjectsListUrl = (projectId: string, params?: DeploymentProjectsListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/deployment_projects/?${stringifiedParams}`
+ : `/api/projects/${projectId}/deployment_projects/`
+}
+
+/**
+ * CRUD for DeploymentProject (the connected-repo + hosting-target entity).
+
+Create-time provisioning calls Cloudflare BEFORE writing the DB row
+(see services/provision_project.py for the rationale). Delete is a
+soft-delete; Cloudflare-side cleanup is deferred to a periodic Celery
+task.
+ */
+export const deploymentProjectsList = async (
+ projectId: string,
+ params?: DeploymentProjectsListParams,
+ options?: RequestInit
+): Promise<PaginatedDeploymentProjectListApi> => {
+ return apiMutator<PaginatedDeploymentProjectListApi>(getDeploymentProjectsListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getDeploymentProjectsCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/deployment_projects/`
+}
+
+/**
+ * CRUD for DeploymentProject (the connected-repo + hosting-target entity).
+
+Create-time provisioning calls Cloudflare BEFORE writing the DB row
+(see services/provision_project.py for the rationale). Delete is a
+soft-delete; Cloudflare-side cleanup is deferred to a periodic Celery
+task.
+ */
+export const deploymentProjectsCreate = async (
+ projectId: string,
+ deploymentProjectApi: NonReadonly<DeploymentProjectApi>,
+ options?: RequestInit
+): Promise<DeploymentProjectApi> => {
+ return apiMutator<DeploymentProjectApi>(getDeploymentProjectsCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(deploymentProjectApi),
+ })
+}
+
+export const getDeploymentProjectsDeploymentsListUrl = (
+ projectId: string,
+ deploymentProjectId: string,
+ params?: DeploymentProjectsDeploymentsListParams
+) => {
const normalizedParams = new URLSearchParams()
Object.entries(params || {}).forEach(([key, value]) => {
@@ -22,117 +115,381 @@ export const getDeploymentsListUrl = (projectId: string, params?: DeploymentsLis
const stringifiedParams = normalizedParams.toString()
return stringifiedParams.length > 0
- ? `/api/projects/${projectId}/deployments/?${stringifiedParams}`
- : `/api/projects/${projectId}/deployments/`
+ ? `/api/projects/${projectId}/deployment_projects/${deploymentProjectId}/deployments/?${stringifiedParams}`
+ : `/api/projects/${projectId}/deployment_projects/${deploymentProjectId}/deployments/`
}
/**
- * Read-only viewset for the Deployments product.
+ * Full lifecycle viewset for Deployments.
-`list` and `retrieve` are wired against the model queryset. The
-`@action` stubs (`redeploy`, `rollback`, `refresh_preview`) intentionally
-return 501 — they exist so OpenAPI / MCP can discover the surface area
-while behavior lands in follow-up commits.
+All deployments are scoped to a parent DeploymentProject via the URL
+parent lookup `deployment_project_id`. The viewset enforces that
+scoping in `safely_get_queryset` so a user can never see / mutate a
+deployment that doesn't belong to the project in the URL.
*/
-export const deploymentsList = async (
+export const deploymentProjectsDeploymentsList = async (
projectId: string,
- params?: DeploymentsListParams,
+ deploymentProjectId: string,
+ params?: DeploymentProjectsDeploymentsListParams,
options?: RequestInit
): Promise<PaginatedDeploymentListApi> => {
- return apiMutator<PaginatedDeploymentListApi>(getDeploymentsListUrl(projectId, params), {
+ return apiMutator<PaginatedDeploymentListApi>(
+ getDeploymentProjectsDeploymentsListUrl(projectId, deploymentProjectId, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getDeploymentProjectsDeploymentsCreateUrl = (projectId: string, deploymentProjectId: string) => {
+ return `/api/projects/${projectId}/deployment_projects/${deploymentProjectId}/deployments/`
+}
+
+/**
+ * Full lifecycle viewset for Deployments.
+
+All deployments are scoped to a parent DeploymentProject via the URL
+parent lookup `deployment_project_id`. The viewset enforces that
+scoping in `safely_get_queryset` so a user can never see / mutate a
+deployment that doesn't belong to the project in the URL.
+ */
+export const deploymentProjectsDeploymentsCreate = async (
+ projectId: string,
+ deploymentProjectId: string,
+ deploymentCreateInputApi?: DeploymentCreateInputApi,
+ options?: RequestInit
+): Promise<DeploymentApi> => {
+ return apiMutator<DeploymentApi>(getDeploymentProjectsDeploymentsCreateUrl(projectId, deploymentProjectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(deploymentCreateInputApi),
+ })
+}
+
+export const getDeploymentProjectsDeploymentsRetrieveUrl = (
+ projectId: string,
+ deploymentProjectId: string,
+ id: string
+) => {
+ return `/api/projects/${projectId}/deployment_projects/${deploymentProjectId}/deployments/${id}/`
+}
+
+/**
+ * Full lifecycle viewset for Deployments.
+
+All deployments are scoped to a parent DeploymentProject via the URL
+parent lookup `deployment_project_id`. The viewset enforces that
+scoping in `safely_get_queryset` so a user can never see / mutate a
+deployment that doesn't belong to the project in the URL.
+ */
+export const deploymentProjectsDeploymentsRetrieve = async (
+ projectId: string,
+ deploymentProjectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<DeploymentApi> => {
+ return apiMutator<DeploymentApi>(getDeploymentProjectsDeploymentsRetrieveUrl(projectId, deploymentProjectId, id), {
...options,
method: 'GET',
})
}
-export const getDeploymentsRetrieveUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/deployments/${id}/`
+export const getDeploymentProjectsDeploymentsCancelCreateUrl = (
+ projectId: string,
+ deploymentProjectId: string,
+ id: string
+) => {
+ return `/api/projects/${projectId}/deployment_projects/${deploymentProjectId}/deployments/${id}/cancel/`
}
/**
- * Read-only viewset for the Deployments product.
+ * Full lifecycle viewset for Deployments.
-`list` and `retrieve` are wired against the model queryset. The
-`@action` stubs (`redeploy`, `rollback`, `refresh_preview`) intentionally
-return 501 — they exist so OpenAPI / MCP can discover the surface area
-while behavior lands in follow-up commits.
+All deployments are scoped to a parent DeploymentProject via the URL
+parent lookup `deployment_project_id`. The viewset enforces that
+scoping in `safely_get_queryset` so a user can never see / mutate a
+deployment that doesn't belong to the project in the URL.
*/
-export const deploymentsRetrieve = async (
+export const deploymentProjectsDeploymentsCancelCreate = async (
projectId: string,
+ deploymentProjectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<DeploymentActionResponseApi> => {
+ return apiMutator<DeploymentActionResponseApi>(
+ getDeploymentProjectsDeploymentsCancelCreateUrl(projectId, deploymentProjectId, id),
+ {
+ ...options,
+ method: 'POST',
+ }
+ )
+}
+
+export const getDeploymentProjectsDeploymentsEventsListUrl = (
+ projectId: string,
+ deploymentProjectId: string,
+ id: string,
+ params?: DeploymentProjectsDeploymentsEventsListParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString())
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/deployment_projects/${deploymentProjectId}/deployments/${id}/events/?${stringifiedParams}`
+ : `/api/projects/${projectId}/deployment_projects/${deploymentProjectId}/deployments/${id}/events/`
+}
+
+/**
+ * Full lifecycle viewset for Deployments.
+
+All deployments are scoped to a parent DeploymentProject via the URL
+parent lookup `deployment_project_id`. The viewset enforces that
+scoping in `safely_get_queryset` so a user can never see / mutate a
+deployment that doesn't belong to the project in the URL.
+ */
+export const deploymentProjectsDeploymentsEventsList = async (
+ projectId: string,
+ deploymentProjectId: string,
+ id: string,
+ params?: DeploymentProjectsDeploymentsEventsListParams,
+ options?: RequestInit
+): Promise<PaginatedDeploymentEventListApi> => {
+ return apiMutator<PaginatedDeploymentEventListApi>(
+ getDeploymentProjectsDeploymentsEventsListUrl(projectId, deploymentProjectId, id, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getDeploymentProjectsDeploymentsLogsRetrieveUrl = (
+ projectId: string,
+ deploymentProjectId: string,
+ id: string
+) => {
+ return `/api/projects/${projectId}/deployment_projects/${deploymentProjectId}/deployments/${id}/logs/`
+}
+
+/**
+ * Full lifecycle viewset for Deployments.
+
+All deployments are scoped to a parent DeploymentProject via the URL
+parent lookup `deployment_project_id`. The viewset enforces that
+scoping in `safely_get_queryset` so a user can never see / mutate a
+deployment that doesn't belong to the project in the URL.
+ */
+export const deploymentProjectsDeploymentsLogsRetrieve = async (
+ projectId: string,
+ deploymentProjectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<DeploymentActionResponseApi> => {
+ return apiMutator<DeploymentActionResponseApi>(
+ getDeploymentProjectsDeploymentsLogsRetrieveUrl(projectId, deploymentProjectId, id),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
+}
+
+export const getDeploymentProjectsDeploymentsRedeployCreateUrl = (
+ projectId: string,
+ deploymentProjectId: string,
+ id: string
+) => {
+ return `/api/projects/${projectId}/deployment_projects/${deploymentProjectId}/deployments/${id}/redeploy/`
+}
+
+/**
+ * Full lifecycle viewset for Deployments.
+
+All deployments are scoped to a parent DeploymentProject via the URL
+parent lookup `deployment_project_id`. The viewset enforces that
+scoping in `safely_get_queryset` so a user can never see / mutate a
+deployment that doesn't belong to the project in the URL.
+ */
+export const deploymentProjectsDeploymentsRedeployCreate = async (
+ projectId: string,
+ deploymentProjectId: string,
id: string,
options?: RequestInit
): Promise<DeploymentApi> => {
- return apiMutator<DeploymentApi>(getDeploymentsRetrieveUrl(projectId, id), {
+ return apiMutator<DeploymentApi>(
+ getDeploymentProjectsDeploymentsRedeployCreateUrl(projectId, deploymentProjectId, id),
+ {
+ ...options,
+ method: 'POST',
+ }
+ )
+}
+
+export const getDeploymentProjectsDeploymentsRefreshPreviewCreateUrl = (
+ projectId: string,
+ deploymentProjectId: string,
+ id: string
+) => {
+ return `/api/projects/${projectId}/deployment_projects/${deploymentProjectId}/deployments/${id}/refresh_preview/`
+}
+
+/**
+ * Full lifecycle viewset for Deployments.
+
+All deployments are scoped to a parent DeploymentProject via the URL
+parent lookup `deployment_project_id`. The viewset enforces that
+scoping in `safely_get_queryset` so a user can never see / mutate a
+deployment that doesn't belong to the project in the URL.
+ */
+export const deploymentProjectsDeploymentsRefreshPreviewCreate = async (
+ projectId: string,
+ deploymentProjectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<DeploymentApi> => {
+ return apiMutator<DeploymentApi>(
+ getDeploymentProjectsDeploymentsRefreshPreviewCreateUrl(projectId, deploymentProjectId, id),
+ {
+ ...options,
+ method: 'POST',
+ }
+ )
+}
+
+export const getDeploymentProjectsDeploymentsRollbackCreateUrl = (
+ projectId: string,
+ deploymentProjectId: string,
+ id: string
+) => {
+ return `/api/projects/${projectId}/deployment_projects/${deploymentProjectId}/deployments/${id}/rollback/`
+}
+
+/**
+ * Full lifecycle viewset for Deployments.
+
+All deployments are scoped to a parent DeploymentProject via the URL
+parent lookup `deployment_project_id`. The viewset enforces that
+scoping in `safely_get_queryset` so a user can never see / mutate a
+deployment that doesn't belong to the project in the URL.
+ */
+export const deploymentProjectsDeploymentsRollbackCreate = async (
+ projectId: string,
+ deploymentProjectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<DeploymentApi> => {
+ return apiMutator<DeploymentApi>(
+ getDeploymentProjectsDeploymentsRollbackCreateUrl(projectId, deploymentProjectId, id),
+ {
+ ...options,
+ method: 'POST',
+ }
+ )
+}
+
+export const getDeploymentProjectsRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/deployment_projects/${id}/`
+}
+
+/**
+ * CRUD for DeploymentProject (the connected-repo + hosting-target entity).
+
+Create-time provisioning calls Cloudflare BEFORE writing the DB row
+(see services/provision_project.py for the rationale). Delete is a
+soft-delete; Cloudflare-side cleanup is deferred to a periodic Celery
+task.
+ */
+export const deploymentProjectsRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<DeploymentProjectApi> => {
+ return apiMutator<DeploymentProjectApi>(getDeploymentProjectsRetrieveUrl(projectId, id), {
...options,
method: 'GET',
})
}
-export const getDeploymentsRedeployCreateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/deployments/${id}/redeploy/`
+export const getDeploymentProjectsUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/deployment_projects/${id}/`
}
/**
- * Read-only viewset for the Deployments product.
+ * CRUD for DeploymentProject (the connected-repo + hosting-target entity).
-`list` and `retrieve` are wired against the model queryset. The
-`@action` stubs (`redeploy`, `rollback`, `refresh_preview`) intentionally
-return 501 — they exist so OpenAPI / MCP can discover the surface area
-while behavior lands in follow-up commits.
+Create-time provisioning calls Cloudflare BEFORE writing the DB row
+(see services/provision_project.py for the rationale). Delete is a
+soft-delete; Cloudflare-side cleanup is deferred to a periodic Celery
+task.
*/
-export const deploymentsRedeployCreate = async (
+export const deploymentProjectsUpdate = async (
projectId: string,
id: string,
+ deploymentProjectApi: NonReadonly<DeploymentProjectApi>,
options?: RequestInit
-): Promise<unknown> => {
- return apiMutator<unknown>(getDeploymentsRedeployCreateUrl(projectId, id), {
+): Promise<DeploymentProjectApi> => {
+ return apiMutator<DeploymentProjectApi>(getDeploymentProjectsUpdateUrl(projectId, id), {
...options,
- method: 'POST',
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(deploymentProjectApi),
})
}
-export const getDeploymentsRefreshPreviewCreateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/deployments/${id}/refresh-preview/`
+export const getDeploymentProjectsPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/deployment_projects/${id}/`
}
/**
- * Read-only viewset for the Deployments product.
+ * CRUD for DeploymentProject (the connected-repo + hosting-target entity).
-`list` and `retrieve` are wired against the model queryset. The
-`@action` stubs (`redeploy`, `rollback`, `refresh_preview`) intentionally
-return 501 — they exist so OpenAPI / MCP can discover the surface area
-while behavior lands in follow-up commits.
+Create-time provisioning calls Cloudflare BEFORE writing the DB row
+(see services/provision_project.py for the rationale). Delete is a
+soft-delete; Cloudflare-side cleanup is deferred to a periodic Celery
+task.
*/
-export const deploymentsRefreshPreviewCreate = async (
+export const deploymentProjectsPartialUpdate = async (
projectId: string,
id: string,
+ patchedDeploymentProjectApi?: NonReadonly<PatchedDeploymentProjectApi>,
options?: RequestInit
-): Promise<unknown> => {
- return apiMutator<unknown>(getDeploymentsRefreshPreviewCreateUrl(projectId, id), {
+): Promise<DeploymentProjectApi> => {
+ return apiMutator<DeploymentProjectApi>(getDeploymentProjectsPartialUpdateUrl(projectId, id), {
...options,
- method: 'POST',
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedDeploymentProjectApi),
})
}
-export const getDeploymentsRollbackCreateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/deployments/${id}/rollback/`
+export const getDeploymentProjectsDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/deployment_projects/${id}/`
}
/**
- * Read-only viewset for the Deployments product.
+ * CRUD for DeploymentProject (the connected-repo + hosting-target entity).
-`list` and `retrieve` are wired against the model queryset. The
-`@action` stubs (`redeploy`, `rollback`, `refresh_preview`) intentionally
-return 501 — they exist so OpenAPI / MCP can discover the surface area
-while behavior lands in follow-up commits.
+Create-time provisioning calls Cloudflare BEFORE writing the DB row
+(see services/provision_project.py for the rationale). Delete is a
+soft-delete; Cloudflare-side cleanup is deferred to a periodic Celery
+task.
*/
-export const deploymentsRollbackCreate = async (
+export const deploymentProjectsDestroy = async (
projectId: string,
id: string,
options?: RequestInit
-): Promise<unknown> => {
- return apiMutator<unknown>(getDeploymentsRollbackCreateUrl(projectId, id), {
+): Promise<void> => {
+ return apiMutator<void>(getDeploymentProjectsDestroyUrl(projectId, id), {
...options,
- method: 'POST',
+ method: 'DELETE',
})
}
diff --git a/products/deployments/frontend/generated/api.zod.ts b/products/deployments/frontend/generated/api.zod.ts
index e8a15d4e1b52..a6b0c5aee6f5 100644
--- a/products/deployments/frontend/generated/api.zod.ts
+++ b/products/deployments/frontend/generated/api.zod.ts
@@ -7,3 +7,264 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+import * as zod from 'zod'
+
+/**
+ * CRUD for DeploymentProject (the connected-repo + hosting-target entity).
+
+Create-time provisioning calls Cloudflare BEFORE writing the DB row
+(see services/provision_project.py for the rationale). Delete is a
+soft-delete; Cloudflare-side cleanup is deferred to a periodic Celery
+task.
+ */
+export const deploymentProjectsCreateBodyNameMax = 200
+
+export const deploymentProjectsCreateBodySlugMax = 80
+
+export const deploymentProjectsCreateBodySlugRegExp = new RegExp('^[-a-zA-Z0-9_]+$')
+export const deploymentProjectsCreateBodyRepoUrlMax = 1024
+
+export const deploymentProjectsCreateBodyDefaultBranchDefault = `main`
+export const deploymentProjectsCreateBodyDefaultBranchMax = 255
+
+export const deploymentProjectsCreateBodyOutputDirDefault = `dist`
+export const deploymentProjectsCreateBodyOutputDirMax = 255
+
+export const deploymentProjectsCreateBodyFrameworkMax = 50
+
+export const deploymentProjectsCreateBodyInjectPosthogSnippetDefault = false
+
+export const DeploymentProjectsCreateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(deploymentProjectsCreateBodyNameMax)
+ .describe('Human-readable project name shown in the UI.'),
+ slug: zod
+ .string()
+ .max(deploymentProjectsCreateBodySlugMax)
+ .regex(deploymentProjectsCreateBodySlugRegExp)
+ .describe(
+ 'URL-safe handle. Combined with the team id to form the Cloudflare project name; the actual subdomain comes from Cloudflare and is returned in the read-only `subdomain` field. Must be unique per team.'
+ ),
+ repo_url: zod
+ .url()
+ .max(deploymentProjectsCreateBodyRepoUrlMax)
+ .describe('HTTPS URL of the source repository this project deploys from.'),
+ default_branch: zod
+ .string()
+ .max(deploymentProjectsCreateBodyDefaultBranchMax)
+ .default(deploymentProjectsCreateBodyDefaultBranchDefault)
+ .describe('Branch the project deploys from when no commit SHA is pinned. Defaults to `main`.'),
+ github_integration: zod
+ .number()
+ .nullish()
+ .describe(
+ 'ID of the `posthog.Integration` row (kind=github) the project uses to read this repository. Must belong to the same team. The actual access token lives on the Integration row and is never exposed through this serializer.'
+ ),
+ build_command: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Optional shell command run inside the build container. Null = the build worker infers it from `framework` (or auto-detection if framework is also null).'
+ ),
+ output_dir: zod
+ .string()
+ .max(deploymentProjectsCreateBodyOutputDirMax)
+ .default(deploymentProjectsCreateBodyOutputDirDefault)
+ .describe('Directory containing the built static site, relative to the repository root.'),
+ framework: zod
+ .string()
+ .max(deploymentProjectsCreateBodyFrameworkMax)
+ .nullish()
+ .describe('Optional framework hint (e.g. `nextjs`, `vite`, `astro`). Null = auto-detect.'),
+ inject_posthog_snippet: zod
+ .boolean()
+ .default(deploymentProjectsCreateBodyInjectPosthogSnippetDefault)
+ .describe(
+ 'If true, the build injects a PostHog snippet into every HTML file that registers `release = deployment_id` as a super-property — runtime exceptions are then linked back to the deployment that introduced them.'
+ ),
+})
+
+/**
+ * Full lifecycle viewset for Deployments.
+
+All deployments are scoped to a parent DeploymentProject via the URL
+parent lookup `deployment_project_id`. The viewset enforces that
+scoping in `safely_get_queryset` so a user can never see / mutate a
+deployment that doesn't belong to the project in the URL.
+ */
+export const deploymentProjectsDeploymentsCreateBodyCommitShaMax = 64
+
+export const deploymentProjectsDeploymentsCreateBodyBranchMax = 255
+
+export const DeploymentProjectsDeploymentsCreateBody = /* @__PURE__ */ zod
+ .object({
+ commit_sha: zod
+ .string()
+ .max(deploymentProjectsDeploymentsCreateBodyCommitShaMax)
+ .optional()
+ .describe(
+ "Optional commit SHA. If omitted, the build worker resolves HEAD of `branch` (or the project's default_branch)."
+ ),
+ branch: zod
+ .string()
+ .max(deploymentProjectsDeploymentsCreateBodyBranchMax)
+ .optional()
+ .describe("Optional branch override. If omitted, uses the project's `default_branch`."),
+ })
+ .describe('Body of POST \/api\/projects\/{}\/deployment_projects\/{}\/deployments\/.')
+
+/**
+ * CRUD for DeploymentProject (the connected-repo + hosting-target entity).
+
+Create-time provisioning calls Cloudflare BEFORE writing the DB row
+(see services/provision_project.py for the rationale). Delete is a
+soft-delete; Cloudflare-side cleanup is deferred to a periodic Celery
+task.
+ */
+export const deploymentProjectsUpdateBodyNameMax = 200
+
+export const deploymentProjectsUpdateBodySlugMax = 80
+
+export const deploymentProjectsUpdateBodySlugRegExp = new RegExp('^[-a-zA-Z0-9_]+$')
+export const deploymentProjectsUpdateBodyRepoUrlMax = 1024
+
+export const deploymentProjectsUpdateBodyDefaultBranchDefault = `main`
+export const deploymentProjectsUpdateBodyDefaultBranchMax = 255
+
+export const deploymentProjectsUpdateBodyOutputDirDefault = `dist`
+export const deploymentProjectsUpdateBodyOutputDirMax = 255
+
+export const deploymentProjectsUpdateBodyFrameworkMax = 50
+
+export const deploymentProjectsUpdateBodyInjectPosthogSnippetDefault = false
+
+export const DeploymentProjectsUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(deploymentProjectsUpdateBodyNameMax)
+ .describe('Human-readable project name shown in the UI.'),
+ slug: zod
+ .string()
+ .max(deploymentProjectsUpdateBodySlugMax)
+ .regex(deploymentProjectsUpdateBodySlugRegExp)
+ .describe(
+ 'URL-safe handle. Combined with the team id to form the Cloudflare project name; the actual subdomain comes from Cloudflare and is returned in the read-only `subdomain` field. Must be unique per team.'
+ ),
+ repo_url: zod
+ .url()
+ .max(deploymentProjectsUpdateBodyRepoUrlMax)
+ .describe('HTTPS URL of the source repository this project deploys from.'),
+ default_branch: zod
+ .string()
+ .max(deploymentProjectsUpdateBodyDefaultBranchMax)
+ .default(deploymentProjectsUpdateBodyDefaultBranchDefault)
+ .describe('Branch the project deploys from when no commit SHA is pinned. Defaults to `main`.'),
+ github_integration: zod
+ .number()
+ .nullish()
+ .describe(
+ 'ID of the `posthog.Integration` row (kind=github) the project uses to read this repository. Must belong to the same team. The actual access token lives on the Integration row and is never exposed through this serializer.'
+ ),
+ build_command: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Optional shell command run inside the build container. Null = the build worker infers it from `framework` (or auto-detection if framework is also null).'
+ ),
+ output_dir: zod
+ .string()
+ .max(deploymentProjectsUpdateBodyOutputDirMax)
+ .default(deploymentProjectsUpdateBodyOutputDirDefault)
+ .describe('Directory containing the built static site, relative to the repository root.'),
+ framework: zod
+ .string()
+ .max(deploymentProjectsUpdateBodyFrameworkMax)
+ .nullish()
+ .describe('Optional framework hint (e.g. `nextjs`, `vite`, `astro`). Null = auto-detect.'),
+ inject_posthog_snippet: zod
+ .boolean()
+ .default(deploymentProjectsUpdateBodyInjectPosthogSnippetDefault)
+ .describe(
+ 'If true, the build injects a PostHog snippet into every HTML file that registers `release = deployment_id` as a super-property — runtime exceptions are then linked back to the deployment that introduced them.'
+ ),
+})
+
+/**
+ * CRUD for DeploymentProject (the connected-repo + hosting-target entity).
+
+Create-time provisioning calls Cloudflare BEFORE writing the DB row
+(see services/provision_project.py for the rationale). Delete is a
+soft-delete; Cloudflare-side cleanup is deferred to a periodic Celery
+task.
+ */
+export const deploymentProjectsPartialUpdateBodyNameMax = 200
+
+export const deploymentProjectsPartialUpdateBodySlugMax = 80
+
+export const deploymentProjectsPartialUpdateBodySlugRegExp = new RegExp('^[-a-zA-Z0-9_]+$')
+export const deploymentProjectsPartialUpdateBodyRepoUrlMax = 1024
+
+export const deploymentProjectsPartialUpdateBodyDefaultBranchDefault = `main`
+export const deploymentProjectsPartialUpdateBodyDefaultBranchMax = 255
+
+export const deploymentProjectsPartialUpdateBodyOutputDirDefault = `dist`
+export const deploymentProjectsPartialUpdateBodyOutputDirMax = 255
+
+export const deploymentProjectsPartialUpdateBodyFrameworkMax = 50
+
+export const deploymentProjectsPartialUpdateBodyInjectPosthogSnippetDefault = false
+
+export const DeploymentProjectsPartialUpdateBody = /* @__PURE__ */ zod.object({
+ name: zod
+ .string()
+ .max(deploymentProjectsPartialUpdateBodyNameMax)
+ .optional()
+ .describe('Human-readable project name shown in the UI.'),
+ slug: zod
+ .string()
+ .max(deploymentProjectsPartialUpdateBodySlugMax)
+ .regex(deploymentProjectsPartialUpdateBodySlugRegExp)
+ .optional()
+ .describe(
+ 'URL-safe handle. Combined with the team id to form the Cloudflare project name; the actual subdomain comes from Cloudflare and is returned in the read-only `subdomain` field. Must be unique per team.'
+ ),
+ repo_url: zod
+ .url()
+ .max(deploymentProjectsPartialUpdateBodyRepoUrlMax)
+ .optional()
+ .describe('HTTPS URL of the source repository this project deploys from.'),
+ default_branch: zod
+ .string()
+ .max(deploymentProjectsPartialUpdateBodyDefaultBranchMax)
+ .default(deploymentProjectsPartialUpdateBodyDefaultBranchDefault)
+ .describe('Branch the project deploys from when no commit SHA is pinned. Defaults to `main`.'),
+ github_integration: zod
+ .number()
+ .nullish()
+ .describe(
+ 'ID of the `posthog.Integration` row (kind=github) the project uses to read this repository. Must belong to the same team. The actual access token lives on the Integration row and is never exposed through this serializer.'
+ ),
+ build_command: zod
+ .string()
+ .nullish()
+ .describe(
+ 'Optional shell command run inside the build container. Null = the build worker infers it from `framework` (or auto-detection if framework is also null).'
+ ),
+ output_dir: zod
+ .string()
+ .max(deploymentProjectsPartialUpdateBodyOutputDirMax)
+ .default(deploymentProjectsPartialUpdateBodyOutputDirDefault)
+ .describe('Directory containing the built static site, relative to the repository root.'),
+ framework: zod
+ .string()
+ .max(deploymentProjectsPartialUpdateBodyFrameworkMax)
+ .nullish()
+ .describe('Optional framework hint (e.g. `nextjs`, `vite`, `astro`). Null = auto-detect.'),
+ inject_posthog_snippet: zod
+ .boolean()
+ .default(deploymentProjectsPartialUpdateBodyInjectPosthogSnippetDefault)
+ .describe(
+ 'If true, the build injects a PostHog snippet into every HTML file that registers `release = deployment_id` as a super-property — runtime exceptions are then linked back to the deployment that introduced them.'
+ ),
+})
diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yaml
index 55728c10837d..fe26acb54538 100644
--- a/products/logs/mcp/tools.yaml
+++ b/products/logs/mcp/tools.yaml
@@ -15,6 +15,9 @@ tools:
batch-exports-runs-logs-retrieve:
operation: batch_exports_runs_logs_retrieve
enabled: false
+ deployment-projects-deployments-logs-retrieve:
+ operation: deployment_projects_deployments_logs_retrieve
+ enabled: false
domains-scim-logs-retrieve:
operation: domains_scim_logs_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b825fc8f315d..883ca0237b5e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -11845,6 +11845,25 @@ export namespace Schemas {
name: string;
}
+ /**
+ * * `dispatch` - Dispatch
+ * `clone` - Clone
+ * `install` - Install
+ * `build` - Build
+ * `publish` - Publish
+ */
+ export type ErrorStepEnum = typeof ErrorStepEnum[keyof typeof ErrorStepEnum];
+
+
+ export const ErrorStepEnum = {
+ Dispatch: 'dispatch',
+ Clone: 'clone',
+ Install: 'install',
+ Build: 'build',
+ Publish: 'publish',
+ } as const;
+
+ export const DeploymentErrorStep = {...ErrorStepEnum,...BlankEnum,} as const
/**
* * `queued` - Queued
* `initializing` - Initializing
@@ -11866,7 +11885,8 @@ export namespace Schemas {
} as const;
/**
- * * `git` - Git
+ * * `manual` - Manual
+ * `git` - Git
* `redeploy` - Redeploy
* `rollback` - Rollback
* `seed` - Seed
@@ -11875,6 +11895,7 @@ export namespace Schemas {
export const TriggerKindEnum = {
+ Manual: 'manual',
Git: 'git',
Redeploy: 'redeploy',
Rollback: 'rollback',
@@ -11884,7 +11905,9 @@ export namespace Schemas {
export interface Deployment {
/** Unique identifier for the deployment. */
readonly id: string;
- /** Current pipeline stage for the deployment. Valid values: queued, initializing, building, ready, error, cancelled.
+ /** The deployment project this deployment belongs to. */
+ readonly project: string;
+ /** Current pipeline stage. Valid values: queued, initializing, building, ready, error, cancelled.
* `queued` - Queued
* `initializing` - Initializing
@@ -11894,19 +11917,19 @@ export namespace Schemas {
* `cancelled` - Cancelled */
status: DeploymentStatusEnum;
/**
- * Timestamp when the pipeline started building. Null while still queued.
+ * When the pipeline started building. Null while still queued.
* @nullable
*/
started_at?: string | null;
/**
- * Timestamp when the pipeline finished (regardless of outcome). Null while still running.
+ * When the pipeline finished (regardless of outcome). Null while still running.
* @nullable
*/
finished_at?: string | null;
- /** Timestamp when the deployment row was created. */
+ /** When the deployment row was created (~ queued_at). */
readonly created_at: string;
/**
- * Git commit SHA the deployment was built from. Empty for non-git triggers.
+ * Git commit SHA the deployment was built from.
* @maxLength 64
*/
commit_sha?: string;
@@ -11918,12 +11941,12 @@ export namespace Schemas {
*/
commit_author_name?: string;
/**
- * Email address of the commit author.
+ * Email address of the commit author. Used by the Author filter on the list page.
* @maxLength 255
*/
commit_author_email?: string;
/**
- * HTTPS URL of the source repository this deployment came from.
+ * HTTPS URL of the source repository. Captured at deploy time.
* @maxLength 1024
*/
repo_url?: string;
@@ -11933,39 +11956,170 @@ export namespace Schemas {
*/
branch?: string;
/**
- * Public URL where the built site is served once the deployment is ready.
+ * Public URL serving the built site once ready.
* @maxLength 1024
*/
deployment_url?: string;
/**
- * URL of a screenshot capture of the deployed site, used in the list view.
+ * URL of the captured site screenshot, used in the list/card view.
* @maxLength 1024
*/
preview_image_url?: string;
/**
- * The deployment this one was triggered from (e.g. for rollbacks/redeploys).
+ * The deployment this one was triggered from (for rollbacks and redeploys).
* @nullable
*/
readonly triggered_by_deployment: string | null;
- /** What caused this deployment to start. One of: git, redeploy, rollback, seed.
+ /**
+ * Posthog user id of the user who clicked Deploy/Redeploy/Rollback. Null for git-triggered or seed rows.
+ * @nullable
+ */
+ readonly triggered_by_user_id: number | null;
+ /** What caused this deployment to start: manual | git | redeploy | rollback | seed.
+ * `manual` - Manual
* `git` - Git
* `redeploy` - Redeploy
* `rollback` - Rollback
* `seed` - Seed */
trigger_kind: TriggerKindEnum;
- /** Whether this deployment is the team's currently-serving production deployment. */
+ /** Failure detail set when status=error. Empty for successful or in-flight deployments. */
+ readonly error_message: string;
+ /** Build step that failed: dispatch | clone | install | build | publish. Empty when status != error.
+
+ * `dispatch` - Dispatch
+ * `clone` - Clone
+ * `install` - Install
+ * `build` - Build
+ * `publish` - Publish */
+ error_step?: typeof DeploymentErrorStep[keyof typeof DeploymentErrorStep];
+ /** Cloudflare Pages deployment id, set once the publish step succeeds. */
+ readonly cloudflare_deployment_id: string;
+ /** Temporal workflow id for this build. Used for cancellation signalling. */
+ readonly temporal_workflow_id: string;
+ /** True if this deployment is currently serving production traffic for its project. */
readonly is_current: boolean;
/** Build duration in seconds (finished_at - started_at). 0 while still running. */
readonly duration_seconds: number;
}
/**
- * Response shape for the redeploy/rollback/refresh-preview stubs.
+ * Response shape for one-off action endpoints (cancel, refresh_preview).
*/
export interface DeploymentActionResponse {
- /** Human-readable explanation of the stub response. */
+ /** Short human-readable confirmation message. */
+ detail: string;
+ }
+
+ /**
+ * Response shape returned with HTTP 409 when an active deploy exists.
+ */
+ export interface DeploymentConflictResponse {
+ /** Reason for the conflict. */
detail: string;
+ /** The deployment currently in-flight for the project. Frontend can poll this id. */
+ active_deployment_id: string;
+ }
+
+ /**
+ * Body of POST /api/projects/{}/deployment_projects/{}/deployments/.
+ */
+ export interface DeploymentCreateInput {
+ /**
+ * Optional commit SHA. If omitted, the build worker resolves HEAD of `branch` (or the project's default_branch).
+ * @maxLength 64
+ */
+ commit_sha?: string;
+ /**
+ * Optional branch override. If omitted, uses the project's `default_branch`.
+ * @maxLength 255
+ */
+ branch?: string;
+ }
+
+ export interface DeploymentEvent {
+ /** Unique identifier for the event row. */
+ readonly id: string;
+ /** The deployment this event belongs to. */
+ readonly deployment: string;
+ /**
+ * Event category, e.g. `status_changed`, `preview_captured`, `dispatched`.
+ * @maxLength 50
+ */
+ event_type: string;
+ /** Arbitrary structured payload for the event. Shape varies by event_type. */
+ payload: unknown;
+ /** When the event occurred (server time). */
+ readonly occurred_at: string;
+ }
+
+ export interface DeploymentProject {
+ /** Unique identifier for the deployment project. */
+ readonly id: string;
+ /**
+ * Human-readable project name shown in the UI.
+ * @maxLength 200
+ */
+ name: string;
+ /**
+ * URL-safe handle. Combined with the team id to form the Cloudflare project name; the actual subdomain comes from Cloudflare and is returned in the read-only `subdomain` field. Must be unique per team.
+ * @maxLength 80
+ * @pattern ^[-a-zA-Z0-9_]+$
+ */
+ slug: string;
+ /**
+ * HTTPS URL of the source repository this project deploys from.
+ * @maxLength 1024
+ */
+ repo_url: string;
+ /**
+ * Branch the project deploys from when no commit SHA is pinned. Defaults to `main`.
+ * @maxLength 255
+ */
+ default_branch?: string;
+ /**
+ * ID of the `posthog.Integration` row (kind=github) the project uses to read this repository. Must belong to the same team. The actual access token lives on the Integration row and is never exposed through this serializer.
+ * @nullable
+ */
+ github_integration?: number | null;
+ /**
+ * Optional shell command run inside the build container. Null = the build worker infers it from `framework` (or auto-detection if framework is also null).
+ * @nullable
+ */
+ build_command?: string | null;
+ /**
+ * Directory containing the built static site, relative to the repository root.
+ * @maxLength 255
+ */
+ output_dir?: string;
+ /**
+ * Optional framework hint (e.g. `nextjs`, `vite`, `astro`). Null = auto-detect.
+ * @maxLength 50
+ * @nullable
+ */
+ framework?: string | null;
+ /** If true, the build injects a PostHog snippet into every HTML file that registers `release = deployment_id` as a super-property — runtime exceptions are then linked back to the deployment that introduced them. */
+ inject_posthog_snippet?: boolean;
+ /** Cloudflare Pages project name, assigned during provisioning. */
+ readonly cloudflare_project_name: string;
+ /** Public subdomain at which deployments of this project serve. */
+ readonly subdomain: string;
+ /**
+ * Timestamp when the Cloudflare project was fully provisioned and ready to receive deploys.
+ * @nullable
+ */
+ readonly cloudflare_ready_at: string | null;
+ /**
+ * The deployment currently serving traffic for this project. Null if no deployment has ever succeeded.
+ * @nullable
+ */
+ readonly current_deployment: string | null;
+ /** True when the project has both a provisioned Cloudflare backend and a configured GitHub credential — meaning a deploy can be triggered right now. */
+ readonly is_ready_to_deploy: boolean;
+ /** Timestamp when the project was created. */
+ readonly created_at: string;
+ /** Timestamp when the project was last modified. */
+ readonly updated_at: string;
}
export interface DeprovisionWarehouseResponse {
@@ -21148,6 +21302,15 @@ export namespace Schemas {
results: Dataset[];
}
+ export interface PaginatedDeploymentEventList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: DeploymentEvent[];
+ }
+
export interface PaginatedDeploymentList {
count: number;
/** @nullable */
@@ -21157,6 +21320,15 @@ export namespace Schemas {
results: Deployment[];
}
+ export interface PaginatedDeploymentProjectList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: DeploymentProject[];
+ }
+
export interface PaginatedDesktopRecordingList {
count: number;
/** @nullable */
@@ -25371,6 +25543,75 @@ export namespace Schemas {
readonly team?: number;
}
+ export interface PatchedDeploymentProject {
+ /** Unique identifier for the deployment project. */
+ readonly id?: string;
+ /**
+ * Human-readable project name shown in the UI.
+ * @maxLength 200
+ */
+ name?: string;
+ /**
+ * URL-safe handle. Combined with the team id to form the Cloudflare project name; the actual subdomain comes from Cloudflare and is returned in the read-only `subdomain` field. Must be unique per team.
+ * @maxLength 80
+ * @pattern ^[-a-zA-Z0-9_]+$
+ */
+ slug?: string;
+ /**
+ * HTTPS URL of the source repository this project deploys from.
+ * @maxLength 1024
+ */
+ repo_url?: string;
+ /**
+ * Branch the project deploys from when no commit SHA is pinned. Defaults to `main`.
+ * @maxLength 255
+ */
+ default_branch?: string;
+ /**
+ * ID of the `posthog.Integration` row (kind=github) the project uses to read this repository. Must belong to the same team. The actual access token lives on the Integration row and is never exposed through this serializer.
+ * @nullable
+ */
+ github_integration?: number | null;
+ /**
+ * Optional shell command run inside the build container. Null = the build worker infers it from `framework` (or auto-detection if framework is also null).
+ * @nullable
+ */
+ build_command?: string | null;
+ /**
+ * Directory containing the built static site, relative to the repository root.
+ * @maxLength 255
+ */
+ output_dir?: string;
+ /**
+ * Optional framework hint (e.g. `nextjs`, `vite`, `astro`). Null = auto-detect.
+ * @maxLength 50
+ * @nullable
+ */
+ framework?: string | null;
+ /** If true, the build injects a PostHog snippet into every HTML file that registers `release = deployment_id` as a super-property — runtime exceptions are then linked back to the deployment that introduced them. */
+ inject_posthog_snippet?: boolean;
+ /** Cloudflare Pages project name, assigned during provisioning. */
+ readonly cloudflare_project_name?: string;
+ /** Public subdomain at which deployments of this project serve. */
+ readonly subdomain?: string;
+ /**
+ * Timestamp when the Cloudflare project was fully provisioned and ready to receive deploys.
+ * @nullable
+ */
+ readonly cloudflare_ready_at?: string | null;
+ /**
+ * The deployment currently serving traffic for this project. Null if no deployment has ever succeeded.
+ * @nullable
+ */
+ readonly current_deployment?: string | null;
+ /** True when the project has both a provisioned Cloudflare backend and a configured GitHub credential — meaning a deploy can be triggered right now. */
+ readonly is_ready_to_deploy?: boolean;
+ /** Timestamp when the project was created. */
+ readonly created_at?: string;
+ /** Timestamp when the project was last modified. */
+ readonly updated_at?: string;
+ }
+
export interface PatchedDesktopRecording {
readonly id?: string;
readonly team?: number;
@@ -40922,7 +41163,7 @@ export namespace Schemas {
search?: string;
};
- export type DeploymentsListParams = {
+ export type DeploymentProjectsListParams = {
/**
* Number of results to return per page.
*/
@@ -40931,6 +41172,52 @@ export namespace Schemas {
* The initial index from which to return the results.
*/
offset?: number;
+ /**
+ * Which field to use when ordering the results.
+ */
+ ordering?: string;
+ /**
+ * A search term.
+ */
+ search?: string;
+ };
+
+ export type DeploymentProjectsDeploymentsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ /**
+ * Which field to use when ordering the results.
+ */
+ ordering?: string;
+ /**
+ * A search term.
+ */
+ search?: string;
+ };
+
+ export type DeploymentProjectsDeploymentsEventsListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ /**
+ * Which field to use when ordering the results.
+ */
+ ordering?: string;
+ /**
+ * A search term.
+ */
+ search?: string;
};
export type EarlyAccessFeatureListParams = {
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index 506469d23f57..88ef08614f20 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -49,6 +49,8 @@ export const OAUTH_SCOPES_SUPPORTED = [
'dashboard_template:write',
'dataset:read',
'dataset:write',
+ 'deployment:read',
+ 'deployment:write',
'desktop_recording:read',
'desktop_recording:write',
'early_access_feature:read',
diff --git a/tach.toml b/tach.toml
index f22fc10521de..34964b385ce8 100644
--- a/tach.toml
+++ b/tach.toml
@@ -182,6 +182,11 @@ layer = "modules"
path = "products.deployments"
depends_on = [
"posthog",
+ # `error_tracking` is not isolated (no contract-check script), so we
+ # import its model directly to upsert an ErrorTrackingRelease row on
+ # successful deploys. If error_tracking later isolates, replace this
+ # raw dep with a facade call (`upsert_release(...)`).
+ "products.error_tracking",
]
layer = "modules"