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 safetyculture import source (#69383)

Tom Owers1390eb47ce99
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 0edabc6a0063..52c9f378125d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -301,6 +301,7 @@ the row lists both.
| rollbar | HTTP | requests | ✅ |
| rootly | HTTP | requests | ✅ |
| ruddr | HTTP | requests | ✅ |
+| safetyculture | HTTP | requests | ✅ |
| salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ |
| salesflare | HTTP | requests | ✅ |
| salesloft | HTTP | requests | ✅ |
@@ -666,7 +667,6 @@ doesn't conflict with concurrent PRs.
- rocket_chat
- rocketlane
- rss
-- safetyculture
- sage_hr
- sage_intacct
- sailthru
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 e149c5e3f5a6..21945e8fd28c 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
@@ -2955,7 +2955,7 @@ class SFTPSourceConfig(config.Config):
@config.config
class SafetyCultureSourceConfig(config.Config):
- pass
+ api_token: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/canonical_descriptions.py
new file mode 100644
index 000000000000..69b91e8fa6f5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/canonical_descriptions.py
@@ -0,0 +1,226 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions taken from the official SafetyCulture Data Feeds API docs
+# (https://developer.safetyculture.com/reference/data-feeds).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "inspections": {
+ "description": "An inspection (audit) conducted from a template, with its score, timings, and location.",
+ "docs_url": "https://developer.safetyculture.com/reference/thepubservice_feedinspections",
+ "columns": {
+ "id": "The ID of this inspection.",
+ "name": "The name of this inspection.",
+ "archived": "If this inspection is archived.",
+ "organisation_id": "The organisation this inspection belongs to.",
+ "owner_name": "The name of the user who created this inspection.",
+ "owner_id": "The ID of the user who created this inspection.",
+ "author_name": "The name of the user who last updated this inspection.",
+ "author_id": "The ID of the user who last updated this inspection.",
+ "score": "The score of this inspection.",
+ "max_score": "The maximum score of this inspection.",
+ "score_percentage": "The percentage of the inspection score.",
+ "site_id": "The site this inspection was conducted at.",
+ "template_id": "The ID of the template this inspection was conducted from.",
+ "template_name": "The name of the template this inspection was conducted from.",
+ "template_author": "The author of the template.",
+ "date_started": "The date this inspection was started.",
+ "date_completed": "The date this inspection was completed.",
+ "date_modified": "The date this inspection was last updated.",
+ "created_at": "The date this inspection was created on the server.",
+ "modified_at": "The date this inspection was last updated on the server.",
+ "latitude": "The latitude this inspection was conducted at.",
+ "longitude": "The longitude this inspection was conducted at.",
+ "document_no": "The document number of this inspection.",
+ "prepared_by": "The user who created this inspection.",
+ "location": "The location this inspection was conducted at.",
+ "conducted_on": "The date this inspection was conducted.",
+ "personnel": "The people involved in this inspection.",
+ "client_site": "The site this inspection was conducted at.",
+ "web_report_link": "The URL to the web report for this inspection.",
+ },
+ },
+ "inspection_items": {
+ "description": "A single question/item answered within an inspection, with its response, score, and media.",
+ "docs_url": "https://developer.safetyculture.com/reference/thepubservice_feedinspectionitems",
+ "columns": {
+ "id": "Combined inspection item ID.",
+ "item_id": "Item ID.",
+ "audit_id": "Inspection ID.",
+ "template_id": "Template ID.",
+ "parent_id": "Parent item ID.",
+ "organisation_id": "Organization that owns this inspection.",
+ "created_at": "Created date for the inspection.",
+ "modified_at": "Modified date for the inspection.",
+ "type": "Type of question.",
+ "category": "Name of the section this falls under.",
+ "category_id": "ID of the section this falls under.",
+ "parent_ids": "All parent IDs for this item.",
+ "label": "Label of the item.",
+ "response": "Response for the item.",
+ "response_id": "ID of the response in the response set.",
+ "response_set_id": "ID of the response set used for this item.",
+ "is_failed_response": "If the response indicates a failure.",
+ "comment": "Notes for the item.",
+ "media_files": "Names of media files associated with this item.",
+ "media_ids": "IDs of media files associated with this item.",
+ "media_hypertext_reference": "URLs of media files associated with this item.",
+ "score": "Score for this item; where this item has children it is the combined score of those children.",
+ "max_score": "Max score for this item; where this item has children it is the combined max score of those children.",
+ "score_percentage": "Score percentage for this item; where this item has children it is the combined score percentage of those children.",
+ "combined_score": "Where this item has children, the combined score of those children, otherwise null.",
+ "combined_max_score": "Where this item has children, the combined max score of those children, otherwise null.",
+ "combined_score_percentage": "Where this item has children, the combined score percentage of those children, otherwise null.",
+ "mandatory": "Item mandatory requirement.",
+ "inactive": "Item visibility.",
+ "location_latitude": "The latitude this inspection was conducted at.",
+ "location_longitude": "The longitude this inspection was conducted at.",
+ "primeelement_id": "For repeated sections/dynamic fields; consistent for every item under a repeated section.",
+ },
+ },
+ "templates": {
+ "description": "An inspection template that inspections are conducted from.",
+ "docs_url": "https://developer.safetyculture.com/reference/thepubservice_feedtemplates",
+ "columns": {
+ "id": "Template ID.",
+ "archived": "Indicates if the template is archived or not.",
+ "name": "Template name.",
+ "owner_name": "Owner name.",
+ "owner_id": "ID of the owner.",
+ "author_name": "Author name.",
+ "author_id": "ID of the author.",
+ "organisation_id": "ID of the organisation.",
+ "created_at": "Date and time when the template was created.",
+ "modified_at": "Date and time when the template was modified.",
+ },
+ },
+ "actions": {
+ "description": "A corrective action, optionally raised against an inspection item, with its priority, status, and assignment context.",
+ "docs_url": "https://developer.safetyculture.com/reference/thepubservice_feedactions",
+ "columns": {
+ "id": "ID of the action.",
+ "title": "Title of the action.",
+ "site_id": "Site ID associated with the action.",
+ "description": "Description of the action.",
+ "priority": "Priority of the action.",
+ "status": "Status of the action.",
+ "due_date": "Due date of the action.",
+ "creator_user_id": "User ID of the user who created this action.",
+ "creator_user_name": "Name of the user who created this action.",
+ "created_at": "Date this action was created.",
+ "modified_at": "Date this action was last modified.",
+ "template_id": "ID of the template this action was created against.",
+ "organisation_id": "ID of the organisation that owns this action.",
+ "audit_id": "ID of the inspection this action was created against.",
+ "audit_title": "Title of the inspection this action was created against.",
+ "audit_item_id": "ID of the item this action was created against.",
+ "audit_item_label": "Label of the item this action was created against.",
+ "completed_at": "Date this action was completed.",
+ "action_label": "Action labels associated with the action in pipe-delimited format.",
+ "unique_id": "Action unique ID.",
+ "type_id": "Action type unique ID.",
+ "type_name": "Action type name.",
+ },
+ },
+ "issues": {
+ "description": "An issue reported in SafetyCulture, with its category, priority, status, and linked inspection/site.",
+ "docs_url": "https://developer.safetyculture.com/reference/thepubservice_feedissues",
+ "columns": {
+ "id": "ID of the issue.",
+ "title": "Title of the issue.",
+ "description": "Description of the issue.",
+ "creator_id": "User ID of the user who created this issue.",
+ "creator_user_name": "Name of the user who created this issue.",
+ "created_at": "Date this issue was created.",
+ "due_at": "Due date of the issue.",
+ "priority": "Priority of the issue.",
+ "status": "Status of the issue.",
+ "template_id": "ID of the template this issue was created against.",
+ "inspection_id": "ID of the inspection this issue was created against.",
+ "inspection_name": "Title of the inspection this issue was created against.",
+ "site_id": "Site ID associated with the issue.",
+ "site_name": "Site name associated with the issue.",
+ "location_name": "Location name associated with the issue.",
+ "category_id": "Issue category ID.",
+ "category_label": "Issue category label.",
+ "category_description": "Issue category description.",
+ "modified_at": "Date this issue was last modified.",
+ "completed_at": "Date this issue was completed.",
+ "unique_id": "Unique ID for the issue.",
+ "occurred_at": "The configurable date that indicates when the issue occurred.",
+ },
+ },
+ "assets": {
+ "description": "An asset tracked in SafetyCulture, with its type, custom fields, site, and state.",
+ "docs_url": "https://developer.safetyculture.com/reference/thepubservice_feedassets",
+ "columns": {
+ "id": "ID of the asset.",
+ "code": "User-defined ID of the asset.",
+ "type_id": "Type ID of the asset.",
+ "type_name": "Type name of the asset.",
+ "fields": "Fields associated to the asset type.",
+ "created_at": "Date and time the asset was created in Coordinated Universal Time (UTC).",
+ "modified_at": "Date and time the asset was modified in Coordinated Universal Time (UTC).",
+ "site_id": "ID of the site associated with the asset.",
+ "state": "Current state of the asset.",
+ },
+ },
+ "users": {
+ "description": "A user in your SafetyCulture organization.",
+ "docs_url": "https://developer.safetyculture.com/reference/thepubservice_feedusers",
+ "columns": {
+ "id": "ID of the user.",
+ "organisation_id": "ID of the organisation.",
+ "email": "Email of the user.",
+ "firstname": "First name of the user.",
+ "lastname": "Last name of the user.",
+ "active": "Indicates if the user is active or not.",
+ "last_seen_at": "Date when the user was last seen.",
+ "seat_type": "Seat type.",
+ "created_at": "Created date for the user.",
+ },
+ },
+ "groups": {
+ "description": "A user group in your SafetyCulture organization.",
+ "docs_url": "https://developer.safetyculture.com/reference/thepubservice_feedgroups",
+ "columns": {
+ "id": "ID of the group.",
+ "organisation_id": "ID of the organisation.",
+ "name": "Name of the group.",
+ },
+ },
+ "sites": {
+ "description": "A site (location, area, region, state, or country) in your SafetyCulture organization.",
+ "docs_url": "https://developer.safetyculture.com/reference/thepubservice_feedsites",
+ "columns": {
+ "id": "ID of the site.",
+ "site_uuid": "UUID of the site.",
+ "name": "Site name.",
+ "creator_id": "ID of the site creator.",
+ "organisation_id": "ID of the organisation.",
+ "deleted": "Indicates if the site is deleted or not.",
+ "meta_label": "Type of site (location, area, region, state, country).",
+ "parent_id": "ID of the parent of this site.",
+ },
+ },
+ "schedules": {
+ "description": "A recurring inspection schedule, with its recurrence pattern, template, and site.",
+ "docs_url": "https://developer.safetyculture.com/reference/thepubservice_feedschedules",
+ "columns": {
+ "id": "ID of the schedule.",
+ "description": "Description of the schedule.",
+ "recurrence": "Recurrence pattern.",
+ "duration": "Duration of the schedule.",
+ "organisation_id": "ID of the organisation.",
+ "from_date": "Start date.",
+ "to_date": "End date.",
+ "modified_at": "Last modified date.",
+ "all_must_complete": "Whether all assignees must complete the schedule.",
+ "timezone": "Timezone of the schedule.",
+ "can_late_submit": "Allow inspections to be submitted after the due date.",
+ "site_id": "ID of the site.",
+ "template_id": "ID of the template.",
+ "creator_user_id": "ID of the creator user.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/safetyculture.py b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/safetyculture.py
new file mode 100644
index 000000000000..485402bb65fd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/safetyculture.py
@@ -0,0 +1,199 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.safetyculture.settings import (
+ SAFETYCULTURE_ENDPOINTS,
+ SafetyCultureEndpointConfig,
+)
+
+SAFETYCULTURE_BASE_URL = "https://api.safetyculture.io"
+REQUEST_TIMEOUT_SECONDS = 60
+# Cheap feed used to confirm an API token is genuine. Feed access is permission-scoped, so a 403
+# here still proves the token itself is valid (see `validate_credentials` on the source class).
+DEFAULT_PROBE_PATH = "/feed/users"
+
+
+class SafetyCultureRetryableError(Exception):
+ pass
+
+
+class SafetyCultureResumeConfig:
+ # Path of the next page to fetch, taken verbatim from the API's `metadata.next_page` (the docs
+ # forbid constructing it yourself). It embeds every filter — including `modified_after` on an
+ # incremental sync — so a crashed sync resumes from the page after the last one yielded; merge
+ # dedupes the re-pulled page on `id`.
+ next_page: str | None = None
+
+
+def _headers(api_token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_token}", "Accept": "application/json"}
+
+
+def _format_modified_after(value: Any) -> str:
+ """Format an incremental cursor as the Internet Date-Time string SafetyCulture expects.
+
+ Since 2025-02-01 the Feed APIs reject anything that isn't `{Y}-{m}-{d}T{H}:{M}:{S}[.{frac}]Z`.
+ """
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ return str(value)
+
+
+def _build_initial_path(
+ config: SafetyCultureEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> str:
+ params = dict(config.params)
+ if config.supports_incremental and should_use_incremental_field and db_incremental_field_last_value:
+ params["modified_after"] = _format_modified_after(db_incremental_field_last_value)
+ if not params:
+ return config.path
+ return f"{config.path}?{urlencode(params)}"
+
+
+def _extract_next_page(data: dict[str, Any]) -> Optional[str]:
+ metadata = data.get("metadata")
+ if not isinstance(metadata, dict):
+ return None
+ next_page = metadata.get("next_page")
+ return next_page if isinstance(next_page, str) and next_page else None
+
+
+@retry(
+ retry=retry_if_exception_type((SafetyCultureRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ path: str,
+ logger: FilteringBoundLogger,
+) -> tuple[list[dict[str, Any]], Optional[str]]:
+ # `path` is either the initial endpoint path or a verbatim `metadata.next_page`, so we never
+ # re-send query params — they're baked into the path.
+ url = f"{SAFETYCULTURE_BASE_URL}{path}"
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # SafetyCulture rate-limits with 429 on all endpoints; transient 5xx are retryable too.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise SafetyCultureRetryableError(
+ f"SafetyCulture API error (retryable): status={response.status_code}, path={path}"
+ )
+
+ if not response.ok:
+ logger.error(f"SafetyCulture API error: status={response.status_code}, body={response.text}, path={path}")
+ response.raise_for_status()
+
+ data = response.json()
+ # Every data feed wraps records in {"metadata": {"next_page", "remaining_records"}, "data": [...]}.
+ if not isinstance(data, dict) or not isinstance(data.get("data"), list):
+ raise SafetyCultureRetryableError(
+ f"SafetyCulture returned an unexpected payload for {path}: {type(data).__name__}"
+ )
+
+ return data["data"], _extract_next_page(data)
+
+
+def get_rows(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SafetyCultureResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = SAFETYCULTURE_ENDPOINTS[endpoint]
+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ path = (
+ resume.next_page
+ if (resume and resume.next_page)
+ else _build_initial_path(config, should_use_incremental_field, db_incremental_field_last_value)
+ )
+ if resume and resume.next_page:
+ logger.debug(f"SafetyCulture: resuming {endpoint} from {path}")
+
+ while True:
+ items, next_page = _fetch_page(session, path, logger)
+ if items:
+ yield items
+
+ # A null `next_page` marks the end of the feed. An empty page also terminates defensively so
+ # a lingering cursor can never produce an infinite loop.
+ if not next_page or not items:
+ break
+
+ path = next_page
+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages are
+ # persisted); merge dedupes the re-pulled page on the primary key.
+ resumable_source_manager.save_state(SafetyCultureResumeConfig(next_page=next_page))
+
+
+def safetyculture_source(
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[SafetyCultureResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = SAFETYCULTURE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ # Incremental feeds paginate by advancing `modified_after` in the server-issued `next_page`
+ # path, so rows arrive oldest-modified-first — matching the pipeline's ascending watermark.
+ sort_mode="asc",
+ )
+
+
+def check_access(api_token: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:
+ """Probe a single feed to validate the API token.
+
+ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a
+ connection problem, other HTTP status otherwise.
+ """
+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))
+ try:
+ response = session.get(f"{SAFETYCULTURE_BASE_URL}{path}", timeout=15)
+ except Exception as e:
+ return 0, f"Could not connect to SafetyCulture: {e}"
+
+ if response.status_code in (401, 403):
+ return response.status_code, None
+
+ if not response.ok:
+ return response.status_code, f"SafetyCulture returned HTTP {response.status_code}"
+
+ return 200, None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/settings.py
new file mode 100644
index 000000000000..42e9f1f454b9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/settings.py
@@ -0,0 +1,112 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+def _modified_at_incremental_fields() -> list[IncrementalField]:
+ # SafetyCulture's only server-side time filter is `modified_after`, which keys off `modified_at`.
+ # Advertising just `modified_at` keeps the user's chosen cursor aligned with what the API filters on.
+ return [
+ {
+ "label": "modified_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "modified_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ]
+
+
+@dataclass
+class SafetyCultureEndpointConfig:
+ name: str
+ path: str # Path under https://api.safetyculture.io, e.g. "/feed/inspections"
+ # The feed documents a `modified_after` query param that filters server-side on `modified_at`.
+ supports_incremental: bool
+ # Static query params sent on the first request only — every later page comes from the verbatim
+ # `metadata.next_page` path, which already carries them.
+ params: dict[str, str] = field(default_factory=dict)
+ # Stable creation-time field to partition by. None when the feed exposes no created_at.
+ partition_key: Optional[str] = "created_at"
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Every data feed row carries a feed-unique `id` (e.g. inspection_items' `id` is the combined
+ # inspection item ID, distinct from the per-template `item_id`).
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+# SafetyCulture Data Feed endpoints (https://developer.safetyculture.com/reference/data-feeds) —
+# the bulk-extraction API SafetyCulture recommends for warehouse syncs. Every feed returns
+# {"metadata": {"next_page", "remaining_records"}, "data": [...]}; the `next_page` path must be
+# followed verbatim. `archived`/`completed` are passed as "both" so the warehouse holds everything
+# and users filter on the corresponding columns instead.
+SAFETYCULTURE_ENDPOINTS: dict[str, SafetyCultureEndpointConfig] = {
+ "inspections": SafetyCultureEndpointConfig(
+ name="inspections",
+ path="/feed/inspections",
+ supports_incremental=True,
+ params={"archived": "both", "completed": "both"},
+ incremental_fields=_modified_at_incremental_fields(),
+ ),
+ "inspection_items": SafetyCultureEndpointConfig(
+ name="inspection_items",
+ path="/feed/inspection_items",
+ supports_incremental=True,
+ params={"archived": "both", "completed": "both"},
+ incremental_fields=_modified_at_incremental_fields(),
+ ),
+ "templates": SafetyCultureEndpointConfig(
+ name="templates",
+ path="/feed/templates",
+ supports_incremental=True,
+ params={"archived": "both"},
+ incremental_fields=_modified_at_incremental_fields(),
+ ),
+ "actions": SafetyCultureEndpointConfig(
+ name="actions",
+ path="/feed/actions",
+ supports_incremental=True,
+ incremental_fields=_modified_at_incremental_fields(),
+ ),
+ "issues": SafetyCultureEndpointConfig(
+ name="issues",
+ path="/feed/issues",
+ # The issues feed documents no `modified_after` param, so it's full refresh only.
+ supports_incremental=False,
+ ),
+ "assets": SafetyCultureEndpointConfig(
+ name="assets",
+ path="/feed/assets",
+ supports_incremental=False,
+ ),
+ "users": SafetyCultureEndpointConfig(
+ name="users",
+ path="/feed/users",
+ supports_incremental=False,
+ ),
+ "groups": SafetyCultureEndpointConfig(
+ name="groups",
+ path="/feed/groups",
+ supports_incremental=False,
+ partition_key=None,
+ ),
+ "sites": SafetyCultureEndpointConfig(
+ name="sites",
+ path="/feed/sites",
+ supports_incremental=False,
+ partition_key=None,
+ ),
+ "schedules": SafetyCultureEndpointConfig(
+ name="schedules",
+ path="/feed/schedules",
+ supports_incremental=False,
+ # The schedules feed exposes `modified_at` but no `created_at`, so there is no stable
+ # partition key.
+ partition_key=None,
+ ),
+}
+
+ENDPOINTS = tuple(SAFETYCULTURE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in SAFETYCULTURE_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/source.py
index b5a9f3632ef7..92638dee5fb1 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/source.py
@@ -1,19 +1,43 @@
-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.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 SafetyCultureSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.safetyculture.safetyculture import (
+ SafetyCultureResumeConfig,
+ check_access,
+ safetyculture_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.safetyculture.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ SAFETYCULTURE_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SafetyCultureSource(SimpleSource[SafetyCultureSourceConfig]):
+class SafetyCultureSource(ResumableSource[SafetyCultureSourceConfig, SafetyCultureResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SAFETYCULTURE
@@ -24,7 +48,107 @@ class SafetyCultureSource(SimpleSource[SafetyCultureSourceConfig]):
name=SchemaExternalDataSourceType.SAFETY_CULTURE,
category=DataWarehouseSourceCategory.PRODUCTIVITY,
label="SafetyCulture",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your SafetyCulture API token to pull your inspections, actions, issues, assets, and workplace-operations data into the PostHog Data warehouse.
+
+You can generate an API token under **Account settings → Integrations → Manage API tokens** in [SafetyCulture](https://app.safetyculture.com) (requires a Premium or Enterprise plan). Tokens expire after 30 days of inactivity, so SafetyCulture recommends a [service user](https://help.safetyculture.com/en-US/1064186-service-users) token with the **Data Access** permission for long-term integrations.
+""",
iconPath="/static/services/safetyculture.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/safetyculture",
+ keywords=["iauditor", "ehs", "inspections"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.safetyculture.canonical_descriptions import ( # noqa: PLC0415
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.safetyculture.io": "Your SafetyCulture API token is invalid or has expired (tokens expire after 30 days of inactivity). Generate a new token — ideally for a service user — then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.safetyculture.io": "Your SafetyCulture API token does not have access to this data. Grant the token's user the Data Access permission, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: SafetyCultureSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = SAFETYCULTURE_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint_config.supports_incremental,
+ supports_append=endpoint_config.supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+
+ schemas = [_build_schema(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: SafetyCultureSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if schema_name is not None and schema_name in SAFETYCULTURE_ENDPOINTS:
+ # Per-schema check: the feed this schema syncs must actually be reachable.
+ status, message = check_access(config.api_token, SAFETYCULTURE_ENDPOINTS[schema_name].path)
+ if status == 200:
+ return True, None
+ if status in (401, 403):
+ return False, f"Your SafetyCulture API token cannot access the {schema_name} feed"
+ return False, message or "Could not validate SafetyCulture API token"
+
+ status, message = check_access(config.api_token)
+ if status == 200:
+ return True, None
+ if status == 401:
+ return False, "Invalid SafetyCulture API token"
+ if status == 403:
+ # The token is genuine but its user lacks permission on the probe feed — feed access is
+ # permission-scoped, so don't block source-create over one unreachable feed.
+ return True, None
+ return False, message or "Could not validate SafetyCulture API token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SafetyCultureResumeConfig]:
+ return ResumableSourceManager[SafetyCultureResumeConfig](inputs, SafetyCultureResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SafetyCultureSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SafetyCultureResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ if inputs.schema_name not in SAFETYCULTURE_ENDPOINTS:
+ raise ValueError(f"Unknown SafetyCulture schema '{inputs.schema_name}'")
+
+ return safetyculture_source(
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/tests/test_safetyculture.py b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/tests/test_safetyculture.py
new file mode 100644
index 000000000000..b6af9b7537e9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/tests/test_safetyculture.py
@@ -0,0 +1,282 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+from unittest.mock import MagicMock
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.safetyculture import safetyculture
+from products.warehouse_sources.backend.temporal.data_imports.sources.safetyculture.safetyculture import (
+ SafetyCultureResumeConfig,
+ SafetyCultureRetryableError,
+ _build_initial_path,
+ _format_modified_after,
+ check_access,
+ get_rows,
+ safetyculture_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.safetyculture.settings import (
+ ENDPOINTS,
+ SAFETYCULTURE_ENDPOINTS,
+)
+
+# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.
+_fetch_page_unwrapped = safetyculture._fetch_page.__wrapped__ # type: ignore[attr-defined]
+
+
+class _FakeResumableManager:
+ def __init__(self, state: SafetyCultureResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[SafetyCultureResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> SafetyCultureResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: SafetyCultureResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestBuildInitialPath:
+ def test_static_params_are_encoded(self) -> None:
+ path = _build_initial_path(SAFETYCULTURE_ENDPOINTS["inspections"], False, None)
+ assert path == "/feed/inspections?archived=both&completed=both"
+
+ def test_no_params_returns_bare_path(self) -> None:
+ path = _build_initial_path(SAFETYCULTURE_ENDPOINTS["users"], False, None)
+ assert path == "/feed/users"
+
+ def test_incremental_cursor_adds_modified_after(self) -> None:
+ cursor = datetime(2024, 3, 1, 12, 30, 45, tzinfo=UTC)
+ path = _build_initial_path(SAFETYCULTURE_ENDPOINTS["actions"], True, cursor)
+ assert path == "/feed/actions?modified_after=2024-03-01T12%3A30%3A45.000Z"
+
+ def test_full_refresh_endpoint_ignores_cursor(self) -> None:
+ # The issues feed rejects/ignores modified_after — a stale watermark must never leak into it.
+ cursor = datetime(2024, 3, 1, tzinfo=UTC)
+ path = _build_initial_path(SAFETYCULTURE_ENDPOINTS["issues"], True, cursor)
+ assert path == "/feed/issues"
+
+
+class TestFormatModifiedAfter:
+ @parameterized.expand(
+ [
+ ("aware_datetime", datetime(2024, 1, 28, 23, 14, 23, tzinfo=UTC), "2024-01-28T23:14:23.000Z"),
+ ("naive_datetime", datetime(2024, 1, 28, 23, 14, 23), "2024-01-28T23:14:23.000Z"),
+ ("date", date(2024, 1, 28), "2024-01-28T00:00:00.000Z"),
+ ("string_passthrough", "2024-01-28T23:14:23.000Z", "2024-01-28T23:14:23.000Z"),
+ ]
+ )
+ def test_internet_date_time_format(self, _name: str, value: Any, expected: str) -> None:
+ # Since 2025-02-01 SafetyCulture rejects timestamps that aren't Internet Date-Time format.
+ assert _format_modified_after(value) == expected
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: dict[str, tuple[list[dict], str | None]],
+ endpoint: str = "users",
+ **kwargs: Any,
+ ) -> list[dict]:
+ fetched: list[str] = []
+
+ def fake_fetch(session: Any, path: str, logger: Any) -> tuple[list[dict], str | None]:
+ fetched.append(path)
+ return pages[path]
+
+ monkeypatch.setattr(safetyculture, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(safetyculture, "make_tracked_session", lambda **_: MagicMock())
+
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_token="sc-token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows
+
+ def test_single_page_no_next_yields_and_stops(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {"/feed/users": ([{"id": "a"}, {"id": "b"}], None)})
+ assert rows == [{"id": "a"}, {"id": "b"}]
+ # `next_page` is null, so we stop without persisting resume state.
+ assert manager.saved == []
+
+ def test_follows_next_page_verbatim(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {
+ "/feed/users": ([{"id": "a"}], "/feed/users?opaque-cursor=xyz"),
+ "/feed/users?opaque-cursor=xyz": ([{"id": "b"}], None),
+ }
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": "a"}, {"id": "b"}]
+ # State is saved after the first page yields, and holds the verbatim next_page path.
+ assert [s.next_page for s in manager.saved] == ["/feed/users?opaque-cursor=xyz"]
+
+ def test_resumes_from_saved_next_page(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager(SafetyCultureResumeConfig(next_page="/feed/users?opaque-cursor=xyz"))
+ # The initial (unfiltered) page must never be fetched on resume.
+ pages: dict[str, tuple[list[dict], str | None]] = {"/feed/users?opaque-cursor=xyz": ([{"id": "b"}], None)}
+ rows = self._collect(manager, monkeypatch, pages)
+ assert rows == [{"id": "b"}]
+
+ def test_incremental_first_request_carries_modified_after(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ cursor = datetime(2024, 3, 1, tzinfo=UTC)
+ expected_path = "/feed/inspections?archived=both&completed=both&modified_after=2024-03-01T00%3A00%3A00.000Z"
+ pages: dict[str, tuple[list[dict], str | None]] = {expected_path: ([{"id": "a"}], None)}
+ rows = self._collect(
+ manager,
+ monkeypatch,
+ pages,
+ endpoint="inspections",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=cursor,
+ )
+ assert rows == [{"id": "a"}]
+
+ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {"/feed/users": ([], None)})
+ assert rows == []
+ assert manager.saved == []
+
+ def test_empty_page_with_next_page_terminates(self, monkeypatch: Any) -> None:
+ # A lingering next_page on an empty page must not loop forever.
+ manager = _FakeResumableManager()
+ rows = self._collect(manager, monkeypatch, {"/feed/users": ([], "/feed/users?opaque-cursor=xyz")})
+ assert rows == []
+ assert manager.saved == []
+
+
+class TestFetchPage:
+ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.ok = status_code < 400
+ response.json.return_value = body if body is not None else {"metadata": {"next_page": None}, "data": []}
+ response.text = ""
+ response.raise_for_status.side_effect = (
+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None
+ )
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])
+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(SafetyCultureRetryableError):
+ _fetch_page_unwrapped(session, "/feed/users", MagicMock())
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:
+ session = self._session_returning(status)
+ with pytest.raises(requests.HTTPError):
+ _fetch_page_unwrapped(session, "/feed/users", MagicMock())
+
+ def test_success_returns_items_and_next_page(self) -> None:
+ body = {"metadata": {"next_page": "/feed/users?cursor=abc", "remaining_records": 10}, "data": [{"id": "a"}]}
+ session = self._session_returning(200, body)
+ items, next_page = _fetch_page_unwrapped(session, "/feed/users", MagicMock())
+ assert items == [{"id": "a"}]
+ assert next_page == "/feed/users?cursor=abc"
+
+ @parameterized.expand(
+ [
+ ("null_next_page", {"metadata": {"next_page": None}, "data": [{"id": "a"}]}),
+ ("missing_metadata", {"data": [{"id": "a"}]}),
+ ("empty_next_page", {"metadata": {"next_page": ""}, "data": [{"id": "a"}]}),
+ ]
+ )
+ def test_terminal_next_page_shapes_yield_none(self, _name: str, body: dict) -> None:
+ session = self._session_returning(200, body)
+ _, next_page = _fetch_page_unwrapped(session, "/feed/users", MagicMock())
+ assert next_page is None
+
+ @parameterized.expand(
+ [
+ ("non_dict_body", [{"id": "a"}]),
+ ("non_list_data", {"metadata": {}, "data": {"id": "a"}}),
+ ]
+ )
+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:
+ session = self._session_returning(200, body)
+ with pytest.raises(SafetyCultureRetryableError):
+ _fetch_page_unwrapped(session, "/feed/users", MagicMock())
+
+ def test_path_is_requested_verbatim_without_extra_params(self) -> None:
+ session = self._session_returning(200)
+ _fetch_page_unwrapped(session, "/feed/users?cursor=abc", MagicMock())
+ args, kwargs = session.get.call_args
+ assert args[0] == "https://api.safetyculture.io/feed/users?cursor=abc"
+ assert "params" not in kwargs
+
+
+class TestCheckAccess:
+ def _patch_session(self, response: Any) -> Any:
+ session = MagicMock()
+ if isinstance(response, Exception):
+ session.get.side_effect = response
+ else:
+ session.get.return_value = response
+ return mock.patch.object(safetyculture, "make_tracked_session", return_value=session)
+
+ @parameterized.expand(
+ [
+ (200, True, 200, None),
+ (401, False, 401, None),
+ (403, False, 403, None),
+ (500, False, 500, "SafetyCulture returned HTTP 500"),
+ ]
+ )
+ def test_status_mapping(self, status: int, ok: bool, expected_status: int, expected_message: str | None) -> None:
+ response = MagicMock()
+ response.status_code = status
+ response.ok = ok
+ with self._patch_session(response):
+ assert check_access("sc-token") == (expected_status, expected_message)
+
+ def test_connection_error_maps_to_zero(self) -> None:
+ with self._patch_session(requests.ConnectionError("boom")):
+ status, message = check_access("sc-token")
+ assert status == 0
+ assert message is not None and "boom" in message
+
+
+class TestSafetyCultureSourceResponse:
+ @parameterized.expand([(e,) for e in ENDPOINTS])
+ def test_source_response_shape(self, endpoint: str) -> None:
+ response = safetyculture_source(
+ api_token="sc-token",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ config = SAFETYCULTURE_ENDPOINTS[endpoint]
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+ 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
+ assert response.partition_keys is None
+
+ def test_incremental_endpoints_match_documented_modified_after_support(self) -> None:
+ # Only these four feeds document a server-side modified_after filter; flipping any other
+ # endpoint to incremental would silently ship a full-refresh-cost "incremental" sync.
+ incremental = {name for name, config in SAFETYCULTURE_ENDPOINTS.items() if config.supports_incremental}
+ assert incremental == {"inspections", "inspection_items", "templates", "actions"}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/tests/test_safetyculture_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/tests/test_safetyculture_source.py
new file mode 100644
index 000000000000..0aa7da9ac6e7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/safetyculture/tests/test_safetyculture_source.py
@@ -0,0 +1,184 @@
+import pytest
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+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 SafetyCultureSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.safetyculture.safetyculture import (
+ SafetyCultureResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.safetyculture.settings import (
+ ENDPOINTS,
+ SAFETYCULTURE_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.safetyculture.source import SafetyCultureSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestSafetyCultureSource:
+ def setup_method(self) -> None:
+ self.source = SafetyCultureSource()
+ self.team_id = 123
+ self.config = SafetyCultureSourceConfig(api_token="sc-token")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.SAFETYCULTURE
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+ assert config.name.value == "SafetyCulture"
+ assert config.label == "SafetyCulture"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source is visible — it must not carry the scaffolding flag.
+ assert not config.unreleasedSource
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/safetyculture"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["api_token"]
+
+ def test_api_token_field_is_secret_password(self) -> None:
+ config = self.source.get_source_config
+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.secret is True
+ assert field.required is True
+
+ def test_no_connection_host_fields(self) -> None:
+ # The only field is the secret API token; the base URL is hardcoded, so there is no
+ # non-secret field an editor could retarget to reuse a preserved token against another host.
+ assert self.source.connection_host_fields == []
+
+ def test_lists_tables_without_credentials(self) -> None:
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_schemas_covers_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ by_name = {s.name: s for s in schemas}
+ for name, endpoint_config in SAFETYCULTURE_ENDPOINTS.items():
+ assert by_name[name].supports_incremental is endpoint_config.supports_incremental
+ assert by_name[name].supports_append is endpoint_config.supports_incremental
+
+ def test_incremental_schemas_advertise_modified_at(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert [f["field"] for f in schemas["inspections"].incremental_fields] == ["modified_at"]
+ assert schemas["users"].incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["inspections"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "inspections"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_documented_tables_render_for_public_docs(self) -> None:
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ("401 Client Error: Unauthorized for url: https://api.safetyculture.io/feed/users",),
+ ("403 Client Error: Forbidden for url: https://api.safetyculture.io/feed/inspections?archived=both",),
+ ]
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("500 Server Error: Internal Server Error for url: https://api.safetyculture.io/feed/users",),
+ ("429 Client Error: Too Many Requests for url: https://api.safetyculture.io/feed/inspections",),
+ ]
+ )
+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:
+ non_retryable = self.source.get_non_retryable_errors()
+ assert not any(key in unrelated_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ (200, True, None),
+ (401, False, "Invalid SafetyCulture API token"),
+ # Feed access is permission-scoped, so a 403 on the probe feed still proves the token
+ # itself is genuine — it must not block source-create.
+ (403, True, None),
+ (500, False, "SafetyCulture returned HTTP 500"),
+ (0, False, "Could not connect to SafetyCulture: boom"),
+ ]
+ )
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.safetyculture.source.check_access")
+ def test_validate_credentials_at_source_create(
+ self,
+ status: int,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_check: mock.MagicMock,
+ ) -> None:
+ message = (
+ "SafetyCulture returned HTTP 500"
+ if status == 500
+ else ("Could not connect to SafetyCulture: boom" if status == 0 else None)
+ )
+ mock_check.return_value = (status, message)
+ is_valid, returned = self.source.validate_credentials(self.config, self.team_id)
+ assert is_valid is expected_valid
+ assert returned == expected_message
+
+ @parameterized.expand([(200, True), (401, False), (403, False)])
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.safetyculture.source.check_access")
+ def test_validate_credentials_for_schema_probes_that_feed(
+ self, status: int, expected_valid: bool, mock_check: mock.MagicMock
+ ) -> None:
+ mock_check.return_value = (status, None)
+ is_valid, _ = self.source.validate_credentials(self.config, self.team_id, schema_name="inspections")
+ assert is_valid is expected_valid
+ mock_check.assert_called_once_with(self.config.api_token, "/feed/inspections")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is SafetyCultureResumeConfig
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.safetyculture.source.safetyculture_source"
+ )
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "inspections"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-03-01T00:00:00.000Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once()
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_token"] == "sc-token"
+ assert kwargs["endpoint"] == "inspections"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-03-01T00:00:00.000Z"
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.safetyculture.source.safetyculture_source"
+ )
+ def test_source_for_pipeline_drops_cursor_on_full_refresh(self, mock_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "inspections"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-03-01T00:00:00.000Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["db_incremental_field_last_value"] is None
+
+ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "not_a_table"
+ with pytest.raises(ValueError, match="Unknown SafetyCulture schema 'not_a_table'"):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)