Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement opsgenie import source (#71178)

Tom Owersbd6436df1534
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 56359dd097dc..ba0fb9014614 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -331,6 +331,7 @@ the row lists both.
| openfda | HTTP | requests | ✅ |
| openrouter | HTTP | requests | ✅ |
| openweather | HTTP | requests | ✅ |
+| opsgenie | HTTP | requests | ✅ |
| ortto | HTTP | requests | ✅ |
| oura | HTTP | requests | ✅ |
| outbrain | HTTP | requests | ✅ |
@@ -789,7 +790,6 @@ doesn't conflict with concurrent PRs.
- onepassword
- onesignal
- open_data_dc
-- opsgenie
- opuswatch
- oracle
- oracle_ebs
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 1e801dc15ef7..9cb74718fee8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -2950,7 +2950,8 @@ class OpinionStageSourceConfig(config.Config):
@config.config
class OpsgenieSourceConfig(config.Config):
- pass
+ api_key: str
+ region: Literal["us", "eu"] = config.value(default="us")
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/canonical_descriptions.py
new file mode 100644
index 000000000000..aa9b9365eb90
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/canonical_descriptions.py
@@ -0,0 +1,129 @@
+"""Canonical, documentation-sourced descriptions for Opsgenie endpoints and columns.
+
+Sourced from the official Opsgenie REST API reference (https://docs.opsgenie.com/docs/api-overview).
+Keyed by the endpoint names in `settings.py` `OPSGENIE_ENDPOINTS`, which match the
+`ExternalDataSchema.name` of a synced Opsgenie table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "alerts": {
+ "description": "An alert created in Opsgenie by an integration, the API, or a user, representing an event that may need attention.",
+ "docs_url": "https://docs.opsgenie.com/docs/alert-api",
+ "columns": {
+ "id": "Unique identifier of the alert.",
+ "tinyId": "Short sequential id of the alert, unique within the account.",
+ "alias": "Client-defined identifier used to deduplicate alerts.",
+ "message": "Alert text shown to responders.",
+ "status": "Current status of the alert: open or closed.",
+ "acknowledged": "Whether the alert has been acknowledged.",
+ "isSeen": "Whether the alert has been seen by at least one responder.",
+ "tags": "Tags attached to the alert.",
+ "snoozed": "Whether the alert is currently snoozed.",
+ "snoozedUntil": "Time until which the alert is snoozed, if snoozed.",
+ "count": "Number of times the alert has occurred (deduplicated on alias).",
+ "lastOccurredAt": "Time the alert last occurred.",
+ "createdAt": "Time the alert was created; the incremental cursor.",
+ "updatedAt": "Time the alert was last updated.",
+ "source": "Source of the alert (e.g. the integration or user that created it).",
+ "owner": "Username of the alert's owner.",
+ "priority": "Priority of the alert: P1 (critical) through P5 (informational).",
+ "responders": "Teams, users, escalations, or schedules the alert was routed to.",
+ "integration": "The integration that created the alert.",
+ "report": "Acknowledge/close timing report for the alert.",
+ },
+ },
+ "incidents": {
+ "description": "An incident representing a service outage or degradation that requires coordinated response.",
+ "docs_url": "https://docs.opsgenie.com/docs/incident-api",
+ "columns": {
+ "id": "Unique identifier of the incident.",
+ "tinyId": "Short sequential id of the incident, unique within the account.",
+ "message": "Incident text shown to responders.",
+ "status": "Current status of the incident: open, resolved, or closed.",
+ "tags": "Tags attached to the incident.",
+ "createdAt": "Time the incident was created; the incremental cursor.",
+ "updatedAt": "Time the incident was last updated.",
+ "priority": "Priority of the incident: P1 (critical) through P5 (informational).",
+ "ownerTeam": "Name of the team that owns the incident.",
+ "responders": "Teams and users responding to the incident.",
+ "impactedServices": "Ids of the services impacted by the incident.",
+ "extraProperties": "Additional key-value details attached to the incident.",
+ },
+ },
+ "users": {
+ "description": "A user account in the Opsgenie organization.",
+ "docs_url": "https://docs.opsgenie.com/docs/user-api",
+ "columns": {
+ "id": "Unique identifier of the user.",
+ "username": "Email address the user signs in with.",
+ "fullName": "Full display name of the user.",
+ "role": "Role of the user (e.g. Admin, User, or a custom role).",
+ "blocked": "Whether the user account is blocked.",
+ "verified": "Whether the user's email address has been verified.",
+ "timeZone": "Time zone of the user.",
+ "locale": "Locale of the user.",
+ "userAddress": "Address details of the user.",
+ "createdAt": "Time the user account was created.",
+ },
+ },
+ "teams": {
+ "description": "A team that owns alerts, services, and on-call schedules.",
+ "docs_url": "https://docs.opsgenie.com/docs/team-api",
+ "columns": {
+ "id": "Unique identifier of the team.",
+ "name": "Name of the team.",
+ "description": "Description of the team.",
+ },
+ },
+ "schedules": {
+ "description": "An on-call schedule defining who is on call and when.",
+ "docs_url": "https://docs.opsgenie.com/docs/schedule-api",
+ "columns": {
+ "id": "Unique identifier of the schedule.",
+ "name": "Name of the schedule.",
+ "description": "Description of the schedule.",
+ "timezone": "Time zone the schedule's rotations are evaluated in.",
+ "enabled": "Whether the schedule is enabled.",
+ "ownerTeam": "The team that owns the schedule.",
+ "rotations": "Rotations that make up the schedule.",
+ },
+ },
+ "escalations": {
+ "description": "An escalation policy describing how unacknowledged alerts are escalated.",
+ "docs_url": "https://docs.opsgenie.com/docs/escalation-api",
+ "columns": {
+ "id": "Unique identifier of the escalation.",
+ "name": "Name of the escalation.",
+ "description": "Description of the escalation.",
+ "rules": "Ordered rules describing who is notified at each escalation step.",
+ "ownerTeam": "The team that owns the escalation.",
+ "repeat": "Repeat settings applied when the escalation completes without acknowledgment.",
+ },
+ },
+ "services": {
+ "description": "A business service used to track incident impact.",
+ "docs_url": "https://docs.opsgenie.com/docs/service-api",
+ "columns": {
+ "id": "Unique identifier of the service.",
+ "name": "Name of the service.",
+ "description": "Description of the service.",
+ "teamId": "Id of the team that owns the service.",
+ "tags": "Tags attached to the service.",
+ },
+ },
+ "integrations": {
+ "description": "An integration that creates alerts in Opsgenie (e.g. a monitoring tool or email integration).",
+ "docs_url": "https://docs.opsgenie.com/docs/integration-api",
+ "columns": {
+ "id": "Unique identifier of the integration.",
+ "name": "Name of the integration.",
+ "type": "Type of the integration (e.g. API, Email, or a vendor integration).",
+ "enabled": "Whether the integration is enabled.",
+ "teamId": "Id of the team the integration is assigned to, if any.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/opsgenie.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/opsgenie.py
new file mode 100644
index 000000000000..b997033b8e18
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/opsgenie.py
@@ -0,0 +1,268 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.opsgenie.settings import (
+ OPSGENIE_ENDPOINTS,
+ OpsgenieEndpointConfig,
+)
+
+OPSGENIE_BASE_URLS = {
+ "us": "https://api.opsgenie.com",
+ "eu": "https://api.eu.opsgenie.com",
+}
+
+# Opsgenie's max page size is 100; the default is 20.
+PAGE_SIZE = 100
+
+# The alert/incident search endpoints reject requests where `offset + limit` exceeds
+# 20,000. Instead of truncating there, we re-slice the search into a new createdAt
+# window starting from the last row we read (rows are sorted createdAt ascending, and
+# createdAt is immutable, so the slices tile the full history).
+MAX_SEARCH_RESULTS = 20_000
+
+# Retry/throttle settings kept near the top for easy tuning. Opsgenie rate limits are
+# token-bucket per API domain and return 429s; exponential backoff is the documented
+# recovery.
+RETRY_ATTEMPTS = 5
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class OpsgenieRetryableError(Exception):
+ pass
+
+
+class OpsgenieResumeConfig:
+ offset: int
+ window_start_ms: Optional[int] = None
+
+
+def _get_base_url(region: str) -> str:
+ return OPSGENIE_BASE_URLS.get(region, OPSGENIE_BASE_URLS["us"])
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"GenieKey {api_key}",
+ "Content-Type": "application/json",
+ }
+
+
+def _to_epoch_ms(value: Any) -> Optional[int]:
+ """Convert an incremental field value to epoch milliseconds for Opsgenie's search syntax."""
+ if isinstance(value, datetime):
+ utc_value = value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)
+ return int(utc_value.timestamp() * 1000)
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp() * 1000)
+ if isinstance(value, int | float):
+ return int(value)
+ if isinstance(value, str):
+ try:
+ return _to_epoch_ms(datetime.fromisoformat(value.replace("Z", "+00:00")))
+ except ValueError:
+ return None
+ return None
+
+
+def _parse_created_at_ms(item: dict[str, Any]) -> Optional[int]:
+ created_at = item.get("createdAt")
+ if not isinstance(created_at, str):
+ return None
+ try:
+ return _to_epoch_ms(datetime.fromisoformat(created_at.replace("Z", "+00:00")))
+ except ValueError:
+ return None
+
+
+def _build_params(
+ config: OpsgenieEndpointConfig,
+ offset: int,
+ window_start_ms: Optional[int],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"limit": PAGE_SIZE, "offset": offset}
+
+ if config.supports_search_window:
+ # createdAt is immutable, so an ascending sort means new rows append to the end
+ # and never shift pages we've already read. We send this on every sync (not just
+ # incremental ones) so full refreshes paginate over a stable ordering too.
+ params["sort"] = "createdAt"
+ params["order"] = "asc"
+
+ # A window opened mid-sync (after hitting the 20,000-result search cap) always
+ # starts at or after the incremental cursor, so it takes precedence.
+ start_ms = window_start_ms
+ if start_ms is None and should_use_incremental_field and db_incremental_field_last_value is not None:
+ start_ms = _to_epoch_ms(db_incremental_field_last_value)
+
+ if start_ms is not None:
+ # `>=` re-fetches rows sharing the boundary millisecond; merge dedupes on id.
+ params["query"] = f"createdAt >= {start_ms}"
+
+ return params
+
+
+def validate_credentials(api_key: str, region: str, endpoint: Optional[str] = None) -> tuple[bool, int, str | None]:
+ """Probe Opsgenie with a cheap single-row request.
+
+ Returns ``(ok, status_code, error_message)``. ``status_code`` is 0 on transport failure.
+ The caller decides how to treat 403 (valid key, missing access for the probed endpoint).
+ """
+ config = OPSGENIE_ENDPOINTS.get(endpoint) if endpoint else None
+ path = config.path if config else "/v2/users"
+ params = {"limit": 1} if config is None or config.paginated else {}
+ url = f"{_get_base_url(region)}{path}"
+ if params:
+ url = f"{url}?{urlencode(params)}"
+
+ try:
+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=10)
+ except requests.exceptions.RequestException as e:
+ return False, 0, str(e)
+
+ if response.status_code == 200:
+ return True, 200, None
+ if response.status_code == 401:
+ return False, 401, "Invalid Opsgenie API key"
+ if response.status_code == 403:
+ return False, 403, "Your Opsgenie API key does not have access to this resource"
+ if response.status_code == 422:
+ # Opsgenie rejects malformed keys with a 422 before checking auth.
+ return False, 422, "Your Opsgenie API key format is not valid"
+
+ try:
+ message = response.json().get("message", response.text)
+ except Exception:
+ message = response.text
+ return False, response.status_code, message
+
+
+def get_rows(
+ api_key: str,
+ region: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[OpsgenieResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[Any]:
+ config = OPSGENIE_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ base_url = _get_base_url(region)
+
+ @retry(
+ retry=retry_if_exception_type((OpsgenieRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch_page(params: dict[str, Any]) -> dict:
+ url = f"{base_url}{config.path}"
+ if params:
+ url = f"{url}?{urlencode(params)}"
+ response = make_tracked_session().get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise OpsgenieRetryableError(f"Opsgenie API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"Opsgenie API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ if not config.paginated:
+ data = fetch_page({})
+ items = data.get("data", [])
+ if items:
+ yield items
+ return
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset = resume_config.offset if resume_config is not None else 0
+ window_start_ms = resume_config.window_start_ms if resume_config is not None else None
+ if resume_config is not None:
+ logger.debug(f"Opsgenie: resuming {endpoint} from offset {offset}, window_start_ms {window_start_ms}")
+
+ while True:
+ params = _build_params(
+ config, offset, window_start_ms, should_use_incremental_field, db_incremental_field_last_value
+ )
+ data = fetch_page(params)
+
+ items = data.get("data", [])
+ if not items:
+ break
+
+ yield items
+
+ has_next = bool(data.get("paging", {}).get("next"))
+ if not has_next or len(items) < PAGE_SIZE:
+ break
+
+ next_offset = offset + PAGE_SIZE
+ if config.supports_search_window and next_offset + PAGE_SIZE > MAX_SEARCH_RESULTS:
+ # Approaching the 20,000-result search cap: open a new createdAt window from
+ # the last row read and restart the offset instead of truncating the sync.
+ new_window_start_ms = _parse_created_at_ms(items[-1])
+ if new_window_start_ms is None or new_window_start_ms == window_start_ms:
+ # Can't advance the window (missing createdAt, or >20k rows share one
+ # millisecond) — stop rather than loop on the same slice forever.
+ logger.warning(
+ f"Opsgenie: unable to advance search window for endpoint '{endpoint}' at offset "
+ f"{next_offset}; stopping pagination (results may be truncated)"
+ )
+ break
+ window_start_ms = new_window_start_ms
+ offset = 0
+ else:
+ offset = next_offset
+
+ # Save AFTER yielding so a crash re-fetches the last page; merge dedupes on primary key.
+ resumable_source_manager.save_state(OpsgenieResumeConfig(offset=offset, window_start_ms=window_start_ms))
+
+
+def opsgenie_source(
+ api_key: str,
+ region: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[OpsgenieResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = OPSGENIE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ region=region,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=[config.primary_key],
+ # Search-window endpoints request createdAt ascending; full-refresh endpoints
+ # replace wholesale, so ascending is correct everywhere.
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/settings.py
new file mode 100644
index 000000000000..b36686dd4490
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/settings.py
@@ -0,0 +1,77 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class OpsgenieEndpointConfig:
+ path: str # Path under the API base URL, including the API version, e.g. "/v2/alerts"
+ primary_key: str = "id"
+ partition_key: Optional[str] = None # Stable datetime field used to partition (never a mutable field)
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # True for endpoints that accept `limit`/`offset` pagination params. Endpoints left
+ # False (teams, schedules, escalations, integrations) return their full collection in
+ # a single response.
+ paginated: bool = False
+ # True only for the alert/incident search endpoints, which accept a `query` search
+ # param with `createdAt >= <epoch millis>` filtering AND a `sort=createdAt&order=asc`
+ # ordering we control. Both are required for safe incremental sync: the filter bounds
+ # the window, the sort guarantees a stable ascending watermark. These endpoints also
+ # hard-cap `offset + limit` at 20,000 per query, so backfills re-slice into new
+ # createdAt windows when they hit the cap.
+ supports_search_window: bool = False
+
+
+_CREATED_AT_INCREMENTAL: list[IncrementalField] = [
+ {
+ "label": "createdAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "createdAt",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+OPSGENIE_ENDPOINTS: dict[str, OpsgenieEndpointConfig] = {
+ "alerts": OpsgenieEndpointConfig(
+ path="/v2/alerts",
+ partition_key="createdAt",
+ incremental_fields=_CREATED_AT_INCREMENTAL,
+ paginated=True,
+ # Incremental sync only picks up newly *created* alerts — Opsgenie's search syntax
+ # can filter on createdAt but not updatedAt, so status changes to alerts created
+ # before the cursor are not re-fetched. Run periodic full refreshes for
+ # change capture.
+ supports_search_window=True,
+ ),
+ "incidents": OpsgenieEndpointConfig(
+ path="/v1/incidents",
+ partition_key="createdAt",
+ incremental_fields=_CREATED_AT_INCREMENTAL,
+ paginated=True,
+ supports_search_window=True,
+ ),
+ "users": OpsgenieEndpointConfig(
+ path="/v2/users",
+ paginated=True,
+ ),
+ "teams": OpsgenieEndpointConfig(
+ path="/v2/teams",
+ ),
+ "schedules": OpsgenieEndpointConfig(
+ path="/v2/schedules",
+ ),
+ "escalations": OpsgenieEndpointConfig(
+ path="/v2/escalations",
+ ),
+ "services": OpsgenieEndpointConfig(
+ path="/v1/services",
+ paginated=True,
+ ),
+ "integrations": OpsgenieEndpointConfig(
+ path="/v2/integrations",
+ ),
+}
+
+ENDPOINTS = tuple(OPSGENIE_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/source.py
index 1d17031031e9..4d13599b8724 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/source.py
@@ -1,19 +1,44 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import OpsgenieSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.opsgenie.opsgenie import (
+ OpsgenieResumeConfig,
+ opsgenie_source,
+ validate_credentials as validate_opsgenie_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.opsgenie.settings import (
+ ENDPOINTS,
+ OPSGENIE_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class OpsgenieSource(SimpleSource[OpsgenieSourceConfig]):
+class OpsgenieSource(ResumableSource[OpsgenieSourceConfig, OpsgenieResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.OPSGENIE
@@ -24,7 +49,113 @@ class OpsgenieSource(SimpleSource[OpsgenieSourceConfig]):
name=SchemaExternalDataSourceType.OPSGENIE,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Opsgenie",
+ caption="""Enter your Opsgenie API key to pull your Opsgenie data into the PostHog Data warehouse.
+
+You can create an API key in Opsgenie under **Settings → API key management**. The key needs **Read** access; the `integrations` table additionally requires **Configuration access**.
+
+Note that Atlassian has announced Opsgenie's end of support: its APIs are scheduled to shut down on April 5, 2027.""",
iconPath="/static/services/opsgenie.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/opsgenie",
+ keywords=["atlassian", "on-call", "alerting"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldSelectConfig(
+ name="region",
+ label="Region",
+ required=True,
+ defaultValue="us",
+ options=[
+ SourceFieldSelectConfigOption(label="US (api.opsgenie.com)", value="us"),
+ SourceFieldSelectConfigOption(label="EU (api.eu.opsgenie.com)", value="eu"),
+ ],
+ ),
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.opsgenie.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: OpsgenieSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=OPSGENIE_ENDPOINTS[endpoint].supports_search_window,
+ supports_append=False,
+ incremental_fields=OPSGENIE_ENDPOINTS[endpoint].incremental_fields,
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: OpsgenieSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ ok, status, error = validate_opsgenie_credentials(config.api_key, config.region, schema_name)
+ if ok:
+ return True, None
+
+ # A valid key may legitimately lack access for a specific endpoint (e.g. only
+ # `integrations` needs Configuration access). Accept 403 at source-create
+ # (schema_name is None) so users can connect with a key scoped to only the
+ # resources they want; re-raise it for per-schema checks.
+ if status == 403 and schema_name is None:
+ return True, None
+
+ return False, error
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ errors: dict[str, str | None] = {}
+ for host in ("https://api.opsgenie.com", "https://api.eu.opsgenie.com"):
+ errors[f"401 Client Error: Unauthorized for url: {host}"] = (
+ "Your Opsgenie API key is invalid or expired. Please generate a new key and reconnect."
+ )
+ errors[f"403 Client Error: Forbidden for url: {host}"] = (
+ "Your Opsgenie API key does not have the required access. Please check the key's access rights and try again."
+ )
+ return errors
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[OpsgenieResumeConfig]:
+ return ResumableSourceManager[OpsgenieResumeConfig](inputs, OpsgenieResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: OpsgenieSourceConfig,
+ resumable_source_manager: ResumableSourceManager[OpsgenieResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return opsgenie_source(
+ api_key=config.api_key,
+ region=config.region,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/tests/test_opsgenie.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/tests/test_opsgenie.py
new file mode 100644
index 000000000000..31db99106632
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/tests/test_opsgenie.py
@@ -0,0 +1,330 @@
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.opsgenie.opsgenie import (
+ PAGE_SIZE,
+ OpsgenieResumeConfig,
+ _build_params,
+ _get_headers,
+ _to_epoch_ms,
+ get_rows,
+ opsgenie_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.opsgenie.settings import OPSGENIE_ENDPOINTS
+
+OPSGENIE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.opsgenie.opsgenie"
+
+
+class FakeResumableManager:
+ """In-memory stand-in for ResumableSourceManager that records saved state."""
+
+ def __init__(self, resume_state: Optional[OpsgenieResumeConfig] = None) -> None:
+ self._resume_state = resume_state
+ self.saved_states: list[OpsgenieResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._resume_state is not None
+
+ def load_state(self) -> Optional[OpsgenieResumeConfig]:
+ return self._resume_state
+
+ def save_state(self, data: OpsgenieResumeConfig) -> None:
+ self.saved_states.append(data)
+
+
+def _mock_response(status_code: int = 200, body: Any = None, text: str = "") -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 300
+ response.text = text
+ response.json.return_value = body if body is not None else {}
+ if not response.ok:
+ error_response = requests.Response()
+ error_response.status_code = status_code
+ response.raise_for_status.side_effect = requests.HTTPError(
+ f"{status_code} Client Error: error for url: https://api.opsgenie.com", response=error_response
+ )
+ return response
+
+
+def _patch_session(get_side_effect: Any) -> Any:
+ session = MagicMock()
+ session.get.side_effect = get_side_effect
+ return patch(f"{OPSGENIE_MODULE}.make_tracked_session", return_value=session), session
+
+
+def _page(items: list[dict], has_next: bool) -> MagicMock:
+ body: dict[str, Any] = {"data": items}
+ if has_next:
+ body["paging"] = {"next": "https://api.opsgenie.com/v2/alerts?offset=next"}
+ return _mock_response(200, body=body)
+
+
+def _query_params(call: Any) -> dict[str, list[str]]:
+ return parse_qs(urlparse(call.args[0]).query)
+
+
+class TestToEpochMs:
+ @pytest.mark.parametrize(
+ "value,expected",
+ [
+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), 1772593094000),
+ (datetime(2026, 3, 4, 2, 58, 14), 1772593094000),
+ (date(2026, 3, 4), 1772582400000),
+ ("2026-03-04T02:58:14Z", 1772593094000),
+ ("2026-03-04T02:58:14+00:00", 1772593094000),
+ (1772593094000, 1772593094000),
+ ("not-a-date", None),
+ (None, None),
+ ],
+ )
+ def test_conversion(self, value: Any, expected: Optional[int]) -> None:
+ assert _to_epoch_ms(value) == expected
+
+
+class TestHeaders:
+ def test_genie_key_auth_header(self) -> None:
+ assert _get_headers("key_abc")["Authorization"] == "GenieKey key_abc"
+
+
+class TestBuildParams:
+ def test_search_endpoint_full_refresh_sends_stable_sort_without_query(self) -> None:
+ params = _build_params(
+ OPSGENIE_ENDPOINTS["alerts"],
+ offset=0,
+ window_start_ms=None,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ assert params == {"limit": PAGE_SIZE, "offset": 0, "sort": "createdAt", "order": "asc"}
+
+ def test_search_endpoint_incremental_sends_created_at_query(self) -> None:
+ params = _build_params(
+ OPSGENIE_ENDPOINTS["alerts"],
+ offset=200,
+ window_start_ms=None,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+ assert params["offset"] == 200
+ assert params["query"] == "createdAt >= 1767225600000"
+
+ def test_window_takes_precedence_over_incremental_cursor(self) -> None:
+ params = _build_params(
+ OPSGENIE_ENDPOINTS["alerts"],
+ offset=0,
+ window_start_ms=1800000000000,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+ assert params["query"] == "createdAt >= 1800000000000"
+
+ def test_non_search_endpoint_sends_no_sort_or_query(self) -> None:
+ params = _build_params(
+ OPSGENIE_ENDPOINTS["users"],
+ offset=0,
+ window_start_ms=None,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ )
+ assert params == {"limit": PAGE_SIZE, "offset": 0}
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code,expected_ok,expected_status",
+ [
+ (200, True, 200),
+ (401, False, 401),
+ (403, False, 403),
+ (422, False, 422),
+ (500, False, 500),
+ ],
+ )
+ def test_status_mapping(self, status_code: int, expected_ok: bool, expected_status: int) -> None:
+ ctx, _ = _patch_session([_mock_response(status_code, body={}, text="boom")])
+ with ctx:
+ ok, status, _error = validate_credentials("key", "us")
+ assert ok is expected_ok
+ assert status == expected_status
+
+ def test_transport_failure_returns_zero_status(self) -> None:
+ ctx, _ = _patch_session(requests.ConnectionError("no network"))
+ with ctx:
+ ok, status, error = validate_credentials("key", "us")
+ assert ok is False
+ assert status == 0
+ assert error == "no network"
+
+ def test_uses_endpoint_path_when_schema_given(self) -> None:
+ ctx, session = _patch_session([_mock_response(200)])
+ with ctx:
+ validate_credentials("key", "us", endpoint="incidents")
+ assert session.get.call_args.args[0].startswith("https://api.opsgenie.com/v1/incidents?")
+
+ @pytest.mark.parametrize(
+ "region,expected_host",
+ [
+ ("us", "https://api.opsgenie.com"),
+ ("eu", "https://api.eu.opsgenie.com"),
+ ("unknown", "https://api.opsgenie.com"),
+ ],
+ )
+ def test_region_selects_base_url(self, region: str, expected_host: str) -> None:
+ ctx, session = _patch_session([_mock_response(200)])
+ with ctx:
+ validate_credentials("key", region)
+ assert session.get.call_args.args[0].startswith(expected_host)
+
+
+class TestGetRows:
+ def test_paginates_and_yields_lists_of_dicts(self) -> None:
+ page1 = _page([{"id": str(i)} for i in range(PAGE_SIZE)], has_next=True)
+ page2 = _page([{"id": "last"}], has_next=False)
+ manager = FakeResumableManager()
+
+ ctx, session = _patch_session([page1, page2])
+ with ctx:
+ batches = list(get_rows("key", "us", "alerts", MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert len(batches) == 2
+ assert batches[1] == [{"id": "last"}]
+ assert session.get.call_count == 2
+ assert _query_params(session.get.call_args_list[1])["offset"] == [str(PAGE_SIZE)]
+
+ def test_saves_state_after_yielding_each_page(self) -> None:
+ page1 = _page([{"id": str(i)} for i in range(PAGE_SIZE)], has_next=True)
+ page2 = _page([{"id": "last"}], has_next=False)
+ manager = FakeResumableManager()
+
+ ctx, _ = _patch_session([page1, page2])
+ with ctx:
+ list(get_rows("key", "us", "alerts", MagicMock(), manager)) # type: ignore[arg-type]
+
+ # State is checkpointed once (the next offset) after the first page is yielded;
+ # the final page has no next link so no further checkpoint is written.
+ assert [s.offset for s in manager.saved_states] == [PAGE_SIZE]
+
+ def test_resumes_from_saved_offset_and_window(self) -> None:
+ manager = FakeResumableManager(
+ resume_state=OpsgenieResumeConfig(offset=PAGE_SIZE, window_start_ms=1700000000000)
+ )
+ page = _page([{"id": "x"}], has_next=False)
+
+ ctx, session = _patch_session([page])
+ with ctx:
+ list(get_rows("key", "us", "alerts", MagicMock(), manager)) # type: ignore[arg-type]
+
+ params = _query_params(session.get.call_args_list[0])
+ assert params["offset"] == [str(PAGE_SIZE)]
+ assert params["query"] == ["createdAt >= 1700000000000"]
+
+ def test_empty_page_stops_iteration(self) -> None:
+ page = _page([], has_next=True)
+ manager = FakeResumableManager()
+
+ ctx, session = _patch_session([page])
+ with ctx:
+ batches = list(get_rows("key", "us", "alerts", MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert batches == []
+ assert session.get.call_count == 1
+
+ def test_full_page_without_next_link_stops_iteration(self) -> None:
+ page = _page([{"id": str(i)} for i in range(PAGE_SIZE)], has_next=False)
+ manager = FakeResumableManager()
+
+ ctx, session = _patch_session([page])
+ with ctx:
+ batches = list(get_rows("key", "us", "alerts", MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert len(batches) == 1
+ assert session.get.call_count == 1
+
+ def test_non_paginated_endpoint_fetches_once_without_state(self) -> None:
+ page = _mock_response(200, body={"data": [{"id": "team_1"}]})
+ manager = FakeResumableManager()
+
+ ctx, session = _patch_session([page])
+ with ctx:
+ batches = list(get_rows("key", "us", "teams", MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert batches == [[{"id": "team_1"}]]
+ assert session.get.call_count == 1
+ assert manager.saved_states == []
+ assert "offset" not in _query_params(session.get.call_args_list[0])
+
+ def test_search_cap_reslices_into_new_created_at_window(self) -> None:
+ items = [{"id": str(i), "createdAt": "2026-01-02T00:00:00Z"} for i in range(PAGE_SIZE)]
+ page1 = _page(items, has_next=True)
+ page2 = _page([{"id": "in-window"}], has_next=False)
+ manager = FakeResumableManager()
+
+ ctx, session = _patch_session([page1, page2])
+ with ctx, patch(f"{OPSGENIE_MODULE}.MAX_SEARCH_RESULTS", PAGE_SIZE):
+ batches = list(get_rows("key", "us", "alerts", MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert len(batches) == 2
+ second_params = _query_params(session.get.call_args_list[1])
+ # The offset resets and the query re-anchors on the last row's createdAt instead
+ # of truncating at the 20,000-result cap.
+ assert second_params["offset"] == ["0"]
+ assert second_params["query"] == [f"createdAt >= {int(datetime(2026, 1, 2, tzinfo=UTC).timestamp() * 1000)}"]
+ assert manager.saved_states[-1].offset == 0
+ assert manager.saved_states[-1].window_start_ms == int(datetime(2026, 1, 2, tzinfo=UTC).timestamp() * 1000)
+
+ def test_search_cap_stops_when_window_cannot_advance(self) -> None:
+ window_ms = int(datetime(2026, 1, 2, tzinfo=UTC).timestamp() * 1000)
+ items = [{"id": str(i), "createdAt": "2026-01-02T00:00:00Z"} for i in range(PAGE_SIZE)]
+ page = _page(items, has_next=True)
+ manager = FakeResumableManager(resume_state=OpsgenieResumeConfig(offset=0, window_start_ms=window_ms))
+
+ ctx, session = _patch_session([page])
+ with ctx, patch(f"{OPSGENIE_MODULE}.MAX_SEARCH_RESULTS", PAGE_SIZE):
+ batches = list(get_rows("key", "us", "alerts", MagicMock(), manager)) # type: ignore[arg-type]
+
+ # Every row shares the current window's createdAt, so re-slicing would loop on the
+ # same page forever — the iterator yields what it has and stops instead.
+ assert len(batches) == 1
+ assert session.get.call_count == 1
+
+ def test_retries_on_429_then_succeeds(self) -> None:
+ rate_limited = _mock_response(429)
+ page = _page([{"id": "1"}], has_next=False)
+ manager = FakeResumableManager()
+
+ ctx, session = _patch_session([rate_limited, page])
+ with ctx, patch(f"{OPSGENIE_MODULE}.wait_exponential_jitter", return_value=lambda retry_state: 0):
+ batches = list(get_rows("key", "us", "alerts", MagicMock(), manager)) # type: ignore[arg-type]
+
+ assert batches == [[{"id": "1"}]]
+ assert session.get.call_count == 2
+
+
+class TestOpsgenieSourceResponse:
+ def test_alerts_partitioned_on_created_at(self) -> None:
+ response = opsgenie_source("key", "us", "alerts", MagicMock(), MagicMock())
+ assert response.primary_keys == ["id"]
+ assert response.partition_keys == ["createdAt"]
+ assert response.partition_mode == "datetime"
+ assert response.sort_mode == "asc"
+
+ def test_unpartitioned_endpoint_has_no_partition_settings(self) -> None:
+ response = opsgenie_source("key", "us", "users", MagicMock(), MagicMock())
+ assert response.primary_keys == ["id"]
+ assert response.partition_keys is None
+ assert response.partition_mode is None
+
+ @pytest.mark.parametrize("endpoint", list(OPSGENIE_ENDPOINTS.keys()))
+ def test_every_endpoint_builds_a_response(self, endpoint: str) -> None:
+ response = opsgenie_source("key", "us", endpoint, MagicMock(), MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == [OPSGENIE_ENDPOINTS[endpoint].primary_key]
+ assert callable(response.items)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/tests/test_opsgenie_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/tests/test_opsgenie_source.py
new file mode 100644
index 000000000000..6be86fc4b596
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/opsgenie/tests/test_opsgenie_source.py
@@ -0,0 +1,165 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.opsgenie.opsgenie import OpsgenieResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.opsgenie.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.opsgenie.source import OpsgenieSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType, IncrementalFieldType
+
+OPSGENIE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.opsgenie"
+
+
+class TestOpsgenieSource:
+ def setup_method(self) -> None:
+ self.source = OpsgenieSource()
+ self.config = MagicMock(api_key="key_123", region="us")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.OPSGENIE
+
+ def test_source_config_shape(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.label == "Opsgenie"
+ assert not config.unreleasedSource
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ assert config.fields is not None
+ assert len(config.fields) == 2
+
+ api_key_field = config.fields[0]
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ region_field = config.fields[1]
+ assert isinstance(region_field, SourceFieldSelectConfig)
+ assert region_field.name == "region"
+ assert region_field.defaultValue == "us"
+ assert {option.value for option in region_field.options} == {"us", "eu"}
+
+ def test_get_schemas_lists_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_only_alerts_and_incidents_support_incremental(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, team_id=1)}
+
+ for name in ("alerts", "incidents"):
+ assert schemas[name].supports_incremental is True, name
+ assert schemas[name].incremental_fields[0]["field"] == "createdAt", name
+ assert schemas[name].incremental_fields[0]["field_type"] == IncrementalFieldType.DateTime, name
+
+ for name in ENDPOINTS:
+ if name in ("alerts", "incidents"):
+ continue
+ assert schemas[name].supports_incremental is False, name
+ assert schemas[name].incremental_fields == [], name
+
+ def test_no_endpoint_supports_append(self) -> None:
+ # Opsgenie alerts and incidents mutate after creation (status, acknowledgement),
+ # so append-only mode is never offered.
+ schemas = self.source.get_schemas(self.config, team_id=1)
+ assert all(s.supports_append is False for s in schemas)
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=1, names=["alerts", "users"])
+ assert {s.name for s in schemas} == {"alerts", "users"}
+
+ @pytest.mark.parametrize(
+ "pattern",
+ [
+ "401 Client Error: Unauthorized for url: https://api.opsgenie.com",
+ "403 Client Error: Forbidden for url: https://api.opsgenie.com",
+ "401 Client Error: Unauthorized for url: https://api.eu.opsgenie.com",
+ "403 Client Error: Forbidden for url: https://api.eu.opsgenie.com",
+ ],
+ )
+ def test_non_retryable_errors_includes_pattern(self, pattern: str) -> None:
+ assert pattern in self.source.get_non_retryable_errors()
+
+ def test_validate_credentials_success(self) -> None:
+ with patch(f"{OPSGENIE_MODULE}.source.validate_opsgenie_credentials", return_value=(True, 200, None)):
+ assert self.source.validate_credentials(self.config, team_id=1) == (True, None)
+
+ @pytest.mark.parametrize(
+ "status,error",
+ [
+ (401, "Invalid Opsgenie API key"),
+ (422, "Your Opsgenie API key format is not valid"),
+ ],
+ )
+ def test_validate_credentials_invalid_key(self, status: int, error: str) -> None:
+ with patch(
+ f"{OPSGENIE_MODULE}.source.validate_opsgenie_credentials",
+ return_value=(False, status, error),
+ ):
+ ok, returned_error = self.source.validate_credentials(self.config, team_id=1)
+ assert ok is False
+ assert returned_error == error
+
+ def test_validate_credentials_accepts_403_at_source_create(self) -> None:
+ # A valid key may only have access to a subset of resources (e.g. no Configuration
+ # access for integrations); don't block connection.
+ with patch(
+ f"{OPSGENIE_MODULE}.source.validate_opsgenie_credentials",
+ return_value=(False, 403, "Your Opsgenie API key does not have access to this resource"),
+ ):
+ assert self.source.validate_credentials(self.config, team_id=1, schema_name=None) == (True, None)
+
+ def test_validate_credentials_rejects_403_for_specific_schema(self) -> None:
+ with patch(
+ f"{OPSGENIE_MODULE}.source.validate_opsgenie_credentials",
+ return_value=(False, 403, "Your Opsgenie API key does not have access to this resource"),
+ ):
+ ok, error = self.source.validate_credentials(self.config, team_id=1, schema_name="integrations")
+ assert ok is False
+ assert error == "Your Opsgenie API key does not have access to this resource"
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ inputs = MagicMock(team_id=1, job_id="job_1", logger=MagicMock())
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is OpsgenieResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ manager = MagicMock()
+ inputs = MagicMock(
+ schema_name="alerts",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00+00:00",
+ logger=MagicMock(),
+ )
+
+ with patch(f"{OPSGENIE_MODULE}.source.opsgenie_source") as mock_source:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "key_123"
+ assert kwargs["region"] == "us"
+ assert kwargs["endpoint"] == "alerts"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00+00:00"
+
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self) -> None:
+ manager = MagicMock()
+ inputs = MagicMock(
+ schema_name="users",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value="2026-01-01T00:00:00+00:00",
+ logger=MagicMock(),
+ )
+
+ with patch(f"{OPSGENIE_MODULE}.source.opsgenie_source") as mock_source:
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["should_use_incremental_field"] is False
+ assert kwargs["db_incremental_field_last_value"] is None