def monitor( operation: Operation, *, poll_interval_seconds: float = 1, timeout_seconds: float = 300, ) -> Operation: """Continuously polls for this operation's server-side state and returns operation when there is a state change Args: operation: Operation to be monitored. poll_interval_seconds: Time interval (in seconds) between subsequent polls. timeout_seconds: Time (in seconds) to wait for operation to resolve. Raises: TimeoutError: If operation takes longer than `timeout_seconds` to resolve. """ status = OperationState[operation.state] started = now() while timeout_seconds is None or now() - started < timeout_seconds: operation = operation.poll() new_status = OperationState[operation.state] if operation.status is None: return operation elif new_status == status: sleep(poll_interval_seconds) else: return operation raise TimeoutError( f"Waiting for operation took longer than {timeout_seconds} seconds.")
def wait( operation: Operation, *, poll_interval_seconds: int = 3, timeout_seconds: Optional[int] = None, ) -> Operation: """Continuously polls for this operation's server-side state. Args: operation: Operation to be polled. poll_interval_seconds: Time interval (in seconds) between subsequent polls. timeout_seconds: Time (in seconds) to wait for operation to resolve. Raises: TimeoutError: If operation takes longer than `timeout_seconds` to resolve. """ started = now() while timeout_seconds is None or now() - started < timeout_seconds: if operation.status is None: return operation elif operation.status["state"] in [ OperationState.PENDING, OperationState.RUNNING ]: sleep(poll_interval_seconds) elif operation.status["state"] in [ OperationState.CANCELED, OperationState.SUCCEEDED, OperationState.FAILED, ]: return operation operation = operation.poll() raise TimeoutError( f"Waiting for operation took longer than {timeout_seconds} seconds.")