insion 1.0.1

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 (75) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE.md +21 -0
  3. data/README.md +172 -0
  4. data/changelog.md +4 -0
  5. data/lib/Insion/client.rb +404 -0
  6. data/lib/Insion/environment.rb +7 -0
  7. data/lib/Insion/errors/api_error.rb +8 -0
  8. data/lib/Insion/errors/client_error.rb +17 -0
  9. data/lib/Insion/errors/redirect_error.rb +8 -0
  10. data/lib/Insion/errors/response_error.rb +42 -0
  11. data/lib/Insion/errors/server_error.rb +11 -0
  12. data/lib/Insion/errors/timeout_error.rb +8 -0
  13. data/lib/Insion/internal/errors/constraint_error.rb +10 -0
  14. data/lib/Insion/internal/errors/type_error.rb +10 -0
  15. data/lib/Insion/internal/http/base_request.rb +51 -0
  16. data/lib/Insion/internal/http/raw_client.rb +248 -0
  17. data/lib/Insion/internal/iterators/cursor_item_iterator.rb +28 -0
  18. data/lib/Insion/internal/iterators/cursor_page_iterator.rb +63 -0
  19. data/lib/Insion/internal/iterators/item_iterator.rb +65 -0
  20. data/lib/Insion/internal/iterators/offset_item_iterator.rb +30 -0
  21. data/lib/Insion/internal/iterators/offset_page_iterator.rb +103 -0
  22. data/lib/Insion/internal/json/request.rb +41 -0
  23. data/lib/Insion/internal/json/serializable.rb +25 -0
  24. data/lib/Insion/internal/multipart/multipart_encoder.rb +141 -0
  25. data/lib/Insion/internal/multipart/multipart_form_data.rb +78 -0
  26. data/lib/Insion/internal/multipart/multipart_form_data_part.rb +51 -0
  27. data/lib/Insion/internal/multipart/multipart_request.rb +40 -0
  28. data/lib/Insion/internal/types/array.rb +47 -0
  29. data/lib/Insion/internal/types/boolean.rb +34 -0
  30. data/lib/Insion/internal/types/enum.rb +56 -0
  31. data/lib/Insion/internal/types/hash.rb +36 -0
  32. data/lib/Insion/internal/types/model/field.rb +38 -0
  33. data/lib/Insion/internal/types/model.rb +208 -0
  34. data/lib/Insion/internal/types/type.rb +35 -0
  35. data/lib/Insion/internal/types/union.rb +161 -0
  36. data/lib/Insion/internal/types/unknown.rb +15 -0
  37. data/lib/Insion/internal/types/utils.rb +116 -0
  38. data/lib/Insion/types/content.rb +13 -0
  39. data/lib/Insion/types/content_external_urls.rb +13 -0
  40. data/lib/Insion/types/create_appeal_response.rb +9 -0
  41. data/lib/Insion/types/create_appeal_response_data.rb +19 -0
  42. data/lib/Insion/types/create_appeal_response_data_action_status.rb +13 -0
  43. data/lib/Insion/types/delete_api_v1ingest_request.rb +9 -0
  44. data/lib/Insion/types/error_response.rb +9 -0
  45. data/lib/Insion/types/error_response_error.rb +9 -0
  46. data/lib/Insion/types/get_api_v1records_record_id_request.rb +9 -0
  47. data/lib/Insion/types/get_api_v1records_request.rb +21 -0
  48. data/lib/Insion/types/get_api_v1records_request_status.rb +12 -0
  49. data/lib/Insion/types/get_api_v1users_request.rb +21 -0
  50. data/lib/Insion/types/get_api_v1users_request_status.rb +13 -0
  51. data/lib/Insion/types/get_api_v1users_user_id_request.rb +9 -0
  52. data/lib/Insion/types/ingest_record_request.rb +23 -0
  53. data/lib/Insion/types/ingest_record_response.rb +15 -0
  54. data/lib/Insion/types/ingest_user_response.rb +11 -0
  55. data/lib/Insion/types/list_records_response.rb +11 -0
  56. data/lib/Insion/types/list_users_response.rb +11 -0
  57. data/lib/Insion/types/metadata.rb +23 -0
  58. data/lib/Insion/types/moderate_request.rb +23 -0
  59. data/lib/Insion/types/moderate_response.rb +21 -0
  60. data/lib/Insion/types/moderate_response_status.rb +12 -0
  61. data/lib/Insion/types/post_api_v1users_user_id_create_appeal_request.rb +11 -0
  62. data/lib/Insion/types/record.rb +35 -0
  63. data/lib/Insion/types/record_input.rb +21 -0
  64. data/lib/Insion/types/record_moderation_status.rb +12 -0
  65. data/lib/Insion/types/record_response.rb +9 -0
  66. data/lib/Insion/types/success_response.rb +9 -0
  67. data/lib/Insion/types/user.rb +33 -0
  68. data/lib/Insion/types/user_action_status.rb +13 -0
  69. data/lib/Insion/types/user_input.rb +23 -0
  70. data/lib/Insion/types/user_response.rb +9 -0
  71. data/lib/Insion/version.rb +5 -0
  72. data/lib/Insion.rb +72 -0
  73. data/lib/insion.rb +4 -0
  74. data/reference.md +676 -0
  75. metadata +121 -0
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insion
4
+ module Errors
5
+ class ServerError < ResponseError
6
+ end
7
+
8
+ class ServiceUnavailableError < ApiError
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insion
4
+ module Errors
5
+ class TimeoutError < ApiError
6
+ end
7
+ end
8
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insion
4
+ module Internal
5
+ module Errors
6
+ class ConstraintError < StandardError
7
+ end
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insion
4
+ module Internal
5
+ module Errors
6
+ class TypeError < StandardError
7
+ end
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,51 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insion
4
+ module Internal
5
+ module Http
6
+ # @api private
7
+ class BaseRequest
8
+ attr_reader :base_url, :path, :method, :headers, :query, :request_options
9
+
10
+ # @param base_url [String] The base URL for the request
11
+ # @param path [String] The path for the request
12
+ # @param method [String] The HTTP method for the request (:get, :post, etc.)
13
+ # @param headers [Hash] Additional headers for the request (optional)
14
+ # @param query [Hash] Query parameters for the request (optional)
15
+ # @param request_options [Insion::RequestOptions, Hash{Symbol=>Object}, nil]
16
+ def initialize(base_url:, path:, method:, headers: {}, query: {}, request_options: {})
17
+ @base_url = base_url
18
+ @path = path
19
+ @method = method
20
+ @headers = headers
21
+ @query = query
22
+ @request_options = request_options
23
+ end
24
+
25
+ # @return [Hash] The query parameters merged with additional query parameters from request options.
26
+ def encode_query
27
+ additional_query = @request_options&.dig(:additional_query_parameters) || @request_options&.dig("additional_query_parameters") || {}
28
+ @query.merge(additional_query)
29
+ end
30
+
31
+ # Child classes should implement:
32
+ # - encode_headers: Returns the encoded HTTP request headers.
33
+ # - encode_body: Returns the encoded HTTP request body.
34
+
35
+ private
36
+
37
+ # Merges additional_headers from request_options into sdk_headers, filtering out
38
+ # any keys that collide with SDK-set or client-protected headers (case-insensitive).
39
+ # @param sdk_headers [Hash] Headers set by the SDK for this request type.
40
+ # @param protected_keys [Array<String>] Additional header keys that must not be overridden.
41
+ # @return [Hash] The merged headers.
42
+ def merge_additional_headers(sdk_headers, protected_keys: [])
43
+ additional_headers = @request_options&.dig(:additional_headers) || @request_options&.dig("additional_headers") || {}
44
+ all_protected = (sdk_headers.keys + protected_keys).to_set { |k| k.to_s.downcase }
45
+ filtered = additional_headers.reject { |key, _| all_protected.include?(key.to_s.downcase) }
46
+ sdk_headers.merge(filtered)
47
+ end
48
+ end
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,248 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insion
4
+ module Internal
5
+ module Http
6
+ # @api private
7
+ class RawClient
8
+ # Default HTTP status codes that trigger a retry
9
+ RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504, 521, 522, 524].freeze
10
+ # Initial delay between retries in seconds
11
+ INITIAL_RETRY_DELAY = 0.5
12
+ # Maximum delay between retries in seconds
13
+ MAX_RETRY_DELAY = 60.0
14
+ # Jitter factor for randomizing retry delays (20%)
15
+ JITTER_FACTOR = 0.2
16
+
17
+ # @return [String] The base URL for requests
18
+ attr_reader :base_url
19
+
20
+ # @param base_url [String] The base url for the request.
21
+ # @param max_retries [Integer] The number of times to retry a failed request, defaults to 2.
22
+ # @param timeout [Float] The timeout for the request, defaults to 60.0 seconds.
23
+ # @param headers [Hash] The headers for the request.
24
+ # @param auth_provider [Object, nil] An optional auth provider responding to
25
+ # `auth_headers`. When present its headers are resolved on every request so
26
+ # token-based schemes (e.g. OAuth) can refresh an expired token mid-session.
27
+ def initialize(base_url:, max_retries: 2, timeout: 60.0, headers: {}, auth_provider: nil)
28
+ @base_url = base_url
29
+ @max_retries = max_retries
30
+ @timeout = timeout
31
+ @auth_provider = auth_provider
32
+ @default_headers = headers
33
+ end
34
+
35
+ # @param request [Insion::Internal::Http::BaseRequest] The HTTP request.
36
+ # @return [HTTP::Response] The HTTP response.
37
+ def send(request)
38
+ url = build_url(request)
39
+ # Resolve auth headers once per request (not per retry) so token-based
40
+ # providers refresh at most once here; static providers are cheap.
41
+ auth_headers = resolve_auth_headers
42
+ attempt = 0
43
+ response = nil
44
+
45
+ loop do
46
+ http_request = build_http_request(
47
+ url:,
48
+ method: request.method,
49
+ headers: request.encode_headers(protected_keys: @default_headers.keys + auth_headers.keys),
50
+ body: request.encode_body,
51
+ auth_headers: auth_headers
52
+ )
53
+
54
+ conn = connect(url)
55
+ conn.open_timeout = @timeout
56
+ conn.read_timeout = @timeout
57
+ conn.write_timeout = @timeout
58
+ conn.continue_timeout = @timeout
59
+
60
+ response = conn.request(http_request)
61
+
62
+ break unless should_retry?(response, attempt)
63
+
64
+ delay = retry_delay(response, attempt)
65
+ sleep(delay)
66
+ attempt += 1
67
+ end
68
+
69
+ response
70
+ end
71
+
72
+ # Determines if a request should be retried based on the response status code.
73
+ # @param response [Net::HTTPResponse] The HTTP response.
74
+ # @param attempt [Integer] The current retry attempt (0-indexed).
75
+ # @return [Boolean] Whether the request should be retried.
76
+ def should_retry?(response, attempt)
77
+ return false if attempt >= @max_retries
78
+
79
+ status = response.code.to_i
80
+ RETRYABLE_STATUSES.include?(status)
81
+ end
82
+
83
+ # Calculates the delay before the next retry attempt using exponential backoff with jitter.
84
+ # Respects Retry-After header if present.
85
+ # @param response [Net::HTTPResponse] The HTTP response.
86
+ # @param attempt [Integer] The current retry attempt (0-indexed).
87
+ # @return [Float] The delay in seconds before the next retry.
88
+ def retry_delay(response, attempt)
89
+ # Check for Retry-After header (can be seconds or HTTP date)
90
+ retry_after = response["Retry-After"]
91
+ if retry_after
92
+ delay = parse_retry_after(retry_after)
93
+ return [delay, MAX_RETRY_DELAY].min if delay&.positive?
94
+ end
95
+
96
+ # Exponential backoff with jitter: base_delay * 2^attempt
97
+ base_delay = INITIAL_RETRY_DELAY * (2**attempt)
98
+ add_jitter([base_delay, MAX_RETRY_DELAY].min)
99
+ end
100
+
101
+ # Parses the Retry-After header value.
102
+ # @param value [String] The Retry-After header value (seconds or HTTP date).
103
+ # @return [Float, nil] The delay in seconds, or nil if parsing fails.
104
+ def parse_retry_after(value)
105
+ # Try parsing as integer (seconds)
106
+ seconds = Integer(value, exception: false)
107
+ return seconds.to_f if seconds
108
+
109
+ # Try parsing as HTTP date
110
+ begin
111
+ retry_time = Time.httpdate(value)
112
+ delay = retry_time - Time.now
113
+ delay.positive? ? delay : nil
114
+ rescue ArgumentError
115
+ nil
116
+ end
117
+ end
118
+
119
+ # Adds random jitter to a delay value.
120
+ # @param delay [Float] The base delay in seconds.
121
+ # @return [Float] The delay with jitter applied.
122
+ def add_jitter(delay)
123
+ jitter = delay * JITTER_FACTOR * (rand - 0.5) * 2
124
+ [delay + jitter, 0].max
125
+ end
126
+
127
+ LOCALHOST_HOSTS = %w[localhost 127.0.0.1 [::1]].freeze
128
+
129
+ # @param request [Insion::Internal::Http::BaseRequest] The HTTP request.
130
+ # @return [URI::Generic] The URL.
131
+ def build_url(request)
132
+ encoded_query = request.encode_query
133
+
134
+ # If the path is already an absolute URL, use it directly
135
+ if request.path.start_with?("http://", "https://")
136
+ url = request.path
137
+ url = "#{url}?#{encode_query(encoded_query)}" if encoded_query&.any?
138
+ parsed = URI.parse(url)
139
+ validate_https!(parsed)
140
+ return parsed
141
+ end
142
+
143
+ path = request.path.start_with?("/") ? request.path[1..] : request.path
144
+ base = request.base_url || @base_url
145
+ url = "#{base.chomp("/")}/#{path}"
146
+ url = "#{url}?#{encode_query(encoded_query)}" if encoded_query&.any?
147
+ parsed = URI.parse(url)
148
+ validate_https!(parsed)
149
+ parsed
150
+ end
151
+
152
+ # Raises if the URL uses http:// for a non-localhost host, which would
153
+ # send authentication credentials in plaintext.
154
+ # @param url [URI::Generic] The parsed URL.
155
+ def validate_https!(url)
156
+ return if url.scheme != "http"
157
+ return if LOCALHOST_HOSTS.include?(url.host)
158
+
159
+ raise ArgumentError,
160
+ "Refusing to send request to non-HTTPS URL: #{url}. " \
161
+ "HTTP is only allowed for localhost. Use HTTPS or pass a localhost URL."
162
+ end
163
+
164
+ # Resolves the auth headers to send with the next request. Delegates to the
165
+ # configured auth provider (if any) on every call so that token-based
166
+ # providers (e.g. OAuth client-credentials) can refresh an expired token
167
+ # before the request is sent. Returns an empty hash when no provider is set,
168
+ # which keeps the api-key / basic / bearer / no-auth paths unchanged.
169
+ # @return [Hash] The auth headers for the current request.
170
+ def resolve_auth_headers
171
+ return {} if @auth_provider.nil?
172
+
173
+ @auth_provider.auth_headers
174
+ end
175
+
176
+ # @param url [URI::Generic] The url to the resource.
177
+ # @param method [String] The HTTP method to use.
178
+ # @param headers [Hash] The headers for the request.
179
+ # @param body [String, nil] The body for the request.
180
+ # @param auth_headers [Hash] The auth headers resolved for this request. These
181
+ # take precedence over the static default headers but not over per-request
182
+ # headers, mirroring the previous baked-header precedence.
183
+ # @return [HTTP::Request] The HTTP request.
184
+ def build_http_request(url:, method:, headers: {}, body: nil, auth_headers: {})
185
+ request = Net::HTTPGenericRequest.new(
186
+ method,
187
+ !body.nil?,
188
+ method != "HEAD",
189
+ url
190
+ )
191
+
192
+ request_headers = @default_headers.merge(auth_headers).merge(headers)
193
+ request_headers.each { |name, value| request[name] = value }
194
+ request.body = body if body
195
+
196
+ # Net::HTTP disables its transparent gzip/deflate decoding as soon as an
197
+ # Accept-Encoding header is set explicitly on the request. Re-enable it so
198
+ # that compressed response bodies are still inflated.
199
+ request.extend(DecodeContent) if request_headers.keys.any? { |name| name.to_s.casecmp("accept-encoding").zero? }
200
+
201
+ request
202
+ end
203
+
204
+ # Keeps Net::HTTP's transparent gzip/deflate response decoding enabled
205
+ # even when an Accept-Encoding header is set explicitly on the request.
206
+ # @api private
207
+ module DecodeContent
208
+ def decode_content # rubocop:disable Naming/PredicateMethod
209
+ true
210
+ end
211
+ end
212
+
213
+ # @param query [Hash] The query for the request.
214
+ # @return [String, nil] The encoded query.
215
+ def encode_query(query)
216
+ query.to_h.empty? ? nil : URI.encode_www_form(query)
217
+ end
218
+
219
+ # @param url [URI::Generic] The url to connect to.
220
+ # @return [Net::HTTP] The HTTP connection.
221
+ def connect(url)
222
+ is_https = (url.scheme == "https")
223
+
224
+ port = if url.port
225
+ url.port
226
+ elsif is_https
227
+ Net::HTTP.https_default_port
228
+ else
229
+ Net::HTTP.http_default_port
230
+ end
231
+
232
+ http = Net::HTTP.new(url.host, port)
233
+ http.use_ssl = is_https
234
+ http.verify_mode = OpenSSL::SSL::VERIFY_PEER if is_https
235
+ # NOTE: We handle retries at the application level with HTTP status code awareness,
236
+ # so we set max_retries to 0 to disable Net::HTTP's built-in network-level retries.
237
+ http.max_retries = 0
238
+ http
239
+ end
240
+
241
+ # @return [String]
242
+ def inspect
243
+ "#<#{self.class.name}:0x#{object_id.to_s(16)} @base_url=#{@base_url.inspect}>"
244
+ end
245
+ end
246
+ end
247
+ end
248
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insion
4
+ module Internal
5
+ class CursorItemIterator < ItemIterator
6
+ # Instantiates a CursorItemIterator, an Enumerable class which wraps calls to a cursor-based paginated API and yields individual items from it.
7
+ #
8
+ # @param initial_cursor [String] The initial cursor to use when iterating, if any.
9
+ # @param cursor_field [Symbol] The field in API responses to extract the next cursor from.
10
+ # @param item_field [Symbol] The field in API responses to extract the items to iterate over.
11
+ # @param block [Proc] A block which is responsible for receiving a cursor to use and returning the given page from the API.
12
+ # @return [Insion::Internal::CursorItemIterator]
13
+ def initialize(initial_cursor:, cursor_field:, item_field:, &)
14
+ super()
15
+ @item_field = item_field
16
+ @page_iterator = CursorPageIterator.new(initial_cursor:, cursor_field:, &)
17
+ @page = nil
18
+ end
19
+
20
+ # Returns the CursorPageIterator mediating access to the underlying API.
21
+ #
22
+ # @return [Insion::Internal::CursorPageIterator]
23
+ def pages
24
+ @page_iterator
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insion
4
+ module Internal
5
+ class CursorPageIterator
6
+ include Enumerable
7
+
8
+ # The raw HTTP response from the most recent page response.
9
+ # @return [Net::HTTPResponse, nil]
10
+ attr_reader :http_response
11
+
12
+ # Instantiates a CursorPageIterator, an Enumerable class which wraps calls to a cursor-based paginated API and yields pages of items.
13
+ #
14
+ # @param initial_cursor [String] The initial cursor to use when iterating, if any.
15
+ # @param cursor_field [Symbol] The name of the field in API responses to extract the next cursor from.
16
+ # @param block [Proc] A block which is responsible for receiving a cursor to use and returning the given page from the API.
17
+ # The block should return a two-element array: [parsed_page, raw_http_response].
18
+ # @return [Insion::Internal::CursorPageIterator]
19
+ def initialize(initial_cursor:, cursor_field:, &block)
20
+ @need_initial_load = initial_cursor.nil?
21
+ @cursor = initial_cursor
22
+ @cursor_field = cursor_field
23
+ @get_next_page = block
24
+ @http_response = nil
25
+ end
26
+
27
+ # Iterates over each page returned by the API.
28
+ #
29
+ # @param block [Proc] The block which each retrieved page is yielded to.
30
+ # @return [NilClass]
31
+ def each(&block)
32
+ while (page = next_page)
33
+ block.call(page)
34
+ end
35
+ end
36
+
37
+ # Whether another page will be available from the API.
38
+ #
39
+ # @return [Boolean]
40
+ def next?
41
+ @need_initial_load || !@cursor.nil?
42
+ end
43
+
44
+ # Retrieves the next page from the API.
45
+ #
46
+ # @return [Object, nil]
47
+ def next_page
48
+ return if !@need_initial_load && @cursor.nil?
49
+
50
+ @need_initial_load = false
51
+ result = @get_next_page.call(@cursor)
52
+ if result.is_a?(Array)
53
+ fetched_page, raw_response = result
54
+ @http_response = raw_response
55
+ else
56
+ fetched_page = result
57
+ end
58
+ @cursor = fetched_page.send(@cursor_field)
59
+ fetched_page
60
+ end
61
+ end
62
+ end
63
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insion
4
+ module Internal
5
+ class ItemIterator
6
+ include Enumerable
7
+
8
+ # The raw HTTP response from the most recent page response.
9
+ # @return [Net::HTTPResponse, nil]
10
+ def http_response
11
+ @page_iterator&.http_response
12
+ end
13
+
14
+ # Iterates over each item returned by the API.
15
+ #
16
+ # @param block [Proc] The block which each retrieved item is yielded to.
17
+ # @return [NilClass]
18
+ def each(&block)
19
+ while (item = next_element)
20
+ block.call(item)
21
+ end
22
+ end
23
+
24
+ # Whether another item will be available from the API.
25
+ #
26
+ # @return [Boolean]
27
+ def next?
28
+ load_next_page if @page.nil?
29
+ return false if @page.nil?
30
+
31
+ return true if any_items_in_cached_page?
32
+
33
+ load_next_page
34
+ any_items_in_cached_page?
35
+ end
36
+
37
+ # Retrieves the next item from the API.
38
+ def next_element
39
+ item = next_item_from_cached_page
40
+ return item if item
41
+
42
+ load_next_page
43
+ next_item_from_cached_page
44
+ end
45
+
46
+ private
47
+
48
+ def next_item_from_cached_page
49
+ return unless @page
50
+
51
+ @page.send(@item_field).shift
52
+ end
53
+
54
+ def any_items_in_cached_page?
55
+ return false unless @page
56
+
57
+ !@page.send(@item_field).empty?
58
+ end
59
+
60
+ def load_next_page
61
+ @page = @page_iterator.next_page
62
+ end
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insion
4
+ module Internal
5
+ class OffsetItemIterator < ItemIterator
6
+ # Instantiates an OffsetItemIterator, an Enumerable class which wraps calls to an offset-based paginated API and yields the individual items from it.
7
+ #
8
+ # @param initial_page [Integer] The initial page or offset to start from when iterating.
9
+ # @param item_field [Symbol] The name of the field in API responses to extract the items to iterate over.
10
+ # @param has_next_field [Symbol] The name of the field in API responses containing a boolean of whether another page exists.
11
+ # @param step [Boolean] If true, treats the page number as a true offset (i.e. increments the page number by the number of items returned from each call rather than just 1)
12
+ # @param block [Proc] A block which is responsible for receiving a page number to use and returning the given page from the API.
13
+ #
14
+ # @return [Insion::Internal::OffsetItemIterator]
15
+ def initialize(initial_page:, item_field:, has_next_field:, step:, &)
16
+ super()
17
+ @item_field = item_field
18
+ @page_iterator = OffsetPageIterator.new(initial_page:, item_field:, has_next_field:, step:, &)
19
+ @page = nil
20
+ end
21
+
22
+ # Returns the OffsetPageIterator that is mediating access to the underlying API.
23
+ #
24
+ # @return [Insion::Internal::OffsetPageIterator]
25
+ def pages
26
+ @page_iterator
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insion
4
+ module Internal
5
+ class OffsetPageIterator
6
+ include Enumerable
7
+
8
+ # The raw HTTP response from the most recent page response.
9
+ # @return [Net::HTTPResponse, nil]
10
+ attr_reader :http_response
11
+
12
+ # Instantiates an OffsetPageIterator, an Enumerable class which wraps calls to an offset-based paginated API and yields pages of items from it.
13
+ #
14
+ # @param initial_page [Integer] The initial page to use when iterating, if any.
15
+ # @param item_field [Symbol] The field to pull the list of items to iterate over.
16
+ # @param has_next_field [Symbol] The field to pull the boolean of whether a next page exists from, if any.
17
+ # @param step [Boolean] If true, treats the page number as a true offset (i.e. increments the page number by the number of items returned from each call rather than just 1)
18
+ # @param block [Proc] A block which is responsible for receiving a page number to use and returning the given page from the API.
19
+ # The block should return a two-element array: [parsed_page, raw_http_response].
20
+ # @return [Insion::Internal::OffsetPageIterator]
21
+ def initialize(initial_page:, item_field:, has_next_field:, step:, &block)
22
+ @page_number = initial_page || (step ? 0 : 1)
23
+ @item_field = item_field
24
+ @has_next_field = has_next_field
25
+ @step = step
26
+ @get_next_page = block
27
+
28
+ # A cache of whether the API has another page, if it gives us that information...
29
+ @next_page = nil
30
+ # ...or the actual next page, preloaded, if it doesn't.
31
+ @has_next_page = nil
32
+
33
+ @http_response = nil
34
+ end
35
+
36
+ # Iterates over each page returned by the API.
37
+ #
38
+ # @param block [Proc] The block which each retrieved page is yielded to.
39
+ # @return [NilClass]
40
+ def each(&block)
41
+ while (page = next_page)
42
+ block.call(page)
43
+ end
44
+ end
45
+
46
+ # Whether another page will be available from the API.
47
+ #
48
+ # @return [Boolean]
49
+ def next?
50
+ return @has_next_page unless @has_next_page.nil?
51
+ return true if @next_page
52
+
53
+ fetched_page = fetch_page(@page_number)
54
+ fetched_page_items = fetched_page&.send(@item_field)
55
+ if fetched_page_items.nil? || fetched_page_items.empty?
56
+ @has_next_page = false
57
+ else
58
+ @next_page = fetched_page
59
+ true
60
+ end
61
+ end
62
+
63
+ # Returns the next page from the API.
64
+ def next_page
65
+ return nil if @page_number.nil?
66
+
67
+ if @next_page
68
+ this_page = @next_page
69
+ @next_page = nil
70
+ else
71
+ this_page = fetch_page(@page_number)
72
+ end
73
+
74
+ @has_next_page = this_page&.send(@has_next_field) if @has_next_field
75
+
76
+ items = this_page.send(@item_field)
77
+ if items.nil? || items.empty?
78
+ @page_number = nil
79
+ return nil
80
+ elsif @step
81
+ @page_number += items.length
82
+ else
83
+ @page_number += 1
84
+ end
85
+
86
+ this_page
87
+ end
88
+
89
+ private
90
+
91
+ def fetch_page(page_number)
92
+ result = @get_next_page.call(page_number)
93
+ if result.is_a?(Array)
94
+ fetched_page, raw_response = result
95
+ @http_response = raw_response
96
+ fetched_page
97
+ else
98
+ result
99
+ end
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Insion
4
+ module Internal
5
+ module JSON
6
+ # @api private
7
+ class Request < Insion::Internal::Http::BaseRequest
8
+ attr_reader :body
9
+
10
+ # @param base_url [String] The base URL for the request
11
+ # @param path [String] The path for the request
12
+ # @param method [Symbol] The HTTP method for the request (:get, :post, etc.)
13
+ # @param headers [Hash] Additional headers for the request (optional)
14
+ # @param query [Hash] Query parameters for the request (optional)
15
+ # @param body [Object, nil] The JSON request body (optional)
16
+ # @param request_options [Insion::RequestOptions, Hash{Symbol=>Object}, nil]
17
+ def initialize(base_url:, path:, method:, headers: {}, query: {}, body: nil, request_options: {})
18
+ super(base_url:, path:, method:, headers:, query:, request_options:)
19
+
20
+ @body = body
21
+ end
22
+
23
+ # @return [Hash] The encoded HTTP request headers.
24
+ # @param protected_keys [Array<String>] Header keys set by the SDK client (e.g. auth, metadata)
25
+ # that must not be overridden by additional_headers from request_options.
26
+ def encode_headers(protected_keys: [])
27
+ sdk_headers = {
28
+ "Content-Type" => "application/json",
29
+ "Accept" => "application/json"
30
+ }.merge(@headers)
31
+ merge_additional_headers(sdk_headers, protected_keys:)
32
+ end
33
+
34
+ # @return [String, nil] The encoded HTTP request body.
35
+ def encode_body
36
+ @body.nil? ? nil : ::JSON.generate(@body)
37
+ end
38
+ end
39
+ end
40
+ end
41
+ end