scales/message.py
class Deadline(object):
  KEY = "__Deadline"
  EVENT_KEY = "__Deadline_Event"

  def __init__(self, timeout):
    """
    Args:
      timeout - The timeout in seconds
    """
    import  time
    self._ts = Long(time.time()) * 1000000000 # Nanoseconds
    self._timeout = Long(timeout * 1000000000)
scales/timer_queue.py
GLOBAL_TIMER_QUEUE = TimerQueue()
scales/message.py
class MethodReturnMessage(Message):
  """A message representing the return value from a service call."""
  __slots__ = ('return_value', 'error', 'stack')

  def __init__(self, return_value=None, error=None):
    """
    Args:
      return_value - The return value of the call, or None
      error - The error that occurred during processing, or None.
              If not None, the current stack will be captured and included.
    """
    super(MethodReturnMessage, self).__init__()
    self.return_value = return_value
    self.error = error
    if error:
      exc_info = sys.exc_info()
      if len(exc_info) != 3 or exc_info[2] is None:
        try:
          raise ZeroDivisionError
        except ZeroDivisionError:
          tb = sys.exc_info()[2]
          frame = tb.tb_frame.f_back
      else:
        tb = exc_info[2]
        while tb.tb_next is not None:
          tb = tb.tb_next
        frame = tb.tb_frame

      stack = traceback.format_list(traceback.extract_stack(frame))
      stack = stack + traceback.format_exception_only(error.__class__, error)
      self.stack = stack
      # Prevent circular references
      del frame
      del tb
    else:
      self.stack = None
scales/constants.py
class ChannelState(object):
  Idle = 1
  Open = 2
  Busy = 3
  Closed = 4
scales/asynchronous.py
class AsyncResult(g_AsyncResult):
  @staticmethod
  def WhenAll(ars):
    """Returns an AsyncResult representing the state of all AsyncResults passed.

    Args:
      ars - An enumerable of AsyncResults.
    Returns:
      An AsyncResult representing the completion of all ars passed in.  When all
      complete, the AsyncResult will be set to an array of the results of each
      AsyncResult, in the order they were enumerated in.
      If any AsyncResult fails, the return result will fail.
    """

    ret = AsyncResult()
    num_ars = len(ars)
    total = [num_ars]
    results = [None] * num_ars
    def complete(_n, _ar):
      if _ar.exception:
        ret.set_exception(_ar.exception)
      elif not ret.ready():
        total[0] -= 1
        results[_n] = _ar.value
        if total[0] == 0:
          ret.set(results)

    for n, ar in enumerate(ars):
      ar.rawlink(functools.partial(complete, n))
    return ret

  @staticmethod
  def WhenAny(ars):
    """Returns an AsyncResult representing the state of any AsyncResult passed in.
    The return value represents the state of the first AsyncResult to complete, or,
    if all fail, the last to fail.

    Args:
      ars - An enumerable of AsyncResults.
    Returns:
      An AsyncResult representing the state of the first AsyncResult to complete.
      The AsyncResult's value will be set to the value of the first result to
      complete, or, if all fail, the exception thrown by the last to fail.
    """
    ready_ars = [ar for ar in ars if ar.ready()]
    if ready_ars:
      return ready_ars[0]

    ret = AsyncResult()
    total = [len(ars)]
    def complete(_ar):
      total[0] -= 1
      if total[0] == 0 and _ar.exception:
        ret.set_exception(_ar.exception)
      elif not ret.ready() and _ar.successful():
        ret.set(_ar.value)

    for ar in ars:
      ar.rawlink(complete)
    return ret

  @staticmethod
  def FromValue(val):
    if val is None:
      return AsyncResult.Complete()
    else:
      ar = AsyncResult()
      ar.set(val)
      return ar

  @staticmethod
  def Complete():
    """Return an AsyncResult that has completed."""
    return _COMPLETE

  @staticmethod
  def CompleteIn(n):
    """Returns an AsyncResult that completes in <n> seconds

    Args:
      n - The number of seconds to wait before completing.
    """
    ar = AsyncResult()
    def helper():
      ar.set()
    g = Greenlet(helper)
    g.start_later(float(n))
    return ar

  def _SafeLinkHelper(self, fn):
    try:
      self.set(fn())
    except:
      self.set_exception(sys.exc_info()[1])

  def SafeLink(self, fn):
    """Propagate the result of calling fn() on a new greenlet to ar

    Args:
      ar - An AsyncResult.
      fn - The function to execute.
    """
    gevent.spawn(self._SafeLinkHelper, fn)

  def ContinueWith(self, fn, on_hub=True):
    cw_ar = AsyncResult()
    def continue_with_callback(_ar):
      def run():
        try:
          val = fn(_ar)
          cw_ar.set(val)
        except:
          cw_ar.set_exception(sys.exc_info()[1])
      if on_hub:
        run()
      else:
        gevent.spawn(run)
    self.rawlink(continue_with_callback)
    return cw_ar

  def Map(self, fn):
    def mapper(_):
      if self.exception:
        return self
      else:
        return fn(self.value)
    return self.ContinueWith(mapper).Unwrap()

  def _UnwrapHelper(self, target):
    if self.ready():
      # We're ready, propagate the result
      if self.exception:
        target.set_exception(self.exception)
      else:
        if isinstance(self.value, AsyncResult):
          self.value._UnwrapHelper(target)
        else:
          target.set(self.value)
    else:
      self.rawlink(
        functools.partial(AsyncResult._UnwrapHelper, target=target))

  def Unwrap(self):
    unwrapped_ar = AsyncResult()
    self._UnwrapHelper(unwrapped_ar)
    return unwrapped_ar

  @staticmethod
  def TryGet(val):
    if isinstance(val, AsyncResult):
      return val.get()
    else:
      return val

  @staticmethod
  def Run(fn):
    ar = AsyncResult()
    ar.SafeLink(fn)
    return ar

  @staticmethod
  def RunInline(fn):
    ar = AsyncResult()
    ar._SafeLinkHelper(fn)
    return ar
scales/message.py
class TimeoutError(Exception):
  def __init__(self):
    super(TimeoutError, self).__init__(
      'The call did not complete within the specified timeout '
      'and has been aborted.')
scales/observable.py
class Observable(object):
  """An object to which consumers can subscribe to notifications for its value
  changing."""
  __slots__ = ('_callbacks', '_one_shot_callbacks', '_value')

  def __init__(self):
    self._callbacks = None
    self._one_shot_callbacks = None
    self._value = None

  def __Notify(self, value):
    if self._callbacks:
      cb_copy = self._callbacks.copy()
      [cb(value) for cb in cb_copy]
    if self._one_shot_callbacks:
      cb_copy, self._one_shot_callbacks = self._one_shot_callbacks, None
      [cb(value) for cb in cb_copy]

  def Get(self):
    """Get the current value of the Observable."""
    return self._value

  def Set(self, value=None):
    """Set the current value of the Observable and notify any subscribers."""
    self._value = value
    gevent.spawn(self.__Notify, value)

  def Subscribe(self, callback, one_shot=False):
    """Subscribe to notifications of the value changing.

    Args:
      callback - The method to be called when the value changes.
      one_shot - If true, the callback will only be invoked once.
    """
    if callback is None or not callable(callback):
      raise Exception("callback can not be None")

    if one_shot:
      if not self._one_shot_callbacks:
        self._one_shot_callbacks = set()
      self._one_shot_callbacks.add(callback)
    else:
      if not self._callbacks:
        self._callbacks = set()
      self._callbacks.add(callback)

  def Unsubscribe(self, callback):
    """Unsubscribe from notifications.

    Args:
      callback - The method previously subscribed.
    """
    if self._callbacks:
      self._callbacks.discard(callback)
    if self._one_shot_callbacks:
      self._one_shot_callbacks.discard(callback)
scales/constants.py
class SinkProperties(object):
  Endpoint = 'endpoint'
  ServiceInterface = 'service_iface'
  Label = 'label'
scales/varz.py
class VarzType(object):
class Source(object):
class VarzMetric(object):
class Gauge(VarzMetric): VARZ_TYPE = VarzType.Gauge
class Rate(VarzMetric): VARZ_TYPE = VarzType.Rate
class AverageRate(VarzMetric): VARZ_TYPE = VarzType.AverageRate
class Counter(Rate): VARZ_TYPE = VarzType.Counter
class VarzTimerBase(VarzMetric):
class AverageTimer(VarzTimerBase): VARZ_TYPE = VarzType.AverageTimer
class AggregateTimer(VarzTimerBase): VARZ_TYPE = VarzType.AggregateTimer
class VarzMeta(type):
class _VarzBase(object):
class _SampleSet(object):
class VarzReceiver(object):
class VarzAggregator(object):
  class _Agg(object):
class VarzSocketWrapper(object):
  class Varz(VarzBase):
class MonoClock(object):
class Ema(object):
  def __init__(self, method=None, service=None, endpoint=None, client_id=None):
  def to_tuple(self):
  def to_dict(self):
  def __cmp__(self, other):
  def __hash__(self):
  def _Adapt(fn):
    def __Adapt(metric, source, amount=1):
  def __init__(self, metric, source):
  def __call__(self, *args):
  def ForSource(self, source):
  def Measure(self, source=None):
  def __new__(mcs, name, bases, dct):
def VerifySource(source):
  def __init__(self, source):
  def __getattr__(self, item):
  def __init__(self, max_size, data=None, p=.1):
  def Sample(self, value):
  def RegisterMetric(metric, varz_type):
  def IncrementVarz(source, metric, amount=1):
  def SetVarz(source, metric, value):
  def RecordPercentileSample(cls, source, metric, value):
def DefaultKeySelector(k):
    def __init__(self):
  def CalculatePercentile(values, pct):
  def _Downsample(lst, target_size):
  def Aggregate(varz, metrics, key_selector=None):
  def __init__(self, socket, varz_tag):
  def host(self):
  def port(self):
  def isOpen(self):
  def read(self, sz):
  def recv_into(self, buf, sz):
  def flush(self):
  def write(self, buff):
  def open(self):
  def close(self):
  def readAll(self, sz):
  def __init__(self):
  def Sample(self):
  def __init__(self, window):
  def Update(self, ts, sample):
  VARZ_TYPE = None
class Gauge(VarzMetric): VARZ_TYPE = VarzType.Gauge
class Rate(VarzMetric): VARZ_TYPE = VarzType.Rate
class AverageRate(VarzMetric): VARZ_TYPE = VarzType.AverageRate
class Counter(Rate): VARZ_TYPE = VarzType.Counter
class AverageTimer(VarzTimerBase): VARZ_TYPE = VarzType.AverageTimer
class AggregateTimer(VarzTimerBase): VARZ_TYPE = VarzType.AggregateTimer
  _VARZ = {}
  _VARZ_BASE_NAME = None
  VARZ_METRICS = {}
  VARZ_DATA = defaultdict(lambda: defaultdict(int))
  VARZ_PERCENTILES = [.5, .90, .99, .999, .9999]
  _MAX_PERCENTILE_SIZE = 1000
  MAX_AGG_AGE = 5 * 60
    _VARZ_BASE_NAME = 'scales.socket'
    _VARZ = {
      'bytes_recv': Rate,
      'bytes_sent': Rate,
      'num_connections': Counter,
      'tests_failed': Counter,
      'connects': Rate,
      'open_latency': AverageTimer
    }
scales/scales_socket.py
class ScalesSocket(object):
  def __init__(self, host, port):
    self.host = host
    self.port = port
    self.handle = None

  def isOpen(self):
    return self.handle is not None

  def _resolveAddr(self):
    return socket.getaddrinfo(
      self.host,
      self.port,
      socket.AF_UNSPEC,
      socket.SOCK_STREAM,
      0,
      socket.AI_PASSIVE | socket.AI_ADDRCONFIG)

  def open(self):
    resolved = self._resolveAddr()
    for res in resolved:
      self.handle = gsocket(res[0], res[1])
      try:
        self.handle.connect(res[4])
      except socket.error as e:
        if res is not resolved[-1]:
          continue
        else:
          raise e
      break

  def close(self):
    if self.handle:
      self.handle.close()
      self.handle = None

  def readAll(self, sz):
    buff = b''
    have = 0
    while have < sz:
      chunk = self.read(sz - have)
      have += len(chunk)
      buff += chunk

      if len(chunk) == 0:
        raise EOFError()

    return buff

  def read(self, sz):
    return self.handle.recv(sz)

  def write(self, buff):
    sent = 0
    have = len(buff)
    while sent < have:
      plus = self.handle.send(buff)
      if plus == 0:
        raise EOFError()
      sent += plus
      buff = buff[plus:]
scales/constants.py
class SinkRole(object):
  Transport = 'transport'
  Pool = 'pool'
  LoadBalancer = 'loadbalancer'
  Formatter = 'formatter'


Question: from abc import (
  ABCMeta,
  abstractmethod,
  abstractproperty
)
from collections import (deque, namedtuple)
from weakref import WeakValueDictionary
  from gevent.coros import RLock
  from gevent.lock import RLock
from .asynchronous import AsyncResult
from .constants import (ChannelState, SinkProperties, SinkRole)
from .observable import Observable
from .message import (
  Deadline,
  MethodReturnMessage,
  TimeoutError
)
from .scales_socket import ScalesSocket
from .timer_queue import GLOBAL_TIMER_QUEUE
from .varz import (
  Rate,
  Source,
  VarzBase,
  VarzSocketWrapper
)
import time
      self.next_sink.Close()

  @abstractmethod
  def AsyncProcessRequest(self, sink_stack, msg, stream, headers):
    """Process a request message, stream, and headers.

    Args:
      sink_stack - The SinkStack representing the processing state of the message.
                   Implementors should push their sink onto this stack before
                   forwarding the message in order to participate in processing
                   the response.
      msg - The message being processed.
      stream - A serialized version of the message.
      headers - Any additional headers to be sent.
    """
    raise NotImplementedError()

  @abstractmethod
  def AsyncProcessResponse(self, sink_stack, context, stream, msg):
    """Process a response stream.

    Args:
      sink_stack - The SinkStack representing the processing state of the message.
                   Implementors should call sink_stack.AsyncProcessMessage(...)
                   to forward the message to the next sink.
      context - The context that was pushed onto the stack in AsyncProcessRequest.
      stream - The stream representing the serialized response.
    """
    raise NotImplementedError()


class SinkStack(object):
  """A stack of sinks."""
  __slots__ = '_stack',

  def __init__(self):
    self._stack = deque()

  def Push(self, sink, context=None):
    """Push a sink, and optional context data, onto the stack.

    Args:
      sink - The sink to push onto the stack.
      context - Optional context data associated with the current processing
                state of the sink.
    """
    if sink is None:
      raise Exception("sink must not be None")

    self._stack.append((sink, context))

  def Pop(self):
    return self._stack.pop()

  def Any(self):
    return any(self._stack)


class ClientMessageSinkStack(SinkStack):
  """A SinkStack of ClientMessageSinks.

  The ClientMessageSinkStack forwards AsyncProcessResponse to the next sink
  on the stack.
  """

  def __init__(self):
    """
    Args:
      reply_sink - An optional ReplySink.
    """
    super(ClientMessageSinkStack, self).__init__()

  def AsyncProcessResponse(self, stream, msg):
    """Pop the next sink off the stack and call AsyncProcessResponse on it."""
    if self.Any():
      next_sink, next_ctx = self.Pop()
      next_sink.AsyncProcessResponse(self, next_ctx, stream, msg)

  def AsyncProcessResponseStream(self, stream):
    self.AsyncProcessResponse(stream, None)

  def AsyncProcessResponseMessage(self, msg):
    self.AsyncProcessResponse(None, msg)


class FailingMessageSink(ClientMessageSink):
  """A sink that always returns a failure message."""

  def __init__(self, ex):
    self._ex = ex
    super(FailingMessageSink, self).__init__()

  def AsyncProcessRequest(self, sink_stack, msg, stream, headers):
    msg = MethodReturnMessage(error=self._ex())
    sink_stack.AsyncProcessResponseMessage(msg)

  def AsyncProcessResponse(self, sink_stack, context, stream, msg):
    raise NotImplementedError("This should never be called")

  @property
  def state(self):
    return ChannelState.Open

  @property
  def endpoint(self):
    return None


class ClientTimeoutSink(ClientMessageSink):

  class Varz(VarzBase):
    _VARZ_BASE_NAME = 'scales.TimeoutSink'
    _VARZ = {
      'timeouts': Rate
    }

  def __init__(self, next_provider, sink_properties, global_properties):
    super(ClientTimeoutSink, self).__init__()
    self.next_sink = next_provider.CreateSink(global_properties)
    self._varz = self.Varz(

Answer:       Source(service=global_properties[SinkProperties.Label]))