:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement google_play_console source (#73757)
Tom Owersa54d80ac9d26
diff --git a/frontend/public/services/google_play_console.png b/frontend/public/services/google_play_console.pngindex becb10946bdf..ee08eaaca09a 100644Binary files a/frontend/public/services/google_play_console.png and b/frontend/public/services/google_play_console.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 841511f8ee7e..53e9588f5873 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -298,6 +298,7 @@ the row lists both.| google_ads | gRPC | google-ads (googleads.client) | ✅ || google_analytics | HTTP | requests (`AuthorizedSession` + `TrackedHTTPAdapter`) | ✅ || google_pagespeed_insights | HTTP | requests | ✅ |+| google_play_console | HTTP | requests | ✅ || google_sheets | HTTP (vendor SDK) | gspread | ✅ || google_webfonts | HTTP | requests | ✅ || grafana | HTTP | requests | ✅ |@@ -1044,7 +1045,6 @@ doesn't conflict with concurrent PRs.- google_drive- google_forms- google_merchant_center-- google_play_console- google_tasks- google_workspace_admin_reports- greythrdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googleplayconsole.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googleplayconsole.pyindex 9c302a8a5430..25eef6d941e0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googleplayconsole.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/googleplayconsole.py@@ -4,6 +4,15 @@from products.warehouse_sources.backend.temporal.data_imports.sources.common import config+class GooglePlayConsoleKeyFileConfig(config.Config):+ client_email: str+ private_key: str+ private_key_id: str+ token_uri: str++@config.configclass GooglePlayConsoleSourceConfig(config.Config):- pass+ key_file: GooglePlayConsoleKeyFileConfig+ app_package_names: str | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/canonical_descriptions.pynew file mode 100644index 000000000000..bd64b69fdc62--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/canonical_descriptions.py@@ -0,0 +1,199 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Columns every vitals metric-set table carries: the app and window the row aggregates, plus the+# version slice it was requested with.+_TIMELINE_COLUMNS: dict[str, str] = {+ "app": "Package name of the app the row belongs to (e.g. com.example.app).",+ "date": "Calendar day the aggregate covers, in Play's default reporting time zone.",+ "startTime": "Inclusive start of the aggregation window.",+ "endTime": "Exclusive end of the aggregation window.",+ "versionCode": "Version code of the app build the row is sliced by.",+ "distinctUsers": "Count of distinct users the metrics are computed over, after Play's privacy thresholding.",+}++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "crash_rate": {+ "description": (+ "Daily Android vitals crash rate: the fraction of distinct users who experienced at least "+ "one crash, sliced by app version."+ ),+ "docs_url": "https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.crashrate",+ "columns": {+ **_TIMELINE_COLUMNS,+ "crashRate": "Fraction of distinct users who had at least one crash on this day.",+ "crashRate7dUserWeighted": "Crash rate over the trailing 7 days, weighted by each day's distinct users.",+ "crashRate28dUserWeighted": "Crash rate over the trailing 28 days, weighted by each day's distinct users.",+ "userPerceivedCrashRate": "Fraction of distinct users who had at least one crash while using the app.",+ "userPerceivedCrashRate7dUserWeighted": "User-perceived crash rate over the trailing 7 days.",+ "userPerceivedCrashRate28dUserWeighted": "User-perceived crash rate over the trailing 28 days.",+ },+ },+ "anr_rate": {+ "description": (+ "Daily Android vitals ANR rate: the fraction of distinct users who experienced at least one "+ "application-not-responding event, sliced by app version."+ ),+ "docs_url": "https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.anrrate",+ "columns": {+ **_TIMELINE_COLUMNS,+ "anrRate": "Fraction of distinct users who had at least one ANR on this day.",+ "anrRate7dUserWeighted": "ANR rate over the trailing 7 days, weighted by each day's distinct users.",+ "anrRate28dUserWeighted": "ANR rate over the trailing 28 days, weighted by each day's distinct users.",+ "userPerceivedAnrRate": "Fraction of distinct users who had at least one ANR while using the app.",+ "userPerceivedAnrRate7dUserWeighted": "User-perceived ANR rate over the trailing 7 days.",+ "userPerceivedAnrRate28dUserWeighted": "User-perceived ANR rate over the trailing 28 days.",+ },+ },+ "excessive_wakeup_rate": {+ "description": (+ "Daily rate of sessions that woke the device more than twice an hour with alarms, sliced by app version."+ ),+ "docs_url": (+ "https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.excessivewakeuprate"+ ),+ "columns": {+ **_TIMELINE_COLUMNS,+ "excessiveWakeupRate": "Fraction of distinct users whose sessions triggered excessive wakeups.",+ "excessiveWakeupRate7dUserWeighted": "Excessive wakeup rate over the trailing 7 days.",+ "excessiveWakeupRate28dUserWeighted": "Excessive wakeup rate over the trailing 28 days.",+ },+ },+ "stuck_background_wakelock_rate": {+ "description": (+ "Daily rate of sessions that held a background wakelock for longer than an hour, sliced by app version."+ ),+ "docs_url": (+ "https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/"+ "vitals.stuckbackgroundwakelockrate"+ ),+ "columns": {+ **_TIMELINE_COLUMNS,+ "stuckBgWakelockRate": "Fraction of distinct users whose sessions held a stuck background wakelock.",+ "stuckBgWakelockRate7dUserWeighted": "Stuck background wakelock rate over the trailing 7 days.",+ "stuckBgWakelockRate28dUserWeighted": "Stuck background wakelock rate over the trailing 28 days.",+ },+ },+ "slow_start_rate": {+ "description": "Daily rate of app starts Play considers slow, sliced by start type and app version.",+ "docs_url": "https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.slowstartrate",+ "columns": {+ **_TIMELINE_COLUMNS,+ "startType": "Start type the row is sliced by: cold, warm, or hot start.",+ "startTypeLabel": "Human-readable label for the start type.",+ "slowStartRate": "Fraction of distinct users who experienced a slow start of this type.",+ "slowStartRate7dUserWeighted": "Slow start rate over the trailing 7 days.",+ "slowStartRate28dUserWeighted": "Slow start rate over the trailing 28 days.",+ },+ },+ "slow_rendering_rate": {+ "description": (+ "Daily rate of sessions with slow frame rendering, at both the 20fps and 30fps thresholds, "+ "sliced by app version."+ ),+ "docs_url": (+ "https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.slowrenderingrate"+ ),+ "columns": {+ **_TIMELINE_COLUMNS,+ "slowRenderingRate20Fps": "Fraction of distinct users whose sessions rendered slowly at the 20fps threshold.",+ "slowRenderingRate20Fps7dUserWeighted": "Slow rendering rate (20fps) over the trailing 7 days.",+ "slowRenderingRate20Fps28dUserWeighted": "Slow rendering rate (20fps) over the trailing 28 days.",+ "slowRenderingRate30Fps": "Fraction of distinct users whose sessions rendered slowly at the 30fps threshold.",+ "slowRenderingRate30Fps7dUserWeighted": "Slow rendering rate (30fps) over the trailing 7 days.",+ "slowRenderingRate30Fps28dUserWeighted": "Slow rendering rate (30fps) over the trailing 28 days.",+ },+ },+ "lmk_rate": {+ "description": (+ "Daily rate of low-memory kills the user perceived, meaning the app was killed while in use, "+ "sliced by app version."+ ),+ "docs_url": "https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.lmkrate",+ "columns": {+ **_TIMELINE_COLUMNS,+ "userPerceivedLmkRate": "Fraction of distinct users whose foreground app was killed for low memory.",+ "userPerceivedLmkRate7dUserWeighted": "User-perceived low-memory kill rate over the trailing 7 days.",+ "userPerceivedLmkRate28dUserWeighted": "User-perceived low-memory kill rate over the trailing 28 days.",+ },+ },+ "error_counts": {+ "description": "Daily count of error reports Play received, sliced by report type and app version.",+ "docs_url": (+ "https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.errors.counts"+ ),+ "columns": {+ **_TIMELINE_COLUMNS,+ "reportType": "Type of error the count covers: crash, ANR, or non-fatal.",+ "reportTypeLabel": "Human-readable label for the report type.",+ "errorReportCount": "Number of error reports Play received on this day for the slice.",+ },+ },+ "apps": {+ "description": "Apps the connected service account is allowed to report on.",+ "docs_url": "https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/apps/search",+ "columns": {+ "name": "Resource name of the app, in the form apps/{package_name}.",+ "packageName": "Package name of the app (e.g. com.example.app).",+ "displayName": "Title of the app as shown on Google Play.",+ },+ },+ "error_issues": {+ "description": (+ "Clustered error issues (groups of similar crash, ANR, or non-fatal reports) with their report "+ "and user counts over the synced window."+ ),+ "docs_url": (+ "https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.errors.issues/search"+ ),+ "columns": {+ "name": "Resource name of the issue, in the form apps/{app}/errorIssues/{id}.",+ "app": "Package name of the app the issue belongs to.",+ "type": "Issue type: crash, ANR, or non-fatal error.",+ "cause": "Cause of the issue, usually the exception or signal that triggered it.",+ "location": "Code location the issue was attributed to.",+ "errorReportCount": "Number of error reports in this issue over the requested window.",+ "distinctUsers": "Number of distinct users affected over the requested window.",+ "distinctUsersPercent": "Share of distinct users affected, relative to the app's user base.",+ "lastErrorReportTime": "Time of the most recent report in this issue.",+ "firstAppVersion": "Earliest app version the issue was reported on.",+ "lastAppVersion": "Latest app version the issue was reported on.",+ "firstOsVersion": "Earliest Android version the issue was reported on.",+ "lastOsVersion": "Latest Android version the issue was reported on.",+ "issueUri": "Deep link to the issue in Play Console.",+ "sampleErrorReports": "Resource names of a few example reports in this issue.",+ "annotations": "Play's automated annotations explaining likely causes and fixes.",+ },+ },+ "error_reports": {+ "description": "Individual crash, ANR, and non-fatal error reports, including stack traces and device details.",+ "docs_url": (+ "https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/vitals.errors.reports/search"+ ),+ "columns": {+ "name": "Resource name of the report, unique across the app.",+ "app": "Package name of the app the report belongs to.",+ "type": "Report type: crash, ANR, or non-fatal error.",+ "eventTime": "Time the error occurred on the device.",+ "reportText": "Stack trace or ANR trace captured with the report.",+ "issue": "Resource name of the error issue this report was clustered into.",+ "deviceModel": "Device the report came from.",+ "osVersion": "Android version the report came from.",+ "appVersion": "App version the report came from.",+ "vcsInformation": "Version control revision the app build was made from, when the developer supplied it.",+ },+ },+ "anomalies": {+ "description": "Metric anomalies Play detected by comparing a metric against its expected range.",+ "docs_url": "https://developers.google.com/play/developer/reporting/reference/rest/v1beta1/anomalies/list",+ "columns": {+ "name": "Resource name of the anomaly.",+ "app": "Package name of the app the anomaly belongs to.",+ "metricSet": "Metric set the anomalous metric belongs to (e.g. crash rate).",+ "timelineSpec": "Aggregation period and time range the anomaly was detected over.",+ "dimensions": "Dimension values that identify the slice the anomaly was detected in.",+ "metric": "The anomalous metric, with its observed and expected values.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/google_play_console.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/google_play_console.pynew file mode 100644index 000000000000..4d80c7a88ad7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/google_play_console.py@@ -0,0 +1,722 @@+import time+import datetime as dt+from collections.abc import Iterable, Iterator+from dataclasses import field+from typing import Any++import jwt+import requests+import structlog+from structlog.types import FilteringBoundLogger++from posthog.dataclasses import frozen++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.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.google_play_console.settings import (+ AGGREGATION_PERIOD,+ ERROR_HISTORY_DAYS,+ LIST_ENDPOINTS,+ METRIC_SET_HISTORY_DAYS,+ METRIC_SET_WINDOW_DAYS,+ METRIC_SETS,+ PRIMARY_KEYS,+ ListEndpoint,+ MetricSetEndpoint,+)++logger = structlog.get_logger(__name__)++API_HOST = "https://playdeveloperreporting.googleapis.com"+PLAY_REPORTING_SCOPE = "https://www.googleapis.com/auth/playdeveloperreporting"+DEFAULT_TOKEN_URI = "https://oauth2.googleapis.com/token"+JWT_BEARER_GRANT = "urn:ietf:params:oauth:grant-type:jwt-bearer"++REQUEST_TIMEOUT_SECONDS = 120+# Google caps service-account assertions (and the tokens minted from them) at one hour.+TOKEN_TTL_SECONDS = 3600+TOKEN_EXPIRY_SKEW_SECONDS = 60++METRIC_PAGE_SIZE = 10000+LIST_PAGE_SIZE = 100+APP_PAGE_SIZE = 50++# Vitals are published with a delay; used only when a metric set reports no daily freshness.+FRESHNESS_LAG_DAYS = 2+++class GooglePlayConsoleAuthError(Exception):+ """The service account key could not be exchanged for a Play Reporting access token."""+++@frozen+class ServiceAccountKey:+ """The fields the source needs out of an uploaded Google service account JSON key."""++ client_email: str+ # Kept out of `repr` so a traceback that prints the key object doesn't carry the PEM.+ private_key: str = field(repr=False)+ private_key_id: str | None = None+ token_uri: str | None = None+++@frozen+class GooglePlayConsoleResumeConfig:+ # Package name currently being fetched — apps are walked in sorted order, so anything+ # sorting before this one has already been synced.+ app: str = ""+ # ISO date of the next window to fetch for `app` (metric sets and day-windowed endpoints).+ date: str | None = None+ # Next page token within the current app/day.+ page_token: str | None = None+++def _normalize_private_key(private_key: str) -> str:+ """Restore real newlines in a PEM key that arrived with escaped ones.++ Service account JSON stores the key with `\\n` escapes. Parsed JSON has real newlines, but+ a key pasted or round-tripped through a form field often keeps the literal backslash-n,+ which the PEM loader rejects.+ """+ return private_key.replace("\\n", "\n").strip() + "\n"+++def _today() -> dt.date:+ return dt.date.today()+++def _date_message(value: dt.date) -> dict[str, int]:+ return {"year": value.year, "month": value.month, "day": value.day}+++def _date_from_message(message: Any) -> dt.date | None:+ if not isinstance(message, dict):+ return None+ try:+ return dt.date(int(message["year"]), int(message["month"]), int(message["day"]))+ except (KeyError, TypeError, ValueError):+ return None+++def _datetime_from_message(message: Any) -> dt.datetime | None:+ """Convert a `google.type.DateTime` body into a naive UTC datetime."""+ day = _date_from_message(message)+ if day is None or not isinstance(message, dict):+ return None+ try:+ return dt.datetime(+ day.year,+ day.month,+ day.day,+ int(message.get("hours") or 0),+ int(message.get("minutes") or 0),+ int(message.get("seconds") or 0),+ )+ except (TypeError, ValueError):+ return None+++def _coerce_datetime(value: Any) -> dt.datetime | None:+ """Normalize a Play timestamp to a naive UTC datetime, whichever shape it arrives in.++ The Reporting API returns some timestamps as `google.type.DateTime` objects and others as+ RFC 3339 strings. A column has to hold one type, so unparseable values become null rather+ than leaking a string into a timestamp column.+ """+ if isinstance(value, dt.datetime):+ parsed = value+ elif isinstance(value, dict):+ return _datetime_from_message(value)+ elif isinstance(value, str):+ try:+ parsed = dt.datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return None+ else:+ return None++ if parsed.tzinfo is not None:+ parsed = parsed.astimezone(dt.UTC).replace(tzinfo=None)+ return parsed+++def _dimension_value(dimension: dict[str, Any]) -> Any:+ if "int64Value" in dimension:+ try:+ return int(dimension["int64Value"])+ except (TypeError, ValueError):+ return None+ value = dimension.get("stringValue")+ return value if value is not None else dimension.get("valueLabel")+++def _metric_value(metric: dict[str, Any]) -> float | None:+ """Metric values arrive as decimal/int wrappers; keep every metric column a float."""+ raw: Any = None+ decimal = metric.get("decimalValue")+ if isinstance(decimal, dict):+ raw = decimal.get("value")+ elif "int64Value" in metric:+ raw = metric["int64Value"]+ elif "doubleValue" in metric:+ raw = metric["doubleValue"]+ if raw is None:+ return None+ try:+ return float(raw)+ except (TypeError, ValueError):+ return None+++def _interval_params(start: dt.datetime, end: dt.datetime) -> dict[str, str]:+ """Query params for a `DateTimeInterval` filter (start inclusive, end exclusive)."""+ params: dict[str, str] = {}+ for prefix, value in (("interval.startTime", start), ("interval.endTime", end)):+ params[f"{prefix}.year"] = str(value.year)+ params[f"{prefix}.month"] = str(value.month)+ params[f"{prefix}.day"] = str(value.day)+ params[f"{prefix}.hours"] = str(value.hour)+ params[f"{prefix}.minutes"] = str(value.minute)+ params[f"{prefix}.seconds"] = str(value.second)+ params[f"{prefix}.timeZone.id"] = "UTC"+ return params+++class GooglePlayConsoleClient:+ """Play Developer Reporting client: mints service-account tokens and issues requests."""++ def __init__(self, key: ServiceAccountKey, api_version: str, logger: FilteringBoundLogger) -> None:+ self._client_email = key.client_email+ self._private_key = _normalize_private_key(key.private_key)+ self._private_key_id = key.private_key_id+ # Always mint tokens against Google's fixed endpoint. Never POST to the uploaded key's+ # `token_uri`: a source-write user could point it at an internal host (SSRF) and read back+ # part of the response. Real Google keys always target this URL anyway.+ self._token_uri = DEFAULT_TOKEN_URI+ self._base_url = f"{API_HOST}/{api_version}"+ self._logger = logger+ # Data responses carry customer content (crash stack traces, device details, VCS info) that+ # the name-based sample scrubbers can't recognise, so keep them out of HTTP sample capture.+ self._session = make_tracked_session(redact_values=(self._private_key,), capture=False)+ # The token exchange posts a signed assertion and receives an access token; keep both+ # out of sample capture, where a generic field name wouldn't be scrubbed.+ self._auth_session = make_tracked_session(redact_values=(self._private_key,), capture=False)+ self._access_token: str | None = None+ self._token_expires_at = 0.0++ def _signed_assertion(self, issued_at: int) -> str:+ headers = {"kid": self._private_key_id} if self._private_key_id else None+ try:+ return jwt.encode(+ {+ "iss": self._client_email,+ "scope": PLAY_REPORTING_SCOPE,+ "aud": self._token_uri,+ "iat": issued_at,+ "exp": issued_at + TOKEN_TTL_SECONDS,+ },+ self._private_key,+ algorithm="RS256",+ headers=headers,+ )+ except Exception as e:+ raise GooglePlayConsoleAuthError(+ "Could not sign a token with the uploaded service account key. "+ "Please upload the JSON key file Google Cloud generated, unmodified."+ ) from e++ def _mint_access_token(self) -> str:+ issued_at = int(time.time())+ response = self._auth_session.post(+ self._token_uri,+ data={"grant_type": JWT_BEARER_GRANT, "assertion": self._signed_assertion(issued_at)},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )+ if not response.ok:+ raise GooglePlayConsoleAuthError(+ f"Google rejected the service account key (status {response.status_code}). "+ "Check that the key is active and the Play Developer Reporting API is enabled "+ f"for its project: {response.text[:200]}"+ )+ payload = response.json()+ token = payload.get("access_token")+ if not token:+ raise GooglePlayConsoleAuthError("Google returned no access token for the service account key")++ try:+ ttl = int(payload.get("expires_in") or TOKEN_TTL_SECONDS)+ except (TypeError, ValueError):+ ttl = TOKEN_TTL_SECONDS+ self._access_token = str(token)+ self._token_expires_at = issued_at + ttl - TOKEN_EXPIRY_SKEW_SECONDS+ return self._access_token++ def _authorization(self) -> str:+ if self._access_token is None or time.time() >= self._token_expires_at:+ return f"Bearer {self._mint_access_token()}"+ return f"Bearer {self._access_token}"++ def _send(+ self, method: str, url: str, params: dict[str, Any] | None, body: dict[str, Any] | None+ ) -> requests.Response:+ return self._session.request(+ method,+ url,+ params=params,+ json=body,+ headers={"Authorization": self._authorization()},+ timeout=REQUEST_TIMEOUT_SECONDS,+ )++ def request(+ self,+ method: str,+ path: str,+ params: dict[str, Any] | None = None,+ body: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ url = f"{self._base_url}/{path}"+ response = self._send(method, url, params, body)+ if response.status_code == 401:+ # Access tokens last an hour, so a long sync outlives the one it started with.+ self._access_token = None+ response = self._send(method, url, params, body)++ if not response.ok:+ self._logger.warning(+ "Google Play Console API error",+ status_code=response.status_code,+ url=url,+ body=response.text[:500],+ )+ response.raise_for_status()++ payload = response.json()+ return payload if isinstance(payload, dict) else {}++ def list_apps(self) -> list[dict[str, Any]]:+ """Every app the service account can report on."""+ apps: list[dict[str, Any]] = []+ page_token: str | None = None+ while True:+ params: dict[str, Any] = {"pageSize": APP_PAGE_SIZE}+ if page_token:+ params["pageToken"] = page_token+ payload = self.request("GET", "apps:search", params=params)+ apps.extend(payload.get("apps") or [])+ page_token = payload.get("nextPageToken") or None+ if not page_token:+ return apps++ def latest_available_date(self, package_name: str, resource: str) -> dt.date | None:+ """Last day a metric set has complete data for, per its own freshness report."""+ payload = self.request("GET", f"apps/{package_name}/{resource}")+ freshness_info = payload.get("freshnessInfo") or {}+ for freshness in freshness_info.get("freshnesses") or []:+ if freshness.get("aggregationPeriod") == AGGREGATION_PERIOD:+ return _date_from_message(freshness.get("latestEndTime"))+ return None+++def resolve_package_names(client: GooglePlayConsoleClient, requested: Iterable[str]) -> list[str]:+ """Packages to sync: the user's list when given, otherwise everything the account can see.++ Sorted because resume state records the package it stopped on and skips everything before it.+ """+ requested_names = sorted({name for name in requested if name})+ if requested_names:+ return requested_names++ return sorted(+ {package for app in client.list_apps() if (package := app.get("packageName")) is not None},+ )+++def parse_package_names(raw: str | None) -> tuple[str, ...]:+ if not raw:+ return ()+ separated = raw.replace("\n", ",").replace(" ", ",")+ return tuple(sorted({name.strip() for name in separated.split(",") if name.strip()}))+++def _metric_row_to_dict(row: dict[str, Any], package_name: str, endpoint: MetricSetEndpoint) -> dict[str, Any]:+ # Every requested dimension and metric is seeded so the table keeps a stable set of columns+ # even when Play omits one from a row (it drops slices whose user counts fall under its+ # privacy threshold) — the primary key columns in particular must always be there.+ out: dict[str, Any] = {"app": package_name}+ out.update(dict.fromkeys(endpoint.dimensions))+ out.update(dict.fromkeys(endpoint.metrics))++ start_time = row.get("startTime")+ out["date"] = _date_from_message(start_time)+ out["startTime"] = _datetime_from_message(start_time)+ out["endTime"] = _datetime_from_message(row.get("endTime"))++ for dimension in row.get("dimensions") or []:+ name = dimension.get("dimension")+ if not name:+ continue+ out[name] = _dimension_value(dimension)+ label = dimension.get("valueLabel")+ if label is not None:+ out[f"{name}Label"] = label++ for metric in row.get("metrics") or []:+ name = metric.get("metric")+ if not name:+ continue+ out[name] = _metric_value(metric)++ return out+++def _query_metric_set(+ client: GooglePlayConsoleClient,+ package_name: str,+ endpoint: MetricSetEndpoint,+ start: dt.date,+ end_inclusive: dt.date,+) -> Iterator[dict[str, Any]]:+ page_token: str | None = None+ while True:+ body: dict[str, Any] = {+ "timelineSpec": {+ "aggregationPeriod": AGGREGATION_PERIOD,+ "startTime": _date_message(start),+ # The timeline's end is exclusive, so ask for the day after the last one wanted.+ "endTime": _date_message(end_inclusive + dt.timedelta(days=1)),+ },+ "dimensions": list(endpoint.dimensions),+ "metrics": list(endpoint.metrics),+ "pageSize": METRIC_PAGE_SIZE,+ }+ if page_token:+ body["pageToken"] = page_token++ payload = client.request("POST", f"apps/{package_name}/{endpoint.resource}:query", body=body)+ yield from payload.get("rows") or []++ page_token = payload.get("nextPageToken") or None+ if not page_token:+ return+++def _batch_by_date(rows: Iterable[dict[str, Any]]) -> list[list[dict[str, Any]]]:+ """Group a window's rows into one batch per day, oldest first.++ A metric-set query can return the days of its window in any order, but the pipeline+ checkpoints the incremental watermark after every batch — so batches have to leave in date+ order, and each has to hold a single day.+ """+ by_date: dict[dt.date, list[dict[str, Any]]] = {}+ undated: list[dict[str, Any]] = []+ for row in rows:+ day = row.get("date")+ if isinstance(day, dt.date):+ by_date.setdefault(day, []).append(row)+ else:+ undated.append(row)++ batches = [by_date[day] for day in sorted(by_date)]+ if undated:+ batches.append(undated)+ return batches+++def _iter_metric_set_rows(+ client: GooglePlayConsoleClient,+ endpoint: MetricSetEndpoint,+ package_names: list[str],+ history_start: dt.date,+ manager: ResumableSourceManager[GooglePlayConsoleResumeConfig],+ resume: GooglePlayConsoleResumeConfig | None,+) -> Iterator[list[dict[str, Any]]]:+ resume_app = resume.app if resume and resume.app else None+ resume_date = resume.date if resume else None++ for package_name in package_names:+ if resume_app is not None and package_name < resume_app:+ continue++ window_start = history_start+ if package_name == resume_app and resume_date is not None:+ window_start = _parse_date(resume_date) or history_start+ resume_app = None++ latest = client.latest_available_date(package_name, endpoint.resource) or (+ _today() - dt.timedelta(days=FRESHNESS_LAG_DAYS)+ )++ current = window_start+ while current <= latest:+ window_end = min(current + dt.timedelta(days=METRIC_SET_WINDOW_DAYS - 1), latest)+ rows = [+ _metric_row_to_dict(row, package_name, endpoint)+ for row in _query_metric_set(client, package_name, endpoint, current, window_end)+ ]+ yield from _batch_by_date(rows)++ current = window_end + dt.timedelta(days=1)+ manager.save_state(GooglePlayConsoleResumeConfig(app=package_name, date=current.isoformat()))+++def _list_row_to_dict(row: dict[str, Any], package_name: str | None, endpoint: ListEndpoint) -> dict[str, Any]:+ out = dict(row)+ if package_name is not None:+ out["app"] = package_name+ for field_name in endpoint.datetime_fields:+ # The cursor column is always emitted, even when absent from the row, so the incremental+ # field never disappears from the table. Other timestamps are only coerced when present,+ # to avoid inventing an all-null column.+ if field_name in out or field_name == endpoint.incremental_field:+ out[field_name] = _coerce_datetime(out.get(field_name))+ return out+++def _paginate(+ client: GooglePlayConsoleClient,+ endpoint: ListEndpoint,+ path: str,+ params: dict[str, Any],+ package_name: str | None,+ page_token: str | None,+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ """Walk one collection, yielding each page with the token that follows it."""+ while True:+ page_params: dict[str, Any] = {**params, "pageSize": LIST_PAGE_SIZE}+ if page_token:+ page_params["pageToken"] = page_token++ payload = client.request("GET", path, params=page_params)+ rows = [_list_row_to_dict(row, package_name, endpoint) for row in payload.get(endpoint.data_key) or []]+ next_token = payload.get("nextPageToken") or None+ yield rows, next_token++ if not next_token:+ return+ page_token = next_token+++def _iter_list_rows(+ client: GooglePlayConsoleClient,+ endpoint: ListEndpoint,+ package_names: list[str],+ history_start: dt.date,+ manager: ResumableSourceManager[GooglePlayConsoleResumeConfig],+ resume: GooglePlayConsoleResumeConfig | None,+) -> Iterator[list[dict[str, Any]]]:+ if not endpoint.per_app:+ for rows, next_token in _paginate(+ client, endpoint, endpoint.path, {}, None, resume.page_token if resume else None+ ):+ if rows:+ yield rows+ manager.save_state(GooglePlayConsoleResumeConfig(page_token=next_token))+ return++ resume_app = resume.app if resume and resume.app else None+ resume_date = resume.date if resume else None+ resume_token = resume.page_token if resume else None++ for package_name in package_names:+ if resume_app is not None and package_name < resume_app:+ continue++ resuming_this_app = package_name == resume_app+ path = endpoint.path.format(app=package_name)++ if endpoint.interval_mode == "daily":+ start = history_start+ if resuming_this_app and resume_date is not None:+ start = _parse_date(resume_date) or history_start+ page_token = resume_token if resuming_this_app else None++ day = start+ today = _today()+ while day <= today:+ params: dict[str, Any] = _interval_params(+ dt.datetime.combine(day, dt.time.min),+ dt.datetime.combine(day + dt.timedelta(days=1), dt.time.min),+ )+ for rows, next_token in _paginate(client, endpoint, path, params, package_name, page_token):+ if rows:+ yield rows+ # A finished day checkpoints the next one, so a restart doesn't re-walk it.+ manager.save_state(+ GooglePlayConsoleResumeConfig(+ app=package_name,+ date=day.isoformat() if next_token else (day + dt.timedelta(days=1)).isoformat(),+ page_token=next_token,+ )+ )+ page_token = None+ day += dt.timedelta(days=1)+ else:+ trailing_params: dict[str, Any] = {}+ if endpoint.interval_mode == "trailing":+ trailing_params = _interval_params(+ dt.datetime.combine(history_start, dt.time.min),+ dt.datetime.combine(_today() + dt.timedelta(days=1), dt.time.min),+ )+ page_token = resume_token if resuming_this_app else None+ for rows, next_token in _paginate(client, endpoint, path, trailing_params, package_name, page_token):+ if rows:+ yield rows+ manager.save_state(GooglePlayConsoleResumeConfig(app=package_name, page_token=next_token))++ if resuming_this_app:+ resume_app = None+ resume_token = None+++def _parse_date(value: Any) -> dt.date | None:+ if isinstance(value, dt.datetime):+ return value.date()+ if isinstance(value, dt.date):+ return value+ if value is None:+ return None+ try:+ return dt.date.fromisoformat(str(value)[:10])+ except ValueError:+ return None+++def resolve_history_start(today: dt.date, watermark: Any, history_days: int) -> dt.date:+ """First day to request: the stored watermark, floored at the retained history window."""+ earliest = today - dt.timedelta(days=history_days)+ last_synced = _parse_date(watermark)+ if last_synced is None:+ return earliest+ return max(last_synced, earliest)+++def validate_credentials(key: ServiceAccountKey, api_version: str) -> tuple[bool, str | None]:+ """Mint a token and list the apps it can reach."""+ client = GooglePlayConsoleClient(key, api_version, logger)+ try:+ client.list_apps()+ except GooglePlayConsoleAuthError as e:+ return False, str(e)+ except requests.HTTPError as e:+ status = e.response.status_code if e.response is not None else None+ if status == 401:+ return False, "Google rejected the service account credentials. Please upload a current JSON key."+ if status in (403, 404):+ return (+ False,+ "The service account can't read Play Console reporting data. Enable the Play Developer "+ "Reporting API in its Google Cloud project and invite the service account in Play Console "+ "with permission to view app quality data.",+ )+ return False, f"Could not reach the Play Developer Reporting API: {e}"+ except Exception as e:+ return False, f"Could not reach the Play Developer Reporting API: {e}"++ return True, None+++def _load_resume_state(+ manager: ResumableSourceManager[GooglePlayConsoleResumeConfig],+) -> GooglePlayConsoleResumeConfig | None:+ return manager.load_state() if manager.can_resume() else None+++def _metric_set_response(+ endpoint: MetricSetEndpoint,+ key: ServiceAccountKey,+ package_names: tuple[str, ...],+ api_version: str,+ manager: ResumableSourceManager[GooglePlayConsoleResumeConfig],+ logger: FilteringBoundLogger,+ watermark: Any,+) -> SourceResponse:+ def get_rows() -> Iterator[list[dict[str, Any]]]:+ client = GooglePlayConsoleClient(key, api_version, logger)+ yield from _iter_metric_set_rows(+ client=client,+ endpoint=endpoint,+ package_names=resolve_package_names(client, package_names),+ history_start=resolve_history_start(_today(), watermark, METRIC_SET_HISTORY_DAYS),+ manager=manager,+ resume=_load_resume_state(manager),+ )++ return SourceResponse(+ name=endpoint.name,+ items=get_rows,+ primary_keys=PRIMARY_KEYS[endpoint.name],+ partition_mode="datetime",+ partition_format="day",+ partition_keys=["date"],+ sort_mode="asc",+ )+++def _list_endpoint_response(+ endpoint: ListEndpoint,+ key: ServiceAccountKey,+ package_names: tuple[str, ...],+ api_version: str,+ manager: ResumableSourceManager[GooglePlayConsoleResumeConfig],+ logger: FilteringBoundLogger,+ watermark: Any,+) -> SourceResponse:+ def get_rows() -> Iterator[list[dict[str, Any]]]:+ client = GooglePlayConsoleClient(key, api_version, logger)+ yield from _iter_list_rows(+ client=client,+ endpoint=endpoint,+ package_names=resolve_package_names(client, package_names) if endpoint.per_app else [],+ history_start=resolve_history_start(_today(), watermark, ERROR_HISTORY_DAYS),+ manager=manager,+ resume=_load_resume_state(manager),+ )++ if endpoint.incremental_field is not None:+ return SourceResponse(+ name=endpoint.name,+ items=get_rows,+ primary_keys=PRIMARY_KEYS[endpoint.name],+ partition_mode="datetime",+ partition_format="day",+ partition_keys=[endpoint.incremental_field],+ sort_mode="asc",+ )++ return SourceResponse(+ name=endpoint.name,+ items=get_rows,+ primary_keys=PRIMARY_KEYS[endpoint.name],+ partition_count=1,+ partition_size=1,+ sort_mode="asc",+ )+++def google_play_console_source(+ key: ServiceAccountKey,+ package_names: tuple[str, ...],+ resource_name: str,+ api_version: str,+ resumable_source_manager: ResumableSourceManager[GooglePlayConsoleResumeConfig],+ logger: FilteringBoundLogger,+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> SourceResponse:+ watermark = db_incremental_field_last_value if should_use_incremental_field else None++ metric_set = METRIC_SETS.get(resource_name)+ if metric_set is not None:+ return _metric_set_response(+ metric_set, key, package_names, api_version, resumable_source_manager, logger, watermark+ )++ list_endpoint = LIST_ENDPOINTS.get(resource_name)+ if list_endpoint is not None:+ return _list_endpoint_response(+ list_endpoint, key, package_names, api_version, resumable_source_manager, logger, watermark+ )++ raise ValueError(f"Unknown Google Play Console endpoint: {resource_name}")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/settings.pynew file mode 100644index 000000000000..9537d6281a2c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/settings.py@@ -0,0 +1,237 @@+from dataclasses import dataclass+from typing import Literal++from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Play aggregates vitals per calendar day (it also exposes HOURLY, but the user-weighted+# release-quality metrics teams care about are the daily ones).+AGGREGATION_PERIOD = "DAILY"++# Days of history requested on a first sync. The Reporting API keeps roughly a year of daily+# vitals; error reports are retained for a much shorter window, so they start closer to today.+METRIC_SET_HISTORY_DAYS = 180+ERROR_HISTORY_DAYS = 30++# Play keeps revising the most recent days of vitals (and the 7d/28d rolling metrics move with+# them), so an incremental run re-reads a trailing week and merges the corrected rows.+METRIC_SET_LOOKBACK_SECONDS = 7 * 24 * 60 * 60+# Error reports are immutable events, but a run interrupted part-way through a day may have+# advanced the watermark past rows it never fetched, so re-read the day.+ERROR_REPORT_LOOKBACK_SECONDS = 24 * 60 * 60++# Days requested per metric-set query. Rows are buffered per window and yielded oldest day+# first, so the window trades request count against how much is held in memory at once.+METRIC_SET_WINDOW_DAYS = 30++IntervalMode = Literal["none", "trailing", "daily"]+++@dataclass(frozen=True)+class MetricSetEndpoint:+ """One `apps/{app}/<resource>:query` metric set exposed as a table."""++ name: str+ resource: str+ metrics: tuple[str, ...]+ dimensions: tuple[str, ...]+ description: str+++@dataclass(frozen=True)+class ListEndpoint:+ """One paginated collection endpoint exposed as a table."""++ name: str+ # Path under the API root; `{app}` is substituted with the package name when `per_app`.+ path: str+ # Key the rows live under in the response body.+ data_key: str+ primary_key: tuple[str, ...]+ per_app: bool+ description: str+ # "none": no time filter. "trailing": one request covering the whole history window.+ # "daily": one request per day, walking the window oldest day first.+ interval_mode: IntervalMode = "none"+ # Cursor field, when the endpoint's time filter makes incremental sync real.+ incremental_field: str | None = None+ # Top-level fields carrying a google.type.DateTime / RFC 3339 timestamp to coerce.+ datetime_fields: tuple[str, ...] = ()+++# Every vitals metric set is sliced by `versionCode` only. Play drops rows whose user counts fall+# under its privacy threshold, and each extra dimension multiplies the slices, so a wider default+# breakdown would silently lose data on smaller apps.+_VERSION_CODE = ("versionCode",)++METRIC_SETS: dict[str, MetricSetEndpoint] = {+ "crash_rate": MetricSetEndpoint(+ name="crash_rate",+ resource="crashRateMetricSet",+ metrics=(+ "crashRate",+ "crashRate7dUserWeighted",+ "crashRate28dUserWeighted",+ "userPerceivedCrashRate",+ "userPerceivedCrashRate7dUserWeighted",+ "userPerceivedCrashRate28dUserWeighted",+ "distinctUsers",+ ),+ dimensions=_VERSION_CODE,+ description="Daily crash rate from Android vitals, broken out by app version.",+ ),+ "anr_rate": MetricSetEndpoint(+ name="anr_rate",+ resource="anrRateMetricSet",+ metrics=(+ "anrRate",+ "anrRate7dUserWeighted",+ "anrRate28dUserWeighted",+ "userPerceivedAnrRate",+ "userPerceivedAnrRate7dUserWeighted",+ "userPerceivedAnrRate28dUserWeighted",+ "distinctUsers",+ ),+ dimensions=_VERSION_CODE,+ description="Daily ANR (application not responding) rate, broken out by app version.",+ ),+ "excessive_wakeup_rate": MetricSetEndpoint(+ name="excessive_wakeup_rate",+ resource="excessiveWakeupRateMetricSet",+ metrics=(+ "excessiveWakeupRate",+ "excessiveWakeupRate7dUserWeighted",+ "excessiveWakeupRate28dUserWeighted",+ "distinctUsers",+ ),+ dimensions=_VERSION_CODE,+ description="Daily rate of sessions waking the device more than twice an hour.",+ ),+ "stuck_background_wakelock_rate": MetricSetEndpoint(+ name="stuck_background_wakelock_rate",+ resource="stuckBackgroundWakelockRateMetricSet",+ metrics=(+ "stuckBgWakelockRate",+ "stuckBgWakelockRate7dUserWeighted",+ "stuckBgWakelockRate28dUserWeighted",+ "distinctUsers",+ ),+ dimensions=_VERSION_CODE,+ description="Daily rate of sessions holding a background wakelock for over an hour.",+ ),+ "slow_start_rate": MetricSetEndpoint(+ name="slow_start_rate",+ resource="slowStartRateMetricSet",+ metrics=(+ "slowStartRate",+ "slowStartRate7dUserWeighted",+ "slowStartRate28dUserWeighted",+ "distinctUsers",+ ),+ # `startType` splits cold, warm, and hot starts, which have different thresholds — the+ # combined rate is not meaningful.+ dimensions=("startType", "versionCode"),+ description="Daily rate of slow app starts, broken out by start type and app version.",+ ),+ "slow_rendering_rate": MetricSetEndpoint(+ name="slow_rendering_rate",+ resource="slowRenderingRateMetricSet",+ metrics=(+ "slowRenderingRate20Fps",+ "slowRenderingRate20Fps7dUserWeighted",+ "slowRenderingRate20Fps28dUserWeighted",+ "slowRenderingRate30Fps",+ "slowRenderingRate30Fps7dUserWeighted",+ "slowRenderingRate30Fps28dUserWeighted",+ "distinctUsers",+ ),+ dimensions=_VERSION_CODE,+ description="Daily rate of sessions with slow frame rendering, broken out by app version.",+ ),+ "lmk_rate": MetricSetEndpoint(+ name="lmk_rate",+ resource="lmkRateMetricSet",+ metrics=(+ "userPerceivedLmkRate",+ "userPerceivedLmkRate7dUserWeighted",+ "userPerceivedLmkRate28dUserWeighted",+ "distinctUsers",+ ),+ dimensions=_VERSION_CODE,+ description="Daily rate of low-memory kills the user perceived, broken out by app version.",+ ),+ "error_counts": MetricSetEndpoint(+ name="error_counts",+ resource="errorCountMetricSet",+ metrics=("errorReportCount", "distinctUsers"),+ dimensions=("reportType", "versionCode"),+ description="Daily error report counts, broken out by report type and app version.",+ ),+}++LIST_ENDPOINTS: dict[str, ListEndpoint] = {+ "apps": ListEndpoint(+ name="apps",+ path="apps:search",+ data_key="apps",+ primary_key=("packageName",),+ per_app=False,+ description="Apps the connected service account can report on.",+ ),+ "error_issues": ListEndpoint(+ name="error_issues",+ path="apps/{app}/errorIssues:search",+ data_key="errorIssues",+ primary_key=("name",),+ per_app=True,+ interval_mode="trailing",+ datetime_fields=("lastErrorReportTime", "firstErrorReportTime"),+ description="Clustered crash, ANR, and non-fatal issues with their report and user counts.",+ ),+ "error_reports": ListEndpoint(+ name="error_reports",+ path="apps/{app}/errorReports:search",+ data_key="errorReports",+ primary_key=("name",),+ per_app=True,+ interval_mode="daily",+ incremental_field="eventTime",+ datetime_fields=("eventTime",),+ description="Individual crash, ANR, and non-fatal error reports, including stack traces.",+ ),+ "anomalies": ListEndpoint(+ name="anomalies",+ path="apps/{app}/anomalies",+ data_key="anomalies",+ primary_key=("name",),+ per_app=True,+ description="Metric anomalies Play detected against its expected range.",+ ),+}++ENDPOINTS: tuple[str, ...] = (*METRIC_SETS, *LIST_ENDPOINTS)++PRIMARY_KEYS: dict[str, list[str]] = {+ # A metric row is identified by the app, the day, and the slice it aggregates — the+ # package name is part of the key because one source syncs every app the account can see.+ **{name: ["app", "date", *endpoint.dimensions] for name, endpoint in METRIC_SETS.items()},+ **{name: list(endpoint.primary_key) for name, endpoint in LIST_ENDPOINTS.items()},+}++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ **{name: [incremental_field("date", IncrementalFieldType.Date)] for name in METRIC_SETS},+ "error_reports": [incremental_field("eventTime", IncrementalFieldType.DateTime)],+}++DESCRIPTIONS: dict[str, str] = {+ **{name: endpoint.description for name, endpoint in METRIC_SETS.items()},+ **{name: endpoint.description for name, endpoint in LIST_ENDPOINTS.items()},+}++LOOKBACK_SECONDS: dict[str, int] = {+ **dict.fromkeys(METRIC_SETS, METRIC_SET_LOOKBACK_SECONDS),+ "error_reports": ERROR_REPORT_LOOKBACK_SECONDS,+}++# Play restates recent metric days, so appending would keep both the old and corrected rows.+MERGE_ONLY: tuple[str, ...] = tuple(METRIC_SETS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/source.pyindex 6b4d1bbd84b5..bcd4f3ef4718 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/source.py@@ -1,32 +1,189 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldFileUploadConfig,+ SourceFieldFileUploadJsonFormatConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+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,+ build_endpoint_schemas,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.googleplayconsole import (GooglePlayConsoleSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.google_play_console.google_play_console import (+ GooglePlayConsoleResumeConfig,+ ServiceAccountKey,+ google_play_console_source,+ parse_package_names,+ validate_credentials as validate_google_play_console_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.google_play_console.settings import (+ DESCRIPTIONS,+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ LOOKBACK_SECONDS,+ MERGE_ONLY,+ PRIMARY_KEYS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+def _service_account_key(config: GooglePlayConsoleSourceConfig) -> ServiceAccountKey:+ return ServiceAccountKey(+ client_email=config.key_file.client_email,+ private_key=config.key_file.private_key,+ private_key_id=config.key_file.private_key_id,+ token_uri=config.key_file.token_uri,+ )++@SourceRegistry.register-class GooglePlayConsoleSource(SimpleSource[GooglePlayConsoleSourceConfig]):+class GooglePlayConsoleSource(ResumableSource[GooglePlayConsoleSourceConfig, GooglePlayConsoleResumeConfig]):+ supported_versions = ("v1beta1",)+ default_version = "v1beta1"+ api_docs_url = "https://developers.google.com/play/developer/reporting"++ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GOOGLEPLAYCONSOLE+ @property+ def connection_host_fields(self) -> list[str]:+ # app_package_names picks which apps the stored service account key reads, and clearing it+ # selects every app the account can see — so changing it must require re-uploading the key+ # rather than letting an editor who never held it widen the import's reach.+ return ["app_package_names"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Google rejected the service account credentials. Please upload a current JSON key file.",+ "403 Client Error": (+ "The service account cannot read Play Console reporting data. Enable the Play Developer Reporting "+ "API in its Google Cloud project, and give the service account permission to view app quality "+ "data in Play Console."+ ),+ "Google rejected the service account key": (+ "Google rejected the service account key. Check that the key is still active and upload a current one."+ ),+ "Could not sign a token with the uploaded service account key": (+ "The uploaded file is not a usable Google service account key. Please upload the JSON key file "+ "Google Cloud generated, unmodified."+ ),+ }+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.GOOGLE_PLAY_CONSOLE,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,- label="Google Play Console (Play Developer Reporting API)",+ keywords=["android", "play store", "vitals", "crash"],+ label="Google Play Console",+ caption="""Sync Android vitals and error reporting from the Play Developer Reporting API: crash and ANR rates, excessive wakeups and stuck wakelocks, slow starts and slow rendering, low-memory kills, plus error issues, error reports, and the anomalies Play detects.++To connect, create a Google Cloud service account and enable the **Play Developer Reporting API** in its project. Then, in Play Console under **Users and permissions**, invite the service account's email and give it access to view app quality data. Upload that service account's JSON key below.++Leave the package names blank to sync every app the service account can see.""",iconPath="/static/services/google_play_console.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/google-play-console",+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldFileUploadConfig(+ name="key_file",+ label="Google service account JSON key",+ fileFormat=SourceFieldFileUploadJsonFormatConfig(+ format=".json",+ keys=["client_email", "private_key", "private_key_id", "token_uri"],+ ),+ required=True,+ ),+ SourceFieldInputConfig(+ name="app_package_names",+ label="App package names",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="com.example.app, com.example.other",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.google_play_console.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: GooglePlayConsoleSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ schemas = build_endpoint_schemas(+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ names=names,+ merge_only=MERGE_ONLY,+ descriptions=DESCRIPTIONS,+ )+ for schema in schemas:+ schema.default_incremental_lookback_seconds = LOOKBACK_SECONDS.get(schema.name)+ schema.detected_primary_keys = PRIMARY_KEYS[schema.name]+ return schemas++ def validate_credentials(+ self,+ config: GooglePlayConsoleSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_google_play_console_credentials(+ _service_account_key(config), self.resolve_api_version(api_version)+ )++ def get_resumable_source_manager(+ self, inputs: SourceInputs+ ) -> ResumableSourceManager[GooglePlayConsoleResumeConfig]:+ return ResumableSourceManager[GooglePlayConsoleResumeConfig](inputs, GooglePlayConsoleResumeConfig)++ def source_for_pipeline(+ self,+ config: GooglePlayConsoleSourceConfig,+ resumable_source_manager: ResumableSourceManager[GooglePlayConsoleResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return google_play_console_source(+ key=_service_account_key(config),+ package_names=parse_package_names(config.app_package_names),+ resource_name=inputs.schema_name,+ api_version=self.resolve_api_version(inputs.api_version),+ resumable_source_manager=resumable_source_manager,+ logger=inputs.logger,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/tests/test_google_play_console.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/tests/test_google_play_console.pynew file mode 100644index 000000000000..8217df32f506--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/tests/test_google_play_console.py@@ -0,0 +1,816 @@+import datetime as dt+import functools+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest import mock++import jwt+import requests+import structlog+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import rsa++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.google_play_console import google_play_console+from products.warehouse_sources.backend.temporal.data_imports.sources.google_play_console.google_play_console import (+ DEFAULT_TOKEN_URI,+ JWT_BEARER_GRANT,+ PLAY_REPORTING_SCOPE,+ GooglePlayConsoleAuthError,+ GooglePlayConsoleClient,+ GooglePlayConsoleResumeConfig,+ ServiceAccountKey,+ _batch_by_date,+ _coerce_datetime,+ _dimension_value,+ _interval_params,+ _iter_list_rows,+ _iter_metric_set_rows,+ _list_row_to_dict,+ _metric_row_to_dict,+ _metric_value,+ _normalize_private_key,+ google_play_console_source,+ parse_package_names,+ resolve_history_start,+ resolve_package_names,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.google_play_console.settings import (+ ENDPOINTS,+ LIST_ENDPOINTS,+ METRIC_SETS,+ PRIMARY_KEYS,+)++MODULE = google_play_console.__name__+TODAY = dt.date(2024, 3, 31)+++def _rsa_key_pair() -> tuple[str, str]:+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)+ private_pem = key.private_bytes(+ encoding=serialization.Encoding.PEM,+ format=serialization.PrivateFormat.PKCS8,+ encryption_algorithm=serialization.NoEncryption(),+ ).decode()+ public_pem = (+ key.public_key()+ .public_bytes(+ encoding=serialization.Encoding.PEM,+ format=serialization.PublicFormat.SubjectPublicKeyInfo,+ )+ .decode()+ )+ return private_pem, public_pem+++def _key(private_key: str | None = None) -> ServiceAccountKey:+ return ServiceAccountKey(+ client_email="[email protected]",+ private_key=private_key if private_key is not None else _rsa_key_pair()[0],+ private_key_id="key-1",+ token_uri=DEFAULT_TOKEN_URI,+ )+++def _response(status_code: int, payload: Any = None, text: str = "") -> mock.MagicMock:+ response = mock.MagicMock(spec=requests.Response)+ response.status_code = status_code+ response.ok = 200 <= status_code < 300+ response.text = text+ response.json.return_value = payload if payload is not None else {}+ if not response.ok:+ response.raise_for_status.side_effect = requests.HTTPError(+ f"{status_code} Client Error: for url: https://playdeveloperreporting.googleapis.com", response=response+ )+ return response+++def _token_response() -> mock.MagicMock:+ return _response(200, {"access_token": "ya29.token", "expires_in": 3600})+++def _client(session: mock.MagicMock, private_key: str | None = None) -> GooglePlayConsoleClient:+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ return GooglePlayConsoleClient(_key(private_key), "v1beta1", structlog.get_logger())+++class FakeResumableSourceManager(ResumableSourceManager[GooglePlayConsoleResumeConfig]):+ def __init__(self, state: GooglePlayConsoleResumeConfig | None = None) -> None:+ self.saved: list[GooglePlayConsoleResumeConfig] = []+ self._state = state++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> GooglePlayConsoleResumeConfig | None:+ return self._state++ def save_state(self, data: GooglePlayConsoleResumeConfig) -> None:+ self.saved.append(data)++ def clear_state(self) -> None:+ self._state = None+++def _manager(state: GooglePlayConsoleResumeConfig | None = None) -> FakeResumableSourceManager:+ return FakeResumableSourceManager(state)+++def _metric_row(day: dt.date, version: int, rate: str, dimension: str = "versionCode") -> dict[str, Any]:+ return {+ "startTime": {"year": day.year, "month": day.month, "day": day.day},+ "endTime": {"year": day.year, "month": day.month, "day": day.day + 1},+ "dimensions": [{"dimension": dimension, "int64Value": str(version), "valueLabel": f"v{version}"}],+ "metrics": [{"metric": "crashRate", "decimalValue": {"value": rate}}],+ }+++def _freshness(day: dt.date) -> dict[str, Any]:+ return {+ "freshnessInfo": {+ "freshnesses": [+ {"aggregationPeriod": "HOURLY", "latestEndTime": {"year": 2024, "month": 3, "day": 30, "hours": 5}},+ {+ "aggregationPeriod": "DAILY",+ "latestEndTime": {"year": day.year, "month": day.month, "day": day.day},+ },+ ]+ }+ }+++ "raw,expected_start",+ [+ ("-----BEGIN PRIVATE KEY-----\nabc\n-----END PRIVATE KEY-----", "-----BEGIN PRIVATE KEY-----\nabc"),+ ("-----BEGIN PRIVATE KEY-----\\nabc\\n-----END PRIVATE KEY-----", "-----BEGIN PRIVATE KEY-----\nabc"),+ ],+)+def test_normalize_private_key_restores_newlines(raw: str, expected_start: str) -> None:+ normalized = _normalize_private_key(raw)+ assert normalized.startswith(expected_start)+ assert normalized.endswith("\n")+ assert "\\n" not in normalized+++def test_mints_a_signed_service_account_assertion() -> None:+ session = mock.MagicMock()+ session.post.return_value = _token_response()+ session.request.return_value = _response(200, {"apps": []})+ client = _client(session)++ client.request("GET", "apps:search")++ assert session.post.call_args.args[0] == DEFAULT_TOKEN_URI+ posted = session.post.call_args.kwargs["data"]+ assert posted["grant_type"] == JWT_BEARER_GRANT++ claims = jwt.decode(posted["assertion"], _rsa_key_pair()[1], algorithms=["RS256"], audience=DEFAULT_TOKEN_URI)+ assert claims["iss"] == "[email protected]"+ assert claims["scope"] == PLAY_REPORTING_SCOPE+ assert claims["exp"] - claims["iat"] == 3600+ assert jwt.get_unverified_header(posted["assertion"])["kid"] == "key-1"+ assert session.request.call_args.kwargs["headers"]["Authorization"] == "Bearer ya29.token"+++def test_ignores_the_uploaded_token_uri_and_posts_to_google() -> None:+ session = mock.MagicMock()+ session.post.return_value = _token_response()+ session.request.return_value = _response(200, {"apps": []})+ malicious_key = ServiceAccountKey(+ client_email="[email protected]",+ private_key=_rsa_key_pair()[0],+ private_key_id="key-1",+ token_uri="http://169.254.169.254/latest/meta-data/",+ )+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ client = GooglePlayConsoleClient(malicious_key, "v1beta1", structlog.get_logger())++ client.request("GET", "apps:search")++ assert session.post.call_args.args[0] == DEFAULT_TOKEN_URI+ claims = jwt.decode(+ session.post.call_args.kwargs["data"]["assertion"],+ _rsa_key_pair()[1],+ algorithms=["RS256"],+ audience=DEFAULT_TOKEN_URI,+ )+ assert claims["aud"] == DEFAULT_TOKEN_URI+++def test_reuses_the_access_token_until_it_expires() -> None:+ session = mock.MagicMock()+ session.post.return_value = _token_response()+ session.request.return_value = _response(200, {"apps": []})+ client = _client(session)++ client.request("GET", "apps:search")+ client.request("GET", "apps:search")++ assert session.post.call_count == 1+++def test_remints_the_access_token_when_a_request_comes_back_unauthorized() -> None:+ session = mock.MagicMock()+ session.post.return_value = _token_response()+ session.request.side_effect = [_response(401, text="expired"), _response(200, {"apps": [{"packageName": "a"}]})]+ client = _client(session)++ assert client.request("GET", "apps:search") == {"apps": [{"packageName": "a"}]}+ assert session.post.call_count == 2+ assert session.request.call_count == 2+++def test_raises_a_permanent_error_when_google_rejects_the_key() -> None:+ session = mock.MagicMock()+ session.post.return_value = _response(400, {"error": "invalid_grant"}, text="invalid_grant")+ client = _client(session)++ with pytest.raises(GooglePlayConsoleAuthError, match="Google rejected the service account key"):+ client.request("GET", "apps:search")+++def test_raises_a_permanent_error_when_the_key_cannot_sign() -> None:+ session = mock.MagicMock()+ client = _client(session, private_key="not-a-pem-key")++ with pytest.raises(GooglePlayConsoleAuthError, match="Could not sign a token"):+ client.request("GET", "apps:search")+++def test_non_2xx_api_responses_raise_for_status() -> None:+ session = mock.MagicMock()+ session.post.return_value = _token_response()+ session.request.return_value = _response(403, text="forbidden")+ client = _client(session)++ with pytest.raises(requests.HTTPError):+ client.request("GET", "apps/com.example/anomalies")+++def test_list_apps_follows_pagination() -> None:+ session = mock.MagicMock()+ session.post.return_value = _token_response()+ session.request.side_effect = [+ _response(200, {"apps": [{"packageName": "com.b"}], "nextPageToken": "t1"}),+ _response(200, {"apps": [{"packageName": "com.a"}]}),+ ]+ client = _client(session)++ assert [app["packageName"] for app in client.list_apps()] == ["com.b", "com.a"]+ assert session.request.call_args_list[1].kwargs["params"]["pageToken"] == "t1"+++ "dimension,expected",+ [+ ({"dimension": "versionCode", "int64Value": "1234"}, 1234),+ ({"dimension": "versionCode", "int64Value": "not-a-number"}, None),+ ({"dimension": "reportType", "stringValue": "CRASH"}, "CRASH"),+ ({"dimension": "startType", "valueLabel": "Cold start"}, "Cold start"),+ ({"dimension": "startType"}, None),+ ],+)+def test_dimension_value_coercion(dimension: dict[str, Any], expected: Any) -> None:+ assert _dimension_value(dimension) == expected+++ "metric,expected",+ [+ ({"metric": "crashRate", "decimalValue": {"value": "0.0125"}}, 0.0125),+ ({"metric": "distinctUsers", "int64Value": "42"}, 42.0),+ ({"metric": "crashRate", "doubleValue": 0.5}, 0.5),+ ({"metric": "crashRate", "decimalValue": {"value": "nonsense"}}, None),+ ({"metric": "crashRate"}, None),+ ],+)+def test_metric_value_is_always_a_float_or_null(metric: dict[str, Any], expected: Any) -> None:+ assert _metric_value(metric) == expected+++ "value,expected",+ [+ (+ {"year": 2024, "month": 3, "day": 2, "hours": 4, "minutes": 5, "seconds": 6},+ dt.datetime(2024, 3, 2, 4, 5, 6),+ ),+ ({"year": 2024, "month": 3, "day": 2}, dt.datetime(2024, 3, 2)),+ ("2024-03-02T04:05:06Z", dt.datetime(2024, 3, 2, 4, 5, 6)),+ ("2024-03-02T06:05:06+02:00", dt.datetime(2024, 3, 2, 4, 5, 6)),+ ("not a timestamp", None),+ ({"month": 3, "day": 2}, None),+ (None, None),+ ],+)+def test_timestamps_normalize_to_naive_utc(value: Any, expected: dt.datetime | None) -> None:+ assert _coerce_datetime(value) == expected+++def test_metric_row_keeps_the_primary_key_columns_when_play_omits_a_dimension() -> None:+ row = _metric_row_to_dict(+ {+ "startTime": {"year": 2024, "month": 3, "day": 2},+ "endTime": {"year": 2024, "month": 3, "day": 3},+ "dimensions": [],+ "metrics": [{"metric": "slowStartRate", "decimalValue": {"value": "0.01"}}],+ },+ "com.example.app",+ METRIC_SETS["slow_start_rate"],+ )++ assert row["app"] == "com.example.app"+ assert row["date"] == dt.date(2024, 3, 2)+ assert row["startTime"] == dt.datetime(2024, 3, 2)+ assert row["endTime"] == dt.datetime(2024, 3, 3)+ assert row["startType"] is None+ assert row["versionCode"] is None+ assert row["slowStartRate"] == 0.01+ # Requested metrics are always columns, even when the row carries no value for them.+ assert row["distinctUsers"] is None+++def test_metric_row_keeps_the_dimension_label_alongside_its_value() -> None:+ row = _metric_row_to_dict(+ _metric_row(dt.date(2024, 3, 2), 45, "0.02"), "com.example.app", METRIC_SETS["crash_rate"]+ )++ assert row["versionCode"] == 45+ assert row["versionCodeLabel"] == "v45"+++def test_window_rows_leave_in_date_order_one_day_per_batch() -> None:+ rows: list[dict[str, Any]] = [+ {"date": dt.date(2024, 3, 3), "versionCode": 1},+ {"date": dt.date(2024, 3, 1), "versionCode": 1},+ {"date": dt.date(2024, 3, 3), "versionCode": 2},+ {"date": None, "versionCode": 3},+ ]++ batches = _batch_by_date(rows)++ assert [{row["date"] for row in batch} for batch in batches] == [+ {dt.date(2024, 3, 1)},+ {dt.date(2024, 3, 3)},+ {None},+ ]+++def test_metric_set_windows_the_timeline_and_stops_at_the_freshness_date() -> None:+ endpoint = METRIC_SETS["crash_rate"]+ manager = _manager()+ calls: list[tuple[str, str, dict[str, Any] | None]] = []++ def request(method: str, path: str, params: Any = None, body: Any = None) -> dict[str, Any]:+ calls.append((method, path, body))+ if path.endswith(":query"):+ return {"rows": [_metric_row(dt.date(2024, 3, 5), 12, "0.01")]}+ return _freshness(dt.date(2024, 3, 10))++ with mock.patch.object(GooglePlayConsoleClient, "request", side_effect=request):+ client = _client(mock.MagicMock())+ batches = list(+ _iter_metric_set_rows(+ client=client,+ endpoint=endpoint,+ package_names=["com.example.app"],+ history_start=dt.date(2024, 3, 1),+ manager=manager,+ resume=None,+ )+ )++ assert len(batches) == 1+ query_bodies = [body for method, path, body in calls if path.endswith(":query")]+ assert len(query_bodies) == 1+ timeline = query_bodies[0]["timelineSpec"] if query_bodies[0] else {}+ assert timeline["aggregationPeriod"] == "DAILY"+ assert timeline["startTime"] == {"year": 2024, "month": 3, "day": 1}+ # The timeline end is exclusive, so the day after the freshness date is requested.+ assert timeline["endTime"] == {"year": 2024, "month": 3, "day": 11}+ assert cast("dict[str, Any]", query_bodies[0])["dimensions"] == ["versionCode"]+ assert manager.saved == [GooglePlayConsoleResumeConfig(app="com.example.app", date="2024-03-11")]+++def test_metric_set_falls_back_to_a_lagged_end_date_without_freshness() -> None:+ manager = _manager()++ def request(method: str, path: str, params: Any = None, body: Any = None) -> dict[str, Any]:+ if path.endswith(":query"):+ return {"rows": []}+ return {}++ with (+ mock.patch(f"{MODULE}._today", return_value=TODAY),+ mock.patch.object(GooglePlayConsoleClient, "request", side_effect=request),+ ):+ client = _client(mock.MagicMock())+ list(+ _iter_metric_set_rows(+ client=client,+ endpoint=METRIC_SETS["anr_rate"],+ package_names=["com.example.app"],+ history_start=dt.date(2024, 3, 20),+ manager=manager,+ resume=None,+ )+ )++ # 2024-03-29 is the last day queried (today minus the freshness lag), so the checkpoint moves past it.+ assert manager.saved[-1].date == "2024-03-30"+++def test_metric_set_query_follows_pagination_until_the_token_runs_out() -> None:+ manager = _manager()+ payloads: list[dict[str, Any]] = [+ {"rows": [_metric_row(dt.date(2024, 3, 1), 1, "0.01")], "nextPageToken": "page-2"},+ {"rows": [_metric_row(dt.date(2024, 3, 2), 1, "0.02")]},+ ]+ bodies: list[dict[str, Any] | None] = []++ def request(method: str, path: str, params: Any = None, body: Any = None) -> dict[str, Any]:+ if not path.endswith(":query"):+ return _freshness(dt.date(2024, 3, 2))+ bodies.append(body)+ return payloads.pop(0)++ with mock.patch.object(GooglePlayConsoleClient, "request", side_effect=request):+ client = _client(mock.MagicMock())+ batches = list(+ _iter_metric_set_rows(+ client=client,+ endpoint=METRIC_SETS["crash_rate"],+ package_names=["com.example.app"],+ history_start=dt.date(2024, 3, 1),+ manager=manager,+ resume=None,+ )+ )++ assert len(bodies) == 2+ assert bodies[1] is not None and bodies[1]["pageToken"] == "page-2"+ assert [batch[0]["date"] for batch in batches] == [dt.date(2024, 3, 1), dt.date(2024, 3, 2)]+++def test_metric_set_resume_skips_finished_apps_and_restarts_at_the_saved_window() -> None:+ manager = _manager(GooglePlayConsoleResumeConfig(app="com.b", date="2024-03-05"))+ queried: list[tuple[str, dict[str, int]]] = []++ def request(method: str, path: str, params: Any = None, body: Any = None) -> dict[str, Any]:+ if path.endswith(":query"):+ queried.append((path, body["timelineSpec"]["startTime"] if body else {}))+ return {"rows": []}+ return _freshness(dt.date(2024, 3, 6))++ with mock.patch.object(GooglePlayConsoleClient, "request", side_effect=request):+ client = _client(mock.MagicMock())+ list(+ _iter_metric_set_rows(+ client=client,+ endpoint=METRIC_SETS["crash_rate"],+ package_names=["com.a", "com.b", "com.c"],+ history_start=dt.date(2024, 3, 1),+ manager=manager,+ resume=GooglePlayConsoleResumeConfig(app="com.b", date="2024-03-05"),+ )+ )++ # com.a was finished before the interruption; com.b picks up at the saved date and com.c+ # starts from the beginning of the history window.+ assert [(path.split("/")[1], start) for path, start in queried] == [+ ("com.b", {"year": 2024, "month": 3, "day": 5}),+ ("com.c", {"year": 2024, "month": 3, "day": 1}),+ ]+++def test_apps_endpoint_paginates_and_checkpoints_each_page() -> None:+ endpoint = LIST_ENDPOINTS["apps"]+ manager = _manager()+ payloads: list[dict[str, Any]] = [+ {"apps": [{"packageName": "com.a"}], "nextPageToken": "p2"},+ {"apps": [{"packageName": "com.b"}]},+ ]++ with mock.patch.object(GooglePlayConsoleClient, "request", side_effect=lambda *a, **kw: payloads.pop(0)):+ client = _client(mock.MagicMock())+ batches = list(+ _iter_list_rows(+ client=client,+ endpoint=endpoint,+ package_names=[],+ history_start=dt.date(2024, 3, 1),+ manager=manager,+ resume=None,+ )+ )++ assert [row["packageName"] for batch in batches for row in batch] == ["com.a", "com.b"]+ assert [state.page_token for state in manager.saved] == ["p2", None]+ # The app catalog is not per-app, so no package name is stamped onto its rows.+ assert "app" not in batches[0][0]+++def test_error_reports_walk_one_day_at_a_time_with_an_interval_filter() -> None:+ endpoint = LIST_ENDPOINTS["error_reports"]+ manager = _manager()+ seen_params: list[dict[str, Any]] = []++ def request(method: str, path: str, params: Any = None, body: Any = None) -> dict[str, Any]:+ seen_params.append(params or {})+ return {"errorReports": [{"name": f"{path}/report-{len(seen_params)}", "eventTime": "2024-03-30T01:02:03Z"}]}++ with (+ mock.patch(f"{MODULE}._today", return_value=TODAY),+ mock.patch.object(GooglePlayConsoleClient, "request", side_effect=request),+ ):+ client = _client(mock.MagicMock())+ batches = list(+ _iter_list_rows(+ client=client,+ endpoint=endpoint,+ package_names=["com.example.app"],+ history_start=dt.date(2024, 3, 30),+ manager=manager,+ resume=None,+ )+ )++ assert len(seen_params) == 2 # 2024-03-30 and 2024-03-31+ assert seen_params[0]["interval.startTime.day"] == "30"+ assert seen_params[0]["interval.endTime.day"] == "31"+ assert seen_params[0]["interval.startTime.timeZone.id"] == "UTC"+ assert batches[0][0]["app"] == "com.example.app"+ assert batches[0][0]["eventTime"] == dt.datetime(2024, 3, 30, 1, 2, 3)+ assert [state.date for state in manager.saved] == ["2024-03-31", "2024-04-01"]+++def test_error_reports_resume_continues_inside_the_interrupted_day() -> None:+ endpoint = LIST_ENDPOINTS["error_reports"]+ resume = GooglePlayConsoleResumeConfig(app="com.example.app", date="2024-03-31", page_token="mid-day")+ manager = _manager(resume)+ seen_params: list[dict[str, Any]] = []++ def request(method: str, path: str, params: Any = None, body: Any = None) -> dict[str, Any]:+ seen_params.append(params or {})+ return {"errorReports": []}++ with (+ mock.patch(f"{MODULE}._today", return_value=TODAY),+ mock.patch.object(GooglePlayConsoleClient, "request", side_effect=request),+ ):+ client = _client(mock.MagicMock())+ list(+ _iter_list_rows(+ client=client,+ endpoint=endpoint,+ package_names=["com.example.app"],+ history_start=dt.date(2024, 3, 1),+ manager=manager,+ resume=resume,+ )+ )++ assert len(seen_params) == 1+ assert seen_params[0]["pageToken"] == "mid-day"+ assert seen_params[0]["interval.startTime.day"] == "31"+++def test_error_issues_request_one_trailing_window_per_app() -> None:+ endpoint = LIST_ENDPOINTS["error_issues"]+ manager = _manager()+ calls: list[tuple[str, dict[str, Any]]] = []++ def request(method: str, path: str, params: Any = None, body: Any = None) -> dict[str, Any]:+ calls.append((path, params or {}))+ return {+ "errorIssues": [+ {"name": f"{path}/issue-1", "lastErrorReportTime": {"year": 2024, "month": 3, "day": 20, "hours": 7}}+ ]+ }++ with (+ mock.patch(f"{MODULE}._today", return_value=TODAY),+ mock.patch.object(GooglePlayConsoleClient, "request", side_effect=request),+ ):+ client = _client(mock.MagicMock())+ batches = list(+ _iter_list_rows(+ client=client,+ endpoint=endpoint,+ package_names=["com.a", "com.b"],+ history_start=dt.date(2024, 3, 1),+ manager=manager,+ resume=None,+ )+ )++ assert [path for path, _ in calls] == ["apps/com.a/errorIssues:search", "apps/com.b/errorIssues:search"]+ assert calls[0][1]["interval.startTime.day"] == "1"+ assert calls[0][1]["interval.endTime.day"] == "1" # exclusive end: 2024-04-01+ assert calls[0][1]["interval.endTime.month"] == "4"+ assert batches[0][0]["lastErrorReportTime"] == dt.datetime(2024, 3, 20, 7)+ assert batches[0][0]["app"] == "com.a"+++def test_anomalies_send_no_time_filter() -> None:+ manager = _manager()+ calls: list[dict[str, Any]] = []++ def request(method: str, path: str, params: Any = None, body: Any = None) -> dict[str, Any]:+ calls.append(params or {})+ return {"anomalies": [{"name": f"{path}/anomaly-1"}]}++ with mock.patch.object(GooglePlayConsoleClient, "request", side_effect=request):+ client = _client(mock.MagicMock())+ list(+ _iter_list_rows(+ client=client,+ endpoint=LIST_ENDPOINTS["anomalies"],+ package_names=["com.a"],+ history_start=dt.date(2024, 3, 1),+ manager=manager,+ resume=None,+ )+ )++ assert calls == [{"pageSize": 100}]+++def test_interval_params_cover_both_bounds() -> None:+ params = _interval_params(dt.datetime(2024, 3, 1), dt.datetime(2024, 3, 2, 13, 14, 15))++ assert params["interval.startTime.year"] == "2024"+ assert params["interval.startTime.hours"] == "0"+ assert params["interval.endTime.hours"] == "13"+ assert params["interval.endTime.minutes"] == "14"+ assert params["interval.endTime.seconds"] == "15"+++ "raw,expected",+ [+ (None, ()),+ ("", ()),+ ("com.example.app", ("com.example.app",)),+ (" com.b , com.a ", ("com.a", "com.b")),+ ("com.a\ncom.b com.a", ("com.a", "com.b")),+ ],+)+def test_parse_package_names(raw: str | None, expected: tuple[str, ...]) -> None:+ assert parse_package_names(raw) == expected+++def test_resolve_package_names_discovers_apps_when_none_are_configured() -> None:+ with mock.patch.object(+ GooglePlayConsoleClient,+ "list_apps",+ return_value=[{"packageName": "com.b"}, {"packageName": "com.a"}, {"displayName": "no package"}],+ ):+ client = _client(mock.MagicMock())+ assert resolve_package_names(client, ()) == ["com.a", "com.b"]+++def test_resolve_package_names_uses_the_configured_list_without_calling_the_api() -> None:+ with mock.patch.object(GooglePlayConsoleClient, "list_apps") as list_apps:+ client = _client(mock.MagicMock())+ assert resolve_package_names(client, ("com.b", "com.a")) == ["com.a", "com.b"]+ list_apps.assert_not_called()+++ "watermark,expected",+ [+ (None, dt.date(2024, 1, 1)),+ (dt.date(2024, 3, 10), dt.date(2024, 3, 10)),+ (dt.datetime(2024, 3, 10, 5, 0, 0), dt.date(2024, 3, 10)),+ ("2024-03-10", dt.date(2024, 3, 10)),+ ("2024-03-10T05:00:00", dt.date(2024, 3, 10)),+ # Older than the retained window, so it is floored.+ (dt.date(2020, 1, 1), dt.date(2024, 1, 1)),+ ("nonsense", dt.date(2024, 1, 1)),+ ],+)+def test_resolve_history_start(watermark: Any, expected: dt.date) -> None:+ assert resolve_history_start(TODAY, watermark, 90) == expected+++ "status,expected_fragment",+ [+ (401, "upload a current JSON key"),+ (403, "Enable the Play Developer"),+ (404, "Enable the Play Developer"),+ (500, "Could not reach the Play Developer Reporting API"),+ ],+)+def test_validate_credentials_maps_status_codes_to_actionable_messages(status: int, expected_fragment: str) -> None:+ response = _response(status, text="denied")+ with mock.patch.object(+ GooglePlayConsoleClient,+ "list_apps",+ side_effect=requests.HTTPError("boom", response=response),+ ):+ is_valid, message = validate_credentials(_key(), "v1beta1")++ assert is_valid is False+ assert message is not None and expected_fragment in message+++def test_validate_credentials_reports_a_rejected_key() -> None:+ with mock.patch.object(+ GooglePlayConsoleClient, "list_apps", side_effect=GooglePlayConsoleAuthError("Google rejected the key")+ ):+ assert validate_credentials(_key(), "v1beta1") == (False, "Google rejected the key")+++def test_validate_credentials_succeeds_when_the_apps_call_works() -> None:+ with mock.patch.object(GooglePlayConsoleClient, "list_apps", return_value=[{"packageName": "com.a"}]):+ assert validate_credentials(_key(), "v1beta1") == (True, None)++[email protected]("resource_name", ENDPOINTS)+def test_source_response_shape_per_endpoint(resource_name: str) -> None:+ response = google_play_console_source(+ key=_key(),+ package_names=("com.example.app",),+ resource_name=resource_name,+ api_version="v1beta1",+ resumable_source_manager=_manager(),+ logger=structlog.get_logger(),+ )++ assert response.name == resource_name+ assert response.primary_keys == PRIMARY_KEYS[resource_name]+ assert response.sort_mode == "asc"+ if resource_name in METRIC_SETS:+ assert response.partition_keys == ["date"]+ assert response.partition_mode == "datetime"+ elif resource_name == "error_reports":+ assert response.partition_keys == ["eventTime"]+ else:+ assert response.partition_mode is None+++def test_source_response_rejects_an_unknown_endpoint() -> None:+ with pytest.raises(ValueError, match="Unknown Google Play Console endpoint"):+ google_play_console_source(+ key=_key(),+ package_names=(),+ resource_name="not_a_table",+ api_version="v1beta1",+ resumable_source_manager=_manager(),+ logger=structlog.get_logger(),+ )+++def test_metric_set_source_streams_rows_for_the_incremental_window() -> None:+ manager = _manager()+ response = google_play_console_source(+ key=_key(),+ package_names=("com.example.app",),+ resource_name="crash_rate",+ api_version="v1beta1",+ resumable_source_manager=manager,+ logger=structlog.get_logger(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=dt.date(2024, 3, 29),+ )++ def request(method: str, path: str, params: Any = None, body: Any = None) -> dict[str, Any]:+ if path.endswith(":query"):+ start = body["timelineSpec"]["startTime"] if body else {}+ return {"rows": [_metric_row(dt.date(start["year"], start["month"], start["day"]), 7, "0.03")]}+ return _freshness(dt.date(2024, 3, 30))++ with (+ mock.patch(f"{MODULE}._today", return_value=TODAY),+ mock.patch(f"{MODULE}.make_tracked_session", return_value=mock.MagicMock()),+ mock.patch.object(GooglePlayConsoleClient, "request", side_effect=request),+ ):+ batches = list(cast("Iterable[Any]", response.items()))++ # The window starts at the stored watermark rather than the full history window.+ assert [row["date"] for batch in batches for row in batch] == [dt.date(2024, 3, 29)]+ assert manager.saved[-1].date == "2024-03-31"+++def test_error_reports_always_carry_an_event_time_column() -> None:+ endpoint = LIST_ENDPOINTS["error_reports"]++ row = _list_row_to_dict({"name": "apps/com.a/errorReports/1"}, "com.a", endpoint)++ assert row["eventTime"] is None+++def test_optional_timestamps_are_not_invented_when_absent() -> None:+ endpoint = LIST_ENDPOINTS["error_issues"]++ row = _list_row_to_dict({"name": "apps/com.a/errorIssues/1"}, "com.a", endpoint)++ assert "firstErrorReportTime" not in rowdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/tests/test_google_play_console_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/tests/test_google_play_console_source.pynew file mode 100644index 000000000000..d32dc342b116--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/google_play_console/tests/test_google_play_console_source.py@@ -0,0 +1,227 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import DataWarehouseSourceCategory, SourceFieldFileUploadConfig++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.googleplayconsole import (+ GooglePlayConsoleKeyFileConfig,+ GooglePlayConsoleSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.google_play_console.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.google_play_console.google_play_console import (+ GooglePlayConsoleResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.google_play_console.settings import (+ ENDPOINTS,+ LIST_ENDPOINTS,+ METRIC_SETS,+ PRIMARY_KEYS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.google_play_console.source import (+ GooglePlayConsoleSource,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType, IncrementalFieldType++SOURCE_MODULE = GooglePlayConsoleSource.__module__+++def _config(app_package_names: str | None = None) -> GooglePlayConsoleSourceConfig:+ return GooglePlayConsoleSourceConfig(+ key_file=GooglePlayConsoleKeyFileConfig(+ client_email="[email protected]",+ private_key="private-key",+ private_key_id="private-key-id",+ token_uri="https://oauth2.googleapis.com/token",+ ),+ app_package_names=app_package_names,+ )+++def test_source_type() -> None:+ assert GooglePlayConsoleSource().source_type == ExternalDataSourceType.GOOGLEPLAYCONSOLE+++def test_package_names_force_the_key_to_be_re_uploaded() -> None:+ assert GooglePlayConsoleSource().connection_host_fields == ["app_package_names"]+++def test_source_ships_visible_as_alpha() -> None:+ config = GooglePlayConsoleSource().get_source_config++ assert config.unreleasedSource is None+ assert config.releaseStatus == "alpha"+ assert config.featureFlag is None+++def test_get_source_config_fields() -> None:+ config = GooglePlayConsoleSource().get_source_config++ assert [field.name for field in config.fields] == ["key_file", "app_package_names"]+ assert config.label == "Google Play Console"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.iconPath.endswith(".png")+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/google-play-console"+++def test_key_file_upload_collects_every_field_the_token_exchange_needs() -> None:+ key_file = next(field for field in GooglePlayConsoleSource().get_source_config.fields if field.name == "key_file")++ assert isinstance(key_file, SourceFieldFileUploadConfig)+ assert key_file.required is True+ assert set(key_file.fileFormat.keys) == {"client_email", "private_key", "private_key_id", "token_uri"}+++def test_api_version_metadata() -> None:+ source = GooglePlayConsoleSource()++ assert source.supported_versions == ("v1beta1",)+ assert source.default_version == "v1beta1"+ assert source.api_docs_url is not None and source.api_docs_url.startswith("https://")+++def test_get_schemas_returns_every_endpoint() -> None:+ schemas = GooglePlayConsoleSource().get_schemas(_config(), team_id=1)++ assert [schema.name for schema in schemas] == list(ENDPOINTS)+ assert all(schema.description for schema in schemas)+ assert {schema.name: schema.detected_primary_keys for schema in schemas} == PRIMARY_KEYS++[email protected]("name", sorted(METRIC_SETS))+def test_metric_sets_sync_incrementally_on_date_but_never_append(name: str) -> None:+ schema = next(s for s in GooglePlayConsoleSource().get_schemas(_config(), team_id=1) if s.name == name)++ assert schema.supports_incremental is True+ # Play restates recent days, so appending would keep the stale rows alongside the corrections.+ assert schema.supports_append is False+ assert [field["field"] for field in schema.incremental_fields] == ["date"]+ assert schema.incremental_fields[0]["field_type"] == IncrementalFieldType.Date+ assert schema.default_incremental_lookback_seconds == 7 * 24 * 60 * 60+++def test_error_reports_sync_incrementally_on_event_time() -> None:+ schema = next(s for s in GooglePlayConsoleSource().get_schemas(_config(), team_id=1) if s.name == "error_reports")++ assert schema.supports_incremental is True+ assert schema.supports_append is True+ assert [field["field"] for field in schema.incremental_fields] == ["eventTime"]+ assert schema.default_incremental_lookback_seconds == 24 * 60 * 60++[email protected]("name", ["apps", "error_issues", "anomalies"])+def test_aggregate_endpoints_are_full_refresh(name: str) -> None:+ schema = next(s for s in GooglePlayConsoleSource().get_schemas(_config(), team_id=1) if s.name == name)++ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []+++def test_get_schemas_filters_by_names() -> None:+ schemas = GooglePlayConsoleSource().get_schemas(_config(), team_id=1, names=["crash_rate", "anomalies"])++ assert {schema.name for schema in schemas} == {"crash_rate", "anomalies"}+++def test_table_catalog_is_published_without_credentials() -> None:+ source = GooglePlayConsoleSource()++ assert source.lists_tables_without_credentials is True+ tables = source.get_documented_tables()+ assert {table["name"] for table in tables} == set(ENDPOINTS)+++def test_canonical_descriptions_cover_every_endpoint() -> None:+ assert set(CANONICAL_DESCRIPTIONS) == set(ENDPOINTS)+ for name, entry in CANONICAL_DESCRIPTIONS.items():+ assert entry["description"], name+ assert entry["docs_url"].startswith("https://"), name+ assert entry["columns"], name++[email protected]("name", sorted(METRIC_SETS))+def test_metric_set_descriptions_document_their_primary_key_columns(name: str) -> None:+ columns = CANONICAL_DESCRIPTIONS[name]["columns"]++ assert set(PRIMARY_KEYS[name]).issubset(columns)++[email protected]("name", sorted(LIST_ENDPOINTS))+def test_list_endpoint_descriptions_document_their_primary_key_columns(name: str) -> None:+ columns = CANONICAL_DESCRIPTIONS[name]["columns"]++ assert set(PRIMARY_KEYS[name]).issubset(columns)+++def test_get_resumable_source_manager_is_bound_to_the_resume_config() -> None:+ manager = GooglePlayConsoleSource().get_resumable_source_manager(mock.MagicMock())++ assert manager._data_class is GooglePlayConsoleResumeConfig++[email protected]("status", [401, 403])+def test_auth_failures_are_non_retryable(status: int) -> None:+ errors = GooglePlayConsoleSource().get_non_retryable_errors()++ assert f"{status} Client Error" in errors+++def test_validate_credentials_passes_the_uploaded_key_and_resolved_version() -> None:+ with mock.patch(f"{SOURCE_MODULE}.validate_google_play_console_credentials", return_value=(True, None)) as validate:+ assert GooglePlayConsoleSource().validate_credentials(_config(), team_id=1) == (True, None)++ key, api_version = validate.call_args.args+ assert key.client_email == "[email protected]"+ assert key.private_key == "private-key"+ assert api_version == "v1beta1"+++def test_validate_credentials_surfaces_the_transport_error() -> None:+ with mock.patch(f"{SOURCE_MODULE}.validate_google_play_console_credentials", return_value=(False, "nope")):+ assert GooglePlayConsoleSource().validate_credentials(_config(), team_id=1) == (False, "nope")+++def _inputs(**overrides: Any) -> mock.MagicMock:+ inputs = mock.MagicMock()+ inputs.schema_name = "crash_rate"+ inputs.api_version = None+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-03-01"+ for key, value in overrides.items():+ setattr(inputs, key, value)+ return inputs+++def test_source_for_pipeline_plumbs_config_and_inputs() -> None:+ manager = mock.MagicMock()+ inputs = _inputs()++ with mock.patch(f"{SOURCE_MODULE}.google_play_console_source") as build_source:+ GooglePlayConsoleSource().source_for_pipeline(_config("com.b, com.a"), manager, inputs)++ kwargs = build_source.call_args.kwargs+ assert kwargs["package_names"] == ("com.a", "com.b")+ assert kwargs["resource_name"] == "crash_rate"+ assert kwargs["api_version"] == "v1beta1"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-03-01"+ assert kwargs["key"].client_email == "[email protected]"+++def test_source_for_pipeline_honors_a_pinned_api_version() -> None:+ with mock.patch(f"{SOURCE_MODULE}.google_play_console_source") as build_source:+ GooglePlayConsoleSource().source_for_pipeline(_config(), mock.MagicMock(), _inputs(api_version="v1alpha1"))++ assert build_source.call_args.kwargs["api_version"] == "v1alpha1"+++def test_source_for_pipeline_syncs_every_visible_app_when_no_packages_are_configured() -> None:+ with mock.patch(f"{SOURCE_MODULE}.google_play_console_source") as build_source:+ GooglePlayConsoleSource().source_for_pipeline(_config(), mock.MagicMock(), _inputs())++ assert build_source.call_args.kwargs["package_names"] == ()