Class: Gapic::Rest::ServerStream

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/gapic/rest/server_stream.rb

Overview

A class to provide the Enumerable interface to the response of a REST server-streaming dmethod.

ServerStream provides the enumerations over the individual response messages within the stream.

Examples:

normal iteration over resources.

server_stream.each { |response| puts response }

Instance Method Summary collapse

Constructor Details

#initialize(message_klass, json_enumerator) ⇒ ServerStream

Initializes ServerStream object.

Parameters:

  • message_klass (Class)
  • json_enumerator (Enumerator<String>)


35
36
37
38
39
40
# File 'lib/gapic/rest/server_stream.rb', line 35

def initialize message_klass, json_enumerator
  @json_enumerator = json_enumerator
  @obj = ""
  @message_klass = message_klass
  @ready_objs = [] # List of strings
end

Instance Method Details

#each {|Object| ... } ⇒ Enumerator

Iterate over JSON objects in the streamed response.

Yields:

  • (Object)

    Gives one complete Message object.

Returns:

  • (Enumerator)

    if no block is provided



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/gapic/rest/server_stream.rb', line 49

def each
  return enum_for :each unless block_given?

  loop do
    while @ready_objs.empty?
      begin
        chunk = @json_enumerator.next
        next unless chunk
        next_json! chunk
      rescue StopIteration
        dangling_content = @obj.strip
        error_expl = "Dangling content left after iterating through the stream. " \
                     "This means that not all content was received or parsed correctly. " \
                     "It is likely a result of server or network error."
        error_text = "#{error_expl}\n Content left unparsed: #{dangling_content}"

        raise Gapic::Common::Error, error_text unless dangling_content.empty?
        return
      end
    end
    yield @message_klass.decode_json @ready_objs.shift, ignore_unknown_fields: true
  end
end