Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/apiclient/__pycache__/__init__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/__pycache__/__init__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/__pycache__/about.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/__pycache__/benchmark.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/tests/__init__.py +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/tests/__pycache__/common.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/tests/__pycache__/test_dotv.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/tests/__pycache__/test_gemm.cpython-310.pyc +0 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/tests/common.py +85 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/tests/test_dotv.py +38 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/tests/test_gemm.py +75 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/__init__.py +41 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/_python_package_support.py +227 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/_python_version_support.py +276 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/_rest_streaming_base.py +118 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/bidi.py +735 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/bidi_async.py +244 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/bidi_base.py +88 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/client_info.py +114 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/client_logging.py +144 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/client_options.py +160 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/datetime_helpers.py +298 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/exceptions.py +669 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/extended_operation.py +225 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/general_helpers.py +52 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/grpc_helpers.py +614 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/grpc_helpers_async.py +348 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/iam.py +427 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/operation.py +365 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/operation_async.py +225 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/page_iterator.py +571 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/page_iterator_async.py +285 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/path_template.py +346 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/protobuf_helpers.py +371 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/py.typed +2 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/rest_helpers.py +109 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/rest_streaming.py +66 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/rest_streaming_async.py +89 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/retry_async.py +34 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/timeout.py +294 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/universe.py +82 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/version.py +15 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/version_header.py +29 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/auth/__init__.py +34 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/auth/_agent_identity_utils.py +272 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/auth/_cache.py +64 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/auth/_cloud_sdk.py +153 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/auth/_credentials_async.py +171 -0
- data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/auth/_credentials_base.py +75 -0
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/apiclient/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (696 Bytes). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (217 Bytes). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/__pycache__/about.cpython-310.pyc
ADDED
|
Binary file (506 Bytes). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/__pycache__/benchmark.cpython-310.pyc
ADDED
|
Binary file (2.79 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/tests/__init__.py
ADDED
|
File without changes
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (184 Bytes). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/tests/__pycache__/common.cpython-310.pyc
ADDED
|
Binary file (3.27 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/tests/__pycache__/test_dotv.cpython-310.pyc
ADDED
|
Binary file (1.13 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/tests/__pycache__/test_gemm.cpython-310.pyc
ADDED
|
Binary file (2.25 kB). View file
|
|
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/tests/common.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright ExplsionAI GmbH, released under BSD.
|
| 2 |
+
from __future__ import print_function
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
|
| 6 |
+
np.random.seed(0)
|
| 7 |
+
from numpy.testing import assert_allclose
|
| 8 |
+
|
| 9 |
+
from hypothesis import assume
|
| 10 |
+
from hypothesis.strategies import tuples, integers, floats
|
| 11 |
+
from hypothesis.extra.numpy import arrays
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def lengths(lo=1, hi=10):
|
| 15 |
+
return integers(min_value=lo, max_value=hi)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def shapes(min_rows=1, max_rows=100, min_cols=1, max_cols=100):
|
| 19 |
+
return tuples(lengths(lo=min_rows, hi=max_rows), lengths(lo=min_cols, hi=max_cols))
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def ndarrays_of_shape(shape, lo=-1000.0, hi=1000.0, dtype="float64"):
|
| 23 |
+
width = 64 if dtype == "float64" else 32
|
| 24 |
+
return arrays(
|
| 25 |
+
dtype, shape=shape, elements=floats(min_value=lo, max_value=hi, width=width)
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def ndarrays(
|
| 30 |
+
min_len=0, max_len=10, min_val=-10000000.0, max_val=1000000.0, dtype="float64"
|
| 31 |
+
):
|
| 32 |
+
return lengths(lo=min_len, hi=max_len).flatmap(
|
| 33 |
+
lambda n: ndarrays_of_shape(n, lo=min_val, hi=max_val, dtype=dtype)
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def matrices(
|
| 38 |
+
min_rows=1,
|
| 39 |
+
max_rows=10,
|
| 40 |
+
min_cols=1,
|
| 41 |
+
max_cols=10,
|
| 42 |
+
min_value=-10000000.0,
|
| 43 |
+
max_value=1000000.0,
|
| 44 |
+
dtype="float64",
|
| 45 |
+
):
|
| 46 |
+
return shapes(
|
| 47 |
+
min_rows=min_rows, max_rows=max_rows, min_cols=min_cols, max_cols=max_cols
|
| 48 |
+
).flatmap(lambda mn: ndarrays_of_shape(mn, lo=min_value, hi=max_value, dtype=dtype))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def positive_ndarrays(min_len=0, max_len=10, max_val=100000.0, dtype="float64"):
|
| 52 |
+
return ndarrays(
|
| 53 |
+
min_len=min_len, max_len=max_len, min_val=0, max_val=max_val, dtype=dtype
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def negative_ndarrays(min_len=0, max_len=10, min_val=-100000.0, dtype="float64"):
|
| 58 |
+
return ndarrays(
|
| 59 |
+
min_len=min_len, max_len=max_len, min_val=min_val, max_val=-1e-10, dtype=dtype
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def parse_layer(layer_data):
|
| 64 |
+
# Get the first row, excluding the first column
|
| 65 |
+
x = layer_data[0, 1:]
|
| 66 |
+
# Get the first column, excluding the first row
|
| 67 |
+
# .ascontiguousarray is support important here!!!!
|
| 68 |
+
b = np.ascontiguousarray(layer_data[1:, 0], dtype="float64")
|
| 69 |
+
# Slice out the row and the column used for the X and the bias
|
| 70 |
+
W = layer_data[1:, 1:]
|
| 71 |
+
assert x.ndim == 1
|
| 72 |
+
assert b.ndim == 1
|
| 73 |
+
assert b.shape[0] == W.shape[0]
|
| 74 |
+
assert x.shape[0] == W.shape[1]
|
| 75 |
+
assume(not np.isnan(W.sum()))
|
| 76 |
+
assume(not np.isnan(x.sum()))
|
| 77 |
+
assume(not np.isnan(b.sum()))
|
| 78 |
+
assume(not any(np.isinf(val) for val in W.flatten()))
|
| 79 |
+
assume(not any(np.isinf(val) for val in x))
|
| 80 |
+
assume(not any(np.isinf(val) for val in b))
|
| 81 |
+
return x, b, W
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def split_row(layer_data):
|
| 85 |
+
return (layer_data[0, :], layer_data[:, :])
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/tests/test_dotv.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright ExplosionAI GmbH, released under BSD.
|
| 2 |
+
from __future__ import division
|
| 3 |
+
from hypothesis import given, assume
|
| 4 |
+
|
| 5 |
+
from blis.tests.common import *
|
| 6 |
+
from blis.py import dotv
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@given(
|
| 10 |
+
ndarrays(min_len=10, max_len=100, min_val=-100.0, max_val=100.0, dtype="float64"),
|
| 11 |
+
ndarrays(min_len=10, max_len=100, min_val=-100.0, max_val=100.0, dtype="float64"),
|
| 12 |
+
)
|
| 13 |
+
def test_memoryview_double_noconj(A, B):
|
| 14 |
+
if len(A) < len(B):
|
| 15 |
+
B = B[: len(A)]
|
| 16 |
+
else:
|
| 17 |
+
A = A[: len(B)]
|
| 18 |
+
assume(A is not None)
|
| 19 |
+
assume(B is not None)
|
| 20 |
+
numpy_result = A.dot(B)
|
| 21 |
+
result = dotv(A, B)
|
| 22 |
+
assert_allclose([numpy_result], result, atol=1e-4, rtol=1e-4)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@given(
|
| 26 |
+
ndarrays(min_len=10, max_len=100, min_val=-100.0, max_val=100.0, dtype="float32"),
|
| 27 |
+
ndarrays(min_len=10, max_len=100, min_val=-100.0, max_val=100.0, dtype="float32"),
|
| 28 |
+
)
|
| 29 |
+
def test_memoryview_float_noconj(A, B):
|
| 30 |
+
if len(A) < len(B):
|
| 31 |
+
B = B[: len(A)]
|
| 32 |
+
else:
|
| 33 |
+
A = A[: len(B)]
|
| 34 |
+
assume(A is not None)
|
| 35 |
+
assume(B is not None)
|
| 36 |
+
numpy_result = A.dot(B)
|
| 37 |
+
result = dotv(A, B)
|
| 38 |
+
assert_allclose([numpy_result], result, atol=1e-4, rtol=1e-3)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/blis/tests/test_gemm.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright ExplosionAI GmbH, released under BSD.
|
| 2 |
+
from __future__ import division
|
| 3 |
+
|
| 4 |
+
from hypothesis import given, assume
|
| 5 |
+
from math import sqrt, floor
|
| 6 |
+
|
| 7 |
+
from blis.tests.common import *
|
| 8 |
+
from blis.py import gemm
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _stretch_matrix(data, m, n):
|
| 12 |
+
orig_len = len(data)
|
| 13 |
+
orig_m = m
|
| 14 |
+
orig_n = n
|
| 15 |
+
ratio = sqrt(len(data) / (m * n))
|
| 16 |
+
m = int(floor(m * ratio))
|
| 17 |
+
n = int(floor(n * ratio))
|
| 18 |
+
data = np.ascontiguousarray(data[: m * n], dtype=data.dtype)
|
| 19 |
+
return data.reshape((m, n)), m, n
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _reshape_for_gemm(
|
| 23 |
+
A, B, a_rows, a_cols, out_cols, dtype, trans_a=False, trans_b=False
|
| 24 |
+
):
|
| 25 |
+
A, a_rows, a_cols = _stretch_matrix(A, a_rows, a_cols)
|
| 26 |
+
if len(B) < a_cols or a_cols < 1:
|
| 27 |
+
return (None, None, None)
|
| 28 |
+
b_cols = int(floor(len(B) / a_cols))
|
| 29 |
+
B = np.ascontiguousarray(B.flatten()[: a_cols * b_cols], dtype=dtype)
|
| 30 |
+
B = B.reshape((a_cols, b_cols))
|
| 31 |
+
out_cols = B.shape[1]
|
| 32 |
+
C = np.zeros(shape=(A.shape[0], B.shape[1]), dtype=dtype)
|
| 33 |
+
if trans_a:
|
| 34 |
+
A = np.ascontiguousarray(A.T, dtype=dtype)
|
| 35 |
+
return A, B, C
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@given(
|
| 39 |
+
ndarrays(min_len=10, max_len=100, min_val=-100.0, max_val=100.0, dtype="float64"),
|
| 40 |
+
ndarrays(min_len=10, max_len=100, min_val=-100.0, max_val=100.0, dtype="float64"),
|
| 41 |
+
integers(min_value=2, max_value=1000),
|
| 42 |
+
integers(min_value=2, max_value=1000),
|
| 43 |
+
integers(min_value=2, max_value=1000),
|
| 44 |
+
)
|
| 45 |
+
def test_memoryview_double_notrans(A, B, a_rows, a_cols, out_cols):
|
| 46 |
+
A, B, C = _reshape_for_gemm(A, B, a_rows, a_cols, out_cols, "float64")
|
| 47 |
+
assume(A is not None)
|
| 48 |
+
assume(B is not None)
|
| 49 |
+
assume(C is not None)
|
| 50 |
+
assume(A.size >= 1)
|
| 51 |
+
assume(B.size >= 1)
|
| 52 |
+
assume(C.size >= 1)
|
| 53 |
+
gemm(A, B, out=C)
|
| 54 |
+
numpy_result = A.dot(B)
|
| 55 |
+
assert_allclose(numpy_result, C, atol=1e-4, rtol=1e-4)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@given(
|
| 59 |
+
ndarrays(min_len=10, max_len=100, min_val=-100.0, max_val=100.0, dtype="float32"),
|
| 60 |
+
ndarrays(min_len=10, max_len=100, min_val=-100.0, max_val=100.0, dtype="float32"),
|
| 61 |
+
integers(min_value=2, max_value=1000),
|
| 62 |
+
integers(min_value=2, max_value=1000),
|
| 63 |
+
integers(min_value=2, max_value=1000),
|
| 64 |
+
)
|
| 65 |
+
def test_memoryview_float_notrans(A, B, a_rows, a_cols, out_cols):
|
| 66 |
+
A, B, C = _reshape_for_gemm(A, B, a_rows, a_cols, out_cols, dtype="float32")
|
| 67 |
+
assume(A is not None)
|
| 68 |
+
assume(B is not None)
|
| 69 |
+
assume(C is not None)
|
| 70 |
+
assume(A.size >= 1)
|
| 71 |
+
assume(B.size >= 1)
|
| 72 |
+
assume(C.size >= 1)
|
| 73 |
+
gemm(A, B, out=C)
|
| 74 |
+
numpy_result = A.dot(B)
|
| 75 |
+
assert_allclose(numpy_result, C, atol=1e-3, rtol=1e-3)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/__init__.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Google API Core.
|
| 16 |
+
|
| 17 |
+
This package contains common code and utilities used by Google client libraries.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from google.api_core import _python_package_support
|
| 21 |
+
from google.api_core import _python_version_support
|
| 22 |
+
from google.api_core import version as api_core_version
|
| 23 |
+
|
| 24 |
+
__version__ = api_core_version.__version__
|
| 25 |
+
|
| 26 |
+
# NOTE: Until dependent artifacts require this version of
|
| 27 |
+
# google.api_core, the functionality below must be made available
|
| 28 |
+
# manually in those artifacts.
|
| 29 |
+
|
| 30 |
+
# expose dependency checks for external callers
|
| 31 |
+
check_python_version = _python_version_support.check_python_version
|
| 32 |
+
check_dependency_versions = _python_package_support.check_dependency_versions
|
| 33 |
+
parse_version_to_tuple = _python_package_support.parse_version_to_tuple
|
| 34 |
+
warn_deprecation_for_versions_less_than = (
|
| 35 |
+
_python_package_support.warn_deprecation_for_versions_less_than
|
| 36 |
+
)
|
| 37 |
+
DependencyConstraint = _python_package_support.DependencyConstraint
|
| 38 |
+
|
| 39 |
+
# perform version checks against api_core, and emit warnings if needed
|
| 40 |
+
check_python_version(package="google.api_core")
|
| 41 |
+
check_dependency_versions("google.api_core")
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/_python_package_support.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Code to check versions of dependencies used by Google Cloud Client Libraries."""
|
| 16 |
+
|
| 17 |
+
import warnings
|
| 18 |
+
from typing import Optional, Tuple
|
| 19 |
+
|
| 20 |
+
from collections import namedtuple
|
| 21 |
+
|
| 22 |
+
from ._python_version_support import (
|
| 23 |
+
_flatten_message,
|
| 24 |
+
_get_distribution_and_import_packages,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
from importlib import metadata
|
| 28 |
+
|
| 29 |
+
ParsedVersion = Tuple[int, ...]
|
| 30 |
+
|
| 31 |
+
# Here we list all the packages for which we want to issue warnings
|
| 32 |
+
# about deprecated and unsupported versions.
|
| 33 |
+
DependencyConstraint = namedtuple(
|
| 34 |
+
"DependencyConstraint",
|
| 35 |
+
["package_name", "minimum_fully_supported_version", "recommended_version"],
|
| 36 |
+
)
|
| 37 |
+
_PACKAGE_DEPENDENCY_WARNINGS = [
|
| 38 |
+
DependencyConstraint(
|
| 39 |
+
"google.protobuf",
|
| 40 |
+
minimum_fully_supported_version="4.25.8",
|
| 41 |
+
recommended_version="6.x",
|
| 42 |
+
)
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
DependencyVersion = namedtuple("DependencyVersion", ["version", "version_string"])
|
| 47 |
+
# Version string we provide in a DependencyVersion when we can't determine the version of a
|
| 48 |
+
# package.
|
| 49 |
+
UNKNOWN_VERSION_STRING = "--"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def parse_version_to_tuple(version_string: str) -> ParsedVersion:
|
| 53 |
+
"""Safely converts a semantic version string to a comparable tuple of integers.
|
| 54 |
+
|
| 55 |
+
Example: "4.25.8" -> (4, 25, 8)
|
| 56 |
+
Ignores non-numeric parts and handles common version formats.
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
version_string: Version string in the format "x.y.z" or "x.y.z<suffix>"
|
| 60 |
+
|
| 61 |
+
Returns:
|
| 62 |
+
Tuple of integers for the parsed version string.
|
| 63 |
+
"""
|
| 64 |
+
parts = []
|
| 65 |
+
for part in version_string.split("."):
|
| 66 |
+
try:
|
| 67 |
+
parts.append(int(part))
|
| 68 |
+
except ValueError:
|
| 69 |
+
# If it's a non-numeric part (e.g., '1.0.0b1' -> 'b1'), stop here.
|
| 70 |
+
# This is a simplification compared to 'packaging.parse_version', but sufficient
|
| 71 |
+
# for comparing strictly numeric semantic versions.
|
| 72 |
+
break
|
| 73 |
+
return tuple(parts)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def get_dependency_version(
|
| 77 |
+
dependency_name: str,
|
| 78 |
+
) -> DependencyVersion:
|
| 79 |
+
"""Get the parsed version of an installed package dependency.
|
| 80 |
+
|
| 81 |
+
This function checks for an installed package and returns its version
|
| 82 |
+
as a comparable tuple of integers object for safe comparison.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
dependency_name: The distribution name of the package (e.g., 'requests').
|
| 86 |
+
|
| 87 |
+
Returns:
|
| 88 |
+
A DependencyVersion namedtuple with `version` (a tuple of integers) and
|
| 89 |
+
`version_string` attributes, or `DependencyVersion(None,
|
| 90 |
+
UNKNOWN_VERSION_STRING)` if the package is not found or
|
| 91 |
+
another error occurs during version discovery.
|
| 92 |
+
|
| 93 |
+
"""
|
| 94 |
+
try:
|
| 95 |
+
version_string: str = metadata.version(dependency_name)
|
| 96 |
+
parsed_version = parse_version_to_tuple(version_string)
|
| 97 |
+
return DependencyVersion(parsed_version, version_string)
|
| 98 |
+
except Exception:
|
| 99 |
+
# Catch exceptions from metadata.version() (e.g., PackageNotFoundError)
|
| 100 |
+
# or errors during parse_version_to_tuple
|
| 101 |
+
return DependencyVersion(None, UNKNOWN_VERSION_STRING)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def warn_deprecation_for_versions_less_than(
|
| 105 |
+
consumer_import_package: str,
|
| 106 |
+
dependency_import_package: str,
|
| 107 |
+
minimum_fully_supported_version: str,
|
| 108 |
+
recommended_version: Optional[str] = None,
|
| 109 |
+
message_template: Optional[str] = None,
|
| 110 |
+
):
|
| 111 |
+
"""Issue any needed deprecation warnings for `dependency_import_package`.
|
| 112 |
+
|
| 113 |
+
If `dependency_import_package` is installed at a version less than
|
| 114 |
+
`minimum_fully_supported_version`, this issues a warning using either a
|
| 115 |
+
default `message_template` or one provided by the user. The
|
| 116 |
+
default `message_template` informs the user that they will not receive
|
| 117 |
+
future updates for `consumer_import_package` if
|
| 118 |
+
`dependency_import_package` is somehow pinned to a version lower
|
| 119 |
+
than `minimum_fully_supported_version`.
|
| 120 |
+
|
| 121 |
+
Args:
|
| 122 |
+
consumer_import_package: The import name of the package that
|
| 123 |
+
needs `dependency_import_package`.
|
| 124 |
+
dependency_import_package: The import name of the dependency to check.
|
| 125 |
+
minimum_fully_supported_version: The dependency_import_package version number
|
| 126 |
+
below which a deprecation warning will be logged.
|
| 127 |
+
recommended_version: If provided, the recommended next version, which
|
| 128 |
+
could be higher than `minimum_fully_supported_version`.
|
| 129 |
+
message_template: A custom default message template to replace
|
| 130 |
+
the default. This `message_template` is treated as an
|
| 131 |
+
f-string, where the following variables are defined:
|
| 132 |
+
`dependency_import_package`, `consumer_import_package` and
|
| 133 |
+
`dependency_distribution_package` and
|
| 134 |
+
`consumer_distribution_package` and `dependency_package`,
|
| 135 |
+
`consumer_package` , which contain the import packages, the
|
| 136 |
+
distribution packages, and pretty string with both the
|
| 137 |
+
distribution and import packages for the dependency and the
|
| 138 |
+
consumer, respectively; and `minimum_fully_supported_version`,
|
| 139 |
+
`version_used`, and `version_used_string`, which refer to supported
|
| 140 |
+
and currently-used versions of the dependency.
|
| 141 |
+
|
| 142 |
+
"""
|
| 143 |
+
if (
|
| 144 |
+
not consumer_import_package
|
| 145 |
+
or not dependency_import_package
|
| 146 |
+
or not minimum_fully_supported_version
|
| 147 |
+
): # pragma: NO COVER
|
| 148 |
+
return
|
| 149 |
+
|
| 150 |
+
dependency_version = get_dependency_version(dependency_import_package)
|
| 151 |
+
if not dependency_version.version:
|
| 152 |
+
return
|
| 153 |
+
|
| 154 |
+
if dependency_version.version < parse_version_to_tuple(
|
| 155 |
+
minimum_fully_supported_version
|
| 156 |
+
):
|
| 157 |
+
(
|
| 158 |
+
dependency_package,
|
| 159 |
+
dependency_distribution_package,
|
| 160 |
+
) = _get_distribution_and_import_packages(dependency_import_package)
|
| 161 |
+
(
|
| 162 |
+
consumer_package,
|
| 163 |
+
consumer_distribution_package,
|
| 164 |
+
) = _get_distribution_and_import_packages(consumer_import_package)
|
| 165 |
+
|
| 166 |
+
recommendation = (
|
| 167 |
+
" (we recommend {recommended_version})" if recommended_version else ""
|
| 168 |
+
)
|
| 169 |
+
message_template = message_template or _flatten_message(
|
| 170 |
+
"""
|
| 171 |
+
DEPRECATION: Package {consumer_package} depends on
|
| 172 |
+
{dependency_package}, currently installed at version
|
| 173 |
+
{version_used_string}. Future updates to
|
| 174 |
+
{consumer_package} will require {dependency_package} at
|
| 175 |
+
version {minimum_fully_supported_version} or
|
| 176 |
+
higher{recommendation}. Please ensure that either (a) your
|
| 177 |
+
Python environment doesn't pin the version of
|
| 178 |
+
{dependency_package}, so that updates to
|
| 179 |
+
{consumer_package} can require the higher version, or (b)
|
| 180 |
+
you manually update your Python environment to use at
|
| 181 |
+
least version {minimum_fully_supported_version} of
|
| 182 |
+
{dependency_package}.
|
| 183 |
+
"""
|
| 184 |
+
)
|
| 185 |
+
warnings.warn(
|
| 186 |
+
message_template.format(
|
| 187 |
+
consumer_import_package=consumer_import_package,
|
| 188 |
+
dependency_import_package=dependency_import_package,
|
| 189 |
+
consumer_distribution_package=consumer_distribution_package,
|
| 190 |
+
dependency_distribution_package=dependency_distribution_package,
|
| 191 |
+
dependency_package=dependency_package,
|
| 192 |
+
consumer_package=consumer_package,
|
| 193 |
+
minimum_fully_supported_version=minimum_fully_supported_version,
|
| 194 |
+
recommendation=recommendation,
|
| 195 |
+
version_used=dependency_version.version,
|
| 196 |
+
version_used_string=dependency_version.version_string,
|
| 197 |
+
),
|
| 198 |
+
FutureWarning,
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def check_dependency_versions(
|
| 203 |
+
consumer_import_package: str, *package_dependency_warnings: DependencyConstraint
|
| 204 |
+
):
|
| 205 |
+
"""Bundle checks for all package dependencies.
|
| 206 |
+
|
| 207 |
+
This function can be called by all consumers of google.api_core,
|
| 208 |
+
to emit needed deprecation warnings for any of their
|
| 209 |
+
dependencies. The dependencies to check can be passed as arguments, or if
|
| 210 |
+
none are provided, it will default to the list in
|
| 211 |
+
`_PACKAGE_DEPENDENCY_WARNINGS`.
|
| 212 |
+
|
| 213 |
+
Args:
|
| 214 |
+
consumer_import_package: The distribution name of the calling package, whose
|
| 215 |
+
dependencies we're checking.
|
| 216 |
+
*package_dependency_warnings: A variable number of DependencyConstraint
|
| 217 |
+
objects, each specifying a dependency to check.
|
| 218 |
+
"""
|
| 219 |
+
if not package_dependency_warnings:
|
| 220 |
+
package_dependency_warnings = tuple(_PACKAGE_DEPENDENCY_WARNINGS)
|
| 221 |
+
for package_info in package_dependency_warnings:
|
| 222 |
+
warn_deprecation_for_versions_less_than(
|
| 223 |
+
consumer_import_package,
|
| 224 |
+
package_info.package_name,
|
| 225 |
+
package_info.minimum_fully_supported_version,
|
| 226 |
+
recommended_version=package_info.recommended_version,
|
| 227 |
+
)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/_python_version_support.py
ADDED
|
@@ -0,0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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Code to check Python versions supported by Google Cloud Client Libraries."""
|
| 16 |
+
|
| 17 |
+
import datetime
|
| 18 |
+
import enum
|
| 19 |
+
import functools
|
| 20 |
+
import logging
|
| 21 |
+
import warnings
|
| 22 |
+
import sys
|
| 23 |
+
import textwrap
|
| 24 |
+
from typing import Any, List, NamedTuple, Optional, Dict, Tuple
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
_LOGGER = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class PythonVersionStatus(enum.Enum):
|
| 31 |
+
"""Support status of a Python version in this client library artifact release.
|
| 32 |
+
|
| 33 |
+
"Support", in this context, means that this release of a client library
|
| 34 |
+
artifact is configured to run on the currently configured version of
|
| 35 |
+
Python.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
PYTHON_VERSION_STATUS_UNSPECIFIED = "PYTHON_VERSION_STATUS_UNSPECIFIED"
|
| 39 |
+
|
| 40 |
+
PYTHON_VERSION_SUPPORTED = "PYTHON_VERSION_SUPPORTED"
|
| 41 |
+
"""This Python version is fully supported, so the artifact running on this
|
| 42 |
+
version will have all features and bug fixes."""
|
| 43 |
+
|
| 44 |
+
PYTHON_VERSION_DEPRECATED = "PYTHON_VERSION_DEPRECATED"
|
| 45 |
+
"""This Python version is still supported, but support will end within a
|
| 46 |
+
year. At that time, there will be no more releases for this artifact
|
| 47 |
+
running under this Python version."""
|
| 48 |
+
|
| 49 |
+
PYTHON_VERSION_EOL = "PYTHON_VERSION_EOL"
|
| 50 |
+
"""This Python version has reached its end of life in the Python community
|
| 51 |
+
(see https://devguide.python.org/versions/), and this artifact will cease
|
| 52 |
+
supporting this Python version within the next few releases."""
|
| 53 |
+
|
| 54 |
+
PYTHON_VERSION_UNSUPPORTED = "PYTHON_VERSION_UNSUPPORTED"
|
| 55 |
+
"""This release of the client library artifact may not be the latest, since
|
| 56 |
+
current releases no longer support this Python version."""
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class VersionInfo(NamedTuple):
|
| 60 |
+
"""Hold release and support date information for a Python version."""
|
| 61 |
+
|
| 62 |
+
version: str
|
| 63 |
+
python_beta: Optional[datetime.date]
|
| 64 |
+
python_start: datetime.date
|
| 65 |
+
python_eol: datetime.date
|
| 66 |
+
gapic_start: Optional[datetime.date] = None # unused
|
| 67 |
+
gapic_deprecation: Optional[datetime.date] = None
|
| 68 |
+
gapic_end: Optional[datetime.date] = None
|
| 69 |
+
dep_unpatchable_cve: Optional[datetime.date] = None # unused
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
PYTHON_VERSIONS: List[VersionInfo] = [
|
| 73 |
+
# Refer to https://devguide.python.org/versions/ and the PEPs linked therefrom.
|
| 74 |
+
VersionInfo(
|
| 75 |
+
version="3.9",
|
| 76 |
+
python_beta=datetime.date(2020, 5, 18),
|
| 77 |
+
python_start=datetime.date(2020, 10, 5),
|
| 78 |
+
python_eol=datetime.date(2025, 10, 5),
|
| 79 |
+
gapic_end=datetime.date(2025, 10, 5) + datetime.timedelta(days=90),
|
| 80 |
+
),
|
| 81 |
+
VersionInfo(
|
| 82 |
+
version="3.10",
|
| 83 |
+
python_beta=datetime.date(2021, 5, 3),
|
| 84 |
+
python_start=datetime.date(2021, 10, 4),
|
| 85 |
+
python_eol=datetime.date(2026, 10, 4), # TODO: specify day when announced
|
| 86 |
+
),
|
| 87 |
+
VersionInfo(
|
| 88 |
+
version="3.11",
|
| 89 |
+
python_beta=datetime.date(2022, 5, 8),
|
| 90 |
+
python_start=datetime.date(2022, 10, 24),
|
| 91 |
+
python_eol=datetime.date(2027, 10, 24), # TODO: specify day when announced
|
| 92 |
+
),
|
| 93 |
+
VersionInfo(
|
| 94 |
+
version="3.12",
|
| 95 |
+
python_beta=datetime.date(2023, 5, 22),
|
| 96 |
+
python_start=datetime.date(2023, 10, 2),
|
| 97 |
+
python_eol=datetime.date(2028, 10, 2), # TODO: specify day when announced
|
| 98 |
+
),
|
| 99 |
+
VersionInfo(
|
| 100 |
+
version="3.13",
|
| 101 |
+
python_beta=datetime.date(2024, 5, 8),
|
| 102 |
+
python_start=datetime.date(2024, 10, 7),
|
| 103 |
+
python_eol=datetime.date(2029, 10, 7), # TODO: specify day when announced
|
| 104 |
+
),
|
| 105 |
+
VersionInfo(
|
| 106 |
+
version="3.14",
|
| 107 |
+
python_beta=datetime.date(2025, 5, 7),
|
| 108 |
+
python_start=datetime.date(2025, 10, 7),
|
| 109 |
+
python_eol=datetime.date(2030, 10, 7), # TODO: specify day when announced
|
| 110 |
+
),
|
| 111 |
+
]
|
| 112 |
+
|
| 113 |
+
PYTHON_VERSION_INFO: Dict[Tuple[int, int], VersionInfo] = {}
|
| 114 |
+
for info in PYTHON_VERSIONS:
|
| 115 |
+
major, minor = map(int, info.version.split("."))
|
| 116 |
+
PYTHON_VERSION_INFO[(major, minor)] = info
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
LOWEST_TRACKED_VERSION = min(PYTHON_VERSION_INFO.keys())
|
| 120 |
+
_FAKE_PAST_DATE = datetime.date.min + datetime.timedelta(days=900)
|
| 121 |
+
_FAKE_PAST_VERSION = VersionInfo(
|
| 122 |
+
version="0.0",
|
| 123 |
+
python_beta=_FAKE_PAST_DATE,
|
| 124 |
+
python_start=_FAKE_PAST_DATE,
|
| 125 |
+
python_eol=_FAKE_PAST_DATE,
|
| 126 |
+
)
|
| 127 |
+
_FAKE_FUTURE_DATE = datetime.date.max - datetime.timedelta(days=900)
|
| 128 |
+
_FAKE_FUTURE_VERSION = VersionInfo(
|
| 129 |
+
version="999.0",
|
| 130 |
+
python_beta=_FAKE_FUTURE_DATE,
|
| 131 |
+
python_start=_FAKE_FUTURE_DATE,
|
| 132 |
+
python_eol=_FAKE_FUTURE_DATE,
|
| 133 |
+
)
|
| 134 |
+
DEPRECATION_WARNING_PERIOD = datetime.timedelta(days=365)
|
| 135 |
+
EOL_GRACE_PERIOD = datetime.timedelta(weeks=1)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _flatten_message(text: str) -> str:
|
| 139 |
+
"""Dedent a multi-line string and flatten it into a single line."""
|
| 140 |
+
return " ".join(textwrap.dedent(text).strip().split())
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# TODO(https://github.com/googleapis/python-api-core/issues/835):
|
| 144 |
+
# Remove once we no longer support Python 3.9.
|
| 145 |
+
# `importlib.metadata.packages_distributions()` is only supported in Python 3.10 and newer
|
| 146 |
+
# https://docs.python.org/3/library/importlib.metadata.html#importlib.metadata.packages_distributions
|
| 147 |
+
if sys.version_info < (3, 10):
|
| 148 |
+
|
| 149 |
+
def _get_pypi_package_name(module_name): # pragma: NO COVER
|
| 150 |
+
"""Determine the PyPI package name for a given module name."""
|
| 151 |
+
return None
|
| 152 |
+
|
| 153 |
+
else:
|
| 154 |
+
from importlib import metadata
|
| 155 |
+
|
| 156 |
+
@functools.cache
|
| 157 |
+
def _cached_packages_distributions():
|
| 158 |
+
return metadata.packages_distributions()
|
| 159 |
+
|
| 160 |
+
def _get_pypi_package_name(module_name):
|
| 161 |
+
"""Determine the PyPI package name for a given module name."""
|
| 162 |
+
try:
|
| 163 |
+
module_to_distributions = _cached_packages_distributions()
|
| 164 |
+
|
| 165 |
+
if module_name in module_to_distributions: # pragma: NO COVER
|
| 166 |
+
return module_to_distributions[module_name][0]
|
| 167 |
+
except Exception as e: # pragma: NO COVER
|
| 168 |
+
_LOGGER.info(
|
| 169 |
+
"An error occurred while determining PyPI package name for %s: %s",
|
| 170 |
+
module_name,
|
| 171 |
+
e,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
return None
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _get_distribution_and_import_packages(import_package: str) -> Tuple[str, Any]:
|
| 178 |
+
"""Return a pretty string with distribution & import package names."""
|
| 179 |
+
distribution_package = _get_pypi_package_name(import_package)
|
| 180 |
+
dependency_distribution_and_import_packages = (
|
| 181 |
+
f"package {distribution_package} ({import_package})"
|
| 182 |
+
if distribution_package
|
| 183 |
+
else import_package
|
| 184 |
+
)
|
| 185 |
+
return dependency_distribution_and_import_packages, distribution_package
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def check_python_version(
|
| 189 |
+
package: str = "this package", today: Optional[datetime.date] = None
|
| 190 |
+
) -> PythonVersionStatus:
|
| 191 |
+
"""Check the running Python version and issue a support warning if needed.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
today: The date to check against. Defaults to the current date.
|
| 195 |
+
|
| 196 |
+
Returns:
|
| 197 |
+
The support status of the current Python version.
|
| 198 |
+
"""
|
| 199 |
+
today = today or datetime.date.today()
|
| 200 |
+
|
| 201 |
+
python_version = sys.version_info
|
| 202 |
+
version_tuple = (python_version.major, python_version.minor)
|
| 203 |
+
py_version_str = sys.version.split()[0]
|
| 204 |
+
|
| 205 |
+
version_info = PYTHON_VERSION_INFO.get(version_tuple)
|
| 206 |
+
|
| 207 |
+
if not version_info:
|
| 208 |
+
if version_tuple < LOWEST_TRACKED_VERSION:
|
| 209 |
+
version_info = _FAKE_PAST_VERSION
|
| 210 |
+
else:
|
| 211 |
+
version_info = _FAKE_FUTURE_VERSION
|
| 212 |
+
|
| 213 |
+
gapic_deprecation = version_info.gapic_deprecation or (
|
| 214 |
+
version_info.python_eol - DEPRECATION_WARNING_PERIOD
|
| 215 |
+
)
|
| 216 |
+
gapic_end = version_info.gapic_end or (version_info.python_eol + EOL_GRACE_PERIOD)
|
| 217 |
+
|
| 218 |
+
def min_python(date: datetime.date) -> str:
|
| 219 |
+
"""Find the minimum supported Python version for a given date."""
|
| 220 |
+
for version, info in sorted(PYTHON_VERSION_INFO.items()):
|
| 221 |
+
if info.python_start <= date < info.python_eol:
|
| 222 |
+
return f"{version[0]}.{version[1]}"
|
| 223 |
+
return "at a currently supported version [https://devguide.python.org/versions]"
|
| 224 |
+
|
| 225 |
+
# Resolve the pretty package label lazily so we avoid any work on
|
| 226 |
+
# the happy path (supported Python version, no warning needed).
|
| 227 |
+
def get_package_label():
|
| 228 |
+
label, _ = _get_distribution_and_import_packages(package)
|
| 229 |
+
return label
|
| 230 |
+
|
| 231 |
+
if gapic_end < today:
|
| 232 |
+
package_label = get_package_label()
|
| 233 |
+
message = _flatten_message(
|
| 234 |
+
f"""
|
| 235 |
+
You are using a non-supported Python version ({py_version_str}).
|
| 236 |
+
Google will not post any further updates to {package_label}
|
| 237 |
+
supporting this Python version. Please upgrade to the latest Python
|
| 238 |
+
version, or at least Python {min_python(today)}, and then update
|
| 239 |
+
{package_label}.
|
| 240 |
+
"""
|
| 241 |
+
)
|
| 242 |
+
warnings.warn(message, FutureWarning)
|
| 243 |
+
return PythonVersionStatus.PYTHON_VERSION_UNSUPPORTED
|
| 244 |
+
|
| 245 |
+
eol_date = version_info.python_eol + EOL_GRACE_PERIOD
|
| 246 |
+
if eol_date <= today <= gapic_end:
|
| 247 |
+
package_label = get_package_label()
|
| 248 |
+
message = _flatten_message(
|
| 249 |
+
f"""
|
| 250 |
+
You are using a Python version ({py_version_str})
|
| 251 |
+
past its end of life. Google will update {package_label}
|
| 252 |
+
with critical bug fixes on a best-effort basis, but not
|
| 253 |
+
with any other fixes or features. Please upgrade
|
| 254 |
+
to the latest Python version, or at least Python
|
| 255 |
+
{min_python(today)}, and then update {package_label}.
|
| 256 |
+
"""
|
| 257 |
+
)
|
| 258 |
+
warnings.warn(message, FutureWarning)
|
| 259 |
+
return PythonVersionStatus.PYTHON_VERSION_EOL
|
| 260 |
+
|
| 261 |
+
if gapic_deprecation <= today <= gapic_end:
|
| 262 |
+
package_label = get_package_label()
|
| 263 |
+
message = _flatten_message(
|
| 264 |
+
f"""
|
| 265 |
+
You are using a Python version ({py_version_str}) which Google will
|
| 266 |
+
stop supporting in new releases of {package_label} once it reaches
|
| 267 |
+
its end of life ({version_info.python_eol}). Please upgrade to the
|
| 268 |
+
latest Python version, or at least Python
|
| 269 |
+
{min_python(version_info.python_eol)}, to continue receiving updates
|
| 270 |
+
for {package_label} past that date.
|
| 271 |
+
"""
|
| 272 |
+
)
|
| 273 |
+
warnings.warn(message, FutureWarning)
|
| 274 |
+
return PythonVersionStatus.PYTHON_VERSION_DEPRECATED
|
| 275 |
+
|
| 276 |
+
return PythonVersionStatus.PYTHON_VERSION_SUPPORTED
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/_rest_streaming_base.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Helpers for server-side streaming in REST."""
|
| 16 |
+
|
| 17 |
+
from collections import deque
|
| 18 |
+
import string
|
| 19 |
+
from typing import Deque, Union
|
| 20 |
+
import types
|
| 21 |
+
|
| 22 |
+
import proto
|
| 23 |
+
import google.protobuf.message
|
| 24 |
+
from google.protobuf.json_format import Parse
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class BaseResponseIterator:
|
| 28 |
+
"""Base Iterator over REST API responses. This class should not be used directly.
|
| 29 |
+
|
| 30 |
+
Args:
|
| 31 |
+
response_message_cls (Union[proto.Message, google.protobuf.message.Message]): A response
|
| 32 |
+
class expected to be returned from an API.
|
| 33 |
+
|
| 34 |
+
Raises:
|
| 35 |
+
ValueError: If `response_message_cls` is not a subclass of `proto.Message` or `google.protobuf.message.Message`.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
def __init__(
|
| 39 |
+
self,
|
| 40 |
+
response_message_cls: Union[proto.Message, google.protobuf.message.Message],
|
| 41 |
+
):
|
| 42 |
+
self._response_message_cls = response_message_cls
|
| 43 |
+
# Contains a list of JSON responses ready to be sent to user.
|
| 44 |
+
self._ready_objs: Deque[str] = deque()
|
| 45 |
+
# Current JSON response being built.
|
| 46 |
+
self._obj = ""
|
| 47 |
+
# Keeps track of the nesting level within a JSON object.
|
| 48 |
+
self._level = 0
|
| 49 |
+
# Keeps track whether HTTP response is currently sending values
|
| 50 |
+
# inside of a string value.
|
| 51 |
+
self._in_string = False
|
| 52 |
+
# Whether an escape symbol "\" was encountered.
|
| 53 |
+
self._escape_next = False
|
| 54 |
+
|
| 55 |
+
self._grab = types.MethodType(self._create_grab(), self)
|
| 56 |
+
|
| 57 |
+
def _process_chunk(self, chunk: str):
|
| 58 |
+
if self._level == 0:
|
| 59 |
+
if chunk[0] != "[":
|
| 60 |
+
raise ValueError(
|
| 61 |
+
"Can only parse array of JSON objects, instead got %s" % chunk
|
| 62 |
+
)
|
| 63 |
+
for char in chunk:
|
| 64 |
+
if char == "{":
|
| 65 |
+
if self._level == 1:
|
| 66 |
+
# Level 1 corresponds to the outermost JSON object
|
| 67 |
+
# (i.e. the one we care about).
|
| 68 |
+
self._obj = ""
|
| 69 |
+
if not self._in_string:
|
| 70 |
+
self._level += 1
|
| 71 |
+
self._obj += char
|
| 72 |
+
elif char == "}":
|
| 73 |
+
self._obj += char
|
| 74 |
+
if not self._in_string:
|
| 75 |
+
self._level -= 1
|
| 76 |
+
if not self._in_string and self._level == 1:
|
| 77 |
+
self._ready_objs.append(self._obj)
|
| 78 |
+
elif char == '"':
|
| 79 |
+
# Helps to deal with an escaped quotes inside of a string.
|
| 80 |
+
if not self._escape_next:
|
| 81 |
+
self._in_string = not self._in_string
|
| 82 |
+
self._obj += char
|
| 83 |
+
elif char in string.whitespace:
|
| 84 |
+
if self._in_string:
|
| 85 |
+
self._obj += char
|
| 86 |
+
elif char == "[":
|
| 87 |
+
if self._level == 0:
|
| 88 |
+
self._level += 1
|
| 89 |
+
else:
|
| 90 |
+
self._obj += char
|
| 91 |
+
elif char == "]":
|
| 92 |
+
if self._level == 1:
|
| 93 |
+
self._level -= 1
|
| 94 |
+
else:
|
| 95 |
+
self._obj += char
|
| 96 |
+
else:
|
| 97 |
+
self._obj += char
|
| 98 |
+
self._escape_next = not self._escape_next if char == "\\" else False
|
| 99 |
+
|
| 100 |
+
def _create_grab(self):
|
| 101 |
+
if issubclass(self._response_message_cls, proto.Message):
|
| 102 |
+
|
| 103 |
+
def grab(this):
|
| 104 |
+
return this._response_message_cls.from_json(
|
| 105 |
+
this._ready_objs.popleft(), ignore_unknown_fields=True
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
return grab
|
| 109 |
+
elif issubclass(self._response_message_cls, google.protobuf.message.Message):
|
| 110 |
+
|
| 111 |
+
def grab(this):
|
| 112 |
+
return Parse(this._ready_objs.popleft(), this._response_message_cls())
|
| 113 |
+
|
| 114 |
+
return grab
|
| 115 |
+
else:
|
| 116 |
+
raise ValueError(
|
| 117 |
+
"Response message class must be a subclass of proto.Message or google.protobuf.message.Message."
|
| 118 |
+
)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/bidi.py
ADDED
|
@@ -0,0 +1,735 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017, Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# https://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Helpers for synchronous bidirectional streaming RPCs."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
import datetime
|
| 19 |
+
import logging
|
| 20 |
+
import queue as queue_module
|
| 21 |
+
import threading
|
| 22 |
+
import time
|
| 23 |
+
|
| 24 |
+
from google.api_core import exceptions
|
| 25 |
+
from google.api_core.bidi_base import BidiRpcBase
|
| 26 |
+
|
| 27 |
+
_LOGGER = logging.getLogger(__name__)
|
| 28 |
+
_BIDIRECTIONAL_CONSUMER_NAME = "Thread-ConsumeBidirectionalStream"
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class _RequestQueueGenerator(object):
|
| 32 |
+
"""A helper for sending requests to a gRPC stream from a Queue.
|
| 33 |
+
|
| 34 |
+
This generator takes requests off a given queue and yields them to gRPC.
|
| 35 |
+
|
| 36 |
+
This helper is useful when you have an indeterminate, indefinite, or
|
| 37 |
+
otherwise open-ended set of requests to send through a request-streaming
|
| 38 |
+
(or bidirectional) RPC.
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
Example::
|
| 42 |
+
|
| 43 |
+
requests = request_queue_generator(q)
|
| 44 |
+
call = stub.StreamingRequest(iter(requests))
|
| 45 |
+
requests.call = call
|
| 46 |
+
|
| 47 |
+
for response in call:
|
| 48 |
+
print(response)
|
| 49 |
+
q.put(...)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
queue (queue_module.Queue): The request queue.
|
| 54 |
+
period (float): The number of seconds to wait for items from the queue
|
| 55 |
+
before checking if the RPC is cancelled. In practice, this
|
| 56 |
+
determines the maximum amount of time the request consumption
|
| 57 |
+
thread will live after the RPC is cancelled.
|
| 58 |
+
initial_request (Union[protobuf.Message,
|
| 59 |
+
Callable[None, protobuf.Message]]): The initial request to
|
| 60 |
+
yield. This is done independently of the request queue to allow fo
|
| 61 |
+
easily restarting streams that require some initial configuration
|
| 62 |
+
request.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def __init__(self, queue, period=1, initial_request=None):
|
| 66 |
+
self._queue = queue
|
| 67 |
+
self._period = period
|
| 68 |
+
self._initial_request = initial_request
|
| 69 |
+
self.call = None
|
| 70 |
+
|
| 71 |
+
def _is_active(self):
|
| 72 |
+
# Note: there is a possibility that this starts *before* the call
|
| 73 |
+
# property is set. So we have to check if self.call is set before
|
| 74 |
+
# seeing if it's active. We need to return True if self.call is None.
|
| 75 |
+
# See https://github.com/googleapis/python-api-core/issues/560.
|
| 76 |
+
return self.call is None or self.call.is_active()
|
| 77 |
+
|
| 78 |
+
def __iter__(self):
|
| 79 |
+
# The reason this is necessary is because gRPC takes an iterator as the
|
| 80 |
+
# request for request-streaming RPCs. gRPC consumes this iterator in
|
| 81 |
+
# another thread to allow it to block while generating requests for
|
| 82 |
+
# the stream. However, if the generator blocks indefinitely gRPC will
|
| 83 |
+
# not be able to clean up the thread as it'll be blocked on
|
| 84 |
+
# `next(iterator)` and not be able to check the channel status to stop
|
| 85 |
+
# iterating. This helper mitigates that by waiting on the queue with
|
| 86 |
+
# a timeout and checking the RPC state before yielding.
|
| 87 |
+
#
|
| 88 |
+
# Finally, it allows for retrying without swapping queues because if
|
| 89 |
+
# it does pull an item off the queue when the RPC is inactive, it'll
|
| 90 |
+
# immediately put it back and then exit. This is necessary because
|
| 91 |
+
# yielding the item in this case will cause gRPC to discard it. In
|
| 92 |
+
# practice, this means that the order of messages is not guaranteed.
|
| 93 |
+
# If such a thing is necessary it would be easy to use a priority
|
| 94 |
+
# queue.
|
| 95 |
+
#
|
| 96 |
+
# Note that it is possible to accomplish this behavior without
|
| 97 |
+
# "spinning" (using a queue timeout). One possible way would be to use
|
| 98 |
+
# more threads to multiplex the grpc end event with the queue, another
|
| 99 |
+
# possible way is to use selectors and a custom event/queue object.
|
| 100 |
+
# Both of these approaches are significant from an engineering
|
| 101 |
+
# perspective for small benefit - the CPU consumed by spinning is
|
| 102 |
+
# pretty minuscule.
|
| 103 |
+
|
| 104 |
+
if self._initial_request is not None:
|
| 105 |
+
if callable(self._initial_request):
|
| 106 |
+
yield self._initial_request()
|
| 107 |
+
else:
|
| 108 |
+
yield self._initial_request
|
| 109 |
+
|
| 110 |
+
while True:
|
| 111 |
+
try:
|
| 112 |
+
item = self._queue.get(timeout=self._period)
|
| 113 |
+
except queue_module.Empty:
|
| 114 |
+
if not self._is_active():
|
| 115 |
+
_LOGGER.debug(
|
| 116 |
+
"Empty queue and inactive call, exiting request " "generator."
|
| 117 |
+
)
|
| 118 |
+
return
|
| 119 |
+
else:
|
| 120 |
+
# call is still active, keep waiting for queue items.
|
| 121 |
+
continue
|
| 122 |
+
|
| 123 |
+
# The consumer explicitly sent "None", indicating that the request
|
| 124 |
+
# should end.
|
| 125 |
+
if item is None:
|
| 126 |
+
_LOGGER.debug("Cleanly exiting request generator.")
|
| 127 |
+
return
|
| 128 |
+
|
| 129 |
+
if not self._is_active():
|
| 130 |
+
# We have an item, but the call is closed. We should put the
|
| 131 |
+
# item back on the queue so that the next call can consume it.
|
| 132 |
+
self._queue.put(item)
|
| 133 |
+
_LOGGER.debug(
|
| 134 |
+
"Inactive call, replacing item on queue and exiting "
|
| 135 |
+
"request generator."
|
| 136 |
+
)
|
| 137 |
+
return
|
| 138 |
+
|
| 139 |
+
yield item
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class _Throttle(object):
|
| 143 |
+
"""A context manager limiting the total entries in a sliding time window.
|
| 144 |
+
|
| 145 |
+
If more than ``access_limit`` attempts are made to enter the context manager
|
| 146 |
+
instance in the last ``time window`` interval, the exceeding requests block
|
| 147 |
+
until enough time elapses.
|
| 148 |
+
|
| 149 |
+
The context manager instances are thread-safe and can be shared between
|
| 150 |
+
multiple threads. If multiple requests are blocked and waiting to enter,
|
| 151 |
+
the exact order in which they are allowed to proceed is not determined.
|
| 152 |
+
|
| 153 |
+
Example::
|
| 154 |
+
|
| 155 |
+
max_three_per_second = _Throttle(
|
| 156 |
+
access_limit=3, time_window=datetime.timedelta(seconds=1)
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
for i in range(5):
|
| 160 |
+
with max_three_per_second as time_waited:
|
| 161 |
+
print("{}: Waited {} seconds to enter".format(i, time_waited))
|
| 162 |
+
|
| 163 |
+
Args:
|
| 164 |
+
access_limit (int): the maximum number of entries allowed in the time window
|
| 165 |
+
time_window (datetime.timedelta): the width of the sliding time window
|
| 166 |
+
"""
|
| 167 |
+
|
| 168 |
+
def __init__(self, access_limit, time_window):
|
| 169 |
+
if access_limit < 1:
|
| 170 |
+
raise ValueError("access_limit argument must be positive")
|
| 171 |
+
|
| 172 |
+
if time_window <= datetime.timedelta(0):
|
| 173 |
+
raise ValueError("time_window argument must be a positive timedelta")
|
| 174 |
+
|
| 175 |
+
self._time_window = time_window
|
| 176 |
+
self._access_limit = access_limit
|
| 177 |
+
self._past_entries = collections.deque(
|
| 178 |
+
maxlen=access_limit
|
| 179 |
+
) # least recent first
|
| 180 |
+
self._entry_lock = threading.Lock()
|
| 181 |
+
|
| 182 |
+
def __enter__(self):
|
| 183 |
+
with self._entry_lock:
|
| 184 |
+
cutoff_time = datetime.datetime.now() - self._time_window
|
| 185 |
+
|
| 186 |
+
# drop the entries that are too old, as they are no longer relevant
|
| 187 |
+
while self._past_entries and self._past_entries[0] < cutoff_time:
|
| 188 |
+
self._past_entries.popleft()
|
| 189 |
+
|
| 190 |
+
if len(self._past_entries) < self._access_limit:
|
| 191 |
+
self._past_entries.append(datetime.datetime.now())
|
| 192 |
+
return 0.0 # no waiting was needed
|
| 193 |
+
|
| 194 |
+
to_wait = (self._past_entries[0] - cutoff_time).total_seconds()
|
| 195 |
+
time.sleep(to_wait)
|
| 196 |
+
|
| 197 |
+
self._past_entries.append(datetime.datetime.now())
|
| 198 |
+
return to_wait
|
| 199 |
+
|
| 200 |
+
def __exit__(self, *_):
|
| 201 |
+
pass
|
| 202 |
+
|
| 203 |
+
def __repr__(self):
|
| 204 |
+
return "{}(access_limit={}, time_window={})".format(
|
| 205 |
+
self.__class__.__name__, self._access_limit, repr(self._time_window)
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class BidiRpc(BidiRpcBase):
|
| 210 |
+
"""A helper for consuming a bi-directional streaming RPC.
|
| 211 |
+
|
| 212 |
+
This maps gRPC's built-in interface which uses a request iterator and a
|
| 213 |
+
response iterator into a socket-like :func:`send` and :func:`recv`. This
|
| 214 |
+
is a more useful pattern for long-running or asymmetric streams (streams
|
| 215 |
+
where there is not a direct correlation between the requests and
|
| 216 |
+
responses).
|
| 217 |
+
|
| 218 |
+
Example::
|
| 219 |
+
|
| 220 |
+
initial_request = example_pb2.StreamingRpcRequest(
|
| 221 |
+
setting='example')
|
| 222 |
+
rpc = BidiRpc(
|
| 223 |
+
stub.StreamingRpc,
|
| 224 |
+
initial_request=initial_request,
|
| 225 |
+
metadata=[('name', 'value')]
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
rpc.open()
|
| 229 |
+
|
| 230 |
+
while rpc.is_active():
|
| 231 |
+
print(rpc.recv())
|
| 232 |
+
rpc.send(example_pb2.StreamingRpcRequest(
|
| 233 |
+
data='example'))
|
| 234 |
+
|
| 235 |
+
rpc.close()
|
| 236 |
+
|
| 237 |
+
This does *not* retry the stream on errors. See :class:`ResumableBidiRpc`.
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
start_rpc (grpc.StreamStreamMultiCallable): The gRPC method used to
|
| 241 |
+
start the RPC.
|
| 242 |
+
initial_request (Union[protobuf.Message,
|
| 243 |
+
Callable[None, protobuf.Message]]): The initial request to
|
| 244 |
+
yield. This is useful if an initial request is needed to start the
|
| 245 |
+
stream.
|
| 246 |
+
metadata (Sequence[Tuple(str, str)]): RPC metadata to include in
|
| 247 |
+
the request.
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
def _create_queue(self):
|
| 251 |
+
"""Create a queue for requests."""
|
| 252 |
+
return queue_module.Queue()
|
| 253 |
+
|
| 254 |
+
def open(self):
|
| 255 |
+
"""Opens the stream."""
|
| 256 |
+
if self.is_active:
|
| 257 |
+
raise ValueError("Cannot open an already open stream.")
|
| 258 |
+
|
| 259 |
+
request_generator = _RequestQueueGenerator(
|
| 260 |
+
self._request_queue, initial_request=self._initial_request
|
| 261 |
+
)
|
| 262 |
+
try:
|
| 263 |
+
call = self._start_rpc(iter(request_generator), metadata=self._rpc_metadata)
|
| 264 |
+
except exceptions.GoogleAPICallError as exc:
|
| 265 |
+
# The original `grpc.RpcError` (which is usually also a `grpc.Call`) is
|
| 266 |
+
# available from the ``response`` property on the mapped exception.
|
| 267 |
+
self._on_call_done(exc.response)
|
| 268 |
+
raise
|
| 269 |
+
|
| 270 |
+
request_generator.call = call
|
| 271 |
+
|
| 272 |
+
# TODO: api_core should expose the future interface for wrapped
|
| 273 |
+
# callables as well.
|
| 274 |
+
if hasattr(call, "_wrapped"): # pragma: NO COVER
|
| 275 |
+
call._wrapped.add_done_callback(self._on_call_done)
|
| 276 |
+
else:
|
| 277 |
+
call.add_done_callback(self._on_call_done)
|
| 278 |
+
|
| 279 |
+
self._request_generator = request_generator
|
| 280 |
+
self.call = call
|
| 281 |
+
|
| 282 |
+
def close(self):
|
| 283 |
+
"""Closes the stream."""
|
| 284 |
+
if self.call is not None:
|
| 285 |
+
self.call.cancel()
|
| 286 |
+
|
| 287 |
+
# Put None in request queue to signal termination.
|
| 288 |
+
self._request_queue.put(None)
|
| 289 |
+
self._request_generator = None
|
| 290 |
+
self._initial_request = None
|
| 291 |
+
self._callbacks = []
|
| 292 |
+
# Don't set self.call to None. Keep it around so that send/recv can
|
| 293 |
+
# raise the error.
|
| 294 |
+
|
| 295 |
+
def send(self, request):
|
| 296 |
+
"""Queue a message to be sent on the stream.
|
| 297 |
+
|
| 298 |
+
Send is non-blocking.
|
| 299 |
+
|
| 300 |
+
If the underlying RPC has been closed, this will raise.
|
| 301 |
+
|
| 302 |
+
Args:
|
| 303 |
+
request (protobuf.Message): The request to send.
|
| 304 |
+
"""
|
| 305 |
+
if self.call is None:
|
| 306 |
+
raise ValueError("Cannot send on an RPC stream that has never been opened.")
|
| 307 |
+
|
| 308 |
+
# Don't use self.is_active(), as ResumableBidiRpc will overload it
|
| 309 |
+
# to mean something semantically different.
|
| 310 |
+
if self.call.is_active():
|
| 311 |
+
self._request_queue.put(request)
|
| 312 |
+
else:
|
| 313 |
+
# calling next should cause the call to raise.
|
| 314 |
+
next(self.call)
|
| 315 |
+
|
| 316 |
+
def recv(self):
|
| 317 |
+
"""Wait for a message to be returned from the stream.
|
| 318 |
+
|
| 319 |
+
Recv is blocking.
|
| 320 |
+
|
| 321 |
+
If the underlying RPC has been closed, this will raise.
|
| 322 |
+
|
| 323 |
+
Returns:
|
| 324 |
+
protobuf.Message: The received message.
|
| 325 |
+
"""
|
| 326 |
+
if self.call is None:
|
| 327 |
+
raise ValueError("Cannot recv on an RPC stream that has never been opened.")
|
| 328 |
+
|
| 329 |
+
return next(self.call)
|
| 330 |
+
|
| 331 |
+
@property
|
| 332 |
+
def is_active(self):
|
| 333 |
+
"""True if this stream is currently open and active."""
|
| 334 |
+
return self.call is not None and self.call.is_active()
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def _never_terminate(future_or_error):
|
| 338 |
+
"""By default, no errors cause BiDi termination."""
|
| 339 |
+
return False
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
class ResumableBidiRpc(BidiRpc):
|
| 343 |
+
"""A :class:`BidiRpc` that can automatically resume the stream on errors.
|
| 344 |
+
|
| 345 |
+
It uses the ``should_recover`` arg to determine if it should re-establish
|
| 346 |
+
the stream on error.
|
| 347 |
+
|
| 348 |
+
Example::
|
| 349 |
+
|
| 350 |
+
def should_recover(exc):
|
| 351 |
+
return (
|
| 352 |
+
isinstance(exc, grpc.RpcError) and
|
| 353 |
+
exc.code() == grpc.StatusCode.UNAVAILABLE)
|
| 354 |
+
|
| 355 |
+
initial_request = example_pb2.StreamingRpcRequest(
|
| 356 |
+
setting='example')
|
| 357 |
+
|
| 358 |
+
metadata = [('header_name', 'value')]
|
| 359 |
+
|
| 360 |
+
rpc = ResumableBidiRpc(
|
| 361 |
+
stub.StreamingRpc,
|
| 362 |
+
should_recover=should_recover,
|
| 363 |
+
initial_request=initial_request,
|
| 364 |
+
metadata=metadata
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
rpc.open()
|
| 368 |
+
|
| 369 |
+
while rpc.is_active():
|
| 370 |
+
print(rpc.recv())
|
| 371 |
+
rpc.send(example_pb2.StreamingRpcRequest(
|
| 372 |
+
data='example'))
|
| 373 |
+
|
| 374 |
+
Args:
|
| 375 |
+
start_rpc (grpc.StreamStreamMultiCallable): The gRPC method used to
|
| 376 |
+
start the RPC.
|
| 377 |
+
initial_request (Union[protobuf.Message,
|
| 378 |
+
Callable[None, protobuf.Message]]): The initial request to
|
| 379 |
+
yield. This is useful if an initial request is needed to start the
|
| 380 |
+
stream.
|
| 381 |
+
should_recover (Callable[[Exception], bool]): A function that returns
|
| 382 |
+
True if the stream should be recovered. This will be called
|
| 383 |
+
whenever an error is encountered on the stream.
|
| 384 |
+
should_terminate (Callable[[Exception], bool]): A function that returns
|
| 385 |
+
True if the stream should be terminated. This will be called
|
| 386 |
+
whenever an error is encountered on the stream.
|
| 387 |
+
metadata Sequence[Tuple(str, str)]: RPC metadata to include in
|
| 388 |
+
the request.
|
| 389 |
+
throttle_reopen (bool): If ``True``, throttling will be applied to
|
| 390 |
+
stream reopen calls. Defaults to ``False``.
|
| 391 |
+
"""
|
| 392 |
+
|
| 393 |
+
def __init__(
|
| 394 |
+
self,
|
| 395 |
+
start_rpc,
|
| 396 |
+
should_recover,
|
| 397 |
+
should_terminate=_never_terminate,
|
| 398 |
+
initial_request=None,
|
| 399 |
+
metadata=None,
|
| 400 |
+
throttle_reopen=False,
|
| 401 |
+
):
|
| 402 |
+
super(ResumableBidiRpc, self).__init__(start_rpc, initial_request, metadata)
|
| 403 |
+
self._should_recover = should_recover
|
| 404 |
+
self._should_terminate = should_terminate
|
| 405 |
+
self._operational_lock = threading.RLock()
|
| 406 |
+
self._finalized = False
|
| 407 |
+
self._finalize_lock = threading.Lock()
|
| 408 |
+
|
| 409 |
+
if throttle_reopen:
|
| 410 |
+
self._reopen_throttle = _Throttle(
|
| 411 |
+
access_limit=5, time_window=datetime.timedelta(seconds=10)
|
| 412 |
+
)
|
| 413 |
+
else:
|
| 414 |
+
self._reopen_throttle = None
|
| 415 |
+
|
| 416 |
+
def _finalize(self, result):
|
| 417 |
+
with self._finalize_lock:
|
| 418 |
+
if self._finalized:
|
| 419 |
+
return
|
| 420 |
+
|
| 421 |
+
for callback in self._callbacks:
|
| 422 |
+
callback(result)
|
| 423 |
+
|
| 424 |
+
self._finalized = True
|
| 425 |
+
|
| 426 |
+
def _on_call_done(self, future):
|
| 427 |
+
# Unlike the base class, we only execute the callbacks on a terminal
|
| 428 |
+
# error, not for errors that we can recover from. Note that grpc's
|
| 429 |
+
# "future" here is also a grpc.RpcError.
|
| 430 |
+
with self._operational_lock:
|
| 431 |
+
if self._should_terminate(future):
|
| 432 |
+
self._finalize(future)
|
| 433 |
+
elif not self._should_recover(future):
|
| 434 |
+
self._finalize(future)
|
| 435 |
+
else:
|
| 436 |
+
_LOGGER.debug("Re-opening stream from gRPC callback.")
|
| 437 |
+
self._reopen()
|
| 438 |
+
|
| 439 |
+
def _reopen(self):
|
| 440 |
+
with self._operational_lock:
|
| 441 |
+
# Another thread already managed to re-open this stream.
|
| 442 |
+
if self.call is not None and self.call.is_active():
|
| 443 |
+
_LOGGER.debug("Stream was already re-established.")
|
| 444 |
+
return
|
| 445 |
+
|
| 446 |
+
self.call = None
|
| 447 |
+
# Request generator should exit cleanly since the RPC its bound to
|
| 448 |
+
# has exited.
|
| 449 |
+
self._request_generator = None
|
| 450 |
+
|
| 451 |
+
# Note: we do not currently do any sort of backoff here. The
|
| 452 |
+
# assumption is that re-establishing the stream under normal
|
| 453 |
+
# circumstances will happen in intervals greater than 60s.
|
| 454 |
+
# However, it is possible in a degenerative case that the server
|
| 455 |
+
# closes the stream rapidly which would lead to thrashing here,
|
| 456 |
+
# but hopefully in those cases the server would return a non-
|
| 457 |
+
# retryable error.
|
| 458 |
+
|
| 459 |
+
try:
|
| 460 |
+
if self._reopen_throttle:
|
| 461 |
+
with self._reopen_throttle:
|
| 462 |
+
self.open()
|
| 463 |
+
else:
|
| 464 |
+
self.open()
|
| 465 |
+
# If re-opening or re-calling the method fails for any reason,
|
| 466 |
+
# consider it a terminal error and finalize the stream.
|
| 467 |
+
except Exception as exc:
|
| 468 |
+
_LOGGER.debug("Failed to re-open stream due to %s", exc)
|
| 469 |
+
self._finalize(exc)
|
| 470 |
+
raise
|
| 471 |
+
|
| 472 |
+
_LOGGER.info("Re-established stream")
|
| 473 |
+
|
| 474 |
+
def _recoverable(self, method, *args, **kwargs):
|
| 475 |
+
"""Wraps a method to recover the stream and retry on error.
|
| 476 |
+
|
| 477 |
+
If a retryable error occurs while making the call, then the stream will
|
| 478 |
+
be re-opened and the method will be retried. This happens indefinitely
|
| 479 |
+
so long as the error is a retryable one. If an error occurs while
|
| 480 |
+
re-opening the stream, then this method will raise immediately and
|
| 481 |
+
trigger finalization of this object.
|
| 482 |
+
|
| 483 |
+
Args:
|
| 484 |
+
method (Callable[..., Any]): The method to call.
|
| 485 |
+
args: The args to pass to the method.
|
| 486 |
+
kwargs: The kwargs to pass to the method.
|
| 487 |
+
"""
|
| 488 |
+
while True:
|
| 489 |
+
try:
|
| 490 |
+
return method(*args, **kwargs)
|
| 491 |
+
|
| 492 |
+
except Exception as exc:
|
| 493 |
+
with self._operational_lock:
|
| 494 |
+
_LOGGER.debug("Call to retryable %r caused %s.", method, exc)
|
| 495 |
+
|
| 496 |
+
if self._should_terminate(exc):
|
| 497 |
+
self.close()
|
| 498 |
+
_LOGGER.debug("Terminating %r due to %s.", method, exc)
|
| 499 |
+
self._finalize(exc)
|
| 500 |
+
break
|
| 501 |
+
|
| 502 |
+
if not self._should_recover(exc):
|
| 503 |
+
self.close()
|
| 504 |
+
_LOGGER.debug("Not retrying %r due to %s.", method, exc)
|
| 505 |
+
self._finalize(exc)
|
| 506 |
+
raise exc
|
| 507 |
+
|
| 508 |
+
_LOGGER.debug("Re-opening stream from retryable %r.", method)
|
| 509 |
+
self._reopen()
|
| 510 |
+
|
| 511 |
+
def _send(self, request):
|
| 512 |
+
# Grab a reference to the RPC call. Because another thread (notably
|
| 513 |
+
# the gRPC error thread) can modify self.call (by invoking reopen),
|
| 514 |
+
# we should ensure our reference can not change underneath us.
|
| 515 |
+
# If self.call is modified (such as replaced with a new RPC call) then
|
| 516 |
+
# this will use the "old" RPC, which should result in the same
|
| 517 |
+
# exception passed into gRPC's error handler being raised here, which
|
| 518 |
+
# will be handled by the usual error handling in retryable.
|
| 519 |
+
with self._operational_lock:
|
| 520 |
+
call = self.call
|
| 521 |
+
|
| 522 |
+
if call is None:
|
| 523 |
+
raise ValueError("Cannot send on an RPC that has never been opened.")
|
| 524 |
+
|
| 525 |
+
# Don't use self.is_active(), as ResumableBidiRpc will overload it
|
| 526 |
+
# to mean something semantically different.
|
| 527 |
+
if call.is_active():
|
| 528 |
+
self._request_queue.put(request)
|
| 529 |
+
pass
|
| 530 |
+
else:
|
| 531 |
+
# calling next should cause the call to raise.
|
| 532 |
+
next(call)
|
| 533 |
+
|
| 534 |
+
def send(self, request):
|
| 535 |
+
return self._recoverable(self._send, request)
|
| 536 |
+
|
| 537 |
+
def _recv(self):
|
| 538 |
+
with self._operational_lock:
|
| 539 |
+
call = self.call
|
| 540 |
+
|
| 541 |
+
if call is None:
|
| 542 |
+
raise ValueError("Cannot recv on an RPC that has never been opened.")
|
| 543 |
+
|
| 544 |
+
return next(call)
|
| 545 |
+
|
| 546 |
+
def recv(self):
|
| 547 |
+
return self._recoverable(self._recv)
|
| 548 |
+
|
| 549 |
+
def close(self):
|
| 550 |
+
self._finalize(None)
|
| 551 |
+
super(ResumableBidiRpc, self).close()
|
| 552 |
+
|
| 553 |
+
@property
|
| 554 |
+
def is_active(self):
|
| 555 |
+
"""bool: True if this stream is currently open and active."""
|
| 556 |
+
# Use the operational lock. It's entirely possible for something
|
| 557 |
+
# to check the active state *while* the RPC is being retried.
|
| 558 |
+
# Also, use finalized to track the actual terminal state here.
|
| 559 |
+
# This is because if the stream is re-established by the gRPC thread
|
| 560 |
+
# it's technically possible to check this between when gRPC marks the
|
| 561 |
+
# RPC as inactive and when gRPC executes our callback that re-opens
|
| 562 |
+
# the stream.
|
| 563 |
+
with self._operational_lock:
|
| 564 |
+
return self.call is not None and not self._finalized
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
class BackgroundConsumer(object):
|
| 568 |
+
"""A bi-directional stream consumer that runs in a separate thread.
|
| 569 |
+
|
| 570 |
+
This maps the consumption of a stream into a callback-based model. It also
|
| 571 |
+
provides :func:`pause` and :func:`resume` to allow for flow-control.
|
| 572 |
+
|
| 573 |
+
Example::
|
| 574 |
+
|
| 575 |
+
def should_recover(exc):
|
| 576 |
+
return (
|
| 577 |
+
isinstance(exc, grpc.RpcError) and
|
| 578 |
+
exc.code() == grpc.StatusCode.UNAVAILABLE)
|
| 579 |
+
|
| 580 |
+
initial_request = example_pb2.StreamingRpcRequest(
|
| 581 |
+
setting='example')
|
| 582 |
+
|
| 583 |
+
rpc = ResumeableBidiRpc(
|
| 584 |
+
stub.StreamingRpc,
|
| 585 |
+
initial_request=initial_request,
|
| 586 |
+
should_recover=should_recover)
|
| 587 |
+
|
| 588 |
+
def on_response(response):
|
| 589 |
+
print(response)
|
| 590 |
+
|
| 591 |
+
consumer = BackgroundConsumer(rpc, on_response)
|
| 592 |
+
consumer.start()
|
| 593 |
+
|
| 594 |
+
Note that error handling *must* be done by using the provided
|
| 595 |
+
``bidi_rpc``'s ``add_done_callback``. This helper will automatically exit
|
| 596 |
+
whenever the RPC itself exits and will not provide any error details.
|
| 597 |
+
|
| 598 |
+
Args:
|
| 599 |
+
bidi_rpc (BidiRpc): The RPC to consume. Should not have been
|
| 600 |
+
``open()``ed yet.
|
| 601 |
+
on_response (Callable[[protobuf.Message], None]): The callback to
|
| 602 |
+
be called for every response on the stream.
|
| 603 |
+
on_fatal_exception (Callable[[Exception], None]): The callback to
|
| 604 |
+
be called on fatal errors during consumption. Default None.
|
| 605 |
+
"""
|
| 606 |
+
|
| 607 |
+
def __init__(self, bidi_rpc, on_response, on_fatal_exception=None):
|
| 608 |
+
self._bidi_rpc = bidi_rpc
|
| 609 |
+
self._on_response = on_response
|
| 610 |
+
self._paused = False
|
| 611 |
+
self._on_fatal_exception = on_fatal_exception
|
| 612 |
+
self._wake = threading.Condition()
|
| 613 |
+
self._thread = None
|
| 614 |
+
self._operational_lock = threading.Lock()
|
| 615 |
+
|
| 616 |
+
def _on_call_done(self, future):
|
| 617 |
+
# Resume the thread if it's paused, this prevents blocking forever
|
| 618 |
+
# when the RPC has terminated.
|
| 619 |
+
self.resume()
|
| 620 |
+
|
| 621 |
+
def _thread_main(self, ready):
|
| 622 |
+
try:
|
| 623 |
+
ready.set()
|
| 624 |
+
self._bidi_rpc.add_done_callback(self._on_call_done)
|
| 625 |
+
self._bidi_rpc.open()
|
| 626 |
+
|
| 627 |
+
while self._bidi_rpc.is_active:
|
| 628 |
+
# Do not allow the paused status to change at all during this
|
| 629 |
+
# section. There is a condition where we could be resumed
|
| 630 |
+
# between checking if we are paused and calling wake.wait(),
|
| 631 |
+
# which means that we will miss the notification to wake up
|
| 632 |
+
# (oops!) and wait for a notification that will never come.
|
| 633 |
+
# Keeping the lock throughout avoids that.
|
| 634 |
+
# In the future, we could use `Condition.wait_for` if we drop
|
| 635 |
+
# Python 2.7.
|
| 636 |
+
# See: https://github.com/googleapis/python-api-core/issues/211
|
| 637 |
+
with self._wake:
|
| 638 |
+
while self._paused:
|
| 639 |
+
_LOGGER.debug("paused, waiting for waking.")
|
| 640 |
+
self._wake.wait()
|
| 641 |
+
_LOGGER.debug("woken.")
|
| 642 |
+
|
| 643 |
+
_LOGGER.debug("waiting for recv.")
|
| 644 |
+
response = self._bidi_rpc.recv()
|
| 645 |
+
_LOGGER.debug("recved response.")
|
| 646 |
+
if self._on_response is not None:
|
| 647 |
+
self._on_response(response)
|
| 648 |
+
|
| 649 |
+
except exceptions.GoogleAPICallError as exc:
|
| 650 |
+
_LOGGER.debug(
|
| 651 |
+
"%s caught error %s and will exit. Generally this is due to "
|
| 652 |
+
"the RPC itself being cancelled and the error will be "
|
| 653 |
+
"surfaced to the calling code.",
|
| 654 |
+
_BIDIRECTIONAL_CONSUMER_NAME,
|
| 655 |
+
exc,
|
| 656 |
+
exc_info=True,
|
| 657 |
+
)
|
| 658 |
+
if self._on_fatal_exception is not None:
|
| 659 |
+
self._on_fatal_exception(exc)
|
| 660 |
+
|
| 661 |
+
except Exception as exc:
|
| 662 |
+
_LOGGER.exception(
|
| 663 |
+
"%s caught unexpected exception %s and will exit.",
|
| 664 |
+
_BIDIRECTIONAL_CONSUMER_NAME,
|
| 665 |
+
exc,
|
| 666 |
+
)
|
| 667 |
+
if self._on_fatal_exception is not None:
|
| 668 |
+
self._on_fatal_exception(exc)
|
| 669 |
+
|
| 670 |
+
_LOGGER.info("%s exiting", _BIDIRECTIONAL_CONSUMER_NAME)
|
| 671 |
+
|
| 672 |
+
def start(self):
|
| 673 |
+
"""Start the background thread and begin consuming the thread."""
|
| 674 |
+
with self._operational_lock:
|
| 675 |
+
ready = threading.Event()
|
| 676 |
+
thread = threading.Thread(
|
| 677 |
+
name=_BIDIRECTIONAL_CONSUMER_NAME,
|
| 678 |
+
target=self._thread_main,
|
| 679 |
+
args=(ready,),
|
| 680 |
+
daemon=True,
|
| 681 |
+
)
|
| 682 |
+
thread.start()
|
| 683 |
+
# Other parts of the code rely on `thread.is_alive` which
|
| 684 |
+
# isn't sufficient to know if a thread is active, just that it may
|
| 685 |
+
# soon be active. This can cause races. Further protect
|
| 686 |
+
# against races by using a ready event and wait on it to be set.
|
| 687 |
+
ready.wait()
|
| 688 |
+
self._thread = thread
|
| 689 |
+
_LOGGER.debug("Started helper thread %s", thread.name)
|
| 690 |
+
|
| 691 |
+
def stop(self):
|
| 692 |
+
"""Stop consuming the stream and shutdown the background thread.
|
| 693 |
+
|
| 694 |
+
NOTE: Cannot be called within `_thread_main`, since it is not
|
| 695 |
+
possible to join a thread to itself.
|
| 696 |
+
"""
|
| 697 |
+
with self._operational_lock:
|
| 698 |
+
self._bidi_rpc.close()
|
| 699 |
+
|
| 700 |
+
if self._thread is not None:
|
| 701 |
+
# Resume the thread to wake it up in case it is sleeping.
|
| 702 |
+
self.resume()
|
| 703 |
+
# The daemonized thread may itself block, so don't wait
|
| 704 |
+
# for it longer than a second.
|
| 705 |
+
self._thread.join(1.0)
|
| 706 |
+
if self._thread.is_alive(): # pragma: NO COVER
|
| 707 |
+
_LOGGER.warning("Background thread did not exit.")
|
| 708 |
+
|
| 709 |
+
self._thread = None
|
| 710 |
+
self._on_response = None
|
| 711 |
+
self._on_fatal_exception = None
|
| 712 |
+
|
| 713 |
+
@property
|
| 714 |
+
def is_active(self):
|
| 715 |
+
"""bool: True if the background thread is active."""
|
| 716 |
+
return self._thread is not None and self._thread.is_alive()
|
| 717 |
+
|
| 718 |
+
def pause(self):
|
| 719 |
+
"""Pauses the response stream.
|
| 720 |
+
|
| 721 |
+
This does *not* pause the request stream.
|
| 722 |
+
"""
|
| 723 |
+
with self._wake:
|
| 724 |
+
self._paused = True
|
| 725 |
+
|
| 726 |
+
def resume(self):
|
| 727 |
+
"""Resumes the response stream."""
|
| 728 |
+
with self._wake:
|
| 729 |
+
self._paused = False
|
| 730 |
+
self._wake.notify_all()
|
| 731 |
+
|
| 732 |
+
@property
|
| 733 |
+
def is_paused(self):
|
| 734 |
+
"""bool: True if the response stream is paused."""
|
| 735 |
+
return self._paused
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/bidi_async.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025, Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# https://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Asynchronous bi-directional streaming RPC helpers."""
|
| 16 |
+
|
| 17 |
+
import asyncio
|
| 18 |
+
import logging
|
| 19 |
+
from typing import Callable, Optional, Union
|
| 20 |
+
|
| 21 |
+
from grpc import aio
|
| 22 |
+
|
| 23 |
+
from google.api_core import exceptions
|
| 24 |
+
from google.api_core.bidi_base import BidiRpcBase
|
| 25 |
+
|
| 26 |
+
from google.protobuf.message import Message as ProtobufMessage
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
_LOGGER = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class _AsyncRequestQueueGenerator:
|
| 33 |
+
"""_AsyncRequestQueueGenerator is a helper class for sending asynchronous
|
| 34 |
+
requests to a gRPC stream from a Queue.
|
| 35 |
+
|
| 36 |
+
This generator takes asynchronous requests off a given `asyncio.Queue` and
|
| 37 |
+
yields them to gRPC.
|
| 38 |
+
|
| 39 |
+
It's useful when you have an indeterminate, indefinite, or otherwise
|
| 40 |
+
open-ended set of requests to send through a request-streaming (or
|
| 41 |
+
bidirectional) RPC.
|
| 42 |
+
|
| 43 |
+
Example::
|
| 44 |
+
|
| 45 |
+
requests = _AsyncRequestQueueGenerator(q)
|
| 46 |
+
call = await stub.StreamingRequest(requests)
|
| 47 |
+
requests.call = call
|
| 48 |
+
|
| 49 |
+
async for response in call:
|
| 50 |
+
print(response)
|
| 51 |
+
await q.put(...)
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
queue (asyncio.Queue): The request queue.
|
| 55 |
+
initial_request (Union[ProtobufMessage,
|
| 56 |
+
Callable[[], ProtobufMessage]]): The initial request to
|
| 57 |
+
yield. This is done independently of the request queue to allow for
|
| 58 |
+
easily restarting streams that require some initial configuration
|
| 59 |
+
request.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
def __init__(
|
| 63 |
+
self,
|
| 64 |
+
queue: asyncio.Queue,
|
| 65 |
+
initial_request: Optional[
|
| 66 |
+
Union[ProtobufMessage, Callable[[], ProtobufMessage]]
|
| 67 |
+
] = None,
|
| 68 |
+
) -> None:
|
| 69 |
+
self._queue = queue
|
| 70 |
+
self._initial_request = initial_request
|
| 71 |
+
self.call: Optional[aio.Call] = None
|
| 72 |
+
|
| 73 |
+
def _is_active(self) -> bool:
|
| 74 |
+
"""Returns true if the call is not set or not completed."""
|
| 75 |
+
# Note: there is a possibility that this starts *before* the call
|
| 76 |
+
# property is set. So we have to check if self.call is set before
|
| 77 |
+
# seeing if it's active. We need to return True if self.call is None.
|
| 78 |
+
# See https://github.com/googleapis/python-api-core/issues/560.
|
| 79 |
+
return self.call is None or not self.call.done()
|
| 80 |
+
|
| 81 |
+
async def __aiter__(self):
|
| 82 |
+
# The reason this is necessary is because it lets the user have
|
| 83 |
+
# control on when they would want to send requests proto messages
|
| 84 |
+
# instead of sending all of them initially.
|
| 85 |
+
#
|
| 86 |
+
# This is achieved via asynchronous queue (asyncio.Queue),
|
| 87 |
+
# gRPC awaits until there's a message in the queue.
|
| 88 |
+
#
|
| 89 |
+
# Finally, it allows for retrying without swapping queues because if
|
| 90 |
+
# it does pull an item off the queue when the RPC is inactive, it'll
|
| 91 |
+
# immediately put it back and then exit. This is necessary because
|
| 92 |
+
# yielding the item in this case will cause gRPC to discard it. In
|
| 93 |
+
# practice, this means that the order of messages is not guaranteed.
|
| 94 |
+
# If preserving order is necessary it would be easy to use a priority
|
| 95 |
+
# queue.
|
| 96 |
+
if self._initial_request is not None:
|
| 97 |
+
if callable(self._initial_request):
|
| 98 |
+
yield self._initial_request()
|
| 99 |
+
else:
|
| 100 |
+
yield self._initial_request
|
| 101 |
+
|
| 102 |
+
while True:
|
| 103 |
+
item = await self._queue.get()
|
| 104 |
+
|
| 105 |
+
# The consumer explicitly sent "None", indicating that the request
|
| 106 |
+
# should end.
|
| 107 |
+
if item is None:
|
| 108 |
+
_LOGGER.debug("Cleanly exiting request generator.")
|
| 109 |
+
return
|
| 110 |
+
|
| 111 |
+
if not self._is_active():
|
| 112 |
+
# We have an item, but the call is closed. We should put the
|
| 113 |
+
# item back on the queue so that the next call can consume it.
|
| 114 |
+
await self._queue.put(item)
|
| 115 |
+
_LOGGER.debug(
|
| 116 |
+
"Inactive call, replacing item on queue and exiting "
|
| 117 |
+
"request generator."
|
| 118 |
+
)
|
| 119 |
+
return
|
| 120 |
+
|
| 121 |
+
yield item
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class AsyncBidiRpc(BidiRpcBase):
|
| 125 |
+
"""A helper for consuming a async bi-directional streaming RPC.
|
| 126 |
+
|
| 127 |
+
This maps gRPC's built-in interface which uses a request iterator and a
|
| 128 |
+
response iterator into a socket-like :func:`send` and :func:`recv`. This
|
| 129 |
+
is a more useful pattern for long-running or asymmetric streams (streams
|
| 130 |
+
where there is not a direct correlation between the requests and
|
| 131 |
+
responses).
|
| 132 |
+
|
| 133 |
+
Example::
|
| 134 |
+
|
| 135 |
+
initial_request = example_pb2.StreamingRpcRequest(
|
| 136 |
+
setting='example')
|
| 137 |
+
rpc = AsyncBidiRpc(
|
| 138 |
+
stub.StreamingRpc,
|
| 139 |
+
initial_request=initial_request,
|
| 140 |
+
metadata=[('name', 'value')]
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
await rpc.open()
|
| 144 |
+
|
| 145 |
+
while rpc.is_active:
|
| 146 |
+
print(await rpc.recv())
|
| 147 |
+
await rpc.send(example_pb2.StreamingRpcRequest(
|
| 148 |
+
data='example'))
|
| 149 |
+
|
| 150 |
+
await rpc.close()
|
| 151 |
+
|
| 152 |
+
This does *not* retry the stream on errors.
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
start_rpc (grpc.aio.StreamStreamMultiCallable): The gRPC method used to
|
| 156 |
+
start the RPC.
|
| 157 |
+
initial_request (Union[ProtobufMessage,
|
| 158 |
+
Callable[[], ProtobufMessage]]): The initial request to
|
| 159 |
+
yield. This is useful if an initial request is needed to start the
|
| 160 |
+
stream.
|
| 161 |
+
metadata (Sequence[Tuple(str, str)]): RPC metadata to include in
|
| 162 |
+
the request.
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
def _create_queue(self) -> asyncio.Queue:
|
| 166 |
+
"""Create a queue for requests."""
|
| 167 |
+
return asyncio.Queue()
|
| 168 |
+
|
| 169 |
+
async def open(self) -> None:
|
| 170 |
+
"""Opens the stream."""
|
| 171 |
+
if self.is_active:
|
| 172 |
+
raise ValueError("Cannot open an already open stream.")
|
| 173 |
+
|
| 174 |
+
request_generator = _AsyncRequestQueueGenerator(
|
| 175 |
+
self._request_queue, initial_request=self._initial_request
|
| 176 |
+
)
|
| 177 |
+
try:
|
| 178 |
+
call = await self._start_rpc(request_generator, metadata=self._rpc_metadata)
|
| 179 |
+
except exceptions.GoogleAPICallError as exc:
|
| 180 |
+
# The original `grpc.aio.AioRpcError` (which is usually also a
|
| 181 |
+
# `grpc.aio.Call`) is available from the ``response`` property on
|
| 182 |
+
# the mapped exception.
|
| 183 |
+
self._on_call_done(exc.response)
|
| 184 |
+
raise
|
| 185 |
+
|
| 186 |
+
request_generator.call = call
|
| 187 |
+
|
| 188 |
+
# TODO: api_core should expose the future interface for wrapped
|
| 189 |
+
# callables as well.
|
| 190 |
+
if hasattr(call, "_wrapped"): # pragma: NO COVER
|
| 191 |
+
call._wrapped.add_done_callback(self._on_call_done)
|
| 192 |
+
else:
|
| 193 |
+
call.add_done_callback(self._on_call_done)
|
| 194 |
+
|
| 195 |
+
self._request_generator = request_generator
|
| 196 |
+
self.call = call
|
| 197 |
+
|
| 198 |
+
async def close(self) -> None:
|
| 199 |
+
"""Closes the stream."""
|
| 200 |
+
if self.call is not None:
|
| 201 |
+
self.call.cancel()
|
| 202 |
+
|
| 203 |
+
# Put None in request queue to signal termination.
|
| 204 |
+
await self._request_queue.put(None)
|
| 205 |
+
self._request_generator = None
|
| 206 |
+
self._initial_request = None
|
| 207 |
+
self._callbacks = []
|
| 208 |
+
# Don't set self.call to None. Keep it around so that send/recv can
|
| 209 |
+
# raise the error.
|
| 210 |
+
|
| 211 |
+
async def send(self, request: ProtobufMessage) -> None:
|
| 212 |
+
"""Queue a message to be sent on the stream.
|
| 213 |
+
|
| 214 |
+
If the underlying RPC has been closed, this will raise.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
request (ProtobufMessage): The request to send.
|
| 218 |
+
"""
|
| 219 |
+
if self.call is None:
|
| 220 |
+
raise ValueError("Cannot send on an RPC stream that has never been opened.")
|
| 221 |
+
|
| 222 |
+
if not self.call.done():
|
| 223 |
+
await self._request_queue.put(request)
|
| 224 |
+
else:
|
| 225 |
+
# calling read should cause the call to raise.
|
| 226 |
+
await self.call.read()
|
| 227 |
+
|
| 228 |
+
async def recv(self) -> ProtobufMessage:
|
| 229 |
+
"""Wait for a message to be returned from the stream.
|
| 230 |
+
|
| 231 |
+
If the underlying RPC has been closed, this will raise.
|
| 232 |
+
|
| 233 |
+
Returns:
|
| 234 |
+
ProtobufMessage: The received message.
|
| 235 |
+
"""
|
| 236 |
+
if self.call is None:
|
| 237 |
+
raise ValueError("Cannot recv on an RPC stream that has never been opened.")
|
| 238 |
+
|
| 239 |
+
return await self.call.read()
|
| 240 |
+
|
| 241 |
+
@property
|
| 242 |
+
def is_active(self) -> bool:
|
| 243 |
+
"""Whether the stream is currently open and active."""
|
| 244 |
+
return self.call is not None and not self.call.done()
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/bidi_base.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025, Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# You may obtain a copy of the License at
|
| 5 |
+
# https://www.apache.org/licenses/LICENSE-2.0
|
| 6 |
+
#
|
| 7 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 8 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 9 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 10 |
+
# See the License for the specific language governing permissions and
|
| 11 |
+
# limitations under the License.
|
| 12 |
+
|
| 13 |
+
"""Base class for bi-directional streaming RPC helpers."""
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class BidiRpcBase:
|
| 17 |
+
"""A base class for consuming a bi-directional streaming RPC.
|
| 18 |
+
|
| 19 |
+
This maps gRPC's built-in interface which uses a request iterator and a
|
| 20 |
+
response iterator into a socket-like :func:`send` and :func:`recv`. This
|
| 21 |
+
is a more useful pattern for long-running or asymmetric streams (streams
|
| 22 |
+
where there is not a direct correlation between the requests and
|
| 23 |
+
responses).
|
| 24 |
+
|
| 25 |
+
This does *not* retry the stream on errors.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
start_rpc (Union[grpc.StreamStreamMultiCallable,
|
| 29 |
+
grpc.aio.StreamStreamMultiCallable]): The gRPC method used
|
| 30 |
+
to start the RPC.
|
| 31 |
+
initial_request (Union[protobuf.Message,
|
| 32 |
+
Callable[[], protobuf.Message]]): The initial request to
|
| 33 |
+
yield. This is useful if an initial request is needed to start the
|
| 34 |
+
stream.
|
| 35 |
+
metadata (Sequence[Tuple(str, str)]): RPC metadata to include in
|
| 36 |
+
the request.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
def __init__(self, start_rpc, initial_request=None, metadata=None):
|
| 40 |
+
self._start_rpc = start_rpc
|
| 41 |
+
self._initial_request = initial_request
|
| 42 |
+
self._rpc_metadata = metadata
|
| 43 |
+
self._request_queue = self._create_queue()
|
| 44 |
+
self._request_generator = None
|
| 45 |
+
self._callbacks = []
|
| 46 |
+
self.call = None
|
| 47 |
+
|
| 48 |
+
def _create_queue(self):
|
| 49 |
+
"""Create a queue for requests."""
|
| 50 |
+
raise NotImplementedError("`_create_queue` is not implemented.")
|
| 51 |
+
|
| 52 |
+
def add_done_callback(self, callback):
|
| 53 |
+
"""Adds a callback that will be called when the RPC terminates.
|
| 54 |
+
|
| 55 |
+
This occurs when the RPC errors or is successfully terminated.
|
| 56 |
+
|
| 57 |
+
Args:
|
| 58 |
+
callback (Union[Callable[[grpc.Future], None], Callable[[Any], None]]):
|
| 59 |
+
The callback to execute after gRPC call completed (success or
|
| 60 |
+
failure).
|
| 61 |
+
|
| 62 |
+
For sync streaming gRPC: Callable[[grpc.Future], None]
|
| 63 |
+
|
| 64 |
+
For async streaming gRPC: Callable[[Any], None]
|
| 65 |
+
"""
|
| 66 |
+
self._callbacks.append(callback)
|
| 67 |
+
|
| 68 |
+
def _on_call_done(self, future):
|
| 69 |
+
# This occurs when the RPC errors or is successfully terminated.
|
| 70 |
+
# Note that grpc's "future" here can also be a grpc.RpcError.
|
| 71 |
+
# See note in https://github.com/grpc/grpc/issues/10885#issuecomment-302651331
|
| 72 |
+
# that `grpc.RpcError` is also `grpc.Call`.
|
| 73 |
+
# for asynchronous gRPC call it would be `grpc.aio.AioRpcError`
|
| 74 |
+
|
| 75 |
+
# Note: sync callbacks can be limiting for async code, because you can't
|
| 76 |
+
# await anything in a sync callback.
|
| 77 |
+
for callback in self._callbacks:
|
| 78 |
+
callback(future)
|
| 79 |
+
|
| 80 |
+
@property
|
| 81 |
+
def is_active(self):
|
| 82 |
+
"""True if the gRPC call is not done yet."""
|
| 83 |
+
raise NotImplementedError("`is_active` is not implemented.")
|
| 84 |
+
|
| 85 |
+
@property
|
| 86 |
+
def pending_requests(self):
|
| 87 |
+
"""Estimate of the number of queued requests."""
|
| 88 |
+
return self._request_queue.qsize()
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/client_info.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Helpers for providing client information.
|
| 16 |
+
|
| 17 |
+
Client information is used to send information about the calling client,
|
| 18 |
+
such as the library and Python version, to API services.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import platform
|
| 22 |
+
from typing import Union
|
| 23 |
+
|
| 24 |
+
from google.api_core import version as api_core_version
|
| 25 |
+
|
| 26 |
+
_PY_VERSION = platform.python_version()
|
| 27 |
+
_API_CORE_VERSION = api_core_version.__version__
|
| 28 |
+
|
| 29 |
+
_GRPC_VERSION: Union[str, None]
|
| 30 |
+
|
| 31 |
+
try:
|
| 32 |
+
import grpc
|
| 33 |
+
|
| 34 |
+
_GRPC_VERSION = grpc.__version__
|
| 35 |
+
except ImportError: # pragma: NO COVER
|
| 36 |
+
_GRPC_VERSION = None
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class ClientInfo(object):
|
| 40 |
+
"""Client information used to generate a user-agent for API calls.
|
| 41 |
+
|
| 42 |
+
This user-agent information is sent along with API calls to allow the
|
| 43 |
+
receiving service to do analytics on which versions of Python and Google
|
| 44 |
+
libraries are being used.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
python_version (str): The Python interpreter version, for example,
|
| 48 |
+
``'3.9.6'``.
|
| 49 |
+
grpc_version (Optional[str]): The gRPC library version.
|
| 50 |
+
api_core_version (str): The google-api-core library version.
|
| 51 |
+
gapic_version (Optional[str]): The version of gapic-generated client
|
| 52 |
+
library, if the library was generated by gapic.
|
| 53 |
+
client_library_version (Optional[str]): The version of the client
|
| 54 |
+
library, generally used if the client library was not generated
|
| 55 |
+
by gapic or if additional functionality was built on top of
|
| 56 |
+
a gapic client library.
|
| 57 |
+
user_agent (Optional[str]): Prefix to the user agent header. This is
|
| 58 |
+
used to supply information such as application name or partner tool.
|
| 59 |
+
Recommended format: ``application-or-tool-ID/major.minor.version``.
|
| 60 |
+
rest_version (Optional[str]): A string with labeled versions of the
|
| 61 |
+
dependencies used for REST transport.
|
| 62 |
+
protobuf_runtime_version (Optional[str]): The protobuf runtime version.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
python_version=_PY_VERSION,
|
| 68 |
+
grpc_version=_GRPC_VERSION,
|
| 69 |
+
api_core_version=_API_CORE_VERSION,
|
| 70 |
+
gapic_version=None,
|
| 71 |
+
client_library_version=None,
|
| 72 |
+
user_agent=None,
|
| 73 |
+
rest_version=None,
|
| 74 |
+
protobuf_runtime_version=None,
|
| 75 |
+
):
|
| 76 |
+
self.python_version = python_version
|
| 77 |
+
self.grpc_version = grpc_version
|
| 78 |
+
self.api_core_version = api_core_version
|
| 79 |
+
self.gapic_version = gapic_version
|
| 80 |
+
self.client_library_version = client_library_version
|
| 81 |
+
self.user_agent = user_agent
|
| 82 |
+
self.rest_version = rest_version
|
| 83 |
+
self.protobuf_runtime_version = protobuf_runtime_version
|
| 84 |
+
|
| 85 |
+
def to_user_agent(self):
|
| 86 |
+
"""Returns the user-agent string for this client info."""
|
| 87 |
+
|
| 88 |
+
# Note: the order here is important as the internal metrics system
|
| 89 |
+
# expects these items to be in specific locations.
|
| 90 |
+
ua = ""
|
| 91 |
+
|
| 92 |
+
if self.user_agent is not None:
|
| 93 |
+
ua += "{user_agent} "
|
| 94 |
+
|
| 95 |
+
ua += "gl-python/{python_version} "
|
| 96 |
+
|
| 97 |
+
if self.grpc_version is not None:
|
| 98 |
+
ua += "grpc/{grpc_version} "
|
| 99 |
+
|
| 100 |
+
if self.rest_version is not None:
|
| 101 |
+
ua += "rest/{rest_version} "
|
| 102 |
+
|
| 103 |
+
ua += "gax/{api_core_version} "
|
| 104 |
+
|
| 105 |
+
if self.gapic_version is not None:
|
| 106 |
+
ua += "gapic/{gapic_version} "
|
| 107 |
+
|
| 108 |
+
if self.client_library_version is not None:
|
| 109 |
+
ua += "gccl/{client_library_version} "
|
| 110 |
+
|
| 111 |
+
if self.protobuf_runtime_version is not None:
|
| 112 |
+
ua += "pb/{protobuf_runtime_version} "
|
| 113 |
+
|
| 114 |
+
return ua.format(**self.__dict__).strip()
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/client_logging.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
from typing import List, Optional
|
| 6 |
+
|
| 7 |
+
_LOGGING_INITIALIZED = False
|
| 8 |
+
_BASE_LOGGER_NAME = "google"
|
| 9 |
+
|
| 10 |
+
# Fields to be included in the StructuredLogFormatter.
|
| 11 |
+
#
|
| 12 |
+
# TODO(https://github.com/googleapis/python-api-core/issues/761): Update this list to support additional logging fields.
|
| 13 |
+
_recognized_logging_fields = [
|
| 14 |
+
"httpRequest",
|
| 15 |
+
"rpcName",
|
| 16 |
+
"serviceName",
|
| 17 |
+
"credentialsType",
|
| 18 |
+
"credentialsInfo",
|
| 19 |
+
"universeDomain",
|
| 20 |
+
"request",
|
| 21 |
+
"response",
|
| 22 |
+
"metadata",
|
| 23 |
+
"retryAttempt",
|
| 24 |
+
"httpResponse",
|
| 25 |
+
] # Additional fields to be Logged.
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def logger_configured(logger) -> bool:
|
| 29 |
+
"""Determines whether `logger` has non-default configuration
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
logger: The logger to check.
|
| 33 |
+
|
| 34 |
+
Returns:
|
| 35 |
+
bool: Whether the logger has any non-default configuration.
|
| 36 |
+
"""
|
| 37 |
+
return (
|
| 38 |
+
logger.handlers != [] or logger.level != logging.NOTSET or not logger.propagate
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def initialize_logging():
|
| 43 |
+
"""Initializes "google" loggers, partly based on the environment variable
|
| 44 |
+
|
| 45 |
+
Initializes the "google" logger and any loggers (at the "google"
|
| 46 |
+
level or lower) specified by the environment variable
|
| 47 |
+
GOOGLE_SDK_PYTHON_LOGGING_SCOPE, as long as none of these loggers
|
| 48 |
+
were previously configured. If any such loggers (including the
|
| 49 |
+
"google" logger) are initialized, they are set to NOT propagate
|
| 50 |
+
log events up to their parent loggers.
|
| 51 |
+
|
| 52 |
+
This initialization is executed only once, and hence the
|
| 53 |
+
environment variable is only processed the first time this
|
| 54 |
+
function is called.
|
| 55 |
+
"""
|
| 56 |
+
global _LOGGING_INITIALIZED
|
| 57 |
+
if _LOGGING_INITIALIZED:
|
| 58 |
+
return
|
| 59 |
+
scopes = os.getenv("GOOGLE_SDK_PYTHON_LOGGING_SCOPE", "")
|
| 60 |
+
setup_logging(scopes)
|
| 61 |
+
_LOGGING_INITIALIZED = True
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def parse_logging_scopes(scopes: Optional[str] = None) -> List[str]:
|
| 65 |
+
"""Returns a list of logger names.
|
| 66 |
+
|
| 67 |
+
Splits the single string of comma-separated logger names into a list of individual logger name strings.
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
scopes: The name of a single logger. (In the future, this will be a comma-separated list of multiple loggers.)
|
| 71 |
+
|
| 72 |
+
Returns:
|
| 73 |
+
A list of all the logger names in scopes.
|
| 74 |
+
"""
|
| 75 |
+
if not scopes:
|
| 76 |
+
return []
|
| 77 |
+
# TODO(https://github.com/googleapis/python-api-core/issues/759): check if the namespace is a valid namespace.
|
| 78 |
+
# TODO(b/380481951): Support logging multiple scopes.
|
| 79 |
+
# TODO(b/380483756): Raise or log a warning for an invalid scope.
|
| 80 |
+
namespaces = [scopes]
|
| 81 |
+
return namespaces
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def configure_defaults(logger):
|
| 85 |
+
"""Configures `logger` to emit structured info to stdout."""
|
| 86 |
+
if not logger_configured(logger):
|
| 87 |
+
console_handler = logging.StreamHandler()
|
| 88 |
+
logger.setLevel("DEBUG")
|
| 89 |
+
logger.propagate = False
|
| 90 |
+
formatter = StructuredLogFormatter()
|
| 91 |
+
console_handler.setFormatter(formatter)
|
| 92 |
+
logger.addHandler(console_handler)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def setup_logging(scopes: str = ""):
|
| 96 |
+
"""Sets up logging for the specified `scopes`.
|
| 97 |
+
|
| 98 |
+
If the loggers specified in `scopes` have not been previously
|
| 99 |
+
configured, this will configure them to emit structured log
|
| 100 |
+
entries to stdout, and to not propagate their log events to their
|
| 101 |
+
parent loggers. Additionally, if the "google" logger (whether it
|
| 102 |
+
was specified in `scopes` or not) was not previously configured,
|
| 103 |
+
it will also configure it to not propagate log events to the root
|
| 104 |
+
logger.
|
| 105 |
+
|
| 106 |
+
Args:
|
| 107 |
+
scopes: The name of a single logger. (In the future, this will be a comma-separated list of multiple loggers.)
|
| 108 |
+
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
# only returns valid logger scopes (namespaces)
|
| 112 |
+
# this list has at most one element.
|
| 113 |
+
logger_names = parse_logging_scopes(scopes)
|
| 114 |
+
|
| 115 |
+
for namespace in logger_names:
|
| 116 |
+
# This will either create a module level logger or get the reference of the base logger instantiated above.
|
| 117 |
+
logger = logging.getLogger(namespace)
|
| 118 |
+
|
| 119 |
+
# Configure default settings.
|
| 120 |
+
configure_defaults(logger)
|
| 121 |
+
|
| 122 |
+
# disable log propagation at base logger level to the root logger only if a base logger is not already configured via code changes.
|
| 123 |
+
base_logger = logging.getLogger(_BASE_LOGGER_NAME)
|
| 124 |
+
if not logger_configured(base_logger):
|
| 125 |
+
base_logger.propagate = False
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# TODO(https://github.com/googleapis/python-api-core/issues/763): Expand documentation.
|
| 129 |
+
class StructuredLogFormatter(logging.Formatter):
|
| 130 |
+
# TODO(https://github.com/googleapis/python-api-core/issues/761): ensure that additional fields such as
|
| 131 |
+
# function name, file name, and line no. appear in a log output.
|
| 132 |
+
def format(self, record: logging.LogRecord):
|
| 133 |
+
log_obj = {
|
| 134 |
+
"timestamp": self.formatTime(record),
|
| 135 |
+
"severity": record.levelname,
|
| 136 |
+
"name": record.name,
|
| 137 |
+
"message": record.getMessage(),
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
for field_name in _recognized_logging_fields:
|
| 141 |
+
value = getattr(record, field_name, None)
|
| 142 |
+
if value is not None:
|
| 143 |
+
log_obj[field_name] = value
|
| 144 |
+
return json.dumps(log_obj)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
|
|
|
|
|
| 1 |
+
# Copyright 2019 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Client options class.
|
| 16 |
+
|
| 17 |
+
Client options provide a consistent interface for user options to be defined
|
| 18 |
+
across clients.
|
| 19 |
+
|
| 20 |
+
You can pass a client options object to a client.
|
| 21 |
+
|
| 22 |
+
.. code-block:: python
|
| 23 |
+
|
| 24 |
+
from google.api_core.client_options import ClientOptions
|
| 25 |
+
from google.cloud.vision_v1 import ImageAnnotatorClient
|
| 26 |
+
|
| 27 |
+
def get_client_cert():
|
| 28 |
+
# code to load client certificate and private key.
|
| 29 |
+
return client_cert_bytes, client_private_key_bytes
|
| 30 |
+
|
| 31 |
+
options = ClientOptions(api_endpoint="foo.googleapis.com",
|
| 32 |
+
client_cert_source=get_client_cert)
|
| 33 |
+
|
| 34 |
+
client = ImageAnnotatorClient(client_options=options)
|
| 35 |
+
|
| 36 |
+
You can also pass a mapping object.
|
| 37 |
+
|
| 38 |
+
.. code-block:: python
|
| 39 |
+
|
| 40 |
+
from google.cloud.vision_v1 import ImageAnnotatorClient
|
| 41 |
+
|
| 42 |
+
client = ImageAnnotatorClient(
|
| 43 |
+
client_options={
|
| 44 |
+
"api_endpoint": "foo.googleapis.com",
|
| 45 |
+
"client_cert_source" : get_client_cert
|
| 46 |
+
})
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
from typing import Callable, Mapping, Optional, Sequence, Tuple
|
| 52 |
+
import warnings
|
| 53 |
+
|
| 54 |
+
from google.api_core import general_helpers
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class ClientOptions(object):
|
| 58 |
+
"""Client Options used to set options on clients.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
api_endpoint (Optional[str]): The desired API endpoint, e.g.,
|
| 62 |
+
compute.googleapis.com
|
| 63 |
+
client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A callback
|
| 64 |
+
which returns client certificate bytes and private key bytes both in
|
| 65 |
+
PEM format. ``client_cert_source`` and ``client_encrypted_cert_source``
|
| 66 |
+
are mutually exclusive.
|
| 67 |
+
client_encrypted_cert_source (Optional[Callable[[], Tuple[str, str, bytes]]]):
|
| 68 |
+
A callback which returns client certificate file path, encrypted
|
| 69 |
+
private key file path, and the passphrase bytes.``client_cert_source``
|
| 70 |
+
and ``client_encrypted_cert_source`` are mutually exclusive.
|
| 71 |
+
quota_project_id (Optional[str]): A project name that a client's
|
| 72 |
+
quota belongs to.
|
| 73 |
+
credentials_file (Optional[str]): Deprecated. A path to a file storing credentials.
|
| 74 |
+
``credentials_file` and ``api_key`` are mutually exclusive. This argument will be
|
| 75 |
+
removed in the next major version of `google-api-core`.
|
| 76 |
+
|
| 77 |
+
.. warning::
|
| 78 |
+
Important: If you accept a credential configuration (credential JSON/File/Stream)
|
| 79 |
+
from an external source for authentication to Google Cloud Platform, you must
|
| 80 |
+
validate it before providing it to any Google API or client library. Providing an
|
| 81 |
+
unvalidated credential configuration to Google APIs or libraries can compromise
|
| 82 |
+
the security of your systems and data. For more information, refer to
|
| 83 |
+
`Validate credential configurations from external sources`_.
|
| 84 |
+
|
| 85 |
+
.. _Validate credential configurations from external sources:
|
| 86 |
+
|
| 87 |
+
https://cloud.google.com/docs/authentication/external/externally-sourced-credentials
|
| 88 |
+
scopes (Optional[Sequence[str]]): OAuth access token override scopes.
|
| 89 |
+
api_key (Optional[str]): Google API key. ``credentials_file`` and
|
| 90 |
+
``api_key`` are mutually exclusive.
|
| 91 |
+
api_audience (Optional[str]): The intended audience for the API calls
|
| 92 |
+
to the service that will be set when using certain 3rd party
|
| 93 |
+
authentication flows. Audience is typically a resource identifier.
|
| 94 |
+
If not set, the service endpoint value will be used as a default.
|
| 95 |
+
An example of a valid ``api_audience`` is: "https://language.googleapis.com".
|
| 96 |
+
universe_domain (Optional[str]): The desired universe domain. This must match
|
| 97 |
+
the one in credentials. If not set, the default universe domain is
|
| 98 |
+
`googleapis.com`. If both `api_endpoint` and `universe_domain` are set,
|
| 99 |
+
then `api_endpoint` is used as the service endpoint. If `api_endpoint` is
|
| 100 |
+
not specified, the format will be `{service}.{universe_domain}`.
|
| 101 |
+
|
| 102 |
+
Raises:
|
| 103 |
+
ValueError: If both ``client_cert_source`` and ``client_encrypted_cert_source``
|
| 104 |
+
are provided, or both ``credentials_file`` and ``api_key`` are provided.
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
def __init__(
|
| 108 |
+
self,
|
| 109 |
+
api_endpoint: Optional[str] = None,
|
| 110 |
+
client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
|
| 111 |
+
client_encrypted_cert_source: Optional[
|
| 112 |
+
Callable[[], Tuple[str, str, bytes]]
|
| 113 |
+
] = None,
|
| 114 |
+
quota_project_id: Optional[str] = None,
|
| 115 |
+
credentials_file: Optional[str] = None,
|
| 116 |
+
scopes: Optional[Sequence[str]] = None,
|
| 117 |
+
api_key: Optional[str] = None,
|
| 118 |
+
api_audience: Optional[str] = None,
|
| 119 |
+
universe_domain: Optional[str] = None,
|
| 120 |
+
):
|
| 121 |
+
if credentials_file is not None:
|
| 122 |
+
warnings.warn(general_helpers._CREDENTIALS_FILE_WARNING, DeprecationWarning)
|
| 123 |
+
|
| 124 |
+
if client_cert_source and client_encrypted_cert_source:
|
| 125 |
+
raise ValueError(
|
| 126 |
+
"client_cert_source and client_encrypted_cert_source are mutually exclusive"
|
| 127 |
+
)
|
| 128 |
+
if api_key and credentials_file:
|
| 129 |
+
raise ValueError("api_key and credentials_file are mutually exclusive")
|
| 130 |
+
self.api_endpoint = api_endpoint
|
| 131 |
+
self.client_cert_source = client_cert_source
|
| 132 |
+
self.client_encrypted_cert_source = client_encrypted_cert_source
|
| 133 |
+
self.quota_project_id = quota_project_id
|
| 134 |
+
self.credentials_file = credentials_file
|
| 135 |
+
self.scopes = scopes
|
| 136 |
+
self.api_key = api_key
|
| 137 |
+
self.api_audience = api_audience
|
| 138 |
+
self.universe_domain = universe_domain
|
| 139 |
+
|
| 140 |
+
def __repr__(self) -> str:
|
| 141 |
+
return "ClientOptions: " + repr(self.__dict__)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def from_dict(options: Mapping[str, object]) -> ClientOptions:
|
| 145 |
+
"""Construct a client options object from a mapping object.
|
| 146 |
+
|
| 147 |
+
Args:
|
| 148 |
+
options (collections.abc.Mapping): A mapping object with client options.
|
| 149 |
+
See the docstring for ClientOptions for details on valid arguments.
|
| 150 |
+
"""
|
| 151 |
+
|
| 152 |
+
client_options = ClientOptions()
|
| 153 |
+
|
| 154 |
+
for key, value in options.items():
|
| 155 |
+
if hasattr(client_options, key):
|
| 156 |
+
setattr(client_options, key, value)
|
| 157 |
+
else:
|
| 158 |
+
raise ValueError("ClientOptions does not accept an option '" + key + "'")
|
| 159 |
+
|
| 160 |
+
return client_options
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/datetime_helpers.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Helpers for :mod:`datetime`."""
|
| 16 |
+
|
| 17 |
+
import calendar
|
| 18 |
+
import datetime
|
| 19 |
+
import re
|
| 20 |
+
|
| 21 |
+
from google.protobuf import timestamp_pb2
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
_UTC_EPOCH = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)
|
| 25 |
+
_RFC3339_MICROS = "%Y-%m-%dT%H:%M:%S.%fZ"
|
| 26 |
+
_RFC3339_NO_FRACTION = "%Y-%m-%dT%H:%M:%S"
|
| 27 |
+
# datetime.strptime cannot handle nanosecond precision: parse w/ regex
|
| 28 |
+
_RFC3339_NANOS = re.compile(
|
| 29 |
+
r"""
|
| 30 |
+
(?P<no_fraction>
|
| 31 |
+
\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2} # YYYY-MM-DDTHH:MM:SS
|
| 32 |
+
)
|
| 33 |
+
( # Optional decimal part
|
| 34 |
+
\. # decimal point
|
| 35 |
+
(?P<nanos>\d{1,9}) # nanoseconds, maybe truncated
|
| 36 |
+
)?
|
| 37 |
+
Z # Zulu
|
| 38 |
+
""",
|
| 39 |
+
re.VERBOSE,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def utcnow():
|
| 44 |
+
"""A :meth:`datetime.datetime.utcnow()` alias to allow mocking in tests."""
|
| 45 |
+
return datetime.datetime.now(tz=datetime.timezone.utc).replace(tzinfo=None)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def to_milliseconds(value):
|
| 49 |
+
"""Convert a zone-aware datetime to milliseconds since the unix epoch.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
value (datetime.datetime): The datetime to covert.
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
int: Milliseconds since the unix epoch.
|
| 56 |
+
"""
|
| 57 |
+
micros = to_microseconds(value)
|
| 58 |
+
return micros // 1000
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def from_microseconds(value):
|
| 62 |
+
"""Convert timestamp in microseconds since the unix epoch to datetime.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
value (float): The timestamp to convert, in microseconds.
|
| 66 |
+
|
| 67 |
+
Returns:
|
| 68 |
+
datetime.datetime: The datetime object equivalent to the timestamp in
|
| 69 |
+
UTC.
|
| 70 |
+
"""
|
| 71 |
+
return _UTC_EPOCH + datetime.timedelta(microseconds=value)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def to_microseconds(value):
|
| 75 |
+
"""Convert a datetime to microseconds since the unix epoch.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
value (datetime.datetime): The datetime to covert.
|
| 79 |
+
|
| 80 |
+
Returns:
|
| 81 |
+
int: Microseconds since the unix epoch.
|
| 82 |
+
"""
|
| 83 |
+
if not value.tzinfo:
|
| 84 |
+
value = value.replace(tzinfo=datetime.timezone.utc)
|
| 85 |
+
# Regardless of what timezone is on the value, convert it to UTC.
|
| 86 |
+
value = value.astimezone(datetime.timezone.utc)
|
| 87 |
+
# Convert the datetime to a microsecond timestamp.
|
| 88 |
+
return int(calendar.timegm(value.timetuple()) * 1e6) + value.microsecond
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def from_iso8601_date(value):
|
| 92 |
+
"""Convert a ISO8601 date string to a date.
|
| 93 |
+
|
| 94 |
+
Args:
|
| 95 |
+
value (str): The ISO8601 date string.
|
| 96 |
+
|
| 97 |
+
Returns:
|
| 98 |
+
datetime.date: A date equivalent to the date string.
|
| 99 |
+
"""
|
| 100 |
+
return datetime.datetime.strptime(value, "%Y-%m-%d").date()
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def from_iso8601_time(value):
|
| 104 |
+
"""Convert a zoneless ISO8601 time string to a time.
|
| 105 |
+
|
| 106 |
+
Args:
|
| 107 |
+
value (str): The ISO8601 time string.
|
| 108 |
+
|
| 109 |
+
Returns:
|
| 110 |
+
datetime.time: A time equivalent to the time string.
|
| 111 |
+
"""
|
| 112 |
+
return datetime.datetime.strptime(value, "%H:%M:%S").time()
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def from_rfc3339(value):
|
| 116 |
+
"""Convert an RFC3339-format timestamp to a native datetime.
|
| 117 |
+
|
| 118 |
+
Supported formats include those without fractional seconds, or with
|
| 119 |
+
any fraction up to nanosecond precision.
|
| 120 |
+
|
| 121 |
+
.. note::
|
| 122 |
+
Python datetimes do not support nanosecond precision; this function
|
| 123 |
+
therefore truncates such values to microseconds.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
value (str): The RFC3339 string to convert.
|
| 127 |
+
|
| 128 |
+
Returns:
|
| 129 |
+
datetime.datetime: The datetime object equivalent to the timestamp
|
| 130 |
+
in UTC.
|
| 131 |
+
|
| 132 |
+
Raises:
|
| 133 |
+
ValueError: If the timestamp does not match the RFC3339
|
| 134 |
+
regular expression.
|
| 135 |
+
"""
|
| 136 |
+
with_nanos = _RFC3339_NANOS.match(value)
|
| 137 |
+
|
| 138 |
+
if with_nanos is None:
|
| 139 |
+
raise ValueError(
|
| 140 |
+
"Timestamp: {!r}, does not match pattern: {!r}".format(
|
| 141 |
+
value, _RFC3339_NANOS.pattern
|
| 142 |
+
)
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
bare_seconds = datetime.datetime.strptime(
|
| 146 |
+
with_nanos.group("no_fraction"), _RFC3339_NO_FRACTION
|
| 147 |
+
)
|
| 148 |
+
fraction = with_nanos.group("nanos")
|
| 149 |
+
|
| 150 |
+
if fraction is None:
|
| 151 |
+
micros = 0
|
| 152 |
+
else:
|
| 153 |
+
scale = 9 - len(fraction)
|
| 154 |
+
nanos = int(fraction) * (10**scale)
|
| 155 |
+
micros = nanos // 1000
|
| 156 |
+
|
| 157 |
+
return bare_seconds.replace(microsecond=micros, tzinfo=datetime.timezone.utc)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
from_rfc3339_nanos = from_rfc3339 # from_rfc3339_nanos method was deprecated.
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def to_rfc3339(value, ignore_zone=True):
|
| 164 |
+
"""Convert a datetime to an RFC3339 timestamp string.
|
| 165 |
+
|
| 166 |
+
Args:
|
| 167 |
+
value (datetime.datetime):
|
| 168 |
+
The datetime object to be converted to a string.
|
| 169 |
+
ignore_zone (bool): If True, then the timezone (if any) of the
|
| 170 |
+
datetime object is ignored and the datetime is treated as UTC.
|
| 171 |
+
|
| 172 |
+
Returns:
|
| 173 |
+
str: The RFC3339 formatted string representing the datetime.
|
| 174 |
+
"""
|
| 175 |
+
if not ignore_zone and value.tzinfo is not None:
|
| 176 |
+
# Convert to UTC and remove the time zone info.
|
| 177 |
+
value = value.replace(tzinfo=None) - value.utcoffset()
|
| 178 |
+
|
| 179 |
+
return value.strftime(_RFC3339_MICROS)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class DatetimeWithNanoseconds(datetime.datetime):
|
| 183 |
+
"""Track nanosecond in addition to normal datetime attrs.
|
| 184 |
+
|
| 185 |
+
Nanosecond can be passed only as a keyword argument.
|
| 186 |
+
"""
|
| 187 |
+
|
| 188 |
+
__slots__ = ("_nanosecond",)
|
| 189 |
+
|
| 190 |
+
# pylint: disable=arguments-differ
|
| 191 |
+
def __new__(cls, *args, **kw):
|
| 192 |
+
nanos = kw.pop("nanosecond", 0)
|
| 193 |
+
if nanos > 0:
|
| 194 |
+
if "microsecond" in kw:
|
| 195 |
+
raise TypeError("Specify only one of 'microsecond' or 'nanosecond'")
|
| 196 |
+
kw["microsecond"] = nanos // 1000
|
| 197 |
+
inst = datetime.datetime.__new__(cls, *args, **kw)
|
| 198 |
+
inst._nanosecond = nanos or 0
|
| 199 |
+
return inst
|
| 200 |
+
|
| 201 |
+
# pylint: disable=arguments-differ
|
| 202 |
+
|
| 203 |
+
@property
|
| 204 |
+
def nanosecond(self):
|
| 205 |
+
"""Read-only: nanosecond precision."""
|
| 206 |
+
return self._nanosecond
|
| 207 |
+
|
| 208 |
+
def rfc3339(self):
|
| 209 |
+
"""Return an RFC3339-compliant timestamp.
|
| 210 |
+
|
| 211 |
+
Returns:
|
| 212 |
+
(str): Timestamp string according to RFC3339 spec.
|
| 213 |
+
"""
|
| 214 |
+
if self._nanosecond == 0:
|
| 215 |
+
return to_rfc3339(self)
|
| 216 |
+
nanos = str(self._nanosecond).rjust(9, "0").rstrip("0")
|
| 217 |
+
return "{}.{}Z".format(self.strftime(_RFC3339_NO_FRACTION), nanos)
|
| 218 |
+
|
| 219 |
+
@classmethod
|
| 220 |
+
def from_rfc3339(cls, stamp):
|
| 221 |
+
"""Parse RFC3339-compliant timestamp, preserving nanoseconds.
|
| 222 |
+
|
| 223 |
+
Args:
|
| 224 |
+
stamp (str): RFC3339 stamp, with up to nanosecond precision
|
| 225 |
+
|
| 226 |
+
Returns:
|
| 227 |
+
:class:`DatetimeWithNanoseconds`:
|
| 228 |
+
an instance matching the timestamp string
|
| 229 |
+
|
| 230 |
+
Raises:
|
| 231 |
+
ValueError: if `stamp` does not match the expected format
|
| 232 |
+
"""
|
| 233 |
+
with_nanos = _RFC3339_NANOS.match(stamp)
|
| 234 |
+
if with_nanos is None:
|
| 235 |
+
raise ValueError(
|
| 236 |
+
"Timestamp: {}, does not match pattern: {}".format(
|
| 237 |
+
stamp, _RFC3339_NANOS.pattern
|
| 238 |
+
)
|
| 239 |
+
)
|
| 240 |
+
bare = datetime.datetime.strptime(
|
| 241 |
+
with_nanos.group("no_fraction"), _RFC3339_NO_FRACTION
|
| 242 |
+
)
|
| 243 |
+
fraction = with_nanos.group("nanos")
|
| 244 |
+
if fraction is None:
|
| 245 |
+
nanos = 0
|
| 246 |
+
else:
|
| 247 |
+
scale = 9 - len(fraction)
|
| 248 |
+
nanos = int(fraction) * (10**scale)
|
| 249 |
+
return cls(
|
| 250 |
+
bare.year,
|
| 251 |
+
bare.month,
|
| 252 |
+
bare.day,
|
| 253 |
+
bare.hour,
|
| 254 |
+
bare.minute,
|
| 255 |
+
bare.second,
|
| 256 |
+
nanosecond=nanos,
|
| 257 |
+
tzinfo=datetime.timezone.utc,
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
def timestamp_pb(self):
|
| 261 |
+
"""Return a timestamp message.
|
| 262 |
+
|
| 263 |
+
Returns:
|
| 264 |
+
(:class:`~google.protobuf.timestamp_pb2.Timestamp`): Timestamp message
|
| 265 |
+
"""
|
| 266 |
+
inst = (
|
| 267 |
+
self
|
| 268 |
+
if self.tzinfo is not None
|
| 269 |
+
else self.replace(tzinfo=datetime.timezone.utc)
|
| 270 |
+
)
|
| 271 |
+
delta = inst - _UTC_EPOCH
|
| 272 |
+
seconds = int(delta.total_seconds())
|
| 273 |
+
nanos = self._nanosecond or self.microsecond * 1000
|
| 274 |
+
return timestamp_pb2.Timestamp(seconds=seconds, nanos=nanos)
|
| 275 |
+
|
| 276 |
+
@classmethod
|
| 277 |
+
def from_timestamp_pb(cls, stamp):
|
| 278 |
+
"""Parse RFC3339-compliant timestamp, preserving nanoseconds.
|
| 279 |
+
|
| 280 |
+
Args:
|
| 281 |
+
stamp (:class:`~google.protobuf.timestamp_pb2.Timestamp`): timestamp message
|
| 282 |
+
|
| 283 |
+
Returns:
|
| 284 |
+
:class:`DatetimeWithNanoseconds`:
|
| 285 |
+
an instance matching the timestamp message
|
| 286 |
+
"""
|
| 287 |
+
microseconds = int(stamp.seconds * 1e6)
|
| 288 |
+
bare = from_microseconds(microseconds)
|
| 289 |
+
return cls(
|
| 290 |
+
bare.year,
|
| 291 |
+
bare.month,
|
| 292 |
+
bare.day,
|
| 293 |
+
bare.hour,
|
| 294 |
+
bare.minute,
|
| 295 |
+
bare.second,
|
| 296 |
+
nanosecond=stamp.nanos,
|
| 297 |
+
tzinfo=datetime.timezone.utc,
|
| 298 |
+
)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/exceptions.py
ADDED
|
@@ -0,0 +1,669 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2014 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Exceptions raised by Google API core & clients.
|
| 16 |
+
|
| 17 |
+
This module provides base classes for all errors raised by libraries based
|
| 18 |
+
on :mod:`google.api_core`, including both HTTP and gRPC clients.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import absolute_import
|
| 22 |
+
from __future__ import unicode_literals
|
| 23 |
+
|
| 24 |
+
import http.client
|
| 25 |
+
from typing import Optional, Dict
|
| 26 |
+
import warnings
|
| 27 |
+
|
| 28 |
+
from google.rpc import error_details_pb2
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _warn_could_not_import_grpcio_status():
|
| 32 |
+
warnings.warn(
|
| 33 |
+
"Please install grpcio-status to obtain helpful grpc error messages.",
|
| 34 |
+
ImportWarning,
|
| 35 |
+
) # pragma: NO COVER
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
import grpc
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
from grpc_status import rpc_status
|
| 43 |
+
except ImportError: # pragma: NO COVER
|
| 44 |
+
_warn_could_not_import_grpcio_status()
|
| 45 |
+
rpc_status = None
|
| 46 |
+
except ImportError: # pragma: NO COVER
|
| 47 |
+
grpc = None
|
| 48 |
+
|
| 49 |
+
# Lookup tables for mapping exceptions from HTTP and gRPC transports.
|
| 50 |
+
# Populated by _GoogleAPICallErrorMeta
|
| 51 |
+
_HTTP_CODE_TO_EXCEPTION: Dict[int, Exception] = {}
|
| 52 |
+
_GRPC_CODE_TO_EXCEPTION: Dict[int, Exception] = {}
|
| 53 |
+
|
| 54 |
+
# Additional lookup table to map integer status codes to grpc status code
|
| 55 |
+
# grpc does not currently support initializing enums from ints
|
| 56 |
+
# i.e., grpc.StatusCode(5) raises an error
|
| 57 |
+
_INT_TO_GRPC_CODE = {}
|
| 58 |
+
if grpc is not None: # pragma: no branch
|
| 59 |
+
for x in grpc.StatusCode:
|
| 60 |
+
_INT_TO_GRPC_CODE[x.value[0]] = x
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class GoogleAPIError(Exception):
|
| 64 |
+
"""Base class for all exceptions raised by Google API Clients."""
|
| 65 |
+
|
| 66 |
+
pass
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class DuplicateCredentialArgs(GoogleAPIError):
|
| 70 |
+
"""Raised when multiple credentials are passed."""
|
| 71 |
+
|
| 72 |
+
pass
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class RetryError(GoogleAPIError):
|
| 76 |
+
"""Raised when a function has exhausted all of its available retries.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
message (str): The exception message.
|
| 80 |
+
cause (Exception): The last exception raised when retrying the
|
| 81 |
+
function.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
def __init__(self, message, cause):
|
| 85 |
+
super(RetryError, self).__init__(message)
|
| 86 |
+
self.message = message
|
| 87 |
+
self._cause = cause
|
| 88 |
+
|
| 89 |
+
@property
|
| 90 |
+
def cause(self):
|
| 91 |
+
"""The last exception raised when retrying the function."""
|
| 92 |
+
return self._cause
|
| 93 |
+
|
| 94 |
+
def __str__(self):
|
| 95 |
+
return "{}, last exception: {}".format(self.message, self.cause)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class _GoogleAPICallErrorMeta(type):
|
| 99 |
+
"""Metaclass for registering GoogleAPICallError subclasses."""
|
| 100 |
+
|
| 101 |
+
def __new__(mcs, name, bases, class_dict):
|
| 102 |
+
cls = type.__new__(mcs, name, bases, class_dict)
|
| 103 |
+
if cls.code is not None:
|
| 104 |
+
_HTTP_CODE_TO_EXCEPTION.setdefault(cls.code, cls)
|
| 105 |
+
if cls.grpc_status_code is not None:
|
| 106 |
+
_GRPC_CODE_TO_EXCEPTION.setdefault(cls.grpc_status_code, cls)
|
| 107 |
+
return cls
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class GoogleAPICallError(GoogleAPIError, metaclass=_GoogleAPICallErrorMeta):
|
| 111 |
+
"""Base class for exceptions raised by calling API methods.
|
| 112 |
+
|
| 113 |
+
Args:
|
| 114 |
+
message (str): The exception message.
|
| 115 |
+
errors (Sequence[Any]): An optional list of error details.
|
| 116 |
+
details (Sequence[Any]): An optional list of objects defined in google.rpc.error_details.
|
| 117 |
+
response (Union[requests.Request, grpc.Call]): The response or
|
| 118 |
+
gRPC call metadata.
|
| 119 |
+
error_info (Union[error_details_pb2.ErrorInfo, None]): An optional object containing error info
|
| 120 |
+
(google.rpc.error_details.ErrorInfo).
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
code: Optional[int] = None
|
| 124 |
+
"""Optional[int]: The HTTP status code associated with this error.
|
| 125 |
+
|
| 126 |
+
This may be ``None`` if the exception does not have a direct mapping
|
| 127 |
+
to an HTTP error.
|
| 128 |
+
|
| 129 |
+
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
grpc_status_code: Optional["grpc.StatusCode"] = None
|
| 133 |
+
"""Optional[grpc.StatusCode]: The gRPC status code associated with this
|
| 134 |
+
error.
|
| 135 |
+
|
| 136 |
+
This may be ``None`` if the exception does not match up to a gRPC error.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
def __init__(self, message, errors=(), details=(), response=None, error_info=None):
|
| 140 |
+
super(GoogleAPICallError, self).__init__(message)
|
| 141 |
+
self.message = message
|
| 142 |
+
"""str: The exception message."""
|
| 143 |
+
self._errors = errors
|
| 144 |
+
self._details = details
|
| 145 |
+
self._response = response
|
| 146 |
+
self._error_info = error_info
|
| 147 |
+
|
| 148 |
+
def __str__(self):
|
| 149 |
+
error_msg = "{} {}".format(self.code, self.message)
|
| 150 |
+
if self.details:
|
| 151 |
+
error_msg = "{} {}".format(error_msg, self.details)
|
| 152 |
+
# Note: This else condition can be removed once proposal A from
|
| 153 |
+
# b/284179390 is implemented.
|
| 154 |
+
else:
|
| 155 |
+
if self.errors:
|
| 156 |
+
errors = [
|
| 157 |
+
f"{error.code}: {error.message}"
|
| 158 |
+
for error in self.errors
|
| 159 |
+
if hasattr(error, "code") and hasattr(error, "message")
|
| 160 |
+
]
|
| 161 |
+
if errors:
|
| 162 |
+
error_msg = "{} {}".format(error_msg, "\n".join(errors))
|
| 163 |
+
return error_msg
|
| 164 |
+
|
| 165 |
+
@property
|
| 166 |
+
def reason(self):
|
| 167 |
+
"""The reason of the error.
|
| 168 |
+
|
| 169 |
+
Reference:
|
| 170 |
+
https://github.com/googleapis/googleapis/blob/master/google/rpc/error_details.proto#L112
|
| 171 |
+
|
| 172 |
+
Returns:
|
| 173 |
+
Union[str, None]: An optional string containing reason of the error.
|
| 174 |
+
"""
|
| 175 |
+
return self._error_info.reason if self._error_info else None
|
| 176 |
+
|
| 177 |
+
@property
|
| 178 |
+
def domain(self):
|
| 179 |
+
"""The logical grouping to which the "reason" belongs.
|
| 180 |
+
|
| 181 |
+
Reference:
|
| 182 |
+
https://github.com/googleapis/googleapis/blob/master/google/rpc/error_details.proto#L112
|
| 183 |
+
|
| 184 |
+
Returns:
|
| 185 |
+
Union[str, None]: An optional string containing a logical grouping to which the "reason" belongs.
|
| 186 |
+
"""
|
| 187 |
+
return self._error_info.domain if self._error_info else None
|
| 188 |
+
|
| 189 |
+
@property
|
| 190 |
+
def metadata(self):
|
| 191 |
+
"""Additional structured details about this error.
|
| 192 |
+
|
| 193 |
+
Reference:
|
| 194 |
+
https://github.com/googleapis/googleapis/blob/master/google/rpc/error_details.proto#L112
|
| 195 |
+
|
| 196 |
+
Returns:
|
| 197 |
+
Union[Dict[str, str], None]: An optional object containing structured details about the error.
|
| 198 |
+
"""
|
| 199 |
+
return self._error_info.metadata if self._error_info else None
|
| 200 |
+
|
| 201 |
+
@property
|
| 202 |
+
def errors(self):
|
| 203 |
+
"""Detailed error information.
|
| 204 |
+
|
| 205 |
+
Returns:
|
| 206 |
+
Sequence[Any]: A list of additional error details.
|
| 207 |
+
"""
|
| 208 |
+
return list(self._errors)
|
| 209 |
+
|
| 210 |
+
@property
|
| 211 |
+
def details(self):
|
| 212 |
+
"""Information contained in google.rpc.status.details.
|
| 213 |
+
|
| 214 |
+
Reference:
|
| 215 |
+
https://github.com/googleapis/googleapis/blob/master/google/rpc/status.proto
|
| 216 |
+
https://github.com/googleapis/googleapis/blob/master/google/rpc/error_details.proto
|
| 217 |
+
|
| 218 |
+
Returns:
|
| 219 |
+
Sequence[Any]: A list of structured objects from error_details.proto
|
| 220 |
+
"""
|
| 221 |
+
return list(self._details)
|
| 222 |
+
|
| 223 |
+
@property
|
| 224 |
+
def response(self):
|
| 225 |
+
"""Optional[Union[requests.Request, grpc.Call]]: The response or
|
| 226 |
+
gRPC call metadata."""
|
| 227 |
+
return self._response
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class Redirection(GoogleAPICallError):
|
| 231 |
+
"""Base class for for all redirection (HTTP 3xx) responses."""
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
class MovedPermanently(Redirection):
|
| 235 |
+
"""Exception mapping a ``301 Moved Permanently`` response."""
|
| 236 |
+
|
| 237 |
+
code = http.client.MOVED_PERMANENTLY
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
class NotModified(Redirection):
|
| 241 |
+
"""Exception mapping a ``304 Not Modified`` response."""
|
| 242 |
+
|
| 243 |
+
code = http.client.NOT_MODIFIED
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class TemporaryRedirect(Redirection):
|
| 247 |
+
"""Exception mapping a ``307 Temporary Redirect`` response."""
|
| 248 |
+
|
| 249 |
+
code = http.client.TEMPORARY_REDIRECT
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
class ResumeIncomplete(Redirection):
|
| 253 |
+
"""Exception mapping a ``308 Resume Incomplete`` response.
|
| 254 |
+
|
| 255 |
+
.. note:: :attr:`http.client.PERMANENT_REDIRECT` is ``308``, but Google
|
| 256 |
+
APIs differ in their use of this status code.
|
| 257 |
+
"""
|
| 258 |
+
|
| 259 |
+
code = 308
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
class ClientError(GoogleAPICallError):
|
| 263 |
+
"""Base class for all client error (HTTP 4xx) responses."""
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
class BadRequest(ClientError):
|
| 267 |
+
"""Exception mapping a ``400 Bad Request`` response."""
|
| 268 |
+
|
| 269 |
+
code = http.client.BAD_REQUEST
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
class InvalidArgument(BadRequest):
|
| 273 |
+
"""Exception mapping a :attr:`grpc.StatusCode.INVALID_ARGUMENT` error."""
|
| 274 |
+
|
| 275 |
+
grpc_status_code = grpc.StatusCode.INVALID_ARGUMENT if grpc is not None else None
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class FailedPrecondition(BadRequest):
|
| 279 |
+
"""Exception mapping a :attr:`grpc.StatusCode.FAILED_PRECONDITION`
|
| 280 |
+
error."""
|
| 281 |
+
|
| 282 |
+
grpc_status_code = grpc.StatusCode.FAILED_PRECONDITION if grpc is not None else None
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class OutOfRange(BadRequest):
|
| 286 |
+
"""Exception mapping a :attr:`grpc.StatusCode.OUT_OF_RANGE` error."""
|
| 287 |
+
|
| 288 |
+
grpc_status_code = grpc.StatusCode.OUT_OF_RANGE if grpc is not None else None
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
class Unauthorized(ClientError):
|
| 292 |
+
"""Exception mapping a ``401 Unauthorized`` response."""
|
| 293 |
+
|
| 294 |
+
code = http.client.UNAUTHORIZED
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
class Unauthenticated(Unauthorized):
|
| 298 |
+
"""Exception mapping a :attr:`grpc.StatusCode.UNAUTHENTICATED` error."""
|
| 299 |
+
|
| 300 |
+
grpc_status_code = grpc.StatusCode.UNAUTHENTICATED if grpc is not None else None
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
class Forbidden(ClientError):
|
| 304 |
+
"""Exception mapping a ``403 Forbidden`` response."""
|
| 305 |
+
|
| 306 |
+
code = http.client.FORBIDDEN
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
class PermissionDenied(Forbidden):
|
| 310 |
+
"""Exception mapping a :attr:`grpc.StatusCode.PERMISSION_DENIED` error."""
|
| 311 |
+
|
| 312 |
+
grpc_status_code = grpc.StatusCode.PERMISSION_DENIED if grpc is not None else None
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
class NotFound(ClientError):
|
| 316 |
+
"""Exception mapping a ``404 Not Found`` response or a
|
| 317 |
+
:attr:`grpc.StatusCode.NOT_FOUND` error."""
|
| 318 |
+
|
| 319 |
+
code = http.client.NOT_FOUND
|
| 320 |
+
grpc_status_code = grpc.StatusCode.NOT_FOUND if grpc is not None else None
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
class MethodNotAllowed(ClientError):
|
| 324 |
+
"""Exception mapping a ``405 Method Not Allowed`` response."""
|
| 325 |
+
|
| 326 |
+
code = http.client.METHOD_NOT_ALLOWED
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
class Conflict(ClientError):
|
| 330 |
+
"""Exception mapping a ``409 Conflict`` response."""
|
| 331 |
+
|
| 332 |
+
code = http.client.CONFLICT
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
class AlreadyExists(Conflict):
|
| 336 |
+
"""Exception mapping a :attr:`grpc.StatusCode.ALREADY_EXISTS` error."""
|
| 337 |
+
|
| 338 |
+
grpc_status_code = grpc.StatusCode.ALREADY_EXISTS if grpc is not None else None
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class Aborted(Conflict):
|
| 342 |
+
"""Exception mapping a :attr:`grpc.StatusCode.ABORTED` error."""
|
| 343 |
+
|
| 344 |
+
grpc_status_code = grpc.StatusCode.ABORTED if grpc is not None else None
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
class LengthRequired(ClientError):
|
| 348 |
+
"""Exception mapping a ``411 Length Required`` response."""
|
| 349 |
+
|
| 350 |
+
code = http.client.LENGTH_REQUIRED
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
class PreconditionFailed(ClientError):
|
| 354 |
+
"""Exception mapping a ``412 Precondition Failed`` response."""
|
| 355 |
+
|
| 356 |
+
code = http.client.PRECONDITION_FAILED
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
class RequestRangeNotSatisfiable(ClientError):
|
| 360 |
+
"""Exception mapping a ``416 Request Range Not Satisfiable`` response."""
|
| 361 |
+
|
| 362 |
+
code = http.client.REQUESTED_RANGE_NOT_SATISFIABLE
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class TooManyRequests(ClientError):
|
| 366 |
+
"""Exception mapping a ``429 Too Many Requests`` response."""
|
| 367 |
+
|
| 368 |
+
code = http.client.TOO_MANY_REQUESTS
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
class ResourceExhausted(TooManyRequests):
|
| 372 |
+
"""Exception mapping a :attr:`grpc.StatusCode.RESOURCE_EXHAUSTED` error."""
|
| 373 |
+
|
| 374 |
+
grpc_status_code = grpc.StatusCode.RESOURCE_EXHAUSTED if grpc is not None else None
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
class Cancelled(ClientError):
|
| 378 |
+
"""Exception mapping a :attr:`grpc.StatusCode.CANCELLED` error."""
|
| 379 |
+
|
| 380 |
+
# This maps to HTTP status code 499. See
|
| 381 |
+
# https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
|
| 382 |
+
code = 499
|
| 383 |
+
grpc_status_code = grpc.StatusCode.CANCELLED if grpc is not None else None
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
class ServerError(GoogleAPICallError):
|
| 387 |
+
"""Base for 5xx responses."""
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
class InternalServerError(ServerError):
|
| 391 |
+
"""Exception mapping a ``500 Internal Server Error`` response. or a
|
| 392 |
+
:attr:`grpc.StatusCode.INTERNAL` error."""
|
| 393 |
+
|
| 394 |
+
code = http.client.INTERNAL_SERVER_ERROR
|
| 395 |
+
grpc_status_code = grpc.StatusCode.INTERNAL if grpc is not None else None
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
class Unknown(ServerError):
|
| 399 |
+
"""Exception mapping a :attr:`grpc.StatusCode.UNKNOWN` error."""
|
| 400 |
+
|
| 401 |
+
grpc_status_code = grpc.StatusCode.UNKNOWN if grpc is not None else None
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
class DataLoss(ServerError):
|
| 405 |
+
"""Exception mapping a :attr:`grpc.StatusCode.DATA_LOSS` error."""
|
| 406 |
+
|
| 407 |
+
grpc_status_code = grpc.StatusCode.DATA_LOSS if grpc is not None else None
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
class MethodNotImplemented(ServerError):
|
| 411 |
+
"""Exception mapping a ``501 Not Implemented`` response or a
|
| 412 |
+
:attr:`grpc.StatusCode.UNIMPLEMENTED` error."""
|
| 413 |
+
|
| 414 |
+
code = http.client.NOT_IMPLEMENTED
|
| 415 |
+
grpc_status_code = grpc.StatusCode.UNIMPLEMENTED if grpc is not None else None
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
class BadGateway(ServerError):
|
| 419 |
+
"""Exception mapping a ``502 Bad Gateway`` response."""
|
| 420 |
+
|
| 421 |
+
code = http.client.BAD_GATEWAY
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
class ServiceUnavailable(ServerError):
|
| 425 |
+
"""Exception mapping a ``503 Service Unavailable`` response or a
|
| 426 |
+
:attr:`grpc.StatusCode.UNAVAILABLE` error."""
|
| 427 |
+
|
| 428 |
+
code = http.client.SERVICE_UNAVAILABLE
|
| 429 |
+
grpc_status_code = grpc.StatusCode.UNAVAILABLE if grpc is not None else None
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
class GatewayTimeout(ServerError):
|
| 433 |
+
"""Exception mapping a ``504 Gateway Timeout`` response."""
|
| 434 |
+
|
| 435 |
+
code = http.client.GATEWAY_TIMEOUT
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
class DeadlineExceeded(GatewayTimeout):
|
| 439 |
+
"""Exception mapping a :attr:`grpc.StatusCode.DEADLINE_EXCEEDED` error."""
|
| 440 |
+
|
| 441 |
+
grpc_status_code = grpc.StatusCode.DEADLINE_EXCEEDED if grpc is not None else None
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
class AsyncRestUnsupportedParameterError(NotImplementedError):
|
| 445 |
+
"""Raised when an unsupported parameter is configured against async rest transport."""
|
| 446 |
+
|
| 447 |
+
pass
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def exception_class_for_http_status(status_code):
|
| 451 |
+
"""Return the exception class for a specific HTTP status code.
|
| 452 |
+
|
| 453 |
+
Args:
|
| 454 |
+
status_code (int): The HTTP status code.
|
| 455 |
+
|
| 456 |
+
Returns:
|
| 457 |
+
:func:`type`: the appropriate subclass of :class:`GoogleAPICallError`.
|
| 458 |
+
"""
|
| 459 |
+
return _HTTP_CODE_TO_EXCEPTION.get(status_code, GoogleAPICallError)
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def from_http_status(status_code, message, **kwargs):
|
| 463 |
+
"""Create a :class:`GoogleAPICallError` from an HTTP status code.
|
| 464 |
+
|
| 465 |
+
Args:
|
| 466 |
+
status_code (int): The HTTP status code.
|
| 467 |
+
message (str): The exception message.
|
| 468 |
+
kwargs: Additional arguments passed to the :class:`GoogleAPICallError`
|
| 469 |
+
constructor.
|
| 470 |
+
|
| 471 |
+
Returns:
|
| 472 |
+
GoogleAPICallError: An instance of the appropriate subclass of
|
| 473 |
+
:class:`GoogleAPICallError`.
|
| 474 |
+
"""
|
| 475 |
+
error_class = exception_class_for_http_status(status_code)
|
| 476 |
+
error = error_class(message, **kwargs)
|
| 477 |
+
|
| 478 |
+
if error.code is None:
|
| 479 |
+
error.code = status_code
|
| 480 |
+
|
| 481 |
+
return error
|
| 482 |
+
|
| 483 |
+
|
| 484 |
+
def _format_rest_error_message(error, method, url):
|
| 485 |
+
method = method.upper() if method else None
|
| 486 |
+
message = "{method} {url}: {error}".format(
|
| 487 |
+
method=method,
|
| 488 |
+
url=url,
|
| 489 |
+
error=error,
|
| 490 |
+
)
|
| 491 |
+
return message
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
# NOTE: We're moving away from `from_http_status` because it expects an aiohttp response compared
|
| 495 |
+
# to `format_http_response_error` which expects a more abstract response from google.auth and is
|
| 496 |
+
# compatible with both sync and async response types.
|
| 497 |
+
# TODO(https://github.com/googleapis/python-api-core/issues/691): Add type hint for response.
|
| 498 |
+
def format_http_response_error(
|
| 499 |
+
response, method: str, url: str, payload: Optional[Dict] = None
|
| 500 |
+
):
|
| 501 |
+
"""Create a :class:`GoogleAPICallError` from a google auth rest response.
|
| 502 |
+
|
| 503 |
+
Args:
|
| 504 |
+
response Union[google.auth.transport.Response, google.auth.aio.transport.Response]: The HTTP response.
|
| 505 |
+
method Optional(str): The HTTP request method.
|
| 506 |
+
url Optional(str): The HTTP request url.
|
| 507 |
+
payload Optional(dict): The HTTP response payload. If not passed in, it is read from response for a response type of google.auth.transport.Response.
|
| 508 |
+
|
| 509 |
+
Returns:
|
| 510 |
+
GoogleAPICallError: An instance of the appropriate subclass of
|
| 511 |
+
:class:`GoogleAPICallError`, with the message and errors populated
|
| 512 |
+
from the response.
|
| 513 |
+
"""
|
| 514 |
+
payload = {} if not payload else payload
|
| 515 |
+
error_message = payload.get("error", {}).get("message", "unknown error")
|
| 516 |
+
errors = payload.get("error", {}).get("errors", ())
|
| 517 |
+
# In JSON, details are already formatted in developer-friendly way.
|
| 518 |
+
details = payload.get("error", {}).get("details", ())
|
| 519 |
+
error_info_list = list(
|
| 520 |
+
filter(
|
| 521 |
+
lambda detail: detail.get("@type", "")
|
| 522 |
+
== "type.googleapis.com/google.rpc.ErrorInfo",
|
| 523 |
+
details,
|
| 524 |
+
)
|
| 525 |
+
)
|
| 526 |
+
error_info = error_info_list[0] if error_info_list else None
|
| 527 |
+
message = _format_rest_error_message(error_message, method, url)
|
| 528 |
+
|
| 529 |
+
exception = from_http_status(
|
| 530 |
+
response.status_code,
|
| 531 |
+
message,
|
| 532 |
+
errors=errors,
|
| 533 |
+
details=details,
|
| 534 |
+
response=response,
|
| 535 |
+
error_info=error_info,
|
| 536 |
+
)
|
| 537 |
+
return exception
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
def from_http_response(response):
|
| 541 |
+
"""Create a :class:`GoogleAPICallError` from a :class:`requests.Response`.
|
| 542 |
+
|
| 543 |
+
Args:
|
| 544 |
+
response (requests.Response): The HTTP response.
|
| 545 |
+
|
| 546 |
+
Returns:
|
| 547 |
+
GoogleAPICallError: An instance of the appropriate subclass of
|
| 548 |
+
:class:`GoogleAPICallError`, with the message and errors populated
|
| 549 |
+
from the response.
|
| 550 |
+
"""
|
| 551 |
+
try:
|
| 552 |
+
payload = response.json()
|
| 553 |
+
except ValueError:
|
| 554 |
+
payload = {"error": {"message": response.text or "unknown error"}}
|
| 555 |
+
return format_http_response_error(
|
| 556 |
+
response, response.request.method, response.request.url, payload
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def exception_class_for_grpc_status(status_code):
|
| 561 |
+
"""Return the exception class for a specific :class:`grpc.StatusCode`.
|
| 562 |
+
|
| 563 |
+
Args:
|
| 564 |
+
status_code (grpc.StatusCode): The gRPC status code.
|
| 565 |
+
|
| 566 |
+
Returns:
|
| 567 |
+
:func:`type`: the appropriate subclass of :class:`GoogleAPICallError`.
|
| 568 |
+
"""
|
| 569 |
+
return _GRPC_CODE_TO_EXCEPTION.get(status_code, GoogleAPICallError)
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
def from_grpc_status(status_code, message, **kwargs):
|
| 573 |
+
"""Create a :class:`GoogleAPICallError` from a :class:`grpc.StatusCode`.
|
| 574 |
+
|
| 575 |
+
Args:
|
| 576 |
+
status_code (Union[grpc.StatusCode, int]): The gRPC status code.
|
| 577 |
+
message (str): The exception message.
|
| 578 |
+
kwargs: Additional arguments passed to the :class:`GoogleAPICallError`
|
| 579 |
+
constructor.
|
| 580 |
+
|
| 581 |
+
Returns:
|
| 582 |
+
GoogleAPICallError: An instance of the appropriate subclass of
|
| 583 |
+
:class:`GoogleAPICallError`.
|
| 584 |
+
"""
|
| 585 |
+
|
| 586 |
+
if isinstance(status_code, int):
|
| 587 |
+
status_code = _INT_TO_GRPC_CODE.get(status_code, status_code)
|
| 588 |
+
|
| 589 |
+
error_class = exception_class_for_grpc_status(status_code)
|
| 590 |
+
error = error_class(message, **kwargs)
|
| 591 |
+
|
| 592 |
+
if error.grpc_status_code is None:
|
| 593 |
+
error.grpc_status_code = status_code
|
| 594 |
+
|
| 595 |
+
return error
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
def _is_informative_grpc_error(rpc_exc):
|
| 599 |
+
return hasattr(rpc_exc, "code") and hasattr(rpc_exc, "details")
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
def _parse_grpc_error_details(rpc_exc):
|
| 603 |
+
if not rpc_status: # pragma: NO COVER
|
| 604 |
+
_warn_could_not_import_grpcio_status()
|
| 605 |
+
return [], None
|
| 606 |
+
try:
|
| 607 |
+
status = rpc_status.from_call(rpc_exc)
|
| 608 |
+
except NotImplementedError: # workaround
|
| 609 |
+
return [], None
|
| 610 |
+
|
| 611 |
+
if not status:
|
| 612 |
+
return [], None
|
| 613 |
+
|
| 614 |
+
possible_errors = [
|
| 615 |
+
error_details_pb2.BadRequest,
|
| 616 |
+
error_details_pb2.PreconditionFailure,
|
| 617 |
+
error_details_pb2.QuotaFailure,
|
| 618 |
+
error_details_pb2.ErrorInfo,
|
| 619 |
+
error_details_pb2.RetryInfo,
|
| 620 |
+
error_details_pb2.ResourceInfo,
|
| 621 |
+
error_details_pb2.RequestInfo,
|
| 622 |
+
error_details_pb2.DebugInfo,
|
| 623 |
+
error_details_pb2.Help,
|
| 624 |
+
error_details_pb2.LocalizedMessage,
|
| 625 |
+
]
|
| 626 |
+
error_info = None
|
| 627 |
+
error_details = []
|
| 628 |
+
for detail in status.details:
|
| 629 |
+
matched_detail_cls = list(
|
| 630 |
+
filter(lambda x: detail.Is(x.DESCRIPTOR), possible_errors)
|
| 631 |
+
)
|
| 632 |
+
# If nothing matched, use detail directly.
|
| 633 |
+
if len(matched_detail_cls) == 0:
|
| 634 |
+
info = detail
|
| 635 |
+
else:
|
| 636 |
+
info = matched_detail_cls[0]()
|
| 637 |
+
detail.Unpack(info)
|
| 638 |
+
error_details.append(info)
|
| 639 |
+
if isinstance(info, error_details_pb2.ErrorInfo):
|
| 640 |
+
error_info = info
|
| 641 |
+
return error_details, error_info
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
def from_grpc_error(rpc_exc):
|
| 645 |
+
"""Create a :class:`GoogleAPICallError` from a :class:`grpc.RpcError`.
|
| 646 |
+
|
| 647 |
+
Args:
|
| 648 |
+
rpc_exc (grpc.RpcError): The gRPC error.
|
| 649 |
+
|
| 650 |
+
Returns:
|
| 651 |
+
GoogleAPICallError: An instance of the appropriate subclass of
|
| 652 |
+
:class:`GoogleAPICallError`.
|
| 653 |
+
"""
|
| 654 |
+
# NOTE(lidiz) All gRPC error shares the parent class grpc.RpcError.
|
| 655 |
+
# However, check for grpc.RpcError breaks backward compatibility.
|
| 656 |
+
if (
|
| 657 |
+
grpc is not None and isinstance(rpc_exc, grpc.Call)
|
| 658 |
+
) or _is_informative_grpc_error(rpc_exc):
|
| 659 |
+
details, err_info = _parse_grpc_error_details(rpc_exc)
|
| 660 |
+
return from_grpc_status(
|
| 661 |
+
rpc_exc.code(),
|
| 662 |
+
rpc_exc.details(),
|
| 663 |
+
errors=(rpc_exc,),
|
| 664 |
+
details=details,
|
| 665 |
+
response=rpc_exc,
|
| 666 |
+
error_info=err_info,
|
| 667 |
+
)
|
| 668 |
+
else:
|
| 669 |
+
return GoogleAPICallError(str(rpc_exc), errors=(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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Futures for extended long-running operations returned from Google Cloud APIs.
|
| 16 |
+
|
| 17 |
+
These futures can be used to synchronously wait for the result of a
|
| 18 |
+
long-running operations using :meth:`ExtendedOperation.result`:
|
| 19 |
+
|
| 20 |
+
.. code-block:: python
|
| 21 |
+
|
| 22 |
+
extended_operation = my_api_client.long_running_method()
|
| 23 |
+
|
| 24 |
+
extended_operation.result()
|
| 25 |
+
|
| 26 |
+
Or asynchronously using callbacks and :meth:`Operation.add_done_callback`:
|
| 27 |
+
|
| 28 |
+
.. code-block:: python
|
| 29 |
+
|
| 30 |
+
extended_operation = my_api_client.long_running_method()
|
| 31 |
+
|
| 32 |
+
def my_callback(ex_op):
|
| 33 |
+
print(f"Operation {ex_op.name} completed")
|
| 34 |
+
|
| 35 |
+
extended_operation.add_done_callback(my_callback)
|
| 36 |
+
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
import threading
|
| 40 |
+
|
| 41 |
+
from google.api_core import exceptions
|
| 42 |
+
from google.api_core.future import polling
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class ExtendedOperation(polling.PollingFuture):
|
| 46 |
+
"""An ExtendedOperation future for interacting with a Google API Long-Running Operation.
|
| 47 |
+
|
| 48 |
+
Args:
|
| 49 |
+
extended_operation (proto.Message): The initial operation.
|
| 50 |
+
refresh (Callable[[], type(extended_operation)]): A callable that returns
|
| 51 |
+
the latest state of the operation.
|
| 52 |
+
cancel (Callable[[], None]): A callable that tries to cancel the operation.
|
| 53 |
+
polling Optional(google.api_core.retry.Retry): The configuration used
|
| 54 |
+
for polling. This can be used to control how often :meth:`done`
|
| 55 |
+
is polled. If the ``timeout`` argument to :meth:`result` is
|
| 56 |
+
specified it will override the ``polling.timeout`` property.
|
| 57 |
+
retry Optional(google.api_core.retry.Retry): DEPRECATED use ``polling``
|
| 58 |
+
instead. If specified it will override ``polling`` parameter to
|
| 59 |
+
maintain backward compatibility.
|
| 60 |
+
|
| 61 |
+
Note: Most long-running API methods use google.api_core.operation.Operation
|
| 62 |
+
This class is a wrapper for a subset of methods that use alternative
|
| 63 |
+
Long-Running Operation (LRO) semantics.
|
| 64 |
+
|
| 65 |
+
Note: there is not a concrete type the extended operation must be.
|
| 66 |
+
It MUST have fields that correspond to the following, POSSIBLY WITH DIFFERENT NAMES:
|
| 67 |
+
* name: str
|
| 68 |
+
* status: Union[str, bool, enum.Enum]
|
| 69 |
+
* error_code: int
|
| 70 |
+
* error_message: str
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
def __init__(
|
| 74 |
+
self,
|
| 75 |
+
extended_operation,
|
| 76 |
+
refresh,
|
| 77 |
+
cancel,
|
| 78 |
+
polling=polling.DEFAULT_POLLING,
|
| 79 |
+
**kwargs,
|
| 80 |
+
):
|
| 81 |
+
super().__init__(polling=polling, **kwargs)
|
| 82 |
+
self._extended_operation = extended_operation
|
| 83 |
+
self._refresh = refresh
|
| 84 |
+
self._cancel = cancel
|
| 85 |
+
# Note: the extended operation does not give a good way to indicate cancellation.
|
| 86 |
+
# We make do with manually tracking cancellation and checking for doneness.
|
| 87 |
+
self._cancelled = False
|
| 88 |
+
self._completion_lock = threading.Lock()
|
| 89 |
+
# Invoke in case the operation came back already complete.
|
| 90 |
+
self._handle_refreshed_operation()
|
| 91 |
+
|
| 92 |
+
# Note: the following four properties MUST be overridden in a subclass
|
| 93 |
+
# if, and only if, the fields in the corresponding extended operation message
|
| 94 |
+
# have different names.
|
| 95 |
+
#
|
| 96 |
+
# E.g. we have an extended operation class that looks like
|
| 97 |
+
#
|
| 98 |
+
# class MyOperation(proto.Message):
|
| 99 |
+
# moniker = proto.Field(proto.STRING, number=1)
|
| 100 |
+
# status_msg = proto.Field(proto.STRING, number=2)
|
| 101 |
+
# optional http_error_code = proto.Field(proto.INT32, number=3)
|
| 102 |
+
# optional http_error_msg = proto.Field(proto.STRING, number=4)
|
| 103 |
+
#
|
| 104 |
+
# the ExtendedOperation subclass would provide property overrides that map
|
| 105 |
+
# to these (poorly named) fields.
|
| 106 |
+
@property
|
| 107 |
+
def name(self):
|
| 108 |
+
return self._extended_operation.name
|
| 109 |
+
|
| 110 |
+
@property
|
| 111 |
+
def status(self):
|
| 112 |
+
return self._extended_operation.status
|
| 113 |
+
|
| 114 |
+
@property
|
| 115 |
+
def error_code(self):
|
| 116 |
+
return self._extended_operation.error_code
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def error_message(self):
|
| 120 |
+
return self._extended_operation.error_message
|
| 121 |
+
|
| 122 |
+
def __getattr__(self, name):
|
| 123 |
+
return getattr(self._extended_operation, name)
|
| 124 |
+
|
| 125 |
+
def done(self, retry=None):
|
| 126 |
+
self._refresh_and_update(retry)
|
| 127 |
+
return self._extended_operation.done
|
| 128 |
+
|
| 129 |
+
def cancel(self):
|
| 130 |
+
if self.done():
|
| 131 |
+
return False
|
| 132 |
+
|
| 133 |
+
self._cancel()
|
| 134 |
+
self._cancelled = True
|
| 135 |
+
return True
|
| 136 |
+
|
| 137 |
+
def cancelled(self):
|
| 138 |
+
# TODO(dovs): there is not currently a good way to determine whether the
|
| 139 |
+
# operation has been cancelled.
|
| 140 |
+
# The best we can do is manually keep track of cancellation
|
| 141 |
+
# and check for doneness.
|
| 142 |
+
if not self._cancelled:
|
| 143 |
+
return False
|
| 144 |
+
|
| 145 |
+
self._refresh_and_update()
|
| 146 |
+
return self._extended_operation.done
|
| 147 |
+
|
| 148 |
+
def _refresh_and_update(self, retry=None):
|
| 149 |
+
if not self._extended_operation.done:
|
| 150 |
+
self._extended_operation = (
|
| 151 |
+
self._refresh(retry=retry) if retry else self._refresh()
|
| 152 |
+
)
|
| 153 |
+
self._handle_refreshed_operation()
|
| 154 |
+
|
| 155 |
+
def _handle_refreshed_operation(self):
|
| 156 |
+
with self._completion_lock:
|
| 157 |
+
if not self._extended_operation.done:
|
| 158 |
+
return
|
| 159 |
+
|
| 160 |
+
if self.error_code and self.error_message:
|
| 161 |
+
# Note: `errors` can be removed once proposal A from
|
| 162 |
+
# b/284179390 is implemented.
|
| 163 |
+
errors = []
|
| 164 |
+
if hasattr(self, "error") and hasattr(self.error, "errors"):
|
| 165 |
+
errors = self.error.errors
|
| 166 |
+
exception = exceptions.from_http_status(
|
| 167 |
+
status_code=self.error_code,
|
| 168 |
+
message=self.error_message,
|
| 169 |
+
response=self._extended_operation,
|
| 170 |
+
errors=errors,
|
| 171 |
+
)
|
| 172 |
+
self.set_exception(exception)
|
| 173 |
+
elif self.error_code or self.error_message:
|
| 174 |
+
exception = exceptions.GoogleAPICallError(
|
| 175 |
+
f"Unexpected error {self.error_code}: {self.error_message}"
|
| 176 |
+
)
|
| 177 |
+
self.set_exception(exception)
|
| 178 |
+
else:
|
| 179 |
+
# Extended operations have no payload.
|
| 180 |
+
self.set_result(None)
|
| 181 |
+
|
| 182 |
+
@classmethod
|
| 183 |
+
def make(cls, refresh, cancel, extended_operation, **kwargs):
|
| 184 |
+
"""
|
| 185 |
+
Return an instantiated ExtendedOperation (or child) that wraps
|
| 186 |
+
* a refresh callable
|
| 187 |
+
* a cancel callable (can be a no-op)
|
| 188 |
+
* an initial result
|
| 189 |
+
|
| 190 |
+
.. note::
|
| 191 |
+
It is the caller's responsibility to set up refresh and cancel
|
| 192 |
+
with their correct request argument.
|
| 193 |
+
The reason for this is that the services that use Extended Operations
|
| 194 |
+
have rpcs that look something like the following:
|
| 195 |
+
|
| 196 |
+
// service.proto
|
| 197 |
+
service MyLongService {
|
| 198 |
+
rpc StartLongTask(StartLongTaskRequest) returns (ExtendedOperation) {
|
| 199 |
+
option (google.cloud.operation_service) = "CustomOperationService";
|
| 200 |
+
}
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
service CustomOperationService {
|
| 204 |
+
rpc Get(GetOperationRequest) returns (ExtendedOperation) {
|
| 205 |
+
option (google.cloud.operation_polling_method) = true;
|
| 206 |
+
}
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
Any info needed for the poll, e.g. a name, path params, etc.
|
| 210 |
+
is held in the request, which the initial client method is in a much
|
| 211 |
+
better position to make made because the caller made the initial request.
|
| 212 |
+
|
| 213 |
+
TL;DR: the caller sets up closures for refresh and cancel that carry
|
| 214 |
+
the properly configured requests.
|
| 215 |
+
|
| 216 |
+
Args:
|
| 217 |
+
refresh (Callable[Optional[Retry]][type(extended_operation)]): A callable that
|
| 218 |
+
returns the latest state of the operation.
|
| 219 |
+
cancel (Callable[][Any]): A callable that tries to cancel the operation
|
| 220 |
+
on a best effort basis.
|
| 221 |
+
extended_operation (Any): The initial response of the long running method.
|
| 222 |
+
See the docstring for ExtendedOperation.__init__ for requirements on
|
| 223 |
+
the type and fields of extended_operation
|
| 224 |
+
"""
|
| 225 |
+
return cls(extended_operation, refresh, cancel, **kwargs)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/general_helpers.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# This import for backward compatibility only.
|
| 16 |
+
from functools import wraps # noqa: F401 pragma: NO COVER
|
| 17 |
+
|
| 18 |
+
_CREDENTIALS_FILE_WARNING = """\
|
| 19 |
+
The `credentials_file` argument is deprecated because of a potential security risk.
|
| 20 |
+
|
| 21 |
+
The `google.auth.load_credentials_from_file` method does not validate the credential
|
| 22 |
+
configuration. The security risk occurs when a credential configuration is accepted
|
| 23 |
+
from a source that is not under your control and used without validation on your side.
|
| 24 |
+
|
| 25 |
+
If you know that you will be loading credential configurations of a
|
| 26 |
+
specific type, it is recommended to use a credential-type-specific
|
| 27 |
+
load method.
|
| 28 |
+
|
| 29 |
+
This will ensure that an unexpected credential type with potential for
|
| 30 |
+
malicious intent is not loaded unintentionally. You might still have to do
|
| 31 |
+
validation for certain credential types. Please follow the recommendations
|
| 32 |
+
for that method. For example, if you want to load only service accounts,
|
| 33 |
+
you can create the service account credentials explicitly:
|
| 34 |
+
|
| 35 |
+
```
|
| 36 |
+
from google.cloud.vision_v1 import ImageAnnotatorClient
|
| 37 |
+
from google.oauth2 import service_account
|
| 38 |
+
|
| 39 |
+
credentials = service_account.Credentials.from_service_account_file(filename)
|
| 40 |
+
client = ImageAnnotatorClient(credentials=credentials)
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
If you are loading your credential configuration from an untrusted source and have
|
| 44 |
+
not mitigated the risks (e.g. by validating the configuration yourself), make
|
| 45 |
+
these changes as soon as possible to prevent security risks to your environment.
|
| 46 |
+
|
| 47 |
+
Regardless of the method used, it is always your responsibility to validate
|
| 48 |
+
configurations received from external sources.
|
| 49 |
+
|
| 50 |
+
Refer to https://cloud.google.com/docs/authentication/external/externally-sourced-credentials
|
| 51 |
+
for more details.
|
| 52 |
+
"""
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/grpc_helpers.py
ADDED
|
@@ -0,0 +1,614 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Helpers for :mod:`grpc`."""
|
| 16 |
+
import collections
|
| 17 |
+
import functools
|
| 18 |
+
from typing import Generic, Iterator, Optional, TypeVar
|
| 19 |
+
import warnings
|
| 20 |
+
|
| 21 |
+
import google.auth
|
| 22 |
+
import google.auth.credentials
|
| 23 |
+
import google.auth.transport.grpc
|
| 24 |
+
import google.auth.transport.requests
|
| 25 |
+
import google.protobuf
|
| 26 |
+
import grpc
|
| 27 |
+
|
| 28 |
+
from google.api_core import exceptions, general_helpers
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
# The list of gRPC Callable interfaces that return iterators.
|
| 32 |
+
_STREAM_WRAP_CLASSES = (grpc.UnaryStreamMultiCallable, grpc.StreamStreamMultiCallable)
|
| 33 |
+
|
| 34 |
+
# denotes the proto response type for grpc calls
|
| 35 |
+
P = TypeVar("P")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _patch_callable_name(callable_):
|
| 39 |
+
"""Fix-up gRPC callable attributes.
|
| 40 |
+
|
| 41 |
+
gRPC callable lack the ``__name__`` attribute which causes
|
| 42 |
+
:func:`functools.wraps` to error. This adds the attribute if needed.
|
| 43 |
+
"""
|
| 44 |
+
if not hasattr(callable_, "__name__"):
|
| 45 |
+
callable_.__name__ = callable_.__class__.__name__
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _wrap_unary_errors(callable_):
|
| 49 |
+
"""Map errors for Unary-Unary and Stream-Unary gRPC callables."""
|
| 50 |
+
_patch_callable_name(callable_)
|
| 51 |
+
|
| 52 |
+
@functools.wraps(callable_)
|
| 53 |
+
def error_remapped_callable(*args, **kwargs):
|
| 54 |
+
try:
|
| 55 |
+
return callable_(*args, **kwargs)
|
| 56 |
+
except grpc.RpcError as exc:
|
| 57 |
+
raise exceptions.from_grpc_error(exc) from exc
|
| 58 |
+
|
| 59 |
+
return error_remapped_callable
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class _StreamingResponseIterator(Generic[P], grpc.Call):
|
| 63 |
+
def __init__(self, wrapped, prefetch_first_result=True):
|
| 64 |
+
self._wrapped = wrapped
|
| 65 |
+
|
| 66 |
+
# This iterator is used in a retry context, and returned outside after init.
|
| 67 |
+
# gRPC will not throw an exception until the stream is consumed, so we need
|
| 68 |
+
# to retrieve the first result, in order to fail, in order to trigger a retry.
|
| 69 |
+
try:
|
| 70 |
+
if prefetch_first_result:
|
| 71 |
+
self._stored_first_result = next(self._wrapped)
|
| 72 |
+
except TypeError:
|
| 73 |
+
# It is possible the wrapped method isn't an iterable (a grpc.Call
|
| 74 |
+
# for instance). If this happens don't store the first result.
|
| 75 |
+
pass
|
| 76 |
+
except StopIteration:
|
| 77 |
+
# ignore stop iteration at this time. This should be handled outside of retry.
|
| 78 |
+
pass
|
| 79 |
+
|
| 80 |
+
def __iter__(self) -> Iterator[P]:
|
| 81 |
+
"""This iterator is also an iterable that returns itself."""
|
| 82 |
+
return self
|
| 83 |
+
|
| 84 |
+
def __next__(self) -> P:
|
| 85 |
+
"""Get the next response from the stream.
|
| 86 |
+
|
| 87 |
+
Returns:
|
| 88 |
+
protobuf.Message: A single response from the stream.
|
| 89 |
+
"""
|
| 90 |
+
try:
|
| 91 |
+
if hasattr(self, "_stored_first_result"):
|
| 92 |
+
result = self._stored_first_result
|
| 93 |
+
del self._stored_first_result
|
| 94 |
+
return result
|
| 95 |
+
return next(self._wrapped)
|
| 96 |
+
except grpc.RpcError as exc:
|
| 97 |
+
# If the stream has already returned data, we cannot recover here.
|
| 98 |
+
raise exceptions.from_grpc_error(exc) from exc
|
| 99 |
+
|
| 100 |
+
# grpc.Call & grpc.RpcContext interface
|
| 101 |
+
|
| 102 |
+
def add_callback(self, callback):
|
| 103 |
+
return self._wrapped.add_callback(callback)
|
| 104 |
+
|
| 105 |
+
def cancel(self):
|
| 106 |
+
return self._wrapped.cancel()
|
| 107 |
+
|
| 108 |
+
def code(self):
|
| 109 |
+
return self._wrapped.code()
|
| 110 |
+
|
| 111 |
+
def details(self):
|
| 112 |
+
return self._wrapped.details()
|
| 113 |
+
|
| 114 |
+
def initial_metadata(self):
|
| 115 |
+
return self._wrapped.initial_metadata()
|
| 116 |
+
|
| 117 |
+
def is_active(self):
|
| 118 |
+
return self._wrapped.is_active()
|
| 119 |
+
|
| 120 |
+
def time_remaining(self):
|
| 121 |
+
return self._wrapped.time_remaining()
|
| 122 |
+
|
| 123 |
+
def trailing_metadata(self):
|
| 124 |
+
return self._wrapped.trailing_metadata()
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
# public type alias denoting the return type of streaming gapic calls
|
| 128 |
+
GrpcStream = _StreamingResponseIterator[P]
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _wrap_stream_errors(callable_):
|
| 132 |
+
"""Wrap errors for Unary-Stream and Stream-Stream gRPC callables.
|
| 133 |
+
|
| 134 |
+
The callables that return iterators require a bit more logic to re-map
|
| 135 |
+
errors when iterating. This wraps both the initial invocation and the
|
| 136 |
+
iterator of the return value to re-map errors.
|
| 137 |
+
"""
|
| 138 |
+
_patch_callable_name(callable_)
|
| 139 |
+
|
| 140 |
+
@functools.wraps(callable_)
|
| 141 |
+
def error_remapped_callable(*args, **kwargs):
|
| 142 |
+
try:
|
| 143 |
+
result = callable_(*args, **kwargs)
|
| 144 |
+
# Auto-fetching the first result causes PubSub client's streaming pull
|
| 145 |
+
# to hang when re-opening the stream, thus we need examine the hacky
|
| 146 |
+
# hidden flag to see if pre-fetching is disabled.
|
| 147 |
+
# https://github.com/googleapis/python-pubsub/issues/93#issuecomment-630762257
|
| 148 |
+
prefetch_first = getattr(callable_, "_prefetch_first_result_", True)
|
| 149 |
+
return _StreamingResponseIterator(
|
| 150 |
+
result, prefetch_first_result=prefetch_first
|
| 151 |
+
)
|
| 152 |
+
except grpc.RpcError as exc:
|
| 153 |
+
raise exceptions.from_grpc_error(exc) from exc
|
| 154 |
+
|
| 155 |
+
return error_remapped_callable
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def wrap_errors(callable_):
|
| 159 |
+
"""Wrap a gRPC callable and map :class:`grpc.RpcErrors` to friendly error
|
| 160 |
+
classes.
|
| 161 |
+
|
| 162 |
+
Errors raised by the gRPC callable are mapped to the appropriate
|
| 163 |
+
:class:`google.api_core.exceptions.GoogleAPICallError` subclasses.
|
| 164 |
+
The original `grpc.RpcError` (which is usually also a `grpc.Call`) is
|
| 165 |
+
available from the ``response`` property on the mapped exception. This
|
| 166 |
+
is useful for extracting metadata from the original error.
|
| 167 |
+
|
| 168 |
+
Args:
|
| 169 |
+
callable_ (Callable): A gRPC callable.
|
| 170 |
+
|
| 171 |
+
Returns:
|
| 172 |
+
Callable: The wrapped gRPC callable.
|
| 173 |
+
"""
|
| 174 |
+
if isinstance(callable_, _STREAM_WRAP_CLASSES):
|
| 175 |
+
return _wrap_stream_errors(callable_)
|
| 176 |
+
else:
|
| 177 |
+
return _wrap_unary_errors(callable_)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _create_composite_credentials(
|
| 181 |
+
credentials=None,
|
| 182 |
+
credentials_file=None,
|
| 183 |
+
default_scopes=None,
|
| 184 |
+
scopes=None,
|
| 185 |
+
ssl_credentials=None,
|
| 186 |
+
quota_project_id=None,
|
| 187 |
+
default_host=None,
|
| 188 |
+
):
|
| 189 |
+
"""Create the composite credentials for secure channels.
|
| 190 |
+
|
| 191 |
+
Args:
|
| 192 |
+
credentials (google.auth.credentials.Credentials): The credentials. If
|
| 193 |
+
not specified, then this function will attempt to ascertain the
|
| 194 |
+
credentials from the environment using :func:`google.auth.default`.
|
| 195 |
+
credentials_file (str): Deprecated. A file with credentials that can be loaded with
|
| 196 |
+
:func:`google.auth.load_credentials_from_file`. This argument is
|
| 197 |
+
mutually exclusive with credentials. This argument will be
|
| 198 |
+
removed in the next major version of `google-api-core`.
|
| 199 |
+
|
| 200 |
+
.. warning::
|
| 201 |
+
Important: If you accept a credential configuration (credential JSON/File/Stream)
|
| 202 |
+
from an external source for authentication to Google Cloud Platform, you must
|
| 203 |
+
validate it before providing it to any Google API or client library. Providing an
|
| 204 |
+
unvalidated credential configuration to Google APIs or libraries can compromise
|
| 205 |
+
the security of your systems and data. For more information, refer to
|
| 206 |
+
`Validate credential configurations from external sources`_.
|
| 207 |
+
|
| 208 |
+
.. _Validate credential configurations from external sources:
|
| 209 |
+
|
| 210 |
+
https://cloud.google.com/docs/authentication/external/externally-sourced-credentials
|
| 211 |
+
default_scopes (Sequence[str]): A optional list of scopes needed for this
|
| 212 |
+
service. These are only used when credentials are not specified and
|
| 213 |
+
are passed to :func:`google.auth.default`.
|
| 214 |
+
scopes (Sequence[str]): A optional list of scopes needed for this
|
| 215 |
+
service. These are only used when credentials are not specified and
|
| 216 |
+
are passed to :func:`google.auth.default`.
|
| 217 |
+
ssl_credentials (grpc.ChannelCredentials): Optional SSL channel
|
| 218 |
+
credentials. This can be used to specify different certificates.
|
| 219 |
+
quota_project_id (str): An optional project to use for billing and quota.
|
| 220 |
+
default_host (str): The default endpoint. e.g., "pubsub.googleapis.com".
|
| 221 |
+
|
| 222 |
+
Returns:
|
| 223 |
+
grpc.ChannelCredentials: The composed channel credentials object.
|
| 224 |
+
|
| 225 |
+
Raises:
|
| 226 |
+
google.api_core.DuplicateCredentialArgs: If both a credentials object and credentials_file are passed.
|
| 227 |
+
"""
|
| 228 |
+
if credentials_file is not None:
|
| 229 |
+
warnings.warn(general_helpers._CREDENTIALS_FILE_WARNING, DeprecationWarning)
|
| 230 |
+
|
| 231 |
+
if credentials and credentials_file:
|
| 232 |
+
raise exceptions.DuplicateCredentialArgs(
|
| 233 |
+
"'credentials' and 'credentials_file' are mutually exclusive."
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
if credentials_file:
|
| 237 |
+
credentials, _ = google.auth.load_credentials_from_file(
|
| 238 |
+
credentials_file, scopes=scopes, default_scopes=default_scopes
|
| 239 |
+
)
|
| 240 |
+
elif credentials:
|
| 241 |
+
credentials = google.auth.credentials.with_scopes_if_required(
|
| 242 |
+
credentials, scopes=scopes, default_scopes=default_scopes
|
| 243 |
+
)
|
| 244 |
+
else:
|
| 245 |
+
credentials, _ = google.auth.default(
|
| 246 |
+
scopes=scopes, default_scopes=default_scopes
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
if quota_project_id and isinstance(
|
| 250 |
+
credentials, google.auth.credentials.CredentialsWithQuotaProject
|
| 251 |
+
):
|
| 252 |
+
credentials = credentials.with_quota_project(quota_project_id)
|
| 253 |
+
|
| 254 |
+
request = google.auth.transport.requests.Request()
|
| 255 |
+
|
| 256 |
+
# Create the metadata plugin for inserting the authorization header.
|
| 257 |
+
metadata_plugin = google.auth.transport.grpc.AuthMetadataPlugin(
|
| 258 |
+
credentials,
|
| 259 |
+
request,
|
| 260 |
+
default_host=default_host,
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
# Create a set of grpc.CallCredentials using the metadata plugin.
|
| 264 |
+
google_auth_credentials = grpc.metadata_call_credentials(metadata_plugin)
|
| 265 |
+
|
| 266 |
+
# if `ssl_credentials` is set, use `grpc.composite_channel_credentials` instead of
|
| 267 |
+
# `grpc.compute_engine_channel_credentials` as the former supports passing
|
| 268 |
+
# `ssl_credentials` via `channel_credentials` which is needed for mTLS.
|
| 269 |
+
if ssl_credentials:
|
| 270 |
+
# Combine the ssl credentials and the authorization credentials.
|
| 271 |
+
# See https://grpc.github.io/grpc/python/grpc.html#grpc.composite_channel_credentials
|
| 272 |
+
return grpc.composite_channel_credentials(
|
| 273 |
+
ssl_credentials, google_auth_credentials
|
| 274 |
+
)
|
| 275 |
+
else:
|
| 276 |
+
# Use grpc.compute_engine_channel_credentials in order to support Direct Path.
|
| 277 |
+
# See https://grpc.github.io/grpc/python/grpc.html#grpc.compute_engine_channel_credentials
|
| 278 |
+
# TODO(https://github.com/googleapis/python-api-core/issues/598):
|
| 279 |
+
# Although `grpc.compute_engine_channel_credentials` returns channel credentials
|
| 280 |
+
# outside of a Google Compute Engine environment (GCE), we should determine if
|
| 281 |
+
# there is a way to reliably detect a GCE environment so that
|
| 282 |
+
# `grpc.compute_engine_channel_credentials` is not called outside of GCE.
|
| 283 |
+
return grpc.compute_engine_channel_credentials(google_auth_credentials)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def create_channel(
|
| 287 |
+
target,
|
| 288 |
+
credentials=None,
|
| 289 |
+
scopes=None,
|
| 290 |
+
ssl_credentials=None,
|
| 291 |
+
credentials_file=None,
|
| 292 |
+
quota_project_id=None,
|
| 293 |
+
default_scopes=None,
|
| 294 |
+
default_host=None,
|
| 295 |
+
compression=None,
|
| 296 |
+
attempt_direct_path: Optional[bool] = False,
|
| 297 |
+
**kwargs,
|
| 298 |
+
):
|
| 299 |
+
"""Create a secure channel with credentials.
|
| 300 |
+
|
| 301 |
+
Args:
|
| 302 |
+
target (str): The target service address in the format 'hostname:port'.
|
| 303 |
+
credentials (google.auth.credentials.Credentials): The credentials. If
|
| 304 |
+
not specified, then this function will attempt to ascertain the
|
| 305 |
+
credentials from the environment using :func:`google.auth.default`.
|
| 306 |
+
scopes (Sequence[str]): A optional list of scopes needed for this
|
| 307 |
+
service. These are only used when credentials are not specified and
|
| 308 |
+
are passed to :func:`google.auth.default`.
|
| 309 |
+
ssl_credentials (grpc.ChannelCredentials): Optional SSL channel
|
| 310 |
+
credentials. This can be used to specify different certificates.
|
| 311 |
+
credentials_file (str): A file with credentials that can be loaded with
|
| 312 |
+
:func:`google.auth.load_credentials_from_file`. This argument is
|
| 313 |
+
mutually exclusive with credentials.
|
| 314 |
+
|
| 315 |
+
.. warning::
|
| 316 |
+
Important: If you accept a credential configuration (credential JSON/File/Stream)
|
| 317 |
+
from an external source for authentication to Google Cloud Platform, you must
|
| 318 |
+
validate it before providing it to any Google API or client library. Providing an
|
| 319 |
+
unvalidated credential configuration to Google APIs or libraries can compromise
|
| 320 |
+
the security of your systems and data. For more information, refer to
|
| 321 |
+
`Validate credential configurations from external sources`_.
|
| 322 |
+
|
| 323 |
+
.. _Validate credential configurations from external sources:
|
| 324 |
+
|
| 325 |
+
https://cloud.google.com/docs/authentication/external/externally-sourced-credentials
|
| 326 |
+
quota_project_id (str): An optional project to use for billing and quota.
|
| 327 |
+
default_scopes (Sequence[str]): Default scopes passed by a Google client
|
| 328 |
+
library. Use 'scopes' for user-defined scopes.
|
| 329 |
+
default_host (str): The default endpoint. e.g., "pubsub.googleapis.com".
|
| 330 |
+
compression (grpc.Compression): An optional value indicating the
|
| 331 |
+
compression method to be used over the lifetime of the channel.
|
| 332 |
+
attempt_direct_path (Optional[bool]): If set, Direct Path will be attempted
|
| 333 |
+
when the request is made. Direct Path is only available within a Google
|
| 334 |
+
Compute Engine (GCE) environment and provides a proxyless connection
|
| 335 |
+
which increases the available throughput, reduces latency, and increases
|
| 336 |
+
reliability. Note:
|
| 337 |
+
|
| 338 |
+
- This argument should only be set in a GCE environment and for Services
|
| 339 |
+
that are known to support Direct Path.
|
| 340 |
+
- If this argument is set outside of GCE, then this request will fail
|
| 341 |
+
unless the back-end service happens to have configured fall-back to DNS.
|
| 342 |
+
- If the request causes a `ServiceUnavailable` response, it is recommended
|
| 343 |
+
that the client repeat the request with `attempt_direct_path` set to
|
| 344 |
+
`False` as the Service may not support Direct Path.
|
| 345 |
+
- Using `ssl_credentials` with `attempt_direct_path` set to `True` will
|
| 346 |
+
result in `ValueError` as this combination is not yet supported.
|
| 347 |
+
|
| 348 |
+
kwargs: Additional key-word args passed to
|
| 349 |
+
:func:`grpc.secure_channel`.
|
| 350 |
+
|
| 351 |
+
Returns:
|
| 352 |
+
grpc.Channel: The created channel.
|
| 353 |
+
|
| 354 |
+
Raises:
|
| 355 |
+
google.api_core.DuplicateCredentialArgs: If both a credentials object and credentials_file are passed.
|
| 356 |
+
ValueError: If `ssl_credentials` is set and `attempt_direct_path` is set to `True`.
|
| 357 |
+
"""
|
| 358 |
+
|
| 359 |
+
# If `ssl_credentials` is set and `attempt_direct_path` is set to `True`,
|
| 360 |
+
# raise ValueError as this is not yet supported.
|
| 361 |
+
# See https://github.com/googleapis/python-api-core/issues/590
|
| 362 |
+
if ssl_credentials and attempt_direct_path:
|
| 363 |
+
raise ValueError("Using ssl_credentials with Direct Path is not supported")
|
| 364 |
+
|
| 365 |
+
composite_credentials = _create_composite_credentials(
|
| 366 |
+
credentials=credentials,
|
| 367 |
+
credentials_file=credentials_file,
|
| 368 |
+
default_scopes=default_scopes,
|
| 369 |
+
scopes=scopes,
|
| 370 |
+
ssl_credentials=ssl_credentials,
|
| 371 |
+
quota_project_id=quota_project_id,
|
| 372 |
+
default_host=default_host,
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
if attempt_direct_path:
|
| 376 |
+
target = _modify_target_for_direct_path(target)
|
| 377 |
+
|
| 378 |
+
return grpc.secure_channel(
|
| 379 |
+
target, composite_credentials, compression=compression, **kwargs
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def _modify_target_for_direct_path(target: str) -> str:
|
| 384 |
+
"""
|
| 385 |
+
Given a target, return a modified version which is compatible with Direct Path.
|
| 386 |
+
|
| 387 |
+
Args:
|
| 388 |
+
target (str): The target service address in the format 'hostname[:port]' or
|
| 389 |
+
'dns://hostname[:port]'.
|
| 390 |
+
|
| 391 |
+
Returns:
|
| 392 |
+
target (str): The target service address which is converted into a format compatible with Direct Path.
|
| 393 |
+
If the target contains `dns:///` or does not contain `:///`, the target will be converted in
|
| 394 |
+
a format compatible with Direct Path; otherwise the original target will be returned as the
|
| 395 |
+
original target may already denote Direct Path.
|
| 396 |
+
"""
|
| 397 |
+
|
| 398 |
+
# A DNS prefix may be included with the target to indicate the endpoint is living in the Internet,
|
| 399 |
+
# outside of Google Cloud Platform.
|
| 400 |
+
dns_prefix = "dns:///"
|
| 401 |
+
# Remove "dns:///" if `attempt_direct_path` is set to True as
|
| 402 |
+
# the Direct Path prefix `google-c2p:///` will be used instead.
|
| 403 |
+
target = target.replace(dns_prefix, "")
|
| 404 |
+
|
| 405 |
+
direct_path_separator = ":///"
|
| 406 |
+
if direct_path_separator not in target:
|
| 407 |
+
target_without_port = target.split(":")[0]
|
| 408 |
+
# Modify the target to use Direct Path by adding the `google-c2p:///` prefix
|
| 409 |
+
target = f"google-c2p{direct_path_separator}{target_without_port}"
|
| 410 |
+
return target
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
_MethodCall = collections.namedtuple(
|
| 414 |
+
"_MethodCall", ("request", "timeout", "metadata", "credentials", "compression")
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
_ChannelRequest = collections.namedtuple("_ChannelRequest", ("method", "request"))
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
class _CallableStub(object):
|
| 421 |
+
"""Stub for the grpc.*MultiCallable interfaces."""
|
| 422 |
+
|
| 423 |
+
def __init__(self, method, channel):
|
| 424 |
+
self._method = method
|
| 425 |
+
self._channel = channel
|
| 426 |
+
self.response = None
|
| 427 |
+
"""Union[protobuf.Message, Callable[protobuf.Message], exception]:
|
| 428 |
+
The response to give when invoking this callable. If this is a
|
| 429 |
+
callable, it will be invoked with the request protobuf. If it's an
|
| 430 |
+
exception, the exception will be raised when this is invoked.
|
| 431 |
+
"""
|
| 432 |
+
self.responses = None
|
| 433 |
+
"""Iterator[
|
| 434 |
+
Union[protobuf.Message, Callable[protobuf.Message], exception]]:
|
| 435 |
+
An iterator of responses. If specified, self.response will be populated
|
| 436 |
+
on each invocation by calling ``next(self.responses)``."""
|
| 437 |
+
self.requests = []
|
| 438 |
+
"""List[protobuf.Message]: All requests sent to this callable."""
|
| 439 |
+
self.calls = []
|
| 440 |
+
"""List[Tuple]: All invocations of this callable. Each tuple is the
|
| 441 |
+
request, timeout, metadata, compression, and credentials."""
|
| 442 |
+
|
| 443 |
+
def __call__(
|
| 444 |
+
self, request, timeout=None, metadata=None, credentials=None, compression=None
|
| 445 |
+
):
|
| 446 |
+
self._channel.requests.append(_ChannelRequest(self._method, request))
|
| 447 |
+
self.calls.append(
|
| 448 |
+
_MethodCall(request, timeout, metadata, credentials, compression)
|
| 449 |
+
)
|
| 450 |
+
self.requests.append(request)
|
| 451 |
+
|
| 452 |
+
response = self.response
|
| 453 |
+
if self.responses is not None:
|
| 454 |
+
if response is None:
|
| 455 |
+
response = next(self.responses)
|
| 456 |
+
else:
|
| 457 |
+
raise ValueError(
|
| 458 |
+
"{method}.response and {method}.responses are mutually "
|
| 459 |
+
"exclusive.".format(method=self._method)
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
if callable(response):
|
| 463 |
+
return response(request)
|
| 464 |
+
|
| 465 |
+
if isinstance(response, Exception):
|
| 466 |
+
raise response
|
| 467 |
+
|
| 468 |
+
if response is not None:
|
| 469 |
+
return response
|
| 470 |
+
|
| 471 |
+
raise ValueError('Method stub for "{}" has no response.'.format(self._method))
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def _simplify_method_name(method):
|
| 475 |
+
"""Simplifies a gRPC method name.
|
| 476 |
+
|
| 477 |
+
When gRPC invokes the channel to create a callable, it gives a full
|
| 478 |
+
method name like "/google.pubsub.v1.Publisher/CreateTopic". This
|
| 479 |
+
returns just the name of the method, in this case "CreateTopic".
|
| 480 |
+
|
| 481 |
+
Args:
|
| 482 |
+
method (str): The name of the method.
|
| 483 |
+
|
| 484 |
+
Returns:
|
| 485 |
+
str: The simplified name of the method.
|
| 486 |
+
"""
|
| 487 |
+
return method.rsplit("/", 1).pop()
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
class ChannelStub(grpc.Channel):
|
| 491 |
+
"""A testing stub for the grpc.Channel interface.
|
| 492 |
+
|
| 493 |
+
This can be used to test any client that eventually uses a gRPC channel
|
| 494 |
+
to communicate. By passing in a channel stub, you can configure which
|
| 495 |
+
responses are returned and track which requests are made.
|
| 496 |
+
|
| 497 |
+
For example:
|
| 498 |
+
|
| 499 |
+
.. code-block:: python
|
| 500 |
+
|
| 501 |
+
channel_stub = grpc_helpers.ChannelStub()
|
| 502 |
+
client = FooClient(channel=channel_stub)
|
| 503 |
+
|
| 504 |
+
channel_stub.GetFoo.response = foo_pb2.Foo(name='bar')
|
| 505 |
+
|
| 506 |
+
foo = client.get_foo(labels=['baz'])
|
| 507 |
+
|
| 508 |
+
assert foo.name == 'bar'
|
| 509 |
+
assert channel_stub.GetFoo.requests[0].labels = ['baz']
|
| 510 |
+
|
| 511 |
+
Each method on the stub can be accessed and configured on the channel.
|
| 512 |
+
Here's some examples of various configurations:
|
| 513 |
+
|
| 514 |
+
.. code-block:: python
|
| 515 |
+
|
| 516 |
+
# Return a basic response:
|
| 517 |
+
|
| 518 |
+
channel_stub.GetFoo.response = foo_pb2.Foo(name='bar')
|
| 519 |
+
assert client.get_foo().name == 'bar'
|
| 520 |
+
|
| 521 |
+
# Raise an exception:
|
| 522 |
+
channel_stub.GetFoo.response = NotFound('...')
|
| 523 |
+
|
| 524 |
+
with pytest.raises(NotFound):
|
| 525 |
+
client.get_foo()
|
| 526 |
+
|
| 527 |
+
# Use a sequence of responses:
|
| 528 |
+
channel_stub.GetFoo.responses = iter([
|
| 529 |
+
foo_pb2.Foo(name='bar'),
|
| 530 |
+
foo_pb2.Foo(name='baz'),
|
| 531 |
+
])
|
| 532 |
+
|
| 533 |
+
assert client.get_foo().name == 'bar'
|
| 534 |
+
assert client.get_foo().name == 'baz'
|
| 535 |
+
|
| 536 |
+
# Use a callable
|
| 537 |
+
|
| 538 |
+
def on_get_foo(request):
|
| 539 |
+
return foo_pb2.Foo(name='bar' + request.id)
|
| 540 |
+
|
| 541 |
+
channel_stub.GetFoo.response = on_get_foo
|
| 542 |
+
|
| 543 |
+
assert client.get_foo(id='123').name == 'bar123'
|
| 544 |
+
"""
|
| 545 |
+
|
| 546 |
+
def __init__(self, responses=[]):
|
| 547 |
+
self.requests = []
|
| 548 |
+
"""Sequence[Tuple[str, protobuf.Message]]: A list of all requests made
|
| 549 |
+
on this channel in order. The tuple is of method name, request
|
| 550 |
+
message."""
|
| 551 |
+
self._method_stubs = {}
|
| 552 |
+
|
| 553 |
+
def _stub_for_method(self, method):
|
| 554 |
+
method = _simplify_method_name(method)
|
| 555 |
+
self._method_stubs[method] = _CallableStub(method, self)
|
| 556 |
+
return self._method_stubs[method]
|
| 557 |
+
|
| 558 |
+
def __getattr__(self, key):
|
| 559 |
+
try:
|
| 560 |
+
return self._method_stubs[key]
|
| 561 |
+
except KeyError:
|
| 562 |
+
raise AttributeError
|
| 563 |
+
|
| 564 |
+
def unary_unary(
|
| 565 |
+
self,
|
| 566 |
+
method,
|
| 567 |
+
request_serializer=None,
|
| 568 |
+
response_deserializer=None,
|
| 569 |
+
_registered_method=False,
|
| 570 |
+
):
|
| 571 |
+
"""grpc.Channel.unary_unary implementation."""
|
| 572 |
+
return self._stub_for_method(method)
|
| 573 |
+
|
| 574 |
+
def unary_stream(
|
| 575 |
+
self,
|
| 576 |
+
method,
|
| 577 |
+
request_serializer=None,
|
| 578 |
+
response_deserializer=None,
|
| 579 |
+
_registered_method=False,
|
| 580 |
+
):
|
| 581 |
+
"""grpc.Channel.unary_stream implementation."""
|
| 582 |
+
return self._stub_for_method(method)
|
| 583 |
+
|
| 584 |
+
def stream_unary(
|
| 585 |
+
self,
|
| 586 |
+
method,
|
| 587 |
+
request_serializer=None,
|
| 588 |
+
response_deserializer=None,
|
| 589 |
+
_registered_method=False,
|
| 590 |
+
):
|
| 591 |
+
"""grpc.Channel.stream_unary implementation."""
|
| 592 |
+
return self._stub_for_method(method)
|
| 593 |
+
|
| 594 |
+
def stream_stream(
|
| 595 |
+
self,
|
| 596 |
+
method,
|
| 597 |
+
request_serializer=None,
|
| 598 |
+
response_deserializer=None,
|
| 599 |
+
_registered_method=False,
|
| 600 |
+
):
|
| 601 |
+
"""grpc.Channel.stream_stream implementation."""
|
| 602 |
+
return self._stub_for_method(method)
|
| 603 |
+
|
| 604 |
+
def subscribe(self, callback, try_to_connect=False):
|
| 605 |
+
"""grpc.Channel.subscribe implementation."""
|
| 606 |
+
pass
|
| 607 |
+
|
| 608 |
+
def unsubscribe(self, callback):
|
| 609 |
+
"""grpc.Channel.unsubscribe implementation."""
|
| 610 |
+
pass
|
| 611 |
+
|
| 612 |
+
def close(self):
|
| 613 |
+
"""grpc.Channel.close implementation."""
|
| 614 |
+
pass
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/grpc_helpers_async.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""AsyncIO helpers for :mod:`grpc` supporting 3.7+.
|
| 16 |
+
|
| 17 |
+
Please combine more detailed docstring in grpc_helpers.py to use following
|
| 18 |
+
functions. This module is implementing the same surface with AsyncIO semantics.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import asyncio
|
| 22 |
+
import functools
|
| 23 |
+
import warnings
|
| 24 |
+
|
| 25 |
+
from typing import AsyncGenerator, Generic, Iterator, Optional, TypeVar
|
| 26 |
+
|
| 27 |
+
import grpc
|
| 28 |
+
from grpc import aio
|
| 29 |
+
|
| 30 |
+
from google.api_core import exceptions, general_helpers, grpc_helpers
|
| 31 |
+
|
| 32 |
+
# denotes the proto response type for grpc calls
|
| 33 |
+
P = TypeVar("P")
|
| 34 |
+
|
| 35 |
+
# NOTE(lidiz) Alternatively, we can hack "__getattribute__" to perform
|
| 36 |
+
# automatic patching for us. But that means the overhead of creating an
|
| 37 |
+
# extra Python function spreads to every single send and receive.
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class _WrappedCall(aio.Call):
|
| 41 |
+
def __init__(self):
|
| 42 |
+
self._call = None
|
| 43 |
+
|
| 44 |
+
def with_call(self, call):
|
| 45 |
+
"""Supplies the call object separately to keep __init__ clean."""
|
| 46 |
+
self._call = call
|
| 47 |
+
return self
|
| 48 |
+
|
| 49 |
+
async def initial_metadata(self):
|
| 50 |
+
return await self._call.initial_metadata()
|
| 51 |
+
|
| 52 |
+
async def trailing_metadata(self):
|
| 53 |
+
return await self._call.trailing_metadata()
|
| 54 |
+
|
| 55 |
+
async def code(self):
|
| 56 |
+
return await self._call.code()
|
| 57 |
+
|
| 58 |
+
async def details(self):
|
| 59 |
+
return await self._call.details()
|
| 60 |
+
|
| 61 |
+
def cancelled(self):
|
| 62 |
+
return self._call.cancelled()
|
| 63 |
+
|
| 64 |
+
def done(self):
|
| 65 |
+
return self._call.done()
|
| 66 |
+
|
| 67 |
+
def time_remaining(self):
|
| 68 |
+
return self._call.time_remaining()
|
| 69 |
+
|
| 70 |
+
def cancel(self):
|
| 71 |
+
return self._call.cancel()
|
| 72 |
+
|
| 73 |
+
def add_done_callback(self, callback):
|
| 74 |
+
self._call.add_done_callback(callback)
|
| 75 |
+
|
| 76 |
+
async def wait_for_connection(self):
|
| 77 |
+
try:
|
| 78 |
+
await self._call.wait_for_connection()
|
| 79 |
+
except grpc.RpcError as rpc_error:
|
| 80 |
+
raise exceptions.from_grpc_error(rpc_error) from rpc_error
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class _WrappedUnaryResponseMixin(Generic[P], _WrappedCall):
|
| 84 |
+
def __await__(self) -> Iterator[P]:
|
| 85 |
+
try:
|
| 86 |
+
response = yield from self._call.__await__()
|
| 87 |
+
return response
|
| 88 |
+
except grpc.RpcError as rpc_error:
|
| 89 |
+
raise exceptions.from_grpc_error(rpc_error) from rpc_error
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class _WrappedStreamResponseMixin(Generic[P], _WrappedCall):
|
| 93 |
+
def __init__(self):
|
| 94 |
+
self._wrapped_async_generator = None
|
| 95 |
+
|
| 96 |
+
async def read(self) -> P:
|
| 97 |
+
try:
|
| 98 |
+
return await self._call.read()
|
| 99 |
+
except grpc.RpcError as rpc_error:
|
| 100 |
+
raise exceptions.from_grpc_error(rpc_error) from rpc_error
|
| 101 |
+
|
| 102 |
+
async def _wrapped_aiter(self) -> AsyncGenerator[P, None]:
|
| 103 |
+
try:
|
| 104 |
+
# NOTE(lidiz) coverage doesn't understand the exception raised from
|
| 105 |
+
# __anext__ method. It is covered by test case:
|
| 106 |
+
# test_wrap_stream_errors_aiter_non_rpc_error
|
| 107 |
+
async for response in self._call: # pragma: no branch
|
| 108 |
+
yield response
|
| 109 |
+
except grpc.RpcError as rpc_error:
|
| 110 |
+
raise exceptions.from_grpc_error(rpc_error) from rpc_error
|
| 111 |
+
|
| 112 |
+
def __aiter__(self) -> AsyncGenerator[P, None]:
|
| 113 |
+
if not self._wrapped_async_generator:
|
| 114 |
+
self._wrapped_async_generator = self._wrapped_aiter()
|
| 115 |
+
return self._wrapped_async_generator
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class _WrappedStreamRequestMixin(_WrappedCall):
|
| 119 |
+
async def write(self, request):
|
| 120 |
+
try:
|
| 121 |
+
await self._call.write(request)
|
| 122 |
+
except grpc.RpcError as rpc_error:
|
| 123 |
+
raise exceptions.from_grpc_error(rpc_error) from rpc_error
|
| 124 |
+
|
| 125 |
+
async def done_writing(self):
|
| 126 |
+
try:
|
| 127 |
+
await self._call.done_writing()
|
| 128 |
+
except grpc.RpcError as rpc_error:
|
| 129 |
+
raise exceptions.from_grpc_error(rpc_error) from rpc_error
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
# NOTE(lidiz) Implementing each individual class separately, so we don't
|
| 133 |
+
# expose any API that should not be seen. E.g., __aiter__ in unary-unary
|
| 134 |
+
# RPC, or __await__ in stream-stream RPC.
|
| 135 |
+
class _WrappedUnaryUnaryCall(_WrappedUnaryResponseMixin[P], aio.UnaryUnaryCall):
|
| 136 |
+
"""Wrapped UnaryUnaryCall to map exceptions."""
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class _WrappedUnaryStreamCall(_WrappedStreamResponseMixin[P], aio.UnaryStreamCall):
|
| 140 |
+
"""Wrapped UnaryStreamCall to map exceptions."""
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class _WrappedStreamUnaryCall(
|
| 144 |
+
_WrappedUnaryResponseMixin[P], _WrappedStreamRequestMixin, aio.StreamUnaryCall
|
| 145 |
+
):
|
| 146 |
+
"""Wrapped StreamUnaryCall to map exceptions."""
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
class _WrappedStreamStreamCall(
|
| 150 |
+
_WrappedStreamRequestMixin, _WrappedStreamResponseMixin[P], aio.StreamStreamCall
|
| 151 |
+
):
|
| 152 |
+
"""Wrapped StreamStreamCall to map exceptions."""
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
# public type alias denoting the return type of async streaming gapic calls
|
| 156 |
+
GrpcAsyncStream = _WrappedStreamResponseMixin
|
| 157 |
+
# public type alias denoting the return type of unary gapic calls
|
| 158 |
+
AwaitableGrpcCall = _WrappedUnaryResponseMixin
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _wrap_unary_errors(callable_):
|
| 162 |
+
"""Map errors for Unary-Unary async callables."""
|
| 163 |
+
|
| 164 |
+
@functools.wraps(callable_)
|
| 165 |
+
def error_remapped_callable(*args, **kwargs):
|
| 166 |
+
call = callable_(*args, **kwargs)
|
| 167 |
+
return _WrappedUnaryUnaryCall().with_call(call)
|
| 168 |
+
|
| 169 |
+
return error_remapped_callable
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _wrap_stream_errors(callable_, wrapper_type):
|
| 173 |
+
"""Map errors for streaming RPC async callables."""
|
| 174 |
+
|
| 175 |
+
@functools.wraps(callable_)
|
| 176 |
+
async def error_remapped_callable(*args, **kwargs):
|
| 177 |
+
call = callable_(*args, **kwargs)
|
| 178 |
+
call = wrapper_type().with_call(call)
|
| 179 |
+
await call.wait_for_connection()
|
| 180 |
+
return call
|
| 181 |
+
|
| 182 |
+
return error_remapped_callable
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def wrap_errors(callable_):
|
| 186 |
+
"""Wrap a gRPC async callable and map :class:`grpc.RpcErrors` to
|
| 187 |
+
friendly error classes.
|
| 188 |
+
|
| 189 |
+
Errors raised by the gRPC callable are mapped to the appropriate
|
| 190 |
+
:class:`google.api_core.exceptions.GoogleAPICallError` subclasses. The
|
| 191 |
+
original `grpc.RpcError` (which is usually also a `grpc.Call`) is
|
| 192 |
+
available from the ``response`` property on the mapped exception. This
|
| 193 |
+
is useful for extracting metadata from the original error.
|
| 194 |
+
|
| 195 |
+
Args:
|
| 196 |
+
callable_ (Callable): A gRPC callable.
|
| 197 |
+
|
| 198 |
+
Returns: Callable: The wrapped gRPC callable.
|
| 199 |
+
"""
|
| 200 |
+
grpc_helpers._patch_callable_name(callable_)
|
| 201 |
+
|
| 202 |
+
if isinstance(callable_, aio.UnaryStreamMultiCallable):
|
| 203 |
+
return _wrap_stream_errors(callable_, _WrappedUnaryStreamCall)
|
| 204 |
+
elif isinstance(callable_, aio.StreamUnaryMultiCallable):
|
| 205 |
+
return _wrap_stream_errors(callable_, _WrappedStreamUnaryCall)
|
| 206 |
+
elif isinstance(callable_, aio.StreamStreamMultiCallable):
|
| 207 |
+
return _wrap_stream_errors(callable_, _WrappedStreamStreamCall)
|
| 208 |
+
else:
|
| 209 |
+
return _wrap_unary_errors(callable_)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def create_channel(
|
| 213 |
+
target,
|
| 214 |
+
credentials=None,
|
| 215 |
+
scopes=None,
|
| 216 |
+
ssl_credentials=None,
|
| 217 |
+
credentials_file=None,
|
| 218 |
+
quota_project_id=None,
|
| 219 |
+
default_scopes=None,
|
| 220 |
+
default_host=None,
|
| 221 |
+
compression=None,
|
| 222 |
+
attempt_direct_path: Optional[bool] = False,
|
| 223 |
+
**kwargs,
|
| 224 |
+
):
|
| 225 |
+
"""Create an AsyncIO secure channel with credentials.
|
| 226 |
+
|
| 227 |
+
Args:
|
| 228 |
+
target (str): The target service address in the format 'hostname:port'.
|
| 229 |
+
credentials (google.auth.credentials.Credentials): The credentials. If
|
| 230 |
+
not specified, then this function will attempt to ascertain the
|
| 231 |
+
credentials from the environment using :func:`google.auth.default`.
|
| 232 |
+
scopes (Sequence[str]): A optional list of scopes needed for this
|
| 233 |
+
service. These are only used when credentials are not specified and
|
| 234 |
+
are passed to :func:`google.auth.default`.
|
| 235 |
+
ssl_credentials (grpc.ChannelCredentials): Optional SSL channel
|
| 236 |
+
credentials. This can be used to specify different certificates.
|
| 237 |
+
credentials_file (str): Deprecated. A file with credentials that can be loaded with
|
| 238 |
+
:func:`google.auth.load_credentials_from_file`. This argument is
|
| 239 |
+
mutually exclusive with credentials. This argument will be
|
| 240 |
+
removed in the next major version of `google-api-core`.
|
| 241 |
+
|
| 242 |
+
.. warning::
|
| 243 |
+
Important: If you accept a credential configuration (credential JSON/File/Stream)
|
| 244 |
+
from an external source for authentication to Google Cloud Platform, you must
|
| 245 |
+
validate it before providing it to any Google API or client library. Providing an
|
| 246 |
+
unvalidated credential configuration to Google APIs or libraries can compromise
|
| 247 |
+
the security of your systems and data. For more information, refer to
|
| 248 |
+
`Validate credential configurations from external sources`_.
|
| 249 |
+
|
| 250 |
+
.. _Validate credential configurations from external sources:
|
| 251 |
+
|
| 252 |
+
https://cloud.google.com/docs/authentication/external/externally-sourced-credentials
|
| 253 |
+
quota_project_id (str): An optional project to use for billing and quota.
|
| 254 |
+
default_scopes (Sequence[str]): Default scopes passed by a Google client
|
| 255 |
+
library. Use 'scopes' for user-defined scopes.
|
| 256 |
+
default_host (str): The default endpoint. e.g., "pubsub.googleapis.com".
|
| 257 |
+
compression (grpc.Compression): An optional value indicating the
|
| 258 |
+
compression method to be used over the lifetime of the channel.
|
| 259 |
+
attempt_direct_path (Optional[bool]): If set, Direct Path will be attempted
|
| 260 |
+
when the request is made. Direct Path is only available within a Google
|
| 261 |
+
Compute Engine (GCE) environment and provides a proxyless connection
|
| 262 |
+
which increases the available throughput, reduces latency, and increases
|
| 263 |
+
reliability. Note:
|
| 264 |
+
|
| 265 |
+
- This argument should only be set in a GCE environment and for Services
|
| 266 |
+
that are known to support Direct Path.
|
| 267 |
+
- If this argument is set outside of GCE, then this request will fail
|
| 268 |
+
unless the back-end service happens to have configured fall-back to DNS.
|
| 269 |
+
- If the request causes a `ServiceUnavailable` response, it is recommended
|
| 270 |
+
that the client repeat the request with `attempt_direct_path` set to
|
| 271 |
+
`False` as the Service may not support Direct Path.
|
| 272 |
+
- Using `ssl_credentials` with `attempt_direct_path` set to `True` will
|
| 273 |
+
result in `ValueError` as this combination is not yet supported.
|
| 274 |
+
|
| 275 |
+
kwargs: Additional key-word args passed to :func:`aio.secure_channel`.
|
| 276 |
+
|
| 277 |
+
Returns:
|
| 278 |
+
aio.Channel: The created channel.
|
| 279 |
+
|
| 280 |
+
Raises:
|
| 281 |
+
google.api_core.DuplicateCredentialArgs: If both a credentials object and credentials_file are passed.
|
| 282 |
+
ValueError: If `ssl_credentials` is set and `attempt_direct_path` is set to `True`.
|
| 283 |
+
"""
|
| 284 |
+
|
| 285 |
+
if credentials_file is not None:
|
| 286 |
+
warnings.warn(general_helpers._CREDENTIALS_FILE_WARNING, DeprecationWarning)
|
| 287 |
+
|
| 288 |
+
# If `ssl_credentials` is set and `attempt_direct_path` is set to `True`,
|
| 289 |
+
# raise ValueError as this is not yet supported.
|
| 290 |
+
# See https://github.com/googleapis/python-api-core/issues/590
|
| 291 |
+
if ssl_credentials and attempt_direct_path:
|
| 292 |
+
raise ValueError("Using ssl_credentials with Direct Path is not supported")
|
| 293 |
+
|
| 294 |
+
composite_credentials = grpc_helpers._create_composite_credentials(
|
| 295 |
+
credentials=credentials,
|
| 296 |
+
credentials_file=credentials_file,
|
| 297 |
+
scopes=scopes,
|
| 298 |
+
default_scopes=default_scopes,
|
| 299 |
+
ssl_credentials=ssl_credentials,
|
| 300 |
+
quota_project_id=quota_project_id,
|
| 301 |
+
default_host=default_host,
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
if attempt_direct_path:
|
| 305 |
+
target = grpc_helpers._modify_target_for_direct_path(target)
|
| 306 |
+
|
| 307 |
+
return aio.secure_channel(
|
| 308 |
+
target, composite_credentials, compression=compression, **kwargs
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
class FakeUnaryUnaryCall(_WrappedUnaryUnaryCall):
|
| 313 |
+
"""Fake implementation for unary-unary RPCs.
|
| 314 |
+
|
| 315 |
+
It is a dummy object for response message. Supply the intended response
|
| 316 |
+
upon the initialization, and the coroutine will return the exact response
|
| 317 |
+
message.
|
| 318 |
+
"""
|
| 319 |
+
|
| 320 |
+
def __init__(self, response=object()):
|
| 321 |
+
self.response = response
|
| 322 |
+
self._future = asyncio.get_event_loop().create_future()
|
| 323 |
+
self._future.set_result(self.response)
|
| 324 |
+
|
| 325 |
+
def __await__(self):
|
| 326 |
+
response = yield from self._future.__await__()
|
| 327 |
+
return response
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
class FakeStreamUnaryCall(_WrappedStreamUnaryCall):
|
| 331 |
+
"""Fake implementation for stream-unary RPCs.
|
| 332 |
+
|
| 333 |
+
It is a dummy object for response message. Supply the intended response
|
| 334 |
+
upon the initialization, and the coroutine will return the exact response
|
| 335 |
+
message.
|
| 336 |
+
"""
|
| 337 |
+
|
| 338 |
+
def __init__(self, response=object()):
|
| 339 |
+
self.response = response
|
| 340 |
+
self._future = asyncio.get_event_loop().create_future()
|
| 341 |
+
self._future.set_result(self.response)
|
| 342 |
+
|
| 343 |
+
def __await__(self):
|
| 344 |
+
response = yield from self._future.__await__()
|
| 345 |
+
return response
|
| 346 |
+
|
| 347 |
+
async def wait_for_connection(self):
|
| 348 |
+
pass
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/iam.py
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Non-API-specific IAM policy definitions
|
| 15 |
+
|
| 16 |
+
For allowed roles / permissions, see:
|
| 17 |
+
https://cloud.google.com/iam/docs/understanding-roles
|
| 18 |
+
|
| 19 |
+
Example usage:
|
| 20 |
+
|
| 21 |
+
.. code-block:: python
|
| 22 |
+
|
| 23 |
+
# ``get_iam_policy`` returns a :class:'~google.api_core.iam.Policy`.
|
| 24 |
+
policy = resource.get_iam_policy(requested_policy_version=3)
|
| 25 |
+
|
| 26 |
+
phred = "user:phred@example.com"
|
| 27 |
+
admin_group = "group:admins@groups.example.com"
|
| 28 |
+
account = "serviceAccount:account-1234@accounts.example.com"
|
| 29 |
+
|
| 30 |
+
policy.version = 3
|
| 31 |
+
policy.bindings = [
|
| 32 |
+
{
|
| 33 |
+
"role": "roles/owner",
|
| 34 |
+
"members": {phred, admin_group, account}
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"role": "roles/editor",
|
| 38 |
+
"members": {"allAuthenticatedUsers"}
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"role": "roles/viewer",
|
| 42 |
+
"members": {"allUsers"}
|
| 43 |
+
"condition": {
|
| 44 |
+
"title": "request_time",
|
| 45 |
+
"description": "Requests made before 2021-01-01T00:00:00Z",
|
| 46 |
+
"expression": "request.time < timestamp(\"2021-01-01T00:00:00Z\")"
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
]
|
| 50 |
+
|
| 51 |
+
resource.set_iam_policy(policy)
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
import collections
|
| 55 |
+
import collections.abc
|
| 56 |
+
import operator
|
| 57 |
+
import warnings
|
| 58 |
+
|
| 59 |
+
# Generic IAM roles
|
| 60 |
+
|
| 61 |
+
OWNER_ROLE = "roles/owner"
|
| 62 |
+
"""Generic role implying all rights to an object."""
|
| 63 |
+
|
| 64 |
+
EDITOR_ROLE = "roles/editor"
|
| 65 |
+
"""Generic role implying rights to modify an object."""
|
| 66 |
+
|
| 67 |
+
VIEWER_ROLE = "roles/viewer"
|
| 68 |
+
"""Generic role implying rights to access an object."""
|
| 69 |
+
|
| 70 |
+
_ASSIGNMENT_DEPRECATED_MSG = """\
|
| 71 |
+
Assigning to '{}' is deprecated. Use the `policy.bindings` property to modify bindings instead."""
|
| 72 |
+
|
| 73 |
+
_DICT_ACCESS_MSG = """\
|
| 74 |
+
Dict access is not supported on policies with version > 1 or with conditional bindings."""
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class InvalidOperationException(Exception):
|
| 78 |
+
"""Raised when trying to use Policy class as a dict."""
|
| 79 |
+
|
| 80 |
+
pass
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class Policy(collections.abc.MutableMapping):
|
| 84 |
+
"""IAM Policy
|
| 85 |
+
|
| 86 |
+
Args:
|
| 87 |
+
etag (Optional[str]): ETag used to identify a unique of the policy
|
| 88 |
+
version (Optional[int]): The syntax schema version of the policy.
|
| 89 |
+
|
| 90 |
+
Note:
|
| 91 |
+
Using conditions in bindings requires the policy's version to be set
|
| 92 |
+
to `3` or greater, depending on the versions that are currently supported.
|
| 93 |
+
|
| 94 |
+
Accessing the policy using dict operations will raise InvalidOperationException
|
| 95 |
+
when the policy's version is set to 3.
|
| 96 |
+
|
| 97 |
+
Use the policy.bindings getter/setter to retrieve and modify the policy's bindings.
|
| 98 |
+
|
| 99 |
+
See:
|
| 100 |
+
IAM Policy https://cloud.google.com/iam/reference/rest/v1/Policy
|
| 101 |
+
Policy versions https://cloud.google.com/iam/docs/policies#versions
|
| 102 |
+
Conditions overview https://cloud.google.com/iam/docs/conditions-overview.
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
_OWNER_ROLES = (OWNER_ROLE,)
|
| 106 |
+
"""Roles mapped onto our ``owners`` attribute."""
|
| 107 |
+
|
| 108 |
+
_EDITOR_ROLES = (EDITOR_ROLE,)
|
| 109 |
+
"""Roles mapped onto our ``editors`` attribute."""
|
| 110 |
+
|
| 111 |
+
_VIEWER_ROLES = (VIEWER_ROLE,)
|
| 112 |
+
"""Roles mapped onto our ``viewers`` attribute."""
|
| 113 |
+
|
| 114 |
+
def __init__(self, etag=None, version=None):
|
| 115 |
+
self.etag = etag
|
| 116 |
+
self.version = version
|
| 117 |
+
self._bindings = []
|
| 118 |
+
|
| 119 |
+
def __iter__(self):
|
| 120 |
+
self.__check_version__()
|
| 121 |
+
# Exclude bindings with no members
|
| 122 |
+
return (binding["role"] for binding in self._bindings if binding["members"])
|
| 123 |
+
|
| 124 |
+
def __len__(self):
|
| 125 |
+
self.__check_version__()
|
| 126 |
+
# Exclude bindings with no members
|
| 127 |
+
return len(list(self.__iter__()))
|
| 128 |
+
|
| 129 |
+
def __getitem__(self, key):
|
| 130 |
+
self.__check_version__()
|
| 131 |
+
for b in self._bindings:
|
| 132 |
+
if b["role"] == key:
|
| 133 |
+
return b["members"]
|
| 134 |
+
# If the binding does not yet exist, create one
|
| 135 |
+
# NOTE: This will create bindings with no members
|
| 136 |
+
# which are ignored by __iter__ and __len__
|
| 137 |
+
new_binding = {"role": key, "members": set()}
|
| 138 |
+
self._bindings.append(new_binding)
|
| 139 |
+
return new_binding["members"]
|
| 140 |
+
|
| 141 |
+
def __setitem__(self, key, value):
|
| 142 |
+
self.__check_version__()
|
| 143 |
+
value = set(value)
|
| 144 |
+
for binding in self._bindings:
|
| 145 |
+
if binding["role"] == key:
|
| 146 |
+
binding["members"] = value
|
| 147 |
+
return
|
| 148 |
+
self._bindings.append({"role": key, "members": value})
|
| 149 |
+
|
| 150 |
+
def __delitem__(self, key):
|
| 151 |
+
self.__check_version__()
|
| 152 |
+
for b in self._bindings:
|
| 153 |
+
if b["role"] == key:
|
| 154 |
+
self._bindings.remove(b)
|
| 155 |
+
return
|
| 156 |
+
raise KeyError(key)
|
| 157 |
+
|
| 158 |
+
def __check_version__(self):
|
| 159 |
+
"""Raise InvalidOperationException if version is greater than 1 or policy contains conditions."""
|
| 160 |
+
raise_version = self.version is not None and self.version > 1
|
| 161 |
+
|
| 162 |
+
if raise_version or self._contains_conditions():
|
| 163 |
+
raise InvalidOperationException(_DICT_ACCESS_MSG)
|
| 164 |
+
|
| 165 |
+
def _contains_conditions(self):
|
| 166 |
+
for b in self._bindings:
|
| 167 |
+
if b.get("condition") is not None:
|
| 168 |
+
return True
|
| 169 |
+
return False
|
| 170 |
+
|
| 171 |
+
@property
|
| 172 |
+
def bindings(self):
|
| 173 |
+
"""The policy's list of bindings.
|
| 174 |
+
|
| 175 |
+
A binding is specified by a dictionary with keys:
|
| 176 |
+
|
| 177 |
+
* role (str): Role that is assigned to `members`.
|
| 178 |
+
|
| 179 |
+
* members (:obj:`set` of str): Specifies the identities associated to this binding.
|
| 180 |
+
|
| 181 |
+
* condition (:obj:`dict` of str:str): Specifies a condition under which this binding will apply.
|
| 182 |
+
|
| 183 |
+
* title (str): Title for the condition.
|
| 184 |
+
|
| 185 |
+
* description (:obj:str, optional): Description of the condition.
|
| 186 |
+
|
| 187 |
+
* expression: A CEL expression.
|
| 188 |
+
|
| 189 |
+
Type:
|
| 190 |
+
:obj:`list` of :obj:`dict`
|
| 191 |
+
|
| 192 |
+
See:
|
| 193 |
+
Policy versions https://cloud.google.com/iam/docs/policies#versions
|
| 194 |
+
Conditions overview https://cloud.google.com/iam/docs/conditions-overview.
|
| 195 |
+
|
| 196 |
+
Example:
|
| 197 |
+
|
| 198 |
+
.. code-block:: python
|
| 199 |
+
|
| 200 |
+
USER = "user:phred@example.com"
|
| 201 |
+
ADMIN_GROUP = "group:admins@groups.example.com"
|
| 202 |
+
SERVICE_ACCOUNT = "serviceAccount:account-1234@accounts.example.com"
|
| 203 |
+
CONDITION = {
|
| 204 |
+
"title": "request_time",
|
| 205 |
+
"description": "Requests made before 2021-01-01T00:00:00Z", # Optional
|
| 206 |
+
"expression": "request.time < timestamp(\"2021-01-01T00:00:00Z\")"
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
# Set policy's version to 3 before setting bindings containing conditions.
|
| 210 |
+
policy.version = 3
|
| 211 |
+
|
| 212 |
+
policy.bindings = [
|
| 213 |
+
{
|
| 214 |
+
"role": "roles/viewer",
|
| 215 |
+
"members": {USER, ADMIN_GROUP, SERVICE_ACCOUNT},
|
| 216 |
+
"condition": CONDITION
|
| 217 |
+
},
|
| 218 |
+
...
|
| 219 |
+
]
|
| 220 |
+
"""
|
| 221 |
+
return self._bindings
|
| 222 |
+
|
| 223 |
+
@bindings.setter
|
| 224 |
+
def bindings(self, bindings):
|
| 225 |
+
self._bindings = bindings
|
| 226 |
+
|
| 227 |
+
@property
|
| 228 |
+
def owners(self):
|
| 229 |
+
"""Legacy access to owner role.
|
| 230 |
+
|
| 231 |
+
Raise InvalidOperationException if version is greater than 1 or policy contains conditions.
|
| 232 |
+
|
| 233 |
+
DEPRECATED: use `policy.bindings` to access bindings instead.
|
| 234 |
+
"""
|
| 235 |
+
result = set()
|
| 236 |
+
for role in self._OWNER_ROLES:
|
| 237 |
+
for member in self.get(role, ()):
|
| 238 |
+
result.add(member)
|
| 239 |
+
return frozenset(result)
|
| 240 |
+
|
| 241 |
+
@owners.setter
|
| 242 |
+
def owners(self, value):
|
| 243 |
+
"""Update owners.
|
| 244 |
+
|
| 245 |
+
Raise InvalidOperationException if version is greater than 1 or policy contains conditions.
|
| 246 |
+
|
| 247 |
+
DEPRECATED: use `policy.bindings` to access bindings instead.
|
| 248 |
+
"""
|
| 249 |
+
warnings.warn(
|
| 250 |
+
_ASSIGNMENT_DEPRECATED_MSG.format("owners", OWNER_ROLE), DeprecationWarning
|
| 251 |
+
)
|
| 252 |
+
self[OWNER_ROLE] = value
|
| 253 |
+
|
| 254 |
+
@property
|
| 255 |
+
def editors(self):
|
| 256 |
+
"""Legacy access to editor role.
|
| 257 |
+
|
| 258 |
+
Raise InvalidOperationException if version is greater than 1 or policy contains conditions.
|
| 259 |
+
|
| 260 |
+
DEPRECATED: use `policy.bindings` to access bindings instead.
|
| 261 |
+
"""
|
| 262 |
+
result = set()
|
| 263 |
+
for role in self._EDITOR_ROLES:
|
| 264 |
+
for member in self.get(role, ()):
|
| 265 |
+
result.add(member)
|
| 266 |
+
return frozenset(result)
|
| 267 |
+
|
| 268 |
+
@editors.setter
|
| 269 |
+
def editors(self, value):
|
| 270 |
+
"""Update editors.
|
| 271 |
+
|
| 272 |
+
Raise InvalidOperationException if version is greater than 1 or policy contains conditions.
|
| 273 |
+
|
| 274 |
+
DEPRECATED: use `policy.bindings` to modify bindings instead.
|
| 275 |
+
"""
|
| 276 |
+
warnings.warn(
|
| 277 |
+
_ASSIGNMENT_DEPRECATED_MSG.format("editors", EDITOR_ROLE),
|
| 278 |
+
DeprecationWarning,
|
| 279 |
+
)
|
| 280 |
+
self[EDITOR_ROLE] = value
|
| 281 |
+
|
| 282 |
+
@property
|
| 283 |
+
def viewers(self):
|
| 284 |
+
"""Legacy access to viewer role.
|
| 285 |
+
|
| 286 |
+
Raise InvalidOperationException if version is greater than 1 or policy contains conditions.
|
| 287 |
+
|
| 288 |
+
DEPRECATED: use `policy.bindings` to modify bindings instead.
|
| 289 |
+
"""
|
| 290 |
+
result = set()
|
| 291 |
+
for role in self._VIEWER_ROLES:
|
| 292 |
+
for member in self.get(role, ()):
|
| 293 |
+
result.add(member)
|
| 294 |
+
return frozenset(result)
|
| 295 |
+
|
| 296 |
+
@viewers.setter
|
| 297 |
+
def viewers(self, value):
|
| 298 |
+
"""Update viewers.
|
| 299 |
+
|
| 300 |
+
Raise InvalidOperationException if version is greater than 1 or policy contains conditions.
|
| 301 |
+
|
| 302 |
+
DEPRECATED: use `policy.bindings` to modify bindings instead.
|
| 303 |
+
"""
|
| 304 |
+
warnings.warn(
|
| 305 |
+
_ASSIGNMENT_DEPRECATED_MSG.format("viewers", VIEWER_ROLE),
|
| 306 |
+
DeprecationWarning,
|
| 307 |
+
)
|
| 308 |
+
self[VIEWER_ROLE] = value
|
| 309 |
+
|
| 310 |
+
@staticmethod
|
| 311 |
+
def user(email):
|
| 312 |
+
"""Factory method for a user member.
|
| 313 |
+
|
| 314 |
+
Args:
|
| 315 |
+
email (str): E-mail for this particular user.
|
| 316 |
+
|
| 317 |
+
Returns:
|
| 318 |
+
str: A member string corresponding to the given user.
|
| 319 |
+
"""
|
| 320 |
+
return "user:%s" % (email,)
|
| 321 |
+
|
| 322 |
+
@staticmethod
|
| 323 |
+
def service_account(email):
|
| 324 |
+
"""Factory method for a service account member.
|
| 325 |
+
|
| 326 |
+
Args:
|
| 327 |
+
email (str): E-mail for this particular service account.
|
| 328 |
+
|
| 329 |
+
Returns:
|
| 330 |
+
str: A member string corresponding to the given service account.
|
| 331 |
+
|
| 332 |
+
"""
|
| 333 |
+
return "serviceAccount:%s" % (email,)
|
| 334 |
+
|
| 335 |
+
@staticmethod
|
| 336 |
+
def group(email):
|
| 337 |
+
"""Factory method for a group member.
|
| 338 |
+
|
| 339 |
+
Args:
|
| 340 |
+
email (str): An id or e-mail for this particular group.
|
| 341 |
+
|
| 342 |
+
Returns:
|
| 343 |
+
str: A member string corresponding to the given group.
|
| 344 |
+
"""
|
| 345 |
+
return "group:%s" % (email,)
|
| 346 |
+
|
| 347 |
+
@staticmethod
|
| 348 |
+
def domain(domain):
|
| 349 |
+
"""Factory method for a domain member.
|
| 350 |
+
|
| 351 |
+
Args:
|
| 352 |
+
domain (str): The domain for this member.
|
| 353 |
+
|
| 354 |
+
Returns:
|
| 355 |
+
str: A member string corresponding to the given domain.
|
| 356 |
+
"""
|
| 357 |
+
return "domain:%s" % (domain,)
|
| 358 |
+
|
| 359 |
+
@staticmethod
|
| 360 |
+
def all_users():
|
| 361 |
+
"""Factory method for a member representing all users.
|
| 362 |
+
|
| 363 |
+
Returns:
|
| 364 |
+
str: A member string representing all users.
|
| 365 |
+
"""
|
| 366 |
+
return "allUsers"
|
| 367 |
+
|
| 368 |
+
@staticmethod
|
| 369 |
+
def authenticated_users():
|
| 370 |
+
"""Factory method for a member representing all authenticated users.
|
| 371 |
+
|
| 372 |
+
Returns:
|
| 373 |
+
str: A member string representing all authenticated users.
|
| 374 |
+
"""
|
| 375 |
+
return "allAuthenticatedUsers"
|
| 376 |
+
|
| 377 |
+
@classmethod
|
| 378 |
+
def from_api_repr(cls, resource):
|
| 379 |
+
"""Factory: create a policy from a JSON resource.
|
| 380 |
+
|
| 381 |
+
Args:
|
| 382 |
+
resource (dict): policy resource returned by ``getIamPolicy`` API.
|
| 383 |
+
|
| 384 |
+
Returns:
|
| 385 |
+
:class:`Policy`: the parsed policy
|
| 386 |
+
"""
|
| 387 |
+
version = resource.get("version")
|
| 388 |
+
etag = resource.get("etag")
|
| 389 |
+
policy = cls(etag, version)
|
| 390 |
+
policy.bindings = resource.get("bindings", [])
|
| 391 |
+
|
| 392 |
+
for binding in policy.bindings:
|
| 393 |
+
binding["members"] = set(binding.get("members", ()))
|
| 394 |
+
|
| 395 |
+
return policy
|
| 396 |
+
|
| 397 |
+
def to_api_repr(self):
|
| 398 |
+
"""Render a JSON policy resource.
|
| 399 |
+
|
| 400 |
+
Returns:
|
| 401 |
+
dict: a resource to be passed to the ``setIamPolicy`` API.
|
| 402 |
+
"""
|
| 403 |
+
resource = {}
|
| 404 |
+
|
| 405 |
+
if self.etag is not None:
|
| 406 |
+
resource["etag"] = self.etag
|
| 407 |
+
|
| 408 |
+
if self.version is not None:
|
| 409 |
+
resource["version"] = self.version
|
| 410 |
+
|
| 411 |
+
if self._bindings and len(self._bindings) > 0:
|
| 412 |
+
bindings = []
|
| 413 |
+
for binding in self._bindings:
|
| 414 |
+
members = binding.get("members")
|
| 415 |
+
if members:
|
| 416 |
+
new_binding = {"role": binding["role"], "members": sorted(members)}
|
| 417 |
+
condition = binding.get("condition")
|
| 418 |
+
if condition:
|
| 419 |
+
new_binding["condition"] = condition
|
| 420 |
+
bindings.append(new_binding)
|
| 421 |
+
|
| 422 |
+
if bindings:
|
| 423 |
+
# Sort bindings by role
|
| 424 |
+
key = operator.itemgetter("role")
|
| 425 |
+
resource["bindings"] = sorted(bindings, key=key)
|
| 426 |
+
|
| 427 |
+
return resource
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/operation.py
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2016 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Futures for long-running operations returned from Google Cloud APIs.
|
| 16 |
+
|
| 17 |
+
These futures can be used to synchronously wait for the result of a
|
| 18 |
+
long-running operation using :meth:`Operation.result`:
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
.. code-block:: python
|
| 22 |
+
|
| 23 |
+
operation = my_api_client.long_running_method()
|
| 24 |
+
result = operation.result()
|
| 25 |
+
|
| 26 |
+
Or asynchronously using callbacks and :meth:`Operation.add_done_callback`:
|
| 27 |
+
|
| 28 |
+
.. code-block:: python
|
| 29 |
+
|
| 30 |
+
operation = my_api_client.long_running_method()
|
| 31 |
+
|
| 32 |
+
def my_callback(future):
|
| 33 |
+
result = future.result()
|
| 34 |
+
|
| 35 |
+
operation.add_done_callback(my_callback)
|
| 36 |
+
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
import functools
|
| 40 |
+
import threading
|
| 41 |
+
|
| 42 |
+
from google.api_core import exceptions
|
| 43 |
+
from google.api_core import protobuf_helpers
|
| 44 |
+
from google.api_core.future import polling
|
| 45 |
+
from google.longrunning import operations_pb2
|
| 46 |
+
from google.protobuf import json_format
|
| 47 |
+
from google.rpc import code_pb2
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class Operation(polling.PollingFuture):
|
| 51 |
+
"""A Future for interacting with a Google API Long-Running Operation.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
operation (google.longrunning.operations_pb2.Operation): The
|
| 55 |
+
initial operation.
|
| 56 |
+
refresh (Callable[[], ~.api_core.operation.Operation]): A callable that
|
| 57 |
+
returns the latest state of the operation.
|
| 58 |
+
cancel (Callable[[], None]): A callable that tries to cancel
|
| 59 |
+
the operation.
|
| 60 |
+
result_type (func:`type`): The protobuf type for the operation's
|
| 61 |
+
result.
|
| 62 |
+
metadata_type (func:`type`): The protobuf type for the operation's
|
| 63 |
+
metadata.
|
| 64 |
+
polling (google.api_core.retry.Retry): The configuration used for polling.
|
| 65 |
+
This parameter controls how often :meth:`done` is polled. If the
|
| 66 |
+
``timeout`` argument is specified in the :meth:`result` method, it will
|
| 67 |
+
override the ``polling.timeout`` property.
|
| 68 |
+
retry (google.api_core.retry.Retry): DEPRECATED: use ``polling`` instead.
|
| 69 |
+
If specified it will override ``polling`` parameter to maintain
|
| 70 |
+
backward compatibility.
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
def __init__(
|
| 74 |
+
self,
|
| 75 |
+
operation,
|
| 76 |
+
refresh,
|
| 77 |
+
cancel,
|
| 78 |
+
result_type,
|
| 79 |
+
metadata_type=None,
|
| 80 |
+
polling=polling.DEFAULT_POLLING,
|
| 81 |
+
**kwargs,
|
| 82 |
+
):
|
| 83 |
+
super(Operation, self).__init__(polling=polling, **kwargs)
|
| 84 |
+
self._operation = operation
|
| 85 |
+
self._refresh = refresh
|
| 86 |
+
self._cancel = cancel
|
| 87 |
+
self._result_type = result_type
|
| 88 |
+
self._metadata_type = metadata_type
|
| 89 |
+
self._completion_lock = threading.Lock()
|
| 90 |
+
# Invoke this in case the operation came back already complete.
|
| 91 |
+
self._set_result_from_operation()
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def operation(self):
|
| 95 |
+
"""google.longrunning.Operation: The current long-running operation."""
|
| 96 |
+
return self._operation
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def metadata(self):
|
| 100 |
+
"""google.protobuf.Message: the current operation metadata."""
|
| 101 |
+
if not self._operation.HasField("metadata"):
|
| 102 |
+
return None
|
| 103 |
+
|
| 104 |
+
return protobuf_helpers.from_any_pb(
|
| 105 |
+
self._metadata_type, self._operation.metadata
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
@classmethod
|
| 109 |
+
def deserialize(self, payload):
|
| 110 |
+
"""Deserialize a ``google.longrunning.Operation`` protocol buffer.
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
payload (bytes): A serialized operation protocol buffer.
|
| 114 |
+
|
| 115 |
+
Returns:
|
| 116 |
+
~.operations_pb2.Operation: An Operation protobuf object.
|
| 117 |
+
"""
|
| 118 |
+
return operations_pb2.Operation.FromString(payload)
|
| 119 |
+
|
| 120 |
+
def _set_result_from_operation(self):
|
| 121 |
+
"""Set the result or exception from the operation if it is complete."""
|
| 122 |
+
# This must be done in a lock to prevent the polling thread
|
| 123 |
+
# and main thread from both executing the completion logic
|
| 124 |
+
# at the same time.
|
| 125 |
+
with self._completion_lock:
|
| 126 |
+
# If the operation isn't complete or if the result has already been
|
| 127 |
+
# set, do not call set_result/set_exception again.
|
| 128 |
+
# Note: self._result_set is set to True in set_result and
|
| 129 |
+
# set_exception, in case those methods are invoked directly.
|
| 130 |
+
if not self._operation.done or self._result_set:
|
| 131 |
+
return
|
| 132 |
+
|
| 133 |
+
if self._operation.HasField("response"):
|
| 134 |
+
response = protobuf_helpers.from_any_pb(
|
| 135 |
+
self._result_type, self._operation.response
|
| 136 |
+
)
|
| 137 |
+
self.set_result(response)
|
| 138 |
+
elif self._operation.HasField("error"):
|
| 139 |
+
exception = exceptions.from_grpc_status(
|
| 140 |
+
status_code=self._operation.error.code,
|
| 141 |
+
message=self._operation.error.message,
|
| 142 |
+
errors=(self._operation.error,),
|
| 143 |
+
response=self._operation,
|
| 144 |
+
)
|
| 145 |
+
self.set_exception(exception)
|
| 146 |
+
else:
|
| 147 |
+
exception = exceptions.GoogleAPICallError(
|
| 148 |
+
"Unexpected state: Long-running operation had neither "
|
| 149 |
+
"response nor error set."
|
| 150 |
+
)
|
| 151 |
+
self.set_exception(exception)
|
| 152 |
+
|
| 153 |
+
def _refresh_and_update(self, retry=None):
|
| 154 |
+
"""Refresh the operation and update the result if needed.
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
retry (google.api_core.retry.Retry): (Optional) How to retry the RPC.
|
| 158 |
+
"""
|
| 159 |
+
# If the currently cached operation is done, no need to make another
|
| 160 |
+
# RPC as it will not change once done.
|
| 161 |
+
if not self._operation.done:
|
| 162 |
+
self._operation = self._refresh(retry=retry) if retry else self._refresh()
|
| 163 |
+
self._set_result_from_operation()
|
| 164 |
+
|
| 165 |
+
def done(self, retry=None):
|
| 166 |
+
"""Checks to see if the operation is complete.
|
| 167 |
+
|
| 168 |
+
Args:
|
| 169 |
+
retry (google.api_core.retry.Retry): (Optional) How to retry the RPC.
|
| 170 |
+
|
| 171 |
+
Returns:
|
| 172 |
+
bool: True if the operation is complete, False otherwise.
|
| 173 |
+
"""
|
| 174 |
+
self._refresh_and_update(retry)
|
| 175 |
+
return self._operation.done
|
| 176 |
+
|
| 177 |
+
def cancel(self):
|
| 178 |
+
"""Attempt to cancel the operation.
|
| 179 |
+
|
| 180 |
+
Returns:
|
| 181 |
+
bool: True if the cancel RPC was made, False if the operation is
|
| 182 |
+
already complete.
|
| 183 |
+
"""
|
| 184 |
+
if self.done():
|
| 185 |
+
return False
|
| 186 |
+
|
| 187 |
+
self._cancel()
|
| 188 |
+
return True
|
| 189 |
+
|
| 190 |
+
def cancelled(self):
|
| 191 |
+
"""True if the operation was cancelled."""
|
| 192 |
+
self._refresh_and_update()
|
| 193 |
+
return (
|
| 194 |
+
self._operation.HasField("error")
|
| 195 |
+
and self._operation.error.code == code_pb2.CANCELLED
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _refresh_http(api_request, operation_name, retry=None):
|
| 200 |
+
"""Refresh an operation using a JSON/HTTP client.
|
| 201 |
+
|
| 202 |
+
Args:
|
| 203 |
+
api_request (Callable): A callable used to make an API request. This
|
| 204 |
+
should generally be
|
| 205 |
+
:meth:`google.cloud._http.Connection.api_request`.
|
| 206 |
+
operation_name (str): The name of the operation.
|
| 207 |
+
retry (google.api_core.retry.Retry): (Optional) retry policy
|
| 208 |
+
|
| 209 |
+
Returns:
|
| 210 |
+
google.longrunning.operations_pb2.Operation: The operation.
|
| 211 |
+
"""
|
| 212 |
+
path = "operations/{}".format(operation_name)
|
| 213 |
+
|
| 214 |
+
if retry is not None:
|
| 215 |
+
api_request = retry(api_request)
|
| 216 |
+
|
| 217 |
+
api_response = api_request(method="GET", path=path)
|
| 218 |
+
return json_format.ParseDict(api_response, operations_pb2.Operation())
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _cancel_http(api_request, operation_name):
|
| 222 |
+
"""Cancel an operation using a JSON/HTTP client.
|
| 223 |
+
|
| 224 |
+
Args:
|
| 225 |
+
api_request (Callable): A callable used to make an API request. This
|
| 226 |
+
should generally be
|
| 227 |
+
:meth:`google.cloud._http.Connection.api_request`.
|
| 228 |
+
operation_name (str): The name of the operation.
|
| 229 |
+
"""
|
| 230 |
+
path = "operations/{}:cancel".format(operation_name)
|
| 231 |
+
api_request(method="POST", path=path)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def from_http_json(operation, api_request, result_type, **kwargs):
|
| 235 |
+
"""Create an operation future using a HTTP/JSON client.
|
| 236 |
+
|
| 237 |
+
This interacts with the long-running operations `service`_ (specific
|
| 238 |
+
to a given API) via `HTTP/JSON`_.
|
| 239 |
+
|
| 240 |
+
.. _HTTP/JSON: https://cloud.google.com/speech/reference/rest/\
|
| 241 |
+
v1beta1/operations#Operation
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
operation (dict): Operation as a dictionary.
|
| 245 |
+
api_request (Callable): A callable used to make an API request. This
|
| 246 |
+
should generally be
|
| 247 |
+
:meth:`google.cloud._http.Connection.api_request`.
|
| 248 |
+
result_type (:func:`type`): The protobuf result type.
|
| 249 |
+
kwargs: Keyword args passed into the :class:`Operation` constructor.
|
| 250 |
+
|
| 251 |
+
Returns:
|
| 252 |
+
~.api_core.operation.Operation: The operation future to track the given
|
| 253 |
+
operation.
|
| 254 |
+
"""
|
| 255 |
+
operation_proto = json_format.ParseDict(operation, operations_pb2.Operation())
|
| 256 |
+
refresh = functools.partial(_refresh_http, api_request, operation_proto.name)
|
| 257 |
+
cancel = functools.partial(_cancel_http, api_request, operation_proto.name)
|
| 258 |
+
return Operation(operation_proto, refresh, cancel, result_type, **kwargs)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _refresh_grpc(operations_stub, operation_name, retry=None):
|
| 262 |
+
"""Refresh an operation using a gRPC client.
|
| 263 |
+
|
| 264 |
+
Args:
|
| 265 |
+
operations_stub (google.longrunning.operations_pb2.OperationsStub):
|
| 266 |
+
The gRPC operations stub.
|
| 267 |
+
operation_name (str): The name of the operation.
|
| 268 |
+
retry (google.api_core.retry.Retry): (Optional) retry policy
|
| 269 |
+
|
| 270 |
+
Returns:
|
| 271 |
+
google.longrunning.operations_pb2.Operation: The operation.
|
| 272 |
+
"""
|
| 273 |
+
request_pb = operations_pb2.GetOperationRequest(name=operation_name)
|
| 274 |
+
|
| 275 |
+
rpc = operations_stub.GetOperation
|
| 276 |
+
if retry is not None:
|
| 277 |
+
rpc = retry(rpc)
|
| 278 |
+
|
| 279 |
+
return rpc(request_pb)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _cancel_grpc(operations_stub, operation_name):
|
| 283 |
+
"""Cancel an operation using a gRPC client.
|
| 284 |
+
|
| 285 |
+
Args:
|
| 286 |
+
operations_stub (google.longrunning.operations_pb2.OperationsStub):
|
| 287 |
+
The gRPC operations stub.
|
| 288 |
+
operation_name (str): The name of the operation.
|
| 289 |
+
"""
|
| 290 |
+
request_pb = operations_pb2.CancelOperationRequest(name=operation_name)
|
| 291 |
+
operations_stub.CancelOperation(request_pb)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def from_grpc(operation, operations_stub, result_type, grpc_metadata=None, **kwargs):
|
| 295 |
+
"""Create an operation future using a gRPC client.
|
| 296 |
+
|
| 297 |
+
This interacts with the long-running operations `service`_ (specific
|
| 298 |
+
to a given API) via gRPC.
|
| 299 |
+
|
| 300 |
+
.. _service: https://github.com/googleapis/googleapis/blob/\
|
| 301 |
+
050400df0fdb16f63b63e9dee53819044bffc857/\
|
| 302 |
+
google/longrunning/operations.proto#L38
|
| 303 |
+
|
| 304 |
+
Args:
|
| 305 |
+
operation (google.longrunning.operations_pb2.Operation): The operation.
|
| 306 |
+
operations_stub (google.longrunning.operations_pb2.OperationsStub):
|
| 307 |
+
The operations stub.
|
| 308 |
+
result_type (:func:`type`): The protobuf result type.
|
| 309 |
+
grpc_metadata (Optional[List[Tuple[str, str]]]): Additional metadata to pass
|
| 310 |
+
to the rpc.
|
| 311 |
+
kwargs: Keyword args passed into the :class:`Operation` constructor.
|
| 312 |
+
|
| 313 |
+
Returns:
|
| 314 |
+
~.api_core.operation.Operation: The operation future to track the given
|
| 315 |
+
operation.
|
| 316 |
+
"""
|
| 317 |
+
refresh = functools.partial(
|
| 318 |
+
_refresh_grpc,
|
| 319 |
+
operations_stub,
|
| 320 |
+
operation.name,
|
| 321 |
+
metadata=grpc_metadata,
|
| 322 |
+
)
|
| 323 |
+
cancel = functools.partial(
|
| 324 |
+
_cancel_grpc,
|
| 325 |
+
operations_stub,
|
| 326 |
+
operation.name,
|
| 327 |
+
metadata=grpc_metadata,
|
| 328 |
+
)
|
| 329 |
+
return Operation(operation, refresh, cancel, result_type, **kwargs)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def from_gapic(operation, operations_client, result_type, grpc_metadata=None, **kwargs):
|
| 333 |
+
"""Create an operation future from a gapic client.
|
| 334 |
+
|
| 335 |
+
This interacts with the long-running operations `service`_ (specific
|
| 336 |
+
to a given API) via a gapic client.
|
| 337 |
+
|
| 338 |
+
.. _service: https://github.com/googleapis/googleapis/blob/\
|
| 339 |
+
050400df0fdb16f63b63e9dee53819044bffc857/\
|
| 340 |
+
google/longrunning/operations.proto#L38
|
| 341 |
+
|
| 342 |
+
Args:
|
| 343 |
+
operation (google.longrunning.operations_pb2.Operation): The operation.
|
| 344 |
+
operations_client (google.api_core.operations_v1.OperationsClient):
|
| 345 |
+
The operations client.
|
| 346 |
+
result_type (:func:`type`): The protobuf result type.
|
| 347 |
+
grpc_metadata (Optional[List[Tuple[str, str]]]): Additional metadata to pass
|
| 348 |
+
to the rpc.
|
| 349 |
+
kwargs: Keyword args passed into the :class:`Operation` constructor.
|
| 350 |
+
|
| 351 |
+
Returns:
|
| 352 |
+
~.api_core.operation.Operation: The operation future to track the given
|
| 353 |
+
operation.
|
| 354 |
+
"""
|
| 355 |
+
refresh = functools.partial(
|
| 356 |
+
operations_client.get_operation,
|
| 357 |
+
operation.name,
|
| 358 |
+
metadata=grpc_metadata,
|
| 359 |
+
)
|
| 360 |
+
cancel = functools.partial(
|
| 361 |
+
operations_client.cancel_operation,
|
| 362 |
+
operation.name,
|
| 363 |
+
metadata=grpc_metadata,
|
| 364 |
+
)
|
| 365 |
+
return Operation(operation, refresh, cancel, result_type, **kwargs)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/operation_async.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""AsyncIO futures for long-running operations returned from Google Cloud APIs.
|
| 16 |
+
|
| 17 |
+
These futures can be used to await for the result of a long-running operation
|
| 18 |
+
using :meth:`AsyncOperation.result`:
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
.. code-block:: python
|
| 22 |
+
|
| 23 |
+
operation = my_api_client.long_running_method()
|
| 24 |
+
result = await operation.result()
|
| 25 |
+
|
| 26 |
+
Or asynchronously using callbacks and :meth:`Operation.add_done_callback`:
|
| 27 |
+
|
| 28 |
+
.. code-block:: python
|
| 29 |
+
|
| 30 |
+
operation = my_api_client.long_running_method()
|
| 31 |
+
|
| 32 |
+
def my_callback(future):
|
| 33 |
+
result = await future.result()
|
| 34 |
+
|
| 35 |
+
operation.add_done_callback(my_callback)
|
| 36 |
+
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
import functools
|
| 40 |
+
import threading
|
| 41 |
+
|
| 42 |
+
from google.api_core import exceptions
|
| 43 |
+
from google.api_core import protobuf_helpers
|
| 44 |
+
from google.api_core.future import async_future
|
| 45 |
+
from google.longrunning import operations_pb2
|
| 46 |
+
from google.rpc import code_pb2
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class AsyncOperation(async_future.AsyncFuture):
|
| 50 |
+
"""A Future for interacting with a Google API Long-Running Operation.
|
| 51 |
+
|
| 52 |
+
Args:
|
| 53 |
+
operation (google.longrunning.operations_pb2.Operation): The
|
| 54 |
+
initial operation.
|
| 55 |
+
refresh (Callable[[], ~.api_core.operation.Operation]): A callable that
|
| 56 |
+
returns the latest state of the operation.
|
| 57 |
+
cancel (Callable[[], None]): A callable that tries to cancel
|
| 58 |
+
the operation.
|
| 59 |
+
result_type (func:`type`): The protobuf type for the operation's
|
| 60 |
+
result.
|
| 61 |
+
metadata_type (func:`type`): The protobuf type for the operation's
|
| 62 |
+
metadata.
|
| 63 |
+
retry (google.api_core.retry.Retry): The retry configuration used
|
| 64 |
+
when polling. This can be used to control how often :meth:`done`
|
| 65 |
+
is polled. Regardless of the retry's ``deadline``, it will be
|
| 66 |
+
overridden by the ``timeout`` argument to :meth:`result`.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
def __init__(
|
| 70 |
+
self,
|
| 71 |
+
operation,
|
| 72 |
+
refresh,
|
| 73 |
+
cancel,
|
| 74 |
+
result_type,
|
| 75 |
+
metadata_type=None,
|
| 76 |
+
retry=async_future.DEFAULT_RETRY,
|
| 77 |
+
):
|
| 78 |
+
super().__init__(retry=retry)
|
| 79 |
+
self._operation = operation
|
| 80 |
+
self._refresh = refresh
|
| 81 |
+
self._cancel = cancel
|
| 82 |
+
self._result_type = result_type
|
| 83 |
+
self._metadata_type = metadata_type
|
| 84 |
+
self._completion_lock = threading.Lock()
|
| 85 |
+
# Invoke this in case the operation came back already complete.
|
| 86 |
+
self._set_result_from_operation()
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def operation(self):
|
| 90 |
+
"""google.longrunning.Operation: The current long-running operation."""
|
| 91 |
+
return self._operation
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def metadata(self):
|
| 95 |
+
"""google.protobuf.Message: the current operation metadata."""
|
| 96 |
+
if not self._operation.HasField("metadata"):
|
| 97 |
+
return None
|
| 98 |
+
|
| 99 |
+
return protobuf_helpers.from_any_pb(
|
| 100 |
+
self._metadata_type, self._operation.metadata
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
@classmethod
|
| 104 |
+
def deserialize(cls, payload):
|
| 105 |
+
"""Deserialize a ``google.longrunning.Operation`` protocol buffer.
|
| 106 |
+
|
| 107 |
+
Args:
|
| 108 |
+
payload (bytes): A serialized operation protocol buffer.
|
| 109 |
+
|
| 110 |
+
Returns:
|
| 111 |
+
~.operations_pb2.Operation: An Operation protobuf object.
|
| 112 |
+
"""
|
| 113 |
+
return operations_pb2.Operation.FromString(payload)
|
| 114 |
+
|
| 115 |
+
def _set_result_from_operation(self):
|
| 116 |
+
"""Set the result or exception from the operation if it is complete."""
|
| 117 |
+
# This must be done in a lock to prevent the async_future thread
|
| 118 |
+
# and main thread from both executing the completion logic
|
| 119 |
+
# at the same time.
|
| 120 |
+
with self._completion_lock:
|
| 121 |
+
# If the operation isn't complete or if the result has already been
|
| 122 |
+
# set, do not call set_result/set_exception again.
|
| 123 |
+
if not self._operation.done or self._future.done():
|
| 124 |
+
return
|
| 125 |
+
|
| 126 |
+
if self._operation.HasField("response"):
|
| 127 |
+
response = protobuf_helpers.from_any_pb(
|
| 128 |
+
self._result_type, self._operation.response
|
| 129 |
+
)
|
| 130 |
+
self.set_result(response)
|
| 131 |
+
elif self._operation.HasField("error"):
|
| 132 |
+
exception = exceptions.GoogleAPICallError(
|
| 133 |
+
self._operation.error.message,
|
| 134 |
+
errors=(self._operation.error,),
|
| 135 |
+
response=self._operation,
|
| 136 |
+
)
|
| 137 |
+
self.set_exception(exception)
|
| 138 |
+
else:
|
| 139 |
+
exception = exceptions.GoogleAPICallError(
|
| 140 |
+
"Unexpected state: Long-running operation had neither "
|
| 141 |
+
"response nor error set."
|
| 142 |
+
)
|
| 143 |
+
self.set_exception(exception)
|
| 144 |
+
|
| 145 |
+
async def _refresh_and_update(self, retry=async_future.DEFAULT_RETRY):
|
| 146 |
+
"""Refresh the operation and update the result if needed.
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
retry (google.api_core.retry.Retry): (Optional) How to retry the RPC.
|
| 150 |
+
"""
|
| 151 |
+
# If the currently cached operation is done, no need to make another
|
| 152 |
+
# RPC as it will not change once done.
|
| 153 |
+
if not self._operation.done:
|
| 154 |
+
self._operation = await self._refresh(retry=retry)
|
| 155 |
+
self._set_result_from_operation()
|
| 156 |
+
|
| 157 |
+
async def done(self, retry=async_future.DEFAULT_RETRY):
|
| 158 |
+
"""Checks to see if the operation is complete.
|
| 159 |
+
|
| 160 |
+
Args:
|
| 161 |
+
retry (google.api_core.retry.Retry): (Optional) How to retry the RPC.
|
| 162 |
+
|
| 163 |
+
Returns:
|
| 164 |
+
bool: True if the operation is complete, False otherwise.
|
| 165 |
+
"""
|
| 166 |
+
await self._refresh_and_update(retry)
|
| 167 |
+
return self._operation.done
|
| 168 |
+
|
| 169 |
+
async def cancel(self):
|
| 170 |
+
"""Attempt to cancel the operation.
|
| 171 |
+
|
| 172 |
+
Returns:
|
| 173 |
+
bool: True if the cancel RPC was made, False if the operation is
|
| 174 |
+
already complete.
|
| 175 |
+
"""
|
| 176 |
+
result = await self.done()
|
| 177 |
+
if result:
|
| 178 |
+
return False
|
| 179 |
+
else:
|
| 180 |
+
await self._cancel()
|
| 181 |
+
return True
|
| 182 |
+
|
| 183 |
+
async def cancelled(self):
|
| 184 |
+
"""True if the operation was cancelled."""
|
| 185 |
+
await self._refresh_and_update()
|
| 186 |
+
return (
|
| 187 |
+
self._operation.HasField("error")
|
| 188 |
+
and self._operation.error.code == code_pb2.CANCELLED
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def from_gapic(operation, operations_client, result_type, grpc_metadata=None, **kwargs):
|
| 193 |
+
"""Create an operation future from a gapic client.
|
| 194 |
+
|
| 195 |
+
This interacts with the long-running operations `service`_ (specific
|
| 196 |
+
to a given API) via a gapic client.
|
| 197 |
+
|
| 198 |
+
.. _service: https://github.com/googleapis/googleapis/blob/\
|
| 199 |
+
050400df0fdb16f63b63e9dee53819044bffc857/\
|
| 200 |
+
google/longrunning/operations.proto#L38
|
| 201 |
+
|
| 202 |
+
Args:
|
| 203 |
+
operation (google.longrunning.operations_pb2.Operation): The operation.
|
| 204 |
+
operations_client (google.api_core.operations_v1.OperationsClient):
|
| 205 |
+
The operations client.
|
| 206 |
+
result_type (:func:`type`): The protobuf result type.
|
| 207 |
+
grpc_metadata (Optional[List[Tuple[str, str]]]): Additional metadata to pass
|
| 208 |
+
to the rpc.
|
| 209 |
+
kwargs: Keyword args passed into the :class:`Operation` constructor.
|
| 210 |
+
|
| 211 |
+
Returns:
|
| 212 |
+
~.api_core.operation.Operation: The operation future to track the given
|
| 213 |
+
operation.
|
| 214 |
+
"""
|
| 215 |
+
refresh = functools.partial(
|
| 216 |
+
operations_client.get_operation,
|
| 217 |
+
operation.name,
|
| 218 |
+
metadata=grpc_metadata,
|
| 219 |
+
)
|
| 220 |
+
cancel = functools.partial(
|
| 221 |
+
operations_client.cancel_operation,
|
| 222 |
+
operation.name,
|
| 223 |
+
metadata=grpc_metadata,
|
| 224 |
+
)
|
| 225 |
+
return AsyncOperation(operation, refresh, cancel, result_type, **kwargs)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/page_iterator.py
ADDED
|
@@ -0,0 +1,571 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Iterators for paging through paged API methods.
|
| 16 |
+
|
| 17 |
+
These iterators simplify the process of paging through API responses
|
| 18 |
+
where the request takes a page token and the response is a list of results with
|
| 19 |
+
a token for the next page. See `list pagination`_ in the Google API Style Guide
|
| 20 |
+
for more details.
|
| 21 |
+
|
| 22 |
+
.. _list pagination:
|
| 23 |
+
https://cloud.google.com/apis/design/design_patterns#list_pagination
|
| 24 |
+
|
| 25 |
+
API clients that have methods that follow the list pagination pattern can
|
| 26 |
+
return an :class:`.Iterator`. You can use this iterator to get **all** of
|
| 27 |
+
the results across all pages::
|
| 28 |
+
|
| 29 |
+
>>> results_iterator = client.list_resources()
|
| 30 |
+
>>> list(results_iterator) # Convert to a list (consumes all values).
|
| 31 |
+
|
| 32 |
+
Or you can walk your way through items and call off the search early if
|
| 33 |
+
you find what you're looking for (resulting in possibly fewer requests)::
|
| 34 |
+
|
| 35 |
+
>>> for resource in results_iterator:
|
| 36 |
+
... print(resource.name)
|
| 37 |
+
... if not resource.is_valid:
|
| 38 |
+
... break
|
| 39 |
+
|
| 40 |
+
At any point, you may check the number of items consumed by referencing the
|
| 41 |
+
``num_results`` property of the iterator::
|
| 42 |
+
|
| 43 |
+
>>> for my_item in results_iterator:
|
| 44 |
+
... if results_iterator.num_results >= 10:
|
| 45 |
+
... break
|
| 46 |
+
|
| 47 |
+
When iterating, not every new item will send a request to the server.
|
| 48 |
+
To iterate based on each page of items (where a page corresponds to
|
| 49 |
+
a request)::
|
| 50 |
+
|
| 51 |
+
>>> for page in results_iterator.pages:
|
| 52 |
+
... print('=' * 20)
|
| 53 |
+
... print(' Page number: {:d}'.format(iterator.page_number))
|
| 54 |
+
... print(' Items in page: {:d}'.format(page.num_items))
|
| 55 |
+
... print(' First item: {!r}'.format(next(page)))
|
| 56 |
+
... print('Items remaining: {:d}'.format(page.remaining))
|
| 57 |
+
... print('Next page token: {}'.format(iterator.next_page_token))
|
| 58 |
+
====================
|
| 59 |
+
Page number: 1
|
| 60 |
+
Items in page: 1
|
| 61 |
+
First item: <MyItemClass at 0x7f1d3cccf690>
|
| 62 |
+
Items remaining: 0
|
| 63 |
+
Next page token: eav1OzQB0OM8rLdGXOEsyQWSG
|
| 64 |
+
====================
|
| 65 |
+
Page number: 2
|
| 66 |
+
Items in page: 19
|
| 67 |
+
First item: <MyItemClass at 0x7f1d3cccffd0>
|
| 68 |
+
Items remaining: 18
|
| 69 |
+
Next page token: None
|
| 70 |
+
|
| 71 |
+
Then, for each page you can get all the resources on that page by iterating
|
| 72 |
+
through it or using :func:`list`::
|
| 73 |
+
|
| 74 |
+
>>> list(page)
|
| 75 |
+
[
|
| 76 |
+
<MyItemClass at 0x7fd64a098ad0>,
|
| 77 |
+
<MyItemClass at 0x7fd64a098ed0>,
|
| 78 |
+
<MyItemClass at 0x7fd64a098e90>,
|
| 79 |
+
]
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
import abc
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class Page(object):
|
| 86 |
+
"""Single page of results in an iterator.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
parent (google.api_core.page_iterator.Iterator): The iterator that owns
|
| 90 |
+
the current page.
|
| 91 |
+
items (Sequence[Any]): An iterable (that also defines __len__) of items
|
| 92 |
+
from a raw API response.
|
| 93 |
+
item_to_value (Callable[google.api_core.page_iterator.Iterator, Any]):
|
| 94 |
+
Callable to convert an item from the type in the raw API response
|
| 95 |
+
into the native object. Will be called with the iterator and a
|
| 96 |
+
single item.
|
| 97 |
+
raw_page Optional[google.protobuf.message.Message]:
|
| 98 |
+
The raw page response.
|
| 99 |
+
"""
|
| 100 |
+
|
| 101 |
+
def __init__(self, parent, items, item_to_value, raw_page=None):
|
| 102 |
+
self._parent = parent
|
| 103 |
+
self._num_items = len(items)
|
| 104 |
+
self._remaining = self._num_items
|
| 105 |
+
self._item_iter = iter(items)
|
| 106 |
+
self._item_to_value = item_to_value
|
| 107 |
+
self._raw_page = raw_page
|
| 108 |
+
|
| 109 |
+
@property
|
| 110 |
+
def raw_page(self):
|
| 111 |
+
"""google.protobuf.message.Message"""
|
| 112 |
+
return self._raw_page
|
| 113 |
+
|
| 114 |
+
@property
|
| 115 |
+
def num_items(self):
|
| 116 |
+
"""int: Total items in the page."""
|
| 117 |
+
return self._num_items
|
| 118 |
+
|
| 119 |
+
@property
|
| 120 |
+
def remaining(self):
|
| 121 |
+
"""int: Remaining items in the page."""
|
| 122 |
+
return self._remaining
|
| 123 |
+
|
| 124 |
+
def __iter__(self):
|
| 125 |
+
"""The :class:`Page` is an iterator of items."""
|
| 126 |
+
return self
|
| 127 |
+
|
| 128 |
+
def __next__(self):
|
| 129 |
+
"""Get the next value in the page."""
|
| 130 |
+
item = next(self._item_iter)
|
| 131 |
+
result = self._item_to_value(self._parent, item)
|
| 132 |
+
# Since we've successfully got the next value from the
|
| 133 |
+
# iterator, we update the number of remaining.
|
| 134 |
+
self._remaining -= 1
|
| 135 |
+
return result
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _item_to_value_identity(iterator, item):
|
| 139 |
+
"""An item to value transformer that returns the item un-changed."""
|
| 140 |
+
# pylint: disable=unused-argument
|
| 141 |
+
# We are conforming to the interface defined by Iterator.
|
| 142 |
+
return item
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class Iterator(object, metaclass=abc.ABCMeta):
|
| 146 |
+
"""A generic class for iterating through API list responses.
|
| 147 |
+
|
| 148 |
+
Args:
|
| 149 |
+
client(google.cloud.client.Client): The API client.
|
| 150 |
+
item_to_value (Callable[google.api_core.page_iterator.Iterator, Any]):
|
| 151 |
+
Callable to convert an item from the type in the raw API response
|
| 152 |
+
into the native object. Will be called with the iterator and a
|
| 153 |
+
single item.
|
| 154 |
+
page_token (str): A token identifying a page in a result set to start
|
| 155 |
+
fetching results from.
|
| 156 |
+
max_results (int): The maximum number of results to fetch.
|
| 157 |
+
"""
|
| 158 |
+
|
| 159 |
+
def __init__(
|
| 160 |
+
self,
|
| 161 |
+
client,
|
| 162 |
+
item_to_value=_item_to_value_identity,
|
| 163 |
+
page_token=None,
|
| 164 |
+
max_results=None,
|
| 165 |
+
):
|
| 166 |
+
self._started = False
|
| 167 |
+
self.__active_iterator = None
|
| 168 |
+
|
| 169 |
+
self.client = client
|
| 170 |
+
"""Optional[Any]: The client that created this iterator."""
|
| 171 |
+
self.item_to_value = item_to_value
|
| 172 |
+
"""Callable[Iterator, Any]: Callable to convert an item from the type
|
| 173 |
+
in the raw API response into the native object. Will be called with
|
| 174 |
+
the iterator and a
|
| 175 |
+
single item.
|
| 176 |
+
"""
|
| 177 |
+
self.max_results = max_results
|
| 178 |
+
"""int: The maximum number of results to fetch"""
|
| 179 |
+
|
| 180 |
+
# The attributes below will change over the life of the iterator.
|
| 181 |
+
self.page_number = 0
|
| 182 |
+
"""int: The current page of results."""
|
| 183 |
+
self.next_page_token = page_token
|
| 184 |
+
"""str: The token for the next page of results. If this is set before
|
| 185 |
+
the iterator starts, it effectively offsets the iterator to a
|
| 186 |
+
specific starting point."""
|
| 187 |
+
self.num_results = 0
|
| 188 |
+
"""int: The total number of results fetched so far."""
|
| 189 |
+
|
| 190 |
+
@property
|
| 191 |
+
def pages(self):
|
| 192 |
+
"""Iterator of pages in the response.
|
| 193 |
+
|
| 194 |
+
returns:
|
| 195 |
+
types.GeneratorType[google.api_core.page_iterator.Page]: A
|
| 196 |
+
generator of page instances.
|
| 197 |
+
|
| 198 |
+
raises:
|
| 199 |
+
ValueError: If the iterator has already been started.
|
| 200 |
+
"""
|
| 201 |
+
if self._started:
|
| 202 |
+
raise ValueError("Iterator has already started", self)
|
| 203 |
+
self._started = True
|
| 204 |
+
return self._page_iter(increment=True)
|
| 205 |
+
|
| 206 |
+
def _items_iter(self):
|
| 207 |
+
"""Iterator for each item returned."""
|
| 208 |
+
for page in self._page_iter(increment=False):
|
| 209 |
+
for item in page:
|
| 210 |
+
self.num_results += 1
|
| 211 |
+
yield item
|
| 212 |
+
|
| 213 |
+
def __iter__(self):
|
| 214 |
+
"""Iterator for each item returned.
|
| 215 |
+
|
| 216 |
+
Returns:
|
| 217 |
+
types.GeneratorType[Any]: A generator of items from the API.
|
| 218 |
+
|
| 219 |
+
Raises:
|
| 220 |
+
ValueError: If the iterator has already been started.
|
| 221 |
+
"""
|
| 222 |
+
if self._started:
|
| 223 |
+
raise ValueError("Iterator has already started", self)
|
| 224 |
+
self._started = True
|
| 225 |
+
return self._items_iter()
|
| 226 |
+
|
| 227 |
+
def __next__(self):
|
| 228 |
+
if self.__active_iterator is None:
|
| 229 |
+
self.__active_iterator = iter(self)
|
| 230 |
+
return next(self.__active_iterator)
|
| 231 |
+
|
| 232 |
+
def _page_iter(self, increment):
|
| 233 |
+
"""Generator of pages of API responses.
|
| 234 |
+
|
| 235 |
+
Args:
|
| 236 |
+
increment (bool): Flag indicating if the total number of results
|
| 237 |
+
should be incremented on each page. This is useful since a page
|
| 238 |
+
iterator will want to increment by results per page while an
|
| 239 |
+
items iterator will want to increment per item.
|
| 240 |
+
|
| 241 |
+
Yields:
|
| 242 |
+
Page: each page of items from the API.
|
| 243 |
+
"""
|
| 244 |
+
page = self._next_page()
|
| 245 |
+
while page is not None:
|
| 246 |
+
self.page_number += 1
|
| 247 |
+
if increment:
|
| 248 |
+
self.num_results += page.num_items
|
| 249 |
+
yield page
|
| 250 |
+
page = self._next_page()
|
| 251 |
+
|
| 252 |
+
@abc.abstractmethod
|
| 253 |
+
def _next_page(self):
|
| 254 |
+
"""Get the next page in the iterator.
|
| 255 |
+
|
| 256 |
+
This does nothing and is intended to be over-ridden by subclasses
|
| 257 |
+
to return the next :class:`Page`.
|
| 258 |
+
|
| 259 |
+
Raises:
|
| 260 |
+
NotImplementedError: Always, this method is abstract.
|
| 261 |
+
"""
|
| 262 |
+
raise NotImplementedError
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def _do_nothing_page_start(iterator, page, response):
|
| 266 |
+
"""Helper to provide custom behavior after a :class:`Page` is started.
|
| 267 |
+
|
| 268 |
+
This is a do-nothing stand-in as the default value.
|
| 269 |
+
|
| 270 |
+
Args:
|
| 271 |
+
iterator (Iterator): An iterator that holds some request info.
|
| 272 |
+
page (Page): The page that was just created.
|
| 273 |
+
response (Any): The API response for a page.
|
| 274 |
+
"""
|
| 275 |
+
# pylint: disable=unused-argument
|
| 276 |
+
pass
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class HTTPIterator(Iterator):
|
| 280 |
+
"""A generic class for iterating through HTTP/JSON API list responses.
|
| 281 |
+
|
| 282 |
+
To make an iterator work, you'll need to provide a way to convert a JSON
|
| 283 |
+
item returned from the API into the object of your choice (via
|
| 284 |
+
``item_to_value``). You also may need to specify a custom ``items_key`` so
|
| 285 |
+
that a given response (containing a page of results) can be parsed into an
|
| 286 |
+
iterable page of the actual objects you want.
|
| 287 |
+
|
| 288 |
+
Args:
|
| 289 |
+
client (google.cloud.client.Client): The API client.
|
| 290 |
+
api_request (Callable): The function to use to make API requests.
|
| 291 |
+
Generally, this will be
|
| 292 |
+
:meth:`google.cloud._http.JSONConnection.api_request`.
|
| 293 |
+
path (str): The method path to query for the list of items.
|
| 294 |
+
item_to_value (Callable[google.api_core.page_iterator.Iterator, Any]):
|
| 295 |
+
Callable to convert an item from the type in the JSON response into
|
| 296 |
+
a native object. Will be called with the iterator and a single
|
| 297 |
+
item.
|
| 298 |
+
items_key (str): The key in the API response where the list of items
|
| 299 |
+
can be found.
|
| 300 |
+
page_token (str): A token identifying a page in a result set to start
|
| 301 |
+
fetching results from.
|
| 302 |
+
page_size (int): The maximum number of results to fetch per page
|
| 303 |
+
max_results (int): The maximum number of results to fetch
|
| 304 |
+
extra_params (dict): Extra query string parameters for the
|
| 305 |
+
API call.
|
| 306 |
+
page_start (Callable[
|
| 307 |
+
google.api_core.page_iterator.Iterator,
|
| 308 |
+
google.api_core.page_iterator.Page, dict]): Callable to provide
|
| 309 |
+
any special behavior after a new page has been created. Assumed
|
| 310 |
+
signature takes the :class:`.Iterator` that started the page,
|
| 311 |
+
the :class:`.Page` that was started and the dictionary containing
|
| 312 |
+
the page response.
|
| 313 |
+
next_token (str): The name of the field used in the response for page
|
| 314 |
+
tokens.
|
| 315 |
+
|
| 316 |
+
.. autoattribute:: pages
|
| 317 |
+
"""
|
| 318 |
+
|
| 319 |
+
_DEFAULT_ITEMS_KEY = "items"
|
| 320 |
+
_PAGE_TOKEN = "pageToken"
|
| 321 |
+
_MAX_RESULTS = "maxResults"
|
| 322 |
+
_NEXT_TOKEN = "nextPageToken"
|
| 323 |
+
_RESERVED_PARAMS = frozenset([_PAGE_TOKEN])
|
| 324 |
+
_HTTP_METHOD = "GET"
|
| 325 |
+
|
| 326 |
+
def __init__(
|
| 327 |
+
self,
|
| 328 |
+
client,
|
| 329 |
+
api_request,
|
| 330 |
+
path,
|
| 331 |
+
item_to_value,
|
| 332 |
+
items_key=_DEFAULT_ITEMS_KEY,
|
| 333 |
+
page_token=None,
|
| 334 |
+
page_size=None,
|
| 335 |
+
max_results=None,
|
| 336 |
+
extra_params=None,
|
| 337 |
+
page_start=_do_nothing_page_start,
|
| 338 |
+
next_token=_NEXT_TOKEN,
|
| 339 |
+
):
|
| 340 |
+
super(HTTPIterator, self).__init__(
|
| 341 |
+
client, item_to_value, page_token=page_token, max_results=max_results
|
| 342 |
+
)
|
| 343 |
+
self.api_request = api_request
|
| 344 |
+
self.path = path
|
| 345 |
+
self._items_key = items_key
|
| 346 |
+
self.extra_params = extra_params
|
| 347 |
+
self._page_size = page_size
|
| 348 |
+
self._page_start = page_start
|
| 349 |
+
self._next_token = next_token
|
| 350 |
+
# Verify inputs / provide defaults.
|
| 351 |
+
if self.extra_params is None:
|
| 352 |
+
self.extra_params = {}
|
| 353 |
+
self._verify_params()
|
| 354 |
+
|
| 355 |
+
def _verify_params(self):
|
| 356 |
+
"""Verifies the parameters don't use any reserved parameter.
|
| 357 |
+
|
| 358 |
+
Raises:
|
| 359 |
+
ValueError: If a reserved parameter is used.
|
| 360 |
+
"""
|
| 361 |
+
reserved_in_use = self._RESERVED_PARAMS.intersection(self.extra_params)
|
| 362 |
+
if reserved_in_use:
|
| 363 |
+
raise ValueError("Using a reserved parameter", reserved_in_use)
|
| 364 |
+
|
| 365 |
+
def _next_page(self):
|
| 366 |
+
"""Get the next page in the iterator.
|
| 367 |
+
|
| 368 |
+
Returns:
|
| 369 |
+
Optional[Page]: The next page in the iterator or :data:`None` if
|
| 370 |
+
there are no pages left.
|
| 371 |
+
"""
|
| 372 |
+
if self._has_next_page():
|
| 373 |
+
response = self._get_next_page_response()
|
| 374 |
+
items = response.get(self._items_key, ())
|
| 375 |
+
page = Page(self, items, self.item_to_value, raw_page=response)
|
| 376 |
+
self._page_start(self, page, response)
|
| 377 |
+
self.next_page_token = response.get(self._next_token)
|
| 378 |
+
return page
|
| 379 |
+
else:
|
| 380 |
+
return None
|
| 381 |
+
|
| 382 |
+
def _has_next_page(self):
|
| 383 |
+
"""Determines whether or not there are more pages with results.
|
| 384 |
+
|
| 385 |
+
Returns:
|
| 386 |
+
bool: Whether the iterator has more pages.
|
| 387 |
+
"""
|
| 388 |
+
if self.page_number == 0:
|
| 389 |
+
return True
|
| 390 |
+
|
| 391 |
+
if self.max_results is not None:
|
| 392 |
+
if self.num_results >= self.max_results:
|
| 393 |
+
return False
|
| 394 |
+
|
| 395 |
+
return self.next_page_token is not None
|
| 396 |
+
|
| 397 |
+
def _get_query_params(self):
|
| 398 |
+
"""Getter for query parameters for the next request.
|
| 399 |
+
|
| 400 |
+
Returns:
|
| 401 |
+
dict: A dictionary of query parameters.
|
| 402 |
+
"""
|
| 403 |
+
result = {}
|
| 404 |
+
if self.next_page_token is not None:
|
| 405 |
+
result[self._PAGE_TOKEN] = self.next_page_token
|
| 406 |
+
|
| 407 |
+
page_size = None
|
| 408 |
+
if self.max_results is not None:
|
| 409 |
+
page_size = self.max_results - self.num_results
|
| 410 |
+
if self._page_size is not None:
|
| 411 |
+
page_size = min(page_size, self._page_size)
|
| 412 |
+
elif self._page_size is not None:
|
| 413 |
+
page_size = self._page_size
|
| 414 |
+
|
| 415 |
+
if page_size is not None:
|
| 416 |
+
result[self._MAX_RESULTS] = page_size
|
| 417 |
+
|
| 418 |
+
result.update(self.extra_params)
|
| 419 |
+
return result
|
| 420 |
+
|
| 421 |
+
def _get_next_page_response(self):
|
| 422 |
+
"""Requests the next page from the path provided.
|
| 423 |
+
|
| 424 |
+
Returns:
|
| 425 |
+
dict: The parsed JSON response of the next page's contents.
|
| 426 |
+
|
| 427 |
+
Raises:
|
| 428 |
+
ValueError: If the HTTP method is not ``GET`` or ``POST``.
|
| 429 |
+
"""
|
| 430 |
+
params = self._get_query_params()
|
| 431 |
+
if self._HTTP_METHOD == "GET":
|
| 432 |
+
return self.api_request(
|
| 433 |
+
method=self._HTTP_METHOD, path=self.path, query_params=params
|
| 434 |
+
)
|
| 435 |
+
elif self._HTTP_METHOD == "POST":
|
| 436 |
+
return self.api_request(
|
| 437 |
+
method=self._HTTP_METHOD, path=self.path, data=params
|
| 438 |
+
)
|
| 439 |
+
else:
|
| 440 |
+
raise ValueError("Unexpected HTTP method", self._HTTP_METHOD)
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
class _GAXIterator(Iterator):
|
| 444 |
+
"""A generic class for iterating through Cloud gRPC APIs list responses.
|
| 445 |
+
|
| 446 |
+
Any:
|
| 447 |
+
client (google.cloud.client.Client): The API client.
|
| 448 |
+
page_iter (google.gax.PageIterator): A GAX page iterator to be wrapped
|
| 449 |
+
to conform to the :class:`Iterator` interface.
|
| 450 |
+
item_to_value (Callable[Iterator, Any]): Callable to convert an item
|
| 451 |
+
from the protobuf response into a native object. Will
|
| 452 |
+
be called with the iterator and a single item.
|
| 453 |
+
max_results (int): The maximum number of results to fetch.
|
| 454 |
+
|
| 455 |
+
.. autoattribute:: pages
|
| 456 |
+
"""
|
| 457 |
+
|
| 458 |
+
def __init__(self, client, page_iter, item_to_value, max_results=None):
|
| 459 |
+
super(_GAXIterator, self).__init__(
|
| 460 |
+
client,
|
| 461 |
+
item_to_value,
|
| 462 |
+
page_token=page_iter.page_token,
|
| 463 |
+
max_results=max_results,
|
| 464 |
+
)
|
| 465 |
+
self._gax_page_iter = page_iter
|
| 466 |
+
|
| 467 |
+
def _next_page(self):
|
| 468 |
+
"""Get the next page in the iterator.
|
| 469 |
+
|
| 470 |
+
Wraps the response from the :class:`~google.gax.PageIterator` in a
|
| 471 |
+
:class:`Page` instance and captures some state at each page.
|
| 472 |
+
|
| 473 |
+
Returns:
|
| 474 |
+
Optional[Page]: The next page in the iterator or :data:`None` if
|
| 475 |
+
there are no pages left.
|
| 476 |
+
"""
|
| 477 |
+
try:
|
| 478 |
+
items = next(self._gax_page_iter)
|
| 479 |
+
page = Page(self, items, self.item_to_value)
|
| 480 |
+
self.next_page_token = self._gax_page_iter.page_token or None
|
| 481 |
+
return page
|
| 482 |
+
except StopIteration:
|
| 483 |
+
return None
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
class GRPCIterator(Iterator):
|
| 487 |
+
"""A generic class for iterating through gRPC list responses.
|
| 488 |
+
|
| 489 |
+
.. note:: The class does not take a ``page_token`` argument because it can
|
| 490 |
+
just be specified in the ``request``.
|
| 491 |
+
|
| 492 |
+
Args:
|
| 493 |
+
client (google.cloud.client.Client): The API client. This unused by
|
| 494 |
+
this class, but kept to satisfy the :class:`Iterator` interface.
|
| 495 |
+
method (Callable[protobuf.Message]): A bound gRPC method that should
|
| 496 |
+
take a single message for the request.
|
| 497 |
+
request (protobuf.Message): The request message.
|
| 498 |
+
items_field (str): The field in the response message that has the
|
| 499 |
+
items for the page.
|
| 500 |
+
item_to_value (Callable[GRPCIterator, Any]): Callable to convert an
|
| 501 |
+
item from the type in the JSON response into a native object. Will
|
| 502 |
+
be called with the iterator and a single item.
|
| 503 |
+
request_token_field (str): The field in the request message used to
|
| 504 |
+
specify the page token.
|
| 505 |
+
response_token_field (str): The field in the response message that has
|
| 506 |
+
the token for the next page.
|
| 507 |
+
max_results (int): The maximum number of results to fetch.
|
| 508 |
+
|
| 509 |
+
.. autoattribute:: pages
|
| 510 |
+
"""
|
| 511 |
+
|
| 512 |
+
_DEFAULT_REQUEST_TOKEN_FIELD = "page_token"
|
| 513 |
+
_DEFAULT_RESPONSE_TOKEN_FIELD = "next_page_token"
|
| 514 |
+
|
| 515 |
+
def __init__(
|
| 516 |
+
self,
|
| 517 |
+
client,
|
| 518 |
+
method,
|
| 519 |
+
request,
|
| 520 |
+
items_field,
|
| 521 |
+
item_to_value=_item_to_value_identity,
|
| 522 |
+
request_token_field=_DEFAULT_REQUEST_TOKEN_FIELD,
|
| 523 |
+
response_token_field=_DEFAULT_RESPONSE_TOKEN_FIELD,
|
| 524 |
+
max_results=None,
|
| 525 |
+
):
|
| 526 |
+
super(GRPCIterator, self).__init__(
|
| 527 |
+
client, item_to_value, max_results=max_results
|
| 528 |
+
)
|
| 529 |
+
self._method = method
|
| 530 |
+
self._request = request
|
| 531 |
+
self._items_field = items_field
|
| 532 |
+
self._request_token_field = request_token_field
|
| 533 |
+
self._response_token_field = response_token_field
|
| 534 |
+
|
| 535 |
+
def _next_page(self):
|
| 536 |
+
"""Get the next page in the iterator.
|
| 537 |
+
|
| 538 |
+
Returns:
|
| 539 |
+
Page: The next page in the iterator or :data:`None` if
|
| 540 |
+
there are no pages left.
|
| 541 |
+
"""
|
| 542 |
+
if not self._has_next_page():
|
| 543 |
+
return None
|
| 544 |
+
|
| 545 |
+
if self.next_page_token is not None:
|
| 546 |
+
setattr(self._request, self._request_token_field, self.next_page_token)
|
| 547 |
+
|
| 548 |
+
response = self._method(self._request)
|
| 549 |
+
|
| 550 |
+
self.next_page_token = getattr(response, self._response_token_field)
|
| 551 |
+
items = getattr(response, self._items_field)
|
| 552 |
+
page = Page(self, items, self.item_to_value, raw_page=response)
|
| 553 |
+
|
| 554 |
+
return page
|
| 555 |
+
|
| 556 |
+
def _has_next_page(self):
|
| 557 |
+
"""Determines whether or not there are more pages with results.
|
| 558 |
+
|
| 559 |
+
Returns:
|
| 560 |
+
bool: Whether the iterator has more pages.
|
| 561 |
+
"""
|
| 562 |
+
if self.page_number == 0:
|
| 563 |
+
return True
|
| 564 |
+
|
| 565 |
+
if self.max_results is not None:
|
| 566 |
+
if self.num_results >= self.max_results:
|
| 567 |
+
return False
|
| 568 |
+
|
| 569 |
+
# Note: intentionally a falsy check instead of a None check. The RPC
|
| 570 |
+
# can return an empty string indicating no more pages.
|
| 571 |
+
return True if self.next_page_token else False
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/page_iterator_async.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""AsyncIO iterators for paging through paged API methods.
|
| 16 |
+
|
| 17 |
+
These iterators simplify the process of paging through API responses
|
| 18 |
+
where the request takes a page token and the response is a list of results with
|
| 19 |
+
a token for the next page. See `list pagination`_ in the Google API Style Guide
|
| 20 |
+
for more details.
|
| 21 |
+
|
| 22 |
+
.. _list pagination:
|
| 23 |
+
https://cloud.google.com/apis/design/design_patterns#list_pagination
|
| 24 |
+
|
| 25 |
+
API clients that have methods that follow the list pagination pattern can
|
| 26 |
+
return an :class:`.AsyncIterator`:
|
| 27 |
+
|
| 28 |
+
>>> results_iterator = await client.list_resources()
|
| 29 |
+
|
| 30 |
+
Or you can walk your way through items and call off the search early if
|
| 31 |
+
you find what you're looking for (resulting in possibly fewer requests)::
|
| 32 |
+
|
| 33 |
+
>>> async for resource in results_iterator:
|
| 34 |
+
... print(resource.name)
|
| 35 |
+
... if not resource.is_valid:
|
| 36 |
+
... break
|
| 37 |
+
|
| 38 |
+
At any point, you may check the number of items consumed by referencing the
|
| 39 |
+
``num_results`` property of the iterator::
|
| 40 |
+
|
| 41 |
+
>>> async for my_item in results_iterator:
|
| 42 |
+
... if results_iterator.num_results >= 10:
|
| 43 |
+
... break
|
| 44 |
+
|
| 45 |
+
When iterating, not every new item will send a request to the server.
|
| 46 |
+
To iterate based on each page of items (where a page corresponds to
|
| 47 |
+
a request)::
|
| 48 |
+
|
| 49 |
+
>>> async for page in results_iterator.pages:
|
| 50 |
+
... print('=' * 20)
|
| 51 |
+
... print(' Page number: {:d}'.format(iterator.page_number))
|
| 52 |
+
... print(' Items in page: {:d}'.format(page.num_items))
|
| 53 |
+
... print(' First item: {!r}'.format(next(page)))
|
| 54 |
+
... print('Items remaining: {:d}'.format(page.remaining))
|
| 55 |
+
... print('Next page token: {}'.format(iterator.next_page_token))
|
| 56 |
+
====================
|
| 57 |
+
Page number: 1
|
| 58 |
+
Items in page: 1
|
| 59 |
+
First item: <MyItemClass at 0x7f1d3cccf690>
|
| 60 |
+
Items remaining: 0
|
| 61 |
+
Next page token: eav1OzQB0OM8rLdGXOEsyQWSG
|
| 62 |
+
====================
|
| 63 |
+
Page number: 2
|
| 64 |
+
Items in page: 19
|
| 65 |
+
First item: <MyItemClass at 0x7f1d3cccffd0>
|
| 66 |
+
Items remaining: 18
|
| 67 |
+
Next page token: None
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
import abc
|
| 71 |
+
|
| 72 |
+
from google.api_core.page_iterator import Page
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _item_to_value_identity(iterator, item):
|
| 76 |
+
"""An item to value transformer that returns the item un-changed."""
|
| 77 |
+
# pylint: disable=unused-argument
|
| 78 |
+
# We are conforming to the interface defined by Iterator.
|
| 79 |
+
return item
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class AsyncIterator(abc.ABC):
|
| 83 |
+
"""A generic class for iterating through API list responses.
|
| 84 |
+
|
| 85 |
+
Args:
|
| 86 |
+
client(google.cloud.client.Client): The API client.
|
| 87 |
+
item_to_value (Callable[google.api_core.page_iterator_async.AsyncIterator, Any]):
|
| 88 |
+
Callable to convert an item from the type in the raw API response
|
| 89 |
+
into the native object. Will be called with the iterator and a
|
| 90 |
+
single item.
|
| 91 |
+
page_token (str): A token identifying a page in a result set to start
|
| 92 |
+
fetching results from.
|
| 93 |
+
max_results (int): The maximum number of results to fetch.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
def __init__(
|
| 97 |
+
self,
|
| 98 |
+
client,
|
| 99 |
+
item_to_value=_item_to_value_identity,
|
| 100 |
+
page_token=None,
|
| 101 |
+
max_results=None,
|
| 102 |
+
):
|
| 103 |
+
self._started = False
|
| 104 |
+
self.__active_aiterator = None
|
| 105 |
+
|
| 106 |
+
self.client = client
|
| 107 |
+
"""Optional[Any]: The client that created this iterator."""
|
| 108 |
+
self.item_to_value = item_to_value
|
| 109 |
+
"""Callable[Iterator, Any]: Callable to convert an item from the type
|
| 110 |
+
in the raw API response into the native object. Will be called with
|
| 111 |
+
the iterator and a
|
| 112 |
+
single item.
|
| 113 |
+
"""
|
| 114 |
+
self.max_results = max_results
|
| 115 |
+
"""int: The maximum number of results to fetch."""
|
| 116 |
+
|
| 117 |
+
# The attributes below will change over the life of the iterator.
|
| 118 |
+
self.page_number = 0
|
| 119 |
+
"""int: The current page of results."""
|
| 120 |
+
self.next_page_token = page_token
|
| 121 |
+
"""str: The token for the next page of results. If this is set before
|
| 122 |
+
the iterator starts, it effectively offsets the iterator to a
|
| 123 |
+
specific starting point."""
|
| 124 |
+
self.num_results = 0
|
| 125 |
+
"""int: The total number of results fetched so far."""
|
| 126 |
+
|
| 127 |
+
@property
|
| 128 |
+
def pages(self):
|
| 129 |
+
"""Iterator of pages in the response.
|
| 130 |
+
|
| 131 |
+
returns:
|
| 132 |
+
types.GeneratorType[google.api_core.page_iterator.Page]: A
|
| 133 |
+
generator of page instances.
|
| 134 |
+
|
| 135 |
+
raises:
|
| 136 |
+
ValueError: If the iterator has already been started.
|
| 137 |
+
"""
|
| 138 |
+
if self._started:
|
| 139 |
+
raise ValueError("Iterator has already started", self)
|
| 140 |
+
self._started = True
|
| 141 |
+
return self._page_aiter(increment=True)
|
| 142 |
+
|
| 143 |
+
async def _items_aiter(self):
|
| 144 |
+
"""Iterator for each item returned."""
|
| 145 |
+
async for page in self._page_aiter(increment=False):
|
| 146 |
+
for item in page:
|
| 147 |
+
self.num_results += 1
|
| 148 |
+
yield item
|
| 149 |
+
|
| 150 |
+
def __aiter__(self):
|
| 151 |
+
"""Iterator for each item returned.
|
| 152 |
+
|
| 153 |
+
Returns:
|
| 154 |
+
types.GeneratorType[Any]: A generator of items from the API.
|
| 155 |
+
|
| 156 |
+
Raises:
|
| 157 |
+
ValueError: If the iterator has already been started.
|
| 158 |
+
"""
|
| 159 |
+
if self._started:
|
| 160 |
+
raise ValueError("Iterator has already started", self)
|
| 161 |
+
self._started = True
|
| 162 |
+
return self._items_aiter()
|
| 163 |
+
|
| 164 |
+
async def __anext__(self):
|
| 165 |
+
if self.__active_aiterator is None:
|
| 166 |
+
self.__active_aiterator = self.__aiter__()
|
| 167 |
+
return await self.__active_aiterator.__anext__()
|
| 168 |
+
|
| 169 |
+
async def _page_aiter(self, increment):
|
| 170 |
+
"""Generator of pages of API responses.
|
| 171 |
+
|
| 172 |
+
Args:
|
| 173 |
+
increment (bool): Flag indicating if the total number of results
|
| 174 |
+
should be incremented on each page. This is useful since a page
|
| 175 |
+
iterator will want to increment by results per page while an
|
| 176 |
+
items iterator will want to increment per item.
|
| 177 |
+
|
| 178 |
+
Yields:
|
| 179 |
+
Page: each page of items from the API.
|
| 180 |
+
"""
|
| 181 |
+
page = await self._next_page()
|
| 182 |
+
while page is not None:
|
| 183 |
+
self.page_number += 1
|
| 184 |
+
if increment:
|
| 185 |
+
self.num_results += page.num_items
|
| 186 |
+
yield page
|
| 187 |
+
page = await self._next_page()
|
| 188 |
+
|
| 189 |
+
@abc.abstractmethod
|
| 190 |
+
async def _next_page(self):
|
| 191 |
+
"""Get the next page in the iterator.
|
| 192 |
+
|
| 193 |
+
This does nothing and is intended to be over-ridden by subclasses
|
| 194 |
+
to return the next :class:`Page`.
|
| 195 |
+
|
| 196 |
+
Raises:
|
| 197 |
+
NotImplementedError: Always, this method is abstract.
|
| 198 |
+
"""
|
| 199 |
+
raise NotImplementedError
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
class AsyncGRPCIterator(AsyncIterator):
|
| 203 |
+
"""A generic class for iterating through gRPC list responses.
|
| 204 |
+
|
| 205 |
+
.. note:: The class does not take a ``page_token`` argument because it can
|
| 206 |
+
just be specified in the ``request``.
|
| 207 |
+
|
| 208 |
+
Args:
|
| 209 |
+
client (google.cloud.client.Client): The API client. This unused by
|
| 210 |
+
this class, but kept to satisfy the :class:`Iterator` interface.
|
| 211 |
+
method (Callable[protobuf.Message]): A bound gRPC method that should
|
| 212 |
+
take a single message for the request.
|
| 213 |
+
request (protobuf.Message): The request message.
|
| 214 |
+
items_field (str): The field in the response message that has the
|
| 215 |
+
items for the page.
|
| 216 |
+
item_to_value (Callable[GRPCIterator, Any]): Callable to convert an
|
| 217 |
+
item from the type in the JSON response into a native object. Will
|
| 218 |
+
be called with the iterator and a single item.
|
| 219 |
+
request_token_field (str): The field in the request message used to
|
| 220 |
+
specify the page token.
|
| 221 |
+
response_token_field (str): The field in the response message that has
|
| 222 |
+
the token for the next page.
|
| 223 |
+
max_results (int): The maximum number of results to fetch.
|
| 224 |
+
|
| 225 |
+
.. autoattribute:: pages
|
| 226 |
+
"""
|
| 227 |
+
|
| 228 |
+
_DEFAULT_REQUEST_TOKEN_FIELD = "page_token"
|
| 229 |
+
_DEFAULT_RESPONSE_TOKEN_FIELD = "next_page_token"
|
| 230 |
+
|
| 231 |
+
def __init__(
|
| 232 |
+
self,
|
| 233 |
+
client,
|
| 234 |
+
method,
|
| 235 |
+
request,
|
| 236 |
+
items_field,
|
| 237 |
+
item_to_value=_item_to_value_identity,
|
| 238 |
+
request_token_field=_DEFAULT_REQUEST_TOKEN_FIELD,
|
| 239 |
+
response_token_field=_DEFAULT_RESPONSE_TOKEN_FIELD,
|
| 240 |
+
max_results=None,
|
| 241 |
+
):
|
| 242 |
+
super().__init__(client, item_to_value, max_results=max_results)
|
| 243 |
+
self._method = method
|
| 244 |
+
self._request = request
|
| 245 |
+
self._items_field = items_field
|
| 246 |
+
self._request_token_field = request_token_field
|
| 247 |
+
self._response_token_field = response_token_field
|
| 248 |
+
|
| 249 |
+
async def _next_page(self):
|
| 250 |
+
"""Get the next page in the iterator.
|
| 251 |
+
|
| 252 |
+
Returns:
|
| 253 |
+
Page: The next page in the iterator or :data:`None` if
|
| 254 |
+
there are no pages left.
|
| 255 |
+
"""
|
| 256 |
+
if not self._has_next_page():
|
| 257 |
+
return None
|
| 258 |
+
|
| 259 |
+
if self.next_page_token is not None:
|
| 260 |
+
setattr(self._request, self._request_token_field, self.next_page_token)
|
| 261 |
+
|
| 262 |
+
response = await self._method(self._request)
|
| 263 |
+
|
| 264 |
+
self.next_page_token = getattr(response, self._response_token_field)
|
| 265 |
+
items = getattr(response, self._items_field)
|
| 266 |
+
page = Page(self, items, self.item_to_value, raw_page=response)
|
| 267 |
+
|
| 268 |
+
return page
|
| 269 |
+
|
| 270 |
+
def _has_next_page(self):
|
| 271 |
+
"""Determines whether or not there are more pages with results.
|
| 272 |
+
|
| 273 |
+
Returns:
|
| 274 |
+
bool: Whether the iterator has more pages.
|
| 275 |
+
"""
|
| 276 |
+
if self.page_number == 0:
|
| 277 |
+
return True
|
| 278 |
+
|
| 279 |
+
# Note: intentionally a falsy check instead of a None check. The RPC
|
| 280 |
+
# can return an empty string indicating no more pages.
|
| 281 |
+
if self.max_results is not None:
|
| 282 |
+
if self.num_results >= self.max_results:
|
| 283 |
+
return False
|
| 284 |
+
|
| 285 |
+
return True if self.next_page_token else False
|
data/tefig/envs/olmes-eval/l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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Expand and validate URL path templates.
|
| 16 |
+
|
| 17 |
+
This module provides the :func:`expand` and :func:`validate` functions for
|
| 18 |
+
interacting with Google-style URL `path templates`_ which are commonly used
|
| 19 |
+
in Google APIs for `resource names`_.
|
| 20 |
+
|
| 21 |
+
.. _path templates: https://github.com/googleapis/googleapis/blob
|
| 22 |
+
/57e2d376ac7ef48681554204a3ba78a414f2c533/google/api/http.proto#L212
|
| 23 |
+
.. _resource names: https://cloud.google.com/apis/design/resource_names
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
from __future__ import unicode_literals
|
| 27 |
+
|
| 28 |
+
from collections import deque
|
| 29 |
+
import copy
|
| 30 |
+
import functools
|
| 31 |
+
import re
|
| 32 |
+
|
| 33 |
+
# Regular expression for extracting variable parts from a path template.
|
| 34 |
+
# The variables can be expressed as:
|
| 35 |
+
#
|
| 36 |
+
# - "*": a single-segment positional variable, for example: "books/*"
|
| 37 |
+
# - "**": a multi-segment positional variable, for example: "shelf/**/book/*"
|
| 38 |
+
# - "{name}": a single-segment wildcard named variable, for example
|
| 39 |
+
# "books/{name}"
|
| 40 |
+
# - "{name=*}: same as above.
|
| 41 |
+
# - "{name=**}": a multi-segment wildcard named variable, for example
|
| 42 |
+
# "shelf/{name=**}"
|
| 43 |
+
# - "{name=/path/*/**}": a multi-segment named variable with a sub-template.
|
| 44 |
+
_VARIABLE_RE = re.compile(
|
| 45 |
+
r"""
|
| 46 |
+
( # Capture the entire variable expression
|
| 47 |
+
(?P<positional>\*\*?) # Match & capture * and ** positional variables.
|
| 48 |
+
|
|
| 49 |
+
# Match & capture named variables {name}
|
| 50 |
+
{
|
| 51 |
+
(?P<name>[^/]+?)
|
| 52 |
+
# Optionally match and capture the named variable's template.
|
| 53 |
+
(?:=(?P<template>.+?))?
|
| 54 |
+
}
|
| 55 |
+
)
|
| 56 |
+
""",
|
| 57 |
+
re.VERBOSE,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
# Segment expressions used for validating paths against a template.
|
| 61 |
+
_SINGLE_SEGMENT_PATTERN = r"([^/]+)"
|
| 62 |
+
_MULTI_SEGMENT_PATTERN = r"(.+)"
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _expand_variable_match(positional_vars, named_vars, match):
|
| 66 |
+
"""Expand a matched variable with its value.
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
positional_vars (list): A list of positional variables. This list will
|
| 70 |
+
be modified.
|
| 71 |
+
named_vars (dict): A dictionary of named variables.
|
| 72 |
+
match (re.Match): A regular expression match.
|
| 73 |
+
|
| 74 |
+
Returns:
|
| 75 |
+
str: The expanded variable to replace the match.
|
| 76 |
+
|
| 77 |
+
Raises:
|
| 78 |
+
ValueError: If a positional or named variable is required by the
|
| 79 |
+
template but not specified or if an unexpected template expression
|
| 80 |
+
is encountered.
|
| 81 |
+
"""
|
| 82 |
+
positional = match.group("positional")
|
| 83 |
+
name = match.group("name")
|
| 84 |
+
if name is not None:
|
| 85 |
+
try:
|
| 86 |
+
return str(named_vars[name])
|
| 87 |
+
except KeyError:
|
| 88 |
+
raise ValueError(
|
| 89 |
+
"Named variable '{}' not specified and needed by template "
|
| 90 |
+
"`{}` at position {}".format(name, match.string, match.start())
|
| 91 |
+
)
|
| 92 |
+
elif positional is not None:
|
| 93 |
+
try:
|
| 94 |
+
return str(positional_vars.pop(0))
|
| 95 |
+
except IndexError:
|
| 96 |
+
raise ValueError(
|
| 97 |
+
"Positional variable not specified and needed by template "
|
| 98 |
+
"`{}` at position {}".format(match.string, match.start())
|
| 99 |
+
)
|
| 100 |
+
else:
|
| 101 |
+
raise ValueError("Unknown template expression {}".format(match.group(0)))
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def expand(tmpl, *args, **kwargs):
|
| 105 |
+
"""Expand a path template with the given variables.
|
| 106 |
+
|
| 107 |
+
.. code-block:: python
|
| 108 |
+
|
| 109 |
+
>>> expand('users/*/messages/*', 'me', '123')
|
| 110 |
+
users/me/messages/123
|
| 111 |
+
>>> expand('/v1/{name=shelves/*/books/*}', name='shelves/1/books/3')
|
| 112 |
+
/v1/shelves/1/books/3
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
tmpl (str): The path template.
|
| 116 |
+
args: The positional variables for the path.
|
| 117 |
+
kwargs: The named variables for the path.
|
| 118 |
+
|
| 119 |
+
Returns:
|
| 120 |
+
str: The expanded path
|
| 121 |
+
|
| 122 |
+
Raises:
|
| 123 |
+
ValueError: If a positional or named variable is required by the
|
| 124 |
+
template but not specified or if an unexpected template expression
|
| 125 |
+
is encountered.
|
| 126 |
+
"""
|
| 127 |
+
replacer = functools.partial(_expand_variable_match, list(args), kwargs)
|
| 128 |
+
return _VARIABLE_RE.sub(replacer, tmpl)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _replace_variable_with_pattern(match):
|
| 132 |
+
"""Replace a variable match with a pattern that can be used to validate it.
|
| 133 |
+
|
| 134 |
+
Args:
|
| 135 |
+
match (re.Match): A regular expression match
|
| 136 |
+
|
| 137 |
+
Returns:
|
| 138 |
+
str: A regular expression pattern that can be used to validate the
|
| 139 |
+
variable in an expanded path.
|
| 140 |
+
|
| 141 |
+
Raises:
|
| 142 |
+
ValueError: If an unexpected template expression is encountered.
|
| 143 |
+
"""
|
| 144 |
+
positional = match.group("positional")
|
| 145 |
+
name = match.group("name")
|
| 146 |
+
template = match.group("template")
|
| 147 |
+
if name is not None:
|
| 148 |
+
if not template:
|
| 149 |
+
return _SINGLE_SEGMENT_PATTERN.format(name)
|
| 150 |
+
elif template == "**":
|
| 151 |
+
return _MULTI_SEGMENT_PATTERN.format(name)
|
| 152 |
+
else:
|
| 153 |
+
return _generate_pattern_for_template(template)
|
| 154 |
+
elif positional == "*":
|
| 155 |
+
return _SINGLE_SEGMENT_PATTERN
|
| 156 |
+
elif positional == "**":
|
| 157 |
+
return _MULTI_SEGMENT_PATTERN
|
| 158 |
+
else:
|
| 159 |
+
raise ValueError("Unknown template expression {}".format(match.group(0)))
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _generate_pattern_for_template(tmpl):
|
| 163 |
+
"""Generate a pattern that can validate a path template.
|
| 164 |
+
|
| 165 |
+
Args:
|
| 166 |
+
tmpl (str): The path template
|
| 167 |
+
|
| 168 |
+
Returns:
|
| 169 |
+
str: A regular expression pattern that can be used to validate an
|
| 170 |
+
expanded path template.
|
| 171 |
+
"""
|
| 172 |
+
return _VARIABLE_RE.sub(_replace_variable_with_pattern, tmpl)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def get_field(request, field):
|
| 176 |
+
"""Get the value of a field from a given dictionary.
|
| 177 |
+
|
| 178 |
+
Args:
|
| 179 |
+
request (dict | Message): A dictionary or a Message object.
|
| 180 |
+
field (str): The key to the request in dot notation.
|
| 181 |
+
|
| 182 |
+
Returns:
|
| 183 |
+
The value of the field.
|
| 184 |
+
"""
|
| 185 |
+
parts = field.split(".")
|
| 186 |
+
value = request
|
| 187 |
+
|
| 188 |
+
for part in parts:
|
| 189 |
+
if not isinstance(value, dict):
|
| 190 |
+
value = getattr(value, part, None)
|
| 191 |
+
else:
|
| 192 |
+
value = value.get(part)
|
| 193 |
+
if isinstance(value, dict):
|
| 194 |
+
return
|
| 195 |
+
return value
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def delete_field(request, field):
|
| 199 |
+
"""Delete the value of a field from a given dictionary.
|
| 200 |
+
|
| 201 |
+
Args:
|
| 202 |
+
request (dict | Message): A dictionary object or a Message.
|
| 203 |
+
field (str): The key to the request in dot notation.
|
| 204 |
+
"""
|
| 205 |
+
parts = deque(field.split("."))
|
| 206 |
+
while len(parts) > 1:
|
| 207 |
+
part = parts.popleft()
|
| 208 |
+
if not isinstance(request, dict):
|
| 209 |
+
if hasattr(request, part):
|
| 210 |
+
request = getattr(request, part, None)
|
| 211 |
+
else:
|
| 212 |
+
return
|
| 213 |
+
else:
|
| 214 |
+
request = request.get(part)
|
| 215 |
+
part = parts.popleft()
|
| 216 |
+
if not isinstance(request, dict):
|
| 217 |
+
if hasattr(request, part):
|
| 218 |
+
request.ClearField(part)
|
| 219 |
+
else:
|
| 220 |
+
return
|
| 221 |
+
else:
|
| 222 |
+
request.pop(part, None)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def validate(tmpl, path):
|
| 226 |
+
"""Validate a path against the path template.
|
| 227 |
+
|
| 228 |
+
.. code-block:: python
|
| 229 |
+
|
| 230 |
+
>>> validate('users/*/messages/*', 'users/me/messages/123')
|
| 231 |
+
True
|
| 232 |
+
>>> validate('users/*/messages/*', 'users/me/drafts/123')
|
| 233 |
+
False
|
| 234 |
+
>>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/books/3)
|
| 235 |
+
True
|
| 236 |
+
>>> validate('/v1/{name=shelves/*/books/*}', /v1/shelves/1/tapes/3)
|
| 237 |
+
False
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
tmpl (str): The path template.
|
| 241 |
+
path (str): The expanded path.
|
| 242 |
+
|
| 243 |
+
Returns:
|
| 244 |
+
bool: True if the path matches.
|
| 245 |
+
"""
|
| 246 |
+
pattern = _generate_pattern_for_template(tmpl) + "$"
|
| 247 |
+
return True if re.match(pattern, path) is not None else False
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def transcode(http_options, message=None, **request_kwargs):
|
| 251 |
+
"""Transcodes a grpc request pattern into a proper HTTP request following the rules outlined here,
|
| 252 |
+
https://github.com/googleapis/googleapis/blob/master/google/api/http.proto#L44-L312
|
| 253 |
+
|
| 254 |
+
Args:
|
| 255 |
+
http_options (list(dict)): A list of dicts which consist of these keys,
|
| 256 |
+
'method' (str): The http method
|
| 257 |
+
'uri' (str): The path template
|
| 258 |
+
'body' (str): The body field name (optional)
|
| 259 |
+
(This is a simplified representation of the proto option `google.api.http`)
|
| 260 |
+
|
| 261 |
+
message (Message) : A request object (optional)
|
| 262 |
+
request_kwargs (dict) : A dict representing the request object
|
| 263 |
+
|
| 264 |
+
Returns:
|
| 265 |
+
dict: The transcoded request with these keys,
|
| 266 |
+
'method' (str) : The http method
|
| 267 |
+
'uri' (str) : The expanded uri
|
| 268 |
+
'body' (dict | Message) : A dict or a Message representing the body (optional)
|
| 269 |
+
'query_params' (dict | Message) : A dict or Message mapping query parameter variables and values
|
| 270 |
+
|
| 271 |
+
Raises:
|
| 272 |
+
ValueError: If the request does not match the given template.
|
| 273 |
+
"""
|
| 274 |
+
transcoded_value = message or request_kwargs
|
| 275 |
+
bindings = []
|
| 276 |
+
for http_option in http_options:
|
| 277 |
+
request = {}
|
| 278 |
+
|
| 279 |
+
# Assign path
|
| 280 |
+
uri_template = http_option["uri"]
|
| 281 |
+
fields = [
|
| 282 |
+
(m.group("name"), m.group("template"))
|
| 283 |
+
for m in _VARIABLE_RE.finditer(uri_template)
|
| 284 |
+
]
|
| 285 |
+
bindings.append((uri_template, fields))
|
| 286 |
+
|
| 287 |
+
path_args = {field: get_field(transcoded_value, field) for field, _ in fields}
|
| 288 |
+
request["uri"] = expand(uri_template, **path_args)
|
| 289 |
+
|
| 290 |
+
if not validate(uri_template, request["uri"]) or not all(path_args.values()):
|
| 291 |
+
continue
|
| 292 |
+
|
| 293 |
+
# Remove fields used in uri path from request
|
| 294 |
+
leftovers = copy.deepcopy(transcoded_value)
|
| 295 |
+
for path_field, _ in fields:
|
| 296 |
+
delete_field(leftovers, path_field)
|
| 297 |
+
|
| 298 |
+
# Assign body and query params
|
| 299 |
+
body = http_option.get("body")
|
| 300 |
+
|
| 301 |
+
if body:
|
| 302 |
+
if body == "*":
|
| 303 |
+
request["body"] = leftovers
|
| 304 |
+
if message:
|
| 305 |
+
request["query_params"] = message.__class__()
|
| 306 |
+
else:
|
| 307 |
+
request["query_params"] = {}
|
| 308 |
+
else:
|
| 309 |
+
try:
|
| 310 |
+
if message:
|
| 311 |
+
request["body"] = getattr(leftovers, body)
|
| 312 |
+
delete_field(leftovers, body)
|
| 313 |
+
else:
|
| 314 |
+
request["body"] = leftovers.pop(body)
|
| 315 |
+
except (KeyError, AttributeError):
|
| 316 |
+
continue
|
| 317 |
+
request["query_params"] = leftovers
|
| 318 |
+
else:
|
| 319 |
+
request["query_params"] = leftovers
|
| 320 |
+
request["method"] = http_option["method"]
|
| 321 |
+
return request
|
| 322 |
+
|
| 323 |
+
bindings_description = [
|
| 324 |
+
'\n\tURI: "{}"'
|
| 325 |
+
"\n\tRequired request fields:\n\t\t{}".format(
|
| 326 |
+
uri,
|
| 327 |
+
"\n\t\t".join(
|
| 328 |
+
[
|
| 329 |
+
'field: "{}", pattern: "{}"'.format(n, p if p else "*")
|
| 330 |
+
for n, p in fields
|
| 331 |
+
]
|
| 332 |
+
),
|
| 333 |
+
)
|
| 334 |
+
for uri, fields in bindings
|
| 335 |
+
]
|
| 336 |
+
|
| 337 |
+
raise ValueError(
|
| 338 |
+
"Invalid request."
|
| 339 |
+
"\nSome of the fields of the request message are either not initialized or "
|
| 340 |
+
"initialized with an invalid value."
|
| 341 |
+
"\nPlease make sure your request matches at least one accepted HTTP binding."
|
| 342 |
+
"\nTo match a binding the request message must have all the required fields "
|
| 343 |
+
"initialized with values matching their patterns as listed below:{}".format(
|
| 344 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Helpers for :mod:`protobuf`."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
import collections.abc
|
| 19 |
+
import copy
|
| 20 |
+
import inspect
|
| 21 |
+
|
| 22 |
+
from google.protobuf import field_mask_pb2
|
| 23 |
+
from google.protobuf import message
|
| 24 |
+
from google.protobuf import wrappers_pb2
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
_SENTINEL = object()
|
| 28 |
+
_WRAPPER_TYPES = (
|
| 29 |
+
wrappers_pb2.BoolValue,
|
| 30 |
+
wrappers_pb2.BytesValue,
|
| 31 |
+
wrappers_pb2.DoubleValue,
|
| 32 |
+
wrappers_pb2.FloatValue,
|
| 33 |
+
wrappers_pb2.Int32Value,
|
| 34 |
+
wrappers_pb2.Int64Value,
|
| 35 |
+
wrappers_pb2.StringValue,
|
| 36 |
+
wrappers_pb2.UInt32Value,
|
| 37 |
+
wrappers_pb2.UInt64Value,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def from_any_pb(pb_type, any_pb):
|
| 42 |
+
"""Converts an ``Any`` protobuf to the specified message type.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
pb_type (type): the type of the message that any_pb stores an instance
|
| 46 |
+
of.
|
| 47 |
+
any_pb (google.protobuf.any_pb2.Any): the object to be converted.
|
| 48 |
+
|
| 49 |
+
Returns:
|
| 50 |
+
pb_type: An instance of the pb_type message.
|
| 51 |
+
|
| 52 |
+
Raises:
|
| 53 |
+
TypeError: if the message could not be converted.
|
| 54 |
+
"""
|
| 55 |
+
msg = pb_type()
|
| 56 |
+
|
| 57 |
+
# Unwrap proto-plus wrapped messages.
|
| 58 |
+
if callable(getattr(pb_type, "pb", None)):
|
| 59 |
+
msg_pb = pb_type.pb(msg)
|
| 60 |
+
else:
|
| 61 |
+
msg_pb = msg
|
| 62 |
+
|
| 63 |
+
# Unpack the Any object and populate the protobuf message instance.
|
| 64 |
+
if not any_pb.Unpack(msg_pb):
|
| 65 |
+
raise TypeError(
|
| 66 |
+
f"Could not convert `{any_pb.TypeName()}` with underlying type `google.protobuf.any_pb2.Any` to `{msg_pb.DESCRIPTOR.full_name}`"
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
# Done; return the message.
|
| 70 |
+
return msg
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def check_oneof(**kwargs):
|
| 74 |
+
"""Raise ValueError if more than one keyword argument is not ``None``.
|
| 75 |
+
|
| 76 |
+
Args:
|
| 77 |
+
kwargs (dict): The keyword arguments sent to the function.
|
| 78 |
+
|
| 79 |
+
Raises:
|
| 80 |
+
ValueError: If more than one entry in ``kwargs`` is not ``None``.
|
| 81 |
+
"""
|
| 82 |
+
# Sanity check: If no keyword arguments were sent, this is fine.
|
| 83 |
+
if not kwargs:
|
| 84 |
+
return
|
| 85 |
+
|
| 86 |
+
not_nones = [val for val in kwargs.values() if val is not None]
|
| 87 |
+
if len(not_nones) > 1:
|
| 88 |
+
raise ValueError(
|
| 89 |
+
"Only one of {fields} should be set.".format(
|
| 90 |
+
fields=", ".join(sorted(kwargs.keys()))
|
| 91 |
+
)
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def get_messages(module):
|
| 96 |
+
"""Discovers all protobuf Message classes in a given import module.
|
| 97 |
+
|
| 98 |
+
Args:
|
| 99 |
+
module (module): A Python module; :func:`dir` will be run against this
|
| 100 |
+
module to find Message subclasses.
|
| 101 |
+
|
| 102 |
+
Returns:
|
| 103 |
+
dict[str, google.protobuf.message.Message]: A dictionary with the
|
| 104 |
+
Message class names as keys, and the Message subclasses themselves
|
| 105 |
+
as values.
|
| 106 |
+
"""
|
| 107 |
+
answer = collections.OrderedDict()
|
| 108 |
+
for name in dir(module):
|
| 109 |
+
candidate = getattr(module, name)
|
| 110 |
+
if inspect.isclass(candidate) and issubclass(candidate, message.Message):
|
| 111 |
+
answer[name] = candidate
|
| 112 |
+
return answer
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _resolve_subkeys(key, separator="."):
|
| 116 |
+
"""Resolve a potentially nested key.
|
| 117 |
+
|
| 118 |
+
If the key contains the ``separator`` (e.g. ``.``) then the key will be
|
| 119 |
+
split on the first instance of the subkey::
|
| 120 |
+
|
| 121 |
+
>>> _resolve_subkeys('a.b.c')
|
| 122 |
+
('a', 'b.c')
|
| 123 |
+
>>> _resolve_subkeys('d|e|f', separator='|')
|
| 124 |
+
('d', 'e|f')
|
| 125 |
+
|
| 126 |
+
If not, the subkey will be :data:`None`::
|
| 127 |
+
|
| 128 |
+
>>> _resolve_subkeys('foo')
|
| 129 |
+
('foo', None)
|
| 130 |
+
|
| 131 |
+
Args:
|
| 132 |
+
key (str): A string that may or may not contain the separator.
|
| 133 |
+
separator (str): The namespace separator. Defaults to `.`.
|
| 134 |
+
|
| 135 |
+
Returns:
|
| 136 |
+
Tuple[str, str]: The key and subkey(s).
|
| 137 |
+
"""
|
| 138 |
+
parts = key.split(separator, 1)
|
| 139 |
+
|
| 140 |
+
if len(parts) > 1:
|
| 141 |
+
return parts
|
| 142 |
+
else:
|
| 143 |
+
return parts[0], None
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def get(msg_or_dict, key, default=_SENTINEL):
|
| 147 |
+
"""Retrieve a key's value from a protobuf Message or dictionary.
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
mdg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the
|
| 151 |
+
object.
|
| 152 |
+
key (str): The key to retrieve from the object.
|
| 153 |
+
default (Any): If the key is not present on the object, and a default
|
| 154 |
+
is set, returns that default instead. A type-appropriate falsy
|
| 155 |
+
default is generally recommended, as protobuf messages almost
|
| 156 |
+
always have default values for unset values and it is not always
|
| 157 |
+
possible to tell the difference between a falsy value and an
|
| 158 |
+
unset one. If no default is set then :class:`KeyError` will be
|
| 159 |
+
raised if the key is not present in the object.
|
| 160 |
+
|
| 161 |
+
Returns:
|
| 162 |
+
Any: The return value from the underlying Message or dict.
|
| 163 |
+
|
| 164 |
+
Raises:
|
| 165 |
+
KeyError: If the key is not found. Note that, for unset values,
|
| 166 |
+
messages and dictionaries may not have consistent behavior.
|
| 167 |
+
TypeError: If ``msg_or_dict`` is not a Message or Mapping.
|
| 168 |
+
"""
|
| 169 |
+
# We may need to get a nested key. Resolve this.
|
| 170 |
+
key, subkey = _resolve_subkeys(key)
|
| 171 |
+
|
| 172 |
+
# Attempt to get the value from the two types of objects we know about.
|
| 173 |
+
# If we get something else, complain.
|
| 174 |
+
if isinstance(msg_or_dict, message.Message):
|
| 175 |
+
answer = getattr(msg_or_dict, key, default)
|
| 176 |
+
elif isinstance(msg_or_dict, collections.abc.Mapping):
|
| 177 |
+
answer = msg_or_dict.get(key, default)
|
| 178 |
+
else:
|
| 179 |
+
raise TypeError(
|
| 180 |
+
"get() expected a dict or protobuf message, got {!r}.".format(
|
| 181 |
+
type(msg_or_dict)
|
| 182 |
+
)
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
# If the object we got back is our sentinel, raise KeyError; this is
|
| 186 |
+
# a "not found" case.
|
| 187 |
+
if answer is _SENTINEL:
|
| 188 |
+
raise KeyError(key)
|
| 189 |
+
|
| 190 |
+
# If a subkey exists, call this method recursively against the answer.
|
| 191 |
+
if subkey is not None and answer is not default:
|
| 192 |
+
return get(answer, subkey, default=default)
|
| 193 |
+
|
| 194 |
+
return answer
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def _set_field_on_message(msg, key, value):
|
| 198 |
+
"""Set helper for protobuf Messages."""
|
| 199 |
+
# Attempt to set the value on the types of objects we know how to deal
|
| 200 |
+
# with.
|
| 201 |
+
if isinstance(value, (collections.abc.MutableSequence, tuple)):
|
| 202 |
+
# Clear the existing repeated protobuf message of any elements
|
| 203 |
+
# currently inside it.
|
| 204 |
+
while getattr(msg, key):
|
| 205 |
+
getattr(msg, key).pop()
|
| 206 |
+
|
| 207 |
+
# Write our new elements to the repeated field.
|
| 208 |
+
for item in value:
|
| 209 |
+
if isinstance(item, collections.abc.Mapping):
|
| 210 |
+
getattr(msg, key).add(**item)
|
| 211 |
+
else:
|
| 212 |
+
# protobuf's RepeatedCompositeContainer doesn't support
|
| 213 |
+
# append.
|
| 214 |
+
getattr(msg, key).extend([item])
|
| 215 |
+
elif isinstance(value, collections.abc.Mapping):
|
| 216 |
+
# Assign the dictionary values to the protobuf message.
|
| 217 |
+
for item_key, item_value in value.items():
|
| 218 |
+
set(getattr(msg, key), item_key, item_value)
|
| 219 |
+
elif isinstance(value, message.Message):
|
| 220 |
+
getattr(msg, key).CopyFrom(value)
|
| 221 |
+
else:
|
| 222 |
+
setattr(msg, key, value)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def set(msg_or_dict, key, value):
|
| 226 |
+
"""Set a key's value on a protobuf Message or dictionary.
|
| 227 |
+
|
| 228 |
+
Args:
|
| 229 |
+
msg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the
|
| 230 |
+
object.
|
| 231 |
+
key (str): The key to set.
|
| 232 |
+
value (Any): The value to set.
|
| 233 |
+
|
| 234 |
+
Raises:
|
| 235 |
+
TypeError: If ``msg_or_dict`` is not a Message or dictionary.
|
| 236 |
+
"""
|
| 237 |
+
# Sanity check: Is our target object valid?
|
| 238 |
+
if not isinstance(msg_or_dict, (collections.abc.MutableMapping, message.Message)):
|
| 239 |
+
raise TypeError(
|
| 240 |
+
"set() expected a dict or protobuf message, got {!r}.".format(
|
| 241 |
+
type(msg_or_dict)
|
| 242 |
+
)
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
# We may be setting a nested key. Resolve this.
|
| 246 |
+
basekey, subkey = _resolve_subkeys(key)
|
| 247 |
+
|
| 248 |
+
# If a subkey exists, then get that object and call this method
|
| 249 |
+
# recursively against it using the subkey.
|
| 250 |
+
if subkey is not None:
|
| 251 |
+
if isinstance(msg_or_dict, collections.abc.MutableMapping):
|
| 252 |
+
msg_or_dict.setdefault(basekey, {})
|
| 253 |
+
set(get(msg_or_dict, basekey), subkey, value)
|
| 254 |
+
return
|
| 255 |
+
|
| 256 |
+
if isinstance(msg_or_dict, collections.abc.MutableMapping):
|
| 257 |
+
msg_or_dict[key] = value
|
| 258 |
+
else:
|
| 259 |
+
_set_field_on_message(msg_or_dict, key, value)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def setdefault(msg_or_dict, key, value):
|
| 263 |
+
"""Set the key on a protobuf Message or dictionary to a given value if the
|
| 264 |
+
current value is falsy.
|
| 265 |
+
|
| 266 |
+
Because protobuf Messages do not distinguish between unset values and
|
| 267 |
+
falsy ones particularly well (by design), this method treats any falsy
|
| 268 |
+
value (e.g. 0, empty list) as a target to be overwritten, on both Messages
|
| 269 |
+
and dictionaries.
|
| 270 |
+
|
| 271 |
+
Args:
|
| 272 |
+
msg_or_dict (Union[~google.protobuf.message.Message, Mapping]): the
|
| 273 |
+
object.
|
| 274 |
+
key (str): The key on the object in question.
|
| 275 |
+
value (Any): The value to set.
|
| 276 |
+
|
| 277 |
+
Raises:
|
| 278 |
+
TypeError: If ``msg_or_dict`` is not a Message or dictionary.
|
| 279 |
+
"""
|
| 280 |
+
if not get(msg_or_dict, key, default=None):
|
| 281 |
+
set(msg_or_dict, key, value)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def field_mask(original, modified):
|
| 285 |
+
"""Create a field mask by comparing two messages.
|
| 286 |
+
|
| 287 |
+
Args:
|
| 288 |
+
original (~google.protobuf.message.Message): the original message.
|
| 289 |
+
If set to None, this field will be interpreted as an empty
|
| 290 |
+
message.
|
| 291 |
+
modified (~google.protobuf.message.Message): the modified message.
|
| 292 |
+
If set to None, this field will be interpreted as an empty
|
| 293 |
+
message.
|
| 294 |
+
|
| 295 |
+
Returns:
|
| 296 |
+
google.protobuf.field_mask_pb2.FieldMask: field mask that contains
|
| 297 |
+
the list of field names that have different values between the two
|
| 298 |
+
messages. If the messages are equivalent, then the field mask is empty.
|
| 299 |
+
|
| 300 |
+
Raises:
|
| 301 |
+
ValueError: If the ``original`` or ``modified`` are not the same type.
|
| 302 |
+
"""
|
| 303 |
+
if original is None and modified is None:
|
| 304 |
+
return field_mask_pb2.FieldMask()
|
| 305 |
+
|
| 306 |
+
if original is None and modified is not None:
|
| 307 |
+
original = copy.deepcopy(modified)
|
| 308 |
+
original.Clear()
|
| 309 |
+
|
| 310 |
+
if modified is None and original is not None:
|
| 311 |
+
modified = copy.deepcopy(original)
|
| 312 |
+
modified.Clear()
|
| 313 |
+
|
| 314 |
+
if not isinstance(original, type(modified)):
|
| 315 |
+
raise ValueError(
|
| 316 |
+
"expected that both original and modified should be of the "
|
| 317 |
+
'same type, received "{!r}" and "{!r}".'.format(
|
| 318 |
+
type(original), type(modified)
|
| 319 |
+
)
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
return field_mask_pb2.FieldMask(paths=_field_mask_helper(original, modified))
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def _field_mask_helper(original, modified, current=""):
|
| 326 |
+
answer = []
|
| 327 |
+
|
| 328 |
+
for name in original.DESCRIPTOR.fields_by_name:
|
| 329 |
+
field_path = _get_path(current, name)
|
| 330 |
+
|
| 331 |
+
original_val = getattr(original, name)
|
| 332 |
+
modified_val = getattr(modified, name)
|
| 333 |
+
|
| 334 |
+
if _is_message(original_val) or _is_message(modified_val):
|
| 335 |
+
if original_val != modified_val:
|
| 336 |
+
# Wrapper types do not need to include the .value part of the
|
| 337 |
+
# path.
|
| 338 |
+
if _is_wrapper(original_val) or _is_wrapper(modified_val):
|
| 339 |
+
answer.append(field_path)
|
| 340 |
+
elif not modified_val.ListFields():
|
| 341 |
+
answer.append(field_path)
|
| 342 |
+
else:
|
| 343 |
+
answer.extend(
|
| 344 |
+
_field_mask_helper(original_val, modified_val, field_path)
|
| 345 |
+
)
|
| 346 |
+
else:
|
| 347 |
+
if original_val != modified_val:
|
| 348 |
+
answer.append(field_path)
|
| 349 |
+
|
| 350 |
+
return answer
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def _get_path(current, name):
|
| 354 |
+
# gapic-generator-python appends underscores to field names
|
| 355 |
+
# that collide with python keywords.
|
| 356 |
+
# `_` is stripped away as it is not possible to
|
| 357 |
+
# natively define a field with a trailing underscore in protobuf.
|
| 358 |
+
# APIs will reject field masks if fields have trailing underscores.
|
| 359 |
+
# See https://github.com/googleapis/python-api-core/issues/227
|
| 360 |
+
name = name.rstrip("_")
|
| 361 |
+
if not current:
|
| 362 |
+
return name
|
| 363 |
+
return "%s.%s" % (current, name)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def _is_message(value):
|
| 367 |
+
return isinstance(value, message.Message)
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def _is_wrapper(value):
|
| 371 |
+
return type(value) in _WRAPPER_TYPES
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/py.typed
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Marker file for PEP 561.
|
| 2 |
+
# The google-api-core package uses inline types.
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/rest_helpers.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Helpers for rest transports."""
|
| 16 |
+
|
| 17 |
+
import functools
|
| 18 |
+
import operator
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def flatten_query_params(obj, strict=False):
|
| 22 |
+
"""Flatten a dict into a list of (name,value) tuples.
|
| 23 |
+
|
| 24 |
+
The result is suitable for setting query params on an http request.
|
| 25 |
+
|
| 26 |
+
.. code-block:: python
|
| 27 |
+
|
| 28 |
+
>>> obj = {'a':
|
| 29 |
+
... {'b':
|
| 30 |
+
... {'c': ['x', 'y', 'z']} },
|
| 31 |
+
... 'd': 'uvw',
|
| 32 |
+
... 'e': True, }
|
| 33 |
+
>>> flatten_query_params(obj, strict=True)
|
| 34 |
+
[('a.b.c', 'x'), ('a.b.c', 'y'), ('a.b.c', 'z'), ('d', 'uvw'), ('e', 'true')]
|
| 35 |
+
|
| 36 |
+
Note that, as described in
|
| 37 |
+
https://github.com/googleapis/googleapis/blob/48d9fb8c8e287c472af500221c6450ecd45d7d39/google/api/http.proto#L117,
|
| 38 |
+
repeated fields (i.e. list-valued fields) may only contain primitive types (not lists or dicts).
|
| 39 |
+
This is enforced in this function.
|
| 40 |
+
|
| 41 |
+
Args:
|
| 42 |
+
obj: a possibly nested dictionary (from json), or None
|
| 43 |
+
strict: a bool, defaulting to False, to enforce that all values in the
|
| 44 |
+
result tuples be strings and, if boolean, lower-cased.
|
| 45 |
+
|
| 46 |
+
Returns: a list of tuples, with each tuple having a (possibly) multi-part name
|
| 47 |
+
and a scalar value.
|
| 48 |
+
|
| 49 |
+
Raises:
|
| 50 |
+
TypeError if obj is not a dict or None
|
| 51 |
+
ValueError if obj contains a list of non-primitive values.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
if obj is not None and not isinstance(obj, dict):
|
| 55 |
+
raise TypeError("flatten_query_params must be called with dict object")
|
| 56 |
+
|
| 57 |
+
return _flatten(obj, key_path=[], strict=strict)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _flatten(obj, key_path, strict=False):
|
| 61 |
+
if obj is None:
|
| 62 |
+
return []
|
| 63 |
+
if isinstance(obj, dict):
|
| 64 |
+
return _flatten_dict(obj, key_path=key_path, strict=strict)
|
| 65 |
+
if isinstance(obj, list):
|
| 66 |
+
return _flatten_list(obj, key_path=key_path, strict=strict)
|
| 67 |
+
return _flatten_value(obj, key_path=key_path, strict=strict)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _is_primitive_value(obj):
|
| 71 |
+
if obj is None:
|
| 72 |
+
return False
|
| 73 |
+
|
| 74 |
+
if isinstance(obj, (list, dict)):
|
| 75 |
+
raise ValueError("query params may not contain repeated dicts or lists")
|
| 76 |
+
|
| 77 |
+
return True
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _flatten_value(obj, key_path, strict=False):
|
| 81 |
+
return [(".".join(key_path), _canonicalize(obj, strict=strict))]
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _flatten_dict(obj, key_path, strict=False):
|
| 85 |
+
items = (
|
| 86 |
+
_flatten(value, key_path=key_path + [key], strict=strict)
|
| 87 |
+
for key, value in obj.items()
|
| 88 |
+
)
|
| 89 |
+
return functools.reduce(operator.concat, items, [])
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _flatten_list(elems, key_path, strict=False):
|
| 93 |
+
# Only lists of scalar values are supported.
|
| 94 |
+
# The name (key_path) is repeated for each value.
|
| 95 |
+
items = (
|
| 96 |
+
_flatten_value(elem, key_path=key_path, strict=strict)
|
| 97 |
+
for elem in elems
|
| 98 |
+
if _is_primitive_value(elem)
|
| 99 |
+
)
|
| 100 |
+
return functools.reduce(operator.concat, items, [])
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _canonicalize(obj, strict=False):
|
| 104 |
+
if strict:
|
| 105 |
+
value = str(obj)
|
| 106 |
+
if isinstance(obj, bool):
|
| 107 |
+
value = value.lower()
|
| 108 |
+
return value
|
| 109 |
+
return obj
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/rest_streaming.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Helpers for server-side streaming in REST."""
|
| 16 |
+
|
| 17 |
+
from typing import Union
|
| 18 |
+
|
| 19 |
+
import proto
|
| 20 |
+
import requests
|
| 21 |
+
import google.protobuf.message
|
| 22 |
+
from google.api_core._rest_streaming_base import BaseResponseIterator
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class ResponseIterator(BaseResponseIterator):
|
| 26 |
+
"""Iterator over REST API responses.
|
| 27 |
+
|
| 28 |
+
Args:
|
| 29 |
+
response (requests.Response): An API response object.
|
| 30 |
+
response_message_cls (Union[proto.Message, google.protobuf.message.Message]): A response
|
| 31 |
+
class expected to be returned from an API.
|
| 32 |
+
|
| 33 |
+
Raises:
|
| 34 |
+
ValueError:
|
| 35 |
+
- If `response_message_cls` is not a subclass of `proto.Message` or `google.protobuf.message.Message`.
|
| 36 |
+
"""
|
| 37 |
+
|
| 38 |
+
def __init__(
|
| 39 |
+
self,
|
| 40 |
+
response: requests.Response,
|
| 41 |
+
response_message_cls: Union[proto.Message, google.protobuf.message.Message],
|
| 42 |
+
):
|
| 43 |
+
self._response = response
|
| 44 |
+
# Inner iterator over HTTP response's content.
|
| 45 |
+
self._response_itr = self._response.iter_content(decode_unicode=True)
|
| 46 |
+
super(ResponseIterator, self).__init__(
|
| 47 |
+
response_message_cls=response_message_cls
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
def cancel(self):
|
| 51 |
+
"""Cancel existing streaming operation."""
|
| 52 |
+
self._response.close()
|
| 53 |
+
|
| 54 |
+
def __next__(self):
|
| 55 |
+
while not self._ready_objs:
|
| 56 |
+
try:
|
| 57 |
+
chunk = next(self._response_itr)
|
| 58 |
+
self._process_chunk(chunk)
|
| 59 |
+
except StopIteration as e:
|
| 60 |
+
if self._level > 0:
|
| 61 |
+
raise ValueError("Unfinished stream: %s" % self._obj)
|
| 62 |
+
raise e
|
| 63 |
+
return self._grab()
|
| 64 |
+
|
| 65 |
+
def __iter__(self):
|
| 66 |
+
return self
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/rest_streaming_async.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Helpers for asynchronous server-side streaming in REST."""
|
| 16 |
+
|
| 17 |
+
from typing import Union
|
| 18 |
+
|
| 19 |
+
import proto
|
| 20 |
+
|
| 21 |
+
try:
|
| 22 |
+
import google.auth.aio.transport
|
| 23 |
+
except ImportError as e: # pragma: NO COVER
|
| 24 |
+
raise ImportError(
|
| 25 |
+
"`google-api-core[async_rest]` is required to use asynchronous rest streaming. "
|
| 26 |
+
"Install the `async_rest` extra of `google-api-core` using "
|
| 27 |
+
"`pip install google-api-core[async_rest]`."
|
| 28 |
+
) from e
|
| 29 |
+
|
| 30 |
+
import google.protobuf.message
|
| 31 |
+
from google.api_core._rest_streaming_base import BaseResponseIterator
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class AsyncResponseIterator(BaseResponseIterator):
|
| 35 |
+
"""Asynchronous Iterator over REST API responses.
|
| 36 |
+
|
| 37 |
+
Args:
|
| 38 |
+
response (google.auth.aio.transport.Response): An API response object.
|
| 39 |
+
response_message_cls (Union[proto.Message, google.protobuf.message.Message]): A response
|
| 40 |
+
class expected to be returned from an API.
|
| 41 |
+
|
| 42 |
+
Raises:
|
| 43 |
+
ValueError:
|
| 44 |
+
- If `response_message_cls` is not a subclass of `proto.Message` or `google.protobuf.message.Message`.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
def __init__(
|
| 48 |
+
self,
|
| 49 |
+
response: google.auth.aio.transport.Response,
|
| 50 |
+
response_message_cls: Union[proto.Message, google.protobuf.message.Message],
|
| 51 |
+
):
|
| 52 |
+
self._response = response
|
| 53 |
+
self._chunk_size = 1024
|
| 54 |
+
# TODO(https://github.com/googleapis/python-api-core/issues/703): mypy does not recognize the abstract content
|
| 55 |
+
# method as an async generator as it looks for the `yield` keyword in the implementation.
|
| 56 |
+
# Given that the abstract method is not implemented, mypy fails to recognize it as an async generator.
|
| 57 |
+
# mypy warnings are silenced until the linked issue is resolved.
|
| 58 |
+
self._response_itr = self._response.content(self._chunk_size).__aiter__() # type: ignore
|
| 59 |
+
super(AsyncResponseIterator, self).__init__(
|
| 60 |
+
response_message_cls=response_message_cls
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
async def __aenter__(self):
|
| 64 |
+
return self
|
| 65 |
+
|
| 66 |
+
async def cancel(self):
|
| 67 |
+
"""Cancel existing streaming operation."""
|
| 68 |
+
await self._response.close()
|
| 69 |
+
|
| 70 |
+
async def __anext__(self):
|
| 71 |
+
while not self._ready_objs:
|
| 72 |
+
try:
|
| 73 |
+
chunk = await self._response_itr.__anext__()
|
| 74 |
+
chunk = chunk.decode("utf-8")
|
| 75 |
+
self._process_chunk(chunk)
|
| 76 |
+
except StopAsyncIteration as e:
|
| 77 |
+
if self._level > 0:
|
| 78 |
+
raise ValueError("i Unfinished stream: %s" % self._obj)
|
| 79 |
+
raise e
|
| 80 |
+
except ValueError as e:
|
| 81 |
+
raise e
|
| 82 |
+
return self._grab()
|
| 83 |
+
|
| 84 |
+
def __aiter__(self):
|
| 85 |
+
return self
|
| 86 |
+
|
| 87 |
+
async def __aexit__(self, exc_type, exc, tb):
|
| 88 |
+
"""Cancel existing async streaming operation."""
|
| 89 |
+
await self._response.close()
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/retry_async.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
#
|
| 15 |
+
# The following imports are for backwards compatibility with https://github.com/googleapis/python-api-core/blob/4d7d2edee2c108d43deb151e6e0fdceb56b73275/google/api_core/retry_async.py
|
| 16 |
+
#
|
| 17 |
+
# TODO: Revert these imports on the next major version release (https://github.com/googleapis/python-api-core/issues/576)
|
| 18 |
+
from google.api_core import datetime_helpers # noqa: F401
|
| 19 |
+
from google.api_core import exceptions # noqa: F401
|
| 20 |
+
from google.api_core.retry import exponential_sleep_generator # noqa: F401
|
| 21 |
+
from google.api_core.retry import if_exception_type # noqa: F401
|
| 22 |
+
from google.api_core.retry import if_transient_error # noqa: F401
|
| 23 |
+
from google.api_core.retry.retry_unary_async import AsyncRetry
|
| 24 |
+
from google.api_core.retry.retry_unary_async import retry_target
|
| 25 |
+
|
| 26 |
+
__all__ = (
|
| 27 |
+
"AsyncRetry",
|
| 28 |
+
"datetime_helpers",
|
| 29 |
+
"exceptions",
|
| 30 |
+
"exponential_sleep_generator",
|
| 31 |
+
"if_exception_type",
|
| 32 |
+
"if_transient_error",
|
| 33 |
+
"retry_target",
|
| 34 |
+
)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/timeout.py
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2017 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Decorators for applying timeout arguments to functions.
|
| 16 |
+
|
| 17 |
+
These decorators are used to wrap API methods to apply either a
|
| 18 |
+
Deadline-dependent (recommended), constant (DEPRECATED) or exponential
|
| 19 |
+
(DEPRECATED) timeout argument.
|
| 20 |
+
|
| 21 |
+
For example, imagine an API method that can take a while to return results,
|
| 22 |
+
such as one that might block until a resource is ready:
|
| 23 |
+
|
| 24 |
+
.. code-block:: python
|
| 25 |
+
|
| 26 |
+
def is_thing_ready(timeout=None):
|
| 27 |
+
response = requests.get('https://example.com/is_thing_ready')
|
| 28 |
+
response.raise_for_status()
|
| 29 |
+
return response.json()
|
| 30 |
+
|
| 31 |
+
This module allows a function like this to be wrapped so that timeouts are
|
| 32 |
+
automatically determined, for example:
|
| 33 |
+
|
| 34 |
+
.. code-block:: python
|
| 35 |
+
|
| 36 |
+
timeout_ = timeout.ExponentialTimeout()
|
| 37 |
+
is_thing_ready_with_timeout = timeout_(is_thing_ready)
|
| 38 |
+
|
| 39 |
+
for n in range(10):
|
| 40 |
+
try:
|
| 41 |
+
is_thing_ready_with_timeout({'example': 'data'})
|
| 42 |
+
except:
|
| 43 |
+
pass
|
| 44 |
+
|
| 45 |
+
In this example the first call to ``is_thing_ready`` will have a relatively
|
| 46 |
+
small timeout (like 1 second). If the resource is available and the request
|
| 47 |
+
completes quickly, the loop exits. But, if the resource isn't yet available
|
| 48 |
+
and the request times out, it'll be retried - this time with a larger timeout.
|
| 49 |
+
|
| 50 |
+
In the broader context these decorators are typically combined with
|
| 51 |
+
:mod:`google.api_core.retry` to implement API methods with a signature that
|
| 52 |
+
matches ``api_method(request, timeout=None, retry=None)``.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
from __future__ import unicode_literals
|
| 56 |
+
|
| 57 |
+
import datetime
|
| 58 |
+
import functools
|
| 59 |
+
|
| 60 |
+
from google.api_core import datetime_helpers
|
| 61 |
+
|
| 62 |
+
_DEFAULT_INITIAL_TIMEOUT = 5.0 # seconds
|
| 63 |
+
_DEFAULT_MAXIMUM_TIMEOUT = 30.0 # seconds
|
| 64 |
+
_DEFAULT_TIMEOUT_MULTIPLIER = 2.0
|
| 65 |
+
# If specified, must be in seconds. If none, deadline is not used in the
|
| 66 |
+
# timeout calculation.
|
| 67 |
+
_DEFAULT_DEADLINE = None
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class TimeToDeadlineTimeout(object):
|
| 71 |
+
"""A decorator that decreases timeout set for an RPC based on how much time
|
| 72 |
+
has left till its deadline. The deadline is calculated as
|
| 73 |
+
``now + initial_timeout`` when this decorator is first called for an rpc.
|
| 74 |
+
|
| 75 |
+
In other words this decorator implements deadline semantics in terms of a
|
| 76 |
+
sequence of decreasing timeouts t0 > t1 > t2 ... tn >= 0.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
timeout (Optional[float]): the timeout (in seconds) to applied to the
|
| 80 |
+
wrapped function. If `None`, the target function is expected to
|
| 81 |
+
never timeout.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
def __init__(self, timeout=None, clock=datetime_helpers.utcnow):
|
| 85 |
+
self._timeout = timeout
|
| 86 |
+
self._clock = clock
|
| 87 |
+
|
| 88 |
+
def __call__(self, func):
|
| 89 |
+
"""Apply the timeout decorator.
|
| 90 |
+
|
| 91 |
+
Args:
|
| 92 |
+
func (Callable): The function to apply the timeout argument to.
|
| 93 |
+
This function must accept a timeout keyword argument.
|
| 94 |
+
|
| 95 |
+
Returns:
|
| 96 |
+
Callable: The wrapped function.
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
first_attempt_timestamp = self._clock().timestamp()
|
| 100 |
+
|
| 101 |
+
@functools.wraps(func)
|
| 102 |
+
def func_with_timeout(*args, **kwargs):
|
| 103 |
+
"""Wrapped function that adds timeout."""
|
| 104 |
+
|
| 105 |
+
if self._timeout is not None:
|
| 106 |
+
# All calculations are in seconds
|
| 107 |
+
now_timestamp = self._clock().timestamp()
|
| 108 |
+
|
| 109 |
+
# To avoid usage of nonlocal but still have round timeout
|
| 110 |
+
# numbers for first attempt (in most cases the only attempt made
|
| 111 |
+
# for an RPC.
|
| 112 |
+
if now_timestamp - first_attempt_timestamp < 0.001:
|
| 113 |
+
now_timestamp = first_attempt_timestamp
|
| 114 |
+
|
| 115 |
+
time_since_first_attempt = now_timestamp - first_attempt_timestamp
|
| 116 |
+
remaining_timeout = self._timeout - time_since_first_attempt
|
| 117 |
+
|
| 118 |
+
# Although the `deadline` parameter in `google.api_core.retry.Retry`
|
| 119 |
+
# is deprecated, and should be treated the same as the `timeout`,
|
| 120 |
+
# it is still possible for the `deadline` argument in
|
| 121 |
+
# `google.api_core.retry.Retry` to be larger than the `timeout`.
|
| 122 |
+
# See https://github.com/googleapis/python-api-core/issues/654
|
| 123 |
+
# Only positive non-zero timeouts are supported.
|
| 124 |
+
# Revert back to the initial timeout for negative or 0 timeout values.
|
| 125 |
+
if remaining_timeout < 1:
|
| 126 |
+
remaining_timeout = self._timeout
|
| 127 |
+
|
| 128 |
+
kwargs["timeout"] = remaining_timeout
|
| 129 |
+
|
| 130 |
+
return func(*args, **kwargs)
|
| 131 |
+
|
| 132 |
+
return func_with_timeout
|
| 133 |
+
|
| 134 |
+
def __str__(self):
|
| 135 |
+
return "<TimeToDeadlineTimeout timeout={:.1f}>".format(self._timeout)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class ConstantTimeout(object):
|
| 139 |
+
"""A decorator that adds a constant timeout argument.
|
| 140 |
+
|
| 141 |
+
DEPRECATED: use ``TimeToDeadlineTimeout`` instead.
|
| 142 |
+
|
| 143 |
+
This is effectively equivalent to
|
| 144 |
+
``functools.partial(func, timeout=timeout)``.
|
| 145 |
+
|
| 146 |
+
Args:
|
| 147 |
+
timeout (Optional[float]): the timeout (in seconds) to applied to the
|
| 148 |
+
wrapped function. If `None`, the target function is expected to
|
| 149 |
+
never timeout.
|
| 150 |
+
"""
|
| 151 |
+
|
| 152 |
+
def __init__(self, timeout=None):
|
| 153 |
+
self._timeout = timeout
|
| 154 |
+
|
| 155 |
+
def __call__(self, func):
|
| 156 |
+
"""Apply the timeout decorator.
|
| 157 |
+
|
| 158 |
+
Args:
|
| 159 |
+
func (Callable): The function to apply the timeout argument to.
|
| 160 |
+
This function must accept a timeout keyword argument.
|
| 161 |
+
|
| 162 |
+
Returns:
|
| 163 |
+
Callable: The wrapped function.
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
@functools.wraps(func)
|
| 167 |
+
def func_with_timeout(*args, **kwargs):
|
| 168 |
+
"""Wrapped function that adds timeout."""
|
| 169 |
+
kwargs["timeout"] = self._timeout
|
| 170 |
+
return func(*args, **kwargs)
|
| 171 |
+
|
| 172 |
+
return func_with_timeout
|
| 173 |
+
|
| 174 |
+
def __str__(self):
|
| 175 |
+
return "<ConstantTimeout timeout={:.1f}>".format(self._timeout)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _exponential_timeout_generator(initial, maximum, multiplier, deadline):
|
| 179 |
+
"""A generator that yields exponential timeout values.
|
| 180 |
+
|
| 181 |
+
Args:
|
| 182 |
+
initial (float): The initial timeout.
|
| 183 |
+
maximum (float): The maximum timeout.
|
| 184 |
+
multiplier (float): The multiplier applied to the timeout.
|
| 185 |
+
deadline (float): The overall deadline across all invocations.
|
| 186 |
+
|
| 187 |
+
Yields:
|
| 188 |
+
float: A timeout value.
|
| 189 |
+
"""
|
| 190 |
+
if deadline is not None:
|
| 191 |
+
deadline_datetime = datetime_helpers.utcnow() + datetime.timedelta(
|
| 192 |
+
seconds=deadline
|
| 193 |
+
)
|
| 194 |
+
else:
|
| 195 |
+
deadline_datetime = datetime.datetime.max
|
| 196 |
+
|
| 197 |
+
timeout = initial
|
| 198 |
+
while True:
|
| 199 |
+
now = datetime_helpers.utcnow()
|
| 200 |
+
yield min(
|
| 201 |
+
# The calculated timeout based on invocations.
|
| 202 |
+
timeout,
|
| 203 |
+
# The set maximum timeout.
|
| 204 |
+
maximum,
|
| 205 |
+
# The remaining time before the deadline is reached.
|
| 206 |
+
float((deadline_datetime - now).seconds),
|
| 207 |
+
)
|
| 208 |
+
timeout = timeout * multiplier
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
class ExponentialTimeout(object):
|
| 212 |
+
"""A decorator that adds an exponentially increasing timeout argument.
|
| 213 |
+
|
| 214 |
+
DEPRECATED: the concept of incrementing timeout exponentially has been
|
| 215 |
+
deprecated. Use ``TimeToDeadlineTimeout`` instead.
|
| 216 |
+
|
| 217 |
+
This is useful if a function is called multiple times. Each time the
|
| 218 |
+
function is called this decorator will calculate a new timeout parameter
|
| 219 |
+
based on the the number of times the function has been called.
|
| 220 |
+
|
| 221 |
+
For example
|
| 222 |
+
|
| 223 |
+
.. code-block:: python
|
| 224 |
+
|
| 225 |
+
Args:
|
| 226 |
+
initial (float): The initial timeout to pass.
|
| 227 |
+
maximum (float): The maximum timeout for any one call.
|
| 228 |
+
multiplier (float): The multiplier applied to the timeout for each
|
| 229 |
+
invocation.
|
| 230 |
+
deadline (Optional[float]): The overall deadline across all
|
| 231 |
+
invocations. This is used to prevent a very large calculated
|
| 232 |
+
timeout from pushing the overall execution time over the deadline.
|
| 233 |
+
This is especially useful in conjunction with
|
| 234 |
+
:mod:`google.api_core.retry`. If ``None``, the timeouts will not
|
| 235 |
+
be adjusted to accommodate an overall deadline.
|
| 236 |
+
"""
|
| 237 |
+
|
| 238 |
+
def __init__(
|
| 239 |
+
self,
|
| 240 |
+
initial=_DEFAULT_INITIAL_TIMEOUT,
|
| 241 |
+
maximum=_DEFAULT_MAXIMUM_TIMEOUT,
|
| 242 |
+
multiplier=_DEFAULT_TIMEOUT_MULTIPLIER,
|
| 243 |
+
deadline=_DEFAULT_DEADLINE,
|
| 244 |
+
):
|
| 245 |
+
self._initial = initial
|
| 246 |
+
self._maximum = maximum
|
| 247 |
+
self._multiplier = multiplier
|
| 248 |
+
self._deadline = deadline
|
| 249 |
+
|
| 250 |
+
def with_deadline(self, deadline):
|
| 251 |
+
"""Return a copy of this timeout with the given deadline.
|
| 252 |
+
|
| 253 |
+
Args:
|
| 254 |
+
deadline (float): The overall deadline across all invocations.
|
| 255 |
+
|
| 256 |
+
Returns:
|
| 257 |
+
ExponentialTimeout: A new instance with the given deadline.
|
| 258 |
+
"""
|
| 259 |
+
return ExponentialTimeout(
|
| 260 |
+
initial=self._initial,
|
| 261 |
+
maximum=self._maximum,
|
| 262 |
+
multiplier=self._multiplier,
|
| 263 |
+
deadline=deadline,
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
def __call__(self, func):
|
| 267 |
+
"""Apply the timeout decorator.
|
| 268 |
+
|
| 269 |
+
Args:
|
| 270 |
+
func (Callable): The function to apply the timeout argument to.
|
| 271 |
+
This function must accept a timeout keyword argument.
|
| 272 |
+
|
| 273 |
+
Returns:
|
| 274 |
+
Callable: The wrapped function.
|
| 275 |
+
"""
|
| 276 |
+
timeouts = _exponential_timeout_generator(
|
| 277 |
+
self._initial, self._maximum, self._multiplier, self._deadline
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
@functools.wraps(func)
|
| 281 |
+
def func_with_timeout(*args, **kwargs):
|
| 282 |
+
"""Wrapped function that adds timeout."""
|
| 283 |
+
kwargs["timeout"] = next(timeouts)
|
| 284 |
+
return func(*args, **kwargs)
|
| 285 |
+
|
| 286 |
+
return func_with_timeout
|
| 287 |
+
|
| 288 |
+
def __str__(self):
|
| 289 |
+
return (
|
| 290 |
+
"<ExponentialTimeout initial={:.1f}, maximum={:.1f}, "
|
| 291 |
+
"multiplier={:.1f}, deadline={:.1f}>".format(
|
| 292 |
+
self._initial, self._maximum, self._multiplier, self._deadline
|
| 293 |
+
)
|
| 294 |
+
)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/universe.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Helpers for universe domain."""
|
| 16 |
+
|
| 17 |
+
from typing import Any, Optional
|
| 18 |
+
|
| 19 |
+
DEFAULT_UNIVERSE = "googleapis.com"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class EmptyUniverseError(ValueError):
|
| 23 |
+
def __init__(self):
|
| 24 |
+
message = "Universe Domain cannot be an empty string."
|
| 25 |
+
super().__init__(message)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class UniverseMismatchError(ValueError):
|
| 29 |
+
def __init__(self, client_universe, credentials_universe):
|
| 30 |
+
message = (
|
| 31 |
+
f"The configured universe domain ({client_universe}) does not match the universe domain "
|
| 32 |
+
f"found in the credentials ({credentials_universe}). "
|
| 33 |
+
"If you haven't configured the universe domain explicitly, "
|
| 34 |
+
f"`{DEFAULT_UNIVERSE}` is the default."
|
| 35 |
+
)
|
| 36 |
+
super().__init__(message)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def determine_domain(
|
| 40 |
+
client_universe_domain: Optional[str], universe_domain_env: Optional[str]
|
| 41 |
+
) -> str:
|
| 42 |
+
"""Return the universe domain used by the client.
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
client_universe_domain (Optional[str]): The universe domain configured via the client options.
|
| 46 |
+
universe_domain_env (Optional[str]): The universe domain configured via the
|
| 47 |
+
"GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable.
|
| 48 |
+
|
| 49 |
+
Returns:
|
| 50 |
+
str: The universe domain to be used by the client.
|
| 51 |
+
|
| 52 |
+
Raises:
|
| 53 |
+
ValueError: If the universe domain is an empty string.
|
| 54 |
+
"""
|
| 55 |
+
universe_domain = DEFAULT_UNIVERSE
|
| 56 |
+
if client_universe_domain is not None:
|
| 57 |
+
universe_domain = client_universe_domain
|
| 58 |
+
elif universe_domain_env is not None:
|
| 59 |
+
universe_domain = universe_domain_env
|
| 60 |
+
if len(universe_domain.strip()) == 0:
|
| 61 |
+
raise EmptyUniverseError
|
| 62 |
+
return universe_domain
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def compare_domains(client_universe: str, credentials: Any) -> bool:
|
| 66 |
+
"""Returns True iff the universe domains used by the client and credentials match.
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
client_universe (str): The universe domain configured via the client options.
|
| 70 |
+
credentials Any: The credentials being used in the client.
|
| 71 |
+
|
| 72 |
+
Returns:
|
| 73 |
+
bool: True iff client_universe matches the universe in credentials.
|
| 74 |
+
|
| 75 |
+
Raises:
|
| 76 |
+
ValueError: when client_universe does not match the universe in credentials.
|
| 77 |
+
"""
|
| 78 |
+
credentials_universe = getattr(credentials, "universe_domain", DEFAULT_UNIVERSE)
|
| 79 |
+
|
| 80 |
+
if client_universe != credentials_universe:
|
| 81 |
+
raise UniverseMismatchError(client_universe, credentials_universe)
|
| 82 |
+
return True
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/version.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
__version__ = "2.30.3"
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/api_core/version_header.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
API_VERSION_METADATA_KEY = "x-goog-api-version"
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def to_api_version_header(version_identifier):
|
| 19 |
+
"""Returns data for the API Version header for the given `version_identifier`.
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
version_identifier (str): The version identifier to be used in the
|
| 23 |
+
tuple returned.
|
| 24 |
+
|
| 25 |
+
Returns:
|
| 26 |
+
Tuple(str, str): A tuple containing the API Version metadata key and
|
| 27 |
+
value.
|
| 28 |
+
"""
|
| 29 |
+
return (API_VERSION_METADATA_KEY, version_identifier)
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/auth/__init__.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2016 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Google Auth Library for Python."""
|
| 16 |
+
|
| 17 |
+
import logging
|
| 18 |
+
|
| 19 |
+
from google.auth import version as google_auth_version
|
| 20 |
+
from google.auth._default import (
|
| 21 |
+
default,
|
| 22 |
+
load_credentials_from_dict,
|
| 23 |
+
load_credentials_from_file,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
__version__ = google_auth_version.__version__
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
__all__ = ["default", "load_credentials_from_file", "load_credentials_from_dict"]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# Set default logging handler to avoid "No handler found" warnings.
|
| 34 |
+
logging.getLogger(__name__).addHandler(logging.NullHandler())
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/auth/_agent_identity_utils.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 1 |
+
# Copyright 2025 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Helpers for Agent Identity credentials."""
|
| 16 |
+
|
| 17 |
+
import base64
|
| 18 |
+
import hashlib
|
| 19 |
+
import logging
|
| 20 |
+
import os
|
| 21 |
+
import re
|
| 22 |
+
import time
|
| 23 |
+
from urllib.parse import quote, urlparse
|
| 24 |
+
|
| 25 |
+
from google.auth import environment_vars
|
| 26 |
+
from google.auth import exceptions
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
_LOGGER = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
CRYPTOGRAPHY_NOT_FOUND_ERROR = (
|
| 32 |
+
"The cryptography library is required for certificate-based authentication."
|
| 33 |
+
"Please install it with `pip install google-auth[cryptography]`."
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
# SPIFFE trust domain patterns for Agent Identities.
|
| 37 |
+
_AGENT_IDENTITY_SPIFFE_TRUST_DOMAIN_PATTERNS = [
|
| 38 |
+
r"^agents\.global\.org-\d+\.system\.id\.goog$",
|
| 39 |
+
r"^agents\.global\.proj-\d+\.system\.id\.goog$",
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
_WELL_KNOWN_CERT_PATH = "/var/run/secrets/workload-spiffe-credentials/certificates.pem"
|
| 43 |
+
|
| 44 |
+
# Constants for polling the certificate file.
|
| 45 |
+
_FAST_POLL_CYCLES = 50
|
| 46 |
+
_FAST_POLL_INTERVAL = 0.1 # 100ms
|
| 47 |
+
_SLOW_POLL_INTERVAL = 0.5 # 500ms
|
| 48 |
+
_TOTAL_TIMEOUT = 30 # seconds
|
| 49 |
+
|
| 50 |
+
# Calculate the number of slow poll cycles based on the total timeout.
|
| 51 |
+
_SLOW_POLL_CYCLES = int(
|
| 52 |
+
(_TOTAL_TIMEOUT - (_FAST_POLL_CYCLES * _FAST_POLL_INTERVAL)) / _SLOW_POLL_INTERVAL
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
_POLLING_INTERVALS = ([_FAST_POLL_INTERVAL] * _FAST_POLL_CYCLES) + (
|
| 56 |
+
[_SLOW_POLL_INTERVAL] * _SLOW_POLL_CYCLES
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _is_certificate_file_ready(path):
|
| 61 |
+
"""Checks if a file exists and is not empty."""
|
| 62 |
+
return path and os.path.exists(path) and os.path.getsize(path) > 0
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def get_agent_identity_certificate_path():
|
| 66 |
+
"""Gets the certificate path from the certificate config file.
|
| 67 |
+
|
| 68 |
+
The path to the certificate config file is read from the
|
| 69 |
+
GOOGLE_API_CERTIFICATE_CONFIG environment variable. This function
|
| 70 |
+
implements a retry mechanism to handle cases where the environment
|
| 71 |
+
variable is set before the files are available on the filesystem.
|
| 72 |
+
|
| 73 |
+
Returns:
|
| 74 |
+
str: The path to the leaf certificate file.
|
| 75 |
+
|
| 76 |
+
Raises:
|
| 77 |
+
google.auth.exceptions.RefreshError: If the certificate config file
|
| 78 |
+
or the certificate file cannot be found after retries.
|
| 79 |
+
"""
|
| 80 |
+
import json
|
| 81 |
+
|
| 82 |
+
cert_config_path = os.environ.get(environment_vars.GOOGLE_API_CERTIFICATE_CONFIG)
|
| 83 |
+
if not cert_config_path:
|
| 84 |
+
return None
|
| 85 |
+
|
| 86 |
+
has_logged_warning = False
|
| 87 |
+
|
| 88 |
+
for interval in _POLLING_INTERVALS:
|
| 89 |
+
try:
|
| 90 |
+
with open(cert_config_path, "r") as f:
|
| 91 |
+
cert_config = json.load(f)
|
| 92 |
+
cert_path = (
|
| 93 |
+
cert_config.get("cert_configs", {})
|
| 94 |
+
.get("workload", {})
|
| 95 |
+
.get("cert_path")
|
| 96 |
+
)
|
| 97 |
+
if _is_certificate_file_ready(cert_path):
|
| 98 |
+
return cert_path
|
| 99 |
+
except (IOError, ValueError, KeyError):
|
| 100 |
+
if not has_logged_warning:
|
| 101 |
+
_LOGGER.warning(
|
| 102 |
+
"Certificate config file not found at %s (from %s environment "
|
| 103 |
+
"variable). Retrying for up to %s seconds.",
|
| 104 |
+
cert_config_path,
|
| 105 |
+
environment_vars.GOOGLE_API_CERTIFICATE_CONFIG,
|
| 106 |
+
_TOTAL_TIMEOUT,
|
| 107 |
+
)
|
| 108 |
+
has_logged_warning = True
|
| 109 |
+
pass
|
| 110 |
+
|
| 111 |
+
# As a fallback, check the well-known certificate path.
|
| 112 |
+
if _is_certificate_file_ready(_WELL_KNOWN_CERT_PATH):
|
| 113 |
+
return _WELL_KNOWN_CERT_PATH
|
| 114 |
+
|
| 115 |
+
# A sleep is required in two cases:
|
| 116 |
+
# 1. The config file is not found (the except block).
|
| 117 |
+
# 2. The config file is found, but the certificate is not yet available.
|
| 118 |
+
# In both cases, we need to poll, so we sleep on every iteration
|
| 119 |
+
# that doesn't return a certificate.
|
| 120 |
+
time.sleep(interval)
|
| 121 |
+
|
| 122 |
+
raise exceptions.RefreshError(
|
| 123 |
+
"Certificate config or certificate file not found after multiple retries. "
|
| 124 |
+
f"Token binding protection is failing. You can turn off this protection by setting "
|
| 125 |
+
f"{environment_vars.GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES} to false "
|
| 126 |
+
"to fall back to unbound tokens."
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def get_and_parse_agent_identity_certificate():
|
| 131 |
+
"""Gets and parses the agent identity certificate if not opted out.
|
| 132 |
+
|
| 133 |
+
Checks if the user has opted out of certificate-bound tokens. If not,
|
| 134 |
+
it gets the certificate path, reads the file, and parses it.
|
| 135 |
+
|
| 136 |
+
Returns:
|
| 137 |
+
The parsed certificate object if found and not opted out, otherwise None.
|
| 138 |
+
"""
|
| 139 |
+
# If the user has opted out of cert bound tokens, there is no need to
|
| 140 |
+
# look up the certificate.
|
| 141 |
+
is_opted_out = (
|
| 142 |
+
os.environ.get(
|
| 143 |
+
environment_vars.GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES,
|
| 144 |
+
"true",
|
| 145 |
+
).lower()
|
| 146 |
+
== "false"
|
| 147 |
+
)
|
| 148 |
+
if is_opted_out:
|
| 149 |
+
return None
|
| 150 |
+
|
| 151 |
+
cert_path = get_agent_identity_certificate_path()
|
| 152 |
+
if not cert_path:
|
| 153 |
+
return None
|
| 154 |
+
|
| 155 |
+
with open(cert_path, "rb") as cert_file:
|
| 156 |
+
cert_bytes = cert_file.read()
|
| 157 |
+
|
| 158 |
+
return parse_certificate(cert_bytes)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def parse_certificate(cert_bytes):
|
| 162 |
+
"""Parses a PEM-encoded certificate.
|
| 163 |
+
|
| 164 |
+
Args:
|
| 165 |
+
cert_bytes (bytes): The PEM-encoded certificate bytes.
|
| 166 |
+
|
| 167 |
+
Returns:
|
| 168 |
+
cryptography.x509.Certificate: The parsed certificate object.
|
| 169 |
+
"""
|
| 170 |
+
try:
|
| 171 |
+
from cryptography import x509
|
| 172 |
+
|
| 173 |
+
return x509.load_pem_x509_certificate(cert_bytes)
|
| 174 |
+
except ImportError as e:
|
| 175 |
+
raise ImportError(CRYPTOGRAPHY_NOT_FOUND_ERROR) from e
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def _is_agent_identity_certificate(cert):
|
| 179 |
+
"""Checks if a certificate is an Agent Identity certificate.
|
| 180 |
+
|
| 181 |
+
This is determined by checking the Subject Alternative Name (SAN) for a
|
| 182 |
+
SPIFFE ID with a trust domain matching Agent Identity patterns.
|
| 183 |
+
|
| 184 |
+
Args:
|
| 185 |
+
cert (cryptography.x509.Certificate): The parsed certificate object.
|
| 186 |
+
|
| 187 |
+
Returns:
|
| 188 |
+
bool: True if the certificate is an Agent Identity certificate,
|
| 189 |
+
False otherwise.
|
| 190 |
+
"""
|
| 191 |
+
try:
|
| 192 |
+
from cryptography import x509
|
| 193 |
+
from cryptography.x509.oid import ExtensionOID
|
| 194 |
+
|
| 195 |
+
try:
|
| 196 |
+
ext = cert.extensions.get_extension_for_oid(
|
| 197 |
+
ExtensionOID.SUBJECT_ALTERNATIVE_NAME
|
| 198 |
+
)
|
| 199 |
+
except x509.ExtensionNotFound:
|
| 200 |
+
return False
|
| 201 |
+
uris = ext.value.get_values_for_type(x509.UniformResourceIdentifier)
|
| 202 |
+
|
| 203 |
+
for uri in uris:
|
| 204 |
+
parsed_uri = urlparse(uri)
|
| 205 |
+
if parsed_uri.scheme == "spiffe":
|
| 206 |
+
trust_domain = parsed_uri.netloc
|
| 207 |
+
for pattern in _AGENT_IDENTITY_SPIFFE_TRUST_DOMAIN_PATTERNS:
|
| 208 |
+
if re.match(pattern, trust_domain):
|
| 209 |
+
return True
|
| 210 |
+
return False
|
| 211 |
+
except ImportError as e:
|
| 212 |
+
raise ImportError(CRYPTOGRAPHY_NOT_FOUND_ERROR) from e
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def calculate_certificate_fingerprint(cert):
|
| 216 |
+
"""Calculates the URL-encoded, unpadded, base64-encoded SHA256 hash of a
|
| 217 |
+
DER-encoded certificate.
|
| 218 |
+
|
| 219 |
+
Args:
|
| 220 |
+
cert (cryptography.x509.Certificate): The parsed certificate object.
|
| 221 |
+
|
| 222 |
+
Returns:
|
| 223 |
+
str: The URL-encoded, unpadded, base64-encoded SHA256 fingerprint.
|
| 224 |
+
"""
|
| 225 |
+
try:
|
| 226 |
+
from cryptography.hazmat.primitives import serialization
|
| 227 |
+
|
| 228 |
+
der_cert = cert.public_bytes(serialization.Encoding.DER)
|
| 229 |
+
fingerprint = hashlib.sha256(der_cert).digest()
|
| 230 |
+
# The certificate fingerprint is generated in two steps to align with GFE's
|
| 231 |
+
# expectations and ensure proper URL transmission:
|
| 232 |
+
# 1. Standard base64 encoding is applied, and padding ('=') is removed.
|
| 233 |
+
# 2. The resulting string is then URL-encoded to handle special characters
|
| 234 |
+
# ('+', '/') that would otherwise be misinterpreted in URL parameters.
|
| 235 |
+
base64_fingerprint = base64.b64encode(fingerprint).decode("utf-8")
|
| 236 |
+
unpadded_base64_fingerprint = base64_fingerprint.rstrip("=")
|
| 237 |
+
return quote(unpadded_base64_fingerprint)
|
| 238 |
+
except ImportError as e:
|
| 239 |
+
raise ImportError(CRYPTOGRAPHY_NOT_FOUND_ERROR) from e
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def should_request_bound_token(cert):
|
| 243 |
+
"""Determines if a bound token should be requested.
|
| 244 |
+
|
| 245 |
+
This is based on the GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES
|
| 246 |
+
environment variable and whether the certificate is an agent identity cert.
|
| 247 |
+
|
| 248 |
+
Args:
|
| 249 |
+
cert (cryptography.x509.Certificate): The parsed certificate object.
|
| 250 |
+
|
| 251 |
+
Returns:
|
| 252 |
+
bool: True if a bound token should be requested, False otherwise.
|
| 253 |
+
"""
|
| 254 |
+
is_agent_cert = _is_agent_identity_certificate(cert)
|
| 255 |
+
is_opted_in = (
|
| 256 |
+
os.environ.get(
|
| 257 |
+
environment_vars.GOOGLE_API_PREVENT_AGENT_TOKEN_SHARING_FOR_GCP_SERVICES,
|
| 258 |
+
"true",
|
| 259 |
+
).lower()
|
| 260 |
+
== "true"
|
| 261 |
+
)
|
| 262 |
+
return is_agent_cert and is_opted_in
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def get_cached_cert_fingerprint(cached_cert):
|
| 266 |
+
"""Returns the fingerprint of the cached certificate."""
|
| 267 |
+
if cached_cert:
|
| 268 |
+
cert_obj = parse_certificate(cached_cert)
|
| 269 |
+
cached_cert_fingerprint = calculate_certificate_fingerprint(cert_obj)
|
| 270 |
+
else:
|
| 271 |
+
raise ValueError("mTLS connection is not configured.")
|
| 272 |
+
return cached_cert_fingerprint
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/auth/_cache.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# https://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from collections import OrderedDict
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class LRUCache(dict):
|
| 19 |
+
def __init__(self, maxsize):
|
| 20 |
+
super().__init__()
|
| 21 |
+
self._order = OrderedDict()
|
| 22 |
+
self.maxsize = maxsize
|
| 23 |
+
|
| 24 |
+
def clear(self):
|
| 25 |
+
super().clear()
|
| 26 |
+
self._order.clear()
|
| 27 |
+
|
| 28 |
+
def get(self, key, default=None):
|
| 29 |
+
try:
|
| 30 |
+
value = super().__getitem__(key)
|
| 31 |
+
self._update(key)
|
| 32 |
+
return value
|
| 33 |
+
except KeyError:
|
| 34 |
+
return default
|
| 35 |
+
|
| 36 |
+
def __getitem__(self, key):
|
| 37 |
+
value = super().__getitem__(key)
|
| 38 |
+
self._update(key)
|
| 39 |
+
return value
|
| 40 |
+
|
| 41 |
+
def __setitem__(self, key, value):
|
| 42 |
+
maxsize = self.maxsize
|
| 43 |
+
if maxsize <= 0:
|
| 44 |
+
return
|
| 45 |
+
if key not in self:
|
| 46 |
+
while len(self) >= maxsize:
|
| 47 |
+
self.popitem()
|
| 48 |
+
super().__setitem__(key, value)
|
| 49 |
+
self._update(key)
|
| 50 |
+
|
| 51 |
+
def __delitem__(self, key):
|
| 52 |
+
super().__delitem__(key)
|
| 53 |
+
del self._order[key]
|
| 54 |
+
|
| 55 |
+
def popitem(self):
|
| 56 |
+
"""Remove and return the least recently used key-value pair."""
|
| 57 |
+
key, _ = self._order.popitem(last=False)
|
| 58 |
+
return key, super().pop(key)
|
| 59 |
+
|
| 60 |
+
def _update(self, key):
|
| 61 |
+
try:
|
| 62 |
+
self._order.move_to_end(key)
|
| 63 |
+
except KeyError:
|
| 64 |
+
self._order[key] = None
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/auth/_cloud_sdk.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2015 Google Inc.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""Helpers for reading the Google Cloud SDK's configuration."""
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import subprocess
|
| 19 |
+
|
| 20 |
+
from google.auth import _helpers
|
| 21 |
+
from google.auth import environment_vars
|
| 22 |
+
from google.auth import exceptions
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# The ~/.config subdirectory containing gcloud credentials.
|
| 26 |
+
_CONFIG_DIRECTORY = "gcloud"
|
| 27 |
+
# Windows systems store config at %APPDATA%\gcloud
|
| 28 |
+
_WINDOWS_CONFIG_ROOT_ENV_VAR = "APPDATA"
|
| 29 |
+
# The name of the file in the Cloud SDK config that contains default
|
| 30 |
+
# credentials.
|
| 31 |
+
_CREDENTIALS_FILENAME = "application_default_credentials.json"
|
| 32 |
+
# The name of the Cloud SDK shell script
|
| 33 |
+
_CLOUD_SDK_POSIX_COMMAND = "gcloud"
|
| 34 |
+
_CLOUD_SDK_WINDOWS_COMMAND = "gcloud.cmd"
|
| 35 |
+
# The command to get the Cloud SDK configuration
|
| 36 |
+
_CLOUD_SDK_CONFIG_GET_PROJECT_COMMAND = ("config", "get", "project")
|
| 37 |
+
# The command to get google user access token
|
| 38 |
+
_CLOUD_SDK_USER_ACCESS_TOKEN_COMMAND = ("auth", "print-access-token")
|
| 39 |
+
# Cloud SDK's application-default client ID
|
| 40 |
+
CLOUD_SDK_CLIENT_ID = (
|
| 41 |
+
"764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com"
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def get_config_path():
|
| 46 |
+
"""Returns the absolute path the the Cloud SDK's configuration directory.
|
| 47 |
+
|
| 48 |
+
Returns:
|
| 49 |
+
str: The Cloud SDK config path.
|
| 50 |
+
"""
|
| 51 |
+
# If the path is explicitly set, return that.
|
| 52 |
+
try:
|
| 53 |
+
return os.environ[environment_vars.CLOUD_SDK_CONFIG_DIR]
|
| 54 |
+
except KeyError:
|
| 55 |
+
pass
|
| 56 |
+
|
| 57 |
+
# Non-windows systems store this at ~/.config/gcloud
|
| 58 |
+
if os.name != "nt":
|
| 59 |
+
return os.path.join(os.path.expanduser("~"), ".config", _CONFIG_DIRECTORY)
|
| 60 |
+
# Windows systems store config at %APPDATA%\gcloud
|
| 61 |
+
else:
|
| 62 |
+
try:
|
| 63 |
+
return os.path.join(
|
| 64 |
+
os.environ[_WINDOWS_CONFIG_ROOT_ENV_VAR], _CONFIG_DIRECTORY
|
| 65 |
+
)
|
| 66 |
+
except KeyError:
|
| 67 |
+
# This should never happen unless someone is really
|
| 68 |
+
# messing with things, but we'll cover the case anyway.
|
| 69 |
+
drive = os.environ.get("SystemDrive", "C:")
|
| 70 |
+
return os.path.join(drive, "\\", _CONFIG_DIRECTORY)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def get_application_default_credentials_path():
|
| 74 |
+
"""Gets the path to the application default credentials file.
|
| 75 |
+
|
| 76 |
+
The path may or may not exist.
|
| 77 |
+
|
| 78 |
+
Returns:
|
| 79 |
+
str: The full path to application default credentials.
|
| 80 |
+
"""
|
| 81 |
+
config_path = get_config_path()
|
| 82 |
+
return os.path.join(config_path, _CREDENTIALS_FILENAME)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _run_subprocess_ignore_stderr(command):
|
| 86 |
+
"""Return subprocess.check_output with the given command and ignores stderr."""
|
| 87 |
+
with open(os.devnull, "w") as devnull:
|
| 88 |
+
output = subprocess.check_output(command, stderr=devnull)
|
| 89 |
+
return output
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def get_project_id():
|
| 93 |
+
"""Gets the project ID from the Cloud SDK.
|
| 94 |
+
|
| 95 |
+
Returns:
|
| 96 |
+
Optional[str]: The project ID.
|
| 97 |
+
"""
|
| 98 |
+
if os.name == "nt":
|
| 99 |
+
command = _CLOUD_SDK_WINDOWS_COMMAND
|
| 100 |
+
else:
|
| 101 |
+
command = _CLOUD_SDK_POSIX_COMMAND
|
| 102 |
+
|
| 103 |
+
try:
|
| 104 |
+
# Ignore the stderr coming from gcloud, so it won't be mixed into the output.
|
| 105 |
+
# https://github.com/googleapis/google-auth-library-python/issues/673
|
| 106 |
+
project = _run_subprocess_ignore_stderr(
|
| 107 |
+
(command,) + _CLOUD_SDK_CONFIG_GET_PROJECT_COMMAND
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
# Turn bytes into a string and remove "\n"
|
| 111 |
+
project = _helpers.from_bytes(project).strip()
|
| 112 |
+
return project if project else None
|
| 113 |
+
except (subprocess.CalledProcessError, OSError, IOError):
|
| 114 |
+
return None
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def get_auth_access_token(account=None):
|
| 118 |
+
"""Load user access token with the ``gcloud auth print-access-token`` command.
|
| 119 |
+
|
| 120 |
+
Args:
|
| 121 |
+
account (Optional[str]): Account to get the access token for. If not
|
| 122 |
+
specified, the current active account will be used.
|
| 123 |
+
|
| 124 |
+
Returns:
|
| 125 |
+
str: The user access token.
|
| 126 |
+
|
| 127 |
+
Raises:
|
| 128 |
+
google.auth.exceptions.UserAccessTokenError: if failed to get access
|
| 129 |
+
token from gcloud.
|
| 130 |
+
"""
|
| 131 |
+
if os.name == "nt":
|
| 132 |
+
command = _CLOUD_SDK_WINDOWS_COMMAND
|
| 133 |
+
else:
|
| 134 |
+
command = _CLOUD_SDK_POSIX_COMMAND
|
| 135 |
+
|
| 136 |
+
try:
|
| 137 |
+
if account:
|
| 138 |
+
command = (
|
| 139 |
+
(command,)
|
| 140 |
+
+ _CLOUD_SDK_USER_ACCESS_TOKEN_COMMAND
|
| 141 |
+
+ ("--account=" + account,)
|
| 142 |
+
)
|
| 143 |
+
else:
|
| 144 |
+
command = (command,) + _CLOUD_SDK_USER_ACCESS_TOKEN_COMMAND
|
| 145 |
+
|
| 146 |
+
access_token = subprocess.check_output(command, stderr=subprocess.STDOUT)
|
| 147 |
+
# remove the trailing "\n"
|
| 148 |
+
return access_token.decode("utf-8").strip()
|
| 149 |
+
except (subprocess.CalledProcessError, OSError, IOError) as caught_exc:
|
| 150 |
+
new_exc = exceptions.UserAccessTokenError(
|
| 151 |
+
"Failed to obtain access token", caught_exc
|
| 152 |
+
)
|
| 153 |
+
raise new_exc from caught_exc
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/auth/_credentials_async.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
"""Interfaces for credentials."""
|
| 17 |
+
|
| 18 |
+
import abc
|
| 19 |
+
import inspect
|
| 20 |
+
|
| 21 |
+
from google.auth import credentials
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Credentials(credentials.Credentials, metaclass=abc.ABCMeta):
|
| 25 |
+
"""Async inherited credentials class from google.auth.credentials.
|
| 26 |
+
The added functionality is the before_request call which requires
|
| 27 |
+
async/await syntax.
|
| 28 |
+
All credentials have a :attr:`token` that is used for authentication and
|
| 29 |
+
may also optionally set an :attr:`expiry` to indicate when the token will
|
| 30 |
+
no longer be valid.
|
| 31 |
+
|
| 32 |
+
Most credentials will be :attr:`invalid` until :meth:`refresh` is called.
|
| 33 |
+
Credentials can do this automatically before the first HTTP request in
|
| 34 |
+
:meth:`before_request`.
|
| 35 |
+
|
| 36 |
+
Although the token and expiration will change as the credentials are
|
| 37 |
+
:meth:`refreshed <refresh>` and used, credentials should be considered
|
| 38 |
+
immutable. Various credentials will accept configuration such as private
|
| 39 |
+
keys, scopes, and other options. These options are not changeable after
|
| 40 |
+
construction. Some classes will provide mechanisms to copy the credentials
|
| 41 |
+
with modifications such as :meth:`ScopedCredentials.with_scopes`.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
async def before_request(self, request, method, url, headers):
|
| 45 |
+
"""Performs credential-specific before request logic.
|
| 46 |
+
|
| 47 |
+
Refreshes the credentials if necessary, then calls :meth:`apply` to
|
| 48 |
+
apply the token to the authentication header.
|
| 49 |
+
|
| 50 |
+
Args:
|
| 51 |
+
request (google.auth.transport.Request): The object used to make
|
| 52 |
+
HTTP requests.
|
| 53 |
+
method (str): The request's HTTP method or the RPC method being
|
| 54 |
+
invoked.
|
| 55 |
+
url (str): The request's URI or the RPC service's URI.
|
| 56 |
+
headers (Mapping): The request's headers.
|
| 57 |
+
"""
|
| 58 |
+
# pylint: disable=unused-argument
|
| 59 |
+
# (Subclasses may use these arguments to ascertain information about
|
| 60 |
+
# the http request.)
|
| 61 |
+
|
| 62 |
+
if not self.valid:
|
| 63 |
+
if inspect.iscoroutinefunction(self.refresh):
|
| 64 |
+
await self.refresh(request)
|
| 65 |
+
else:
|
| 66 |
+
self.refresh(request)
|
| 67 |
+
self.apply(headers)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class CredentialsWithQuotaProject(credentials.CredentialsWithQuotaProject):
|
| 71 |
+
"""Abstract base for credentials supporting ``with_quota_project`` factory"""
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class AnonymousCredentials(credentials.AnonymousCredentials, Credentials):
|
| 75 |
+
"""Credentials that do not provide any authentication information.
|
| 76 |
+
|
| 77 |
+
These are useful in the case of services that support anonymous access or
|
| 78 |
+
local service emulators that do not use credentials. This class inherits
|
| 79 |
+
from the sync anonymous credentials file, but is kept if async credentials
|
| 80 |
+
is initialized and we would like anonymous credentials.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class ReadOnlyScoped(credentials.ReadOnlyScoped, metaclass=abc.ABCMeta):
|
| 85 |
+
"""Interface for credentials whose scopes can be queried.
|
| 86 |
+
|
| 87 |
+
OAuth 2.0-based credentials allow limiting access using scopes as described
|
| 88 |
+
in `RFC6749 Section 3.3`_.
|
| 89 |
+
If a credential class implements this interface then the credentials either
|
| 90 |
+
use scopes in their implementation.
|
| 91 |
+
|
| 92 |
+
Some credentials require scopes in order to obtain a token. You can check
|
| 93 |
+
if scoping is necessary with :attr:`requires_scopes`::
|
| 94 |
+
|
| 95 |
+
if credentials.requires_scopes:
|
| 96 |
+
# Scoping is required.
|
| 97 |
+
credentials = _credentials_async.with_scopes(scopes=['one', 'two'])
|
| 98 |
+
|
| 99 |
+
Credentials that require scopes must either be constructed with scopes::
|
| 100 |
+
|
| 101 |
+
credentials = SomeScopedCredentials(scopes=['one', 'two'])
|
| 102 |
+
|
| 103 |
+
Or must copy an existing instance using :meth:`with_scopes`::
|
| 104 |
+
|
| 105 |
+
scoped_credentials = _credentials_async.with_scopes(scopes=['one', 'two'])
|
| 106 |
+
|
| 107 |
+
Some credentials have scopes but do not allow or require scopes to be set,
|
| 108 |
+
these credentials can be used as-is.
|
| 109 |
+
|
| 110 |
+
.. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class Scoped(credentials.Scoped):
|
| 115 |
+
"""Interface for credentials whose scopes can be replaced while copying.
|
| 116 |
+
|
| 117 |
+
OAuth 2.0-based credentials allow limiting access using scopes as described
|
| 118 |
+
in `RFC6749 Section 3.3`_.
|
| 119 |
+
If a credential class implements this interface then the credentials either
|
| 120 |
+
use scopes in their implementation.
|
| 121 |
+
|
| 122 |
+
Some credentials require scopes in order to obtain a token. You can check
|
| 123 |
+
if scoping is necessary with :attr:`requires_scopes`::
|
| 124 |
+
|
| 125 |
+
if credentials.requires_scopes:
|
| 126 |
+
# Scoping is required.
|
| 127 |
+
credentials = _credentials_async.create_scoped(['one', 'two'])
|
| 128 |
+
|
| 129 |
+
Credentials that require scopes must either be constructed with scopes::
|
| 130 |
+
|
| 131 |
+
credentials = SomeScopedCredentials(scopes=['one', 'two'])
|
| 132 |
+
|
| 133 |
+
Or must copy an existing instance using :meth:`with_scopes`::
|
| 134 |
+
|
| 135 |
+
scoped_credentials = credentials.with_scopes(scopes=['one', 'two'])
|
| 136 |
+
|
| 137 |
+
Some credentials have scopes but do not allow or require scopes to be set,
|
| 138 |
+
these credentials can be used as-is.
|
| 139 |
+
|
| 140 |
+
.. _RFC6749 Section 3.3: https://tools.ietf.org/html/rfc6749#section-3.3
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def with_scopes_if_required(credentials, scopes):
|
| 145 |
+
"""Creates a copy of the credentials with scopes if scoping is required.
|
| 146 |
+
|
| 147 |
+
This helper function is useful when you do not know (or care to know) the
|
| 148 |
+
specific type of credentials you are using (such as when you use
|
| 149 |
+
:func:`google.auth.default`). This function will call
|
| 150 |
+
:meth:`Scoped.with_scopes` if the credentials are scoped credentials and if
|
| 151 |
+
the credentials require scoping. Otherwise, it will return the credentials
|
| 152 |
+
as-is.
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
credentials (google.auth.credentials.Credentials): The credentials to
|
| 156 |
+
scope if necessary.
|
| 157 |
+
scopes (Sequence[str]): The list of scopes to use.
|
| 158 |
+
|
| 159 |
+
Returns:
|
| 160 |
+
google.auth._credentials_async.Credentials: Either a new set of scoped
|
| 161 |
+
credentials, or the passed in credentials instance if no scoping
|
| 162 |
+
was required.
|
| 163 |
+
"""
|
| 164 |
+
if isinstance(credentials, Scoped) and credentials.requires_scopes:
|
| 165 |
+
return credentials.with_scopes(scopes)
|
| 166 |
+
else:
|
| 167 |
+
return credentials
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class Signing(credentials.Signing, metaclass=abc.ABCMeta):
|
| 171 |
+
"""Interface for credentials that can cryptographically sign messages."""
|
data/tefig/envs/olmes-eval/lib/python3.10/site-packages/google/auth/_credentials_base.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024 Google LLC
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
"""Interface for base credentials."""
|
| 17 |
+
|
| 18 |
+
import abc
|
| 19 |
+
|
| 20 |
+
from google.auth import _helpers
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class _BaseCredentials(metaclass=abc.ABCMeta):
|
| 24 |
+
"""Base class for all credentials.
|
| 25 |
+
|
| 26 |
+
All credentials have a :attr:`token` that is used for authentication and
|
| 27 |
+
may also optionally set an :attr:`expiry` to indicate when the token will
|
| 28 |
+
no longer be valid.
|
| 29 |
+
|
| 30 |
+
Most credentials will be :attr:`invalid` until :meth:`refresh` is called.
|
| 31 |
+
Credentials can do this automatically before the first HTTP request in
|
| 32 |
+
:meth:`before_request`.
|
| 33 |
+
|
| 34 |
+
Although the token and expiration will change as the credentials are
|
| 35 |
+
:meth:`refreshed <refresh>` and used, credentials should be considered
|
| 36 |
+
immutable. Various credentials will accept configuration such as private
|
| 37 |
+
keys, scopes, and other options. These options are not changeable after
|
| 38 |
+
construction. Some classes will provide mechanisms to copy the credentials
|
| 39 |
+
with modifications such as :meth:`ScopedCredentials.with_scopes`.
|
| 40 |
+
|
| 41 |
+
Attributes:
|
| 42 |
+
token (Optional[str]): The bearer token that can be used in HTTP headers to make
|
| 43 |
+
authenticated requests.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
def __init__(self):
|
| 47 |
+
self.token = None
|
| 48 |
+
|
| 49 |
+
@abc.abstractmethod
|
| 50 |
+
def refresh(self, request):
|
| 51 |
+
"""Refreshes the access token.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
request (google.auth.transport.Request): The object used to make
|
| 55 |
+
HTTP requests.
|
| 56 |
+
|
| 57 |
+
Raises:
|
| 58 |
+
google.auth.exceptions.RefreshError: If the credentials could
|
| 59 |
+
not be refreshed.
|
| 60 |
+
"""
|
| 61 |
+
# pylint: disable=missing-raises-doc
|
| 62 |
+
# (pylint doesn't recognize that this is abstract)
|
| 63 |
+
raise NotImplementedError("Refresh must be implemented")
|
| 64 |
+
|
| 65 |
+
def _apply(self, headers, token=None):
|
| 66 |
+
"""Apply the token to the authentication header.
|
| 67 |
+
|
| 68 |
+
Args:
|
| 69 |
+
headers (Mapping): The HTTP request headers.
|
| 70 |
+
token (Optional[str]): If specified, overrides the current access
|
| 71 |
+
token.
|
| 72 |
+
"""
|
| 73 |
+
headers["authorization"] = "Bearer {}".format(
|
| 74 |
+
_helpers.from_bytes(token or self.token)
|
| 75 |
+
)
|