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 recreation import source (#72622)

Tom Owerscca5e80bb4fb
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 974c4465c08d..614fea29e2e7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -442,6 +442,7 @@ the row lists both.
| raygun | HTTP | requests | ✅ |
| razorpay | HTTP | requests + `rest_source.RESTClient` | ✅ |
| recharge | HTTP | requests | ✅ |
+| recreation | HTTP | requests + `rest_source.RESTClient` | ✅ |
| recruitee | HTTP | requests | ✅ |
| reddit_ads | HTTP | requests + `rest_source.RESTClient` | ✅ |
| redshift | DB protocol | psycopg (Postgres-compatible) | ➖ |
@@ -886,7 +887,6 @@ doesn't conflict with concurrent PRs.
- raygun
- rb2b
- rd_station_marketing
-- recreation
- reddit
- redis
- referralhero
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/recreation.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/recreation.py
index e9f1937b78f0..6f7e4f88c094 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/recreation.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/recreation.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class RecreationSourceConfig(config.Config):
- pass
+ api_key: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/canonical_descriptions.py
new file mode 100644
index 000000000000..c6440eb165e1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/canonical_descriptions.py
@@ -0,0 +1,222 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS_URL = "https://ridb.recreation.gov/docs"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Activities": {
+ "description": "The catalog of recreational activity types (e.g. camping, hiking, fishing) that recreation areas and facilities can offer.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "ActivityID": "Unique identifier for the activity type.",
+ "ActivityName": "Name of the activity (e.g. CAMPING, HIKING).",
+ "ActivityLevel": "Level of the activity within the activity hierarchy.",
+ "ActivityParentID": "Identifier of the parent activity when the activity is part of a hierarchy.",
+ },
+ },
+ "Campsites": {
+ "description": "Individual campsites within facilities, including type, use, accessibility, location, attributes, and permitted equipment.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "CampsiteID": "Unique identifier for the campsite.",
+ "FacilityID": "Identifier of the facility the campsite belongs to.",
+ "CampsiteName": "Name or number of the campsite.",
+ "CampsiteType": "Type of campsite (e.g. STANDARD NONELECTRIC, TENT ONLY NONELECTRIC).",
+ "TypeOfUse": "Whether the campsite is for overnight or day use.",
+ "Loop": "Campground loop the campsite sits on.",
+ "CampsiteAccessible": "Whether the campsite is wheelchair accessible.",
+ "CampsiteLatitude": "Latitude of the campsite location.",
+ "CampsiteLongitude": "Longitude of the campsite location.",
+ "CreatedDate": "Date the campsite record was created in RIDB.",
+ "LastUpdatedDate": "Date the campsite record was last updated in RIDB.",
+ "ATTRIBUTES": "List of attribute name/value pairs describing the campsite (e.g. max people, driveway length).",
+ "PERMITTEDEQUIPMENT": "List of equipment types permitted at the campsite (e.g. tent, RV) with maximum lengths.",
+ "ENTITYMEDIA": "Media (images) associated with the campsite.",
+ },
+ },
+ "Events": {
+ "description": "Events taking place at recreation areas and facilities.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "EventID": "Unique identifier for the event.",
+ "EventName": "Name of the event.",
+ "ResourceLink": "Link to the event resource.",
+ },
+ },
+ "Facilities": {
+ "description": "Recreation facilities (campgrounds, permit offices, visitor centers, trailheads) with descriptions, contact info, coordinates, and reservability.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "FacilityID": "Unique identifier for the facility.",
+ "LegacyFacilityID": "Legacy identifier carried over from the source agency system.",
+ "OrgFacilityID": "Identifier the managing organization uses for the facility.",
+ "ParentOrgID": "Identifier of the organization that manages the facility.",
+ "ParentRecAreaID": "Identifier of the recreation area the facility belongs to.",
+ "FacilityName": "Name of the facility.",
+ "FacilityDescription": "Description of the facility.",
+ "FacilityTypeDescription": "Type of facility (e.g. Campground, Permit, Facility).",
+ "FacilityUseFeeDescription": "Description of fees for using the facility.",
+ "FacilityDirections": "Driving or access directions to the facility.",
+ "FacilityPhone": "Contact phone number for the facility.",
+ "FacilityEmail": "Contact email address for the facility.",
+ "FacilityReservationURL": "URL for making reservations at the facility.",
+ "FacilityMapURL": "URL of a map for the facility.",
+ "FacilityAdaAccess": "ADA accessibility information for the facility.",
+ "GEOJSON": "GeoJSON geometry for the facility location.",
+ "FacilityLatitude": "Latitude of the facility location.",
+ "FacilityLongitude": "Longitude of the facility location.",
+ "Keywords": "Search keywords associated with the facility.",
+ "StayLimit": "Stay limit for the facility.",
+ "Reservable": "Whether the facility is reservable.",
+ "Enabled": "Whether the facility is enabled in RIDB.",
+ "LastUpdatedDate": "Date the facility record was last updated in RIDB.",
+ },
+ },
+ "FacilityAddresses": {
+ "description": "Physical and mailing addresses for facilities.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "FacilityAddressID": "Unique identifier for the facility address.",
+ "FacilityID": "Identifier of the facility the address belongs to.",
+ "FacilityAddressType": "Type of address (e.g. Default, Physical, Mailing).",
+ "FacilityStreetAddress1": "First street address line.",
+ "FacilityStreetAddress2": "Second street address line.",
+ "FacilityStreetAddress3": "Third street address line.",
+ "City": "City of the address.",
+ "PostalCode": "Postal code of the address.",
+ "AddressStateCode": "State code of the address.",
+ "AddressCountryCode": "Country code of the address.",
+ "LastUpdatedDate": "Date the address record was last updated in RIDB.",
+ },
+ },
+ "Links": {
+ "description": "Links (official websites, maps, downloadable documents) attached to recreation areas and facilities.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "EntityLinkID": "Unique identifier for the link.",
+ "EntityID": "Identifier of the entity (facility or recreation area) the link belongs to.",
+ "EntityType": "Type of entity the link belongs to (e.g. Facility, RecArea).",
+ "LinkType": "Type of link (e.g. Official Web Site, Map).",
+ "Title": "Title of the link.",
+ "Description": "Description of the link.",
+ "URL": "The link URL.",
+ },
+ },
+ "Media": {
+ "description": "Media items (images, videos, webcams) attached to recreation areas, facilities, and campsites.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "EntityMediaID": "Unique identifier for the media item.",
+ "EntityID": "Identifier of the entity the media belongs to.",
+ "EntityType": "Type of entity the media belongs to (e.g. Facility, RecArea, Campsite).",
+ "MediaType": "Type of media (e.g. Image, Video, Webcam).",
+ "Title": "Title of the media item.",
+ "Subtitle": "Subtitle of the media item.",
+ "Description": "Description of the media item.",
+ "EmbedCode": "Embed code for the media item.",
+ "URL": "URL of the media item.",
+ "Credits": "Attribution credits for the media item.",
+ "Height": "Height of the media in pixels.",
+ "Width": "Width of the media in pixels.",
+ "IsPrimary": "Whether this is the entity's primary media item.",
+ "IsPreview": "Whether this media item is used as the entity's preview.",
+ "IsGallery": "Whether this media item is part of the entity's gallery.",
+ },
+ },
+ "Organizations": {
+ "description": "Federal agencies and organizations (e.g. National Park Service, USDA Forest Service) that contribute recreation data to RIDB.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "OrgID": "Unique identifier for the organization.",
+ "OrgName": "Full name of the organization.",
+ "OrgAbbrevName": "Abbreviated name of the organization.",
+ "OrgType": "Type of organization.",
+ "OrgJurisdictionType": "Jurisdiction type of the organization (e.g. Federal, State).",
+ "OrgParentID": "Identifier of the parent organization, when applicable.",
+ "OrgImageURL": "URL of the organization's logo image.",
+ "OrgURLAddress": "Website address of the organization.",
+ "OrgURLText": "Display text for the organization's website link.",
+ "LastUpdatedDate": "Date the organization record was last updated in RIDB.",
+ },
+ },
+ "PermitEntrances": {
+ "description": "Permit entrances (wilderness areas, river launch points, lottery entrances) where recreation permits apply, with zones and attributes.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "PermitEntranceID": "Unique identifier for the permit entrance.",
+ "FacilityID": "Identifier of the facility the permit entrance belongs to.",
+ "PermitEntranceName": "Name of the permit entrance.",
+ "PermitEntranceDescription": "Description of the permit entrance.",
+ "District": "District where the permit entrance is located.",
+ "Town": "Town where the permit entrance is located.",
+ "PermitEntranceAccessible": "Whether the permit entrance is accessible.",
+ "Latitude": "Latitude of the permit entrance.",
+ "Longitude": "Longitude of the permit entrance.",
+ "GEOSJON": "GeoJSON geometry for the permit entrance (field name as returned by the API).",
+ "CreatedDate": "Date the permit entrance record was created in RIDB.",
+ "LastUpdatedDate": "Date the permit entrance record was last updated in RIDB.",
+ "ATTRIBUTES": "List of attribute name/value pairs describing the permit entrance.",
+ "ZONES": "Permit zones associated with the entrance.",
+ },
+ },
+ "RecAreas": {
+ "description": "Recreation areas (national parks, forests, lakes) with descriptions, contact info, coordinates, and reservability.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "RecAreaID": "Unique identifier for the recreation area.",
+ "OrgRecAreaID": "Identifier the managing organization uses for the recreation area.",
+ "ParentOrgID": "Identifier of the organization that manages the recreation area.",
+ "RecAreaName": "Name of the recreation area.",
+ "RecAreaDescription": "Description of the recreation area.",
+ "RecAreaFeeDescription": "Description of fees for the recreation area.",
+ "RecAreaDirections": "Driving or access directions to the recreation area.",
+ "RecAreaPhone": "Contact phone number for the recreation area.",
+ "RecAreaEmail": "Contact email address for the recreation area.",
+ "RecAreaReservationURL": "URL for making reservations in the recreation area.",
+ "RecAreaMapURL": "URL of a map for the recreation area.",
+ "GEOJSON": "GeoJSON geometry for the recreation area.",
+ "RecAreaLatitude": "Latitude of the recreation area.",
+ "RecAreaLongitude": "Longitude of the recreation area.",
+ "Keywords": "Search keywords associated with the recreation area.",
+ "StayLimit": "Stay limit for the recreation area.",
+ "Reservable": "Whether the recreation area is reservable.",
+ "Enabled": "Whether the recreation area is enabled in RIDB.",
+ "LastUpdatedDate": "Date the recreation area record was last updated in RIDB.",
+ },
+ },
+ "RecAreaAddresses": {
+ "description": "Physical and mailing addresses for recreation areas.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "RecAreaAddressID": "Unique identifier for the recreation area address.",
+ "RecAreaID": "Identifier of the recreation area the address belongs to.",
+ "RecAreaAddressType": "Type of address (e.g. Default, Physical, Mailing).",
+ "RecAreaStreetAddress1": "First street address line.",
+ "RecAreaStreetAddress2": "Second street address line.",
+ "RecAreaStreetAddress3": "Third street address line.",
+ "City": "City of the address.",
+ "PostalCode": "Postal code of the address.",
+ "AddressStateCode": "State code of the address.",
+ "AddressCountryCode": "Country code of the address.",
+ "LastUpdatedDate": "Date the address record was last updated in RIDB.",
+ },
+ },
+ "Tours": {
+ "description": "Ticketed and guided tours offered at facilities, with duration, type, accessibility, and member tours.",
+ "docs_url": _DOCS_URL,
+ "columns": {
+ "TourID": "Unique identifier for the tour.",
+ "FacilityID": "Identifier of the facility the tour belongs to.",
+ "TourName": "Name of the tour.",
+ "TourType": "Type of tour (e.g. Guided, Self-Guided).",
+ "TourDescription": "Description of the tour.",
+ "TourDuration": "Duration of the tour in minutes.",
+ "TourAccessible": "Whether the tour is accessible.",
+ "CreatedDate": "Date the tour record was created in RIDB.",
+ "LastUpdatedDate": "Date the tour record was last updated in RIDB.",
+ "ATTRIBUTES": "List of attribute name/value pairs describing the tour.",
+ "MEMBERTOURS": "Member tours included within this tour.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/recreation.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/recreation.py
new file mode 100644
index 000000000000..f7934fc83e5d
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/recreation.py
@@ -0,0 +1,134 @@
+import dataclasses
+from typing import Any, Optional
+
+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.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ OffsetPaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import EndpointResource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.recreation.settings import (
+ PAGE_LIMIT,
+ RECREATION_ENDPOINTS,
+ RIDB_BASE_URL,
+)
+
+VALIDATION_TIMEOUT_SECONDS = 10
+
+
+class RecreationResumeConfig:
+ offset: int
+
+
+def _build_paginator() -> OffsetPaginator:
+ # RIDB reports the grand total at METADATA.RESULTS.TOTAL_COUNT, so pagination stops
+ # without paying an extra empty-page request; the short-page check is the fallback.
+ return OffsetPaginator(limit=PAGE_LIMIT, total_path="METADATA.RESULTS.TOTAL_COUNT")
+
+
+def get_resource(endpoint: str) -> EndpointResource:
+ config = RECREATION_ENDPOINTS[endpoint]
+ return {
+ "name": config.name,
+ "table_name": config.name.lower(),
+ "write_disposition": "replace",
+ "endpoint": {
+ "data_selector": "RECDATA",
+ "path": config.path,
+ "paginator": _build_paginator(),
+ },
+ "table_format": "delta",
+ }
+
+
+def recreation_source(
+ api_key: str,
+ endpoint: str,
+ team_id: int,
+ job_id: str,
+ resumable_source_manager: ResumableSourceManager[RecreationResumeConfig],
+) -> SourceResponse:
+ endpoint_config = RECREATION_ENDPOINTS[endpoint]
+
+ config: RESTAPIConfig = {
+ "client": {
+ "base_url": RIDB_BASE_URL,
+ "auth": {
+ "type": "api_key",
+ "name": "apikey",
+ "api_key": api_key,
+ "location": "header",
+ },
+ "headers": {"Accept": "application/json"},
+ # The apikey credential rides a custom header, which `requests` would replay to a
+ # cross-origin redirect target (unlike `Authorization`) — refuse redirects instead.
+ "allow_redirects": False,
+ },
+ "resource_defaults": {
+ "write_disposition": "replace",
+ },
+ "resources": [get_resource(endpoint)],
+ }
+
+ initial_paginator_state: Optional[dict[str, Any]] = None
+ if resumable_source_manager.can_resume():
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None:
+ initial_paginator_state = {"offset": resume_config.offset}
+
+ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
+ # Only persist when there's a next page to resume to; the Redis TTL
+ # handles cleanup on completion.
+ if state and state.get("offset") is not None:
+ resumable_source_manager.save_state(RecreationResumeConfig(offset=int(state["offset"])))
+
+ resource = rest_api_resource(
+ config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
+
+ partition_kwargs: dict[str, Any] = {}
+ if endpoint_config.partition_key is not None:
+ partition_kwargs = {
+ "partition_count": 1,
+ "partition_size": 1,
+ "partition_mode": "datetime",
+ "partition_format": "month",
+ "partition_keys": [endpoint_config.partition_key],
+ }
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: resource,
+ primary_keys=[endpoint_config.primary_key],
+ **partition_kwargs,
+ )
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ try:
+ # `allow_redirects=False` matches the sync path's credential boundary: never replay
+ # the apikey header to a redirect target.
+ res = make_tracked_session(redact_values=(api_key,), allow_redirects=False).get(
+ f"{RIDB_BASE_URL}/activities",
+ params={"limit": 1},
+ headers={"apikey": api_key, "Accept": "application/json"},
+ timeout=VALIDATION_TIMEOUT_SECONDS,
+ )
+ if res.status_code == 200:
+ return True, None
+ if res.status_code in (401, 403):
+ return False, "Invalid RIDB API key. Copy the key from your profile at ridb.recreation.gov and try again."
+ return False, f"RIDB API returned an unexpected response (HTTP {res.status_code})"
+ except Exception as e:
+ return False, str(e)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/settings.py
new file mode 100644
index 000000000000..e012948389ce
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/settings.py
@@ -0,0 +1,91 @@
+from dataclasses import dataclass
+
+from products.warehouse_sources.backend.types import IncrementalField
+
+RIDB_BASE_URL = "https://ridb.recreation.gov/api/v1"
+
+# RIDB caps the `limit` query param at 50 records per page.
+PAGE_LIMIT = 50
+
+
+@dataclass(frozen=True)
+class RecreationEndpointConfig:
+ name: str
+ path: str
+ primary_key: str
+ # Stable creation timestamp for datetime partitioning. Most RIDB entities only expose
+ # LastUpdatedDate, which changes over time and is unsafe as a partition key.
+ partition_key: str | None = None
+
+
+RECREATION_ENDPOINTS: dict[str, RecreationEndpointConfig] = {
+ "Activities": RecreationEndpointConfig(
+ name="Activities",
+ path="/activities",
+ primary_key="ActivityID",
+ ),
+ "Campsites": RecreationEndpointConfig(
+ name="Campsites",
+ path="/campsites",
+ primary_key="CampsiteID",
+ partition_key="CreatedDate",
+ ),
+ "Events": RecreationEndpointConfig(
+ name="Events",
+ path="/events",
+ primary_key="EventID",
+ ),
+ "Facilities": RecreationEndpointConfig(
+ name="Facilities",
+ path="/facilities",
+ primary_key="FacilityID",
+ ),
+ "FacilityAddresses": RecreationEndpointConfig(
+ name="FacilityAddresses",
+ path="/facilityaddresses",
+ primary_key="FacilityAddressID",
+ ),
+ "Links": RecreationEndpointConfig(
+ name="Links",
+ path="/links",
+ primary_key="EntityLinkID",
+ ),
+ "Media": RecreationEndpointConfig(
+ name="Media",
+ path="/media",
+ primary_key="EntityMediaID",
+ ),
+ "Organizations": RecreationEndpointConfig(
+ name="Organizations",
+ path="/organizations",
+ primary_key="OrgID",
+ ),
+ "PermitEntrances": RecreationEndpointConfig(
+ name="PermitEntrances",
+ path="/permits",
+ primary_key="PermitEntranceID",
+ partition_key="CreatedDate",
+ ),
+ "RecAreas": RecreationEndpointConfig(
+ name="RecAreas",
+ path="/recareas",
+ primary_key="RecAreaID",
+ ),
+ "RecAreaAddresses": RecreationEndpointConfig(
+ name="RecAreaAddresses",
+ path="/recareaaddresses",
+ primary_key="RecAreaAddressID",
+ ),
+ "Tours": RecreationEndpointConfig(
+ name="Tours",
+ path="/tours",
+ primary_key="TourID",
+ partition_key="CreatedDate",
+ ),
+}
+
+ENDPOINTS = tuple(RECREATION_ENDPOINTS.keys())
+
+# RIDB has no server-side timestamp filter on any list endpoint (query params cover
+# state/activity/keyword/radius only), so every endpoint is full refresh.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/source.py
index b1443183afcd..fe7d0d13a52a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/source.py
@@ -1,32 +1,121 @@
-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,
+ build_endpoint_schemas,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.recreation import (
RecreationSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.recreation.recreation import (
+ RecreationResumeConfig,
+ recreation_source,
+ validate_credentials as validate_recreation_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.recreation.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class RecreationSource(SimpleSource[RecreationSourceConfig]):
+class RecreationSource(ResumableSource[RecreationSourceConfig, RecreationResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://ridb.recreation.gov/docs"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.RECREATION
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://ridb.recreation.gov": "Your RIDB API key is invalid or expired. Copy the key from your profile at ridb.recreation.gov and reconnect.",
+ "403 Client Error: Forbidden for url: https://ridb.recreation.gov": "Your RIDB API key was rejected. Copy the key from your profile at ridb.recreation.gov and reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.recreation.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: RecreationSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self, config: RecreationSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_recreation_credentials(config.api_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RecreationResumeConfig]:
+ return ResumableSourceManager[RecreationResumeConfig](inputs, RecreationResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: RecreationSourceConfig,
+ resumable_source_manager: ResumableSourceManager[RecreationResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return recreation_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ resumable_source_manager=resumable_source_manager,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.RECREATION,
category=DataWarehouseSourceCategory.ANALYTICS,
- label="Recreation",
+ label="Recreation.gov",
+ caption="""Import public US federal recreation data from the Recreation Information Database (RIDB) behind Recreation.gov: recreation areas, facilities, campsites, tours, permit entrances, and more.
+
+To get an API key, sign in at [ridb.recreation.gov](https://ridb.recreation.gov/), open your profile from the account menu, and copy the API key shown there.""",
+ keywords=["ridb", "recreation.gov", "campgrounds", "campsites"],
+ docsUrl="https://posthog.com/docs/cdp/sources/recreation",
iconPath="/static/services/recreation.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="Enter your RIDB API key",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/tests/test_recreation.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/tests/test_recreation.py
new file mode 100644
index 000000000000..a1d304df219a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/tests/test_recreation.py
@@ -0,0 +1,127 @@
+import json
+from collections.abc import Iterable
+from typing import Any, cast
+
+from unittest.mock import MagicMock, patch
+
+from requests import Response
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.recreation.recreation import (
+ RecreationResumeConfig,
+ recreation_source,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.recreation.settings import PAGE_LIMIT
+
+
+def _ridb_response(records: list[dict[str, Any]], total_count: int, offset: int) -> Response:
+ resp = Response()
+ resp.status_code = 200
+ resp._content = json.dumps(
+ {
+ "RECDATA": records,
+ "METADATA": {
+ "RESULTS": {"CURRENT_COUNT": len(records), "TOTAL_COUNT": total_count},
+ "SEARCH_PARAMETERS": {"QUERY": "", "LIMIT": PAGE_LIMIT, "OFFSET": offset},
+ },
+ }
+ ).encode()
+ resp.headers["Content-Type"] = "application/json"
+ return resp
+
+
+def _facility_rows(start: int, count: int) -> list[dict[str, Any]]:
+ return [{"FacilityID": str(i), "FacilityName": f"Facility {i}"} for i in range(start, start + count)]
+
+
+class TestRecreationSourceTransport:
+ def _drive(
+ self, endpoint: str, manager: MagicMock, responses: list[Response]
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
+ """Drive ``recreation_source`` with a mocked HTTP session.
+
+ Returns ``(rows, sent_params)``. ``sent_params`` holds shallow copies of
+ ``request.params`` captured at send-time because the paginator mutates the
+ Request object in place between pages.
+ """
+ sent_params: list[dict[str, Any]] = []
+ response_iter = iter(responses)
+
+ def fake_send(request: Any, *_args: Any, **_kwargs: Any) -> Response:
+ sent_params.append(dict(request.params or {}))
+ return next(response_iter)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client.make_tracked_session"
+ ) as MockSession:
+ mock_session = MockSession.return_value
+ mock_session.headers = {}
+ mock_session.prepare_request.side_effect = lambda req: req
+ mock_session.send.side_effect = fake_send
+
+ source_response = recreation_source(
+ api_key="test-key",
+ endpoint=endpoint,
+ team_id=123,
+ job_id="test_job",
+ resumable_source_manager=manager,
+ )
+ rows: list[dict[str, Any]] = []
+ for page in cast(Iterable[Any], source_response.items()):
+ rows.extend(page if isinstance(page, list) else [page])
+ return rows, sent_params
+
+ def test_fresh_run_paginates_to_total_count_and_checkpoints(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ # 100 total records across two full pages: pagination must stop at TOTAL_COUNT
+ # without paying a third, empty-page request.
+ responses = [
+ _ridb_response(_facility_rows(0, PAGE_LIMIT), total_count=100, offset=0),
+ _ridb_response(_facility_rows(PAGE_LIMIT, PAGE_LIMIT), total_count=100, offset=PAGE_LIMIT),
+ ]
+ rows, sent_params = self._drive("Facilities", manager, responses)
+
+ assert len(rows) == 100
+ assert rows[0]["FacilityID"] == "0"
+ assert [p.get("offset") for p in sent_params] == [0, PAGE_LIMIT]
+ assert all(p.get("limit") == PAGE_LIMIT for p in sent_params)
+
+ # The api key must ride the header, never the query string.
+ assert all("apikey" not in p for p in sent_params)
+
+ # State is saved only after the non-terminal page, pointing at the next offset.
+ saved = [call.args[0] for call in manager.save_state.call_args_list]
+ assert saved == [RecreationResumeConfig(offset=PAGE_LIMIT)]
+
+ def test_short_page_terminates_without_saving_state(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_ridb_response(_facility_rows(0, 3), total_count=3, offset=0)]
+ rows, sent_params = self._drive("Facilities", manager, responses)
+
+ assert len(rows) == 3
+ assert len(sent_params) == 1
+ manager.save_state.assert_not_called()
+
+ def test_resume_seeds_paginator_with_saved_offset(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = RecreationResumeConfig(offset=150)
+
+ responses = [_ridb_response(_facility_rows(150, 10), total_count=160, offset=150)]
+ _, sent_params = self._drive("Facilities", manager, responses)
+
+ assert [p.get("offset") for p in sent_params] == [150]
+ manager.load_state.assert_called_once()
+
+ def test_does_not_load_state_when_cannot_resume(self) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ responses = [_ridb_response(_facility_rows(0, 1), total_count=1, offset=0)]
+ self._drive("Facilities", manager, responses)
+
+ manager.load_state.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/tests/test_recreation_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/tests/test_recreation_source.py
new file mode 100644
index 000000000000..5b8330fb0ed5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/recreation/tests/test_recreation_source.py
@@ -0,0 +1,114 @@
+from typing import Optional
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.recreation import (
+ RecreationSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.recreation.recreation import (
+ RecreationResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.recreation.settings import RECREATION_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.recreation.source import RecreationSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _source_inputs(schema_name: str) -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-1",
+ source_id="source-1",
+ team_id=1,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field=None,
+ incremental_field_type=None,
+ job_id="job-1",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+class TestRecreationSource:
+ def setup_method(self) -> None:
+ self.source = RecreationSource()
+ self.config = RecreationSourceConfig(api_key="test-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.RECREATION
+
+ def test_source_is_released_with_alpha_status(self) -> None:
+ config = self.source.get_source_config
+ assert not config.unreleasedSource
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ def test_api_key_field_is_secret_password(self) -> None:
+ fields = self.source.get_source_config.fields
+ assert [f.name for f in fields] == ["api_key"]
+ field = fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.secret is True
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.required is True
+
+ def test_get_schemas_returns_full_refresh_only_catalog(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=1)
+ assert {s.name for s in schemas} == set(RECREATION_ENDPOINTS.keys())
+ assert all(not s.supports_incremental and not s.supports_append for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, team_id=1, names=["Facilities", "Campsites"])
+ assert {s.name for s in schemas} == {"Facilities", "Campsites"}
+
+ @pytest.mark.parametrize(
+ ("status_code", "expected_valid", "expected_error_fragment"),
+ [
+ (200, True, None),
+ (401, False, "Invalid RIDB API key"),
+ (403, False, "Invalid RIDB API key"),
+ (500, False, "unexpected response"),
+ ],
+ )
+ def test_validate_credentials_status_mapping(
+ self, status_code: int, expected_valid: bool, expected_error_fragment: Optional[str]
+ ) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.recreation.recreation.make_tracked_session"
+ ) as mock_session_factory:
+ mock_session_factory.return_value.get.return_value.status_code = status_code
+ valid, error = self.source.validate_credentials(self.config, team_id=1)
+
+ assert valid is expected_valid
+ if expected_error_fragment is None:
+ assert error is None
+ else:
+ assert error is not None and expected_error_fragment in error
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_source_inputs("Facilities"))
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is RecreationResumeConfig
+
+ @pytest.mark.parametrize("endpoint", list(RECREATION_ENDPOINTS.keys()))
+ def test_source_for_pipeline_maps_endpoint_to_response(self, endpoint: str) -> None:
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.can_resume.return_value = False
+
+ response = self.source.source_for_pipeline(self.config, manager, _source_inputs(endpoint))
+
+ endpoint_config = RECREATION_ENDPOINTS[endpoint]
+ assert response.name == endpoint
+ assert response.primary_keys == [endpoint_config.primary_key]
+ if endpoint_config.partition_key is not None:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [endpoint_config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None