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 bluetally import source (#66739)

Tom Owersd9e4124dfcb1
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 9265010e0741..e3fa23acdddb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -69,6 +69,7 @@ the row lists both.
| bigquery | HTTP + gRPC | google-cloud-bigquery + bigquery-storage | ✅ (HTTP + gRPC) |
| bing_ads | HTTP (vendor SDK, SOAP) | bingads SDK | ⚠️ |
| blogger | HTTP | requests | ✅ |
+| bluetally | HTTP | requests | ✅ |
| boldsign | HTTP | requests | ✅ |
| braintree | HTTP (GraphQL) | requests | ✅ |
| braze | HTTP | requests | ✅ |
@@ -333,7 +334,6 @@ doesn't conflict with concurrent PRs.
- basecamp
- bigcommerce
- bitly
-- bluetally
- box
- braintrust
- branch
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/bluetally.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/bluetally.py
new file mode 100644
index 000000000000..6fe08e11a88c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/bluetally.py
@@ -0,0 +1,155 @@
+import dataclasses
+from collections.abc import Iterator
+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.bluetally.settings import BLUETALLY_ENDPOINTS
+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
+
+BLUETALLY_BASE_URL = "https://app.bluetallyapp.com/api/v1"
+# BlueTally caps a single response at 1000 rows; using the max minimizes requests against the
+# 10,000-requests-per-hour budget.
+PAGE_SIZE = 1000
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class BluetallyRetryableError(Exception):
+ pass
+
+
+class BluetallyResumeConfig:
+ # Offset of the next page to fetch. BlueTally paginates with limit/offset, so persisting the
+ # offset is all we need to pick a full-refresh sync back up after a heartbeat timeout.
+ offset: int = 0
+
+
+def _get_headers(api_key: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_key}",
+ "Accept": "application/json",
+ }
+
+
+def _make_session(api_key: str) -> requests.Session:
+ # `redact_values` masks the bearer token in logged URLs and captured HTTP samples so a failed or
+ # sampled request can never persist the raw BlueTally credential in PostHog's HTTP telemetry.
+ return make_tracked_session(headers=_get_headers(api_key), redact_values=(api_key,))
+
+
+def _build_url(path: str, params: dict[str, Any]) -> str:
+ query = {key: value for key, value in params.items() if value is not None and value != ""}
+ return f"{BLUETALLY_BASE_URL}{path}?{urlencode(query)}"
+
+
+@retry(
+ retry=retry_if_exception_type((BluetallyRetryableError, 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, url: str, logger: FilteringBoundLogger) -> list[dict[str, Any]]:
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise BluetallyRetryableError(f"BlueTally API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # Don't log the response body: it can echo back the Authorization header or other secrets.
+ logger.error(f"BlueTally API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ data = response.json()
+ # Every list endpoint returns a bare JSON array. A non-list 200 is a permanent API-contract
+ # violation (wrapped payload, proxy HTML, …), not a transient failure — raise a plain ValueError
+ # so it surfaces immediately instead of burning the retry budget on something retries can't fix.
+ if not isinstance(data, list):
+ raise ValueError(f"BlueTally API returned a non-list response: url={url}")
+ return data
+
+
+def validate_credentials(api_key: str, tenant_id: str | None = None, path: str = "/assets") -> bool:
+ url = _build_url(path, {"limit": 1, "tenant_id": tenant_id})
+ try:
+ response = _make_session(api_key).get(url, timeout=10)
+ return response.status_code == 200
+ except Exception:
+ return False
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BluetallyResumeConfig],
+ tenant_id: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = BLUETALLY_ENDPOINTS[endpoint]
+ # One session reused across every page so urllib3 keeps the connection alive.
+ session = _make_session(api_key)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset = resume.offset if resume else 0
+ if resume:
+ logger.debug(f"BlueTally: resuming {endpoint} from offset={offset}")
+
+ while True:
+ url = _build_url(
+ config.path,
+ {
+ "limit": PAGE_SIZE,
+ "offset": offset,
+ "sort": config.sort,
+ "order": "asc",
+ "tenant_id": tenant_id,
+ },
+ )
+ page = _fetch_page(session, url, logger)
+ if not page:
+ break
+
+ yield page
+
+ # A short page means we've reached the end of the resource.
+ if len(page) < PAGE_SIZE:
+ break
+
+ offset += len(page)
+ # Save AFTER yielding so a crash re-runs from the last persisted offset rather than skipping
+ # ahead; the merge dedupes any re-pulled rows on the primary key.
+ resumable_source_manager.save_state(BluetallyResumeConfig(offset=offset))
+
+
+def bluetally_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[BluetallyResumeConfig],
+ tenant_id: Optional[str] = None,
+) -> SourceResponse:
+ config = BLUETALLY_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ tenant_id=tenant_id,
+ ),
+ 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,
+ # We request `sort=created_at&order=asc`, so rows arrive oldest-first.
+ sort_mode="asc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/canonical_descriptions.py
new file mode 100644
index 000000000000..51bc9373f2a8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/canonical_descriptions.py
@@ -0,0 +1,237 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+_DOCS = "https://developer.bluetally.com/reference"
+
+# Descriptions taken from BlueTally's public API reference (https://developer.bluetally.com/reference).
+# Partial coverage is fine — any endpoint/column not listed here falls back to LLM enrichment.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "assets": {
+ "description": "Individual tracked IT assets (hardware) in BlueTally, including their lifecycle dates, assignment, and related catalog references.",
+ "docs_url": f"{_DOCS}/list-assets",
+ "columns": {
+ "id": "Unique identifier for the asset.",
+ "asset_id": "Human-readable asset tag / ID shown in the BlueTally UI.",
+ "asset_name": "Name of the asset.",
+ "asset_serial": "Serial number of the asset.",
+ "warranty_expiration_date": "Date the asset's warranty expires.",
+ "order_number": "Purchase order number associated with the asset.",
+ "purchase_date": "Date the asset was purchased.",
+ "purchase_cost": "Purchase cost of the asset.",
+ "currency": "Currency of the purchase cost.",
+ "product_id": "ID of the product (model) this asset is an instance of.",
+ "status_id": "ID of the asset's current status.",
+ "category_id": "ID of the asset's category.",
+ "manufacturer_id": "ID of the asset's manufacturer.",
+ "supplier_id": "ID of the supplier the asset was bought from.",
+ "depreciation_id": "ID of the depreciation schedule applied to the asset.",
+ "location_id": "ID of the asset's location.",
+ "department_id": "ID of the department the asset belongs to.",
+ "notes": "Free-text notes on the asset.",
+ "custom_fields": "Custom field values configured for the asset.",
+ "deployed_to": "Employees the asset is currently checked out to, with checkout dates.",
+ "end_of_life_date": "Date the asset reaches end of life.",
+ "created_at": "Timestamp when the asset was created.",
+ "updated_at": "Timestamp when the asset was last updated.",
+ },
+ },
+ "employees": {
+ "description": "People in BlueTally that assets, accessories, consumables, and licenses can be checked out to.",
+ "docs_url": f"{_DOCS}/list-employees",
+ "columns": {
+ "id": "Unique identifier for the employee.",
+ "name": "Employee's full name.",
+ "email": "Employee's email address.",
+ "title": "Employee's job title.",
+ "location_id": "ID of the employee's location.",
+ "department_id": "ID of the employee's department.",
+ "manager_id": "ID of the employee's manager.",
+ "notes": "Free-text notes on the employee.",
+ "archived": "Whether the employee has been archived.",
+ "assets": "IDs of assets currently checked out to the employee.",
+ "accessories": "IDs of accessories currently checked out to the employee.",
+ "consumables": "IDs of consumables checked out to the employee.",
+ "licenses": "IDs of licenses checked out to the employee.",
+ "created_at": "Timestamp when the employee was created.",
+ "updated_at": "Timestamp when the employee was last updated.",
+ },
+ },
+ "licenses": {
+ "description": "Software licenses tracked in BlueTally, including seat counts and assignment.",
+ "docs_url": f"{_DOCS}/list-licenses",
+ "columns": {
+ "id": "Unique identifier for the license.",
+ "name": "Name of the license.",
+ "licensed_to_name": "Name the license is registered to.",
+ "licensed_to_email": "Email the license is registered to.",
+ "expiration_date": "Date the license expires.",
+ "number_of_seats": "Total number of seats for the license.",
+ "available": "Number of seats currently available.",
+ "license_type": "Type of license.",
+ "created_at": "Timestamp when the license was created.",
+ "updated_at": "Timestamp when the license was last updated.",
+ },
+ },
+ "accessories": {
+ "description": "Accessories (peripherals and other non-serialized hardware) tracked by quantity in BlueTally.",
+ "docs_url": f"{_DOCS}/list-all-accessories",
+ "columns": {
+ "id": "Unique identifier for the accessory.",
+ "name": "Name of the accessory.",
+ "model_number": "Model number of the accessory.",
+ "minimum_quantity": "Minimum stock quantity before a low-stock alert.",
+ "quantity": "Total quantity owned.",
+ "available": "Quantity currently available (not checked out).",
+ "created_at": "Timestamp when the accessory was created.",
+ "updated_at": "Timestamp when the accessory was last updated.",
+ },
+ },
+ "consumables": {
+ "description": "Consumable items tracked by quantity in BlueTally (e.g. cables, ink) that deplete as they are checked out.",
+ "docs_url": f"{_DOCS}/list-consumables",
+ "columns": {
+ "id": "Unique identifier for the consumable.",
+ "name": "Name of the consumable.",
+ "minimum_quantity": "Minimum stock quantity before a low-stock alert.",
+ "available": "Quantity currently available.",
+ "created_at": "Timestamp when the consumable was created.",
+ "updated_at": "Timestamp when the consumable was last updated.",
+ },
+ },
+ "components": {
+ "description": "Components tracked in BlueTally that can be checked out to assets (e.g. RAM, drives).",
+ "docs_url": f"{_DOCS}/list-components",
+ "columns": {
+ "id": "Unique identifier for the component.",
+ "name": "Name of the component.",
+ "quantity": "Total quantity owned.",
+ "available": "Quantity currently available.",
+ "created_at": "Timestamp when the component was created.",
+ "updated_at": "Timestamp when the component was last updated.",
+ },
+ },
+ "products": {
+ "description": "Product models in BlueTally's catalog that assets are instances of.",
+ "docs_url": f"{_DOCS}/list-products",
+ "columns": {
+ "id": "Unique identifier for the product.",
+ "name": "Name of the product.",
+ "model_number": "Model number of the product.",
+ "category_id": "ID of the product's category.",
+ "manufacturer_id": "ID of the product's manufacturer.",
+ "end_of_life_date": "End-of-life date for the product.",
+ "created_at": "Timestamp when the product was created.",
+ "updated_at": "Timestamp when the product was last updated.",
+ },
+ },
+ "categories": {
+ "description": "Categories used to group BlueTally assets, accessories, and other items.",
+ "docs_url": f"{_DOCS}/list-categories",
+ "columns": {
+ "id": "Unique identifier for the category.",
+ "name": "Name of the category.",
+ "type": "Type of item the category applies to.",
+ "created_at": "Timestamp when the category was created.",
+ "updated_at": "Timestamp when the category was last updated.",
+ },
+ },
+ "manufacturers": {
+ "description": "Manufacturers referenced by BlueTally assets, products, and licenses.",
+ "docs_url": f"{_DOCS}/list-manufacturers",
+ "columns": {
+ "id": "Unique identifier for the manufacturer.",
+ "name": "Name of the manufacturer.",
+ "url": "Manufacturer's website URL.",
+ "created_at": "Timestamp when the manufacturer was created.",
+ "updated_at": "Timestamp when the manufacturer was last updated.",
+ },
+ },
+ "suppliers": {
+ "description": "Suppliers that BlueTally assets and other items were purchased from.",
+ "docs_url": f"{_DOCS}/list-suppliers",
+ "columns": {
+ "id": "Unique identifier for the supplier.",
+ "name": "Name of the supplier.",
+ "created_at": "Timestamp when the supplier was created.",
+ "updated_at": "Timestamp when the supplier was last updated.",
+ },
+ },
+ "locations": {
+ "description": "Physical locations where BlueTally assets and employees are based.",
+ "docs_url": f"{_DOCS}/list-locations",
+ "columns": {
+ "id": "Unique identifier for the location.",
+ "name": "Name of the location.",
+ "city": "City of the location.",
+ "country": "Country of the location.",
+ "created_at": "Timestamp when the location was created.",
+ "updated_at": "Timestamp when the location was last updated.",
+ },
+ },
+ "departments": {
+ "description": "Organizational departments used to group BlueTally assets and employees.",
+ "docs_url": f"{_DOCS}/list-departments",
+ "columns": {
+ "id": "Unique identifier for the department.",
+ "name": "Name of the department.",
+ "created_at": "Timestamp when the department was created.",
+ "updated_at": "Timestamp when the department was last updated.",
+ },
+ },
+ "statuses": {
+ "description": "Status labels (e.g. Deployable, Archived) that BlueTally assets can be assigned.",
+ "docs_url": f"{_DOCS}/list-statuses",
+ "columns": {
+ "id": "Unique identifier for the status.",
+ "name": "Name of the status.",
+ "type": "Status type.",
+ "created_at": "Timestamp when the status was created.",
+ "updated_at": "Timestamp when the status was last updated.",
+ },
+ },
+ "depreciations": {
+ "description": "Depreciation schedules applied to BlueTally assets, licenses, and products.",
+ "docs_url": f"{_DOCS}/list-depreciations",
+ "columns": {
+ "id": "Unique identifier for the depreciation schedule.",
+ "name": "Name of the depreciation schedule.",
+ "months": "Number of months over which the value depreciates.",
+ "minimum_value": "Minimum (floor) value after depreciation.",
+ "created_at": "Timestamp when the depreciation schedule was created.",
+ "updated_at": "Timestamp when the depreciation schedule was last updated.",
+ },
+ },
+ "maintenances": {
+ "description": "Maintenance records logged against BlueTally assets.",
+ "docs_url": f"{_DOCS}/list-maintenances",
+ "columns": {
+ "id": "Unique identifier for the maintenance record.",
+ "type": "Type of maintenance.",
+ "name": "Name of the maintenance record.",
+ "start_date": "Date the maintenance started.",
+ "end_date": "Date the maintenance ended.",
+ "cost": "Cost of the maintenance.",
+ "asset_id": "ID of the asset the maintenance applies to.",
+ "supplier_id": "ID of the supplier that performed the maintenance.",
+ "created_at": "Timestamp when the maintenance record was created.",
+ "updated_at": "Timestamp when the maintenance record was last updated.",
+ },
+ },
+ "audits": {
+ "description": "Asset audit records in BlueTally, tracking scheduled and completed audits.",
+ "docs_url": f"{_DOCS}/list-audits",
+ "columns": {
+ "id": "Unique identifier for the audit.",
+ "audit_date": "Date the audit was performed.",
+ "next_audit_date": "Date the next audit is scheduled for.",
+ "scheduled": "Whether the audit is scheduled.",
+ "completed": "Whether the audit has been completed.",
+ "asset_id": "ID of the audited asset.",
+ "location_id": "ID of the location where the audit took place.",
+ "audit_status": "Status of the audit.",
+ "created_at": "Timestamp when the audit was created.",
+ "updated_at": "Timestamp when the audit was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/docs/bluetally.mdx b/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/docs/bluetally.mdx
new file mode 100644
index 000000000000..45733777ab02
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/docs/bluetally.mdx
@@ -0,0 +1,68 @@
+---
+title: Linking BlueTally as a source
+sidebar: Docs
+showTitle: true
+availability: { free: full, selfServe: full, enterprise: full }
+sourceId: Bluetally
+---
+
+<!--
+This is the user-facing posthog.com source doc. It lives here only because no posthog.com
+checkout was available when the source was implemented. Move it to
+`posthog.com/contents/docs/cdp/sources/bluetally.mdx` and delete this copy, then run
+`python manage.py audit_source_docs --docs-dir <posthog.com>/contents/docs/cdp/sources`.
+-->
+
+import SourceSetupIntro from '../_snippets/source-setup-intro.mdx'
+import SyncModes from '../_snippets/sync-modes.mdx'
+import TroubleshootingLink from '../_snippets/dw-troubleshooting-link.mdx'
+import AlphaRelease from '../_snippets/alpha-release.mdx'
+
+<AlphaRelease />
+
+[BlueTally](https://bluetally.com) is an IT asset management platform for tracking assets, employees,
+licenses, accessories, consumables, and the rest of your hardware and software inventory. Linking it as
+a source syncs that inventory into the PostHog Data warehouse so you can join it with your product data
+— for example, correlating device or license assignments with in-product behavior.
+
+## Prerequisites
+
+To connect BlueTally, you need:
+
+- A BlueTally account with access to **Settings → API Keys**.
+- An API key generated there (used as a bearer token).
+- If your account has multi-tenancy enabled, the tenant ID the key should act on.
+
+## Adding a data source
+
+<SourceSetupIntro />
+
+1. Open BlueTally and go to **Settings → API Keys**.
+2. Create a new API key and copy it.
+3. Paste the key into the **API key** field in PostHog.
+4. If your BlueTally account uses multi-tenancy, also enter the **Tenant ID** the key should act on.
+ Leave it blank otherwise.
+
+## Sync modes
+
+<SyncModes />
+
+BlueTally's API has no server-side "updated since" filter, so every table syncs as a **full refresh** —
+each sync re-reads the resource and merges on the primary key. Schedule syncs at a cadence that fits how
+often your inventory changes (BlueTally allows up to 10,000 API requests per hour).
+
+## Configuration
+
+<SourceParameters />
+
+## Supported tables
+
+<SourceTables />
+
+## Troubleshooting
+
+- **"Invalid BlueTally API key"** when connecting: the key is wrong, has been revoked, or (for
+ multi-tenant accounts) the tenant ID is missing or incorrect. Regenerate the key under
+ **Settings → API Keys** and re-enter it, along with the tenant ID if applicable.
+
+<TroubleshootingLink />
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/settings.py
new file mode 100644
index 000000000000..75c138ef35d9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/settings.py
@@ -0,0 +1,39 @@
+from dataclasses import dataclass, field
+
+
+@dataclass
+class BluetallyEndpointConfig:
+ path: str
+ # BlueTally IDs are globally unique integers per resource, so `id` alone is a safe key.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Stable creation timestamp used for datetime partitioning (never `updated_at`, which churns).
+ partition_key: str | None = "created_at"
+ # Column to sort by while paginating. Every list endpoint accepts `created_at`; sorting on it
+ # ascending keeps offset pagination stable even as new rows are appended mid-sync.
+ sort: str = "created_at"
+
+
+# Core IT-asset-management resources exposed by BlueTally's REST API. Every one is a plain
+# `GET /<resource>` list endpoint returning a bare JSON array with limit/offset pagination, an
+# integer `id`, and `created_at`/`updated_at` timestamps. The API has no server-side
+# `updated_after`-style filter, so all of these sync as full refresh (see source.py / get_schemas).
+BLUETALLY_ENDPOINTS: dict[str, BluetallyEndpointConfig] = {
+ "assets": BluetallyEndpointConfig(path="/assets"),
+ "accessories": BluetallyEndpointConfig(path="/accessories"),
+ "components": BluetallyEndpointConfig(path="/components"),
+ "consumables": BluetallyEndpointConfig(path="/consumables"),
+ "licenses": BluetallyEndpointConfig(path="/licenses"),
+ "employees": BluetallyEndpointConfig(path="/employees"),
+ "products": BluetallyEndpointConfig(path="/products"),
+ "categories": BluetallyEndpointConfig(path="/categories"),
+ "manufacturers": BluetallyEndpointConfig(path="/manufacturers"),
+ "suppliers": BluetallyEndpointConfig(path="/suppliers"),
+ "locations": BluetallyEndpointConfig(path="/locations"),
+ "departments": BluetallyEndpointConfig(path="/departments"),
+ "statuses": BluetallyEndpointConfig(path="/statuses"),
+ "depreciations": BluetallyEndpointConfig(path="/depreciations"),
+ "maintenances": BluetallyEndpointConfig(path="/maintenances"),
+ "audits": BluetallyEndpointConfig(path="/audits"),
+}
+
+ENDPOINTS = tuple(BLUETALLY_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/source.py
index dde61482d986..e6de21c4352b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/source.py
@@ -1,30 +1,152 @@
-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.bluetally.bluetally import (
+ BluetallyResumeConfig,
+ bluetally_source,
+ validate_credentials as validate_bluetally_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bluetally.settings import (
+ BLUETALLY_ENDPOINTS,
+ ENDPOINTS,
+)
+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 BluetallySourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class BluetallySource(SimpleSource[BluetallySourceConfig]):
+class BluetallySource(ResumableSource[BluetallySourceConfig, BluetallyResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.BLUETALLY
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The stored API key is sent with whatever `tenant_id` is configured, so changing it
+ # retargets the saved credential at a different tenant — force secret re-entry on a change.
+ return ["tenant_id"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.BLUETALLY,
- category=DataWarehouseSourceCategory.PRODUCTIVITY,
- label="Bluetally",
+ category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
+ label="BlueTally",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your BlueTally API key to sync your IT asset management data into the PostHog Data warehouse.
+
+Create an API key in BlueTally under **Settings → API Keys**, then paste it here.
+
+If your account has multi-tenancy enabled, also enter the tenant ID the key should act on.""",
iconPath="/static/services/bluetally.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/bluetally",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="tenant_id",
+ label="Tenant ID (optional)",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.bluetally.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or expired API key surfaces as a requests HTTPError when `_fetch_page`
+ # calls `raise_for_status()`. Retrying can never satisfy a credential problem, so stop
+ # the sync. Match the stable status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://app.bluetallyapp.com": "Your BlueTally API key is invalid or has expired. Create a new key under Settings → API Keys in BlueTally, then reconnect.",
+ "403 Client Error: Forbidden for url: https://app.bluetallyapp.com": "Your BlueTally API key does not have permission to read this data. Check the key's permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: BluetallySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ # BlueTally exposes no server-side timestamp filter (only exact-match filters and sort), so
+ # every endpoint is full refresh — incremental would re-fetch every page each sync anyway.
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=[],
+ detected_primary_keys=BLUETALLY_ENDPOINTS[endpoint].primary_keys,
+ )
+ 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: BluetallySourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ path = BLUETALLY_ENDPOINTS[schema_name].path if schema_name in BLUETALLY_ENDPOINTS else "/assets"
+ if validate_bluetally_credentials(config.api_key, config.tenant_id, path):
+ return True, None
+
+ return False, "Invalid BlueTally API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BluetallyResumeConfig]:
+ return ResumableSourceManager[BluetallyResumeConfig](inputs, BluetallyResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: BluetallySourceConfig,
+ resumable_source_manager: ResumableSourceManager[BluetallyResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return bluetally_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ tenant_id=config.tenant_id,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/test_bluetally.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/test_bluetally.py
new file mode 100644
index 000000000000..e86f0d6346d8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/test_bluetally.py
@@ -0,0 +1,192 @@
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bluetally import bluetally
+from products.warehouse_sources.backend.temporal.data_imports.sources.bluetally.bluetally import (
+ PAGE_SIZE,
+ BluetallyResumeConfig,
+ BluetallyRetryableError,
+ _build_url,
+ bluetally_source,
+ get_rows,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bluetally.settings import (
+ BLUETALLY_ENDPOINTS,
+ ENDPOINTS,
+)
+
+
+class _FakeResumableManager:
+ def __init__(self, state: BluetallyResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[BluetallyResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> BluetallyResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: BluetallyResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _response_with_status(status_code: int, body: Any = None) -> requests.Response:
+ response = requests.Response()
+ response.status_code = status_code
+ response._content = b"" if body is None else str(body).encode()
+ return response
+
+
+class TestBuildUrl:
+ def test_includes_all_pagination_params(self) -> None:
+ url = _build_url("/assets", {"limit": 1000, "offset": 0, "sort": "created_at", "order": "asc"})
+ assert url == "https://app.bluetallyapp.com/api/v1/assets?limit=1000&offset=0&sort=created_at&order=asc"
+
+ def test_omits_none_tenant_id(self) -> None:
+ url = _build_url("/employees", {"limit": 50, "offset": 0, "tenant_id": None})
+ assert "tenant_id" not in url
+
+ def test_includes_tenant_id_when_set(self) -> None:
+ url = _build_url("/employees", {"offset": 0, "tenant_id": "42"})
+ assert "tenant_id=42" in url
+
+ def test_offset_zero_is_kept(self) -> None:
+ # offset=0 is the first page; it must not be dropped as a falsy value.
+ url = _build_url("/assets", {"offset": 0})
+ assert "offset=0" in url
+
+
+class TestFetchPage:
+ @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 = MagicMock()
+ session.get.return_value = _response_with_status(status)
+ # No-op the backoff sleep so the 5 attempts run instantly.
+ with patch.object(bluetally._fetch_page.retry, "sleep", lambda *a, **k: None): # type: ignore[attr-defined]
+ with pytest.raises(BluetallyRetryableError):
+ bluetally._fetch_page(session, "https://app.bluetallyapp.com/api/v1/assets", MagicMock())
+ assert session.get.call_count == 5
+
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])
+ def test_client_errors_raise_http_error(self, _name: str, status: int) -> None:
+ session = MagicMock()
+ session.get.return_value = _response_with_status(status)
+ with pytest.raises(requests.HTTPError):
+ bluetally._fetch_page(session, "https://app.bluetallyapp.com/api/v1/assets", MagicMock())
+
+ def test_returns_list_payload(self) -> None:
+ response = _response_with_status(200)
+ response._content = b'[{"id": 1}, {"id": 2}]'
+ session = MagicMock()
+ session.get.return_value = response
+ rows = bluetally._fetch_page(session, "https://app.bluetallyapp.com/api/v1/assets", MagicMock())
+ assert rows == [{"id": 1}, {"id": 2}]
+
+ def test_non_list_payload_raises_value_error(self) -> None:
+ # A non-list 200 is a permanent contract violation, so it must bypass the retry decorator.
+ response = _response_with_status(200)
+ response._content = b'{"error": "unexpected"}'
+ session = MagicMock()
+ session.get.return_value = response
+ with pytest.raises(ValueError):
+ bluetally._fetch_page(session, "https://app.bluetallyapp.com/api/v1/assets", MagicMock())
+ assert session.get.call_count == 1
+
+
+class TestGetRows:
+ @staticmethod
+ def _collect(
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ pages: list[list[dict]],
+ tenant_id: str | None = None,
+ ) -> tuple[list[dict], list[str]]:
+ fetched_urls: list[str] = []
+
+ def fake_fetch(session: Any, url: str, logger: Any) -> list[dict]:
+ fetched_urls.append(url)
+ # Map the requested offset to the corresponding canned page.
+ offset = int(url.split("offset=")[1].split("&")[0])
+ index = offset // PAGE_SIZE
+ return pages[index] if index < len(pages) else []
+
+ monkeypatch.setattr(bluetally, "_fetch_page", fake_fetch)
+ monkeypatch.setattr(bluetally, "make_tracked_session", lambda **kwargs: MagicMock())
+
+ rows: list[dict] = []
+ for page in get_rows(
+ api_key="key",
+ endpoint="assets",
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ tenant_id=tenant_id,
+ ):
+ rows.extend(page)
+ return rows, fetched_urls
+
+ def test_single_short_page_stops_without_saving_state(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows, urls = self._collect(manager, monkeypatch, [[{"id": 1}, {"id": 2}]])
+ assert rows == [{"id": 1}, {"id": 2}]
+ assert len(urls) == 1
+ # A short first page never advances the offset, so no resume state is persisted.
+ assert manager.saved == []
+
+ def test_paginates_until_short_page(self, monkeypatch: Any) -> None:
+ full_page = [{"id": i} for i in range(PAGE_SIZE)]
+ last_page = [{"id": PAGE_SIZE}]
+ manager = _FakeResumableManager()
+ rows, urls = self._collect(manager, monkeypatch, [full_page, last_page])
+ assert len(rows) == PAGE_SIZE + 1
+ assert len(urls) == 2
+ # State is saved after the full page (pointing at the next offset), then we stop on the short page.
+ assert manager.saved == [BluetallyResumeConfig(offset=PAGE_SIZE)]
+
+ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:
+ full_page = [{"id": i} for i in range(PAGE_SIZE)]
+ last_page = [{"id": PAGE_SIZE}]
+ manager = _FakeResumableManager(BluetallyResumeConfig(offset=PAGE_SIZE))
+ rows, urls = self._collect(manager, monkeypatch, [full_page, last_page])
+ # Resuming at offset=PAGE_SIZE skips the already-synced first page.
+ assert rows == [{"id": PAGE_SIZE}]
+ assert urls == [
+ f"https://app.bluetallyapp.com/api/v1/assets?limit={PAGE_SIZE}&offset={PAGE_SIZE}&sort=created_at&order=asc"
+ ]
+
+ def test_threads_tenant_id_into_requests(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ _, urls = self._collect(manager, monkeypatch, [[{"id": 1}]], tenant_id="99")
+ assert all("tenant_id=99" in url for url in urls)
+
+ def test_empty_first_page_yields_nothing(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ rows, urls = self._collect(manager, monkeypatch, [[]])
+ assert rows == []
+ assert len(urls) == 1
+
+
+class TestBluetallySourceResponse:
+ @parameterized.expand([(name,) for name in ENDPOINTS])
+ def test_source_response_shape(self, name: str) -> None:
+ response = bluetally_source(
+ api_key="key",
+ endpoint=name,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == name
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == "asc"
+ # Stable creation timestamp drives datetime partitioning for every endpoint.
+ assert response.partition_keys == ["created_at"]
+ assert response.partition_mode == "datetime"
+
+ def test_every_endpoint_partitions_on_created_at(self) -> None:
+ # Guards against accidentally partitioning on a churning field like updated_at.
+ assert all(cfg.partition_key == "created_at" for cfg in BLUETALLY_ENDPOINTS.values())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/test_bluetally_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/test_bluetally_source.py
new file mode 100644
index 000000000000..c876423d1cc0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/test_bluetally_source.py
@@ -0,0 +1,170 @@
+from typing import Any
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import DataWarehouseSourceCategory, ReleaseStatus, SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.bluetally.bluetally import BluetallyResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.bluetally.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.bluetally.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.bluetally.source import BluetallySource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config(api_key: str = "key", tenant_id: str | None = None) -> Any:
+ config = MagicMock()
+ config.api_key = api_key
+ config.tenant_id = tenant_id
+ return config
+
+
+class TestSourceConfig:
+ def test_source_type(self) -> None:
+ assert BluetallySource().source_type == ExternalDataSourceType.BLUETALLY
+
+ def test_config_is_visible_and_alpha(self) -> None:
+ config = BluetallySource().get_source_config
+ # A finished source must not be hidden from users.
+ assert getattr(config, "unreleasedSource", None) in (None, False)
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/bluetally"
+
+ def test_fields(self) -> None:
+ fields = {
+ f.name: f for f in BluetallySource().get_source_config.fields if isinstance(f, SourceFieldInputConfig)
+ }
+ assert set(fields) == {"api_key", "tenant_id"}
+ assert fields["api_key"].required is True
+ assert fields["api_key"].secret is True
+ # The tenant id is a non-secret, optional connection parameter.
+ assert fields["tenant_id"].required is False
+ assert fields["tenant_id"].secret is False
+
+ def test_connection_host_fields_force_secret_reentry_on_tenant_change(self) -> None:
+ # Changing tenant_id retargets the stored API key, so it must count as a host field.
+ assert BluetallySource().connection_host_fields == ["tenant_id"]
+
+
+class TestGetSchemas:
+ def test_lists_every_endpoint_as_full_refresh(self) -> None:
+ schemas = BluetallySource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # BlueTally has no server-side timestamp filter, so nothing is incremental/append.
+ assert all(not s.supports_incremental and not s.supports_append for s in schemas)
+ assert all(s.incremental_fields == [] for s in schemas)
+ assert all(s.detected_primary_keys == ["id"] for s in schemas)
+
+ def test_names_filter(self) -> None:
+ schemas = BluetallySource().get_schemas(_config(), team_id=1, names=["assets", "employees"])
+ assert {s.name for s in schemas} == {"assets", "employees"}
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # Static endpoint catalog (no I/O) — public docs render the table list.
+ assert BluetallySource.lists_tables_without_credentials is True
+ tables = BluetallySource().get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+ assets = next(t for t in tables if t["name"] == "assets")
+ assert assets["sync_methods"] == ["Full refresh"]
+ assert assets["primary_keys"] == ["id"]
+
+
+class TestValidateCredentials:
+ def test_success(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bluetally.source.validate_bluetally_credentials",
+ return_value=True,
+ ) as mocked:
+ ok, error = BluetallySource().validate_credentials(_config(tenant_id="7"), team_id=1)
+ assert ok is True
+ assert error is None
+ mocked.assert_called_once_with("key", "7", "/assets")
+
+ def test_failure(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bluetally.source.validate_bluetally_credentials",
+ return_value=False,
+ ):
+ ok, error = BluetallySource().validate_credentials(_config(), team_id=1)
+ assert ok is False
+ assert error is not None
+
+ def test_probes_specific_endpoint_path(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bluetally.source.validate_bluetally_credentials",
+ return_value=True,
+ ) as mocked:
+ BluetallySource().validate_credentials(_config(), team_id=1, schema_name="employees")
+ mocked.assert_called_once_with("key", None, "/employees")
+
+
+class TestResumableWiring:
+ def test_get_resumable_source_manager_binds_data_class(self) -> None:
+ inputs = MagicMock()
+ inputs.logger = MagicMock()
+ manager = BluetallySource().get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is BluetallyResumeConfig
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "licenses"
+ inputs.logger = MagicMock()
+ manager = MagicMock()
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.bluetally.source.bluetally_source"
+ ) as mocked:
+ BluetallySource().source_for_pipeline(_config(tenant_id="3"), manager, inputs)
+ mocked.assert_called_once_with(
+ api_key="key",
+ endpoint="licenses",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ tenant_id="3",
+ )
+
+
+class TestNonRetryableErrors:
+ @parameterized.expand(
+ [
+ (
+ "unauthorized",
+ "401 Client Error: Unauthorized for url: https://app.bluetallyapp.com/api/v1/assets?limit=1000&offset=0",
+ ),
+ (
+ "forbidden",
+ "403 Client Error: Forbidden for url: https://app.bluetallyapp.com/api/v1/employees",
+ ),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable = BluetallySource().get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable)
+
+ @parameterized.expand(
+ [
+ ("read_timeout", "HTTPSConnectionPool(host='app.bluetallyapp.com', port=443): Read timed out."),
+ (
+ "server_error",
+ "500 Server Error: Internal Server Error for url: https://app.bluetallyapp.com/api/v1/assets",
+ ),
+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://app.bluetallyapp.com/api/v1/assets"),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:
+ non_retryable = BluetallySource().get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable)
+
+
+class TestCanonicalDescriptions:
+ def test_canonical_descriptions_keys_are_known_endpoints(self) -> None:
+ # Every documented table must map to a real endpoint, or its descriptions never apply.
+ assert set(CANONICAL_DESCRIPTIONS).issubset(set(ENDPOINTS))
+
+ def test_source_exposes_canonical_descriptions(self) -> None:
+ assert BluetallySource().get_canonical_descriptions() is CANONICAL_DESCRIPTIONS
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 cb292d3d6437..be2d0ea25775 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
@@ -447,7 +447,8 @@ class BloggerSourceConfig(config.Config):
@config.config
class BluetallySourceConfig(config.Config):
- pass
+ api_key: str
+ tenant_id: str | None = None
@config.config