Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.

Expand All @@ -55,15 +57,18 @@ 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:
A documentai.Document from OCR processor.

"""
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(),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
)
Comment on lines +47 to +61

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Converting client_options from a Mapping to a ClientOptions instance via client_options_lib.from_dict just to extract the universe_domain is inefficient and redundant, as it is converted again in _get_documentai_client_options. Additionally, if an older version of google-api-core is used where from_dict does not support or parse universe_domain, the value would be lost.

Instead, we can directly retrieve universe_domain from the Mapping or ClientOptions object without performing the redundant conversion.

Suggested change
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
)
options_universe = None
if isinstance(client_options, Mapping):
options_universe = client_options.get("universe_domain")
elif isinstance(client_options, client_options_lib.ClientOptions):
options_universe = getattr(client_options, "universe_domain", None)
elif client_options is not None:
raise TypeError(
"client_options must be a ClientOptions instance, Mapping, or "
f"None; got {type(client_options).__name__}."
)

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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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.

Expand All @@ -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.
Expand All @@ -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
),
)

Expand Down Expand Up @@ -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()`.

Expand All @@ -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.
Expand All @@ -653,6 +664,7 @@ def from_batch_process_operation(
operation_name=operation_name,
location=location,
timeout=timeout,
client_options=client_options,
)
)

Expand Down
Original file line number Diff line number Diff line change
@@ -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()
Loading