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 teamcity import source (#71222)

Tom Owersc0e52f64f784
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 3a1d3a5c9c19..220a8fc3ecc9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -450,6 +450,7 @@ the row lists both.
| svix | HTTP | requests | ✅ |
| taboola | HTTP | requests | ✅ |
| tavus | HTTP | requests | ✅ |
+| teamcity | HTTP | requests | ✅ |
| teamtailor | HTTP | requests | ✅ |
| teamwork | HTTP | requests | ✅ |
| tempo | HTTP | requests | ✅ |
@@ -929,7 +930,6 @@ doesn't conflict with concurrent PRs.
- tailscale
- tawk_to
- teachable
-- teamcity
- telli
- tempo
- terra_api
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 d3fd061a31e9..eb143a235b91 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
@@ -4184,7 +4184,8 @@ class TeachableSourceConfig(config.Config):
@config.config
class TeamcitySourceConfig(config.Config):
- pass
+ host: str
+ access_token: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/canonical_descriptions.py
new file mode 100644
index 000000000000..d5c4af3fe6c4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/canonical_descriptions.py
@@ -0,0 +1,137 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "projects": {
+ "description": "A TeamCity project: a container that groups build configurations and child projects.",
+ "docs_url": "https://www.jetbrains.com/help/teamcity/rest/project.html",
+ "columns": {
+ "id": "Unique identifier of the project (e.g. MyCompany_MyProduct).",
+ "name": "Display name of the project.",
+ "description": "Free-text description of the project.",
+ "parentProjectId": "Identifier of the parent project (_Root for top-level projects).",
+ "archived": "Whether the project has been archived.",
+ "virtual": "Whether the project is virtual (auto-generated, hidden from the UI).",
+ "webUrl": "URL of the project's page in the TeamCity UI.",
+ },
+ },
+ "build_types": {
+ "description": "A build configuration: the definition of how a build runs (steps, triggers, VCS roots) inside a project.",
+ "docs_url": "https://www.jetbrains.com/help/teamcity/rest/buildtype.html",
+ "columns": {
+ "id": "Unique identifier of the build configuration.",
+ "name": "Display name of the build configuration.",
+ "description": "Free-text description of the build configuration.",
+ "projectName": "Full display name of the project the configuration belongs to.",
+ "projectId": "Identifier of the project the configuration belongs to.",
+ "paused": "Whether the build configuration is paused (triggers disabled).",
+ "templateFlag": "Whether this entry is a template rather than a runnable configuration.",
+ "webUrl": "URL of the build configuration's page in the TeamCity UI.",
+ },
+ },
+ "agents": {
+ "description": "A build agent: a machine registered with the TeamCity server that runs builds.",
+ "docs_url": "https://www.jetbrains.com/help/teamcity/rest/agent.html",
+ "columns": {
+ "id": "Unique numeric identifier of the agent.",
+ "name": "Display name of the agent.",
+ "typeId": "Identifier of the agent type (shared by cloud agents started from one image).",
+ "connected": "Whether the agent is currently connected to the server.",
+ "enabled": "Whether the agent is enabled to run builds.",
+ "authorized": "Whether the agent is authorized on the server.",
+ "uptodate": "Whether the agent is running the latest agent software version.",
+ "ip": "IP address of the agent machine.",
+ "version": "Version of the agent software.",
+ "lastActivityTime": "Timestamp of the agent's last activity.",
+ "registrationTimestamp": "Timestamp when the agent registered with the server.",
+ "os": "Operating system reported by the agent.",
+ "pool": "Agent pool the agent belongs to (id and name).",
+ },
+ },
+ "vcs_roots": {
+ "description": "A VCS root: a version control repository connection builds check out sources from.",
+ "docs_url": "https://www.jetbrains.com/help/teamcity/rest/vcsroot.html",
+ "columns": {
+ "id": "Unique identifier of the VCS root.",
+ "name": "Display name of the VCS root.",
+ "vcsName": "VCS provider type (e.g. jetbrains.git, mercurial, svn).",
+ "modificationCheckInterval": "Custom interval in seconds between VCS polling checks, when overridden.",
+ "project": "Project the VCS root belongs to (id and name).",
+ },
+ },
+ "builds": {
+ "description": "A finished build: one execution of a build configuration, with queue/start/finish times, status, branch, and agent.",
+ "docs_url": "https://www.jetbrains.com/help/teamcity/rest/build.html",
+ "columns": {
+ "id": "Unique numeric identifier of the build.",
+ "buildTypeId": "Identifier of the build configuration the build ran under.",
+ "number": "Build number shown in the TeamCity UI.",
+ "status": "Result of the build: SUCCESS, FAILURE, or ERROR.",
+ "state": "Lifecycle state of the build; always finished for synced rows.",
+ "branchName": "Logical branch name the build ran on.",
+ "defaultBranch": "Whether the build ran on the build configuration's default branch.",
+ "personal": "Whether the build was a personal (developer-initiated, pre-commit) build.",
+ "composite": "Whether the build is a composite build that aggregates snapshot dependencies.",
+ "failedToStart": "Whether the build failed before its first step ran.",
+ "queuedDate": "Timestamp when the build entered the queue.",
+ "startDate": "Timestamp when the build started running on an agent.",
+ "finishDate": "Timestamp when the build finished.",
+ "statusText": "Human-readable summary of the build result.",
+ "webUrl": "URL of the build's page in the TeamCity UI.",
+ "agent": "Agent the build ran on (id, name, typeId).",
+ "triggered": "What triggered the build (type, date, and user when applicable).",
+ },
+ },
+ "changes": {
+ "description": "A VCS change (commit) detected by the TeamCity server across its VCS roots.",
+ "docs_url": "https://www.jetbrains.com/help/teamcity/rest/change.html",
+ "columns": {
+ "id": "Unique numeric identifier of the change on the TeamCity server.",
+ "version": "VCS-native revision of the change (e.g. the git commit hash).",
+ "username": "VCS username of the change author.",
+ "date": "Timestamp of the change in the VCS.",
+ "comment": "Commit message of the change.",
+ "webUrl": "URL of the change's page in the TeamCity UI.",
+ "user": "TeamCity user matched to the change author, when mapped.",
+ "vcsRootInstance": "VCS root instance the change was detected in.",
+ },
+ },
+ "test_occurrences": {
+ "description": "A single test run within a build. One row per test per build, so pass rates and flakiness can be computed over time.",
+ "docs_url": "https://www.jetbrains.com/help/teamcity/rest/testoccurrence.html",
+ "columns": {
+ "id": "Identifier of the test occurrence, unique across builds (embeds the build id).",
+ "name": "Full name of the test.",
+ "status": "Result of this test run: SUCCESS, FAILURE, or UNKNOWN.",
+ "duration": "Test run duration in milliseconds.",
+ "runOrder": "Order in which the test ran within the build.",
+ "muted": "Whether the failure was muted in this build.",
+ "currentlyMuted": "Whether the test is currently muted.",
+ "currentlyInvestigated": "Whether the test failure is currently under investigation.",
+ "ignored": "Whether the test was ignored in this build.",
+ "newFailure": "Whether this run is the test's first failure after passing.",
+ "test": "The test entity this occurrence belongs to (stable id and name).",
+ "build": "The build this occurrence belongs to (id and buildTypeId).",
+ "build_id": "Numeric id of the parent build (injected for joins against the builds table).",
+ "build_finish_date": "Finish timestamp of the parent build (injected; used as the incremental cursor).",
+ },
+ },
+ "problem_occurrences": {
+ "description": "A build problem within a build (compilation error, exit code failure, etc.). One row per problem per build.",
+ "docs_url": "https://www.jetbrains.com/help/teamcity/rest/problemoccurrence.html",
+ "columns": {
+ "id": "Identifier of the problem occurrence, unique across builds (embeds the build id).",
+ "type": "Type of the problem (e.g. TC_COMPILATION_ERROR, TC_EXIT_CODE).",
+ "identity": "Stable identity of the problem, used to track it across builds.",
+ "muted": "Whether the problem was muted in this build.",
+ "currentlyMuted": "Whether the problem is currently muted.",
+ "currentlyInvestigated": "Whether the problem is currently under investigation.",
+ "newFailure": "Whether this occurrence is the problem's first appearance.",
+ "problem": "The problem entity this occurrence belongs to (id, type, identity).",
+ "build": "The build this occurrence belongs to (id and buildTypeId).",
+ "build_id": "Numeric id of the parent build (injected for joins against the builds table).",
+ "build_finish_date": "Finish timestamp of the parent build (injected; used as the incremental cursor).",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/settings.py
new file mode 100644
index 000000000000..4966c81a0dd1
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/settings.py
@@ -0,0 +1,232 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# TeamCity pages with the `count` locator dimension; the server batches at ~100 by default
+# but accepts larger counts. Occurrence rows are small, so we fetch them in bigger pages.
+DEFAULT_PAGE_SIZE = 100
+OCCURRENCE_PAGE_SIZE = 1000
+
+# Hard cap on pages fetched per parent build during occurrence fan-out, to bound runaway
+# pagination. A structured warning is logged if the cap is reached.
+MAX_PAGES_PER_BUILD = 100
+
+# Hard cap on pages fetched in a single pagination walk. nextHref comes from the remote
+# server, so a misbehaving or malicious host could otherwise return a non-empty cursor
+# forever and pin an import worker until the activity timeout. At 100–1000 rows per page
+# this still allows tens of millions of rows per walk before the cap trips.
+MAX_PAGES_PER_WALK = 50_000
+
+# Hard cap on a single response body. The server URL is customer-supplied, so a hostile or
+# misbehaving host could otherwise return an unbounded body that `response.json()` buffers
+# and exhaust an import worker's memory. A page of ~1000 rich rows is a few MiB, so 128 MiB
+# leaves ample headroom for legitimate pages while bounding memory.
+MAX_RESPONSE_BYTES = 128 * 1024 * 1024
+
+# Wall-clock cap on downloading a single response body, enforced by a watchdog that closes the
+# response when it expires. `requests`' read timeout only bounds an idle socket, so a hostile host
+# can trickle one byte before each timeout to hold a blocking read open indefinitely while staying
+# under MAX_RESPONSE_BYTES. A page of a few MiB downloads in well under a second, so 300s leaves
+# ample headroom for a large legitimate page on a slow link while stopping a malicious host from
+# pinning an import worker.
+MAX_RESPONSE_DOWNLOAD_SECONDS = 300
+
+# Chunk size for the bounded body read. Small enough to re-check the byte cap frequently, large
+# enough that legitimate pages read in a few iterations.
+DOWNLOAD_CHUNK_BYTES = 1024 * 1024
+
+# Builds locator applied to the builds endpoint and to the parent walk of the occurrence
+# fan-outs. `branch:(default:any)` lifts TeamCity's default-branch-only filter so feature
+# branch builds are synced too; `state:finished` keeps rows immutable (a running build's
+# finishDate would change under us). TeamCity's default filter still excludes canceled and
+# personal builds.
+BUILDS_LOCATOR_DEFAULTS: dict[str, str] = {
+ "branch": "(default:any)",
+ "state": "finished",
+}
+
+# Synthetic columns injected onto occurrence rows from the parent build during fan-out.
+FAN_OUT_BUILD_ID_FIELD = "build_id"
+FAN_OUT_BUILD_FINISH_DATE_FIELD = "build_finish_date"
+
+
+def _finish_date_incremental_fields() -> list[IncrementalField]:
+ return [
+ {
+ "label": "finishDate",
+ "type": IncrementalFieldType.DateTime,
+ "field": "finishDate",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ]
+
+
+def _build_finish_date_incremental_fields() -> list[IncrementalField]:
+ return [
+ {
+ "label": "build finish date",
+ "type": IncrementalFieldType.DateTime,
+ "field": FAN_OUT_BUILD_FINISH_DATE_FIELD,
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ]
+
+
+@dataclass
+class TeamCityEndpointConfig:
+ name: str
+ path: str # Path under /app/rest, e.g. "/builds"
+ # Root key of the entity list in the JSON response (e.g. "build", "vcs-root").
+ response_key: str
+ # TeamCity `fields` spec requesting a richer payload than the default stubs. Unknown
+ # field names are silently ignored by the server, so this can never 400.
+ fields: str
+ # The endpoint's locator exposes a server-side filter usable as an incremental cursor
+ # (builds: finishDate condition:after; changes: sinceChange; occurrences: bounded via
+ # the parent builds walk). Everything else is full refresh.
+ supports_incremental: bool
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Extra locator dimensions always sent with list requests (e.g. defaultFilter:false).
+ locator_defaults: dict[str, str] = field(default_factory=dict)
+ # Timestamp columns in TeamCity's compact format (20260715T160948+0000), parsed to
+ # datetimes at the source so incremental watermarks and datetime partitioning work.
+ timestamp_fields: list[str] = field(default_factory=list)
+ # Stable field to partition by. None when the resource has no reliable timestamp.
+ partition_key: Optional[str] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # TeamCity list endpoints return newest-first and expose no sort control.
+ sort_mode: Literal["asc", "desc"] = "desc"
+ page_size: int = DEFAULT_PAGE_SIZE
+ # Fan-out: occurrences can only be listed scoped to a build, so they are fetched by
+ # walking the builds endpoint and querying this child once per build.
+ fan_out_over_builds: bool = False
+ should_sync_default: bool = True
+
+
+TEAMCITY_ENDPOINTS: dict[str, TeamCityEndpointConfig] = {
+ "projects": TeamCityEndpointConfig(
+ name="projects",
+ path="/projects",
+ response_key="project",
+ fields="count,nextHref,project(id,name,description,parentProjectId,archived,virtual,webUrl)",
+ # The project locator has no timestamp dimension; project lists are tiny anyway.
+ supports_incremental=False,
+ ),
+ "build_types": TeamCityEndpointConfig(
+ name="build_types",
+ path="/buildTypes",
+ response_key="buildType",
+ fields="count,nextHref,buildType(id,name,description,projectName,projectId,paused,templateFlag,webUrl)",
+ supports_incremental=False,
+ ),
+ "agents": TeamCityEndpointConfig(
+ name="agents",
+ path="/agents",
+ response_key="agent",
+ fields=(
+ "count,nextHref,agent(id,name,typeId,connected,enabled,authorized,uptodate,outdated,"
+ "ip,version,currentAgentVersion,lastActivityTime,idleSinceTime,registrationTimestamp,"
+ "os,osType,cpuRank,pool(id,name))"
+ ),
+ supports_incremental=False,
+ # The default agent locator only returns connected, authorized agents; lift it so the
+ # whole fleet (disconnected/unauthorized agents included) is visible in the warehouse.
+ locator_defaults={"defaultFilter": "false"},
+ timestamp_fields=["lastActivityTime", "idleSinceTime", "registrationTimestamp"],
+ ),
+ "vcs_roots": TeamCityEndpointConfig(
+ name="vcs_roots",
+ path="/vcs-roots",
+ response_key="vcs-root",
+ fields="count,nextHref,vcs-root(id,name,vcsName,modificationCheckInterval,project(id,name))",
+ supports_incremental=False,
+ ),
+ "builds": TeamCityEndpointConfig(
+ name="builds",
+ path="/builds",
+ response_key="build",
+ fields=(
+ "count,nextHref,build(id,buildTypeId,number,status,state,branchName,defaultBranch,"
+ "personal,composite,failedToStart,queuedDate,startDate,finishDate,statusText,webUrl,"
+ "agent(id,name,typeId),triggered(type,date,user(id,username,name)))"
+ ),
+ # `finishDate:(date:<cursor>,condition:after)` filters server-side and is preserved
+ # across nextHref pages, so incremental syncs only fetch newly finished builds.
+ supports_incremental=True,
+ incremental_fields=_finish_date_incremental_fields(),
+ locator_defaults=dict(BUILDS_LOCATOR_DEFAULTS),
+ timestamp_fields=["queuedDate", "startDate", "finishDate"],
+ # finishDate is immutable for finished builds (the only state we sync) and aligns
+ # with the incremental cursor.
+ partition_key="finishDate",
+ ),
+ "changes": TeamCityEndpointConfig(
+ name="changes",
+ path="/changes",
+ response_key="change",
+ fields=(
+ "count,nextHref,change(id,version,username,date,comment,webUrl,"
+ "user(id,username,name),vcsRootInstance(id,vcs-root-id))"
+ ),
+ # `sinceChange:(id:<cursor>)` filters server-side (verified: an id above the newest
+ # change returns 0 rows), so the change id is the incremental cursor.
+ supports_incremental=True,
+ incremental_fields=[
+ {
+ "label": "id",
+ "type": IncrementalFieldType.Integer,
+ "field": "id",
+ "field_type": IncrementalFieldType.Integer,
+ },
+ ],
+ timestamp_fields=["date"],
+ partition_key="date",
+ ),
+ "test_occurrences": TeamCityEndpointConfig(
+ name="test_occurrences",
+ path="/testOccurrences",
+ response_key="testOccurrence",
+ fields=(
+ "count,nextHref,testOccurrence(id,name,status,duration,runOrder,muted,currentlyMuted,"
+ "currentlyInvestigated,ignored,newFailure,build(id,buildTypeId),test(id,name))"
+ ),
+ # Bounded at the parent: the builds walk is windowed with the finishDate locator from
+ # the child's build_finish_date watermark, so incremental syncs only fan out over
+ # newly finished builds.
+ supports_incremental=True,
+ incremental_fields=_build_finish_date_incremental_fields(),
+ partition_key=FAN_OUT_BUILD_FINISH_DATE_FIELD,
+ # The occurrence id embeds the build id ("build:(id:123),id:2000000001"), so it is
+ # unique table-wide despite being a fan-out child.
+ primary_keys=["id"],
+ page_size=OCCURRENCE_PAGE_SIZE,
+ fan_out_over_builds=True,
+ # One request per build (more for test-heavy builds): a first sync fans out over the
+ # server's whole retained build history. Off by default so connecting a source
+ # doesn't silently start a very expensive crawl; users opt in deliberately.
+ should_sync_default=False,
+ ),
+ "problem_occurrences": TeamCityEndpointConfig(
+ name="problem_occurrences",
+ path="/problemOccurrences",
+ response_key="problemOccurrence",
+ fields=(
+ "count,nextHref,problemOccurrence(id,type,identity,muted,currentlyMuted,"
+ "currentlyInvestigated,newFailure,build(id,buildTypeId),problem(id,type,identity))"
+ ),
+ supports_incremental=True,
+ incremental_fields=_build_finish_date_incremental_fields(),
+ partition_key=FAN_OUT_BUILD_FINISH_DATE_FIELD,
+ primary_keys=["id"],
+ page_size=OCCURRENCE_PAGE_SIZE,
+ fan_out_over_builds=True,
+ should_sync_default=False,
+ ),
+}
+
+ENDPOINTS = tuple(TEAMCITY_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in TEAMCITY_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/source.py
index 27ab381449bc..21a5c5ad4ec6 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/source.py
@@ -1,19 +1,43 @@
-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 TeamcitySourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.teamcity.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ TEAMCITY_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.teamcity.teamcity import (
+ TeamCityResumeConfig,
+ teamcity_source,
+ validate_credentials as validate_teamcity_credentials,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class TeamcitySource(SimpleSource[TeamcitySourceConfig]):
+class TeamcitySource(ResumableSource[TeamcitySourceConfig, TeamCityResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.TEAMCITY
@@ -24,7 +48,106 @@ class TeamcitySource(SimpleSource[TeamcitySourceConfig]):
name=SchemaExternalDataSourceType.TEAMCITY,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="JetBrains TeamCity",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your TeamCity server URL and an access token to pull your CI/CD data into the PostHog Data warehouse.
+
+Create an access token under **Your profile → Access Tokens** in TeamCity. The token inherits your user's permissions, so it can read every project and build you can see.""",
iconPath="/static/services/teamcity.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/teamcity",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="host",
+ label="Server URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="https://teamcity.example.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="access_token",
+ label="Access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.teamcity.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls
+ # `raise_for_status()`. Retrying can never fix a credential/permission problem.
+ "401 Client Error: Unauthorized": "Your TeamCity access token is invalid or has expired. Create a new token under Your profile → Access Tokens, then reconnect.",
+ "403 Client Error: Forbidden": "Your TeamCity access token is missing the permissions needed to sync this data. Check the token owner's project view permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: TeamcitySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = TEAMCITY_ENDPOINTS[endpoint]
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=endpoint_config.supports_incremental,
+ supports_append=endpoint_config.supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ )
+
+ schemas = [_build_schema(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: TeamcitySourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ try:
+ ok, status_code = validate_teamcity_credentials(config.host, config.access_token, team_id)
+ except ValueError as e:
+ return False, str(e)
+
+ if ok:
+ return True, None
+ if status_code == 401:
+ return False, "Invalid TeamCity access token"
+ return False, "Could not connect to TeamCity with the provided server URL and access token"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[TeamCityResumeConfig]:
+ return ResumableSourceManager[TeamCityResumeConfig](inputs, TeamCityResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: TeamcitySourceConfig,
+ resumable_source_manager: ResumableSourceManager[TeamCityResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return teamcity_source(
+ host=config.host,
+ access_token=config.access_token,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ 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,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/teamcity.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/teamcity.py
new file mode 100644
index 000000000000..2b3bd7b5a49e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/teamcity.py
@@ -0,0 +1,467 @@
+import json
+import threading
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, datetime
+from typing import Any, Optional
+from urllib.parse import urlencode, urljoin, urlparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.cloud_utils import is_cloud
+
+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.teamcity.settings import (
+ DOWNLOAD_CHUNK_BYTES,
+ FAN_OUT_BUILD_FINISH_DATE_FIELD,
+ FAN_OUT_BUILD_ID_FIELD,
+ MAX_PAGES_PER_BUILD,
+ MAX_PAGES_PER_WALK,
+ MAX_RESPONSE_BYTES,
+ MAX_RESPONSE_DOWNLOAD_SECONDS,
+ TEAMCITY_ENDPOINTS,
+ TeamCityEndpointConfig,
+)
+
+TEAMCITY_API_PATH = "/app/rest"
+
+# TeamCity's compact ISO-8601 timestamp format, e.g. "20260715T160948+0000".
+TEAMCITY_DATETIME_FORMAT = "%Y%m%dT%H%M%S%z"
+
+# Slim parent payload for the occurrence fan-out: only the fields the fan-out itself needs.
+FAN_OUT_PARENT_FIELDS = "count,nextHref,build(id,finishDate)"
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class TeamCityRetryableError(Exception):
+ pass
+
+
+class TeamCityResumeConfig:
+ # Server-relative nextHref of the next page to fetch (for fan-out endpoints, the next
+ # page of the parent builds walk). None means "start from the first page".
+ next_href: str | None = None
+
+
+def normalize_host(host: str) -> str:
+ """Reduce user input to a validated TeamCity server root URL.
+
+ Accepts "https://teamcity.example.com", a bare host, or a URL with a context path
+ (TeamCity is often served under one, e.g. "https://ci.example.com/teamcity"), with or
+ without a trailing "/app/rest". Raises ``ValueError`` on anything that could retarget
+ the stored token (userinfo, query, fragment) or that isn't a plain http(s) URL.
+ """
+ cleaned = host.strip().rstrip("/")
+ if not cleaned:
+ raise ValueError("TeamCity server URL is required")
+ if "://" not in cleaned:
+ cleaned = f"https://{cleaned}"
+
+ parsed = urlparse(cleaned)
+ if parsed.scheme not in ("http", "https"):
+ raise ValueError(f"Invalid TeamCity server URL: {host!r}. Use an http(s) URL.")
+ if not parsed.hostname:
+ raise ValueError(
+ f"Invalid TeamCity server URL: {host!r}. Enter your server URL, e.g. https://teamcity.example.com."
+ )
+ if parsed.username or parsed.password or parsed.query or parsed.fragment:
+ raise ValueError(
+ f"Invalid TeamCity server URL: {host!r}. Enter just the server URL, without credentials or query parameters."
+ )
+
+ path = parsed.path.rstrip("/")
+ if path.endswith(TEAMCITY_API_PATH):
+ path = path[: -len(TEAMCITY_API_PATH)]
+
+ return f"{parsed.scheme}://{parsed.netloc}{path}"
+
+
+def _server_root(host: str) -> str:
+ """Scheme + netloc only — nextHref values are server-relative and already carry any context path."""
+ parsed = urlparse(normalize_host(host))
+ return f"{parsed.scheme}://{parsed.netloc}"
+
+
+def _resolve_next_href(server_root: str, next_href: str) -> str:
+ """Resolve a pagination cursor, pinning it to the validated server.
+
+ ``nextHref`` comes from the remote response (and, on resume, from stored state), and
+ ``urljoin`` would honor an absolute or scheme-relative value — letting a compromised or
+ attacker-controlled server retarget the next authenticated request (Bearer token attached)
+ at an internal host. Resolve against the server root, then require the result to stay on
+ the same scheme and netloc. Redirects are pinned off at the session too (defense in depth).
+ """
+ resolved = urljoin(server_root, next_href)
+ root = urlparse(server_root)
+ target = urlparse(resolved)
+ if (target.scheme, target.netloc) != (root.scheme, root.netloc):
+ raise ValueError(f"TeamCity pagination cursor points off the configured server: {next_href!r}")
+ return resolved
+
+
+def _api_base(host: str) -> str:
+ return f"{normalize_host(host)}{TEAMCITY_API_PATH}"
+
+
+def _headers(access_token: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {access_token}", "Accept": "application/json"}
+
+
+def _check_host_safe(host: str, team_id: int) -> None:
+ """Vet the server URL at both source-create and sync time.
+
+ On Cloud the Bearer token crosses the public internet, so plain http would expose it to
+ on-path capture — require https there (mirrors `custom/source.py:_check_url`). Self-hosted
+ PostHog may sit next to an internal TeamCity server over http, so http stays allowed.
+ """
+ parsed = urlparse(normalize_host(host))
+ if is_cloud() and parsed.scheme != "https":
+ raise ValueError(f"Invalid TeamCity server URL: {host!r} must use https:// on PostHog Cloud")
+ is_safe, error = _is_host_safe(parsed.hostname or "", team_id)
+ if not is_safe:
+ raise ValueError(f"Invalid TeamCity server URL: {error}")
+
+
+def _format_teamcity_datetime(value: Any) -> str:
+ """Format an incremental cursor as the compact ISO-8601 string TeamCity locators expect."""
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return aware.astimezone(UTC).strftime(TEAMCITY_DATETIME_FORMAT)
+ return str(value)
+
+
+def _parse_teamcity_datetime(value: Any) -> Any:
+ if isinstance(value, str):
+ try:
+ return datetime.strptime(value, TEAMCITY_DATETIME_FORMAT)
+ except ValueError:
+ return value
+ return value
+
+
+def _normalize_row(row: dict[str, Any], timestamp_fields: list[str]) -> dict[str, Any]:
+ for timestamp_field in timestamp_fields:
+ if timestamp_field in row:
+ row[timestamp_field] = _parse_teamcity_datetime(row[timestamp_field])
+ return row
+
+
+def _build_locator(dimensions: dict[str, str]) -> str:
+ return ",".join(f"{name}:{value}" for name, value in dimensions.items())
+
+
+def _incremental_locator_dimensions(
+ config: TeamCityEndpointConfig,
+ db_incremental_field_last_value: Any,
+) -> dict[str, str]:
+ """Server-side incremental filter dimensions for an endpoint's locator.
+
+ Verified against a live server: both filters are honored (a future-dated/too-high
+ cursor returns 0 rows) and are preserved in nextHref, so every page stays windowed.
+ """
+ if db_incremental_field_last_value is None:
+ return {}
+ if config.name == "changes":
+ return {"sinceChange": f"(id:{int(db_incremental_field_last_value)})"}
+ # builds, and the parent walk of the occurrence fan-outs
+ return {"finishDate": f"(date:{_format_teamcity_datetime(db_incremental_field_last_value)},condition:after)"}
+
+
+def _build_list_url(
+ api_base: str,
+ path: str,
+ locator_dimensions: dict[str, str],
+ fields: str,
+) -> str:
+ params = {"locator": _build_locator(locator_dimensions), "fields": fields}
+ return f"{api_base}{path}?{urlencode(params)}"
+
+
+@retry(
+ retry=retry_if_exception_type((TeamCityRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+) -> dict[str, Any]:
+ # stream=True so the body isn't buffered until we read it under a cap below — the server URL is
+ # customer-supplied, so a hostile host could otherwise return an unbounded body and OOM the worker.
+ response = session.get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, stream=True)
+
+ # Throughput is bounded by the customer's own server; back off on 429 and transient 5xx
+ # rather than failing the sync.
+ if response.status_code == 429 or response.status_code >= 500:
+ response.close()
+ raise TeamCityRetryableError(f"TeamCity API error (retryable): status={response.status_code}, url={url}")
+
+ # `requests`' timeout only bounds an idle socket, and `raw.read(n)` blocks until it has n
+ # bytes — so a hostile host can trickle one byte before each read timeout to keep a read
+ # blocked forever while staying under the byte cap, and an in-loop deadline check would never
+ # run. A watchdog closes the response when the wall-clock deadline expires, which unblocks the
+ # read; we translate that closure into a non-retryable error. Cancel it and close the response
+ # in `finally` so a completed or partial hostile stream can't leak the connection.
+ timed_out = threading.Event()
+
+ def _abort_on_deadline() -> None:
+ timed_out.set()
+ response.close()
+
+ watchdog = threading.Timer(MAX_RESPONSE_DOWNLOAD_SECONDS, _abort_on_deadline)
+ watchdog.start()
+ try:
+ if not response.ok:
+ # Read only a capped snippet for diagnostics — don't buffer a hostile error body.
+ snippet = response.raw.read(500, decode_content=True)
+ logger.error(f"TeamCity API error: status={response.status_code}, body={snippet!r}, url={url}")
+ response.raise_for_status()
+
+ chunks: list[bytes] = []
+ total = 0
+ while True:
+ try:
+ chunk = response.raw.read(DOWNLOAD_CHUNK_BYTES, decode_content=True)
+ except Exception:
+ # The watchdog closing the socket surfaces here as a read error; report the deadline.
+ if timed_out.is_set():
+ raise ValueError(
+ f"TeamCity API response exceeded the {MAX_RESPONSE_DOWNLOAD_SECONDS}s download deadline: url={url}"
+ )
+ raise
+ if not chunk:
+ break
+ total += len(chunk)
+ if total > MAX_RESPONSE_BYTES:
+ raise ValueError(
+ f"TeamCity API returned an oversized response (over {MAX_RESPONSE_BYTES} bytes): url={url}"
+ )
+ chunks.append(chunk)
+
+ # The read can also finish (e.g. at EOF) right as the deadline fires; treat that as a timeout.
+ if timed_out.is_set():
+ raise ValueError(
+ f"TeamCity API response exceeded the {MAX_RESPONSE_DOWNLOAD_SECONDS}s download deadline: url={url}"
+ )
+
+ return json.loads(b"".join(chunks))
+ finally:
+ watchdog.cancel()
+ response.close()
+
+
+def _paginate(
+ session: requests.Session,
+ server_root: str,
+ first_url: str,
+ headers: dict[str, str],
+ response_key: str,
+ logger: FilteringBoundLogger,
+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:
+ """Yield ``(items, next_href)`` per page, following TeamCity's nextHref cursor.
+
+ ``nextHref`` is supplied by the remote server, so pagination is bounded two ways to keep a
+ misbehaving or malicious host from pinning an import worker: a repeated cursor (the same
+ URL seen twice, e.g. a server that returns a fixed nextHref forever) aborts the walk, and a
+ hard ``MAX_PAGES_PER_WALK`` cap bounds cursors that keep changing but never terminate.
+ """
+ url = first_url
+ seen: set[str] = set()
+ pages = 0
+ while True:
+ data = _fetch_page(session, url, headers, logger)
+ next_href = data.get("nextHref")
+ yield data.get(response_key, []), next_href
+ if not next_href:
+ return
+ seen.add(url)
+ pages += 1
+ next_url = _resolve_next_href(server_root, next_href)
+ if next_url in seen:
+ logger.warning(f"TeamCity: pagination cursor repeated, aborting walk. url={next_url}, pages={pages}")
+ return
+ if pages >= MAX_PAGES_PER_WALK:
+ logger.warning(f"TeamCity: page cap reached, truncating walk. pages={pages}, url={next_url}")
+ return
+ url = next_url
+
+
+def _top_level_rows(
+ session: requests.Session,
+ host: str,
+ headers: dict[str, str],
+ config: TeamCityEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TeamCityResumeConfig],
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ server_root = _server_root(host)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.next_href:
+ logger.debug(f"TeamCity: resuming {config.name} from {resume.next_href}")
+ first_url = _resolve_next_href(server_root, resume.next_href)
+ else:
+ locator_dimensions = {
+ **config.locator_defaults,
+ **_incremental_locator_dimensions(config, db_incremental_field_last_value),
+ "count": str(config.page_size),
+ }
+ first_url = _build_list_url(_api_base(host), config.path, locator_dimensions, config.fields)
+
+ for items, next_href in _paginate(session, server_root, first_url, headers, config.response_key, logger):
+ if items:
+ yield [_normalize_row(item, config.timestamp_fields) for item in items]
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it —
+ # merge dedupes on the primary key.
+ if next_href:
+ resumable_source_manager.save_state(TeamCityResumeConfig(next_href=next_href))
+
+
+def _occurrence_rows_for_build(
+ session: requests.Session,
+ host: str,
+ headers: dict[str, str],
+ config: TeamCityEndpointConfig,
+ build: dict[str, Any],
+ logger: FilteringBoundLogger,
+) -> Iterator[list[dict[str, Any]]]:
+ build_id = build["id"]
+ build_finish_date = _parse_teamcity_datetime(build.get("finishDate"))
+ locator_dimensions = {"build": f"(id:{build_id})", "count": str(config.page_size)}
+ first_url = _build_list_url(_api_base(host), config.path, locator_dimensions, config.fields)
+
+ pages = 0
+ for items, next_href in _paginate(session, _server_root(host), first_url, headers, config.response_key, logger):
+ if items:
+ for item in items:
+ item[FAN_OUT_BUILD_ID_FIELD] = build_id
+ item[FAN_OUT_BUILD_FINISH_DATE_FIELD] = build_finish_date
+ yield items
+
+ pages += 1
+ if next_href and pages >= MAX_PAGES_PER_BUILD:
+ logger.warning(
+ f"TeamCity: page cap reached for {config.name}, truncating fan-out. "
+ f"build_id={build_id}, pages={pages}, page_size={config.page_size}"
+ )
+ return
+ if not next_href:
+ return
+
+
+def _fan_out_rows(
+ session: requests.Session,
+ host: str,
+ headers: dict[str, str],
+ config: TeamCityEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TeamCityResumeConfig],
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ builds_config = TEAMCITY_ENDPOINTS["builds"]
+ server_root = _server_root(host)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None and resume.next_href:
+ logger.debug(f"TeamCity: resuming {config.name} fan-out from parent page {resume.next_href}")
+ first_url = _resolve_next_href(server_root, resume.next_href)
+ else:
+ locator_dimensions = {
+ **builds_config.locator_defaults,
+ **_incremental_locator_dimensions(builds_config, db_incremental_field_last_value),
+ "count": str(builds_config.page_size),
+ }
+ first_url = _build_list_url(_api_base(host), builds_config.path, locator_dimensions, FAN_OUT_PARENT_FIELDS)
+
+ for builds, next_href in _paginate(session, server_root, first_url, headers, builds_config.response_key, logger):
+ for build in builds:
+ yield from _occurrence_rows_for_build(session, host, headers, config, build, logger)
+ # Checkpoint at parent-page granularity, after every child of the page has been
+ # yielded: a resume re-fans the interrupted page at worst, and merge dedupes.
+ if next_href:
+ resumable_source_manager.save_state(TeamCityResumeConfig(next_href=next_href))
+
+
+def get_rows(
+ host: str,
+ access_token: str,
+ endpoint: str,
+ team_id: int,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TeamCityResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = TEAMCITY_ENDPOINTS[endpoint]
+ _check_host_safe(host, team_id)
+ session = make_tracked_session(allow_redirects=False)
+ headers = _headers(access_token)
+
+ cursor = db_incremental_field_last_value if config.supports_incremental and should_use_incremental_field else None
+
+ try:
+ if config.fan_out_over_builds:
+ yield from _fan_out_rows(session, host, headers, config, logger, resumable_source_manager, cursor)
+ else:
+ yield from _top_level_rows(session, host, headers, config, logger, resumable_source_manager, cursor)
+ finally:
+ session.close()
+
+
+def teamcity_source(
+ host: str,
+ access_token: str,
+ endpoint: str,
+ team_id: int,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[TeamCityResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = TEAMCITY_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ host=host,
+ access_token=access_token,
+ endpoint=endpoint,
+ team_id=team_id,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ sort_mode=config.sort_mode,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def validate_credentials(host: str, access_token: str, team_id: int) -> tuple[bool, int | None]:
+ """Probe TeamCity's `/app/rest/server` endpoint to confirm the token is genuine.
+
+ Returns ``(ok, status_code)``. ``status_code`` is ``None`` on a transport error. Raises
+ ``ValueError`` if the host is malformed or unsafe so the caller can surface a precise
+ message.
+ """
+ _check_host_safe(host, team_id)
+ url = f"{_api_base(host)}/server"
+ session = make_tracked_session(allow_redirects=False)
+ try:
+ response = session.get(url, headers=_headers(access_token), timeout=10)
+ except Exception:
+ return False, None
+ finally:
+ session.close()
+ return response.status_code == 200, response.status_code
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/tests/test_teamcity.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/tests/test_teamcity.py
new file mode 100644
index 000000000000..f4726c0d97c9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/tests/test_teamcity.py
@@ -0,0 +1,542 @@
+import threading
+from datetime import UTC, datetime, timedelta, timezone
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.teamcity import teamcity
+from products.warehouse_sources.backend.temporal.data_imports.sources.teamcity.settings import TEAMCITY_ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.teamcity.teamcity import (
+ TeamCityResumeConfig,
+ _format_teamcity_datetime,
+ _incremental_locator_dimensions,
+ _parse_teamcity_datetime,
+ _resolve_next_href,
+ get_rows,
+ normalize_host,
+ teamcity_source,
+ validate_credentials,
+)
+
+TEAM_ID = 1
+
+
+class TestNormalizeHost:
+ @parameterized.expand(
+ [
+ ("bare_host", "teamcity.example.com", "https://teamcity.example.com"),
+ ("trailing_slash", "https://teamcity.example.com/", "https://teamcity.example.com"),
+ ("app_rest_suffix", "https://teamcity.example.com/app/rest", "https://teamcity.example.com"),
+ ("context_path", "https://ci.example.com/teamcity", "https://ci.example.com/teamcity"),
+ ("context_path_app_rest", "https://ci.example.com/teamcity/app/rest/", "https://ci.example.com/teamcity"),
+ ("explicit_http", "http://teamcity.internal:8111", "http://teamcity.internal:8111"),
+ ("whitespace", " https://teamcity.example.com ", "https://teamcity.example.com"),
+ ]
+ )
+ def test_valid_hosts(self, _name: str, value: str, expected: str) -> None:
+ assert normalize_host(value) == expected
+
+ @parameterized.expand(
+ [
+ ("empty", ""),
+ ("userinfo_injection", "https://user:[email protected]"),
+ ("query_string", "https://teamcity.example.com?redirect=evil"),
+ ("fragment", "https://teamcity.example.com#frag"),
+ ("bad_scheme", "ftp://teamcity.example.com"),
+ ]
+ )
+ def test_invalid_hosts_raise(self, _name: str, value: str) -> None:
+ with pytest.raises(ValueError):
+ normalize_host(value)
+
+
+class TestResolveNextHref:
+ SERVER_ROOT = "https://teamcity.example.com"
+
+ @parameterized.expand(
+ [
+ ("relative_path", "/app/rest/builds?locator=count:100,start:100"),
+ ("same_host_absolute", "https://teamcity.example.com/app/rest/builds?locator=count:100"),
+ ]
+ )
+ def test_on_host_cursor_is_resolved(self, _name: str, next_href: str) -> None:
+ resolved = _resolve_next_href(self.SERVER_ROOT, next_href)
+ assert urlparse(resolved).netloc == "teamcity.example.com"
+
+ @parameterized.expand(
+ [
+ ("absolute_metadata_host", "http://169.254.169.254/latest/meta-data/"),
+ ("absolute_other_host", "https://evil.example.com/app/rest/builds"),
+ ("scheme_relative", "//evil.example.com/app/rest/builds"),
+ ("scheme_downgrade", "http://teamcity.example.com/app/rest/builds"),
+ ]
+ )
+ def test_off_host_cursor_raises(self, _name: str, next_href: str) -> None:
+ with pytest.raises(ValueError):
+ _resolve_next_href(self.SERVER_ROOT, next_href)
+
+
+class TestTimestampHandling:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "20260304T025814+0000"),
+ ("naive_datetime_assumed_utc", datetime(2026, 3, 4, 2, 58, 14), "20260304T025814+0000"),
+ (
+ "offset_datetime_converted_to_utc",
+ datetime(2026, 3, 4, 5, 58, 14, tzinfo=timezone(timedelta(hours=3))),
+ "20260304T025814+0000",
+ ),
+ ("string_passthrough", "20260304T025814+0000", "20260304T025814+0000"),
+ ]
+ )
+ def test_format(self, _name: str, value: Any, expected: str) -> None:
+ assert _format_teamcity_datetime(value) == expected
+
+ @parameterized.expand(
+ [
+ ("compact_timestamp", "20260715T160948+0000", datetime(2026, 7, 15, 16, 9, 48, tzinfo=UTC)),
+ ("non_timestamp_string", "not-a-date", "not-a-date"),
+ ("none_passthrough", None, None),
+ ]
+ )
+ def test_parse(self, _name: str, value: Any, expected: Any) -> None:
+ assert _parse_teamcity_datetime(value) == expected
+
+
+class TestIncrementalLocatorDimensions:
+ def test_builds_use_finish_date_condition_after(self) -> None:
+ dims = _incremental_locator_dimensions(
+ TEAMCITY_ENDPOINTS["builds"], datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)
+ )
+ assert dims == {"finishDate": "(date:20260304T025814+0000,condition:after)"}
+
+ def test_changes_use_since_change_id(self) -> None:
+ dims = _incremental_locator_dimensions(TEAMCITY_ENDPOINTS["changes"], 42)
+ assert dims == {"sinceChange": "(id:42)"}
+
+ def test_no_cursor_means_no_filter(self) -> None:
+ assert _incremental_locator_dimensions(TEAMCITY_ENDPOINTS["builds"], None) == {}
+
+
+class _FakeResumableManager:
+ def __init__(self, state: TeamCityResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[TeamCityResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> TeamCityResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: TeamCityResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _patch_fetch(monkeypatch: Any, responses: list[dict[str, Any]]) -> list[str]:
+ """Return page payloads in call order, recording each requested URL."""
+ fetched: list[str] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict[str, Any]:
+ fetched.append(url)
+ return responses[len(fetched) - 1]
+
+ monkeypatch.setattr(teamcity, "_fetch_page", fake_fetch)
+ return fetched
+
+
+def _locator_of(url: str) -> str:
+ return parse_qs(urlparse(url).query)["locator"][0]
+
+
+def _collect(manager: _FakeResumableManager, **kwargs: Any) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ for batch in get_rows(
+ host="https://teamcity.example.com",
+ access_token="token",
+ team_id=TEAM_ID,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows
+
+
+class TestGetRowsTopLevel:
+ def test_paginates_following_next_href_and_parses_timestamps(self, monkeypatch: Any) -> None:
+ fetched = _patch_fetch(
+ monkeypatch,
+ [
+ {
+ "build": [{"id": 2, "finishDate": "20260715T160948+0000"}],
+ "nextHref": "/app/rest/builds?locator=count:100,start:100",
+ },
+ {"build": [{"id": 1, "finishDate": "20260715T150000+0000"}]},
+ ],
+ )
+ rows = _collect(_FakeResumableManager(), endpoint="builds")
+
+ assert [r["id"] for r in rows] == [2, 1]
+ assert rows[0]["finishDate"] == datetime(2026, 7, 15, 16, 9, 48, tzinfo=UTC)
+ first = urlparse(fetched[0])
+ assert first.path == "/app/rest/builds"
+ assert _locator_of(fetched[0]) == "branch:(default:any),state:finished,count:100"
+ # The second request follows nextHref verbatim against the server root.
+ assert fetched[1] == "https://teamcity.example.com/app/rest/builds?locator=count:100,start:100"
+
+ def test_saves_resume_state_only_while_more_pages_remain(self, monkeypatch: Any) -> None:
+ _patch_fetch(
+ monkeypatch,
+ [
+ {"project": [{"id": "a"}], "nextHref": "/app/rest/projects?locator=count:100,start:100"},
+ {"project": [{"id": "b"}]},
+ ],
+ )
+ manager = _FakeResumableManager()
+ _collect(manager, endpoint="projects")
+
+ assert manager.saved == [TeamCityResumeConfig(next_href="/app/rest/projects?locator=count:100,start:100")]
+
+ def test_resumes_from_saved_next_href(self, monkeypatch: Any) -> None:
+ fetched = _patch_fetch(monkeypatch, [{"project": [{"id": "b"}]}])
+ rows = _collect(
+ _FakeResumableManager(TeamCityResumeConfig(next_href="/app/rest/projects?locator=count:100,start:100")),
+ endpoint="projects",
+ )
+
+ assert [r["id"] for r in rows] == ["b"]
+ assert fetched == ["https://teamcity.example.com/app/rest/projects?locator=count:100,start:100"]
+
+ def test_tampered_resume_cursor_off_host_raises(self, monkeypatch: Any) -> None:
+ fetched = _patch_fetch(monkeypatch, [{"project": [{"id": "b"}]}])
+ with pytest.raises(ValueError):
+ _collect(
+ _FakeResumableManager(TeamCityResumeConfig(next_href="http://169.254.169.254/latest/meta-data/")),
+ endpoint="projects",
+ )
+ assert fetched == []
+
+ def test_incremental_builds_cursor_windows_the_locator(self, monkeypatch: Any) -> None:
+ fetched = _patch_fetch(monkeypatch, [{"build": []}])
+ _collect(
+ _FakeResumableManager(),
+ endpoint="builds",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ )
+ assert "finishDate:(date:20260304T025814+0000,condition:after)" in _locator_of(fetched[0])
+
+ def test_incremental_changes_cursor_uses_since_change(self, monkeypatch: Any) -> None:
+ fetched = _patch_fetch(monkeypatch, [{"change": []}])
+ _collect(
+ _FakeResumableManager(),
+ endpoint="changes",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=42,
+ )
+ assert "sinceChange:(id:42)" in _locator_of(fetched[0])
+
+ def test_full_refresh_never_leaks_cursor(self, monkeypatch: Any) -> None:
+ # projects has no server-side filter; a stale cursor must not reach the locator.
+ fetched = _patch_fetch(monkeypatch, [{"project": []}])
+ _collect(
+ _FakeResumableManager(),
+ endpoint="projects",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ )
+ assert "finishDate" not in _locator_of(fetched[0])
+ assert "sinceChange" not in _locator_of(fetched[0])
+
+
+class _FakeRaw:
+ def __init__(self, data: bytes) -> None:
+ self._data = data
+ self._pos = 0
+
+ def read(self, amt: int, decode_content: bool = False) -> bytes:
+ chunk = self._data[self._pos : self._pos + amt]
+ self._pos += len(chunk)
+ return chunk
+
+ def close(self) -> None:
+ pass
+
+
+class _BlockingRaw:
+ """A raw stream that blocks on read until the response is closed, then raises.
+
+ Mimics a hostile host that keeps a socket read blocked (staying under the byte cap and the
+ idle socket timeout) until the download watchdog closes the connection.
+ """
+
+ def __init__(self) -> None:
+ self._closed = threading.Event()
+
+ def read(self, amt: int, decode_content: bool = False) -> bytes:
+ if self._closed.wait(timeout=5):
+ raise OSError("connection closed")
+ return b""
+
+ def close(self) -> None:
+ self._closed.set()
+
+
+class _FakeResponse:
+ def __init__(self, status_code: int, data: bytes, raw: Any = None) -> None:
+ self.status_code = status_code
+ self.ok = 200 <= status_code < 400
+ self.raw = raw if raw is not None else _FakeRaw(data)
+ self.closed = False
+
+ def close(self) -> None:
+ self.closed = True
+ self.raw.close()
+
+ def raise_for_status(self) -> None:
+ if not self.ok:
+ raise AssertionError("raise_for_status called on ok response")
+
+
+class TestFetchPage:
+ def _session_returning(self, response: _FakeResponse) -> Any:
+ session = MagicMock()
+ session.get.return_value = response
+ return session
+
+ def test_parses_body_under_cap(self) -> None:
+ session = self._session_returning(_FakeResponse(200, b'{"build": [{"id": 1}]}'))
+ data = teamcity._fetch_page(session, "https://teamcity.example.com/app/rest/builds", {}, MagicMock())
+ assert data == {"build": [{"id": 1}]}
+
+ def test_oversized_body_raises_without_buffering(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(teamcity, "MAX_RESPONSE_BYTES", 10)
+ session = self._session_returning(_FakeResponse(200, b'{"x": "' + b"y" * 50 + b'"}'))
+ with pytest.raises(ValueError):
+ teamcity._fetch_page(session, "https://teamcity.example.com/app/rest/builds", {}, MagicMock())
+
+ def test_download_deadline_closes_a_blocked_read(self, monkeypatch: Any) -> None:
+ # A host that keeps a read blocked (below the byte cap and socket idle timeout) must be
+ # aborted by the watchdog closing the response, surfaced as a non-retryable deadline error.
+ monkeypatch.setattr(teamcity, "MAX_RESPONSE_DOWNLOAD_SECONDS", 0.05)
+ response = _FakeResponse(200, b"", raw=_BlockingRaw())
+ session = self._session_returning(response)
+ with pytest.raises(ValueError, match="download deadline"):
+ teamcity._fetch_page(session, "https://teamcity.example.com/app/rest/builds", {}, MagicMock())
+ assert response.closed
+
+
+class TestPaginationBounds:
+ def test_repeated_cursor_aborts_walk(self, monkeypatch: Any) -> None:
+ # A server that returns the same non-empty nextHref forever must not loop indefinitely.
+ fetched: list[str] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict[str, Any]:
+ fetched.append(url)
+ return {"project": [{"id": "a"}], "nextHref": "/app/rest/projects?locator=count:100,start:100"}
+
+ monkeypatch.setattr(teamcity, "_fetch_page", fake_fetch)
+ rows = _collect(_FakeResumableManager(), endpoint="projects")
+
+ # First page + one repeat of the fixed cursor, then repetition is detected and the walk stops.
+ assert fetched == [
+ mock.ANY,
+ "https://teamcity.example.com/app/rest/projects?locator=count:100,start:100",
+ ]
+ assert len(rows) == 2
+
+ def test_page_cap_truncates_endless_changing_cursor(self, monkeypatch: Any) -> None:
+ # Cursors that keep changing (so repetition never trips) are bounded by the hard page cap.
+ monkeypatch.setattr(teamcity, "MAX_PAGES_PER_WALK", 3)
+ fetched: list[str] = []
+
+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict[str, Any]:
+ n = len(fetched)
+ fetched.append(url)
+ return {"project": [{"id": n}], "nextHref": f"/app/rest/projects?locator=count:100,start:{(n + 1) * 100}"}
+
+ monkeypatch.setattr(teamcity, "_fetch_page", fake_fetch)
+ rows = _collect(_FakeResumableManager(), endpoint="projects")
+
+ # Stops after MAX_PAGES_PER_WALK pages instead of paginating forever.
+ assert len(fetched) == 3
+ assert [r["id"] for r in rows] == [0, 1, 2]
+
+
+class TestGetRowsFanOut:
+ def test_fans_out_per_build_and_injects_parent_fields(self, monkeypatch: Any) -> None:
+ fetched = _patch_fetch(
+ monkeypatch,
+ [
+ {
+ "build": [
+ {"id": 10, "finishDate": "20260715T160948+0000"},
+ {"id": 11, "finishDate": "20260715T170000+0000"},
+ ]
+ },
+ {"testOccurrence": [{"id": "build:(id:10),id:1", "status": "SUCCESS"}]},
+ {"testOccurrence": [{"id": "build:(id:11),id:1", "status": "FAILURE"}]},
+ ],
+ )
+ rows = _collect(_FakeResumableManager(), endpoint="test_occurrences")
+
+ parent = urlparse(fetched[0])
+ assert parent.path == "/app/rest/builds"
+ assert _locator_of(fetched[1]) == "build:(id:10),count:1000"
+ assert _locator_of(fetched[2]) == "build:(id:11),count:1000"
+ assert [r["build_id"] for r in rows] == [10, 11]
+ assert rows[0]["build_finish_date"] == datetime(2026, 7, 15, 16, 9, 48, tzinfo=UTC)
+
+ def test_incremental_cursor_windows_the_parent_builds_walk(self, monkeypatch: Any) -> None:
+ fetched = _patch_fetch(monkeypatch, [{"build": []}])
+ _collect(
+ _FakeResumableManager(),
+ endpoint="problem_occurrences",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ )
+ assert "finishDate:(date:20260304T025814+0000,condition:after)" in _locator_of(fetched[0])
+
+ def test_saves_parent_page_state_after_its_children(self, monkeypatch: Any) -> None:
+ _patch_fetch(
+ monkeypatch,
+ [
+ {
+ "build": [{"id": 10, "finishDate": "20260715T160948+0000"}],
+ "nextHref": "/app/rest/builds?locator=count:100,start:100",
+ },
+ {"testOccurrence": [{"id": "build:(id:10),id:1"}]},
+ {"build": []},
+ ],
+ )
+ manager = _FakeResumableManager()
+ _collect(manager, endpoint="test_occurrences")
+
+ assert manager.saved == [TeamCityResumeConfig(next_href="/app/rest/builds?locator=count:100,start:100")]
+
+ def test_resumes_from_saved_parent_page(self, monkeypatch: Any) -> None:
+ fetched = _patch_fetch(monkeypatch, [{"build": []}])
+ _collect(
+ _FakeResumableManager(TeamCityResumeConfig(next_href="/app/rest/builds?locator=count:100,start:100")),
+ endpoint="test_occurrences",
+ )
+ assert fetched == ["https://teamcity.example.com/app/rest/builds?locator=count:100,start:100"]
+
+ def test_page_cap_truncates_runaway_child_pagination_with_warning(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(teamcity, "MAX_PAGES_PER_BUILD", 2)
+ _patch_fetch(
+ monkeypatch,
+ [
+ {"build": [{"id": 10, "finishDate": "20260715T160948+0000"}]},
+ {
+ "testOccurrence": [{"id": "build:(id:10),id:1"}],
+ "nextHref": "/app/rest/testOccurrences?locator=build:(id:10),count:1000,start:1000",
+ },
+ {
+ "testOccurrence": [{"id": "build:(id:10),id:2"}],
+ "nextHref": "/app/rest/testOccurrences?locator=build:(id:10),count:1000,start:2000",
+ },
+ # A third child page exists but must never be fetched.
+ {"testOccurrence": [{"id": "build:(id:10),id:3"}]},
+ ],
+ )
+ logger = MagicMock()
+ rows: list[dict[str, Any]] = []
+ for batch in get_rows(
+ host="https://teamcity.example.com",
+ access_token="token",
+ endpoint="test_occurrences",
+ team_id=TEAM_ID,
+ logger=logger,
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ ):
+ rows.extend(batch)
+
+ assert [r["id"] for r in rows] == ["build:(id:10),id:1", "build:(id:10),id:2"]
+ logger.warning.assert_called_once()
+
+
+class TestTeamcitySourceResponse:
+ @parameterized.expand(
+ [
+ ("builds", ["id"], "desc", ["finishDate"]),
+ ("projects", ["id"], "desc", None),
+ ("changes", ["id"], "desc", ["date"]),
+ ("test_occurrences", ["id"], "desc", ["build_finish_date"]),
+ ]
+ )
+ def test_source_response_merge_and_partition_settings(
+ self, endpoint: str, primary_keys: list[str], sort_mode: str, partition_keys: list[str] | None
+ ) -> None:
+ response = teamcity_source(
+ host="https://teamcity.example.com",
+ access_token="token",
+ endpoint=endpoint,
+ team_id=TEAM_ID,
+ logger=MagicMock(),
+ resumable_source_manager=MagicMock(),
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == primary_keys
+ assert response.sort_mode == sort_mode
+ assert response.partition_keys == partition_keys
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("valid_token", 200, (True, 200)),
+ ("invalid_token", 401, (False, 401)),
+ ("missing_permission", 403, (False, 403)),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status_code: int, expected: tuple[bool, int]) -> None:
+ session = MagicMock()
+ session.get.return_value = MagicMock(status_code=status_code)
+ with mock.patch.object(teamcity, "make_tracked_session", return_value=session):
+ assert validate_credentials("https://teamcity.example.com", "token", TEAM_ID) == expected
+ assert session.get.call_args.args[0] == "https://teamcity.example.com/app/rest/server"
+
+ def test_transport_error_maps_to_none_status(self, monkeypatch: Any) -> None:
+ session = MagicMock()
+ session.get.side_effect = ConnectionError("boom")
+ monkeypatch.setattr(teamcity, "make_tracked_session", lambda **_: session)
+
+ assert validate_credentials("https://teamcity.example.com", "token", TEAM_ID) == (False, None)
+ session.close.assert_called_once()
+
+ def test_malformed_host_raises_before_any_request(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(teamcity, "make_tracked_session", MagicMock())
+ with pytest.raises(ValueError):
+ validate_credentials("https://user:[email protected]", "token", TEAM_ID)
+
+ def test_http_host_rejected_on_cloud_before_any_request(self, monkeypatch: Any) -> None:
+ # On Cloud the Bearer token would cross the public internet in plaintext over http.
+ monkeypatch.setattr(teamcity, "is_cloud", lambda: True)
+ monkeypatch.setattr(teamcity, "make_tracked_session", MagicMock())
+ with pytest.raises(ValueError, match="https"):
+ validate_credentials("http://teamcity.internal:8111", "token", TEAM_ID)
+
+ def test_http_host_rejected_on_cloud_at_sync_time(self, monkeypatch: Any) -> None:
+ # The same guard must hold at sync time, so an edited stored config can't leak the token.
+ monkeypatch.setattr(teamcity, "is_cloud", lambda: True)
+ monkeypatch.setattr(teamcity, "make_tracked_session", MagicMock())
+ with pytest.raises(ValueError, match="https"):
+ next(
+ iter(
+ get_rows(
+ host="http://teamcity.internal:8111",
+ access_token="token",
+ endpoint="projects",
+ team_id=TEAM_ID,
+ logger=MagicMock(),
+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
+ )
+ )
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/tests/test_teamcity_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/tests/test_teamcity_source.py
new file mode 100644
index 000000000000..f915c08f9970
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/teamcity/tests/test_teamcity_source.py
@@ -0,0 +1,170 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import TeamcitySourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.teamcity.settings import (
+ ENDPOINTS,
+ TEAMCITY_ENDPOINTS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.teamcity.source import TeamcitySource
+from products.warehouse_sources.backend.temporal.data_imports.sources.teamcity.teamcity import TeamCityResumeConfig
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+_INCREMENTAL_ENDPOINTS = {"builds", "changes", "test_occurrences", "problem_occurrences"}
+_FULL_REFRESH_ENDPOINTS = {"projects", "build_types", "agents", "vcs_roots"}
+# Occurrence fan-outs are one request per build; a first sync crawls the server's whole
+# retained history, so they must stay opt-in.
+_OPT_IN_ENDPOINTS = {"test_occurrences", "problem_occurrences"}
+
+
+class TestTeamcitySource:
+ def setup_method(self):
+ self.source = TeamcitySource()
+ self.team_id = 123
+ self.config = TeamcitySourceConfig(host="https://teamcity.example.com", access_token="token")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.TEAMCITY
+
+ def test_get_source_config_ships_released(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "Teamcity"
+ assert config.label == "JetBrains TeamCity"
+ assert config.unreleasedSource is None
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/teamcity.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/teamcity"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["host", "access_token"]
+
+ def test_access_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 == "access_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://teamcity.example.com/app/rest/builds?locator=count:100",
+ "403 Client Error: Forbidden for url: https://teamcity.example.com/app/rest/agents?locator=count:100",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ 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",
+ [
+ "429 Client Error: Too Many Requests for url: https://teamcity.example.com/app/rest/builds",
+ "500 Server Error: Internal Server Error for url: https://teamcity.example.com/app/rest/builds",
+ "HTTPSConnectionPool(host='teamcity.example.com', port=443): Read timed out.",
+ ],
+ )
+ def test_non_retryable_errors_do_not_match_transient(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_match_endpoints_with_correct_sync_modes(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+ for name in _INCREMENTAL_ENDPOINTS:
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].supports_append is True
+ assert len(schemas[name].incremental_fields) == 1
+ for name in _FULL_REFRESH_ENDPOINTS:
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].incremental_fields == []
+ for name in ENDPOINTS:
+ assert schemas[name].should_sync_default is (name not in _OPT_IN_ENDPOINTS)
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["builds", "nope"])
+ assert [s.name for s in schemas] == ["builds"]
+
+ def test_lists_tables_without_credentials_publishes_catalog(self):
+ # Static endpoint catalog (no I/O) — the public docs table list should render.
+ assert self.source.lists_tables_without_credentials is True
+ documented = self.source.get_documented_tables()
+ assert {table["name"] for table in documented} == set(ENDPOINTS)
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ canonical = self.source.get_canonical_descriptions()
+ assert set(canonical) == set(TEAMCITY_ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ ((True, 200), True, None),
+ ((False, 401), False, "Invalid TeamCity access token"),
+ ((False, 403), False, "Could not connect to TeamCity with the provided server URL and access token"),
+ ((False, None), False, "Could not connect to TeamCity with the provided server URL and access token"),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.teamcity.source.validate_teamcity_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ 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("https://teamcity.example.com", "token", self.team_id)
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.teamcity.source.validate_teamcity_credentials"
+ )
+ def test_validate_credentials_surfaces_bad_host(self, mock_validate):
+ mock_validate.side_effect = ValueError("Invalid TeamCity server URL: 'ftp://x'.")
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert "Invalid TeamCity server URL" in (error_message or "")
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert manager._data_class is TeamCityResumeConfig
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.teamcity.source.teamcity_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_teamcity_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "builds"
+ inputs.team_id = self.team_id
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_teamcity_source.assert_called_once()
+ kwargs = mock_teamcity_source.call_args.kwargs
+ assert kwargs["host"] == "https://teamcity.example.com"
+ assert kwargs["access_token"] == "token"
+ assert kwargs["endpoint"] == "builds"
+ assert kwargs["team_id"] == self.team_id
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.teamcity.source.teamcity_source")
+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_teamcity_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "projects"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_teamcity_source.call_args.kwargs["db_incremental_field_last_value"] is None