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 campfire import source (#71469)

Tom Owers9c53bc3118ba
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 8c5d2c70fe90..95608f1ff63a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -109,6 +109,7 @@ the row lists both.
| callrail | HTTP | requests | ✅ |
| campaign_monitor | HTTP | requests | ✅ |
| campayn | HTTP | requests | ✅ |
+| campfire | HTTP | requests | ✅ |
| canny | HTTP | requests | ✅ |
| capsule_crm | HTTP | requests | ✅ |
| care_quality_commission | HTTP | requests | ✅ |
@@ -635,7 +636,6 @@ doesn't conflict with concurrent PRs.
- browse_ai
- cal_com
- campaign_manager_360
-- campfire
- captain_data
- cart_com
- castor_edc
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/campfire.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/campfire.py
new file mode 100644
index 000000000000..8adbbc567452
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/campfire.py
@@ -0,0 +1,214 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode, urlparse
+
+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.campfire.settings import (
+ CAMPFIRE_BASE_URL,
+ CAMPFIRE_ENDPOINTS,
+ CampfireEndpointConfig,
+)
+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
+
+# Bound the paginator so a misbehaving `next` chain can't loop forever.
+MAX_PAGES = 100_000
+
+
+class CampfireRetryableError(Exception):
+ pass
+
+
+class CampfireResumeConfig:
+ # The `next` link of the last fully-yielded page. Absolute URL on api.meetcampfire.com,
+ # carrying the pagination cursor/offset plus any incremental filter for this job.
+ next_url: str
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Token {api_key}",
+ "Accept": "application/json",
+ }
+
+
+def _format_incremental_value(value: Any) -> str:
+ """Format the watermark for `last_modified_at__gte`, which accepts ISO 8601."""
+ if isinstance(value, datetime):
+ utc_value = value.astimezone(UTC) if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return utc_value.strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return value.isoformat()
+ return str(value)
+
+
+def _build_first_url(
+ config: CampfireEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Optional[Any],
+) -> str:
+ params: dict[str, Any] = {"limit": config.page_size, **config.extra_params}
+ if config.use_cursor:
+ # An empty `cursor=` opts the endpoint into cursor pagination; every later page
+ # comes from the response's `next` link.
+ params["cursor"] = ""
+ if should_use_incremental_field and config.incremental_fields and db_incremental_field_last_value is not None:
+ params["last_modified_at__gte"] = _format_incremental_value(db_incremental_field_last_value)
+ return f"{CAMPFIRE_BASE_URL}{config.path}?{urlencode(params)}"
+
+
+def _validate_next_url(next_url: str) -> None:
+ """Only follow `next` links that stay on the Campfire API host.
+
+ The API key rides in a header on every request, so following an off-host link would
+ hand the credential to whatever host the response named.
+ """
+ parsed = urlparse(next_url)
+ expected = urlparse(CAMPFIRE_BASE_URL)
+ if parsed.scheme != "https" or parsed.netloc != expected.netloc:
+ raise ValueError(f"Campfire returned a next link on an unexpected host: {parsed.netloc!r}")
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ CampfireRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> Any:
+ response = session.get(url, headers=headers, timeout=60)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise CampfireRetryableError(f"Campfire API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # Log status and URL only — error bodies can echo request data from an accounting
+ # system, which must not spill into application logs.
+ logger.error(f"Campfire API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def _parse_page(data: Any) -> tuple[list[dict[str, Any]], str | None]:
+ """Split a response into (rows, next link) for both DRF envelopes and bare lists."""
+ if isinstance(data, dict):
+ results = data.get("results") or []
+ return results, data.get("next")
+ if isinstance(data, list):
+ return data, None
+ return [], None
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CampfireResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = CAMPFIRE_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key)
+ # One session reused across every page so urllib3 keeps the connection alive.
+ # capture=False keeps accounting responses (amounts, invoice/transaction IDs, free-form
+ # business fields the name-based scrubbers can't recognise) out of HTTP sample storage.
+ session = make_tracked_session(redact_values=(api_key,), capture=False)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.next_url:
+ _validate_next_url(resume.next_url)
+ url = resume.next_url
+ logger.debug(f"Campfire: resuming {endpoint} from URL: {url}")
+ else:
+ url = _build_first_url(config, should_use_incremental_field, db_incremental_field_last_value)
+
+ pages = 0
+ while True:
+ data = _fetch_page(session, url, headers, logger)
+ results, next_url = _parse_page(data)
+ if next_url is not None:
+ _validate_next_url(next_url)
+
+ if results:
+ yield results
+ # Save AFTER yielding (and only when more pages remain) so a crash re-yields the
+ # last page rather than skipping it — merge dedupes on the primary key.
+ if next_url:
+ resumable_source_manager.save_state(CampfireResumeConfig(next_url=next_url))
+
+ if not next_url:
+ break
+
+ url = next_url
+ pages += 1
+ if pages >= MAX_PAGES:
+ logger.error(f"Campfire: page cap of {MAX_PAGES} reached for endpoint {endpoint}; truncating sync")
+ break
+
+
+def campfire_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[CampfireResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = CAMPFIRE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ 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,
+ # "desc" endpoints persist the incremental watermark only at successful job end —
+ # their response order is undocumented, so per-batch persistence could advance the
+ # watermark past rows a crashed run still owes.
+ sort_mode=config.sort_mode,
+ 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,
+ )
+
+
+def validate_credentials(api_key: str, path: str | None = None) -> bool:
+ """Probe the key with the cheapest call on the given endpoint (chart of accounts when
+ unset — every Campfire role, including view-only, can GET it)."""
+ probe_path = path or CAMPFIRE_ENDPOINTS["chart_of_accounts"].path
+ try:
+ response = make_tracked_session(redact_values=(api_key,), capture=False).get(
+ f"{CAMPFIRE_BASE_URL}{probe_path}?{urlencode({'limit': 1})}",
+ headers=_get_headers(api_key),
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/canonical_descriptions.py
new file mode 100644
index 000000000000..9212ce341578
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/canonical_descriptions.py
@@ -0,0 +1,172 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "chart_transactions": {
+ "description": "General-ledger transactions (ChartTransaction records) - Campfire's GL transaction log and the recommended endpoint for row-level GL data. Each transaction carries account, department, vendor, entity, and journal/date metadata.",
+ "docs_url": "https://docs.campfire.ai/api-reference/core-accounting/list-chart-transactions",
+ "columns": {
+ "id": "Unique identifier for the GL transaction.",
+ "amount": "Amount in the consolidated currency (the root entity's currency).",
+ "amount_book": "Amount in the currency of the entity the transaction belongs to.",
+ "amount_native": "Amount in the currency the transaction was originally created in.",
+ "posted_at": "The transaction date; determines which accounting period the transaction falls in.",
+ "vendor": "ID of the linked Campfire Vendor object.",
+ "vendor_name": "Name of the linked Campfire Vendor object.",
+ "merchant_name": "Free-text merchant name stored directly on the transaction; not linked to any Campfire object.",
+ "account": "The Campfire ChartAccount (GL account) the transaction is posted to.",
+ "entity": "The Campfire ChartEntity ID the transaction belongs to.",
+ "last_modified_at": "Timestamp of the last modification to the transaction.",
+ },
+ },
+ "journal_entries": {
+ "description": "Journal entries with their transactions, account information, vendor and department details, tag associations, attachments, and exchange rate data for multi-currency entries.",
+ "docs_url": "https://docs.campfire.ai/api-reference/core-accounting/list-journal-entries",
+ "columns": {
+ "id": "Unique identifier for the journal entry.",
+ "date": "The journal entry date, which determines the accounting period.",
+ "created_at": "Timestamp when the journal entry was created.",
+ "last_modified_at": "Timestamp of the last modification to the journal entry.",
+ },
+ },
+ "invoices": {
+ "description": "Accounts receivable invoices, including line items, payment status, client and entity relationships, and totals.",
+ "docs_url": "https://docs.campfire.ai/api-reference/accounts-receivable/list-invoices",
+ "columns": {
+ "id": "Unique identifier for the invoice.",
+ "invoice_date": "The invoice date.",
+ "created_at": "Timestamp when the invoice was created.",
+ "last_modified_at": "Timestamp of the last modification to the invoice.",
+ },
+ },
+ "invoice_payments": {
+ "description": "Payments applied against accounts receivable invoices. Voided payments are included with voided_date set, so payments reversed after a previous sync can be detected.",
+ "docs_url": "https://docs.campfire.ai/api-reference/accounts-receivable/list-invoice-payments",
+ "columns": {
+ "id": "Unique identifier for the invoice payment.",
+ "amount": "Payment amount.",
+ "currency": "Payment currency.",
+ "payment_date": "Date the payment was applied.",
+ "source": "Where the payment originated.",
+ "source_id": "Identifier of the payment in its source system.",
+ "voided_date": "Date the payment was voided, when it has been reversed.",
+ "created_at": "Timestamp when the payment record was created.",
+ "last_modified_at": "Timestamp of the last modification to the payment record.",
+ },
+ },
+ "credit_memos": {
+ "description": "Accounts receivable credit memos, including line items, application status (open, partially used, used, voided), and client relationships.",
+ "docs_url": "https://docs.campfire.ai/api-reference/accounts-receivable/list-credit-memos",
+ "columns": {
+ "id": "Unique identifier for the credit memo.",
+ "credit_memo_date": "The credit memo date.",
+ "created_at": "Timestamp when the credit memo was created.",
+ "last_modified_at": "Timestamp of the last modification to the credit memo.",
+ },
+ },
+ "bills": {
+ "description": "Accounts payable bills with vendor, entity, currency, aging, and payment status information, including calculated totals, amounts paid, and amounts due.",
+ "docs_url": "https://docs.campfire.ai/api-reference/accounts-payable/list-accounting-bills",
+ "columns": {
+ "id": "Unique identifier for the bill.",
+ "last_modified_at": "Timestamp of the last modification to the bill.",
+ },
+ },
+ "bill_payments": {
+ "description": "Payments applied against accounts payable bills. Voided payments are included with voided_date set, so payments reversed after a previous sync can be detected.",
+ "docs_url": "https://docs.campfire.ai/api-reference/accounts-payable/list-bill-payments",
+ "columns": {
+ "id": "Unique identifier for the bill payment.",
+ "bill_id": "ID of the bill the payment was applied to.",
+ "bill_number": "Number of the bill the payment was applied to.",
+ "amount": "Payment amount.",
+ "currency": "Payment currency.",
+ "payment_date": "Date the payment was applied.",
+ "source": "Where the payment originated.",
+ "source_id": "Identifier of the payment in its source system.",
+ "voided_date": "Date the payment was voided, when it has been reversed.",
+ "created_at": "Timestamp when the payment record was created.",
+ "last_modified_at": "Timestamp of the last modification to the payment record.",
+ },
+ },
+ "debit_memos": {
+ "description": "Accounts payable debit memos, including line items, status, and vendor relationships.",
+ "docs_url": "https://docs.campfire.ai/api-reference/accounts-payable/list-debit-memos",
+ "columns": {
+ "id": "Unique identifier for the debit memo.",
+ "debit_memo_date": "The debit memo date.",
+ "created_at": "Timestamp when the debit memo was created.",
+ "last_modified_at": "Timestamp of the last modification to the debit memo.",
+ },
+ },
+ "bank_accounts": {
+ "description": "Bank accounts with balances, currency, institution details, and their mapping to chart of accounts types.",
+ "docs_url": "https://docs.campfire.ai/api-reference/cash-management/list-bank-accounts",
+ "columns": {
+ "id": "Unique identifier for the bank account.",
+ "created_at": "Timestamp when the bank account record was created.",
+ "last_modified_at": "Timestamp of the last modification to the bank account record.",
+ },
+ },
+ "bank_transactions": {
+ "description": "Bank transactions from connected bank accounts.",
+ "docs_url": "https://docs.campfire.ai/api-reference/cash-management/list-bank-transactions",
+ "columns": {
+ "id": "Unique identifier for the bank transaction.",
+ "posted_at": "Date the transaction posted at the bank.",
+ "created_at": "Timestamp when the bank transaction record was created.",
+ "last_modified_at": "Timestamp of the last modification to the bank transaction record.",
+ },
+ },
+ "vendors": {
+ "description": "Vendors and customers, including contact details, parent vendor metadata, and the full lineage of ancestor vendors so parent/child relationships can be reconstructed.",
+ "docs_url": "https://docs.campfire.ai/api-reference/company-objects/list-vendors",
+ "columns": {
+ "id": "Unique identifier for the vendor.",
+ "name": "Vendor or customer name.",
+ "vendor_type": "Whether the record is a vendor or a customer.",
+ "parent_name": "Name of the parent vendor, when the vendor has one.",
+ "created_at": "Timestamp when the vendor record was created.",
+ "last_modified_at": "Timestamp of the last modification to the vendor record.",
+ },
+ },
+ "departments": {
+ "description": "Departments, including parent department metadata so parent/child relationships can be reconstructed.",
+ "docs_url": "https://docs.campfire.ai/api-reference/company-objects/list-departments",
+ "columns": {
+ "id": "Unique identifier for the department.",
+ "created_at": "Timestamp when the department record was created.",
+ "last_modified_at": "Timestamp of the last modification to the department record.",
+ },
+ },
+ "chart_of_accounts": {
+ "description": "The chart of accounts (GL accounts). Each account includes metadata about its parent account and its full lineage, so parent/child account relationships can be reconstructed.",
+ "docs_url": "https://docs.campfire.ai/api-reference/company-objects/list-chart-of-accounts",
+ "columns": {
+ "id": "Unique identifier for the GL account.",
+ "created_at": "Timestamp when the account record was created.",
+ "last_modified_at": "Timestamp of the last modification to the account record.",
+ },
+ },
+ "contracts": {
+ "description": "Revenue recognition contracts.",
+ "docs_url": "https://docs.campfire.ai/api-reference/revenue-recognition/list-contracts",
+ "columns": {
+ "id": "Unique identifier for the contract.",
+ "start_date": "Contract start date.",
+ "created_at": "Timestamp when the contract record was created.",
+ "last_modified_at": "Timestamp of the last modification to the contract record.",
+ },
+ },
+ "revenue_transactions": {
+ "description": "Revenue transactions used for revenue recognition.",
+ "docs_url": "https://docs.campfire.ai/api-reference/revenue-recognition/list-revenue-transactions",
+ "columns": {
+ "id": "Unique identifier for the revenue transaction.",
+ "transaction_date": "The revenue transaction date.",
+ "created_at": "Timestamp when the revenue transaction record was created.",
+ "last_modified_at": "Timestamp of the last modification to the revenue transaction record.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/settings.py
new file mode 100644
index 000000000000..76a974873d51
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/settings.py
@@ -0,0 +1,137 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SortMode
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+CAMPFIRE_BASE_URL = "https://api.meetcampfire.com"
+
+# Every incremental-capable Campfire list endpoint filters on the same server-side
+# `last_modified_at__gte` param (ISO 8601), documented to cover both active and deleted records.
+LAST_MODIFIED_AT_FIELD: list[IncrementalField] = [
+ {
+ "label": "last_modified_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "last_modified_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+@dataclass(frozen=True)
+class CampfireEndpointConfig:
+ name: str
+ path: str
+ # Non-empty only where the API documents a server-side `last_modified_at__gte` filter.
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Stable created-at style field confirmed present in the endpoint's response schema.
+ partition_key: str | None = None
+ page_size: int = 500
+ # Opt into DRF cursor pagination: pass an empty `cursor=` on the first request and follow
+ # the `next` link. Recommended by Campfire for large/syncing endpoints.
+ use_cursor: bool = False
+ # "asc" only where Campfire documents a stable ascending order on the incremental field
+ # (the payment sync endpoints order by (last_modified_at, id) ascending). Everywhere else
+ # the response order is not documented, so "desc" keeps the pipeline from checkpointing
+ # the incremental watermark until the sync completes.
+ sort_mode: SortMode = "desc"
+ # Extra query params sent on the first request (e.g. all_time=true to escape the
+ # endpoint's default six-month date window).
+ extra_params: dict[str, str] = field(default_factory=dict)
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+
+
+CAMPFIRE_ENDPOINTS: dict[str, CampfireEndpointConfig] = {
+ # Campfire's GL transaction log; the recommended endpoint for row-level GL data.
+ # Without all_time=true the endpoint defaults to roughly the last six months.
+ "chart_transactions": CampfireEndpointConfig(
+ name="chart_transactions",
+ path="/coa/api/transaction",
+ incremental_fields=LAST_MODIFIED_AT_FIELD,
+ page_size=1000,
+ use_cursor=True,
+ extra_params={"all_time": "true"},
+ ),
+ "journal_entries": CampfireEndpointConfig(
+ name="journal_entries",
+ path="/coa/api/journal_entry",
+ partition_key="created_at",
+ extra_params={"all_time": "true"},
+ ),
+ "invoices": CampfireEndpointConfig(
+ name="invoices",
+ path="/coa/api/v1/invoice/",
+ partition_key="created_at",
+ ),
+ "invoice_payments": CampfireEndpointConfig(
+ name="invoice_payments",
+ path="/coa/api/v1/invoice-payments",
+ incremental_fields=LAST_MODIFIED_AT_FIELD,
+ partition_key="created_at",
+ use_cursor=True,
+ sort_mode="asc",
+ ),
+ "credit_memos": CampfireEndpointConfig(
+ name="credit_memos",
+ path="/coa/api/v1/credit-memo",
+ partition_key="created_at",
+ ),
+ "bills": CampfireEndpointConfig(
+ name="bills",
+ path="/coa/api/v1/bill/",
+ incremental_fields=LAST_MODIFIED_AT_FIELD,
+ ),
+ "bill_payments": CampfireEndpointConfig(
+ name="bill_payments",
+ path="/coa/api/v1/bill-payments",
+ incremental_fields=LAST_MODIFIED_AT_FIELD,
+ partition_key="created_at",
+ use_cursor=True,
+ sort_mode="asc",
+ ),
+ "debit_memos": CampfireEndpointConfig(
+ name="debit_memos",
+ path="/coa/api/v1/debit-memo",
+ partition_key="created_at",
+ ),
+ "bank_accounts": CampfireEndpointConfig(
+ name="bank_accounts",
+ path="/ca/api/account",
+ incremental_fields=LAST_MODIFIED_AT_FIELD,
+ ),
+ "bank_transactions": CampfireEndpointConfig(
+ name="bank_transactions",
+ path="/ca/api/transaction",
+ partition_key="created_at",
+ ),
+ "vendors": CampfireEndpointConfig(
+ name="vendors",
+ path="/coa/api/vendor",
+ incremental_fields=LAST_MODIFIED_AT_FIELD,
+ ),
+ "departments": CampfireEndpointConfig(
+ name="departments",
+ path="/coa/api/department",
+ incremental_fields=LAST_MODIFIED_AT_FIELD,
+ ),
+ "chart_of_accounts": CampfireEndpointConfig(
+ name="chart_of_accounts",
+ path="/coa/api/account",
+ ),
+ "contracts": CampfireEndpointConfig(
+ name="contracts",
+ path="/rr/api/v1/contracts",
+ incremental_fields=LAST_MODIFIED_AT_FIELD,
+ ),
+ "revenue_transactions": CampfireEndpointConfig(
+ name="revenue_transactions",
+ path="/rr/api/v1/transactions",
+ incremental_fields=LAST_MODIFIED_AT_FIELD,
+ partition_key="created_at",
+ ),
+}
+
+ENDPOINTS = tuple(CAMPFIRE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in CAMPFIRE_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/source.py
index a328120ced7f..845ff4fd8a46 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/source.py
@@ -1,19 +1,44 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-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.campfire.campfire import (
+ CampfireResumeConfig,
+ campfire_source,
+ validate_credentials as validate_campfire_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.campfire.settings import (
+ CAMPFIRE_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import CampfireSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class CampfireSource(SimpleSource[CampfireSourceConfig]):
+class CampfireSource(ResumableSource[CampfireSourceConfig, CampfireResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://docs.campfire.ai/api-reference"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CAMPFIRE
@@ -24,7 +49,91 @@ class CampfireSource(SimpleSource[CampfireSourceConfig]):
name=SchemaExternalDataSourceType.CAMPFIRE,
category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,
label="Campfire",
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["erp", "meetcampfire"],
+ caption="""Enter your Campfire API key to pull your accounting data into the PostHog Data warehouse.
+
+Create an API user and key on the [API keys page](https://app.meetcampfire.com/v2/settings/api-keys) in your Campfire settings. A `view only` role is enough, since PostHog only reads data. The key is shown once, so copy it when you create it.
+""",
iconPath="/static/services/campfire.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/campfire",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.campfire.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized for url: https://api.meetcampfire.com": "Your Campfire API key is invalid or has been revoked. Create a new API key in your Campfire settings (Settings > API keys), then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.meetcampfire.com": "Your Campfire API key does not have permission to read this data. Check the API user's role in your Campfire settings, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: CampfireSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,
+ supports_append=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in ENDPOINTS
+ ]
+
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+
+ return schemas
+
+ def validate_credentials(
+ self, config: CampfireSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ endpoint_config = CAMPFIRE_ENDPOINTS.get(schema_name) if schema_name else None
+ if validate_campfire_credentials(config.api_key, path=endpoint_config.path if endpoint_config else None):
+ return True, None
+
+ return False, "Invalid Campfire API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[CampfireResumeConfig]:
+ return ResumableSourceManager[CampfireResumeConfig](inputs, CampfireResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: CampfireSourceConfig,
+ resumable_source_manager: ResumableSourceManager[CampfireResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return campfire_source(
+ api_key=config.api_key,
+ 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/campfire/tests/test_campfire.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/tests/test_campfire.py
new file mode 100644
index 000000000000..405ab993fbd7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/tests/test_campfire.py
@@ -0,0 +1,275 @@
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.campfire import campfire
+from products.warehouse_sources.backend.temporal.data_imports.sources.campfire.campfire import (
+ CampfireResumeConfig,
+ _build_first_url,
+ _format_incremental_value,
+ _parse_page,
+ _validate_next_url,
+ campfire_source,
+ get_rows,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.campfire.settings import (
+ CAMPFIRE_BASE_URL,
+ CAMPFIRE_ENDPOINTS,
+ ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+
+class _FakeResumableManager(ResumableSourceManager[CampfireResumeConfig]):
+ def __init__(self, state: CampfireResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[CampfireResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> CampfireResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: CampfireResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _session_returning(pages: dict[str, dict[str, Any]]) -> MagicMock:
+ """A fake session whose GET returns the page registered for each exact URL."""
+
+ def _get(url: str, **kwargs: Any) -> MagicMock:
+ response = MagicMock()
+ response.status_code = 200
+ response.ok = True
+ response.json.return_value = pages[url]
+ return response
+
+ session = MagicMock()
+ session.get.side_effect = _get
+ return session
+
+
+def _query(url: str) -> dict[str, list[str]]:
+ return parse_qs(urlparse(url).query, keep_blank_values=True)
+
+
+class TestBuildFirstUrl:
+ def test_windowed_endpoints_request_all_time(self) -> None:
+ # Without all_time=true these endpoints silently default to roughly the last six
+ # months, truncating the initial sync.
+ for endpoint in ("chart_transactions", "journal_entries"):
+ url = _build_first_url(CAMPFIRE_ENDPOINTS[endpoint], False, None)
+ assert _query(url)["all_time"] == ["true"], endpoint
+
+ def test_cursor_endpoints_send_empty_cursor(self) -> None:
+ url = _build_first_url(CAMPFIRE_ENDPOINTS["bill_payments"], False, None)
+ assert _query(url)["cursor"] == [""]
+
+ def test_offset_endpoints_do_not_send_cursor(self) -> None:
+ url = _build_first_url(CAMPFIRE_ENDPOINTS["vendors"], False, None)
+ assert "cursor" not in _query(url)
+
+ def test_incremental_value_becomes_last_modified_filter(self) -> None:
+ url = _build_first_url(CAMPFIRE_ENDPOINTS["vendors"], True, datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC))
+ assert _query(url)["last_modified_at__gte"] == ["2026-01-02T03:04:05Z"]
+
+ def test_no_filter_on_full_refresh_or_missing_watermark(self) -> None:
+ assert "last_modified_at__gte" not in _query(_build_first_url(CAMPFIRE_ENDPOINTS["vendors"], False, None))
+ assert "last_modified_at__gte" not in _query(_build_first_url(CAMPFIRE_ENDPOINTS["vendors"], True, None))
+
+ def test_full_refresh_only_endpoint_never_sends_filter(self) -> None:
+ # journal_entries has no server-side last_modified filter; sending one anyway would
+ # be silently ignored at best.
+ url = _build_first_url(CAMPFIRE_ENDPOINTS["journal_entries"], True, datetime(2026, 1, 1, tzinfo=UTC))
+ assert "last_modified_at__gte" not in _query(url)
+
+
+class TestFormatIncrementalValue:
+ @parameterized.expand(
+ [
+ ("aware_datetime", datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), "2026-01-02T03:04:05Z"),
+ ("naive_datetime", datetime(2026, 1, 2, 3, 4, 5), "2026-01-02T03:04:05Z"),
+ ("date", date(2026, 1, 2), "2026-01-02"),
+ ("string_passthrough", "2026-01-02T03:04:05Z", "2026-01-02T03:04:05Z"),
+ ]
+ )
+ def test_formats(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_incremental_value(value) == expected
+
+
+class TestParsePage:
+ @parameterized.expand(
+ [
+ (
+ "drf_envelope",
+ {"count": 2, "next": "https://x/next", "results": [{"id": 1}]},
+ [{"id": 1}],
+ "https://x/next",
+ ),
+ ("null_results", {"count": 0, "next": None, "results": None}, [], None),
+ ("bare_list", [{"id": 1}, {"id": 2}], [{"id": 1}, {"id": 2}], None),
+ ("unexpected_scalar", "nope", [], None),
+ ]
+ )
+ def test_shapes(self, _name: str, data: Any, expected_rows: list, expected_next: Any) -> None:
+ assert _parse_page(data) == (expected_rows, expected_next)
+
+
+class TestValidateNextUrl:
+ def test_same_host_https_is_allowed(self) -> None:
+ _validate_next_url(f"{CAMPFIRE_BASE_URL}/coa/api/vendor?offset=100")
+
+ @parameterized.expand(
+ [
+ ("other_host", "https://evil.example.com/coa/api/vendor?offset=100"),
+ ("http_downgrade", "http://api.meetcampfire.com/coa/api/vendor?offset=100"),
+ ]
+ )
+ def test_off_host_links_are_rejected(self, _name: str, url: str) -> None:
+ # The API key rides in a header; following an off-host next link would leak it.
+ with pytest.raises(ValueError):
+ _validate_next_url(url)
+
+
+class TestGetRows:
+ def test_follows_next_links_and_saves_state_after_each_yield(self) -> None:
+ first_url = _build_first_url(CAMPFIRE_ENDPOINTS["vendors"], False, None)
+ page2 = f"{CAMPFIRE_BASE_URL}/coa/api/vendor?limit=500&offset=500"
+ session = _session_returning(
+ {
+ first_url: {"count": 3, "next": page2, "results": [{"id": 1}, {"id": 2}]},
+ page2: {"count": 3, "next": None, "results": [{"id": 3}]},
+ }
+ )
+ manager = _FakeResumableManager()
+
+ with patch.object(campfire, "make_tracked_session", return_value=session):
+ batches = list(get_rows("key", "vendors", MagicMock(), manager))
+
+ assert batches == [[{"id": 1}, {"id": 2}], [{"id": 3}]]
+ # State is saved only while more pages remain, so a crash re-yields (not skips) the
+ # last page — merge dedupes on the primary key.
+ assert [s.next_url for s in manager.saved] == [page2]
+
+ def test_resumes_from_saved_next_url(self) -> None:
+ page2 = f"{CAMPFIRE_BASE_URL}/coa/api/vendor?limit=500&offset=500"
+ session = _session_returning({page2: {"count": 3, "next": None, "results": [{"id": 3}]}})
+ manager = _FakeResumableManager(CampfireResumeConfig(next_url=page2))
+
+ with patch.object(campfire, "make_tracked_session", return_value=session):
+ batches = list(get_rows("key", "vendors", MagicMock(), manager))
+
+ assert batches == [[{"id": 3}]]
+ session.get.assert_called_once()
+ assert session.get.call_args[0][0] == page2
+
+ def test_empty_first_page_yields_nothing(self) -> None:
+ first_url = _build_first_url(CAMPFIRE_ENDPOINTS["vendors"], False, None)
+ session = _session_returning({first_url: {"count": 0, "next": None, "results": []}})
+
+ with patch.object(campfire, "make_tracked_session", return_value=session):
+ batches = list(get_rows("key", "vendors", MagicMock(), _FakeResumableManager()))
+
+ assert batches == []
+
+ def test_off_host_next_link_stops_the_sync(self) -> None:
+ first_url = _build_first_url(CAMPFIRE_ENDPOINTS["vendors"], False, None)
+ session = _session_returning(
+ {first_url: {"count": 1, "next": "https://evil.example.com/x", "results": [{"id": 1}]}}
+ )
+
+ with patch.object(campfire, "make_tracked_session", return_value=session):
+ with pytest.raises(ValueError):
+ list(get_rows("key", "vendors", MagicMock(), _FakeResumableManager()))
+
+
+class TestFetchRetries:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 503)])
+ def test_retryable_status_codes_are_retried(self, _name: str, status: int) -> None:
+ bad = MagicMock(status_code=status)
+ good = MagicMock(status_code=200, ok=True)
+ good.json.return_value = {"results": []}
+ session = MagicMock()
+ session.get.side_effect = [bad, good]
+
+ with patch.object(campfire._fetch_page.retry, "sleep", lambda *_: None): # type: ignore[attr-defined]
+ result = campfire._fetch_page(session, f"{CAMPFIRE_BASE_URL}/coa/api/vendor", {}, MagicMock())
+
+ assert result == {"results": []}
+ assert session.get.call_count == 2
+
+ def test_client_error_raises_without_retry(self) -> None:
+ bad = requests.Response()
+ bad.status_code = 401
+ bad.url = f"{CAMPFIRE_BASE_URL}/coa/api/vendor"
+ session = MagicMock()
+ session.get.return_value = bad
+
+ with pytest.raises(requests.HTTPError):
+ campfire._fetch_page(session, f"{CAMPFIRE_BASE_URL}/coa/api/vendor", {}, MagicMock())
+ assert session.get.call_count == 1
+
+
+class TestCampfireSourceResponse:
+ def test_every_endpoint_builds_a_source_response(self) -> None:
+ for endpoint in ENDPOINTS:
+ response = campfire_source("key", endpoint, MagicMock(), MagicMock())
+ assert response.name == endpoint
+ assert response.primary_keys == ["id"]
+
+ def test_payment_sync_endpoints_are_ascending(self) -> None:
+ # Campfire documents (last_modified_at, id) ascending order on the payment sync
+ # endpoints, which lets the pipeline checkpoint the watermark per batch.
+ for endpoint in ("bill_payments", "invoice_payments"):
+ assert campfire_source("key", endpoint, MagicMock(), MagicMock()).sort_mode == "asc"
+
+ def test_undocumented_order_endpoints_are_descending(self) -> None:
+ # Everything else has no documented response order, so the watermark must only be
+ # persisted once the sync completes.
+ for endpoint in ("chart_transactions", "vendors", "contracts"):
+ assert campfire_source("key", endpoint, MagicMock(), MagicMock()).sort_mode == "desc"
+
+ @parameterized.expand(
+ [
+ ("partitioned", "journal_entries", ["created_at"]),
+ ("unpartitioned", "chart_of_accounts", None),
+ ]
+ )
+ def test_partitioning(self, _name: str, endpoint: str, expected_keys: list[str] | None) -> None:
+ response = campfire_source("key", endpoint, MagicMock(), MagicMock())
+ assert response.partition_keys == expected_keys
+ assert response.partition_mode == ("datetime" if expected_keys else None)
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("ok", 200, True), ("unauthorized", 401, False), ("forbidden", 403, False)])
+ def test_status_maps_to_validity(self, _name: str, status: int, expected: bool) -> None:
+ response = MagicMock()
+ response.status_code = status
+ session = MagicMock()
+ session.get.return_value = response
+ with patch.object(campfire, "make_tracked_session", return_value=session):
+ assert validate_credentials("cf_test_key") is expected
+
+ def test_network_error_is_not_valid(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = Exception("boom")
+ with patch.object(campfire, "make_tracked_session", return_value=session):
+ assert validate_credentials("cf_test_key") is False
+
+ def test_schema_probe_targets_the_given_path(self) -> None:
+ response = MagicMock()
+ response.status_code = 200
+ session = MagicMock()
+ session.get.return_value = response
+ with patch.object(campfire, "make_tracked_session", return_value=session):
+ validate_credentials("cf_test_key", path="/rr/api/v1/contracts")
+ assert session.get.call_args[0][0].startswith(f"{CAMPFIRE_BASE_URL}/rr/api/v1/contracts?")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/tests/test_campfire_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/tests/test_campfire_source.py
new file mode 100644
index 000000000000..c05bafaf65fa
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/campfire/tests/test_campfire_source.py
@@ -0,0 +1,142 @@
+from typing import Optional
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+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.campfire import source as source_module
+from products.warehouse_sources.backend.temporal.data_imports.sources.campfire.campfire import CampfireResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.campfire.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.campfire.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.campfire.source import CampfireSource
+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 CampfireSourceConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _source_inputs(
+ schema_name: str, last_value: Optional[object] = None, use_incremental: bool = False
+) -> SourceInputs:
+ return SourceInputs(
+ schema_name=schema_name,
+ schema_id="schema-1",
+ source_id="source-1",
+ team_id=1,
+ should_use_incremental_field=use_incremental,
+ db_incremental_field_last_value=last_value,
+ db_incremental_field_earliest_value=None,
+ incremental_field="last_modified_at" if use_incremental else None,
+ incremental_field_type=None,
+ job_id="job-1",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+class TestCampfireSource:
+ def setup_method(self) -> None:
+ self.source = CampfireSource()
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.CAMPFIRE
+
+ def test_source_is_released_as_alpha(self) -> None:
+ config = self.source.get_source_config
+ assert not config.unreleasedSource
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/campfire"
+
+ def test_source_config_has_a_single_secret_api_key_field(self) -> None:
+ config = self.source.get_source_config
+ assert len(config.fields) == 1
+ field = config.fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.name == "api_key"
+ assert field.type == SourceFieldInputConfigType.PASSWORD
+ assert field.required is True
+ assert field.secret is True
+
+ def test_get_schemas_returns_every_endpoint(self) -> None:
+ schemas = self.source.get_schemas(CampfireSourceConfig(api_key="k"), team_id=1)
+ assert [s.name for s in schemas] == list(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ ("chart_transactions", True),
+ ("bill_payments", True),
+ ("vendors", True),
+ ("journal_entries", False),
+ ("invoices", False),
+ ("chart_of_accounts", False),
+ ]
+ )
+ def test_incremental_support_matches_server_side_filter_availability(self, endpoint: str, expected: bool) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(CampfireSourceConfig(api_key="k"), team_id=1)}
+ schema = schemas[endpoint]
+ assert schema.supports_incremental is expected
+ if expected:
+ assert [f["field"] for f in schema.incremental_fields] == ["last_modified_at"]
+ else:
+ assert schema.incremental_fields == []
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(CampfireSourceConfig(api_key="k"), team_id=1, names=["vendors", "bills"])
+ assert {s.name for s in schemas} == {"vendors", "bills"}
+
+ def test_documented_tables_render_without_credentials(self) -> None:
+ # Public docs list the table catalog through this path; it must not need I/O.
+ tables = self.source.get_documented_tables()
+ assert [t["name"] for t in tables] == list(ENDPOINTS)
+
+ def test_canonical_descriptions_are_keyed_by_endpoint_names(self) -> None:
+ assert set(CANONICAL_DESCRIPTIONS.keys()) <= set(ENDPOINTS)
+
+ @parameterized.expand([("valid", True, (True, None)), ("invalid", False, (False, "Invalid Campfire API key"))])
+ def test_validate_credentials_maps_transport_result(
+ self, _name: str, transport_result: bool, expected: tuple
+ ) -> None:
+ with patch.object(source_module, "validate_campfire_credentials", return_value=transport_result) as mock:
+ result = self.source.validate_credentials(CampfireSourceConfig(api_key="k"), team_id=1)
+ assert result == expected
+ mock.assert_called_once_with("k", path=None)
+
+ def test_validate_credentials_probes_the_schema_endpoint(self) -> None:
+ with patch.object(source_module, "validate_campfire_credentials", return_value=True) as mock:
+ self.source.validate_credentials(CampfireSourceConfig(api_key="k"), team_id=1, schema_name="contracts")
+ mock.assert_called_once_with("k", path="/rr/api/v1/contracts")
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_source_inputs("vendors"))
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is CampfireResumeConfig
+
+ def test_non_retryable_errors_cover_auth_failures(self) -> None:
+ errors = self.source.get_non_retryable_errors()
+ assert any(key.startswith("401 ") for key in errors)
+ assert any(key.startswith("403 ") for key in errors)
+ assert all("api.meetcampfire.com" in key for key in errors)
+
+ @parameterized.expand(
+ [
+ ("incremental", True, "2026-01-01"),
+ ("full_refresh", False, None),
+ ]
+ )
+ def test_source_for_pipeline_plumbs_inputs(self, _name: str, use_incremental: bool, expected_value) -> None:
+ inputs = _source_inputs("vendors", last_value="2026-01-01", use_incremental=use_incremental)
+ manager = MagicMock()
+ with patch.object(source_module, "campfire_source") as mock_source:
+ self.source.source_for_pipeline(CampfireSourceConfig(api_key="k"), manager, inputs)
+
+ kwargs = mock_source.call_args.kwargs
+ assert kwargs["api_key"] == "k"
+ assert kwargs["endpoint"] == "vendors"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["should_use_incremental_field"] is use_incremental
+ # The stored watermark must not leak into a full-refresh run.
+ assert kwargs["db_incremental_field_last_value"] == expected_value
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 8832088a7d86..755358dca023 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
@@ -745,7 +745,7 @@ class CampaynSourceConfig(config.Config):
@config.config
class CampfireSourceConfig(config.Config):
- pass
+ api_key: str
@config.config