davixlabs-h2i 1.2.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 2b44d4cc003ab8487223577d44e0ca0c5c8d860bc1b0bc48f2ed116b31c770fc
4
+ data.tar.gz: 90da31b814f42b9566b6b640a03f625d5e586f4dc0e6bc9d4863e570c13c6923
5
+ SHA512:
6
+ metadata.gz: bb0e6e259bd5fea965001c2ed8c23bb7ffa214951b86f34aaf1864b67e35310d8b779b1fe841e8df99115bcf6d0e1bb707a24c26a2c4455bc9d8e17902162b77
7
+ data.tar.gz: 52e3f8382bb85cb56e54ce6520426128454bbf77391c0a69c8eeec10dab2698717d3847976841d4464c7e661c7fe0d5701d953623dd78d52fb8c6c10e3a996d0
data/LICENSE ADDED
@@ -0,0 +1,10 @@
1
+ Davix H2I SDK License
2
+
3
+ Copyright (c) 2026 Davix Labs. All rights reserved.
4
+
5
+ You may install, copy and use this software, and include it unchanged or modified in your own applications, in order to
6
+ use the Davix H2I API with a Davix H2I account, under the Davix H2I terms of service (https://h2i.davixlabs.io/terms/).
7
+ You may not sell this software on its own, or use it to build or offer a service that competes with Davix H2I.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. TO THE EXTENT THE LAW ALLOWS,
10
+ DAVIX LABS IS NOT LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY ARISING FROM THE SOFTWARE OR ITS USE.
data/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # Davix H2I Ruby SDK (`davixlabs-h2i`)
2
+
3
+ Official client for the [Davix H2I](https://h2i.davixlabs.io) API: images, PDFs, documents, data and AI tools.
4
+ Every method, field list, enum and error code is generated from the same API contract as the server.
5
+
6
+ ## Install
7
+
8
+ Ruby 3.0 or newer, standard library only.
9
+
10
+ ```bash
11
+ gem install davixlabs-h2i
12
+ ```
13
+
14
+ ## Use
15
+
16
+ ```ruby
17
+ require 'davix_h2i'
18
+
19
+ h2i = DavixH2I::Client.new(api_key: ENV['DAVIX_H2I_API_KEY'])
20
+ begin
21
+ result = h2i.images.resize(images: 'photo.jpg', width: 800)
22
+ h2i.download(result.files.first, dest: 'photo-800.jpg')
23
+ rescue DavixH2I::Error => e
24
+ warn [e.code, e.hint, e.request_id].inspect
25
+ end
26
+ ```
27
+
28
+ ## What it does for you
29
+
30
+ * **Key safety:** the API key is only sent as a header, is never printed, and never follows a redirect or goes to a download address.
31
+ * **Retries:** only failures that are safe to repeat; one Idempotency-Key per call, reused by its retries, so a retry never bills twice.
32
+ * **Errors:** every error carries the API's code, status, hint, details and request id.
33
+ * **Files:** a plain text value is read from disk only for a field the API defines as a file.
34
+ * **New endpoints:** the generic request method reaches public `/v1/` paths this version does not know yet.
35
+ * **Metadata:** each endpoint's schema (types, limits, defaults, allowed values) with an optional check before sending.
36
+
37
+ Pass the parameters as a hash to add call options: `h2i.images.resize({ images: 'photo.jpg' }, idempotency_key: 'order-42')`.
38
+ Ruby keeps `inspect` for itself, so that API method is called `inspect_file` (for images and for PDFs).
39
+ Tests: `ruby test/test_conformance.rb`.
40
+
41
+ ## Help
42
+
43
+ [Developer guide](https://h2i.davixlabs.io/developers/) · h2i-support@davixlabs.io
@@ -0,0 +1,289 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'securerandom'
5
+ require 'uri'
6
+
7
+ module DavixH2I
8
+ DEFAULT_BASE_URL = 'https://app.h2i.davixlabs.io'
9
+
10
+ # h2i = DavixH2I::Client.new(api_key: ENV['DAVIX_H2I_API_KEY'])
11
+ # h2i.images.resize(images: 'photo.jpg', width: 800)
12
+ class Client
13
+ include Generated::Namespaces
14
+
15
+ SCHEMA_MAJOR = 1
16
+ REPEATABLE = %w[GET HEAD OPTIONS PUT DELETE].freeze
17
+ OPTIONS = %i[idempotency_key headers timeout max_retries retry validate strict].freeze
18
+
19
+ attr_reader :base_url, :contract, :capabilities
20
+
21
+ def initialize(api_key:, base_url: DEFAULT_BASE_URL, timeout: 60, max_retries: 2, max_retry_delay: 30, auth_scheme: 'x-api-key',
22
+ auto_idempotency_key: true, validate: false, allow_insecure: false, user_agent_suffix: nil)
23
+ raise ConfigError, 'Davix H2I: api_key is required.' unless api_key.is_a?(String) && !api_key.strip.empty?
24
+ raise ConfigError, 'Davix H2I: api_key contains invalid characters.' if api_key.match?(/[\r\n]/)
25
+
26
+ uri = parse_base(base_url || DEFAULT_BASE_URL, allow_insecure)
27
+ raise ConfigError, 'Davix H2I: auth_scheme must be "x-api-key" or "bearer".' unless %w[x-api-key bearer].include?(auth_scheme)
28
+
29
+ @api_key = api_key.strip
30
+ @origin = [uri.scheme, uri.host.downcase, uri.port]
31
+ @base_uri = uri
32
+ @base_url = base_url.to_s.sub(%r{/+\z}, '')
33
+ @timeout = timeout
34
+ @max_retries = max_retries
35
+ @max_retry_delay = max_retry_delay
36
+ @auth_scheme = auth_scheme
37
+ @auto_idempotency_key = auto_idempotency_key
38
+ @validate = validate
39
+ @user_agent = "davix-h2i-ruby/#{VERSION}#{user_agent_suffix ? " #{user_agent_suffix}" : ''}"
40
+ @contract = ContractView.new(self)
41
+ @capabilities = Capabilities.new(self)
42
+ @schemas = {}
43
+ end
44
+
45
+ # never shows the key
46
+ def inspect
47
+ "#<DavixH2I::Client #{base_url}>"
48
+ end
49
+ alias to_s inspect
50
+
51
+ def marshal_dump
52
+ raise TypeError, 'The client holds your API key and cannot be serialized.'
53
+ end
54
+
55
+ def schema(id)
56
+ @schemas[id] ||= begin
57
+ endpoints = contract.active['endpoints']
58
+ found = endpoints.find { |e| e['id'] == id } || endpoints.find { |e| "#{e['sdk']['namespace'].join('.')}.#{e['sdk']['method']}" == id }
59
+ raise ConfigError, "Unknown endpoint \"#{id}\"." unless found
60
+
61
+ Schema.new(found)
62
+ end
63
+ end
64
+
65
+ # Calls an endpoint by its id. Options: idempotency_key, headers, timeout, max_retries, retry, validate, strict.
66
+ def call(id, params = nil, **options)
67
+ invoke(id, params, options)
68
+ end
69
+
70
+ # What the generated methods use. Without a params hash, keywords that are not options are the parameters.
71
+ def invoke(id, params, options)
72
+ if params.nil?
73
+ params = options.reject { |k, _| OPTIONS.include?(k) }
74
+ options = options.select { |k, _| OPTIONS.include?(k) }
75
+ end
76
+ check_options(options)
77
+ info = schema(id)
78
+ raise ConfigError, "#{id}: params must be a Hash." unless params.is_a?(Hash)
79
+
80
+ params = params.transform_keys(&:to_s)
81
+ validate_params(info, params) if options.fetch(:validate, @validate)
82
+ unknown = params.keys - info.fields.keys
83
+ raise ConfigError, "#{id}: unknown parameter(s): #{unknown.join(', ')}." if options[:strict] && !unknown.empty?
84
+
85
+ path_values = {}
86
+ query = {}
87
+ headers = {}
88
+ body = {}
89
+ params.each do |name, value| # your order is kept; unknown names (a newer server) go in the body
90
+ field = info.fields[name]
91
+ location = field && field['location']
92
+ next if location == 'header' && field['standard']
93
+
94
+ if location == 'path' then path_values[name] = value
95
+ elsif value.nil? then next
96
+ elsif location == 'query' then query[name] = value
97
+ elsif location == 'header' then headers[name] = value.to_s
98
+ else body[name] = value
99
+ end
100
+ end
101
+ url_path = Paths.expand(info.path, path_values)
102
+ payload = content_type = nil
103
+ if info.endpoint['request']['contentType'] == 'multipart/form-data'
104
+ payload, content_type = Multipart.build(info.fields.values.select { |f| f['location'] == 'form' }, body)
105
+ elsif !body.empty?
106
+ payload = JSON.generate(body)
107
+ content_type = 'application/json'
108
+ end
109
+ perform(info.method_name, url_path, query: query, headers: headers, payload: payload, content_type: content_type,
110
+ eligible: info.method_name == 'POST' && info.idempotent?, options: options)
111
+ end
112
+
113
+ # For endpoints this version does not know yet. Only the public API (/v1/...) can be reached.
114
+ def request(method, path, query: nil, json: nil, form: nil, **options)
115
+ check_options(options)
116
+ verb = method.to_s.upcase
117
+ raise ConfigError, "request(): unsupported method \"#{method}\"." unless %w[GET POST PUT PATCH DELETE].include?(verb)
118
+
119
+ Paths.assert_public(path, contract.active['requestPolicy'])
120
+ endpoint = contract.active['endpoints'].find { |e| e['method'] == verb && Paths.match_template?(e['path'], path) }
121
+ raise ConfigError, 'request(): pass either json or form, not both.' if !json.nil? && !form.nil?
122
+
123
+ payload = content_type = nil
124
+ if !json.nil?
125
+ payload = JSON.generate(json)
126
+ content_type = 'application/json'
127
+ elsif form
128
+ known = endpoint && endpoint['request']['fields'].select { |f| f['location'] == 'form' }
129
+ payload, content_type = Multipart.build(known, form)
130
+ end
131
+ eligible = verb == 'POST' && endpoint && endpoint.dig('idempotency', 'supported') ? true : false
132
+ perform(verb, path, query: query, payload: payload, content_type: content_type, eligible: eligible, options: options)
133
+ end
134
+
135
+ # Fetches a signed result address of this server. The API key is NOT sent. Returns the bytes, or dest when given.
136
+ def download(url_or_result, dest: nil, timeout: nil)
137
+ raw = url_or_result.is_a?(Hash) ? url_or_result['url'] : url_or_result
138
+ raise ConfigError, 'download(): pass a URL string or a result with a "url".' unless raw.is_a?(String)
139
+
140
+ url = URI.join("#{base_url}/", raw)
141
+ raise ConfigError, 'download(): refusing to fetch a URL that is not on the configured Davix H2I host.' unless [url.scheme, url.host.to_s.downcase, url.port] == @origin
142
+
143
+ written = raw.split('?').first
144
+ unless url.path.match?(%r{\A/(render|image|pdf|ai|data|documents)/[^/\\]+\z}) && !written.match?(%r{/(\.|%2e){1,2}(/|\z)}i)
145
+ raise ConfigError, 'download(): not a Davix H2I output URL.'
146
+ end
147
+
148
+ status, headers, data = Transport.call('GET', url.to_s, { 'user-agent' => @user_agent }, nil, timeout || @timeout)
149
+ raise api_error(status, parse(headers, data), headers) if status >= 300
150
+ return data unless dest
151
+
152
+ require 'fileutils'
153
+ FileUtils.mkdir_p(::File.dirname(::File.expand_path(dest)))
154
+ ::File.binwrite(dest, data)
155
+ dest
156
+ end
157
+
158
+ private
159
+
160
+ def parse_base(base, allow_insecure)
161
+ uri = begin
162
+ URI.parse(base)
163
+ rescue URI::InvalidURIError
164
+ raise ConfigError, 'Davix H2I: base_url is not a valid URL.'
165
+ end
166
+ host = uri.hostname.to_s.downcase
167
+ local = %w[localhost 127.0.0.1 ::1].include?(host) || host.end_with?('.localhost')
168
+ secure = uri.scheme == 'https' || (uri.scheme == 'http' && (local || allow_insecure))
169
+ raise ConfigError, 'Davix H2I: base_url must use https:// (http:// is only allowed for localhost, or with allow_insecure).' if host.empty? || !secure
170
+ raise ConfigError, 'Davix H2I: credentials in base_url are not allowed.' if uri.userinfo
171
+
172
+ uri
173
+ end
174
+
175
+ def check_options(options)
176
+ unknown = options.keys - OPTIONS
177
+ raise ConfigError, "Unknown option(s): #{unknown.join(', ')}. API parameters go in the params hash." unless unknown.empty?
178
+ end
179
+
180
+ def validate_params(info, params)
181
+ result = info.validate(params)
182
+ return if result[:valid]
183
+
184
+ raise ConfigError.new("#{info.id}: invalid parameters: #{result[:errors].map { |e| e[:message] }.join(' ')}",
185
+ code: 'sdk_validation_failed', details: { 'errors' => result[:errors] })
186
+ end
187
+
188
+ def check_contract(contract)
189
+ raise ConfigError, 'The live contract is malformed.' unless contract.is_a?(Hash) && contract['endpoints'].is_a?(Array)
190
+ return if contract['metadataSchemaVersion'].to_i == SCHEMA_MAJOR
191
+
192
+ raise ConfigError, "The live contract uses metadata schema #{contract['metadataSchemaVersion']}, which this SDK version (#{VERSION}) does not understand. Upgrade the SDK."
193
+ end
194
+
195
+ def forget_schemas
196
+ @schemas = {}
197
+ end
198
+
199
+ def parse(headers, data)
200
+ type = headers['content-type'].to_s
201
+ if type.include?('json')
202
+ begin
203
+ JSON.parse(data.dup.force_encoding(Encoding::UTF_8))
204
+ rescue JSON::ParserError, EncodingError
205
+ nil
206
+ end
207
+ elsif type.start_with?('text/')
208
+ data.dup.force_encoding(Encoding::UTF_8).scrub
209
+ else
210
+ data.empty? ? nil : data
211
+ end
212
+ end
213
+
214
+ def api_error(status, body, headers)
215
+ hash = body.is_a?(Hash) ? body : {}
216
+ error = hash['error'].is_a?(Hash) ? hash['error'] : {}
217
+ code = error['code'] || hash['code']
218
+ meta = code && contract.active['errors'].find { |e| e['code'] == code }
219
+ details = error['details']
220
+ after = Float(headers['retry-after'].to_s, exception: false) || Float((details.is_a?(Hash) ? details['retry_after_seconds'] : nil).to_s, exception: false)
221
+ DavixH2I.error_class(status, meta && meta['family']).new(
222
+ error['message'] || hash['message'] || "Davix H2I API error (HTTP #{status})",
223
+ code: code, status: status, hint: error['hint'], details: details, request_id: headers['request-id'] || hash['request_id'],
224
+ renewal_url: error['renewal_url'], retryable: meta ? meta['retryable'] : [503, 504].include?(status), retry_after: after, body: body
225
+ )
226
+ end
227
+
228
+ def perform(method, path, query: nil, headers: nil, payload: nil, content_type: nil, eligible: false, options: {}, attach_key: true)
229
+ url = base_url + path
230
+ target = URI.parse(url)
231
+ raise ConfigError, 'Resolved URL left the configured Davix H2I host.' unless [target.scheme, target.host.to_s.downcase, target.port] == @origin
232
+
233
+ pairs = (query || {}).flat_map { |name, value| Array(value).reject(&:nil?).map { |v| [name.to_s, v.to_s] } }
234
+ url += "?#{URI.encode_www_form(pairs)}" unless pairs.empty?
235
+ sent = { 'accept' => 'application/json', 'user-agent' => @user_agent }
236
+ if attach_key
237
+ @auth_scheme == 'bearer' ? sent['authorization'] = "Bearer #{@api_key}" : sent['x-api-key'] = @api_key
238
+ end
239
+ (headers || {}).merge(options[:headers] || {}).each do |name, value|
240
+ lower = name.to_s.downcase
241
+ raise ConfigError, "Header \"#{name}\" is managed by the SDK and cannot be overridden." if %w[x-api-key authorization host].include?(lower)
242
+
243
+ sent[lower] = value.to_s
244
+ end
245
+ sent['content-type'] = content_type if content_type
246
+ retries = options[:retry] == false ? 0 : options.fetch(:max_retries, @max_retries)
247
+ key = options[:idempotency_key]
248
+ if key
249
+ raise ConfigError, 'idempotency_key must be 8-128 characters from [A-Za-z0-9._:-].' unless key.match?(/\A[A-Za-z0-9._:-]{8,128}\z/)
250
+ elsif @auto_idempotency_key && eligible && retries.positive?
251
+ key = "h2i-#{SecureRandom.uuid}" # one key per call, reused by every retry, so a retry never bills twice
252
+ end
253
+ sent['idempotency-key'] = key if key
254
+ attempt_loop(method, url, sent, payload, options.fetch(:timeout, @timeout), retries, key)
255
+ end
256
+
257
+ def attempt_loop(method, url, sent, payload, timeout, retries, key)
258
+ safe = REPEATABLE.include?(method) || !key.nil? # repeating cannot duplicate work
259
+ attempt = 0
260
+ loop do
261
+ attempt += 1
262
+ begin
263
+ status, headers, data = Transport.call(method, url, sent, payload, timeout)
264
+ rescue NetworkError
265
+ raise unless attempt <= retries && safe
266
+
267
+ wait(attempt, nil)
268
+ next
269
+ end
270
+ body = parse(headers, data)
271
+ if status >= 200 && status < 300
272
+ request_id = headers['request-id'] || (body.is_a?(Hash) ? body['request_id'] : nil)
273
+ return Response.new(status: status, headers: headers, data: body, request_id: request_id, idempotency_key: key, attempts: attempt)
274
+ end
275
+ error = api_error(status, body, headers)
276
+ again = (status == 429 && error.retryable) || ([503, 504].include?(status) && error.retryable && safe)
277
+ raise error unless attempt <= retries && again
278
+
279
+ wait(attempt, error.retry_after)
280
+ end
281
+ end
282
+
283
+ def wait(attempt, retry_after)
284
+ delay = rand * [8.0, 0.5 * (2**(attempt - 1))].min
285
+ delay = [delay, retry_after].max if retry_after
286
+ sleep([delay, @max_retry_delay].min)
287
+ end
288
+ end
289
+ end