• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2015 gRPC authors.
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
15import threading
16
17from grpc._cython import cygrpc
18
19
20class SimpleFuture(object):
21    """A simple future mechanism."""
22
23    def __init__(self, function, *args, **kwargs):
24        def wrapped_function():
25            try:
26                self._result = function(*args, **kwargs)
27            except Exception as error:  # pylint: disable=broad-except
28                self._error = error
29
30        self._result = None
31        self._error = None
32        self._thread = threading.Thread(target=wrapped_function)
33        self._thread.start()
34
35    def result(self):
36        """The resulting value of this future.
37
38        Re-raises any exceptions.
39        """
40        self._thread.join()
41        if self._error:
42            # TODO(atash): re-raise exceptions in a way that preserves tracebacks
43            raise self._error  # pylint: disable=raising-bad-type
44        return self._result
45
46
47class CompletionQueuePollFuture(SimpleFuture):
48    def __init__(self, completion_queue, deadline):
49        super(CompletionQueuePollFuture, self).__init__(
50            lambda: completion_queue.poll(deadline=deadline)
51        )
52