: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse-sources): add jotform usage, history and label tables (#112551)
Tom Owers4bdc05e6f78b
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.mdindex f8b64b9ac683..4560bd6a46e9 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@@ -4589,10 +4589,10 @@ Today (4): `forms`, `questions`, `reports`, `submissions`Diffed against: <https://api.jotform.com/docs/>-- [ ] `GET /user/usage` — monthly submission, upload, view and payment counts - Jotform's headline account metric (high)-- [ ] `GET /user/folders` — lookup grouping forms into folders, the org dimension for form reporting (medium)-- [ ] `GET /user/history` — account activity log (form created/deleted/edited events) (medium)-- [ ] `GET /user/labels and GET /label/{id}/resources` — label lookup plus the label-to-form/submission edges that resolve tags (medium)+- [x] `GET /user/usage` — monthly submission, upload, view and payment counts - Jotform's headline account metric (high). Added as `usage` (single-row snapshot of the current month).+- [ ] `GET /user/folders` — lookup grouping forms into folders, the org dimension for form reporting (medium). Skipped: Jotform marks the folder endpoints deprecated in favor of labels, which `labels` covers.+- [x] `GET /user/history` — account activity log (form created/deleted/edited events) (medium). Added as `history`.+- [x] `GET /user/labels and GET /label/{id}/resources` — label lookup plus the label-to-form/submission edges that resolve tags (medium). Added as `labels` (flattened label tree) and `label_resources` (fan-out over `labels`).- [ ] `GET /user/subusers` — sub-account users, needed to attribute forms and submissions in team accounts (low)- [ ] `GET /user` — account record (plan, limits) as the parent row for usage (low)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/canonical_descriptions.pyindex 8dc1b95f3750..7ba10759d193 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/canonical_descriptions.py@@ -67,4 +67,58 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"order": "Display order of the question within the form.",},},+ "usage": {+ "description": "Single-row snapshot of the account's usage for the current month. Each sync replaces the row.",+ "docs_url": "https://api.jotform.com/docs/#user-usage",+ "columns": {+ "submissions": "Number of submissions received this month.",+ "ssl_submissions": "Number of secure (SSL) submissions received this month.",+ "payments": "Number of payment submissions received this month.",+ "uploads": "Total disk space used by uploaded files, in bytes.",+ "mobile_submissions": "Number of mobile submissions received this month.",+ "views": "Number of form views received this month.",+ "api": "Number of API calls used today.",+ },+ },+ "history": {+ "description": "Account activity log: account creation, logins, and form creation, update, delete and purge events.",+ "docs_url": "https://api.jotform.com/docs/#user-history",+ "columns": {+ "type": "Activity type (userCreation, userLogin, formCreation, formUpdate, formDelete or formPurge).",+ "formID": "Identifier of the form the activity applies to, for form activities.",+ "username": "Username of the account that performed the activity.",+ "formTitle": "Title of the form at the time of the activity.",+ "formStatus": "Status of the form at the time of the activity.",+ "ip": "IP address the activity came from.",+ "timestamp": "Time of the activity, in seconds since the Unix epoch.",+ },+ },+ "labels": {+ "description": "One row per label (tag) on the account. Labels form a tree: each row links to its parent through `parent_label_id`.",+ "docs_url": "https://api.jotform.com/docs/#get-user-labels",+ "columns": {+ "id": "Unique identifier of the label.",+ "name": "Display name of the label.",+ "color": "Label color as a hex code.",+ "order": "Display order of the label among its siblings.",+ "parent_label_id": "Identifier of the parent label. Empty for the account's root label.",+ "owner": "Username of the account that owns the label.",+ "owner_type": "Type of the owner of the root label (e.g. USER).",+ "created_at": "Timestamp the label was created.",+ "updated_at": "Timestamp the label was last updated.",+ },+ },+ "label_resources": {+ "description": "One row per asset (form, workflow, sheet or app) tagged with a label. The same asset appears once for each label it carries.",+ "docs_url": "https://api.jotform.com/docs/#get-label-id-resources",+ "columns": {+ "label_id": "Identifier of the label the asset is tagged with.",+ "id": "Identifier of the asset, unique within its asset type.",+ "assetType": "Asset type (e.g. form, workflow, sheet, portal).",+ "title": "Display title of the asset.",+ "status": "Asset status (e.g. ENABLED, DISABLED).",+ "created_at": "Timestamp the asset was created.",+ "updated_at": "Timestamp the asset was last updated.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/jotform.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/jotform.pyindex d4254d5da22b..f08646add95c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/jotform.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/jotform.py@@ -136,7 +136,7 @@ def _list_params(last_value: Optional[Any],incremental_field: Optional[str],) -> dict[str, Any]:- params: dict[str, Any] = {}+ params: dict[str, Any] = dict(config.params)if not config.incremental_fields:# Full-refresh endpoints (reports): no orderby/filter.return params@@ -165,6 +165,36 @@ def _question_row(row: dict[str, Any]) -> dict[str, Any]:return row+def _flatten_label_tree(label: dict[str, Any]) -> list[dict[str, Any]]:+ # `/user/labels` returns one root label with labels nested under `sublabels`; emit one row per+ # label (pre-order), each linked to its parent through `parent_label_id`. An id-less node can't+ # be keyed or fanned out over, so it is dropped (its children are still walked).+ rows: list[dict[str, Any]] = []+ stack = [label]+ while stack:+ node = stack.pop()+ children = node.get("sublabels") or []+ if node.get("id") is not None:+ rows.append({key: value for key, value in node.items() if key != "sublabels"})+ stack.extend(child for child in reversed(children) if isinstance(child, dict))+ return rows+++def _label_resource_row(row: dict[str, Any]) -> dict[str, Any]:+ row["label_id"] = str(row.pop("_labels_id"))+ return row+++def _load_fanout_state(+ resumable_source_manager: ResumableSourceManager[JotformResumeConfig],+) -> Optional[dict[str, Any]]:+ if resumable_source_manager.can_resume():+ resume = resumable_source_manager.load_state()+ if resume is not None:+ return resume.fanout_state+ return None++def _list_source(api_key: str,base_url: str,@@ -180,7 +210,9 @@ def _list_source("client": {**_client_config(api_key, base_url),# Jotform reports no reliable top-level total; termination is the short/empty page.- "paginator": OffsetPaginator(limit=config.page_size, total_path=None),+ "paginator": SinglePagePaginator()+ if config.single_page+ else OffsetPaginator(limit=config.page_size, total_path=None),},"resources": [{@@ -206,7 +238,7 @@ def _list_source(if state and state.get("offset") is not None:resumable_source_manager.save_state(JotformResumeConfig(offset=int(state["offset"])))- return rest_api_resource(+ resource = rest_api_resource(rest_config,team_id,job_id,@@ -214,6 +246,9 @@ def _list_source(resume_hook=save_checkpoint,initial_paginator_state=initial_paginator_state,)+ if endpoint == "labels":+ resource.add_map(_flatten_label_tree)+ return resourcedef _questions_source(@@ -254,12 +289,6 @@ def _questions_source(],}- initial_paginator_state: Optional[dict[str, Any]] = None- if resumable_source_manager.can_resume():- resume = resumable_source_manager.load_state()- if resume is not None:- initial_paginator_state = resume.fanout_state-def save_checkpoint(state: Optional[dict[str, Any]]) -> None:resumable_source_manager.save_state(JotformResumeConfig(fanout_state=state))@@ -269,7 +298,7 @@ def _questions_source(job_id,None,resume_hook=save_checkpoint,- initial_paginator_state=initial_paginator_state,+ initial_paginator_state=_load_fanout_state(resumable_source_manager),)forms_resource = next(r for r in resources if r.name == "forms")# Skip forms without an id so the fan-out never tries to resolve a form-less path (the@@ -278,6 +307,60 @@ def _questions_source(return next(r for r in resources if r.name == "questions")+def _label_resources_source(+ api_key: str,+ base_url: str,+ config: JotformEndpointConfig,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[JotformResumeConfig],+) -> Resource:+ labels_config = JOTFORM_ENDPOINTS["labels"]++ rest_config: RESTAPIConfig = {+ "client": _client_config(api_key, base_url),+ "resources": [+ {+ "name": "labels",+ "endpoint": {+ "path": labels_config.path,+ "data_selector": "content",+ "paginator": SinglePagePaginator(),+ },+ },+ {+ "name": "label_resources",+ "include_from_parent": ["id"],+ "endpoint": {+ "path": config.path,+ "params": {+ "label_id": {"type": "resolve", "resource": "labels", "field": "id"},+ "orderby": "created_at",+ },+ "data_selector": "content",+ "paginator": OffsetPaginator(limit=config.page_size, total_path=None),+ },+ "data_map": _label_resource_row,+ },+ ],+ }++ def save_checkpoint(state: Optional[dict[str, Any]]) -> None:+ resumable_source_manager.save_state(JotformResumeConfig(fanout_state=state))++ resources = rest_api_resources(+ rest_config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint,+ initial_paginator_state=_load_fanout_state(resumable_source_manager),+ )+ labels_resource = next(r for r in resources if r.name == "labels")+ labels_resource.add_map(_flatten_label_tree)+ return next(r for r in resources if r.name == "label_resources")++def validate_credentials(api_key: str, region: Optional[str], enterprise_domain: Optional[str] = None) -> bool:"""Confirm the API key is valid for the target host. ``/user`` is the cheapest authenticated probe."""# Same SSRF posture as the sync client: no redirects off the validated host, redact the key.@@ -307,6 +390,8 @@ def jotform_source(if config.fan_out_over_forms:resource = _questions_source(api_key, base_url, config, team_id, job_id, resumable_source_manager)+ elif config.fan_out_over_labels:+ resource = _label_resources_source(api_key, base_url, config, team_id, job_id, resumable_source_manager)else:resource = _list_source(api_key,@@ -323,7 +408,7 @@ def jotform_source(return SourceResponse(name=endpoint,items=lambda: resource,- primary_keys=list(config.primary_keys),+ primary_keys=list(config.primary_keys) if config.primary_keys else None,sort_mode="asc",partition_count=1,partition_size=1,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/settings.pyindex 784574aee1a4..48149e36612a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/settings.py@@ -18,13 +18,14 @@ CREATED_AT_INCREMENTAL = _datetime_field("created_at")UPDATED_AT_INCREMENTAL = _datetime_field("updated_at")-@dataclass+@dataclass(frozen=False)class JotformEndpointConfig:name: str# Path relative to the regional API host. A `{form_id}` placeholder marks a per-form fan-out# endpoint (questions), which iterates every form on the account.path: str- primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # None when the API returns no stable identifier (single-row snapshots, the activity log).+ primary_keys: Optional[list[str]] = field(default_factory=lambda: ["id"])incremental_fields: list[IncrementalField] = field(default_factory=list)default_incremental_field: Optional[str] = None# Stable creation-time field used for datetime partitioning. Never an updated_at-style field,@@ -32,15 +33,26 @@ class JotformEndpointConfig:partition_key: Optional[str] = Nonepartition_format: Optional[PartitionFormat] = Nonepage_size: int = 100+ # Static query params sent on every request.+ params: dict[str, str] = field(default_factory=dict)+ # The endpoint returns everything in one response (no offset/limit support).+ single_page: bool = False# Fan out one request per form. The questions response is an object keyed by question id (not a# list), so it uses the dedicated questions iterator rather than offset pagination.fan_out_over_forms: bool = False+ # Fan out one offset-paginated request per label, over the flattened `/user/labels` tree.+ fan_out_over_labels: bool = False# Forms and submissions expose Jotform's server-side `filter={"<field>:gt":"..."}` timestamp filter,# so they're advertised as incremental. Reports has no documented timestamp filter (full refresh).# Questions describe form structure (no timestamps), fan out per form, and are full refresh; their# `qid` is unique only within a form, so the form id is part of the primary key.+# Usage, history, labels and label resources have no server-side timestamp filter fine enough to+# merge on, so they are full refresh. Usage is a single-row snapshot of the current month. History+# rows carry no identifier, so neither has a primary key. A label resource is an asset (form,+# workflow, sheet, app) tagged with a label; the same asset can carry several labels, and asset ids+# are only documented as unique within their type, so the key includes the label id and asset type.JOTFORM_ENDPOINTS: dict[str, JotformEndpointConfig] = {"forms": JotformEndpointConfig(name="forms",@@ -73,6 +85,35 @@ JOTFORM_ENDPOINTS: dict[str, JotformEndpointConfig] = {primary_keys=["form_id", "qid"],fan_out_over_forms=True,),+ "usage": JotformEndpointConfig(+ name="usage",+ path="/user/usage",+ primary_keys=None,+ single_page=True,+ ),+ "history": JotformEndpointConfig(+ name="history",+ path="/user/history",+ primary_keys=None,+ params={"date": "all", "sortBy": "ASC"},+ single_page=True,+ ),+ "labels": JotformEndpointConfig(+ name="labels",+ path="/user/labels",+ primary_keys=["id"],+ partition_key="created_at",+ partition_format="month",+ single_page=True,+ ),+ "label_resources": JotformEndpointConfig(+ name="label_resources",+ path="/label/{label_id}/resources",+ primary_keys=["label_id", "assetType", "id"],+ partition_key="created_at",+ partition_format="month",+ fan_out_over_labels=True,+ ),}ENDPOINTS = tuple(JOTFORM_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/source.pyindex c8aef04cfb79..60ff958c753e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/source.py@@ -59,6 +59,10 @@ Supported tables:- `submissions`- `reports`- `questions`+- `usage`+- `history`+- `labels`+- `label_resources`""",iconPath="/static/services/jotform.png",docsUrl="https://posthog.com/docs/cdp/sources/jotform",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/tests/test_jotform.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/tests/test_jotform.pyindex cbfbab138d6f..742da189b17b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/tests/test_jotform.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jotform/tests/test_jotform.py@@ -240,6 +240,139 @@ class TestListEndpoints:assert _rows(_source("reports", _make_manager())) == []+class TestSinglePageEndpoints:+ @pytest.mark.parametrize(+ "endpoint, content, expected_params, expected_rows",+ [+ (+ "usage",+ {"submissions": "478", "uploads": "31246868", "views": "2014"},+ {},+ [{"submissions": "478", "uploads": "31246868", "views": "2014"}],+ ),+ (+ "history",+ [+ {"type": "userLogin", "username": "johnsmith", "timestamp": 1372145800},+ {"type": "formCreation", "formID": "31751954731962", "timestamp": 1372145854},+ ],+ {"date": "all", "sortBy": "ASC"},+ [+ {"type": "userLogin", "username": "johnsmith", "timestamp": 1372145800},+ {"type": "formCreation", "formID": "31751954731962", "timestamp": 1372145854},+ ],+ ),+ ],+ )+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_fetches_once_without_offset_pagination(+ self, MockSession, endpoint, content, expected_params, expected_rows+ ):+ session = MockSession.return_value+ capture = _wire(session, [_response(content)])++ rows = _rows(_source(endpoint, _make_manager()))++ assert rows == expected_rows+ assert session.send.call_count == 1+ assert capture.params[0] == expected_params++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_labels_tree_is_flattened_to_one_row_per_label(self, MockSession):+ session = MockSession.return_value+ tree = {+ "id": "root",+ "owner": "johnsmith",+ "sublabels": [+ {+ "id": "finance",+ "parent_label_id": "root",+ "sublabels": [{"id": "hr", "parent_label_id": "finance", "sublabels": []}],+ },+ {"name": "no id", "sublabels": [{"id": "orphan", "parent_label_id": "missing"}]},+ {"id": "it", "parent_label_id": "root", "sublabels": []},+ ],+ }+ capture = _wire(session, [_response(tree)])++ rows = _rows(_source("labels", _make_manager()))++ assert rows == [+ {"id": "root", "owner": "johnsmith"},+ {"id": "finance", "parent_label_id": "root"},+ {"id": "hr", "parent_label_id": "finance"},+ {"id": "orphan", "parent_label_id": "missing"},+ {"id": "it", "parent_label_id": "root"},+ ]+ assert capture.urls == [f"{US_BASE}/user/labels"]+ assert capture.params[0] == {}+++class TestLabelResourcesFanOut:+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_fans_out_over_nested_labels_and_injects_label_id(self, MockSession):+ session = MockSession.return_value+ tree = {"id": "root", "sublabels": [{"id": "child", "parent_label_id": "root", "sublabels": []}]}+ root_assets = [{"id": "251453058472053", "assetType": "form"}]+ child_assets = [+ {"id": "251453058472053", "assetType": "form"},+ {"id": "251453701279861", "assetType": "workflow"},+ ]+ capture = _wire(session, [_response(tree), _response(root_assets), _response(child_assets)])++ manager = _make_manager()+ rows = _rows(_source("label_resources", manager))++ assert [(r["label_id"], r["assetType"], r["id"]) for r in rows] == [+ ("root", "form", "251453058472053"),+ ("child", "form", "251453058472053"),+ ("child", "workflow", "251453701279861"),+ ]+ assert all("_labels_id" not in r for r in rows)+ assert capture.urls == [+ f"{US_BASE}/user/labels",+ f"{US_BASE}/label/root/resources",+ f"{US_BASE}/label/child/resources",+ ]+ assert capture.params[1]["orderby"] == "created_at"+ assert capture.params[1]["offset"] == 0+ saved_states = [c.args[0].fanout_state for c in manager.save_state.call_args_list]+ assert set(saved_states[-1]["completed"]) == {"/label/root/resources", "/label/child/resources"}+ assert saved_states[-1]["current"] is None+ assert saved_states[-1]["child_state"] is None++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_paginates_each_label_until_partial_page(self, MockSession):+ session = MockSession.return_value+ with mock.patch.object(JOTFORM_ENDPOINTS["label_resources"], "page_size", 2):+ capture = _wire(+ session,+ [+ _response({"id": "root", "sublabels": []}),+ _response([{"id": "1", "assetType": "form"}, {"id": "2", "assetType": "form"}]),+ _response([{"id": "3", "assetType": "form"}]),+ ],+ )+ rows = _rows(_source("label_resources", _make_manager()))++ assert [r["id"] for r in rows] == ["1", "2", "3"]+ assert [p.get("offset") for p in capture.params[1:]] == [0, 2]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_resumes_and_skips_completed_labels(self, MockSession):+ session = MockSession.return_value+ tree = {"id": "root", "sublabels": [{"id": "child", "sublabels": []}]}+ capture = _wire(session, [_response(tree), _response([{"id": "1", "assetType": "form"}])])++ resume = JotformResumeConfig(+ fanout_state={"completed": ["/label/root/resources"], "current": None, "child_state": None}+ )+ rows = _rows(_source("label_resources", _make_manager(resume)))++ assert [r["label_id"] for r in rows] == ["child"]+ assert capture.urls == [f"{US_BASE}/user/labels", f"{US_BASE}/label/child/resources"]++class TestRetries:@pytest.mark.parametrize("status_code", [429, 500, 503])@mock.patch("tenacity.nap.time.sleep", return_value=None)