Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

8.8 KB
Raw Blame
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

from typing import Optional

import httpx

from mcp_server.client import (
    CatalogOperation,
    GravitinoOperation,
    MetalakeOperation,
    ModelOperation,
    PolicyOperation,
    SchemaOperation,
    TableOperation,
    TagOperation,
)
from mcp_server.client.domain_operation import DomainOperation
from mcp_server.client.job_operation import JobOperation
from mcp_server.client.plain.exception import GravitinoException
from mcp_server.client.plain.plain_rest_client_catalog_operation import (
    PlainRESTClientCatalogOperation,
)
from mcp_server.client.plain.plain_rest_client_domain_operation import (
    PlainRESTClientDomainOperation,
)
from mcp_server.client.plain.plain_rest_client_fileset_operation import (
    PlainRESTClientFilesetOperation,
)
from mcp_server.client.plain.plain_rest_client_job_operation import (
    PlainRESTClientJobOperation,
)
from mcp_server.client.plain.plain_rest_client_metalake_operation import (
    PlainRESTClientMetalakeOperation,
)
from mcp_server.client.plain.plain_rest_client_model_operation import (
    PlainRESTClientModelOperation,
)
from mcp_server.client.plain.plain_rest_client_partition_operation import (
    PlainRESTClientPartitionOperation,
)
from mcp_server.client.plain.plain_rest_client_policy_operation import (
    PlainRESTClientPolicyOperation,
)
from mcp_server.client.plain.plain_rest_client_schema_operation import (
    PlainRESTClientSchemaOperation,
)
from mcp_server.client.plain.plain_rest_client_semantic_model_operation import (
    PlainRESTClientSemanticModelOperation,
)
from mcp_server.client.plain.plain_rest_client_statistic_operation import (
    PlainRESTClientStatisticOperation,
)
from mcp_server.client.plain.plain_rest_client_table_operation import (
    PlainRESTClientTableOperation,
)
from mcp_server.client.plain.plain_rest_client_tag_operation import (
    PlainRESTClientTagOperation,
)
from mcp_server.client.plain.plain_rest_client_topic_operation import (
    PlainRESTClientTopicOperation,
)
from mcp_server.client.plain.plain_rest_client_view_operation import (
    PlainRESTClientViewOperation,
)
from mcp_server.client.semantic_model_operation import SemanticModelOperation
from mcp_server.client.topic_operation import TopicOperation


class _GravitinoAsyncClient(httpx.AsyncClient):
    """Preserve actionable timeout details instead of FastMCP's generic timeout."""

    async def send(self, request, **kwargs):
        try:
            return await super().send(request, **kwargs)
        except httpx.ReadTimeout as exc:
            # OAuth hooks can time out on their own token request, with a different budget.
            # Preserve that exception instead of misreporting a Gravitino timeout.
            if exc.request.url != request.url:
                raise
            # Include only the encoded path: queries, userinfo and credentials are excluded.
            resource = request.url.raw_path.split(b"?", 1)[0].decode(
                "ascii", errors="backslashreplace"
            )
            # Do not retry writes: the upstream operation may already have committed.
            raise GravitinoException(
                f"The MCP server stopped waiting for Gravitino ({request.method} "
                f"{resource}) after a response read "
                f"timeout of {self.timeout.read:g} seconds. The operation may still "
                "complete on the server; check its result before retrying.",
                error_type="ReadTimeout",
            ) from exc


# pylint: disable=too-many-instance-attributes
class PlainRESTClientOperation(GravitinoOperation):
    def __init__(
        self,
        metalake_name: str,
        uri: str,
        authorization: str = "",
        *,
        auth: Optional[httpx.Auth] = None,
        read_timeout: float = 60.0,
    ):
        """Create a REST client for one identity.

        Args:
            metalake_name: Name of the metalake.
            uri: Gravitino server URI.
            authorization: Full ``Authorization`` header value forwarded verbatim
                on every request (for example ``"Bearer <token>"`` for OAuth2 or
                ``"Basic <base64(user:secret)>"`` for simple or Basic auth).
                Empty string means anonymous (no header sent).
            read_timeout: Response read timeout in seconds (default 60).
            auth: Optional httpx auth hook used instead of a frozen header
                (OAuth client-credentials refresh).
        """
        headers = {}
        if authorization:
            headers["Authorization"] = authorization
        _rest_client = _GravitinoAsyncClient(
            base_url=uri,
            headers=headers,
            auth=auth,
            timeout=httpx.Timeout(
                read_timeout, connect=5.0, pool=5.0, write=5.0
            ),
        )
        # Kept so the shared connection pool can be closed (see close()).
        self._rest_client = _rest_client
        self._catalog_operation = PlainRESTClientCatalogOperation(
            metalake_name, _rest_client
        )
        self._table_operation = PlainRESTClientTableOperation(
            metalake_name, _rest_client
        )
        self._schema_operation = PlainRESTClientSchemaOperation(
            metalake_name, _rest_client
        )
        self._topic_operation = PlainRESTClientTopicOperation(
            metalake_name, _rest_client
        )
        self._model_operation = PlainRESTClientModelOperation(
            metalake_name, _rest_client
        )
        self._domain_operation = PlainRESTClientDomainOperation(
            metalake_name, _rest_client
        )
        self._tag_operation = PlainRESTClientTagOperation(
            metalake_name, _rest_client
        )
        self._fileset_operation = PlainRESTClientFilesetOperation(
            metalake_name, _rest_client
        )
        self._job_operation = PlainRESTClientJobOperation(
            metalake_name, _rest_client
        )
        self._policy_operation = PlainRESTClientPolicyOperation(
            metalake_name, _rest_client
        )
        self._statistic_operation = PlainRESTClientStatisticOperation(
            metalake_name, _rest_client
        )
        self._partition_operation = PlainRESTClientPartitionOperation(
            metalake_name, _rest_client
        )
        self._view_operation = PlainRESTClientViewOperation(
            metalake_name, _rest_client
        )
        self._semantic_model_operation = PlainRESTClientSemanticModelOperation(
            metalake_name, _rest_client
        )
        # Not metalake-scoped: addresses the server's top-level endpoint.
        self._metalake_operation = PlainRESTClientMetalakeOperation(
            _rest_client
        )

    async def close(self) -> None:
        """Close the shared httpx client and release its connection pool."""
        await self._rest_client.aclose()

    def as_metalake_operation(self) -> MetalakeOperation:
        return self._metalake_operation

    def as_catalog_operation(self) -> CatalogOperation:
        return self._catalog_operation

    def as_table_operation(self) -> TableOperation:
        return self._table_operation

    def as_schema_operation(self) -> SchemaOperation:
        return self._schema_operation

    def as_topic_operation(self) -> TopicOperation:
        return self._topic_operation

    def as_model_operation(self) -> ModelOperation:
        return self._model_operation

    def as_fileset_operation(self):
        return self._fileset_operation

    def as_tag_operation(self) -> TagOperation:
        return self._tag_operation

    def as_job_operation(self) -> JobOperation:
        return self._job_operation

    def as_statistic_operation(self):
        return self._statistic_operation

    def as_policy_operation(self) -> PolicyOperation:
        return self._policy_operation

    def as_partition_operation(self):
        return self._partition_operation

    def as_view_operation(self):
        return self._view_operation

    def as_semantic_model_operation(self) -> SemanticModelOperation:
        return self._semantic_model_operation

    def as_domain_operation(self) -> DomainOperation:
        return self._domain_operation