:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(uptime-monitoring): add the uptime monitor crud api (#122248)
Jon McCallum7c15ae086a56
diff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.pyindex f7d3bfce4d4a..1a108150c51d 100644--- a/posthog/test/repo_invariants/test_pagination_contract.py+++ b/posthog/test/repo_invariants/test_pagination_contract.py@@ -269,6 +269,7 @@ EXISTING_CUSTOM_LIST_VIEWSETS = {"products.tasks.backend.presentation.views.config_api.TasksUserConfigViewSet","products.tasks.backend.presentation.views.desktop.DesktopBetaTermsViewSet","products.tasks.backend.presentation.views.sandbox_pricing_api.SandboxComputePricingViewSet",+ "products.uptime_monitoring.backend.presentation.views.UptimeMonitorViewSet","products.visual_review.backend.presentation.views.RepoRunsViewSet","products.visual_review.backend.presentation.views.RepoViewSet","products.visual_review.backend.presentation.views.RunViewSet",diff --git a/products/uptime_monitoring/backend/facade/api.py b/products/uptime_monitoring/backend/facade/api.pyindex 0bfe006b2334..d3f5f70cb52e 100644--- a/products/uptime_monitoring/backend/facade/api.py+++ b/products/uptime_monitoring/backend/facade/api.py@@ -8,8 +8,53 @@ dataclasses. Never return ORM instances or import DRF.from __future__ import annotations+from uuid import UUID+from ..feature_flags import is_uptime_monitoring_enabled+from ..logic import monitors+from ..models import UptimeMonitor as UptimeMonitorModel+from . import contracts+from .enums import UptimeMonitorMethoddef is_enabled(team_id: int) -> bool:return is_uptime_monitoring_enabled(team_id)+++def _to_contract(monitor: UptimeMonitorModel) -> contracts.UptimeMonitor:+ return contracts.UptimeMonitor(+ id=monitor.id,+ team_id=monitor.team_id,+ name=monitor.name,+ url=monitor.url,+ method=UptimeMonitorMethod(monitor.method),+ interval_seconds=monitor.interval_seconds,+ timeout_seconds=monitor.timeout_seconds,+ enabled=monitor.enabled,+ created_at=monitor.created_at,+ updated_at=monitor.updated_at,+ )+++def list_monitors(team_id: int, *, limit: int, offset: int) -> tuple[list[contracts.UptimeMonitor], int]:+ """One page of the team's monitors, newest first, and the total count, paged in SQL."""+ page, count = monitors.list_monitors(team_id, limit=limit, offset=offset)+ return [_to_contract(m) for m in page], count+++def get_monitor(team_id: int, monitor_id: UUID) -> contracts.UptimeMonitor:+ return _to_contract(monitors.get_monitor(team_id, monitor_id))+++def create_monitor(+ team_id: int, created_by_id: int | None, data: contracts.CreateUptimeMonitorInput+) -> contracts.UptimeMonitor:+ return _to_contract(monitors.create_monitor(team_id, created_by_id, data))+++def update_monitor(team_id: int, monitor_id: UUID, data: contracts.UpdateUptimeMonitorInput) -> contracts.UptimeMonitor:+ return _to_contract(monitors.update_monitor(team_id, monitor_id, data))+++def delete_monitor(team_id: int, monitor_id: UUID) -> None:+ monitors.delete_monitor(team_id, monitor_id)diff --git a/products/uptime_monitoring/backend/facade/contracts.py b/products/uptime_monitoring/backend/facade/contracts.pyindex d16e9785905d..931c3bf66e39 100644--- a/products/uptime_monitoring/backend/facade/contracts.py+++ b/products/uptime_monitoring/backend/facade/contracts.py@@ -4,3 +4,57 @@ Contract types for uptime_monitoring.Frozen dataclasses that define what this product exposes.No Django imports. Used by facade as inputs/outputs."""++from datetime import datetime+from uuid import UUID++from pydantic.dataclasses import dataclass++from .enums import UptimeMonitorMethod++MIN_INTERVAL_SECONDS = 60+MAX_INTERVAL_SECONDS = 24 * 60 * 60+DEFAULT_INTERVAL_SECONDS = 300+MIN_TIMEOUT_SECONDS = 1+MAX_TIMEOUT_SECONDS = 10+DEFAULT_TIMEOUT_SECONDS = 10+++class UptimeMonitorNotFoundError(Exception):+ pass+++@dataclass(frozen=True)+class UptimeMonitor:+ id: UUID+ team_id: int+ name: str+ url: str+ method: UptimeMonitorMethod+ interval_seconds: int+ timeout_seconds: int+ enabled: bool+ created_at: datetime+ updated_at: datetime+++@dataclass(frozen=True)+class CreateUptimeMonitorInput:+ name: str+ url: str+ method: UptimeMonitorMethod = UptimeMonitorMethod.GET+ interval_seconds: int = DEFAULT_INTERVAL_SECONDS+ timeout_seconds: int = DEFAULT_TIMEOUT_SECONDS+ enabled: bool = True+++@dataclass(frozen=True)+class UpdateUptimeMonitorInput:+ """Fields left as None keep their stored value."""++ name: str | None = None+ url: str | None = None+ method: UptimeMonitorMethod | None = None+ interval_seconds: int | None = None+ timeout_seconds: int | None = None+ enabled: bool | None = Nonediff --git a/products/uptime_monitoring/backend/logic/__init__.py b/products/uptime_monitoring/backend/logic/__init__.pynew file mode 100644index 000000000000..e69de29bb2d1diff --git a/products/uptime_monitoring/backend/logic/monitors.py b/products/uptime_monitoring/backend/logic/monitors.pynew file mode 100644index 000000000000..2da3f172099d--- /dev/null+++ b/products/uptime_monitoring/backend/logic/monitors.py@@ -0,0 +1,35 @@+from dataclasses import asdict+from uuid import UUID++from ..facade.contracts import CreateUptimeMonitorInput, UpdateUptimeMonitorInput, UptimeMonitorNotFoundError+from ..models import UptimeMonitor+++def get_monitor(team_id: int, monitor_id: UUID) -> UptimeMonitor:+ try:+ return UptimeMonitor.objects.for_team(team_id).get(id=monitor_id)+ except UptimeMonitor.DoesNotExist as e:+ raise UptimeMonitorNotFoundError(f"Uptime monitor {monitor_id} not found") from e+++def list_monitors(team_id: int, *, limit: int, offset: int) -> tuple[list[UptimeMonitor], int]:+ monitors = UptimeMonitor.objects.for_team(team_id)+ return list(monitors.order_by("-created_at", "id")[offset : offset + limit]), monitors.count()+++def create_monitor(team_id: int, created_by_id: int | None, data: CreateUptimeMonitorInput) -> UptimeMonitor:+ return UptimeMonitor.objects.for_team(team_id).create(team_id=team_id, created_by_id=created_by_id, **asdict(data))+++def update_monitor(team_id: int, monitor_id: UUID, data: UpdateUptimeMonitorInput) -> UptimeMonitor:+ monitor = get_monitor(team_id, monitor_id)+ changes = {field: value for field, value in asdict(data).items() if value is not None}+ for field, value in changes.items():+ setattr(monitor, field, value)+ if changes:+ monitor.save(update_fields=[*changes, "updated_at"])+ return monitor+++def delete_monitor(team_id: int, monitor_id: UUID) -> None:+ get_monitor(team_id, monitor_id).delete()diff --git a/products/uptime_monitoring/backend/models/uptime_monitor.py b/products/uptime_monitoring/backend/models/uptime_monitor.pyindex 8770b9dcd6a9..87439e7128b0 100644--- a/products/uptime_monitoring/backend/models/uptime_monitor.py+++ b/products/uptime_monitoring/backend/models/uptime_monitor.py@@ -10,13 +10,16 @@ from django.db import modelsfrom posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import UUIDModel+from products.uptime_monitoring.backend.facade.contracts import (+ DEFAULT_INTERVAL_SECONDS,+ DEFAULT_TIMEOUT_SECONDS,+ MAX_INTERVAL_SECONDS,+ MAX_TIMEOUT_SECONDS,+ MIN_INTERVAL_SECONDS,+ MIN_TIMEOUT_SECONDS,+)from products.uptime_monitoring.backend.facade.enums import UptimeMonitorMethod-MIN_INTERVAL_SECONDS = 60-MAX_INTERVAL_SECONDS = 24 * 60 * 60-MIN_TIMEOUT_SECONDS = 1-MAX_TIMEOUT_SECONDS = 10-class UptimeMonitor(TeamScopedRootMixin, UUIDModel):Method = UptimeMonitorMethod@@ -37,13 +40,13 @@ class UptimeMonitor(TeamScopedRootMixin, UUIDModel):max_length=8, choices=Method.choices, default=Method.GET.value, db_default=Method.GET.value)interval_seconds = models.PositiveIntegerField(- default=300,- db_default=300,+ default=DEFAULT_INTERVAL_SECONDS,+ db_default=DEFAULT_INTERVAL_SECONDS,validators=[MinValueValidator(MIN_INTERVAL_SECONDS), MaxValueValidator(MAX_INTERVAL_SECONDS)],)timeout_seconds = models.PositiveIntegerField(- default=10,- db_default=10,+ default=DEFAULT_TIMEOUT_SECONDS,+ db_default=DEFAULT_TIMEOUT_SECONDS,validators=[MinValueValidator(MIN_TIMEOUT_SECONDS), MaxValueValidator(MAX_TIMEOUT_SECONDS)],)enabled = models.BooleanField(default=True, db_default=True)diff --git a/products/uptime_monitoring/backend/presentation/serializers.py b/products/uptime_monitoring/backend/presentation/serializers.pynew file mode 100644index 000000000000..baff4428ed3a--- /dev/null+++ b/products/uptime_monitoring/backend/presentation/serializers.py@@ -0,0 +1,93 @@+from django.core.validators import URLValidator++from rest_framework import serializers+from rest_framework_dataclasses.serializers import DataclassSerializer++from ..facade.contracts import (+ MAX_INTERVAL_SECONDS,+ MAX_TIMEOUT_SECONDS,+ MIN_INTERVAL_SECONDS,+ MIN_TIMEOUT_SECONDS,+ CreateUptimeMonitorInput,+ UpdateUptimeMonitorInput,+ UptimeMonitor,+)++_FIELD_HELP = {+ "name": "Display name for the monitor.",+ "url": "The http or https URL to check.",+ "method": "HTTP method used for each check.",+ "interval_seconds": f"Seconds between checks, a whole number of minutes from {MIN_INTERVAL_SECONDS} to {MAX_INTERVAL_SECONDS}.",+ "timeout_seconds": f"Seconds to wait for a response before the check fails, from {MIN_TIMEOUT_SECONDS} to {MAX_TIMEOUT_SECONDS}.",+ "enabled": "Whether checks run for this monitor.",+}+++def _validate_whole_minutes(value: int) -> None:+ # Schedulers that drive monitors count in minutes, so a value between minutes cannot be honored.+ if value % 60:+ raise serializers.ValidationError("Must be a whole number of minutes.")+++CREATE_NULL_MESSAGE = "Can't be null. Send a value for this field."+# Update inputs use None for "keep the stored value", so an explicit null is rejected rather than silently ignored.+UPDATE_NULL_MESSAGE = "Can't be null. To keep the current value, leave this field out of the request."+++def _input_kwargs(null_message: str) -> dict[str, dict]:+ not_null = {"allow_null": False, "error_messages": {"null": null_message}}+ return {+ **{field: {"help_text": help_text, **not_null} for field, help_text in _FIELD_HELP.items() if field != "url"},+ "name": {"help_text": _FIELD_HELP["name"], "max_length": 255, **not_null},+ "interval_seconds": {+ "help_text": _FIELD_HELP["interval_seconds"],+ "min_value": MIN_INTERVAL_SECONDS,+ "max_value": MAX_INTERVAL_SECONDS,+ "validators": [_validate_whole_minutes],+ **not_null,+ },+ "timeout_seconds": {+ "help_text": _FIELD_HELP["timeout_seconds"],+ "min_value": MIN_TIMEOUT_SECONDS,+ "max_value": MAX_TIMEOUT_SECONDS,+ **not_null,+ },+ }+++def _url_field(required: bool, null_message: str) -> serializers.CharField:+ return serializers.CharField(+ max_length=2048,+ required=required,+ error_messages={"null": null_message},+ validators=[URLValidator(schemes=["http", "https"])],+ help_text=_FIELD_HELP["url"],+ )+++class UptimeMonitorSerializer(DataclassSerializer):+ class Meta:+ dataclass = UptimeMonitor+ extra_kwargs = {+ **{field: {"help_text": help_text} for field, help_text in _FIELD_HELP.items()},+ "id": {"help_text": "Unique identifier of the monitor."},+ "team_id": {"help_text": "Project the monitor belongs to."},+ "created_at": {"help_text": "When the monitor was created."},+ "updated_at": {"help_text": "When the monitor was last changed."},+ }+++class CreateUptimeMonitorInputSerializer(DataclassSerializer):+ url = _url_field(required=True, null_message=CREATE_NULL_MESSAGE)++ class Meta:+ dataclass = CreateUptimeMonitorInput+ extra_kwargs = _input_kwargs(CREATE_NULL_MESSAGE)+++class UpdateUptimeMonitorInputSerializer(DataclassSerializer):+ url = _url_field(required=False, null_message=UPDATE_NULL_MESSAGE)++ class Meta:+ dataclass = UpdateUptimeMonitorInput+ extra_kwargs = _input_kwargs(UPDATE_NULL_MESSAGE)diff --git a/products/uptime_monitoring/backend/presentation/views.py b/products/uptime_monitoring/backend/presentation/views.pynew file mode 100644index 000000000000..62131dbcbbd3--- /dev/null+++ b/products/uptime_monitoring/backend/presentation/views.py@@ -0,0 +1,91 @@+from typing import Any, cast+from uuid import UUID++from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema+from rest_framework import status, viewsets+from rest_framework.exceptions import NotFound+from rest_framework.request import Request+from rest_framework.response import Response++from posthog.api.mixins import TypedRequest, validated_request+from posthog.api.pagination import PrecountedLimitOffsetPagination+from posthog.api.routing import TeamAndOrgViewSetMixin++from ..facade import api+from ..facade.contracts import CreateUptimeMonitorInput, UpdateUptimeMonitorInput, UptimeMonitorNotFoundError+from .serializers import CreateUptimeMonitorInputSerializer, UpdateUptimeMonitorInputSerializer, UptimeMonitorSerializer++_ID_PARAMETER = OpenApiParameter("id", OpenApiTypes.UUID, OpenApiParameter.PATH)+DEFAULT_PAGE_SIZE = 100+++def _parse_id(pk: str) -> UUID:+ try:+ return UUID(pk)+ except ValueError:+ raise NotFound()+++class UptimeMonitorViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ """URLs that PostHog checks on a schedule."""++ # Session access only until the product is released and has its own API scope.+ scope_object = "INTERNAL"+ pagination_class = PrecountedLimitOffsetPagination++ def initial(self, request: Request, *args: Any, **kwargs: Any) -> None:+ super().initial(request, *args, **kwargs)+ if not api.is_enabled(self.team_id):+ raise NotFound()++ @extend_schema(responses={200: UptimeMonitorSerializer(many=True)})+ def list(self, request: Request, **kwargs: Any) -> Response:+ """List the project's uptime monitors, newest first."""+ paginator = cast(PrecountedLimitOffsetPagination, self.paginator)+ monitors, count = api.list_monitors(+ self.team_id, limit=paginator.get_limit(request) or DEFAULT_PAGE_SIZE, offset=paginator.get_offset(request)+ )+ paginator.set_count(count)+ page = self.paginate_queryset(monitors)+ return self.get_paginated_response(UptimeMonitorSerializer(instance=page, many=True).data)++ @validated_request(+ request_serializer=CreateUptimeMonitorInputSerializer,+ responses={201: OpenApiResponse(response=UptimeMonitorSerializer)},+ )+ def create(self, request: TypedRequest[CreateUptimeMonitorInput], **kwargs: Any) -> Response:+ """Create an uptime monitor."""+ monitor = api.create_monitor(self.team_id, request.user.id, request.validated_data)+ return Response(UptimeMonitorSerializer(instance=monitor).data, status=status.HTTP_201_CREATED)++ @extend_schema(parameters=[_ID_PARAMETER], responses={200: UptimeMonitorSerializer})+ def retrieve(self, request: Request, pk: str, **kwargs: Any) -> Response:+ """Get an uptime monitor."""+ try:+ monitor = api.get_monitor(self.team_id, _parse_id(pk))+ except UptimeMonitorNotFoundError:+ raise NotFound()+ return Response(UptimeMonitorSerializer(instance=monitor).data)++ @extend_schema(parameters=[_ID_PARAMETER])+ @validated_request(+ request_serializer=UpdateUptimeMonitorInputSerializer,+ responses={200: OpenApiResponse(response=UptimeMonitorSerializer)},+ )+ def partial_update(self, request: TypedRequest[UpdateUptimeMonitorInput], pk: str, **kwargs: Any) -> Response:+ """Change some fields of an uptime monitor."""+ try:+ monitor = api.update_monitor(self.team_id, _parse_id(pk), request.validated_data)+ except UptimeMonitorNotFoundError:+ raise NotFound()+ return Response(UptimeMonitorSerializer(instance=monitor).data)++ @extend_schema(parameters=[_ID_PARAMETER], responses={204: None})+ def destroy(self, request: Request, pk: str, **kwargs: Any) -> Response:+ """Delete an uptime monitor."""+ try:+ api.delete_monitor(self.team_id, _parse_id(pk))+ except UptimeMonitorNotFoundError:+ raise NotFound()+ return Response(status=status.HTTP_204_NO_CONTENT)diff --git a/products/uptime_monitoring/backend/routes.py b/products/uptime_monitoring/backend/routes.pynew file mode 100644index 000000000000..7c93d7dd609b--- /dev/null+++ b/products/uptime_monitoring/backend/routes.py@@ -0,0 +1,7 @@+from posthog.api.routing import RouterRegistry++from products.uptime_monitoring.backend.presentation.views import UptimeMonitorViewSet+++def register_routes(routers: RouterRegistry) -> None:+ routers.projects.register(r"uptime_monitors", UptimeMonitorViewSet, "project_uptime_monitors", ["project_id"])diff --git a/products/uptime_monitoring/backend/tests/test_api.py b/products/uptime_monitoring/backend/tests/test_api.pynew file mode 100644index 000000000000..986507473218--- /dev/null+++ b/products/uptime_monitoring/backend/tests/test_api.py@@ -0,0 +1,71 @@+import time_machine+from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from parameterized import parameterized+from rest_framework import status++from posthog.models import Organization, Team++from products.uptime_monitoring.backend.models import UptimeMonitor+++@patch("products.uptime_monitoring.backend.facade.api.is_uptime_monitoring_enabled", return_value=True)+class TestUptimeMonitorAPI(APIBaseTest):+ def _url(self, monitor_id: object = None) -> str:+ base = f"/api/projects/{self.team.id}/uptime_monitors/"+ return f"{base}{monitor_id}/" if monitor_id else base++ def test_create_update_list_delete(self, _flag: MagicMock) -> None:+ created = self.client.post(self._url(), {"name": "Site", "url": "https://example.com"}, format="json")+ assert created.status_code == status.HTTP_201_CREATED, created.json()+ monitor_id = created.json()["id"]+ assert UptimeMonitor.objects.for_team(self.team.id).get(id=monitor_id).created_by_id == self.user.id++ updated = self.client.patch(self._url(monitor_id), {"enabled": False, "interval_seconds": 600}, format="json")+ assert updated.status_code == status.HTTP_200_OK, updated.json()+ assert updated.json()["enabled"] is False+ assert updated.json()["interval_seconds"] == 600+ assert updated.json()["name"] == "Site"++ listed = self.client.get(self._url())+ assert [m["id"] for m in listed.json()["results"]] == [monitor_id]++ assert self.client.delete(self._url(monitor_id)).status_code == status.HTTP_204_NO_CONTENT+ assert not UptimeMonitor.objects.for_team(self.team.id).exists()++ def test_list_pages_newest_first(self, _flag: MagicMock) -> None:+ with time_machine.travel("2026-01-01", tick=False):+ older = UptimeMonitor.objects.for_team(self.team.id).create(+ team=self.team, name="Older", url="https://example.com"+ )+ with time_machine.travel("2026-01-02", tick=False):+ newer = UptimeMonitor.objects.for_team(self.team.id).create(+ team=self.team, name="Newer", url="https://example.com"+ )++ first = self.client.get(self._url(), {"limit": 1}).json()+ second = self.client.get(self._url(), {"limit": 1, "offset": 1}).json()++ assert first["count"] == 2+ assert [m["id"] for m in first["results"]] == [str(newer.id)]+ assert [m["id"] for m in second["results"]] == [str(older.id)]++ def test_invalid_body_is_rejected(self, _flag: MagicMock) -> None:+ response = self.client.post(self._url(), {"name": "Site", "url": "not a url"}, format="json")+ assert response.status_code == status.HTTP_400_BAD_REQUEST++ @parameterized.expand([("get",), ("patch",), ("delete",)])+ def test_another_teams_monitor_is_not_found(self, _flag: MagicMock, method: str) -> None:+ other_team = Team.objects.create(organization=Organization.objects.create(name="Other"))+ other = UptimeMonitor.objects.for_team(other_team.id).create(+ team=other_team, name="Other", url="https://example.org"+ )+ response = getattr(self.client, method)(self._url(other.id), {"name": "Taken"}, format="json")+ assert response.status_code == status.HTTP_404_NOT_FOUND+ other.refresh_from_db()+ assert other.name == "Other"++ def test_flag_off_hides_the_api(self, flag: MagicMock) -> None:+ flag.return_value = False+ assert self.client.get(self._url()).status_code == status.HTTP_404_NOT_FOUNDdiff --git a/products/uptime_monitoring/backend/tests/test_serializers.py b/products/uptime_monitoring/backend/tests/test_serializers.pynew file mode 100644index 000000000000..4c90ea42f79a--- /dev/null+++ b/products/uptime_monitoring/backend/tests/test_serializers.py@@ -0,0 +1,53 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from products.uptime_monitoring.backend.presentation.serializers import (+ CREATE_NULL_MESSAGE,+ UPDATE_NULL_MESSAGE,+ CreateUptimeMonitorInputSerializer,+ UpdateUptimeMonitorInputSerializer,+)+++class TestUptimeMonitorInputValidation(SimpleTestCase):+ @parameterized.expand(+ [+ ("name_too_long", {"name": "x" * 256}, "name"),+ ("null_name", {"name": None}, "name"),+ ("null_interval", {"interval_seconds": None}, "interval_seconds"),+ ("non_http_scheme", {"url": "ftp://example.com"}, "url"),+ ("not_a_url", {"url": "example"}, "url"),+ ("interval_below_minimum", {"interval_seconds": 30}, "interval_seconds"),+ ("interval_above_maximum", {"interval_seconds": 2 * 24 * 60 * 60}, "interval_seconds"),+ ("interval_between_minutes", {"interval_seconds": 90}, "interval_seconds"),+ ("timeout_above_maximum", {"timeout_seconds": 11}, "timeout_seconds"),+ ("unknown_method", {"method": "POST"}, "method"),+ ]+ )+ def test_rejects_invalid_input_on_create_and_update(self, _name: str, override: dict, field: str) -> None:+ for serializer_class, base in (+ (CreateUptimeMonitorInputSerializer, {"name": "Site", "url": "https://example.com"}),+ (UpdateUptimeMonitorInputSerializer, {}),+ ):+ serializer = serializer_class(data={**base, **override})+ assert not serializer.is_valid()+ assert field in serializer.errors++ @parameterized.expand(+ [+ ("create", CreateUptimeMonitorInputSerializer, CREATE_NULL_MESSAGE),+ ("update", UpdateUptimeMonitorInputSerializer, UPDATE_NULL_MESSAGE),+ ]+ )+ def test_null_error_says_what_to_do_instead(self, _name: str, serializer_class: type, message: str) -> None:+ serializer = serializer_class(data={"name": None, "url": None, "interval_seconds": None})+ assert not serializer.is_valid()+ for field in ("name", "url", "interval_seconds"):+ assert serializer.errors[field] == [message]++ def test_create_fills_defaults(self) -> None:+ serializer = CreateUptimeMonitorInputSerializer(data={"name": "Site", "url": "https://example.com"})+ assert serializer.is_valid(), serializer.errors+ assert serializer.validated_data.interval_seconds == 300+ assert serializer.validated_data.method == "GET"diff --git a/products/uptime_monitoring/frontend/generated/api.schemas.ts b/products/uptime_monitoring/frontend/generated/api.schemas.tsnew file mode 100644index 000000000000..1f3c32ebd507--- /dev/null+++ b/products/uptime_monitoring/frontend/generated/api.schemas.ts@@ -0,0 +1,129 @@+/**+ * 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+ */+/**+ * * `GET` - GET+ * * `HEAD` - HEAD+ */+export type UptimeMonitorMethodEnumApi = (typeof UptimeMonitorMethodEnumApi)[keyof typeof UptimeMonitorMethodEnumApi]++export const UptimeMonitorMethodEnumApi = {+ Get: 'GET',+ Head: 'HEAD',+} as const++export interface UptimeMonitorApi {+ /** Unique identifier of the monitor. */+ id: string+ /** Project the monitor belongs to. */+ team_id: number+ /** Display name for the monitor. */+ name: string+ /** The http or https URL to check. */+ url: string+ /** HTTP method used for each check.+ *+ * * `GET` - GET+ * * `HEAD` - HEAD */+ method: UptimeMonitorMethodEnumApi+ /** Seconds between checks, a whole number of minutes from 60 to 86400. */+ interval_seconds: number+ /** Seconds to wait for a response before the check fails, from 1 to 10. */+ timeout_seconds: number+ /** Whether checks run for this monitor. */+ enabled: boolean+ /** When the monitor was created. */+ created_at: string+ /** When the monitor was last changed. */+ updated_at: string+}++export interface PaginatedUptimeMonitorListApi {+ count: number+ /** @nullable */+ next?: string | null+ /** @nullable */+ previous?: string | null+ results: UptimeMonitorApi[]+}++export interface CreateUptimeMonitorInputApi {+ /**+ * The http or https URL to check.+ * @maxLength 2048+ */+ url: string+ /**+ * Display name for the monitor.+ * @maxLength 255+ */+ name: string+ /** HTTP method used for each check.+ *+ * * `GET` - GET+ * * `HEAD` - HEAD */+ method?: UptimeMonitorMethodEnumApi+ /**+ * Seconds between checks, a whole number of minutes from 60 to 86400.+ * @minimum 60+ * @maximum 86400+ */+ interval_seconds?: number+ /**+ * Seconds to wait for a response before the check fails, from 1 to 10.+ * @minimum 1+ * @maximum 10+ */+ timeout_seconds?: number+ /** Whether checks run for this monitor. */+ enabled?: boolean+}++export interface PatchedUpdateUptimeMonitorInputApi {+ /**+ * The http or https URL to check.+ * @maxLength 2048+ */+ url?: string+ /**+ * Display name for the monitor.+ * @maxLength 255+ */+ name?: string+ /** HTTP method used for each check.+ *+ * * `GET` - GET+ * * `HEAD` - HEAD */+ method?: UptimeMonitorMethodEnumApi+ /**+ * Seconds between checks, a whole number of minutes from 60 to 86400.+ * @minimum 60+ * @maximum 86400+ */+ interval_seconds?: number+ /**+ * Seconds to wait for a response before the check fails, from 1 to 10.+ * @minimum 1+ * @maximum 10+ */+ timeout_seconds?: number+ /** Whether checks run for this monitor. */+ enabled?: boolean+}++export type UptimeMonitorsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number+ /**+ * The initial index from which to return the results.+ */+ offset?: number+}diff --git a/products/uptime_monitoring/frontend/generated/api.ts b/products/uptime_monitoring/frontend/generated/api.tsnew file mode 100644index 000000000000..e5447dc3ecdb--- /dev/null+++ b/products/uptime_monitoring/frontend/generated/api.ts@@ -0,0 +1,120 @@+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 {+ CreateUptimeMonitorInputApi,+ PaginatedUptimeMonitorListApi,+ PatchedUpdateUptimeMonitorInputApi,+ UptimeMonitorApi,+ UptimeMonitorsListParams,+} from './api.schemas'++export const getUptimeMonitorsListUrl = (projectId: string, params?: UptimeMonitorsListParams) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/uptime_monitors/?${stringifiedParams}`+ : `/api/projects/${projectId}/uptime_monitors/`+}++/**+ * List the project's uptime monitors, newest first.+ */+export const uptimeMonitorsList = async (+ projectId: string,+ params?: UptimeMonitorsListParams,+ options?: RequestInit+): Promise<PaginatedUptimeMonitorListApi> => {+ return apiMutator<PaginatedUptimeMonitorListApi>(getUptimeMonitorsListUrl(projectId, params), {+ ...options,+ method: 'GET',+ })+}++export const getUptimeMonitorsCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/uptime_monitors/`+}++/**+ * Create an uptime monitor.+ */+export const uptimeMonitorsCreate = async (+ projectId: string,+ createUptimeMonitorInputApi: CreateUptimeMonitorInputApi,+ options?: RequestInit+): Promise<UptimeMonitorApi> => {+ return apiMutator<UptimeMonitorApi>(getUptimeMonitorsCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(createUptimeMonitorInputApi),+ })+}++export const getUptimeMonitorsRetrieveUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/uptime_monitors/${id}/`+}++/**+ * Get an uptime monitor.+ */+export const uptimeMonitorsRetrieve = async (+ projectId: string,+ id: string,+ options?: RequestInit+): Promise<UptimeMonitorApi> => {+ return apiMutator<UptimeMonitorApi>(getUptimeMonitorsRetrieveUrl(projectId, id), {+ ...options,+ method: 'GET',+ })+}++export const getUptimeMonitorsPartialUpdateUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/uptime_monitors/${id}/`+}++/**+ * Change some fields of an uptime monitor.+ */+export const uptimeMonitorsPartialUpdate = async (+ projectId: string,+ id: string,+ patchedUpdateUptimeMonitorInputApi?: PatchedUpdateUptimeMonitorInputApi,+ options?: RequestInit+): Promise<UptimeMonitorApi> => {+ return apiMutator<UptimeMonitorApi>(getUptimeMonitorsPartialUpdateUrl(projectId, id), {+ ...options,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchedUpdateUptimeMonitorInputApi),+ })+}++export const getUptimeMonitorsDestroyUrl = (projectId: string, id: string) => {+ return `/api/projects/${projectId}/uptime_monitors/${id}/`+}++/**+ * Delete an uptime monitor.+ */+export const uptimeMonitorsDestroy = async (projectId: string, id: string, options?: RequestInit): Promise<void> => {+ return apiMutator<void>(getUptimeMonitorsDestroyUrl(projectId, id), {+ ...options,+ method: 'DELETE',+ })+}diff --git a/products/uptime_monitoring/frontend/generated/api.zod.ts b/products/uptime_monitoring/frontend/generated/api.zod.tsnew file mode 100644index 000000000000..e0846a86d753--- /dev/null+++ b/products/uptime_monitoring/frontend/generated/api.zod.ts@@ -0,0 +1,80 @@+/**+ * 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'++/**+ * Create an uptime monitor.+ */+export const uptimeMonitorsCreateBodyUrlMax = 2048++export const uptimeMonitorsCreateBodyNameMax = 255++export const uptimeMonitorsCreateBodyIntervalSecondsMin = 60+export const uptimeMonitorsCreateBodyIntervalSecondsMax = 86400++export const uptimeMonitorsCreateBodyTimeoutSecondsMax = 10++export const UptimeMonitorsCreateBody = /* @__PURE__ */ zod.object({+ url: zod.url().max(uptimeMonitorsCreateBodyUrlMax).describe('The http or https URL to check.'),+ name: zod.string().max(uptimeMonitorsCreateBodyNameMax).describe('Display name for the monitor.'),+ method: zod+ .enum(['GET', 'HEAD'])+ .describe('\* `GET` - GET\n\* `HEAD` - HEAD')+ .optional()+ .describe('HTTP method used for each check.\n\n\* `GET` - GET\n\* `HEAD` - HEAD'),+ interval_seconds: zod+ .number()+ .min(uptimeMonitorsCreateBodyIntervalSecondsMin)+ .max(uptimeMonitorsCreateBodyIntervalSecondsMax)+ .optional()+ .describe('Seconds between checks, a whole number of minutes from 60 to 86400.'),+ timeout_seconds: zod+ .number()+ .min(1)+ .max(uptimeMonitorsCreateBodyTimeoutSecondsMax)+ .optional()+ .describe('Seconds to wait for a response before the check fails, from 1 to 10.'),+ enabled: zod.boolean().optional().describe('Whether checks run for this monitor.'),+})++/**+ * Change some fields of an uptime monitor.+ */+export const uptimeMonitorsPartialUpdateBodyUrlMax = 2048++export const uptimeMonitorsPartialUpdateBodyNameMax = 255++export const uptimeMonitorsPartialUpdateBodyIntervalSecondsMin = 60+export const uptimeMonitorsPartialUpdateBodyIntervalSecondsMax = 86400++export const uptimeMonitorsPartialUpdateBodyTimeoutSecondsMax = 10++export const UptimeMonitorsPartialUpdateBody = /* @__PURE__ */ zod.object({+ url: zod.url().max(uptimeMonitorsPartialUpdateBodyUrlMax).optional().describe('The http or https URL to check.'),+ name: zod.string().max(uptimeMonitorsPartialUpdateBodyNameMax).optional().describe('Display name for the monitor.'),+ method: zod+ .enum(['GET', 'HEAD'])+ .describe('\* `GET` - GET\n\* `HEAD` - HEAD')+ .optional()+ .describe('HTTP method used for each check.\n\n\* `GET` - GET\n\* `HEAD` - HEAD'),+ interval_seconds: zod+ .number()+ .min(uptimeMonitorsPartialUpdateBodyIntervalSecondsMin)+ .max(uptimeMonitorsPartialUpdateBodyIntervalSecondsMax)+ .optional()+ .describe('Seconds between checks, a whole number of minutes from 60 to 86400.'),+ timeout_seconds: zod+ .number()+ .min(1)+ .max(uptimeMonitorsPartialUpdateBodyTimeoutSecondsMax)+ .optional()+ .describe('Seconds to wait for a response before the check fails, from 1 to 10.'),+ enabled: zod.boolean().optional().describe('Whether checks run for this monitor.'),+})diff --git a/products/uptime_monitoring/turbo.json b/products/uptime_monitoring/turbo.jsonindex d1764a666306..434d9959251a 100644--- a/products/uptime_monitoring/turbo.json+++ b/products/uptime_monitoring/turbo.json@@ -5,6 +5,7 @@"inputs": ["backend/facade/**","backend/presentation/**",+ "backend/routes.py","backend/webhook_consumers.py","backend/tasks/**","backend/models/**",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 532a38b8d2fe..8269178fce79 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -26962,6 +26962,50 @@ export namespace Schemas {color?: string | null;}+ /**+ * * `GET` - GET+ * * `HEAD` - HEAD+ */+ export type UptimeMonitorMethodEnum = typeof UptimeMonitorMethodEnum[keyof typeof UptimeMonitorMethodEnum];+++ export const UptimeMonitorMethodEnum = {+ Get: 'GET',+ Head: 'HEAD',+ } as const;++ export interface CreateUptimeMonitorInput {+ /**+ * The http or https URL to check.+ * @maxLength 2048+ */+ url: string;+ /**+ * Display name for the monitor.+ * @maxLength 255+ */+ name: string;+ /** HTTP method used for each check.+ *+ * * `GET` - GET+ * * `HEAD` - HEAD */+ method?: UptimeMonitorMethodEnum;+ /**+ * Seconds between checks, a whole number of minutes from 60 to 86400.+ * @minimum 60+ * @maximum 86400+ */+ interval_seconds?: number;+ /**+ * Seconds to wait for a response before the check fails, from 1 to 10.+ * @minimum 1+ * @maximum 10+ */+ timeout_seconds?: number;+ /** Whether checks run for this monitor. */+ enabled?: boolean;+ }+/*** Extra text files to ship next to app.py, keyed by project-relative path (for example 'utils.py' or 'data/config.json'), each as plain text (max 1 MB).*/@@ -79700,6 +79744,41 @@ export namespace Schemas {results: UploadedMedia[];}+ export interface UptimeMonitor {+ /** Unique identifier of the monitor. */+ id: string;+ /** Project the monitor belongs to. */+ team_id: number;+ /** Display name for the monitor. */+ name: string;+ /** The http or https URL to check. */+ url: string;+ /** HTTP method used for each check.+ *+ * * `GET` - GET+ * * `HEAD` - HEAD */+ method: UptimeMonitorMethodEnum;+ /** Seconds between checks, a whole number of minutes from 60 to 86400. */+ interval_seconds: number;+ /** Seconds to wait for a response before the check fails, from 1 to 10. */+ timeout_seconds: number;+ /** Whether checks run for this monitor. */+ enabled: boolean;+ /** When the monitor was created. */+ created_at: string;+ /** When the monitor was last changed. */+ updated_at: string;+ }++ export interface PaginatedUptimeMonitorList {+ count: number;+ /** @nullable */+ next?: string | null;+ /** @nullable */+ previous?: string | null;+ results: UptimeMonitor[];+ }+export interface UserGitHubAccount {/*** GitHub account type for the installation (e.g. User or Organization).@@ -90469,6 +90548,38 @@ export namespace Schemas {library_ids?: string[];}+ export interface PatchedUpdateUptimeMonitorInput {+ /**+ * The http or https URL to check.+ * @maxLength 2048+ */+ url?: string;+ /**+ * Display name for the monitor.+ * @maxLength 255+ */+ name?: string;+ /** HTTP method used for each check.+ *+ * * `GET` - GET+ * * `HEAD` - HEAD */+ method?: UptimeMonitorMethodEnum;+ /**+ * Seconds between checks, a whole number of minutes from 60 to 86400.+ * @minimum 60+ * @maximum 86400+ */+ interval_seconds?: number;+ /**+ * Seconds to wait for a response before the check fails, from 1 to 10.+ * @minimum 1+ * @maximum 10+ */+ timeout_seconds?: number;+ /** Whether checks run for this monitor. */+ enabled?: boolean;+ }+/*** Map of notification preferences. Keys include `plugin_disabled`, `all_weekly_report_disabled`, `project_weekly_digest_disabled`, `error_tracking_weekly_digest_project_enabled`, `web_analytics_weekly_digest_project_enabled`, `organization_member_join_email_disabled`, `data_pipeline_error_threshold` (number between 0.0 and 1.0), and other per-topic switches. Values are either booleans, or (for per-project/per-resource keys) a map of IDs to booleans. Only the keys you send are updated — other preferences stay as-is.*/@@ -136735,6 +136846,17 @@ export namespace Schemas {purpose?: UploadedMediaCreateBodyPurpose;};+ export type UptimeMonitorsListParams = {+ /**+ * Number of results to return per page.+ */+ limit?: number;+ /**+ * The initial index from which to return the results.+ */+ offset?: number;+ };+export type VisionAlertsListParams = {/*** Number of results to return per page.