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 the semaphore (semaphore ci) import source (#111862)

Tom Owers91e3e4d263ab
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 ea78eb63aca7..ee9cf3ae474d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -680,6 +680,7 @@ the row lists both.
| segment | HTTP | requests | ✅ |
| select_star | HTTP | requests + `rest_source.RESTClient` | ✅ |
| semantic_scholar | HTTP | requests + `rest_source.RESTClient` | ✅ |
+| semaphore | HTTP | requests | ✅ |
| semgrep | HTTP | requests | ✅ |
| semrush | HTTP | requests | ✅ |
| sendgrid | HTTP | requests | ✅ |
@@ -1381,7 +1382,7 @@ doesn't conflict with concurrent PRs.
- search_ads_360
- sec_edgar
- secureframe
-- semaphore
+- semrush
- sendpulse
- senseforce
- service_fusion
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/semaphore.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/semaphore.py
index 7b90be6d5764..e4e164bbc18d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/semaphore.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/semaphore.py
@@ -6,4 +6,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class SemaphoreSourceConfig(config.Config):
- pass
+ api_token: str
+ organization: str
+ project_id: str
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semaphore/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semaphore/canonical_descriptions.py
new file mode 100644
index 000000000000..ec4105ceb27f
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semaphore/canonical_descriptions.py
@@ -0,0 +1,39 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "workflows": {
+ "description": "Workflow runs for the selected Semaphore project.",
+ "docs_url": "https://docs.semaphore.io/reference/api#list-workflows",
+ "columns": {
+ "wf_id": "Unique workflow identifier.",
+ "project_id": "Project that owns the workflow.",
+ "created_at": "Workflow creation time in UTC.",
+ "initial_ppl_id": "Identifier of the first pipeline.",
+ "commit_sha": "Git commit for the workflow.",
+ "branch_name": "Git branch for the workflow.",
+ },
+ },
+ "pipelines": {
+ "description": "Pipelines and their execution states for the selected project.",
+ "docs_url": "https://docs.semaphore.io/reference/api#list-pipelines",
+ "columns": {
+ "ppl_id": "Unique pipeline identifier.",
+ "wf_id": "Workflow that contains the pipeline.",
+ "state": "Pipeline execution state.",
+ "result": "Pipeline result after execution ends.",
+ "created_at": "Pipeline creation time in UTC.",
+ },
+ },
+ "deployment_targets": {
+ "description": "Deployment targets configured for the selected project.",
+ "docs_url": "https://docs.semaphore.io/reference/api#list-targets",
+ "columns": {
+ "id": "Unique deployment target identifier.",
+ "project_id": "Project that owns the target.",
+ "name": "Deployment target name.",
+ "created_at": "Target creation time in UTC.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semaphore/semaphore.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semaphore/semaphore.py
new file mode 100644
index 000000000000..6ec228a98ae9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semaphore/semaphore.py
@@ -0,0 +1,155 @@
+import re
+from datetime import UTC, datetime, timedelta
+from typing import Any, cast
+from uuid import UUID
+
+from requests.exceptions import HTTPError
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import APIKeyAuth
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ Endpoint,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import schema_for_resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.semaphore import (
+ SemaphoreSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semaphore.settings import (
+ AUTH_ERROR,
+ ENDPOINTS,
+ NOT_FOUND_ERROR,
+ PERMISSION_ERROR,
+)
+
+
+@frozen
+class SemaphoreResumeConfig:
+ next_url: str | None = None
+ completed: bool = False
+
+
+def client_config(config: SemaphoreSourceConfig, api_version: str) -> ClientConfig:
+ if not re.fullmatch(r"[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?", config.organization):
+ raise ValueError("Enter the Semaphore organization subdomain, such as 'example', without a URL.")
+ try:
+ UUID(config.project_id)
+ except ValueError:
+ raise ValueError("Enter a valid Semaphore project ID (UUID).") from None
+ return {
+ "base_url": f"https://{config.organization}.semaphoreci.com/api/{api_version}/",
+ "auth": APIKeyAuth(api_key=f"Token {config.api_token}", name="Authorization", location="header"),
+ "headers": {"User-Agent": "SemaphoreCI v2.0 Client"},
+ "paginator": "header_link",
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ "request_timeout": (10, 60),
+ }
+
+
+def validate_credentials(config: SemaphoreSourceConfig, api_version: str) -> tuple[bool, str | None]:
+ settings = client_config(config, api_version)
+ client = RESTClient(
+ base_url=settings["base_url"],
+ auth=APIKeyAuth(api_key=f"Token {config.api_token}"),
+ headers=settings["headers"],
+ allowed_hosts=[],
+ allow_redirects=False,
+ request_timeout=(10, 30),
+ )
+ try:
+ next(
+ client.paginate(
+ "plumber-workflows",
+ params={"project_id": config.project_id},
+ paginator=SinglePagePaginator(),
+ data_selector_required=True,
+ )
+ )
+ except HTTPError as error:
+ status = error.response.status_code if error.response is not None else None
+ if status in (401, 403, 404):
+ return False, {401: AUTH_ERROR, 403: PERMISSION_ERROR, 404: NOT_FOUND_ERROR}[status]
+ raise
+ return True, None
+
+
+def normalize_created_at(row: dict[str, Any]) -> dict[str, Any]:
+ value = row.get("created_at")
+ if isinstance(value, dict):
+ row["created_at"] = datetime.fromtimestamp(int(value["seconds"]), UTC) + timedelta(
+ microseconds=int(value.get("nanos", 0)) // 1000
+ )
+ elif value is not None:
+ parsed = parse_datetime_value(value)
+ if parsed is None:
+ raise ValueError("Semaphore returned an invalid creation time.")
+ row["created_at"] = parsed
+ return row
+
+
+def semaphore_source(
+ config: SemaphoreSourceConfig,
+ inputs: SourceInputs,
+ manager: ResumableSourceManager[SemaphoreResumeConfig],
+ api_version: str,
+) -> SourceResponse:
+ endpoint = schema_for_resource(ENDPOINTS, inputs.schema_name)
+ client = client_config(config, api_version)
+ resume = manager.load_state() if manager.can_resume() else None
+ if resume is not None and resume.completed:
+ return SourceResponse(
+ name=inputs.schema_name, items=list, primary_keys=[endpoint.primary_key], sort_mode="desc"
+ )
+
+ params: dict[str, Any] = {"project_id": config.project_id}
+ incremental = inputs.schema_name == "workflows" and inputs.should_use_incremental_field
+ if incremental and inputs.db_incremental_field_last_value is not None:
+ watermark = parse_datetime_value(inputs.db_incremental_field_last_value)
+ if watermark is None:
+ raise ValueError("The Semaphore workflow sync position is invalid. Reset this table and try again.")
+ # The API uses exclusive whole seconds; overlap one second to preserve records at the boundary.
+ params["created_after"] = int(watermark.timestamp()) - 1
+
+ endpoint_config: Endpoint = cast(
+ Endpoint, {"path": endpoint.path, "params": params, "data_selector_required": True}
+ )
+ resource_config: EndpointResource = {
+ "name": inputs.schema_name,
+ "endpoint": endpoint_config,
+ "data_map": normalize_created_at,
+ }
+ rest_config: RESTAPIConfig = {"client": client, "resources": [resource_config]}
+
+ def save_checkpoint(state: dict[str, Any] | None) -> None:
+ manager.save_state(
+ SemaphoreResumeConfig(next_url=state["next_url"]) if state else SemaphoreResumeConfig(completed=True)
+ )
+
+ resource = rest_api_resource(
+ rest_config,
+ inputs.team_id,
+ inputs.job_id,
+ None,
+ resume_hook=save_checkpoint,
+ initial_paginator_state={"next_url": resume.next_url} if resume and resume.next_url else None,
+ )
+ return SourceResponse(
+ name=inputs.schema_name,
+ items=lambda: resource,
+ primary_keys=[endpoint.primary_key],
+ sort_mode="desc",
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semaphore/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semaphore/settings.py
new file mode 100644
index 000000000000..32585367a736
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semaphore/settings.py
@@ -0,0 +1,24 @@
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_field
+
+
+@frozen
+class SemaphoreEndpoint:
+ path: str
+ primary_key: str
+
+
+ENDPOINTS = {
+ "workflows": SemaphoreEndpoint(path="plumber-workflows", primary_key="wf_id"),
+ "pipelines": SemaphoreEndpoint(path="pipelines", primary_key="ppl_id"),
+ "deployment_targets": SemaphoreEndpoint(path="deployment_targets", primary_key="id"),
+}
+
+INCREMENTAL_FIELDS = {"workflows": [incremental_field("created_at")]}
+API_DOCS_URL = "https://docs.semaphore.io/reference/api"
+AUTH_ERROR = "Semaphore rejected your API token. Check the token in your account settings."
+PERMISSION_ERROR = "Your Semaphore token cannot read this project. Check your project permissions."
+NOT_FOUND_ERROR = (
+ "Semaphore could not find this project. Check the organization name, project ID, and token permissions."
+)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semaphore/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semaphore/source.py
index 3e86f0649feb..e3947532fe8f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/semaphore/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semaphore/source.py
@@ -1,20 +1,101 @@
from typing import cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+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,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.semaphore import (
SemaphoreSourceConfig,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semaphore.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semaphore.semaphore import (
+ SemaphoreResumeConfig,
+ semaphore_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semaphore.settings import (
+ API_DOCS_URL,
+ AUTH_ERROR,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ NOT_FOUND_ERROR,
+ PERMISSION_ERROR,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class SemaphoreSource(SimpleSource[SemaphoreSourceConfig]):
+class SemaphoreSource(ResumableSource[SemaphoreSourceConfig, SemaphoreResumeConfig]):
+ lists_tables_without_credentials = True
+ # Semaphore Cloud documents v1alpha as its public API despite the version name.
+ supported_versions = ("v1alpha",)
+ default_version = "v1alpha"
+ api_docs_url = API_DOCS_URL
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.SEMAPHORE
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": AUTH_ERROR,
+ "403 Client Error": PERMISSION_ERROR,
+ "404 Client Error": NOT_FOUND_ERROR,
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: SemaphoreSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only={"workflows"})
+
+ def validate_credentials(
+ self,
+ config: SemaphoreSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ try:
+ return validate_credentials(config, self.resolve_api_version(api_version))
+ except ValueError as error:
+ return False, str(error)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SemaphoreResumeConfig]:
+ return ResumableSourceManager(inputs, SemaphoreResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: SemaphoreSourceConfig,
+ resumable_source_manager: ResumableSourceManager[SemaphoreResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return semaphore_source(config, inputs, resumable_source_manager, self.resolve_api_version(inputs.api_version))
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
@@ -22,6 +103,36 @@ class SemaphoreSource(SimpleSource[SemaphoreSourceConfig]):
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Semaphore (Semaphore CI)",
iconPath="/static/services/semaphore.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="Copy your API token from [Semaphore account settings](https://me.semaphoreci.com/account). "
+ "Enter your organization subdomain and the project ID to import.",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ secret=True,
+ placeholder="",
+ ),
+ SourceFieldInputConfig(
+ name="organization",
+ label="Organization subdomain",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ secret=False,
+ placeholder="example",
+ ),
+ SourceFieldInputConfig(
+ name="project_id",
+ label="Project ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ secret=False,
+ placeholder="00000000-0000-4000-8000-000000000001",
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/semaphore/tests/test_semaphore.py b/products/warehouse_sources/backend/temporal/data_imports/sources/semaphore/tests/test_semaphore.py
new file mode 100644
index 000000000000..015fc8d752c8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/semaphore/tests/test_semaphore.py
@@ -0,0 +1,286 @@
+import json
+from collections.abc import Iterable
+from datetime import UTC, datetime
+from http import HTTPStatus
+from typing import Any, cast
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import PreparedRequest, Response
+from requests.exceptions import HTTPError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.semaphore import (
+ SemaphoreSourceConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semaphore.semaphore import SemaphoreResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.semaphore.settings import (
+ AUTH_ERROR,
+ NOT_FOUND_ERROR,
+ PERMISSION_ERROR,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.semaphore.source import SemaphoreSource
+
+BASE_URL = "https://example.semaphoreci.com/api/v1alpha/"
+PROJECT_ID = "00000000-0000-4000-8000-000000000001"
+TOKEN = "test-semaphore-token"
+SEND = "requests.sessions.Session.send"
+
+
+def config() -> SemaphoreSourceConfig:
+ return SemaphoreSourceConfig(api_token=TOKEN, organization="example", project_id=PROJECT_ID)
+
+
+def inputs() -> SourceInputs:
+ return SourceInputs(
+ schema_name="workflows",
+ schema_id="schema-id",
+ source_id="source-id",
+ team_id=1,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ db_incremental_field_earliest_value=None,
+ incremental_field="created_at",
+ incremental_field_type=None,
+ job_id="job-id",
+ logger=MagicMock(),
+ reset_pipeline=False,
+ )
+
+
+def manager() -> MagicMock:
+ result = MagicMock(spec=ResumableSourceManager)
+ result.can_resume.return_value = False
+ return result
+
+
+def response(body: object, status: int = 200, next_url: str | None = None) -> Response:
+ result = Response()
+ result.status_code = status
+ result.reason = HTTPStatus(status).phrase
+ result.url = BASE_URL + "plumber-workflows"
+ result._content = json.dumps(body).encode()
+ result.headers["Content-Type"] = "application/json"
+ if next_url:
+ result.headers["Link"] = f'<{next_url}>; rel="next"'
+ return result
+
+
+ ("table", "path", "key"),
+ [
+ ("workflows", "plumber-workflows", "wf_id"),
+ ("pipelines", "pipelines", "ppl_id"),
+ ("deployment_targets", "deployment_targets", "id"),
+ ],
+)
[email protected]("empty_terminal", [False, True])
+def test_transport_and_terminal_page(
+ config: SemaphoreSourceConfig,
+ inputs: SourceInputs,
+ manager: MagicMock,
+ table: str,
+ path: str,
+ key: str,
+ empty_terminal: bool,
+) -> None:
+ inputs.schema_name = table
+ next_url = f"{BASE_URL}{path}?project_id={PROJECT_ID}&page=2"
+ first = {key: "row-1", "created_at": {"seconds": 1704067200, "nanos": 123456000}}
+ last = [] if empty_terminal else [{key: "row-2", "created_at": "2024-01-02T00:00:00Z"}]
+ with patch(SEND, side_effect=[response([first], next_url=next_url), response(last)]) as send:
+ result = SemaphoreSource().source_for_pipeline(config, manager, inputs)
+ rows = [row for page in cast(Iterable[Any], result.items()) for row in page]
+ assert [row[key] for row in rows] == (["row-1"] if empty_terminal else ["row-1", "row-2"])
+ assert rows[0]["created_at"] == datetime(2024, 1, 1, 0, 0, 0, 123456, UTC)
+ assert result.primary_keys == [key]
+ requests = [call.args[0] for call in send.call_args_list]
+ assert urlsplit(requests[0].url).path == f"/api/v1alpha/{path}"
+ assert parse_qs(urlsplit(requests[0].url).query) == {"project_id": [PROJECT_ID]}
+ assert requests[1].url == next_url
+ for request in requests:
+ assert request.headers["Authorization"] == f"Token {TOKEN}"
+ assert request.headers["User-Agent"] == "SemaphoreCI v2.0 Client"
+ assert all(call.kwargs["allow_redirects"] is False for call in send.call_args_list)
+ assert manager.save_state.call_args_list[0].args[0] == SemaphoreResumeConfig(next_url=next_url)
+ assert manager.save_state.call_args_list[-1].args[0] == SemaphoreResumeConfig(completed=True)
+
+
+ ("table", "incremental", "watermark", "expected"),
+ [
+ ("workflows", True, datetime(2024, 1, 1, tzinfo=UTC), "1704067199"),
+ ("workflows", True, "2024-01-01T00:00:00.999999Z", "1704067199"),
+ ("workflows", True, None, None),
+ ("workflows", False, "2024-01-01T00:00:00Z", None),
+ ("pipelines", True, "2024-01-01T00:00:00Z", None),
+ ("deployment_targets", True, "2024-01-01T00:00:00Z", None),
+ ],
+)
+def test_incremental_filter(
+ config: SemaphoreSourceConfig,
+ inputs: SourceInputs,
+ manager: MagicMock,
+ table: str,
+ incremental: bool,
+ watermark: datetime | str | None,
+ expected: str | None,
+) -> None:
+ inputs.schema_name = table
+ inputs.should_use_incremental_field = incremental
+ inputs.db_incremental_field_last_value = watermark
+ with patch(SEND, return_value=response([])) as send:
+ result = SemaphoreSource().source_for_pipeline(config, manager, inputs)
+ list(cast(Iterable[Any], result.items()))
+ params = parse_qs(urlsplit(cast(str, send.call_args.args[0].url)).query)
+ assert params == {"project_id": [PROJECT_ID], **({"created_after": [expected]} if expected else {})}
+ if table == "workflows" and incremental:
+ assert result.sort_mode == "desc"
+
+
[email protected]("completed", [False, True])
+def test_resume_skips_saved_pages(
+ config: SemaphoreSourceConfig,
+ inputs: SourceInputs,
+ manager: MagicMock,
+ completed: bool,
+) -> None:
+ next_url = f"{BASE_URL}plumber-workflows?project_id={PROJECT_ID}&page=3"
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = SemaphoreResumeConfig(next_url=next_url, completed=completed)
+ with patch(SEND, return_value=response([{"wf_id": "last"}])) as send:
+ result = SemaphoreSource().source_for_pipeline(config, manager, inputs)
+ rows = [row for page in cast(Iterable[Any], result.items()) for row in page]
+ if completed:
+ assert rows == []
+ send.assert_not_called()
+ else:
+ assert rows == [{"wf_id": "last"}]
+ assert send.call_args.args[0].url == next_url
+ manager.save_state.assert_called_once_with(SemaphoreResumeConfig(completed=True))
+
+
+ ("status", "expected_message"),
+ [(401, AUTH_ERROR), (403, PERMISSION_ERROR), (404, NOT_FOUND_ERROR)],
+)
+def test_auth_errors_are_actionable_and_non_retryable(
+ config: SemaphoreSourceConfig,
+ inputs: SourceInputs,
+ manager: MagicMock,
+ status: int,
+ expected_message: str,
+) -> None:
+ source = SemaphoreSource()
+ with patch(SEND, return_value=response({}, status)) as send:
+ valid, message = source.validate_credentials(config, 1)
+ assert valid is False
+ assert message == expected_message
+ send.assert_called_once()
+ with patch(SEND, return_value=response({}, status)) as send:
+ result = source.source_for_pipeline(config, manager, inputs)
+ with pytest.raises(HTTPError) as error:
+ list(cast(Iterable[Any], result.items()))
+ assert f"{status} Client Error" in str(error.value)
+ assert TOKEN not in str(error.value)
+ send.assert_called_once()
+
+
+def test_validation_reads_only_one_page(config: SemaphoreSourceConfig) -> None:
+ with patch(SEND, return_value=response([], next_url=BASE_URL + "plumber-workflows?page=2")) as send:
+ assert SemaphoreSource().validate_credentials(config, 1) == (True, None)
+ send.assert_called_once()
+ request: PreparedRequest = send.call_args.args[0]
+ assert request.headers["Authorization"] == f"Token {TOKEN}"
+ assert parse_qs(urlsplit(cast(str, request.url)).query) == {"project_id": [PROJECT_ID]}
+
+
+ ("field", "value"),
+ [
+ ("organization", "https://example.com"),
+ ("organization", "example.com"),
+ ("organization", "[email protected]"),
+ ("organization", "bad\n"),
+ ("organization", "-bad"),
+ ("organization", "a" * 64),
+ ("project_id", "not-a-uuid"),
+ ],
+)
+def test_invalid_configuration_never_sends_credentials(
+ config: SemaphoreSourceConfig,
+ inputs: SourceInputs,
+ manager: MagicMock,
+ field: str,
+ value: str,
+) -> None:
+ setattr(config, field, value)
+ with patch(SEND) as send:
+ assert SemaphoreSource().validate_credentials(config, 1)[0] is False
+ with pytest.raises(ValueError):
+ SemaphoreSource().source_for_pipeline(config, manager, inputs)
+ send.assert_not_called()
+
+
+ "next_url", ["https://example.com/steal", "http://example.semaphoreci.com/api/v1alpha/pipelines"]
+)
[email protected]("resumed", [False, True])
+def test_pagination_cannot_send_token_to_another_origin(
+ config: SemaphoreSourceConfig,
+ inputs: SourceInputs,
+ manager: MagicMock,
+ next_url: str,
+ resumed: bool,
+) -> None:
+ manager.can_resume.return_value = resumed
+ manager.load_state.return_value = SemaphoreResumeConfig(next_url=next_url)
+ with patch(SEND, return_value=response([{"wf_id": "first"}], next_url=next_url)) as send:
+ result = SemaphoreSource().source_for_pipeline(config, manager, inputs)
+ with pytest.raises(ValueError):
+ list(cast(Iterable[Any], result.items()))
+ assert send.call_count == (0 if resumed else 1)
+
+
[email protected]("body", [{"error": "unexpected"}, None])
+def test_malformed_success_does_not_silently_complete(
+ config: SemaphoreSourceConfig,
+ inputs: SourceInputs,
+ manager: MagicMock,
+ body: Any,
+) -> None:
+ with patch(SEND, return_value=response(body)):
+ result = SemaphoreSource().source_for_pipeline(config, manager, inputs)
+ with pytest.raises(ValueError):
+ list(cast(Iterable[Any], result.items()))
+ manager.save_state.assert_not_called()
+
+
+def test_invalid_watermark_does_not_run_a_full_refresh(
+ config: SemaphoreSourceConfig,
+ inputs: SourceInputs,
+ manager: MagicMock,
+) -> None:
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "invalid"
+ with patch(SEND) as send, pytest.raises(ValueError, match="sync position"):
+ SemaphoreSource().source_for_pipeline(config, manager, inputs)
+ send.assert_not_called()
+
+
+def test_invalid_created_at_does_not_save_a_checkpoint(
+ config: SemaphoreSourceConfig,
+ inputs: SourceInputs,
+ manager: MagicMock,
+) -> None:
+ with patch(SEND, return_value=response([{"wf_id": "invalid", "created_at": "invalid"}])):
+ result = SemaphoreSource().source_for_pipeline(config, manager, inputs)
+ with pytest.raises(ValueError, match="invalid creation time"):
+ list(cast(Iterable[Any], result.items()))
+ manager.save_state.assert_not_called()