incenar 0.2.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.
- checksums.yaml +7 -0
- data/README.md +32 -0
- data/lib/incenar/client.rb +190 -0
- data/lib/incenar/errors.rb +37 -0
- data/lib/incenar/webhook.rb +37 -0
- data/lib/incenar.rb +9 -0
- metadata +48 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 68d70fe44f827d7f74b475844cd15ece64b78eaa1da654975da479171412c068
|
|
4
|
+
data.tar.gz: e966af195423e62e893b44f9e564f0e09266c72ea4f97ee9840bd48f31fe866d
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 34608831c2e7293492571d413395db5a4dfef63d0a6e65d77a610872687f21c2964983ccdfe7916771d60e105ec1616c792d5eaba8f362be99c8084ef969554f
|
|
7
|
+
data.tar.gz: bdaeaba1e788d892a8df3f2b7dab37a20b817af403a36cc1ca6e1417ee1a97a0795d725047d7bb8383c32b98c4c5a035797129e1e29e9caf4b8c0ff91dcc63b3
|
data/README.md
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# incenar
|
|
2
|
+
|
|
3
|
+
Dependency-free Ruby client for the InceNar API (Ruby 3.0+).
|
|
4
|
+
|
|
5
|
+
```ruby
|
|
6
|
+
require "incenar"
|
|
7
|
+
|
|
8
|
+
api = InceNar::Client.new(api_key: ENV["INCENAR_KEY"])
|
|
9
|
+
api.each_book(category: "fiction") { |book| puts book["title"] }
|
|
10
|
+
eur = api.convert(10, to: "EUR") # `from` defaults to the platform base currency
|
|
11
|
+
|
|
12
|
+
begin
|
|
13
|
+
api.key_info
|
|
14
|
+
rescue InceNar::RateLimitError => e
|
|
15
|
+
puts "resets #{e.reset_at}"
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
event = InceNar::Webhook.verify(request.body.read, request.headers["X-Webhook-Signature"], ENV["WEBHOOK_SECRET"])
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Retries, rate-limit handling and webhook safety match the JavaScript SDK. Test: `ruby test/test_sdk.rb`.
|
|
22
|
+
|
|
23
|
+
## Windows setup (tests and publishing)
|
|
24
|
+
|
|
25
|
+
The client has no dependencies, so the plain Ruby package is enough, with no DevKit. In an **Administrator** PowerShell:
|
|
26
|
+
|
|
27
|
+
```powershell
|
|
28
|
+
winget install RubyInstallerTeam.Ruby.3.3
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Exit code 5 ("You cancelled the installation") means the installer's elevation prompt was dismissed or the shell is not elevated. Reopen PowerShell with Run as administrator and accept the prompt. Then open a new terminal and check with `ruby -v`.
|
|
32
|
+
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "net/http"
|
|
4
|
+
require "uri"
|
|
5
|
+
require "json"
|
|
6
|
+
require "openssl"
|
|
7
|
+
|
|
8
|
+
module InceNar
|
|
9
|
+
class Client
|
|
10
|
+
DEFAULT_BASE_URL = "https://api.incenar.com"
|
|
11
|
+
KEY_RE = /\Aink_[A-Za-z0-9_\-]+\z/
|
|
12
|
+
UUID_RE = /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/i
|
|
13
|
+
LOCAL = %w[localhost 127.0.0.1 [::1] ::1].freeze
|
|
14
|
+
|
|
15
|
+
# Rate-limit headers from the most recent response that had them: { limit:, remaining:, reset_at: }.
|
|
16
|
+
attr_reader :rate_limit
|
|
17
|
+
|
|
18
|
+
# api_key is optional: meta, rates and webhook verification need none.
|
|
19
|
+
def initialize(api_key: nil, base_url: DEFAULT_BASE_URL, timeout: 15.0, max_retries: 3, max_retry_after: 30.0, sleeper: nil)
|
|
20
|
+
raise ArgumentError, "api_key must look like ink_..." unless api_key.nil? || (api_key.is_a?(String) && KEY_RE.match?(api_key))
|
|
21
|
+
|
|
22
|
+
u = URI.parse(base_url)
|
|
23
|
+
raise ArgumentError, "base_url must use https" unless u.scheme == "https" || (u.scheme == "http" && LOCAL.include?(u.host))
|
|
24
|
+
|
|
25
|
+
@base = "#{u.scheme}://#{u.host}#{u.port == u.default_port ? '' : ":#{u.port}"}#{u.path.sub(%r{/+\z}, '').sub(%r{/v1\z}, '')}"
|
|
26
|
+
@key = api_key
|
|
27
|
+
@timeout = timeout.to_f
|
|
28
|
+
@retries = [[max_retries.to_i, 0].max, 6].min
|
|
29
|
+
@max_retry_after = max_retry_after.to_f
|
|
30
|
+
@sleeper = sleeper
|
|
31
|
+
@rate_limit = nil
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def list_books(params = {})
|
|
35
|
+
request(:get, "/v1/books#{query(params)}", auth: true)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def get_book(id)
|
|
39
|
+
request(:get, "/v1/books/#{check_id('id', id)}", auth: true)
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# Walks every page; stops when the API says there is no more. Returns an Enumerator without a block.
|
|
43
|
+
def each_book(params = {})
|
|
44
|
+
return enum_for(:each_book, params) unless block_given?
|
|
45
|
+
|
|
46
|
+
params = params.dup
|
|
47
|
+
page = [params.delete(:page).to_i, 1].max
|
|
48
|
+
loop do
|
|
49
|
+
res = list_books(params.merge(page: page))
|
|
50
|
+
(res["data"] || []).each { |b| yield b }
|
|
51
|
+
break unless res.dig("meta", "hasMore")
|
|
52
|
+
|
|
53
|
+
page += 1
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
def get_author(id)
|
|
58
|
+
request(:get, "/v1/authors/#{check_id('id', id)}", auth: true)
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def embed(book_id, domain: nil)
|
|
62
|
+
request(:get, "/v1/reader/embed#{query(bookId: check_id('book_id', book_id), domain: domain)}", auth: true)
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def rates
|
|
66
|
+
request(:get, "/v1/rates")
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# from defaults to the platform base currency (see meta["baseCurrency"]).
|
|
70
|
+
def convert(amount, to:, from: nil)
|
|
71
|
+
raise ArgumentError, "amount must be a positive number" unless amount.is_a?(Numeric) && amount.to_f.finite? && amount.positive?
|
|
72
|
+
raise ArgumentError, "to is required" unless to.is_a?(String) && !to.empty?
|
|
73
|
+
|
|
74
|
+
body = { amount: amount, to: to }
|
|
75
|
+
body[:from] = from if from && !from.empty?
|
|
76
|
+
request(:post, "/v1/rates", body: body, idempotent: true)
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def meta
|
|
80
|
+
request(:get, "/v1/meta")
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
def key_info
|
|
84
|
+
request(:get, "/v1/keys/me", auth: true)
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# Sends a test event to your registered endpoints. Never retried: it would deliver twice.
|
|
88
|
+
def trigger_webhook(event, data = nil)
|
|
89
|
+
raise ArgumentError, "event is required" unless event.is_a?(String) && !event.empty?
|
|
90
|
+
|
|
91
|
+
request(:post, "/v1/webhooks", auth: true, body: { event: event, data: data })
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
private
|
|
95
|
+
|
|
96
|
+
def request(method, path, auth: false, body: nil, idempotent: nil)
|
|
97
|
+
raise ArgumentError, "This call needs an api_key" if auth && @key.nil?
|
|
98
|
+
|
|
99
|
+
idem = idempotent.nil? ? method == :get : idempotent
|
|
100
|
+
attempt = 0
|
|
101
|
+
loop do
|
|
102
|
+
begin
|
|
103
|
+
status, headers, raw = perform(method, path, auth, body)
|
|
104
|
+
rescue Net::OpenTimeout, Net::ReadTimeout, Timeout::Error => e
|
|
105
|
+
failure = "Request timed out"
|
|
106
|
+
rescue SocketError, SystemCallError, IOError, OpenSSL::SSL::SSLError, EOFError
|
|
107
|
+
failure = "Could not reach the API"
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
if failure
|
|
111
|
+
if idem && attempt < @retries
|
|
112
|
+
pause(backoff(attempt))
|
|
113
|
+
attempt += 1
|
|
114
|
+
failure = nil
|
|
115
|
+
next
|
|
116
|
+
end
|
|
117
|
+
raise NetworkError.new(failure)
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
rl = read_rate_limit(headers)
|
|
121
|
+
@rate_limit = rl if rl
|
|
122
|
+
decoded = begin
|
|
123
|
+
JSON.parse(raw)
|
|
124
|
+
rescue JSON::ParserError
|
|
125
|
+
nil
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
return(decoded.is_a?(Hash) ? decoded : raise(Error.new("Invalid response from the API", status: status))) if status.between?(200, 299)
|
|
129
|
+
|
|
130
|
+
err = Error.for_response(status, decoded, headers, rl)
|
|
131
|
+
retryable = [502, 503, 504].include?(status) || (status == 429 && err.retry_after && err.retry_after <= @max_retry_after)
|
|
132
|
+
if retryable && idem && attempt < @retries
|
|
133
|
+
wait = err.retry_after || backoff(attempt)
|
|
134
|
+
attempt += 1
|
|
135
|
+
pause(wait)
|
|
136
|
+
next
|
|
137
|
+
end
|
|
138
|
+
raise err
|
|
139
|
+
end
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
def perform(method, path, auth, body)
|
|
143
|
+
uri = URI.parse(@base + path) # no redirects are followed: the key never leaves the host
|
|
144
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
|
145
|
+
http.use_ssl = uri.scheme == "https"
|
|
146
|
+
http.open_timeout = [@timeout, 10].min
|
|
147
|
+
http.read_timeout = @timeout
|
|
148
|
+
http.write_timeout = @timeout
|
|
149
|
+
req = (method == :post ? Net::HTTP::Post : Net::HTTP::Get).new(uri.request_uri)
|
|
150
|
+
req["Accept"] = "application/json"
|
|
151
|
+
req["User-Agent"] = "incenar-ruby/#{InceNar::VERSION}"
|
|
152
|
+
req["Authorization"] = "Bearer #{@key}" if auth
|
|
153
|
+
unless body.nil?
|
|
154
|
+
req["Content-Type"] = "application/json"
|
|
155
|
+
req.body = JSON.generate(body)
|
|
156
|
+
end
|
|
157
|
+
res = http.start { |h| h.request(req) }
|
|
158
|
+
headers = res.each_header.to_h { |k, v| [k.downcase, v] }
|
|
159
|
+
[res.code.to_i, headers, res.body.to_s]
|
|
160
|
+
end
|
|
161
|
+
|
|
162
|
+
def read_rate_limit(h)
|
|
163
|
+
limit = Integer(h["x-ratelimit-limit"], exception: false)
|
|
164
|
+
remaining = Integer(h["x-ratelimit-remaining"], exception: false)
|
|
165
|
+
return nil if limit.nil? || remaining.nil?
|
|
166
|
+
|
|
167
|
+
{ limit: limit, remaining: remaining, reset_at: h["x-ratelimit-reset"] }
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
def backoff(attempt)
|
|
171
|
+
base = [8.0, 0.25 * (2**attempt)].min
|
|
172
|
+
base / 2 + rand * base / 2
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
def pause(seconds)
|
|
176
|
+
@sleeper ? @sleeper.call(seconds) : sleep(seconds)
|
|
177
|
+
end
|
|
178
|
+
|
|
179
|
+
def check_id(name, v)
|
|
180
|
+
raise ArgumentError, "#{name} must be a valid id" unless v.is_a?(String) && UUID_RE.match?(v)
|
|
181
|
+
|
|
182
|
+
v
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
def query(params)
|
|
186
|
+
clean = params.reject { |_, v| v.nil? || v == "" }
|
|
187
|
+
clean.empty? ? "" : "?" + URI.encode_www_form(clean.transform_values(&:to_s))
|
|
188
|
+
end
|
|
189
|
+
end
|
|
190
|
+
end
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module InceNar
|
|
4
|
+
class Error < StandardError
|
|
5
|
+
attr_reader :status, :code, :retry_after, :reset_at, :rate_limit
|
|
6
|
+
|
|
7
|
+
def initialize(message, status: 0, code: "error", retry_after: nil, reset_at: nil, rate_limit: nil)
|
|
8
|
+
super(message)
|
|
9
|
+
@status = status
|
|
10
|
+
@code = code
|
|
11
|
+
@retry_after = retry_after
|
|
12
|
+
@reset_at = reset_at
|
|
13
|
+
@rate_limit = rate_limit
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
def self.for_response(status, body, headers, rate_limit)
|
|
17
|
+
b = body.is_a?(Hash) ? body : {}
|
|
18
|
+
message = if b["message"].is_a?(String) && !b["message"].empty? then b["message"]
|
|
19
|
+
elsif b["error"].is_a?(String) then b["error"]
|
|
20
|
+
else "Request failed (#{status})"
|
|
21
|
+
end
|
|
22
|
+
ra = Float(headers["retry-after"], exception: false)
|
|
23
|
+
klass = { 401 => AuthenticationError, 403 => PermissionError, 404 => NotFoundError,
|
|
24
|
+
400 => ValidationError, 422 => ValidationError, 429 => RateLimitError }.fetch(status, Error)
|
|
25
|
+
klass.new(message, status: status, code: b["error"].is_a?(String) ? b["error"] : "error",
|
|
26
|
+
retry_after: ra && ra >= 0 ? ra : nil,
|
|
27
|
+
reset_at: b["resetAt"].is_a?(String) ? b["resetAt"] : nil, rate_limit: rate_limit)
|
|
28
|
+
end
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
class AuthenticationError < Error; end
|
|
32
|
+
class PermissionError < Error; end
|
|
33
|
+
class NotFoundError < Error; end
|
|
34
|
+
class ValidationError < Error; end
|
|
35
|
+
class RateLimitError < Error; end
|
|
36
|
+
class NetworkError < Error; end
|
|
37
|
+
end
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "openssl"
|
|
4
|
+
require "json"
|
|
5
|
+
|
|
6
|
+
module InceNar
|
|
7
|
+
module Webhook
|
|
8
|
+
SIG = /\Asha256=([0-9a-f]{64})\z/i
|
|
9
|
+
|
|
10
|
+
# Verifies an InceNar webhook. Pass the RAW request body exactly as received (request.body.read),
|
|
11
|
+
# the X-Webhook-Signature header and your endpoint secret. Returns the parsed payload or raises ArgumentError.
|
|
12
|
+
# tolerance (seconds) rejects old payloads using the payload's own timestamp (milliseconds); 0 skips the check.
|
|
13
|
+
def self.verify(raw_body, signature_header, secret, tolerance: 300, now: Time.now.to_f)
|
|
14
|
+
raise ArgumentError, "secret is required" unless secret.is_a?(String) && !secret.empty?
|
|
15
|
+
raise ArgumentError, "raw_body must be the raw string, not parsed JSON" unless raw_body.is_a?(String)
|
|
16
|
+
|
|
17
|
+
m = SIG.match(signature_header.to_s)
|
|
18
|
+
raise ArgumentError, "Invalid webhook signature" unless m
|
|
19
|
+
|
|
20
|
+
expected = OpenSSL::HMAC.hexdigest("SHA256", secret, raw_body)
|
|
21
|
+
unless OpenSSL.fixed_length_secure_compare(expected, m[1].downcase)
|
|
22
|
+
raise ArgumentError, "Invalid webhook signature"
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
payload = begin
|
|
26
|
+
JSON.parse(raw_body)
|
|
27
|
+
rescue JSON::ParserError
|
|
28
|
+
raise ArgumentError, "Invalid webhook payload"
|
|
29
|
+
end
|
|
30
|
+
if tolerance.to_f > 0
|
|
31
|
+
ts = payload.is_a?(Hash) ? payload["timestamp"] : nil
|
|
32
|
+
raise ArgumentError, "Webhook timestamp outside tolerance" unless ts.is_a?(Numeric) && (now - ts / 1000.0).abs <= tolerance
|
|
33
|
+
end
|
|
34
|
+
payload
|
|
35
|
+
end
|
|
36
|
+
end
|
|
37
|
+
end
|
data/lib/incenar.rb
ADDED
metadata
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: incenar
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.2.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- InceNar
|
|
8
|
+
autorequire:
|
|
9
|
+
bindir: bin
|
|
10
|
+
cert_chain: []
|
|
11
|
+
date: 2026-11-30 00:00:00.000000000 Z
|
|
12
|
+
dependencies: []
|
|
13
|
+
description: 'Dependency-free Ruby client for the InceNar API: retries with backoff,
|
|
14
|
+
rate limit handling, pagination and webhook verification.'
|
|
15
|
+
email:
|
|
16
|
+
executables: []
|
|
17
|
+
extensions: []
|
|
18
|
+
extra_rdoc_files: []
|
|
19
|
+
files:
|
|
20
|
+
- README.md
|
|
21
|
+
- lib/incenar.rb
|
|
22
|
+
- lib/incenar/client.rb
|
|
23
|
+
- lib/incenar/errors.rb
|
|
24
|
+
- lib/incenar/webhook.rb
|
|
25
|
+
homepage:
|
|
26
|
+
licenses:
|
|
27
|
+
- MIT
|
|
28
|
+
metadata: {}
|
|
29
|
+
post_install_message:
|
|
30
|
+
rdoc_options: []
|
|
31
|
+
require_paths:
|
|
32
|
+
- lib
|
|
33
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
34
|
+
requirements:
|
|
35
|
+
- - ">="
|
|
36
|
+
- !ruby/object:Gem::Version
|
|
37
|
+
version: '3.0'
|
|
38
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
39
|
+
requirements:
|
|
40
|
+
- - ">="
|
|
41
|
+
- !ruby/object:Gem::Version
|
|
42
|
+
version: '0'
|
|
43
|
+
requirements: []
|
|
44
|
+
rubygems_version: 3.5.22
|
|
45
|
+
signing_key:
|
|
46
|
+
specification_version: 4
|
|
47
|
+
summary: Official Ruby client for the InceNar API.
|
|
48
|
+
test_files: []
|