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 windmill import source (#70038)

Tom Owers119816110897
diff --git a/frontend/public/services/windmill.svg b/frontend/public/services/windmill.svg
new file mode 100644
index 000000000000..c0f3771ec5b5
--- /dev/null
+++ b/frontend/public/services/windmill.svg
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="utf-8"?>
+<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
+ viewBox="0 0 256 256" xml:space="preserve">
+<style type="text/css">
+ .st2{fill:#BCD4FC;}
+ .st3{fill:#3B82F6;}
+</style>
+<g>
+ <polygon class="st2" points="134.78,14.22 114.31,48.21 101.33,69.75 158.22,69.75 177.97,36.95 191.67,14.22 "/>
+ <polygon class="st3" points="227.55,69.75 186.61,69.75 101.33,69.75 129.78,119.02 158.16,119.02 228.61,119.02 256,119.02 "/>
+ <polygon class="st3" points="136.93,132.47 116.46,167.93 73.82,241.78 130.71,241.78 144.9,217.2 180.13,156.18 193.82,132.46
+ "/>
+ <polygon class="st3" points="121.7,131.95 101.23,96.49 58.59,22.63 30.15,71.91 44.34,96.49 79.57,157.5 93.26,181.22 "/>
+ <polygon class="st2" points="64.81,131.95 25.15,131.21 0,130.74 28.44,180.01 66.73,180.72 93.26,181.21 "/>
+ <polygon class="st2" points="165.38,181.74 184.58,216.46 196.75,238.47 225.19,189.2 206.66,155.69 193.83,132.46 "/>
+</g>
+</svg>
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 33fa2ab00113..5eca429f2ecb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -400,6 +400,7 @@ the row lists both.
| vercel | HTTP | requests | ✅ |
| vitally | HTTP | requests + `rest_source.RESTClient` | ✅ |
| webflow | HTTP | requests | ✅ |
+| windmill | HTTP | requests | ✅ |
| woocommerce | HTTP | requests + `rest_source.RESTClient` | ✅ |
| wordpress | HTTP | requests | ✅ |
| workable | HTTP | requests | ✅ |
@@ -846,7 +847,6 @@ doesn't conflict with concurrent PRs.
- watchmode
- when_i_work
- wikipedia_pageviews
-- windmill
- workday
- workflowmax
- workramp
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 9a9f4ee78a23..996ed5d81c63 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
@@ -4014,7 +4014,9 @@ class WikipediaPageviewsSourceConfig(config.Config):
@config.config
class WindmillSourceConfig(config.Config):
- pass
+ host: str
+ workspace: str
+ api_token: str
@config.config
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
new file mode 100644
index 000000000000..a577ba941a9a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/canonical_descriptions.py
@@ -0,0 +1,146 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+WINDMILL_DOCS = "https://www.windmill.dev/docs/core_concepts"
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "completed_jobs": {
+ "description": "Execution history of finished jobs (scripts, flows, and previews) in the workspace.",
+ "docs_url": WINDMILL_DOCS + "/monitor_past_and_future_runs",
+ "columns": {
+ "id": "Unique identifier (UUID) of the job.",
+ "workspace_id": "Workspace the job ran in.",
+ "parent_job": "UUID of the parent job, if this job was spawned by a flow or another job.",
+ "created_by": "Username that triggered the job.",
+ "created_at": "Timestamp when the job was created/enqueued.",
+ "started_at": "Timestamp when execution started.",
+ "duration_ms": "Total execution time in milliseconds.",
+ "success": "Whether the job completed successfully.",
+ "canceled": "Whether the job was canceled.",
+ "canceled_by": "Username that canceled the job, if any.",
+ "canceled_reason": "Reason the job was canceled, if any.",
+ "job_kind": "Kind of job (script, flow, preview, dependencies, etc.).",
+ "script_path": "Path of the script or flow that was run.",
+ "script_hash": "Hash of the exact script version that was run.",
+ "schedule_path": "Path of the schedule that triggered the job, if any.",
+ "language": "Language of the executed script.",
+ "tag": "Worker tag the job was assigned to.",
+ "email": "Email of the user the job was permissioned as.",
+ "is_flow_step": "Whether this job is a step within a flow.",
+ "is_skipped": "Whether the job was skipped.",
+ "labels": "Labels attached to the job.",
+ },
+ },
+ "queued_jobs": {
+ "description": "Jobs currently queued or running in the workspace.",
+ "docs_url": WINDMILL_DOCS + "/monitor_past_and_future_runs",
+ "columns": {
+ "id": "Unique identifier (UUID) of the job.",
+ "workspace_id": "Workspace the job belongs to.",
+ "created_by": "Username that triggered the job.",
+ "created_at": "Timestamp when the job was created/enqueued.",
+ "started_at": "Timestamp when execution started, if it has.",
+ "scheduled_for": "Timestamp the job is scheduled to run at.",
+ "running": "Whether the job is currently running.",
+ "script_path": "Path of the script or flow to run.",
+ "job_kind": "Kind of job (script, flow, preview, etc.).",
+ "tag": "Worker tag the job is assigned to.",
+ },
+ },
+ "scripts": {
+ "description": "Deployed scripts in the workspace, one row per latest version per path.",
+ "docs_url": "https://www.windmill.dev/docs/script_editor",
+ "columns": {
+ "hash": "Hash of this script version (primary key).",
+ "path": "Path of the script in the workspace.",
+ "summary": "Short human-readable summary.",
+ "description": "Longer description of the script.",
+ "created_by": "Username that created this version.",
+ "created_at": "Timestamp when this version was created.",
+ "language": "Script language (python3, deno, go, bash, etc.).",
+ "kind": "Script kind (script, trigger, approval, etc.).",
+ "archived": "Whether the script is archived.",
+ "starred": "Whether the current user starred the script.",
+ },
+ },
+ "flows": {
+ "description": "Deployed flows (multi-step workflows) in the workspace, one row per path.",
+ "docs_url": "https://www.windmill.dev/docs/flows/flow_editor",
+ "columns": {
+ "path": "Path of the flow in the workspace (primary key).",
+ "summary": "Short human-readable summary.",
+ "description": "Longer description of the flow.",
+ "edited_by": "Username that last edited the flow.",
+ "edited_at": "Timestamp of the last edit.",
+ "archived": "Whether the flow is archived.",
+ "starred": "Whether the current user starred the flow.",
+ },
+ },
+ "apps": {
+ "description": "Deployed apps (internal UIs built on Windmill) in the workspace.",
+ "docs_url": "https://www.windmill.dev/docs/apps/app_editor",
+ "columns": {
+ "id": "Unique identifier of the app (primary key).",
+ "workspace_id": "Workspace the app belongs to.",
+ "path": "Path of the app in the workspace.",
+ "summary": "Short human-readable summary.",
+ "version": "Deployed version number.",
+ "edited_at": "Timestamp of the last edit.",
+ "execution_mode": "Execution mode of the app (viewer, publisher, etc.).",
+ },
+ },
+ "schedules": {
+ "description": "Cron schedules that trigger scripts and flows in the workspace.",
+ "docs_url": WINDMILL_DOCS + "/scheduling",
+ "columns": {
+ "path": "Path of the schedule (primary key).",
+ "schedule": "Cron expression defining the schedule.",
+ "timezone": "Timezone the cron expression is evaluated in.",
+ "enabled": "Whether the schedule is enabled.",
+ "script_path": "Path of the script or flow the schedule runs.",
+ "is_flow": "Whether the scheduled runnable is a flow.",
+ "edited_by": "Username that last edited the schedule.",
+ "edited_at": "Timestamp of the last edit.",
+ },
+ },
+ "resources": {
+ "description": "Resource definitions (connection configs) in the workspace. Secret values are not returned.",
+ "docs_url": WINDMILL_DOCS + "/resources_and_types",
+ "columns": {
+ "path": "Path of the resource (primary key).",
+ "workspace_id": "Workspace the resource belongs to.",
+ "resource_type": "Type of the resource (postgresql, s3, etc.).",
+ "description": "Description of the resource.",
+ "is_oauth": "Whether the resource is backed by an OAuth connection.",
+ "created_by": "Username that created the resource.",
+ "edited_at": "Timestamp of the last edit.",
+ },
+ },
+ "users": {
+ "description": "Members of the workspace.",
+ "docs_url": WINDMILL_DOCS + "/roles_and_permissions",
+ "columns": {
+ "email": "Email of the user (primary key within the workspace).",
+ "username": "Username of the user in the workspace.",
+ "is_admin": "Whether the user is a workspace admin.",
+ "is_super_admin": "Whether the user is a Windmill instance super admin.",
+ "operator": "Whether the user is an operator (restricted role).",
+ "disabled": "Whether the user is disabled.",
+ "created_at": "Timestamp the user was added to the workspace.",
+ },
+ },
+ "audit_logs": {
+ "description": "Audit log entries for the workspace (Windmill Enterprise Edition).",
+ "docs_url": WINDMILL_DOCS + "/audit_logs",
+ "columns": {
+ "id": "Unique identifier of the audit log entry (primary key).",
+ "workspace_id": "Workspace the action occurred in.",
+ "timestamp": "Timestamp of the audited action.",
+ "username": "Username that performed the action.",
+ "operation": "Operation that was performed.",
+ "action_kind": "Kind of action (Created, Updated, Delete, Execute).",
+ "resource": "Resource the action targeted, if any.",
+ },
+ },
+}
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
new file mode 100644
index 000000000000..803f7e0c6358
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/settings.py
@@ -0,0 +1,131 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import PartitionFormat
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class WindmillEndpointConfig:
+ name: str
+ # Path relative to the workspace root (``{base}/api/w/{workspace}``).
+ path: str
+ primary_keys: list[str]
+ # Windmill list endpoints paginate with 1-based ``page`` + ``per_page`` and return bare JSON
+ # arrays, so we walk pages until one comes back short. ``listUsers`` is the one exception: it
+ # 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
+ # 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.
+ supports_order_desc: bool = False
+ # Stable (immutable) datetime field for partitioning. Only a creation timestamp — never an
+ # ``edited_at``/``last_*`` field, which would rewrite partitions on every sync.
+ partition_key: Optional[str] = None
+ partition_format: PartitionFormat = "month"
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Maps an incremental field name -> the server-side "after" (exclusive) query param that
+ # filters on it. Only set for endpoints Windmill genuinely filters server-side. When empty the
+ # endpoint is full-refresh only.
+ incremental_after_params: dict[str, str] = field(default_factory=dict)
+ should_sync_default: bool = True
+ description: Optional[str] = None
+
+
+def _datetime_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+WINDMILL_ENDPOINTS: dict[str, WindmillEndpointConfig] = {
+ # Completed jobs are immutable execution records, so they are the one genuinely incremental
+ # stream. Windmill exposes exclusive ``created_after`` / ``started_after`` filters; we request
+ # ascending order and advance the watermark from the chosen cursor field.
+ "completed_jobs": WindmillEndpointConfig(
+ name="completed_jobs",
+ path="/jobs/completed/list",
+ primary_keys=["id"],
+ supports_order_desc=True,
+ partition_key="created_at",
+ partition_format="day",
+ incremental_fields=[_datetime_field("created_at"), _datetime_field("started_at")],
+ incremental_after_params={"created_at": "created_after", "started_at": "started_after"},
+ description="Execution history of finished jobs (scripts, flows, previews) with status, duration, and script path. Immutable, so supports incremental sync.",
+ ),
+ # Queued/running jobs are transient (they move to completed_jobs when they finish), so each
+ # sync captures a fresh snapshot via full refresh.
+ "queued_jobs": WindmillEndpointConfig(
+ name="queued_jobs",
+ path="/jobs/queue/list",
+ primary_keys=["id"],
+ supports_order_desc=True,
+ partition_key="created_at",
+ partition_format="day",
+ description="Snapshot of jobs currently queued or running. Full refresh each sync since queued jobs are transient.",
+ ),
+ "scripts": WindmillEndpointConfig(
+ name="scripts",
+ path="/scripts/list",
+ primary_keys=["hash"],
+ supports_order_desc=True,
+ partition_key="created_at",
+ description="Deployed scripts, one row per latest version per path. The list endpoint has no updated-since filter, so it is full-refresh only.",
+ ),
+ "flows": WindmillEndpointConfig(
+ name="flows",
+ path="/flows/list",
+ primary_keys=["path"],
+ supports_order_desc=True,
+ description="Deployed flows (multi-step workflows), one row per path.",
+ ),
+ "apps": WindmillEndpointConfig(
+ name="apps",
+ path="/apps/list",
+ primary_keys=["id"],
+ supports_order_desc=True,
+ description="Deployed apps (internal UIs built on Windmill), one row per path.",
+ ),
+ "schedules": WindmillEndpointConfig(
+ name="schedules",
+ path="/schedules/list",
+ primary_keys=["path"],
+ description="Cron schedules that trigger scripts and flows.",
+ ),
+ "resources": WindmillEndpointConfig(
+ name="resources",
+ path="/resources/list",
+ primary_keys=["path"],
+ description="Resource definitions (connection configs). The list endpoint returns metadata; secret values are not included.",
+ ),
+ "users": WindmillEndpointConfig(
+ name="users",
+ path="/users/list",
+ primary_keys=["email"],
+ paginated=False,
+ partition_key="created_at",
+ description="Workspace members. Returned in a single unpaginated response.",
+ ),
+ # 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.
+ "audit_logs": WindmillEndpointConfig(
+ name="audit_logs",
+ path="/audit/list",
+ primary_keys=["id"],
+ partition_key="timestamp",
+ partition_format="week",
+ should_sync_default=False,
+ description="Audit log entries. Windmill Enterprise Edition only and requires a workspace-admin token (empty on Community Edition).",
+ ),
+}
+
+ENDPOINTS = tuple(WINDMILL_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in WINDMILL_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/source.py
index 9b8c32f417e6..e4ca97ff0f5f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/source.py
@@ -1,31 +1,161 @@
-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.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 WindmillSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.windmill.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ WINDMILL_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill import (
+ WindmillResumeConfig,
+ validate_credentials as validate_windmill_credentials,
+ windmill_source,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class WindmillSource(SimpleSource[WindmillSourceConfig]):
+class WindmillSource(ResumableSource[WindmillSourceConfig, WindmillResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.WINDMILL
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The API token is sent to whatever host `host` points at, so retargeting it must
+ # re-require the token (prevents exfiltrating the stored bearer token to another host).
+ return ["host"]
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.windmill.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.WINDMILL,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Windmill",
- iconPath="/static/services/windmill.png",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Windmill instance URL, workspace ID, and API token to sync your Windmill data into the PostHog Data warehouse.
+
+Create a personal API token in your Windmill account under **User settings → Tokens**. For cloud, your instance URL is `https://app.windmill.dev`; for self-hosted, use your own instance URL.
+
+The audit logs table requires a workspace-admin token and is a Windmill Enterprise Edition feature.""",
+ iconPath="/static/services/windmill.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/windmill",
keywords=["workflow", "automation", "jobs", "scripts"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="host",
+ label="Instance URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="https://app.windmill.dev",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="workspace",
+ label="Workspace ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="my-workspace",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Invalid Windmill API token. Create a new token in your Windmill user settings and reconnect.",
+ "403 Client Error": "Your Windmill API token lacks permission for this workspace or resource. Check the token's access and reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: WindmillSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=WINDMILL_ENDPOINTS[endpoint].should_sync_default,
+ description=WINDMILL_ENDPOINTS[endpoint].description,
+ )
+ 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: WindmillSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_windmill_credentials(config.api_token, config.host, config.workspace, team_id)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[WindmillResumeConfig]:
+ return ResumableSourceManager[WindmillResumeConfig](inputs, WindmillResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: WindmillSourceConfig,
+ resumable_source_manager: ResumableSourceManager[WindmillResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return windmill_source(
+ api_token=config.api_token,
+ base_url=config.host,
+ workspace=config.workspace,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=inputs.team_id,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
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
new file mode 100644
index 000000000000..11e5167fcf8e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/tests/test_windmill.py
@@ -0,0 +1,414 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+
+import requests
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.windmill.settings import (
+ ENDPOINTS,
+ WINDMILL_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill import (
+ PER_PAGE,
+ WindmillHostNotAllowedError,
+ WindmillResumeConfig,
+ _build_params,
+ _format_after,
+ _workspace_url,
+ get_rows,
+ normalize_base_url,
+ validate_credentials,
+ windmill_source,
+)
+
+BASE_URL = "https://app.windmill.dev"
+WORKSPACE = "my-workspace"
+
+
+def _make_manager(resume_state: WindmillResumeConfig | None = None) -> mock.MagicMock:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = resume_state is not None
+ manager.load_state.return_value = resume_state
+ return manager
+
+
+def _response(body: Any, status_code: int = 200) -> mock.MagicMock:
+ resp = mock.MagicMock()
+ resp.json.return_value = body
+ resp.status_code = status_code
+ resp.ok = 200 <= status_code < 400
+ return resp
+
+
+def _page(n: int) -> list[dict[str, Any]]:
+ return [{"id": str(i)} for i in range(n)]
+
+
+class TestNormalizeBaseUrl:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ ("https://app.windmill.dev", "https://app.windmill.dev/api"),
+ ("https://app.windmill.dev/", "https://app.windmill.dev/api"),
+ # A user pasting the full API root must not produce /api/api.
+ ("https://app.windmill.dev/api", "https://app.windmill.dev/api"),
+ ("https://app.windmill.dev/api/", "https://app.windmill.dev/api"),
+ # Plaintext is upgraded to https; a scheme-less host gets one.
+ ("http://windmill.internal.example.com", "https://windmill.internal.example.com/api"),
+ ("windmill.example.com", "https://windmill.example.com/api"),
+ (" https://app.windmill.dev ", "https://app.windmill.dev/api"),
+ # Embedded userinfo / query / fragment must not change the authority we connect to,
+ # so the SSRF host check can't diverge from the effective request host.
+ ("https://user:[email protected]", "https://app.windmill.dev/api"),
+ ("https://app.windmill.dev?x=1", "https://app.windmill.dev/api"),
+ ("https://app.windmill.dev#frag", "https://app.windmill.dev/api"),
+ # A custom port is preserved for self-hosted instances.
+ ("https://windmill.internal:8080", "https://windmill.internal:8080/api"),
+ ],
+ )
+ def test_normalizes(self, value, expected):
+ assert normalize_base_url(value) == expected
+
+
+class TestWorkspaceUrl:
+ def test_builds_workspace_scoped_path(self):
+ assert (
+ _workspace_url(BASE_URL, WORKSPACE, "/jobs/completed/list")
+ == "https://app.windmill.dev/api/w/my-workspace/jobs/completed/list"
+ )
+
+ def test_url_encodes_workspace(self):
+ # A workspace id with a slash must not escape the /w/ path segment.
+ assert "/w/a%2Fb/" in _workspace_url(BASE_URL, "a/b", "/users/list")
+
+
+class TestFormatAfter:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14+00:00"),
+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14+00:00"),
+ (date(2026, 3, 4), "2026-03-04T00:00:00+00:00"),
+ ("already-a-string", "already-a-string"),
+ ],
+ )
+ def test_format(self, value, expected):
+ assert _format_after(value) == expected
+
+
+class TestBuildParams:
+ def test_paginated_endpoint_sends_page_and_order(self):
+ params = _build_params(WINDMILL_ENDPOINTS["completed_jobs"], page=2, incremental_field=None, after_value=None)
+ assert params["page"] == 2
+ assert params["per_page"] == PER_PAGE
+ # Ascending so mid-sync inserts don't shift already-walked pages.
+ assert params["order_desc"] == "false"
+
+ def test_unpaginated_endpoint_omits_page_params(self):
+ params = _build_params(WINDMILL_ENDPOINTS["users"], page=1, incremental_field=None, after_value=None)
+ assert "page" not in params
+ assert "per_page" not in params
+ assert "order_desc" not in params
+
+ @pytest.mark.parametrize(
+ "incremental_field, expected_param",
+ [("created_at", "created_after"), ("started_at", "started_after")],
+ )
+ def test_incremental_field_maps_to_after_param(self, incremental_field, expected_param):
+ params = _build_params(
+ WINDMILL_ENDPOINTS["completed_jobs"],
+ page=1,
+ incremental_field=incremental_field,
+ after_value="2026-01-01T00:00:00+00:00",
+ )
+ assert params[expected_param] == "2026-01-01T00:00:00+00:00"
+
+ def test_after_value_ignored_for_full_refresh_endpoint(self):
+ # scripts has no server-side timestamp filter, so a cutoff must never leak into params.
+ params = _build_params(
+ WINDMILL_ENDPOINTS["scripts"],
+ page=1,
+ incremental_field="created_at",
+ after_value="2026-01-01T00:00:00+00:00",
+ )
+ assert "created_after" not in params
+ assert "started_after" not in params
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected_valid, expected_message",
+ [
+ (200, True, None),
+ (401, False, "Invalid Windmill API token"),
+ (403, False, "Could not access Windmill workspace 'my-workspace' with this token"),
+ (404, False, "Could not access Windmill workspace 'my-workspace' with this token"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill.make_tracked_session"
+ )
+ def test_status_mapping(self, mock_session, status_code, expected_valid, expected_message):
+ mock_session.return_value.get.return_value = _response({"message": "x"}, status_code=status_code)
+
+ valid, message = validate_credentials("token", BASE_URL, WORKSPACE)
+
+ assert valid is expected_valid
+ assert message == expected_message
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill.make_tracked_session"
+ )
+ def test_uses_no_redirect_session(self, mock_session):
+ mock_session.return_value.get.return_value = _response({}, status_code=200)
+ validate_credentials("token", BASE_URL, WORKSPACE)
+ assert mock_session.call_args.kwargs["allow_redirects"] is False
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill.make_tracked_session"
+ )
+ def test_redacts_api_token_in_tracked_session(self, mock_session):
+ # The bearer token rides in a header the name-based scrubbers can't see, so it must be
+ # value-redacted or it leaks into captured request samples.
+ mock_session.return_value.get.return_value = _response({}, status_code=200)
+ validate_credentials("token", BASE_URL, WORKSPACE)
+ assert mock_session.call_args.kwargs["redact_values"] == ("token",)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill.make_tracked_session"
+ )
+ def test_swallows_request_exceptions(self, mock_session):
+ mock_session.return_value.get.side_effect = requests.exceptions.ConnectionError("boom")
+ valid, message = validate_credentials("token", BASE_URL, WORKSPACE)
+ assert valid is False
+ assert message == "boom"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill._is_host_safe")
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill.make_tracked_session"
+ )
+ def test_blocks_internal_host_when_team_id_given(self, mock_session, mock_host_safe):
+ mock_host_safe.return_value = (False, "host not allowed")
+
+ valid, message = validate_credentials("token", "https://10.0.0.1", WORKSPACE, team_id=42)
+
+ assert valid is False
+ assert message == "host not allowed"
+ mock_session.return_value.get.assert_not_called()
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill._is_host_safe")
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill.make_tracked_session"
+ )
+ def test_skips_host_check_when_team_id_omitted(self, mock_session, mock_host_safe):
+ mock_session.return_value.get.return_value = _response({}, status_code=200)
+ validate_credentials("token", BASE_URL, WORKSPACE)
+ mock_host_safe.assert_not_called()
+
+
+class TestGetRows:
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill.make_tracked_session"
+ )
+ def test_walks_pages_until_short_page(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(_page(PER_PAGE)),
+ _response(_page(3)),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("token", BASE_URL, WORKSPACE, "completed_jobs", mock.MagicMock(), manager, team_id=1))
+
+ assert [len(b) for b in batches] == [PER_PAGE, 3]
+ pages = [call.args[0] for call in mock_session.return_value.get.call_args_list]
+ assert "page=1" in pages[0]
+ assert "page=2" in pages[1]
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill.make_tracked_session"
+ )
+ def test_stops_on_empty_full_page_boundary(self, mock_session):
+ # A full final page is followed by one more request that comes back empty.
+ mock_session.return_value.get.side_effect = [
+ _response(_page(PER_PAGE)),
+ _response([]),
+ ]
+
+ manager = _make_manager()
+ batches = list(get_rows("token", BASE_URL, WORKSPACE, "completed_jobs", mock.MagicMock(), manager, team_id=1))
+
+ assert [len(b) for b in batches] == [PER_PAGE]
+ assert mock_session.return_value.get.call_count == 2
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill.make_tracked_session"
+ )
+ def test_empty_first_page_yields_nothing(self, mock_session):
+ mock_session.return_value.get.return_value = _response([])
+
+ manager = _make_manager()
+ batches = list(get_rows("token", BASE_URL, WORKSPACE, "completed_jobs", mock.MagicMock(), manager, team_id=1))
+
+ assert batches == []
+ manager.save_state.assert_not_called()
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill.make_tracked_session"
+ )
+ def test_unpaginated_endpoint_makes_single_request(self, mock_session):
+ # listUsers ignores page params, so paging would loop forever on the same full list.
+ mock_session.return_value.get.return_value = _response([{"email": "[email protected]"}, {"email": "[email protected]"}])
+
+ manager = _make_manager()
+ batches = list(get_rows("token", BASE_URL, WORKSPACE, "users", mock.MagicMock(), manager, team_id=1))
+
+ assert mock_session.return_value.get.call_count == 1
+ assert [item["email"] for batch in batches for item in batch] == ["[email protected]", "[email protected]"]
+ manager.save_state.assert_not_called()
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill.make_tracked_session"
+ )
+ def test_saves_current_page_after_each_yield(self, mock_session):
+ mock_session.return_value.get.side_effect = [
+ _response(_page(PER_PAGE)),
+ _response(_page(PER_PAGE)),
+ _response(_page(1)),
+ ]
+
+ manager = _make_manager()
+ list(get_rows("token", BASE_URL, WORKSPACE, "completed_jobs", mock.MagicMock(), manager, team_id=1))
+
+ saved = [call.args[0].page for call in manager.save_state.call_args_list]
+ assert saved == [1, 2, 3]
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill.make_tracked_session"
+ )
+ def test_resumes_from_saved_page(self, mock_session):
+ mock_session.return_value.get.side_effect = [_response(_page(2))]
+
+ manager = _make_manager(WindmillResumeConfig(page=7))
+ list(get_rows("token", BASE_URL, WORKSPACE, "completed_jobs", mock.MagicMock(), manager, team_id=1))
+
+ first_url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert "page=7" in first_url
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill.make_tracked_session"
+ )
+ def test_incremental_resume_ignores_saved_page(self, mock_session):
+ # The watermark may have advanced since page 7 was saved, so honouring the saved page
+ # would skip earlier unsynced rows in the re-filtered result set. Restart from page 1.
+ mock_session.return_value.get.side_effect = [_response(_page(1))]
+
+ manager = _make_manager(WindmillResumeConfig(page=7))
+ list(
+ get_rows(
+ "token",
+ BASE_URL,
+ WORKSPACE,
+ "completed_jobs",
+ mock.MagicMock(),
+ manager,
+ team_id=1,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ incremental_field="started_at",
+ )
+ )
+
+ first_url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert "page=1" in first_url
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill.make_tracked_session"
+ )
+ def test_incremental_applies_after_filter(self, mock_session):
+ mock_session.return_value.get.side_effect = [_response(_page(1))]
+
+ manager = _make_manager()
+ list(
+ get_rows(
+ "token",
+ BASE_URL,
+ WORKSPACE,
+ "completed_jobs",
+ mock.MagicMock(),
+ manager,
+ team_id=1,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ incremental_field="started_at",
+ )
+ )
+
+ first_url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert "started_after=2026-01-01" in first_url
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill.make_tracked_session"
+ )
+ def test_full_refresh_endpoint_never_sends_after_filter(self, mock_session):
+ mock_session.return_value.get.side_effect = [_response(_page(1))]
+
+ manager = _make_manager()
+ list(
+ get_rows(
+ "token",
+ BASE_URL,
+ WORKSPACE,
+ "scripts",
+ mock.MagicMock(),
+ manager,
+ team_id=1,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),
+ incremental_field="created_at",
+ )
+ )
+
+ first_url = mock_session.return_value.get.call_args_list[0].args[0]
+ assert "after=" not in first_url
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill._is_host_safe")
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill.make_tracked_session"
+ )
+ def test_raises_when_host_not_allowed(self, mock_session, mock_host_safe):
+ mock_host_safe.return_value = (False, "host not allowed")
+
+ manager = _make_manager()
+ with pytest.raises(WindmillHostNotAllowedError):
+ list(
+ get_rows(
+ "token", "https://10.0.0.1", WORKSPACE, "completed_jobs", mock.MagicMock(), manager, team_id=42
+ )
+ )
+
+ mock_session.return_value.get.assert_not_called()
+
+
+class TestWindmillSourceResponse:
+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))
+ def test_response_metadata_per_endpoint(self, endpoint):
+ config = WINDMILL_ENDPOINTS[endpoint]
+ response = windmill_source("token", BASE_URL, WORKSPACE, endpoint, mock.MagicMock(), _make_manager(), team_id=1)
+
+ assert response.name == endpoint
+ assert response.primary_keys == config.primary_keys
+ assert response.sort_mode == "asc"
+ if config.partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [config.partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ @pytest.mark.parametrize("config", list(WINDMILL_ENDPOINTS.values()))
+ def test_partition_keys_are_stable_fields(self, config):
+ # Partition keys must be immutable creation timestamps, never edited/last-* fields.
+ if config.partition_key:
+ assert config.partition_key in {"created_at", "timestamp"}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/tests/test_windmill_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/tests/test_windmill_source.py
new file mode 100644
index 000000000000..5f28f50e1923
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/tests/test_windmill_source.py
@@ -0,0 +1,157 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import WindmillSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.windmill.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.windmill.source import WindmillSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.windmill.windmill import WindmillResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+BASE_URL = "https://app.windmill.dev"
+WORKSPACE = "my-workspace"
+
+
+class TestWindmillSource:
+ def setup_method(self):
+ self.source = WindmillSource()
+ self.team_id = 123
+ self.config = WindmillSourceConfig(host=BASE_URL, workspace=WORKSPACE, api_token="token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.WINDMILL
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Windmill"
+ assert config.label == "Windmill"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert not config.unreleasedSource
+ assert config.iconPath == "/static/services/windmill.svg"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["host", "workspace", "api_token"]
+
+ def test_connection_host_fields_force_token_reentry_on_host_change(self):
+ # host receives the api_token, so editing it must re-require the token (no exfiltration
+ # of the stored bearer token to an attacker-controlled host).
+ assert self.source.connection_host_fields == ["host"]
+
+ def test_api_token_field_is_secret_password(self):
+ config = self.source.get_source_config
+ token_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.secret is True
+ assert token_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://app.windmill.dev/api/w/my-workspace/scripts/list",
+ "403 Client Error: Forbidden for url: https://app.windmill.dev/api/w/my-workspace/audit/list",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ @pytest.mark.parametrize(
+ "other_error",
+ ["500 Server Error", "429 Client Error: Too Many Requests"],
+ )
+ def test_non_retryable_errors_does_not_match_transient(self, other_error):
+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())
+
+ def test_get_schemas(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ incremental = {schema.name for schema in schemas if schema.supports_incremental}
+ # Only completed_jobs exposes a genuine server-side timestamp filter.
+ assert incremental == {"completed_jobs"}
+
+ def test_completed_jobs_advertises_both_cursor_fields(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert schemas["completed_jobs"].incremental_fields == INCREMENTAL_FIELDS["completed_jobs"]
+ assert {f["field"] for f in schemas["completed_jobs"].incremental_fields} == {"created_at", "started_at"}
+ assert schemas["scripts"].incremental_fields == []
+ assert schemas["scripts"].supports_append is False
+
+ def test_audit_logs_off_by_default(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+ # Audit logs are EE-only and admin-gated, so they must not be selected by default.
+ assert schemas["audit_logs"].should_sync_default is False
+ assert schemas["completed_jobs"].should_sync_default is True
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["scripts"])
+ assert [s.name for s in schemas] == ["scripts"]
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ def test_lists_tables_without_credentials(self):
+ # Static endpoint catalog with no I/O, so the public docs can render the table list.
+ assert self.source.lists_tables_without_credentials is True
+ tables = self.source.get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "mock_return",
+ [(True, None), (False, "Invalid Windmill API token")],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.windmill.source.validate_windmill_credentials"
+ )
+ def test_validate_credentials_plumbs_arguments(self, mock_validate, mock_return):
+ mock_validate.return_value = mock_return
+
+ result = self.source.validate_credentials(self.config, self.team_id)
+
+ assert result == mock_return
+ mock_validate.assert_called_once_with("token", BASE_URL, WORKSPACE, self.team_id)
+
+ def test_get_resumable_source_manager_binds_resume_config(self):
+ manager = self.source.get_resumable_source_manager(mock.MagicMock())
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is WindmillResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.windmill.source.windmill_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_windmill_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "completed_jobs"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ inputs.incremental_field = "created_at"
+ inputs.team_id = 777
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ kwargs = mock_windmill_source.call_args.kwargs
+ assert kwargs["api_token"] == "token"
+ assert kwargs["base_url"] == BASE_URL
+ assert kwargs["workspace"] == WORKSPACE
+ assert kwargs["endpoint"] == "completed_jobs"
+ assert kwargs["team_id"] == 777
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+ assert kwargs["incremental_field"] == "created_at"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.windmill.source.windmill_source")
+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_windmill_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "scripts"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ inputs.incremental_field = None
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_windmill_source.call_args.kwargs["db_incremental_field_last_value"] is None
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
new file mode 100644
index 000000000000..b0910e9306e3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/windmill/windmill.py
@@ -0,0 +1,287 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import quote, urlencode, urlparse
+
+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.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.windmill.settings import (
+ WINDMILL_ENDPOINTS,
+ WindmillEndpointConfig,
+)
+
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+PER_PAGE = 100
+
+HOST_NOT_ALLOWED_ERROR = "Windmill instance URL is not allowed"
+
+
+class WindmillRetryableError(Exception):
+ pass
+
+
+class WindmillHostNotAllowedError(Exception):
+ pass
+
+
+class WindmillResumeConfig:
+ # 1-based index of the last-yielded page, so a resume re-fetches it and merge dedupes on the
+ # primary key.
+ page: int
+
+
+def normalize_base_url(url: str) -> str:
+ """Return the API root (``https://<host>/api``) for a user-supplied Windmill instance URL.
+
+ Forces https (matching the Okta/ServiceNow/Braze connectors that also take a user-supplied
+ host), strips any trailing slash, and tolerates the user pasting a URL that already ends in
+ ``/api`` so we never build ``/api/api``.
+
+ The authority is rebuilt from the parsed host (and port) alone, dropping any userinfo, query,
+ or fragment. This keeps the host we SSRF-check identical to the host requests actually connects
+ to — an embedded ``user@`` or trailing ``?``/``#`` can't make the checked authority diverge
+ from the effective one.
+ """
+ stripped = re.sub(r"^https?://", "", url.strip(), flags=re.IGNORECASE)
+ parsed = urlparse(f"https://{stripped}")
+ host = (parsed.hostname or "").lower()
+ try:
+ port = parsed.port
+ except ValueError:
+ port = None
+ netloc = f"{host}:{port}" if port else host
+ path = parsed.path.rstrip("/")
+ if path.lower().endswith("/api"):
+ path = path[: -len("/api")]
+ return f"https://{netloc}{path}/api"
+
+
+def _host_from_url(base_url: str) -> str:
+ return (urlparse(normalize_base_url(base_url)).hostname or "").lower()
+
+
+def _workspace_url(base_url: str, workspace: str, path: str) -> str:
+ return f"{normalize_base_url(base_url)}/w/{quote(workspace, safe='')}{path}"
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_token}",
+ "Accept": "application/json",
+ }
+
+
+def _format_after(value: Any) -> str:
+ """Format an incremental cursor value as an RFC 3339 timestamp for Windmill's *_after filters."""
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return dt.isoformat()
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()
+ return str(value)
+
+
+def _build_params(
+ config: WindmillEndpointConfig,
+ page: int,
+ incremental_field: str | None,
+ after_value: str | None,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+ if config.paginated:
+ params["page"] = page
+ params["per_page"] = PER_PAGE
+ if config.supports_order_desc:
+ # Ascending so rows inserted mid-sync append at the end instead of shifting earlier pages,
+ # and so the incremental watermark advances monotonically.
+ params["order_desc"] = "false"
+
+ after_param = config.incremental_after_params.get(incremental_field or "")
+ if after_param and after_value:
+ params[after_param] = after_value
+
+ return params
+
+
+def _normalize_items(items: Any) -> list[dict[str, Any]]:
+ """Windmill list endpoints return bare JSON arrays; keep only object rows."""
+ if not isinstance(items, list):
+ return []
+ return [item for item in items if isinstance(item, dict)]
+
+
+def validate_credentials(
+ api_token: str, base_url: str, workspace: str, team_id: int | None = None
+) -> tuple[bool, str | None]:
+ """Probe ``/w/{workspace}/users/whoami`` to confirm the token can reach the workspace."""
+ # The instance URL is fully customer-controlled, so block hosts that resolve to
+ # private/internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.
+ if team_id is not None:
+ host_ok, host_err = _is_host_safe(_host_from_url(base_url), team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ url = _workspace_url(base_url, workspace, "/users/whoami")
+ # Redact the bearer token wherever the tracked adapter records request samples — the
+ # Authorization header uses a scheme the name-based scrubbers don't cover.
+ session = make_tracked_session(allow_redirects=False, redact_values=(api_token,))
+ try:
+ response = session.get(url, headers=_get_headers(api_token), timeout=10)
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Invalid Windmill API token"
+ if response.status_code in (403, 404):
+ return False, f"Could not access Windmill workspace '{workspace}' with this token"
+
+ try:
+ message = response.json().get("message", response.text)
+ except Exception:
+ message = response.text
+ return False, message
+
+
+def get_rows(
+ api_token: str,
+ base_url: str,
+ workspace: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[WindmillResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = WINDMILL_ENDPOINTS[endpoint]
+ headers = _get_headers(api_token)
+
+ # Re-check at run time (not just at source-create) in case the URL was edited or now resolves
+ # to an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ host_ok, host_err = _is_host_safe(_host_from_url(base_url), team_id)
+ if not host_ok:
+ raise WindmillHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+ after_value: str | None = None
+ if (
+ incremental_field in config.incremental_after_params
+ and should_use_incremental_field
+ and db_incremental_field_last_value
+ ):
+ after_value = _format_after(db_incremental_field_last_value)
+
+ # Redact the bearer token wherever the tracked adapter records request samples — the
+ # Authorization header uses a scheme the name-based scrubbers don't cover. One session is
+ # reused across every page so the redaction applies to all requests.
+ session = make_tracked_session(allow_redirects=False, redact_values=(api_token,))
+
+ @retry(
+ retry=retry_if_exception_type((WindmillRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch_page(page: int) -> list[dict[str, Any]]:
+ params = _build_params(config, page, incremental_field, after_value)
+ page_url = _workspace_url(base_url, workspace, config.path)
+ if params:
+ page_url = f"{page_url}?{urlencode(params)}"
+ response = session.get(page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise WindmillRetryableError(
+ f"Windmill API error (retryable): status={response.status_code}, url={page_url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Windmill API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return _normalize_items(response.json())
+
+ # listUsers ignores pagination params and returns every row at once; a single request avoids
+ # re-fetching the same full list forever.
+ if not config.paginated:
+ items = fetch_page(1)
+ if items:
+ yield items
+ return
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ # A saved page number only indexes into a fixed result set. When an incremental watermark is
+ # active it may have advanced since the page was saved (a partial run commits rows and moves
+ # the cursor), which reshuffles the filtered pages so page N would skip earlier unsynced rows.
+ # Restart from page 1 in that case; the watermark still bounds the scan and merge dedupes.
+ if after_value is not None:
+ resume_config = None
+ page = resume_config.page if resume_config is not None else 1
+ if resume_config is not None:
+ logger.debug(f"Windmill: resuming {endpoint} from page={page}")
+
+ while True:
+ items = fetch_page(page)
+ if not items:
+ break
+
+ yield items
+
+ # Save the page we just yielded (not the next one) so a resume re-fetches it; merge
+ # semantics on the primary key dedupe.
+ resumable_source_manager.save_state(WindmillResumeConfig(page=page))
+
+ if len(items) < PER_PAGE:
+ break
+ page += 1
+
+
+def windmill_source(
+ api_token: str,
+ base_url: str,
+ workspace: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[WindmillResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = WINDMILL_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ base_url=base_url,
+ workspace=workspace,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=team_id,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=config.primary_keys,
+ # We always request ascending order where the API allows it, so incremental watermarks
+ # advance safely batch by batch.
+ sort_mode="asc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format=config.partition_format if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )