ankusa-sdk 0.3.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 99e44d64d5de0bc0b009a85ef6108009f93c42c90a4b28d39c8d39426421d588
4
+ data.tar.gz: 5084fce56a8a86cc4e1259c1b96a25c2fb1fa599b42e21cbc0248e7f179bd0b8
5
+ SHA512:
6
+ metadata.gz: 25f553755bd7f33506aba3992f103c69a82e3e1fa11ffd81909f4a4e4df8fb5a649d0eaa658ec285dffac01dfb6f14b3d057257d8f55ec7b6d667c54b51856b6
7
+ data.tar.gz: bf270c6e0dcec34696106eaf96cb320004094126f8390e42ff84cd065d874c26b01fc653462aae47eb3960b4ab5a174f49d0e2bbae9fb7f339e4acf1f0956302
data/CHANGELOG.md ADDED
@@ -0,0 +1,41 @@
1
+ # Changelog
2
+
3
+ All notable changes to `ankusa-sdk` (the RubyGems gem) are documented here.
4
+ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/);
5
+ this project follows [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.3.0] - 2026-10-01
10
+
11
+ ### Added
12
+
13
+ - `Ankusa::ClaimCheckClient`: `redeem(ref, sha256)` parses a claim-check ref,
14
+ fetches its bytes from the gateway, and verifies them against the message's
15
+ sha256 before returning them; `health` for a liveness probe.
16
+ - `Ankusa::RoutesClient`: the route-management client
17
+ (`routes.admin.port`) — `health`, `list_routes`, `create_route`, `get_route`,
18
+ `replace_route`, `update_route`, `delete_route`, `get_ip_rules`,
19
+ `put_ip_rules`, `test_route`.
20
+ - `Ankusa::AdminClient`: the operator client (`admin.port`) — `health`,
21
+ `metrics`, `config`, `list_dead_letters`, `replay_dead_letters`,
22
+ `list_quarantined`.
23
+ - `Ankusa::SourcesClient`, a client for `Ankusa.Admin.Router`: the tenant-scoped
24
+ source API's `server_version`, `list_sources`, `get_source`, `create_source`,
25
+ `update_source`, and `delete_source`, with `Ankusa::SourceSpec` (the writable
26
+ spec, `to_request_body` omits unset fields) and `Ankusa::Source` (a stored,
27
+ redacted source).
28
+ - `Ankusa.parse_headers(headers)`, for receivers of Ankusa's HTTP sink: parses
29
+ `x-ankusa-id`/`x-ankusa-source`/`x-ankusa-tenant`/`content-type` into a
30
+ `HookHeaders` value, raising `MissingHookIdError` if `x-ankusa-id` is absent
31
+ or empty. `Ankusa.parse_claim_ref` is exported the same way.
32
+ - `Ankusa::Transport`, the injectable transport hook (`Transport::Request` in,
33
+ `Transport::Response` out) with the default `Transport::NetHTTP`: one
34
+ connection per request, no redirects, no retries.
35
+ - A `ClaimCheckError`/`RoutesError`/`AdminError`/`SourcesError` hierarchy under
36
+ `Ankusa::Error`, every class carrying a `retryable?` bit (except the sources
37
+ family, which carries `.status` and `.body` instead), so a consumer needs
38
+ exactly one bit to route a failure to dead-letter or retry.
39
+
40
+ [Unreleased]: https://github.com/jamescarr/ankusa/compare/sdk-ruby-v0.3.0...HEAD
41
+ [0.3.0]: https://github.com/jamescarr/ankusa/releases/tag/sdk-ruby-v0.3.0
data/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the
44
+ purposes of this License, Derivative Works shall not include works
45
+ that remain separable from, or merely link (or bind by name) to the
46
+ interfaces of, the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including the
49
+ original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing
141
+ the origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 The Ankusa Contributors
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,256 @@
1
+ # ankusa-sdk
2
+
3
+ The Ruby client SDK for [Ankusa](https://github.com/jamescarr/ankusa)
4
+ deployments: one gem meant to bundle everything a non-Elixir consumer needs to
5
+ talk to an Ankusa deployment. Today that's the
6
+ [claim-check gateway](https://github.com/jamescarr/ankusa/blob/main/docs/claim-check.md)
7
+ client, the route-management and operator (admin) clients, the
8
+ source-management client, and a webhook-receiving header helper; more clients
9
+ (ingest) land here as they're built.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ gem install ankusa-sdk
15
+ ```
16
+
17
+ or in a `Gemfile`:
18
+
19
+ ```ruby
20
+ gem "ankusa-sdk"
21
+ ```
22
+
23
+ then, in code:
24
+
25
+ ```ruby
26
+ require "ankusa/sdk"
27
+ ```
28
+
29
+ Before the first RubyGems release, depend on it as a path gem the same way the
30
+ Elixir packages in this monorepo depend on `ankusa` core before their first Hex
31
+ release:
32
+
33
+ ```ruby
34
+ gem "ankusa-sdk", path: "packages/sdk-ruby"
35
+ ```
36
+
37
+ Everything the SDK exposes lives under `Ankusa::`.
38
+
39
+ ## Claim-check client
40
+
41
+ Redeem a claim-check ref, verify the bytes it returns against the message's
42
+ `sha256`, and classify failures into dead-letter vs. retry, without holding any
43
+ object-store credentials. Conforms to the framework's own contract,
44
+ [`priv/openapi/claim_check.v1.yaml`](../ankusa/priv/openapi/claim_check.v1.yaml):
45
+ the spec is the source of truth, this package conforms to it, not the reverse.
46
+
47
+ ```ruby
48
+ require "ankusa/sdk"
49
+
50
+ CLAIM_CHECK = Ankusa::ClaimCheckClient.new(ENV.fetch("CLAIM_CHECK_URL", "http://localhost:4001"))
51
+
52
+ # A queue message that carries a claim also carries its sha256:
53
+ # "claim": "urn:ankusa:claim:v1:<tenant>:<claim_id>" (claim_id: uppercase ULID)
54
+ # "sha256": 64-char lowercase hex of the claim's bytes
55
+ def resolve_body(message)
56
+ CLAIM_CHECK.redeem(message["claim"], message["sha256"])
57
+ rescue Ankusa::ClaimCheckError => e
58
+ # bad ref/sha256, 404, or an integrity mismatch: dead-letter, don't requeue
59
+ raise unless e.retryable?
60
+
61
+ # gateway unreachable or 5xx: safe to retry
62
+ raise
63
+ end
64
+ ```
65
+
66
+ `redeem` does three things `GET /v1/claims/...` alone doesn't:
67
+
68
+ 1. Parses the ref into its tenant id, claim id, and gateway path
69
+ (`GET /v1/claims/{tenant_id}/{claim_id}`) (`Ankusa.parse_claim_ref`, also
70
+ exported standalone).
71
+ 2. Fetches the bytes.
72
+ 3. Verifies them against the message's `sha256` (the gateway itself does not
73
+ check this, see "Redeem a claim" in
74
+ [`docs/claim-check.md`](https://github.com/jamescarr/ankusa/blob/main/docs/claim-check.md))
75
+ before ever returning them to you.
76
+
77
+ Every failure is a `ClaimCheckError` subclass with a `retryable?` method, so a
78
+ consumer needs exactly one bit to decide dead-letter vs. retry:
79
+
80
+ | Class | `retryable?` | Cause |
81
+ | --- | --- | --- |
82
+ | `InvalidClaimRefError` | `false` | `ref` isn't a well-formed claim-check URN, or `sha256` isn't 64-char lowercase hex |
83
+ | `ClaimNotFoundError` | `false` | gateway `404`: expired by retention, or never written |
84
+ | `ClaimRejectedError` | `false` | gateway `4xx` other than `404` (`.status`, `.body`) |
85
+ | `ClaimIntegrityError` | `false` | sha256 of the returned bytes doesn't match |
86
+ | `ClaimCheckUnavailableError` | `true` | gateway `5xx`/`503`, or unreachable |
87
+
88
+ `health` hits `GET /health` for a liveness probe. There's no `close`: the
89
+ default transport opens one connection per request.
90
+
91
+ ## Webhook receiver helper
92
+
93
+ Every receiver of Ankusa's HTTP sink needs the same handful of headers off each
94
+ request; `Ankusa.parse_headers` replaces the hand-rolled
95
+ `env["HTTP_X_ANKUSA_ID"]` lookups with one call and a typed result. Names are
96
+ matched case-insensitively, so it takes anything from a lowercased header hash
97
+ to a Rack env mapped once:
98
+
99
+ ```ruby
100
+ require "ankusa/sdk"
101
+
102
+ # Rack carries these as HTTP_X_ANKUSA_* (content-type as CONTENT_TYPE):
103
+ # parse_headers downcases what it is given, but it does not strip Rack's
104
+ # HTTP_ prefix or its underscores.
105
+ def header_map(env)
106
+ headers = env.filter_map do |key, value|
107
+ [key.delete_prefix("HTTP_").tr("_", "-"), value] if key.start_with?("HTTP_")
108
+ end.to_h
109
+ headers["content-type"] = env["CONTENT_TYPE"] if env["CONTENT_TYPE"]
110
+ headers
111
+ end
112
+
113
+ def call(env)
114
+ hook =
115
+ begin
116
+ Ankusa.parse_headers(header_map(env))
117
+ rescue Ankusa::MissingHookIdError
118
+ return [400, {}, []]
119
+ end
120
+
121
+ body = env["rack.input"].read
122
+ # hook.id, hook.source, hook.tenant, hook.content_type
123
+ [200, {}, []]
124
+ end
125
+ ```
126
+
127
+ `HookHeaders#id` is what a receiver dedupes on: delivery is at-least-once (see
128
+ "HTTP handoff" in
129
+ [`docs/integrations.md`](https://github.com/jamescarr/ankusa/blob/main/docs/integrations.md)),
130
+ so the same hook can arrive twice after a retry. Header lookup is always
131
+ case-insensitive, regardless of whether the mapping passed in already is.
132
+
133
+ ## Routes client
134
+
135
+ Manage route definitions and the global IP rules on the route-management
136
+ listener (`routes.admin.port`, default 4003) — the `routes` tag of
137
+ [`priv/openapi/admin.v1.yaml`](../ankusa/priv/openapi/admin.v1.yaml).
138
+
139
+ ```ruby
140
+ require "ankusa/sdk"
141
+
142
+ routes = Ankusa::RoutesClient.new(ENV.fetch("ROUTES_URL", "http://localhost:4003"))
143
+
144
+ routes.create_route({"id" => "stripe", "path" => "/webhooks/stripe"})
145
+ routes.get_ip_rules # {"default" => "allow", "rules" => []}
146
+ routes.test_route({"method" => "POST", "path" => "/webhooks/stripe", "ip" => "203.0.113.7"})
147
+ ```
148
+
149
+ Methods: `health`, `list_routes`, `create_route`, `get_route`, `replace_route`,
150
+ `update_route`, `delete_route`, `get_ip_rules`, `put_ip_rules`, `test_route`.
151
+ Route ids are percent-encoded as one path segment, so `/`, `?`, `#`, `%` and a
152
+ space in an id can't reshape the URL.
153
+
154
+ Failures are `RoutesError` subclasses: `InvalidRouteIdError` (an id that isn't a
155
+ string, is empty, or is `.`/`..` — raised before any request, because a URL
156
+ parser would otherwise normalize it into the collection endpoint and hand back
157
+ the list page as if it were a route), `RouteNotFoundError` (404),
158
+ `RoutesRejectedError` (any other 4xx, carrying `code`, `field`, `message`,
159
+ `conflicting_id`, `max_routes`), and `RoutesUnavailableError` (5xx, an
160
+ unfollowed redirect, a non-JSON success body, or unreachable; retryable).
161
+
162
+ ## Admin client
163
+
164
+ The operator API on `admin.port` (default 4002): health, Prometheus metrics, the
165
+ redacted config, the DLQ, and the quarantine list — the `operations`, `dlq`, and
166
+ `quarantine` tags of `admin.v1.yaml`.
167
+
168
+ ```ruby
169
+ require "ankusa/sdk"
170
+
171
+ admin = Ankusa::AdminClient.new(ENV.fetch("ADMIN_URL", "http://localhost:4002"))
172
+
173
+ admin.health # {"status" => "ok", "instance" => ..., "roles" => [...]}
174
+ admin.list_dead_letters({"limit" => 10}) # {"total" => ..., "entries" => [...]}
175
+ admin.replay_dead_letters({"source_id" => "demo"})
176
+ admin.list_quarantined
177
+ ```
178
+
179
+ Methods: `health`, `metrics` (Prometheus text), `config`, `list_dead_letters`,
180
+ `replay_dead_letters`, `list_quarantined`. Failures are `AdminError` subclasses:
181
+ `RoleNotEnabledError` (409 `role_not_enabled`, carrying `role`),
182
+ `AdminRejectedError` (any other 4xx, carrying `code`), and
183
+ `AdminUnavailableError` (5xx, an unfollowed redirect, or unreachable;
184
+ retryable).
185
+
186
+ ## Sources client
187
+
188
+ Ankusa's ingest sources are tenant-scoped: a source is addressed as
189
+ `<tenant>.<name>`, and `Ankusa.Admin.Router` serves their CRUD API on the same
190
+ `admin.port` as the operator API. `SourcesClient` speaks in those terms and
191
+ builds the paths for you.
192
+
193
+ ```ruby
194
+ require "ankusa/sdk"
195
+
196
+ sources = Ankusa::SourcesClient.new(ENV.fetch("ADMIN_URL", "http://localhost:4002"))
197
+
198
+ sources.list_sources("acme") # [Source, ...]
199
+ sources.get_source("acme", "billing") # Source
200
+ sources.create_source("acme", "billing", Ankusa::SourceSpec.new(sinks: [{"type" => "log"}]))
201
+ sources.update_source(
202
+ "acme",
203
+ "billing",
204
+ Ankusa::SourceSpec.new(sinks: [{"type" => "log"}], on_verify_failure: "reject")
205
+ )
206
+ sources.delete_source("acme", "billing")
207
+ ```
208
+
209
+ Methods: `server_version`, `list_sources`, `get_source`, `create_source`,
210
+ `update_source`, `delete_source`. A write takes the whole spec (`SourceSpec`,
211
+ whose `to_request_body` omits unset fields); a read returns a `Source`, which is
212
+ always redacted — resending a read-back `verify` map is not the same as
213
+ resending the stored secret, so supply secrets through `SourceSpec`.
214
+
215
+ `expected_version: "0.3.0"` is an optional latch: the first API call fetches
216
+ `GET /health`, compares its `"version"` field, and raises
217
+ `VersionMismatchError` on a mismatch (the version is cached afterwards, so no
218
+ further request checks it). Failures are `SourcesError` subclasses, each
219
+ carrying `.status` and `.body`: `SourceNotFoundError` (404),
220
+ `SourceConflictError` (409), `SourceStoreReadOnlyError` (409 — the deployment's
221
+ source store is a static seed), `SourceInvalidError` (400, or an invalid
222
+ tenant/name caught before any request), `VersionMismatchError`, and
223
+ `SourcesUnavailableError` (unreachable, timed out, or 5xx).
224
+
225
+ Tenants and source names must match `[A-Za-z0-9_-]{1,64}`; anything else raises
226
+ `SourceInvalidError` before a path is built.
227
+
228
+ ## Layout
229
+
230
+ ```
231
+ lib/ankusa/
232
+ sdk.rb # entry point: require "ankusa/sdk"
233
+ sdk/version.rb
234
+ error.rb # Ankusa::Error, the root of every SDK error
235
+ transport.rb # the injectable transport hook + the default Net::HTTP one
236
+ connection.rb # shared URL/query/body/JSON rules (@api private)
237
+ webhook.rb # x-ankusa-* header parsing for HTTP-sink receivers
238
+ claim_check.rb # the claim-check gateway client
239
+ routes.rb # the route-management client (routes.admin.port)
240
+ admin.rb # the operator client (admin.port)
241
+ sources.rb # the tenant-scoped source-management client (admin.port)
242
+ test/
243
+ test_helper.rb
244
+ test_conformance.rb # runs the language-neutral vectors in conformance/
245
+ test_routes.rb
246
+ test_admin.rb
247
+ test_sources.rb
248
+ ```
249
+
250
+ ## Develop
251
+
252
+ ```sh
253
+ bundle install
254
+ bundle exec rake # tests + standard
255
+ bundle exec rake conformance # just the conformance vectors
256
+ ```
@@ -0,0 +1,141 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Ankusa
4
+ # Every failure the admin client can raise.
5
+ #
6
+ # `retryable?` is the whole point of this hierarchy, exactly as in the
7
+ # claim-check client: a caller (an operator script, a dashboard) needs one bit
8
+ # -- retry, or surface the rejection -- and nothing here requires it to know
9
+ # the operator API's status codes to get that right.
10
+ #
11
+ # Non-retryable: the listener said 409 role_not_enabled (ask another node) or
12
+ # another 4xx (a rejected filter). Retryable: the listener said 5xx, or the
13
+ # request never completed (network error, timeout).
14
+ class AdminError < Error
15
+ def retryable? = false
16
+ end
17
+
18
+ # The listener is unreachable, or answered 5xx. Safe to retry.
19
+ class AdminUnavailableError < AdminError
20
+ def retryable? = true
21
+ end
22
+
23
+ # The listener returned 409 role_not_enabled: this node does not run the role
24
+ # the operation needs. Ask another node; `role` names it.
25
+ class RoleNotEnabledError < AdminError
26
+ attr_reader :role
27
+
28
+ def initialize(message, role:)
29
+ super(message)
30
+ @role = role
31
+ end
32
+ end
33
+
34
+ # The listener rejected the request (any other 4xx).
35
+ #
36
+ # `status` is the HTTP status; `code` is the body's `error` field
37
+ # (`invalid_filter`, ...).
38
+ class AdminRejectedError < AdminError
39
+ attr_reader :status, :code
40
+
41
+ def initialize(message, status:, code:)
42
+ super(message)
43
+ @status = status
44
+ @code = code
45
+ end
46
+ end
47
+
48
+ # Operate against the operator API (`admin.port`, default 4002): health,
49
+ # Prometheus metrics, the redacted config, the dead-letter queue, and the
50
+ # quarantine list. Responses are node-local by design, so a fleet operator
51
+ # scrapes every node's admin port.
52
+ #
53
+ # Like the claim-check client, the listener itself performs no authentication
54
+ # -- `headers` is for whatever a deployer's own boundary (service mesh, an API
55
+ # gateway) expects in front of it.
56
+ class AdminClient
57
+ def initialize(base_url, headers: nil, timeout: 10.0, transport: nil)
58
+ @connection = Connection.new(base_url, headers: headers, timeout: timeout, transport: transport)
59
+ end
60
+
61
+ # Liveness probe: GET /health -> {status, instance, roles}.
62
+ def health
63
+ json(request("GET", "/health"))
64
+ end
65
+
66
+ # GET /metrics -> the Prometheus text exposition body.
67
+ def metrics
68
+ request("GET", "/metrics").body.dup.force_encoding(Encoding::UTF_8)
69
+ end
70
+
71
+ # GET /v1/config -> the effective, redacted configuration.
72
+ def config
73
+ json(request("GET", "/v1/config"))
74
+ end
75
+
76
+ # GET /v1/dlq -> a page of dead-lettered hooks, newest first.
77
+ #
78
+ # `params` may carry `source_id`, `since` and `limit`; absent keys are
79
+ # omitted from the query string rather than sent as `=`.
80
+ def list_dead_letters(params = nil)
81
+ json(request("GET", "/v1/dlq", query: params))
82
+ end
83
+
84
+ # POST /v1/dlq/replay -> {replayed}.
85
+ #
86
+ # `filter` is a filter, not a payload; omitted or empty (`{}`) replays
87
+ # everything.
88
+ def replay_dead_letters(filter = nil)
89
+ json(request("POST", "/v1/dlq/replay", json: filter || {}))
90
+ end
91
+
92
+ # GET /v1/quarantine -> recent quarantined hooks, newest first.
93
+ #
94
+ # `params` may carry `limit`; absent keys are omitted from the query string
95
+ # rather than sent as `=`.
96
+ def list_quarantined(params = nil)
97
+ json(request("GET", "/v1/quarantine", query: params))
98
+ end
99
+
100
+ private
101
+
102
+ def request(http_method, path, query: nil, json: nil)
103
+ response = @connection.request(http_method, path, query: query, json: json)
104
+ raise_for_status(response)
105
+ response
106
+ rescue Transport::Error => e
107
+ raise AdminUnavailableError, "admin listener unreachable: #{e.message}"
108
+ end
109
+
110
+ def json(response)
111
+ Connection.parse_json(response.body)
112
+ rescue JSON::ParserError
113
+ raise AdminUnavailableError, "admin listener returned a non-JSON body (#{response.status})"
114
+ end
115
+
116
+ def raise_for_status(response)
117
+ status = response.status
118
+ return if status >= 200 && status < 300
119
+
120
+ body = Connection.error_body(response)
121
+ code = body.is_a?(Hash) ? body["error"] : nil
122
+
123
+ if status == 409 && code == "role_not_enabled"
124
+ role = body.is_a?(Hash) ? body["role"] : nil
125
+ raise RoleNotEnabledError.new("role not enabled on this node: #{role.inspect}", role: role)
126
+ end
127
+
128
+ if status >= 400 && status < 500
129
+ raise AdminRejectedError.new(
130
+ "admin listener rejected the request (#{status}): #{body.inspect}",
131
+ status: status,
132
+ code: code
133
+ )
134
+ end
135
+
136
+ # Everything else that isn't 2xx is retryable: 1xx, an unfollowed 3xx
137
+ # redirect, and 5xx.
138
+ raise AdminUnavailableError, "admin listener error (#{status}): #{body.inspect}"
139
+ end
140
+ end
141
+ end