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): add 4 missing tables to the Gridly source (#116321)

Tom Owers7c66ecbb9895
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 b51da011a26b..f96db29cfb4c 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
@@ -5553,10 +5553,10 @@ Diffed against: <https://www.gridly.com/docs/api/>
- [x] `grids (GET /v1/grids?dbId=)` — lookup resolving the grid that owns each view/record set (high)
- [x] `databases (GET /v1/databases?projectId=)` — lookup completing the project > database > grid > view hierarchy around synced records (high)
- [x] `projects (GET /v1/projects)` — top-level lookup for project names/IDs referenced by databases (high)
-- [ ] `record histories (GET /v1/views/{viewId}/records/{recordId}/histories)` — per-cell change history - who changed which localization value and when (medium)
-- [ ] `dependencies (GET /v1/views/{viewId}/dependencies)` — source-to-target column mapping that explains translation status columns (medium)
-- [ ] `branches (GET /v1/branches?gridId=)` — branch metadata needed to interpret records synced from a branched grid (medium)
-- [ ] `automation executions (GET /v1/automations/{id}/executions)` — run history with status and timing - the analytical table for automation reliability (medium)
+- [x] `record histories (GET /v1/views/{viewId}/records/{recordId}/histories)` — per-cell change history - who changed which localization value and when (medium)
+- [x] `dependencies (GET /v1/views/{viewId}/dependencies)` — source-to-target column mapping that explains translation status columns (medium)
+- [x] `branches (GET /v1/branches?gridId=)` — branch metadata needed to interpret records synced from a branched grid (medium)
+- [x] `automation executions (GET /v1/automations/{id}/executions)` — run history with status and timing - the analytical table for automation reliability (medium)
- [ ] `automations (GET /v1/automations)` — lookup naming the automations whose executions you would analyze (medium)
- [ ] `glossaries (GET /v1/glossaries)` — terminology lookup joined to localization records (low)
- [ ] `translation memories (GET /v1/transmems)` — TM inventory for leverage/reuse reporting (low)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/canonical_descriptions.py
index 39f071efa788..51c6a6b2a8e8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/canonical_descriptions.py
@@ -60,4 +60,43 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"gridId": "ID of the grid the view belongs to.",
},
},
+ "branches": {
+ "description": "Branches of each Gridly grid. A branch is a copy of a grid that you can change and then merge back.",
+ "docs_url": "https://www.gridly.com/docs/api/#list-branches",
+ "columns": {
+ "id": "Unique identifier of the branch.",
+ "name": "Name of the branch.",
+ "gridId": "ID of the grid the branch belongs to.",
+ },
+ },
+ "dependencies": {
+ "description": "Column dependencies of the configured Gridly view. A dependency links a source column to a target column, so Gridly can track whether the target is up to date with the source.",
+ "docs_url": "https://www.gridly.com/docs/api/#list-dependencies",
+ "columns": {
+ "id": "Unique identifier of the dependency.",
+ "sourceColumnId": "ID of the source column.",
+ "targetColumnId": "ID of the target column.",
+ },
+ },
+ "automation_executions": {
+ "description": "Run history of each automation of the configured Gridly view, one row per execution.",
+ "docs_url": "https://www.gridly.com/docs/api/#list-executions-of-an-automation",
+ "columns": {
+ "id": "Identifier of the execution.",
+ "status": "Status of the execution (e.g. STARTED, SUCCESS).",
+ "startedTime": "Time the execution started.",
+ "automationId": "ID of the automation that ran.",
+ },
+ },
+ "record_histories": {
+ "description": "Change history of each record of the configured Gridly view, one row per recorded change.",
+ "docs_url": "https://www.gridly.com/docs/api/#get-record-history",
+ "columns": {
+ "lastModifiedBy": "User who made the change.",
+ "lastModifiedTime": "Time of the change.",
+ "path": "Path to the folder where the record was stored at the time of the change.",
+ "cells": "List of the record's cells at the time of the change, each with a `columnId` and `value`, plus `dependencyStatus` and `sourceStatus` on localization columns.",
+ "recordId": "ID of the record the history entry belongs to.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/gridly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/gridly.py
index 3ba7fb687441..2945b4d1298f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/gridly.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/gridly.py
@@ -1,14 +1,16 @@
import json
+import contextlib
import dataclasses
from collections.abc import Iterator
from typing import Any
-from urllib.parse import urlsplit
+from urllib.parse import quote, urlsplit
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.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http.observer import redact_request_urls
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.gridly.settings import GRIDLY_ENDPOINTS
@@ -25,11 +27,14 @@ class GridlyRetryableError(Exception):
pass
[email protected] # nosemgrep: prefer-frozen-dataclasses -- pre-existing; new field shifts the backlog finding into diff
class GridlyResumeConfig:
- # Offset of the next records page to fetch. Records is the only paginated endpoint; the columns
- # endpoint is a single request and never resumes.
+ # Position to resume from. For `records` it is the offset of the next records page. For
+ # `record_histories` and `automation_executions` it is the index of the next parent (record or
+ # automation) to fan out over. The other endpoints never resume.
offset: int = 0
+ # For `record_histories` only: the offset of the next history page of the record at `offset`.
+ history_offset: int = 0
def _headers(api_key: str) -> dict[str, str]:
@@ -70,17 +75,30 @@ def _fetch(
params: dict[str, Any],
headers: dict[str, str],
logger: FilteringBoundLogger,
+ redacted_url: str | None = None,
) -> requests.Response:
- response = session.get(url, params=params, headers=headers, timeout=60)
+ # `redacted_url` replaces `url` in every log line and error when the URL embeds customer content,
+ # such as a customer-defined record id.
+ try:
+ # The tracked transport records the request URL, so a redacted request hides it there too.
+ with redact_request_urls() if redacted_url else contextlib.nullcontext():
+ response = session.get(url, params=params, headers=headers, timeout=60)
+ except (requests.ReadTimeout, requests.ConnectionError, requests.exceptions.ChunkedEncodingError) as error:
+ if redacted_url is None:
+ raise
+ # The transport message repeats the request path and query, so rebuild it from the redacted URL.
+ raise type(error)(f"{type(error).__name__} requesting {redacted_url}") from None
if response.status_code == 429 or response.status_code >= 500:
- raise GridlyRetryableError(f"Gridly API error (retryable): status={response.status_code}, url={url}")
+ raise GridlyRetryableError(
+ f"Gridly API error (retryable): status={response.status_code}, url={redacted_url or url}"
+ )
if not response.ok:
# Never log response.text or the raw URL: the error body can echo customer record content
# from the synced view, and the query string carries the paginated `page` blob. Both would
# leak into operational logs. Log only status plus scheme/host/path.
- safe = urlsplit(response.url)
+ safe = urlsplit(redacted_url or response.url)
safe_url = f"{safe.scheme}://{safe.netloc}{safe.path}"
logger.error(f"Gridly API error: status={response.status_code}, url={safe_url}")
# raise_for_status() would embed the full request URL (query string included) in the
@@ -158,6 +176,109 @@ def _iter_columns(
yield columns
+def _iter_dependencies(
+ session: requests.Session,
+ view_id: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ dependencies = _fetch(session, f"{GRIDLY_BASE_URL}/views/{view_id}/dependencies", {}, headers, logger).json()
+ if dependencies:
+ yield dependencies
+
+
+def _iter_automation_executions(
+ session: requests.Session,
+ view_id: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[GridlyResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield the executions of every automation of the view, one request per automation.
+
+ The API reference documents no pagination for automations or their executions, so each list is
+ read in a single request.
+ """
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ start = resume.offset if resume is not None else 0
+
+ automations = _fetch(session, f"{GRIDLY_BASE_URL}/automations", {"viewId": view_id}, headers, logger).json()
+
+ for index, automation in enumerate(automations[start:], start=start):
+ automation_id = automation["id"]
+ url = f"{GRIDLY_BASE_URL}/automations/{automation_id}/executions"
+ executions = _fetch(session, url, {}, headers, logger).json()
+
+ resumable_source_manager.save_state(GridlyResumeConfig(offset=index + 1))
+ if executions:
+ yield [{**execution, "automationId": automation_id} for execution in executions]
+ else:
+ resumable_source_manager.safe_point()
+
+
+def _iter_record_histories(
+ session: requests.Session,
+ view_id: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[GridlyResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Yield the history entries of every record of the view, one paginated walk per record.
+
+ A history entry carries no record id, so each row gets the `recordId` of the record it belongs to.
+ """
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ record_offset = resume.offset if resume is not None else 0
+ # Only the first record of a resumed walk starts partway through its history.
+ resume_history_offset = resume.history_offset if resume is not None else 0
+ if record_offset:
+ logger.debug(
+ f"Gridly: resuming record histories from record offset={record_offset}, "
+ f"history offset={resume_history_offset}"
+ )
+
+ records_url = f"{GRIDLY_BASE_URL}/views/{view_id}/records"
+
+ while True:
+ records_page = json.dumps({"offset": record_offset, "limit": PAGE_SIZE}, separators=(",", ":"))
+ records = _fetch(session, records_url, {"page": records_page}, headers, logger).json()
+
+ for record in records:
+ record_id = record["id"]
+ record_offset += 1
+ # Record ids are customer-defined, so they may hold `/`, `?` or `#`.
+ url = f"{records_url}/{quote(str(record_id), safe='')}/histories"
+ history_offset = resume_history_offset
+ resume_history_offset = 0
+
+ while True:
+ page = json.dumps({"offset": history_offset, "limit": PAGE_SIZE}, separators=(",", ":"))
+ histories = _fetch(
+ session, url, {"page": page}, headers, logger, redacted_url=f"{records_url}/{{recordId}}/histories"
+ ).json()
+ history_offset += len(histories)
+ is_last_page = len(histories) < PAGE_SIZE
+
+ # An earlier page keeps the cursor on this record, at the page after it, so a resume
+ # neither skips the pages that follow nor replays the ones already written. The last
+ # page moves the cursor to the next record.
+ if is_last_page:
+ resumable_source_manager.save_state(GridlyResumeConfig(offset=record_offset))
+ else:
+ resumable_source_manager.save_state(
+ GridlyResumeConfig(offset=record_offset - 1, history_offset=history_offset)
+ )
+ if histories:
+ yield [{**history, "recordId": record_id} for history in histories]
+ else:
+ resumable_source_manager.safe_point()
+ if is_last_page:
+ break
+
+ if len(records) < PAGE_SIZE:
+ break
+
+
def _iter_hierarchy(
session: requests.Session,
endpoint: str,
@@ -202,8 +323,14 @@ def get_rows(
yield from _iter_columns(session, view_id, headers, logger)
elif endpoint == "records":
yield from _iter_records(session, view_id, headers, logger, resumable_source_manager)
- elif endpoint in ("projects", "databases", "grids", "views"):
+ elif endpoint in ("projects", "databases", "grids", "views", "branches"):
yield from _iter_hierarchy(session, endpoint, headers, logger)
+ elif endpoint == "dependencies":
+ yield from _iter_dependencies(session, view_id, headers, logger)
+ elif endpoint == "automation_executions":
+ yield from _iter_automation_executions(session, view_id, headers, logger, resumable_source_manager)
+ elif endpoint == "record_histories":
+ yield from _iter_record_histories(session, view_id, headers, logger, resumable_source_manager)
else:
raise ValueError(f"Unknown Gridly endpoint: {endpoint!r}")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/settings.py
index eeacf183a802..c243010ff2db 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/settings.py
@@ -7,7 +7,8 @@ class GridlyEndpointConfig:
# Record and column ids are unique within a view, and a Gridly source targets exactly one
# view, so `id` is unique table-wide. Project, database, grid and view ids are global: each one
# is retrievable on its own via `GET /v1/<resource>/<id>`.
- primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # A record history entry has no id of its own, so that table has no primary key.
+ primary_keys: list[str] | None = field(default_factory=lambda: ["id"])
should_sync_default: bool = True
description: str | None = None
# Hierarchy endpoints are listed once per parent row. `parent_id_param` is the query param that
@@ -61,6 +62,34 @@ GRIDLY_ENDPOINTS: dict[str, GridlyEndpointConfig] = {
parent="grids",
parent_id_param="gridId",
),
+ # Listed once per grid, like views. Gridly serves this API on the Team and Enterprise plans only.
+ "branches": GridlyEndpointConfig(
+ name="branches",
+ should_sync_default=False,
+ description="Branches of every Gridly grid, with the owning gridId. Needs a Gridly Team or Enterprise plan. Full refresh only.",
+ parent="grids",
+ parent_id_param="gridId",
+ ),
+ "dependencies": GridlyEndpointConfig(
+ name="dependencies",
+ description="Column dependencies of the configured Gridly view. Each one maps a source column to a target column. Full refresh only.",
+ ),
+ # An execution id is only documented under its automation
+ # (`GET /v1/automations/{automationId}/executions/{id}`), so the key includes the automation.
+ "automation_executions": GridlyEndpointConfig(
+ name="automation_executions",
+ primary_keys=["automationId", "id"],
+ should_sync_default=False,
+ description="Run history of every automation of the configured Gridly view, with the owning automationId. Full refresh only.",
+ ),
+ # One request per record on every sync, and Gridly serves this API on the Enterprise plan only,
+ # so it is off by default.
+ "record_histories": GridlyEndpointConfig(
+ name="record_histories",
+ primary_keys=None,
+ should_sync_default=False,
+ description="Change history of every record of the configured Gridly view, with the owning recordId. Makes one request per record on every sync. Needs a Gridly Enterprise plan. Full refresh only.",
+ ),
}
ENDPOINTS = tuple(GRIDLY_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/tests/test_gridly.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/tests/test_gridly.py
index bf24857cc3a6..dc763568ae2b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/tests/test_gridly.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gridly/tests/test_gridly.py
@@ -20,7 +20,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.gridly.gri
GridlyRetryableError,
validate_credentials,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.gridly.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.gridly.settings import ENDPOINTS, GRIDLY_ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.gridly.source import GridlySource
_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.gridly.gridly"
@@ -93,6 +93,8 @@ _HIERARCHY_RESPONSES: dict[tuple[str, tuple[tuple[str, str], ...]], list[dict[st
("/v1/grids", (("dbId", "db1"),)): [{"id": "g1", "name": "G1"}, {"id": "g2", "name": "G2"}],
("/v1/views", (("gridId", "g1"),)): [{"id": "v1", "name": "Default view"}],
("/v1/views", (("gridId", "g2"),)): [{"id": "v2", "name": "Default view"}, {"id": "v3", "name": "Fr"}],
+ ("/v1/branches", (("gridId", "g1"),)): [],
+ ("/v1/branches", (("gridId", "g2"),)): [{"id": "b1", "name": "Summer"}],
}
@@ -118,6 +120,7 @@ class TestHierarchy:
[{"id": "v2", "name": "Default view", "gridId": "g2"}, {"id": "v3", "name": "Fr", "gridId": "g2"}],
],
),
+ ("branches", [[{"id": "b1", "name": "Summer", "gridId": "g2"}]]),
],
)
def test_walks_hierarchy_and_tags_rows_with_parent_id(
@@ -129,6 +132,182 @@ class TestHierarchy:
assert result.items == expected_batches
+class TestDependencies:
+ def test_reads_dependencies_of_the_view(self) -> None:
+ dependencies = [{"id": "d1", "sourceColumnId": "enUS", "targetColumnId": "frFR"}]
+ result = _driver().run("dependencies", [ScriptedResponse(json=dependencies)])
+
+ assert result.raised is None
+ assert result.items == [dependencies]
+ assert result.paths == ["/v1/views/view/dependencies"]
+
+
+_EXECUTIONS: dict[str, list[dict[str, Any]]] = {
+ "/v1/automations/a1/executions": [{"id": "e1", "status": "SUCCESS"}, {"id": "e2", "status": "FAILED"}],
+ "/v1/automations/a2/executions": [],
+ "/v1/automations/a3/executions": [{"id": "e1", "status": "STARTED"}],
+}
+
+
+def _automations_response(request: RecordedRequest) -> ScriptedResponse:
+ if request.path == "/v1/automations":
+ assert request.param("viewId") == "view"
+ return ScriptedResponse(json=[{"id": "a1"}, {"id": "a2"}, {"id": "a3"}])
+ return ScriptedResponse(json=_EXECUTIONS[request.path])
+
+
+class TestAutomationExecutions:
+ @pytest.mark.parametrize(
+ "resume_offset, expected_items, expected_paths",
+ [
+ (
+ None,
+ [
+ [
+ {"id": "e1", "status": "SUCCESS", "automationId": "a1"},
+ {"id": "e2", "status": "FAILED", "automationId": "a1"},
+ ],
+ [{"id": "e1", "status": "STARTED", "automationId": "a3"}],
+ ],
+ [
+ "/v1/automations",
+ "/v1/automations/a1/executions",
+ "/v1/automations/a2/executions",
+ "/v1/automations/a3/executions",
+ ],
+ ),
+ (
+ 2,
+ [[{"id": "e1", "status": "STARTED", "automationId": "a3"}]],
+ ["/v1/automations", "/v1/automations/a3/executions"],
+ ),
+ ],
+ )
+ def test_fans_out_over_automations_from_the_resume_position(
+ self, resume_offset: int | None, expected_items: list[list[dict[str, Any]]], expected_paths: list[str]
+ ) -> None:
+ resume_state = None if resume_offset is None else GridlyResumeConfig(offset=resume_offset)
+ result = _driver().run("automation_executions", _automations_response, resume_state=resume_state)
+
+ assert result.raised is None
+ assert result.items == expected_items
+ assert result.paths == expected_paths
+
+
+_RECORD_PAGES: dict[int, list[dict[str, Any]]] = {0: [{"id": "r1"}, {"id": "r2"}], 2: [{"id": "r3"}]}
+_HISTORY_PAGES: dict[tuple[str, int], list[dict[str, Any]]] = {
+ ("r1", 0): [{"lastModifiedTime": "t1"}, {"lastModifiedTime": "t2"}],
+ ("r1", 2): [{"lastModifiedTime": "t3"}],
+ ("r2", 0): [],
+ ("r3", 0): [{"lastModifiedTime": "t4"}],
+}
+
+
+def _histories_response(request: RecordedRequest) -> ScriptedResponse:
+ page = json.loads(request.param("page") or "null")
+ assert page["limit"] == 2
+ if request.path == "/v1/views/view/records":
+ return ScriptedResponse(json=_RECORD_PAGES[page["offset"]])
+ record_id = request.path.split("/")[-2]
+ return ScriptedResponse(json=_HISTORY_PAGES[(record_id, page["offset"])])
+
+
+class TestRecordHistories:
+ @patch(f"{_MODULE}.PAGE_SIZE", 2)
+ @pytest.mark.parametrize(
+ "resume_offset, expected_items, expected_paths",
+ [
+ (
+ None,
+ [
+ [{"lastModifiedTime": "t1", "recordId": "r1"}, {"lastModifiedTime": "t2", "recordId": "r1"}],
+ [{"lastModifiedTime": "t3", "recordId": "r1"}],
+ [{"lastModifiedTime": "t4", "recordId": "r3"}],
+ ],
+ [
+ "/v1/views/view/records",
+ "/v1/views/view/records/r1/histories",
+ "/v1/views/view/records/r1/histories",
+ "/v1/views/view/records/r2/histories",
+ "/v1/views/view/records",
+ "/v1/views/view/records/r3/histories",
+ ],
+ ),
+ (
+ 2,
+ [[{"lastModifiedTime": "t4", "recordId": "r3"}]],
+ ["/v1/views/view/records", "/v1/views/view/records/r3/histories"],
+ ),
+ ],
+ )
+ def test_walks_every_history_page_of_every_record_from_the_resume_position(
+ self, resume_offset: int | None, expected_items: list[list[dict[str, Any]]], expected_paths: list[str]
+ ) -> None:
+ resume_state = None if resume_offset is None else GridlyResumeConfig(offset=resume_offset)
+ result = _driver().run("record_histories", _histories_response, resume_state=resume_state)
+
+ assert result.raised is None
+ assert result.items == expected_items
+ assert result.paths == expected_paths
+
+ @patch(f"{_MODULE}.PAGE_SIZE", 2)
+ def test_cursor_moves_past_a_record_only_with_its_last_history_page(self) -> None:
+ result = _driver().run("record_histories", _histories_response)
+
+ # r1 has two history pages: the cursor stays on r1 after its first page, at the second page,
+ # and moves past r1 only with the second page.
+ assert result.saved_states[0] == GridlyResumeConfig(offset=0, history_offset=2)
+ assert result.saved_states[1] == GridlyResumeConfig(offset=1)
+ assert GridlyResumeConfig(offset=2) in result.saved_states
+
+ @patch(f"{_MODULE}.PAGE_SIZE", 2)
+ def test_resumes_partway_through_the_history_of_a_record(self) -> None:
+ result = _driver().run(
+ "record_histories", _histories_response, resume_state=GridlyResumeConfig(offset=0, history_offset=2)
+ )
+
+ assert result.raised is None
+ assert result.items[0] == [{"lastModifiedTime": "t3", "recordId": "r1"}]
+ assert json.loads(result.requests[1].param("page") or "null")["offset"] == 2
+
+ @patch(f"{_MODULE}.PAGE_SIZE", 2)
+ def test_record_id_is_encoded_in_the_url_and_redacted_from_errors(self) -> None:
+ record_id = "a/b?c#d"
+ logger = MagicMock()
+
+ def respond(request: RecordedRequest) -> ScriptedResponse:
+ if request.path == "/v1/views/view/records":
+ return ScriptedResponse(json=[{"id": record_id}])
+ return ScriptedResponse(status=403)
+
+ result = _driver().run("record_histories", respond, logger=logger)
+
+ assert isinstance(result.raised, requests.HTTPError)
+ assert "a%2Fb%3Fc%23d" in result.requests[1].url
+ assert record_id not in str(result.raised)
+ assert "a%2Fb" not in str(result.raised)
+ assert "{recordId}/histories" in str(result.raised)
+ assert "a%2Fb" not in " ".join(str(call) for call in logger.error.call_args_list)
+
+ @patch(f"{_MODULE}.PAGE_SIZE", 2)
+ def test_record_id_is_redacted_from_connection_errors(self) -> None:
+ record_id = "[email protected]"
+ failure = requests.ConnectionError(
+ f"Max retries exceeded with url: /v1/views/view/records/{record_id}/histories"
+ )
+
+ def respond(request: RecordedRequest) -> ScriptedResponse:
+ if request.path == "/v1/views/view/records":
+ return ScriptedResponse(json=[{"id": record_id}])
+ raise failure
+
+ result = _driver().run("record_histories", respond)
+
+ assert isinstance(result.raised, requests.ConnectionError)
+ assert record_id not in str(result.raised)
+ assert "{recordId}/histories" in str(result.raised)
+
+
class TestRetries:
def test_retries_exhausted_raises(self) -> None:
result = _driver().run("records", always(ScriptedResponse(status=500)))
@@ -198,7 +377,7 @@ class TestSourceResponse:
assert result.raised is None
assert result.response is not None
assert result.response.name == endpoint
- assert result.response.primary_keys == ["id"]
+ assert result.response.primary_keys == GRIDLY_ENDPOINTS[endpoint].primary_keys
assert result.response.sort_mode == "asc"
# No stable datetime on records → nothing to partition on.
assert result.response.partition_keys is None