From ce445c6707de17bff119d58ae74b1542f8dcb94d Mon Sep 17 00:00:00 2001 From: chalmer lowe Date: Tue, 1 Dec 2026 10:29:04 -0500 Subject: [PATCH] fix(documentai-toolbox): honor universe_domain and client_options for regional Document AI endpoints --- .../converters/converter.py | 11 +- .../utilities/gcs_utilities.py | 77 ++++++++- .../documentai_toolbox/wrappers/document.py | 16 +- .../tests/unit/test_universe_domain.py | 156 ++++++++++++++++++ 4 files changed, 254 insertions(+), 6 deletions(-) create mode 100644 packages/google-cloud-documentai-toolbox/tests/unit/test_universe_domain.py diff --git a/packages/google-cloud-documentai-toolbox/google/cloud/documentai_toolbox/converters/converter.py b/packages/google-cloud-documentai-toolbox/google/cloud/documentai_toolbox/converters/converter.py index 8de74c108001..2dc69f755dce 100644 --- a/packages/google-cloud-documentai-toolbox/google/cloud/documentai_toolbox/converters/converter.py +++ b/packages/google-cloud-documentai-toolbox/google/cloud/documentai_toolbox/converters/converter.py @@ -17,8 +17,9 @@ import os import time +from collections.abc import Mapping from concurrent import futures -from typing import Dict, List, Optional, Set, Tuple +from typing import Any, Dict, List, Optional, Set, Tuple, Union from google.api_core.client_options import ClientOptions @@ -37,6 +38,7 @@ def _get_base_ocr( mime_type: str, field_mask: Optional[str] = None, processor_version_id: Optional[str] = None, + client_options: Optional[Union[ClientOptions, Mapping[str, Any]]] = None, ) -> documentai.Document: r"""Returns `documentai.Document` from OCR processor. @@ -55,6 +57,9 @@ def _get_base_ocr( Optional. Specifies which fields to include in the `Document` output. processor_version_id (Optional[str]): Optional. Specifies the processor version to use. + client_options (Optional[Union[ClientOptions, Mapping[str, Any]]]): + Optional. Custom client options (such as ``universe_domain`` or + ``api_endpoint``) for ``DocumentProcessorServiceClient``. Returns: documentai.Document: @@ -62,8 +67,8 @@ def _get_base_ocr( """ client = documentai.DocumentProcessorServiceClient( - client_options=ClientOptions( - api_endpoint=f"{location}-documentai.googleapis.com" + client_options=gcs_utilities._get_documentai_client_options( + location=location, client_options=client_options ), client_info=gcs_utilities._get_client_info(), ) diff --git a/packages/google-cloud-documentai-toolbox/google/cloud/documentai_toolbox/utilities/gcs_utilities.py b/packages/google-cloud-documentai-toolbox/google/cloud/documentai_toolbox/utilities/gcs_utilities.py index d28e643cf086..4d8853f4ff0a 100644 --- a/packages/google-cloud-documentai-toolbox/google/cloud/documentai_toolbox/utilities/gcs_utilities.py +++ b/packages/google-cloud-documentai-toolbox/google/cloud/documentai_toolbox/utilities/gcs_utilities.py @@ -15,11 +15,15 @@ # """Google Cloud Storage utilities.""" +import copy import os import re -from typing import Dict, List, Optional, Tuple +from collections.abc import Mapping +from typing import Any, Dict, List, Optional, Tuple, Union +from google.api_core import client_options as client_options_lib from google.api_core.gapic_v1 import client_info +from google.api_core.universe import EmptyUniverseError from google.cloud import ( # type: ignore[attr-defined] documentai, @@ -28,6 +32,77 @@ ) from google.cloud.documentai_toolbox import constants +_DEFAULT_UNIVERSE = "googleapis.com" +_UNIVERSE_DOMAIN_ENV = "GOOGLE_CLOUD_UNIVERSE_DOMAIN" + + +# TODO(universe-domain): Replace with google.api_core.universe.resolve_client_universe +# once minimum allowed google-api-core version exceeds 2.44.0. +def _resolve_client_universe( + client_options: Optional[ + Union[client_options_lib.ClientOptions, Mapping[str, Any]] + ] = None, +) -> str: + """Resolve universe_domain from client_options, env var, or default.""" + if isinstance(client_options, Mapping): + client_options = client_options_lib.from_dict(client_options) + elif client_options is not None and not isinstance( + client_options, client_options_lib.ClientOptions + ): + raise TypeError( + "client_options must be a ClientOptions instance, Mapping, or " + f"None; got {type(client_options).__name__}." + ) + + options_universe = ( + getattr(client_options, "universe_domain", None) + if client_options is not None + else None + ) + if options_universe is not None: + if not isinstance(options_universe, str): + raise TypeError( + "universe_domain must be a string; " + f"got {type(options_universe).__name__}." + ) + resolved = options_universe.strip() + if not resolved: + raise EmptyUniverseError() + return resolved + + env_universe = os.getenv(_UNIVERSE_DOMAIN_ENV) + if env_universe is not None: + resolved = env_universe.strip() + if not resolved: + raise EmptyUniverseError() + return resolved + + return _DEFAULT_UNIVERSE + + +def _get_documentai_client_options( + location: str, + client_options: Optional[ + Union[client_options_lib.ClientOptions, Mapping[str, Any]] + ] = None, +) -> client_options_lib.ClientOptions: + """Build regional Document AI ClientOptions honoring universe_domain.""" + universe_domain = _resolve_client_universe(client_options) + if client_options is None: + return client_options_lib.ClientOptions( + api_endpoint=f"{location}-documentai.{universe_domain}", + universe_domain=universe_domain, + ) + if isinstance(client_options, Mapping): + opts = client_options_lib.from_dict(client_options) + else: + opts = copy.copy(client_options) + if getattr(opts, "universe_domain", None) is None: + opts.universe_domain = universe_domain + if not opts.api_endpoint: + opts.api_endpoint = f"{location}-documentai.{universe_domain}" + return opts + def _get_client_info(module: Optional[str] = None) -> client_info.ClientInfo: r"""Returns a custom user agent header. diff --git a/packages/google-cloud-documentai-toolbox/google/cloud/documentai_toolbox/wrappers/document.py b/packages/google-cloud-documentai-toolbox/google/cloud/documentai_toolbox/wrappers/document.py index 2e6f3d7d694f..645f25d0e267 100644 --- a/packages/google-cloud-documentai-toolbox/google/cloud/documentai_toolbox/wrappers/document.py +++ b/packages/google-cloud-documentai-toolbox/google/cloud/documentai_toolbox/wrappers/document.py @@ -21,6 +21,7 @@ import glob import os import re +from collections.abc import Mapping from functools import cached_property from typing import Any, Dict, Iterable, Iterator, List, Optional, Type, Union @@ -169,6 +170,7 @@ def _get_batch_process_metadata( operation_name: str, location: Optional[str] = None, timeout: Optional[float] = None, + client_options: Optional[Union[ClientOptions, Mapping[str, Any]]] = None, ) -> documentai.BatchProcessMetadata: r"""Get `BatchProcessMetadata` from a `batch_process_documents()` long-running operation. @@ -183,6 +185,10 @@ def _get_batch_process_metadata( timeout (float): Optional. Default None. Time in seconds to wait for operation to complete. If None, will wait indefinitely. + + client_options (Optional[Union[ClientOptions, Mapping[str, Any]]]): + Optional. Custom client options (such as ``universe_domain`` or + ``api_endpoint``) for ``DocumentProcessorServiceClient``. Returns: documentai.BatchProcessMetadata: Metadata from batch process. @@ -202,8 +208,8 @@ def _get_batch_process_metadata( client = documentai.DocumentProcessorServiceClient( client_info=gcs_utilities._get_client_info(module="get_batch_process_metadata"), - client_options=ClientOptions( - api_endpoint=f"{location}-documentai.googleapis.com" + client_options=gcs_utilities._get_documentai_client_options( + location=location, client_options=client_options ), ) @@ -618,6 +624,7 @@ def from_batch_process_operation( location: str, # pylint: disable=unused-argument operation_name: str, timeout: Optional[float] = None, + client_options: Optional[Union[ClientOptions, Mapping[str, Any]]] = None, ) -> List["Document"]: r"""Loads Documents from Cloud Storage, using the operation name returned from `batch_process_documents()`. @@ -644,6 +651,10 @@ def from_batch_process_operation( Optional. Default None. Time in seconds to wait for operation to complete. If None, will wait indefinitely. + client_options (Optional[Union[ClientOptions, Mapping[str, Any]]]): + Optional. Custom client options (such as ``universe_domain`` or + ``api_endpoint``) for ``DocumentProcessorServiceClient``. + Returns: List[Document]: A list of wrapped documents from gcs. Each document corresponds to an input file. @@ -653,6 +664,7 @@ def from_batch_process_operation( operation_name=operation_name, location=location, timeout=timeout, + client_options=client_options, ) ) diff --git a/packages/google-cloud-documentai-toolbox/tests/unit/test_universe_domain.py b/packages/google-cloud-documentai-toolbox/tests/unit/test_universe_domain.py new file mode 100644 index 000000000000..98c7c9a7d25d --- /dev/null +++ b/packages/google-cloud-documentai-toolbox/tests/unit/test_universe_domain.py @@ -0,0 +1,156 @@ +# Copyright 2026 Google LLC +# +# Licensed 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. + +"""Unit tests for universe_domain endpoint resolution in documentai-toolbox.""" + +from types import MappingProxyType +from unittest import mock + +import pytest +from google.api_core import client_options as client_options_lib +from google.api_core.universe import EmptyUniverseError + +from google.cloud import documentai +from google.cloud.documentai_toolbox.converters import converter +from google.cloud.documentai_toolbox.utilities import gcs_utilities +from google.cloud.documentai_toolbox.wrappers import document + +DEFAULT_UNIVERSE = "googleapis.com" +CUSTOM_UNIVERSE = "apis-tpclp.goog" + + +@pytest.fixture(autouse=True) +def clean_universe_env(monkeypatch): + monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) + + +def test_resolve_client_universe_precedence_and_errors(monkeypatch): + assert gcs_utilities._resolve_client_universe(None) == DEFAULT_UNIVERSE + + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", f" {CUSTOM_UNIVERSE} ") + assert gcs_utilities._resolve_client_universe(None) == CUSTOM_UNIVERSE + + opts = client_options_lib.ClientOptions(universe_domain="explicit.goog") + assert gcs_utilities._resolve_client_universe(opts) == "explicit.goog" + + mapping = MappingProxyType({"universe_domain": "mapping.goog"}) + assert gcs_utilities._resolve_client_universe(mapping) == "mapping.goog" + + with pytest.raises(EmptyUniverseError): + gcs_utilities._resolve_client_universe({"universe_domain": " "}) + + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", " ") + with pytest.raises(EmptyUniverseError): + gcs_utilities._resolve_client_universe(None) + + with pytest.raises(TypeError, match="ClientOptions instance, Mapping, or None"): + gcs_utilities._resolve_client_universe("invalid") # type: ignore[arg-type] + + with pytest.raises(TypeError, match="universe_domain must be a string"): + gcs_utilities._resolve_client_universe( + client_options_lib.ClientOptions(universe_domain=123) # type: ignore[arg-type] + ) + + +def test_get_documentai_client_options_respects_env_and_does_not_mutate(monkeypatch): + default_opts = gcs_utilities._get_documentai_client_options("us") + assert default_opts.api_endpoint == "us-documentai.googleapis.com" + assert default_opts.universe_domain == DEFAULT_UNIVERSE + + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", CUSTOM_UNIVERSE) + env_opts = gcs_utilities._get_documentai_client_options("eu") + assert env_opts.api_endpoint == f"eu-documentai.{CUSTOM_UNIVERSE}" + assert env_opts.universe_domain == CUSTOM_UNIVERSE + + caller_opts = client_options_lib.ClientOptions(quota_project_id="qp-1") + derived = gcs_utilities._get_documentai_client_options("us", caller_opts) + assert derived is not caller_opts + assert derived.api_endpoint == f"us-documentai.{CUSTOM_UNIVERSE}" + assert derived.universe_domain == CUSTOM_UNIVERSE + assert derived.quota_project_id == "qp-1" + assert caller_opts.api_endpoint is None + assert caller_opts.universe_domain is None + + explicit_endpoint = MappingProxyType({"api_endpoint": "custom.endpoint:443"}) + derived_ep = gcs_utilities._get_documentai_client_options("us", explicit_endpoint) + assert derived_ep.api_endpoint == "custom.endpoint:443" + assert derived_ep.universe_domain == CUSTOM_UNIVERSE + + +@mock.patch("google.cloud.documentai_toolbox.converters.converter.documentai") +def test_get_base_ocr_honors_universe_domain(mock_docai, monkeypatch): + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", CUSTOM_UNIVERSE) + mock_client = mock_docai.DocumentProcessorServiceClient.return_value + mock_client.process_document.return_value.document = "Done" + + actual = converter._get_base_ocr( + project_id="proj", + location="us", + processor_id="proc", + file_bytes=b"pdf", + mime_type="application/pdf", + ) + + assert actual == "Done" + passed_opts = mock_docai.DocumentProcessorServiceClient.call_args.kwargs[ + "client_options" + ] + assert passed_opts.api_endpoint == f"us-documentai.{CUSTOM_UNIVERSE}" + assert passed_opts.universe_domain == CUSTOM_UNIVERSE + + +@mock.patch("google.cloud.documentai_toolbox.wrappers.document.documentai") +def test_get_batch_process_metadata_honors_universe_domain(mock_docai, monkeypatch): + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", CUSTOM_UNIVERSE) + mock_client = mock_docai.DocumentProcessorServiceClient.return_value + metadata = documentai.BatchProcessMetadata( + state=documentai.BatchProcessMetadata.State.SUCCEEDED, + ) + mock_client.get_operation.return_value = mock.Mock( + done=True, + metadata=mock.Mock( + type_url="type.googleapis.com/google.cloud.documentai.v1.BatchProcessMetadata", + value=documentai.BatchProcessMetadata.serialize(metadata), + ), + ) + + document._get_batch_process_metadata("projects/123/locations/eu/operations/456") + + passed_opts = mock_docai.DocumentProcessorServiceClient.call_args.kwargs[ + "client_options" + ] + assert passed_opts.api_endpoint == f"eu-documentai.{CUSTOM_UNIVERSE}" + assert passed_opts.universe_domain == CUSTOM_UNIVERSE + + +@mock.patch( + "google.cloud.documentai_toolbox.wrappers.document._get_batch_process_metadata" +) +@mock.patch.object(document.Document, "from_batch_process_metadata", return_value=[]) +def test_from_batch_process_operation_forwards_client_options( + mock_from_meta, mock_get_meta +): + opts = client_options_lib.ClientOptions(universe_domain=CUSTOM_UNIVERSE) + document.Document.from_batch_process_operation( + location="us", + operation_name="projects/123/locations/us/operations/456", + client_options=opts, + ) + mock_get_meta.assert_called_once_with( + operation_name="projects/123/locations/us/operations/456", + location="us", + timeout=None, + client_options=opts, + ) + mock_from_meta.assert_called_once()