File manager - Edit - /home/newsbmcs.com/public_html/static/img/logo/api_core.zip
Back
PK ��Z���% �% timeout.pynu �[��� # Copyright 2017 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Decorators for applying timeout arguments to functions. These decorators are used to wrap API methods to apply either a Deadline-dependent (recommended), constant (DEPRECATED) or exponential (DEPRECATED) timeout argument. For example, imagine an API method that can take a while to return results, such as one that might block until a resource is ready: .. code-block:: python def is_thing_ready(timeout=None): response = requests.get('https://example.com/is_thing_ready') response.raise_for_status() return response.json() This module allows a function like this to be wrapped so that timeouts are automatically determined, for example: .. code-block:: python timeout_ = timeout.ExponentialTimeout() is_thing_ready_with_timeout = timeout_(is_thing_ready) for n in range(10): try: is_thing_ready_with_timeout({'example': 'data'}) except: pass In this example the first call to ``is_thing_ready`` will have a relatively small timeout (like 1 second). If the resource is available and the request completes quickly, the loop exits. But, if the resource isn't yet available and the request times out, it'll be retried - this time with a larger timeout. In the broader context these decorators are typically combined with :mod:`google.api_core.retry` to implement API methods with a signature that matches ``api_method(request, timeout=None, retry=None)``. """ from __future__ import unicode_literals import datetime import functools from google.api_core import datetime_helpers _DEFAULT_INITIAL_TIMEOUT = 5.0 # seconds _DEFAULT_MAXIMUM_TIMEOUT = 30.0 # seconds _DEFAULT_TIMEOUT_MULTIPLIER = 2.0 # If specified, must be in seconds. If none, deadline is not used in the # timeout calculation. _DEFAULT_DEADLINE = None class TimeToDeadlineTimeout(object): """A decorator that decreases timeout set for an RPC based on how much time has left till its deadline. The deadline is calculated as ``now + initial_timeout`` when this decorator is first called for an rpc. In other words this decorator implements deadline semantics in terms of a sequence of decreasing timeouts t0 > t1 > t2 ... tn >= 0. Args: timeout (Optional[float]): the timeout (in seconds) to applied to the wrapped function. If `None`, the target function is expected to never timeout. """ def __init__(self, timeout=None, clock=datetime_helpers.utcnow): self._timeout = timeout self._clock = clock def __call__(self, func): """Apply the timeout decorator. Args: func (Callable): The function to apply the timeout argument to. This function must accept a timeout keyword argument. Returns: Callable: The wrapped function. """ first_attempt_timestamp = self._clock().timestamp() @functools.wraps(func) def func_with_timeout(*args, **kwargs): """Wrapped function that adds timeout.""" remaining_timeout = self._timeout if remaining_timeout is not None: # All calculations are in seconds now_timestamp = self._clock().timestamp() # To avoid usage of nonlocal but still have round timeout # numbers for first attempt (in most cases the only attempt made # for an RPC. if now_timestamp - first_attempt_timestamp < 0.001: now_timestamp = first_attempt_timestamp time_since_first_attempt = now_timestamp - first_attempt_timestamp # Avoid setting negative timeout kwargs["timeout"] = max(0, self._timeout - time_since_first_attempt) return func(*args, **kwargs) return func_with_timeout def __str__(self): return "<TimeToDeadlineTimeout timeout={:.1f}>".format(self._timeout) class ConstantTimeout(object): """A decorator that adds a constant timeout argument. DEPRECATED: use ``TimeToDeadlineTimeout`` instead. This is effectively equivalent to ``functools.partial(func, timeout=timeout)``. Args: timeout (Optional[float]): the timeout (in seconds) to applied to the wrapped function. If `None`, the target function is expected to never timeout. """ def __init__(self, timeout=None): self._timeout = timeout def __call__(self, func): """Apply the timeout decorator. Args: func (Callable): The function to apply the timeout argument to. This function must accept a timeout keyword argument. Returns: Callable: The wrapped function. """ @functools.wraps(func) def func_with_timeout(*args, **kwargs): """Wrapped function that adds timeout.""" kwargs["timeout"] = self._timeout return func(*args, **kwargs) return func_with_timeout def __str__(self): return "<ConstantTimeout timeout={:.1f}>".format(self._timeout) def _exponential_timeout_generator(initial, maximum, multiplier, deadline): """A generator that yields exponential timeout values. Args: initial (float): The initial timeout. maximum (float): The maximum timeout. multiplier (float): The multiplier applied to the timeout. deadline (float): The overall deadline across all invocations. Yields: float: A timeout value. """ if deadline is not None: deadline_datetime = datetime_helpers.utcnow() + datetime.timedelta( seconds=deadline ) else: deadline_datetime = datetime.datetime.max timeout = initial while True: now = datetime_helpers.utcnow() yield min( # The calculated timeout based on invocations. timeout, # The set maximum timeout. maximum, # The remaining time before the deadline is reached. float((deadline_datetime - now).seconds), ) timeout = timeout * multiplier class ExponentialTimeout(object): """A decorator that adds an exponentially increasing timeout argument. DEPRECATED: the concept of incrementing timeout exponentially has been deprecated. Use ``TimeToDeadlineTimeout`` instead. This is useful if a function is called multiple times. Each time the function is called this decorator will calculate a new timeout parameter based on the the number of times the function has been called. For example .. code-block:: python Args: initial (float): The initial timeout to pass. maximum (float): The maximum timeout for any one call. multiplier (float): The multiplier applied to the timeout for each invocation. deadline (Optional[float]): The overall deadline across all invocations. This is used to prevent a very large calculated timeout from pushing the overall execution time over the deadline. This is especially useful in conjunction with :mod:`google.api_core.retry`. If ``None``, the timeouts will not be adjusted to accommodate an overall deadline. """ def __init__( self, initial=_DEFAULT_INITIAL_TIMEOUT, maximum=_DEFAULT_MAXIMUM_TIMEOUT, multiplier=_DEFAULT_TIMEOUT_MULTIPLIER, deadline=_DEFAULT_DEADLINE, ): self._initial = initial self._maximum = maximum self._multiplier = multiplier self._deadline = deadline def with_deadline(self, deadline): """Return a copy of this timeout with the given deadline. Args: deadline (float): The overall deadline across all invocations. Returns: ExponentialTimeout: A new instance with the given deadline. """ return ExponentialTimeout( initial=self._initial, maximum=self._maximum, multiplier=self._multiplier, deadline=deadline, ) def __call__(self, func): """Apply the timeout decorator. Args: func (Callable): The function to apply the timeout argument to. This function must accept a timeout keyword argument. Returns: Callable: The wrapped function. """ timeouts = _exponential_timeout_generator( self._initial, self._maximum, self._multiplier, self._deadline ) @functools.wraps(func) def func_with_timeout(*args, **kwargs): """Wrapped function that adds timeout.""" kwargs["timeout"] = next(timeouts) return func(*args, **kwargs) return func_with_timeout def __str__(self): return ( "<ExponentialTimeout initial={:.1f}, maximum={:.1f}, " "multiplier={:.1f}, deadline={:.1f}>".format( self._initial, self._maximum, self._multiplier, self._deadline ) ) PK ��Z���n n operation_async.pynu �[��� # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """AsyncIO futures for long-running operations returned from Google Cloud APIs. These futures can be used to await for the result of a long-running operation using :meth:`AsyncOperation.result`: .. code-block:: python operation = my_api_client.long_running_method() result = await operation.result() Or asynchronously using callbacks and :meth:`Operation.add_done_callback`: .. code-block:: python operation = my_api_client.long_running_method() def my_callback(future): result = await future.result() operation.add_done_callback(my_callback) """ import functools import threading from google.api_core import exceptions from google.api_core import protobuf_helpers from google.api_core.future import async_future from google.longrunning import operations_pb2 from google.rpc import code_pb2 class AsyncOperation(async_future.AsyncFuture): """A Future for interacting with a Google API Long-Running Operation. Args: operation (google.longrunning.operations_pb2.Operation): The initial operation. refresh (Callable[[], ~.api_core.operation.Operation]): A callable that returns the latest state of the operation. cancel (Callable[[], None]): A callable that tries to cancel the operation. result_type (func:`type`): The protobuf type for the operation's result. metadata_type (func:`type`): The protobuf type for the operation's metadata. retry (google.api_core.retry.Retry): The retry configuration used when polling. This can be used to control how often :meth:`done` is polled. Regardless of the retry's ``deadline``, it will be overridden by the ``timeout`` argument to :meth:`result`. """ def __init__( self, operation, refresh, cancel, result_type, metadata_type=None, retry=async_future.DEFAULT_RETRY, ): super().__init__(retry=retry) self._operation = operation self._refresh = refresh self._cancel = cancel self._result_type = result_type self._metadata_type = metadata_type self._completion_lock = threading.Lock() # Invoke this in case the operation came back already complete. self._set_result_from_operation() @property def operation(self): """google.longrunning.Operation: The current long-running operation.""" return self._operation @property def metadata(self): """google.protobuf.Message: the current operation metadata.""" if not self._operation.HasField("metadata"): return None return protobuf_helpers.from_any_pb( self._metadata_type, self._operation.metadata ) @classmethod def deserialize(cls, payload): """Deserialize a ``google.longrunning.Operation`` protocol buffer. Args: payload (bytes): A serialized operation protocol buffer. Returns: ~.operations_pb2.Operation: An Operation protobuf object. """ return operations_pb2.Operation.FromString(payload) def _set_result_from_operation(self): """Set the result or exception from the operation if it is complete.""" # This must be done in a lock to prevent the async_future thread # and main thread from both executing the completion logic # at the same time. with self._completion_lock: # If the operation isn't complete or if the result has already been # set, do not call set_result/set_exception again. if not self._operation.done or self._future.done(): return if self._operation.HasField("response"): response = protobuf_helpers.from_any_pb( self._result_type, self._operation.response ) self.set_result(response) elif self._operation.HasField("error"): exception = exceptions.GoogleAPICallError( self._operation.error.message, errors=(self._operation.error,), response=self._operation, ) self.set_exception(exception) else: exception = exceptions.GoogleAPICallError( "Unexpected state: Long-running operation had neither " "response nor error set." ) self.set_exception(exception) async def _refresh_and_update(self, retry=async_future.DEFAULT_RETRY): """Refresh the operation and update the result if needed. Args: retry (google.api_core.retry.Retry): (Optional) How to retry the RPC. """ # If the currently cached operation is done, no need to make another # RPC as it will not change once done. if not self._operation.done: self._operation = await self._refresh(retry=retry) self._set_result_from_operation() async def done(self, retry=async_future.DEFAULT_RETRY): """Checks to see if the operation is complete. Args: retry (google.api_core.retry.Retry): (Optional) How to retry the RPC. Returns: bool: True if the operation is complete, False otherwise. """ await self._refresh_and_update(retry) return self._operation.done async def cancel(self): """Attempt to cancel the operation. Returns: bool: True if the cancel RPC was made, False if the operation is already complete. """ result = await self.done() if result: return False else: await self._cancel() return True async def cancelled(self): """True if the operation was cancelled.""" await self._refresh_and_update() return ( self._operation.HasField("error") and self._operation.error.code == code_pb2.CANCELLED ) def from_gapic(operation, operations_client, result_type, grpc_metadata=None, **kwargs): """Create an operation future from a gapic client. This interacts with the long-running operations `service`_ (specific to a given API) via a gapic client. .. _service: https://github.com/googleapis/googleapis/blob/\ 050400df0fdb16f63b63e9dee53819044bffc857/\ google/longrunning/operations.proto#L38 Args: operation (google.longrunning.operations_pb2.Operation): The operation. operations_client (google.api_core.operations_v1.OperationsClient): The operations client. result_type (:func:`type`): The protobuf result type. grpc_metadata (Optional[List[Tuple[str, str]]]): Additional metadata to pass to the rpc. kwargs: Keyword args passed into the :class:`Operation` constructor. Returns: ~.api_core.operation.Operation: The operation future to track the given operation. """ refresh = functools.partial( operations_client.get_operation, operation.name, metadata=grpc_metadata, ) cancel = functools.partial( operations_client.cancel_operation, operation.name, metadata=grpc_metadata, ) return AsyncOperation(operation, refresh, cancel, result_type, **kwargs) PK ��Z}��W�! �! extended_operation.pynu �[��� # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Futures for extended long-running operations returned from Google Cloud APIs. These futures can be used to synchronously wait for the result of a long-running operations using :meth:`ExtendedOperation.result`: .. code-block:: python extended_operation = my_api_client.long_running_method() extended_operation.result() Or asynchronously using callbacks and :meth:`Operation.add_done_callback`: .. code-block:: python extended_operation = my_api_client.long_running_method() def my_callback(ex_op): print(f"Operation {ex_op.name} completed") extended_operation.add_done_callback(my_callback) """ import threading from google.api_core import exceptions from google.api_core.future import polling class ExtendedOperation(polling.PollingFuture): """An ExtendedOperation future for interacting with a Google API Long-Running Operation. Args: extended_operation (proto.Message): The initial operation. refresh (Callable[[], type(extended_operation)]): A callable that returns the latest state of the operation. cancel (Callable[[], None]): A callable that tries to cancel the operation. polling Optional(google.api_core.retry.Retry): The configuration used for polling. This can be used to control how often :meth:`done` is polled. If the ``timeout`` argument to :meth:`result` is specified it will override the ``polling.timeout`` property. retry Optional(google.api_core.retry.Retry): DEPRECATED use ``polling`` instead. If specified it will override ``polling`` parameter to maintain backward compatibility. Note: Most long-running API methods use google.api_core.operation.Operation This class is a wrapper for a subset of methods that use alternative Long-Running Operation (LRO) semantics. Note: there is not a concrete type the extended operation must be. It MUST have fields that correspond to the following, POSSIBLY WITH DIFFERENT NAMES: * name: str * status: Union[str, bool, enum.Enum] * error_code: int * error_message: str """ def __init__( self, extended_operation, refresh, cancel, polling=polling.DEFAULT_POLLING, **kwargs, ): super().__init__(polling=polling, **kwargs) self._extended_operation = extended_operation self._refresh = refresh self._cancel = cancel # Note: the extended operation does not give a good way to indicate cancellation. # We make do with manually tracking cancellation and checking for doneness. self._cancelled = False self._completion_lock = threading.Lock() # Invoke in case the operation came back already complete. self._handle_refreshed_operation() # Note: the following four properties MUST be overridden in a subclass # if, and only if, the fields in the corresponding extended operation message # have different names. # # E.g. we have an extended operation class that looks like # # class MyOperation(proto.Message): # moniker = proto.Field(proto.STRING, number=1) # status_msg = proto.Field(proto.STRING, number=2) # optional http_error_code = proto.Field(proto.INT32, number=3) # optional http_error_msg = proto.Field(proto.STRING, number=4) # # the ExtendedOperation subclass would provide property overrides that map # to these (poorly named) fields. @property def name(self): return self._extended_operation.name @property def status(self): return self._extended_operation.status @property def error_code(self): return self._extended_operation.error_code @property def error_message(self): return self._extended_operation.error_message def __getattr__(self, name): return getattr(self._extended_operation, name) def done(self, retry=None): self._refresh_and_update(retry) return self._extended_operation.done def cancel(self): if self.done(): return False self._cancel() self._cancelled = True return True def cancelled(self): # TODO(dovs): there is not currently a good way to determine whether the # operation has been cancelled. # The best we can do is manually keep track of cancellation # and check for doneness. if not self._cancelled: return False self._refresh_and_update() return self._extended_operation.done def _refresh_and_update(self, retry=None): if not self._extended_operation.done: self._extended_operation = ( self._refresh(retry=retry) if retry else self._refresh() ) self._handle_refreshed_operation() def _handle_refreshed_operation(self): with self._completion_lock: if not self._extended_operation.done: return if self.error_code and self.error_message: # Note: `errors` can be removed once proposal A from # b/284179390 is implemented. errors = [] if hasattr(self, "error") and hasattr(self.error, "errors"): errors = self.error.errors exception = exceptions.from_http_status( status_code=self.error_code, message=self.error_message, response=self._extended_operation, errors=errors, ) self.set_exception(exception) elif self.error_code or self.error_message: exception = exceptions.GoogleAPICallError( f"Unexpected error {self.error_code}: {self.error_message}" ) self.set_exception(exception) else: # Extended operations have no payload. self.set_result(None) @classmethod def make(cls, refresh, cancel, extended_operation, **kwargs): """ Return an instantiated ExtendedOperation (or child) that wraps * a refresh callable * a cancel callable (can be a no-op) * an initial result .. note:: It is the caller's responsibility to set up refresh and cancel with their correct request argument. The reason for this is that the services that use Extended Operations have rpcs that look something like the following: // service.proto service MyLongService { rpc StartLongTask(StartLongTaskRequest) returns (ExtendedOperation) { option (google.cloud.operation_service) = "CustomOperationService"; } } service CustomOperationService { rpc Get(GetOperationRequest) returns (ExtendedOperation) { option (google.cloud.operation_polling_method) = true; } } Any info needed for the poll, e.g. a name, path params, etc. is held in the request, which the initial client method is in a much better position to make made because the caller made the initial request. TL;DR: the caller sets up closures for refresh and cancel that carry the properly configured requests. Args: refresh (Callable[Optional[Retry]][type(extended_operation)]): A callable that returns the latest state of the operation. cancel (Callable[][Any]): A callable that tries to cancel the operation on a best effort basis. extended_operation (Any): The initial response of the long running method. See the docstring for ExtendedOperation.__init__ for requirements on the type and fields of extended_operation """ return cls(extended_operation, refresh, cancel, **kwargs) PK ��Z�ߩ�3 �3 iam.pynu �[��� # Copyright 2017 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Non-API-specific IAM policy definitions For allowed roles / permissions, see: https://cloud.google.com/iam/docs/understanding-roles Example usage: .. code-block:: python # ``get_iam_policy`` returns a :class:'~google.api_core.iam.Policy`. policy = resource.get_iam_policy(requested_policy_version=3) phred = "user:phred@example.com" admin_group = "group:admins@groups.example.com" account = "serviceAccount:account-1234@accounts.example.com" policy.version = 3 policy.bindings = [ { "role": "roles/owner", "members": {phred, admin_group, account} }, { "role": "roles/editor", "members": {"allAuthenticatedUsers"} }, { "role": "roles/viewer", "members": {"allUsers"} "condition": { "title": "request_time", "description": "Requests made before 2021-01-01T00:00:00Z", "expression": "request.time < timestamp(\"2021-01-01T00:00:00Z\")" } } ] resource.set_iam_policy(policy) """ import collections import collections.abc import operator import warnings # Generic IAM roles OWNER_ROLE = "roles/owner" """Generic role implying all rights to an object.""" EDITOR_ROLE = "roles/editor" """Generic role implying rights to modify an object.""" VIEWER_ROLE = "roles/viewer" """Generic role implying rights to access an object.""" _ASSIGNMENT_DEPRECATED_MSG = """\ Assigning to '{}' is deprecated. Use the `policy.bindings` property to modify bindings instead.""" _DICT_ACCESS_MSG = """\ Dict access is not supported on policies with version > 1 or with conditional bindings.""" class InvalidOperationException(Exception): """Raised when trying to use Policy class as a dict.""" pass class Policy(collections.abc.MutableMapping): """IAM Policy Args: etag (Optional[str]): ETag used to identify a unique of the policy version (Optional[int]): The syntax schema version of the policy. Note: Using conditions in bindings requires the policy's version to be set to `3` or greater, depending on the versions that are currently supported. Accessing the policy using dict operations will raise InvalidOperationException when the policy's version is set to 3. Use the policy.bindings getter/setter to retrieve and modify the policy's bindings. See: IAM Policy https://cloud.google.com/iam/reference/rest/v1/Policy Policy versions https://cloud.google.com/iam/docs/policies#versions Conditions overview https://cloud.google.com/iam/docs/conditions-overview. """ _OWNER_ROLES = (OWNER_ROLE,) """Roles mapped onto our ``owners`` attribute.""" _EDITOR_ROLES = (EDITOR_ROLE,) """Roles mapped onto our ``editors`` attribute.""" _VIEWER_ROLES = (VIEWER_ROLE,) """Roles mapped onto our ``viewers`` attribute.""" def __init__(self, etag=None, version=None): self.etag = etag self.version = version self._bindings = [] def __iter__(self): self.__check_version__() # Exclude bindings with no members return (binding["role"] for binding in self._bindings if binding["members"]) def __len__(self): self.__check_version__() # Exclude bindings with no members return len(list(self.__iter__())) def __getitem__(self, key): self.__check_version__() for b in self._bindings: if b["role"] == key: return b["members"] # If the binding does not yet exist, create one # NOTE: This will create bindings with no members # which are ignored by __iter__ and __len__ new_binding = {"role": key, "members": set()} self._bindings.append(new_binding) return new_binding["members"] def __setitem__(self, key, value): self.__check_version__() value = set(value) for binding in self._bindings: if binding["role"] == key: binding["members"] = value return self._bindings.append({"role": key, "members": value}) def __delitem__(self, key): self.__check_version__() for b in self._bindings: if b["role"] == key: self._bindings.remove(b) return raise KeyError(key) def __check_version__(self): """Raise InvalidOperationException if version is greater than 1 or policy contains conditions.""" raise_version = self.version is not None and self.version > 1 if raise_version or self._contains_conditions(): raise InvalidOperationException(_DICT_ACCESS_MSG) def _contains_conditions(self): for b in self._bindings: if b.get("condition") is not None: return True return False @property def bindings(self): """The policy's list of bindings. A binding is specified by a dictionary with keys: * role (str): Role that is assigned to `members`. * members (:obj:`set` of str): Specifies the identities associated to this binding. * condition (:obj:`dict` of str:str): Specifies a condition under which this binding will apply. * title (str): Title for the condition. * description (:obj:str, optional): Description of the condition. * expression: A CEL expression. Type: :obj:`list` of :obj:`dict` See: Policy versions https://cloud.google.com/iam/docs/policies#versions Conditions overview https://cloud.google.com/iam/docs/conditions-overview. Example: .. code-block:: python USER = "user:phred@example.com" ADMIN_GROUP = "group:admins@groups.example.com" SERVICE_ACCOUNT = "serviceAccount:account-1234@accounts.example.com" CONDITION = { "title": "request_time", "description": "Requests made before 2021-01-01T00:00:00Z", # Optional "expression": "request.time < timestamp(\"2021-01-01T00:00:00Z\")" } # Set policy's version to 3 before setting bindings containing conditions. policy.version = 3 policy.bindings = [ { "role": "roles/viewer", "members": {USER, ADMIN_GROUP, SERVICE_ACCOUNT}, "condition": CONDITION }, ... ] """ return self._bindings @bindings.setter def bindings(self, bindings): self._bindings = bindings @property def owners(self): """Legacy access to owner role. Raise InvalidOperationException if version is greater than 1 or policy contains conditions. DEPRECATED: use `policy.bindings` to access bindings instead. """ result = set() for role in self._OWNER_ROLES: for member in self.get(role, ()): result.add(member) return frozenset(result) @owners.setter def owners(self, value): """Update owners. Raise InvalidOperationException if version is greater than 1 or policy contains conditions. DEPRECATED: use `policy.bindings` to access bindings instead. """ warnings.warn( _ASSIGNMENT_DEPRECATED_MSG.format("owners", OWNER_ROLE), DeprecationWarning ) self[OWNER_ROLE] = value @property def editors(self): """Legacy access to editor role. Raise InvalidOperationException if version is greater than 1 or policy contains conditions. DEPRECATED: use `policy.bindings` to access bindings instead. """ result = set() for role in self._EDITOR_ROLES: for member in self.get(role, ()): result.add(member) return frozenset(result) @editors.setter def editors(self, value): """Update editors. Raise InvalidOperationException if version is greater than 1 or policy contains conditions. DEPRECATED: use `policy.bindings` to modify bindings instead. """ warnings.warn( _ASSIGNMENT_DEPRECATED_MSG.format("editors", EDITOR_ROLE), DeprecationWarning, ) self[EDITOR_ROLE] = value @property def viewers(self): """Legacy access to viewer role. Raise InvalidOperationException if version is greater than 1 or policy contains conditions. DEPRECATED: use `policy.bindings` to modify bindings instead. """ result = set() for role in self._VIEWER_ROLES: for member in self.get(role, ()): result.add(member) return frozenset(result) @viewers.setter def viewers(self, value): """Update viewers. Raise InvalidOperationException if version is greater than 1 or policy contains conditions. DEPRECATED: use `policy.bindings` to modify bindings instead. """ warnings.warn( _ASSIGNMENT_DEPRECATED_MSG.format("viewers", VIEWER_ROLE), DeprecationWarning, ) self[VIEWER_ROLE] = value @staticmethod def user(email): """Factory method for a user member. Args: email (str): E-mail for this particular user. Returns: str: A member string corresponding to the given user. """ return "user:%s" % (email,) @staticmethod def service_account(email): """Factory method for a service account member. Args: email (str): E-mail for this particular service account. Returns: str: A member string corresponding to the given service account. """ return "serviceAccount:%s" % (email,) @staticmethod def group(email): """Factory method for a group member. Args: email (str): An id or e-mail for this particular group. Returns: str: A member string corresponding to the given group. """ return "group:%s" % (email,) @staticmethod def domain(domain): """Factory method for a domain member. Args: domain (str): The domain for this member. Returns: str: A member string corresponding to the given domain. """ return "domain:%s" % (domain,) @staticmethod def all_users(): """Factory method for a member representing all users. Returns: str: A member string representing all users. """ return "allUsers" @staticmethod def authenticated_users(): """Factory method for a member representing all authenticated users. Returns: str: A member string representing all authenticated users. """ return "allAuthenticatedUsers" @classmethod def from_api_repr(cls, resource): """Factory: create a policy from a JSON resource. Args: resource (dict): policy resource returned by ``getIamPolicy`` API. Returns: :class:`Policy`: the parsed policy """ version = resource.get("version") etag = resource.get("etag") policy = cls(etag, version) policy.bindings = resource.get("bindings", []) for binding in policy.bindings: binding["members"] = set(binding.get("members", ())) return policy def to_api_repr(self): """Render a JSON policy resource. Returns: dict: a resource to be passed to the ``setIamPolicy`` API. """ resource = {} if self.etag is not None: resource["etag"] = self.etag if self.version is not None: resource["version"] = self.version if self._bindings and len(self._bindings) > 0: bindings = [] for binding in self._bindings: members = binding.get("members") if members: new_binding = {"role": binding["role"], "members": sorted(members)} condition = binding.get("condition") if condition: new_binding["condition"] = condition bindings.append(new_binding) if bindings: # Sort bindings by role key = operator.itemgetter("role") resource["bindings"] = sorted(bindings, key=key) return resource PK ��Z%S0D� � gapic_v1/config_async.pynu �[��� # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """AsyncIO helpers for loading gapic configuration data. The Google API generator creates supplementary configuration for each RPC method to tell the client library how to deal with retries and timeouts. """ from google.api_core import retry_async from google.api_core.gapic_v1 import config from google.api_core.gapic_v1.config import MethodConfig # noqa: F401 def parse_method_configs(interface_config): """Creates default retry and timeout objects for each method in a gapic interface config with AsyncIO semantics. Args: interface_config (Mapping): The interface config section of the full gapic library config. For example, If the full configuration has an interface named ``google.example.v1.ExampleService`` you would pass in just that interface's configuration, for example ``gapic_config['interfaces']['google.example.v1.ExampleService']``. Returns: Mapping[str, MethodConfig]: A mapping of RPC method names to their configuration. """ return config.parse_method_configs( interface_config, retry_impl=retry_async.AsyncRetry ) PK ��Z3��(Y Y 1 gapic_v1/__pycache__/method_async.cpython-310.pycnu �[��� o �h� � @ s` d Z ddlZddlmZ ddlmZ ddlmZ ddlmZ ddlm Z dddej fdd �ZdS ) z�AsyncIO helpers for wrapping gRPC methods with common functionality. This is used by gapic clients to provide common error mapping, retry, timeout, compression, pagination, and long-running operations to gRPC methods. � N)�grpc_helpers_async)�client_info)�_GapicCallable)�DEFAULT)�USE_DEFAULT_METADATAc C s<