galaxy-ruby 0.4.0 → 0.6.0

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.
Files changed (102) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +188 -0
  3. data/README.md +26 -5
  4. data/SKILL.md +6 -4
  5. data/api.md +8 -8
  6. data/lib/galaxy-ruby/client.rb +52 -41
  7. data/lib/galaxy-ruby/errors.rb +40 -0
  8. data/lib/galaxy-ruby/file_part.rb +13 -1
  9. data/lib/galaxy-ruby/internal/transport/base_client.rb +278 -42
  10. data/lib/galaxy-ruby/internal/transport/connection_pool.rb +160 -0
  11. data/lib/galaxy-ruby/internal/transport/pooled_net_requester.rb +77 -10
  12. data/lib/galaxy-ruby/internal/type/base_model.rb +62 -17
  13. data/lib/galaxy-ruby/internal/type/boolean.rb +3 -1
  14. data/lib/galaxy-ruby/internal/type/converter.rb +13 -3
  15. data/lib/galaxy-ruby/internal/type/enum.rb +9 -4
  16. data/lib/galaxy-ruby/internal/type/file_input.rb +8 -2
  17. data/lib/galaxy-ruby/internal/type/hash_of.rb +3 -1
  18. data/lib/galaxy-ruby/internal/type/union.rb +17 -6
  19. data/lib/galaxy-ruby/internal/type/unknown.rb +3 -1
  20. data/lib/galaxy-ruby/internal/util.rb +273 -15
  21. data/lib/galaxy-ruby/internal/webhook_verifier.rb +240 -0
  22. data/lib/galaxy-ruby/internal.rb +4 -1
  23. data/lib/galaxy-ruby/models/authentication_create_token_params.rb +7 -1
  24. data/lib/galaxy-ruby/models/authentication_create_user_params.rb +2 -0
  25. data/lib/galaxy-ruby/models/celestial_body_create_params.rb +3 -3
  26. data/lib/galaxy-ruby/models/celestial_body_param.rb +72 -0
  27. data/lib/galaxy-ruby/models/credentials.rb +1 -9
  28. data/lib/galaxy-ruby/models/planet_create_params.rb +11 -1
  29. data/lib/galaxy-ruby/models/{planet_list_all_data_params.rb → planet_list_params.rb} +2 -2
  30. data/lib/galaxy-ruby/models/{planet_list_all_data_response.rb → planet_list_response.rb} +9 -9
  31. data/lib/galaxy-ruby/models/planet_param.rb +204 -0
  32. data/lib/galaxy-ruby/models/planet_update_params.rb +12 -1
  33. data/lib/galaxy-ruby/models/{planet_delte_image_params.rb → planet_upload_image_params.rb} +2 -2
  34. data/lib/galaxy-ruby/models/{planet_delte_image_response.rb → planet_upload_image_response.rb} +2 -2
  35. data/lib/galaxy-ruby/models/user_param.rb +19 -0
  36. data/lib/galaxy-ruby/models/webhook_unwrap_params.rb +2 -0
  37. data/lib/galaxy-ruby/models.rb +38 -33
  38. data/lib/galaxy-ruby/request_options.rb +13 -5
  39. data/lib/galaxy-ruby/resources/celestial_bodies.rb +1 -1
  40. data/lib/galaxy-ruby/resources/planets.rb +37 -47
  41. data/lib/galaxy-ruby/resources/webhooks.rb +63 -6
  42. data/lib/galaxy-ruby/version.rb +1 -1
  43. data/lib/galaxy-ruby.rb +12 -10
  44. data/rbi/galaxy-ruby/client.rbi +28 -5
  45. data/rbi/galaxy-ruby/errors.rbi +25 -27
  46. data/rbi/galaxy-ruby/internal/transport/base_client.rbi +88 -68
  47. data/rbi/galaxy-ruby/internal/transport/connection_pool.rbi +44 -0
  48. data/rbi/galaxy-ruby/internal/transport/pooled_net_requester.rbi +18 -19
  49. data/rbi/galaxy-ruby/internal/type/base_model.rbi +27 -49
  50. data/rbi/galaxy-ruby/internal/type/base_page.rbi +1 -2
  51. data/rbi/galaxy-ruby/internal/type/converter.rbi +12 -51
  52. data/rbi/galaxy-ruby/internal/type/enum.rbi +1 -5
  53. data/rbi/galaxy-ruby/internal/type/request_parameters.rbi +2 -6
  54. data/rbi/galaxy-ruby/internal/type/union.rbi +2 -11
  55. data/rbi/galaxy-ruby/internal/util.rbi +101 -115
  56. data/rbi/galaxy-ruby/internal/webhook_verifier.rbi +86 -0
  57. data/rbi/galaxy-ruby/internal.rbi +1 -4
  58. data/rbi/galaxy-ruby/models/authentication_create_token_params.rbi +11 -5
  59. data/rbi/galaxy-ruby/models/celestial_body_create_params.rbi +8 -5
  60. data/rbi/galaxy-ruby/models/celestial_body_param.rbi +138 -0
  61. data/rbi/galaxy-ruby/models/credentials.rbi +2 -5
  62. data/rbi/galaxy-ruby/models/planet_create_params.rbi +22 -5
  63. data/rbi/galaxy-ruby/models/{planet_list_all_data_params.rbi → planet_list_params.rbi} +2 -5
  64. data/rbi/galaxy-ruby/models/{planet_list_all_data_response.rbi → planet_list_response.rbi} +11 -15
  65. data/rbi/galaxy-ruby/models/planet_param.rbi +346 -0
  66. data/rbi/galaxy-ruby/models/planet_update_params.rbi +19 -2
  67. data/rbi/galaxy-ruby/models/{planet_delte_image_params.rbi → planet_upload_image_params.rbi} +2 -2
  68. data/rbi/galaxy-ruby/models/{planet_delte_image_response.rbi → planet_upload_image_response.rbi} +2 -2
  69. data/rbi/galaxy-ruby/models/unwrap_webhook_event.rbi +1 -1
  70. data/rbi/galaxy-ruby/models/user_param.rbi +27 -0
  71. data/rbi/galaxy-ruby/models/webhook_unwrap_params.rbi +2 -0
  72. data/rbi/galaxy-ruby/models.rbi +10 -2
  73. data/rbi/galaxy-ruby/request_options.rbi +4 -10
  74. data/rbi/galaxy-ruby/resources/celestial_bodies.rbi +2 -2
  75. data/rbi/galaxy-ruby/resources/planets.rbi +22 -30
  76. data/rbi/galaxy-ruby/resources/webhooks.rbi +64 -3
  77. data/sig/galaxy-ruby/client.rbs +13 -5
  78. data/sig/galaxy-ruby/errors.rbs +13 -0
  79. data/sig/galaxy-ruby/internal/transport/base_client.rbs +38 -2
  80. data/sig/galaxy-ruby/internal/transport/connection_pool.rbs +19 -0
  81. data/sig/galaxy-ruby/internal/transport/pooled_net_requester.rbs +13 -2
  82. data/sig/galaxy-ruby/internal/type/base_model.rbs +4 -0
  83. data/sig/galaxy-ruby/internal/util.rbs +29 -1
  84. data/sig/galaxy-ruby/internal/webhook_verifier.rbs +53 -0
  85. data/sig/galaxy-ruby/models/authentication_create_token_params.rbs +13 -3
  86. data/sig/galaxy-ruby/models/celestial_body_create_params.rbs +4 -4
  87. data/sig/galaxy-ruby/models/celestial_body_param.rbs +69 -0
  88. data/sig/galaxy-ruby/models/credentials.rbs +1 -3
  89. data/sig/galaxy-ruby/models/planet_create_params.rbs +14 -3
  90. data/sig/galaxy-ruby/models/{planet_list_all_data_params.rbs → planet_list_params.rbs} +2 -2
  91. data/sig/galaxy-ruby/models/{planet_list_all_data_response.rbs → planet_list_response.rbs} +15 -13
  92. data/sig/galaxy-ruby/models/planet_param.rbs +199 -0
  93. data/sig/galaxy-ruby/models/planet_update_params.rbs +8 -1
  94. data/sig/galaxy-ruby/models/{planet_delte_image_params.rbs → planet_upload_image_params.rbs} +2 -2
  95. data/sig/galaxy-ruby/models/{planet_delte_image_response.rbs → planet_upload_image_response.rbs} +2 -2
  96. data/sig/galaxy-ruby/models/user_param.rbs +15 -0
  97. data/sig/galaxy-ruby/models/webhook_unwrap_params.rbs +4 -0
  98. data/sig/galaxy-ruby/models.rbs +10 -2
  99. data/sig/galaxy-ruby/resources/celestial_bodies.rbs +1 -1
  100. data/sig/galaxy-ruby/resources/planets.rbs +10 -14
  101. data/sig/galaxy-ruby/resources/webhooks.rbs +17 -1
  102. metadata +32 -71
@@ -160,7 +160,8 @@ module ScalarGalaxy
160
160
  in Hash | nil => coerced
161
161
  coerced
162
162
  else
163
- message = "Expected a #{Hash} or #{ScalarGalaxy::Internal::Type::BaseModel}, got #{input.inspect}"
163
+ message =
164
+ "Expected a #{Hash} or #{ScalarGalaxy::Internal::Type::BaseModel}, got #{input.inspect}"
164
165
  raise ArgumentError.new(message)
165
166
  end
166
167
  end
@@ -250,7 +251,12 @@ module ScalarGalaxy
250
251
  #
251
252
  # @return [String]
252
253
  def uri_origin(uri)
253
- "#{uri.scheme}://#{uri.host}#{":#{uri.port}" unless uri.port == uri.default_port}"
254
+ # Re-parsed because `unparse_uri` and `join_parsed_uri` build a plain `URI::Generic`, which
255
+ # knows no default port, and the host downcased because hosts are case-insensitive. Without
256
+ # both, `https://API.example.com:443` and `https://api.example.com` read as two origins, and
257
+ # a same-origin redirect loses its credentials.
258
+ uri = URI(uri.to_s)
259
+ "#{uri.scheme}://#{uri.host&.downcase}#{":#{uri.port}" unless uri.port == uri.default_port}"
254
260
  end
255
261
 
256
262
  # @api private
@@ -259,13 +265,28 @@ module ScalarGalaxy
259
265
  #
260
266
  # @return [String]
261
267
  def encode_path(path)
262
- path.to_s.gsub(ScalarGalaxy::Internal::Util::RFC_3986_NOT_PCHARS) { ERB::Util.url_encode(_1) }
268
+ path
269
+ .to_s
270
+ .gsub(ScalarGalaxy::Internal::Util::RFC_3986_NOT_PCHARS) do
271
+ ERB::Util.url_encode(_1)
272
+ end
263
273
  end
264
274
 
265
275
  # @api private
266
276
  #
277
+ # Fills a path template with its encoded parameters, refusing a value that would address a
278
+ # different endpoint than the one the method names.
279
+ #
280
+ # Encoding stops a value from adding `/`, `?` or `#`, but not from being a whole segment of its
281
+ # own: `URI.join` resolves a `.` or `..` segment away, so a `..` id would send the request, with
282
+ # the client's credentials, to the parent resource, and an empty value silently addresses the
283
+ # parent collection. Both are refused before any request is built. The assembled path is
284
+ # checked as well as each value, because values that pass alone can combine (`{a}{b}` with two
285
+ # `.`s). A `%2e` spelling is not a dot segment here: `encode_path` escapes its `%`.
286
+ #
267
287
  # @param path [String, Array<String>]
268
288
  #
289
+ # @raise [ArgumentError]
269
290
  # @return [String]
270
291
  def interpolate_path(path)
271
292
  case path
@@ -275,7 +296,21 @@ module ScalarGalaxy
275
296
  ""
276
297
  in [String => p, *interpolations]
277
298
  encoded = interpolations.map { encode_path(_1) }
278
- format(p, *encoded)
299
+ if encoded.any?(&:empty?)
300
+ raise ArgumentError.new(
301
+ "A path parameter in `#{p}` is empty, which would address a different endpoint."
302
+ )
303
+ end
304
+
305
+ assembled = format(p, *encoded)
306
+ # Only the path takes part in dot-segment removal, not a query the template carries.
307
+ segment = assembled.split(/[?#]/, 2).first.to_s.split("/").find { %w[. ..].include?(_1) }
308
+ unless segment.nil?
309
+ message =
310
+ "The request path `#{assembled}` contains a #{segment.inspect} segment, which would address a different endpoint."
311
+ raise ArgumentError.new(message)
312
+ end
313
+ assembled
279
314
  end
280
315
  end
281
316
  end
@@ -287,7 +322,43 @@ module ScalarGalaxy
287
322
  #
288
323
  # @return [Hash{String=>Array<String>}]
289
324
  def decode_query(query)
290
- CGI.parse(query.to_s)
325
+ # Pairs split on `;` as well as `&`, empty pairs are skipped, and a key with no `=` maps to
326
+ # `[]` rather than `[""]`, so a bare flag survives as a key without gaining a value.
327
+ # `URI.decode_www_form` does none of those, and on Ruby 3.2 it also swaps bytes that are not
328
+ # UTF-8 for U+FFFD, which would rewrite a query value the client re-sends.
329
+ pairs = query.to_s.split(/[&;]/)
330
+ decoded = {}
331
+ pairs.each do |pair|
332
+ key, value = pair.split("=", 2).map { unescape_query_component(_1) }
333
+ next if key.nil?
334
+
335
+ values = (decoded[key] ||= [])
336
+ values << value unless value.nil?
337
+ end
338
+ # Callers read absent keys as "no values" (`decoded[key].empty?`), so a miss is `[]`. Frozen,
339
+ # so an `<<` on a miss raises instead of writing into the one array every miss shares.
340
+ decoded.default = [].freeze
341
+ decoded
342
+ end
343
+
344
+ # @api private
345
+ #
346
+ # `+` is a space, and each run of `%XX` escapes becomes the bytes it encodes. A `%` that starts
347
+ # no valid escape is kept as written rather than raising. The result is UTF-8 when its bytes
348
+ # are, else it keeps the input's encoding.
349
+ #
350
+ # `CGI.unescape` stops decoding at a `%` in a component's last two bytes, which leaves a
351
+ # trailing `%+` as written; that one case is kept, so no decoded value changes.
352
+ #
353
+ # @param component [String]
354
+ #
355
+ # @return [String]
356
+ private def unescape_query_component(component)
357
+ bytes = component.b
358
+ kept = bytes.end_with?("%+") ? bytes.slice!(-1..) : ""
359
+ unescaped = bytes.tr("+", " ").gsub(/(?:%\h\h)+/) { [_1.delete("%")].pack("H*") } << kept
360
+ unescaped.force_encoding(Encoding::UTF_8)
361
+ unescaped.valid_encoding? ? unescaped : unescaped.force_encoding(component.encoding)
291
362
  end
292
363
 
293
364
  # @api private
@@ -398,6 +469,48 @@ module ScalarGalaxy
398
469
  [key.downcase, value]
399
470
  end
400
471
  end
472
+
473
+ # @api private
474
+ #
475
+ # A cookie value percent-encoded the way `encodeURIComponent` encodes one, byte by byte.
476
+ #
477
+ # A cookie parameter is caller input, often end-user input, and the `Cookie` header gives `;`,
478
+ # `,`, whitespace, `"` and `\` meaning: left raw, `x; sid=evil` would add a cookie of its own and
479
+ # could stand in for the client's credential cookie.
480
+ #
481
+ # @param value [Object]
482
+ #
483
+ # @return [String]
484
+ def encode_cookie_value(value)
485
+ value.to_s.b.gsub(/[^A-Za-z0-9\-_.!~*'()]/n) { format("%%%02X", _1.ord) }
486
+ end
487
+
488
+ # @api private
489
+ #
490
+ # Joins `Cookie` header values into one, by cookie name: a later value replaces an earlier
491
+ # cookie of the same name and adds the rest, in the order they first appeared.
492
+ #
493
+ # The client's credential cookie and an operation's cookie parameters arrive as separate
494
+ # `cookie` headers, and a plain header merge would let the operation's replace the credential's
495
+ # outright. Merging by name keeps both, while an operation parameter that shares the
496
+ # credential's name still replaces that one cookie.
497
+ #
498
+ # @param values [Array<String, nil>]
499
+ #
500
+ # @return [String, nil]
501
+ def merge_cookies(*values)
502
+ merged = {}
503
+ values.each do |value|
504
+ value
505
+ .to_s
506
+ .split(";")
507
+ .each do |pair|
508
+ name = pair.split("=", 2).first.to_s.strip
509
+ merged[name] = pair.strip unless name.empty?
510
+ end
511
+ end
512
+ merged.empty? ? nil : merged.values.join("; ")
513
+ end
401
514
  end
402
515
 
403
516
  # @api private
@@ -501,10 +614,23 @@ module ScalarGalaxy
501
614
  end
502
615
 
503
616
  # @type [Regexp]
504
- JSON_CONTENT = %r{^application/(?:[a-zA-Z0-9.-]+\+)?json(?!l)}
617
+ JSON_CONTENT = %r{^application/(?:[a-zA-Z0-9.-]+\+)?json(?!l)}i
505
618
  # @type [Regexp]
506
619
  JSONL_CONTENT = %r{^application/(:?x-(?:n|l)djson)|(:?(?:x-)?jsonl)}
507
620
 
621
+ # Most bytes of a response body the SDK holds to decode it, counted after decompression.
622
+ # @type [Integer]
623
+ MAX_BUFFERED_BODY_BYTES = 64 * 1024 * 1024
624
+
625
+ # Most bytes of an error response read for the error's `body`; the rest is never read.
626
+ # @type [Integer]
627
+ MAX_ERROR_BODY_BYTES = 64 * 1024
628
+
629
+ # Most bytes one pending stream line or server-sent event may hold before the stream fails, so
630
+ # a server that never ends one cannot grow the buffer without bound.
631
+ # @type [Integer]
632
+ MAX_PENDING_STREAM_BYTES = 64 * 1024 * 1024
633
+
508
634
  class << self
509
635
  # @api private
510
636
  #
@@ -529,7 +655,9 @@ module ScalarGalaxy
529
655
  in Hash
530
656
  element.each { |name, value| write_query_param_element!(collection, "#{key}[#{name}]", value) }
531
657
  in Array
532
- collection[key] = element.map(&:to_s).join(",")
658
+ collection[key] = element.map { _1.is_a?(Time) ? _1.iso8601 : _1.to_s }.join(",")
659
+ in Time
660
+ collection[key] = element.iso8601
533
661
  else
534
662
  collection[key] = element.to_s
535
663
  end
@@ -570,6 +698,20 @@ module ScalarGalaxy
570
698
  y << "\r\n"
571
699
  end
572
700
 
701
+ # @api private
702
+ #
703
+ # A multipart field name escaped for its quoted `name` parameter: `"` as `%22`, a backslash
704
+ # doubled, and every C0 control but ESC as `%XX`. A body hash can carry a caller's keys, and
705
+ # left raw a `"` would end the quoted name early and a CR or LF would start a part header of
706
+ # its own.
707
+ #
708
+ # @param name [Symbol, String]
709
+ #
710
+ # @return [String]
711
+ def encode_form_name(name)
712
+ name.to_s.gsub(/["\\\x00-\x1A\x1C-\x1F]/) { _1 == "\\" ? "\\\\" : format("%%%02X", _1.ord) }
713
+ end
714
+
573
715
  # @api private
574
716
  #
575
717
  # @param y [Enumerator::Yielder]
@@ -581,13 +723,13 @@ module ScalarGalaxy
581
723
  y << "--#{boundary}\r\n"
582
724
  y << "Content-Disposition: form-data"
583
725
 
584
- y << "; name=\"#{key}\"" unless key.nil?
726
+ y << "; name=\"#{encode_form_name(key)}\"" unless key.nil?
585
727
 
586
728
  case val
587
729
  in ScalarGalaxy::FilePart unless val.filename.nil?
588
730
  filename = encode_path(val.filename)
589
731
  y << "; filename=\"#{filename}\""
590
- in Pathname | IO
732
+ in Pathname | IO if val.respond_to?(:to_path)
591
733
  filename = encode_path(::File.basename(val.to_path))
592
734
  y << "; filename=\"#{filename}\""
593
735
  else
@@ -610,13 +752,14 @@ module ScalarGalaxy
610
752
  boundary = SecureRandom.urlsafe_base64(46)
611
753
 
612
754
  closing = []
755
+ file_input = ScalarGalaxy::Internal::Type::FileInput
613
756
  strio =
614
757
  writable_enum do |y|
615
758
  case body
616
759
  in Hash
617
760
  body.each do |key, val|
618
761
  case val
619
- in Array if val.all? { primitive?(_1) || ScalarGalaxy::Internal::Type::FileInput === _1 }
762
+ in Array if val.all? { primitive?(_1) || file_input === _1 }
620
763
  val.each do |v|
621
764
  write_multipart_chunk(y, boundary: boundary, key: key, val: v, closing: closing)
622
765
  end
@@ -635,6 +778,41 @@ module ScalarGalaxy
635
778
  # rubocop:enable Style/CaseEquality
636
779
  end
637
780
 
781
+ # @api private
782
+ #
783
+ # A form body is encoded the way the query string is, through `encode_query_params`, so a list
784
+ # follows the configured array format and an object nests as `key[name]`. A form has no file
785
+ # parts, so a file value goes out as its contents, the way a string field would.
786
+ #
787
+ # @param body [Hash{Symbol=>Object}]
788
+ #
789
+ # @return [String]
790
+ def encode_form(body)
791
+ URI.encode_www_form(encode_query_params(form_field_value(body)))
792
+ end
793
+
794
+ # @api private
795
+ #
796
+ # @param value [Object]
797
+ #
798
+ # @return [Object]
799
+ private def form_field_value(value)
800
+ case value
801
+ in Hash
802
+ value.transform_values { form_field_value(_1) }
803
+ in Array
804
+ value.map { form_field_value(_1) }
805
+ in ScalarGalaxy::FilePart
806
+ form_field_value(value.content)
807
+ in StringIO
808
+ value.string
809
+ in IO | Pathname
810
+ value.read
811
+ else
812
+ value
813
+ end
814
+ end
815
+
638
816
  # @api private
639
817
  #
640
818
  # @param headers [Hash{String=>String}]
@@ -652,6 +830,8 @@ module ScalarGalaxy
652
830
  Enumerable
653
831
  ] unless ScalarGalaxy::Internal::Type::FileInput === body
654
832
  [headers, body.lazy.map { JSON.generate(_1) }]
833
+ in [%r{^application/x-www-form-urlencoded}i, Hash]
834
+ [headers, encode_form(body)]
655
835
  in [%r{^multipart/form-data}, Hash | ScalarGalaxy::Internal::Type::FileInput]
656
836
  boundary, strio = encode_multipart_streaming(body)
657
837
  headers = {**headers, "content-type" => "#{content_type}; boundary=#{boundary}"}
@@ -687,20 +867,68 @@ module ScalarGalaxy
687
867
  end
688
868
  end
689
869
 
870
+ # @api private
871
+ #
872
+ # Reads a body into one string, holding at most `limit` bytes of it.
873
+ #
874
+ # The chunks are counted as they arrive, after `Net::HTTP` has inflated a `gzip` or `deflate`
875
+ # body, so a small compressed response cannot inflate past the limit in memory. Over the limit
876
+ # a body is either refused or, with `truncate`, cut at the limit and the rest left unread;
877
+ # leaving the iteration early closes the connection rather than draining it.
878
+ #
879
+ # @param stream [Enumerable<String>]
880
+ # @param limit [Integer]
881
+ # @param truncate [Boolean]
882
+ #
883
+ # @raise [ScalarGalaxy::Errors::Error] when the body is over `limit` and `truncate` is false
884
+ # @return [String]
885
+ def read_body(stream, limit:, truncate: false)
886
+ body = String.new
887
+ stream.each do |chunk|
888
+ room = limit - body.bytesize
889
+ if chunk.bytesize > room
890
+ unless truncate
891
+ message = "The response body is larger than the #{limit}-byte limit for a buffered response."
892
+ raise ScalarGalaxy::Errors::Error.new(message)
893
+ end
894
+
895
+ body << chunk.byteslice(0, room)
896
+ break
897
+ end
898
+ body << chunk
899
+ end
900
+ body
901
+ end
902
+
690
903
  # @api private
691
904
  #
692
905
  # Assumes each chunk in stream has `Encoding::BINARY`.
693
906
  #
907
+ # A buffered body is held to {MAX_BUFFERED_BODY_BYTES}, whatever its type: the type is the
908
+ # server's word, so a JSON answer labelled `text/plain` (or not labelled) must not escape the
909
+ # limit. Only `download` lifts it, and the caller sets that from the operation's declared
910
+ # binary model, never from the response. With `truncate_at` (an error response, read only for
911
+ # its message) every buffered type keeps at most that many bytes.
912
+ #
694
913
  # @param headers [Hash{String=>String}]
695
914
  # @param stream [Enumerable<String>]
696
915
  # @param suppress_error [Boolean]
916
+ # @param truncate_at [Integer, nil]
917
+ # @param download [Boolean] the operation returns raw bytes the caller asked for
697
918
  #
698
919
  # @raise [JSON::ParserError]
920
+ # @raise [ScalarGalaxy::Errors::Error] when a buffered body is over the buffered-body limit
699
921
  # @return [Object]
700
- def decode_content(headers, stream:, suppress_error: false)
922
+ def decode_content(headers, stream:, suppress_error: false, truncate_at: nil, download: false)
701
923
  case (content_type = headers["content-type"])
702
924
  in ScalarGalaxy::Internal::Util::JSON_CONTENT
703
- return nil if (json = stream.to_a.join).empty?
925
+ json =
926
+ if truncate_at.nil?
927
+ read_body(stream, limit: ScalarGalaxy::Internal::Util::MAX_BUFFERED_BODY_BYTES)
928
+ else
929
+ read_body(stream, limit: truncate_at, truncate: true)
930
+ end
931
+ return nil if json.empty?
704
932
 
705
933
  begin
706
934
  JSON.parse(json, symbolize_names: true)
@@ -721,7 +949,14 @@ module ScalarGalaxy
721
949
  lines = decode_lines(stream)
722
950
  decode_sse(lines)
723
951
  else
724
- text = stream.to_a.join
952
+ text =
953
+ if !truncate_at.nil?
954
+ read_body(stream, limit: truncate_at, truncate: true)
955
+ elsif download
956
+ stream.to_a.join
957
+ else
958
+ read_body(stream, limit: ScalarGalaxy::Internal::Util::MAX_BUFFERED_BODY_BYTES)
959
+ end
725
960
  force_charset!(content_type, text: text)
726
961
  StringIO.new(text)
727
962
  end
@@ -764,9 +999,8 @@ module ScalarGalaxy
764
999
  def close_fused!(enum)
765
1000
  return unless enum.is_a?(Enumerator)
766
1001
 
767
- # rubocop:disable Lint/UnreachableLoop
1002
+ # rubocop:disable-next Lint/UnreachableLoop
768
1003
  enum.rewind.each { break }
769
- # rubocop:enable Lint/UnreachableLoop
770
1004
  end
771
1005
 
772
1006
  # @api private
@@ -790,8 +1024,12 @@ module ScalarGalaxy
790
1024
  # This decoder is responsible for reassembling lines split across multiple
791
1025
  # fragments.
792
1026
  #
1027
+ # A line still pending past {MAX_PENDING_STREAM_BYTES} fails the stream: the server controls
1028
+ # where lines end, and one that never ends would otherwise be buffered without bound.
1029
+ #
793
1030
  # @param enum [Enumerable<String>]
794
1031
  #
1032
+ # @raise [ScalarGalaxy::Errors::Error] when one line outgrows the pending-line limit
795
1033
  # @return [Enumerable<String>]
796
1034
  def decode_lines(enum)
797
1035
  re = /(\r\n|\r|\n)/
@@ -815,6 +1053,7 @@ module ScalarGalaxy
815
1053
  offset = 0
816
1054
  cr_seen = nil
817
1055
  end
1056
+ check_pending_stream!(buffer.bytesize)
818
1057
  end
819
1058
 
820
1059
  y << buffer.slice!(..(cr_seen.pred)) unless cr_seen.nil?
@@ -822,6 +1061,22 @@ module ScalarGalaxy
822
1061
  end
823
1062
  end
824
1063
 
1064
+ # @api private
1065
+ #
1066
+ # Fails a stream whose pending line or event has outgrown {MAX_PENDING_STREAM_BYTES}.
1067
+ #
1068
+ # @param bytesize [Integer]
1069
+ #
1070
+ # @raise [ScalarGalaxy::Errors::Error]
1071
+ private def check_pending_stream!(bytesize)
1072
+ limit = ScalarGalaxy::Internal::Util::MAX_PENDING_STREAM_BYTES
1073
+ return if bytesize <= limit
1074
+
1075
+ raise ScalarGalaxy::Errors::Error.new(
1076
+ "A stream line or event is larger than the #{limit}-byte limit."
1077
+ )
1078
+ end
1079
+
825
1080
  # @api private
826
1081
  #
827
1082
  # https://html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream
@@ -851,7 +1106,10 @@ module ScalarGalaxy
851
1106
  in "event"
852
1107
  current.merge!(event: value)
853
1108
  in "data"
1109
+ # An event's `data` lines accumulate until a blank line, which the server may
1110
+ # never send, so the event is held to the same limit as one line.
854
1111
  (current[:data] ||= String.new) << (value << "\n")
1112
+ check_pending_stream!(current[:data].bytesize)
855
1113
  in "id" unless value.include?("\0")
856
1114
  current.merge!(id: value)
857
1115
  in "retry" if /^\d+$/ =~ value