Expand description
§ankusa
Client SDK for Ankusa, the self-hosted webhook receiver: claim-check redemption, webhook header parsing, queue-message decoding, and clients for the route-management and operator APIs.
Async only, on Tokio: every call is an async fn you drive yourself, and every
request is bounded by tokio::time::timeout, so the runtime needs its timers (a
plain #[tokio::main] has them). The crate’s own HTTP client is reqwest,
behind a Transport hook you can replace with anything that speaks
http::Request<Bytes>/http::Response<Bytes>.
§Install
cargo add ankusaThe crate is async: add tokio = { version = "1", features = ["macros", "rt-multi-thread"] } to your binary — or any other Tokio runtime, as long as
its time driver is enabled. TLS uses rustls by default;
default-features = false builds a plain-HTTP-only client.
§Claim-check client
A queue worker that receives claim_ref in a job message calls redeem: it
parses the ref, fetches the bytes from the claim-check gateway, and verifies
them against the expected sha256 before handing them over.
use ankusa::ClaimCheckClient;
let client = ClaimCheckClient::new("http://127.0.0.1:4001")?;
let bytes = client
.redeem(
"urn:ankusa:claim:v1:acme:01M39VMD8RA3C5HR4RBV67Y002",
"8e1bed597394cf01672e49232d9929c8bc6b3d6ea4e2f489517ec88701f01581",
)
.await?;
println!("{} bytes", bytes.len());parse_claim_ref is exported standalone, for a consumer that wants the tenant
and claim id without a request:
use ankusa::parse_claim_ref;
let parsed = parse_claim_ref("urn:ankusa:claim:v1:acme:01M39VMD8RA3C5HR4RBV67Y002")?;
assert_eq!(parsed.tenant_id(), "acme");
assert_eq!(parsed.path(), "/v1/claims/acme/01M39VMD8RA3C5HR4RBV67Y002");Every failure is a ClaimCheckError; is_retryable() distinguishes “try again
later” (the gateway was unavailable) from “give up or dead-letter” (the claim is
gone, the sha256 did not match, the gateway rejected the request):
use ankusa::ClaimCheckClient;
let client = ClaimCheckClient::new("http://127.0.0.1:4001")?;
match client
.redeem("urn:ankusa:claim:v1:acme:01M39VMD8RA3C5HR4RBV67Y002", "8e1bed597394cf01672e49232d9929c8bc6b3d6ea4e2f489517ec88701f01581")
.await
{
Err(err) if err.is_retryable() => eprintln!("retry later: {err}"),
Err(err) => eprintln!("give up: {err}"),
Ok(bytes) => println!("{} bytes", bytes.len()),
}§Webhook helper
For the receiving side of Ankusa’s HTTP sink: parse_headers reads the
x-ankusa-* headers (plus content-type) out of a http::HeaderMap,
case-insensitively, and fails when x-ankusa-id is missing or empty.
use ankusa::{parse_headers, MissingHookIdError};
use ankusa::http::HeaderMap;
fn hook_id(headers: &HeaderMap) -> Result<&str, MissingHookIdError> {
Ok(parse_headers(headers)?.id)
}
let mut headers = HeaderMap::new();
headers.insert("x-ankusa-id", "01a0".parse()?);
headers.insert("x-ankusa-source", "demo".parse()?);
assert_eq!(hook_id(&headers)?, "01a0");HookHeaders also carries dedupe_key (from x-ankusa-dedupe-key),
replay_id (from x-ankusa-replay-id) and idempotency_key (from
x-ankusa-idempotency-key), each None when the header is absent or empty,
and its idempotency_key(include_replay) applies the same rule as Message
below.
§Verifying signed deliveries
An HTTP sink with a secret signs every delivery the
Standard Webhooks way. Verify the raw
body before trusting it; answer 401 when it fails:
use ankusa::http::HeaderMap;
use ankusa::{verify_signature, InvalidSignatureError, VerifyOptions};
fn verify(headers: &HeaderMap, body: &[u8], secret: &str) -> Result<(), InvalidSignatureError> {
verify_signature(headers, body, &[secret], VerifyOptions::default())?;
Ok(())
}
let err = verify(&HeaderMap::new(), b"{}", "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw").unwrap_err();
assert_eq!(err.code, "missing_header");Secrets are whsec_ + base64, or any other string used as its own bytes;
pass several during a rotation. VerifyOptions::tolerance_seconds (default
300) bounds the webhook-timestamp window. Signatures are compared in
constant time; a failure is an InvalidSignatureError with code and
field, never retryable.
§Receiving a delivery (signed by default)
Ankusa’s HTTP sink signs every delivery unless it is configured
allow_unsigned: true, so a receiver is closed by default. receive_delivery
is the one call that decides: with the sink’s secrets it verifies as above;
with none, and no allow_unsigned, it refuses every delivery
(InvalidSignatureError, code invalid_secret) — otherwise any host that can
reach your URL could inject hooks. A configured secret is never weakened by
allow_unsigned. The signature is judged before the hook id, so a delivery
that fails it is a 401 even when it also lacks x-ankusa-id
(ReceiveError::MissingHookId, 400).
use ankusa::http::HeaderMap;
use ankusa::{receive_delivery, ReceiveError, ReceiveOptions};
let options = ReceiveOptions {
secrets: vec!["whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw".to_owned()],
..ReceiveOptions::default()
};
let headers = HeaderMap::new();
let err = receive_delivery(&headers, b"{}", &options).unwrap_err();
assert!(matches!(err, ReceiveError::Signature(_)));hook.verification (also on parse_headers and decode_message results) is
an Option<Verification> saying how the node verified the hook at ingest,
None from a node older than the field. verification.flagged == true means
the node accepted a failed check (on_verify_failure: accept_flag) — treat it
as unverified. hook.is_trusted() (on Message, HookHeaders and
Verification) is that decision in one call: true only for status ok with
flagged false, so a flagged, failed or skipped hook, or one from a node
older than the field, is untrusted.
§Consuming queue messages
The message’s v is the wire format’s major version: decode_message accepts
every v from MIN_SUPPORTED_VERSION to MAX_SUPPORTED_VERSION (1 and 2) into
the one Message, with v as the wire said it. A v: 2 message is a v: 1
message plus additive fields, so a consumer reads it the same way; any other
v is unsupported_version (permanent: dead-letter it). message.instance and
message.region are the Ankusa instance that published the message and the
region it is configured with (None for none). A message from the instance’s
lifecycle sinks carries a CloudEvents event as its body:
decode_lifecycle(body) returns a LifecycleEvent.
An Ankusa sink delivers the v: 1 queue message as JSON: the body inline
(body_base64) or as a claim-check ref (claim), the body’s sha256, the
provider’s dedupe_key, the idempotency_key Ankusa computed for the hook,
and forwarded headers, and a replay_id when the
delivery is a replay. decode_message validates all of it and, on any
malformed input, returns an InvalidMessageError that is never retryable
(err.code is invalid_json, size_mismatch, integrity, …; err.field
names the offending key when the code is invalid_field).
Key a processed-ids table on idempotency_key: the key Ankusa shipped
(tenant:source_id:dedupe_key when the hook has a provider event key, else
id). For a message from a node that predates the field it computes the same
key itself, with tenant default when there is none. Pass
include_replay: true only if the consumer must reprocess replays — the
default drops replays of events it already processed.
use ankusa::{InvalidMessageError, decode_message};
use std::collections::HashSet;
/// Returns `false` when the delivery was already processed.
fn first_delivery(
raw: &[u8],
processed: &mut HashSet<String>,
) -> Result<bool, InvalidMessageError> {
let message = decode_message(raw)?;
let key = message.idempotency_key(false);
if !processed.insert(key) {
return Ok(false); // a provider retry, or a replay of an event we ran
}
// ... perform the effect, keyed by `key` ...
Ok(true)
}Both body forms are supported: an inline message exposes the bytes as
message.body, while a claim-form message exposes the ref as message.claim
for a ClaimCheckClient::redeem call.
§Routes client
RoutesClient drives the route-management listener (routes.admin.port): the
route table this node enforces, plus the global IP rules and a dry run that
shows which route a request would match.
use ankusa::{ListRoutesParams, RouteInput, RoutesClient};
let routes = RoutesClient::new("http://127.0.0.1:4003")?;
let created = routes
.create_route(&RouteInput {
id: Some("stripe".to_owned()),
path: "/webhooks/stripe".to_owned(),
metadata: Some([("owner".to_owned(), "payments".into())].into_iter().collect()),
..RouteInput::default()
})
.await?;
println!("{} captures {:?}", created.id, created.methods);
let page = routes
.list_routes(&ListRoutesParams {
enabled: Some(true),
limit: Some(10),
..ListRoutesParams::default()
})
.await?;
println!("{} routes, next cursor {:?}", page.routes.len(), page.next_cursor);Route ids travel as one percent-encoded path segment, and an id that is empty,
. or .. is refused with RoutesError::InvalidRouteId before any request is
sent.
§Admin client
AdminClient drives the operator listener (admin.port): health, Prometheus
metrics, the redacted config, the dead-letter queue, and quarantine.
use ankusa::{AdminClient, ListDeadLettersParams};
let admin = AdminClient::new("http://127.0.0.1:4002")?;
let health = admin.health().await?;
if !health.roles.iter().any(|role| role == "dispatch") {
eprintln!("this node does not run dispatch");
}
let page = admin
.list_dead_letters(&ListDeadLettersParams {
source_id: Some("demo".to_owned()),
limit: Some(100),
..ListDeadLettersParams::default()
})
.await?;
println!("{} of {} dead letters", page.entries.len(), page.total);list_audit pages the audit trail (newest first), filtered by since,
until, actor, action and tenant; naming a tenant the credential
cannot see is AdminError::Rejected with scope tenant:*:
use ankusa::{AdminClient, ListAuditParams};
let admin = AdminClient::new("http://127.0.0.1:4002")?;
let page = admin
.list_audit(&ListAuditParams {
tenant: Some("acme".to_owned()),
action: Some("route.update".to_owned()),
limit: Some(50),
..ListAuditParams::default()
})
.await?;
for row in &page.entries {
println!("{} {} {}", row.at, row.actor, row.action);
}Replay jobs are managed on the same listener. create_replay starts one (a
dlq job over dead-lettered rows, an archive job over a time window, or a
quarantine job that re-verifies held hooks and releases those that pass) and
returns the running job when the same spec is posted twice, so a proxy retry is
safe:
use ankusa::{AdminClient, ReplayPatch, ReplaySpec};
let admin = AdminClient::new("http://127.0.0.1:4002")?;
let replay = admin
.create_replay(&ReplaySpec {
kind: "dlq".to_owned(),
source_id: Some("stripe".to_owned()),
rate: Some(500),
..ReplaySpec::default()
})
.await?;
println!("replay {} is {}", replay.id, replay.state);
let jobs = admin.list_replays().await?;
println!("{} jobs", jobs.replays.len());
let paused = admin
.update_replay(
&replay.id,
&ReplayPatch {
state: Some("paused".to_owned()),
..ReplayPatch::default()
},
)
.await?;
println!("replay {} is now {}", paused.id, paused.state);§Custom transport
ClientBuilder shares a base URL, headers, and a timeout across whichever
client you build, and Transport replaces the network entirely — useful for a
proxy, a fake in a test, or an HTTP stack you already have. A transport must
not follow redirects: a 3xx is reported as “unavailable”. The timeout stays
Tokio’s — every request is bounded by tokio::time::timeout, whatever the
transport — so a Tokio runtime with timers is still required.
use ankusa::{ClientBuilder, Transport, TransportError};
use ankusa::bytes::Bytes;
use ankusa::http::{Request, Response};
use std::future::Future;
#[derive(Debug)]
struct Echo;
impl Transport for Echo {
fn send(
&self,
_request: Request<Bytes>,
) -> impl Future<Output = Result<Response<Bytes>, TransportError>> + Send {
async move {
Response::builder()
.status(200)
.body(Bytes::from_static(br#"{"status":"ok"}"#))
.map_err(TransportError::new)
}
}
}
let client = ClientBuilder::with_transport("http://gateway.invalid", Echo)
.header("authorization", "Bearer t0k3n")
.timeout(std::time::Duration::from_secs(5))
.claim_check()?;
let health = client.health().await?;
println!("{}", health.status);§Develop
cargo test --locked # unit tests, README doctests, and the conformance vectors
mise run check:package sdk-rust # format, clippy -D warnings, tests, docs, cargo packageThe conformance suite runs the language-neutral vectors in
conformance/
against this crate’s public API, so ankusa passes the same conformance cases the
TypeScript and Python SDKs do.
Re-exports§
Structs§
- Admin
Client - Client for the operator listener (
admin.port). - Admin
Health GET /healthon the operator listener.- Audit
Entry - One row of the audit trail.
- Audit
Page - One page of the audit trail, newest first.
- Claim
Check Client - Client for the claim-check gateway (
claim_check.port): where a queue worker collects the body a hook was too large to carry. - Claim
Check Health GET /health: the gateway is up.- Client
Builder - Builds a client for one deployment, sharing its base URL, headers, and timeout.
- DlqEntry
- One dead-lettered hook.
- DlqPage
- One page of the dead-letter queue.
- DryRun
IpRule - The rule that produced an IP decision, and the list it came from.
- DryRun
Request - A request to dry-run against the route table.
- DryRun
Result - What the dry run decided.
- Hook
Headers - The
x-ankusa-*headers of a delivered hook, borrowed from the header map they were parsed out of. - Invalid
Claim RefError - A claim-check ref that is not
urn:ankusa:claim:v1:<tenant>:<claim_id>. - Invalid
Message Error - A queue message that cannot be decoded.
- Invalid
Signature Error - A delivery whose signature does not verify.
- IpRule
- One IP rule: a network and what to do with a client in it.
- IpRules
- The global IP rules: the floor every route inherits.
- Lifecycle
Event - A decoded lifecycle event.
- List
Audit Params - The filters
GET /v1/auditaccepts. - List
Dead Letters Params - The filters
GET /v1/dlqaccepts. - List
Quarantined Params - The filters
GET /v1/quarantineaccepts. - List
Routes Params - The filters
GET /admin/routesaccepts. - Message
- A decoded queue message.
- Missing
Hook IdError - A delivery with no (or an empty)
x-ankusa-idheader. - Parsed
Claim Ref - A claim-check ref, split into the parts the gateway path is built from.
- Quarantine
Entry - One quarantined hook.
- Quarantine
Page - One page of the quarantine.
- Receive
Options - How
receive_deliveryjudges a delivery. The default refuses every delivery: no secret and noallow_unsigned. - Received
Delivery - An accepted delivery: its identity, and whether its signature verified.
- Replay
- A replay job.
- Replay
List - Every replay job, newest first.
- Replay
Patch - What
PATCH /v1/replays/{id}changes. - Replay
Spec - What
POST /v1/replaysstarts: adlqjob over dead-lettered rows, anarchivejob over a time window of an archived source, or aquarantinejob that re-verifies held hooks and releases the ones that now pass. - Reqwest
Transport - The default
Transport:reqwest, with redirects disabled. - Route
- A stored route definition.
- Route
Input - A route definition as written. Only the fields that are set travel: the node applies its own defaults to the rest.
- Route
Page - One page of the route table.
- Route
Patch - The four fields
PATCHmay change.pathandidare immutable: replace the definition instead. - Routes
Client - Client for the route-management listener (
routes.admin.port). - Routes
Health GET /healthon the route-management listener.- Routes
Rejection - A
4xxfrom the route-management API, with every field the error shape can carry. - Transport
Error - A transport failure, with the underlying error kept as its source.
- Verification
- How Ankusa verified the hook at ingest.
- Verified
Signature - A verified delivery’s
webhook-idandwebhook-timestamp. - Verify
Options - How
verify_signaturejudges the timestamp.
Enums§
- Access
- Allow or deny.
- Admin
Error - Something the operator API would not do.
- Claim
Check Error - Why a claim could not be redeemed, or the gateway could not be reached.
- Config
Error - Something a client cannot be built with.
- DryRun
Reason - Why a dry run decided what it did. Only
Matchedallows. - IpRule
Scope - Where a deciding IP rule lives.
- Receive
Error - Why a delivery was refused.
- Routes
Error - Something the route-management API would not do.
- Unavailable
Reason - Why a request never produced an answer.
Constants§
- DEFAULT_
TOLERANCE_ SECONDS - The default
webhook-timestampwindow, in seconds either side of now. - MAX_
SUPPORTED_ VERSION - The highest message
vdecode_messageaccepts. - MIN_
SUPPORTED_ VERSION - The lowest message
vdecode_messageaccepts.
Traits§
- Transport
- A pluggable HTTP transport.
Functions§
- decode_
lifecycle - Decodes one lifecycle event (the JSON of the
CloudEvent). - decode_
message - Decodes a queue message of any supported
v(MIN_SUPPORTED_VERSIONtoMAX_SUPPORTED_VERSION). - parse_
claim_ ref - Parses
urn:ankusa:claim:v1:<tenant>:<claim_id>andurn:ankusa:claim:v2:<tenant>:<claim_id>:<exp_unix>:<signature>. - parse_
headers - Reads the hook headers out of
headers. - receive_
delivery - Judges one delivery.
bodymust be the raw bytes received. - verify_
signature - Verifies one delivery.
bodymust be the raw bytes received;secretsarewhsec_+ base64, or any other string used as its own bytes.