ordainer 0.1.0 → 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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6f012928c3aedf7e8eafb2b5f2fd6fcec671f467e4a44d6214bc55c3adf49ee1
4
- data.tar.gz: b748a4a31fa42620dc1fa045182147001f526fa789571ec9a1f2c112be85d416
3
+ metadata.gz: c334caafef590bf890323811b0991f030976be205644efeaf24c191550024cdb
4
+ data.tar.gz: 2da2ee9ff7936324cbf724fed6f2dc34a4e889488db5ebff0132a77126985ea7
5
5
  SHA512:
6
- metadata.gz: 7c4e07d10dfb6911bddc8cba631b5ec33cc52499a9dfd8e83dfd75ce5424870a04fa8f1b69c87e73f66a4a719f44e8e14eb0fe4ee7b2c29cebdbda029ef044b0
7
- data.tar.gz: 5fd5691ec62d7f837706fc46c6e4024cad416fa647dbac76357d74200446c1c077a58af50489752f8b6d8a4ced135bef3f88254ee3803082d50ba7ee9bc2fdf3
6
+ metadata.gz: 2dbcc6bd69d64046f5a37e178bbb6fb63ad5531fce367e3ffc5253dd02c1d5ced8f1ea0116cf96fd1486337c4685d7d7ade0e05930b427fea242f8da36c126e4
7
+ data.tar.gz: e46fd038be053292a6ab5a202a76ab2264cbec590ee8291ee440e425cead4f85ba59d631d33c32882468c727fed025b0fe9da9cc98cb147d9e00ba555fb74404
data/CHANGELOG.md CHANGED
@@ -1,4 +1,56 @@
1
1
  # Changelog
2
2
 
3
- ## 0.1.0 (unreleased)
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
+
19
+ ## 0.1.1 (2026-10-18)
20
+ - Fixed (QA P95F-N4): `Ordainer.deny_response` no longer raises `FloatDomainError` when the server's `resets_at` parses but
21
+ gives a non-finite number of seconds (for example a fraction hundreds of digits long); there is no `Retry-After` header
22
+ then, as for an unknown reset time. Status, code and body are unchanged.
23
+ - Changed (PM final wording, Oct 18; replaces the P95R-N3 text below): Error messages reworded; codes, statuses and fields unchanged. Match on error.code, not the message. Same bytes as the Node SDK. `503 ordainer_unavailable`: "This call wasn't run. The service couldn't finish a safety check it does before each call, so it stopped instead of going ahead without it. Nothing is wrong on your side. Please try again in a minute. (ordainer_unavailable)".
24
+ `429 test_limit_reached`: "This call wasn't run. This service's test calls for the month are used up. They reset on
25
+ November 1 (UTC). Nothing is wrong on your side, and trying again won't help until they reset. If you need it sooner, contact
26
+ the service's team. (test_limit_reached)". The reset day is `resets_at` in UTC as "<Month D>" (full English month, no
27
+ leading zero, no year; no locale APIs), and the sentence appears only when `resets_at` is a valid ISO-8601 date-time
28
+ String (`YYYY-MM-DDTHH:MM:SS`, optional fraction, `Z` or `±HH:MM`); nil, empty, numbers, garbage or trailing text leave
29
+ it out (closes P95R-N4 for this message; `plan_limit_reached` is unchanged). `403 plan_denied` with `tool_not_in_plan`:
30
+ "This call wasn't run because your plan doesn't include "<tool>". If you need it, ask whoever manages your plan.
31
+ (tool_not_in_plan)", where `<tool>` is the tool passed to `decide` / `decide!` / the Rails guard (no extra request),
32
+ quoted 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" without quotes. Any other
33
+ plan deny: "This call wasn't run because it isn't allowed on your account right now. If you need it, contact the
34
+ service's team. (<reason>)", with the bracket only when the reason matches `\A[a-z][a-z_]{0,39}\z`. Status, `code`,
35
+ `reason`, `resets_at`, `request_id`, headers and whether the call runs are unchanged.
36
+ - Changed (P95R-N3, Content & DevRel Addendum 3, same bytes as the Node SDK): three more caller messages drop our name
37
+ and our terms. `503 ordainer_unavailable`: "This call wasn't run. The service couldn't complete a check it needs before
38
+ running it, and it's set to stop rather than go ahead without one. Please try again in a moment. (ordainer_unavailable)".
39
+ `429 test_limit_reached`: "This call wasn't run. The service's test allowance for this month is used up. It resets at
40
+ {resets_at}. It isn't something you did, and retrying won't help until the allowance resets. (test_limit_reached)" (no
41
+ "It resets at" sentence when `resets_at` is nil or empty; an empty value used to render "They reset at ."). `403
42
+ plan_denied`: "This call wasn't run because this agent's plan doesn't allow it. ({reason})", with the bracketed reason
43
+ only when it matches `\A[a-z][a-z_]{0,39}\z` (the same check as the `plan_check_rejected` message); otherwise it ends at
44
+ "allow it.". Before, the Ruby 403 message never named the reason. Only `message` (and the raised errors' `message`)
45
+ changes: status, `code` (still `ordainer_unavailable`), `reason`, `resets_at`, `request_id`, headers and whether the call
46
+ runs are unchanged.
47
+ - Changed (T18-P40, same strings as the Node SDK): the caller's `500 plan_check_rejected` message says what kind of setup
48
+ issue it is (a key isn't recognized, has been turned off, or is missing; anything else) and ends with the API's code for
49
+ the service's team. The `429 rate_limited` message no longer names us: "The service is getting too many requests on this
50
+ key right now, so this call was held back. Please wait a moment and try again. (rate_limited)". A `429 concurrency_limited`
51
+ now gets its own: "The service is handling too many calls on this key at once, so this call was held back. Please wait a moment and try again. (concurrency_limited)" (the `code` field stays `rate_limited`). Only `message` changes:
52
+ status, `code`, headers (`Retry-After`, `X-Request-Id`), `retry_after`, `rejected?` / `rate_limited?` and whether the call
53
+ runs are unchanged. The 403 billing message is unchanged.
54
+
55
+ ## 0.1.0 (2026-10-14)
4
56
  - First version: Ordainer::Client#decide, Decision, typed errors, retries, fail_mode, optional Rails guard.
data/README.md CHANGED
@@ -4,12 +4,22 @@ Ask Ordainer before your tool runs: one `decide` call checks the caller's plan a
4
4
  Ruby 3.0+, standard library only (net/http, json), no runtime dependencies. Mirrors the Node SDK
5
5
  (`packages/ordainer-node`, 1.2.2).
6
6
 
7
- > 0.1.0, not on RubyGems yet. Install from the repo (see the Ruby quickstart in the docs).
7
+ Install from [RubyGems](https://rubygems.org/gems/ordainer):
8
+
9
+ ```sh
10
+ gem install ordainer
11
+ ```
12
+
13
+ or in your Gemfile:
14
+
15
+ ```ruby
16
+ gem "ordainer", "~> 0.1"
17
+ ```
8
18
 
9
19
  ```ruby
10
20
  require "ordainer"
11
21
 
12
- client = Ordainer::Client.new(api_key: ENV["ORDAINER_API_KEY"]) # ord_test_... or ord_live_...
22
+ client = Ordainer::Client.new(api_key: ENV["ORDAINER_KEY"]) # ord_test_...
13
23
  decision = client.decide(tool: "research.run")
14
24
 
15
25
  if decision.allowed?
@@ -23,7 +33,7 @@ end
23
33
 
24
34
  | Option | Default | Meaning |
25
35
  | --- | --- | --- |
26
- | `api_key:` | `ENV["ORDAINER_API_KEY"]`, then `ENV["ORDAINER_KEY"]` | Agent key. Override per call: `decide(tool:, api_key:)`. |
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:)`. |
27
37
  | `base_url:` | `ENV["ORDAINER_BASE_URL"]` or `https://api.ordainer.dev` | |
28
38
  | `timeout:` | `0.3` | Seconds per attempt. |
29
39
  | `fail_mode:` | `:open` | `:open` lets the call run when Ordainer can't answer; `:closed` blocks it. |
@@ -36,6 +46,33 @@ end
36
46
  | `logger:` | warn to `$stderr` | A `Logger`, or `false`. |
37
47
  | `on_decision:` | `nil` | Called with every `Decision`. |
38
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
+
39
76
  ## Rules (same as the Node SDK)
40
77
 
41
78
  - `decide` never raises for an Ordainer answer or an outage. A deny is a normal result. Bad options raise
@@ -47,6 +84,30 @@ end
47
84
  `fail_mode` (`rejected?`). 403 `subscription_inactive` follows `billing_lapse` instead. 429
48
85
  `safety_limit_reached` lets the call run (`safety_limited`).
49
86
  - Only timeouts, network errors and 503 are retried, never other 5xx or 4xx.
87
+ - What the caller reads (`Ordainer.deny_response`, same text as the Node SDK): a block a retry can't fix answers
88
+ `500 plan_check_rejected` with plain words for the cause and the API's code last, e.g. "This call wasn't run. This is a
89
+ setup issue on the service's side: one of its keys isn't recognized. It isn't something you did, and retrying won't help
90
+ until the service fixes the key. (For the service's team: unknown_key.)" A `429 rate_limited` answers "The service is
91
+ getting too many requests on this key right now, so this call was held back. Please wait a moment and try again.
92
+ (rate_limited)" with `Retry-After`; a `429 concurrency_limited` answers "The service is handling too many calls on this key at once, so this call was held back. Please wait a moment and try again. (concurrency_limited)" (the `code` field
93
+ stays `rate_limited`). Billing blocks (403) keep the Legal-approved text.
94
+ - The same text as the Node SDK for the other blocks too (PM final wording, Oct 18). Error messages can be reworded;
95
+ codes, statuses and fields stay the same, so match on `code`, not the message. An outage under `fail_mode: :closed`
96
+ answers `503 ordainer_unavailable` with `Retry-After: 5`: "This call wasn't run. The service couldn't finish a safety check it does before each call, so it stopped instead of going ahead without it. Nothing is wrong on your side. Please try again in a minute. (ordainer_unavailable)".
97
+ A used-up test allowance answers `429 test_limit_reached`: "This call wasn't run. This service's test calls for the
98
+ month are used up. They reset on November 1 (UTC). Nothing is wrong on your side, and trying again won't help until
99
+ they reset. If you need it sooner, contact the service's team. (test_limit_reached)" (the day is `resets_at` in UTC as
100
+ "<Month D>"; no "They reset on" sentence unless `resets_at` is a valid ISO-8601 date-time). A `tool_not_in_plan` deny
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
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
103
+ call wasn't run because it isn't allowed on your account right now. If you need it, contact the service's team.
104
+ (reason)", with the reason in brackets only when it looks like an API code (lowercase letters and `_`, up to 40
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.
50
111
 
51
112
  ## Decision
52
113
 
@@ -60,7 +121,7 @@ end
60
121
  ```ruby
61
122
  # config/initializers/ordainer.rb
62
123
  Ordainer.configure do |c|
63
- c.api_key = ENV["ORDAINER_API_KEY"]
124
+ c.api_key = ENV["ORDAINER_KEY"]
64
125
  end
65
126
 
66
127
  class ResearchController < ApplicationController
@@ -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["ORDAINER_API_KEY"] or ENV["ORDAINER_KEY"].
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
- @api_key = api_key || ENV["ORDAINER_API_KEY"] || ENV["ORDAINER_KEY"]
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 / ORDAINER_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
- http = Net::HTTP.new(@uri.host, @uri.port)
246
- http.use_ssl = @uri.scheme == "https"
247
- http.open_timeout = timeout
248
- http.read_timeout = timeout
249
- http.write_timeout = timeout
250
- http.ssl_timeout = timeout if http.use_ssl?
251
- http.max_retries = 0 # retries are ours (same idempotency key, budgeted)
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
- ::Timeout.timeout(timeout * 2) { http.request(req) } # hard cap on top of the socket timeouts
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["ORDAINER_API_KEY"]; c.fail_mode = :open }
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
- @api_key = ENV["ORDAINER_API_KEY"] || ENV["ORDAINER_KEY"]
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
- @client = nil
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
@@ -9,6 +9,34 @@ module Ordainer
9
9
  TEST_LIMIT_REASON = "test_limit_reached"
10
10
  # Legal-approved (Oct 3; tech/billing-lapse-scope.md item 2), verbatim, same as the Node SDK.
11
11
  BILLING_BLOCKED_MESSAGE = "This action isn't available right now. This is a setup issue on the service's side; retrying won't help."
12
+ # Caller-facing text for a 429 rate_limited / concurrency_limited block, same as the Node SDK (Content & DevRel, Oct 18):
13
+ # no product name. Only the message differs; the code field stays rate_limited for both, and status, Retry-After and
14
+ # retry_after are unchanged.
15
+ RATE_LIMITED_MESSAGE = "The service is getting too many requests on this key right now, so this call was held back. Please wait a moment and try again. (rate_limited)"
16
+ CONCURRENCY_LIMITED_MESSAGE = "The service is handling too many calls on this key at once, so this call was held back. Please wait a moment and try again. (concurrency_limited)"
17
+ # T18-P40 (Content & DevRel final wording, Oct 18; same strings as the Node SDK's rejectedMessage()): the caller-facing
18
+ # sentence for a block a retry can't fix (500 plan_check_rejected). Plain words first, the API's own code last for the
19
+ # service's team; the code is echoed only if it looks like an API code (lowercase letters and _, <= 40 chars).
20
+ # too_many_failed_auth stays with "isn't recognized": the API's "couldn't check this key" variant has the same status,
21
+ # code, limit_scope and headers; only its English message differs.
22
+ KEY_NOT_RECOGNIZED_CODES = %w[unknown_key old_key_format too_many_failed_auth].freeze
23
+ REJECTED_TAIL = "It isn't something you did, and retrying won't help until the service"
24
+ # P95R-N3 (Content & DevRel, Oct 18, content/persona-2-2026-10-18/p40-sdk-key-messages.md Addendum 3; same bytes as
25
+ # the Node SDK): the 503 fail-closed outage, the 429 test allowance and the 403 plan deny. No product name and none of
26
+ # our terms. Only the message changes: status, code (ordainer_unavailable is kept), headers and fields are unchanged.
27
+ # Text replaced by the PM's final wording (Oct 18); codes and fields are as before.
28
+ UNAVAILABLE_MESSAGE = "This call wasn't run. The service couldn't finish a safety check it does before each call, so it stopped instead of going ahead without it. Nothing is wrong on your side. Please try again in a minute. (#{UNAVAILABLE_CODE})"
29
+ API_CODE_SHAPE = /\A[a-z][a-z_]{0,39}\z/
30
+ # PM final wording (Oct 18): tool_not_in_plan names the tool sent in decide(), in double quotes, only when it looks
31
+ # like a plain tool name; otherwise "this action". Same check and bytes as the Node SDK's TOOL_NAME_SHAPE.
32
+ TOOL_NAME_SHAPE = /\A[A-Za-z0-9][A-Za-z0-9_.:\/-]{0,63}\z/
33
+ # QA P95F-N3: nothing URL-like is echoed either: no "//" anywhere and no leading "scheme:" (RFC 3986 shape). Same as Node.
34
+ TOOL_SCHEME_PREFIX = /\A[A-Za-z][A-Za-z0-9+.-]*:/
35
+ # Addendum 3 amendment (Oct 18, CoS): the reset day as "<Month D>" in UTC (full English month, no leading zero, no
36
+ # year). Only for a String that is a valid ISO-8601 date-time (YYYY-MM-DDTHH:MM:SS, optional .fraction, then Z or
37
+ # +HH:MM/-HH:MM). Fixed month list and integer UTC math only (no Time.parse, no locale), same bytes as Node.
38
+ MONTHS = %w[January February March April May June July August September October November December].freeze
39
+ ISO_DATE_TIME = /\A(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|([+-])(\d{2}):(\d{2}))\z/
12
40
 
13
41
  module_function
14
42
 
@@ -21,52 +49,136 @@ module Ordainer
21
49
  retry_after = (d.retry_after_sec || 1).to_s
22
50
  return resp(429, { "Retry-After" => retry_after }.merge(rid),
23
51
  code: "rate_limited",
24
- message: "Too many plan checks for this agent right now (#{BRAND_NAME}'s per-key rate limit). Retry after #{retry_after}s. This call was not run.",
52
+ message: d.reason == "concurrency_limited" ? CONCURRENCY_LIMITED_MESSAGE : RATE_LIMITED_MESSAGE,
25
53
  request_id: d.request_id, retry_after: retry_after.to_i)
26
54
  end
27
55
  if d.rejected || (d.fail_closed && d.billing_inactive)
28
56
  billing = d.billing_inactive
29
57
  return resp(billing ? 403 : 500, rid,
30
58
  code: REJECTED_CODE,
31
- message: billing ? BILLING_BLOCKED_MESSAGE : "The plan check refused this call because of a setup problem on the service's side, so it was not run. This is not an outage: retrying will not help until whoever runs the service fixes its setup.",
59
+ message: billing ? BILLING_BLOCKED_MESSAGE : rejected_message(d.error&.code),
32
60
  request_id: d.request_id)
33
61
  end
34
62
  if d.fail_closed
35
63
  return resp(503, { "Retry-After" => "5" }.merge(rid),
36
64
  code: UNAVAILABLE_CODE,
37
- message: "The plan check is unavailable, so this call was not run. Try again shortly.",
65
+ message: UNAVAILABLE_MESSAGE,
38
66
  request_id: d.request_id)
39
67
  end
40
68
  if d.reason == TEST_LIMIT_REASON
41
69
  return resp(429, retry_after_header(d.resets_at, now).merge(rid),
42
70
  code: TEST_LIMIT_REASON,
43
- message: "This #{BRAND_NAME} sandbox account has used its free test-key decisions for this month." +
44
- (d.resets_at ? " They reset at #{d.resets_at}." : "") +
45
- " This is a sandbox limit on test keys, not a plan limit and not an outage. Live keys are not affected. This call was not run.",
71
+ message: test_limit_message(d.resets_at),
46
72
  request_id: d.request_id, reason: d.reason, resets_at: d.resets_at)
47
73
  end
48
74
  if d.reason == "quota_exceeded"
49
75
  return resp(d.deny_status || 429, retry_after_header(d.resets_at, now).merge(rid),
50
76
  code: "plan_limit_reached",
51
- message: "This agent's plan limit is reached (#{d.remaining || 0} of #{d.limit || "?"} left)." +
77
+ message: "This call wasn't run because the usage limit was reached (#{d.remaining || 0} of #{d.limit || "?"} left)." +
52
78
  (d.resets_at ? " It resets at #{d.resets_at}." : "") +
53
- " Retrying before then will not succeed. This call was not run.",
79
+ " Retrying before then won't work.",
54
80
  request_id: d.request_id, reason: d.reason, remaining: d.remaining, limit: d.limit, resets_at: d.resets_at)
55
81
  end
56
- # Node says "(<reason>)" in the message; here the reason is only a field (no raw codes in the message).
82
+ # Same as Node: the reason in brackets at the end, only when it looks like an API code.
57
83
  resp(403, rid,
58
84
  code: "plan_denied",
59
- message: "This agent's plan does not allow this call, so it was not run.",
85
+ message: plan_denied_message(d.reason, d.tool),
60
86
  request_id: d.request_id, reason: d.reason)
61
87
  end
62
88
 
89
+ def rejected_message(code)
90
+ msg =
91
+ if code == "missing_key"
92
+ "This call wasn't run. This is a setup issue on the service's side: a key it needs is missing. #{REJECTED_TAIL} adds the key."
93
+ elsif code == "revoked_key"
94
+ "This call wasn't run. This is a setup issue on the service's side: one of its keys has been turned off. #{REJECTED_TAIL} switches to a new key."
95
+ elsif KEY_NOT_RECOGNIZED_CODES.include?(code)
96
+ "This call wasn't run. This is a setup issue on the service's side: one of its keys isn't recognized. #{REJECTED_TAIL} fixes the key."
97
+ else
98
+ "This call wasn't run because of a setup issue on the service's side. #{REJECTED_TAIL} fixes it."
99
+ end
100
+ code.is_a?(String) && code.match?(API_CODE_SHAPE) ? "#{msg} (For the service's team: #{code}.)" : msg
101
+ end
102
+
103
+ # Same rules as Node's resetDayUtc(): nil for anything that isn't a valid ISO-8601 date-time String.
104
+ def reset_day_utc(v)
105
+ return nil unless v.is_a?(String) && v.valid_encoding?
106
+
107
+ m = ISO_DATE_TIME.match(v)
108
+ return nil unless m
109
+
110
+ y, mo, d, h, mi, s = m.captures[0, 6].map(&:to_i)
111
+ leap = (y % 4).zero? && !(y % 100).zero? || (y % 400).zero?
112
+ dim = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
113
+ return nil if mo < 1 || mo > 12 || d < 1 || d > dim[mo - 1] || h > 23 || mi > 59 || s > 59
114
+
115
+ off = 0
116
+ if m[7]
117
+ oh = m[8].to_i
118
+ om = m[9].to_i
119
+ return nil if oh > 23 || om > 59
120
+
121
+ off = (m[7] == "-" ? -1 : 1) * (oh * 60 + om)
122
+ end
123
+ # Minutes from local midnight, shifted to UTC; at most one day either way.
124
+ mins = h * 60 + mi - off
125
+ uy, um, ud = y, mo, d
126
+ if mins.negative?
127
+ ud -= 1
128
+ if ud < 1
129
+ um -= 1
130
+ if um < 1
131
+ um = 12
132
+ uy -= 1
133
+ end
134
+ ud = dim[um - 1] # February only from March 1 (same year)
135
+ end
136
+ elsif mins >= 1440
137
+ ud += 1
138
+ if ud > dim[mo - 1]
139
+ ud = 1
140
+ um += 1
141
+ um = 1 if um > 12
142
+ end
143
+ end
144
+ "#{MONTHS[um - 1]} #{ud}"
145
+ end
146
+
147
+ def test_limit_message(resets_at)
148
+ day = reset_day_utc(resets_at)
149
+ "This call wasn't run. This service's test calls for the month are used up." +
150
+ (day ? " They reset on #{day} (UTC)." : "") +
151
+ " Nothing is wrong on your side, and trying again won't help until they reset. If you need it sooner, contact the service's team. (test_limit_reached)"
152
+ end
153
+
154
+ def showable_tool?(tool)
155
+ tool.is_a?(String) && tool.valid_encoding? && tool.match?(TOOL_NAME_SHAPE) && !tool.include?("//") &&
156
+ !tool.match?(TOOL_SCHEME_PREFIX)
157
+ end
158
+
159
+ def plan_denied_message(reason, tool = nil)
160
+ if reason == "tool_not_in_plan"
161
+ what = showable_tool?(tool) ? "\"#{tool}\"" : "this action"
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
+ end
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
+ reason.is_a?(String) && reason.valid_encoding? && reason.match?(API_CODE_SHAPE) ? "#{msg} (#{reason})" : msg
166
+ end
167
+
63
168
  def resp(status, headers, **error)
64
169
  { status: status, headers: headers, body: { error: error } }
65
170
  end
66
171
 
67
172
  def retry_after_header(resets_at, now)
68
173
  t = Time.iso8601(resets_at.to_s) rescue nil
69
- t ? { "Retry-After" => [1, (t - now).ceil].max.to_s } : {}
174
+ return {} unless t
175
+
176
+ # QA P95F-N4: a huge fraction can make the difference NaN/Infinity; no header then, never a FloatDomainError.
177
+ secs = (t - now).to_f
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 }
70
182
  end
71
183
  private_class_method :resp, :retry_after_header
72
184
  end
@@ -5,7 +5,7 @@
5
5
  #
6
6
  # # config/initializers/ordainer.rb
7
7
  # Ordainer.configure do |c|
8
- # c.api_key = ENV["ORDAINER_API_KEY"]
8
+ # c.api_key = ENV["ORDAINER_KEY"]
9
9
  # c.fail_mode = :open
10
10
  # end
11
11
  #
@@ -1,3 +1,3 @@
1
1
  module Ordainer
2
- VERSION = "0.1.0"
2
+ VERSION = "0.1.3"
3
3
  end
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["ORDAINER_API_KEY"])
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,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ordainer
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.1.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ordainer