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 confluence import source (#61651)

Tom Owers1f81750cdbe6
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 365dd72bb33a..74ff21c229ff 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -56,6 +56,7 @@ the row lists both.
| calendly | HTTP | requests | ✅ |
| campaign_monitor | HTTP | requests | ✅ |
| chargebee | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| confluence | HTTP | requests | ✅ |
| chartmogul | HTTP | requests | ✅ |
| clerk | HTTP | requests + `rest_source.RESTClient` | ✅ |
| clickhouse | DB protocol (HTTP-based) | clickhouse-connect / clickhouse-driver | ➖ |
@@ -175,7 +176,6 @@ doesn't conflict with concurrent PRs.
- braintree
- circleci
- cockroachdb
-- confluence
- copper
- dynamodb
- elasticsearch
diff --git a/posthog/temporal/data_imports/sources/confluence/confluence.py b/posthog/temporal/data_imports/sources/confluence/confluence.py
new file mode 100644
index 000000000000..0ff74f8edc4d
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/confluence/confluence.py
@@ -0,0 +1,186 @@
+import re
+import base64
+import dataclasses
+from collections.abc import Iterator
+from typing import Any
+from urllib.parse import urlencode
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.confluence.settings import CONFLUENCE_ENDPOINTS
+
+# Confluence Cloud sites always live under <subdomain>.atlassian.net. Building
+# the host ourselves from a validated subdomain (rather than accepting an
+# arbitrary host) keeps the API token from being sent anywhere off-Atlassian.
+_SUBDOMAIN_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9-]{0,62}$")
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class ConfluenceRetryableError(Exception):
+ pass
+
+
+class ConfluenceResumeConfig:
+ next_url: str
+
+
+def _site_origin(subdomain: str) -> str:
+ return f"https://{subdomain}.atlassian.net"
+
+
+def _base_url(subdomain: str) -> str:
+ return f"{_site_origin(subdomain)}/wiki/api/v2"
+
+
+def is_valid_subdomain(subdomain: str) -> bool:
+ return bool(subdomain) and _SUBDOMAIN_RE.match(subdomain) is not None
+
+
+def _get_headers(email: str, api_token: str) -> dict[str, str]:
+ token = base64.b64encode(f"{email}:{api_token}".encode()).decode()
+ return {
+ "Authorization": f"Basic {token}",
+ "Accept": "application/json",
+ }
+
+
+def _build_initial_url(subdomain: str, path: str, limit: int) -> str:
+ return f"{_base_url(subdomain)}{path}?{urlencode({'limit': limit})}"
+
+
+def _resolve_next_url(subdomain: str, data: dict[str, Any]) -> str | None:
+ """Confluence v2 returns the next page as a site-relative path in
+ ``_links.next`` (e.g. ``/wiki/api/v2/pages?cursor=...``). Absence of the key
+ signals the last page."""
+ links = data.get("_links") or {}
+ next_path = links.get("next")
+ if not next_path:
+ return None
+ if next_path.startswith("http://") or next_path.startswith("https://"):
+ return next_path
+ return f"{_site_origin(subdomain)}{next_path}"
+
+
+def validate_credentials(
+ subdomain: str, email: str, api_token: str, schema_name: str | None = None
+) -> tuple[bool, str | None]:
+ """Probe the Confluence API to confirm the credentials are genuine.
+
+ A 403 at source-create (``schema_name is None``) is accepted: the token may
+ be valid but lack access to the probed resource. Once a specific schema is
+ being validated we surface the 403.
+ """
+ if not is_valid_subdomain(subdomain):
+ return (
+ False,
+ "Invalid Confluence subdomain. Use just the site name, e.g. 'your-domain' for your-domain.atlassian.net.",
+ )
+
+ url = _build_initial_url(subdomain, CONFLUENCE_ENDPOINTS["spaces"].path, limit=1)
+ try:
+ response = make_tracked_session().get(url, headers=_get_headers(email, 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 Confluence credentials. Check your email and API token."
+ if response.status_code == 403:
+ if schema_name is None:
+ return True, None
+ return False, "Your Confluence account does not have permission to access this resource."
+
+ return False, f"Confluence API returned status {response.status_code}: {response.text}"
+
+
+def get_rows(
+ subdomain: str,
+ email: str,
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ConfluenceResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ config = CONFLUENCE_ENDPOINTS[endpoint]
+ headers = _get_headers(email, api_token)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ url: str = resume_config.next_url
+ logger.debug(f"Confluence: resuming from URL: {url}")
+ else:
+ url = _build_initial_url(subdomain, config.path, config.limit)
+
+ @retry(
+ retry=retry_if_exception_type((ConfluenceRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> dict[str, Any]:
+ response = make_tracked_session().get(page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise ConfluenceRetryableError(
+ f"Confluence API error (retryable): status={response.status_code}, url={page_url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Confluence API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ data = fetch_page(url)
+
+ results = data.get("results", [])
+ next_url = _resolve_next_url(subdomain, data)
+
+ if results:
+ yield results
+
+ # Save state AFTER yielding so a crash re-fetches the page we just
+ # emitted (merge dedupes on primary key) rather than skipping it.
+ if not next_url:
+ break
+
+ resumable_source_manager.save_state(ConfluenceResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def confluence_source(
+ subdomain: str,
+ email: str,
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[ConfluenceResumeConfig],
+) -> SourceResponse:
+ endpoint_config = CONFLUENCE_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ subdomain=subdomain,
+ email=email,
+ api_token=api_token,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ ),
+ primary_keys=[endpoint_config.primary_key],
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="week" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
diff --git a/posthog/temporal/data_imports/sources/confluence/settings.py b/posthog/temporal/data_imports/sources/confluence/settings.py
new file mode 100644
index 000000000000..8ccb21867f08
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/confluence/settings.py
@@ -0,0 +1,75 @@
+from dataclasses import dataclass
+from typing import Optional
+
+from products.data_warehouse.backend.types import IncrementalField
+
+
+@dataclass
+class ConfluenceEndpointConfig:
+ name: str
+ path: str # Path relative to the v2 API base, e.g. "/pages"
+ primary_key: str = "id"
+ # Stable, immutable datetime field used for partitioning. Confluence's v2
+ # objects expose `createdAt` at the top level (never use a mutable field
+ # like the nested version timestamp). `None` for resources that don't carry
+ # a top-level creation timestamp (labels, comments).
+ partition_key: Optional[str] = None
+ limit: int = 250 # v2 list endpoints accept up to 250 results per page
+
+
+# Confluence Cloud REST API v2 top-level list endpoints. All use cursor-based
+# pagination (`_links.next`) and require no parent context to enumerate.
+#
+# We intentionally ship every endpoint as full-refresh: the v2 list endpoints
+# expose a `sort` parameter but NO server-side timestamp filter (there is no
+# `since` / `modified_after` / `created-date>=` query param), so an "incremental"
+# sync would still page through the entire collection every run. Per the
+# implementing-warehouse-sources guidance we only advertise incremental when a
+# genuine server-side filter exists, so all endpoints here are full refresh.
+CONFLUENCE_ENDPOINTS: dict[str, ConfluenceEndpointConfig] = {
+ "spaces": ConfluenceEndpointConfig(
+ name="spaces",
+ path="/spaces",
+ partition_key="createdAt",
+ ),
+ "pages": ConfluenceEndpointConfig(
+ name="pages",
+ path="/pages",
+ partition_key="createdAt",
+ ),
+ "blogposts": ConfluenceEndpointConfig(
+ name="blogposts",
+ path="/blogposts",
+ partition_key="createdAt",
+ ),
+ "attachments": ConfluenceEndpointConfig(
+ name="attachments",
+ path="/attachments",
+ partition_key="createdAt",
+ ),
+ "tasks": ConfluenceEndpointConfig(
+ name="tasks",
+ path="/tasks",
+ partition_key="createdAt",
+ ),
+ # Labels and comments don't carry a top-level creation timestamp, so they
+ # have no stable partition key.
+ "labels": ConfluenceEndpointConfig(
+ name="labels",
+ path="/labels",
+ ),
+ "footer_comments": ConfluenceEndpointConfig(
+ name="footer_comments",
+ path="/footer-comments",
+ ),
+ "inline_comments": ConfluenceEndpointConfig(
+ name="inline_comments",
+ path="/inline-comments",
+ ),
+}
+
+ENDPOINTS = tuple(CONFLUENCE_ENDPOINTS.keys())
+
+# No endpoint supports server-side incremental filtering (see note above), so no
+# endpoint advertises incremental fields.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in CONFLUENCE_ENDPOINTS}
diff --git a/posthog/temporal/data_imports/sources/confluence/source.py b/posthog/temporal/data_imports/sources/confluence/source.py
index ff63b8da570e..81e82e36d6b8 100644
--- a/posthog/temporal/data_imports/sources/confluence/source.py
+++ b/posthog/temporal/data_imports/sources/confluence/source.py
@@ -1,29 +1,139 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
+from posthog.temporal.data_imports.sources.confluence.confluence import (
+ ConfluenceResumeConfig,
+ confluence_source,
+ validate_credentials as validate_confluence_credentials,
+)
+from posthog.temporal.data_imports.sources.confluence.settings import ENDPOINTS, INCREMENTAL_FIELDS
from posthog.temporal.data_imports.sources.generated_configs import ConfluenceSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class ConfluenceSource(SimpleSource[ConfluenceSourceConfig]):
+class ConfluenceSource(ResumableSource[ConfluenceSourceConfig, ConfluenceResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.CONFLUENCE
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The API token is sent to <subdomain>.atlassian.net, so retargeting the
+ # subdomain must force re-entry of the token.
+ return ["subdomain"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.CONFLUENCE,
label="Confluence",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Atlassian Confluence Cloud credentials to pull your Confluence content into the PostHog Data warehouse.
+
+Create an API token from your [Atlassian account settings](https://id.atlassian.com/manage-profile/security/api-tokens), then connect using the email address tied to that account.
+
+Only Confluence Cloud sites (`your-domain.atlassian.net`) are supported.""",
iconPath="/static/services/confluence.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/confluence",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="subdomain",
+ label="Subdomain",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="your-domain",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="email",
+ label="Email",
+ type=SourceFieldInputConfigType.EMAIL,
+ required=True,
+ placeholder="[email protected]",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_schemas(
+ self,
+ config: ConfluenceSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ # v2 list endpoints have no server-side timestamp filter, so all
+ # endpoints are full refresh only.
+ supports_incremental=False,
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ 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: ConfluenceSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_confluence_credentials(
+ subdomain=config.subdomain,
+ email=config.email,
+ api_token=config.api_token,
+ schema_name=schema_name,
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error: Unauthorized": "Your Confluence credentials are invalid or expired. Check your email and API token and reconnect.",
+ "403 Client Error: Forbidden": "Your Confluence account does not have permission to access this resource.",
+ }
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[ConfluenceResumeConfig]:
+ return ResumableSourceManager[ConfluenceResumeConfig](inputs, ConfluenceResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: ConfluenceSourceConfig,
+ resumable_source_manager: ResumableSourceManager[ConfluenceResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return confluence_source(
+ subdomain=config.subdomain,
+ email=config.email,
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
)
diff --git a/posthog/temporal/data_imports/sources/confluence/tests/test_confluence.py b/posthog/temporal/data_imports/sources/confluence/tests/test_confluence.py
new file mode 100644
index 000000000000..f93d4f37a310
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/confluence/tests/test_confluence.py
@@ -0,0 +1,220 @@
+import base64
+from typing import Any
+
+from unittest import mock
+
+from parameterized import parameterized
+
+from posthog.temporal.data_imports.sources.confluence.confluence import (
+ ConfluenceResumeConfig,
+ _get_headers,
+ _resolve_next_url,
+ confluence_source,
+ get_rows,
+ is_valid_subdomain,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.confluence.settings import CONFLUENCE_ENDPOINTS, ENDPOINTS
+
+
+def _mock_response(status_code: int, json_body: Any = None, text: str = "") -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 300
+ response.json.return_value = json_body if json_body is not None else {}
+ response.text = text
+
+ def raise_for_status() -> None:
+ if not response.ok:
+ raise Exception(f"{status_code} Client Error")
+
+ response.raise_for_status.side_effect = raise_for_status
+ return response
+
+
+class TestSubdomainValidation:
+ @parameterized.expand(
+ [
+ ("simple", "mycompany", True),
+ ("with_hyphen", "my-company", True),
+ ("alphanumeric", "team123", True),
+ ("empty", "", False),
+ ("with_dot", "evil.com", False),
+ ("with_slash", "evil/path", False),
+ ("with_protocol", "https://evil", False),
+ ("leading_hyphen", "-bad", False),
+ ]
+ )
+ def test_is_valid_subdomain(self, _name: str, subdomain: str, expected: bool) -> None:
+ assert is_valid_subdomain(subdomain) is expected
+
+
+class TestHeaders:
+ def test_basic_auth_header(self) -> None:
+ headers = _get_headers("[email protected]", "token123")
+ expected = base64.b64encode(b"[email protected]:token123").decode()
+ assert headers["Authorization"] == f"Basic {expected}"
+ assert headers["Accept"] == "application/json"
+
+
+class TestResolveNextUrl:
+ @parameterized.expand(
+ [
+ (
+ "relative_path",
+ {"_links": {"next": "/wiki/api/v2/pages?cursor=abc"}},
+ "https://acme.atlassian.net/wiki/api/v2/pages?cursor=abc",
+ ),
+ (
+ "absolute_url",
+ {"_links": {"next": "https://acme.atlassian.net/wiki/api/v2/pages?cursor=xyz"}},
+ "https://acme.atlassian.net/wiki/api/v2/pages?cursor=xyz",
+ ),
+ ("no_next_key", {"_links": {}}, None),
+ ("no_links_key", {"results": []}, None),
+ ("null_next", {"_links": {"next": None}}, None),
+ ]
+ )
+ def test_resolve_next_url(self, _name: str, data: dict, expected: str | None) -> None:
+ assert _resolve_next_url("acme", data) == expected
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, None, True, None),
+ ("bad_token", 401, None, False, "Invalid Confluence credentials. Check your email and API token."),
+ ("forbidden_source_create", 403, None, True, None),
+ (
+ "forbidden_specific_schema",
+ 403,
+ "pages",
+ False,
+ "Your Confluence account does not have permission to access this resource.",
+ ),
+ ]
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.confluence.confluence.make_tracked_session")
+ def test_validate_credentials_status_mapping(
+ self,
+ _name: str,
+ status_code: int,
+ schema_name: str | None,
+ expected_valid: bool,
+ expected_message: str | None,
+ mock_session: mock.MagicMock,
+ ) -> None:
+ mock_session.return_value.get.return_value = _mock_response(status_code)
+
+ is_valid, message = validate_credentials("acme", "[email protected]", "token", schema_name=schema_name)
+
+ assert is_valid is expected_valid
+ assert message == expected_message
+
+ def test_invalid_subdomain_short_circuits(self) -> None:
+ is_valid, message = validate_credentials("evil.com", "[email protected]", "token")
+ assert is_valid is False
+ assert message is not None and "subdomain" in message
+
+
+class TestConfluenceSource:
+ @parameterized.expand([(endpoint,) for endpoint in ENDPOINTS])
+ def test_source_response_shape_for_endpoint(self, endpoint: str) -> None:
+ response = confluence_source(
+ subdomain="acme",
+ api_token="token",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=mock.MagicMock(),
+ )
+ config = CONFLUENCE_ENDPOINTS[endpoint]
+ assert response.name == endpoint
+ assert response.primary_keys == [config.primary_key]
+ 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
+
+ @parameterized.expand([("spaces", "createdAt"), ("pages", "createdAt"), ("labels", None)])
+ def test_partition_key_matches_endpoint(self, endpoint: str, expected_partition: str | None) -> None:
+ assert CONFLUENCE_ENDPOINTS[endpoint].partition_key == expected_partition
+
+
+class TestGetRows:
+ @mock.patch("posthog.temporal.data_imports.sources.confluence.confluence.make_tracked_session")
+ def test_paginates_until_no_next_and_saves_state(self, mock_session: mock.MagicMock) -> None:
+ page1 = _mock_response(
+ 200,
+ {"results": [{"id": "1"}, {"id": "2"}], "_links": {"next": "/wiki/api/v2/pages?cursor=p2"}},
+ )
+ page2 = _mock_response(200, {"results": [{"id": "3"}], "_links": {}})
+ mock_session.return_value.get.side_effect = [page1, page2]
+
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+
+ batches = list(
+ get_rows(
+ subdomain="acme",
+ api_token="token",
+ endpoint="pages",
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ )
+ )
+
+ assert batches == [[{"id": "1"}, {"id": "2"}], [{"id": "3"}]]
+ # State saved once, after the first page (which has a next cursor).
+ manager.save_state.assert_called_once()
+ saved = manager.save_state.call_args.args[0]
+ assert isinstance(saved, ConfluenceResumeConfig)
+ assert saved.next_url == "https://acme.atlassian.net/wiki/api/v2/pages?cursor=p2"
+
+ @mock.patch("posthog.temporal.data_imports.sources.confluence.confluence.make_tracked_session")
+ def test_resumes_from_saved_state(self, mock_session: mock.MagicMock) -> None:
+ page = _mock_response(200, {"results": [{"id": "9"}], "_links": {}})
+ mock_session.return_value.get.return_value = page
+
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = ConfluenceResumeConfig(
+ next_url="https://acme.atlassian.net/wiki/api/v2/pages?cursor=resumed"
+ )
+
+ list(
+ get_rows(
+ subdomain="acme",
+ api_token="token",
+ endpoint="pages",
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ )
+ )
+
+ called_url = mock_session.return_value.get.call_args.args[0]
+ assert called_url == "https://acme.atlassian.net/wiki/api/v2/pages?cursor=resumed"
+
+ @mock.patch("posthog.temporal.data_imports.sources.confluence.confluence.make_tracked_session")
+ def test_empty_results_does_not_yield(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.return_value = _mock_response(200, {"results": [], "_links": {}})
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+
+ batches = list(
+ get_rows(
+ subdomain="acme",
+ api_token="token",
+ endpoint="spaces",
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ )
+ )
+
+ assert batches == []
+ manager.save_state.assert_not_called()
diff --git a/posthog/temporal/data_imports/sources/confluence/tests/test_confluence_source.py b/posthog/temporal/data_imports/sources/confluence/tests/test_confluence_source.py
new file mode 100644
index 000000000000..07e00dde5bc5
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/confluence/tests/test_confluence_source.py
@@ -0,0 +1,136 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.confluence.confluence import ConfluenceResumeConfig
+from posthog.temporal.data_imports.sources.confluence.settings import ENDPOINTS, INCREMENTAL_FIELDS
+from posthog.temporal.data_imports.sources.confluence.source import ConfluenceSource
+from posthog.temporal.data_imports.sources.generated_configs import ConfluenceSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestConfluenceSource:
+ def setup_method(self) -> None:
+ self.source = ConfluenceSource()
+ self.team_id = 123
+ self.config = ConfluenceSourceConfig(subdomain="acme", email="[email protected]", api_token="token")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.CONFLUENCE
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Confluence"
+ assert config.label == "Confluence"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/confluence.png"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["subdomain", "email", "api_token"]
+
+ def test_api_token_field_is_secret_password(self) -> None:
+ 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
+
+ def test_connection_host_fields_includes_subdomain(self) -> None:
+ # Changing the subdomain retargets where the API token is sent.
+ assert self.source.connection_host_fields == ["subdomain"]
+
+ def test_get_schemas_covers_all_endpoints_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+
+ assert {schema.name for schema in schemas} == set(ENDPOINTS)
+ # No endpoint supports server-side incremental filtering.
+ assert all(schema.supports_incremental is False for schema in schemas)
+ assert all(schema.supports_append is False for schema in schemas)
+ assert all(schema.incremental_fields == INCREMENTAL_FIELDS[schema.name] for schema in schemas)
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["pages"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "pages"
+
+ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://acme.atlassian.net/wiki/api/v2/spaces",
+ "403 Client Error: Forbidden for url: https://acme.atlassian.net/wiki/api/v2/pages",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "500 Server Error for url: https://acme.atlassian.net/wiki/api/v2/spaces",
+ "429 Client Error: Too Many Requests",
+ ],
+ )
+ def test_non_retryable_errors_does_not_match_transient(self, other_error: str) -> None:
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ ((True, None), True, None),
+ (
+ (False, "Invalid Confluence credentials. Check your email and API token."),
+ False,
+ "Invalid Confluence credentials. Check your email and API token.",
+ ),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.confluence.source.validate_confluence_credentials")
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ mock_return: tuple[bool, str | None],
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(
+ subdomain="acme", email="[email protected]", api_token="token", schema_name=None
+ )
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is ConfluenceResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.confluence.source.confluence_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_confluence_source: mock.MagicMock) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "pages"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_confluence_source.assert_called_once()
+ kwargs = mock_confluence_source.call_args.kwargs
+ assert kwargs["subdomain"] == "acme"
+ assert kwargs["email"] == "[email protected]"
+ assert kwargs["api_token"] == "token"
+ assert kwargs["endpoint"] == "pages"
+ assert kwargs["resumable_source_manager"] is manager
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index bf492a294eca..0958f7f13bab 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -283,7 +283,9 @@ class CockroachDBSourceConfig(config.Config):
@config.config
class ConfluenceSourceConfig(config.Config):
- pass
+ subdomain: str
+ email: str
+ api_token: str
@config.config