aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/python/_framework/face/_calls.py
blob: ab58e6378b1f19c77f735258c1c5eb75cdf328dd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
#     * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#     * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

"""Utility functions for invoking RPCs."""

import threading

from _framework.base import interfaces as base_interfaces
from _framework.base import util as base_util
from _framework.face import _control
from _framework.face import interfaces
from _framework.foundation import callable_util
from _framework.foundation import future

_ITERATOR_EXCEPTION_LOG_MESSAGE = 'Exception iterating over requests!'
_DONE_CALLBACK_LOG_MESSAGE = 'Exception calling Future "done" callback!'


class _RendezvousServicedIngestor(base_interfaces.ServicedIngestor):

  def __init__(self, rendezvous):
    self._rendezvous = rendezvous

  def consumer(self, operation_context):
    return self._rendezvous


class _EventServicedIngestor(base_interfaces.ServicedIngestor):

  def __init__(self, result_consumer, abortion_callback):
    self._result_consumer = result_consumer
    self._abortion_callback = abortion_callback

  def consumer(self, operation_context):
    operation_context.add_termination_callback(
        _control.as_operation_termination_callback(self._abortion_callback))
    return self._result_consumer


def _rendezvous_subscription(rendezvous):
  return base_util.full_serviced_subscription(
      _RendezvousServicedIngestor(rendezvous))


def _unary_event_subscription(completion_callback, abortion_callback):
  return base_util.full_serviced_subscription(
      _EventServicedIngestor(
          _control.UnaryConsumer(completion_callback), abortion_callback))


def _stream_event_subscription(result_consumer, abortion_callback):
  return base_util.full_serviced_subscription(
      _EventServicedIngestor(result_consumer, abortion_callback))


class _OperationCancellableIterator(interfaces.CancellableIterator):
  """An interfaces.CancellableIterator for response-streaming operations."""

  def __init__(self, rendezvous, operation):
    self._rendezvous = rendezvous
    self._operation = operation

  def __iter__(self):
    return self

  def next(self):
    return next(self._rendezvous)

  def cancel(self):
    self._operation.cancel()
    self._rendezvous.set_outcome(base_interfaces.CANCELLED)


class _OperationFuture(future.Future):
  """A future.Future interface to an operation."""

  def __init__(self, rendezvous, operation):
    self._condition = threading.Condition()
    self._rendezvous = rendezvous
    self._operation = operation

    self._outcome = None
    self._callbacks = []

  def cancel(self):
    """See future.Future.cancel for specification."""
    with self._condition:
      if self._outcome is None:
        self._operation.cancel()
        self._outcome = future.aborted()
        self._condition.notify_all()
    return False

  def cancelled(self):
    """See future.Future.cancelled for specification."""
    return False

  def done(self):
    """See future.Future.done for specification."""
    with self._condition:
      return (self._outcome is not None and
              self._outcome.category is not future.ABORTED)

  def outcome(self):
    """See future.Future.outcome for specification."""
    with self._condition:
      while self._outcome is None:
        self._condition.wait()
      return self._outcome

  def add_done_callback(self, callback):
    """See future.Future.add_done_callback for specification."""
    with self._condition:
      if self._callbacks is not None:
        self._callbacks.add(callback)
        return

      outcome = self._outcome

    callable_util.call_logging_exceptions(
        callback, _DONE_CALLBACK_LOG_MESSAGE, outcome)

  def on_operation_termination(self, operation_outcome):
    """Indicates to this object that the operation has terminated.

    Args:
      operation_outcome: One of base_interfaces.COMPLETED,
        base_interfaces.CANCELLED, base_interfaces.EXPIRED,
        base_interfaces.RECEPTION_FAILURE, base_interfaces.TRANSMISSION_FAILURE,
        base_interfaces.SERVICED_FAILURE, or base_interfaces.SERVICER_FAILURE
        indicating the categorical outcome of the operation.
    """
    with self._condition:
      if (self._outcome is None and
          operation_outcome != base_interfaces.COMPLETED):
        self._outcome = future.raised(
            _control.abortion_outcome_to_exception(operation_outcome))
        self._condition.notify_all()

      outcome = self._outcome
      rendezvous = self._rendezvous
      callbacks = list(self._callbacks)
      self._callbacks = None

    if outcome is None:
      try:
        return_value = next(rendezvous)
      except Exception as e:  # pylint: disable=broad-except
        outcome = future.raised(e)
      else:
        outcome = future.returned(return_value)
      with self._condition:
        if self._outcome is None:
          self._outcome = outcome
          self._condition.notify_all()
        else:
          outcome = self._outcome

    for callback in callbacks:
      callable_util.call_logging_exceptions(
          callback, _DONE_CALLBACK_LOG_MESSAGE, outcome)


class _Call(interfaces.Call):

  def __init__(self, operation):
    self._operation = operation
    self.context = _control.RpcContext(operation.context)

  def cancel(self):
    self._operation.cancel()


def blocking_value_in_value_out(front, name, payload, timeout, trace_id):
  """Services in a blocking fashion a value-in value-out servicer method."""
  rendezvous = _control.Rendezvous()
  subscription = _rendezvous_subscription(rendezvous)
  operation = front.operate(
      name, payload, True, timeout, subscription, trace_id)
  operation.context.add_termination_callback(rendezvous.set_outcome)
  return next(rendezvous)


def future_value_in_value_out(front, name, payload, timeout, trace_id):
  """Services a value-in value-out servicer method by returning a Future."""
  rendezvous = _control.Rendezvous()
  subscription = _rendezvous_subscription(rendezvous)
  operation = front.operate(
      name, payload, True, timeout, subscription, trace_id)
  operation.context.add_termination_callback(rendezvous.set_outcome)
  operation_future = _OperationFuture(rendezvous, operation)
  operation.context.add_termination_callback(
      operation_future.on_operation_termination)
  return operation_future


def inline_value_in_stream_out(front, name, payload, timeout, trace_id):
  """Services a value-in stream-out servicer method."""
  rendezvous = _control.Rendezvous()
  subscription = _rendezvous_subscription(rendezvous)
  operation = front.operate(
      name, payload, True, timeout, subscription, trace_id)
  operation.context.add_termination_callback(rendezvous.set_outcome)
  return _OperationCancellableIterator(rendezvous, operation)


def blocking_stream_in_value_out(
    front, name, payload_iterator, timeout, trace_id):
  """Services in a blocking fashion a stream-in value-out servicer method."""
  rendezvous = _control.Rendezvous()
  subscription = _rendezvous_subscription(rendezvous)
  operation = front.operate(name, None, False, timeout, subscription, trace_id)
  operation.context.add_termination_callback(rendezvous.set_outcome)
  for payload in payload_iterator:
    operation.consumer.consume(payload)
  operation.consumer.terminate()
  return next(rendezvous)


def future_stream_in_value_out(
    front, name, payload_iterator, timeout, trace_id, pool):
  """Services a stream-in value-out servicer method by returning a Future."""
  rendezvous = _control.Rendezvous()
  subscription = _rendezvous_subscription(rendezvous)
  operation = front.operate(name, None, False, timeout, subscription, trace_id)
  operation.context.add_termination_callback(rendezvous.set_outcome)
  pool.submit(
      callable_util.with_exceptions_logged(
          _control.pipe_iterator_to_consumer, _ITERATOR_EXCEPTION_LOG_MESSAGE),
      payload_iterator, operation.consumer, lambda: True, True)
  operation_future = _OperationFuture(rendezvous, operation)
  operation.context.add_termination_callback(
      operation_future.on_operation_termination)
  return operation_future


def inline_stream_in_stream_out(
    front, name, payload_iterator, timeout, trace_id, pool):
  """Services a stream-in stream-out servicer method."""
  rendezvous = _control.Rendezvous()
  subscription = _rendezvous_subscription(rendezvous)
  operation = front.operate(name, None, False, timeout, subscription, trace_id)
  operation.context.add_termination_callback(rendezvous.set_outcome)
  pool.submit(
      callable_util.with_exceptions_logged(
          _control.pipe_iterator_to_consumer, _ITERATOR_EXCEPTION_LOG_MESSAGE),
      payload_iterator, operation.consumer, lambda: True, True)
  return _OperationCancellableIterator(rendezvous, operation)


def event_value_in_value_out(
    front, name, payload, completion_callback, abortion_callback, timeout,
    trace_id):
  subscription = _unary_event_subscription(
      completion_callback, abortion_callback)
  operation = front.operate(
      name, payload, True, timeout, subscription, trace_id)
  return _Call(operation)


def event_value_in_stream_out(
    front, name, payload, result_payload_consumer, abortion_callback, timeout,
    trace_id):
  subscription = _stream_event_subscription(
      result_payload_consumer, abortion_callback)
  operation = front.operate(
      name, payload, True, timeout, subscription, trace_id)
  return _Call(operation)


def event_stream_in_value_out(
    front, name, completion_callback, abortion_callback, timeout, trace_id):
  subscription = _unary_event_subscription(
      completion_callback, abortion_callback)
  operation = front.operate(name, None, False, timeout, subscription, trace_id)
  return _Call(operation), operation.consumer


def event_stream_in_stream_out(
    front, name, result_payload_consumer, abortion_callback, timeout, trace_id):
  subscription = _stream_event_subscription(
      result_payload_consumer, abortion_callback)
  operation = front.operate(name, None, False, timeout, subscription, trace_id)
  return _Call(operation), operation.consumer