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(bluetally): sync the activity log and the tenant list (#99802)

Tom Owers8e4044c681cf
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 91c13b26e844..470cce152637 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -878,12 +878,12 @@ Note: Discovery doc lists only 8 resources; blogs, posts, pages and comments are
## Bluetally — gaps
-Today (16): `accessories`, `assets`, `audits`, `categories`, `components`, `consumables`, `departments`, `depreciations`, `employees`, `licenses`, `locations`, `maintenances`, `manufacturers`, `products`, `statuses`, `suppliers`
+Today (18): `accessories`, `activity`, `assets`, `audits`, `categories`, `components`, `consumables`, `departments`, `depreciations`, `employees`, `licenses`, `locations`, `maintenances`, `manufacturers`, `products`, `statuses`, `suppliers`, `tenants`
Diffed against: <https://developer.bluetally.com/reference/list-assets (readme reference nav enumerating every list/get endpoint)>
-- [ ] `list-activity (/activity)` — check-in/check-out and field-change history for assets — the state transition log behind every asset we already sync (high)
-- [ ] `list-tenants-for-multi-tenant-users (/tenants)` — tenant lookup for multi-tenant accounts, needed to scope every other table (low)
+- [x] `list-activity (/activity)` — check-in/check-out and field-change history for assets — the state transition log behind every asset we already sync (high)
+- [x] `list-tenants-for-multi-tenant-users (/tenants)` — tenant lookup for multi-tenant accounts, needed to scope every other table (low)
Note: Coverage is otherwise complete — every list-\* endpoint in the reference maps to an existing table. The remaining operations are POST check-in/check-out actions, which are not queryable collections.
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
index 6c0ccfc3a073..af4fba25a2ae 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/bluetally.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/bluetally.py
@@ -10,6 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
OffsetPaginator,
+ SinglePagePaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
@@ -39,10 +40,13 @@ def bluetally_source(
) -> SourceResponse:
config = BLUETALLY_ENDPOINTS[endpoint]
- # Sorting on `created_at` ascending keeps offset pagination stable even as new rows are
- # appended mid-sync.
- params: dict[str, Any] = {"sort": config.sort, "order": "asc"}
- if tenant_id:
+ params: dict[str, Any] = {}
+ if config.sort:
+ # Sorting on `created_at` ascending keeps offset pagination stable even as new rows are
+ # appended mid-sync.
+ params["sort"] = config.sort
+ params["order"] = "asc"
+ if tenant_id and config.accepts_tenant_id:
params["tenant_id"] = tenant_id
rest_config: RESTAPIConfig = {
@@ -53,7 +57,9 @@ def bluetally_source(
"headers": {"Accept": "application/json"},
"auth": {"type": "bearer", "token": api_key},
# BlueTally reports no total anywhere; termination is short/empty page (OffsetPaginator default).
- "paginator": OffsetPaginator(limit=PAGE_SIZE, total_path=None),
+ "paginator": OffsetPaginator(limit=PAGE_SIZE, total_path=None)
+ if config.paginated
+ else SinglePagePaginator(),
},
"resources": [
{
@@ -61,17 +67,19 @@ def bluetally_source(
"endpoint": {
"path": config.path,
"params": params,
- # Every list endpoint returns a bare JSON array. A non-list 200 (wrapped payload,
- # proxy HTML, …) is a permanent API-contract violation — fail loud instead of
- # syncing the stray object as a row.
+ "data_selector": config.data_selector,
+ # The rows always arrive as a JSON array, bare or under `data_selector`. A 200
+ # that doesn't carry one (wrapped payload, proxy HTML, …) is a permanent
+ # API-contract violation — fail loud instead of syncing the stray object as a row.
"data_selector_required": True,
},
}
],
}
+ # Only offset pagination has a position worth persisting; a single-page endpoint is one request.
initial_paginator_state: Optional[dict[str, Any]] = None
- if resumable_source_manager.can_resume():
+ if config.paginated and resumable_source_manager.can_resume():
resume = resumable_source_manager.load_state()
if resume is not None:
initial_paginator_state = {"offset": resume.offset}
@@ -87,7 +95,7 @@ def bluetally_source(
team_id,
job_id,
db_incremental_field_last_value,
- resume_hook=save_checkpoint,
+ resume_hook=save_checkpoint if config.paginated else None,
initial_paginator_state=initial_paginator_state,
)
@@ -100,19 +108,26 @@ def bluetally_source(
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",
+ # We request `sort=created_at&order=asc`, so rows arrive oldest-first. Endpoints that take
+ # no sort parameter make no ordering guarantee, so they declare none.
+ sort_mode="asc" if config.sort else None,
column_hints=resource.column_hints,
)
-def validate_credentials(api_key: str, tenant_id: str | None = None, path: str = "/assets") -> bool:
- query: dict[str, Any] = {"limit": 1}
- if tenant_id:
+def validate_credentials(api_key: str, tenant_id: str | None = None, endpoint: str = "assets") -> bool:
+ config = BLUETALLY_ENDPOINTS[endpoint]
+ query: dict[str, Any] = {}
+ if config.paginated:
+ query["limit"] = 1
+ if tenant_id and config.accepts_tenant_id:
query["tenant_id"] = tenant_id
+ url = f"{BLUETALLY_BASE_URL}{config.path}"
+ if query:
+ url = f"{url}?{urlencode(query)}"
ok, _status = validate_via_probe(
lambda: make_tracked_session(redact_values=(api_key,)),
- f"{BLUETALLY_BASE_URL}{path}?{urlencode(query)}",
+ url,
headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},
)
return ok
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
index 51bc9373f2a8..5c802b4a5c15 100644
--- 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
@@ -234,4 +234,31 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updated_at": "Timestamp when the audit was last updated.",
},
},
+ "activity": {
+ "description": "Activity log entries in BlueTally: the create, update, delete, check-in, check-out, schedule, complete and recover events recorded against assets, accessories, components, consumables, licenses, maintenances and audits.",
+ "docs_url": f"{_DOCS}/list-activity",
+ "columns": {
+ "timestamp": "Timestamp when the logged action happened.",
+ "user_id": "ID of the user who performed the action.",
+ "user_name": "Name of the user who performed the action.",
+ "user_email": "Email address of the user who performed the action.",
+ "type": "Type of item the entry refers to, such as Asset, Accessory, Component, Consumable, License, Maintenance or Audit.",
+ "event": "Action that was recorded, such as Create, Update, Delete, Checkin, Checkout, Complete, Schedule or Recover.",
+ "item_id": "ID of the item the action was performed on.",
+ "item_name": "Name of the item the action was performed on.",
+ "checked_out_to_from_type": "Type of the party the item was checked out to or in from, such as Employee or Location.",
+ "checked_out_to_from_id": "ID of the party the item was checked out to or in from.",
+ "checked_out_to_from_name": "Name of the party the item was checked out to or in from.",
+ "checked_out_to_from_email": "Email address of the party the item was checked out to or in from.",
+ "notes": "Description of what changed, or the note left on the action.",
+ },
+ },
+ "tenants": {
+ "description": "Tenants the API key can act on. Only populated for BlueTally accounts with multi-tenancy enabled; the tenant ID scopes every other table.",
+ "docs_url": f"{_DOCS}/list-tenants-for-multi-tenant-users",
+ "columns": {
+ "tenant_id": "Unique identifier for the tenant.",
+ "tenant_name": "Name of the tenant.",
+ },
+ },
}
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
index 75c138ef35d9..080cd91f9107 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bluetally/settings.py
@@ -1,22 +1,32 @@
-from dataclasses import dataclass, field
+from dataclasses import field
+from posthog.dataclasses import frozen
-@dataclass
+
+@frozen
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"
+ # Column to sort by while paginating. Every paginated list endpoint accepts `created_at`; sorting
+ # on it ascending keeps offset pagination stable even as new rows are appended mid-sync. `None`
+ # for endpoints that take no parameters at all.
+ sort: str | None = "created_at"
+ # JSONPath to the row array. `None` means the response body is the array itself.
+ data_selector: str | None = None
+ # Whether the endpoint accepts `limit`/`offset`.
+ paginated: bool = True
+ # Whether the endpoint accepts the `tenant_id` scoping parameter.
+ accepts_tenant_id: bool = True
-# 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).
+# IT-asset-management resources exposed by BlueTally's REST API. Except where a config below says
+# otherwise, each 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"),
@@ -34,6 +44,25 @@ BLUETALLY_ENDPOINTS: dict[str, BluetallyEndpointConfig] = {
"depreciations": BluetallyEndpointConfig(path="/depreciations"),
"maintenances": BluetallyEndpointConfig(path="/maintenances"),
"audits": BluetallyEndpointConfig(path="/audits"),
+ # The activity log carries no identifier for the log line itself — `item_id` and `user_id` point
+ # at the affected resource and the actor — so the key is the composite that pins one entry, and
+ # `timestamp` is the only temporal column it returns.
+ "activity": BluetallyEndpointConfig(
+ path="/activity",
+ primary_keys=["timestamp", "type", "event", "item_id", "user_id"],
+ partition_key="timestamp",
+ ),
+ # `/tenants` documents no parameters and wraps its rows in a `tenants` key. It returns one row
+ # per tenant the API key can act on, with no timestamps to partition or sort on.
+ "tenants": BluetallyEndpointConfig(
+ path="/tenants",
+ primary_keys=["tenant_id"],
+ partition_key=None,
+ sort=None,
+ data_selector="tenants",
+ paginated=False,
+ accepts_tenant_id=False,
+ ),
}
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 e7605115e9ae..6d10c4286643 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
@@ -135,8 +135,8 @@ If your account has multi-tenancy enabled, also enter the tenant ID the key shou
schema_name: Optional[str] = None,
api_version: str | None = 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):
+ endpoint = schema_name if schema_name in BLUETALLY_ENDPOINTS else "assets"
+ if validate_bluetally_credentials(config.api_key, config.tenant_id, endpoint):
return True, None
return False, "Invalid BlueTally API key"
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
index 5e8cdc358314..9fe2d8c36616 100644
--- 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
@@ -38,6 +38,14 @@ def _response(items: list[dict[str, Any]], status_code: int = 200) -> Response:
return resp
+def _wrapped_response(body: dict[str, Any], status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp.url = "https://app.bluetallyapp.com/api/v1/tenants"
+ resp._content = json.dumps(body).encode()
+ return resp
+
+
def _error_response(status_code: int) -> Response:
resp = Response()
resp.status_code = status_code
@@ -219,17 +227,83 @@ class TestBluetallySourceResponse:
@parameterized.expand([(name,) for name in ENDPOINTS])
@mock.patch(CLIENT_SESSION_PATCH)
def test_source_response_shape(self, name: str, MockSession) -> None:
+ config = BLUETALLY_ENDPOINTS[name]
response = _source(endpoint=name)
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"
+ assert response.primary_keys == config.primary_keys
+ # An endpoint we can't sort stays unordered rather than claiming an order it never requested.
+ assert response.sort_mode == ("asc" if config.sort else None)
+ assert response.partition_keys == ([config.partition_key] if config.partition_key else None)
+ assert response.partition_mode == ("datetime" if config.partition_key else None)
- def test_every_endpoint_partitions_on_created_at(self) -> None:
+ def test_every_partition_key_is_a_creation_timestamp(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())
+ assert {cfg.partition_key for cfg in BLUETALLY_ENDPOINTS.values()} == {"created_at", "timestamp", None}
+
+
+class TestUnparameterizedEndpoints:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_tenants_sends_no_query_params(self, MockSession) -> None:
+ # `/tenants` documents no parameters, so it must not be sent limit/offset/sort/tenant_id.
+ session = MockSession.return_value
+ params = _wire(session, [_wrapped_response({"tenants": [{"tenant_id": 1, "tenant_name": "Acme"}]})])
+
+ rows = _rows(_source(endpoint="tenants", tenant_id="99"))
+
+ assert rows == [{"tenant_id": 1, "tenant_name": "Acme"}]
+ assert params[0] == {}
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_tenants_fetches_a_single_page(self, MockSession) -> None:
+ # Without limit/offset there is no second page to ask for, even on a large response.
+ session = MockSession.return_value
+ tenants = [{"tenant_id": i, "tenant_name": str(i)} for i in range(PAGE_SIZE)]
+ _wire(session, [_wrapped_response({"tenants": tenants})])
+
+ manager = _make_manager()
+ rows = _rows(_source(endpoint="tenants", manager=manager))
+
+ assert len(rows) == PAGE_SIZE
+ assert session.send.call_count == 1
+ manager.save_state.assert_not_called()
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_tenants_ignores_stale_offset_resume_state(self, MockSession) -> None:
+ # Resume state can outlive a schema switch; a single-page endpoint must not skip its only page.
+ session = MockSession.return_value
+ params = _wire(session, [_wrapped_response({"tenants": [{"tenant_id": 1, "tenant_name": "Acme"}]})])
+
+ manager = _make_manager(BluetallyResumeConfig(offset=PAGE_SIZE))
+ rows = _rows(_source(endpoint="tenants", manager=manager))
+
+ assert rows == [{"tenant_id": 1, "tenant_name": "Acme"}]
+ assert "offset" not in params[0]
+
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_tenants_missing_envelope_raises(self, MockSession) -> None:
+ # The rows live under `tenants`; a body without it is a contract change, not an empty page.
+ session = MockSession.return_value
+ _wire(session, [_wrapped_response({"unexpected": []})])
+
+ with pytest.raises(ValueError):
+ _rows(_source(endpoint="tenants"))
+
+
+class TestActivity:
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_activity_paginates_with_sorted_params(self, MockSession) -> None:
+ session = MockSession.return_value
+ full_page = [{"item_id": i} for i in range(PAGE_SIZE)]
+ params = _wire(session, [_response(full_page), _response([{"item_id": PAGE_SIZE}])])
+
+ rows = _rows(_source(endpoint="activity", tenant_id="99"))
+
+ assert len(rows) == PAGE_SIZE + 1
+ # The log defaults to newest-first; we ask for oldest-first so the offset walk stays stable.
+ assert params[0]["sort"] == "created_at"
+ assert params[0]["order"] == "asc"
+ assert params[0]["tenant_id"] == "99"
+ assert params[1]["offset"] == PAGE_SIZE
class TestValidateCredentials:
@@ -249,14 +323,22 @@ class TestValidateCredentials:
assert validate_credentials("key") is False
@mock.patch(BLUETALLY_SESSION_PATCH)
- def test_probes_given_path_with_tenant_id(self, mock_session) -> None:
+ def test_probes_given_endpoint_with_tenant_id(self, mock_session) -> None:
mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
- assert validate_credentials("key", tenant_id="42", path="/employees") is True
+ assert validate_credentials("key", tenant_id="42", endpoint="employees") is True
url = mock_session.return_value.get.call_args.args[0]
assert url.startswith("https://app.bluetallyapp.com/api/v1/employees?")
assert "limit=1" in url
assert "tenant_id=42" in url
+ @mock.patch(BLUETALLY_SESSION_PATCH)
+ def test_probes_unparameterized_endpoint_without_a_query_string(self, mock_session) -> None:
+ # `/tenants` takes no parameters, so probing it with limit/tenant_id could be rejected.
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
+ assert validate_credentials("key", tenant_id="42", endpoint="tenants") is True
+ url = mock_session.return_value.get.call_args.args[0]
+ assert url == "https://app.bluetallyapp.com/api/v1/tenants"
+
@mock.patch(BLUETALLY_SESSION_PATCH)
def test_omits_unset_tenant_id(self, mock_session) -> None:
mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
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
index b12f28d86ae7..02db858d6aeb 100644
--- 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
@@ -9,7 +9,10 @@ from posthog.schema import SourceFieldInputConfig
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.settings import (
+ BLUETALLY_ENDPOINTS,
+ ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.bluetally.source import BluetallySource
@@ -44,7 +47,7 @@ class TestGetSchemas:
# 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)
+ assert all(s.detected_primary_keys == BLUETALLY_ENDPOINTS[s.name].primary_keys for s in schemas)
def test_names_filter(self) -> None:
schemas = BluetallySource().get_schemas(_config(), team_id=1, names=["assets", "employees"])
@@ -69,7 +72,7 @@ class TestValidateCredentials:
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")
+ mocked.assert_called_once_with("key", "7", "assets")
def test_failure(self) -> None:
with patch(
@@ -86,7 +89,7 @@ class TestValidateCredentials:
return_value=True,
) as mocked:
BluetallySource().validate_credentials(_config(), team_id=1, schema_name="employees")
- mocked.assert_called_once_with("key", None, "/employees")
+ mocked.assert_called_once_with("key", None, "employees")
class TestNonRetryableErrors: