taba-client 0.3.20.rc1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,359 @@
1
+ require 'json'
2
+ require 'thread'
3
+ require 'taba/calls'
4
+ require 'taba/cancel_token'
5
+ require 'taba/config'
6
+ require 'taba/error'
7
+ require 'taba/models'
8
+ require 'taba/options'
9
+ require 'taba/transport'
10
+
11
+ module Taba
12
+ # What the +consume_with+ handler receives: the +message+, the +delete+ flag (the message is deleted at the end if the
13
+ # handler returns without raising; the default is true) and +change_visibility+. While the handler runs, the
14
+ # connector renews the invisibility by itself, so no other consumer takes the message.
15
+ class MessageContext
16
+ attr_reader :message
17
+ # Set it to false to keep the message even though the handler returned normally.
18
+ attr_accessor :delete
19
+ # +consume_json+ only: the parsed body.
20
+ attr_accessor :body
21
+
22
+ def initialize(message, lease_seconds, change)
23
+ @message = message
24
+ @delete = true
25
+ @body = nil
26
+ @mutex = Mutex.new
27
+ @lease_seconds = lease_seconds
28
+ @lease_lost = false
29
+ @change = change
30
+ end
31
+
32
+ # The seconds of invisibility the automatic renewal requests on each round.
33
+ def lease_seconds
34
+ @mutex.synchronize { @lease_seconds }
35
+ end
36
+
37
+ # True when the server refused the renewal (the message already went back to the queue or was deleted).
38
+ def lease_lost?
39
+ @mutex.synchronize { @lease_lost }
40
+ end
41
+
42
+ # Changes the invisibility to +seconds+ from now on. The value becomes the one of the automatic renewal.
43
+ def change_visibility(seconds)
44
+ @change.call(seconds)
45
+ @mutex.synchronize { @lease_seconds = seconds }
46
+ nil
47
+ end
48
+
49
+ # :nodoc:
50
+ def lease_lost!
51
+ @mutex.synchronize { @lease_lost = true }
52
+ end
53
+ end
54
+
55
+ # The Taba client API client (doc 21): the nine operations, +subscribe+ and the consume with a handler. It is safe
56
+ # for concurrent use: each thread has its own connection.
57
+ #
58
+ # client = Taba::Client.new('http://localhost:8080', token: token)
59
+ # client.publish_json('orders', order: 9001)
60
+ # client.consume_with('orders', wait_time: 20) { |context| puts context.message.body_text }
61
+ class Client
62
+ # Creates the client from a Taba::Config, or from the address and the Config fields as options.
63
+ def initialize(config = nil, **options)
64
+ if config.is_a?(Config)
65
+ raise ArgumentError, 'pass either a Config or options, not both' unless options.empty?
66
+ @config = config
67
+ else
68
+ @config = Config.new(config, **options)
69
+ end
70
+ @transport = Transport.new(@config)
71
+ end
72
+
73
+ attr_reader :config
74
+
75
+ # Test hook: the wait between attempts, +lambda { |seconds, token| ... }+.
76
+ def sleeper=(callable)
77
+ @transport.sleeper = callable
78
+ end
79
+
80
+ # Closes the calling thread's connection. The client can be used again afterwards.
81
+ def close
82
+ @transport.close
83
+ end
84
+
85
+ # -- topics ---------------------------------------------------------------------------------------------
86
+
87
+ # +POST /topics+. +request+ is a Taba::TopicRequest, or give its fields as options.
88
+ def create_topic(request = nil, cancel: nil, **fields)
89
+ request = request.nil? ? TopicRequest.new(fields) : TopicRequest.from(request)
90
+ reply = send_call(Calls.create_topic(request), cancel)
91
+ return get_topic(request.name, cancel: cancel) if reply.recovered
92
+ Parser.topic(utf8(reply.body))
93
+ end
94
+
95
+ def get_topic(name, cancel: nil)
96
+ Parser.topic(utf8(send_call(Calls.get_topic(name), cancel).body))
97
+ end
98
+
99
+ # +GET /topics+. Parameters left nil do not go in the query.
100
+ def list_topics(limit: nil, cursor: nil, name: nil, cancel: nil)
101
+ Parser.page(utf8(send_call(Calls.list_topics(limit, cursor, name), cancel).body))
102
+ end
103
+
104
+ # All topics, page by page. With a block, yields each topic.
105
+ def each_topic(name: nil, cancel: nil)
106
+ return to_enum(:each_topic, name: name, cancel: cancel) unless block_given?
107
+ cursor = nil
108
+ loop do
109
+ page = list_topics(cursor: cursor, name: name, cancel: cancel)
110
+ page.items.each { |topic| yield topic }
111
+ cursor = page.next_cursor
112
+ break if cursor.nil?
113
+ end
114
+ end
115
+
116
+ def list_all_topics(name: nil, cancel: nil)
117
+ each_topic(name: name, cancel: cancel).to_a
118
+ end
119
+
120
+ # +PATCH /topics/{topic}+: a real +PATCH+, with no verb-override header. +update+ is a Taba::TopicUpdate, or
121
+ # give its fields as options.
122
+ def update_topic(name, update = nil, cancel: nil, **fields)
123
+ update = update.nil? ? TopicUpdate.new(fields) : TopicUpdate.from(update)
124
+ Parser.topic(utf8(send_call(Calls.update_topic(name, update), cancel).body))
125
+ end
126
+
127
+ # +DELETE /topics/{topic}+. With +if_empty: true+, removes the queue only if it and its dead-letter hold no
128
+ # message on any node (+409 topic.not-empty+ otherwise; a distributor holds none).
129
+ def delete_topic(name, if_empty: false, cancel: nil)
130
+ send_call(Calls.delete_topic(name, if_empty), cancel)
131
+ nil
132
+ end
133
+
134
+ # +PUT /topics/{topic}+: brings the topic to the declared state, creating it if it does not exist. What is left
135
+ # out goes back to the server default (a full replacement, unlike +update_topic+); the name of the request is the
136
+ # topic of the path. Another +type+, +fifo+ or +volatile+ is +409 topic.immutable-mismatch+ unless +recreate+
137
+ # (+'if-empty'+ or +'always'+) says otherwise. Repeated after a 503 like the other calls: the route is
138
+ # idempotent. +request+ is a Taba::TopicRequest, or give its fields as options. Returns a Taba::TopicPut.
139
+ def create_or_update_topic(request = nil, recreate: nil, cancel: nil, **fields)
140
+ request = request.nil? ? TopicRequest.new(fields) : TopicRequest.from(request)
141
+ reply = send_call(Calls.put_topic(request, recreate), cancel)
142
+ outcome = if reply.status == 201
143
+ reply.recreated ? TopicPut::RECREATED : TopicPut::CREATED
144
+ else
145
+ TopicPut::UPDATED
146
+ end
147
+ TopicPut.new(Parser.topic(utf8(reply.body)), outcome)
148
+ end
149
+
150
+ # -- publishing -----------------------------------------------------------------------------------------
151
+
152
+ # +POST /topics/{topic}/messages+. The body goes as bytes (a String is sent as it is), without validation. Set
153
+ # +fifo: true+ when the topic is a FIFO queue: only there can a 502/504 be repeated. Options: content_type,
154
+ # group_id, deduplication_id, request_id, traceparent, fifo.
155
+ def publish(topic, body, cancel: nil, **options)
156
+ reply = send_call(Calls.publish(topic, body, PublishOptions.new(options)), cancel)
157
+ Parser.publish_response(utf8(reply.body))
158
+ end
159
+
160
+ # Serializes the value (with +JSON+) and publishes it as +application/json+. The options are a trailing hash, so
161
+ # the value itself can be written as keywords: +publish_json('orders', order: 9001)+ (a Hash) or
162
+ # +publish_json('orders', { order: 9001 }, group_id: 'g')+.
163
+ def publish_json(topic, value, options = {})
164
+ raise Error.client('client.invalid-request', 'value is required') if value.nil?
165
+ begin
166
+ text = ::JSON.generate(value, quirks_mode: true)
167
+ rescue ::JSON::GeneratorError, EncodingError => e
168
+ raise Error.client('client.invalid-request', "cannot serialize the value: #{e.message}")
169
+ end
170
+ publish(topic, text, **options.merge(content_type: 'application/json'))
171
+ end
172
+
173
+ # Publishes a JSON text the application already built, without serializing.
174
+ def publish_raw_json(topic, text, **options)
175
+ publish(topic, text, **options.merge(content_type: 'application/json'))
176
+ end
177
+
178
+ # Publishes a text (+Content-Type: text/plain; charset=utf-8+).
179
+ def publish_text(topic, text, **options)
180
+ publish(topic, text.to_s.dup.force_encoding(Encoding::UTF_8), **options.merge(content_type: 'text/plain; charset=utf-8'))
181
+ end
182
+
183
+ # +POST /topics/{topic}/messages/batch+: publishes many messages in one request (1 to the server's
184
+ # +api.batch.max-messages+, 1000 by default). Each item is answered as its single publication and one that fails
185
+ # does not undo the others (look at +ok?+). On a FIFO queue the items of a group are published in the order of
186
+ # the array. A failure of the network is not repeated (it could duplicate).
187
+ def publish_batch(topic, messages, cancel: nil)
188
+ Parser.batch_results(utf8(send_call(Calls.publish_batch(topic, messages), cancel).body))
189
+ end
190
+
191
+ # -- consuming ------------------------------------------------------------------------------------------
192
+
193
+ # +GET /topics/{topic}/messages+. The read time is +wait_time + 10+ seconds, not the +request_timeout+. A
194
+ # timeout is not repeated (the node may have captured messages, which come back by themselves at the end of the
195
+ # +visibility_timeout+). Returns an empty array if there are no messages. Options: max_messages,
196
+ # visibility_timeout, wait_time, auto_create, volatile, idle_timeout, fifo, tags, request_id, traceparent.
197
+ def consume(topic, cancel: nil, **options)
198
+ fetch(topic, ConsumeOptions.new(options), cancel)
199
+ end
200
+
201
+ # +DELETE /topics/{topic}/messages/{id}?receiptToken=+. +message+ is what +consume+ returned, or its id.
202
+ def ack(topic, message, receipt_token = nil, cancel: nil)
203
+ id, token = reference(message, receipt_token)
204
+ send_call(Calls.ack(topic, id, token), cancel)
205
+ nil
206
+ end
207
+
208
+ # +PUT /topics/{topic}/messages/{id}/visibility?receiptToken=+.
209
+ def change_visibility(topic, message, seconds, receipt_token = nil, cancel: nil)
210
+ id, token = reference(message, receipt_token)
211
+ reply = send_call(Calls.change_visibility(topic, id, token, seconds), cancel)
212
+ Parser.visibility(utf8(reply.body))
213
+ end
214
+
215
+ # +POST /topics/{topic}/messages/ack+: acknowledges many messages +consume+ returned, in one request.
216
+ def ack_batch(topic, messages, cancel: nil)
217
+ Parser.batch_results(utf8(send_call(Calls.receipts(topic, 'ack', messages), cancel).body))
218
+ end
219
+
220
+ # +POST /topics/{topic}/messages/visibility+: the invisibility of each message, +seconds+ from now.
221
+ def change_visibility_batch(topic, messages, seconds, cancel: nil)
222
+ call = Calls.receipts(topic, 'visibility', messages, seconds)
223
+ Parser.batch_results(utf8(send_call(call, cancel).body))
224
+ end
225
+
226
+ # Reads from the queue and hands each message to the block as a MessageContext. The message is deleted if the
227
+ # block returns without raising (+context.delete = false+ keeps it). While the block runs, the invisibility is
228
+ # renewed every third of it, by another thread. Defaults: one message at a time, 20 s of long polling, 120 s of
229
+ # invisibility. If the block raises, the message is not deleted and the exception propagates. Returns how many
230
+ # messages were handled.
231
+ def consume_with(topic, cancel: nil, **options, &handler)
232
+ handle_all(topic, options, cancel, false, handler)
233
+ end
234
+
235
+ # +consume_with+ with the body already parsed (with +JSON+) in +context.body+. A body that does not parse gives
236
+ # +client.invalid-response+ before the block is called, and the message is not deleted.
237
+ def consume_json(topic, cancel: nil, **options, &handler)
238
+ handle_all(topic, options, cancel, true, handler)
239
+ end
240
+
241
+ # The consume loop: long polling (+wait_time+ 20 and one message at a time, if not set), yields each message to
242
+ # the block and acknowledges by itself only if it returns without raising (a message that fails goes back to the
243
+ # queue at the end of the +visibility_timeout+, and the exception goes to +on_error.call(message, error)+).
244
+ # Blocks until +cancel+ is cancelled and then returns without an exception. A server error while consuming
245
+ # propagates.
246
+ def subscribe(topic, cancel: nil, on_error: nil, **options)
247
+ raise ArgumentError, 'a block is required' unless block_given?
248
+ cancel ||= CancelToken.new
249
+ poll = Calls.subscribe_defaults(ConsumeOptions.new(options))
250
+ until cancel.cancelled?
251
+ begin
252
+ messages = fetch(topic, poll, cancel)
253
+ rescue Cancelled
254
+ return nil
255
+ end
256
+ messages.each do |message|
257
+ handled = false
258
+ begin
259
+ yield message
260
+ handled = true
261
+ rescue StandardError => e # the block is the application's code
262
+ on_error.call(message, e) if on_error
263
+ end
264
+ settle(topic, message) if handled
265
+ return nil if cancel.cancelled?
266
+ end
267
+ end
268
+ nil
269
+ end
270
+
271
+ private
272
+
273
+ def send_call(call, cancel)
274
+ @transport.send_call(call, cancel)
275
+ end
276
+
277
+ def utf8(body)
278
+ body.dup.force_encoding(Encoding::UTF_8)
279
+ end
280
+
281
+ def fetch(topic, options, cancel)
282
+ Parser.messages(utf8(send_call(Calls.consume(topic, options), cancel).body))
283
+ end
284
+
285
+ def reference(message, receipt_token)
286
+ return [message.id, message.receipt_token] if message.is_a?(Message)
287
+ raise Error.client('client.invalid-request', 'receipt_token is required with a message id') if receipt_token.nil?
288
+ [message.to_s, receipt_token]
289
+ end
290
+
291
+ def lost_or_gone?(error)
292
+ [409, 404].include?(error.status)
293
+ end
294
+
295
+ # Without the token: the message was already handled, and acknowledging it must not be cut short.
296
+ def settle(topic, message)
297
+ ack(topic, message)
298
+ rescue Error => e
299
+ raise unless lost_or_gone?(e)
300
+ end
301
+
302
+ def handle_all(topic, options, cancel, parse, handler)
303
+ raise ArgumentError, 'a block is required' if handler.nil?
304
+ opts = Calls.handler_defaults(ConsumeOptions.new(options))
305
+ handled = 0
306
+ fetch(topic, opts, cancel).each do |message|
307
+ body = nil
308
+ if parse
309
+ begin
310
+ body = ::JSON.parse(message.body_text, quirks_mode: true)
311
+ rescue ::JSON::ParserError => e
312
+ raise Error.client('client.invalid-response', "body of message #{message.id} is not valid JSON: #{e.message}")
313
+ end
314
+ end
315
+ context = MessageContext.new(message, opts.visibility_timeout,
316
+ lambda { |seconds| change_visibility(topic, message, seconds, cancel: cancel) })
317
+ context.body = body
318
+ run_with_renewal(topic, context) { handler.call(context) }
319
+ settle(topic, message) if context.delete
320
+ handled += 1
321
+ end
322
+ handled
323
+ end
324
+
325
+ # Runs the handler while a second thread renews the invisibility.
326
+ def run_with_renewal(topic, context)
327
+ stop = CancelToken.new
328
+ renewal = Thread.new { keep_alive(topic, context, stop) }
329
+ renewal.abort_on_exception = false
330
+ begin
331
+ yield
332
+ ensure
333
+ stop.cancel
334
+ renewal.join
335
+ end
336
+ end
337
+
338
+ # The second thread: renews the invisibility until the handler finishes. Never raises.
339
+ def keep_alive(topic, context, stop)
340
+ until stop.cancelled?
341
+ @transport.sleeper.call(Calls.renewal_interval(context.lease_seconds), stop)
342
+ begin
343
+ change_visibility(topic, context.message, context.lease_seconds, cancel: stop)
344
+ rescue Error => e
345
+ if lost_or_gone?(e)
346
+ # The message already went back to the queue or was deleted: renewing is no longer of any use.
347
+ context.lease_lost!
348
+ return
349
+ end
350
+ # A transient failure (network, 5xx): tries again on the next round, before the deadline expires.
351
+ end
352
+ end
353
+ rescue Cancelled
354
+ nil
355
+ ensure
356
+ @transport.close # this thread's own connection
357
+ end
358
+ end
359
+ end
@@ -0,0 +1,52 @@
1
+ require 'taba/version'
2
+ require 'taba/error'
3
+
4
+ module Taba
5
+ # The client configuration (doc 21). It does not read environment variables: +TABA_*+ is the prefix of the server
6
+ # configuration; whoever uses the connector reads their own and fills this object.
7
+ #
8
+ # Taba::Config.new('http://localhost:8080', token: token)
9
+ class Config
10
+ FIELDS = [:base_url, :token, :connect_timeout, :request_timeout, :max_attempts, :user_agent, :ca_file, :ca_path].freeze
11
+
12
+ # Address of the client API load balancer (+http://host:port+ or +https://...+). Required.
13
+ attr_accessor :base_url
14
+ # Goes in +Authorization: Bearer+. Without it, the call goes without the header.
15
+ attr_accessor :token
16
+ # Seconds to open the connection.
17
+ attr_accessor :connect_timeout
18
+ # Seconds of an ordinary call (each wait for the response). +consume+ uses +wait_time + 10+.
19
+ attr_accessor :request_timeout
20
+ # Attempts, counting the first.
21
+ attr_accessor :max_attempts
22
+ # Goes in +User-Agent+. Add the application name.
23
+ attr_accessor :user_agent
24
+ # An own CA bundle file (a private CA, for example). Default: the system's. The certificate is always verified.
25
+ attr_accessor :ca_file
26
+ # An own directory of CA certificates.
27
+ attr_accessor :ca_path
28
+
29
+ def initialize(base_url = nil, **options)
30
+ @base_url = base_url
31
+ @token = nil
32
+ @connect_timeout = 5.0
33
+ @request_timeout = 30.0
34
+ @max_attempts = 3
35
+ @user_agent = "taba-ruby/#{VERSION}"
36
+ @ca_file = nil
37
+ @ca_path = nil
38
+ options.each do |key, value|
39
+ unless FIELDS.include?(key)
40
+ raise Error.client('client.invalid-config', "unknown configuration field: #{key}")
41
+ end
42
+ send("#{key}=", value)
43
+ end
44
+ end
45
+
46
+ # A Config from itself or an address (the options only apply to an address).
47
+ def self.from(value, **options)
48
+ return value if value.is_a?(Config)
49
+ new(value, **options)
50
+ end
51
+ end
52
+ end
data/lib/taba/error.rb ADDED
@@ -0,0 +1,54 @@
1
+ module Taba
2
+ # The only kind of error of the connector (doc 21, "The common contract"): the API +ErrorResponse+, or a failure of
3
+ # the client itself (+status+ 0 and a +code+ +client.network+, +client.timeout+, +client.invalid-config+,
4
+ # +client.invalid-response+ or +client.invalid-request+). Test the +code+, never the +message+.
5
+ class Error < StandardError
6
+ # The HTTP status, or zero on a failure of the client itself.
7
+ attr_reader :status
8
+ # The +group.reason+ code of the error.
9
+ attr_reader :code
10
+ # The +requestId+ of the +ErrorResponse+, or the +X-Request-Id+ header.
11
+ attr_reader :request_id
12
+ # The seconds of the +Retry-After+, if the response carried it (nil otherwise).
13
+ attr_reader :retry_after
14
+ # The +details+ of the +ErrorResponse+, as JSON text.
15
+ attr_reader :details
16
+ # The response body, as it came (empty on a client failure).
17
+ attr_reader :body
18
+
19
+ # The message of the +ErrorResponse+ alone (+message+ and +to_s+ also carry the code and the request id).
20
+ attr_reader :reason
21
+
22
+ def initialize(status, code, message, request_id: nil, retry_after: nil, details: nil, body: '')
23
+ super(message)
24
+ @reason = message
25
+ @status = status
26
+ @code = code || ''
27
+ @request_id = request_id
28
+ @retry_after = retry_after
29
+ @details = details
30
+ @body = body
31
+ end
32
+
33
+ def self.client(code, message)
34
+ new(0, code, message)
35
+ end
36
+
37
+ # A failure of the client itself, not a server response.
38
+ def client_side?
39
+ @status == 0
40
+ end
41
+
42
+ def to_s
43
+ suffix = @request_id.nil? ? '' : " (requestId #{@request_id})"
44
+ "#{@code}: #{@reason}#{suffix}"
45
+ end
46
+ end
47
+
48
+ # The call was cancelled through a CancelToken. It is not a Taba::Error: it is not a failure of the call.
49
+ class Cancelled < StandardError
50
+ def initialize(message = 'the call was cancelled')
51
+ super
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,175 @@
1
+ require 'json'
2
+ require 'taba/error'
3
+
4
+ module Taba
5
+ # The minimal JSON reader (doc 21, "No dependencies"): walks the text once and delivers the fields of an object as
6
+ # name => text fragment and the items of an array as text fragments, without interpreting them. That keeps the
7
+ # message +body+ exactly as the server sent it (+JSON.parse+ would turn +1.0+ into a Float and reformat the text).
8
+ class JsonError < StandardError; end
9
+
10
+ module JsonText
11
+ WHITESPACE = [0x20, 0x09, 0x0d, 0x0a].freeze
12
+ QUOTE = 0x22
13
+ BACKSLASH = 0x5c
14
+ OPEN = [0x7b, 0x5b].freeze # { [
15
+ CLOSE = [0x7d, 0x5d].freeze # } ]
16
+ DELIMITERS = [0x2c, 0x5d, 0x7d, 0x20, 0x09, 0x0d, 0x0a].freeze # , ] } and the whitespace
17
+
18
+ module_function
19
+
20
+ # The text as bytes: structural characters are ASCII, so multibyte characters need no care while scanning.
21
+ def bytes(text)
22
+ text.dup.force_encoding(Encoding::BINARY)
23
+ end
24
+
25
+ def skip(s, i)
26
+ i += 1 while i < s.bytesize && WHITESPACE.include?(s.getbyte(i))
27
+ i
28
+ end
29
+
30
+ def scan_string(s, i)
31
+ i += 1
32
+ n = s.bytesize
33
+ while i < n
34
+ c = s.getbyte(i)
35
+ if c == BACKSLASH
36
+ i += 1
37
+ elsif c == QUOTE
38
+ return i + 1
39
+ end
40
+ i += 1
41
+ end
42
+ raise JsonError, 'unterminated string'
43
+ end
44
+
45
+ # The index right after the value that starts at +i+ (iterative: deep nesting does not use the stack).
46
+ def scan_value(s, i)
47
+ n = s.bytesize
48
+ raise JsonError, 'value expected' if i >= n
49
+ first = s.getbyte(i)
50
+ return scan_string(s, i) if first == QUOTE
51
+ if OPEN.include?(first)
52
+ depth = 0
53
+ while i < n
54
+ c = s.getbyte(i)
55
+ if c == QUOTE
56
+ i = scan_string(s, i) - 1
57
+ elsif OPEN.include?(c)
58
+ depth += 1
59
+ elsif CLOSE.include?(c)
60
+ depth -= 1
61
+ return i + 1 if depth == 0
62
+ end
63
+ i += 1
64
+ end
65
+ raise JsonError, 'unterminated object or array'
66
+ end
67
+ start = i
68
+ i += 1 while i < n && !DELIMITERS.include?(s.getbyte(i))
69
+ raise JsonError, 'value expected' if i == start
70
+ i
71
+ end
72
+
73
+ def fragment(s, from, to)
74
+ s.byteslice(from, to - from).force_encoding(Encoding::UTF_8)
75
+ end
76
+
77
+ # Decodes a string fragment (with the quotes) into text.
78
+ def decode_string(fragment)
79
+ raise JsonError, 'string expected' unless fragment.start_with?('"')
80
+ value = ::JSON.parse(fragment, quirks_mode: true)
81
+ raise JsonError, 'invalid string' unless value.is_a?(String)
82
+ value
83
+ rescue ::JSON::ParserError
84
+ raise JsonError, 'invalid string'
85
+ end
86
+
87
+ # The items of an array fragment, each as a text fragment.
88
+ def items(text)
89
+ s = bytes(text)
90
+ i = skip(s, 0)
91
+ raise JsonError, 'array expected' if i >= s.bytesize || s.getbyte(i) != 0x5b
92
+ items = []
93
+ i = skip(s, i + 1)
94
+ return items if i < s.bytesize && s.getbyte(i) == 0x5d
95
+ loop do
96
+ i = skip(s, i)
97
+ stop = scan_value(s, i)
98
+ items << fragment(s, i, stop)
99
+ i = skip(s, stop)
100
+ if i < s.bytesize && s.getbyte(i) == 0x2c
101
+ i += 1
102
+ elsif i < s.bytesize && s.getbyte(i) == 0x5d
103
+ return items
104
+ else
105
+ raise JsonError, '"," or "]" expected'
106
+ end
107
+ end
108
+ end
109
+ end
110
+
111
+ # The fields of one JSON object.
112
+ class JsonFields
113
+ def self.parse(text)
114
+ s = JsonText.bytes(text)
115
+ n = s.bytesize
116
+ fields = {}
117
+ i = JsonText.skip(s, 0)
118
+ raise JsonError, 'object expected' if i >= n || s.getbyte(i) != 0x7b
119
+ i = JsonText.skip(s, i + 1)
120
+ raise JsonError, 'unterminated object' if i >= n
121
+ if s.getbyte(i) != 0x7d
122
+ loop do
123
+ i = JsonText.skip(s, i)
124
+ raise JsonError, 'field name expected' if i >= n || s.getbyte(i) != 0x22
125
+ key_end = JsonText.scan_string(s, i)
126
+ key = JsonText.decode_string(JsonText.fragment(s, i, key_end))
127
+ i = JsonText.skip(s, key_end)
128
+ raise JsonError, '":" expected' if i >= n || s.getbyte(i) != 0x3a
129
+ i = JsonText.skip(s, i + 1)
130
+ stop = JsonText.scan_value(s, i)
131
+ fields[key] = JsonText.fragment(s, i, stop)
132
+ i = JsonText.skip(s, stop)
133
+ if i < n && s.getbyte(i) == 0x2c
134
+ i += 1
135
+ elsif i < n && s.getbyte(i) == 0x7d
136
+ break
137
+ else
138
+ raise JsonError, '"," or "}" expected'
139
+ end
140
+ end
141
+ end
142
+ raise JsonError, 'unexpected text after the object' if JsonText.skip(s, i + 1) != n
143
+ new(fields)
144
+ end
145
+
146
+ def initialize(fields)
147
+ @fields = fields
148
+ end
149
+
150
+ # The field's text fragment, or nil when absent or +null+.
151
+ def raw(name)
152
+ value = @fields[name]
153
+ value.nil? || value == 'null' ? nil : value
154
+ end
155
+
156
+ def string(name)
157
+ value = raw(name)
158
+ value.nil? ? nil : JsonText.decode_string(value)
159
+ end
160
+
161
+ def boolean(name)
162
+ value = raw(name)
163
+ return nil if value.nil?
164
+ return value == 'true' if %w(true false).include?(value)
165
+ raise JsonError, "field \"#{name}\" is not a boolean"
166
+ end
167
+
168
+ def integer(name)
169
+ value = raw(name)
170
+ return nil if value.nil?
171
+ raise JsonError, "field \"#{name}\" is not an integer" unless value =~ /\A-?[0-9]+\z/
172
+ value.to_i
173
+ end
174
+ end
175
+ end