Package-level declarations

Types

Link copied to clipboard
abstract class BudgetEvent

Something the budget did, delivered to a BudgetObserver and logged. Every event describes itself, so an observer need not rely on order.

Link copied to clipboard
interface BudgetObserver

Receives every BudgetEvent.

Link copied to clipboard
class BudgetSnapshot(val version: Int, val takenAtEpochMillis: Long, windows: List<WindowSnapshot>, val pausedUntilEpochMillis: Long)

What a BudgetStore keeps between runs: the counts of the budget's hard windows, the instant they were taken and the pause in force. A plain value with a public constructor and no serializer: a store chooses its own encoding.

Link copied to clipboard
interface BudgetStore

Keeps a BudgetSnapshot across runs so a hard window survives a restart. The budget calls load lazily until one succeeds (a failed load is retried on the budget's schedule), then never again, and save write-ahead and on flush(), each under its own lock and bounded by storeTimeout. A failure a call returns or an Exception it throws is a store failure the budget handles; an Error is never swallowed: it propagates to the budget's caller.

Link copied to clipboard
class BudgetUtilisation(windows: List<WindowUtilisation>, val pausedFor: Duration, val waiting: Int)

A reading of the budget: each rate window's current period (windows, in declaration order), how long the budget is paused (pausedFor, zero for none) and how many calls wait (waiting).

Link copied to clipboard
class CacheKey<V : Any>(val endpointId: String, params: List<Pair<String, String>>)

Identifies one cached answer: an endpoint id and the endpoint's parameters, and nothing else.

Link copied to clipboard

How long a load's outcome is stored. ttl is for a value (Lookup.Found), missTtl for a confirmed miss (Lookup.Missing); both are measured from the load's completion. A failure is never stored. Build one with the factory CachePolicy(ttl) { missTtl = … }.

Link copied to clipboard
class CacheStats(val hits: Long, val misses: Long, val evictions: Long, val failedLoads: Long)

A reading of a cache's four counts. Stable Core.

Link copied to clipboard

The supplied ResponseCache: Caffeine 3 under the port's contract, built with the factory CaffeineResponseCache { } and usable without any opt-in (it is a supplied default, not a seam); final, with every policy number a property of its Builder.

Link copied to clipboard

Grants permits under a provider's rate windows and lane shares, pauses on server signals and, when a store is supplied, holds a hard daily stop across a restart.

Link copied to clipboard

The per-call settings of UpstreamClient.call: the receiver of its lambda. Stable Core. Every property is seeded, so reading it inside the lambda gives the effective value (maxWait = maxWait * 2 doubles the client's default). Not thread-safe; use it only inside the lambda.

Link copied to clipboard
class CidrBlock

An address block in CIDR notation, for Untrusted's extraDeniedRanges.

Link copied to clipboard
class Endpoint<T : Any>

One call an upstream offers: a stable id, the function that decodes its answer, and how the answer is cached, charged and classified. Build one with Endpoint("heroes", ::decodeHeroes) { ttl = 10.minutes; misses(404) }, once, and reuse it.

Link copied to clipboard

Why the call budget refused a call; the reason of HttpFailure.BudgetExhausted.

Link copied to clipboard

Marks a WebTools seam whose implementation or subclassing is Experimental: the seam's shape has not been proven by a consumer's own implementation yet, so implementing it may break in a minor release.

Link copied to clipboard

The per-call settings of UrlFetcher.fetch: the receiver of its lambda. Stable Core. Seeded; not thread-safe.

Link copied to clipboard
abstract class HttpFailure : Exception

The root of the stack's failure model: every failure a port or a facade returns inside a Result.

Link copied to clipboard

An immutable, ordered list of header entries. Names are RFC 9110 tokens and values obey the container rule (after trimming SP and HTAB at the ends, no CR, LF or NUL); both are checked by the Builder. Lookup folds ASCII letters only.

Link copied to clipboard

An HTTP request method: an RFC 9110 token, compared case-sensitively.

Link copied to clipboard

An immutable request: method, URL, headers and an optional body.

Link copied to clipboard

An immutable response: status, the URL it came from, headers, the redirect chain that led to it and the body.

Link copied to clipboard

The seam between the stack and the network: sends one HttpRequest and returns the HttpResponse or the HttpFailure inside a Result.

Link copied to clipboard

The supplied BudgetStore: keeps the last snapshot in memory.

Link copied to clipboard
class Lane(val name: String)

A class of callers that shares a budget's windows. Calls on one lane are served first come first served; a lane's share (WindowedCallBudget.Builder.laneShares) is a floor held back for it and never lent.

Link copied to clipboard
sealed interface Lookup<out V : Any>

What a load found: a value (Found) or a confirmed miss (Missing). A confirmed miss is a value, never null and never a failure.

Link copied to clipboard

What an Untrusted policy does with a resolver answer that holds both allowed and denied addresses.

Link copied to clipboard

The supplied HttpTransport: OkHttp 5 under the outbound-URL policy's rules, with manual redirects, a capped body, and never a retry. Built with the factory OkHttpTransport(userAgent, policy); usable without any opt-in (it is a supplied default, not a seam), and final: every number comes from policy.settings, there is no builder and nothing to override.

Link copied to clipboard
sealed class OutboundUrlPolicy

Which URLs and addresses a fetch may reach, and the TransportSettings that go with that choice. A closed pair: Trusted for a known upstream, Untrusted for a URL a third party supplied.

Link copied to clipboard

Which hint set a pause of the call budget; the source of BudgetEvent.Paused.

Link copied to clipboard
interface Permit

A granted unit of budget. Charged at the grant, so a permit never completed is simply spent: the budget holds no lock or lease for it. Not AutoCloseable: its completion is suspend.

Link copied to clipboard

What a response told the budget, passed to Permit.complete: whether the server throttled the call, how long it asked the caller to wait (retryAfter), and its readings by RateWindow.name. Build one with RateSignals { throttled = true; retryAfter = 30.seconds; reading("minute", WindowReading(0)) }.

Link copied to clipboard

Turns a response into the RateSignals the budget acts on. A consumer supplies a per-provider reader for the headers and counts its provider sends.

Link copied to clipboard

One provider rate window: published calls per period, counted in fixed windows that start at multiples of period since the Unix epoch (UTC), so they meet the provider's own wall-clock boundaries. The budget enforces limit = published − margin. A hard window refuses until its boundary with no overdraft and is persisted write-ahead when the budget has a store (it guards a provider that bills per period). Build one with the factory RateWindow(name, published, period) { margin = …; hard = … }.

Link copied to clipboard
class RedirectHop(val url: Url, val status: Int)

One followed redirect: the URL that was requested and the 3xx status it answered with. A chain [(A, 301), (B, 302)] with a response whose url is C means A answered 301, B answered 302 and C answered the response.

Link copied to clipboard

Why the outbound-URL policy refused a request or a redirect hop; the reason of TransportFailure.RefusedByPolicy.

Link copied to clipboard
class RequestBody(bytes: ByteArray, val contentType: String?)

A request body: its bytes and an optional content type.

Link copied to clipboard

Stores the decoded answer of a load for a bounded time and serves it to any number of concurrent callers from one load; failures are never stored.

Link copied to clipboard
object RetryAfter

Reads a Retry-After header value: a number of seconds (delay-seconds) or an HTTP-date in any of RFC 9110's three forms.

Link copied to clipboard

Which store call failed; the operation of BudgetEvent.StoreFailed.

Link copied to clipboard
abstract class TransportFailure : HttpFailure

A failure of the exchange itself: the request never completed, or completed with something no HttpResponse can hold. Produced by an HttpTransport and by the URL policy.

Link copied to clipboard

The caps, timeouts and concurrency limits of a transport, one set per OutboundUrlPolicy: they belong to the policy because Untrusted's caps and timeouts are part of what makes it untrusted.

Link copied to clipboard

Calls the endpoints of one upstream API from a base URL, composing a response cache, a call budget and a transport in one fixed order: the policy's pre-check, then the cache, then the budget inside the cache's loader, then the transport. A hit costs nothing and N coalesced callers cost one permit and one request. Stable Core.

Link copied to clipboard

The configuration of an UpstreamClient: the receiver of the factory's lambda (Ktor's HttpClientConfig is the precedent). Stable Core. Not thread-safe; use it only inside the lambda.

Link copied to clipboard
abstract class UpstreamFailure : HttpFailure

A complete answer from the server that the caller must treat as a failure: the exchange succeeded, the status did not. Produced by the call facades.

Link copied to clipboard
class Url

A canonical http or https URL. parse accepts text and rewrites it exactly as OkHttp 5.5.0's HttpUrl does when the host is ASCII: it percent-encodes with HttpUrl's sets (non-ASCII path and query text as UTF-8 in upper-case hex), resolves . and .. (the %2e forms included), drops the default port, gives an empty path /, trims TAB, LF, FF, CR and SP at the ends, drops a #fragment, keeps an existing %XX and a malformed % as typed, keeps a bare ? as an empty query, prints IPv6 in RFC 5952 form and an IPv4-mapped address as dotted IPv4, and keeps digits-and-dots hosts and a trailing dot as written. It is only ever stricter than HttpUrl: it refuses a backslash, whitespace or a control character anywhere in the text, an unpaired surrogate, any scheme but http and https and any separator but ://, user-info, a host that is non-ASCII, percent-encoded, outside a-z 0-9 - _ ., outside the length rules or holding an xn-- label, a malformed IPv6 literal (a zone included), and a port that is signed, non-numeric, 0 or above 65535. Building a URL from parts is done as text, then parsed; there is no builder.

Link copied to clipboard

Fetches administrator-supplied URLs: checks the URL against the outbound-URL policy first, then charges the call budget, sends the request through the transport and returns the response. Stable Core. No endpoint, no decode and no cache: an administrator-supplied URL population is an unbounded key space and a conditional GET is its cache.

Link copied to clipboard

The configuration of a UrlFetcher: the receiver of the factory's lambda. Stable Core. Not thread-safe; use it only inside the lambda.

Link copied to clipboard
interface WallClock

A source of wall-clock time, in milliseconds since the Unix epoch (UTC).

Link copied to clipboard
annotation class WebToolsDsl

Marks the configuration builders of webtools-http as one DSL. Inside a lambda whose receiver is a builder carrying this marker, only the innermost such builder is an implicit receiver, so a nested block cannot read or set an outer builder's member by accident: in OutboundUrlPolicy.untrusted { settings { allowedPorts = null } } the assignment does not compile, because allowedPorts belongs to the outer builder. The outer builder stays reachable through its label: this@untrusted.allowedPorts = null.

Link copied to clipboard

The supplied CallBudget: an integer ledger of epoch-aligned fixed rate windows with lane floors, first-come-first-served waits, pauses from server signals and a hard window that survives a restart through a BudgetStore. Built with the factory WindowedCallBudget(windows) { }; Stable Core, usable without any opt-in.

Link copied to clipboard
class WindowReading(val remaining: Int, val resetIn: Duration?)

What a server said about one window after it counted a call: remaining calls left (may be negative once the server is over its limit) and, when it said, resetIn until the window resets.

Link copied to clipboard
class WindowSnapshot(val window: String, val windowStartEpochMillis: Long, val used: Int)

The count of one hard window in one period: used units charged in the period that started at windowStartEpochMillis (a multiple of the window's period since the epoch).

Link copied to clipboard
class WindowUtilisation(val name: String, val used: Int, val queued: Int, val limit: Int, val published: Int, val windowStartEpochMillis: Long, val resetsAtEpochMillis: Long, val hard: Boolean, val elapsedFraction: Double)

One window's current period. used is the count charged against the window this period, in cost units (a call of cost 3 adds 3), not calls: what was granted in this process, what was restored from the store, any rise a server reading forced (see BudgetEvent.Reconciled) and any count a backward wall-clock step copied into the period; queued is the count reserved for waiters; remaining = max(0, limit - used - queued); fraction = used / limit. A consumer that wants to stretch polling intervals needs the burn ratio, not the raw fraction: worked example — 40 of 50 at second 55 of a minute (fraction 0.8, elapsedFraction 0.92) is slack, 40 of 50 at second 10 (0.8 over 0.17) is not; fraction / elapsedFraction is the projected end-of-period usage, and the threshold is the consumer's policy.

Functions

Link copied to clipboard
fun CachePolicy(ttl: Duration, configure: CachePolicy.Builder.() -> Unit = {}): CachePolicy

Builds a CachePolicy.

Link copied to clipboard

Builds a CaffeineResponseCache. Stable Core. CaffeineResponseCache { maxWeight = 5_000 }; without the lambda every property has its default.

Link copied to clipboard
fun <T : Any> Endpoint(id: String, decode: (HttpResponse) -> Result<T>, configure: Endpoint.Builder.() -> Unit = {}): Endpoint<T>

Builds an Endpoint. Stable Core. Endpoint("heroes", ::decodeHeroes) { ttl = 10.minutes; cost = 2; misses(404) }.

Link copied to clipboard
fun HttpHeaders(configure: HttpHeaders.Builder.() -> Unit = {}): HttpHeaders

Builds an HttpHeaders from the calls made on the HttpHeaders.Builder in configure.

Link copied to clipboard
fun HttpRequest(method: HttpMethod, url: Url, configure: HttpRequest.Builder.() -> Unit = {}): HttpRequest

Builds an HttpRequest for method and url with the optional parts set in configure.

Link copied to clipboard
fun HttpResponse(status: Int, url: Url, configure: HttpResponse.Builder.() -> Unit = {}): HttpResponse

Builds an HttpResponse with status from url and the optional parts set in configure.

Link copied to clipboard

Builds an OkHttpTransport for policy: the system resolver, a fresh client, dispatcher and connection pool. The caller closes it.

Link copied to clipboard
fun RateSignals(configure: RateSignals.Builder.() -> Unit = {}): RateSignals

Builds a RateSignals.

Link copied to clipboard
fun RateWindow(name: String, published: Int, period: Duration, configure: RateWindow.Builder.() -> Unit = {}): RateWindow

Builds a RateWindow. RateWindow("day", 3_000, 1.days) { margin = 100; hard = true }.

Link copied to clipboard

Derives a TransportSettings: starts from from, applies configure, validates.

Link copied to clipboard
fun UpstreamClient(transport: HttpTransport, baseUrl: Url, configure: UpstreamClientConfig.() -> Unit = {}): UpstreamClient

Builds an UpstreamClient over a transport the caller owns. Stable Core. The client never closes the transport. The configuration's policy is the pre-check's only; the transport enforces the policy it was built with, so build both from the same policy. Without cache(...) it uses ResponseCache.Disabled, without a budget CallBudget.Unlimited; a budget(windows) is built and owned. On the JVM, UpstreamClient(baseUrl, userAgent) builds and owns the transport, a Caffeine cache and the budget instead.

fun UpstreamClient(baseUrl: Url, userAgent: String, configure: UpstreamClientConfig.() -> Unit = {}): UpstreamClient

Builds an UpstreamClient that owns what it uses: an OkHttpTransport(userAgent, policy), a CaffeineResponseCache on the configuration's clock and dispatcher (unless cache(...) was called) and, when budget(windows) was called, the WindowedCallBudget it built. Stable Core. When the budget is a WindowedCallBudget (built or supplied) both OkHttp concurrency limits are raised to at least its maxBurst, because a client talks to one host (the per-host limit binds) and a permit queued in OkHttp would wait outside the call timeout and the wait cap; they are never lowered and there is no ceiling (worst-case memory is concurrent requests × policy.settings.maxResponseBytes). close() closes the cache, the budget and the transport, in that order, and nothing it was handed. The default policy is Trusted, pinned to the base URL's host, https only.

Link copied to clipboard
fun UrlFetcher(transport: HttpTransport, policy: OutboundUrlPolicy, configure: UrlFetcherConfig.() -> Unit = {}): UrlFetcher

Builds a UrlFetcher over a transport the caller owns. Stable Core. The fetcher never closes the transport. policy is the pre-check's; the transport enforces its own, so pass the same policy to both.

fun UrlFetcher(userAgent: String, configure: UrlFetcherConfig.() -> Unit = {}): UrlFetcher

Builds a UrlFetcher for URLs an administrator supplies: an Untrusted policy (OutboundUrlPolicy.untrusted()), an owned OkHttpTransport(userAgent, policy), CallBudget.Unlimited unless budget is set. Stable Core. close() closes the transport. See the overload with a policy to add the deployment's own denied ranges or ports.

fun UrlFetcher(userAgent: String, policy: OutboundUrlPolicy, configure: UrlFetcherConfig.() -> Unit = {}): UrlFetcher

As the overload without a policy, for a policy of the caller's own: OutboundUrlPolicy.untrusted { extraDeniedRanges += … } adds the deployment's own NAT64 prefix or internal ranges. Stable Core. The transport is built with the policy's settings as they are (an Untrusted policy's concurrency caps are part of what makes it untrusted) and the pre-check applies the same policy.

Link copied to clipboard

Builds a WindowedCallBudget. Stable Core. WindowedCallBudget(listOf(RateWindow("minute", 60, 1.minutes) { margin = 10 })) { maxQueued = 200 }; without the lambda every property has its default. The caller closes the budget; the budget never closes its store or observer.

Link copied to clipboard
suspend fun <T> CallBudget.withPermit(cost: Int, lane: Lane, maxWait: Duration, block: suspend (Permit) -> Result<T>): Result<T>

Acquires a permit, runs block with it and completes the permit as spent (no signals) in a finally unless the block completed or released it. An exception the block throws propagates after the permit is completed; a refused or closed acquire is returned as the failure and block does not run.