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.

chore(deployments): remove hackathon deployments product (#61059)

Richard Solomou49cedeae33ed
diff --git a/frontend/package.json b/frontend/package.json
index 99d82904855b..c20770c5b5c1 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -83,7 +83,6 @@
"@posthog/products-data-modeling": "workspace:*",
"@posthog/products-data-tools": "workspace:*",
"@posthog/products-data-warehouse": "workspace:*",
- "@posthog/products-deployments": "workspace:*",
"@posthog/products-early-access-features": "workspace:*",
"@posthog/products-endpoints": "workspace:*",
"@posthog/products-engineering-analytics": "workspace:*",
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f8b874f4428c..27a30d2627ef 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -4618,34 +4618,6 @@ snapshots:
hash: v1.k794b7964.8a77e7a0171fcd435c6595297bf027b8f0a241439ee5921ba1e98ac8989fde19.heCouatVYmHaFYRqmD6XBpq_K1abbgOOnCJSBR9O1ok
scenes-app-data-warehouse-settings-schemas--default--light:
hash: v1.k794b7964.f44aebec23a383bf47c5310e229767e329dc9a52d220851265c86e2531dfd8f6.cg8SBdNPjYob5gTIonGhj0QupXWDzvTSG73043B7QEk
- scenes-app-deployments--deployment-detail--dark:
- hash: v1.k794b7964.730cf1e1893098848eb94256ee69b47079f4e8b52e1c353df23c21064d1e95f5.Isj5Cg427JNnbPPltSPxKH5wtPIbErCVOOQo-yOBsrE
- scenes-app-deployments--deployment-detail--light:
- hash: v1.k794b7964.3b1f90f25565620345e1b7c14e47b472216f6af2cf5770dedf363db49dd654bc.siJOXse4AEatFHf6QbHz15PfeqP3uS-IbBA7Oslz9eo
- scenes-app-deployments--no-projects--dark:
- hash: v1.k794b7964.a327fbfc54655dc5dd43143ba568a61e9b1b33f216fac06acfd0f2c0ebb7a503.Njv3HWsi9qD8vRi2JAOpcFY11BHVhhneNJ6DB9G91Lw
- scenes-app-deployments--no-projects--light:
- hash: v1.k794b7964.495253b3e454a856d703f8cc062bcc3721ebb45eee67e6c5e98a924b4b799316.MamPpGZnjp-CZvvtiG0AA0ge6KEPXYN0I5-nX5RbaR4
- scenes-app-deployments--project-grid--dark:
- hash: v1.k794b7964.dc3cdc37f995a9406e2fb6500c847db69945a6f657063e8a56f4b51b8a52047b.gsPEbsMTuamePItJTXjd7xPjJCxmM_-Z7MKAT2nr454
- scenes-app-deployments--project-grid--light:
- hash: v1.k794b7964.284bbd10d1170278d7f4cdc95fd76a41aeb31eb47f018d1b50171195fdcab6bd.YHtCzn7NJnzpQZme0YtIhsCjKPB-bH7FkL5DGbA2yIQ
- scenes-app-deployments--project-page--dark:
- hash: v1.k794b7964.72cab7519d9528bd14b964ecd4baf8782785721ee81cbfd3a61a9835ca9c90ff.FKZL-TLySm45d7LC5XwmVn0jLzRo3_6tqONzqak6XVc
- scenes-app-deployments--project-page--light:
- hash: v1.k794b7964.1cca04bcacc6eacd642ff7c57450011984813b4892329f0ec36f6f2c4b5b6948.JjotFOfPbb2bYddwSLHlLGwQKA22Qs3zMGavVVsh_hs
- scenes-app-deployments--project-page-current-errored--dark:
- hash: v1.k794b7964.fb02344bb3b5cafb929508bb62efaca633763f346b0559816d13f2cd62896c03.fiLuUb1vMr07C5z9u1ahtgp2-0aEbb4SdeMHAj3gEI8
- scenes-app-deployments--project-page-current-errored--light:
- hash: v1.k794b7964.9a7c00a70ae13d4b664146846c22f0ce5dc274de23b80bcc413c609fa9b26e64.1gzhgwNLbEYeKQSerPqHvC3gufWhhx-EkHIy6PzKmeY
- scenes-app-deployments--project-page-no-deployments--dark:
- hash: v1.k794b7964.a0a9f2923a7b7d59d5dad6fb46fa6bed3e7eea0181f76db52cc0b47a24c223e4.JSF4JyAmTZrldM5j1xSmo2NP4zwypD2QuBVWfIj9YwE
- scenes-app-deployments--project-page-no-deployments--light:
- hash: v1.k794b7964.72af12f4ae90499f2d610935b110772f896cc2bbe05961db7b608a52805d8f8f.DhNdzNrxL0WjEp4Z9Hxxc0OeA4vg17dqtE7DcR9hnmo
- scenes-app-deployments--single-project-grid--dark:
- hash: v1.k794b7964.e37fb8c0a3875956192aea719b91594172ff19876dba963f27fda51773cd2184.rcL8zcm0Gg08zdmH9r8EFHsgtm3BUt0rY5h-CJEzJgY
- scenes-app-deployments--single-project-grid--light:
- hash: v1.k794b7964.e6423eb6dc9a6a60fbb03162efd63905fc6f08639c42da93f62711a6728f02dc.mBfArZvqFDtXeVckWTp78JkvWtebD9-C84-3PF1gLwo
scenes-app-error-project-unavailable--access-revoked--dark:
hash: v1.k794b7964.551951688a4131cbd9c0d08e553c79238fb9831c6e227e3854eb3596a95d5725.lEJkOr35uSHLqc-IqIYv7Z2bc4-rjbJut0zmTNBae6Y
scenes-app-error-project-unavailable--access-revoked--light:
diff --git a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
index 2fb1cdbe12e7..a564248d8229 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/defaultTree.tsx
@@ -7,7 +7,6 @@ import {
IconBug,
IconCircleDashed,
IconClock,
- IconCloud,
IconCode,
IconEndpoints,
IconEye,
@@ -351,10 +350,6 @@ const iconTypes: Record<FileSystemIconType, { icon: JSX.Element; iconColor?: Fil
exports: {
icon: <IconDownload />,
},
- deployments: {
- icon: <IconCloud />,
- iconColor: ['var(--color-product-deployments-light)', 'var(--color-product-deployments-dark)'],
- },
}
const getIconColor = (type?: string, colorOverride?: FileSystemIconColor): FileSystemIconColor => {
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 632c06d4e8ef..e884ee269930 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -269,7 +269,6 @@ export const FEATURE_FLAGS = {
DATA_MODELING_TAB: 'data-modeling-tab', // owner: #team-data-modeling
DATA_WAREHOUSE_SCENE: 'data-warehouse-scene', // owner: #team-data-modeling
DEFAULT_EVALUATION_ENVIRONMENTS: 'default-evaluation-environments', // owner: @dmarticus #team-feature-flags
- DEPLOYMENTS: 'deployments', // owner: @richardsolomou
DROP_PERSON_LIST_ORDER_BY: 'drop-person-list-order-by', // owner: @arthurdedeus #team-customer-analytics
DWH_FREE_SYNCS: 'dwh-free-syncs', // owner: @Gilbert09 #team-warehouse-sources
DWH_JOIN_TABLE_PREVIEW: 'dwh-join-table-preview', // owner: @arthurdedeus #team-customer-analytics
diff --git a/frontend/src/lib/scopes.tsx b/frontend/src/lib/scopes.tsx
index 7dcedda41f4c..58dc0edb7ea8 100644
--- a/frontend/src/lib/scopes.tsx
+++ b/frontend/src/lib/scopes.tsx
@@ -30,7 +30,6 @@ export const API_SCOPES: APIScope[] = [
{ key: 'dashboard', objectName: 'Dashboard', objectPlural: 'dashboards' },
{ key: 'dashboard_template', objectName: 'Dashboard template', objectPlural: 'dashboard templates' },
{ key: 'dataset', objectName: 'Dataset', objectPlural: 'datasets' },
- { key: 'deployment', objectName: 'Deployment', objectPlural: 'deployments' },
{ key: 'desktop_recording', objectName: 'Desktop recording', objectPlural: 'desktop recordings' },
{ key: 'early_access_feature', objectName: 'Early access feature', objectPlural: 'early access features' },
{ key: 'element', objectName: 'Element', objectPlural: 'elements' },
diff --git a/frontend/src/products.json b/frontend/src/products.json
index 046e7c4f0b6b..83cf179622d9 100644
--- a/frontend/src/products.json
+++ b/frontend/src/products.json
@@ -98,13 +98,6 @@
"type": null,
"intents": ["data_warehouse", "data_warehouse_saved_queries"]
},
- {
- "path": "Deployments",
- "category": "Tools",
- "iconType": null,
- "type": "deployments",
- "intents": ["deployments"]
- },
{
"path": "Early access features",
"category": "Features",
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index ac0f1922e011..7aa96d3aa7e5 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -98,9 +98,6 @@ export const productScenes: Record<string, () => Promise<any>> = {
DataWarehouseSource: () => import('../../products/data_warehouse/frontend/scenes/SourceScene/SourceScene'),
DataWarehouseSourceNew: () => import('../../products/data_warehouse/frontend/scenes/NewSourceScene/NewSourceScene'),
DataWarehouseSourceSchema: () => import('../../products/data_warehouse/frontend/scenes/SchemaScene/SchemaScene'),
- Deployments: () => import('../../products/deployments/frontend/Deployments'),
- DeploymentProject: () => import('../../products/deployments/frontend/DeploymentProject'),
- Deployment: () => import('../../products/deployments/frontend/Deployment'),
EarlyAccessFeatures: () => import('../../products/early_access_features/frontend/EarlyAccessFeatures'),
EarlyAccessFeature: () => import('../../products/early_access_features/frontend/EarlyAccessFeature'),
EndpointsScene: () => import('../../products/endpoints/frontend/EndpointsScene'),
@@ -223,9 +220,6 @@ export const productRoutes: Record<string, [string, string]> = {
],
'/data-management/sources/:id/:tab': ['DataWarehouseSource', 'dataWarehouseSource'],
'/data-warehouse/new-source': ['DataWarehouseSourceNew', 'dataWarehouseSourceNew'],
- '/deployments': ['Deployments', 'deployments'],
- '/deployments/:projectId': ['DeploymentProject', 'deploymentProject'],
- '/deployments/:projectId/:deploymentId': ['Deployment', 'deployment'],
'/early_access_features': ['EarlyAccessFeatures', 'earlyAccessFeatures'],
'/early_access_features/:id': ['EarlyAccessFeature', 'earlyAccessFeature'],
'/endpoints': ['EndpointsScene', 'endpoints'],
@@ -600,14 +594,6 @@ export const productConfiguration: Record<string, any> = {
DataWarehouseSource: { projectBased: true, name: 'Data warehouse source' },
DataWarehouseSourceNew: { projectBased: true, name: 'New data warehouse source' },
DataWarehouseSourceSchema: { projectBased: true, name: 'Data warehouse schema' },
- Deployments: {
- projectBased: true,
- name: 'Deployments',
- iconType: 'deployments',
- description: 'Connect a GitHub repository to start deploying your site.',
- },
- DeploymentProject: { projectBased: true, name: 'Deployment project' },
- Deployment: { projectBased: true, name: 'Deployment' },
EarlyAccessFeatures: {
name: 'Early access features',
projectBased: true,
@@ -941,9 +927,6 @@ export const productUrls = {
const queryString = params.toString()
return `/data-warehouse/new-source${queryString ? `?${queryString}` : ''}`
},
- deployments: (): string => '/deployments',
- deploymentProject: (projectId: string): string => `/deployments/${projectId}`,
- deployment: (projectId: string, deploymentId: string): string => `/deployments/${projectId}/${deploymentId}`,
earlyAccessFeatures: (): string => '/early_access_features',
earlyAccessFeature: (id: string): string => `/early_access_features/${id}`,
endpoints: (): string => '/endpoints',
@@ -1238,13 +1221,6 @@ export const fileSystemTypes = {
iconColor: ['var(--color-product-dashboards-light)'],
filterKey: 'dashboard',
},
- deployments: {
- name: 'Deployment',
- iconType: 'deployments',
- iconColor: ['var(--color-product-deployments-light)'] as FileSystemIconColor,
- href: () => urls.deployments(),
- filterKey: 'deployments',
- },
early_access_feature: {
name: 'Early access feature',
iconType: 'early_access_feature' as FileSystemIconType,
@@ -1624,22 +1600,6 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [
'AIObservabilityCluster',
],
},
- {
- path: 'Deployments',
- intents: [ProductKey.DEPLOYMENTS],
- category: ProductItemCategory.TOOLS,
- href: urls.deployments(),
- type: 'deployments',
- iconType: 'deployments' as FileSystemIconType,
- iconColor: [
- 'var(--color-product-deployments-light)',
- 'var(--color-product-deployments-dark)',
- ] as FileSystemIconColor,
- sceneKey: 'Deployments',
- sceneKeys: ['Deployments', 'DeploymentProject', 'Deployment'],
- flag: FEATURE_FLAGS.DEPLOYMENTS,
- tags: ['alpha'],
- },
{
path: 'Early access features',
intents: [ProductKey.EARLY_ACCESS_FEATURES],
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 842d4ed9edf7..9e118b307a66 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -20342,8 +20342,7 @@
"llm_playground",
"llm_prompts",
"llm_clusters",
- "exports",
- "deployments"
+ "exports"
],
"type": "string"
},
@@ -29005,7 +29004,6 @@
"customer_analytics",
"data_warehouse",
"data_warehouse_saved_queries",
- "deployments",
"early_access_features",
"endpoints",
"error_tracking",
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index a2908e6ceedc..639f63ecab58 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -3384,7 +3384,6 @@ export type FileSystemIconType =
| 'llm_prompts'
| 'llm_clusters'
| 'exports'
- | 'deployments'
export interface FileSystemImport extends Omit<FileSystemEntry, 'id'> {
id?: string
@@ -6582,7 +6581,6 @@ export enum ProductKey {
CUSTOMER_ANALYTICS = 'customer_analytics',
DATA_WAREHOUSE = 'data_warehouse',
DATA_WAREHOUSE_SAVED_QUERY = 'data_warehouse_saved_queries',
- DEPLOYMENTS = 'deployments',
EARLY_ACCESS_FEATURES = 'early_access_features',
ENDPOINTS = 'endpoints',
ERROR_TRACKING = 'error_tracking',
diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.ts
index 03329d3e9683..cf01eea9d5f4 100644
--- a/frontend/src/scenes/sceneTypes.ts
+++ b/frontend/src/scenes/sceneTypes.ts
@@ -63,9 +63,6 @@ export enum Scene {
Subscription = 'Subscription',
ExperimentsSharedMetric = 'ExperimentsSharedMetric',
ExperimentsSharedMetrics = 'ExperimentsSharedMetrics',
- Deployment = 'Deployment',
- DeploymentProject = 'DeploymentProject',
- Deployments = 'Deployments',
ExploreEvents = 'ExploreEvents',
ExploreSessions = 'ExploreSessions',
FeatureFlag = 'FeatureFlag',
diff --git a/frontend/src/styles/base.scss b/frontend/src/styles/base.scss
index 36e392ddd86c..de5859f7f5e3 100644
--- a/frontend/src/styles/base.scss
+++ b/frontend/src/styles/base.scss
@@ -348,8 +348,6 @@
--color-product-early-access-features-dark: rgb(53 213 189);
--color-product-support-light: rgb(243 84 84);
--color-product-support-dark: rgb(247 165 1);
- --color-product-deployments-light: rgb(220 38 38);
- --color-product-deployments-dark: rgb(248 113 113);
// Insight colors
--color-insight-funnel-light: rgb(47 128 250);
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index ccf53c8f1a85..ac81fe9eebda 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -5378,7 +5378,6 @@ export type APIScopeObject =
| 'dashboard'
| 'dashboard_template'
| 'dataset'
- | 'deployment'
| 'desktop_recording'
| 'early_access_feature'
| 'element'
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2a6eae5dd094..dea42707cbbe 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -627,9 +627,6 @@ importers:
'@posthog/products-data-warehouse':
specifier: workspace:*
version: link:../products/data_warehouse
- '@posthog/products-deployments':
- specifier: workspace:*
- version: link:../products/deployments
'@posthog/products-early-access-features':
specifier: workspace:*
version: link:../products/early_access_features
@@ -2507,37 +2504,6 @@ importers:
specifier: 18.3.1
version: 18.3.1
- products/deployments:
- dependencies:
- '@posthog/icons':
- specifier: '*'
- '@types/react':
- specifier: 18.3.27
- version: 18.3.27
- kea:
- specifier: 'catalog:'
- version: 4.0.0-pre.5([email protected])
- kea-loaders:
- specifier: 'catalog:'
- kea-router:
- specifier: 'catalog:'
- posthog-js:
- specifier: 'catalog:'
- version: 1.378.1
- react:
- specifier: 18.3.1
- version: 18.3.1
- devDependencies:
- '@storybook/react':
- specifier: 'catalog:'
- kea-test-utils:
- specifier: 'catalog:'
-
products/desktop_recordings: {}
products/early_access_features:
diff --git a/posthog/api/__init__.py b/posthog/api/__init__.py
index d375463dde1f..52ba5597bbbf 100644
--- a/posthog/api/__init__.py
+++ b/posthog/api/__init__.py
@@ -22,7 +22,6 @@ import products.tasks.backend.api as tasks
import products.endpoints.backend.api as endpoints
import products.signals.backend.views as signals
import products.tasks.backend.seat_api as seats
-import products.deployments.backend.api as deployments
import products.alerts.backend.api.alert as alert
import products.conversations.backend.api as conversations
import products.live_debugger.backend.api as live_debugger
@@ -359,22 +358,6 @@ projects_router.register(
"project_wizard_sessions",
["project_id"],
)
-# 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_deployment_projects_deployments",
- ["project_id", "deployment_project_id"],
-)
-
# Tasks endpoints
project_tasks_router = projects_router.register(r"tasks", tasks.TaskViewSet, "project_tasks", ["team_id"])
project_tasks_router.register(r"runs", tasks.TaskRunViewSet, "project_task_runs", ["team_id", "task_id"])
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index e232c3f6a4b5..a95566df2b6d 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -167,10 +167,6 @@ from products.batch_exports.backend.temporal import (
ACTIVITIES as BATCH_EXPORTS_ACTIVITIES,
WORKFLOWS as BATCH_EXPORTS_WORKFLOWS,
)
-from products.deployments.backend.temporal import (
- ACTIVITIES as DEPLOYMENTS_ACTIVITIES,
- WORKFLOWS as DEPLOYMENTS_WORKFLOWS,
-)
from products.logs.backend.temporal import (
ACTIVITIES as LOGS_ALERTING_ACTIVITIES,
WORKFLOWS as LOGS_ALERTING_WORKFLOWS,
@@ -351,11 +347,6 @@ _task_queue_specs = [
LOGS_ALERTING_WORKFLOWS,
LOGS_ALERTING_ACTIVITIES,
),
- (
- settings.DEPLOYMENTS_TASK_QUEUE,
- DEPLOYMENTS_WORKFLOWS,
- DEPLOYMENTS_ACTIVITIES,
- ),
]
# Note: When running locally, many task queues resolve to the same queue name.
diff --git a/posthog/rbac/user_access_control.py b/posthog/rbac/user_access_control.py
index db1ba14fc454..355343c3da20 100644
--- a/posthog/rbac/user_access_control.py
+++ b/posthog/rbac/user_access_control.py
@@ -303,11 +303,6 @@ def model_to_resource(model: Model) -> Optional[APIScopeObject]:
return "customer_journey"
if name in ("replayscanner", "replayobservation"):
return "replay_scanner"
- 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/schema.py b/posthog/schema.py
index ff7a7c0485df..7fc33f91e8dd 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -2402,7 +2402,6 @@ class FileSystemIconType(StrEnum):
LLM_PROMPTS = "llm_prompts"
LLM_CLUSTERS = "llm_clusters"
EXPORTS = "exports"
- DEPLOYMENTS = "deployments"
class FileSystemViewLogEntry(BaseModel):
@@ -4024,7 +4023,6 @@ class ProductKey(StrEnum):
CUSTOMER_ANALYTICS = "customer_analytics"
DATA_WAREHOUSE = "data_warehouse"
DATA_WAREHOUSE_SAVED_QUERIES = "data_warehouse_saved_queries"
- DEPLOYMENTS = "deployments"
EARLY_ACCESS_FEATURES = "early_access_features"
ENDPOINTS = "endpoints"
ERROR_TRACKING = "error_tracking"
diff --git a/posthog/scopes.py b/posthog/scopes.py
index db684f0a3692..8de016f982ac 100644
--- a/posthog/scopes.py
+++ b/posthog/scopes.py
@@ -35,7 +35,6 @@ APIScopeObject = Literal[
"event_filter",
"dashboard_template",
"dataset",
- "deployment",
"desktop_recording",
"early_access_feature",
"endpoint",
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index 6ef53a5d08ca..9be09e8ff107 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -113,5 +113,4 @@ LLMA_SENTIMENT_TASK_QUEUE = _set_temporal_task_queue("llm-analytics-sentiment-ta
LLMA_TASK_QUEUE = _set_temporal_task_queue("llm-analytics-task-queue")
EVENT_SCREENSHOTS_TASK_QUEUE = _set_temporal_task_queue("event-screenshots-task-queue")
LOGS_ALERTING_TASK_QUEUE = _set_temporal_task_queue("logs-alerting-task-queue")
-DEPLOYMENTS_TASK_QUEUE = _set_temporal_task_queue("deployments-task-queue")
RASTERIZATION_TASK_QUEUE = "rasterization-task-queue" # Not collapsed in dev — separate Node.js worker process
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 94e20907b8ca..7b8a8a946eb5 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -75,7 +75,6 @@ PRODUCTS_APPS = [
"products.access_control.backend.apps.AccessControlConfig",
"products.warehouse_sources_queue.backend.apps.WarehouseSourcesQueueConfig",
"products.business_knowledge.backend.apps.BusinessKnowledgeConfig",
- "products.deployments.backend.apps.DeploymentsConfig",
"products.web_analytics.backend.apps.WebAnalyticsConfig",
"products.warehouse_sources.backend.apps.WarehouseSourcesConfig",
"products.data_tools.backend.apps.DataToolsConfig",
@@ -634,20 +633,6 @@ CLOUDFLARE_ZONE_ID = get_from_env("CLOUDFLARE_ZONE_ID", "")
CLOUDFLARE_WORKER_NAME = get_from_env("CLOUDFLARE_WORKER_NAME", "")
CLOUDFLARE_PROXY_BASE_CNAME = get_from_env("CLOUDFLARE_PROXY_BASE_CNAME", "")
-# Single-tenant Cloudflare Pages settings for the Deployments product.
-# Separate from the SaaS proxy block above: different account scope (Pages,
-# not Workers + DNS for posthog.com) and a different zone (hog.dev).
-DEPLOYMENTS_CLOUDFLARE_ACCOUNT_ID = get_from_env("DEPLOYMENTS_CLOUDFLARE_ACCOUNT_ID", "")
-DEPLOYMENTS_CLOUDFLARE_API_TOKEN = get_from_env("DEPLOYMENTS_CLOUDFLARE_API_TOKEN", "")
-DEPLOYMENTS_HOG_DEV_ZONE_ID = get_from_env("DEPLOYMENTS_HOG_DEV_ZONE_ID", "")
-DEPLOYMENTS_CLOUDFLARE_PROJECT_PREFIX = get_from_env("DEPLOYMENTS_CLOUDFLARE_PROJECT_PREFIX", "hogdev-")
-
-# Base URL the deployments Temporal worker uses when calling back into
-# the internal API. Worker pods in the same cluster set this to the
-# cluster-internal Service URL (e.g. http://posthog-web-django.posthog
-# .svc.cluster.local:8000). Empty value falls back to SITE_URL.
-DEPLOYMENTS_INTERNAL_API_BASE_URL = get_from_env("DEPLOYMENTS_INTERNAL_API_BASE_URL", "")
-
# Domain Connect (automated DNS configuration)
DOMAIN_CONNECT_PRIVATE_KEY: str | None = os.getenv("DOMAIN_CONNECT_PRIVATE_KEY", "").replace("\\n", "\n") or None
DOMAIN_CONNECT_KEY_ID: str = os.getenv("DOMAIN_CONNECT_KEY_ID", "_dcpubkeyv1")
diff --git a/posthog/urls.py b/posthog/urls.py
index d539f46e8e9a..56e1e8b4ded7 100644
--- a/posthog/urls.py
+++ b/posthog/urls.py
@@ -51,7 +51,6 @@ from posthog.temporal.codec_server import decode_payloads
from products.ai_observability.backend.api.personal_spend import personal_spend_eu_redirect
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
@@ -342,15 +341,6 @@ 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/__init__.py b/products/deployments/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/deployments/backend/__init__.py b/products/deployments/backend/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/deployments/backend/access.py b/products/deployments/backend/access.py
deleted file mode 100644
index 6b413f952bd5..000000000000
--- a/products/deployments/backend/access.py
+++ /dev/null
@@ -1,31 +0,0 @@
-"""Feature-flag gate for the Deployments product.
-
-Access is gated on the `deployments` feature flag. Rollout (e.g. limiting to
-specific teams or organizations) is configured on the flag itself in the
-PostHog admin — code only asks 'is this enabled for this user / team?' and
-returns the answer.
-"""
-
-from django.contrib.auth.models import AbstractBaseUser, AnonymousUser
-
-import posthoganalytics
-
-
-def has_deployments_access(user: AbstractBaseUser | AnonymousUser | None, *, team_id: int | None = None) -> bool:
- # Accept the union DRF gives us on `request.user` (authenticated User or AnonymousUser).
- # Bail on anything that can't carry a distinct_id — the flag check below needs one.
- if not user or not user.is_authenticated:
- return False
- distinct_id = getattr(user, "distinct_id", None)
- if not distinct_id:
- return False
-
- kwargs: dict = {
- "only_evaluate_locally": False,
- "send_feature_flag_events": False,
- }
- if team_id is not None:
- kwargs["groups"] = {"project": str(team_id)}
- kwargs["group_properties"] = {"project": {"id": str(team_id)}}
-
- return bool(posthoganalytics.feature_enabled("deployments", distinct_id, **kwargs))
diff --git a/products/deployments/backend/adapters/__init__.py b/products/deployments/backend/adapters/__init__.py
deleted file mode 100644
index 5d7d6c0ac39a..000000000000
--- a/products/deployments/backend/adapters/__init__.py
+++ /dev/null
@@ -1,46 +0,0 @@
-"""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, most adapters default to a `Null*` stub
-that returns canned values. GitHub repository reads use the existing PostHog
-GitHub integration by default, while deployment commit resolution remains
-stubbed until the build stream owns that contract.
-"""
-
-from .cloudflare import (
- CloudflareAdapter,
- CloudflareError,
- CloudflarePagesAdapter,
- NullCloudflareAdapter,
- get_cloudflare_adapter,
-)
-from .github import GitHubAdapter, GitHubBranch, GitHubError, GitHubRepository, NullGitHubAdapter, get_github_adapter
-from .microlink import NullScreenshotAdapter, ScreenshotAdapter, get_screenshot_adapter
-from .temporal import NullWorkflowAdapter, TemporalWorkflowAdapter, WorkflowAdapter, WorkflowError, get_workflow_adapter
-
-__all__ = [
- "CloudflareAdapter",
- "CloudflareError",
- "CloudflarePagesAdapter",
- "GitHubAdapter",
- "GitHubBranch",
- "GitHubError",
- "GitHubRepository",
- "NullCloudflareAdapter",
- "NullGitHubAdapter",
- "NullScreenshotAdapter",
- "NullWorkflowAdapter",
- "ScreenshotAdapter",
- "TemporalWorkflowAdapter",
- "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
deleted file mode 100644
index ff72d087e8dc..000000000000
--- a/products/deployments/backend/adapters/cloudflare.py
+++ /dev/null
@@ -1,227 +0,0 @@
-"""Cloudflare Pages adapter boundary.
-
-Declares the Protocol the rest of the product depends on, a Null stub
-for tests and dev, and `CloudflarePagesAdapter` — the real implementation
-that calls the Cloudflare Pages REST API. The resolver
-`get_cloudflare_adapter()` returns the Null stub unless
-`DEPLOYMENTS_CLOUDFLARE_ADAPTER` is wired to point at the real class,
-which happens via chart values once the API token is in place.
-"""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-from importlib import import_module
-from typing import Any, Protocol
-
-from django.conf import settings
-
-import requests
-import structlog
-
-# Tight timeout — `create_project` runs synchronously on the public POST
-# /deployment_projects/ request path. Anything longer hurts user-visible
-# latency more than it helps a flaky CF response.
-CLOUDFLARE_API_TIMEOUT_SECONDS = 10
-CLOUDFLARE_API_BASE = "https://api.cloudflare.com/client/v4"
-HOG_DEV_ZONE = "hog.dev"
-
-logger = structlog.get_logger(__name__)
-
-
-@dataclass(frozen=True)
-class CFProject:
- """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")
-
-
-class CloudflarePagesAdapter:
- """Cloudflare Pages adapter backed by the real REST API.
-
- Resolves settings lazily (at call time, not import time) so missing
- env vars only blow up when the adapter is actually exercised. This
- keeps test environments and the Null path unaffected by the real
- adapter's deployment-dependent config.
-
- `create_project` creates the Pages project and attaches a custom
- domain under `hog.dev` in a single call sequence. The custom domain
- attachment relies on the `hog.dev` zone living in the same CF
- account as the project — Cloudflare then auto-creates the CNAME
- record in the zone, so DNS records aren't managed from this side.
- """
-
- def _config(self) -> tuple[str, str, str]:
- account_id = getattr(settings, "DEPLOYMENTS_CLOUDFLARE_ACCOUNT_ID", "")
- api_token = getattr(settings, "DEPLOYMENTS_CLOUDFLARE_API_TOKEN", "")
- project_prefix = getattr(settings, "DEPLOYMENTS_CLOUDFLARE_PROJECT_PREFIX", "")
- if not account_id or not api_token:
- raise CloudflareError(
- "CloudflarePagesAdapter is missing required settings: "
- "DEPLOYMENTS_CLOUDFLARE_ACCOUNT_ID and DEPLOYMENTS_CLOUDFLARE_API_TOKEN."
- )
- return account_id, api_token, project_prefix
-
- def _request(self, method: str, path: str, *, api_token: str, json: dict[str, Any] | None = None) -> dict[str, Any]:
- url = f"{CLOUDFLARE_API_BASE}{path}"
- headers = {"Authorization": f"Bearer {api_token}", "Content-Type": "application/json"}
- try:
- response = requests.request(method, url, headers=headers, json=json, timeout=CLOUDFLARE_API_TIMEOUT_SECONDS)
- except requests.RequestException as err:
- # Path contains the CF account ID and is logged internally
- # for ops, but is intentionally kept out of the exception
- # message — `CloudflareError` is rendered into the public
- # 502 response body by the viewset.
- logger.warning("cloudflare_api_network_error", method=method, path=path, error=str(err))
- raise CloudflareError(f"Cloudflare API request failed: {err}") from err
-
- try:
- body = response.json()
- except ValueError as err:
- logger.warning("cloudflare_api_non_json_response", method=method, path=path, status=response.status_code)
- raise CloudflareError(
- f"Cloudflare API returned non-JSON response (status {response.status_code})."
- ) from err
-
- if not response.ok or not body.get("success", False):
- errors = body.get("errors") or []
- # Fall back to "Unknown error" rather than letting `None` slip
- # into the user-facing message when the error dict is missing
- # `"message"` (or `response.reason` is None for a malformed
- # response).
- message = (
- errors[0].get("message", "Unknown error")
- if errors and isinstance(errors[0], dict)
- else (response.reason or "Unknown error")
- )
- logger.warning(
- "cloudflare_api_call_failed",
- method=method,
- path=path,
- status=response.status_code,
- message=message,
- )
- raise CloudflareError(f"Cloudflare API call failed: {message} (status {response.status_code})")
-
- result = body.get("result")
- if not isinstance(result, dict):
- logger.warning("cloudflare_api_unexpected_result_shape", method=method, path=path)
- raise CloudflareError("Cloudflare API returned an unexpected result shape.")
- return result
-
- def create_project(self, *, name: str, production_branch: str) -> CFProject:
- account_id, api_token, project_prefix = self._config()
- cf_project_name = f"{project_prefix}{name}"
- create_path = f"/accounts/{account_id}/pages/projects"
- project_path = f"{create_path}/{cf_project_name}"
-
- self._request(
- "POST",
- create_path,
- api_token=api_token,
- json={"name": cf_project_name, "production_branch": production_branch},
- )
-
- # Attach the customer-facing `<name>.hog.dev` custom domain. CF
- # creates the CNAME in the hog.dev zone automatically because the
- # zone and the project live in the same account. The CF Pages
- # project's own `*.pages.dev` URL still works, but `subdomain`
- # below is what the product surfaces to the user.
- custom_domain = f"{name}.{HOG_DEV_ZONE}"
- try:
- self._request("POST", f"{project_path}/domains", api_token=api_token, json={"name": custom_domain})
- except CloudflareError:
- # The project create succeeded but the domain attach failed.
- # The CF project name is deterministic (`{prefix}{team_id}-{slug}`),
- # so leaving the orphan would block the user's next retry with
- # "Project name already taken". Best-effort cleanup; if the
- # delete itself fails we still surface the original error.
- try:
- self._request("DELETE", project_path, api_token=api_token)
- except CloudflareError as cleanup_err:
- logger.warning(
- "cloudflare_orphan_cleanup_failed",
- project=cf_project_name,
- error=str(cleanup_err),
- )
- raise
-
- return CFProject(name=cf_project_name, subdomain=custom_domain)
-
- def rollback(self, *, project_name: str, deployment_id: str) -> CFDeployment:
- account_id, api_token, _ = self._config()
- result = self._request(
- "POST",
- f"/accounts/{account_id}/pages/projects/{project_name}/deployments/{deployment_id}/rollback",
- api_token=api_token,
- )
- # The rollback endpoint returns a deployment object. `url` is the
- # public URL of the deployment that's now serving production.
- url = result.get("url")
- if not isinstance(url, str) or not url:
- raise CloudflareError("Cloudflare rollback succeeded but returned no deployment URL.")
- new_deployment_id = result.get("id")
- if not isinstance(new_deployment_id, str) or not new_deployment_id:
- raise CloudflareError("Cloudflare rollback succeeded but returned no deployment id.")
- return CFDeployment(id=new_deployment_id, url=url)
-
-
-def get_cloudflare_adapter() -> CloudflareAdapter:
- """Resolve the adapter implementation from settings.
-
- Reads `settings.DEPLOYMENTS_CLOUDFLARE_ADAPTER` as a `"module.path:ClassName"`
- string; if unset, returns `NullCloudflareAdapter`. Wire the real
- implementation in by setting this env var to
- `products.deployments.backend.adapters.cloudflare:CloudflarePagesAdapter`.
- """
- path = getattr(settings, "DEPLOYMENTS_CLOUDFLARE_ADAPTER", None)
- if not path:
- 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
deleted file mode 100644
index 579322761190..000000000000
--- a/products/deployments/backend/adapters/github.py
+++ /dev/null
@@ -1,223 +0,0 @@
-"""GitHub adapter boundary.
-
-The rest of Deployments talks to GitHub through this module. For the
-hackathon path, repository selection uses the existing PostHog
-``Integration(kind="github")`` installation rather than a Deployments-specific
-GitHub App or live push webhooks.
-"""
-
-from __future__ import annotations
-
-import re
-from dataclasses import dataclass
-from importlib import import_module
-from typing import TYPE_CHECKING, Any, Protocol
-from urllib.parse import quote
-
-from django.conf import settings
-
-from posthog.models.github_integration_base import GitHubIntegrationError
-from posthog.models.integration import GitHubIntegration
-
-from ..domain.contracts import CommitMetadata
-
-if TYPE_CHECKING:
- from posthog.models.integration import Integration
-
-
-_REPO_FULL_NAME_RE = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")
-
-# TODO(deployments-v1): move request-path GitHub verification to async jobs before increasing retry budgets.
-DEPLOYMENTS_GITHUB_API_TIMEOUT_SECONDS = 2
-
-
-@dataclass(frozen=True)
-class GitHubRepository:
- id: int
- full_name: str
- default_branch: str
- html_url: str
-
-
-@dataclass(frozen=True)
-class GitHubBranch:
- name: str
- sha: str
-
-
-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: ...
-
- def get_repository_by_id(self, *, integration: Integration, github_repo_id: int) -> GitHubRepository: ...
-
- def get_repository(self, *, integration: Integration, repo_full_name: str) -> GitHubRepository: ...
-
- def get_branch(self, *, integration: Integration, repo_full_name: str, branch: str) -> GitHubBranch: ...
-
-
-class GitHubError(Exception):
- """Raised when a GitHub API call fails. Translated by callers."""
-
-
-def validate_repo_full_name(repo_full_name: str) -> None:
- if not _REPO_FULL_NAME_RE.fullmatch(repo_full_name):
- raise GitHubError("Repository must be in owner/repo format.")
- owner, repo = repo_full_name.split("/", 1)
- if owner in (".", "..") or repo in (".", ".."):
- raise GitHubError("Repository must be in owner/repo format.")
-
-
-def repo_url_from_full_name(repo_full_name: str) -> str:
- validate_repo_full_name(repo_full_name)
- return f"https://github.com/{repo_full_name}"
-
-
-class NullGitHubAdapter:
- """Stub used in tests and the dev environment for deployment commits.
-
- Repository/branch selection is implemented by ``GitHubIntegrationAdapter``
- below because it uses the existing Integration installation token. Commit
- resolution remains synthetic until the build stream wires the full clone
- credentials contract.
- """
-
- 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_repository_by_id(self, *, integration: Integration, github_repo_id: int) -> GitHubRepository:
- return GitHubRepository(
- id=github_repo_id,
- full_name="example-org/site",
- default_branch="main",
- html_url="https://github.com/example-org/site",
- )
-
- def get_repository(self, *, integration: Integration, repo_full_name: str) -> GitHubRepository:
- validate_repo_full_name(repo_full_name)
- return GitHubRepository(
- id=0,
- full_name=repo_full_name,
- default_branch="main",
- html_url=repo_url_from_full_name(repo_full_name),
- )
-
- def get_branch(self, *, integration: Integration, repo_full_name: str, branch: str) -> GitHubBranch:
- validate_repo_full_name(repo_full_name)
- return GitHubBranch(name=branch, sha="0" * 40)
-
-
-class GitHubIntegrationAdapter(NullGitHubAdapter):
- """GitHub adapter backed by the existing PostHog GitHub integration."""
-
- def _get_json(self, *, integration: Integration, path: str, endpoint: str) -> dict[str, Any]:
- try:
- payload = GitHubIntegration(integration)._gh_api_get(
- path,
- endpoint=endpoint,
- timeout=DEPLOYMENTS_GITHUB_API_TIMEOUT_SECONDS,
- )
- except GitHubIntegrationError as err:
- raise GitHubError(str(err)) from err
- if not isinstance(payload, dict):
- raise GitHubError("GitHub API returned an unexpected response shape.")
- return payload
-
- def _repository_from_payload(self, payload: dict[str, Any]) -> GitHubRepository:
- repository_id = payload.get("id")
- full_name = payload.get("full_name")
- default_branch = payload.get("default_branch")
- html_url = payload.get("html_url")
- if not isinstance(repository_id, int):
- raise GitHubError("GitHub repository response was missing a valid id.")
- if not isinstance(full_name, str) or not full_name:
- raise GitHubError("GitHub repository response was missing a full_name.")
- if not isinstance(default_branch, str) or not default_branch:
- raise GitHubError("GitHub repository response was missing a default branch.")
- if not isinstance(html_url, str) or not html_url:
- html_url = repo_url_from_full_name(full_name)
-
- return GitHubRepository(
- id=repository_id,
- full_name=full_name,
- default_branch=default_branch,
- html_url=html_url,
- )
-
- def get_repository_by_id(self, *, integration: Integration, github_repo_id: int) -> GitHubRepository:
- payload = self._get_json(
- integration=integration,
- path=f"/repositories/{github_repo_id}",
- endpoint="/repositories/{repository_id}",
- )
- repository = self._repository_from_payload(payload)
- if repository.id != github_repo_id:
- raise GitHubError("GitHub repository response id did not match the requested repository.")
- return repository
-
- def get_repository(self, *, integration: Integration, repo_full_name: str) -> GitHubRepository:
- validate_repo_full_name(repo_full_name)
- payload = self._get_json(
- integration=integration,
- path=f"/repos/{repo_full_name}",
- endpoint="/repos/{owner}/{repo}",
- )
-
- return self._repository_from_payload(payload)
-
- def get_branch(self, *, integration: Integration, repo_full_name: str, branch: str) -> GitHubBranch:
- validate_repo_full_name(repo_full_name)
- if not branch:
- raise GitHubError("A tracked branch is required.")
- payload = self._get_json(
- integration=integration,
- path=f"/repos/{repo_full_name}/branches/{quote(branch, safe='')}",
- endpoint="/repos/{owner}/{repo}/branches/{branch}",
- )
-
- branch_name = payload.get("name")
- commit = payload.get("commit")
- sha = commit.get("sha") if isinstance(commit, dict) else None
- if not isinstance(branch_name, str) or not branch_name:
- branch_name = branch
- if not isinstance(sha, str) or not sha:
- raise GitHubError("GitHub branch response was missing a commit SHA.")
- return GitHubBranch(name=branch_name, sha=sha)
-
-
-def get_github_adapter() -> GitHubAdapter:
- path = getattr(settings, "DEPLOYMENTS_GITHUB_ADAPTER", None)
- if not path:
- return GitHubIntegrationAdapter()
- 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
deleted file mode 100644
index feb7420d1682..000000000000
--- a/products/deployments/backend/adapters/microlink.py
+++ /dev/null
@@ -1,43 +0,0 @@
-"""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
deleted file mode 100644
index 5320ae346886..000000000000
--- a/products/deployments/backend/adapters/temporal.py
+++ /dev/null
@@ -1,177 +0,0 @@
-"""Temporal workflow adapter boundary.
-
-Declares the Protocol the rest of the product depends on, a Null stub
-for tests and dev, and `TemporalWorkflowAdapter` — the real implementation
-that talks to a Temporal cluster.
-
-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
-
-import asyncio
-from dataclasses import dataclass
-from importlib import import_module
-from typing import Protocol
-
-from django.conf import settings
-
-import structlog
-from temporalio.client import WorkflowHandle as TemporalWorkflowHandle
-from temporalio.common import RetryPolicy
-from temporalio.exceptions import WorkflowAlreadyStartedError
-from temporalio.service import RPCError, RPCStatusCode
-
-from posthog.temporal.common.client import sync_connect
-
-from ..domain.contracts import BuildInput
-
-# Workflow type name registered by the deployments Temporal worker. The
-# worker chart isn't deployed yet; flipping `DEPLOYMENTS_WORKFLOW_ADAPTER`
-# to this adapter before that lands means workflows get queued and sit
-# unprocessed until the worker comes online.
-DEPLOYMENT_BUILD_WORKFLOW = "deployment-build"
-
-logger = structlog.get_logger(__name__)
-
-
-@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
-
-
-class TemporalWorkflowAdapter:
- """Workflow adapter backed by the real Temporal cluster.
-
- Inert until both:
- - `DEPLOYMENTS_WORKFLOW_ADAPTER` env var points at this class
- (otherwise `get_workflow_adapter()` returns the Null stub).
- - A deployments Temporal worker is running on `DEPLOYMENTS_TASK_QUEUE`
- and has registered the `deployment-build` workflow type.
-
- Until the worker lands, flipping the env var still "works" — workflows
- get queued and sit unprocessed. That's a useful intermediate state
- for observability, not a regression.
-
- `start_build` is called synchronously from the public POST handler,
- so we use `sync_connect` + `asyncio.run` rather than async views.
- Same pattern as `posthog/api/proxy_record.py`.
- """
-
- def _task_queue(self) -> str:
- task_queue = getattr(settings, "DEPLOYMENTS_TASK_QUEUE", "")
- if not task_queue:
- raise WorkflowError("TemporalWorkflowAdapter is missing setting: DEPLOYMENTS_TASK_QUEUE.")
- return task_queue
-
- def _max_attempts(self) -> int:
- # Temporal-level retry budget for the workflow itself. Activity
- # retries inside the workflow are configured separately by the
- # worker. Defaults to the cluster-wide setting so this matches
- # the rest of PostHog's Temporal usage.
- return int(getattr(settings, "TEMPORAL_WORKFLOW_MAX_ATTEMPTS", "3"))
-
- def start_build(self, *, workflow_input: BuildInput) -> WorkflowHandle:
- task_queue = self._task_queue()
- max_attempts = self._max_attempts()
- workflow_id = f"deployment-{workflow_input.deployment_id}"
-
- try:
- client = sync_connect()
- handle: TemporalWorkflowHandle = asyncio.run(
- client.start_workflow(
- DEPLOYMENT_BUILD_WORKFLOW,
- workflow_input,
- id=workflow_id,
- task_queue=task_queue,
- retry_policy=RetryPolicy(maximum_attempts=max_attempts),
- )
- )
- except WorkflowAlreadyStartedError as err:
- # WorkflowAlreadyStartedError doesn't inherit from RPCError —
- # they share TemporalError as the common ancestor but sit on
- # different branches. Caught separately so a deterministic
- # workflow-id collision (HTTP retry, mid-transaction retry)
- # surfaces with a clear error rather than a 500.
- logger.info("temporal_start_workflow_already_started", workflow_id=workflow_id)
- raise WorkflowError(f"Deployment workflow already running: {err}") from err
- except RPCError as err:
- logger.warning("temporal_start_workflow_failed", workflow_id=workflow_id, error=str(err))
- raise WorkflowError(f"Failed to start deployment workflow: {err}") from err
-
- run_id = handle.result_run_id or handle.first_execution_run_id or ""
- if not run_id:
- # Temporal always returns one of these; the empty fallback
- # exists so the caller's persist step has something to write,
- # not because we expect to hit it.
- logger.warning("temporal_start_workflow_no_run_id", workflow_id=workflow_id)
- return WorkflowHandle(workflow_id=workflow_id, run_id=run_id)
-
- def signal_cancel(self, *, workflow_id: str) -> None:
- try:
- client = sync_connect()
-
- async def _cancel() -> None:
- handle = client.get_workflow_handle(workflow_id)
- await handle.cancel()
-
- asyncio.run(_cancel())
- except RPCError as err:
- # Workflow already finished or doesn't exist → not an error
- # from the user's perspective; the cancel is a no-op. Match
- # on the structured status code rather than the message text,
- # which can vary across SDK versions or locales. Other RPC
- # failures bubble up so the viewset can surface them.
- if err.status == RPCStatusCode.NOT_FOUND:
- logger.info("temporal_cancel_workflow_not_found", workflow_id=workflow_id)
- return
- logger.warning("temporal_cancel_workflow_failed", workflow_id=workflow_id, error=str(err))
- raise WorkflowError(f"Failed to cancel deployment workflow: {err}") from err
-
-
-def get_workflow_adapter() -> WorkflowAdapter:
- """Resolve the adapter implementation from settings.
-
- Reads `settings.DEPLOYMENTS_WORKFLOW_ADAPTER` as a `"module.path:ClassName"`
- string; if unset, returns `NullWorkflowAdapter`. Wire the real
- implementation in by setting this env var to
- `products.deployments.backend.adapters.temporal:TemporalWorkflowAdapter`.
- """
- 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
deleted file mode 100644
index 6eb4de889acb..000000000000
--- a/products/deployments/backend/api/__init__.py
+++ /dev/null
@@ -1,10 +0,0 @@
-from .deployment_projects import DeploymentProjectViewSet, DeploymentsAccessPermission
-from .deployments import DeploymentViewSet
-from .internal import InternalDeploymentTransitionsViewSet
-
-__all__ = [
- "DeploymentProjectViewSet",
- "DeploymentViewSet",
- "DeploymentsAccessPermission",
- "InternalDeploymentTransitionsViewSet",
-]
diff --git a/products/deployments/backend/api/deployment_projects.py b/products/deployments/backend/api/deployment_projects.py
deleted file mode 100644
index 57f938591696..000000000000
--- a/products/deployments/backend/api/deployment_projects.py
+++ /dev/null
@@ -1,429 +0,0 @@
-"""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 dataclasses import dataclass
-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.decorators import action
-from rest_framework.exceptions import NotFound, ValidationError
-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.mixins import ValidatedRequest, validated_request
-from posthog.api.routing import TeamAndOrgViewSetMixin
-from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication
-from posthog.models.integration import Integration
-from posthog.permissions import APIScopePermission
-from posthog.rbac.access_control_api_mixin import AccessControlViewSetMixin
-from posthog.rbac.user_access_control import UserAccessControl, access_level_satisfied_for_resource
-
-from ..access import has_deployments_access
-from ..adapters import CloudflareError, get_cloudflare_adapter, get_github_adapter
-from ..adapters.github import GitHubError, repo_url_from_full_name
-from ..models import DeploymentProject
-from ..serializers import (
- DeploymentProjectCreateSerializer,
- DeploymentProjectSerializer,
- DeploymentProjectWriteSerializer,
-)
-from ..services import provision_project
-from ..services.detection import PackageManager, detect_config
-
-
-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)
-
-
-@dataclass(frozen=True)
-class ResolvedRepositoryConfig:
- repo_url: str
- default_branch: str
- github_integration_id: int | None
- github_repo_id: int | None
-
-
-@dataclass(frozen=True)
-class RefreshedRepositoryState:
- repo_url: str
- default_branch: str
- commit_sha: str
-
-
-def _can_view_integration(integration: Integration, *, user_access_control: UserAccessControl) -> bool:
- if user_access_control.check_access_level_for_resource("integration", required_level="viewer"):
- return user_access_control.check_access_level_for_object(integration, required_level="viewer")
-
- specific_access_level = user_access_control.specific_access_level_for_object(integration)
- return bool(
- specific_access_level
- and access_level_satisfied_for_resource("integration", specific_access_level, required_level="viewer")
- )
-
-
-def _get_team_github_integration(
- *, team_id: int, integration_id: int, user_access_control: UserAccessControl
-) -> Integration:
- integration = Integration.objects.filter(
- id=integration_id,
- team_id=team_id,
- kind=Integration.IntegrationKind.GITHUB.value,
- ).first()
- if integration is None or not _can_view_integration(integration, user_access_control=user_access_control):
- raise NotFound("GitHub integration not found for this project.")
- return integration
-
-
-def _resolve_repository_config(
- data: dict[str, Any], *, team_id: int, user_access_control: UserAccessControl
-) -> ResolvedRepositoryConfig:
- github_integration_id = data.get("github_integration_id")
- if github_integration_id is None:
- raise ValidationError({"github_integration_id": "This field is required."})
-
- github_repo_id = data.get("github_repo_id")
- if github_repo_id is None:
- raise ValidationError({"github_repo_id": "This field is required."})
-
- integration = _get_team_github_integration(
- team_id=team_id,
- integration_id=int(github_integration_id),
- user_access_control=user_access_control,
- )
- adapter = get_github_adapter()
- try:
- repository = adapter.get_repository_by_id(integration=integration, github_repo_id=int(github_repo_id))
- branch_name = str(data.get("default_branch") or repository.default_branch).strip() or repository.default_branch
- branch = adapter.get_branch(integration=integration, repo_full_name=repository.full_name, branch=branch_name)
- except GitHubError as err:
- raise ValidationError({"github": str(err)}) from err
-
- return ResolvedRepositoryConfig(
- repo_url=repository.html_url or repo_url_from_full_name(repository.full_name),
- default_branch=branch.name,
- github_integration_id=integration.id,
- github_repo_id=repository.id,
- )
-
-
-class DetectConfigRequestSerializer(serializers.Serializer):
- """Inputs the `/detect/` endpoint needs to suggest a project config.
-
- Decouples detection from any one git provider — callers fetch
- `package.json` and the list of lockfiles however they like (GitHub
- raw content via the team's existing integration, a temporary clone,
- user-pasted JSON during early development) and pass them here.
- """
-
- package_json = serializers.JSONField(
- required=False,
- allow_null=True,
- help_text=(
- "Parsed contents of the repo's `package.json`. Pass null or omit if the "
- "repo doesn't have one — the response is then the plain-HTML fallback."
- ),
- )
- lockfiles = serializers.ListField(
- child=serializers.CharField(max_length=64),
- required=False,
- default=list,
- help_text=(
- "Filenames of package-manager lockfiles found in the repo root "
- '(e.g. ["pnpm-lock.yaml"]). Used to pick the package manager.'
- ),
- )
-
-
-class DetectConfigResponseSerializer(serializers.Serializer):
- """Suggested project config. Every field is overridable in the connect-repo UI.
-
- `build_command`, `output_dir`, and `framework` map directly to the
- `DeploymentProject` model fields. `package_manager`, `install_command`,
- and `node_version` are informational hints — the model doesn't store
- them today, but the UI can display them so the user knows what the
- build worker will end up running.
- """
-
- package_manager = serializers.ChoiceField(
- choices=[(m.value, m.value) for m in PackageManager],
- help_text="Detected package manager from lockfile presence.",
- )
- install_command = serializers.CharField(
- allow_blank=True,
- help_text="Suggested install command, or empty when no install is needed.",
- )
- build_command = serializers.CharField(
- allow_blank=True,
- help_text="Suggested build command, or empty when no known framework matched.",
- )
- output_dir = serializers.CharField(help_text="Suggested output directory relative to repo root.")
- node_version = serializers.CharField(
- help_text="Suggested Node major version, parsed from `engines.node` or defaulted to 20.",
- )
- framework = serializers.CharField(
- allow_null=True,
- help_text=(
- "Detected framework hint (e.g. `nextjs`, `vite`, `astro`) to write into "
- "`DeploymentProject.framework`. Null when no framework matched — leaving the "
- "field null lets the build worker fall back to its own auto-detection."
- ),
- )
-
-
-class DeploymentProjectRefreshResponseSerializer(serializers.Serializer):
- """Response shape for refreshing a deployment project's GitHub branch."""
-
- detail = serializers.CharField(help_text="Human-readable explanation of the refresh result.")
- repo_url = serializers.URLField(help_text="HTTPS URL of the connected GitHub repository.")
- default_branch = serializers.CharField(help_text="Branch checked by the refresh action.")
- commit_sha = serializers.CharField(help_text="Current GitHub HEAD SHA for default_branch.")
-
-
-def _refresh_project_repository_state(
- project: DeploymentProject, *, user_access_control: UserAccessControl
-) -> RefreshedRepositoryState:
- if project.github_integration_id is None or project.github_repo_id is None:
- raise ValidationError("Deployment project is not connected to a GitHub repository.")
-
- integration = _get_team_github_integration(
- team_id=project.team_id,
- integration_id=project.github_integration_id,
- user_access_control=user_access_control,
- )
- adapter = get_github_adapter()
- try:
- repository = adapter.get_repository_by_id(integration=integration, github_repo_id=project.github_repo_id)
- branch = adapter.get_branch(
- integration=integration,
- repo_full_name=repository.full_name,
- branch=project.default_branch,
- )
- except GitHubError as err:
- raise ValidationError({"github": str(err)}) from err
-
- repo_url = repository.html_url or repo_url_from_full_name(repository.full_name)
- if project.repo_url != repo_url:
- project.repo_url = repo_url
- project.save(update_fields=["repo_url", "updated_at"])
-
- return RefreshedRepositoryState(
- repo_url=repo_url,
- default_branch=branch.name,
- commit_sha=branch.sha,
- )
-
-
-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", "default_branch"]
- 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=DeploymentProjectCreateSerializer,
- 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 = DeploymentProjectCreateSerializer(data=request.data, context=self.get_serializer_context())
- serializer.is_valid(raise_exception=True)
- repository_config = _resolve_repository_config(
- serializer.validated_data,
- team_id=self.team_id,
- user_access_control=self.user_access_control,
- )
- 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=repository_config.repo_url,
- default_branch=repository_config.default_branch,
- github_integration_id=repository_config.github_integration_id,
- github_repo_id=repository_config.github_repo_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)
-
- def _save_with_repository_config(self, instance: DeploymentProject, serializer: Any) -> DeploymentProject:
- tracking_fields = {"github_integration_id", "github_repo_id", "default_branch"}
- save_kwargs: dict[str, Any] = {}
- if tracking_fields.intersection(serializer.validated_data):
- merged_data = {
- "default_branch": instance.default_branch,
- "github_integration_id": instance.github_integration_id,
- "github_repo_id": instance.github_repo_id,
- }
- merged_data.update(serializer.validated_data)
- repository_config = _resolve_repository_config(
- merged_data,
- team_id=self.team_id,
- user_access_control=self.user_access_control,
- )
- save_kwargs = {
- "repo_url": repository_config.repo_url,
- "default_branch": repository_config.default_branch,
- "github_integration_id": repository_config.github_integration_id,
- "github_repo_id": repository_config.github_repo_id,
- }
- return serializer.save(**save_kwargs)
-
- @extend_schema(
- request=DeploymentProjectWriteSerializer, responses={status.HTTP_200_OK: DeploymentProjectSerializer}
- )
- def update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- instance = self.get_object()
- serializer = DeploymentProjectWriteSerializer(
- instance,
- data=request.data,
- context=self.get_serializer_context(),
- )
- serializer.is_valid(raise_exception=True)
- project = self._save_with_repository_config(instance, serializer)
- return Response(self.get_serializer(project).data, status=status.HTTP_200_OK)
-
- @extend_schema(
- request=DeploymentProjectWriteSerializer, responses={status.HTTP_200_OK: DeploymentProjectSerializer}
- )
- def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:
- instance = self.get_object()
- serializer = DeploymentProjectWriteSerializer(
- instance,
- data=request.data,
- partial=True,
- context=self.get_serializer_context(),
- )
- serializer.is_valid(raise_exception=True)
- project = self._save_with_repository_config(instance, serializer)
- return Response(self.get_serializer(project).data, status=status.HTTP_200_OK)
-
- @extend_schema(
- request=None,
- responses={status.HTTP_200_OK: OpenApiResponse(response=DeploymentProjectRefreshResponseSerializer)},
- summary="Refresh a deployment project's GitHub branch",
- )
- @action(detail=True, methods=["post"])
- def refresh(self, request: Request, **kwargs: Any) -> Response:
- project = self.get_object()
- refreshed = _refresh_project_repository_state(project, user_access_control=self.user_access_control)
- return Response(
- DeploymentProjectRefreshResponseSerializer(
- {
- "detail": "GitHub branch refreshed.",
- "repo_url": refreshed.repo_url,
- "default_branch": refreshed.default_branch,
- "commit_sha": refreshed.commit_sha,
- }
- ).data,
- status=status.HTTP_200_OK,
- )
-
- @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)
-
- @validated_request(
- request_serializer=DetectConfigRequestSerializer,
- responses={status.HTTP_200_OK: OpenApiResponse(response=DetectConfigResponseSerializer)},
- summary="Suggest project config from a repo's package.json and lockfiles",
- description=(
- "Pure inspection — no git access, no DB writes. The connect-repo "
- "UI calls this after fetching `package.json` (via the team's "
- "GitHub integration) and uses the response to prefill the form."
- ),
- )
- @action(detail=False, methods=["post"], pagination_class=None)
- def detect(self, request: ValidatedRequest, **kwargs: Any) -> Response:
- package_json = request.validated_data.get("package_json")
- lockfiles = request.validated_data.get("lockfiles", [])
- detected = detect_config(package_json, lockfiles)
- return Response(
- DetectConfigResponseSerializer(
- {
- "package_manager": detected.package_manager.value,
- "install_command": detected.install_command,
- "build_command": detected.build_command,
- "output_dir": detected.output_dir,
- "node_version": detected.node_version,
- "framework": detected.framework,
- }
- ).data,
- )
-
-
-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
deleted file mode 100644
index 2a4fd8e19a95..000000000000
--- a/products/deployments/backend/api/deployments.py
+++ /dev/null
@@ -1,418 +0,0 @@
-"""DRF wiring for the Deployment viewset (nested under DeploymentProject).
-
-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 django.db.models import Exists, OuterRef
-
-import structlog
-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.exceptions import NotFound, PermissionDenied
-from rest_framework.permissions import IsAuthenticated
-from rest_framework.request import Request
-from rest_framework.response import Response
-
-from posthog.hogql import ast
-from posthog.hogql.parser import parse_select
-from posthog.hogql.query import execute_hogql_query
-
-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 ..adapters import GitHubError
-from ..domain.trigger import TriggerKind
-from ..models import Deployment, DeploymentEvent, DeploymentProject
-from ..serializers import DeploymentEventSerializer, DeploymentLogsResponseSerializer, DeploymentSerializer
-from ..serializers.deployment import (
- DeploymentActionResponseSerializer,
- DeploymentConflictResponseSerializer,
- DeploymentCreateInputSerializer,
-)
-from ..services import cancel, create_deployment, redeploy, refresh_preview, rollback
-from .deployment_projects import DeploymentsAccessPermission
-
-logger = structlog.get_logger(__name__)
-
-
-# Build logs land in the standard `events` table as `$log` events tagged with
-# `properties.deployment_id`. See `2026-05-13-deployments.md` (Pipeline →
-# "Build logs") for the emission contract owned by the build-runner stream.
-LOGS_ROW_LIMIT = 1000
-_LOGS_QUERY_SQL = """
-SELECT
- timestamp,
- properties.level AS level,
- properties.step AS step,
- properties.$log_line AS line,
- properties.exit_code AS exit_code
-FROM events
-WHERE event = {log_event}
- AND properties.deployment_id = {deployment_id}
-ORDER BY timestamp ASC
-LIMIT {row_limit}
-"""
-
-
-@extend_schema(
- tags=["deployments"],
- parameters=[
- OpenApiParameter(
- name="deployment_project_id",
- type=OpenApiTypes.UUID,
- location=OpenApiParameter.PATH,
- description="UUID of the parent DeploymentProject.",
- ),
- ],
-)
-class DeploymentViewSet(
- TeamAndOrgViewSetMixin,
- AccessControlViewSetMixin,
- viewsets.ModelViewSet,
-):
- """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.
- """
-
- scope_object = "deployment"
- authentication_classes = [
- SessionAuthentication,
- PersonalAPIKeyAuthentication,
- OAuthAccessTokenAuthentication,
- ]
- permission_classes = [IsAuthenticated, APIScopePermission, DeploymentsAccessPermission]
- serializer_class = DeploymentSerializer
- # 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
- # and rewrites `project_id` to `team__project_id` — but `Deployment`
- # stores `team_id` as a plain `BigIntegerField`. `safely_get_queryset`
- # below applies the team scope directly using `self.team_id`.
- return True
-
- def safely_get_queryset(self, queryset: Any) -> Any:
- # 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_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:
- # 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_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:
- 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_200_OK: DeploymentActionResponseSerializer},
- )
- @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:
- 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: DeploymentLogsResponseSerializer,
- status.HTTP_502_BAD_GATEWAY: OpenApiResponse(
- description="HogQL query against the events store failed.",
- ),
- },
- )
- @action(detail=True, methods=["get"])
- def logs(self, request: Request, **kwargs: Any) -> Response:
- # Build logs land as `$log` events on the standard `events` table,
- # tagged with `properties.deployment_id`. We project the deployment-
- # specific properties (level, step, $log_line, exit_code) the build
- # runner emits per `2026-05-13-deployments.md`. `execute_hogql_query`
- # auto-scopes to the current team via HogQLContext, so the URL's
- # team_id is already enforced; `get_object()` covers the project +
- # deployment scope and RBAC.
- source = self.get_object()
- select = parse_select(_LOGS_QUERY_SQL)
- # Fetch one row beyond the cap so we can distinguish "ran out at
- # exactly the cap" (`has_more=False`) from "more rows exist beyond
- # the page" (`has_more=True`). The extra row is sliced off before
- # serialization so the response shape stays bounded.
- fetch_limit = LOGS_ROW_LIMIT + 1
- try:
- result = execute_hogql_query(
- query=select,
- team=self.team,
- placeholders={
- "log_event": ast.Constant(value="$log"),
- "deployment_id": ast.Constant(value=str(source.pk)),
- "row_limit": ast.Constant(value=fetch_limit),
- },
- query_type="DeploymentLogsQuery",
- )
- except Exception as exc:
- logger.exception(
- "deployments.logs.hogql_failed",
- deployment_id=str(source.pk),
- error=str(exc),
- )
- return Response(
- {"detail": "Failed to fetch logs from the analytics store."},
- status=status.HTTP_502_BAD_GATEWAY,
- )
-
- rows = result.results or []
- has_more = len(rows) > LOGS_ROW_LIMIT
- page = rows[:LOGS_ROW_LIMIT]
- serialized = DeploymentLogsResponseSerializer(
- {
- "results": [
- {
- "timestamp": row[0],
- "level": row[1],
- "step": row[2],
- "line": row[3],
- "exit_code": row[4],
- }
- for row in page
- ],
- "has_more": has_more,
- "row_limit": LOGS_ROW_LIMIT,
- }
- )
- return Response(serialized.data, status=status.HTTP_200_OK)
diff --git a/products/deployments/backend/api/internal.py b/products/deployments/backend/api/internal.py
deleted file mode 100644
index df15f0cd2f4e..000000000000
--- a/products/deployments/backend/api/internal.py
+++ /dev/null
@@ -1,182 +0,0 @@
-"""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 posthog.models.scoping import team_scope
-
-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
-
- # InternalAPIAuthentication does not set team context. Resolve the row
- # with `all_teams`, then enter scope so ModelActivityMixin and any
- # ProductTeamModel writes inside the transition use the deployment's
- # canonical team.
- deployment_for_scope = self._get_deployment(deployment_id)
- with team_scope(deployment_for_scope.team_id, canonical=True):
- 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)
-
- with team_scope(deployment.team_id, canonical=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/apps.py b/products/deployments/backend/apps.py
deleted file mode 100644
index 2b21047aea3a..000000000000
--- a/products/deployments/backend/apps.py
+++ /dev/null
@@ -1,7 +0,0 @@
-from django.apps import AppConfig
-
-
-class DeploymentsConfig(AppConfig):
- default_auto_field = "django.db.models.BigAutoField"
- name = "products.deployments.backend"
- label = "deployments"
diff --git a/products/deployments/backend/domain/__init__.py b/products/deployments/backend/domain/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/deployments/backend/domain/contracts.py b/products/deployments/backend/domain/contracts.py
deleted file mode 100644
index ad38a844953c..000000000000
--- a/products/deployments/backend/domain/contracts.py
+++ /dev/null
@@ -1,80 +0,0 @@
-"""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
deleted file mode 100644
index 17c89c5b3a3e..000000000000
--- a/products/deployments/backend/domain/status.py
+++ /dev/null
@@ -1,61 +0,0 @@
-"""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
deleted file mode 100644
index 5f94dae063f1..000000000000
--- a/products/deployments/backend/domain/trigger.py
+++ /dev/null
@@ -1,25 +0,0 @@
-"""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/__init__.py b/products/deployments/backend/management/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/deployments/backend/management/commands/__init__.py b/products/deployments/backend/management/commands/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/deployments/backend/management/commands/seed_deployments.py b/products/deployments/backend/management/commands/seed_deployments.py
deleted file mode 100644
index 8bbc0a61d69c..000000000000
--- a/products/deployments/backend/management/commands/seed_deployments.py
+++ /dev/null
@@ -1,330 +0,0 @@
-"""`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."
-
- 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:
- 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/0001_initial.py b/products/deployments/backend/migrations/0001_initial.py
deleted file mode 100644
index 09ab2880ff31..000000000000
--- a/products/deployments/backend/migrations/0001_initial.py
+++ /dev/null
@@ -1,90 +0,0 @@
-# Generated by Django 4.2.29 — initial scaffold for the Deployments product.
-
-import django.db.models.deletion
-from django.db import migrations, models
-
-import posthog.models.utils
-
-
-class Migration(migrations.Migration):
- initial = True
-
- dependencies = []
-
- operations = [
- migrations.CreateModel(
- name="Deployment",
- fields=[
- (
- "id",
- models.UUIDField(
- default=posthog.models.utils.uuid7,
- editable=False,
- primary_key=True,
- serialize=False,
- ),
- ),
- ("team_id", models.BigIntegerField(db_index=True)),
- (
- "status",
- models.CharField(
- choices=[
- ("queued", "Queued"),
- ("initializing", "Initializing"),
- ("building", "Building"),
- ("ready", "Ready"),
- ("error", "Error"),
- ("cancelled", "Cancelled"),
- ],
- db_index=True,
- default="queued",
- max_length=32,
- ),
- ),
- ("started_at", models.DateTimeField(blank=True, null=True)),
- ("finished_at", models.DateTimeField(blank=True, null=True)),
- ("created_at", models.DateTimeField(auto_now_add=True, db_index=True)),
- ("commit_sha", models.CharField(blank=True, default="", max_length=64)),
- ("commit_message", models.TextField(blank=True, default="")),
- ("commit_author_name", models.CharField(blank=True, default="", max_length=255)),
- ("commit_author_email", models.CharField(blank=True, default="", max_length=255)),
- ("repo_url", models.URLField(blank=True, default="", max_length=1024)),
- ("branch", models.CharField(blank=True, default="", max_length=255)),
- ("deployment_url", models.URLField(blank=True, default="", max_length=1024)),
- ("preview_image_url", models.URLField(blank=True, default="", max_length=1024)),
- (
- "trigger_kind",
- models.CharField(
- choices=[
- ("git", "Git"),
- ("redeploy", "Redeploy"),
- ("rollback", "Rollback"),
- ("seed", "Seed"),
- ],
- default="git",
- max_length=16,
- ),
- ),
- (
- "triggered_by_deployment",
- models.ForeignKey(
- blank=True,
- null=True,
- on_delete=django.db.models.deletion.SET_NULL,
- related_name="+",
- to="deployments.deployment",
- ),
- ),
- ],
- options={
- "ordering": ("-created_at",),
- },
- ),
- migrations.AddIndex(
- model_name="deployment",
- index=models.Index(
- fields=["team_id", "-created_at"],
- name="deploy_team_created_idx",
- ),
- ),
- ]
diff --git a/products/deployments/backend/migrations/0002_deploymentproject_deploymentevent_and_more.py b/products/deployments/backend/migrations/0002_deploymentproject_deploymentevent_and_more.py
deleted file mode 100644
index 253915990833..000000000000
--- a/products/deployments/backend/migrations/0002_deploymentproject_deploymentevent_and_more.py
+++ /dev/null
@@ -1,249 +0,0 @@
-"""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
deleted file mode 100644
index 5223033236f1..000000000000
--- a/products/deployments/backend/migrations/0003_deployment_project_idx_concurrent.py
+++ /dev/null
@@ -1,32 +0,0 @@
-"""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
deleted file mode 100644
index e4bcd56734bb..000000000000
--- a/products/deployments/backend/migrations/0004_alter_deploymentevent_managers_and_more.py
+++ /dev/null
@@ -1,44 +0,0 @@
-# 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/0005_deploymentproject_github_tracking.py b/products/deployments/backend/migrations/0005_deploymentproject_github_tracking.py
deleted file mode 100644
index d7bcfd6fd619..000000000000
--- a/products/deployments/backend/migrations/0005_deploymentproject_github_tracking.py
+++ /dev/null
@@ -1,17 +0,0 @@
-# Generated manually for Deployments GitHub repository tracking.
-
-from django.db import migrations, models
-
-
-class Migration(migrations.Migration):
- dependencies = [
- ("deployments", "0004_alter_deploymentevent_managers_and_more"),
- ]
-
- operations = [
- migrations.AddField(
- model_name="deploymentproject",
- name="github_repo_id",
- field=models.BigIntegerField(blank=True, null=True),
- ),
- ]
diff --git a/products/deployments/backend/migrations/0006_deploymentproject_github_indexes_concurrent.py b/products/deployments/backend/migrations/0006_deploymentproject_github_indexes_concurrent.py
deleted file mode 100644
index 1ab38786c9ee..000000000000
--- a/products/deployments/backend/migrations/0006_deploymentproject_github_indexes_concurrent.py
+++ /dev/null
@@ -1,19 +0,0 @@
-# Generated manually for Deployments GitHub repository tracking indexes.
-
-from django.contrib.postgres.operations import AddIndexConcurrently
-from django.db import migrations, models
-
-
-class Migration(migrations.Migration):
- atomic = False
-
- dependencies = [
- ("deployments", "0005_deploymentproject_github_tracking"),
- ]
-
- operations = [
- AddIndexConcurrently(
- model_name="deploymentproject",
- index=models.Index(fields=("team_id", "github_integration_id"), name="deploy_project_team_int_idx"),
- ),
- ]
diff --git a/products/deployments/backend/migrations/0007_deploymentproject_github_repo_unique_index_concurrent.py b/products/deployments/backend/migrations/0007_deploymentproject_github_repo_unique_index_concurrent.py
deleted file mode 100644
index 6632017bce91..000000000000
--- a/products/deployments/backend/migrations/0007_deploymentproject_github_repo_unique_index_concurrent.py
+++ /dev/null
@@ -1,37 +0,0 @@
-# Generated manually for Deployments GitHub repository uniqueness.
-
-from django.db import migrations, models
-
-
-class Migration(migrations.Migration):
- atomic = False
-
- dependencies = [
- ("deployments", "0006_deploymentproject_github_indexes_concurrent"),
- ]
-
- operations = [
- migrations.SeparateDatabaseAndState(
- state_operations=[
- migrations.AddConstraint(
- model_name="deploymentproject",
- constraint=models.UniqueConstraint(
- condition=models.Q(("github_repo_id__isnull", False))
- & (models.Q(("deleted", False)) | models.Q(("deleted__isnull", True))),
- fields=("team_id", "github_repo_id"),
- name="deploy_project_team_repo_uniq",
- ),
- ),
- ],
- database_operations=[
- migrations.RunSQL(
- sql="""
- CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "deploy_project_team_repo_uniq"
- ON "deployments_deploymentproject" ("team_id", "github_repo_id")
- WHERE ("github_repo_id" IS NOT NULL AND (NOT "deleted" OR "deleted" IS NULL));
- """,
- reverse_sql='DROP INDEX CONCURRENTLY IF EXISTS "deploy_project_team_repo_uniq";',
- ),
- ],
- ),
- ]
diff --git a/products/deployments/backend/migrations/__init__.py b/products/deployments/backend/migrations/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/deployments/backend/migrations/max_migration.txt b/products/deployments/backend/migrations/max_migration.txt
deleted file mode 100644
index e4314716d364..000000000000
--- a/products/deployments/backend/migrations/max_migration.txt
+++ /dev/null
@@ -1 +0,0 @@
-0007_deploymentproject_github_repo_unique_index_concurrent
diff --git a/products/deployments/backend/models.py b/products/deployments/backend/models.py
deleted file mode 100644
index 2367ad61e8ef..000000000000
--- a/products/deployments/backend/models.py
+++ /dev/null
@@ -1,241 +0,0 @@
-"""Django models for the Deployments product.
-
-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
-
-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 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")
- # Existing PostHog GitHub integration used for repo/branch access. These
- # are plain ids because integrations live in the main app and Deployments
- # keeps product-owned tenant data behind ProductTeamModel.team_id.
- github_integration_id = models.BigIntegerField(null=True, blank=True)
- github_repo_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",
- ),
- models.UniqueConstraint(
- fields=("team_id", "github_repo_id"),
- condition=models.Q(github_repo_id__isnull=False)
- & (models.Q(deleted=False) | models.Q(deleted__isnull=True)),
- name="deploy_project_team_repo_uniq",
- ),
- ]
- indexes = [
- models.Index(fields=["team_id", "-created_at"]),
- models.Index(fields=("team_id", "github_integration_id"), name="deploy_project_team_int_idx"),
- ]
-
- 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`.
- """
-
- class Status(models.TextChoices):
- QUEUED = "queued", "Queued"
- INITIALIZING = "initializing", "Initializing"
- BUILDING = "building", "Building"
- READY = "ready", "Ready"
- 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,
- default=Status.QUEUED,
- db_index=True,
- )
- started_at = models.DateTimeField(null=True, blank=True)
- 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="")
-
- # 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,
- blank=True,
- on_delete=models.SET_NULL,
- related_name="+",
- )
- trigger_kind = models.CharField(
- max_length=16,
- choices=TriggerKind.choices,
- 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
deleted file mode 100644
index b0f81b03d6ec..000000000000
--- a/products/deployments/backend/serializers/__init__.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from .deployment import DeploymentLogEntrySerializer, DeploymentLogsResponseSerializer, DeploymentSerializer
-from .event import DeploymentEventSerializer
-from .project import DeploymentProjectCreateSerializer, DeploymentProjectSerializer, DeploymentProjectWriteSerializer
-
-__all__ = [
- "DeploymentEventSerializer",
- "DeploymentLogEntrySerializer",
- "DeploymentLogsResponseSerializer",
- "DeploymentProjectCreateSerializer",
- "DeploymentProjectSerializer",
- "DeploymentProjectWriteSerializer",
- "DeploymentSerializer",
-]
diff --git a/products/deployments/backend/serializers/deployment.py b/products/deployments/backend/serializers/deployment.py
deleted file mode 100644
index 359880369280..000000000000
--- a/products/deployments/backend/serializers/deployment.py
+++ /dev/null
@@ -1,252 +0,0 @@
-"""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.",
- )
-
-
-class DeploymentLogEntrySerializer(serializers.Serializer):
- """One line of build output emitted by the build worker as a `$log` event."""
-
- timestamp = serializers.DateTimeField(help_text="When the line was emitted by the build worker.")
- level = serializers.CharField(
- allow_null=True,
- help_text='Log level: "info" | "warn" | "error". Null if the event did not carry one.',
- )
- step = serializers.CharField(
- allow_null=True,
- help_text='Pipeline step: "clone" | "install" | "build" | "publish". Null if the event did not carry one.',
- )
- line = serializers.CharField(
- allow_null=True,
- help_text="The log line itself (a single line of stdout or stderr).",
- )
- exit_code = serializers.IntegerField(
- allow_null=True,
- help_text="Set on the last line of a step; null on all other lines.",
- )
-
-
-class DeploymentLogsResponseSerializer(serializers.Serializer):
- """Response shape for GET /deployments/{id}/logs/."""
-
- results = DeploymentLogEntrySerializer(many=True, help_text="Log lines for the deployment, oldest first.")
- has_more = serializers.BooleanField(
- help_text="True if the row limit was hit and older lines may exist beyond this page.",
- )
- row_limit = serializers.IntegerField(help_text="The hard cap applied by the server.")
diff --git a/products/deployments/backend/serializers/event.py b/products/deployments/backend/serializers/event.py
deleted file mode 100644
index c21c8ca2250a..000000000000
--- a/products/deployments/backend/serializers/event.py
+++ /dev/null
@@ -1,31 +0,0 @@
-"""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
deleted file mode 100644
index d70efd16d5e0..000000000000
--- a/products/deployments/backend/serializers/project.py
+++ /dev/null
@@ -1,286 +0,0 @@
-"""Serializer for DeploymentProject.
-
-Repository selection is keyed by ``github_integration_id`` + ``github_repo_id``.
-``repo_url`` is derived from GitHub and exposed as read-only display metadata.
-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 collections.abc import Mapping
-from typing import Any
-
-from drf_spectacular.utils import extend_schema_field
-from rest_framework import serializers
-
-from ..models import DeploymentProject
-
-
-class RejectUnknownFieldsMixin(serializers.Serializer):
- def to_internal_value(self, data: Any) -> Any:
- if isinstance(data, Mapping):
- unknown_fields = set(data) - set(self.fields)
- if unknown_fields:
- raise serializers.ValidationError(dict.fromkeys(sorted(unknown_fields), "Unknown field."))
- return super().to_internal_value(data)
-
-
-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,
- read_only=True,
- help_text="HTTPS URL of the connected GitHub repository, resolved from the selected repository id.",
- )
- default_branch = serializers.CharField(
- max_length=255,
- required=False,
- help_text="Branch PostHog tracks for deployment updates. Defaults to the repository default branch.",
- )
- github_integration_id = serializers.IntegerField(
- required=False,
- allow_null=True,
- help_text="Existing PostHog GitHub integration id used for repository access.",
- )
- github_repo_id = serializers.IntegerField(
- required=False,
- allow_null=True,
- help_text="Stable GitHub repository identifier selected from the existing integration's repository list.",
- )
- 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_id",
- "github_repo_id",
- "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",
- "repo_url",
- "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
-
-
-class DeploymentProjectWriteSerializer(RejectUnknownFieldsMixin, serializers.ModelSerializer):
- 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."
- ),
- )
- default_branch = serializers.CharField(
- max_length=255,
- required=False,
- help_text="Branch PostHog tracks for deployment updates. Defaults to the repository default branch.",
- )
- github_integration_id = serializers.IntegerField(
- required=False,
- allow_null=True,
- help_text="Existing PostHog GitHub integration id used for repository access.",
- )
- github_repo_id = serializers.IntegerField(
- required=False,
- allow_null=True,
- help_text="Stable GitHub repository identifier selected from the existing integration's repository list.",
- )
- 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."
- ),
- )
-
- class Meta:
- model = DeploymentProject
- fields = [
- "name",
- "slug",
- "default_branch",
- "github_integration_id",
- "github_repo_id",
- "build_command",
- "output_dir",
- "framework",
- "inject_posthog_snippet",
- ]
-
-
-class DeploymentProjectCreateSerializer(RejectUnknownFieldsMixin, serializers.Serializer):
- 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. Becomes the subdomain `{slug}.posthog-app.com`. Must be unique per team.",
- )
- default_branch = serializers.CharField(
- max_length=255,
- required=False,
- help_text="Branch PostHog tracks for deployment updates. Defaults to the repository default branch.",
- )
- github_integration_id = serializers.IntegerField(
- help_text="Existing PostHog GitHub integration id used for repository access."
- )
- github_repo_id = serializers.IntegerField(
- help_text="Stable GitHub repository identifier selected from the existing integration's repository list."
- )
- 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."
- ),
- )
diff --git a/products/deployments/backend/services/__init__.py b/products/deployments/backend/services/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/deployments/backend/services/cancel.py b/products/deployments/backend/services/cancel.py
deleted file mode 100644
index 7ed1ae4155ac..000000000000
--- a/products/deployments/backend/services/cancel.py
+++ /dev/null
@@ -1,52 +0,0 @@
-"""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
deleted file mode 100644
index 6f74ae36342a..000000000000
--- a/products/deployments/backend/services/create_deployment.py
+++ /dev/null
@@ -1,207 +0,0 @@
-"""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/detection.py b/products/deployments/backend/services/detection.py
deleted file mode 100644
index 751a1aac91e3..000000000000
--- a/products/deployments/backend/services/detection.py
+++ /dev/null
@@ -1,226 +0,0 @@
-"""Framework + package-manager detection for connected repositories.
-
-Pure inspection — no I/O, no DB. The caller fetches `package.json` and the
-list of present lockfiles from the repo root (via GitHub raw content, a
-temporary clone, or wherever) and hands them in; we return a suggested
-build configuration the UI can prefill.
-
-The detection table is the only place where framework signatures live;
-new frameworks land here as one entry rather than scattered specials in
-the build worker. Framework names match the free-text convention on
-`DeploymentProject.framework` (lowercase, no spaces, e.g. `nextjs`,
-`vite`, `astro`).
-"""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-from enum import StrEnum
-from typing import Any
-
-
-class PackageManager(StrEnum):
- NPM = "npm"
- PNPM = "pnpm"
- YARN = "yarn"
- BUN = "bun"
-
-
-@dataclass(frozen=True)
-class DetectedConfig:
- """Suggested config from a repo's `package.json` + lockfile presence.
-
- `framework` is `None` when no signature matched — the UI should leave
- `DeploymentProject.framework` null so the build worker falls back to
- its own auto-detection. `install_command` and `node_version` are
- informational; `DeploymentProject` doesn't store them today.
- """
-
- package_manager: PackageManager
- install_command: str
- build_command: str
- output_dir: str
- node_version: str
- framework: str | None
-
-
-# (lockfile_name, package_manager) — order matters: if a repo has both a
-# pnpm lockfile and a leftover `package-lock.json`, pnpm wins because the
-# pnpm lockfile is the explicit signal a developer is using pnpm. npm is
-# the last-resort default because `package-lock.json` is what npm happily
-# generates on top of anything.
-#
-# Bun has two lockfile names in the wild: `bun.lockb` (binary, pre-1.2) and
-# `bun.lock` (text, 1.2+ default). Both are listed so a fresh Bun 1.2 repo
-# doesn't fall through to npm.
-_LOCKFILE_PRECEDENCE: tuple[tuple[str, PackageManager], ...] = (
- ("bun.lock", PackageManager.BUN),
- ("bun.lockb", PackageManager.BUN),
- ("pnpm-lock.yaml", PackageManager.PNPM),
- ("yarn.lock", PackageManager.YARN),
- ("package-lock.json", PackageManager.NPM),
-)
-
-
-def detect_package_manager(lockfile_names: list[str]) -> PackageManager:
- """Pick a package manager from the lockfiles present in the repo root."""
- present = set(lockfile_names)
- for lockfile, manager in _LOCKFILE_PRECEDENCE:
- if lockfile in present:
- return manager
- return PackageManager.NPM
-
-
-def _install_command_for(manager: PackageManager) -> str:
- return {
- PackageManager.NPM: "npm ci",
- PackageManager.PNPM: "pnpm install --frozen-lockfile",
- PackageManager.YARN: "yarn install --frozen-lockfile",
- PackageManager.BUN: "bun install --frozen-lockfile",
- }[manager]
-
-
-def _build_invocation(manager: PackageManager, script: str) -> str:
- """`<manager> run <script>` for all four — `npm run build`, `pnpm build`, etc."""
- prefix = {
- PackageManager.NPM: "npm run",
- PackageManager.PNPM: "pnpm",
- PackageManager.YARN: "yarn",
- PackageManager.BUN: "bun run",
- }[manager]
- return f"{prefix} {script}"
-
-
-@dataclass(frozen=True)
-class _FrameworkSignature:
- """Detection rule for one framework.
-
- `dep_keys` is the set of dependencies that must *all* be present in the
- union of `dependencies` + `devDependencies` for this framework to match.
- First signature whose deps all match wins, so order in
- `_FRAMEWORK_SIGNATURES` is significant — more specific frameworks
- (Remix, SvelteKit, Nuxt) come before more general ones that share a
- transitive dep (Vite, React).
-
- `all()` (not `any()`): a repo carrying only `@remix-run/react` without
- `@remix-run/node` is some downstream package's transitive dep, not a
- Remix project. Picking Remix here would suggest the wrong build
- command and break the user's deploy.
- """
-
- framework: str
- dep_keys: tuple[str, ...]
- build_script: str
- output_dir: str
-
-
-_FRAMEWORK_SIGNATURES: tuple[_FrameworkSignature, ...] = (
- _FrameworkSignature("nextjs", ("next",), "build", "out"),
- _FrameworkSignature("remix", ("@remix-run/react", "@remix-run/node"), "build", "public"),
- _FrameworkSignature("sveltekit", ("@sveltejs/kit",), "build", "build"),
- _FrameworkSignature("nuxt", ("nuxt",), "generate", ".output/public"),
- _FrameworkSignature("astro", ("astro",), "build", "dist"),
- _FrameworkSignature("gatsby", ("gatsby",), "build", "public"),
- _FrameworkSignature("eleventy", ("@11ty/eleventy",), "build", "_site"),
- _FrameworkSignature("vite", ("vite",), "build", "dist"),
- _FrameworkSignature("create-react-app", ("react-scripts",), "build", "build"),
-)
-
-
-def _collect_dependency_keys(package_json: dict[str, Any]) -> set[str]:
- deps = package_json.get("dependencies") or {}
- dev_deps = package_json.get("devDependencies") or {}
- if not isinstance(deps, dict) or not isinstance(dev_deps, dict):
- return set()
- return set(deps.keys()) | set(dev_deps.keys())
-
-
-def _detect_framework_signature(package_json: dict[str, Any]) -> _FrameworkSignature | None:
- all_deps = _collect_dependency_keys(package_json)
- for signature in _FRAMEWORK_SIGNATURES:
- if all(dep in all_deps for dep in signature.dep_keys):
- return signature
- return None
-
-
-def _detect_node_version(package_json: dict[str, Any]) -> str:
- """Extract a Node major version from `engines.node`, falling back to "20".
-
- `engines.node` is a semver range. We don't need to evaluate the range —
- just pull the leading major number so we know which Node line to
- install. "Doesn't pick the freshest patch" is fine; the build env can
- decide that.
- """
- engines = package_json.get("engines") or {}
- if not isinstance(engines, dict):
- return "20"
- node_constraint = engines.get("node")
- if not isinstance(node_constraint, str):
- return "20"
- for char in node_constraint:
- if char.isdigit():
- return _read_leading_int(node_constraint[node_constraint.index(char) :])
- return "20"
-
-
-def _read_leading_int(s: str) -> str:
- digits: list[str] = []
- for char in s:
- if char.isdigit():
- digits.append(char)
- else:
- break
- return "".join(digits) or "20"
-
-
-def detect_config(
- package_json: dict[str, Any] | None,
- lockfile_names: list[str],
-) -> DetectedConfig:
- """Suggest a config from a repo's `package.json` + lockfile presence.
-
- `package_json=None` (or an empty dict) means "no package.json found" —
- treated as a plain-HTML repo: no install, no build, serve the root.
-
- The returned config is a suggestion; the user can override every field
- in the connect-repo UI. Detection should never raise — bad inputs land
- on the plain-HTML fallback so the connect flow can still complete and
- the user fixes things in the form.
- """
- manager = detect_package_manager(lockfile_names)
-
- if not package_json:
- return DetectedConfig(
- package_manager=manager,
- install_command="",
- build_command="",
- output_dir=".",
- node_version="20",
- framework=None,
- )
-
- signature = _detect_framework_signature(package_json)
- node_version = _detect_node_version(package_json)
-
- if signature is None:
- # `package.json` present but no known framework — leave the build
- # command empty so the user has to fill it in. We return
- # `framework=None` so the build worker's own auto-detection can
- # have a go.
- return DetectedConfig(
- package_manager=manager,
- install_command=_install_command_for(manager),
- build_command="",
- output_dir="dist",
- node_version=node_version,
- framework=None,
- )
-
- return DetectedConfig(
- package_manager=manager,
- install_command=_install_command_for(manager),
- build_command=_build_invocation(manager, signature.build_script),
- output_dir=signature.output_dir,
- node_version=node_version,
- framework=signature.framework,
- )
diff --git a/products/deployments/backend/services/finalize_failure.py b/products/deployments/backend/services/finalize_failure.py
deleted file mode 100644
index c4ec5b91d6ad..000000000000
--- a/products/deployments/backend/services/finalize_failure.py
+++ /dev/null
@@ -1,53 +0,0 @@
-"""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
deleted file mode 100644
index 11d49fab5683..000000000000
--- a/products/deployments/backend/services/finalize_success.py
+++ /dev/null
@@ -1,173 +0,0 @@
-"""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/mock_pipeline.py b/products/deployments/backend/services/mock_pipeline.py
deleted file mode 100644
index c5f9a900e157..000000000000
--- a/products/deployments/backend/services/mock_pipeline.py
+++ /dev/null
@@ -1,6 +0,0 @@
-"""Mock build pipeline for the Deployments product.
-
-# TODO(deployments-v1): walk a deployment through Queued -> Initializing
-# -> Building -> Ready, writing `started_at` / `finished_at` along the way.
-# Will be exposed as a Celery task once `posthog/celery.py` is wired.
-"""
diff --git a/products/deployments/backend/services/preview_capture.py b/products/deployments/backend/services/preview_capture.py
deleted file mode 100644
index 12167df0d7d1..000000000000
--- a/products/deployments/backend/services/preview_capture.py
+++ /dev/null
@@ -1,5 +0,0 @@
-"""Preview screenshot capture for the Deployments product.
-
-# TODO(deployments-v1): wire up microlink-backed screenshot capture and
-# persistence of `preview_image_url` on the `Deployment` model.
-"""
diff --git a/products/deployments/backend/services/provision_project.py b/products/deployments/backend/services/provision_project.py
deleted file mode 100644
index adbdd4e6e045..000000000000
--- a/products/deployments/backend/services/provision_project.py
+++ /dev/null
@@ -1,82 +0,0 @@
-"""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 loses a uniqueness
-race, 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
- github_repo_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,
- github_repo_id=payload.github_repo_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
deleted file mode 100644
index 81714db78a0f..000000000000
--- a/products/deployments/backend/services/redeploy.py
+++ /dev/null
@@ -1,34 +0,0 @@
-"""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
deleted file mode 100644
index 1fef2e23f171..000000000000
--- a/products/deployments/backend/services/refresh_preview.py
+++ /dev/null
@@ -1,44 +0,0 @@
-"""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
deleted file mode 100644
index eb4785e72a04..000000000000
--- a/products/deployments/backend/services/rollback.py
+++ /dev/null
@@ -1,40 +0,0 @@
-"""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
deleted file mode 100644
index e47e5699a68d..000000000000
--- a/products/deployments/backend/services/update_status.py
+++ /dev/null
@@ -1,105 +0,0 @@
-"""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/temporal/__init__.py b/products/deployments/backend/temporal/__init__.py
deleted file mode 100644
index 328d39109bf2..000000000000
--- a/products/deployments/backend/temporal/__init__.py
+++ /dev/null
@@ -1,32 +0,0 @@
-"""Temporal workflows + activities for the Deployments product.
-
-The `start_temporal_worker` management command imports `WORKFLOWS` and
-`ACTIVITIES` from here and registers them on the `deployments-task-queue`.
-"""
-
-from .activities import (
- build_site,
- clone_repo,
- initialize_build,
- install_dependencies,
- mark_failed,
- mark_ready,
- start_building,
- upload_artifacts,
-)
-from .build_workflow import DeploymentBuildWorkflow
-
-WORKFLOWS = [DeploymentBuildWorkflow]
-
-ACTIVITIES = [
- initialize_build,
- clone_repo,
- install_dependencies,
- start_building,
- build_site,
- upload_artifacts,
- mark_ready,
- mark_failed,
-]
-
-__all__ = ["ACTIVITIES", "WORKFLOWS", "DeploymentBuildWorkflow"]
diff --git a/products/deployments/backend/temporal/activities.py b/products/deployments/backend/temporal/activities.py
deleted file mode 100644
index 415c6348c4d9..000000000000
--- a/products/deployments/backend/temporal/activities.py
+++ /dev/null
@@ -1,182 +0,0 @@
-"""Activities for the Deployments build workflow.
-
-This is the v1 scaffolding: every activity posts an event/transition so
-the timeline + state machine work end-to-end, but the actual build
-steps (clone, install, build, upload) are stubs. The real work lives
-behind hogland sandbox provisioning in a follow-up PR — see
-`.notes/deployments-substrate.md` for why we run user code in a
-Firecracker microVM, not directly in this worker pod.
-
-Each activity returns quickly. Temporal handles retries; we don't
-retry inside.
-"""
-
-from __future__ import annotations
-
-import asyncio
-from dataclasses import dataclass
-from uuid import UUID
-
-from temporalio import activity
-
-from ..domain.status import Status
-from ..domain.trigger import ErrorStep
-from .internal_api import post_event, post_transition
-
-
-@dataclass(frozen=True)
-class StepInput:
- """Common shape for build-step activities.
-
- Carries every field from `BuildInput` that any activity may need —
- `github_access_token` and `build_command` are unused by the current
- stub activities but the real `clone_repo` / `build_site` will read
- them. Locking the shape in now means swapping the stubs for real
- activities is a body-only change, not a signature change.
- """
-
- deployment_id: UUID
- cloudflare_project_name: str
- repo_url: str
- branch: str
- commit_sha: str
- output_dir: str
- github_access_token: str | None
- build_command: str | None
-
-
-@dataclass(frozen=True)
-class MarkReadyInput:
- deployment_id: UUID
- deployment_url: str
- cloudflare_deployment_id: str | None
-
-
-@dataclass(frozen=True)
-class MarkFailedInput:
- deployment_id: UUID
- error_message: str
- error_step: ErrorStep
-
-
-# Stub sleep durations — keep small enough that test runs don't drag,
-# big enough that the timeline UI shows something happening when this
-# is running against a real cluster.
-_STUB_STEP_SLEEP_SECONDS = 0.5
-
-
[email protected](name="deployment-build.initialize")
-async def initialize_build(payload: StepInput) -> None:
- """Move the deployment from QUEUED to INITIALIZING."""
- await post_transition(deployment_id=payload.deployment_id, status=Status.INITIALIZING)
- await post_event(
- deployment_id=payload.deployment_id,
- event_type="status_changed",
- payload={"to": Status.INITIALIZING.value},
- )
-
-
[email protected](name="deployment-build.clone")
-async def clone_repo(payload: StepInput) -> None:
- """STUB: pretend to clone `payload.repo_url` at `payload.commit_sha`."""
- await post_event(
- deployment_id=payload.deployment_id,
- event_type="clone_started",
- payload={"repo_url": payload.repo_url, "branch": payload.branch, "commit_sha": payload.commit_sha},
- )
- await asyncio.sleep(_STUB_STEP_SLEEP_SECONDS)
- await post_event(deployment_id=payload.deployment_id, event_type="clone_complete")
-
-
[email protected](name="deployment-build.install")
-async def install_dependencies(payload: StepInput) -> None:
- """STUB: pretend to install dependencies."""
- await post_event(deployment_id=payload.deployment_id, event_type="install_started")
- await asyncio.sleep(_STUB_STEP_SLEEP_SECONDS)
- await post_event(deployment_id=payload.deployment_id, event_type="install_complete")
-
-
[email protected](name="deployment-build.start_building")
-async def start_building(payload: StepInput) -> None:
- """Move the deployment from INITIALIZING to BUILDING."""
- await post_transition(deployment_id=payload.deployment_id, status=Status.BUILDING)
- await post_event(
- deployment_id=payload.deployment_id,
- event_type="status_changed",
- payload={"to": Status.BUILDING.value},
- )
-
-
[email protected](name="deployment-build.build")
-async def build_site(payload: StepInput) -> None:
- """STUB: pretend to run the build."""
- await post_event(deployment_id=payload.deployment_id, event_type="build_started")
- await asyncio.sleep(_STUB_STEP_SLEEP_SECONDS)
- await post_event(
- deployment_id=payload.deployment_id,
- event_type="build_complete",
- payload={"output_dir": payload.output_dir},
- )
-
-
[email protected](name="deployment-build.upload")
-async def upload_artifacts(payload: StepInput) -> str:
- """STUB: pretend to upload to Cloudflare Pages.
-
- Returns a synthetic deployment URL so the workflow can complete.
- The real adapter will return Cloudflare's actual deployment URL
- once the upload step is implemented (hogland-side).
- """
- await post_event(deployment_id=payload.deployment_id, event_type="upload_started")
- await asyncio.sleep(_STUB_STEP_SLEEP_SECONDS)
- synthetic_url = f"https://{payload.cloudflare_project_name}.pages.dev"
- await post_event(
- deployment_id=payload.deployment_id,
- event_type="upload_complete",
- payload={"deployment_url": synthetic_url, "stub": True},
- )
- return synthetic_url
-
-
[email protected](name="deployment-build.mark_ready")
-async def mark_ready(payload: MarkReadyInput) -> None:
- """Move the deployment from BUILDING to READY."""
- await post_transition(
- deployment_id=payload.deployment_id,
- status=Status.READY,
- deployment_url=payload.deployment_url,
- cloudflare_deployment_id=payload.cloudflare_deployment_id,
- )
- await post_event(
- deployment_id=payload.deployment_id,
- event_type="status_changed",
- payload={"to": Status.READY.value, "deployment_url": payload.deployment_url},
- )
-
-
[email protected](name="deployment-build.mark_failed")
-async def mark_failed(payload: MarkFailedInput) -> None:
- """Move the deployment from a non-terminal status to ERROR.
-
- Best-effort: the workflow calls this in an exception handler. If
- posting the transition itself fails (e.g. internal API down), the
- activity raises and Temporal retries. If we exhaust retries, the
- workflow run is left in whatever non-terminal status it was in when
- the original error fired — a janitor sweep would need to catch that
- separately, but that's out of scope for v1.
- """
- await post_transition(
- deployment_id=payload.deployment_id,
- status=Status.ERROR,
- error_message=payload.error_message,
- error_step=payload.error_step,
- )
- await post_event(
- deployment_id=payload.deployment_id,
- event_type="status_changed",
- payload={
- "to": Status.ERROR.value,
- "error_step": payload.error_step.value,
- "error_message": payload.error_message,
- },
- )
diff --git a/products/deployments/backend/temporal/build_workflow.py b/products/deployments/backend/temporal/build_workflow.py
deleted file mode 100644
index 7ddae8f29d99..000000000000
--- a/products/deployments/backend/temporal/build_workflow.py
+++ /dev/null
@@ -1,139 +0,0 @@
-"""Temporal workflow that drives a single deployment build.
-
-Orchestrates the stub activities in `activities.py`. Real build work
-(clone / install / build / upload) is stubbed at the activity level
-pending hogland integration — this file shouldn't change when that
-lands; only the underlying activities will.
-
-The workflow id is `deployment-{deployment_id}` (set by the Django-side
-`TemporalWorkflowAdapter.start_build`). The workflow type is
-`"deployment-build"`.
-
-Each activity gets its own retry policy:
-- Initialize / mark_ready / mark_failed / start_building → API calls
- to ourselves, retry liberally.
-- Build steps (clone / install / build / upload) → retry once, since
- they're stubs today but will run real user code in a sandbox once
- hogland lands. Retrying a flaky `npm install` is fine; retrying a
- build that hit a real compile error wastes minutes.
-
-On any activity failure, the workflow posts an `ERROR` transition with
-the right `error_step` and re-raises so Temporal records the run as
-failed.
-"""
-
-from __future__ import annotations
-
-from datetime import timedelta
-
-from temporalio import workflow
-from temporalio.common import RetryPolicy
-from temporalio.exceptions import ActivityError
-
-from ..domain.contracts import BuildInput
-from ..domain.trigger import ErrorStep
-from .activities import (
- MarkFailedInput,
- MarkReadyInput,
- StepInput,
- build_site,
- clone_repo,
- initialize_build,
- install_dependencies,
- mark_failed,
- mark_ready,
- start_building,
- upload_artifacts,
-)
-
-# API-call activities (`initialize`, `start_building`, `mark_*`) are
-# cheap idempotent posts to the internal HTTP API. Build-step activities
-# do real work and are expensive to retry. Different retry profiles.
-_API_RETRY = RetryPolicy(maximum_attempts=5, initial_interval=timedelta(seconds=1))
-_BUILD_RETRY = RetryPolicy(maximum_attempts=2, initial_interval=timedelta(seconds=2))
-
-_API_TIMEOUT = timedelta(seconds=30)
-_BUILD_TIMEOUT = timedelta(minutes=10)
-
-
[email protected](name="deployment-build")
-class DeploymentBuildWorkflow:
- """One run per Deployment row.
-
- Posts status transitions through QUEUED → INITIALIZING → BUILDING →
- READY (or ERROR on any failure). Activities post to the internal
- API; this workflow never writes to the DB directly.
- """
-
- @workflow.run
- async def run(self, payload: BuildInput) -> None:
- step = StepInput(
- deployment_id=payload.deployment_id,
- cloudflare_project_name=payload.cloudflare_project_name,
- repo_url=payload.repo_url,
- branch=payload.branch,
- commit_sha=payload.commit_sha,
- output_dir=payload.output_dir,
- github_access_token=payload.github_access_token,
- build_command=payload.build_command,
- )
-
- # `current_step` tracks which build phase is in flight so we
- # can mark_failed with the right error_step if anything raises.
- current_step = ErrorStep.DISPATCH
- try:
- await workflow.execute_activity(
- initialize_build, step, start_to_close_timeout=_API_TIMEOUT, retry_policy=_API_RETRY
- )
-
- current_step = ErrorStep.CLONE
- await workflow.execute_activity(
- clone_repo, step, start_to_close_timeout=_BUILD_TIMEOUT, retry_policy=_BUILD_RETRY
- )
-
- current_step = ErrorStep.INSTALL
- await workflow.execute_activity(
- install_dependencies, step, start_to_close_timeout=_BUILD_TIMEOUT, retry_policy=_BUILD_RETRY
- )
-
- # `start_building` is the gateway to the BUILD phase — a
- # failure transitioning into building should report
- # `error_step=build`, not `install`.
- current_step = ErrorStep.BUILD
- await workflow.execute_activity(
- start_building, step, start_to_close_timeout=_API_TIMEOUT, retry_policy=_API_RETRY
- )
-
- await workflow.execute_activity(
- build_site, step, start_to_close_timeout=_BUILD_TIMEOUT, retry_policy=_BUILD_RETRY
- )
-
- current_step = ErrorStep.PUBLISH
- deployment_url = await workflow.execute_activity(
- upload_artifacts, step, start_to_close_timeout=_BUILD_TIMEOUT, retry_policy=_BUILD_RETRY
- )
-
- await workflow.execute_activity(
- mark_ready,
- MarkReadyInput(
- deployment_id=payload.deployment_id,
- deployment_url=deployment_url,
- # No CF deployment id yet — populated once the real
- # upload activity returns one.
- cloudflare_deployment_id=None,
- ),
- start_to_close_timeout=_API_TIMEOUT,
- retry_policy=_API_RETRY,
- )
- except ActivityError as err:
- await workflow.execute_activity(
- mark_failed,
- MarkFailedInput(
- deployment_id=payload.deployment_id,
- error_message=str(err),
- error_step=current_step,
- ),
- start_to_close_timeout=_API_TIMEOUT,
- retry_policy=_API_RETRY,
- )
- raise
diff --git a/products/deployments/backend/temporal/internal_api.py b/products/deployments/backend/temporal/internal_api.py
deleted file mode 100644
index 7dd3de168155..000000000000
--- a/products/deployments/backend/temporal/internal_api.py
+++ /dev/null
@@ -1,113 +0,0 @@
-"""Thin HTTP client the build worker uses to call the Deployments internal API.
-
-The internal endpoints (`POST /api/internal/deployments/{id}/transitions/`
-and `.../events/`) live in `products/deployments/backend/api/internal.py`.
-The worker uses them to advance the deployment's state machine and to
-append timeline events as activities run.
-
-Auth is the shared `X-Internal-Api-Secret` header. URL is configurable
-via `DEPLOYMENTS_INTERNAL_API_BASE_URL` so the worker can target the
-cluster-internal Service rather than the public ingress.
-"""
-
-from __future__ import annotations
-
-from typing import Any
-from uuid import UUID
-
-from django.conf import settings
-
-import httpx
-from temporalio.exceptions import ApplicationError
-
-from ..domain.status import Status
-from ..domain.trigger import ErrorStep
-
-# Tight enough that activity heartbeats from a hung internal API surface
-# fast, but generous enough to ride out a routine pod restart.
-INTERNAL_API_TIMEOUT_SECONDS = 15
-
-
-class InternalApiError(Exception):
- """Raised when the internal API returns a non-2xx response."""
-
-
-def _raise_for_status(*, method: str, path: str, status_code: int, body: str) -> None:
- """Raise the right exception type for a non-2xx response.
-
- 4xx indicates a client error (invalid transition, missing row, auth
- failure) — retrying won't help, so raise as a non-retryable
- `ApplicationError` so Temporal stops immediately. 5xx is a server
- error or transient infra failure; raise the plain `InternalApiError`
- so Temporal's retry policy kicks in.
- """
- message = f"Internal API {method} {path} failed: {status_code} {body[:200]}"
- if 400 <= status_code < 500:
- raise ApplicationError(message, type="InternalApiClientError", non_retryable=True)
- raise InternalApiError(message)
-
-
-def _base_url() -> str:
- base = getattr(settings, "DEPLOYMENTS_INTERNAL_API_BASE_URL", "") or getattr(settings, "SITE_URL", "")
- if not base:
- # Missing env vars won't fix themselves between retries — raise
- # a non-retryable error so the activity fails immediately rather
- # than burning the full _API_RETRY budget on a misconfiguration.
- raise ApplicationError(
- "Missing setting: DEPLOYMENTS_INTERNAL_API_BASE_URL (or SITE_URL). "
- "The deployments worker needs a URL to call back to the web pods.",
- type="InternalApiConfigError",
- non_retryable=True,
- )
- return base.rstrip("/")
-
-
-def _headers() -> dict[str, str]:
- secret = getattr(settings, "INTERNAL_API_SECRET", "")
- if not secret:
- raise ApplicationError(
- "Missing setting: INTERNAL_API_SECRET.",
- type="InternalApiConfigError",
- non_retryable=True,
- )
- return {"X-Internal-Api-Secret": secret, "Content-Type": "application/json"}
-
-
-async def post_transition(
- *,
- 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,
-) -> None:
- """Post a status transition to the internal API."""
- body: dict[str, Any] = {"status": status.value}
- if cloudflare_deployment_id:
- body["cloudflare_deployment_id"] = cloudflare_deployment_id
- if deployment_url:
- body["deployment_url"] = deployment_url
- if error_message:
- body["error_message"] = error_message
- if error_step is not None:
- body["error_step"] = error_step.value
-
- url = f"{_base_url()}/api/internal/deployments/{deployment_id}/transitions/"
- async with httpx.AsyncClient(timeout=INTERNAL_API_TIMEOUT_SECONDS) as client:
- response = await client.post(url, json=body, headers=_headers())
- if not response.is_success:
- _raise_for_status(method="POST", path="transitions", status_code=response.status_code, body=response.text)
-
-
-async def post_event(*, deployment_id: UUID | str, event_type: str, payload: dict[str, Any] | None = None) -> None:
- """Append a timeline event for the deployment."""
- body: dict[str, Any] = {"event_type": event_type}
- if payload is not None:
- body["payload"] = payload
-
- url = f"{_base_url()}/api/internal/deployments/{deployment_id}/events/"
- async with httpx.AsyncClient(timeout=INTERNAL_API_TIMEOUT_SECONDS) as client:
- response = await client.post(url, json=body, headers=_headers())
- if not response.is_success:
- _raise_for_status(method="POST", path="events", status_code=response.status_code, body=response.text)
diff --git a/products/deployments/backend/test/__init__.py b/products/deployments/backend/test/__init__.py
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/deployments/backend/test/_helpers.py b/products/deployments/backend/test/_helpers.py
deleted file mode 100644
index e89eace23dd8..000000000000
--- a/products/deployments/backend/test/_helpers.py
+++ /dev/null
@@ -1,41 +0,0 @@
-"""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_build_workflow_activities.py b/products/deployments/backend/test/test_build_workflow_activities.py
deleted file mode 100644
index b1a58ba0efcb..000000000000
--- a/products/deployments/backend/test/test_build_workflow_activities.py
+++ /dev/null
@@ -1,137 +0,0 @@
-from __future__ import annotations
-
-from uuid import UUID
-
-import pytest
-from unittest.mock import AsyncMock, patch
-
-from django.test import SimpleTestCase
-
-from parameterized import parameterized
-
-from products.deployments.backend.domain.status import Status
-from products.deployments.backend.domain.trigger import ErrorStep
-from products.deployments.backend.temporal.activities import (
- MarkFailedInput,
- MarkReadyInput,
- StepInput,
- build_site,
- clone_repo,
- initialize_build,
- install_dependencies,
- mark_failed,
- mark_ready,
- start_building,
- upload_artifacts,
-)
-
-DEPLOYMENT_ID = UUID("00000000-0000-7000-8000-000000000001")
-STEP = StepInput(
- deployment_id=DEPLOYMENT_ID,
- cloudflare_project_name="hogdev-1-myapp",
- repo_url="https://github.com/example/repo",
- branch="main",
- commit_sha="abc123",
- output_dir="dist",
- github_access_token=None,
- build_command=None,
-)
-
-
-class TestBuildActivities(SimpleTestCase):
- @pytest.mark.asyncio
- async def test_initialize_build_posts_initializing_transition(self) -> None:
- with (
- patch("products.deployments.backend.temporal.activities.post_transition", new=AsyncMock()) as t,
- patch("products.deployments.backend.temporal.activities.post_event", new=AsyncMock()) as e,
- ):
- await initialize_build(STEP)
-
- t.assert_awaited_once_with(deployment_id=DEPLOYMENT_ID, status=Status.INITIALIZING)
- e.assert_awaited_once()
- # Event payload mirrors the transition.
- assert e.await_args is not None
- kwargs = e.await_args.kwargs
- self.assertEqual(kwargs["deployment_id"], DEPLOYMENT_ID)
- self.assertEqual(kwargs["event_type"], "status_changed")
- self.assertEqual(kwargs["payload"], {"to": "initializing"})
-
- @pytest.mark.asyncio
- async def test_start_building_posts_building_transition(self) -> None:
- with (
- patch("products.deployments.backend.temporal.activities.post_transition", new=AsyncMock()) as t,
- patch("products.deployments.backend.temporal.activities.post_event", new=AsyncMock()),
- ):
- await start_building(STEP)
- t.assert_awaited_once_with(deployment_id=DEPLOYMENT_ID, status=Status.BUILDING)
-
- @pytest.mark.asyncio
- async def test_mark_ready_propagates_deployment_url(self) -> None:
- payload = MarkReadyInput(
- deployment_id=DEPLOYMENT_ID,
- deployment_url="https://hogdev-1-myapp.pages.dev",
- cloudflare_deployment_id="d1",
- )
- with (
- patch("products.deployments.backend.temporal.activities.post_transition", new=AsyncMock()) as t,
- patch("products.deployments.backend.temporal.activities.post_event", new=AsyncMock()),
- ):
- await mark_ready(payload)
- t.assert_awaited_once_with(
- deployment_id=DEPLOYMENT_ID,
- status=Status.READY,
- deployment_url="https://hogdev-1-myapp.pages.dev",
- cloudflare_deployment_id="d1",
- )
-
- @pytest.mark.asyncio
- async def test_mark_failed_propagates_error_step(self) -> None:
- payload = MarkFailedInput(deployment_id=DEPLOYMENT_ID, error_message="kaboom", error_step=ErrorStep.BUILD)
- with (
- patch("products.deployments.backend.temporal.activities.post_transition", new=AsyncMock()) as t,
- patch("products.deployments.backend.temporal.activities.post_event", new=AsyncMock()) as e,
- ):
- await mark_failed(payload)
- t.assert_awaited_once_with(
- deployment_id=DEPLOYMENT_ID,
- status=Status.ERROR,
- error_message="kaboom",
- error_step=ErrorStep.BUILD,
- )
- # Event payload includes the error step + message for the timeline.
- assert e.await_args is not None
- kwargs = e.await_args.kwargs
- self.assertEqual(kwargs["payload"]["error_step"], "build")
- self.assertEqual(kwargs["payload"]["error_message"], "kaboom")
-
- @parameterized.expand(
- [
- ("clone_repo", clone_repo),
- ("install_dependencies", install_dependencies),
- ("build_site", build_site),
- ]
- )
- @pytest.mark.asyncio
- async def test_build_step_stub_only_emits_events(self, _name: str, activity) -> None:
- # The build-step stubs don't post transitions — those are the
- # responsibility of initialize_build / start_building / mark_*.
- # Each stub only emits events for the timeline.
- with (
- patch("products.deployments.backend.temporal.activities.post_transition", new=AsyncMock()) as t,
- patch("products.deployments.backend.temporal.activities.post_event", new=AsyncMock()) as e,
- ):
- await activity(STEP)
- t.assert_not_awaited()
- self.assertGreaterEqual(e.await_count, 1)
-
- @pytest.mark.asyncio
- async def test_upload_artifacts_returns_synthetic_pages_url(self) -> None:
- with (
- patch("products.deployments.backend.temporal.activities.post_transition", new=AsyncMock()),
- patch("products.deployments.backend.temporal.activities.post_event", new=AsyncMock()),
- ):
- url = await upload_artifacts(STEP)
- # Until the hogland-backed real upload lands, this is a known
- # placeholder so the workflow can complete end-to-end. The
- # placeholder shape mirrors what CF would return.
- self.assertEqual(url, "https://hogdev-1-myapp.pages.dev")
diff --git a/products/deployments/backend/test/test_cloudflare_adapter.py b/products/deployments/backend/test/test_cloudflare_adapter.py
deleted file mode 100644
index c3bf97f54b61..000000000000
--- a/products/deployments/backend/test/test_cloudflare_adapter.py
+++ /dev/null
@@ -1,264 +0,0 @@
-from __future__ import annotations
-
-from django.test import SimpleTestCase, override_settings
-
-import requests
-import responses
-from parameterized import parameterized
-
-from products.deployments.backend.adapters.cloudflare import (
- CLOUDFLARE_API_BASE,
- CLOUDFLARE_API_TIMEOUT_SECONDS,
- CFProject,
- CloudflareError,
- CloudflarePagesAdapter,
-)
-
-ACCOUNT_ID = "test-account-id"
-PROJECT_PREFIX = "hogdev-"
-
-
-@override_settings(
- DEPLOYMENTS_CLOUDFLARE_ACCOUNT_ID=ACCOUNT_ID,
- DEPLOYMENTS_CLOUDFLARE_API_TOKEN="test-token",
- DEPLOYMENTS_CLOUDFLARE_PROJECT_PREFIX=PROJECT_PREFIX,
-)
-class TestCloudflarePagesAdapter(SimpleTestCase):
- @responses.activate
- def test_create_project_posts_prefixed_name_and_attaches_hog_dev_domain(self) -> None:
- create_url = f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects"
- domain_url = f"{create_url}/{PROJECT_PREFIX}1-myapp/domains"
- responses.add(
- responses.POST,
- create_url,
- json={"success": True, "errors": [], "messages": [], "result": {"name": f"{PROJECT_PREFIX}1-myapp"}},
- status=200,
- )
- responses.add(
- responses.POST,
- domain_url,
- json={"success": True, "errors": [], "messages": [], "result": {"name": "1-myapp.hog.dev"}},
- status=200,
- )
-
- project = CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")
-
- self.assertEqual(project, CFProject(name=f"{PROJECT_PREFIX}1-myapp", subdomain="1-myapp.hog.dev"))
- self.assertEqual(len(responses.calls), 2)
- self.assertEqual(
- responses.calls[0].request.body,
- b'{"name": "hogdev-1-myapp", "production_branch": "main"}',
- )
- self.assertEqual(responses.calls[1].request.body, b'{"name": "1-myapp.hog.dev"}')
- # Bearer auth + request-path timeout.
- self.assertEqual(responses.calls[0].request.headers["Authorization"], "Bearer test-token")
-
- @responses.activate
- def test_create_project_raises_when_cloudflare_returns_success_false(self) -> None:
- responses.add(
- responses.POST,
- f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects",
- json={
- "success": False,
- "errors": [{"code": 1009, "message": "Project name already taken"}],
- "result": None,
- },
- status=200,
- )
-
- with self.assertRaises(CloudflareError) as cm:
- CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")
- self.assertIn("Project name already taken", str(cm.exception))
-
- @responses.activate
- def test_create_project_falls_back_when_cf_error_lacks_message_key(self) -> None:
- # Some CF responses come back with an `errors` array of dicts
- # that lack a `"message"` key — without a fallback, the user
- # would see `"Cloudflare API call failed: None (status 500)"`.
- responses.add(
- responses.POST,
- f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects",
- json={"success": False, "errors": [{"code": 9001}], "result": None},
- status=500,
- )
-
- with self.assertRaises(CloudflareError) as cm:
- CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")
- self.assertIn("Unknown error", str(cm.exception))
- self.assertNotIn("None", str(cm.exception))
-
- @responses.activate
- def test_create_project_error_does_not_leak_account_id(self) -> None:
- # CloudflareError is rendered into a public 502 response body by
- # the viewset, so the account ID (which appears in the API path)
- # must never end up in the exception message.
- responses.add(
- responses.POST,
- f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects",
- json={"success": False, "errors": [{"message": "boom"}], "result": None},
- status=500,
- )
-
- with self.assertRaises(CloudflareError) as cm:
- CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")
- self.assertNotIn(ACCOUNT_ID, str(cm.exception))
-
- @responses.activate
- def test_create_project_raises_on_http_error(self) -> None:
- responses.add(
- responses.POST,
- f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects",
- json={"success": False, "errors": [{"message": "Unauthorized"}], "result": None},
- status=401,
- )
-
- with self.assertRaises(CloudflareError) as cm:
- CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")
- self.assertIn("Unauthorized", str(cm.exception))
- self.assertIn("401", str(cm.exception))
-
- @responses.activate
- def test_create_project_raises_on_network_error(self) -> None:
- responses.add(
- responses.POST,
- f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects",
- body=requests.ConnectionError("connection refused"),
- )
-
- with self.assertRaises(CloudflareError) as cm:
- CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")
- self.assertIn("connection refused", str(cm.exception))
-
- @parameterized.expand(
- [
- ("missing_account_id", "", "test-token"),
- ("missing_api_token", ACCOUNT_ID, ""),
- ("both_missing", "", ""),
- ]
- )
- def test_create_project_raises_when_settings_missing(self, _name: str, account_id: str, api_token: str) -> None:
- with override_settings(
- DEPLOYMENTS_CLOUDFLARE_ACCOUNT_ID=account_id,
- DEPLOYMENTS_CLOUDFLARE_API_TOKEN=api_token,
- ):
- with self.assertRaises(CloudflareError) as cm:
- CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")
- self.assertIn("missing required settings", str(cm.exception))
-
- @responses.activate
- def test_create_project_does_not_attach_domain_if_create_call_fails(self) -> None:
- responses.add(
- responses.POST,
- f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects",
- json={"success": False, "errors": [{"message": "bad request"}], "result": None},
- status=400,
- )
-
- with self.assertRaises(CloudflareError):
- CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")
- # Only the create call should have been attempted.
- self.assertEqual(len(responses.calls), 1)
-
- @responses.activate
- def test_create_project_deletes_orphan_when_domain_attach_fails(self) -> None:
- # Create succeeds.
- create_url = f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects"
- project_url = f"{create_url}/{PROJECT_PREFIX}1-myapp"
- responses.add(
- responses.POST,
- create_url,
- json={"success": True, "errors": [], "messages": [], "result": {"name": f"{PROJECT_PREFIX}1-myapp"}},
- status=200,
- )
- # Domain attach fails.
- responses.add(
- responses.POST,
- f"{project_url}/domains",
- json={"success": False, "errors": [{"message": "domain conflict"}], "result": None},
- status=409,
- )
- # Cleanup DELETE succeeds.
- responses.add(
- responses.DELETE,
- project_url,
- json={"success": True, "errors": [], "messages": [], "result": {"id": f"{PROJECT_PREFIX}1-myapp"}},
- status=200,
- )
-
- with self.assertRaises(CloudflareError) as cm:
- CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")
- # The error surfaced is the domain-attach failure, not a delete-cleanup error.
- self.assertIn("domain conflict", str(cm.exception))
- # All three calls happened: create, attach, delete (cleanup).
- self.assertEqual(len(responses.calls), 3)
- self.assertEqual(responses.calls[2].request.method, "DELETE")
-
- @responses.activate
- def test_create_project_still_raises_original_error_if_cleanup_also_fails(self) -> None:
- create_url = f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects"
- project_url = f"{create_url}/{PROJECT_PREFIX}1-myapp"
- responses.add(
- responses.POST,
- create_url,
- json={"success": True, "errors": [], "messages": [], "result": {"name": f"{PROJECT_PREFIX}1-myapp"}},
- status=200,
- )
- responses.add(
- responses.POST,
- f"{project_url}/domains",
- json={"success": False, "errors": [{"message": "domain attach failed"}], "result": None},
- status=500,
- )
- responses.add(
- responses.DELETE,
- project_url,
- json={"success": False, "errors": [{"message": "cleanup also failed"}], "result": None},
- status=500,
- )
-
- with self.assertRaises(CloudflareError) as cm:
- CloudflarePagesAdapter().create_project(name="1-myapp", production_branch="main")
- # User-facing error is still the attach failure — cleanup error is logged, not raised.
- self.assertIn("domain attach failed", str(cm.exception))
- self.assertNotIn("cleanup also failed", str(cm.exception))
-
- @responses.activate
- def test_rollback_returns_deployment_from_response(self) -> None:
- url = f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects/hogdev-1-myapp/deployments/dep-old/rollback"
- responses.add(
- responses.POST,
- url,
- json={
- "success": True,
- "errors": [],
- "messages": [],
- "result": {"id": "dep-new", "url": "https://hogdev-1-myapp.pages.dev"},
- },
- status=200,
- )
-
- deployment = CloudflarePagesAdapter().rollback(project_name="hogdev-1-myapp", deployment_id="dep-old")
-
- self.assertEqual(deployment.id, "dep-new")
- self.assertEqual(deployment.url, "https://hogdev-1-myapp.pages.dev")
-
- @responses.activate
- def test_rollback_raises_when_response_missing_url(self) -> None:
- responses.add(
- responses.POST,
- f"{CLOUDFLARE_API_BASE}/accounts/{ACCOUNT_ID}/pages/projects/p/deployments/d/rollback",
- json={"success": True, "errors": [], "messages": [], "result": {"id": "dep-new"}},
- status=200,
- )
-
- with self.assertRaises(CloudflareError) as cm:
- CloudflarePagesAdapter().rollback(project_name="p", deployment_id="d")
- self.assertIn("no deployment URL", str(cm.exception))
-
-
-class TestCloudflareApiConstants(SimpleTestCase):
- def test_timeout_is_short_enough_for_request_path(self) -> None:
- # Sanity: the timeout exists for a reason — keep it small enough
- # that a hanging CF API doesn't drag the user-facing POST handler
- # past typical browser timeouts.
- self.assertLessEqual(CLOUDFLARE_API_TIMEOUT_SECONDS, 15)
diff --git a/products/deployments/backend/test/test_deployments_api.py b/products/deployments/backend/test/test_deployments_api.py
deleted file mode 100644
index fc5db1f37c0c..000000000000
--- a/products/deployments/backend/test/test_deployments_api.py
+++ /dev/null
@@ -1,827 +0,0 @@
-"""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
-
-import uuid as uuidlib
-import datetime as dt
-
-from posthog.test.base import APIBaseTest, ClickhouseTestMixin
-from unittest.mock import MagicMock, patch
-
-from django.utils import timezone
-
-from parameterized import parameterized
-from rest_framework import status
-
-from posthog.clickhouse.client import sync_execute
-from posthog.constants import AvailableFeature
-from posthog.models.event.util import bulk_create_events
-from posthog.models.integration import Integration
-from posthog.models.utils import uuid7
-
-from products.deployments.backend.adapters.github import GitHubBranch, GitHubRepository
-from products.deployments.backend.api.deployments import LOGS_ROW_LIMIT
-from products.deployments.backend.models import Deployment, DeploymentProject
-from products.deployments.backend.test._helpers import DeploymentsTeamScopedTestMixin
-
-from ee.models.rbac.access_control import AccessControl
-
-
-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 _enable_access_control(self) -> None:
- self.organization.available_product_features = [
- {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
- ]
- self.organization.save(update_fields=["available_product_features"])
-
- def _restrict_integrations_resource(self) -> None:
- self._enable_access_control()
- AccessControl.objects.create(
- team=self.team,
- resource="integration",
- resource_id=None,
- access_level="none",
- )
-
- def _restrict_integration(self, integration: Integration) -> None:
- self._enable_access_control()
- AccessControl.objects.create(
- team=self.team,
- resource="integration",
- resource_id=str(integration.id),
- access_level="none",
- )
-
- def _github_integration(self) -> Integration:
- return Integration.objects.create(
- team=self.team,
- kind=Integration.IntegrationKind.GITHUB.value,
- integration_id="12345",
- config={"account": {"name": "PostHog", "type": "Organization"}},
- sensitive_config={"access_token": "ghs_test"},
- errors="",
- )
-
- 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_create_project_rejects_repo_url_input(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",
- "github_integration_id": 42,
- "github_repo_id": 42,
- },
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
- self.assertEqual(response.json().get("attr"), "repo_url")
-
- 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",
- "github_integration_id": outsider.id,
- "github_repo_id": 42,
- },
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND, response.content)
-
- 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",
- "github_integration_id": slack.id,
- "github_repo_id": 42,
- },
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND, response.content)
-
- @patch("products.deployments.backend.api.deployment_projects.get_github_adapter")
- def test_create_provisions_cloudflare_via_null_adapter(self, mock_get_github_adapter: MagicMock) -> None:
- integration = self._github_integration()
- adapter = mock_get_github_adapter.return_value
- adapter.get_repository_by_id.return_value = GitHubRepository(
- id=42,
- full_name="example-org/site",
- default_branch="main",
- html_url="https://github.com/example-org/site",
- )
- adapter.get_branch.return_value = GitHubBranch(name="main", sha="abc123")
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/deployment_projects/",
- {
- "name": "Site",
- "slug": "site",
- "github_integration_id": integration.id,
- "github_repo_id": 42,
- },
- 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"])
-
- @patch("products.deployments.backend.api.deployment_projects.get_github_adapter")
- def test_create_project_uses_existing_github_integration(self, mock_get_github_adapter: MagicMock) -> None:
- integration = self._github_integration()
- adapter = mock_get_github_adapter.return_value
- adapter.get_repository_by_id.return_value = GitHubRepository(
- id=42,
- full_name="PostHog/posthog",
- default_branch="master",
- html_url="https://github.com/PostHog/posthog",
- )
- adapter.get_branch.return_value = GitHubBranch(name="master", sha="abc123")
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/deployment_projects/",
- {
- "name": "Site",
- "slug": "site",
- "github_integration_id": integration.id,
- "github_repo_id": 42,
- },
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.content)
- body = response.json()
- self.assertEqual(body["github_integration_id"], integration.id)
- self.assertEqual(body["github_repo_id"], 42)
- self.assertEqual(body["repo_url"], "https://github.com/PostHog/posthog")
- self.assertEqual(body["default_branch"], "master")
- project = DeploymentProject.all_teams.get(team_id=self.team.id, github_repo_id=42)
- self.assertEqual(project.github_integration_id, integration.id)
-
- @patch("products.deployments.backend.api.deployment_projects.get_github_adapter")
- def test_update_project_rejects_repo_url_input(self, mock_get_github_adapter: MagicMock) -> None:
- integration = self._github_integration()
- project = DeploymentProject.objects.create(
- team_id=self.team.id,
- name="Site",
- slug="site",
- repo_url="https://github.com/PostHog/posthog",
- github_integration_id=integration.id,
- github_repo_id=42,
- default_branch="master",
- )
-
- response = self.client.put(
- f"/api/projects/{self.team.id}/deployment_projects/{project.id}/",
- {
- "name": "Renamed site",
- "slug": "site",
- "repo_url": "https://github.com/Other/repo",
- "github_integration_id": integration.id,
- "github_repo_id": 42,
- },
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
- self.assertEqual(response.json().get("attr"), "repo_url")
- mock_get_github_adapter.assert_not_called()
- project.refresh_from_db()
- self.assertEqual(project.repo_url, "https://github.com/PostHog/posthog")
-
- @parameterized.expand(
- [
- ("resource",),
- ("object",),
- ]
- )
- @patch("products.deployments.backend.api.deployment_projects.get_github_adapter")
- def test_create_project_rejects_restricted_github_integration(
- self, restriction_kind: str, mock_get_github_adapter: MagicMock
- ) -> None:
- integration = self._github_integration()
- if restriction_kind == "resource":
- self._restrict_integrations_resource()
- else:
- self._restrict_integration(integration)
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/deployment_projects/",
- {
- "name": "Site",
- "slug": "site",
- "github_integration_id": integration.id,
- "github_repo_id": 42,
- },
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
- mock_get_github_adapter.return_value.get_repository_by_id.assert_not_called()
-
- def test_create_project_rejects_non_project_github_integration(self) -> None:
- other_team = self.organization.teams.create(name="Other team")
- integration = Integration.objects.create(
- team=other_team,
- kind=Integration.IntegrationKind.GITHUB.value,
- integration_id="12345",
- config={},
- sensitive_config={"access_token": "ghs_test"},
- errors="",
- )
-
- response = self.client.post(
- f"/api/projects/{self.team.id}/deployment_projects/",
- {
- "name": "Site",
- "slug": "site",
- "github_integration_id": integration.id,
- "github_repo_id": 42,
- "default_branch": "master",
- },
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
-
- @patch("products.deployments.backend.api.deployment_projects.get_github_adapter")
- def test_refresh_project_returns_current_branch_sha(self, mock_get_github_adapter: MagicMock) -> None:
- integration = self._github_integration()
- project = DeploymentProject.objects.create(
- team_id=self.team.id,
- name="Site",
- slug="site",
- repo_url="https://github.com/PostHog/posthog",
- github_integration_id=integration.id,
- github_repo_id=42,
- default_branch="master",
- )
- adapter = mock_get_github_adapter.return_value
- adapter.get_repository_by_id.return_value = GitHubRepository(
- id=42,
- full_name="PostHog/posthog",
- default_branch="main",
- html_url="https://github.com/PostHog/posthog",
- )
- adapter.get_branch.return_value = GitHubBranch(name="master", sha="new-sha")
-
- response = self.client.post(f"/api/projects/{self.team.id}/deployment_projects/{project.id}/refresh/")
-
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- body = response.json()
- self.assertEqual(body["default_branch"], "master")
- self.assertEqual(body["commit_sha"], "new-sha")
- project.refresh_from_db()
- self.assertEqual(project.default_branch, "master")
-
- @patch("products.deployments.backend.api.deployment_projects.get_github_adapter")
- def test_refresh_project_rejects_restricted_github_integration(self, mock_get_github_adapter: MagicMock) -> None:
- integration = self._github_integration()
- self._restrict_integration(integration)
- project = DeploymentProject.objects.create(
- team_id=self.team.id,
- name="Site",
- slug="site",
- repo_url="https://github.com/PostHog/posthog",
- github_integration_id=integration.id,
- github_repo_id=42,
- default_branch="master",
- )
-
- response = self.client.post(f"/api/projects/{self.team.id}/deployment_projects/{project.id}/refresh/")
-
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
- mock_get_github_adapter.return_value.get_repository_by_id.assert_not_called()
-
- 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."""
-
- @patch("products.deployments.backend.api.deployment_projects.get_github_adapter")
- def test_create_feature_flag_off_does_not_call_github(self, mock_get_github_adapter: MagicMock) -> None:
- self._flag_patcher.stop()
- with patch(
- "products.deployments.backend.access.posthoganalytics.feature_enabled",
- return_value=False,
- ):
- response = self.client.post(
- f"/api/projects/{self.team.id}/deployment_projects/",
- {
- "name": "Site",
- "slug": "site",
- "github_integration_id": 42,
- "github_repo_id": 42,
- },
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
- mock_get_github_adapter.assert_not_called()
- self._flag_patcher.start()
-
- @parameterized.expand(
- [
- ("flag on returns empty list", True, status.HTTP_200_OK),
- ("flag off returns 403", False, status.HTTP_403_FORBIDDEN),
- ]
- )
- 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}/deployment_projects/")
-
- self.assertEqual(response.status_code, expected_status)
- if expected_status == status.HTTP_200_OK:
- self.assertEqual(response.json()["results"], [])
- # 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()
-
-
-class TestDeploymentLogsEndpoint(
- ClickhouseTestMixin,
- DeploymentsTeamScopedTestMixin,
- APIBaseTest,
-):
- """GET /deployments/{id}/logs/ — HogQL proxy over `$log` events."""
-
- def setUp(self) -> None:
- super().setUp()
- # The feature-flag gate is patched on for the whole suite below;
- # `_BaseDeploymentsAPITest` already does this elsewhere but this
- # class inherits `APIBaseTest` directly (we need ClickhouseTestMixin
- # in front of APIBaseTest, which doesn't compose with the existing
- # `_BaseDeploymentsAPITest` cleanly).
- self._flag_patcher = patch(
- "products.deployments.backend.access.posthoganalytics.feature_enabled",
- return_value=True,
- )
- self._flag_patcher.start()
- self.addCleanup(self._flag_patcher.stop)
-
- # Isolation: scrub the ClickHouse events table so rows from other
- # tests in the same session can't leak in. Mirrors the live_debugger
- # tests at products/live_debugger/backend/test_models.py:18.
- sync_execute("TRUNCATE TABLE IF EXISTS sharded_events")
-
- 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="abc1234",
- )
-
- # ---- helpers ------------------------------------------------------
-
- def _logs_url(self, deployment_id: str | None = None, project_id: str | None = None) -> str:
- pid = project_id or str(self.deployment_project.id)
- did = deployment_id or str(self.deployment.id)
- return f"/api/projects/{self.team.id}/deployment_projects/{pid}/deployments/{did}/logs/"
-
- def _capture_log_event(
- self,
- *,
- deployment_id: str,
- level: str = "info",
- step: str = "build",
- line: str = "hello",
- exit_code: int | None = None,
- timestamp: dt.datetime | None = None,
- team_id: int | None = None,
- event: str = "$log",
- ) -> None:
- properties: dict[str, object] = {
- "deployment_id": deployment_id,
- "level": level,
- "step": step,
- "$log_line": line,
- }
- if exit_code is not None:
- properties["exit_code"] = exit_code
- bulk_create_events(
- [
- {
- "uuid": str(uuidlib.uuid4()),
- "event": event,
- "team_id": team_id if team_id is not None else self.team.pk,
- "distinct_id": "build-worker",
- "timestamp": timestamp or dt.datetime.now(), # nosemgrep: test-datetime-now-without-freeze
- "properties": properties,
- }
- ]
- )
-
- # ---- tests --------------------------------------------------------
-
- def test_feature_flag_off_returns_403(self) -> None:
- self._flag_patcher.stop()
- with patch(
- "products.deployments.backend.access.posthoganalytics.feature_enabled",
- return_value=False,
- ):
- response = self.client.get(self._logs_url())
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, response.content)
- self._flag_patcher.start()
-
- def test_unknown_deployment_returns_404(self) -> None:
- response = self.client.get(self._logs_url(deployment_id=str(uuid7())))
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
-
- def test_deployment_from_other_team_is_404(self) -> None:
- # Mirrors test_action_endpoint_refuses_cross_project_deployment_id —
- # we use get_object() so cross-team access surfaces as a clean 404,
- # not a leak.
- other_team = self.organization.teams.create(name="Other Team")
- other_project = DeploymentProject.objects.create(
- team_id=other_team.id,
- name="Other",
- slug="other",
- repo_url="https://github.com/example-org/other",
- )
- other_deployment = Deployment.objects.create(
- project=other_project,
- team_id=other_team.id,
- status=Deployment.Status.READY.value,
- )
- response = self.client.get(self._logs_url(deployment_id=str(other_deployment.id)))
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
-
- def test_deployment_from_sibling_project_is_404(self) -> None:
- sibling = DeploymentProject.objects.create(
- team_id=self.team.id,
- name="Sibling",
- slug="sibling",
- repo_url="https://github.com/example-org/sibling",
- )
- sibling_deployment = Deployment.objects.create(
- project=sibling,
- team_id=self.team.id,
- status=Deployment.Status.READY.value,
- )
- # URL uses self.deployment_project, body references sibling's deployment.
- response = self.client.get(self._logs_url(deployment_id=str(sibling_deployment.id)))
- self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
-
- def test_empty_events_returns_empty_results(self) -> None:
- response = self.client.get(self._logs_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- body = response.json()
- self.assertEqual(body["results"], [])
- self.assertFalse(body["has_more"])
- self.assertEqual(body["row_limit"], LOGS_ROW_LIMIT)
-
- def test_returns_log_lines_in_ascending_order(self) -> None:
- deployment_id = str(self.deployment.id)
- base = dt.datetime(2026, 5, 14, 10, 0, 0)
- # Insert out of order so the test confirms server-side sort, not insertion order.
- self._capture_log_event(
- deployment_id=deployment_id,
- step="build",
- line="line-three",
- timestamp=base + dt.timedelta(seconds=2),
- )
- self._capture_log_event(
- deployment_id=deployment_id,
- step="install",
- line="line-one",
- timestamp=base,
- )
- self._capture_log_event(
- deployment_id=deployment_id,
- step="install",
- line="line-two",
- timestamp=base + dt.timedelta(seconds=1),
- exit_code=0,
- )
-
- response = self.client.get(self._logs_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- body = response.json()
- lines = [entry["line"] for entry in body["results"]]
- self.assertEqual(lines, ["line-one", "line-two", "line-three"])
- # exit_code projects through; non-final lines stay null.
- self.assertEqual(body["results"][0]["exit_code"], None)
- self.assertEqual(body["results"][1]["exit_code"], 0)
- self.assertEqual(body["results"][2]["exit_code"], None)
- # Each entry carries level and step from the event properties.
- self.assertEqual(body["results"][0]["level"], "info")
- self.assertEqual(body["results"][0]["step"], "install")
- self.assertFalse(body["has_more"])
-
- def test_excludes_logs_from_other_deployments_in_same_project(self) -> None:
- # The single guarantee that matters: filtering by
- # properties.deployment_id only returns this deployment's lines.
- other_deployment = Deployment.objects.create(
- project=self.deployment_project,
- team_id=self.team.id,
- status=Deployment.Status.READY.value,
- )
- self._capture_log_event(deployment_id=str(self.deployment.id), line="mine")
- self._capture_log_event(deployment_id=str(other_deployment.id), line="theirs")
-
- response = self.client.get(self._logs_url())
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- lines = [entry["line"] for entry in response.json()["results"]]
- self.assertEqual(lines, ["mine"])
-
- def test_excludes_non_log_events_with_matching_deployment_id(self) -> None:
- # A non-`$log` event (e.g. a `$deployment` event or a customer's
- # own event) tagged with the same deployment_id must not leak in.
- deployment_id = str(self.deployment.id)
- self._capture_log_event(deployment_id=deployment_id, line="real-log")
- self._capture_log_event(
- deployment_id=deployment_id,
- line="should-not-show",
- event="$deployment",
- )
-
- response = self.client.get(self._logs_url())
- lines = [entry["line"] for entry in response.json()["results"]]
- self.assertEqual(lines, ["real-log"])
-
- def test_row_limit_signals_has_more_only_when_extra_row_exists(self) -> None:
- # We fetch LIMIT + 1 rows under the hood so `has_more` can
- # distinguish "ran out at exactly the cap" from "page is full and
- # more exist beyond it". Verify both paths and confirm the
- # placeholder values are bound by `ast.Constant`, not interpolated.
- deployment_id = str(self.deployment.id)
-
- def _synthetic(rows: int) -> list[tuple[dt.datetime, str, str, str, None]]:
- return [
- (dt.datetime(2026, 5, 14, 10, 0, 0, i % 1_000_000), "info", "build", f"line-{i}", None)
- for i in range(rows)
- ]
-
- # Exactly LOGS_ROW_LIMIT rows returned (no overflow row from DB) → has_more False.
- with patch("products.deployments.backend.api.deployments.execute_hogql_query") as mock_execute:
- mock_execute.return_value = MagicMock(results=_synthetic(LOGS_ROW_LIMIT))
- response = self.client.get(self._logs_url(deployment_id=deployment_id))
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- body = response.json()
- self.assertEqual(len(body["results"]), LOGS_ROW_LIMIT)
- self.assertFalse(body["has_more"])
-
- # LOGS_ROW_LIMIT + 1 rows returned (DB hit the overflow row) →
- # has_more True; response slices off the overflow.
- with patch("products.deployments.backend.api.deployments.execute_hogql_query") as mock_execute:
- mock_execute.return_value = MagicMock(results=_synthetic(LOGS_ROW_LIMIT + 1))
- response = self.client.get(self._logs_url(deployment_id=deployment_id))
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.content)
- body = response.json()
- self.assertEqual(len(body["results"]), LOGS_ROW_LIMIT)
- self.assertTrue(body["has_more"])
-
- # Confirm parameterization on the last call.
- placeholders = mock_execute.call_args.kwargs["placeholders"]
- self.assertEqual(placeholders["deployment_id"].value, deployment_id)
- self.assertEqual(placeholders["log_event"].value, "$log")
- # SQL fetches one extra row to support honest has_more.
- self.assertEqual(placeholders["row_limit"].value, LOGS_ROW_LIMIT + 1)
- # Response still advertises the user-facing cap, not the +1 internal.
- self.assertEqual(body["row_limit"], LOGS_ROW_LIMIT)
-
- def test_hogql_failure_returns_502(self) -> None:
- with patch(
- "products.deployments.backend.api.deployments.execute_hogql_query",
- side_effect=RuntimeError("ClickHouse offline"),
- ):
- response = self.client.get(self._logs_url())
- self.assertEqual(response.status_code, status.HTTP_502_BAD_GATEWAY, response.content)
- self.assertIn("detail", response.json())
diff --git a/products/deployments/backend/test/test_detect_endpoint.py b/products/deployments/backend/test/test_detect_endpoint.py
deleted file mode 100644
index c2ef5ccdfcc1..000000000000
--- a/products/deployments/backend/test/test_detect_endpoint.py
+++ /dev/null
@@ -1,79 +0,0 @@
-"""HTTP-level tests for `POST /deployment_projects/detect/`."""
-
-from __future__ import annotations
-
-from posthog.test.base import APIBaseTest
-from unittest.mock import patch
-
-from rest_framework import status
-
-from products.deployments.backend.test._helpers import DeploymentsTeamScopedTestMixin
-
-
-class _BaseDetectTest(DeploymentsTeamScopedTestMixin, APIBaseTest):
- def setUp(self) -> None:
- super().setUp()
- self._flag_patcher = patch(
- "products.deployments.backend.access.posthoganalytics.feature_enabled",
- return_value=True,
- )
- self._flag_patcher.start()
- self.addCleanup(self._flag_patcher.stop)
-
- @property
- def _detect_url(self) -> str:
- return f"/api/projects/{self.team.id}/deployment_projects/detect/"
-
-
-class TestDetectEndpoint(_BaseDetectTest):
- def test_returns_suggested_config_for_known_framework(self) -> None:
- response = self.client.post(
- self._detect_url,
- data={
- "package_json": {"dependencies": {"vite": "^5"}, "engines": {"node": ">=20"}},
- "lockfiles": ["pnpm-lock.yaml"],
- },
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
- body = response.json()
- self.assertEqual(body["framework"], "vite")
- self.assertEqual(body["package_manager"], "pnpm")
- self.assertEqual(body["install_command"], "pnpm install --frozen-lockfile")
- self.assertEqual(body["build_command"], "pnpm build")
- self.assertEqual(body["output_dir"], "dist")
- self.assertEqual(body["node_version"], "20")
-
- def test_plain_html_repo_returns_null_framework_and_empty_build(self) -> None:
- # Real case — a static-site repo with no package.json. Endpoint must
- # not 500 and must return `framework=None` so the UI saves null into
- # `DeploymentProject.framework` rather than the literal string
- # "plain", letting the build worker do its own thing.
- response = self.client.post(
- self._detect_url,
- data={"lockfiles": []},
- format="json",
- )
-
- self.assertEqual(response.status_code, status.HTTP_200_OK, response.json())
- body = response.json()
- self.assertIsNone(body["framework"])
- self.assertEqual(body["build_command"], "")
- self.assertEqual(body["install_command"], "")
- self.assertEqual(body["output_dir"], ".")
-
-
-class TestDetectEndpointFeatureFlag(DeploymentsTeamScopedTestMixin, APIBaseTest):
- # Separate class so this one *doesn't* force the flag on.
- def test_returns_403_when_feature_flag_off(self) -> None:
- with patch(
- "products.deployments.backend.access.posthoganalytics.feature_enabled",
- return_value=False,
- ):
- response = self.client.post(
- f"/api/projects/{self.team.id}/deployment_projects/detect/",
- data={"lockfiles": []},
- format="json",
- )
- self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
diff --git a/products/deployments/backend/test/test_detection.py b/products/deployments/backend/test/test_detection.py
deleted file mode 100644
index fa6958284f9c..000000000000
--- a/products/deployments/backend/test/test_detection.py
+++ /dev/null
@@ -1,140 +0,0 @@
-"""Pure-function tests for the framework + package-manager detector."""
-
-from __future__ import annotations
-
-from typing import Any
-
-import pytest
-
-from products.deployments.backend.services.detection import PackageManager, detect_config, detect_package_manager
-
-
- "lockfiles, expected",
- [
- (["package-lock.json"], PackageManager.NPM),
- (["pnpm-lock.yaml"], PackageManager.PNPM),
- (["yarn.lock"], PackageManager.YARN),
- # Bun pre-1.2 — binary lockfile.
- (["bun.lockb"], PackageManager.BUN),
- # Bun 1.2+ — text lockfile is the new default and must not fall through to npm.
- (["bun.lock"], PackageManager.BUN),
- # Mid-upgrade repo with both Bun lockfiles still resolves to Bun.
- (["bun.lock", "bun.lockb"], PackageManager.BUN),
- # Bun wins over everything — explicit lockfile beats accidental siblings.
- (["bun.lockb", "package-lock.json", "yarn.lock"], PackageManager.BUN),
- (["bun.lock", "package-lock.json", "yarn.lock"], PackageManager.BUN),
- # pnpm beats a leftover npm lockfile from before a migration.
- (["pnpm-lock.yaml", "package-lock.json"], PackageManager.PNPM),
- # Nothing recognisable → npm as the conservative default.
- ([], PackageManager.NPM),
- (["README.md", "Dockerfile"], PackageManager.NPM),
- ],
-)
-def test_detect_package_manager(lockfiles: list[str], expected: PackageManager) -> None:
- assert detect_package_manager(lockfiles) == expected
-
-
- "deps, expected_framework, expected_build, expected_output",
- [
- ({"next": "^14"}, "nextjs", "npm run build", "out"),
- ({"vite": "^5"}, "vite", "npm run build", "dist"),
- ({"react-scripts": "5.0.0"}, "create-react-app", "npm run build", "build"),
- ({"astro": "^4"}, "astro", "npm run build", "dist"),
- ({"gatsby": "^5"}, "gatsby", "npm run build", "public"),
- ({"@11ty/eleventy": "^2"}, "eleventy", "npm run build", "_site"),
- ({"@remix-run/react": "^2", "@remix-run/node": "^2"}, "remix", "npm run build", "public"),
- ({"@sveltejs/kit": "^2"}, "sveltekit", "npm run build", "build"),
- ({"nuxt": "^3"}, "nuxt", "npm run generate", ".output/public"),
- ],
-)
-def test_detect_framework_returns_expected_hint(
- deps: dict[str, str],
- expected_framework: str,
- expected_build: str,
- expected_output: str,
-) -> None:
- result = detect_config({"dependencies": deps}, ["package-lock.json"])
- assert result.framework == expected_framework
- assert result.build_command == expected_build
- assert result.output_dir == expected_output
-
-
-def test_detect_framework_respects_dev_dependencies() -> None:
- # Most projects pin Vite in devDependencies rather than runtime deps.
- result = detect_config({"devDependencies": {"vite": "^5"}}, ["pnpm-lock.yaml"])
- assert result.framework == "vite"
- assert result.build_command == "pnpm build"
- assert result.install_command == "pnpm install --frozen-lockfile"
-
-
-def test_detect_framework_uses_first_matching_signature() -> None:
- # Remix repos commonly carry React + Vite as transitive concerns; the
- # Remix signature is checked first so it wins over Vite.
- package_json = {"dependencies": {"@remix-run/react": "^2", "@remix-run/node": "^2", "vite": "^5"}}
- result = detect_config(package_json, ["package-lock.json"])
- assert result.framework == "remix"
-
-
-def test_remix_signature_requires_all_dep_keys_present() -> None:
- # A repo carrying only `@remix-run/react` (as some downstream library's
- # transitive concern) but no Remix runtime is not a Remix project. The
- # signature must require *all* listed deps so we don't suggest a
- # wrong build command that breaks the deploy.
- package_json = {"dependencies": {"@remix-run/react": "^2", "vite": "^5"}}
- result = detect_config(package_json, ["package-lock.json"])
- assert result.framework == "vite"
-
-
-def test_no_package_json_means_null_framework_with_no_build() -> None:
- # The connect-repo flow should still complete for a static-site repo
- # that's literally just HTML — empty install/build, serve repo root,
- # framework null so the build worker doesn't pretend a framework is in play.
- result = detect_config(None, [])
- assert result.framework is None
- assert result.install_command == ""
- assert result.build_command == ""
- assert result.output_dir == "."
-
-
-def test_package_json_with_no_known_framework_leaves_build_empty() -> None:
- # Detected the package manager, but nothing we recognise. Install deps
- # but make the user fill in the build command — better than guessing
- # `npm run build` and silently producing the wrong output. Framework
- # stays null so the build worker can have its own go at detection.
- result = detect_config({"dependencies": {"left-pad": "^1.3.0"}}, ["package-lock.json"])
- assert result.framework is None
- assert result.install_command == "npm ci"
- assert result.build_command == ""
-
-
- "engines, expected",
- [
- ({"node": ">=20"}, "20"),
- ({"node": "^18.17.0"}, "18"),
- ({"node": "22"}, "22"),
- ({"node": "20.x"}, "20"),
- ({}, "20"),
- ],
-)
-def test_node_version_extracted_from_engines_with_default(
- engines: dict[str, Any],
- expected: str,
-) -> None:
- package_json = {"engines": engines, "dependencies": {"vite": "^5"}}
- result = detect_config(package_json, ["package-lock.json"])
- assert result.node_version == expected
-
-
-def test_install_command_matches_package_manager() -> None:
- for manager, lockfile, expected_install in [
- (PackageManager.NPM, "package-lock.json", "npm ci"),
- (PackageManager.PNPM, "pnpm-lock.yaml", "pnpm install --frozen-lockfile"),
- (PackageManager.YARN, "yarn.lock", "yarn install --frozen-lockfile"),
- (PackageManager.BUN, "bun.lockb", "bun install --frozen-lockfile"),
- ]:
- result = detect_config({"dependencies": {"vite": "^5"}}, [lockfile])
- assert result.package_manager == manager
- assert result.install_command == expected_install
diff --git a/products/deployments/backend/test/test_finalize_success.py b/products/deployments/backend/test/test_finalize_success.py
deleted file mode 100644
index af0af86b2f23..000000000000
--- a/products/deployments/backend/test/test_finalize_success.py
+++ /dev/null
@@ -1,172 +0,0 @@
-"""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_github_adapter.py b/products/deployments/backend/test/test_github_adapter.py
deleted file mode 100644
index 65440b5e3e02..000000000000
--- a/products/deployments/backend/test/test_github_adapter.py
+++ /dev/null
@@ -1,62 +0,0 @@
-from __future__ import annotations
-
-from typing import cast
-
-from unittest import TestCase
-from unittest.mock import MagicMock, patch
-
-from posthog.models.integration import Integration
-
-from products.deployments.backend.adapters.github import (
- DEPLOYMENTS_GITHUB_API_TIMEOUT_SECONDS,
- GitHubIntegrationAdapter,
-)
-
-
-class TestGitHubIntegrationAdapter(TestCase):
- @patch("products.deployments.backend.adapters.github.GitHubIntegration._gh_api_get")
- def test_get_json_uses_short_request_path_timeout(self, mock_gh_api_get: MagicMock) -> None:
- mock_gh_api_get.return_value = {"ok": True}
- adapter = GitHubIntegrationAdapter()
- integration_mock = MagicMock()
- integration_mock.kind = "github"
- integration = cast(Integration, integration_mock)
-
- payload = adapter._get_json(
- integration=integration,
- path="/repositories/42",
- endpoint="/repositories/{repository_id}",
- )
-
- self.assertEqual(payload, {"ok": True})
- mock_gh_api_get.assert_called_once_with(
- "/repositories/42",
- endpoint="/repositories/{repository_id}",
- timeout=DEPLOYMENTS_GITHUB_API_TIMEOUT_SECONDS,
- )
-
- def test_get_repository_by_id_resolves_current_repository_by_numeric_id(self) -> None:
- adapter = GitHubIntegrationAdapter()
- integration = cast(Integration, MagicMock())
-
- with patch.object(
- adapter,
- "_get_json",
- return_value={
- "id": 42,
- "full_name": "PostHog/renamed-repo",
- "default_branch": "master",
- "html_url": "https://github.com/PostHog/renamed-repo",
- },
- ) as get_json:
- repository = adapter.get_repository_by_id(integration=integration, github_repo_id=42)
-
- get_json.assert_called_once_with(
- integration=integration,
- path="/repositories/42",
- endpoint="/repositories/{repository_id}",
- )
- self.assertEqual(repository.id, 42)
- self.assertEqual(repository.full_name, "PostHog/renamed-repo")
- self.assertEqual(repository.default_branch, "master")
- self.assertEqual(repository.html_url, "https://github.com/PostHog/renamed-repo")
diff --git a/products/deployments/backend/test/test_internal_auth.py b/products/deployments/backend/test/test_internal_auth.py
deleted file mode 100644
index 5698f9f81691..000000000000
--- a/products/deployments/backend/test/test_internal_auth.py
+++ /dev/null
@@ -1,178 +0,0 @@
-"""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 posthog.models.scoping import reset_current_team_id, set_current_team_id
-
-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_valid_secret_runs_without_outer_team_scope(self) -> None:
- token = set_current_team_id(None)
- try:
- response = self._post_transition({"status": Status.INITIALIZING.value})
- finally:
- reset_current_team_id(token)
-
- self.assertEqual(response.status_code, drf_status.HTTP_200_OK, response.content)
- self.deployment.refresh_from_db()
- self.assertEqual(self.deployment.status, Deployment.Status.INITIALIZING.value)
-
- 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_creates_event_without_outer_team_scope(self) -> None:
- token = set_current_team_id(None)
- try:
- 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},
- )
- finally:
- reset_current_team_id(token)
-
- self.assertEqual(response.status_code, drf_status.HTTP_202_ACCEPTED, response.content)
- self.assertEqual(
- DeploymentEvent.all_teams.filter(deployment_id=self.deployment.pk, event_type="step_started").count(),
- 1,
- )
-
- 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
deleted file mode 100644
index 98e05d2692c4..000000000000
--- a/products/deployments/backend/test/test_models.py
+++ /dev/null
@@ -1,161 +0,0 @@
-"""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",
- *,
- github_repo_id: int | None = None,
- ) -> 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",
- github_repo_id=github_repo_id,
- 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_github_repo_uniqueness_per_team(self) -> None:
- self._make_project(slug="alpha", github_repo_id=42)
-
- with self.assertRaises(IntegrityError):
- with transaction.atomic():
- self._make_project(slug="beta", github_repo_id=42)
-
- def test_soft_deleted_project_releases_github_repo(self) -> None:
- original = self._make_project(slug="alpha", github_repo_id=42)
- original.deleted = True
- original.deleted_at = timezone.now()
- original.save(update_fields=["deleted", "deleted_at"])
-
- reused = self._make_project(slug="beta", github_repo_id=42)
- self.assertNotEqual(reused.pk, original.pk)
-
- def test_projects_without_github_repo_id_are_not_repo_constrained(self) -> None:
- self._make_project(slug="alpha")
- project = self._make_project(slug="beta")
-
- self.assertIsNone(project.github_repo_id)
-
- 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
deleted file mode 100644
index ab169ea86135..000000000000
--- a/products/deployments/backend/test/test_seed_command.py
+++ /dev/null
@@ -1,45 +0,0 @@
-"""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
deleted file mode 100644
index c8104b8e9569..000000000000
--- a/products/deployments/backend/test/test_services.py
+++ /dev/null
@@ -1,448 +0,0 @@
-"""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
deleted file mode 100644
index 5c5d23116106..000000000000
--- a/products/deployments/backend/test/test_state_machine.py
+++ /dev/null
@@ -1,94 +0,0 @@
-"""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/backend/test/test_temporal_adapter.py b/products/deployments/backend/test/test_temporal_adapter.py
deleted file mode 100644
index 7451d393b37c..000000000000
--- a/products/deployments/backend/test/test_temporal_adapter.py
+++ /dev/null
@@ -1,150 +0,0 @@
-from __future__ import annotations
-
-from uuid import UUID
-
-from unittest.mock import AsyncMock, MagicMock, patch
-
-from django.test import SimpleTestCase, override_settings
-
-from parameterized import parameterized
-from temporalio.exceptions import WorkflowAlreadyStartedError
-from temporalio.service import RPCError, RPCStatusCode
-
-from products.deployments.backend.adapters.temporal import (
- DEPLOYMENT_BUILD_WORKFLOW,
- TemporalWorkflowAdapter,
- WorkflowError,
-)
-from products.deployments.backend.domain.contracts import BuildInput
-from products.deployments.backend.domain.trigger import TriggerKind
-
-BUILD_INPUT = BuildInput(
- deployment_id=UUID("00000000-0000-7000-8000-000000000001"),
- project_id=UUID("00000000-0000-7000-8000-000000000002"),
- team_id=1,
- repo_url="https://github.com/example/repo",
- branch="main",
- commit_sha="abc123",
- github_access_token=None,
- build_command=None,
- output_dir="dist",
- framework=None,
- inject_posthog_snippet=False,
- cloudflare_project_name="hogdev-1-myapp",
- trigger_kind=TriggerKind.GIT,
-)
-
-
-def _make_rpc_error(message: str, status: RPCStatusCode = RPCStatusCode.UNKNOWN) -> RPCError:
- # RPCError's third positional arg (raw_proto) is bytes, not str.
- return RPCError(message, status, b"")
-
-
-@override_settings(DEPLOYMENTS_TASK_QUEUE="deployments-task-queue", TEMPORAL_WORKFLOW_MAX_ATTEMPTS="5")
-class TestTemporalWorkflowAdapter(SimpleTestCase):
- @patch("products.deployments.backend.adapters.temporal.sync_connect")
- def test_start_build_invokes_temporal_with_correct_arguments(self, mock_connect: MagicMock) -> None:
- handle = MagicMock()
- handle.first_execution_run_id = "run-abc"
- handle.result_run_id = None
- client = MagicMock()
- client.start_workflow = AsyncMock(return_value=handle)
- mock_connect.return_value = client
-
- result = TemporalWorkflowAdapter().start_build(workflow_input=BUILD_INPUT)
-
- self.assertEqual(result.workflow_id, f"deployment-{BUILD_INPUT.deployment_id}")
- self.assertEqual(result.run_id, "run-abc")
- client.start_workflow.assert_awaited_once()
- call = client.start_workflow.await_args
- self.assertEqual(call.args[0], DEPLOYMENT_BUILD_WORKFLOW)
- self.assertEqual(call.args[1], BUILD_INPUT)
- self.assertEqual(call.kwargs["id"], f"deployment-{BUILD_INPUT.deployment_id}")
- self.assertEqual(call.kwargs["task_queue"], "deployments-task-queue")
- self.assertEqual(call.kwargs["retry_policy"].maximum_attempts, 5)
-
- @patch("products.deployments.backend.adapters.temporal.sync_connect")
- def test_start_build_prefers_result_run_id_when_available(self, mock_connect: MagicMock) -> None:
- handle = MagicMock()
- handle.result_run_id = "run-result"
- handle.first_execution_run_id = "run-first"
- client = MagicMock()
- client.start_workflow = AsyncMock(return_value=handle)
- mock_connect.return_value = client
-
- result = TemporalWorkflowAdapter().start_build(workflow_input=BUILD_INPUT)
- self.assertEqual(result.run_id, "run-result")
-
- @patch("products.deployments.backend.adapters.temporal.sync_connect")
- def test_start_build_wraps_rpc_error_in_workflow_error(self, mock_connect: MagicMock) -> None:
- client = MagicMock()
- client.start_workflow = AsyncMock(side_effect=_make_rpc_error("temporal unreachable"))
- mock_connect.return_value = client
-
- with self.assertRaises(WorkflowError) as cm:
- TemporalWorkflowAdapter().start_build(workflow_input=BUILD_INPUT)
- self.assertIn("temporal unreachable", str(cm.exception))
-
- @patch("products.deployments.backend.adapters.temporal.sync_connect")
- def test_start_build_wraps_workflow_already_started_in_workflow_error(self, mock_connect: MagicMock) -> None:
- # `WorkflowAlreadyStartedError` doesn't inherit from `RPCError` —
- # exercised separately so the catch in start_build stays correct.
- client = MagicMock()
- client.start_workflow = AsyncMock(
- side_effect=WorkflowAlreadyStartedError(workflow_id="deployment-abc", workflow_type="deployment-build")
- )
- mock_connect.return_value = client
-
- with self.assertRaises(WorkflowError) as cm:
- TemporalWorkflowAdapter().start_build(workflow_input=BUILD_INPUT)
- self.assertIn("already running", str(cm.exception))
-
- def test_start_build_raises_when_task_queue_setting_missing(self) -> None:
- with override_settings(DEPLOYMENTS_TASK_QUEUE=""):
- with self.assertRaises(WorkflowError) as cm:
- TemporalWorkflowAdapter().start_build(workflow_input=BUILD_INPUT)
- self.assertIn("DEPLOYMENTS_TASK_QUEUE", str(cm.exception))
-
- @patch("products.deployments.backend.adapters.temporal.sync_connect")
- def test_signal_cancel_calls_handle_cancel(self, mock_connect: MagicMock) -> None:
- handle = MagicMock()
- handle.cancel = AsyncMock()
- client = MagicMock()
- client.get_workflow_handle = MagicMock(return_value=handle)
- mock_connect.return_value = client
-
- TemporalWorkflowAdapter().signal_cancel(workflow_id="deployment-abc")
-
- client.get_workflow_handle.assert_called_once_with("deployment-abc")
- handle.cancel.assert_awaited_once()
-
- # Drive signal_cancel's NOT_FOUND detection from the structured
- # RPCStatusCode rather than the message string — including the case
- # where the message *contains* "not found" but the status is wrong
- # (which should still raise), proving the substring-match path is
- # gone.
- @parameterized.expand(
- [
- ("not_found_with_canonical_message", RPCStatusCode.NOT_FOUND, "workflow execution not found", False),
- ("not_found_with_different_message", RPCStatusCode.NOT_FOUND, "execution does not exist", False),
- ("unknown_error", RPCStatusCode.UNKNOWN, "internal server error", True),
- ("unavailable_with_not_found_substring", RPCStatusCode.UNAVAILABLE, "task queue not found", True),
- ]
- )
- @patch("products.deployments.backend.adapters.temporal.sync_connect")
- def test_signal_cancel_status_code_drives_behaviour(
- self, _name: str, status: RPCStatusCode, message: str, should_raise: bool, mock_connect: MagicMock
- ) -> None:
- handle = MagicMock()
- handle.cancel = AsyncMock(side_effect=_make_rpc_error(message, status))
- client = MagicMock()
- client.get_workflow_handle = MagicMock(return_value=handle)
- mock_connect.return_value = client
-
- if should_raise:
- with self.assertRaises(WorkflowError) as cm:
- TemporalWorkflowAdapter().signal_cancel(workflow_id="deployment-abc")
- self.assertIn(message, str(cm.exception))
- else:
- # No exception — the workflow finished or never existed.
- TemporalWorkflowAdapter().signal_cancel(workflow_id="deployment-abc")
diff --git a/products/deployments/frontend/Deployment.tsx b/products/deployments/frontend/Deployment.tsx
deleted file mode 100644
index ecfdc984eec8..000000000000
--- a/products/deployments/frontend/Deployment.tsx
+++ /dev/null
@@ -1,114 +0,0 @@
-import { BindLogic, useActions, useValues } from 'kea'
-
-import { LemonButton } from '@posthog/lemon-ui'
-
-import { NotFound } from 'lib/components/NotFound'
-import { SceneExport } from 'scenes/sceneTypes'
-
-import { SceneContent } from '~/layout/scenes/components/SceneContent'
-import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
-import { FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'
-
-import { LogsViewer } from 'products/logs/frontend/components/LogsViewer/LogsViewer'
-
-import { CurrentDeploymentCard } from './components/CurrentDeploymentCard'
-import { openRedeployDialog, openRollbackDialog } from './components/deploymentActions'
-import { deploymentLogic, DeploymentLogicProps } from './deploymentLogic'
-import { deploymentProjectLogic } from './deploymentProjectLogic'
-
-export const scene: SceneExport<DeploymentLogicProps> = {
- component: Deployment,
- logic: deploymentLogic,
- paramsToProps: ({ params: { projectId, deploymentId } }) => ({ projectId, id: deploymentId }),
-}
-
-export function Deployment({ projectId, id }: DeploymentLogicProps): JSX.Element {
- return (
- <BindLogic logic={deploymentProjectLogic} props={{ projectId }}>
- <BindLogic logic={deploymentLogic} props={{ projectId, id }}>
- <DeploymentInner projectId={projectId} id={id} />
- </BindLogic>
- </BindLogic>
- )
-}
-
-function DeploymentInner({ projectId, id }: DeploymentLogicProps): JSX.Element {
- const { deployment, deploymentMissing, deploymentLoading } = useValues(deploymentLogic({ projectId, id }))
- const { redeployDeployment, rollbackDeployment } = useActions(deploymentProjectLogic({ projectId }))
-
- if (deploymentMissing) {
- return (
- <SceneContent>
- <NotFound object="deployment" />
- </SceneContent>
- )
- }
-
- if (deploymentLoading || !deployment) {
- return (
- <SceneContent>
- <SceneTitleSection name="Deployment" description="Loading…" resourceType={{ type: 'deployments' }} />
- </SceneContent>
- )
- }
-
- const d = deployment
-
- return (
- <SceneContent>
- <SceneTitleSection
- name={d.commit_message || d.commit_sha || d.id}
- description={d.branch ? `Branch: ${d.branch}` : undefined}
- resourceType={{ type: 'deployments' }}
- actions={
- <>
- <LemonButton type="secondary" onClick={() => openRedeployDialog(d, redeployDeployment)}>
- Redeploy
- </LemonButton>
- <LemonButton
- type="secondary"
- status="danger"
- onClick={() => openRollbackDialog(d, rollbackDeployment)}
- disabledReason={d.is_current ? 'Already current' : undefined}
- >
- Rollback
- </LemonButton>
- </>
- }
- />
- <CurrentDeploymentCard deployment={d} />
- <div className="flex flex-col gap-2">
- <h3 className="text-lg font-semibold">Logs</h3>
- <p className="text-secondary text-sm">
- Filtered to this deployment via the <code>deployment_id</code> attribute. Once ingestion stamps that
- attribute, real entries will show here.
- </p>
- <LogsViewer
- id={`deployment-${id}`}
- initialFilters={{
- filterGroup: {
- type: FilterLogicalOperator.And,
- values: [
- {
- type: FilterLogicalOperator.And,
- values: [
- {
- key: 'deployment_id',
- type: PropertyFilterType.LogAttribute,
- operator: PropertyOperator.Exact,
- value: id,
- } as any,
- ],
- },
- ],
- },
- }}
- showFullScreenButton={false}
- showSavedViewsButton={false}
- />
- </div>
- </SceneContent>
- )
-}
-
-export default Deployment
diff --git a/products/deployments/frontend/DeploymentProject.tsx b/products/deployments/frontend/DeploymentProject.tsx
deleted file mode 100644
index bb32492bf433..000000000000
--- a/products/deployments/frontend/DeploymentProject.tsx
+++ /dev/null
@@ -1,232 +0,0 @@
-import { BindLogic, useActions, useValues } from 'kea'
-
-import { IconExternal, IconGithub } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonTable, LemonTableColumns, LemonTag, PaginationManual } from '@posthog/lemon-ui'
-
-import { NotFound } from 'lib/components/NotFound'
-import { More } from 'lib/lemon-ui/LemonButton/More'
-import { createdAtColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
-import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
-import { Sorting } from 'lib/lemon-ui/LemonTable/sorting'
-import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
-import { SceneExport } from 'scenes/sceneTypes'
-import { urls } from 'scenes/urls'
-
-import { SceneContent } from '~/layout/scenes/components/SceneContent'
-import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
-
-import { CurrentDeploymentCard } from './components/CurrentDeploymentCard'
-import { openRedeployDialog, openRollbackDialog } from './components/deploymentActions'
-import { DeploymentsFilters } from './components/DeploymentsFilters'
-import { DeploymentStatusTag } from './components/DeploymentStatusTag'
-import { deploymentProjectLogic, DeploymentProjectLogicProps } from './deploymentProjectLogic'
-import { deploymentsLogic } from './deploymentsLogic'
-import { Deployment, DEPLOYMENTS_PER_PAGE, DeploymentStatus, formatDuration } from './fixtures'
-
-export const scene: SceneExport<DeploymentProjectLogicProps> = {
- component: DeploymentProject,
- logic: deploymentProjectLogic,
- paramsToProps: ({ params: { projectId } }) => ({ projectId }),
-}
-
-export function DeploymentProject({ projectId }: DeploymentProjectLogicProps): JSX.Element {
- return (
- <BindLogic logic={deploymentProjectLogic} props={{ projectId }}>
- <DeploymentProjectInner projectId={projectId} />
- </BindLogic>
- )
-}
-
-function DeploymentProjectInner({ projectId }: DeploymentProjectLogicProps): JSX.Element {
- const {
- deploymentProject,
- deployments,
- deploymentsCount,
- deploymentsLoading,
- currentDeployment,
- filters,
- shouldShowEmptyState,
- } = useValues(deploymentProjectLogic({ projectId }))
- const { setFilters, redeployDeployment, rollbackDeployment } = useActions(deploymentProjectLogic({ projectId }))
- const { deploymentProjectsLoading } = useValues(deploymentsLogic)
-
- if (!deploymentProject && !deploymentProjectsLoading) {
- return (
- <SceneContent>
- <NotFound object="deployment project" />
- </SceneContent>
- )
- }
-
- const columns: LemonTableColumns<Deployment> = [
- {
- title: 'Deployment',
- dataIndex: 'id',
- sticky: true,
- render: (_, d) => (
- <LemonTableLink
- to={urls.deployment(projectId, d.id)}
- title={
- <span className="flex items-center gap-2 min-w-0">
- <span className="truncate">{d.commit_message || d.id}</span>
- {d.is_current && <LemonTag type="success">Current</LemonTag>}
- </span>
- }
- />
- ),
- },
- {
- title: 'Status',
- dataIndex: 'status',
- render: (status) => <DeploymentStatusTag status={status as DeploymentStatus} />,
- },
- {
- title: 'Duration',
- dataIndex: 'duration_seconds',
- render: (_, d) => formatDuration(d.duration_seconds),
- },
- // Override the column's client-side sorter (`createdAtColumn` ships one)
- // with `sorter: true`, then drive ordering from `filters.order` via the
- // controlled `sorting`/`onSort` props on `LemonTable`. The list is
- // server-paginated, so per-page sorts would silently misrepresent the
- // full dataset.
- { ...createdAtColumn<Deployment>(), sorter: true } as LemonTableColumns<Deployment>[number],
- {
- title: 'Author',
- dataIndex: 'commit_author_name',
- render: (_, d) => (
- <ProfilePicture
- user={{
- first_name: d.commit_author_name ?? '',
- email: d.commit_author_email ?? '',
- }}
- size="sm"
- showName
- />
- ),
- },
- {
- width: 0,
- render: (_, d) => (
- <More
- overlay={
- <>
- <LemonButton fullWidth onClick={() => openRedeployDialog(d, redeployDeployment)}>
- Redeploy
- </LemonButton>
- <LemonButton
- fullWidth
- onClick={() => openRollbackDialog(d, rollbackDeployment)}
- disabledReason={d.is_current ? 'Already current' : undefined}
- >
- Rollback
- </LemonButton>
- {d.repo_url && d.commit_sha && (
- <LemonButton fullWidth to={`${d.repo_url}/commit/${d.commit_sha}`} targetBlank>
- View source
- </LemonButton>
- )}
- <LemonButton
- fullWidth
- to={d.deployment_url || undefined}
- targetBlank
- disabledReason={!d.deployment_url ? 'Not available' : undefined}
- >
- View live
- </LemonButton>
- </>
- }
- />
- ),
- },
- ]
-
- const pagination: PaginationManual = {
- controlled: true,
- pageSize: DEPLOYMENTS_PER_PAGE,
- currentPage: filters.page,
- entryCount: deploymentsCount,
- onForward: () => setFilters({ page: filters.page + 1 }),
- onBackward: () => setFilters({ page: Math.max(1, filters.page - 1) }),
- }
-
- // Translate the backend `ordering` string (`field` or `-field`) into the
- // LemonTable's controlled-sort shape, and back again on click. The backend
- // only supports `created_at` / `started_at` / `finished_at` today, so
- // only the Created column is marked sortable.
- const sorting: Sorting | null = filters.order
- ? {
- columnKey: filters.order.startsWith('-') ? filters.order.slice(1) : filters.order,
- order: filters.order.startsWith('-') ? -1 : 1,
- }
- : null
- const handleSort = (next: Sorting | null): void => {
- if (!next) {
- setFilters({ order: '-created_at' })
- return
- }
- setFilters({ order: `${next.order === -1 ? '-' : ''}${next.columnKey}` })
- }
-
- const repoLabel = deploymentProject?.repo_url?.replace('https://github.com/', '')
- const liveUrl = deploymentProject?.subdomain ? `https://${deploymentProject.subdomain}` : null
-
- return (
- <SceneContent>
- <SceneTitleSection
- name={deploymentProject?.name ?? 'Deployment project'}
- description={
- deploymentProject
- ? `${repoLabel ?? ''}${deploymentProject.default_branch ? ` · ${deploymentProject.default_branch}` : ''}`
- : undefined
- }
- resourceType={{ type: 'deployments' }}
- actions={
- <>
- {deploymentProject?.repo_url && (
- <LemonButton
- type="secondary"
- to={deploymentProject.repo_url}
- targetBlank
- sideIcon={<IconGithub />}
- >
- View source
- </LemonButton>
- )}
- {liveUrl && (
- <LemonButton type="primary" to={liveUrl} targetBlank sideIcon={<IconExternal />}>
- Visit
- </LemonButton>
- )}
- </>
- }
- />
-
- {currentDeployment && <CurrentDeploymentCard deployment={currentDeployment} />}
-
- {shouldShowEmptyState ? (
- <LemonBanner type="info">
- No deployments yet for this project. Push to{' '}
- <code>{deploymentProject?.default_branch ?? 'the tracked branch'}</code> to trigger one.
- </LemonBanner>
- ) : (
- <>
- <DeploymentsFilters projectId={projectId} />
- <LemonTable
- dataSource={deployments}
- columns={columns}
- loading={deploymentsLoading}
- pagination={pagination}
- rowKey="id"
- data-attr="deployments-table"
- sorting={sorting}
- onSort={handleSort}
- useURLForSorting={false}
- />
- </>
- )}
- </SceneContent>
- )
-}
-
-export default DeploymentProject
diff --git a/products/deployments/frontend/Deployments.stories.tsx b/products/deployments/frontend/Deployments.stories.tsx
deleted file mode 100644
index 255d361b2fc0..000000000000
--- a/products/deployments/frontend/Deployments.stories.tsx
+++ /dev/null
@@ -1,249 +0,0 @@
-import { Meta, StoryObj } from '@storybook/react'
-
-import { App } from 'scenes/App'
-import { urls } from 'scenes/urls'
-
-import { mswDecorator } from '~/mocks/browser'
-
-import type { DeploymentApi, DeploymentProjectApi } from './generated/api.schemas'
-
-const baseProject: DeploymentProjectApi = {
- id: 'project-1',
- name: 'Site',
- slug: 'site',
- repo_url: 'https://github.com/acme/site',
- default_branch: 'main',
- github_integration_id: null,
- github_repo_id: null,
- build_command: null,
- output_dir: 'dist',
- framework: null,
- inject_posthog_snippet: false,
- cloudflare_project_name: 'team-site',
- subdomain: 'site.pages.dev',
- cloudflare_ready_at: '2026-05-01T00:00:00Z',
- current_deployment: 'd-current',
- is_ready_to_deploy: true,
- created_at: '2026-05-01T00:00:00Z',
- updated_at: '2026-05-01T00:00:00Z',
-}
-
-const docsProject: DeploymentProjectApi = {
- ...baseProject,
- id: 'project-2',
- name: 'Docs',
- slug: 'docs',
- repo_url: 'https://github.com/acme/docs',
- cloudflare_project_name: 'team-docs',
- subdomain: 'docs.pages.dev',
- current_deployment: 'd-docs',
-}
-
-const makeDeployment = (id: string, overrides: Partial<DeploymentApi> = {}): DeploymentApi => ({
- id,
- project: 'project-1',
- status: 'ready',
- started_at: '2026-05-13T12:00:00Z',
- finished_at: '2026-05-13T12:01:30Z',
- created_at: '2026-05-13T12:00:00Z',
- commit_sha: id.slice(0, 7),
- commit_message: `commit ${id}`,
- commit_author_name: 'Alice Chen',
- commit_author_email: '[email protected]',
- repo_url: 'https://github.com/acme/site',
- branch: 'main',
- deployment_url: `https://site-${id}.pages.dev`,
- preview_image_url: '',
- triggered_by_deployment: null,
- triggered_by_user_id: null,
- trigger_kind: 'git',
- error_message: '',
- error_step: '',
- cloudflare_deployment_id: '',
- temporal_workflow_id: '',
- is_current: false,
- duration_seconds: 90,
- ...overrides,
-})
-
-const currentDeployment = makeDeployment('d-current', {
- is_current: true,
- commit_message: 'feat: deployments list page',
- duration_seconds: 84,
- deployment_url: 'https://acme-site.pages.dev',
-})
-
-const docsCurrent = makeDeployment('d-docs', {
- project: 'project-2',
- is_current: true,
- commit_message: 'docs: refresh getting started',
- duration_seconds: 36,
- deployment_url: 'https://acme-docs.pages.dev',
-})
-
-const failedDeployment = makeDeployment('d-failed', {
- status: 'error',
- commit_message: 'fix: null author handling',
- commit_author_name: 'Bob Rivera',
- commit_author_email: '[email protected]',
- duration_seconds: 42,
- deployment_url: '',
- error_step: 'build',
- error_message: 'TypeError: cannot read property of undefined in src/utils.ts',
-})
-
-const buildingDeployment = makeDeployment('d-building', {
- status: 'building',
- commit_message: 'chore: bump posthog-js to 1.220.0',
- finished_at: null,
- duration_seconds: 0,
- deployment_url: '',
-})
-
-const meta: Meta = {
- component: App,
- title: 'Scenes-App/Deployments',
- parameters: {
- layout: 'fullscreen',
- viewMode: 'story',
- mockDate: '2026-05-13',
- pageUrl: urls.deployments(),
- testOptions: { waitForLoadersToDisappear: true },
- },
- decorators: [
- mswDecorator({
- get: {
- '/api/projects/:team_id/deployment_projects/': {
- count: 2,
- next: null,
- previous: null,
- results: [baseProject, docsProject],
- },
- '/api/projects/:team_id/deployment_projects/project-1/deployments/': {
- count: 5,
- next: null,
- previous: null,
- results: [
- currentDeployment,
- failedDeployment,
- buildingDeployment,
- makeDeployment('d-3', { commit_message: 'feat: new card layout' }),
- makeDeployment('d-4', { commit_message: 'chore: tidy filters' }),
- ],
- },
- '/api/projects/:team_id/deployment_projects/project-2/deployments/': {
- count: 1,
- next: null,
- previous: null,
- results: [docsCurrent],
- },
- '/api/projects/:team_id/deployment_projects/:project_id/deployments/d-current/': currentDeployment,
- '/api/projects/:team_id/deployment_projects/:project_id/deployments/d-docs/': docsCurrent,
- },
- }),
- ],
-}
-export default meta
-
-type Story = StoryObj<{}>
-
-// Grid of project cards on /deployments
-export const ProjectGrid: Story = {}
-
-// Empty state — onboarding into the product, no projects yet
-export const NoProjects: Story = {
- decorators: [
- mswDecorator({
- get: {
- '/api/projects/:team_id/deployment_projects/': { count: 0, next: null, previous: null, results: [] },
- },
- }),
- ],
-}
-
-// Single-project grid (current behavior with one connected repo)
-export const SingleProjectGrid: Story = {
- decorators: [
- mswDecorator({
- get: {
- '/api/projects/:team_id/deployment_projects/': {
- count: 1,
- next: null,
- previous: null,
- results: [baseProject],
- },
- '/api/projects/:team_id/deployment_projects/:project_id/deployments/': {
- count: 1,
- next: null,
- previous: null,
- results: [currentDeployment],
- },
- },
- }),
- ],
-}
-
-// Per-project page: card + table at /deployments/:projectId
-export const ProjectPage: Story = {
- parameters: {
- pageUrl: urls.deploymentProject(baseProject.id),
- },
-}
-
-// Per-project page where the current deployment failed
-export const ProjectPageCurrentErrored: Story = {
- parameters: {
- pageUrl: urls.deploymentProject(baseProject.id),
- },
- decorators: [
- mswDecorator({
- get: {
- '/api/projects/:team_id/deployment_projects/': {
- count: 1,
- next: null,
- previous: null,
- results: [baseProject],
- },
- '/api/projects/:team_id/deployment_projects/:project_id/deployments/': {
- count: 2,
- next: null,
- previous: null,
- results: [failedDeployment, currentDeployment],
- },
- '/api/projects/:team_id/deployment_projects/:project_id/deployments/d-current/': currentDeployment,
- },
- }),
- ],
-}
-
-// Per-project page with zero deployments (just-provisioned project)
-export const ProjectPageNoDeployments: Story = {
- parameters: {
- pageUrl: urls.deploymentProject(baseProject.id),
- },
- decorators: [
- mswDecorator({
- get: {
- '/api/projects/:team_id/deployment_projects/': {
- count: 1,
- next: null,
- previous: null,
- results: [baseProject],
- },
- '/api/projects/:team_id/deployment_projects/:project_id/deployments/': {
- count: 0,
- next: null,
- previous: null,
- results: [],
- },
- },
- }),
- ],
-}
-
-// Deployment detail page at /deployments/:projectId/:deploymentId
-export const DeploymentDetail: Story = {
- parameters: {
- pageUrl: urls.deployment(baseProject.id, currentDeployment.id),
- },
-}
diff --git a/products/deployments/frontend/Deployments.tsx b/products/deployments/frontend/Deployments.tsx
deleted file mode 100644
index 1e6b60e3f1a8..000000000000
--- a/products/deployments/frontend/Deployments.tsx
+++ /dev/null
@@ -1,99 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { IconGithub } from '@posthog/icons'
-import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
-
-import { ProductIntroduction } from 'lib/components/ProductIntroduction/ProductIntroduction'
-import { sceneConfigurations } from 'scenes/scenes'
-import { Scene, SceneExport } from 'scenes/sceneTypes'
-
-import { SceneContent } from '~/layout/scenes/components/SceneContent'
-import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
-import { ProductKey } from '~/queries/schema/schema-general'
-
-import { AddProjectModal } from './components/AddProjectModal'
-import { DeploymentProjectCard } from './components/DeploymentProjectCard'
-import { deploymentsLogic } from './deploymentsLogic'
-
-export const scene: SceneExport = {
- component: Deployments,
- logic: deploymentsLogic,
- productKey: ProductKey.DEPLOYMENTS,
-}
-
-export function Deployments(): JSX.Element {
- const { deploymentProjects, deploymentProjectsLoading, hasNoProjects, currentDeploymentsByProject } =
- useValues(deploymentsLogic)
- const { openAddProjectModal } = useActions(deploymentsLogic)
-
- return (
- <SceneContent>
- <SceneTitleSection
- name={sceneConfigurations[Scene.Deployments]?.name ?? 'Deployments'}
- description={
- sceneConfigurations[Scene.Deployments]?.description ??
- 'Connect a GitHub repository to start deploying your site.'
- }
- resourceType={{ type: 'deployments' }}
- actions={
- hasNoProjects ? undefined : (
- <LemonButton
- type="primary"
- size="small"
- sideIcon={<IconGithub />}
- onClick={() => openAddProjectModal()}
- data-attr="add-deployment-project"
- >
- Add project
- </LemonButton>
- )
- }
- />
-
- {deploymentProjectsLoading && deploymentProjects.length === 0 ? (
- // Two-card skeleton matches the loaded grid's 2-per-row layout
- // so the empty-state CTA doesn't flash for users with projects.
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4" data-attr="deployments-grid-loading">
- <LemonSkeleton className="h-64" />
- <LemonSkeleton className="h-64" />
- </div>
- ) : hasNoProjects ? (
- <ProductIntroduction
- productName="Deployments"
- productKey={ProductKey.DEPLOYMENTS}
- thingName="deployment project"
- description="Connect a GitHub repository to deploy a static site through PostHog. Each push creates a new deployment with its own preview URL — redeploy or roll back from this page."
- titleOverride="Connect your first GitHub repository"
- isEmpty
- // Custom button (not `action`) so we can show the GitHub
- // icon — `action` would render the default "Create …"
- // button with a plus icon and discard this override.
- actionElementOverride={
- <LemonButton
- type="primary"
- sideIcon={<IconGithub />}
- onClick={() => openAddProjectModal()}
- data-attr="add-deployment-project-empty"
- >
- Connect a GitHub repository
- </LemonButton>
- }
- />
- ) : (
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
- {deploymentProjects.map((p) => (
- <DeploymentProjectCard
- key={p.id}
- project={p}
- currentDeployment={currentDeploymentsByProject[p.id] ?? null}
- />
- ))}
- </div>
- )}
-
- <AddProjectModal />
- </SceneContent>
- )
-}
-
-export default Deployments
diff --git a/products/deployments/frontend/components/AddProjectModal.tsx b/products/deployments/frontend/components/AddProjectModal.tsx
deleted file mode 100644
index e9ea2cb28b40..000000000000
--- a/products/deployments/frontend/components/AddProjectModal.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { IconGithub } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonInput, LemonModal, LemonSelect, Link } from '@posthog/lemon-ui'
-
-import { GitHubRepositoryPicker } from 'lib/integrations/GitHubIntegrationHelpers'
-import { LemonField } from 'lib/lemon-ui/LemonField'
-import { urls } from 'scenes/urls'
-
-import { deploymentsLogic } from '../deploymentsLogic'
-import { addProjectLogic } from './addProjectLogic'
-
-export function AddProjectModal(): JSX.Element {
- const { addProjectModalOpen } = useValues(deploymentsLogic)
- const { closeAddProjectModal } = useActions(deploymentsLogic)
- const { integrationId, repoName, name, slug, submitting, error, githubIntegrations, canSubmit } =
- useValues(addProjectLogic)
- const { setIntegrationId, setRepoName, setName, setSlug, submit, reset } = useActions(addProjectLogic)
-
- const handleClose = (): void => {
- closeAddProjectModal()
- reset()
- }
-
- const noIntegrations = githubIntegrations.length === 0
-
- return (
- <LemonModal
- isOpen={addProjectModalOpen}
- onClose={handleClose}
- title="Add a deployment project"
- description="Connect a GitHub repository. PostHog will create a Cloudflare-backed deployment for it and run the first build on save."
- footer={
- <>
- <LemonButton
- type="secondary"
- onClick={handleClose}
- disabledReason={submitting ? 'Saving…' : undefined}
- >
- Cancel
- </LemonButton>
- <LemonButton
- type="primary"
- onClick={() => submit()}
- loading={submitting}
- disabledReason={!canSubmit ? 'Fill in all fields' : undefined}
- data-attr="add-deployment-project-submit"
- >
- Create & deploy
- </LemonButton>
- </>
- }
- >
- <div className="flex flex-col gap-3 min-w-[28rem]">
- {noIntegrations ? (
- <LemonBanner type="warning">
- Install the GitHub integration first.{' '}
- <Link to={urls.settings('environment-integrations')}>Open integration settings →</Link>
- </LemonBanner>
- ) : (
- <>
- <LemonField.Pure label="GitHub integration">
- <LemonSelect
- value={integrationId}
- onChange={(id) => setIntegrationId(id ?? null)}
- options={githubIntegrations.map((i) => ({
- value: i.id,
- label: i.display_name || `GitHub #${i.id}`,
- icon: <IconGithub />,
- }))}
- placeholder="Select a GitHub integration"
- fullWidth
- />
- </LemonField.Pure>
-
- {integrationId && (
- <LemonField.Pure label="Repository">
- <GitHubRepositoryPicker
- integrationId={integrationId}
- value={repoName}
- onChange={setRepoName}
- />
- </LemonField.Pure>
- )}
-
- <LemonField.Pure label="Project name" info="Shown in the UI; can be edited later.">
- <LemonInput value={name} onChange={setName} placeholder="my-site" />
- </LemonField.Pure>
-
- <LemonField.Pure
- label="Slug"
- info="Used for the deployment subdomain. Only letters, numbers, underscores and hyphens."
- >
- <LemonInput value={slug} onChange={setSlug} placeholder="my-site" />
- </LemonField.Pure>
-
- {error && <LemonBanner type="error">{error}</LemonBanner>}
- </>
- )}
- </div>
- </LemonModal>
- )
-}
diff --git a/products/deployments/frontend/components/CurrentDeploymentCard.tsx b/products/deployments/frontend/components/CurrentDeploymentCard.tsx
deleted file mode 100644
index 0cc610f959f7..000000000000
--- a/products/deployments/frontend/components/CurrentDeploymentCard.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-import { IconExternal, IconGithub } from '@posthog/icons'
-import { LemonButton, LemonCard, LemonTag } from '@posthog/lemon-ui'
-
-import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'
-import { TZLabel } from 'lib/components/TZLabel'
-import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
-
-import { Deployment, formatDuration } from '../fixtures'
-import { DeploymentPreviewImage } from './DeploymentPreviewImage'
-import { DeploymentStatusTag } from './DeploymentStatusTag'
-
-export function CurrentDeploymentCard({ deployment: d }: { deployment: Deployment }): JSX.Element {
- return (
- <LemonCard hoverEffect={false} className="overflow-hidden">
- <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
- <DeploymentPreviewImage
- src={d.preview_image_url ?? ''}
- alt={`Preview of ${d.commit_message || d.id}`}
- className="aspect-video md:aspect-auto md:h-full"
- failed={d.status === 'error'}
- />
- <div className="flex flex-col gap-4">
- {d.branch && <div className="font-mono text-sm text-secondary">{d.branch}</div>}
- <div className="flex items-center gap-2 flex-wrap">
- <CopyToClipboardInline description="deployment id" explicitValue={d.id}>
- <span className="font-mono text-sm">{d.id}</span>
- </CopyToClipboardInline>
- {d.is_current && <LemonTag type="success">Current</LemonTag>}
- <DeploymentStatusTag status={d.status} />
- </div>
- <div className="text-lg font-semibold">{d.commit_message || d.commit_sha || d.id}</div>
- {d.status === 'error' && d.error_message && (
- <div className="text-sm text-danger">
- {d.error_step ? <strong>Failed at {d.error_step}: </strong> : null}
- {d.error_message}
- </div>
- )}
- <dl className="grid grid-cols-2 gap-x-4 gap-y-2 text-sm">
- <dt className="text-secondary">Duration</dt>
- <dd>{formatDuration(d.duration_seconds)}</dd>
- <dt className="text-secondary">Deployed</dt>
- <dd>
- <TZLabel time={d.created_at} />
- </dd>
- <dt className="text-secondary">Author</dt>
- <dd>
- <ProfilePicture
- user={{
- first_name: d.commit_author_name ?? '',
- email: d.commit_author_email ?? '',
- }}
- size="sm"
- showName
- />
- </dd>
- </dl>
- <div className="flex gap-2 mt-auto pt-2">
- {d.repo_url && d.commit_sha && (
- <LemonButton
- type="secondary"
- to={`${d.repo_url}/commit/${d.commit_sha}`}
- targetBlank
- sideIcon={<IconGithub />}
- >
- View source
- </LemonButton>
- )}
- {d.deployment_url && (
- <LemonButton type="primary" to={d.deployment_url} targetBlank sideIcon={<IconExternal />}>
- View live
- </LemonButton>
- )}
- </div>
- </div>
- </div>
- </LemonCard>
- )
-}
diff --git a/products/deployments/frontend/components/DeploymentPreviewImage.tsx b/products/deployments/frontend/components/DeploymentPreviewImage.tsx
deleted file mode 100644
index 0f96174a18ec..000000000000
--- a/products/deployments/frontend/components/DeploymentPreviewImage.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import { useState } from 'react'
-
-import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton/LemonSkeleton'
-
-interface DeploymentPreviewImageProps {
- src: string
- alt: string
- className?: string
- failed?: boolean
-}
-
-export function DeploymentPreviewImage({ src, alt, className, failed }: DeploymentPreviewImageProps): JSX.Element {
- const [loading, setLoading] = useState(!!src && !failed)
- const [errored, setErrored] = useState(false)
- const showImage = !failed && !!src && !errored
-
- return (
- <div className={`relative overflow-hidden bg-surface-secondary rounded ${className ?? ''}`}>
- {failed && (
- <div className="absolute inset-0 flex items-center justify-center text-danger text-sm font-semibold">
- Build failed
- </div>
- )}
- {!failed && loading && <LemonSkeleton className="absolute inset-0 w-full h-full" />}
- {!failed && !loading && !showImage && (
- <div className="absolute inset-0 flex items-center justify-center text-secondary text-sm">
- No preview
- </div>
- )}
- {showImage && (
- <img
- src={src}
- alt={alt}
- className="w-full h-full object-cover"
- onLoad={() => setLoading(false)}
- onError={() => {
- setLoading(false)
- setErrored(true)
- }}
- />
- )}
- </div>
- )
-}
diff --git a/products/deployments/frontend/components/DeploymentProjectCard.tsx b/products/deployments/frontend/components/DeploymentProjectCard.tsx
deleted file mode 100644
index 6bc11c5b00ca..000000000000
--- a/products/deployments/frontend/components/DeploymentProjectCard.tsx
+++ /dev/null
@@ -1,89 +0,0 @@
-import { router } from 'kea-router'
-
-import { IconExternal, IconGithub } from '@posthog/icons'
-import { LemonButton, LemonCard, LemonTag } from '@posthog/lemon-ui'
-
-import { TZLabel } from 'lib/components/TZLabel'
-import { urls } from 'scenes/urls'
-
-import { Deployment, DeploymentProject } from '../fixtures'
-import { DeploymentPreviewImage } from './DeploymentPreviewImage'
-import { DeploymentStatusTag } from './DeploymentStatusTag'
-
-interface DeploymentProjectCardProps {
- project: DeploymentProject
- currentDeployment: Deployment | null
-}
-
-export function DeploymentProjectCard({ project, currentDeployment }: DeploymentProjectCardProps): JSX.Element {
- const repoLabel = project.repo_url.replace('https://github.com/', '')
- const liveUrl = project.subdomain ? `https://${project.subdomain}` : null
-
- const goToProject = (): void => {
- router.actions.push(urls.deploymentProject(project.id))
- }
-
- return (
- <LemonCard
- hoverEffect
- onClick={goToProject}
- className="overflow-hidden flex flex-col p-0"
- data-attr={`deployment-project-card-${project.id}`}
- >
- <div className="flex items-start justify-between p-4 gap-2">
- <div className="flex flex-col min-w-0">
- <span className="font-semibold truncate">{project.name}</span>
- <span className="text-xs text-secondary truncate">
- {repoLabel}
- {project.default_branch ? ` · ${project.default_branch}` : ''}
- </span>
- </div>
- {currentDeployment ? (
- <DeploymentStatusTag status={currentDeployment.status} />
- ) : (
- <LemonTag type="default">Building</LemonTag>
- )}
- </div>
-
- <DeploymentPreviewImage
- src={currentDeployment?.preview_image_url ?? ''}
- alt={`Preview of ${project.name}`}
- className="aspect-video"
- failed={currentDeployment?.status === 'error'}
- />
-
- {currentDeployment ? (
- <div className="flex flex-col gap-1 p-4 border-t border-border min-w-0">
- <span className="text-sm truncate">
- {currentDeployment.commit_message || currentDeployment.commit_sha || currentDeployment.id}
- </span>
- <div className="text-xs text-secondary flex items-center gap-2 min-w-0">
- <span className="truncate">{currentDeployment.commit_author_name ?? 'Unknown author'}</span>
- <span>·</span>
- <TZLabel time={currentDeployment.created_at} />
- </div>
- </div>
- ) : (
- <div className="flex flex-col gap-1 p-4 border-t border-border">
- <span className="text-sm text-secondary">No deployments yet</span>
- </div>
- )}
-
- <div className="flex gap-2 p-4 border-t border-border" onClick={(e) => e.stopPropagation()}>
- <LemonButton type="secondary" size="small" to={project.repo_url} targetBlank sideIcon={<IconGithub />}>
- View source
- </LemonButton>
- <LemonButton
- type="primary"
- size="small"
- to={liveUrl || undefined}
- targetBlank
- sideIcon={<IconExternal />}
- disabledReason={!liveUrl ? 'Not yet available' : undefined}
- >
- Visit
- </LemonButton>
- </div>
- </LemonCard>
- )
-}
diff --git a/products/deployments/frontend/components/DeploymentStatusTag.tsx b/products/deployments/frontend/components/DeploymentStatusTag.tsx
deleted file mode 100644
index a07b471f0c5c..000000000000
--- a/products/deployments/frontend/components/DeploymentStatusTag.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'
-
-import { DeploymentStatus } from '../fixtures'
-
-const STATUS_TYPE: Record<DeploymentStatus, LemonTagType> = {
- ready: 'success',
- error: 'danger',
- building: 'primary',
- queued: 'default',
- initializing: 'default',
- cancelled: 'muted',
-}
-
-const STATUS_LABEL: Record<DeploymentStatus, string> = {
- ready: 'Ready',
- error: 'Error',
- building: 'Building',
- queued: 'Queued',
- initializing: 'Initializing',
- cancelled: 'Cancelled',
-}
-
-export function DeploymentStatusTag({ status }: { status: DeploymentStatus }): JSX.Element {
- return <LemonTag type={STATUS_TYPE[status]}>{STATUS_LABEL[status]}</LemonTag>
-}
diff --git a/products/deployments/frontend/components/DeploymentsFilters.tsx b/products/deployments/frontend/components/DeploymentsFilters.tsx
deleted file mode 100644
index 58f3af5e54a7..000000000000
--- a/products/deployments/frontend/components/DeploymentsFilters.tsx
+++ /dev/null
@@ -1,56 +0,0 @@
-import { useActions, useValues } from 'kea'
-
-import { LemonInput, LemonInputSelect } from '@posthog/lemon-ui'
-
-import { deploymentProjectLogic } from '../deploymentProjectLogic'
-import { DeploymentStatus } from '../fixtures'
-
-const STATUS_OPTIONS: { label: string; key: DeploymentStatus }[] = [
- { label: 'Ready', key: 'ready' },
- { label: 'Error', key: 'error' },
- { label: 'Building', key: 'building' },
- { label: 'Queued', key: 'queued' },
- { label: 'Initializing', key: 'initializing' },
- { label: 'Cancelled', key: 'cancelled' },
-]
-
-export function DeploymentsFilters({ projectId }: { projectId: string }): JSX.Element {
- const { filters } = useValues(deploymentProjectLogic({ projectId }))
- const { setFilters } = useActions(deploymentProjectLogic({ projectId }))
-
- return (
- <div className="flex flex-wrap items-center gap-2">
- <LemonInput
- type="search"
- placeholder="Search by commit, branch, or id"
- value={filters.search}
- onChange={(search) => setFilters({ search, page: 1 })}
- className="min-w-64"
- />
- <div className="w-64">
- <LemonInputSelect
- mode="multiple"
- placeholder="Status"
- options={STATUS_OPTIONS}
- value={filters.status}
- onChange={(status) => setFilters({ status: status as DeploymentStatus[], page: 1 })}
- allowCustomValues={false}
- autoWidth={false}
- />
- </div>
- {/* Free-text input: the backend matches `author` against
- `commit_author_email` (iexact). A dropdown built from the
- current page would silently hide authors who only appear on
- other pages and shift its option list as filters narrow the
- result set, so we accept the small typing cost for a stable,
- complete filter. */}
- <LemonInput
- type="search"
- placeholder="Filter by author email"
- value={filters.author ?? ''}
- onChange={(author) => setFilters({ author: author || null, page: 1 })}
- className="w-64"
- />
- </div>
- )
-}
diff --git a/products/deployments/frontend/components/addProjectLogic.ts b/products/deployments/frontend/components/addProjectLogic.ts
deleted file mode 100644
index 6e47ba560267..000000000000
--- a/products/deployments/frontend/components/addProjectLogic.ts
+++ /dev/null
@@ -1,160 +0,0 @@
-import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
-import { router } from 'kea-router'
-
-import { githubIntegrationLogic } from 'lib/integrations/githubIntegrationLogic'
-import { integrationsLogic } from 'lib/integrations/integrationsLogic'
-import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { teamLogic } from 'scenes/teamLogic'
-import { urls } from 'scenes/urls'
-
-import { IntegrationType } from '~/types'
-
-import { deploymentsLogic } from '../deploymentsLogic'
-import { deploymentProjectsCreate, deploymentProjectsDeploymentsCreate } from '../generated/api'
-import type { addProjectLogicType } from './addProjectLogicType'
-
-const slugify = (s: string): string =>
- s
- .toLowerCase()
- .replace(/[^a-z0-9_-]+/g, '-')
- .replace(/^-+|-+$/g, '')
- .slice(0, 80)
-
-export const addProjectLogic = kea<addProjectLogicType>([
- path(['products', 'deployments', 'frontend', 'components', 'addProjectLogic']),
- connect(() => ({
- values: [teamLogic, ['currentTeamId'], integrationsLogic, ['integrations']],
- actions: [deploymentsLogic, ['loadDeploymentProjects', 'closeAddProjectModal']],
- })),
- actions({
- setIntegrationId: (integrationId: number | null) => ({ integrationId }),
- setRepoName: (repoName: string) => ({ repoName }),
- setName: (name: string) => ({ name }),
- setSlug: (slug: string) => ({ slug }),
- setSubmitting: (submitting: boolean) => ({ submitting }),
- setError: (error: string | null) => ({ error }),
- reset: true,
- submit: true,
- }),
- reducers({
- integrationId: [
- null as number | null,
- {
- setIntegrationId: (_, { integrationId }) => integrationId,
- reset: () => null,
- },
- ],
- repoName: [
- '',
- {
- setRepoName: (_, { repoName }) => repoName,
- // Switching integrations invalidates the previously picked repo.
- setIntegrationId: () => '',
- reset: () => '',
- },
- ],
- name: [
- '',
- {
- setName: (_, { name }) => name,
- setRepoName: (_, { repoName }) => {
- // Autofill the project name from the repo's short name on first pick.
- const base = repoName.includes('/') ? (repoName.split('/').pop() ?? '') : repoName
- return base
- },
- setIntegrationId: () => '',
- reset: () => '',
- },
- ],
- slug: [
- '',
- {
- setSlug: (_, { slug }) => slug,
- setName: (_, { name }) => slugify(name),
- setRepoName: (_, { repoName }) => {
- const base = repoName.includes('/') ? (repoName.split('/').pop() ?? '') : repoName
- return slugify(base)
- },
- setIntegrationId: () => '',
- reset: () => '',
- },
- ],
- submitting: [
- false,
- {
- setSubmitting: (_, { submitting }) => submitting,
- reset: () => false,
- },
- ],
- error: [
- null as string | null,
- {
- setError: (_, { error }) => error,
- setIntegrationId: () => null,
- setRepoName: () => null,
- setName: () => null,
- setSlug: () => null,
- reset: () => null,
- },
- ],
- }),
- selectors({
- githubIntegrations: [
- (s) => [s.integrations],
- (integrations: IntegrationType[] | null): IntegrationType[] =>
- (integrations ?? []).filter((i) => i.kind === 'github'),
- ],
- canSubmit: [
- (s) => [s.integrationId, s.repoName, s.name, s.slug, s.submitting],
- (integrationId, repoName, name, slug, submitting): boolean =>
- !!integrationId && !!repoName && !!name.trim() && !!slug.trim() && !submitting,
- ],
- }),
- listeners(({ actions, values }) => ({
- submit: async () => {
- const teamId = values.currentTeamId
- const integrationId = values.integrationId
- const repoName = values.repoName
- if (!teamId || !integrationId || !repoName) {
- return
- }
- // Resolve repo id from the integration's repository list.
- const githubLogic = githubIntegrationLogic({ id: integrationId })
- const repo = githubLogic.values.repositories.find((r) => r.name === repoName)
- if (!repo) {
- actions.setError('Could not resolve repository — try reselecting it.')
- return
- }
-
- actions.setSubmitting(true)
- actions.setError(null)
- try {
- const created = await deploymentProjectsCreate(String(teamId), {
- name: values.name.trim(),
- slug: values.slug.trim(),
- github_integration_id: integrationId,
- github_repo_id: repo.id,
- })
- // Auto-deploy on create — user-confirmed behavior.
- try {
- await deploymentProjectsDeploymentsCreate(String(teamId), created.id, {})
- } catch (e: any) {
- // Project exists but initial deployment failed; surface a
- // toast and still close the modal so the user can retry
- // from the project's page.
- lemonToast.warning(
- `Project created, but initial deployment couldn't start: ${e?.message ?? 'unknown error'}`
- )
- }
- actions.loadDeploymentProjects()
- actions.closeAddProjectModal()
- actions.reset()
- router.actions.push(urls.deploymentProject(created.id))
- } catch (e: any) {
- actions.setError(e?.message ?? 'Failed to create project')
- } finally {
- actions.setSubmitting(false)
- }
- },
- })),
-])
diff --git a/products/deployments/frontend/components/deploymentActions.ts b/products/deployments/frontend/components/deploymentActions.ts
deleted file mode 100644
index 87136b6c7ad1..000000000000
--- a/products/deployments/frontend/components/deploymentActions.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { LemonDialog } from '@posthog/lemon-ui'
-
-import { Deployment } from '../fixtures'
-
-/**
- * Shared confirm dialogs for the Redeploy / Rollback flow. Used from
- * both the deployment detail scene and the per-row More menu on the
- * project scene — keeping the copy in one place avoids drift when the
- * wording or button styling needs to change.
- */
-
-export function openRedeployDialog(target: Deployment, onConfirm: (id: string) => void): void {
- LemonDialog.open({
- title: 'Redeploy?',
- description: `This will start a new deployment based on ${
- target.commit_sha || target.id
- }. It will run through the build pipeline before becoming current.`,
- primaryButton: {
- children: 'Redeploy',
- type: 'primary',
- onClick: () => onConfirm(target.id),
- },
- secondaryButton: { children: 'Cancel', type: 'secondary' },
- })
-}
-
-export function openRollbackDialog(target: Deployment, onConfirm: (id: string) => void): void {
- LemonDialog.open({
- title: 'Roll back to this deployment?',
- description: `This will immediately make ${target.commit_message || target.id} current.`,
- primaryButton: {
- children: 'Roll back',
- type: 'primary',
- status: 'danger',
- onClick: () => onConfirm(target.id),
- },
- secondaryButton: { children: 'Cancel', type: 'secondary' },
- })
-}
diff --git a/products/deployments/frontend/deploymentLogic.test.ts b/products/deployments/frontend/deploymentLogic.test.ts
deleted file mode 100644
index 9fb74cb3df52..000000000000
--- a/products/deployments/frontend/deploymentLogic.test.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-import { router } from 'kea-router'
-import { expectLogic } from 'kea-test-utils'
-
-import { Scene } from 'scenes/sceneTypes'
-
-import { useMocks } from '~/mocks/jest'
-import { initKeaTests } from '~/test/init'
-
-import { deploymentLogic } from './deploymentLogic'
-import { deploymentProjectLogic } from './deploymentProjectLogic'
-import { deploymentsLogic } from './deploymentsLogic'
-import { makeDeployment, makeProject } from './testHelpers'
-
-const project = makeProject('project-1', 'Site', { current_deployment: 'dep-current' })
-
-const deployments = [
- makeDeployment('dep-current', {
- commit_sha: '7a3f9c2',
- commit_message: 'feat: ship deployments',
- deployment_url: 'https://site-dep-current.pages.dev',
- cloudflare_deployment_id: 'cf-1',
- is_current: true,
- }),
-]
-
-describe('deploymentLogic', () => {
- let listLogic: ReturnType<typeof deploymentsLogic.build>
- let projectLogic: ReturnType<typeof deploymentProjectLogic.build>
-
- beforeEach(async () => {
- initKeaTests()
-
- useMocks({
- get: {
- '/api/projects/:team/deployment_projects/': () => [
- 200,
- { count: 1, next: null, previous: null, results: [project] },
- ],
- '/api/projects/:team/deployment_projects/:project_id/deployments/': () => [
- 200,
- { count: deployments.length, next: null, previous: null, results: deployments },
- ],
- '/api/projects/:team/deployment_projects/:project_id/deployments/:id/': (req) => {
- const found = deployments.find((d) => d.id === String(req.params.id))
- return found ? [200, found] : [404, { detail: 'Not found' }]
- },
- },
- })
-
- router.actions.push('/deployments')
-
- listLogic = deploymentsLogic()
- listLogic.mount()
- await expectLogic(listLogic).toFinishAllListeners()
-
- projectLogic = deploymentProjectLogic({ projectId: project.id })
- projectLogic.mount()
- await expectLogic(projectLogic).toFinishAllListeners()
- })
-
- afterEach(() => {
- projectLogic?.unmount()
- listLogic?.unmount()
- })
-
- it('fetches the deployment by id from the retrieve endpoint', async () => {
- const detail = deploymentLogic({ projectId: project.id, id: 'dep-current' })
- detail.mount()
- try {
- await expectLogic(detail).toFinishAllListeners()
- expect(detail.values.deployment?.id).toEqual('dep-current')
- expect(detail.values.deployment?.commit_message).toEqual('feat: ship deployments')
- expect(detail.values.deploymentMissing).toBe(false)
- } finally {
- detail.unmount()
- }
- })
-
- it('flags deploymentMissing once the retrieve returns 404', async () => {
- const detail = deploymentLogic({ projectId: project.id, id: 'does-not-exist' })
- detail.mount()
- try {
- await expectLogic(detail).toFinishAllListeners()
- expect(detail.values.deploymentLoading).toBe(false)
- expect(detail.values.deployment).toBeNull()
- expect(detail.values.deploymentMissing).toBe(true)
- } finally {
- detail.unmount()
- }
- })
-
- it('builds breadcrumbs: Deployments → project name → commit message (or fallback)', async () => {
- const found = deploymentLogic({ projectId: project.id, id: 'dep-current' })
- found.mount()
- try {
- await expectLogic(found).toFinishAllListeners()
- const crumbs = found.values.breadcrumbs
- expect(crumbs).toHaveLength(3)
- expect(crumbs[0]).toMatchObject({ key: Scene.Deployments, name: 'Deployments' })
- expect(crumbs[1]).toMatchObject({ name: project.name })
- expect(crumbs[2]).toMatchObject({ name: 'feat: ship deployments' })
- } finally {
- found.unmount()
- }
-
- const missing = deploymentLogic({ projectId: project.id, id: 'does-not-exist' })
- missing.mount()
- try {
- await expectLogic(missing).toFinishAllListeners()
- const crumbs = missing.values.breadcrumbs
- // Falls back to 'Deployment' literal when retrieve returns no row.
- expect(crumbs[2]).toMatchObject({ name: 'Deployment' })
- } finally {
- missing.unmount()
- }
- })
-
- it('deep-link: loads the deployment without waiting on a project list mount', async () => {
- // Simulate a cold start — neither the list logic nor the project logic
- // have been mounted yet. The detail logic should still fetch via its
- // own props (projectId + id come from paramsToProps in the route).
- projectLogic.unmount()
- listLogic.unmount()
- initKeaTests()
- useMocks({
- get: {
- '/api/projects/:team/deployment_projects/': () => [
- 200,
- { count: 1, next: null, previous: null, results: [project] },
- ],
- '/api/projects/:team/deployment_projects/:project_id/deployments/:id/': (req) => {
- const found = deployments.find((d) => d.id === String(req.params.id))
- return found ? [200, found] : [404, { detail: 'Not found' }]
- },
- },
- })
-
- const detail = deploymentLogic({ projectId: project.id, id: 'dep-current' })
- detail.mount()
- try {
- await expectLogic(detail).toFinishAllListeners()
- expect(detail.values.deployment?.id).toEqual('dep-current')
- expect(detail.values.deploymentMissing).toBe(false)
- } finally {
- detail.unmount()
- }
- })
-})
diff --git a/products/deployments/frontend/deploymentLogic.ts b/products/deployments/frontend/deploymentLogic.ts
deleted file mode 100644
index 4e8b8e40d27a..000000000000
--- a/products/deployments/frontend/deploymentLogic.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { afterMount, connect, kea, key, path, props, selectors } from 'kea'
-import { loaders } from 'kea-loaders'
-
-import { Scene } from 'scenes/sceneTypes'
-import { teamLogic } from 'scenes/teamLogic'
-import { urls } from 'scenes/urls'
-
-import { Breadcrumb } from '~/types'
-
-import type { deploymentLogicType } from './deploymentLogicType'
-import { deploymentProjectLogic } from './deploymentProjectLogic'
-import { Deployment } from './fixtures'
-import { deploymentProjectsDeploymentsRetrieve } from './generated/api'
-import type { DeploymentProjectApi } from './generated/api.schemas'
-
-export interface DeploymentLogicProps {
- projectId: string
- id: string
-}
-
-export const deploymentLogic = kea<deploymentLogicType>([
- props({} as DeploymentLogicProps),
- key(({ projectId, id }) => `${projectId}/${id}`),
- path((key) => ['products', 'deployments', 'frontend', 'deploymentLogic', key]),
- connect((props: DeploymentLogicProps) => ({
- values: [
- teamLogic,
- ['currentTeamId'],
- deploymentProjectLogic({ projectId: props.projectId }),
- ['deploymentProject'],
- ],
- actions: [deploymentProjectLogic({ projectId: props.projectId }), ['redeployDeployment', 'rollbackDeployment']],
- })),
- loaders(({ values, props }) => ({
- deployment: [
- null as Deployment | null,
- {
- loadDeployment: async (): Promise<Deployment | null> => {
- const teamId = values.currentTeamId
- if (!teamId) {
- return null
- }
- return deploymentProjectsDeploymentsRetrieve(String(teamId), props.projectId, props.id)
- },
- },
- ],
- })),
- selectors(({ props }) => ({
- deploymentMissing: [
- (s) => [s.deployment, s.deploymentLoading],
- (d: Deployment | null, loading: boolean): boolean => !loading && !d,
- ],
- breadcrumbs: [
- (s) => [s.deployment, s.deploymentProject],
- (d: Deployment | null, project: DeploymentProjectApi | null): Breadcrumb[] => [
- { key: Scene.Deployments, name: 'Deployments', path: urls.deployments() },
- {
- key: [Scene.DeploymentProject, props.projectId],
- name: project?.name || 'Project',
- path: urls.deploymentProject(props.projectId),
- },
- {
- key: [Scene.Deployment, props.id],
- name: d?.commit_message || d?.id || 'Deployment',
- },
- ],
- ],
- })),
- afterMount(({ actions }) => {
- actions.loadDeployment()
- }),
-])
diff --git a/products/deployments/frontend/deploymentProjectLogic.test.ts b/products/deployments/frontend/deploymentProjectLogic.test.ts
deleted file mode 100644
index 63ff6dc6d1ed..000000000000
--- a/products/deployments/frontend/deploymentProjectLogic.test.ts
+++ /dev/null
@@ -1,177 +0,0 @@
-import { router } from 'kea-router'
-import { expectLogic } from 'kea-test-utils'
-
-import { useMocks } from '~/mocks/jest'
-import { initKeaTests } from '~/test/init'
-
-import { deploymentProjectLogic } from './deploymentProjectLogic'
-import { deploymentsLogic } from './deploymentsLogic'
-import type { DeploymentApi } from './generated/api.schemas'
-import { makeDeployment, makeProject } from './testHelpers'
-
-const projectA = makeProject('project-1', 'Site')
-
-describe('deploymentProjectLogic', () => {
- let listLogic: ReturnType<typeof deploymentsLogic.build>
- let logic: ReturnType<typeof deploymentProjectLogic.build>
- let lastDeploymentsRequestUrl: string | null
-
- beforeEach(async () => {
- initKeaTests()
- lastDeploymentsRequestUrl = null
-
- useMocks({
- get: {
- '/api/projects/:team/deployment_projects/': () => [
- 200,
- { count: 1, next: null, previous: null, results: [projectA] },
- ],
- '/api/projects/:team/deployment_projects/:project_id/deployments/': (req) => {
- lastDeploymentsRequestUrl = req.url.toString()
- return [
- 200,
- {
- count: 1,
- next: null,
- previous: null,
- results: [
- makeDeployment(`${req.params.project_id}-d1`, {
- project: String(req.params.project_id),
- is_current: true,
- }),
- ],
- },
- ]
- },
- '/api/projects/:team/deployment_projects/:project_id/deployments/:id/': (req) => [
- 200,
- makeDeployment(String(req.params.id), {
- project: String(req.params.project_id),
- is_current: true,
- }),
- ],
- },
- post: {
- '/api/projects/:team/deployment_projects/:project_id/deployments/:id/redeploy/': () => [
- 201,
- makeDeployment('new-redeploy', { status: 'queued', trigger_kind: 'redeploy' }),
- ],
- '/api/projects/:team/deployment_projects/:project_id/deployments/:id/rollback/': () => [
- 201,
- makeDeployment('new-rollback', { status: 'ready', trigger_kind: 'rollback' }),
- ],
- },
- })
-
- router.actions.push(`/deployments/${projectA.id}`)
-
- listLogic = deploymentsLogic()
- listLogic.mount()
- await expectLogic(listLogic).toFinishAllListeners()
-
- logic = deploymentProjectLogic({ projectId: projectA.id })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
- })
-
- afterEach(() => {
- logic?.unmount()
- listLogic?.unmount()
- })
-
- it('loads deployments and current deployment for its project on mount', () => {
- expect(logic.values.deployments).toHaveLength(1)
- expect(logic.values.deployments[0]?.project).toEqual(projectA.id)
- expect(logic.values.currentDeployment?.is_current).toBe(true)
- })
-
- it('forwards status/author/search to the backend as query params', async () => {
- await expectLogic(logic, () => {
- logic.actions.setFilters({
- search: 'feat: add',
- status: ['ready', 'error'],
- author: '[email protected]',
- })
- }).toFinishAllListeners()
-
- expect(lastDeploymentsRequestUrl).not.toBeNull()
- const url = new URL(lastDeploymentsRequestUrl!)
- expect(url.searchParams.get('search')).toEqual('feat: add')
- expect(url.searchParams.get('status')).toEqual('ready,error')
- expect(url.searchParams.get('author')).toEqual('[email protected]')
- expect(url.searchParams.get('ordering')).toEqual('-created_at')
- expect(url.searchParams.get('limit')).toEqual('50')
- expect(url.searchParams.get('offset')).toEqual('0')
- })
-
- it('resets `page` to 1 when filters change', async () => {
- await expectLogic(logic, () => {
- logic.actions.setFilters({ page: 3 })
- }).toMatchValues({ filters: expect.objectContaining({ page: 3 }) })
-
- await expectLogic(logic, () => {
- logic.actions.setFilters({ search: 'something' })
- }).toMatchValues({ filters: expect.objectContaining({ page: 1, search: 'something' }) })
- })
-
- it('redeployDeployment calls the nested redeploy endpoint then reloads', async () => {
- const redeploySpy = jest.fn(
- () =>
- [201, makeDeployment('new-redeploy', { status: 'queued', trigger_kind: 'redeploy' })] as [
- number,
- DeploymentApi,
- ]
- )
- useMocks({
- post: {
- '/api/projects/:team/deployment_projects/:project_id/deployments/:id/redeploy/': redeploySpy,
- },
- })
-
- await expectLogic(logic, () => {
- logic.actions.redeployDeployment('project-1-d1')
- }).toFinishAllListeners()
-
- expect(redeploySpy).toHaveBeenCalled()
- const calledReq = (redeploySpy.mock.calls[0] as unknown as [{ params: Record<string, string> }])[0]
- expect(calledReq.params.project_id).toEqual(projectA.id)
- expect(calledReq.params.id).toEqual('project-1-d1')
- })
-
- it('rollbackDeployment calls the nested rollback endpoint then reloads', async () => {
- const rollbackSpy = jest.fn(
- () =>
- [201, makeDeployment('new-rollback', { status: 'ready', trigger_kind: 'rollback' })] as [
- number,
- DeploymentApi,
- ]
- )
- useMocks({
- post: {
- '/api/projects/:team/deployment_projects/:project_id/deployments/:id/rollback/': rollbackSpy,
- },
- })
-
- await expectLogic(logic, () => {
- logic.actions.rollbackDeployment('project-1-d1')
- }).toFinishAllListeners()
-
- expect(rollbackSpy).toHaveBeenCalled()
- const calledReq = (rollbackSpy.mock.calls[0] as unknown as [{ params: Record<string, string> }])[0]
- expect(calledReq.params.project_id).toEqual(projectA.id)
- expect(calledReq.params.id).toEqual('project-1-d1')
- })
-
- it('pushes filters into the project URL when set', async () => {
- await expectLogic(logic, () => {
- logic.actions.setFilters({ search: 'feat', status: ['ready', 'error'] })
- }).toFinishAllListeners()
-
- // `urls.deploymentProject(id)` returns `/deployments/<id>`; kea's
- // project router prefixes it with `/project/<teamId>`, so match
- // against the suffix rather than the full path.
- expect(router.values.location.pathname).toMatch(new RegExp(`/deployments/${projectA.id}$`))
- expect(router.values.searchParams.search).toEqual('feat')
- expect(router.values.searchParams.status).toEqual('ready,error')
- })
-})
diff --git a/products/deployments/frontend/deploymentProjectLogic.ts b/products/deployments/frontend/deploymentProjectLogic.ts
deleted file mode 100644
index 5a840d4bcc89..000000000000
--- a/products/deployments/frontend/deploymentProjectLogic.ts
+++ /dev/null
@@ -1,262 +0,0 @@
-import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
-import { loaders } from 'kea-loaders'
-import { actionToUrl, router, urlToAction } from 'kea-router'
-
-import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
-import { objectsEqual } from 'lib/utils'
-import { teamLogic } from 'scenes/teamLogic'
-import { urls } from 'scenes/urls'
-
-import type { deploymentProjectLogicType } from './deploymentProjectLogicType'
-import { deploymentsLogic } from './deploymentsLogic'
-import { DEFAULT_DEPLOYMENT_FILTERS, DEPLOYMENTS_PER_PAGE, DeploymentsFilters, DeploymentStatus } from './fixtures'
-import {
- deploymentProjectsDeploymentsList,
- deploymentProjectsDeploymentsRedeployCreate,
- deploymentProjectsDeploymentsRetrieve,
- deploymentProjectsDeploymentsRollbackCreate,
-} from './generated/api'
-import type { DeploymentApi, DeploymentProjectApi, PaginatedDeploymentListApi } from './generated/api.schemas'
-
-export interface DeploymentProjectLogicProps {
- projectId: string
-}
-
-const filtersFromParams = (params: Record<string, any>): Partial<DeploymentsFilters> => {
- const out: Partial<DeploymentsFilters> = {}
- if (typeof params.search === 'string') {
- out.search = params.search
- }
- if (typeof params.author === 'string' && params.author) {
- out.author = params.author
- }
- if (typeof params.order === 'string') {
- out.order = params.order
- }
- if (params.page !== undefined) {
- const page = parseInt(String(params.page))
- if (!isNaN(page)) {
- out.page = page
- }
- }
- if (typeof params.status === 'string') {
- out.status = params.status.split(',').filter(Boolean) as DeploymentStatus[]
- } else if (Array.isArray(params.status)) {
- out.status = params.status as DeploymentStatus[]
- }
- return out
-}
-
-const filtersToParams = (filters: DeploymentsFilters): Record<string, string | number> => {
- const params: Record<string, string | number> = {}
- if (filters.search) {
- params.search = filters.search
- }
- if (filters.author) {
- params.author = filters.author
- }
- if (filters.order !== DEFAULT_DEPLOYMENT_FILTERS.order) {
- params.order = filters.order
- }
- if (filters.page > 1) {
- params.page = filters.page
- }
- if (filters.status.length > 0) {
- params.status = filters.status.join(',')
- }
- return params
-}
-
-const buildListQueryParams = (filters: DeploymentsFilters, pageSize: number): Record<string, string | number> => {
- const offset = (filters.page - 1) * pageSize
- const params: Record<string, string | number> = {
- limit: pageSize,
- offset,
- ordering: filters.order,
- }
- if (filters.search.trim()) {
- params.search = filters.search.trim()
- }
- if (filters.author) {
- params.author = filters.author
- }
- if (filters.status.length > 0) {
- params.status = filters.status.join(',')
- }
- return params
-}
-
-export const deploymentProjectLogic = kea<deploymentProjectLogicType>([
- props({} as DeploymentProjectLogicProps),
- key((p) => p.projectId),
- path((projectId) => ['products', 'deployments', 'frontend', 'deploymentProjectLogic', projectId]),
- connect(() => ({
- values: [teamLogic, ['currentTeamId'], deploymentsLogic, ['deploymentProjects', 'deploymentProjectsLoading']],
- actions: [deploymentsLogic, ['loadDeploymentProjects']],
- })),
- actions({
- setFilters: (filters: Partial<DeploymentsFilters>) => ({ filters }),
- resetFilters: true,
- redeployDeployment: (id: string) => ({ id }),
- rollbackDeployment: (id: string) => ({ id }),
- }),
- reducers({
- filters: [
- DEFAULT_DEPLOYMENT_FILTERS,
- {
- setFilters: (state, { filters }) => ({
- ...state,
- ...filters,
- page:
- filters.page ??
- (filters.search !== undefined || filters.status !== undefined || filters.author !== undefined
- ? 1
- : state.page),
- }),
- resetFilters: () => DEFAULT_DEPLOYMENT_FILTERS,
- },
- ],
- }),
- loaders(({ values, props }) => ({
- deploymentsResponse: [
- null as PaginatedDeploymentListApi | null,
- {
- loadDeployments: async (): Promise<PaginatedDeploymentListApi | null> => {
- const teamId = values.currentTeamId
- if (!teamId) {
- return null
- }
- return deploymentProjectsDeploymentsList(
- String(teamId),
- props.projectId,
- buildListQueryParams(values.filters, DEPLOYMENTS_PER_PAGE) as any
- )
- },
- },
- ],
- // Fetched by id so the currently-serving deployment stays visible on
- // any filter / pagination state — otherwise a status filter that
- // excludes it would hide the CurrentDeploymentCard.
- currentDeployment: [
- null as DeploymentApi | null,
- {
- loadCurrentDeployment: async (): Promise<DeploymentApi | null> => {
- const teamId = values.currentTeamId
- const currentId = values.deploymentProject?.current_deployment ?? null
- if (!teamId || !currentId) {
- return null
- }
- return deploymentProjectsDeploymentsRetrieve(String(teamId), props.projectId, currentId)
- },
- },
- ],
- })),
- listeners(({ actions, values, props }) => ({
- setFilters: () => {
- actions.loadDeployments()
- },
- resetFilters: () => {
- actions.loadDeployments()
- },
- redeployDeployment: async ({ id }) => {
- const teamId = values.currentTeamId
- if (!teamId) {
- return
- }
- try {
- await deploymentProjectsDeploymentsRedeployCreate(String(teamId), props.projectId, id)
- actions.loadDeployments()
- actions.loadCurrentDeployment()
- } catch (e: any) {
- lemonToast.error(`Failed to redeploy: ${e?.message ?? 'unknown error'}`)
- }
- },
- rollbackDeployment: async ({ id }) => {
- const teamId = values.currentTeamId
- if (!teamId) {
- return
- }
- try {
- await deploymentProjectsDeploymentsRollbackCreate(String(teamId), props.projectId, id)
- actions.loadDeployments()
- actions.loadCurrentDeployment()
- } catch (e: any) {
- lemonToast.error(`Failed to roll back: ${e?.message ?? 'unknown error'}`)
- }
- },
- loadDeploymentProjectsSuccess: () => {
- // Refresh current deployment once we know which project we're bound to.
- if (values.deploymentProject?.current_deployment) {
- actions.loadCurrentDeployment()
- }
- },
- })),
- selectors(({ props }) => ({
- deploymentProject: [
- (s) => [s.deploymentProjects],
- (projects: DeploymentProjectApi[]): DeploymentProjectApi | null =>
- projects.find((p) => p.id === props.projectId) ?? null,
- ],
- deployments: [
- (s) => [s.deploymentsResponse],
- (response: PaginatedDeploymentListApi | null): DeploymentApi[] => response?.results ?? [],
- ],
- deploymentsCount: [
- (s) => [s.deploymentsResponse],
- (response: PaginatedDeploymentListApi | null): number => response?.count ?? 0,
- ],
- deploymentsLoading: [(s) => [s.deploymentsResponseLoading], (loading: boolean): boolean => loading],
- hasActiveFilters: [
- (s) => [s.filters],
- (filters: DeploymentsFilters): boolean => !!filters.search || !!filters.author || filters.status.length > 0,
- ],
- shouldShowEmptyState: [
- (s) => [s.deployments, s.deploymentsLoading, s.hasActiveFilters],
- (rows: DeploymentApi[], loading: boolean, hasFilters: boolean): boolean => {
- if (loading) {
- return false
- }
- return rows.length === 0 && !hasFilters
- },
- ],
- })),
- actionToUrl(({ values, props }) => {
- const updateUrl = (): [string, Record<string, any>, Record<string, any>, { replace: boolean }] => {
- return [
- urls.deploymentProject(props.projectId),
- filtersToParams(values.filters),
- router.values.hashParams,
- { replace: true },
- ]
- }
- return {
- setFilters: updateUrl,
- resetFilters: updateUrl,
- }
- }),
- urlToAction(({ actions, values, props }) => ({
- [urls.deploymentProject(':projectId')]: (params, searchParams) => {
- if (params.projectId !== props.projectId) {
- return
- }
- const next = filtersFromParams(searchParams)
- const merged = { ...DEFAULT_DEPLOYMENT_FILTERS, ...next }
- if (!objectsEqual(merged, values.filters)) {
- actions.setFilters(merged)
- }
- },
- })),
- afterMount(({ actions, values }) => {
- // `deploymentsLogic` mounts first via `connect()`, and its own
- // `afterMount` already triggers `loadDeploymentProjects`. Without
- // the loading guard this `afterMount` would issue a redundant
- // parallel request on cold start.
- if (values.deploymentProjects.length === 0 && !values.deploymentProjectsLoading) {
- actions.loadDeploymentProjects()
- }
- actions.loadDeployments()
- if (values.deploymentProject?.current_deployment) {
- actions.loadCurrentDeployment()
- }
- }),
-])
diff --git a/products/deployments/frontend/deploymentsLogic.test.ts b/products/deployments/frontend/deploymentsLogic.test.ts
deleted file mode 100644
index 875513bc0366..000000000000
--- a/products/deployments/frontend/deploymentsLogic.test.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { router } from 'kea-router'
-import { expectLogic } from 'kea-test-utils'
-
-import { useMocks } from '~/mocks/jest'
-import { initKeaTests } from '~/test/init'
-
-import { deploymentsLogic } from './deploymentsLogic'
-import { makeDeployment, makeProject } from './testHelpers'
-
-describe('deploymentsLogic (grid)', () => {
- let logic: ReturnType<typeof deploymentsLogic.build>
-
- const projectA = makeProject('project-1', 'Site')
- const projectB = makeProject('project-2', 'Docs')
-
- beforeEach(async () => {
- initKeaTests()
-
- useMocks({
- get: {
- '/api/projects/:team/deployment_projects/': () => [
- 200,
- { count: 2, next: null, previous: null, results: [projectA, projectB] },
- ],
- // Each fixture project has a `current_deployment` set by
- // `makeProject`, so the grid's fan-out takes the
- // retrieve-by-id path. List is the fallback for
- // never-deployed projects — mocked too so tests that null
- // out `current_deployment` still resolve.
- '/api/projects/:team/deployment_projects/:project_id/deployments/:id/': (req) => [
- 200,
- makeDeployment(String(req.params.id), {
- project: String(req.params.project_id),
- is_current: true,
- }),
- ],
- '/api/projects/:team/deployment_projects/:project_id/deployments/': (req) => [
- 200,
- {
- count: 1,
- next: null,
- previous: null,
- results: [
- makeDeployment(`${req.params.project_id}-d1`, {
- project: String(req.params.project_id),
- is_current: true,
- }),
- ],
- },
- ],
- },
- })
-
- router.actions.push('/deployments')
-
- logic = deploymentsLogic()
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
- })
-
- afterEach(() => {
- logic?.unmount()
- })
-
- it('loads the project list on mount', () => {
- expect(logic.values.deploymentProjects.map((p) => p.id)).toEqual([projectA.id, projectB.id])
- expect(logic.values.hasNoProjects).toBe(false)
- })
-
- it('fans out one current-deployment fetch per project for the grid', () => {
- expect(Object.keys(logic.values.currentDeploymentsByProject).sort()).toEqual([projectA.id, projectB.id].sort())
- expect(logic.values.currentDeploymentsByProject[projectA.id]?.id).toEqual(`${projectA.id}-d1`)
- expect(logic.values.currentDeploymentsByProject[projectB.id]?.id).toEqual(`${projectB.id}-d1`)
- })
-
- it('opens and closes the Add Project modal via reducer', async () => {
- expect(logic.values.addProjectModalOpen).toBe(false)
- await expectLogic(logic, () => {
- logic.actions.openAddProjectModal()
- }).toMatchValues({ addProjectModalOpen: true })
- await expectLogic(logic, () => {
- logic.actions.closeAddProjectModal()
- }).toMatchValues({ addProjectModalOpen: false })
- })
-
- it('reports hasNoProjects when the team has zero projects', async () => {
- useMocks({
- get: {
- '/api/projects/:team/deployment_projects/': () => [
- 200,
- { count: 0, next: null, previous: null, results: [] },
- ],
- },
- })
- await expectLogic(logic, () => {
- logic.actions.loadDeploymentProjects()
- }).toFinishAllListeners()
- expect(logic.values.hasNoProjects).toBe(true)
- })
-})
diff --git a/products/deployments/frontend/deploymentsLogic.ts b/products/deployments/frontend/deploymentsLogic.ts
deleted file mode 100644
index bebdcd90f584..000000000000
--- a/products/deployments/frontend/deploymentsLogic.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import { actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
-import { loaders } from 'kea-loaders'
-
-import { teamLogic } from 'scenes/teamLogic'
-
-import type { deploymentsLogicType } from './deploymentsLogicType'
-import { Deployment, DeploymentProject, DeploymentsFilters, DeploymentStatus } from './fixtures'
-import {
- deploymentProjectsDeploymentsList,
- deploymentProjectsDeploymentsRetrieve,
- deploymentProjectsList,
-} from './generated/api'
-import type { DeploymentApi, DeploymentProjectApi } from './generated/api.schemas'
-
-export const deploymentsLogic = kea<deploymentsLogicType>([
- path(['products', 'deployments', 'frontend', 'deploymentsLogic']),
- connect(() => ({
- values: [teamLogic, ['currentTeamId']],
- })),
- actions({
- openAddProjectModal: true,
- closeAddProjectModal: true,
- }),
- reducers({
- addProjectModalOpen: [
- false,
- {
- openAddProjectModal: () => true,
- closeAddProjectModal: () => false,
- },
- ],
- }),
- loaders(({ values }) => ({
- deploymentProjects: [
- [] as DeploymentProjectApi[],
- {
- loadDeploymentProjects: async (): Promise<DeploymentProjectApi[]> => {
- const teamId = values.currentTeamId
- if (!teamId) {
- return []
- }
- const response = await deploymentProjectsList(String(teamId), { limit: 100 })
- return response.results ?? []
- },
- },
- ],
- // Map of projectId → the deployment currently serving traffic, used
- // by the grid view. Fetched by id (when the project has a
- // `current_deployment`) so the card reflects what's live — list[0]
- // would return the most recent build, which is wrong after a rollback.
- // Falls back to the newest deployment for never-deployed projects.
- currentDeploymentsByProject: [
- {} as Record<string, DeploymentApi | null>,
- {
- loadCurrentDeploymentsByProject: async (): Promise<Record<string, DeploymentApi | null>> => {
- const teamId = values.currentTeamId
- if (!teamId) {
- return {}
- }
- const projects = values.deploymentProjects
- const entries = await Promise.all(
- projects.map(async (p): Promise<[string, DeploymentApi | null]> => {
- try {
- if (p.current_deployment) {
- return [
- p.id,
- await deploymentProjectsDeploymentsRetrieve(
- String(teamId),
- p.id,
- p.current_deployment
- ),
- ]
- }
- const list = await deploymentProjectsDeploymentsList(String(teamId), p.id, {
- limit: 1,
- } as any)
- return [p.id, list.results?.[0] ?? null]
- } catch {
- return [p.id, null]
- }
- })
- )
- return Object.fromEntries(entries)
- },
- },
- ],
- })),
- listeners(({ actions }) => ({
- loadDeploymentProjectsSuccess: () => {
- actions.loadCurrentDeploymentsByProject()
- },
- })),
- selectors({
- hasNoProjects: [
- (s) => [s.deploymentProjects, s.deploymentProjectsLoading],
- (projects: DeploymentProjectApi[], loading: boolean): boolean => !loading && projects.length === 0,
- ],
- }),
- afterMount(({ actions }) => {
- actions.loadDeploymentProjects()
- }),
-])
-
-// Re-export for callers that still import from this module.
-export type { Deployment, DeploymentProject, DeploymentsFilters, DeploymentStatus }
diff --git a/products/deployments/frontend/fixtures.ts b/products/deployments/frontend/fixtures.ts
deleted file mode 100644
index 02e9a58cb190..000000000000
--- a/products/deployments/frontend/fixtures.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * Shared types + small UI helpers for the Deployments product.
- *
- * Re-exports the canonical generated API types as the names the rest of the
- * scene uses today (`Deployment`, `DeploymentStatus`). Backend-driven filters
- * mean we no longer apply them client-side — see `deploymentProjectsDeploymentsList`
- * in `./generated/api.ts` for the wire shape.
- */
-import { DeploymentApi, DeploymentProjectApi, DeploymentStatusEnumApi } from './generated/api.schemas'
-
-export type Deployment = DeploymentApi
-export type DeploymentProject = DeploymentProjectApi
-export type DeploymentStatus = DeploymentStatusEnumApi
-export { DeploymentStatusEnumApi }
-
-export interface DeploymentsFilters {
- search: string
- status: DeploymentStatus[]
- /** Single email — backend supports one author at a time via `author=<email>`. */
- author: string | null
- order: string
- page: number
-}
-
-export const DEPLOYMENTS_PER_PAGE = 50
-
-export const DEFAULT_DEPLOYMENT_FILTERS: DeploymentsFilters = {
- search: '',
- status: [],
- author: null,
- order: '-created_at',
- page: 1,
-}
-
-export function formatDuration(seconds: number | null | undefined): string {
- if (seconds == null) {
- return '—'
- }
- if (seconds < 60) {
- return `${seconds}s`
- }
- const m = Math.floor(seconds / 60)
- const s = seconds % 60
- return s === 0 ? `${m}m` : `${m}m ${s}s`
-}
diff --git a/products/deployments/frontend/generated/api.schemas.ts b/products/deployments/frontend/generated/api.schemas.ts
deleted file mode 100644
index cda32c973a77..000000000000
--- a/products/deployments/frontend/generated/api.schemas.ts
+++ /dev/null
@@ -1,628 +0,0 @@
-/**
- * Auto-generated from the Django backend OpenAPI schema.
- * To modify these types, update the Django serializers or views, then run:
- * hogli build:openapi
- * Questions or issues? #team-devex on Slack
- *
- * 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 connected GitHub repository, resolved from the selected repository id.
- * @maxLength 1024
- */
- readonly repo_url: string
- /**
- * Branch PostHog tracks for deployment updates. Defaults to the repository default branch.
- * @maxLength 255
- */
- default_branch?: string
- /**
- * Existing PostHog GitHub integration id used for repository access.
- * @nullable
- */
- github_integration_id?: number | null
- /**
- * Stable GitHub repository identifier selected from the existing integration's repository list.
- * @nullable
- */
- github_repo_id?: 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[]
-}
-
-export interface DeploymentProjectCreateApi {
- /**
- * Human-readable project name shown in the UI.
- * @maxLength 200
- */
- name: string
- /**
- * URL-safe handle. Becomes the subdomain `{slug}.posthog-app.com`. Must be unique per team.
- * @maxLength 80
- * @pattern ^[-a-zA-Z0-9_]+$
- */
- slug: string
- /**
- * Branch PostHog tracks for deployment updates. Defaults to the repository default branch.
- * @maxLength 255
- */
- default_branch?: string
- /** Existing PostHog GitHub integration id used for repository access. */
- github_integration_id: number
- /** Stable GitHub repository identifier selected from the existing integration's repository list. */
- github_repo_id: number
- /**
- * 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
-}
-
-/**
- * * `queued` - Queued
- * `initializing` - Initializing
- * `building` - Building
- * `ready` - Ready
- * `error` - Error
- * `cancelled` - Cancelled
- */
-export type DeploymentStatusEnumApi = (typeof DeploymentStatusEnumApi)[keyof typeof DeploymentStatusEnumApi]
-
-export const DeploymentStatusEnumApi = {
- Queued: 'queued',
- Initializing: 'initializing',
- Building: 'building',
- Ready: 'ready',
- Error: 'error',
- Cancelled: 'cancelled',
-} as const
-
-/**
- * * `manual` - Manual
- * `git` - Git
- * `redeploy` - Redeploy
- * `rollback` - Rollback
- * `seed` - Seed
- */
-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
- /** 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
- * `building` - Building
- * `ready` - Ready
- * `error` - Error
- * `cancelled` - Cancelled */
- status: DeploymentStatusEnumApi
- /**
- * When the pipeline started building. Null while still queued.
- * @nullable
- */
- started_at?: string | null
- /**
- * When the pipeline finished (regardless of outcome). Null while still running.
- * @nullable
- */
- finished_at?: string | null
- /** When the deployment row was created (~ queued_at). */
- readonly created_at: string
- /**
- * Git commit SHA the deployment was built from.
- * @maxLength 64
- */
- commit_sha?: string
- /** Commit message associated with the commit SHA. */
- commit_message?: string
- /**
- * Display name of the commit author.
- * @maxLength 255
- */
- commit_author_name?: string
- /**
- * 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. Captured at deploy time.
- * @maxLength 1024
- */
- repo_url?: string
- /**
- * Source branch the deployment was built from.
- * @maxLength 255
- */
- branch?: string
- /**
- * Public URL serving the built site once ready.
- * @maxLength 1024
- */
- deployment_url?: string
- /**
- * 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 (for rollbacks and redeploys).
- * @nullable
- */
- readonly triggered_by_deployment: string | null
- /**
- * 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
- /** 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
-}
-
-export interface PaginatedDeploymentListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: DeploymentApi[]
-}
-
-/**
- * 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 {
- /** Short human-readable confirmation message. */
- detail: string
-}
-
-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[]
-}
-
-/**
- * One line of build output emitted by the build worker as a `$log` event.
- */
-export interface DeploymentLogEntryApi {
- /** When the line was emitted by the build worker. */
- timestamp: string
- /**
- * Log level: "info" | "warn" | "error". Null if the event did not carry one.
- * @nullable
- */
- level: string | null
- /**
- * Pipeline step: "clone" | "install" | "build" | "publish". Null if the event did not carry one.
- * @nullable
- */
- step: string | null
- /**
- * The log line itself (a single line of stdout or stderr).
- * @nullable
- */
- line: string | null
- /**
- * Set on the last line of a step; null on all other lines.
- * @nullable
- */
- exit_code: number | null
-}
-
-/**
- * Response shape for GET /deployments/{id}/logs/.
- */
-export interface DeploymentLogsResponseApi {
- /** Log lines for the deployment, oldest first. */
- results: DeploymentLogEntryApi[]
- /** True if the row limit was hit and older lines may exist beyond this page. */
- has_more: boolean
- /** The hard cap applied by the server. */
- row_limit: number
-}
-
-export interface DeploymentProjectWriteApi {
- /**
- * 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
- /**
- * Branch PostHog tracks for deployment updates. Defaults to the repository default branch.
- * @maxLength 255
- */
- default_branch?: string
- /**
- * Existing PostHog GitHub integration id used for repository access.
- * @nullable
- */
- github_integration_id?: number | null
- /**
- * Stable GitHub repository identifier selected from the existing integration's repository list.
- * @nullable
- */
- github_repo_id?: 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
-}
-
-export interface PatchedDeploymentProjectWriteApi {
- /**
- * 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
- /**
- * Branch PostHog tracks for deployment updates. Defaults to the repository default branch.
- * @maxLength 255
- */
- default_branch?: string
- /**
- * Existing PostHog GitHub integration id used for repository access.
- * @nullable
- */
- github_integration_id?: number | null
- /**
- * Stable GitHub repository identifier selected from the existing integration's repository list.
- * @nullable
- */
- github_repo_id?: 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
-}
-
-/**
- * Response shape for refreshing a deployment project's GitHub branch.
- */
-export interface DeploymentProjectRefreshResponseApi {
- /** Human-readable explanation of the refresh result. */
- detail: string
- /** HTTPS URL of the connected GitHub repository. */
- repo_url: string
- /** Branch checked by the refresh action. */
- default_branch: string
- /** Current GitHub HEAD SHA for default_branch. */
- commit_sha: string
-}
-
-/**
- * Inputs the `/detect/` endpoint needs to suggest a project config.
-
-Decouples detection from any one git provider — callers fetch
-`package.json` and the list of lockfiles however they like (GitHub
-raw content via the team's existing integration, a temporary clone,
-user-pasted JSON during early development) and pass them here.
- */
-export interface DetectConfigRequestApi {
- /** Parsed contents of the repo's `package.json`. Pass null or omit if the repo doesn't have one — the response is then the plain-HTML fallback. */
- package_json?: unknown
- /** Filenames of package-manager lockfiles found in the repo root (e.g. ["pnpm-lock.yaml"]). Used to pick the package manager. */
- lockfiles?: string[]
-}
-
-/**
- * * `npm` - npm
- * `pnpm` - pnpm
- * `yarn` - yarn
- * `bun` - bun
- */
-export type PackageManagerEnumApi = (typeof PackageManagerEnumApi)[keyof typeof PackageManagerEnumApi]
-
-export const PackageManagerEnumApi = {
- Npm: 'npm',
- Pnpm: 'pnpm',
- Yarn: 'yarn',
- Bun: 'bun',
-} as const
-
-/**
- * Suggested project config. Every field is overridable in the connect-repo UI.
-
-`build_command`, `output_dir`, and `framework` map directly to the
-`DeploymentProject` model fields. `package_manager`, `install_command`,
-and `node_version` are informational hints — the model doesn't store
-them today, but the UI can display them so the user knows what the
-build worker will end up running.
- */
-export interface DetectConfigResponseApi {
- /** Detected package manager from lockfile presence.
-
- * `npm` - npm
- * `pnpm` - pnpm
- * `yarn` - yarn
- * `bun` - bun */
- package_manager: PackageManagerEnumApi
- /** Suggested install command, or empty when no install is needed. */
- install_command: string
- /** Suggested build command, or empty when no known framework matched. */
- build_command: string
- /** Suggested output directory relative to repo root. */
- output_dir: string
- /** Suggested Node major version, parsed from `engines.node` or defaulted to 20. */
- node_version: string
- /**
- * Detected framework hint (e.g. `nextjs`, `vite`, `astro`) to write into `DeploymentProject.framework`. Null when no framework matched — leaving the field null lets the build worker fall back to its own auto-detection.
- * @nullable
- */
- framework: string | null
-}
-
-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.
- */
- 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
-}
diff --git a/products/deployments/frontend/generated/api.ts b/products/deployments/frontend/generated/api.ts
deleted file mode 100644
index 8d2f84c41a36..000000000000
--- a/products/deployments/frontend/generated/api.ts
+++ /dev/null
@@ -1,529 +0,0 @@
-import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
-/**
- * Auto-generated from the Django backend OpenAPI schema.
- * To modify these types, update the Django serializers or views, then run:
- * hogli build:openapi
- * Questions or issues? #team-devex on Slack
- *
- * PostHog API - generated
- * OpenAPI spec version: 1.0.0
- */
-import type {
- DeploymentActionResponseApi,
- DeploymentApi,
- DeploymentCreateInputApi,
- DeploymentLogsResponseApi,
- DeploymentProjectApi,
- DeploymentProjectCreateApi,
- DeploymentProjectRefreshResponseApi,
- DeploymentProjectWriteApi,
- DeploymentProjectsDeploymentsEventsListParams,
- DeploymentProjectsDeploymentsListParams,
- DeploymentProjectsListParams,
- DetectConfigRequestApi,
- DetectConfigResponseApi,
- PaginatedDeploymentEventListApi,
- PaginatedDeploymentListApi,
- PaginatedDeploymentProjectListApi,
- PatchedDeploymentProjectWriteApi,
-} from './api.schemas'
-
-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,
- deploymentProjectCreateApi: DeploymentProjectCreateApi,
- options?: RequestInit
-): Promise<DeploymentProjectApi> => {
- return apiMutator<DeploymentProjectApi>(getDeploymentProjectsCreateUrl(projectId), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(deploymentProjectCreateApi),
- })
-}
-
-export const getDeploymentProjectsDeploymentsListUrl = (
- projectId: string,
- deploymentProjectId: string,
- params?: DeploymentProjectsDeploymentsListParams
-) => {
- 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/?${stringifiedParams}`
- : `/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 deploymentProjectsDeploymentsList = async (
- projectId: string,
- deploymentProjectId: string,
- params?: DeploymentProjectsDeploymentsListParams,
- options?: RequestInit
-): Promise<PaginatedDeploymentListApi> => {
- 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 getDeploymentProjectsDeploymentsCancelCreateUrl = (
- projectId: string,
- deploymentProjectId: string,
- id: string
-) => {
- return `/api/projects/${projectId}/deployment_projects/${deploymentProjectId}/deployments/${id}/cancel/`
-}
-
-/**
- * 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 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<DeploymentLogsResponseApi> => {
- return apiMutator<DeploymentLogsResponseApi>(
- 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>(
- 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 getDeploymentProjectsUpdateUrl = (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 deploymentProjectsUpdate = async (
- projectId: string,
- id: string,
- deploymentProjectWriteApi: DeploymentProjectWriteApi,
- options?: RequestInit
-): Promise<DeploymentProjectApi> => {
- return apiMutator<DeploymentProjectApi>(getDeploymentProjectsUpdateUrl(projectId, id), {
- ...options,
- method: 'PUT',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(deploymentProjectWriteApi),
- })
-}
-
-export const getDeploymentProjectsPartialUpdateUrl = (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 deploymentProjectsPartialUpdate = async (
- projectId: string,
- id: string,
- patchedDeploymentProjectWriteApi?: PatchedDeploymentProjectWriteApi,
- options?: RequestInit
-): Promise<DeploymentProjectApi> => {
- return apiMutator<DeploymentProjectApi>(getDeploymentProjectsPartialUpdateUrl(projectId, id), {
- ...options,
- method: 'PATCH',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(patchedDeploymentProjectWriteApi),
- })
-}
-
-export const getDeploymentProjectsDestroyUrl = (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 deploymentProjectsDestroy = async (
- projectId: string,
- id: string,
- options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getDeploymentProjectsDestroyUrl(projectId, id), {
- ...options,
- method: 'DELETE',
- })
-}
-
-export const getDeploymentProjectsRefreshCreateUrl = (projectId: string, id: string) => {
- return `/api/projects/${projectId}/deployment_projects/${id}/refresh/`
-}
-
-/**
- * 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.
- * @summary Refresh a deployment project's GitHub branch
- */
-export const deploymentProjectsRefreshCreate = async (
- projectId: string,
- id: string,
- options?: RequestInit
-): Promise<DeploymentProjectRefreshResponseApi> => {
- return apiMutator<DeploymentProjectRefreshResponseApi>(getDeploymentProjectsRefreshCreateUrl(projectId, id), {
- ...options,
- method: 'POST',
- })
-}
-
-export const getDeploymentProjectsDetectCreateUrl = (projectId: string) => {
- return `/api/projects/${projectId}/deployment_projects/detect/`
-}
-
-/**
- * Pure inspection — no git access, no DB writes. The connect-repo UI calls this after fetching `package.json` (via the team's GitHub integration) and uses the response to prefill the form.
- * @summary Suggest project config from a repo's package.json and lockfiles
- */
-export const deploymentProjectsDetectCreate = async (
- projectId: string,
- detectConfigRequestApi?: DetectConfigRequestApi,
- options?: RequestInit
-): Promise<DetectConfigResponseApi> => {
- return apiMutator<DetectConfigResponseApi>(getDeploymentProjectsDetectCreateUrl(projectId), {
- ...options,
- method: 'POST',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(detectConfigRequestApi),
- })
-}
diff --git a/products/deployments/frontend/generated/api.zod.schemas.ts b/products/deployments/frontend/generated/api.zod.schemas.ts
deleted file mode 100644
index 15514d6bd13f..000000000000
--- a/products/deployments/frontend/generated/api.zod.schemas.ts
+++ /dev/null
@@ -1,222 +0,0 @@
-/**
- * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
- * To modify these schemas, update the Django serializers or views, then run:
- * hogli build:openapi
- * Questions or issues? #team-devex on Slack
- *
- * PostHog API - generated
- * OpenAPI spec version: 1.0.0
- */
-import { z as zod } from 'zod'
-
-export const DeploymentStatusEnumApi = zod
- .enum(['queued', 'initializing', 'building', 'ready', 'error', 'cancelled'])
- .describe(
- '\* `queued` - Queued\n\* `initializing` - Initializing\n\* `building` - Building\n\* `ready` - Ready\n\* `error` - Error\n\* `cancelled` - Cancelled'
- )
-
-export type DeploymentStatusEnumApi = zod.input<typeof DeploymentStatusEnumApi>
-export type DeploymentStatusEnumApiOutput = zod.output<typeof DeploymentStatusEnumApi>
-
-export const TriggerKindEnumApi = zod
- .enum(['git', 'redeploy', 'rollback', 'seed'])
- .describe('\* `git` - Git\n\* `redeploy` - Redeploy\n\* `rollback` - Rollback\n\* `seed` - Seed')
-
-export type TriggerKindEnumApi = zod.input<typeof TriggerKindEnumApi>
-export type TriggerKindEnumApiOutput = zod.output<typeof TriggerKindEnumApi>
-
-export const deploymentApiCommitShaMax = 64
-
-export const deploymentApiCommitAuthorNameMax = 255
-
-export const deploymentApiCommitAuthorEmailMax = 255
-
-export const deploymentApiRepoUrlMax = 1024
-
-export const deploymentApiBranchMax = 255
-
-export const deploymentApiDeploymentUrlMax = 1024
-
-export const deploymentApiPreviewImageUrlMax = 1024
-
-export const DeploymentApi = zod.object({
- id: zod.uuid().describe('Unique identifier for the deployment.'),
- status: zod
- .enum(['queued', 'initializing', 'building', 'ready', 'error', 'cancelled'])
- .describe(
- '\* `queued` - Queued\n\* `initializing` - Initializing\n\* `building` - Building\n\* `ready` - Ready\n\* `error` - Error\n\* `cancelled` - Cancelled'
- )
- .describe(
- 'Current pipeline stage for the deployment. Valid values: queued, initializing, building, ready, error, cancelled.\n\n\* `queued` - Queued\n\* `initializing` - Initializing\n\* `building` - Building\n\* `ready` - Ready\n\* `error` - Error\n\* `cancelled` - Cancelled'
- ),
- started_at: zod.iso
- .datetime({ offset: true })
- .nullish()
- .describe('Timestamp when the pipeline started building. Null while still queued.'),
- finished_at: zod.iso
- .datetime({ offset: true })
- .nullish()
- .describe('Timestamp when the pipeline finished (regardless of outcome). Null while still running.'),
- created_at: zod.iso.datetime({ offset: true }).describe('Timestamp when the deployment row was created.'),
- commit_sha: zod
- .string()
- .max(deploymentApiCommitShaMax)
- .optional()
- .describe('Git commit SHA the deployment was built from. Empty for non-git triggers.'),
- commit_message: zod.string().optional().describe('Commit message associated with the commit SHA.'),
- commit_author_name: zod
- .string()
- .max(deploymentApiCommitAuthorNameMax)
- .optional()
- .describe('Display name of the commit author.'),
- commit_author_email: zod
- .string()
- .max(deploymentApiCommitAuthorEmailMax)
- .optional()
- .describe('Email address of the commit author.'),
- repo_url: zod
- .url()
- .max(deploymentApiRepoUrlMax)
- .optional()
- .describe('HTTPS URL of the source repository this deployment came from.'),
- branch: zod
- .string()
- .max(deploymentApiBranchMax)
- .optional()
- .describe('Source branch the deployment was built from.'),
- deployment_url: zod
- .url()
- .max(deploymentApiDeploymentUrlMax)
- .optional()
- .describe('Public URL where the built site is served once the deployment is ready.'),
- preview_image_url: zod
- .url()
- .max(deploymentApiPreviewImageUrlMax)
- .optional()
- .describe('URL of a screenshot capture of the deployed site, used in the list view.'),
- triggered_by_deployment: zod
- .uuid()
- .nullable()
- .describe('The deployment this one was triggered from (e.g. for rollbacks\/redeploys).'),
- trigger_kind: zod
- .enum(['git', 'redeploy', 'rollback', 'seed'])
- .describe('\* `git` - Git\n\* `redeploy` - Redeploy\n\* `rollback` - Rollback\n\* `seed` - Seed')
- .describe(
- 'What caused this deployment to start. One of: git, redeploy, rollback, seed.\n\n\* `git` - Git\n\* `redeploy` - Redeploy\n\* `rollback` - Rollback\n\* `seed` - Seed'
- ),
- is_current: zod
- .boolean()
- .describe("Whether this deployment is the team's currently-serving production deployment."),
- duration_seconds: zod
- .number()
- .describe('Build duration in seconds (finished_at - started_at). 0 while still running.'),
-})
-
-export type DeploymentApi = zod.input<typeof DeploymentApi>
-export type DeploymentApiOutput = zod.output<typeof DeploymentApi>
-
-export const paginatedDeploymentListApiResultsItemCommitShaMax = 64
-
-export const paginatedDeploymentListApiResultsItemCommitAuthorNameMax = 255
-
-export const paginatedDeploymentListApiResultsItemCommitAuthorEmailMax = 255
-
-export const paginatedDeploymentListApiResultsItemRepoUrlMax = 1024
-
-export const paginatedDeploymentListApiResultsItemBranchMax = 255
-
-export const paginatedDeploymentListApiResultsItemDeploymentUrlMax = 1024
-
-export const paginatedDeploymentListApiResultsItemPreviewImageUrlMax = 1024
-
-export const PaginatedDeploymentListApi = zod.object({
- count: zod.number(),
- next: zod.url().nullish(),
- previous: zod.url().nullish(),
- results: zod.array(
- zod.object({
- id: zod.uuid().describe('Unique identifier for the deployment.'),
- status: zod
- .enum(['queued', 'initializing', 'building', 'ready', 'error', 'cancelled'])
- .describe(
- '\* `queued` - Queued\n\* `initializing` - Initializing\n\* `building` - Building\n\* `ready` - Ready\n\* `error` - Error\n\* `cancelled` - Cancelled'
- )
- .describe(
- 'Current pipeline stage for the deployment. Valid values: queued, initializing, building, ready, error, cancelled.\n\n\* `queued` - Queued\n\* `initializing` - Initializing\n\* `building` - Building\n\* `ready` - Ready\n\* `error` - Error\n\* `cancelled` - Cancelled'
- ),
- started_at: zod.iso
- .datetime({ offset: true })
- .nullish()
- .describe('Timestamp when the pipeline started building. Null while still queued.'),
- finished_at: zod.iso
- .datetime({ offset: true })
- .nullish()
- .describe('Timestamp when the pipeline finished (regardless of outcome). Null while still running.'),
- created_at: zod.iso.datetime({ offset: true }).describe('Timestamp when the deployment row was created.'),
- commit_sha: zod
- .string()
- .max(paginatedDeploymentListApiResultsItemCommitShaMax)
- .optional()
- .describe('Git commit SHA the deployment was built from. Empty for non-git triggers.'),
- commit_message: zod.string().optional().describe('Commit message associated with the commit SHA.'),
- commit_author_name: zod
- .string()
- .max(paginatedDeploymentListApiResultsItemCommitAuthorNameMax)
- .optional()
- .describe('Display name of the commit author.'),
- commit_author_email: zod
- .string()
- .max(paginatedDeploymentListApiResultsItemCommitAuthorEmailMax)
- .optional()
- .describe('Email address of the commit author.'),
- repo_url: zod
- .url()
- .max(paginatedDeploymentListApiResultsItemRepoUrlMax)
- .optional()
- .describe('HTTPS URL of the source repository this deployment came from.'),
- branch: zod
- .string()
- .max(paginatedDeploymentListApiResultsItemBranchMax)
- .optional()
- .describe('Source branch the deployment was built from.'),
- deployment_url: zod
- .url()
- .max(paginatedDeploymentListApiResultsItemDeploymentUrlMax)
- .optional()
- .describe('Public URL where the built site is served once the deployment is ready.'),
- preview_image_url: zod
- .url()
- .max(paginatedDeploymentListApiResultsItemPreviewImageUrlMax)
- .optional()
- .describe('URL of a screenshot capture of the deployed site, used in the list view.'),
- triggered_by_deployment: zod
- .uuid()
- .nullable()
- .describe('The deployment this one was triggered from (e.g. for rollbacks\/redeploys).'),
- trigger_kind: zod
- .enum(['git', 'redeploy', 'rollback', 'seed'])
- .describe('\* `git` - Git\n\* `redeploy` - Redeploy\n\* `rollback` - Rollback\n\* `seed` - Seed')
- .describe(
- 'What caused this deployment to start. One of: git, redeploy, rollback, seed.\n\n\* `git` - Git\n\* `redeploy` - Redeploy\n\* `rollback` - Rollback\n\* `seed` - Seed'
- ),
- is_current: zod
- .boolean()
- .describe("Whether this deployment is the team's currently-serving production deployment."),
- duration_seconds: zod
- .number()
- .describe('Build duration in seconds (finished_at - started_at). 0 while still running.'),
- })
- ),
-})
-
-export type PaginatedDeploymentListApi = zod.input<typeof PaginatedDeploymentListApi>
-export type PaginatedDeploymentListApiOutput = zod.output<typeof PaginatedDeploymentListApi>
-
-export const DeploymentActionResponseApi = zod
- .object({
- detail: zod.string().describe('Human-readable explanation of the stub response.'),
- })
- .describe('Response shape for the redeploy\/rollback\/refresh-preview stubs.')
-
-export type DeploymentActionResponseApi = zod.input<typeof DeploymentActionResponseApi>
-export type DeploymentActionResponseApiOutput = zod.output<typeof DeploymentActionResponseApi>
diff --git a/products/deployments/frontend/generated/api.zod.ts b/products/deployments/frontend/generated/api.zod.ts
deleted file mode 100644
index 719ec1a68d84..000000000000
--- a/products/deployments/frontend/generated/api.zod.ts
+++ /dev/null
@@ -1,273 +0,0 @@
-/**
- * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
- * To modify these schemas, update the Django serializers or views, then run:
- * hogli build:openapi
- * Questions or issues? #team-devex on Slack
- *
- * 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 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. Becomes the subdomain `{slug}.posthog-app.com`. Must be unique per team.'),
- default_branch: zod
- .string()
- .max(deploymentProjectsCreateBodyDefaultBranchMax)
- .optional()
- .describe('Branch PostHog tracks for deployment updates. Defaults to the repository default branch.'),
- github_integration_id: zod.number().describe('Existing PostHog GitHub integration id used for repository access.'),
- github_repo_id: zod
- .number()
- .describe("Stable GitHub repository identifier selected from the existing integration's repository list."),
- 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 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.'
- ),
- default_branch: zod
- .string()
- .max(deploymentProjectsUpdateBodyDefaultBranchMax)
- .optional()
- .describe('Branch PostHog tracks for deployment updates. Defaults to the repository default branch.'),
- github_integration_id: zod
- .number()
- .nullish()
- .describe('Existing PostHog GitHub integration id used for repository access.'),
- github_repo_id: zod
- .number()
- .nullish()
- .describe("Stable GitHub repository identifier selected from the existing integration's repository list."),
- 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 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.'
- ),
- default_branch: zod
- .string()
- .max(deploymentProjectsPartialUpdateBodyDefaultBranchMax)
- .optional()
- .describe('Branch PostHog tracks for deployment updates. Defaults to the repository default branch.'),
- github_integration_id: zod
- .number()
- .nullish()
- .describe('Existing PostHog GitHub integration id used for repository access.'),
- github_repo_id: zod
- .number()
- .nullish()
- .describe("Stable GitHub repository identifier selected from the existing integration's repository list."),
- 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.'
- ),
-})
-
-/**
- * Pure inspection — no git access, no DB writes. The connect-repo UI calls this after fetching `package.json` (via the team's GitHub integration) and uses the response to prefill the form.
- * @summary Suggest project config from a repo's package.json and lockfiles
- */
-export const deploymentProjectsDetectCreateBodyLockfilesItemMax = 64
-
-export const DeploymentProjectsDetectCreateBody = /* @__PURE__ */ zod
- .object({
- package_json: zod
- .unknown()
- .optional()
- .describe(
- "Parsed contents of the repo's `package.json`. Pass null or omit if the repo doesn't have one — the response is then the plain-HTML fallback."
- ),
- lockfiles: zod
- .array(zod.string().max(deploymentProjectsDetectCreateBodyLockfilesItemMax))
- .optional()
- .describe(
- 'Filenames of package-manager lockfiles found in the repo root (e.g. [\"pnpm-lock.yaml\"]). Used to pick the package manager.'
- ),
- })
- .describe(
- "Inputs the `\/detect\/` endpoint needs to suggest a project config.\n\nDecouples detection from any one git provider — callers fetch\n`package.json` and the list of lockfiles however they like (GitHub\nraw content via the team's existing integration, a temporary clone,\nuser-pasted JSON during early development) and pass them here."
- )
diff --git a/products/deployments/frontend/testHelpers.ts b/products/deployments/frontend/testHelpers.ts
deleted file mode 100644
index cfe6266ceeef..000000000000
--- a/products/deployments/frontend/testHelpers.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * Shared fixture factories for deployments tests + stories. Keeps the
- * `DeploymentProjectApi` / `DeploymentApi` shapes in one place so each
- * caller doesn't have to keep its own copy in sync with the generated
- * schemas.
- */
-import type { DeploymentApi, DeploymentProjectApi } from './generated/api.schemas'
-
-export const makeProject = (
- id: string,
- name: string,
- overrides: Partial<DeploymentProjectApi> = {}
-): DeploymentProjectApi => ({
- id,
- name,
- slug: name.toLowerCase(),
- repo_url: `https://github.com/acme/${name.toLowerCase()}`,
- default_branch: 'main',
- github_integration_id: null,
- github_repo_id: null,
- build_command: null,
- output_dir: 'dist',
- framework: null,
- inject_posthog_snippet: false,
- cloudflare_project_name: `team-${name.toLowerCase()}`,
- subdomain: `${name.toLowerCase()}.pages.dev`,
- cloudflare_ready_at: '2026-05-01T00:00:00Z',
- current_deployment: `${id}-d1`,
- is_ready_to_deploy: true,
- created_at: '2026-05-01T00:00:00Z',
- updated_at: '2026-05-01T00:00:00Z',
- ...overrides,
-})
-
-export const makeDeployment = (id: string, overrides: Partial<DeploymentApi> = {}): DeploymentApi => ({
- id,
- project: 'project-1',
- status: 'ready',
- started_at: '2026-05-13T12:00:00Z',
- finished_at: '2026-05-13T12:01:30Z',
- created_at: '2026-05-13T12:00:00Z',
- commit_sha: id.slice(0, 7),
- commit_message: `commit ${id}`,
- commit_author_name: 'Alice',
- commit_author_email: '[email protected]',
- repo_url: 'https://github.com/acme/site',
- branch: 'main',
- deployment_url: `https://site-${id}.pages.dev`,
- preview_image_url: '',
- triggered_by_deployment: null,
- triggered_by_user_id: null,
- trigger_kind: 'git',
- error_message: '',
- error_step: '',
- cloudflare_deployment_id: '',
- temporal_workflow_id: '',
- is_current: false,
- duration_seconds: 90,
- ...overrides,
-})
diff --git a/products/deployments/manifest.tsx b/products/deployments/manifest.tsx
deleted file mode 100644
index 7bf41893e80d..000000000000
--- a/products/deployments/manifest.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-import { FEATURE_FLAGS } from 'lib/constants'
-import { urls } from 'scenes/urls'
-
-import { FileSystemIconType, ProductItemCategory, ProductKey } from '~/queries/schema/schema-general'
-
-import { FileSystemIconColor, ProductManifest } from '../../frontend/src/types'
-
-export const manifest: ProductManifest = {
- name: 'Deployments',
- scenes: {
- Deployments: {
- import: () => import('./frontend/Deployments'),
- projectBased: true,
- name: 'Deployments',
- iconType: 'deployments',
- description: 'Connect a GitHub repository to start deploying your site.',
- },
- DeploymentProject: {
- import: () => import('./frontend/DeploymentProject'),
- projectBased: true,
- name: 'Deployment project',
- },
- Deployment: {
- import: () => import('./frontend/Deployment'),
- projectBased: true,
- name: 'Deployment',
- },
- },
- routes: {
- '/deployments': ['Deployments', 'deployments'],
- '/deployments/:projectId': ['DeploymentProject', 'deploymentProject'],
- '/deployments/:projectId/:deploymentId': ['Deployment', 'deployment'],
- },
- urls: {
- deployments: (): string => '/deployments',
- deploymentProject: (projectId: string): string => `/deployments/${projectId}`,
- deployment: (projectId: string, deploymentId: string): string => `/deployments/${projectId}/${deploymentId}`,
- },
- fileSystemTypes: {
- deployments: {
- name: 'Deployment',
- iconType: 'deployments',
- iconColor: ['var(--color-product-deployments-light)'] as FileSystemIconColor,
- href: () => urls.deployments(),
- filterKey: 'deployments',
- },
- },
- treeItemsNew: [],
- treeItemsProducts: [
- {
- path: 'Deployments',
- intents: [ProductKey.DEPLOYMENTS],
- category: ProductItemCategory.TOOLS,
- href: urls.deployments(),
- type: 'deployments',
- iconType: 'deployments' as FileSystemIconType,
- iconColor: [
- 'var(--color-product-deployments-light)',
- 'var(--color-product-deployments-dark)',
- ] as FileSystemIconColor,
- sceneKey: 'Deployments',
- sceneKeys: ['Deployments', 'DeploymentProject', 'Deployment'],
- flag: FEATURE_FLAGS.DEPLOYMENTS,
- tags: ['alpha'],
- },
- ],
-}
diff --git a/products/deployments/package.json b/products/deployments/package.json
deleted file mode 100644
index 8caa79e3efb9..000000000000
--- a/products/deployments/package.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "name": "@posthog/products-deployments",
- "scripts": {
- "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/test -v --tb=short"
- },
- "dependencies": {
- "kea": "catalog:",
- "kea-loaders": "catalog:",
- "kea-router": "catalog:",
- "posthog-js": "catalog:"
- },
- "devDependencies": {
- "@storybook/react": "catalog:",
- "kea-test-utils": "catalog:"
- },
- "peerDependencies": {
- "@posthog/icons": "*",
- "@types/react": "*",
- "react": "*"
- }
-}
diff --git a/products/deployments/product.yaml b/products/deployments/product.yaml
deleted file mode 100644
index e919222d1535..000000000000
--- a/products/deployments/product.yaml
+++ /dev/null
@@ -1,6 +0,0 @@
-name: Deployments
-owners:
- - '@richardsolomou'
- - '@matheus-vb'
- - '@rubychilds'
- - '@dustinbyrne'
diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yaml
index 7f6c27b2005c..572b5f7a5d36 100644
--- a/products/logs/mcp/tools.yaml
+++ b/products/logs/mcp/tools.yaml
@@ -15,9 +15,6 @@ 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 1977b8b47890..b22efe7197f2 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13141,430 +13141,6 @@ 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
- * `building` - Building
- * `ready` - Ready
- * `error` - Error
- * `cancelled` - Cancelled
- */
- export type DeploymentStatusEnum = typeof DeploymentStatusEnum[keyof typeof DeploymentStatusEnum];
-
-
- export const DeploymentStatusEnum = {
- Queued: 'queued',
- Initializing: 'initializing',
- Building: 'building',
- Ready: 'ready',
- Error: 'error',
- Cancelled: 'cancelled',
- } as const;
-
- /**
- * * `manual` - Manual
- * `git` - Git
- * `redeploy` - Redeploy
- * `rollback` - Rollback
- * `seed` - Seed
- */
- export type TriggerKindEnum = typeof TriggerKindEnum[keyof typeof TriggerKindEnum];
-
-
- export const TriggerKindEnum = {
- Manual: 'manual',
- Git: 'git',
- Redeploy: 'redeploy',
- Rollback: 'rollback',
- Seed: 'seed',
- } as const;
-
- export interface Deployment {
- /** Unique identifier for the deployment. */
- readonly id: string;
- /** 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
- * `building` - Building
- * `ready` - Ready
- * `error` - Error
- * `cancelled` - Cancelled */
- status: DeploymentStatusEnum;
- /**
- * When the pipeline started building. Null while still queued.
- * @nullable
- */
- started_at?: string | null;
- /**
- * When the pipeline finished (regardless of outcome). Null while still running.
- * @nullable
- */
- finished_at?: string | null;
- /** When the deployment row was created (~ queued_at). */
- readonly created_at: string;
- /**
- * Git commit SHA the deployment was built from.
- * @maxLength 64
- */
- commit_sha?: string;
- /** Commit message associated with the commit SHA. */
- commit_message?: string;
- /**
- * Display name of the commit author.
- * @maxLength 255
- */
- commit_author_name?: string;
- /**
- * 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. Captured at deploy time.
- * @maxLength 1024
- */
- repo_url?: string;
- /**
- * Source branch the deployment was built from.
- * @maxLength 255
- */
- branch?: string;
- /**
- * Public URL serving the built site once ready.
- * @maxLength 1024
- */
- deployment_url?: string;
- /**
- * 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 (for rollbacks and redeploys).
- * @nullable
- */
- readonly triggered_by_deployment: string | null;
- /**
- * 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;
- /** 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 one-off action endpoints (cancel, refresh_preview).
- */
- export interface DeploymentActionResponse {
- /** 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;
- }
-
- /**
- * One line of build output emitted by the build worker as a `$log` event.
- */
- export interface DeploymentLogEntry {
- /** When the line was emitted by the build worker. */
- timestamp: string;
- /**
- * Log level: "info" | "warn" | "error". Null if the event did not carry one.
- * @nullable
- */
- level: string | null;
- /**
- * Pipeline step: "clone" | "install" | "build" | "publish". Null if the event did not carry one.
- * @nullable
- */
- step: string | null;
- /**
- * The log line itself (a single line of stdout or stderr).
- * @nullable
- */
- line: string | null;
- /**
- * Set on the last line of a step; null on all other lines.
- * @nullable
- */
- exit_code: number | null;
- }
-
- /**
- * Response shape for GET /deployments/{id}/logs/.
- */
- export interface DeploymentLogsResponse {
- /** Log lines for the deployment, oldest first. */
- results: DeploymentLogEntry[];
- /** True if the row limit was hit and older lines may exist beyond this page. */
- has_more: boolean;
- /** The hard cap applied by the server. */
- row_limit: number;
- }
-
- 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 connected GitHub repository, resolved from the selected repository id.
- * @maxLength 1024
- */
- readonly repo_url: string;
- /**
- * Branch PostHog tracks for deployment updates. Defaults to the repository default branch.
- * @maxLength 255
- */
- default_branch?: string;
- /**
- * Existing PostHog GitHub integration id used for repository access.
- * @nullable
- */
- github_integration_id?: number | null;
- /**
- * Stable GitHub repository identifier selected from the existing integration's repository list.
- * @nullable
- */
- github_repo_id?: 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 DeploymentProjectCreate {
- /**
- * Human-readable project name shown in the UI.
- * @maxLength 200
- */
- name: string;
- /**
- * URL-safe handle. Becomes the subdomain `{slug}.posthog-app.com`. Must be unique per team.
- * @maxLength 80
- * @pattern ^[-a-zA-Z0-9_]+$
- */
- slug: string;
- /**
- * Branch PostHog tracks for deployment updates. Defaults to the repository default branch.
- * @maxLength 255
- */
- default_branch?: string;
- /** Existing PostHog GitHub integration id used for repository access. */
- github_integration_id: number;
- /** Stable GitHub repository identifier selected from the existing integration's repository list. */
- github_repo_id: number;
- /**
- * 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;
- }
-
- /**
- * Response shape for refreshing a deployment project's GitHub branch.
- */
- export interface DeploymentProjectRefreshResponse {
- /** Human-readable explanation of the refresh result. */
- detail: string;
- /** HTTPS URL of the connected GitHub repository. */
- repo_url: string;
- /** Branch checked by the refresh action. */
- default_branch: string;
- /** Current GitHub HEAD SHA for default_branch. */
- commit_sha: string;
- }
-
- export interface DeploymentProjectWrite {
- /**
- * 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;
- /**
- * Branch PostHog tracks for deployment updates. Defaults to the repository default branch.
- * @maxLength 255
- */
- default_branch?: string;
- /**
- * Existing PostHog GitHub integration id used for repository access.
- * @nullable
- */
- github_integration_id?: number | null;
- /**
- * Stable GitHub repository identifier selected from the existing integration's repository list.
- * @nullable
- */
- github_repo_id?: 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;
- }
-
export interface DeprovisionWarehouseResponse {
status: string;
team: string;
@@ -13643,69 +13219,6 @@ export namespace Schemas {
readonly updated_at: string;
}
- /**
- * Inputs the `/detect/` endpoint needs to suggest a project config.
-
- Decouples detection from any one git provider — callers fetch
- `package.json` and the list of lockfiles however they like (GitHub
- raw content via the team's existing integration, a temporary clone,
- user-pasted JSON during early development) and pass them here.
- */
- export interface DetectConfigRequest {
- /** Parsed contents of the repo's `package.json`. Pass null or omit if the repo doesn't have one — the response is then the plain-HTML fallback. */
- package_json?: unknown;
- /** Filenames of package-manager lockfiles found in the repo root (e.g. ["pnpm-lock.yaml"]). Used to pick the package manager. */
- lockfiles?: string[];
- }
-
- /**
- * * `npm` - npm
- * `pnpm` - pnpm
- * `yarn` - yarn
- * `bun` - bun
- */
- export type PackageManagerEnum = typeof PackageManagerEnum[keyof typeof PackageManagerEnum];
-
-
- export const PackageManagerEnum = {
- Npm: 'npm',
- Pnpm: 'pnpm',
- Yarn: 'yarn',
- Bun: 'bun',
- } as const;
-
- /**
- * Suggested project config. Every field is overridable in the connect-repo UI.
-
- `build_command`, `output_dir`, and `framework` map directly to the
- `DeploymentProject` model fields. `package_manager`, `install_command`,
- and `node_version` are informational hints — the model doesn't store
- them today, but the UI can display them so the user knows what the
- build worker will end up running.
- */
- export interface DetectConfigResponse {
- /** Detected package manager from lockfile presence.
-
- * `npm` - npm
- * `pnpm` - pnpm
- * `yarn` - yarn
- * `bun` - bun */
- package_manager: PackageManagerEnum;
- /** Suggested install command, or empty when no install is needed. */
- install_command: string;
- /** Suggested build command, or empty when no known framework matched. */
- build_command: string;
- /** Suggested output directory relative to repo root. */
- output_dir: string;
- /** Suggested Node major version, parsed from `engines.node` or defaulted to 20. */
- node_version: string;
- /**
- * Detected framework hint (e.g. `nextjs`, `vite`, `astro`) to write into `DeploymentProject.framework`. Null when no framework matched — leaving the field null lets the build worker fall back to its own auto-detection.
- * @nullable
- */
- framework: string | null;
- }
-
/**
* * `Desktop` - Desktop
* `Mobile` - Mobile
@@ -23387,33 +22900,6 @@ 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 */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: Deployment[];
- }
-
- export interface PaginatedDeploymentProjectList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: DeploymentProject[];
- }
-
export interface PaginatedDesktopRecordingList {
count: number;
/** @nullable */
@@ -27948,53 +27434,6 @@ export namespace Schemas {
readonly team?: number;
}
- export interface PatchedDeploymentProjectWrite {
- /**
- * 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;
- /**
- * Branch PostHog tracks for deployment updates. Defaults to the repository default branch.
- * @maxLength 255
- */
- default_branch?: string;
- /**
- * Existing PostHog GitHub integration id used for repository access.
- * @nullable
- */
- github_integration_id?: number | null;
- /**
- * Stable GitHub repository identifier selected from the existing integration's repository list.
- * @nullable
- */
- github_repo_id?: 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;
- }
-
export interface PatchedDesktopRecording {
readonly id?: string;
readonly team?: number;
@@ -46132,63 +45571,6 @@ export namespace Schemas {
search?: 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.
- */
- 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 DesktopRecordingsListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/lib/oauth-scopes.generated.ts b/services/mcp/src/lib/oauth-scopes.generated.ts
index fd957a24ede3..e7b9312975db 100644
--- a/services/mcp/src/lib/oauth-scopes.generated.ts
+++ b/services/mcp/src/lib/oauth-scopes.generated.ts
@@ -51,8 +51,6 @@ 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 c119271f79c2..7d94394ba6bc 100644
--- a/tach.toml
+++ b/tach.toml
@@ -73,7 +73,6 @@ depends_on = [
"products.dashboards",
"products.data_modeling",
"products.data_warehouse",
- "products.deployments",
"products.desktop_recordings",
"products.early_access_features",
"products.endpoints",
@@ -220,19 +219,6 @@ depends_on = [
]
layer = "modules"
-[[modules]]
-path = "products.deployments"
-depends_on = [
- "ee",
- "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"
-
[[modules]]
path = "products.desktop_recordings"
depends_on = [