scalar_api_ruby 0.2.0 → 0.3.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 (160) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +71 -0
  3. data/README.md +5 -3
  4. data/SKILL.md +3 -1
  5. data/api.md +20 -181
  6. data/lib/scalar_api_ruby/client.rb +14 -5
  7. data/lib/scalar_api_ruby/errors.rb +22 -0
  8. data/lib/scalar_api_ruby/file_part.rb +13 -1
  9. data/lib/scalar_api_ruby/internal/transport/base_client.rb +187 -42
  10. data/lib/scalar_api_ruby/internal/transport/connection_pool.rb +160 -0
  11. data/lib/scalar_api_ruby/internal/transport/pooled_net_requester.rb +77 -10
  12. data/lib/scalar_api_ruby/internal/type/base_model.rb +70 -18
  13. data/lib/scalar_api_ruby/internal/type/boolean.rb +3 -1
  14. data/lib/scalar_api_ruby/internal/type/converter.rb +13 -3
  15. data/lib/scalar_api_ruby/internal/type/enum.rb +9 -4
  16. data/lib/scalar_api_ruby/internal/type/file_input.rb +8 -2
  17. data/lib/scalar_api_ruby/internal/type/hash_of.rb +3 -1
  18. data/lib/scalar_api_ruby/internal/type/union.rb +21 -7
  19. data/lib/scalar_api_ruby/internal/type/unknown.rb +3 -1
  20. data/lib/scalar_api_ruby/internal/util.rb +277 -17
  21. data/lib/scalar_api_ruby/internal.rb +5 -1
  22. data/lib/scalar_api_ruby/models/access_group_create_params.rb +3 -3
  23. data/lib/scalar_api_ruby/models/access_group_create_response.rb +6 -6
  24. data/lib/scalar_api_ruby/models/access_group_retrieve_response.rb +6 -6
  25. data/lib/scalar_api_ruby/models/api_document.rb +3 -3
  26. data/lib/scalar_api_ruby/models/docs_project.rb +3 -3
  27. data/lib/scalar_api_ruby/models/github_project.rb +16 -4
  28. data/lib/scalar_api_ruby/models/mcp/mcp_server.rb +23 -18
  29. data/lib/scalar_api_ruby/models/mcp/server_create_response.rb +1 -7
  30. data/lib/scalar_api_ruby/models/mcp/server_list_response.rb +72 -1
  31. data/lib/scalar_api_ruby/models/sdk.rb +13 -7
  32. data/lib/scalar_api_ruby/models/sdk_build_params.rb +7 -1
  33. data/lib/scalar_api_ruby/models/sdk_create_params.rb +14 -7
  34. data/lib/scalar_api_ruby/models/sdk_update_params.rb +13 -3
  35. data/lib/scalar_api_ruby/models/sdk_version.rb +5 -34
  36. data/lib/scalar_api_ruby/models/sdks/repository_link_params.rb +33 -2
  37. data/lib/scalar_api_ruby/models/sdks/repository_update_publishing_params.rb +31 -1
  38. data/lib/scalar_api_ruby/models/sdks/version_create_params.rb +13 -7
  39. data/lib/scalar_api_ruby/models.rb +28 -31
  40. data/lib/scalar_api_ruby/request_options.rb +13 -5
  41. data/lib/scalar_api_ruby/resources/access_groups.rb +1 -1
  42. data/lib/scalar_api_ruby/resources/mcp/servers.rb +7 -74
  43. data/lib/scalar_api_ruby/resources/registry.rb +44 -16
  44. data/lib/scalar_api_ruby/resources/rules.rb +16 -8
  45. data/lib/scalar_api_ruby/resources/schemas/access_group.rb +6 -2
  46. data/lib/scalar_api_ruby/resources/schemas/version.rb +18 -8
  47. data/lib/scalar_api_ruby/resources/schemas.rb +6 -2
  48. data/lib/scalar_api_ruby/resources/sdks/repositories.rb +38 -6
  49. data/lib/scalar_api_ruby/resources/sdks/versions.rb +22 -5
  50. data/lib/scalar_api_ruby/resources/sdks.rb +45 -10
  51. data/lib/scalar_api_ruby/resources/themes.rb +1 -3
  52. data/lib/scalar_api_ruby/version.rb +1 -1
  53. data/lib/scalar_api_ruby.rb +4 -19
  54. data/rbi/scalar_api_ruby/client.rbi +5 -0
  55. data/rbi/scalar_api_ruby/errors.rbi +15 -27
  56. data/rbi/scalar_api_ruby/internal/transport/base_client.rbi +45 -54
  57. data/rbi/scalar_api_ruby/internal/transport/connection_pool.rbi +44 -0
  58. data/rbi/scalar_api_ruby/internal/transport/pooled_net_requester.rbi +14 -14
  59. data/rbi/scalar_api_ruby/internal/type/base_model.rbi +28 -35
  60. data/rbi/scalar_api_ruby/internal/type/converter.rbi +9 -30
  61. data/rbi/scalar_api_ruby/internal/type/enum.rbi +1 -5
  62. data/rbi/scalar_api_ruby/internal/type/request_parameters.rbi +1 -3
  63. data/rbi/scalar_api_ruby/internal/type/union.rbi +2 -9
  64. data/rbi/scalar_api_ruby/internal/util.rbi +101 -112
  65. data/rbi/scalar_api_ruby/internal.rbi +1 -2
  66. data/rbi/scalar_api_ruby/models/access_group_create_params.rbi +4 -4
  67. data/rbi/scalar_api_ruby/models/access_group_create_response.rbi +6 -6
  68. data/rbi/scalar_api_ruby/models/access_group_retrieve_response.rbi +6 -6
  69. data/rbi/scalar_api_ruby/models/api_document.rbi +3 -3
  70. data/rbi/scalar_api_ruby/models/docs_project.rbi +3 -3
  71. data/rbi/scalar_api_ruby/models/github_project.rbi +18 -6
  72. data/rbi/scalar_api_ruby/models/mcp/mcp_server.rbi +22 -16
  73. data/rbi/scalar_api_ruby/models/mcp/server_create_response.rbi +5 -19
  74. data/rbi/scalar_api_ruby/models/mcp/server_list_response.rbi +116 -1
  75. data/rbi/scalar_api_ruby/models/sdk.rbi +15 -9
  76. data/rbi/scalar_api_ruby/models/sdk_build_params.rbi +15 -1
  77. data/rbi/scalar_api_ruby/models/sdk_create_params.rbi +19 -6
  78. data/rbi/scalar_api_ruby/models/sdk_update_params.rbi +9 -4
  79. data/rbi/scalar_api_ruby/models/sdk_version.rbi +7 -52
  80. data/rbi/scalar_api_ruby/models/sdks/repository_link_params.rbi +59 -0
  81. data/rbi/scalar_api_ruby/models/sdks/repository_update_publishing_params.rbi +45 -0
  82. data/rbi/scalar_api_ruby/models/sdks/version_create_params.rbi +16 -6
  83. data/rbi/scalar_api_ruby/request_options.rbi +6 -8
  84. data/rbi/scalar_api_ruby/resources/access_groups.rbi +1 -1
  85. data/rbi/scalar_api_ruby/resources/mcp/servers.rbi +6 -51
  86. data/rbi/scalar_api_ruby/resources/sdks/repositories.rbi +28 -1
  87. data/rbi/scalar_api_ruby/resources/sdks/versions.rbi +21 -4
  88. data/rbi/scalar_api_ruby/resources/sdks.rbi +40 -10
  89. data/sig/scalar_api_ruby/client.rbs +2 -0
  90. data/sig/scalar_api_ruby/errors.rbs +6 -0
  91. data/sig/scalar_api_ruby/internal/transport/base_client.rbs +19 -1
  92. data/sig/scalar_api_ruby/internal/transport/connection_pool.rbs +19 -0
  93. data/sig/scalar_api_ruby/internal/transport/pooled_net_requester.rbs +11 -1
  94. data/sig/scalar_api_ruby/internal/type/base_model.rbs +4 -0
  95. data/sig/scalar_api_ruby/internal/util.rbs +29 -1
  96. data/sig/scalar_api_ruby/models/access_group_create_params.rbs +5 -5
  97. data/sig/scalar_api_ruby/models/access_group_create_response.rbs +8 -8
  98. data/sig/scalar_api_ruby/models/access_group_retrieve_response.rbs +8 -8
  99. data/sig/scalar_api_ruby/models/api_document.rbs +4 -4
  100. data/sig/scalar_api_ruby/models/docs_project.rbs +4 -4
  101. data/sig/scalar_api_ruby/models/github_project.rbs +17 -7
  102. data/sig/scalar_api_ruby/models/mcp/mcp_server.rbs +22 -17
  103. data/sig/scalar_api_ruby/models/mcp/server_create_response.rbs +3 -15
  104. data/sig/scalar_api_ruby/models/mcp/server_list_response.rbs +66 -1
  105. data/sig/scalar_api_ruby/models/sdk.rbs +13 -8
  106. data/sig/scalar_api_ruby/models/sdk_build_params.rbs +7 -0
  107. data/sig/scalar_api_ruby/models/sdk_create_params.rbs +9 -5
  108. data/sig/scalar_api_ruby/models/sdk_update_params.rbs +6 -4
  109. data/sig/scalar_api_ruby/models/sdk_version.rbs +7 -37
  110. data/sig/scalar_api_ruby/models/sdks/repository_link_params.rbs +21 -1
  111. data/sig/scalar_api_ruby/models/sdks/repository_update_publishing_params.rbs +36 -1
  112. data/sig/scalar_api_ruby/models/sdks/version_create_params.rbs +7 -5
  113. data/sig/scalar_api_ruby/resources/access_groups.rbs +1 -1
  114. data/sig/scalar_api_ruby/resources/mcp/servers.rbs +1 -20
  115. data/sig/scalar_api_ruby/resources/sdks/repositories.rbs +6 -0
  116. data/sig/scalar_api_ruby/resources/sdks/versions.rbs +1 -1
  117. data/sig/scalar_api_ruby/resources/sdks.rbs +3 -2
  118. metadata +8 -73
  119. data/lib/scalar_api_ruby/models/mcp/mcp_installation.rb +0 -75
  120. data/lib/scalar_api_ruby/models/mcp/server_delete_params.rb +0 -22
  121. data/lib/scalar_api_ruby/models/mcp/server_retrieve_params.rb +0 -22
  122. data/lib/scalar_api_ruby/models/mcp/server_update_params.rb +0 -52
  123. data/lib/scalar_api_ruby/models/mcp/servers/installation_create_access_group_params.rb +0 -36
  124. data/lib/scalar_api_ruby/models/mcp/servers/installation_create_params.rb +0 -44
  125. data/lib/scalar_api_ruby/models/mcp/servers/installation_delete_access_group_params.rb +0 -36
  126. data/lib/scalar_api_ruby/models/mcp/servers/installation_delete_params.rb +0 -30
  127. data/lib/scalar_api_ruby/models/mcp/servers/installation_list_params.rb +0 -24
  128. data/lib/scalar_api_ruby/models/mcp/servers/installation_list_response.rb +0 -13
  129. data/lib/scalar_api_ruby/models/mcp/servers/installation_retrieve_params.rb +0 -30
  130. data/lib/scalar_api_ruby/models/mcp/servers/installation_update_params.rb +0 -68
  131. data/lib/scalar_api_ruby/models/mcp/servers/mcp_installation_list_item.rb +0 -43
  132. data/lib/scalar_api_ruby/resources/mcp/servers/installations.rb +0 -200
  133. data/rbi/scalar_api_ruby/models/mcp/mcp_installation.rbi +0 -93
  134. data/rbi/scalar_api_ruby/models/mcp/server_delete_params.rbi +0 -37
  135. data/rbi/scalar_api_ruby/models/mcp/server_retrieve_params.rbi +0 -37
  136. data/rbi/scalar_api_ruby/models/mcp/server_update_params.rbi +0 -88
  137. data/rbi/scalar_api_ruby/models/mcp/servers/installation_create_access_group_params.rbi +0 -60
  138. data/rbi/scalar_api_ruby/models/mcp/servers/installation_create_params.rbi +0 -69
  139. data/rbi/scalar_api_ruby/models/mcp/servers/installation_delete_access_group_params.rbi +0 -60
  140. data/rbi/scalar_api_ruby/models/mcp/servers/installation_delete_params.rbi +0 -50
  141. data/rbi/scalar_api_ruby/models/mcp/servers/installation_list_params.rbi +0 -42
  142. data/rbi/scalar_api_ruby/models/mcp/servers/installation_list_response.rbi +0 -17
  143. data/rbi/scalar_api_ruby/models/mcp/servers/installation_retrieve_params.rbi +0 -50
  144. data/rbi/scalar_api_ruby/models/mcp/servers/installation_update_params.rbi +0 -102
  145. data/rbi/scalar_api_ruby/models/mcp/servers/mcp_installation_list_item.rbi +0 -60
  146. data/rbi/scalar_api_ruby/resources/mcp/servers/installations.rbi +0 -140
  147. data/sig/scalar_api_ruby/models/mcp/mcp_installation.rbs +0 -69
  148. data/sig/scalar_api_ruby/models/mcp/server_delete_params.rbs +0 -22
  149. data/sig/scalar_api_ruby/models/mcp/server_retrieve_params.rbs +0 -22
  150. data/sig/scalar_api_ruby/models/mcp/server_update_params.rbs +0 -63
  151. data/sig/scalar_api_ruby/models/mcp/servers/installation_create_access_group_params.rbs +0 -36
  152. data/sig/scalar_api_ruby/models/mcp/servers/installation_create_params.rbs +0 -47
  153. data/sig/scalar_api_ruby/models/mcp/servers/installation_delete_access_group_params.rbs +0 -36
  154. data/sig/scalar_api_ruby/models/mcp/servers/installation_delete_params.rbs +0 -32
  155. data/sig/scalar_api_ruby/models/mcp/servers/installation_list_params.rbs +0 -27
  156. data/sig/scalar_api_ruby/models/mcp/servers/installation_list_response.rbs +0 -12
  157. data/sig/scalar_api_ruby/models/mcp/servers/installation_retrieve_params.rbs +0 -32
  158. data/sig/scalar_api_ruby/models/mcp/servers/installation_update_params.rbs +0 -73
  159. data/sig/scalar_api_ruby/models/mcp/servers/mcp_installation_list_item.rbs +0 -44
  160. data/sig/scalar_api_ruby/resources/mcp/servers/installations.rbs +0 -62
@@ -12,7 +12,11 @@ module Scalar
12
12
  # from whatwg fetch spec
13
13
  MAX_REDIRECTS = 20
14
14
 
15
- # rubocop:disable Style/MutableConstant
15
+ # Longest wait, in seconds, a `retry-after-ms` or `Retry-After` header may ask for before the
16
+ # client's own backoff is used instead.
17
+ MAX_RETRY_AFTER = 60
18
+
19
+ # rubocop:disable-next Style/MutableConstant
16
20
  PLATFORM_HEADERS = {
17
21
  "x-scalar-arch" => Scalar::Internal::Util.arch,
18
22
  "x-scalar-lang" => "ruby",
@@ -21,7 +25,6 @@ module Scalar
21
25
  "x-scalar-runtime" => ::RUBY_ENGINE,
22
26
  "x-scalar-runtime-version" => ::RUBY_ENGINE_VERSION
23
27
  }
24
- # rubocop:enable Style/MutableConstant
25
28
 
26
29
  class << self
27
30
  # @api private
@@ -30,7 +33,7 @@ module Scalar
30
33
  #
31
34
  # @raise [ArgumentError]
32
35
  def validate!(req)
33
- keys = %i[method path query headers body unwrap page stream model options]
36
+ keys = %i[method path query headers body unwrap page stream model security options]
34
37
  case req
35
38
  in Hash
36
39
  req.each_key do |k|
@@ -66,6 +69,61 @@ module Scalar
66
69
  end
67
70
  end
68
71
 
72
+ # @api private
73
+ #
74
+ # The wait in seconds a `retry-after-ms` or `Retry-After` header asks for, when it is a
75
+ # finite value over zero and at most {MAX_RETRY_AFTER}; otherwise `nil`, and the caller backs
76
+ # off on its own schedule.
77
+ #
78
+ # Both headers come from the server, so neither is trusted: a negative or past value would
79
+ # make `sleep` raise, and an hour or `1e400` would park the call. `Retry-After` is seconds
80
+ # or an HTTP date; a date that does not parse is ignored rather than raised.
81
+ #
82
+ # @param headers [Hash{String=>String}, Net::HTTPResponse]
83
+ #
84
+ # @return [Float, nil]
85
+ def retry_after(headers)
86
+ millis = Float(headers["retry-after-ms"], exception: false)
87
+ if millis&.finite? && millis.positive? && millis <= self::MAX_RETRY_AFTER * 1000
88
+ return millis / 1000
89
+ end
90
+
91
+ header = headers["retry-after"]
92
+ return nil if header.nil?
93
+
94
+ seconds = Float(header, exception: false)
95
+ seconds ||=
96
+ begin
97
+ Time.httpdate(header.to_s) - Time.now
98
+ rescue ArgumentError, RangeError
99
+ nil
100
+ end
101
+ seconds.to_f if seconds&.finite? && seconds.positive? && seconds <= self::MAX_RETRY_AFTER
102
+ end
103
+
104
+ # @api private
105
+ #
106
+ # Whether a response is a redirect the client follows: a 301, 302, 303, 307 or 308 that
107
+ # names a `location`, the statuses the fetch spec follows. A 300 only offers choices, a 304
108
+ # tells a conditional request its copy is current, and a redirect with no `location` names
109
+ # no target, so `send_request` treats each as the server's answer and raises it as a status
110
+ # error, as it does a 4xx.
111
+ #
112
+ # @param status [Integer]
113
+ # @param headers [Hash{String=>String}]
114
+ #
115
+ # @return [Boolean]
116
+ def redirect?(status, headers:)
117
+ case status
118
+ in 301 | 302 | 303 | 307 | 308
119
+ # Net::HTTP strips a blank `location` to "", which `URI.join` resolves to the request's
120
+ # own URL, so it would be re-requested until the redirect limit.
121
+ !headers["location"].to_s.strip.empty?
122
+ else
123
+ false
124
+ end
125
+ end
126
+
69
127
  # @api private
70
128
  #
71
129
  # @param request [Hash{Symbol=>Object}] .
@@ -86,13 +144,23 @@ module Scalar
86
144
  #
87
145
  # @param response_headers [Hash{String=>String}]
88
146
  #
147
+ # @param base_url [URI::Generic] the client's base URL, whose origin is the only one its
148
+ # credentials belong to
149
+ #
150
+ # @param credential_headers [Array<String>] lowercase names of the client's header
151
+ # credentials, its `auth_header_keys`
152
+ #
89
153
  # @return [Hash{Symbol=>Object}]
90
- def follow_redirect(request, status:, response_headers:)
154
+ def follow_redirect(request, status:, response_headers:, base_url:, credential_headers:)
91
155
  method, url, headers = request.fetch_values(:method, :url, :headers)
156
+ # `send_request` only passes a response `redirect?` accepted. The rescue covers a call
157
+ # handed a 3xx with no `location` (`ArgumentError`), and a `location` that is not a valid
158
+ # URI reference (`URI::Error`), such as one with a space or a bad `%` escape, or two
159
+ # `Location` headers Net::HTTP joined into "/a, /b".
92
160
  location =
93
161
  Kernel.then do
94
162
  URI.join(url, response_headers["location"])
95
- rescue ArgumentError
163
+ rescue ArgumentError, URI::Error
96
164
  message = "Server responded with status #{status} but no valid location header."
97
165
  raise Scalar::Errors::APIConnectionError.new(
98
166
  url: url,
@@ -129,11 +197,22 @@ module Scalar
129
197
  end
130
198
 
131
199
  # from undici
132
- if Scalar::Internal::Util.uri_origin(url) != Scalar::Internal::Util.uri_origin(location)
200
+ if Scalar::Internal::Util.uri_origin(url) !=
201
+ Scalar::Internal::Util.uri_origin(location)
133
202
  drop = %w[authorization cookie host proxy-authorization]
134
203
  request = {**request, headers: request.fetch(:headers).except(*drop)}
135
204
  end
136
205
 
206
+ # The list above only knows the standard credential headers, so an API key sent in a
207
+ # header of its own (`x-api-key`) would otherwise follow any redirect to a foreign host,
208
+ # and a 307/308 would carry the method and body with it. The drop is sticky: nothing
209
+ # re-adds a header once it is gone, so a chain that returns to the client's origin after
210
+ # a foreign hop still arrives without it.
211
+ if Scalar::Internal::Util.uri_origin(base_url) !=
212
+ Scalar::Internal::Util.uri_origin(location)
213
+ request = {**request, headers: request.fetch(:headers).except(*credential_headers)}
214
+ end
215
+
137
216
  request
138
217
  end
139
218
 
@@ -222,8 +301,31 @@ module Scalar
222
301
 
223
302
  # @api private
224
303
  #
304
+ # The credential headers one request is sent with, given the security requirement groups its
305
+ # operation passes as `security:` (`nil` for the client's default). A client that scopes its
306
+ # credentials per operation overrides this; every other one sends all of `auth_headers`.
307
+ #
308
+ # @param _security [Array<Array<String>>, nil]
309
+ #
310
+ # @return [Hash{String=>String}]
311
+ private def auth_headers_for(_security) = auth_headers
312
+
313
+ # @api private
314
+ #
315
+ # Lowercased names of every header credential `auth_headers` can write, whether or not the
316
+ # client holds a value for it. A redirect that leaves the base URL's origin drops these, so a
317
+ # key passed per call through `extra_headers` is dropped the same as one the client holds.
318
+ #
319
+ # @return [Array<String>]
320
+ private def auth_header_keys = []
321
+
322
+ # @api private
323
+ #
324
+ # A literal rather than `self.class.name`: a class name is namespaced (`Acme::Client`), and
325
+ # `:` is not a token character (RFC 9110 §5.6.2).
326
+ #
225
327
  # @return [String]
226
- private def user_agent = "#{self.class.name}/Ruby #{Scalar::VERSION}"
328
+ private def user_agent = "Scalar/Ruby #{Scalar::VERSION}"
227
329
 
228
330
  # @api private
229
331
  #
@@ -252,6 +354,8 @@ module Scalar
252
354
  #
253
355
  # @option req [Scalar::Internal::Type::Converter, Class, nil] :model
254
356
  #
357
+ # @option req [Array<Array<String>>, nil] :security
358
+ #
255
359
  # @param opts [Hash{Symbol=>Object}] .
256
360
  #
257
361
  # @option opts [String, nil] :idempotency_key
@@ -272,15 +376,27 @@ module Scalar
272
376
 
273
377
  path = Scalar::Internal::Util.interpolate_path(uninterpolated_path)
274
378
 
275
- query = Scalar::Internal::Util.deep_merge(req[:query].to_h, opts[:extra_query].to_h)
276
-
379
+ query = Scalar::Internal::Util.deep_merge(
380
+ req[:query].to_h,
381
+ opts[:extra_query].to_h
382
+ )
383
+
384
+ # The client's defaults, its credentials and the operation's own headers each may carry a
385
+ # `cookie`, and a plain merge would let the operation's cookie parameters replace the
386
+ # credential cookie. Those three are merged by cookie name instead; `extra_headers` still
387
+ # replaces the whole header, as it replaces any other.
388
+ sources =
389
+ [@headers, auth_headers_for(req[:security]), req[:headers].to_h].map do
390
+ Scalar::Internal::Util.normalized_headers(_1)
391
+ end
392
+ merged = Scalar::Internal::Util.normalized_headers(*sources)
393
+ # A local rather than an inline block: under a long module name the inline form is broken
394
+ # inside its braces, and the multi-line `{ }` block that leaves is a `Style` offense.
395
+ cookies = sources.map { _1["cookie"] }
396
+ cookie = Scalar::Internal::Util.merge_cookies(*cookies)
397
+ merged["cookie"] = cookie unless cookie.nil?
277
398
  headers =
278
- Scalar::Internal::Util.normalized_headers(
279
- @headers,
280
- auth_headers,
281
- req[:headers].to_h,
282
- opts[:extra_headers].to_h
283
- )
399
+ Scalar::Internal::Util.normalized_headers(merged, opts[:extra_headers].to_h)
284
400
 
285
401
  if @idempotency_header && !headers.key?(@idempotency_header) &&
286
402
  (!Net::HTTP::IDEMPOTENT_METHODS_.include?(method.to_s.upcase) || opts.key?(:idempotency_key))
@@ -308,7 +424,10 @@ module Scalar
308
424
  headers.delete("content-type") if body.nil? && !req.key?(:body)
309
425
 
310
426
  url =
311
- Scalar::Internal::Util.join_parsed_uri(@base_url_components, {**req, path: path, query: query})
427
+ Scalar::Internal::Util.join_parsed_uri(
428
+ @base_url_components,
429
+ {**req, path: path, query: query}
430
+ )
312
431
  headers, encoded = Scalar::Internal::Util.encode_content(headers, body)
313
432
  {
314
433
  method: method,
@@ -327,20 +446,8 @@ module Scalar
327
446
  #
328
447
  # @return [Float]
329
448
  private def retry_delay(headers, retry_count:)
330
- # Non-standard extension
331
- span = Float(headers["retry-after-ms"], exception: false)&.then { _1 / 1000 }
332
- return span if span
333
-
334
- retry_header = headers["retry-after"]
335
- return span if (span = Float(retry_header, exception: false))
336
-
337
- span =
338
- retry_header&.then do
339
- Time.httpdate(_1) - Time.now
340
- rescue ArgumentError
341
- nil
342
- end
343
- return span if span
449
+ asked = self.class.retry_after(headers)
450
+ return asked if asked
344
451
 
345
452
  scale = retry_count**2
346
453
  jitter = 1 - (0.25 * rand)
@@ -373,7 +480,10 @@ module Scalar
373
480
  # @return [Array(Integer, Net::HTTPResponse, Enumerable<String>)]
374
481
  def send_request(request, redirect_count:, retry_count:, send_retry_header:)
375
482
  url, headers, max_retries, timeout = request.fetch_values(:url, :headers, :max_retries, :timeout)
376
- input = {**request.except(:timeout), deadline: Scalar::Internal::Util.monotonic_secs + timeout}
483
+ input = {
484
+ **request.except(:timeout),
485
+ deadline: Scalar::Internal::Util.monotonic_secs + timeout
486
+ }
377
487
 
378
488
  headers["x-scalar-retry-count"] = retry_count.to_s if send_retry_header
379
489
 
@@ -384,18 +494,31 @@ module Scalar
384
494
  end
385
495
  headers = Scalar::Internal::Util.normalized_headers(response&.each_header&.to_h)
386
496
 
497
+ redirect = status.is_a?(Integer) && self.class.redirect?(status, headers: headers)
498
+
387
499
  case status
388
500
  in ..299
389
501
  [status, response, stream]
390
- in 300..399 if redirect_count >= self.class::MAX_REDIRECTS
502
+ in Integer if redirect && redirect_count >= self.class::MAX_REDIRECTS
391
503
  self.class.reap_connection!(status, stream: stream)
392
504
 
393
505
  message = "Failed to complete the request within #{self.class::MAX_REDIRECTS} redirects."
394
- raise Scalar::Errors::APIConnectionError.new(url: url, response: response, message: message)
395
- in 300..399
506
+ raise Scalar::Errors::APIConnectionError.new(
507
+ url: url,
508
+ response: response,
509
+ message: message
510
+ )
511
+ in Integer if redirect
396
512
  self.class.reap_connection!(status, stream: stream)
397
513
 
398
- request = self.class.follow_redirect(request, status: status, response_headers: headers)
514
+ request =
515
+ self.class.follow_redirect(
516
+ request,
517
+ status: status,
518
+ response_headers: headers,
519
+ base_url: @base_url,
520
+ credential_headers: auth_header_keys
521
+ )
399
522
  send_request(
400
523
  request,
401
524
  redirect_count: redirect_count + 1,
@@ -404,10 +527,19 @@ module Scalar
404
527
  )
405
528
  in Scalar::Errors::APIConnectionError if retry_count >= max_retries
406
529
  raise status
407
- in (400..) if retry_count >= max_retries || !self.class.should_retry?(status, headers: headers)
530
+ # Any other 3xx — a 304 answering a conditional request, a 300, a redirect status without a
531
+ # `location` — is the server's answer rather than a hop, so it fails as a status error, like a 4xx.
532
+ in (300..) if retry_count >= max_retries || !self.class.should_retry?(status, headers: headers)
533
+ # Read only for the error's `body`, so only its first `MAX_ERROR_BODY_BYTES` are kept and
534
+ # the rest is never read: a server cannot make an error cost more than that in memory.
408
535
  decoded =
409
536
  Kernel.then do
410
- Scalar::Internal::Util.decode_content(headers, stream: stream, suppress_error: true)
537
+ Scalar::Internal::Util.decode_content(
538
+ headers,
539
+ stream: stream,
540
+ suppress_error: true,
541
+ truncate_at: Scalar::Internal::Util::MAX_ERROR_BODY_BYTES
542
+ )
411
543
  ensure
412
544
  self.class.reap_connection!(status, stream: stream)
413
545
  end
@@ -420,7 +552,7 @@ module Scalar
420
552
  request: nil,
421
553
  response: response
422
554
  )
423
- in 400.. | Scalar::Errors::APIConnectionError
555
+ in 300.. | Scalar::Errors::APIConnectionError
424
556
  self.class.reap_connection!(status, stream: stream)
425
557
 
426
558
  delay = retry_delay(response || {}, retry_count: retry_count)
@@ -489,7 +621,14 @@ module Scalar
489
621
  send_request(request, redirect_count: 0, retry_count: 0, send_retry_header: send_retry_header)
490
622
 
491
623
  headers = Scalar::Internal::Util.normalized_headers(response.each_header.to_h)
492
- decoded = Scalar::Internal::Util.decode_content(headers, stream: stream)
624
+ # Only an operation declared to return raw bytes reads its body whole; every other buffered
625
+ # body is capped, since the response's own content type cannot be trusted to say which it is.
626
+ decoded =
627
+ Scalar::Internal::Util.decode_content(
628
+ headers,
629
+ stream: stream,
630
+ download: model == StringIO
631
+ )
493
632
  case req
494
633
  in stream: Class => st
495
634
  st.new(
@@ -513,9 +652,8 @@ module Scalar
513
652
  #
514
653
  # @return [String]
515
654
  def inspect
516
- # rubocop:disable Layout/LineLength
655
+ # rubocop:disable-next Layout/LineLength
517
656
  "#<#{self.class.name}:0x#{object_id.to_s(16)} base_url=#{@base_url} max_retries=#{@max_retries} timeout=#{@timeout}>"
518
- # rubocop:enable Layout/LineLength
519
657
  end
520
658
 
521
659
  define_sorbet_constant!(:RequestComponents) do
@@ -541,7 +679,14 @@ module Scalar
541
679
  T.proc.params(arg0: T.anything).returns(T.anything)
542
680
  )
543
681
  ),
544
- page: T.nilable(T::Class[Scalar::Internal::Type::BasePage[Scalar::Internal::Type::BaseModel]]),
682
+ page:
683
+ T.nilable(
684
+ T::Class[
685
+ Scalar::Internal::Type::BasePage[
686
+ Scalar::Internal::Type::BaseModel
687
+ ]
688
+ ]
689
+ ),
545
690
  stream: T.nilable(T::Class[T.anything]),
546
691
  model: T.nilable(Scalar::Internal::Type::Converter::Input),
547
692
  options: T.nilable(Scalar::RequestOptions::OrHash)
@@ -0,0 +1,160 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Scalar
4
+ module Internal
5
+ module Transport
6
+ # @api private
7
+ #
8
+ # A fixed-size, thread-safe pool of lazily created connections. `PooledNetRequester` keeps one per
9
+ # origin, so `size` caps the concurrent requests to that origin.
10
+ class ConnectionPool
11
+ # @api private
12
+ #
13
+ # Checks a connection out for the duration of the block and back in afterwards, even when the
14
+ # block raises.
15
+ #
16
+ # @param timeout [Float] seconds to wait for a connection when every one is checked out
17
+ # @param blk [Proc]
18
+ #
19
+ # @raise [Timeout::Error] when no connection frees up within `timeout`
20
+ # @yieldparam [Object]
21
+ # @return [Object] the block's result
22
+ def with(timeout:, &blk)
23
+ # Interrupts (`Thread#raise`, `Timeout.timeout`) are held back while a connection changes
24
+ # hands, so none can land between the checkout and the `ensure` and leak the connection. The
25
+ # block itself runs with them enabled again.
26
+ ::Thread.handle_interrupt(Object => :never) do
27
+ conn, pid = checkout(timeout)
28
+ begin
29
+ ::Thread.handle_interrupt(Object => :immediate) { blk.call(conn) }
30
+ ensure
31
+ checkin(conn, pid)
32
+ end
33
+ end
34
+ end
35
+
36
+ # @api private
37
+ #
38
+ # @param timeout [Float]
39
+ #
40
+ # @raise [Timeout::Error]
41
+ # @return [Array(Object, Integer)] the connection, and the process it was checked out in
42
+ private def checkout(timeout)
43
+ # The deadline is on the monotonic clock, as the requester's own is, so a wall-clock jump can
44
+ # neither stretch nor cut the wait.
45
+ deadline = Scalar::Internal::Util.monotonic_secs + timeout
46
+ @mutex.synchronize do
47
+ reset_after_fork
48
+ loop do
49
+ # An idle connection or a free slot is handed out even once the deadline has passed: the
50
+ # timeout bounds the wait for one, and the requester raises its own timeout from there
51
+ # before it uses the connection. Most recently returned first, so the connection most
52
+ # likely to still be alive is the one reused.
53
+ return @idle.pop, @pid unless @idle.empty?
54
+
55
+ if @created < @size
56
+ # Created under the lock so two threads cannot both take the last slot. That is cheap:
57
+ # the block only builds the client object, and the requester connects it later.
58
+ conn = @create.call
59
+ @created += 1
60
+ return conn, @pid
61
+ end
62
+
63
+ remaining = deadline - Scalar::Internal::Util.monotonic_secs
64
+ unless remaining.positive?
65
+ raise Timeout::Error, "Waited #{timeout} seconds for one of #{@size} pooled connections"
66
+ end
67
+
68
+ # `wait` releases the mutex while it sleeps and takes it back before returning, whether a
69
+ # check-in, the timeout or a spurious wakeup woke it. So the loop looks at the pool again
70
+ # instead of trusting the reason, and only ever waits for what is left of the deadline.
71
+ @available.wait(@mutex, remaining)
72
+ end
73
+ end
74
+ end
75
+
76
+ # @api private
77
+ #
78
+ # @param conn [Object]
79
+ # @param pid [Integer]
80
+ private def checkin(conn, pid)
81
+ close = nil
82
+ @mutex.synchronize do
83
+ reset_after_fork
84
+ # A connection checked out before a fork is the parent's: `reset_after_fork` has already
85
+ # stopped counting it, so it is dropped rather than handed to the child's next request.
86
+ if pid == @pid && @close
87
+ close = @close
88
+ # Its slot is free again, so the next checkout can build a connection in its place.
89
+ @created -= 1
90
+ elsif pid == @pid
91
+ @idle.push(conn)
92
+ end
93
+ @available.signal
94
+ end
95
+ # A pool shut down while this connection was out keeps nothing; closed outside the lock.
96
+ begin
97
+ close&.call(conn)
98
+ rescue StandardError
99
+ nil
100
+ end
101
+ end
102
+
103
+ # @api private
104
+ #
105
+ # Closes every idle connection with `close` and every connection still checked out as it comes
106
+ # back, so a pool the owner has let go of holds no socket open. The pool still works after
107
+ # this, one connection per checkout, for a caller that looked it up just before.
108
+ #
109
+ # @param close [Proc] closes one connection
110
+ #
111
+ # @yieldparam [Object]
112
+ def shutdown(&close)
113
+ idle =
114
+ @mutex.synchronize do
115
+ @close = close
116
+ # A forked child does not own the parent's connections, so it closes none of them.
117
+ taken = @pid == Process.pid ? @idle.slice!(0..) : []
118
+ @created -= taken.size
119
+ taken
120
+ end
121
+ idle.each do |conn|
122
+ close.call(conn)
123
+ rescue StandardError
124
+ nil
125
+ end
126
+ end
127
+
128
+ # @api private
129
+ #
130
+ # A forked child inherits the parent's open sockets. Reusing one would interleave both
131
+ # processes' requests on a single connection, so the first checkout or check-in in a new
132
+ # process forgets every connection and lets the pool fill up again from empty. The forgotten
133
+ # ones are not closed either: closing a TLS connection writes to the socket the parent is still
134
+ # using.
135
+ private def reset_after_fork
136
+ return if @pid == Process.pid
137
+
138
+ @idle.clear
139
+ @created = 0
140
+ @pid = Process.pid
141
+ end
142
+
143
+ # @api private
144
+ #
145
+ # @param size [Integer]
146
+ # @param blk [Proc] builds one connection, called lazily as the pool fills up
147
+ def initialize(size:, &blk)
148
+ @size = size
149
+ @create = blk
150
+ @mutex = Mutex.new
151
+ @available = ConditionVariable.new
152
+ @idle = []
153
+ @created = 0
154
+ @pid = Process.pid
155
+ @close = nil
156
+ end
157
+ end
158
+ end
159
+ end
160
+ end
@@ -13,6 +13,24 @@ module Scalar
13
13
 
14
14
  DEFAULT_MAX_CONNECTIONS = [Etc.nprocessors, 99].max
15
15
 
16
+ # Most origins the requester keeps a connection pool for at once.
17
+ MAX_POOLS = 16
18
+
19
+ # Seconds each socket wait gets once the deadline has passed between two body chunks: enough
20
+ # for a read that finds the rest of the body already buffered, never enough to wait for more.
21
+ ELAPSED_SOCKET_TIMEOUT = 0.001
22
+
23
+ # @api private
24
+ #
25
+ # The trust store every TLS connection of this requester verifies against: OpenSSL's default
26
+ # paths, read when the client is constructed, so `SSL_CERT_FILE` and `SSL_CERT_DIR` as they
27
+ # stand then. A signed upload and a requested-URL fetch, which go to other hosts on connections
28
+ # of their own, verify against this same store, so those hosts are trusted exactly as the
29
+ # client's own are.
30
+ #
31
+ # @return [OpenSSL::X509::Store]
32
+ attr_reader :cert_store
33
+
16
34
  class << self
17
35
  # @api private
18
36
  #
@@ -43,10 +61,30 @@ module Scalar
43
61
 
44
62
  # @api private
45
63
  #
64
+ # Sets every socket timeout of `conn` to what is left of `deadline`.
65
+ #
66
+ # A passed deadline never reaches `Net::HTTP` as a negative or zero timeout: a negative one
67
+ # makes the next socket wait raise `ArgumentError`, which would surface as a connection
68
+ # error, and a zero open timeout means no timeout at all. It raises instead, which `execute`
69
+ # maps to the SDK's timeout error, unless `finishing` is set.
70
+ #
46
71
  # @param conn [Net::HTTP]
47
72
  # @param deadline [Float]
48
- def calibrate_socket_timeout(conn, deadline)
73
+ # @param finishing [Boolean] whether `conn` is between two chunks of a response body. The
74
+ # consumer's time on the chunk it was handed can carry the deadline past, and the body may
75
+ # be complete already, so the timeouts drop to `ELAPSED_SOCKET_TIMEOUT` rather than
76
+ # raising: a read that still has to wait raises `Net::ReadTimeout`, and the next chunk's
77
+ # own check raises when there is more to come.
78
+ #
79
+ # @raise [Timeout::Error] when the deadline has already passed and `finishing` is not set
80
+ def calibrate_socket_timeout(conn, deadline, finishing: false)
49
81
  timeout = deadline - Scalar::Internal::Util.monotonic_secs
82
+ unless timeout.positive?
83
+ raise Timeout::Error, "The request did not finish within its timeout" unless finishing
84
+
85
+ timeout = self::ELAPSED_SOCKET_TIMEOUT
86
+ end
87
+
50
88
  conn.open_timeout = conn.read_timeout = conn.write_timeout = conn.continue_timeout = timeout
51
89
  end
52
90
 
@@ -105,12 +143,30 @@ module Scalar
105
143
  private def with_pool(url, deadline:, &blk)
106
144
  origin = Scalar::Internal::Util.uri_origin(url)
107
145
  timeout = deadline - Scalar::Internal::Util.monotonic_secs
146
+ # A request whose deadline has already passed times out before it takes a connection, as
147
+ # `calibrate_socket_timeout` would raise on it first thing, rather than checking one out (or
148
+ # opening a pool for its origin) only to hand it straight back.
149
+ raise Timeout::Error, "The request did not finish within its timeout" unless timeout.positive?
150
+
151
+ # One pool per origin, created on first use. `@mutex` only guards the lookup: waiting for a
152
+ # connection happens in the pool, so a full pool for one origin never blocks another's.
153
+ evicted = nil
108
154
  pool =
109
155
  @mutex.synchronize do
110
- @pools[origin] ||= ConnectionPool.new(size: @size) do
111
- self.class.connect(cert_store: @cert_store, url: url)
112
- end
156
+ # Re-inserted on every use, so the hash's insertion order is least recently used first.
157
+ found = @pools.delete(origin)
158
+ found ||=
159
+ Scalar::Internal::Transport::ConnectionPool.new(size: @size) do
160
+ self.class.connect(cert_store: @cert_store, url: url)
161
+ end
162
+ # Origins come from redirects and next-page links as well as the base URL, so a server
163
+ # could otherwise name a new one on every response and hold a socket open for each.
164
+ # Past `MAX_POOLS` the least recently used pool is shut down.
165
+ evicted = @pools.shift&.last if @pools.size >= self.class::MAX_POOLS
166
+ @pools[origin] = found
113
167
  end
168
+ # Outside `@mutex`, since closing a connection can wait on the network.
169
+ evicted&.shutdown { _1.finish if _1.started? }
114
170
 
115
171
  pool.with(timeout: timeout, &blk)
116
172
  end
@@ -133,10 +189,9 @@ module Scalar
133
189
  def execute(request)
134
190
  url, deadline = request.fetch_values(:url, :deadline)
135
191
 
136
- req = nil
137
192
  finished = false
138
193
 
139
- # rubocop:disable Metrics/BlockLength
194
+ # rubocop:disable-next Metrics/BlockLength
140
195
  enum =
141
196
  Enumerator.new do |y|
142
197
  next if finished
@@ -164,10 +219,15 @@ module Scalar
164
219
  ::Kernel.throw(:jump) if finished
165
220
 
166
221
  rsp.read_body do |bytes|
222
+ # A chunk read once the deadline has passed means the body did not finish
223
+ # within it. Checked here, not only before a wait, because a read that finds
224
+ # bytes already buffered never waits, so a server that keeps a body coming
225
+ # would otherwise outlast the deadline indefinitely.
226
+ self.class.calibrate_socket_timeout(conn, deadline)
167
227
  y << bytes.force_encoding(Encoding::BINARY)
168
228
  ::Kernel.throw(:jump) if finished
169
229
 
170
- self.class.calibrate_socket_timeout(conn, deadline)
230
+ self.class.calibrate_socket_timeout(conn, deadline, finishing: true)
171
231
  end
172
232
  eof = true
173
233
  end
@@ -181,12 +241,19 @@ module Scalar
181
241
  end
182
242
  end
183
243
  end
244
+ # `request: nil`, as every other error site passes: the built request carries the client's
245
+ # credential headers, and an error is the kind of object that gets logged or inspected.
184
246
  rescue Timeout::Error
185
- raise Scalar::Errors::APITimeoutError.new(url: url, request: req)
247
+ raise Scalar::Errors::APITimeoutError.new(
248
+ url: url,
249
+ request: nil
250
+ )
186
251
  rescue StandardError
187
- raise Scalar::Errors::APIConnectionError.new(url: url, request: req)
252
+ raise Scalar::Errors::APIConnectionError.new(
253
+ url: url,
254
+ request: nil
255
+ )
188
256
  end
189
- # rubocop:enable Metrics/BlockLength
190
257
 
191
258
  _, response = enum.next
192
259
  body =