ordainer 0.1.1 → 0.1.3
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 +4 -4
- data/CHANGELOG.md +16 -0
- data/README.md +36 -5
- data/lib/ordainer/client.rb +147 -12
- data/lib/ordainer/configuration.rb +15 -3
- data/lib/ordainer/deny_response.rb +7 -4
- data/lib/ordainer/rails.rb +1 -1
- data/lib/ordainer/version.rb +1 -1
- data/lib/ordainer.rb +1 -1
- metadata +2 -2
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: c334caafef590bf890323811b0991f030976be205644efeaf24c191550024cdb
|
|
4
|
+
data.tar.gz: 2da2ee9ff7936324cbf724fed6f2dc34a4e889488db5ebff0132a77126985ea7
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 2dbcc6bd69d64046f5a37e178bbb6fb63ad5531fce367e3ffc5253dd02c1d5ced8f1ea0116cf96fd1486337c4685d7d7ade0e05930b427fea242f8da36c126e4
|
|
7
|
+
data.tar.gz: e46fd038be053292a6ab5a202a76ab2264cbec590ee8291ee440e425cead4f85ba59d631d33c32882468c727fed025b0fe9da9cc98cb147d9e00ba555fb74404
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.3 (2026-11-23)
|
|
4
|
+
|
|
5
|
+
`Ordainer::VERSION` is 0.1.3. Includes the earlier unreleased changes below.
|
|
6
|
+
|
|
7
|
+
- Changed (speed): a `Client` now keeps its connections to the API open and reuses them (HTTP keep-alive), like the Python SDK. Before, every `decide` opened a new TCP (and TLS) connection, which cost two or three network round trips per call. A call now takes an idle connection or opens a new one, so threads never share a socket and never wait for each other; up to 8 idle connections are kept (`Ordainer::MAX_IDLE_CONNECTIONS`), idle ones are reopened after 30 seconds (`Ordainer::KEEP_ALIVE_TIMEOUT`, below the API server's 65 seconds), and a child process after `fork` drops the connections it inherited without closing them and opens its own.
|
|
8
|
+
- Changed: if a reused connection turns out to be closed by the server (EOFError, `ECONNRESET`, `EPIPE`, `ECONNABORTED`, a closed stream, a TLS EOF, or `Net::HTTPBadResponse` from headers cut short), the call is sent again once on a new connection (not another idle one) with the same idempotency key, inside the same attempt. The API replays a repeated key, so the call is never counted twice and a deny is never turned into an allow. It does not use a `retries:` attempt. A read or open timeout is never resent this way, and a failure on a connection that was just opened is not resent. A response body shorter than its `Content-Length` is treated as that same transport failure (never parsed as an allow or a deny). An idle connection that already has bytes waiting (a leftover response or an idle `408`) is dropped at checkout instead of being reused.
|
|
9
|
+
- Unchanged: `timeout:` per attempt (300 ms default), the hard cap of twice the timeout per attempt, `retries:`, `retry_budget:`, `fail_mode:`, `billing_lapse:`, sticky deny, and every `Decision` field. A connection that timed out or failed is closed, never reused.
|
|
10
|
+
- Added: `Client#close` closes the idle connections. Optional; the client stays usable and opens a new connection on the next call. `Ordainer.configure` and `Ordainer.reset!` close the previous shared client.
|
|
11
|
+
- The SDK reads `ORDAINER_KEY` first, then `ORDAINER_API_KEY`.
|
|
12
|
+
- Changed: `Retry-After` on a quota or test-limit block is capped at 3600 seconds (one hour). The header is the seconds until `resets_at`, rounded up (at least 1), and never more than 3600. A monthly reset no longer produces a ~27-day `Retry-After`. Use `resets_at` in the JSON body for the real reset time; that field is unchanged. A non-finite difference still sends no header and never raises `FloatDomainError` (QA P95F-N4). The server's own `Retry-After` on `429 rate_limited` and `Retry-After: 5` on `503 ordainer_unavailable` are not this cap.
|
|
13
|
+
|
|
14
|
+
## 0.1.2
|
|
15
|
+
|
|
16
|
+
- Changed (behaviour): the agent key is read from `ENV["ORDAINER_KEY"]` first. `ENV["ORDAINER_API_KEY"]` is used only when `ORDAINER_KEY` is unset or empty. If both are set, `ORDAINER_KEY` wins; previously `ORDAINER_API_KEY` won. Passing `api_key:` still overrides both. An empty `ORDAINER_KEY` is treated as unset and falls through to `ORDAINER_API_KEY`, the same as Python (`or` does not strip whitespace). Not published. Not part of the Node README-only 1.2.6 release.
|
|
17
|
+
- Changed: Error messages reworded; codes, statuses and fields unchanged. Match on error.code, not the message. Same bytes as the Node SDK 1.2.5. Not published. `429 plan_limit_reached`: "This call wasn't run because the usage limit was reached ({remaining} of {limit} left). It resets at {resets_at}. Retrying before then won't work." The "It resets at" sentence is still omitted when `resets_at` is nil or empty. `403 plan_denied` with `tool_not_in_plan`: "This call wasn't run because "<tool>" isn't included in your current access. If you need it, contact the provider of this service. (tool_not_in_plan)", with the same quoting rules as 0.1.1 (otherwise "this action"). Any other plan deny is unchanged. Status, `code`, `reason`, `remaining`, `limit`, `resets_at`, `request_id`, headers and whether the call runs are unchanged.
|
|
18
|
+
|
|
3
19
|
## 0.1.1 (2026-10-18)
|
|
4
20
|
- Fixed (QA P95F-N4): `Ordainer.deny_response` no longer raises `FloatDomainError` when the server's `resets_at` parses but
|
|
5
21
|
gives a non-finite number of seconds (for example a fraction hundreds of digits long); there is no `Retry-After` header
|
data/README.md
CHANGED
|
@@ -19,7 +19,7 @@ gem "ordainer", "~> 0.1"
|
|
|
19
19
|
```ruby
|
|
20
20
|
require "ordainer"
|
|
21
21
|
|
|
22
|
-
client = Ordainer::Client.new(api_key: ENV["
|
|
22
|
+
client = Ordainer::Client.new(api_key: ENV["ORDAINER_KEY"]) # ord_test_...
|
|
23
23
|
decision = client.decide(tool: "research.run")
|
|
24
24
|
|
|
25
25
|
if decision.allowed?
|
|
@@ -33,7 +33,7 @@ end
|
|
|
33
33
|
|
|
34
34
|
| Option | Default | Meaning |
|
|
35
35
|
| --- | --- | --- |
|
|
36
|
-
| `api_key:` | `ENV["
|
|
36
|
+
| `api_key:` | `ENV["ORDAINER_KEY"]`, then `ENV["ORDAINER_API_KEY"]` | Agent key. If both are set, `ORDAINER_KEY` is used. Override per call: `decide(tool:, api_key:)`. |
|
|
37
37
|
| `base_url:` | `ENV["ORDAINER_BASE_URL"]` or `https://api.ordainer.dev` | |
|
|
38
38
|
| `timeout:` | `0.3` | Seconds per attempt. |
|
|
39
39
|
| `fail_mode:` | `:open` | `:open` lets the call run when Ordainer can't answer; `:closed` blocks it. |
|
|
@@ -46,6 +46,33 @@ end
|
|
|
46
46
|
| `logger:` | warn to `$stderr` | A `Logger`, or `false`. |
|
|
47
47
|
| `on_decision:` | `nil` | Called with every `Decision`. |
|
|
48
48
|
|
|
49
|
+
## Connections
|
|
50
|
+
|
|
51
|
+
A `Client` keeps its HTTPS connections to Ordainer open and reuses them, so only the first `decide` pays for TCP and TLS
|
|
52
|
+
setup (before 0.1.3 every call opened a new connection). Share one client per process; do not create one per request.
|
|
53
|
+
`Ordainer.configure` and `Ordainer.reset!` close the previous shared client (its idle connections); the next
|
|
54
|
+
`Ordainer.client` builds a new one.
|
|
55
|
+
|
|
56
|
+
- **Threads:** a connection serves one call at a time. A call takes an idle connection or opens a new one, so threads never
|
|
57
|
+
wait on each other and never share a socket. At most 8 idle connections are kept; extras are closed.
|
|
58
|
+
- **Idle:** a connection idle for more than 30 seconds is reopened. The API server holds idle connections for 65 seconds.
|
|
59
|
+
- **Fork (Puma, Unicorn, Spring):** a child process drops the connections it inherited without closing them (the parent
|
|
60
|
+
still uses them) and opens its own on the first call.
|
|
61
|
+
- **Closed by the other side:** if the server or a proxy closed an idle connection, the next call fails on it at once. The
|
|
62
|
+
client then opens a new connection (it does not take another idle one) and sends the call again, once, with the same
|
|
63
|
+
idempotency key, so Ordainer replays the answer and never counts the call twice. This happens inside the same attempt: it
|
|
64
|
+
doesn't use up one of your `retries:` and it doesn't change `timeout:` or `retry_budget:`. A timeout is never resent this
|
|
65
|
+
way. A response cut off before its `Content-Length` is treated the same (it is never parsed as an allow or a deny).
|
|
66
|
+
- **Unexpected bytes:** if an idle connection already has data waiting (a leftover or late response, or a proxy `408`), it
|
|
67
|
+
is dropped and a new connection is used, so those bytes are never read as the next answer.
|
|
68
|
+
- **Lost answer on a new connection:** the resend above only covers a reused idle connection. If a new connection drops
|
|
69
|
+
before the answer arrives, the call ends as a network error. With `retries: 0` and `fail_mode: :open` that is a fail-open
|
|
70
|
+
allow, even if Ordainer already processed (or denied) the call. Keep `retries:` at 1 or more, or use `fail_mode: :closed`,
|
|
71
|
+
if that matters for the tool. This is the same as earlier versions.
|
|
72
|
+
- **Unchanged:** `timeout:`, `retries:`, `retry_budget:`, `fail_mode:` and what each outcome means are as before.
|
|
73
|
+
- **`client.close`** closes the idle connections. It is optional (call it at shutdown, or in a test); the client keeps
|
|
74
|
+
working afterwards and opens a new connection on the next call.
|
|
75
|
+
|
|
49
76
|
## Rules (same as the Node SDK)
|
|
50
77
|
|
|
51
78
|
- `decide` never raises for an Ordainer answer or an outage. A deny is a normal result. Bad options raise
|
|
@@ -71,12 +98,16 @@ end
|
|
|
71
98
|
month are used up. They reset on November 1 (UTC). Nothing is wrong on your side, and trying again won't help until
|
|
72
99
|
they reset. If you need it sooner, contact the service's team. (test_limit_reached)" (the day is `resets_at` in UTC as
|
|
73
100
|
"<Month D>"; no "They reset on" sentence unless `resets_at` is a valid ISO-8601 date-time). A `tool_not_in_plan` deny
|
|
74
|
-
answers `403 plan_denied`: "This call wasn't run because
|
|
75
|
-
whoever manages your plan. (tool_not_in_plan)", naming the tool you passed to `decide` (or the Rails guard) in quotes
|
|
101
|
+
answers `403 plan_denied`: "This call wasn't run because "research.run" isn't included in your current access. If you need it, contact the provider of this service. (tool_not_in_plan)", naming the tool you passed to `decide` (or the Rails guard) in quotes
|
|
76
102
|
only when it matches `\A[A-Za-z0-9][A-Za-z0-9_.:/-]{0,63}\z` and has no `//` and no leading `scheme:` (`\A[A-Za-z][A-Za-z0-9+.-]*:`, so nothing URL-like is echoed), otherwise "this action". Any other deny answers "This
|
|
77
103
|
call wasn't run because it isn't allowed on your account right now. If you need it, contact the service's team.
|
|
78
104
|
(reason)", with the reason in brackets only when it looks like an API code (lowercase letters and `_`, up to 40
|
|
79
105
|
characters); the reason is also its own `reason` field.
|
|
106
|
+
- `Retry-After` on a quota (`plan_limit_reached`) or `test_limit_reached` block is the seconds until `resets_at`,
|
|
107
|
+
rounded up (at least 1), and capped at 3600 (one hour). Use `resets_at` in the JSON body for the real reset time.
|
|
108
|
+
A monthly reset no longer produces a multi-day `Retry-After`. Unknown or non-finite `resets_at` sends no header
|
|
109
|
+
(QA P95F-N4). The server's `Retry-After` on `429 rate_limited` and `Retry-After: 5` on `503 ordainer_unavailable`
|
|
110
|
+
are not this cap.
|
|
80
111
|
|
|
81
112
|
## Decision
|
|
82
113
|
|
|
@@ -90,7 +121,7 @@ end
|
|
|
90
121
|
```ruby
|
|
91
122
|
# config/initializers/ordainer.rb
|
|
92
123
|
Ordainer.configure do |c|
|
|
93
|
-
c.api_key = ENV["
|
|
124
|
+
c.api_key = ENV["ORDAINER_KEY"]
|
|
94
125
|
end
|
|
95
126
|
|
|
96
127
|
class ResearchController < ApplicationController
|
data/lib/ordainer/client.rb
CHANGED
|
@@ -6,6 +6,11 @@ require "json"
|
|
|
6
6
|
require "securerandom"
|
|
7
7
|
require "digest"
|
|
8
8
|
require "logger"
|
|
9
|
+
begin
|
|
10
|
+
require "openssl"
|
|
11
|
+
rescue LoadError
|
|
12
|
+
nil # net/http works without it for http:// URLs
|
|
13
|
+
end
|
|
9
14
|
|
|
10
15
|
module Ordainer
|
|
11
16
|
DEFAULT_BASE_URL = "https://api.ordainer.dev"
|
|
@@ -19,6 +24,14 @@ module Ordainer
|
|
|
19
24
|
MAX_STICKY_DENY = 300
|
|
20
25
|
MAX_STICKY_ENTRIES = 10_000
|
|
21
26
|
MAX_IDEMPOTENCY_LEN = 255
|
|
27
|
+
# Connection reuse (0.1.3). Idle connections are kept per Client and reused by the next decide.
|
|
28
|
+
KEEP_ALIVE_TIMEOUT = 30 # seconds a connection may sit idle before net/http reopens it (API server: 65 s)
|
|
29
|
+
MAX_IDLE_CONNECTIONS = 8 # idle connections kept per Client; any extra is closed when its call finishes
|
|
30
|
+
# A reused connection the server (or a proxy) closed while it sat idle fails like this on the next write or read.
|
|
31
|
+
# The call is sent once more on a fresh connection, with the same idempotency key. A timeout is never in this list.
|
|
32
|
+
# Net::HTTPBadResponse covers a response cut off in the middle of the headers.
|
|
33
|
+
STALE_CONNECTION_ERRORS = ([EOFError, IOError, Errno::ECONNRESET, Errno::EPIPE, Errno::ECONNABORTED, Net::HTTPBadResponse] +
|
|
34
|
+
(defined?(OpenSSL::SSL::SSLError) ? [OpenSSL::SSL::SSLError] : [])).freeze
|
|
22
35
|
MODES = %i[enforce shadow].freeze
|
|
23
36
|
FAIL_MODES = %i[open closed].freeze
|
|
24
37
|
DENY_STATUSES = [429, 402].freeze
|
|
@@ -40,11 +53,13 @@ module Ordainer
|
|
|
40
53
|
with_tool.length <= MAX_IDEMPOTENCY_LEN && with_tool !~ BAD_KEY_TEXT ? with_tool : digest
|
|
41
54
|
end
|
|
42
55
|
|
|
43
|
-
# Thread-safe; share one per process.
|
|
56
|
+
# Thread-safe; share one per process. Keeps connections open for reuse (see #close).
|
|
44
57
|
class Client
|
|
45
58
|
attr_reader :base_url, :timeout, :fail_mode, :retries, :retry_budget, :mode, :billing_lapse, :deny_status
|
|
46
59
|
|
|
47
|
-
# api_key: agent key (ord_test_/ord_live_). Default ENV["
|
|
60
|
+
# api_key: agent key (ord_test_/ord_live_). Default ENV["ORDAINER_KEY"], then ENV["ORDAINER_API_KEY"].
|
|
61
|
+
# If both are set, ORDAINER_KEY wins. An empty ORDAINER_KEY is unset and falls through
|
|
62
|
+
# (same as Python's `or`; whitespace is not stripped). An explicit api_key: still overrides both.
|
|
48
63
|
# base_url: default ENV["ORDAINER_BASE_URL"] or https://api.ordainer.dev
|
|
49
64
|
# timeout: seconds per attempt, default 0.3
|
|
50
65
|
# fail_mode: :open (default) or :closed. ONLY for timeouts, network errors, 5xx and malformed answers.
|
|
@@ -62,7 +77,13 @@ module Ordainer
|
|
|
62
77
|
def initialize(api_key: nil, base_url: nil, timeout: DEFAULT_TIMEOUT, fail_mode: :open, retries: DEFAULT_RETRIES,
|
|
63
78
|
retry_budget: DEFAULT_RETRY_BUDGET, mode: nil, billing_lapse: :open, deny_status: 429,
|
|
64
79
|
sticky_deny: DEFAULT_STICKY_DENY, logger: nil, on_decision: nil, sleeper: nil)
|
|
65
|
-
|
|
80
|
+
# ORDAINER_KEY is primary. ORDAINER_API_KEY is the fallback when it is unset.
|
|
81
|
+
# If both are set, ORDAINER_KEY wins. An empty string is unset, same as Python's `or`.
|
|
82
|
+
# Whitespace is kept; Python does not strip it.
|
|
83
|
+
@api_key = api_key || begin
|
|
84
|
+
env_key = ENV["ORDAINER_KEY"]
|
|
85
|
+
env_key.to_s.empty? ? ENV["ORDAINER_API_KEY"] : env_key
|
|
86
|
+
end
|
|
66
87
|
@base_url = (base_url || ENV["ORDAINER_BASE_URL"] || DEFAULT_BASE_URL).to_s.sub(%r{/+\z}, "")
|
|
67
88
|
@timeout = Float(timeout)
|
|
68
89
|
raise ConfigurationError, "timeout must be > 0" unless @timeout.positive?
|
|
@@ -84,6 +105,9 @@ module Ordainer
|
|
|
84
105
|
@on_decision = on_decision
|
|
85
106
|
@sleeper = sleeper || ->(s) { sleep(s) }
|
|
86
107
|
@uri = URI.join("#{@base_url}/", "v1/decide")
|
|
108
|
+
@pool_lock = Mutex.new
|
|
109
|
+
@idle = [] # [Net::HTTP, pid, generation], most recently used last
|
|
110
|
+
@generation = 0
|
|
87
111
|
rescue ArgumentError, TypeError => e
|
|
88
112
|
raise ConfigurationError, e.message
|
|
89
113
|
end
|
|
@@ -105,7 +129,7 @@ module Ordainer
|
|
|
105
129
|
|
|
106
130
|
result =
|
|
107
131
|
if key.nil? || key.to_s.empty?
|
|
108
|
-
rejected(base, ErrorInfo.new(code: "missing_key", message: "No #{BRAND_NAME} agent key (api_key /
|
|
132
|
+
rejected(base, ErrorInfo.new(code: "missing_key", message: "No #{BRAND_NAME} agent key (api_key / ORDAINER_KEY)."))
|
|
109
133
|
elsif !tool.is_a?(String) || tool.empty?
|
|
110
134
|
rejected(base, ErrorInfo.new(code: "invalid_request", message: "tool is required."))
|
|
111
135
|
else
|
|
@@ -149,6 +173,19 @@ module Ordainer
|
|
|
149
173
|
yield decision
|
|
150
174
|
end
|
|
151
175
|
|
|
176
|
+
# Closes the idle connections this client keeps open for reuse. Optional: the client is still usable afterwards
|
|
177
|
+
# (the next decide opens a new connection), and a call running right now finishes normally. Call it at shutdown.
|
|
178
|
+
def close
|
|
179
|
+
conns = @pool_lock.synchronize do
|
|
180
|
+
@generation += 1
|
|
181
|
+
idle = @idle
|
|
182
|
+
@idle = []
|
|
183
|
+
idle
|
|
184
|
+
end
|
|
185
|
+
conns.each { |http, pid, _| finish_connection(http) if pid == Process.pid }
|
|
186
|
+
nil
|
|
187
|
+
end
|
|
188
|
+
|
|
152
189
|
def inspect = "#<Ordainer::Client base_url=#{@base_url} fail_mode=#{@fail_mode}>" # never shows the key
|
|
153
190
|
|
|
154
191
|
private
|
|
@@ -241,20 +278,118 @@ module Ordainer
|
|
|
241
278
|
replayed: res["idempotent-replayed"] == "true"), false]
|
|
242
279
|
end
|
|
243
280
|
|
|
281
|
+
# One POST /v1/decide on a reused keep-alive connection. The total time stays what it was with one connection per
|
|
282
|
+
# call: socket timeouts of `timeout` each, and a hard cap of 2 x timeout over everything below, including the one
|
|
283
|
+
# resend after a stale connection.
|
|
244
284
|
def post(key, payload, timeout)
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
285
|
+
::Timeout.timeout(timeout * 2) do
|
|
286
|
+
resent = false
|
|
287
|
+
loop do
|
|
288
|
+
http, reused, generation = checkout(timeout, fresh: resent)
|
|
289
|
+
done = false
|
|
290
|
+
begin
|
|
291
|
+
http.start unless http.started?
|
|
292
|
+
res = http.request(build_request(key, payload))
|
|
293
|
+
# net/http (ignore_eof defaults to true; not settable before Ruby 3.1) returns a short body without raising.
|
|
294
|
+
clen = Integer(res["content-length"], exception: false)
|
|
295
|
+
raise EOFError, "response body shorter than Content-Length" if clen && res.body.to_s.bytesize < clen
|
|
296
|
+
done = true
|
|
297
|
+
checkin(http, generation, res)
|
|
298
|
+
return res
|
|
299
|
+
rescue *STALE_CONNECTION_ERRORS
|
|
300
|
+
# The server closed a connection we had left idle. Nothing proves the first copy was not processed, so the
|
|
301
|
+
# resend carries the same idempotency key (the API replays it, never counts it twice). Once per call, and
|
|
302
|
+
# never after a fresh connection failed.
|
|
303
|
+
raise if resent || !reused
|
|
304
|
+
|
|
305
|
+
resent = true
|
|
306
|
+
ensure
|
|
307
|
+
discard(http) unless done # timeout, reset, any error: never put a half-used connection back
|
|
308
|
+
end
|
|
309
|
+
end
|
|
310
|
+
end
|
|
311
|
+
end
|
|
312
|
+
|
|
313
|
+
def build_request(key, payload)
|
|
252
314
|
req = Net::HTTP::Post.new(@uri)
|
|
253
315
|
req["Authorization"] = "Bearer #{key}"
|
|
254
316
|
req["Content-Type"] = "application/json"
|
|
317
|
+
req["Connection"] = "keep-alive"
|
|
255
318
|
req["User-Agent"] = "ordainer-ruby/#{VERSION}"
|
|
256
319
|
req.body = payload
|
|
257
|
-
|
|
320
|
+
req
|
|
321
|
+
end
|
|
322
|
+
|
|
323
|
+
# An idle connection of this process (most recently used first), or a new unopened one. Never shared between
|
|
324
|
+
# threads: a connection belongs to one call from checkout to checkin, so no lock is held during network I/O.
|
|
325
|
+
# Connections inherited across fork are dropped without closing them (closing would shut the socket the parent
|
|
326
|
+
# is still using).
|
|
327
|
+
def checkout(timeout, fresh: false)
|
|
328
|
+
pid = Process.pid
|
|
329
|
+
http, generation = @pool_lock.synchronize do
|
|
330
|
+
@idle.reject! { |_, conn_pid, _| conn_pid != pid }
|
|
331
|
+
entry = fresh ? nil : @idle.pop
|
|
332
|
+
[entry && entry[0], @generation]
|
|
333
|
+
end
|
|
334
|
+
http = nil if http && unsolicited_bytes?(http)
|
|
335
|
+
reused = !http.nil?
|
|
336
|
+
http ||= new_connection
|
|
337
|
+
http.open_timeout = timeout
|
|
338
|
+
http.read_timeout = timeout
|
|
339
|
+
http.write_timeout = timeout
|
|
340
|
+
http.ssl_timeout = timeout if http.use_ssl?
|
|
341
|
+
[http, reused, generation]
|
|
342
|
+
end
|
|
343
|
+
|
|
344
|
+
# Anything readable on an idle connection (a stray or late response, a 408, a TLS alert) is not the answer to our
|
|
345
|
+
# next request: drop the connection instead of reading it as one.
|
|
346
|
+
# SSLSocket#pending covers a decoded TLS record still in OpenSSL; IO.select covers bytes in the kernel; @rbuf is
|
|
347
|
+
# net/http's private read-ahead buffer (bytes already pulled off the socket after the last response).
|
|
348
|
+
def unsolicited_bytes?(http)
|
|
349
|
+
sock = http.instance_variable_get(:@socket)
|
|
350
|
+
io = sock&.io
|
|
351
|
+
return false unless io
|
|
352
|
+
|
|
353
|
+
raw = io.respond_to?(:to_io) ? io.to_io : io
|
|
354
|
+
pending_tls = io.respond_to?(:pending) && io.pending.to_i.positive?
|
|
355
|
+
already_read = sock.instance_variable_get(:@rbuf).to_s.bytesize.positive?
|
|
356
|
+
readable = raw && IO.select([raw], nil, nil, 0)
|
|
357
|
+
bad = pending_tls || already_read || !readable.nil?
|
|
358
|
+
finish_connection(http) if bad
|
|
359
|
+
bad
|
|
360
|
+
rescue StandardError
|
|
361
|
+
finish_connection(http)
|
|
362
|
+
true
|
|
363
|
+
end
|
|
364
|
+
|
|
365
|
+
def new_connection
|
|
366
|
+
http = Net::HTTP.new(@uri.host, @uri.port)
|
|
367
|
+
http.use_ssl = @uri.scheme == "https"
|
|
368
|
+
http.keep_alive_timeout = KEEP_ALIVE_TIMEOUT
|
|
369
|
+
http.max_retries = 0 # retries are ours (same idempotency key, budgeted)
|
|
370
|
+
http
|
|
371
|
+
end
|
|
372
|
+
|
|
373
|
+
# Back to the pool unless the server said it is closing, the client was closed meanwhile, or the pool is full.
|
|
374
|
+
def checkin(http, generation, res)
|
|
375
|
+
keep = !res["connection"].to_s.casecmp?("close")
|
|
376
|
+
surplus = nil
|
|
377
|
+
@pool_lock.synchronize do
|
|
378
|
+
if keep && generation == @generation && @idle.size < MAX_IDLE_CONNECTIONS
|
|
379
|
+
@idle.push([http, Process.pid, generation])
|
|
380
|
+
else
|
|
381
|
+
surplus = http
|
|
382
|
+
end
|
|
383
|
+
end
|
|
384
|
+
finish_connection(surplus) if surplus
|
|
385
|
+
end
|
|
386
|
+
|
|
387
|
+
def discard(http) = finish_connection(http)
|
|
388
|
+
|
|
389
|
+
def finish_connection(http)
|
|
390
|
+
http.finish if http.started?
|
|
391
|
+
rescue StandardError
|
|
392
|
+
nil
|
|
258
393
|
end
|
|
259
394
|
|
|
260
395
|
def rejected(base, err)
|
|
@@ -2,13 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
module Ordainer
|
|
4
4
|
# Global settings for Ordainer.client and the Rails guard:
|
|
5
|
-
# Ordainer.configure { |c| c.api_key = ENV["
|
|
5
|
+
# Ordainer.configure { |c| c.api_key = ENV["ORDAINER_KEY"]; c.fail_mode = :open }
|
|
6
6
|
class Configuration
|
|
7
7
|
attr_accessor :api_key, :base_url, :timeout, :fail_mode, :retries, :retry_budget, :mode,
|
|
8
8
|
:billing_lapse, :deny_status, :sticky_deny, :logger, :on_decision
|
|
9
9
|
|
|
10
10
|
def initialize
|
|
11
|
-
|
|
11
|
+
# ORDAINER_KEY is primary. ORDAINER_API_KEY is the fallback when ORDAINER_KEY is unset.
|
|
12
|
+
# If both are set, ORDAINER_KEY wins. An empty string is unset, same as Python's `or`.
|
|
13
|
+
# Whitespace is kept; Python does not strip it.
|
|
14
|
+
env_key = ENV["ORDAINER_KEY"]
|
|
15
|
+
@api_key = env_key.to_s.empty? ? ENV["ORDAINER_API_KEY"] : env_key
|
|
12
16
|
@base_url = nil
|
|
13
17
|
end
|
|
14
18
|
|
|
@@ -24,7 +28,7 @@ module Ordainer
|
|
|
24
28
|
|
|
25
29
|
def configure
|
|
26
30
|
yield configuration
|
|
27
|
-
|
|
31
|
+
close_shared_client
|
|
28
32
|
configuration
|
|
29
33
|
end
|
|
30
34
|
|
|
@@ -32,8 +36,16 @@ module Ordainer
|
|
|
32
36
|
def client = (@client ||= Client.new(**configuration.to_client_options))
|
|
33
37
|
|
|
34
38
|
def reset!
|
|
39
|
+
close_shared_client
|
|
35
40
|
@configuration = nil
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
private
|
|
44
|
+
|
|
45
|
+
def close_shared_client
|
|
46
|
+
old = @client
|
|
36
47
|
@client = nil
|
|
48
|
+
old&.close
|
|
37
49
|
end
|
|
38
50
|
end
|
|
39
51
|
end
|
|
@@ -74,9 +74,9 @@ module Ordainer
|
|
|
74
74
|
if d.reason == "quota_exceeded"
|
|
75
75
|
return resp(d.deny_status || 429, retry_after_header(d.resets_at, now).merge(rid),
|
|
76
76
|
code: "plan_limit_reached",
|
|
77
|
-
message: "This
|
|
77
|
+
message: "This call wasn't run because the usage limit was reached (#{d.remaining || 0} of #{d.limit || "?"} left)." +
|
|
78
78
|
(d.resets_at ? " It resets at #{d.resets_at}." : "") +
|
|
79
|
-
" Retrying before then
|
|
79
|
+
" Retrying before then won't work.",
|
|
80
80
|
request_id: d.request_id, reason: d.reason, remaining: d.remaining, limit: d.limit, resets_at: d.resets_at)
|
|
81
81
|
end
|
|
82
82
|
# Same as Node: the reason in brackets at the end, only when it looks like an API code.
|
|
@@ -159,7 +159,7 @@ module Ordainer
|
|
|
159
159
|
def plan_denied_message(reason, tool = nil)
|
|
160
160
|
if reason == "tool_not_in_plan"
|
|
161
161
|
what = showable_tool?(tool) ? "\"#{tool}\"" : "this action"
|
|
162
|
-
return "This call wasn't run because
|
|
162
|
+
return "This call wasn't run because #{what} isn't included in your current access. If you need it, contact the provider of this service. (tool_not_in_plan)"
|
|
163
163
|
end
|
|
164
164
|
msg = "This call wasn't run because it isn't allowed on your account right now. If you need it, contact the service's team."
|
|
165
165
|
reason.is_a?(String) && reason.valid_encoding? && reason.match?(API_CODE_SHAPE) ? "#{msg} (#{reason})" : msg
|
|
@@ -175,7 +175,10 @@ module Ordainer
|
|
|
175
175
|
|
|
176
176
|
# QA P95F-N4: a huge fraction can make the difference NaN/Infinity; no header then, never a FloatDomainError.
|
|
177
177
|
secs = (t - now).to_f
|
|
178
|
-
|
|
178
|
+
return {} unless secs.finite?
|
|
179
|
+
|
|
180
|
+
# Cap at one hour. The JSON body still sends the original resets_at.
|
|
181
|
+
{ "Retry-After" => [3600, [1, secs.ceil].max].min.to_s }
|
|
179
182
|
end
|
|
180
183
|
private_class_method :resp, :retry_after_header
|
|
181
184
|
end
|
data/lib/ordainer/rails.rb
CHANGED
data/lib/ordainer/version.rb
CHANGED
data/lib/ordainer.rb
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
# ordainer: call Ordainer's POST /v1/decide before your tool runs. Ruby >= 3.0, stdlib only.
|
|
4
4
|
#
|
|
5
|
-
# client = Ordainer::Client.new(api_key: ENV["
|
|
5
|
+
# client = Ordainer::Client.new(api_key: ENV["ORDAINER_KEY"])
|
|
6
6
|
# decision = client.decide(tool: "research.run")
|
|
7
7
|
# return render_blocked(decision) unless decision.allowed?
|
|
8
8
|
#
|
metadata
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: ordainer
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.1.
|
|
4
|
+
version: 0.1.3
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Ordainer
|
|
8
8
|
bindir: bin
|
|
9
9
|
cert_chain: []
|
|
10
|
-
date:
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
11
|
dependencies: []
|
|
12
12
|
executables: []
|
|
13
13
|
extensions: []
|