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 appsignal import source (#71205)

Tom Owers3ab8a2f1fe8f
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 332ff6257814..4f4af8147c7b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -64,6 +64,7 @@ the row lists both.
| appfigures | HTTP | requests | ✅ |
| appfollow | HTTP | requests | ✅ |
| appsflyer | HTTP (CSV reports) | requests | ✅ |
+| appsignal | HTTP (REST + GraphQL) | requests | ✅ |
| asana | HTTP | requests | ✅ |
| ashby | HTTP | requests | ✅ |
| asknicely | HTTP | requests | ✅ |
@@ -574,7 +575,6 @@ doesn't conflict with concurrent PRs.
- amazon_sqs
- appcues
- apple_search_ads
-- appsignal
- appstack
- apptivo
- appwrite
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/appsignal.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/appsignal.py
new file mode 100644
index 000000000000..c774ea8e7180
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/appsignal.py
@@ -0,0 +1,430 @@
+import dataclasses
+from collections import deque
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, NoReturn, Optional
+
+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.appsignal.settings import (
+ APPSIGNAL_ENDPOINTS,
+ AppsignalEndpointConfig,
+)
+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.http.url_utils import (
+ redact_literal_values,
+ scrub_url,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+APPSIGNAL_BASE_URL = "https://appsignal.com"
+APPSIGNAL_GRAPHQL_URL = f"{APPSIGNAL_BASE_URL}/graphql"
+
+# Row cap per windowed REST fetch. The Samples/Markers APIs have no cursor pagination — only
+# `limit` plus time bounds — so windows holding more rows than this are bisected.
+WINDOW_PAGE_LIMIT = 200
+# Hard ceiling on a single fetch once a window can't be bisected further (1-second windows).
+MAX_LEAF_LIMIT = 10_000
+# Smallest leaf window a bisection can produce. A window must be at least twice this to split
+# (see `_get_windowed_rows`); anything narrower is fetched directly even if it's over the page limit.
+MIN_WINDOW_SECONDS = 2
+GRAPHQL_PAGE_SIZE = 100
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+# Default lower time bound for full-history walks — predates AppSignal's founding, and the
+# window bisection skips empty ranges in O(log) count probes.
+EARLIEST_START = int(datetime(2010, 1, 1, tzinfo=UTC).timestamp())
+
+
+class AppsignalRetryableError(Exception):
+ pass
+
+
+class AppsignalResumeConfig:
+ # REST windowed endpoints: epoch second the remaining walk starts from.
+ window_start: int | None = None
+ # GraphQL incident endpoints: offset of the next page to fetch.
+ offset: int | None = None
+
+
+def _to_epoch(value: Any) -> Optional[int]:
+ """Coerce an incremental cursor value to UNIX epoch seconds.
+
+ Samples carry `time` as an epoch integer; markers carry `created_at` as an ISO 8601
+ string; persisted watermarks come back as ints or datetimes depending on the field type.
+ """
+ if value is None or isinstance(value, bool):
+ return None
+ if isinstance(value, int):
+ return value
+ if isinstance(value, float):
+ return int(value)
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return int(dt.timestamp())
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp())
+ if isinstance(value, str):
+ try:
+ return int(value)
+ except ValueError:
+ pass
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ parsed = parsed.replace(tzinfo=UTC) if parsed.tzinfo is None else parsed
+ return int(parsed.timestamp())
+ return None
+
+
+def _raise_scrubbed_transport_error(error: requests.RequestException, api_token: str, context: str) -> NoReturn:
+ """Re-raise a transport failure with the API token stripped from the message.
+
+ requests' connection/timeout exceptions embed the full request URL — including the
+ `?token=` credential — in their text. Left intact that lands in job logs and
+ `latest_error`, so anyone able to view a failed import could recover the token.
+ Convert to a retryable error whose message has the credential (and its URL-encoded
+ forms) redacted; unlike `_raise_for_status_scrubbed`, this covers failures raised
+ before any response exists.
+ """
+ scrubbed = redact_literal_values(str(error), [api_token])
+ raise AppsignalRetryableError(f"AppSignal {context} transport error: {scrubbed}") from None
+
+
+def _raise_for_status_scrubbed(response: requests.Response) -> None:
+ """`raise_for_status` equivalent that never leaks the `token` query param.
+
+ AppSignal authenticates via a `?token=` URL param, and requests' own HTTPError message
+ embeds the full URL — which would surface the credential in job error messages and logs.
+ """
+ if response.ok:
+ return
+ kind = "Client Error" if response.status_code < 500 else "Server Error"
+ raise requests.HTTPError(
+ f"{response.status_code} {kind}: {response.reason} for url: {scrub_url(response.url or '')}",
+ response=response,
+ )
+
+
+@retry(
+ retry=retry_if_exception_type((AppsignalRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch_json(
+ session: requests.Session,
+ api_token: str,
+ url: str,
+ params: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ try:
+ response = session.get(
+ url,
+ params={**params, "token": api_token},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ except requests.RequestException as error:
+ _raise_scrubbed_transport_error(error, api_token, "API")
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AppsignalRetryableError(f"AppSignal API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ logger.error(f"AppSignal API error: status={response.status_code}, url={scrub_url(response.url or url)}")
+ _raise_for_status_scrubbed(response)
+
+ return response.json()
+
+
+@retry(
+ retry=retry_if_exception_type((AppsignalRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+)
+def _fetch_graphql(
+ session: requests.Session,
+ api_token: str,
+ query: str,
+ variables: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> dict[str, Any]:
+ try:
+ response = session.post(
+ APPSIGNAL_GRAPHQL_URL,
+ params={"token": api_token},
+ json={"query": query, "variables": variables},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ except requests.RequestException as error:
+ _raise_scrubbed_transport_error(error, api_token, "GraphQL")
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AppsignalRetryableError(f"AppSignal GraphQL error (retryable): status={response.status_code}")
+
+ if not response.ok:
+ logger.error(f"AppSignal GraphQL error: status={response.status_code}")
+ _raise_for_status_scrubbed(response)
+
+ body = response.json()
+ if body.get("errors"):
+ messages = "; ".join(str(error.get("message", error)) for error in body["errors"])
+ raise Exception(f"AppSignal GraphQL query failed: {messages}")
+
+ return body
+
+
+def validate_credentials(api_token: str, app_id: str) -> bool:
+ """One cheap probe that exercises both the personal token and the app ID."""
+ try:
+ response = make_tracked_session().get(
+ f"{APPSIGNAL_BASE_URL}/api/{app_id}/markers.json",
+ params={"token": api_token, "count_only": "true", "limit": "1"},
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def _incident_query(config: AppsignalEndpointConfig) -> str:
+ return (
+ "query IncidentsList($appId: String!, $limit: Int, $offset: Int, $order: IncidentOrderEnum) {\n"
+ " app(id: $appId) {\n"
+ f" {config.graphql_field}(limit: $limit, offset: $offset, order: $order) {{\n"
+ f"{config.graphql_selection}\n"
+ " }\n"
+ " }\n"
+ "}"
+ )
+
+
+def _get_incident_rows(
+ session: requests.Session,
+ api_token: str,
+ app_id: str,
+ config: AppsignalEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[AppsignalResumeConfig],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ assert config.graphql_field is not None
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset = resume.offset if resume is not None and resume.offset is not None else 0
+ if offset:
+ logger.debug(f"AppSignal: resuming {config.name} from offset={offset}")
+
+ query = _incident_query(config)
+
+ while True:
+ body = _fetch_graphql(
+ session,
+ api_token,
+ query,
+ # order=ID keeps offset pages stable while incidents update mid-walk.
+ {"appId": app_id, "limit": GRAPHQL_PAGE_SIZE, "offset": offset, "order": "ID"},
+ logger,
+ )
+ app = (body.get("data") or {}).get("app")
+ if app is None:
+ raise Exception("AppSignal app not found: check that the app ID matches your AppSignal app")
+ rows = app.get(config.graphql_field) or []
+ if not rows:
+ break
+
+ yield rows
+ offset += len(rows)
+
+ if len(rows) < GRAPHQL_PAGE_SIZE:
+ break
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it.
+ resumable_source_manager.save_state(AppsignalResumeConfig(offset=offset))
+
+
+def _window_count(
+ session: requests.Session,
+ api_token: str,
+ url: str,
+ config: AppsignalEndpointConfig,
+ since: int,
+ before: int,
+ logger: FilteringBoundLogger,
+) -> int:
+ data = _fetch_json(
+ session,
+ api_token,
+ url,
+ {**config.extra_params, config.since_param: since, config.before_param: before, "count_only": "true"},
+ logger,
+ )
+ return int(data.get("count") or 0)
+
+
+def _window_rows(
+ session: requests.Session,
+ api_token: str,
+ url: str,
+ config: AppsignalEndpointConfig,
+ since: int,
+ before: int,
+ limit: int,
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ data = _fetch_json(
+ session,
+ api_token,
+ url,
+ {**config.extra_params, config.since_param: since, config.before_param: before, "limit": limit},
+ logger,
+ )
+ rows = data.get(config.data_key or "", []) or []
+ return [row for row in rows if isinstance(row, dict)]
+
+
+def _get_windowed_rows(
+ session: requests.Session,
+ api_token: str,
+ app_id: str,
+ config: AppsignalEndpointConfig,
+ resumable_source_manager: ResumableSourceManager[AppsignalResumeConfig],
+ logger: FilteringBoundLogger,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk a legacy REST endpoint through ascending time windows.
+
+ The Samples/Markers APIs only expose `limit` plus lower/upper time bounds — no cursor —
+ and their sort order is undocumented. A `count_only` probe per window drives an
+ order-agnostic bisection: windows holding more than WINDOW_PAGE_LIMIT rows split in half
+ until each leaf fits in a single request. Leaves are yielded oldest-window-first with rows
+ sorted ascending on the cursor field, so `sort_mode="asc"` watermark checkpointing holds.
+ """
+ # Bound to a local so the None-narrowing survives into the sort lambda below.
+ cursor_field = config.cursor_field
+ assert config.path is not None and cursor_field is not None
+
+ url = f"{APPSIGNAL_BASE_URL}{config.path.format(app_id=app_id)}"
+ now = int(datetime.now(UTC).timestamp())
+
+ start = EARLIEST_START
+ if should_use_incremental_field:
+ watermark = _to_epoch(db_incremental_field_last_value)
+ if watermark is not None:
+ # 1-second overlap: the API's bound inclusivity is undocumented, so re-pull the
+ # boundary second and let merge dedupe on the primary key.
+ start = max(watermark - 1, EARLIEST_START)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.window_start is not None:
+ start = resume.window_start
+ logger.debug(f"AppSignal: resuming {config.name} from window_start={start}")
+
+ if start >= now:
+ return
+
+ windows: deque[tuple[int, int]] = deque([(start, now)])
+ while windows:
+ window_since, window_before = windows.popleft()
+ count = _window_count(session, api_token, url, config, window_since, window_before, logger)
+ if count == 0:
+ continue
+
+ # Require at least 2 * MIN_WINDOW_SECONDS before splitting: the right child's `mid - 1`
+ # overlap eats a second, so on a narrower window it would equal the parent and the walk
+ # would spin forever. Below that, fetch directly even if the window is over the page limit.
+ if count > WINDOW_PAGE_LIMIT and (window_before - window_since) >= 2 * MIN_WINDOW_SECONDS:
+ mid = (window_since + window_before) // 2
+ # The right child starts 1s early: if both bounds turn out exclusive, a row landing
+ # exactly on `mid` would otherwise fall between the halves. Dupes merge away.
+ windows.appendleft((max(mid - 1, window_since), window_before))
+ windows.appendleft((window_since, mid))
+ continue
+
+ limit = min(max(count, WINDOW_PAGE_LIMIT), MAX_LEAF_LIMIT)
+ if count > MAX_LEAF_LIMIT:
+ logger.warning(
+ f"AppSignal: {config.name} window [{window_since}, {window_before}] holds {count} rows, "
+ f"fetching only the first {MAX_LEAF_LIMIT}"
+ )
+ rows = _window_rows(session, api_token, url, config, window_since, window_before, limit, logger)
+ if not rows:
+ continue
+
+ rows.sort(key=lambda row: _to_epoch(row.get(cursor_field)) or 0)
+ yield rows
+
+ # Save AFTER yielding: everything before the next pending window is now complete, so a
+ # resumed attempt restarts the walk there and re-yields at most the last window.
+ next_start = windows[0][0] if windows else window_before
+ resumable_source_manager.save_state(AppsignalResumeConfig(window_start=next_start))
+
+
+def get_rows(
+ api_token: str,
+ app_id: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AppsignalResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = APPSIGNAL_ENDPOINTS[endpoint]
+ # One session reused across every request so urllib3 keeps the connection alive.
+ session = make_tracked_session()
+
+ if config.api == "graphql":
+ yield from _get_incident_rows(session, api_token, app_id, config, resumable_source_manager, logger)
+ return
+
+ yield from _get_windowed_rows(
+ session,
+ api_token,
+ app_id,
+ config,
+ resumable_source_manager,
+ logger,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+
+
+def appsignal_source(
+ api_token: str,
+ app_id: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AppsignalResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = APPSIGNAL_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ app_id=app_id,
+ 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,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=[config.primary_key],
+ 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/appsignal/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/canonical_descriptions.py
new file mode 100644
index 000000000000..41fcb47c527f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/canonical_descriptions.py
@@ -0,0 +1,102 @@
+"""Canonical, documentation-sourced descriptions for AppSignal endpoints and columns.
+
+Sourced from the official AppSignal API docs (https://docs.appsignal.com/api/) and the published
+GraphQL schema reference (https://appsignal.com/graphql/docs). Keyed by the endpoint names in
+`settings.py` `APPSIGNAL_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced
+AppSignal 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 = {
+ "exception_incidents": {
+ "description": "An exception incident: a group of similar errors tracked by AppSignal, with its occurrence count and triage state.",
+ "docs_url": "https://docs.appsignal.com/api/graphql/examples.html",
+ "columns": {
+ "id": "Unique identifier for the incident.",
+ "number": "Human-facing incident number, unique within the app.",
+ "count": "Total number of occurrences recorded for this incident.",
+ "state": "Triage state of the incident: OPEN, CLOSED, or WIP.",
+ "severity": "Severity assigned to the incident.",
+ "namespace": "Namespace the incident occurred in (e.g. web, background).",
+ "description": "Description of the incident.",
+ "actionNames": "Actions (controller/job names) the incident occurred in.",
+ "lastOccurredAt": "Time the incident last occurred.",
+ "createdAt": "Time the incident was first created.",
+ "updatedAt": "Time the incident was last updated.",
+ "exceptionName": "Class name of the exception (e.g. NoMethodError).",
+ "exceptionMessage": "Message of the most recent exception occurrence.",
+ "firstBacktraceLine": "First line of the exception backtrace.",
+ "errorGroupingStrategy": "Strategy AppSignal used to group errors into this incident.",
+ },
+ },
+ "performance_incidents": {
+ "description": "A performance incident: a slow action tracked by AppSignal, with its duration statistics and triage state.",
+ "docs_url": "https://docs.appsignal.com/api/graphql/examples.html",
+ "columns": {
+ "id": "Unique identifier for the incident.",
+ "number": "Human-facing incident number, unique within the app.",
+ "count": "Total number of occurrences recorded for this incident.",
+ "state": "Triage state of the incident: OPEN, CLOSED, or WIP.",
+ "severity": "Severity assigned to the incident.",
+ "namespace": "Namespace the incident occurred in (e.g. web, background).",
+ "description": "Description of the incident.",
+ "actionNames": "Actions (controller/job names) the incident occurred in.",
+ "lastOccurredAt": "Time the incident last occurred.",
+ "createdAt": "Time the incident was first created.",
+ "updatedAt": "Time the incident was last updated.",
+ "mean": "Mean duration of the action in milliseconds.",
+ "totalDuration": "Total time spent in the action in milliseconds.",
+ "hasNPlusOne": "Whether any of the last 5 deploys contained an N+1 query for this action.",
+ },
+ },
+ "deploy_markers": {
+ "description": "A deploy marker: an application release tracked by AppSignal, with the error rate observed while it was live.",
+ "docs_url": "https://docs.appsignal.com/api/markers.html",
+ "columns": {
+ "id": "Unique identifier for the marker.",
+ "created_at": "Time the deploy marker was created.",
+ "closed_at": "Time the next deploy superseded this one; null while it is the live deploy.",
+ "live_for": "Time this deploy was live, in seconds.",
+ "live_for_in_words": "Human-readable version of the live duration (e.g. 1d).",
+ "gem_version": "Version of the AppSignal integration that reported the deploy.",
+ "repository": "Git repository reference for the deploy.",
+ "revision": "Git revision of the deploy.",
+ "short_revision": "Abbreviated git revision of the deploy.",
+ "git_compare_url": "URL comparing this deploy's revision with the previous one.",
+ "user": "User who triggered the deploy.",
+ "exception_count": "Number of exceptions recorded while this deploy was live.",
+ "exception_rate": "Exception rate observed while this deploy was live.",
+ },
+ },
+ "error_samples": {
+ "description": "An individual error sample: one recorded occurrence of an exception, with request context.",
+ "docs_url": "https://docs.appsignal.com/api/samples.html",
+ "columns": {
+ "id": "Unique identifier for the sample.",
+ "action": "Action (controller/job name) the sample was recorded in.",
+ "path": "Request path of the sampled request.",
+ "duration": "Duration of the request in milliseconds; null for error samples.",
+ "status": "HTTP status code of the sampled request.",
+ "time": "Time the sample was recorded, as a UNIX timestamp.",
+ "is_exception": "Whether the sample is an error sample.",
+ "exception": "Exception details: name, message, and backtrace.",
+ },
+ },
+ "performance_samples": {
+ "description": "An individual performance sample: one recorded slow request, with timing breakdown.",
+ "docs_url": "https://docs.appsignal.com/api/samples.html",
+ "columns": {
+ "id": "Unique identifier for the sample.",
+ "action": "Action (controller/job name) the sample was recorded in.",
+ "path": "Request path of the sampled request.",
+ "duration": "Duration of the request in milliseconds.",
+ "status": "HTTP status code of the sampled request.",
+ "time": "Time the sample was recorded, as a UNIX timestamp.",
+ "is_exception": "Whether the sample is an error sample; null for performance samples.",
+ "exception": "Exception details; null for performance samples.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/settings.py
new file mode 100644
index 000000000000..feb7d42ba2f8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/settings.py
@@ -0,0 +1,147 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class AppsignalEndpointConfig:
+ name: str
+ # "rest" endpoints page through time windows on AppSignal's legacy JSON API;
+ # "graphql" endpoints walk the incident lists with limit/offset paging.
+ api: Literal["rest", "graphql"]
+ # REST-only: path template under appsignal.com with an {app_id} placeholder.
+ path: Optional[str] = None
+ # REST-only: key the list of rows is nested under in the response body.
+ data_key: Optional[str] = None
+ # REST-only: extra query params sent on every request (e.g. kind=deploy).
+ extra_params: dict[str, str] = field(default_factory=dict)
+ # REST-only: names of the lower/upper time-bound query params for windowing.
+ since_param: str = "since"
+ before_param: str = "before"
+ # GraphQL-only: the field on the App type holding the incident list, and the
+ # selection set to request for each row.
+ graphql_field: Optional[str] = None
+ graphql_selection: Optional[str] = None
+ primary_key: str = "id"
+ # Field the time windows filter on (REST) — also the sort key within a yielded window.
+ cursor_field: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable creation-time field used for datetime partitioning. Never an updated_at-style
+ # field, which would rewrite partitions on every sync.
+ partition_key: Optional[str] = None
+ # Rows are immutable once written (samples). Mutable resources (deploy markers keep
+ # accumulating exception counts) must merge instead of append.
+ immutable_rows: bool = False
+
+
+# Selection sets are built from AppSignal's published GraphQL schema reference
+# (https://appsignal.com/graphql/docs). `exceptionIncidents` args (limit/offset/order) come from
+# the documented ExceptionIncidentsQuery example; `performanceIncidents` mirrors the same
+# resolver signature per the schema reference.
+_INCIDENT_SHARED_FIELDS = """
+ id
+ number
+ count
+ state
+ severity
+ namespace
+ description
+ actionNames
+ lastOccurredAt
+ createdAt
+ updatedAt
+"""
+
+APPSIGNAL_ENDPOINTS: dict[str, AppsignalEndpointConfig] = {
+ # Exception incidents are mutable aggregates (count, state, lastOccurredAt keep changing)
+ # and the GraphQL list has no server-side timestamp filter, so they sync full refresh only.
+ "exception_incidents": AppsignalEndpointConfig(
+ name="exception_incidents",
+ api="graphql",
+ graphql_field="exceptionIncidents",
+ graphql_selection=_INCIDENT_SHARED_FIELDS
+ + """
+ exceptionName
+ exceptionMessage
+ firstBacktraceLine
+ errorGroupingStrategy
+""",
+ partition_key="createdAt",
+ ),
+ "performance_incidents": AppsignalEndpointConfig(
+ name="performance_incidents",
+ api="graphql",
+ graphql_field="performanceIncidents",
+ graphql_selection=_INCIDENT_SHARED_FIELDS
+ + """
+ mean
+ totalDuration
+ hasNPlusOne
+""",
+ partition_key="createdAt",
+ ),
+ # Deploy markers keep mutating after creation (closed_at, exception_count, exception_rate
+ # accumulate until the next deploy), so incremental syncs merge rather than append.
+ "deploy_markers": AppsignalEndpointConfig(
+ name="deploy_markers",
+ api="rest",
+ path="/api/{app_id}/markers.json",
+ data_key="markers",
+ extra_params={"kind": "deploy"},
+ since_param="from",
+ before_param="to",
+ cursor_field="created_at",
+ partition_key="created_at",
+ incremental_fields=[
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ # Samples are immutable once recorded; `time` is a UNIX epoch integer that the API's
+ # `since`/`before` params filter on server-side.
+ "error_samples": AppsignalEndpointConfig(
+ name="error_samples",
+ api="rest",
+ path="/api/{app_id}/samples/errors.json",
+ data_key="log_entries",
+ cursor_field="time",
+ partition_key="time",
+ immutable_rows=True,
+ incremental_fields=[
+ {
+ "label": "time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "time",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ ),
+ "performance_samples": AppsignalEndpointConfig(
+ name="performance_samples",
+ api="rest",
+ path="/api/{app_id}/samples/performance.json",
+ data_key="log_entries",
+ cursor_field="time",
+ partition_key="time",
+ immutable_rows=True,
+ incremental_fields=[
+ {
+ "label": "time",
+ "type": IncrementalFieldType.DateTime,
+ "field": "time",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ ),
+}
+
+ENDPOINTS = tuple(APPSIGNAL_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in APPSIGNAL_ENDPOINTS.items() if config.incremental_fields
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/source.py
index 42276819dac1..46d7f784ed4c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/source.py
@@ -1,30 +1,156 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-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.appsignal.appsignal import (
+ AppsignalResumeConfig,
+ appsignal_source,
+ validate_credentials as validate_appsignal_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.appsignal.settings import (
+ APPSIGNAL_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+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 AppsignalSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AppsignalSource(SimpleSource[AppsignalSourceConfig]):
+class AppsignalSource(ResumableSource[AppsignalSourceConfig, AppsignalResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.APPSIGNAL
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # app_id selects which AppSignal app the stored token is used against; changing it must
+ # require re-entering the secret so a preserved token can't be retargeted at another app.
+ return ["app_id"]
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://appsignal.com": "Your AppSignal personal API token is invalid or has been revoked. Copy a fresh token from your AppSignal personal settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://appsignal.com": "Your AppSignal personal API token does not have access to this app. Check the token and app ID, then reconnect.",
+ "404 Client Error: Not Found for url: https://appsignal.com": "AppSignal app not found. Check that the app ID matches the ID in your AppSignal app's URL.",
+ "AppSignal app not found": "AppSignal app not found. Check that the app ID matches the ID in your AppSignal app's URL.",
+ }
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.APPSIGNAL,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="AppSignal",
+ caption="""Enter your AppSignal personal API token and app ID to pull your AppSignal error and performance data into the PostHog Data warehouse.
+
+Your personal API token is in your [AppSignal personal settings](https://appsignal.com/users/edit) under "API key". The app ID is the identifier in your app's AppSignal URL: `https://appsignal.com/<organization>/sites/<app ID>`.""",
iconPath="/static/services/appsignal.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/appsignal",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["apm", "error tracking", "monitoring"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="Personal API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="app_id",
+ label="App ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.appsignal.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: AppsignalSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=INCREMENTAL_FIELDS.get(endpoint) is not None,
+ # Only immutable rows (samples) may append; deploy markers mutate after
+ # creation, so incremental syncs must merge on the primary key.
+ supports_append=APPSIGNAL_ENDPOINTS[endpoint].immutable_rows,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ 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: AppsignalSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_appsignal_credentials(config.api_token, config.app_id):
+ return True, None
+
+ return False, "Invalid AppSignal personal API token or app ID"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AppsignalResumeConfig]:
+ return ResumableSourceManager[AppsignalResumeConfig](inputs, AppsignalResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AppsignalSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AppsignalResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return appsignal_source(
+ api_token=config.api_token,
+ app_id=config.app_id,
+ 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,
+ incremental_field=inputs.incremental_field,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/tests/test_appsignal.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/tests/test_appsignal.py
new file mode 100644
index 000000000000..6ed1641dcfa4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/tests/test_appsignal.py
@@ -0,0 +1,339 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.appsignal.appsignal import (
+ AppsignalResumeConfig,
+ AppsignalRetryableError,
+ _fetch_graphql,
+ _fetch_json,
+ _to_epoch,
+ appsignal_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.appsignal.settings import (
+ APPSIGNAL_ENDPOINTS,
+ ENDPOINTS,
+)
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.appsignal.appsignal"
+
+
+def _make_manager(resume_state: AppsignalResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _response(payload: dict[str, Any], status_code: int = 200, url: str = "https://appsignal.com") -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.reason = {200: "OK", 401: "Unauthorized", 404: "Not Found"}.get(status_code, "Error")
+ response.url = url
+ response.json.return_value = payload
+ return response
+
+
+def _windowed_session(rows: list[dict[str, Any]], cursor: str = "time") -> mock.MagicMock:
+ """Fake a legacy REST endpoint: `since`/`from` and `before`/`to` bound the rows (both
+ inclusive), `count_only` returns the matching count, `limit` caps returned rows. Rows are
+ served newest-first to prove the walk doesn't rely on server ordering."""
+
+ def get(url: str, params: dict[str, Any] | None = None, timeout: Any = None) -> mock.MagicMock:
+ params = params or {}
+ since = params.get("since", params.get("from", 0))
+ before = params.get("before", params.get("to", 2**62))
+ matching = [row for row in rows if since <= row[cursor] <= before]
+ if params.get("count_only"):
+ return _response({"count": len(matching)})
+ matching = sorted(matching, key=lambda row: row[cursor], reverse=True)
+ return _response({"log_entries": matching[: int(params["limit"])], "markers": matching[: int(params["limit"])]})
+
+ session = mock.MagicMock()
+ session.get.side_effect = get
+ return session
+
+
+class TestToEpoch:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (None, None),
+ (True, None),
+ (1700000000, 1700000000),
+ (1700000000.9, 1700000000),
+ ("1700000000", 1700000000),
+ ("2023-11-14T22:13:20Z", 1700000000),
+ ("2023-11-14T22:13:20+00:00", 1700000000),
+ (datetime(2023, 11, 14, 22, 13, 20, tzinfo=UTC), 1700000000),
+ (date(2023, 11, 15), int(datetime(2023, 11, 15, tzinfo=UTC).timestamp())),
+ ("not-a-date", None),
+ ],
+ )
+ def test_to_epoch_values(self, value, expected):
+ assert _to_epoch(value) == expected
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize("status_code, expected", [(200, True), (401, False), (404, False), (500, False)])
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_status_mapping(self, mock_session, status_code, expected):
+ mock_session.return_value.get.return_value = _response({}, status_code=status_code)
+ assert validate_credentials("token", "app-id") is expected
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_swallows_exceptions(self, mock_session):
+ mock_session.return_value.get.side_effect = Exception("boom")
+ assert validate_credentials("token", "app-id") is False
+
+
+class TestWindowedRows:
+ def _now(self) -> int:
+ return int(datetime.now(UTC).timestamp())
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_single_window_yields_sorted_rows(self, mock_session):
+ base = self._now() - 10_000
+ rows = [{"id": "b", "time": base + 50}, {"id": "a", "time": base + 10}]
+ mock_session.return_value = _windowed_session(rows)
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "app-id", "error_samples", mock.MagicMock(), manager))
+
+ assert len(batches) == 1
+ # Server returned newest-first; the walk re-sorts ascending so asc watermarking holds.
+ assert [row["id"] for row in batches[0]] == ["a", "b"]
+ manager.save_state.assert_called_once()
+
+ @mock.patch(f"{MODULE}.WINDOW_PAGE_LIMIT", 2)
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_bisection_fetches_every_row_when_window_overflows(self, mock_session):
+ base = self._now() - 100_000
+ rows = [{"id": str(offset), "time": base + offset * 1000} for offset in range(7)]
+ mock_session.return_value = _windowed_session(rows)
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "app-id", "error_samples", mock.MagicMock(), manager))
+
+ yielded_ids = {row["id"] for batch in batches for row in batch}
+ assert yielded_ids == {str(offset) for offset in range(7)}
+ for batch in batches:
+ assert [row["time"] for row in batch] == sorted(row["time"] for row in batch)
+ # State advances after each yielded window.
+ assert manager.save_state.call_count == len(batches)
+
+ @mock.patch(f"{MODULE}.WINDOW_PAGE_LIMIT", 2)
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_over_limit_narrow_window_is_fetched_not_split_forever(self, mock_session):
+ # More rows than the page limit inside a span narrower than 2 * MIN_WINDOW_SECONDS.
+ # Bisection can't shrink such a window (the right child's `mid - 1` overlap makes it equal
+ # to its parent), so it must be fetched directly rather than split endlessly.
+ base = self._now() - 10
+ rows = [{"id": str(offset), "time": base + offset} for offset in range(3)]
+ session = _windowed_session(rows)
+ inner_get = session.get.side_effect
+ calls = {"n": 0}
+
+ def guarded_get(*args: Any, **kwargs: Any) -> mock.MagicMock:
+ calls["n"] += 1
+ assert calls["n"] <= 100, "windowed walk failed to terminate"
+ return inner_get(*args, **kwargs)
+
+ session.get.side_effect = guarded_get
+ mock_session.return_value = session
+
+ manager = _make_manager(AppsignalResumeConfig(window_start=base))
+ batches = list(get_rows("token", "app-id", "error_samples", mock.MagicMock(), manager))
+
+ assert {row["id"] for batch in batches for row in batch} == {"0", "1", "2"}
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_incremental_walk_starts_just_below_watermark(self, mock_session):
+ base = self._now() - 10_000
+ rows = [{"id": "old", "time": base}, {"id": "new", "time": base + 5000}]
+ mock_session.return_value = _windowed_session(rows)
+
+ manager = _make_manager()
+ batches = list(
+ get_rows(
+ "token",
+ "app-id",
+ "error_samples",
+ mock.MagicMock(),
+ manager,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=base + 4000,
+ )
+ )
+
+ assert {row["id"] for batch in batches for row in batch} == {"new"}
+ first_params = mock_session.return_value.get.call_args_list[0].kwargs["params"]
+ # 1s overlap below the watermark: bound inclusivity is undocumented upstream.
+ assert first_params["since"] == base + 4000 - 1
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_resumes_from_saved_window_start(self, mock_session):
+ base = self._now() - 10_000
+ rows = [{"id": "done", "time": base}, {"id": "pending", "time": base + 5000}]
+ mock_session.return_value = _windowed_session(rows)
+
+ manager = _make_manager(AppsignalResumeConfig(window_start=base + 1000))
+ batches = list(get_rows("token", "app-id", "error_samples", mock.MagicMock(), manager))
+
+ assert {row["id"] for batch in batches for row in batch} == {"pending"}
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_empty_range_yields_nothing_and_saves_no_state(self, mock_session):
+ mock_session.return_value = _windowed_session([])
+
+ manager = _make_manager()
+ assert list(get_rows("token", "app-id", "error_samples", mock.MagicMock(), manager)) == []
+ manager.save_state.assert_not_called()
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_deploy_markers_use_from_to_params_and_kind_filter(self, mock_session):
+ base = self._now() - 10_000
+ rows = [{"id": "m1", "created_at": base + 10}]
+ mock_session.return_value = _windowed_session(rows, cursor="created_at")
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "app-id", "deploy_markers", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["m1"]
+ params = mock_session.return_value.get.call_args_list[0].kwargs["params"]
+ assert params["kind"] == "deploy"
+ assert "from" in params and "to" in params
+ url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert url == "https://appsignal.com/api/app-id/markers.json"
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_auth_failure_error_message_does_not_leak_token(self, mock_session):
+ secret = "super-secret-token-value"
+ response = _response(
+ {}, status_code=401, url=f"https://appsignal.com/api/app-id/samples/errors.json?token={secret}"
+ )
+ mock_session.return_value.get.return_value = response
+
+ with pytest.raises(requests.HTTPError) as exc_info:
+ list(get_rows(secret, "app-id", "error_samples", mock.MagicMock(), _make_manager()))
+
+ message = str(exc_info.value)
+ assert secret not in message
+ assert message.startswith("401 Client Error: Unauthorized for url: https://appsignal.com")
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_transport_error_message_does_not_leak_token(self, mock_session):
+ # requests raises ConnectionError before any response exists, with the full request URL —
+ # token included — in its message. That path is not covered by the status-error scrubbing.
+ secret = "super-secret-token-value"
+ mock_session.return_value.get.side_effect = requests.ConnectionError(
+ f"HTTPSConnectionPool(host='appsignal.com', port=443): Max retries exceeded with url: "
+ f"/api/app-id/samples/errors.json?token={secret} (Caused by NewConnectionError())"
+ )
+
+ with (
+ mock.patch.object(_fetch_json.retry, "sleep", lambda _: None), # type: ignore[attr-defined]
+ pytest.raises(AppsignalRetryableError) as exc_info,
+ ):
+ list(get_rows(secret, "app-id", "error_samples", mock.MagicMock(), _make_manager()))
+
+ assert secret not in str(exc_info.value)
+
+
+class TestIncidentRows:
+ def _graphql_session(self, pages: list[list[dict[str, Any]]], field: str) -> mock.MagicMock:
+ session = mock.MagicMock()
+ session.post.side_effect = [_response({"data": {"app": {field: page}}}) for page in pages]
+ return session
+
+ @mock.patch(f"{MODULE}.GRAPHQL_PAGE_SIZE", 2)
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_pages_by_offset_until_short_page(self, mock_session):
+ pages = [[{"id": "1"}, {"id": "2"}], [{"id": "3"}]]
+ mock_session.return_value = self._graphql_session(pages, "exceptionIncidents")
+
+ manager = _make_manager()
+ batches = list(get_rows("token", "app-id", "exception_incidents", mock.MagicMock(), manager))
+
+ assert [row["id"] for batch in batches for row in batch] == ["1", "2", "3"]
+ offsets = [call.kwargs["json"]["variables"]["offset"] for call in mock_session.return_value.post.call_args_list]
+ assert offsets == [0, 2]
+ # State saved only after the full first page — the short page ends the walk.
+ manager.save_state.assert_called_once()
+ assert manager.save_state.call_args.args[0].offset == 2
+
+ @mock.patch(f"{MODULE}.GRAPHQL_PAGE_SIZE", 2)
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_resumes_from_saved_offset(self, mock_session):
+ mock_session.return_value = self._graphql_session([[{"id": "5"}]], "performanceIncidents")
+
+ manager = _make_manager(AppsignalResumeConfig(offset=4))
+ list(get_rows("token", "app-id", "performance_incidents", mock.MagicMock(), manager))
+
+ variables = mock_session.return_value.post.call_args_list[0].kwargs["json"]["variables"]
+ assert variables["offset"] == 4
+ assert variables["appId"] == "app-id"
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_missing_app_raises_clear_error(self, mock_session):
+ session = mock.MagicMock()
+ session.post.return_value = _response({"data": {"app": None}})
+ mock_session.return_value = session
+
+ with pytest.raises(Exception, match="AppSignal app not found"):
+ list(get_rows("token", "app-id", "exception_incidents", mock.MagicMock(), _make_manager()))
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_graphql_errors_raise(self, mock_session):
+ session = mock.MagicMock()
+ session.post.return_value = _response({"errors": [{"message": "Field 'nope' doesn't exist"}]})
+ mock_session.return_value = session
+
+ with pytest.raises(Exception, match="Field 'nope' doesn't exist"):
+ list(get_rows("token", "app-id", "exception_incidents", mock.MagicMock(), _make_manager()))
+
+ @mock.patch(f"{MODULE}.make_tracked_session")
+ def test_transport_error_message_does_not_leak_token(self, mock_session):
+ secret = "super-secret-token-value"
+ session = mock.MagicMock()
+ session.post.side_effect = requests.ConnectionError(
+ f"HTTPSConnectionPool(host='appsignal.com', port=443): Max retries exceeded with url: "
+ f"/graphql?token={secret} (Caused by NewConnectionError())"
+ )
+ mock_session.return_value = session
+
+ with (
+ mock.patch.object(_fetch_graphql.retry, "sleep", lambda _: None), # type: ignore[attr-defined]
+ pytest.raises(AppsignalRetryableError) as exc_info,
+ ):
+ list(get_rows(secret, "app-id", "exception_incidents", mock.MagicMock(), _make_manager()))
+
+ assert secret not in str(exc_info.value)
+
+
+class TestAppsignalSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = APPSIGNAL_ENDPOINTS[endpoint]
+ response = appsignal_source("token", "app-id", endpoint, mock.MagicMock(), _make_manager())
+
+ assert response.name == endpoint
+ assert response.primary_keys == [config.primary_key]
+ assert response.sort_mode == "asc"
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+
+ @pytest.mark.parametrize("config", list(APPSIGNAL_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_creation_fields(self, config):
+ if config.partition_key:
+ assert config.partition_key in {"created_at", "createdAt", "time"}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/tests/test_appsignal_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/tests/test_appsignal_source.py
new file mode 100644
index 000000000000..817f825019ae
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/appsignal/tests/test_appsignal_source.py
@@ -0,0 +1,157 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.appsignal.appsignal import AppsignalResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.appsignal.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.appsignal.source import AppsignalSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AppsignalSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestAppsignalSource:
+ def setup_method(self):
+ self.source = AppsignalSource()
+ self.team_id = 123
+ self.config = AppsignalSourceConfig(api_token="api-token", app_id="app-id")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.APPSIGNAL
+
+ def test_connection_host_fields_force_secret_reentry_on_app_change(self):
+ # Changing app_id retargets the stored token at a different AppSignal app, so the update
+ # serializer must require re-entering the secret — regressing this reopens that hole.
+ assert self.source.connection_host_fields == ["app_id"]
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Appsignal"
+ assert config.label == "AppSignal"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/appsignal.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_token", "app_id"]
+
+ def test_api_token_field_is_secret_password(self):
+ config = self.source.get_source_config
+ token_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.secret is True
+ assert token_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://appsignal.com/api/app-id/samples/errors.json",
+ "403 Client Error: Forbidden for url: https://appsignal.com/graphql",
+ "404 Client Error: Not Found for url: https://appsignal.com/api/app-id/markers.json",
+ "AppSignal app not found: check that the app ID matches your AppSignal app",
+ ],
+ )
+ def test_non_retryable_errors_match_permanent_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
+ "500 Server Error for url: https://appsignal.com/api/app-id/samples.json",
+ ],
+ )
+ def test_non_retryable_errors_do_not_match_unrelated(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ # Only the REST endpoints expose a server-side time filter; the GraphQL incident
+ # lists don't, so they stay full refresh.
+ assert incremental == {"deploy_markers", "error_samples", "performance_samples"}
+
+ def test_only_immutable_sample_tables_support_append(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["error_samples"].supports_append is True
+ assert schemas["performance_samples"].supports_append is True
+ # Deploy markers mutate after creation (exception counts accumulate) — merge only.
+ assert schemas["deploy_markers"].supports_append is False
+ assert schemas["exception_incidents"].supports_append is False
+
+ def test_incremental_schemas_advertise_their_fields(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["deploy_markers"].incremental_fields == INCREMENTAL_FIELDS["deploy_markers"]
+ assert schemas["error_samples"].incremental_fields == INCREMENTAL_FIELDS["error_samples"]
+ assert schemas["exception_incidents"].incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["error_samples"])
+ assert [schema.name for schema in schemas] == ["error_samples"]
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ (True, True, None),
+ (False, False, "Invalid AppSignal personal API token or app ID"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.appsignal.source.validate_appsignal_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(self.config.api_token, self.config.app_id)
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is AppsignalResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.appsignal.source.appsignal_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_appsignal_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "error_samples"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = 1700000000
+ inputs.incremental_field = "time"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ kwargs = mock_appsignal_source.call_args.kwargs
+ assert kwargs["api_token"] == "api-token"
+ assert kwargs["app_id"] == "app-id"
+ assert kwargs["endpoint"] == "error_samples"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == 1700000000
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.appsignal.source.appsignal_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_appsignal_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "exception_incidents"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = 1700000000
+ inputs.incremental_field = None
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_appsignal_source.call_args.kwargs["db_incremental_field_last_value"] is None
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 6becbf24df23..aeb287b0fca8 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
@@ -359,7 +359,8 @@ class AppsFlyerSourceConfig(config.Config):
@config.config
class AppsignalSourceConfig(config.Config):
- pass
+ api_token: str
+ app_id: str
@config.config