: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement gitbook import source (#69332)
Tom Owers353265deff44
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 80dbba109959..119829c37e7e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -168,6 +168,7 @@ the row lists both.| fulcrum | HTTP | requests | ✅ || fullstory | HTTP | requests | ✅ || gainsight_px | HTTP | requests | ✅ |+| gitbook | HTTP | requests | ✅ || github | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || giphy | HTTP | requests | ✅ || gitlab | HTTP | requests | ✅ |@@ -528,7 +529,6 @@ doesn't conflict with concurrent PRs.- freshchat- freshservice- fulcrum-- gitbook- glassfrog- gmail- gnewsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex d779ff7a6ce2..522f5b01afba 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@@ -1391,7 +1391,7 @@ class GiphySourceConfig(config.Config):@config.configclass GitBookSourceConfig(config.Config):- pass+ api_token: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/canonical_descriptions.pynew file mode 100644index 000000000000..7e3780d475a5--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/canonical_descriptions.py@@ -0,0 +1,146 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions taken from the official GitBook API reference (https://gitbook.com/docs/developers)+# and its published OpenAPI spec. Keys match the endpoint names in settings.GITBOOK_ENDPOINTS.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "organizations": {+ "description": "Organizations the API token's owner is a member of. An organization is the top-level workspace that owns spaces, collections, sites, and members.",+ "docs_url": "https://gitbook.com/docs/developers/gitbook-api/api-reference/organizations",+ "columns": {+ "id": "Unique identifier for the organization.",+ "object": 'Type of object, always equal to "organization".',+ "title": "Name of the organization.",+ "createdAt": "Timestamp of when the organization was created.",+ "hostname": "Default hostname for the organization's public content, e.g. <org-hostname>.gitbook.io.",+ "customHostname": "Custom hostname linked to this organization.",+ "defaultRole": "Default role of a member in the organization, null for guests.",+ "sso": "Whether SSO is enforced organization-wide.",+ "inviteLinks": "Whether invite links are enabled for this organization.",+ "plan": "Name of the product plan the organization is on.",+ "urls": "URLs associated with the organization.",+ },+ },+ "spaces": {+ "description": "Spaces across every organization the token can access. A space is a single project of documentation content.",+ "docs_url": "https://gitbook.com/docs/developers/gitbook-api/api-reference/spaces",+ "columns": {+ "id": "Unique identifier for the space.",+ "object": 'Type of object, always equal to "space".',+ "title": "Title of the space.",+ "emoji": "Unicode codepoint or character of the space's emoji.",+ "visibility": "Who can access the content: public, unlisted, share-link, visitor-auth, in-collection, or private.",+ "createdAt": "Timestamp of when the space was created.",+ "updatedAt": "Timestamp of when the space was last updated.",+ "deletedAt": "Timestamp of when the space was deleted, if it has been.",+ "editMode": "How the space can be edited: live (direct edits) or locked (edits via change requests).",+ "organization": "ID of the organization owning this space.",+ "parent": "ID of the parent collection.",+ "revision": "ID of the active revision in the space.",+ "comments": "Count of opened comments on the space.",+ "changeRequests": "Total count of change requests on the space.",+ "changeRequestsOpen": "Count of open change requests on the space.",+ "changeRequestsDraft": "Count of draft change requests on the space.",+ "urls": "URLs associated with the space.",+ },+ },+ "collections": {+ "description": "Collections across every organization the token can access. A collection groups spaces (and nested collections) together.",+ "docs_url": "https://gitbook.com/docs/developers/gitbook-api/api-reference/collections",+ "columns": {+ "id": "Unique identifier for the collection.",+ "object": 'Type of object, always equal to "collection".',+ "title": "Title of the collection.",+ "description": "Description of the collection.",+ "organization": "ID of the organization owning this collection.",+ "parent": "ID of the parent collection, if any.",+ "urls": "URLs associated with the collection.",+ },+ },+ "sites": {+ "description": "Published documentation sites across every organization the token can access.",+ "docs_url": "https://gitbook.com/docs/developers/gitbook-api/api-reference/sites",+ "columns": {+ "id": "Unique identifier of the site.",+ "object": 'Type of object, always equal to "site".',+ "organization_id": "ID of the organization owning this site (added by PostHog during sync).",+ "title": "Title of the site.",+ "type": "The type of the site.",+ "hostname": "Custom hostname for the site, e.g. docs.mycompany.com.",+ "basename": "Basename for the site, e.g. api.",+ "visibility": "The audience of the site: public, unlisted, share-link, visitor-auth, or members-only.",+ "published": "Whether the site is live and accessible to its audience.",+ "createdAt": "Timestamp of when the site was created.",+ "urls": "URLs associated with the site.",+ },+ },+ "members": {+ "description": "Organization memberships across every organization the token can access. One row per user per organization.",+ "docs_url": "https://gitbook.com/docs/developers/gitbook-api/api-reference/organizations/organization-members",+ "columns": {+ "id": "Unique identifier for the user.",+ "object": 'Type of object, always equal to "member".',+ "organization_id": "ID of the organization the membership belongs to (added by PostHog during sync).",+ "role": "The role of the member in the organization, null for guests.",+ "user": "Profile of the user: id, display name, email, and photo URL.",+ "disabled": "Whether the membership is disabled, preventing the user from accessing content.",+ "joinedAt": "Timestamp of when the user joined the organization.",+ "lastSeenAt": "Timestamp of when the user was last active in the organization.",+ "sso": "Whether the user can log in with SSO.",+ },+ },+ "teams": {+ "description": "Teams across every organization the token can access. Teams group organization members for access management.",+ "docs_url": "https://gitbook.com/docs/developers/gitbook-api/api-reference/teams",+ "columns": {+ "id": "Unique identifier for the team.",+ "object": 'Type of object, always equal to "team".',+ "organization_id": "ID of the organization the team belongs to (added by PostHog during sync).",+ "title": "Title of the team.",+ "members": "Count of members in this team.",+ "spaces": "Count of spaces this team has access to.",+ "createdAt": "Timestamp of when the team was created.",+ },+ },+ "change_requests": {+ "description": "Change requests across every organization the token can access. A change request is a proposed set of edits to a space's content, similar to a pull request.",+ "docs_url": "https://gitbook.com/docs/developers/gitbook-api/api-reference/change-requests",+ "columns": {+ "id": "Unique identifier for the change request.",+ "object": 'Type of object, always equal to "change-request".',+ "organization_id": "ID of the organization the change request belongs to (added by PostHog during sync).",+ "number": "Incremental identifier of the change request within its space.",+ "status": "Status of the change request: draft, open, merged, or archived.",+ "subject": "Subject of the change request.",+ "createdBy": "Profile of the user who created the change request.",+ "createdAt": "Timestamp of when the change request was created.",+ "updatedAt": "Timestamp of when the change request was last updated.",+ "space": "ID of the space in which the change request was created.",+ "revision": "ID of the active revision in the change request.",+ "revisionMerged": "When merged, ID of the revision resulting from the merge.",+ "comments": "Count of opened comments on the change request.",+ "outdated": "Whether the change request is out of date with the latest changes in the main content.",+ "urls": "URLs associated with the change request.",+ },+ },+ "comments": {+ "description": "Comments posted on spaces across every organization the token can access.",+ "docs_url": "https://gitbook.com/docs/developers/gitbook-api/api-reference/comments",+ "columns": {+ "id": "Unique identifier for the comment.",+ "object": 'Type of object, always equal to "comment".',+ "space_id": "ID of the space the comment was posted in (added by PostHog during sync).",+ "postedBy": "Profile of the user who posted the comment.",+ "postedAt": "Timestamp of when the comment was posted.",+ "editedAt": "Timestamp of when the comment was last edited.",+ "status": "Status of the comment: open or resolved.",+ "resolvedAt": "Timestamp of when the comment was resolved.",+ "resolvedBy": "Profile of the user who resolved the comment.",+ "replies": "The number of replies to this comment.",+ "body": "Content of the comment as a GitBook document.",+ "target": "Information about the target of the comment, such as the page or change request it was posted on.",+ "urls": "URLs associated with the comment.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/gitbook.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/gitbook.pynew file mode 100644index 000000000000..8f0fef232406--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/gitbook.py@@ -0,0 +1,211 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.gitbook.settings import GITBOOK_ENDPOINTS++GITBOOK_BASE_URL = "https://api.gitbook.com/v1"+# List endpoints accept a `limit` of up to 1000 per the OpenAPI spec; a moderate page keeps+# individual payloads small (change requests and comments embed document bodies).+PAGE_SIZE = 250+REQUEST_TIMEOUT_SECONDS = 60+# Cheap endpoint used to confirm an API token is genuine. The token inherits its owner's+# permissions, so per-endpoint access is validated lazily at sync time.+DEFAULT_PROBE_PATH = "/user"+++class GitBookRetryableError(Exception):+ pass+++class GitBookResumeConfig:+ # Fan-out parents (organization or space ids) whose pages have all been yielded already.+ completed_parent_ids: list[str] = dataclasses.field(default_factory=list)+ # Parent currently being paginated; `None` for the top-level organizations endpoint.+ current_parent_id: Optional[str] = None+ # Opaque `next.page` token for the next page within the current parent (or the top-level+ # list). A crashed full-refresh sync resumes from the page after the last one yielded; merge+ # dedupes the re-pulled page on the primary key.+ next_page: Optional[str] = None+++def _headers(api_token: str) -> dict[str, str]:+ return {"Authorization": f"Bearer {api_token}", "Accept": "application/json"}+++@retry(+ retry=retry_if_exception_type((GitBookRetryableError, 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,+ page: Optional[str],+ logger: FilteringBoundLogger,+) -> tuple[list[dict[str, Any]], Optional[str]]:+ params: dict[str, Any] = {"limit": PAGE_SIZE}+ if page is not None:+ params["page"] = page++ response = session.get(url, params=params, timeout=REQUEST_TIMEOUT_SECONDS)++ # GitBook enforces per-method rate limits surfaced via X-RateLimit-* headers and HTTP 429.+ if response.status_code == 429 or response.status_code >= 500:+ raise GitBookRetryableError(f"GitBook API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"GitBook API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ data = response.json()+ # Every list response is `{"items": [...], "next": {"page": "..."}}`; `next` is omitted on+ # the last page.+ if not isinstance(data, dict) or not isinstance(data.get("items"), list):+ raise GitBookRetryableError(f"GitBook returned an unexpected payload for {url}: {type(data).__name__}")++ next_obj = data.get("next")+ next_page = next_obj.get("page") if isinstance(next_obj, dict) else None+ return data["items"], next_page+++def _list_all_ids(session: requests.Session, path: str, logger: FilteringBoundLogger) -> list[str]:+ ids: list[str] = []+ page: Optional[str] = None+ while True:+ items, page = _fetch_page(session, f"{GITBOOK_BASE_URL}{path}", page, logger)+ ids.extend(item["id"] for item in items)+ if not page:+ return ids+++def _parent_ids(session: requests.Session, parent: str, logger: FilteringBoundLogger) -> list[str]:+ org_ids = _list_all_ids(session, "/orgs", logger)+ if parent == "organization":+ return org_ids+ # Spaces are enumerated per organization: orgs -> spaces.+ space_ids: list[str] = []+ for org_id in org_ids:+ space_ids.extend(_list_all_ids(session, f"/orgs/{org_id}/spaces", logger))+ return space_ids+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GitBookResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = GITBOOK_ENDPOINTS[endpoint]+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None++ if config.parent is None:+ page = resume.next_page if resume else None+ if page:+ logger.debug(f"GitBook: resuming {endpoint} from page token {page}")+ while True:+ items, next_page = _fetch_page(session, f"{GITBOOK_BASE_URL}{config.path}", page, logger)+ if items:+ yield items+ if not next_page:+ return+ page = next_page+ # Save AFTER yielding so a crash re-fetches from the next page (already-yielded pages+ # are persisted); merge dedupes the re-pulled page on the primary key.+ resumable_source_manager.save_state(GitBookResumeConfig(next_page=next_page))++ else:+ completed = set(resume.completed_parent_ids) if resume else set()+ if completed:+ logger.debug(f"GitBook: resuming {endpoint}, skipping {len(completed)} completed parents")++ for parent_id in _parent_ids(session, config.parent, logger):+ if parent_id in completed:+ continue++ url = f"{GITBOOK_BASE_URL}{config.path.format(parent_id=parent_id)}"+ page = resume.next_page if (resume and resume.current_parent_id == parent_id) else None+ while True:+ items, next_page = _fetch_page(session, url, page, logger)+ if items:+ if config.parent_id_key:+ yield [{**item, config.parent_id_key: parent_id} for item in items]+ else:+ yield items+ if not next_page:+ break+ page = next_page+ resumable_source_manager.save_state(+ GitBookResumeConfig(+ completed_parent_ids=sorted(completed),+ current_parent_id=parent_id,+ next_page=next_page,+ )+ )++ completed.add(parent_id)+ resumable_source_manager.save_state(GitBookResumeConfig(completed_parent_ids=sorted(completed)))+++def gitbook_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GitBookResumeConfig],+) -> SourceResponse:+ config = GITBOOK_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ )+++def check_access(api_token: str, path: str = DEFAULT_PROBE_PATH) -> tuple[int, Optional[str]]:+ """Probe a single endpoint to validate the API token.++ Returns ``(status, message)``: ``200`` reachable, ``401``/``403`` auth failure, ``0`` for a+ connection problem, other HTTP status otherwise.+ """+ session = make_tracked_session(headers=_headers(api_token), redact_values=(api_token,))+ try:+ response = session.get(f"{GITBOOK_BASE_URL}{path}", timeout=15)+ except Exception as e:+ return 0, f"Could not connect to GitBook: {e}"++ # GitBook answers 401 for an invalid token and 403 for a missing/unauthorized one.+ if response.status_code in (401, 403):+ return response.status_code, None++ if not response.ok:+ return response.status_code, f"GitBook returned HTTP {response.status_code}"++ return 200, None+++def validate_credentials(api_token: str) -> tuple[bool, str | None]:+ status, message = check_access(api_token)+ if status == 200:+ return True, None+ if status in (401, 403):+ return False, "Invalid GitBook API token"+ return False, message or "Could not validate GitBook API token"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/settings.pynew file mode 100644index 000000000000..26083e6fec73--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/settings.py@@ -0,0 +1,75 @@+from dataclasses import dataclass, field+from typing import Literal, Optional+++@dataclass+class GitBookEndpointConfig:+ name: str+ # Path relative to the API base URL. Fan-out endpoints carry a single `{parent_id}`+ # placeholder resolved per parent organization or space.+ path: str+ # Fan-out parent resource. Organizations come straight from `/orgs`; spaces are+ # enumerated per organization via `/orgs/{id}/spaces`.+ parent: Optional[Literal["organization", "space"]] = None+ # When set, the parent's id is injected into every row under this column so rows from+ # different parents stay distinguishable (and usable in composite primary keys).+ parent_id_key: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+++# GitBook REST API v1 list endpoints (https://gitbook.com/docs/developers). All are full refresh+# only: per the published OpenAPI spec, no list endpoint accepts an updated-after/since timestamp+# filter, so there is no server-side cursor to advance an incremental sync (see the+# implementing-warehouse-sources skill).+#+# Primary keys: space and collection ids are globally addressable (`/spaces/{id}`,+# `/collections/{id}`), so `id` alone is safe there. Member ids are user ids (the same user can+# belong to several organizations) and the uniqueness scope of site/team ids is undocumented, so+# those use a composite key with the injected parent id. Change request `id` scope is also+# undocumented (`number` is explicitly per space), so it pairs with the row's own `space` field.+GITBOOK_ENDPOINTS: dict[str, GitBookEndpointConfig] = {+ "organizations": GitBookEndpointConfig(name="organizations", path="/orgs"),+ "spaces": GitBookEndpointConfig(name="spaces", path="/orgs/{parent_id}/spaces", parent="organization"),+ "collections": GitBookEndpointConfig(+ name="collections", path="/orgs/{parent_id}/collections", parent="organization"+ ),+ "sites": GitBookEndpointConfig(+ name="sites",+ path="/orgs/{parent_id}/sites",+ parent="organization",+ parent_id_key="organization_id",+ primary_keys=["organization_id", "id"],+ ),+ "members": GitBookEndpointConfig(+ name="members",+ path="/orgs/{parent_id}/members",+ parent="organization",+ parent_id_key="organization_id",+ primary_keys=["organization_id", "id"],+ ),+ "teams": GitBookEndpointConfig(+ name="teams",+ path="/orgs/{parent_id}/teams",+ parent="organization",+ parent_id_key="organization_id",+ primary_keys=["organization_id", "id"],+ ),+ "change_requests": GitBookEndpointConfig(+ name="change_requests",+ path="/orgs/{parent_id}/change-requests",+ parent="organization",+ parent_id_key="organization_id",+ primary_keys=["space", "id"],+ ),+ "comments": GitBookEndpointConfig(+ name="comments",+ path="/spaces/{parent_id}/comments",+ parent="space",+ parent_id_key="space_id",+ primary_keys=["space_id", "id"],+ ),+}++ENDPOINTS = tuple(GITBOOK_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/source.pyindex ec6e32c1c22d..cee2c3320125 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/source.py@@ -1,19 +1,42 @@-from typing import cast+from typing import Optional, castfrom 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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import GitBookSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.gitbook.gitbook import (+ GitBookResumeConfig,+ gitbook_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gitbook.settings import (+ ENDPOINTS,+ GITBOOK_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class GitBookSource(SimpleSource[GitBookSourceConfig]):+class GitBookSource(ResumableSource[GitBookSourceConfig, GitBookResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GITBOOK@@ -24,7 +47,89 @@ class GitBookSource(SimpleSource[GitBookSourceConfig]):name=SchemaExternalDataSourceType.GIT_BOOK,category=DataWarehouseSourceCategory.PRODUCTIVITY,label="GitBook",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your GitBook API token to pull your documentation workspace into the PostHog Data warehouse.++You can create a personal access token under **Account settings → Developer** in [GitBook](https://app.gitbook.com/account/developer). The token inherits your account permissions and grants read access to your organizations, spaces, collections, sites, members, teams, change requests, and comments.+""",iconPath="/static/services/gitbook.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/gitbook",+ keywords=["docs", "documentation", "knowledge base", "wiki"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),unreleasedSource=True,)++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.gitbook.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.gitbook.com": "Your GitBook API token is invalid or has been revoked. Generate a new token under Account settings → Developer, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.gitbook.com": "Your GitBook API token does not have access to this data. Check the token owner's organization permissions, then reconnect.",+ }++ def get_schemas(+ self,+ config: GitBookSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Every endpoint is full refresh only — GitBook's list endpoints expose no server-side+ # updated-after/since filter, so there is no timestamp cursor to advance an incremental sync.+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=[],+ )+ 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: GitBookSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ # A single probe of `/user` confirms the token is genuine; per-endpoint access follows the+ # token owner's permissions and is surfaced at sync time via get_non_retryable_errors.+ return validate_credentials(config.api_token)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GitBookResumeConfig]:+ return ResumableSourceManager[GitBookResumeConfig](inputs, GitBookResumeConfig)++ def source_for_pipeline(+ self,+ config: GitBookSourceConfig,+ resumable_source_manager: ResumableSourceManager[GitBookResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ if inputs.schema_name not in GITBOOK_ENDPOINTS:+ raise ValueError(f"Unknown GitBook schema '{inputs.schema_name}'")++ return gitbook_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/tests/test_gitbook.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/tests/test_gitbook.pynew file mode 100644index 000000000000..b1b7af4be083--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/tests/test_gitbook.py@@ -0,0 +1,320 @@+from collections.abc import Mapping+from typing import Any, Optional++import pytest+from unittest.mock import MagicMock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.gitbook import gitbook+from products.warehouse_sources.backend.temporal.data_imports.sources.gitbook.gitbook import (+ GITBOOK_BASE_URL,+ PAGE_SIZE,+ GitBookResumeConfig,+ GitBookRetryableError,+ check_access,+ get_rows,+ gitbook_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gitbook.settings import (+ ENDPOINTS,+ GITBOOK_ENDPOINTS,+)++# Call the undecorated function so the tenacity retry/backoff wrapper doesn't slow failure-path tests.+_fetch_page_unwrapped = gitbook._fetch_page.__wrapped__ # type: ignore[attr-defined]++PageKey = tuple[str, Optional[str]]+++class _FakeResumableManager:+ def __init__(self, state: GitBookResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[GitBookResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> GitBookResumeConfig | None:+ return self._state++ def save_state(self, data: GitBookResumeConfig) -> None:+ self.saved.append(data)+++def _collect(+ manager: _FakeResumableManager,+ monkeypatch: Any,+ pages: Mapping[PageKey, tuple[list[dict], Optional[str]]],+ endpoint: str,+) -> list[dict]:+ def fake_fetch(session: Any, url: str, page: Optional[str], logger: Any) -> tuple[list[dict], Optional[str]]:+ return pages[(url, page)]++ monkeypatch.setattr(gitbook, "_fetch_page", fake_fetch)+ monkeypatch.setattr(gitbook, "make_tracked_session", lambda **kwargs: MagicMock())++ rows: list[dict] = []+ for batch in get_rows(+ api_token="gb-token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows+++class TestGetRowsTopLevel:+ ORGS_URL = f"{GITBOOK_BASE_URL}/orgs"++ def test_single_page_yields_and_stops(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = _collect(+ manager, monkeypatch, {(self.ORGS_URL, None): ([{"id": "org1"}, {"id": "org2"}], None)}, "organizations"+ )+ assert rows == [{"id": "org1"}, {"id": "org2"}]+ # No next page means the sync ends without persisting resume state.+ assert manager.saved == []++ def test_follows_page_token_until_exhausted(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: dict[PageKey, tuple[list[dict], Optional[str]]] = {+ (self.ORGS_URL, None): ([{"id": "org1"}], "tok2"),+ (self.ORGS_URL, "tok2"): ([{"id": "org2"}], None),+ }+ rows = _collect(manager, monkeypatch, pages, "organizations")+ assert rows == [{"id": "org1"}, {"id": "org2"}]+ # State is saved once — after the first page yields, pointing at the next token.+ assert [s.next_page for s in manager.saved] == ["tok2"]++ def test_resumes_from_saved_page_token(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(GitBookResumeConfig(next_page="tok2"))+ # The first page must never be fetched on resume.+ rows = _collect(manager, monkeypatch, {(self.ORGS_URL, "tok2"): ([{"id": "org2"}], None)}, "organizations")+ assert rows == [{"id": "org2"}]++ def test_empty_page_yields_nothing(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ rows = _collect(manager, monkeypatch, {(self.ORGS_URL, None): ([], None)}, "organizations")+ assert rows == []+ assert manager.saved == []+++class TestGetRowsFanOut:+ ORGS_URL = f"{GITBOOK_BASE_URL}/orgs"++ def test_org_fanout_injects_parent_id_into_rows(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: dict[PageKey, tuple[list[dict], Optional[str]]] = {+ (self.ORGS_URL, None): ([{"id": "org1"}, {"id": "org2"}], None),+ (f"{GITBOOK_BASE_URL}/orgs/org1/members", None): ([{"id": "user1"}], None),+ (f"{GITBOOK_BASE_URL}/orgs/org2/members", None): ([{"id": "user1"}, {"id": "user2"}], None),+ }+ rows = _collect(manager, monkeypatch, pages, "members")+ # The same user id in two orgs stays distinguishable via the injected organization_id.+ assert rows == [+ {"id": "user1", "organization_id": "org1"},+ {"id": "user1", "organization_id": "org2"},+ {"id": "user2", "organization_id": "org2"},+ ]++ def test_spaces_rows_keep_api_shape_without_injection(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: dict[PageKey, tuple[list[dict], Optional[str]]] = {+ (self.ORGS_URL, None): ([{"id": "org1"}], None),+ (f"{GITBOOK_BASE_URL}/orgs/org1/spaces", None): ([{"id": "sp1", "organization": "org1"}], None),+ }+ rows = _collect(manager, monkeypatch, pages, "spaces")+ assert rows == [{"id": "sp1", "organization": "org1"}]++ def test_comments_fan_out_through_orgs_then_spaces(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: dict[PageKey, tuple[list[dict], Optional[str]]] = {+ (self.ORGS_URL, None): ([{"id": "org1"}], None),+ (f"{GITBOOK_BASE_URL}/orgs/org1/spaces", None): ([{"id": "sp1"}, {"id": "sp2"}], None),+ (f"{GITBOOK_BASE_URL}/spaces/sp1/comments", None): ([{"id": "c1"}], None),+ (f"{GITBOOK_BASE_URL}/spaces/sp2/comments", None): ([{"id": "c2"}], None),+ }+ rows = _collect(manager, monkeypatch, pages, "comments")+ assert rows == [{"id": "c1", "space_id": "sp1"}, {"id": "c2", "space_id": "sp2"}]++ def test_saves_completed_parents_and_mid_parent_page_token(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager()+ pages: dict[PageKey, tuple[list[dict], Optional[str]]] = {+ (self.ORGS_URL, None): ([{"id": "org1"}, {"id": "org2"}], None),+ (f"{GITBOOK_BASE_URL}/orgs/org1/teams", None): ([{"id": "t1"}], "tok2"),+ (f"{GITBOOK_BASE_URL}/orgs/org1/teams", "tok2"): ([{"id": "t2"}], None),+ (f"{GITBOOK_BASE_URL}/orgs/org2/teams", None): ([{"id": "t3"}], None),+ }+ _collect(manager, monkeypatch, pages, "teams")+ assert [(s.completed_parent_ids, s.current_parent_id, s.next_page) for s in manager.saved] == [+ ([], "org1", "tok2"),+ (["org1"], None, None),+ (["org1", "org2"], None, None),+ ]++ def test_resume_skips_completed_parents_and_resumes_current_at_token(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(+ GitBookResumeConfig(completed_parent_ids=["org1"], current_parent_id="org2", next_page="tok2")+ )+ # org1's pages and org2's first page must never be fetched on resume.+ pages: dict[PageKey, tuple[list[dict], Optional[str]]] = {+ (self.ORGS_URL, None): ([{"id": "org1"}, {"id": "org2"}, {"id": "org3"}], None),+ (f"{GITBOOK_BASE_URL}/orgs/org2/teams", "tok2"): ([{"id": "t2"}], None),+ (f"{GITBOOK_BASE_URL}/orgs/org3/teams", None): ([{"id": "t3"}], None),+ }+ rows = _collect(manager, monkeypatch, pages, "teams")+ assert rows == [+ {"id": "t2", "organization_id": "org2"},+ {"id": "t3", "organization_id": "org3"},+ ]+++class TestFetchPage:+ URL = f"{GITBOOK_BASE_URL}/orgs"++ def _session_returning(self, status_code: int, body: Any = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.json.return_value = body if body is not None else {"items": []}+ response.text = ""+ response.raise_for_status.side_effect = (+ requests.HTTPError(f"{status_code} error", response=response) if status_code >= 400 else None+ )+ session = MagicMock()+ session.get.return_value = response+ return session++ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(GitBookRetryableError):+ _fetch_page_unwrapped(session, self.URL, None, MagicMock())++ @parameterized.expand([("unauthorized", 401), ("forbidden", 403), ("not_found", 404)])+ def test_client_errors_raise_for_status(self, _name: str, status: int) -> None:+ session = self._session_returning(status)+ with pytest.raises(requests.HTTPError):+ _fetch_page_unwrapped(session, self.URL, None, MagicMock())++ def test_success_returns_items_and_next_page_token(self) -> None:+ body = {"items": [{"id": "org1"}], "next": {"page": "tok2"}, "count": 5}+ session = self._session_returning(200, body)+ rows, next_page = _fetch_page_unwrapped(session, self.URL, None, MagicMock())+ assert rows == [{"id": "org1"}]+ assert next_page == "tok2"++ def test_missing_next_returns_none(self) -> None:+ session = self._session_returning(200, {"items": [{"id": "org1"}]})+ _, next_page = _fetch_page_unwrapped(session, self.URL, None, MagicMock())+ assert next_page is None++ @parameterized.expand([("bare_list", [{"id": "a"}]), ("missing_items", {"count": 1})])+ def test_unexpected_payload_is_retryable(self, _name: str, body: Any) -> None:+ session = self._session_returning(200, body)+ with pytest.raises(GitBookRetryableError):+ _fetch_page_unwrapped(session, self.URL, None, MagicMock())++ @parameterized.expand(+ [+ ("first_page", None, {"limit": PAGE_SIZE}),+ ("later_page", "tok2", {"limit": PAGE_SIZE, "page": "tok2"}),+ ]+ )+ def test_request_params_carry_limit_and_page_token(+ self, _name: str, page: Optional[str], expected_params: dict+ ) -> None:+ session = self._session_returning(200, {"items": []})+ _fetch_page_unwrapped(session, self.URL, page, MagicMock())+ args, kwargs = session.get.call_args+ assert args[0] == self.URL+ assert kwargs["params"] == expected_params+++class TestCheckAccess:+ def _session(self, response: Any) -> MagicMock:+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value = response+ return session++ @parameterized.expand(+ [+ ("ok", 200, True, 200, None),+ ("unauthorized", 401, False, 401, None),+ ("forbidden", 403, False, 403, None),+ ("server_error", 500, False, 500, "GitBook returned HTTP 500"),+ ]+ )+ def test_status_mapping(+ self, _name: str, status: int, ok: bool, expected_status: int, expected_message: str | None+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = ok+ with patch.object(gitbook, "make_tracked_session", return_value=self._session(response)):+ assert check_access("gb-token") == (expected_status, expected_message)++ def test_connection_error_maps_to_zero(self) -> None:+ session = self._session(requests.ConnectionError("boom"))+ with patch.object(gitbook, "make_tracked_session", return_value=session):+ status, message = check_access("gb-token")+ assert status == 0+ assert message is not None and "boom" in message++ @parameterized.expand(+ [+ ("ok", 200, True, None),+ ("unauthorized", 401, False, "Invalid GitBook API token"),+ ("forbidden", 403, False, "Invalid GitBook API token"),+ ("server_error", 500, False, "GitBook returned HTTP 500"),+ ]+ )+ def test_validate_credentials(+ self, _name: str, status: int, expected_valid: bool, expected_message: str | None+ ) -> None:+ response = MagicMock()+ response.status_code = status+ response.ok = status < 400+ with patch.object(gitbook, "make_tracked_session", return_value=self._session(response)):+ assert validate_credentials("gb-token") == (expected_valid, expected_message)+++class TestGitBookSourceResponse:+ @parameterized.expand(+ [+ ("organizations", ["id"]),+ ("spaces", ["id"]),+ ("collections", ["id"]),+ ("sites", ["organization_id", "id"]),+ ("members", ["organization_id", "id"]),+ ("teams", ["organization_id", "id"]),+ ("change_requests", ["space", "id"]),+ ("comments", ["space_id", "id"]),+ ]+ )+ def test_source_response_shape(self, endpoint: str, expected_primary_keys: list[str]) -> None:+ response = gitbook_source(+ api_token="gb-token",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=MagicMock(),+ )+ assert response.name == endpoint+ assert response.primary_keys == expected_primary_keys+ # No stable creation timestamp exists on every object, so we don't partition by datetime.+ assert response.partition_mode is None++ def test_endpoint_catalog_is_consistent(self) -> None:+ assert set(GITBOOK_ENDPOINTS) == set(ENDPOINTS)+ # Fan-out endpoints whose ids are not documented as globally unique must carry the parent+ # id in their composite key, and that column must actually be injected into rows.+ for config in GITBOOK_ENDPOINTS.values():+ if config.parent_id_key is not None and config.parent_id_key in config.primary_keys:+ assert config.parent is not Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/tests/test_gitbook_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/tests/test_gitbook_source.pynew file mode 100644index 000000000000..c95089380748--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitbook/tests/test_gitbook_source.py@@ -0,0 +1,126 @@+import pytest+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import GitBookSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.gitbook.gitbook import GitBookResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.gitbook.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.gitbook.source import GitBookSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestGitBookSource:+ def setup_method(self) -> None:+ self.source = GitBookSource()+ self.team_id = 123+ self.config = GitBookSourceConfig(api_token="gb-token")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.GITBOOK++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "GitBook"+ assert config.label == "GitBook"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/gitbook"++ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ assert field_names == ["api_token"]++ def test_api_token_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_token")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_no_connection_host_fields(self) -> None:+ # The only field is the secret API token; the base URL is hardcoded, so there is no+ # non-secret field an editor could retarget to reuse a preserved token against another host.+ assert self.source.connection_host_fields == []++ def test_lists_tables_without_credentials(self) -> None:+ assert self.source.lists_tables_without_credentials is True++ def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(s.supports_incremental is False for s in schemas)+ assert all(s.supports_append is False for s in schemas)+ assert all(s.incremental_fields == [] for s in schemas)++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["spaces"])+ assert len(schemas) == 1+ assert schemas[0].name == "spaces"++ def test_get_schemas_filtered_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_documented_tables_render_for_public_docs(self) -> None:+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)+ assert all("Full refresh" in t["sync_methods"] for t in tables)++ @parameterized.expand(+ [+ ("401 Client Error: Unauthorized for url: https://api.gitbook.com/v1/orgs",),+ ("403 Client Error: Forbidden for url: https://api.gitbook.com/v1/user",),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("500 Server Error: Internal Server Error for url: https://api.gitbook.com/v1/orgs",),+ ("429 Client Error: Too Many Requests for url: https://api.gitbook.com/v1/user",),+ ]+ )+ def test_non_retryable_errors_ignore_transient(self, unrelated_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in unrelated_error for key in non_retryable)++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.gitbook.source.validate_credentials")+ def test_validate_credentials_delegates_to_shared_helper(self, mock_validate: mock.MagicMock) -> None:+ # The source method forwards the API token to the shared validator and returns its result verbatim.+ mock_validate.return_value = (False, "Invalid GitBook API token")+ result = self.source.validate_credentials(self.config, self.team_id)+ assert result == (False, "Invalid GitBook API token")+ mock_validate.assert_called_once_with("gb-token")++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is GitBookResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.gitbook.source.gitbook_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "spaces"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_token"] == "gb-token"+ assert kwargs["endpoint"] == "spaces"+ assert kwargs["resumable_source_manager"] is manager++ def test_source_for_pipeline_rejects_unknown_schema(self) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "not_a_table"+ with pytest.raises(ValueError, match="Unknown GitBook schema 'not_a_table'"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ def test_canonical_descriptions_cover_declared_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ # Docs enrichment keys by schema name; a stray key would silently never apply.+ assert set(descriptions) == set(ENDPOINTS)