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 Windmill source (#118804)

Tom Owers798ec5bed8a1
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 9338c1ac82b4..561ca39f7352 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -1210,7 +1210,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/whop/whop.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/wikipedia_pageviews/wikipedia_pageviews.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/windmill/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/windmill/windmill.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/woocommerce/woocommerce.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/wordpress/settings.py
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 25b508fef39b..a91729f7574a 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
@@ -13127,10 +13127,10 @@ Today (9): `apps`, `audit_logs`, `completed_jobs`, `flows`, `queued_jobs`, `reso
Diffed against: <https://raw.githubusercontent.com/windmill-labs/windmill/main/backend/windmill-api/openapi.yaml>
-- [ ] `folders/list (GET /w/{workspace}/folders/list)` — lookup that resolves the f/<folder>/ path prefix carried by every script, flow, app and resource we already sync (high)
-- [ ] `groups/list + groups/get (GET /w/{workspace}/groups/list, /groups/get)` — group membership and ownership lookup for the ACLs on synced runnables (high)
-- [ ] `workspaces/list (GET /workspaces/list)` — lookup resolving the workspace id every other table is scoped by (high)
-- [ ] `users/list_usage + workspaces/usage` — per-user and per-workspace execution counts, the natural cost/usage metric (medium)
+- [x] `folders/list (GET /w/{workspace}/folders/list)` — lookup that resolves the f/<folder>/ path prefix carried by every script, flow, app and resource we already sync (high)
+- [x] `groups/list + groups/get (GET /w/{workspace}/groups/list, /groups/get)` — group membership and ownership lookup for the ACLs on synced runnables (high)
+- [x] `workspaces/list (GET /workspaces/list)` — lookup resolving the workspace id every other table is scoped by (high)
+- [x] `users/list_usage + workspaces/usage` — per-user and per-workspace execution counts, the natural cost/usage metric (medium)
- [ ] `workers/list, workers/queue_counts, workers/queue_metrics` — worker capacity and queue depth telemetry to pair with queued_jobs/completed_jobs (medium)
- [ ] `scripts/history, flows/history, apps/history` — deployment version history for the runnables we already sync (medium)
- [ ] `concurrency_groups/list (GET /concurrency_groups/list)` — concurrency limits and running counts explaining job queue waits (medium)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/canonical_descriptions.py
index a577ba941a9a..c8ecbd688370 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/canonical_descriptions.py
@@ -130,6 +130,56 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"created_at": "Timestamp the user was added to the workspace.",
},
},
+ "user_usage": {
+ "description": "Execution usage of each workspace member over the last 7 days.",
+ "docs_url": "https://www.windmill.dev/docs/misc/plans_details",
+ "columns": {
+ "email": "Email of the workspace member (primary key).",
+ "executions": "Execution units of the member's non-flow jobs in the last 7 days. Each job counts its run time in seconds, plus one.",
+ },
+ },
+ "folders": {
+ "description": "Folders in the workspace. Items in a folder carry an f/<folder>/ path prefix and inherit its permissions.",
+ "docs_url": WINDMILL_DOCS + "/groups_and_folders",
+ "columns": {
+ "name": "Name of the folder, as used in the f/<folder>/ path prefix (primary key).",
+ "workspace_id": "Workspace the folder belongs to.",
+ "display_name": "Display name of the folder.",
+ "owners": "Users and groups that own the folder.",
+ "extra_perms": "Map of user or group to write permission (true) or read-only access (false).",
+ "summary": "Summary of the folder.",
+ "created_by": "Username that created the folder.",
+ "edited_at": "Timestamp of the last edit.",
+ "default_permissioned_as": "Ordered rules that set the default identity of items deployed in the folder, matched by path glob.",
+ "labels": "Labels set on the folder. Items in the folder inherit them.",
+ },
+ },
+ "groups": {
+ "description": "Groups of users in the workspace, used to share scripts, flows, apps, resources and folders.",
+ "docs_url": WINDMILL_DOCS + "/groups_and_folders",
+ "columns": {
+ "name": "Name of the group, as used in the g/<group> owner prefix (primary key).",
+ "workspace_id": "Workspace the group belongs to.",
+ "summary": "Summary of the group.",
+ "members": "Usernames of the group members.",
+ "extra_perms": "Map of user or group to write permission (true) or read-only access (false) on the group.",
+ },
+ },
+ "workspaces": {
+ "description": "Workspaces visible to the user that owns the API token.",
+ "docs_url": WINDMILL_DOCS + "/workspace_settings",
+ "columns": {
+ "id": "Workspace ID, as used in API paths (primary key).",
+ "name": "Display name of the workspace.",
+ "owner": "Email of the workspace owner.",
+ "domain": "Email domain allowed to join the workspace automatically.",
+ "color": "Color used for the workspace in the Windmill UI.",
+ "parent_workspace_id": "ID of the parent workspace, for a fork or a dev workspace.",
+ "deleted": "Whether the workspace is archived.",
+ "is_dev_workspace": "Whether the workspace is a dev workspace.",
+ "dev_workspace_label": "Environment label of a dev workspace, such as dev or staging.",
+ },
+ },
"audit_logs": {
"description": "Audit log entries for the workspace (Windmill Enterprise Edition).",
"docs_url": WINDMILL_DOCS + "/audit_logs",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/settings.py
index 2038431d0017..c71eba5831a3 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/settings.py
@@ -5,7 +5,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-@dataclass
+@dataclass(frozen=True)
class WindmillEndpointConfig:
name: str
# Path relative to the workspace root (``{base}/api/w/{workspace}``).
@@ -16,6 +16,14 @@ class WindmillEndpointConfig:
# ignores pagination params and returns every member in a single array, so paging it would
# re-request the same full list forever. Those endpoints set ``paginated=False``.
paginated: bool = True
+ # ``listFolders`` drops folders the token's scope can't read after applying LIMIT/OFFSET, so a
+ # short page there doesn't mean the scan is done. Those endpoints stop on an empty page instead.
+ stop_on_short_page: bool = True
+ # ``listWorkspaces`` lives at the API root rather than under ``/w/{workspace}``.
+ workspace_scoped: bool = True
+ # Detail path fetched once per listed row, with ``{name}`` bound to the row's ``name``. Used
+ # where the list endpoint omits fields the detail carries (group members).
+ detail_path: Optional[str] = None
# Whether the endpoint accepts the ``order_desc`` param. When it does we request ascending
# order (``order_desc=false``) so newly inserted rows land at the end of the result set and
# don't shift the offsets of pages we've already walked mid-sync.
@@ -110,6 +118,36 @@ WINDMILL_ENDPOINTS: dict[str, WindmillEndpointConfig] = {
partition_key="created_at",
description="Workspace members. Returned in a single unpaginated response.",
),
+ "user_usage": WindmillEndpointConfig(
+ name="user_usage",
+ path="/users/list_usage",
+ primary_keys=["email"],
+ paginated=False,
+ description="Per-member execution usage over the last 7 days. A rolling snapshot, so each sync replaces the table.",
+ ),
+ "folders": WindmillEndpointConfig(
+ name="folders",
+ path="/folders/list",
+ primary_keys=["name"],
+ stop_on_short_page=False,
+ description="Folders that group scripts, flows, apps and resources under an f/<folder>/ path, with owners and permissions.",
+ ),
+ "groups": WindmillEndpointConfig(
+ name="groups",
+ path="/groups/list",
+ primary_keys=["name"],
+ detail_path="/groups/get/{name}",
+ description="Workspace groups with their members and permissions. Fetches each group once to read its members.",
+ ),
+ # Every workspace the token's user can see, not only the one this source syncs.
+ "workspaces": WindmillEndpointConfig(
+ name="workspaces",
+ path="/workspaces/list",
+ primary_keys=["id"],
+ paginated=False,
+ workspace_scoped=False,
+ description="Workspaces visible to the token's user, with name, owner and domain.",
+ ),
# Audit logs are a Windmill Enterprise Edition feature and require a workspace-admin token; the
# endpoint returns an empty list on Community Edition. Ordering is not part of the public API,
# so this stays full refresh rather than risk a corrupt incremental watermark.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/tests/test_windmill.py b/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/tests/test_windmill.py
index f529eba84975..1562399964fe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/tests/test_windmill.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/tests/test_windmill.py
@@ -10,6 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.tes
ScriptedResponse,
SourceDriver,
always,
+ route,
scripted_network,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.windmill import (
@@ -193,6 +194,78 @@ class TestSync:
assert len(result.requests) == 1
assert result.requests[0].url.startswith(BASE_URL)
+ @pytest.mark.parametrize(
+ "endpoint, page_sizes, expected_pages",
+ [
+ # A short page ends the walk for endpoints whose pages are filled by LIMIT/OFFSET.
+ ("completed_jobs", [PER_PAGE, 1], ["1", "2"]),
+ # listFolders drops out-of-scope folders after LIMIT, so a short page can precede more
+ # rows and only an empty page ends the walk.
+ ("folders", [PER_PAGE, 1, 3, 0], ["1", "2", "3", "4"]),
+ ],
+ )
+ def test_page_walk_terminates(self, endpoint, page_sizes, expected_pages):
+ result = _driver().run(endpoint, [_json_response(_page(n)) for n in page_sizes])
+
+ assert result.raised is None
+ assert result.params("page") == expected_pages
+ assert len(result.rows) == sum(page_sizes)
+
+ @pytest.mark.parametrize(
+ "endpoint, expected_url",
+ [
+ ("workspaces", f"{BASE_URL}/api/workspaces/list"),
+ ("user_usage", f"{BASE_URL}/api/w/{WORKSPACE}/users/list_usage"),
+ ],
+ )
+ def test_unpaginated_endpoint_makes_one_request(self, endpoint, expected_url):
+ rows = [{"id": "ws-1", "email": "[email protected]", "executions": 12}]
+
+ result = _driver().run(endpoint, [_json_response(rows)])
+
+ assert result.raised is None
+ assert result.urls == [expected_url]
+ assert result.rows == rows
+
+ def test_groups_fetch_each_detail_for_members(self):
+ detail_alpha = {"name": "alpha", "summary": "A", "members": ["ann", "bob"], "extra_perms": {}}
+ result = _driver().run(
+ "groups",
+ route(
+ {
+ "/groups/list": [
+ _json_response([{"name": "alpha", "extra_perms": {}}, {"name": "gone", "extra_perms": {}}]),
+ ],
+ "/groups/get/alpha": [_json_response(detail_alpha)],
+ # Deleted between the list call and its detail call.
+ "/groups/get/gone": [_json_response({"error": "not found"}, status_code=404)],
+ }
+ ),
+ )
+
+ assert result.raised is None
+ assert result.paths == [
+ f"/api/w/{WORKSPACE}/groups/list",
+ f"/api/w/{WORKSPACE}/groups/get/alpha",
+ f"/api/w/{WORKSPACE}/groups/get/gone",
+ ]
+ assert [{k: row[k] for k in detail_alpha} for row in result.rows] == [detail_alpha]
+
+ def test_groups_percent_encode_names_in_detail_path(self):
+ result = _driver().run(
+ "groups",
+ route(
+ {
+ "/groups/list": [_json_response([{"name": "team#ops/eu", "extra_perms": {}}])],
+ "/groups/get/team%23ops%2Feu": [_json_response({"name": "team#ops/eu", "members": ["ann"]})],
+ }
+ ),
+ )
+
+ assert result.raised is None
+ assert result.paths[-1] == f"/api/w/{WORKSPACE}/groups/get/team%23ops%2Feu"
+ assert [row["members"] for row in result.rows] == [["ann"]]
+
@mock.patch(HOST_SAFE_PATCH)
def test_raises_when_host_not_allowed(self, mock_host_safe):
mock_host_safe.return_value = (False, "host not allowed")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/windmill.py b/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/windmill.py
index 2434727c6ba8..63c703257880 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/windmill.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/windmill.py
@@ -13,15 +13,24 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mix
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
RESTAPIConfig,
rest_api_resource,
+ rest_api_resources,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BasePaginator,
PageNumberPaginator,
SinglePagePaginator,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
+)
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.windmill.settings import WINDMILL_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.windmill.settings import (
+ WINDMILL_ENDPOINTS,
+ WindmillEndpointConfig,
+)
MAX_RETRY_ATTEMPTS = 5
PER_PAGE = 100
@@ -79,6 +88,10 @@ def _workspace_base_url(base_url: str, workspace: str) -> str:
return f"{normalize_base_url(base_url)}/w/{quote(workspace, safe='')}"
+def _endpoint_base_url(base_url: str, workspace: str, config: WindmillEndpointConfig) -> str:
+ return _workspace_base_url(base_url, workspace) if config.workspace_scoped else normalize_base_url(base_url)
+
+
def _get_headers(api_token: str) -> dict[str, str]:
return {
"Authorization": f"Bearer {api_token}",
@@ -101,16 +114,18 @@ class WindmillPageNumberPaginator(PageNumberPaginator):
Windmill list endpoints return bare JSON arrays with no total, so a page shorter than
``per_page`` is the last one — stop there instead of paying an extra empty-page request the
- built-in (empty-page-only) stop check would incur.
+ built-in (empty-page-only) stop check would incur. ``stop_on_short_page=False`` keeps only the
+ empty-page check, for endpoints that can return a short page before the end.
"""
- def __init__(self, per_page: int) -> None:
+ def __init__(self, per_page: int, stop_on_short_page: bool = True) -> None:
super().__init__(base_page=1, page_param="page")
self._per_page = per_page
+ self._stop_on_short_page = stop_on_short_page
def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
super().update_state(response, data)
- if self._has_next_page and data is not None and len(data) < self._per_page:
+ if self._stop_on_short_page and self._has_next_page and data is not None and len(data) < self._per_page:
self._has_next_page = False
@@ -181,31 +196,30 @@ def windmill_source(
# listUsers ignores pagination params and returns every row at once, so a single request avoids
# re-fetching the same full list forever.
- paginator: BasePaginator = WindmillPageNumberPaginator(PER_PAGE) if config.paginated else SinglePagePaginator()
+ paginator: BasePaginator = (
+ WindmillPageNumberPaginator(PER_PAGE, stop_on_short_page=config.stop_on_short_page)
+ if config.paginated
+ else SinglePagePaginator()
+ )
+
+ list_endpoint: Endpoint = {"path": config.path, "params": params}
+ client_config: ClientConfig = {
+ "base_url": _endpoint_base_url(base_url, workspace, config),
+ # Auth (Bearer) is supplied via the framework auth config so its value is redacted from
+ # logs and error messages; only the non-secret Accept header is set here.
+ "headers": {"Accept": "application/json"},
+ "auth": {"type": "bearer", "token": api_token},
+ "paginator": paginator,
+ "max_retries": MAX_RETRY_ATTEMPTS,
+ # The instance host is customer-controlled, so never follow a redirect that could carry
+ # the bearer token to another origin.
+ "allow_redirects": False,
+ }
rest_config: RESTAPIConfig = {
- "client": {
- "base_url": _workspace_base_url(base_url, workspace),
- # Auth (Bearer) is supplied via the framework auth config so its value is redacted from
- # logs and error messages; only the non-secret Accept header is set here.
- "headers": {"Accept": "application/json"},
- "auth": {"type": "bearer", "token": api_token},
- "paginator": paginator,
- "max_retries": MAX_RETRY_ATTEMPTS,
- # The instance host is customer-controlled, so never follow a redirect that could carry
- # the bearer token to another origin.
- "allow_redirects": False,
- },
+ "client": client_config,
"resource_defaults": {},
- "resources": [
- {
- "name": endpoint,
- "endpoint": {
- "path": config.path,
- "params": params,
- },
- }
- ],
+ "resources": [{"name": endpoint, "endpoint": list_endpoint}],
}
# A saved page only indexes into a fixed result set. When an incremental watermark is active it
@@ -224,14 +238,22 @@ def windmill_source(
if state and state.get("page") is not None:
resumable_source_manager.save_state(WindmillResumeConfig(page=int(state["page"])))
- resource = rest_api_resource(
- rest_config,
- team_id,
- job_id,
- None,
- resume_hook=save_checkpoint,
- initial_paginator_state=initial_paginator_state,
- )
+ if config.detail_path is not None:
+ # The framework can't resume a parent/child walk, so these endpoints restart from page 1.
+ # They are small lookups (groups), so a restart costs little.
+ resources = rest_api_resources(
+ _detail_rest_config(endpoint, config.detail_path, client_config, list_endpoint), team_id, job_id, None
+ )
+ resource = next(r for r in resources if r.name == endpoint)
+ else:
+ resource = rest_api_resource(
+ rest_config,
+ team_id,
+ job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state=initial_paginator_state,
+ )
def items() -> Iterator[list[dict[str, Any]]]:
# Re-check at run time (not just at source-create) in case the URL was edited or now
@@ -255,3 +277,36 @@ def windmill_source(
partition_keys=[config.partition_key] if config.partition_key else None,
column_hints=resource.column_hints,
)
+
+
+_PATH_SEGMENT_FIELD = "_path_segment"
+
+
+def _add_path_segment(row: dict[str, Any]) -> dict[str, Any]:
+ return {**row, _PATH_SEGMENT_FIELD: quote(str(row["name"]), safe="")}
+
+
+def _detail_rest_config(
+ endpoint: str, detail_path: str, client_config: ClientConfig, list_endpoint: Endpoint
+) -> RESTAPIConfig:
+ """Walk the list endpoint, then fetch each row's detail, which carries fields the list omits."""
+ parent_name = f"{endpoint}_list"
+ detail_resource: EndpointResource = {
+ "name": endpoint,
+ "endpoint": {
+ "path": detail_path,
+ "params": {"name": {"type": "resolve", "resource": parent_name, "field": _PATH_SEGMENT_FIELD}},
+ "paginator": SinglePagePaginator(),
+ # A row deleted between the list call and its detail call is gone, not an error.
+ "response_actions": [{"status_code": 404, "action": "ignore"}],
+ },
+ }
+ return {
+ "client": client_config,
+ "resource_defaults": {},
+ "resources": [
+ # The path is bound with `str.format`, so percent-encode the name here (`#`, `/`, `?` in a name).
+ {"name": parent_name, "endpoint": list_endpoint, "data_map": _add_path_segment},
+ detail_resource,
+ ],
+ }