Payment gateway and request enforcement
The payment gateway is the server-side boundary between an API caller and a provider service. It identifies the endpoint, decides whether the request is free or needs payment, checks the caller's credential, and only then serves or proxies the request. It also turns the same endpoint and pricing rules into discovery data, receipts, usage records, and provider setup checks. The production path uses Pingora as the public data plane and an internal Axum service for control-plane routes; the shared gate keeps both paths on the same payment contract. See Rust payment runtime, client payment flows, session channels and metering, and deployment payment policy for related views.
Request enforcement
Request enforcement is the shared decision layer for the gateway. It uses request metadata and the configured API surface to choose a response, a forward action, or a pass-through action before normal request handling runs (rust/…/gate.rs• L48-61, rust/…/gate.rs• L414-435). The Axum middleware maps the decision to an HTTP response or provider call. The Pingora gateway uses the same decision model at the public edge (rust/…/payment.rs• L48-109).
The gateway first protects its own control and discovery paths from payment checks. It then maps the request host to an API and matches the path and method to a declared endpoint. A single configured API can serve any subdomain. A browser payment link and a session commit can resolve an endpoint by path when the request method does not match the declared method (rust/…/gate.rs• L549-657). Pingora sends free and discovery traffic to the internal control plane. A verified payment always goes to the real provider route.
The decision has three broad outcomes:
- Passthrough: free, unknown, or discovery traffic continues to normal routing.
- Respond: the gateway returns a challenge, error, control response, or channel-close result without calling the provider.
- Forward: a valid payment or subscription credential allows the request to reach the endpoint handler. The decision can also carry receipt data, session state, or post-response settlement work.
The gateway treats only Authorization: Payment ... as a payment credential. Other authorization schemes remain available for the upstream provider and do not become malformed payment errors. A missing or unusable payment credential produces a 402 Payment Required response with all accepted and available payment schemes (rust/…/gate.rs• L679-793, rust/…/gate.rs• L998-1053). The Axum boundary removes caller-supplied internal identity and policy headers before evaluation. It adds verified identity only after the gate accepts the payment (rust/…/payment.rs• L53-57, rust/…/payment.rs• L181-185).
Payment challenge and verification
Payment challenge and verification form one contract. The gateway advertises the amount, scheme, and resource identity that it will accept, then rebuilds or checks those terms when it receives the credential. This prevents a client from changing the price, recipient split, or resource after the challenge (rust/…/gate.rs• L801-1053, rust/…/gate.rs• L1055-1151). Resource-backed MPP and x402 charge challenges add a short unique suffix to the payment memo. Verification accepts that suffix or the older exact resource form while keeping the payment bound to the endpoint (rust/…/payment.rs• L687-746, rust/…/gate.rs• L1091-1107).
The endpoint can accept several payment forms. The configured schemes determine which challenges appear and which verification paths are active:
| Scheme | Request behavior | Settlement point |
|---|---|---|
| MPP charge | One payment credential covers one request. | Before the provider response is served. |
| MPP session | A channel credential opens or advances a reusable payment channel. | Through vouchers while the session serves data. |
| x402 exact | An exact payment is checked and settled for one request. | Before the provider response is served. |
| x402 upto | The client opens a channel up to an advertised ceiling. | After the response, for measured use or a configured amount. |
| x402 batch settlement | The gateway verifies a channel action and reserves it for one request. | After a successful provider response, with later operator settlement. |
The default for a metered endpoint is MPP charge. When the API has a session configuration and the endpoint does not list schemes, the server adds MPP session to the default. Explicit schemes remain a restriction rather than an addition (rust/…/metering.rs• L64-91, rust/…/metering.rs• L1177-1236).
This sequence shows the main request path from endpoint lookup to provider response.
flowchart TD
A[HTTP request] --> B[Identify API and endpoint]
B --> C{Control or free endpoint?}
C -->|Yes| D[Pass through or serve locally]
C -->|No| E{Payment credential present?}
E -->|No| F[Return 402 challenge]
E -->|Yes| G[Verify against current price and terms]
G -->|Rejected| H[Return payment error or new 402]
G -->|Accepted| I[Forward to provider]
I --> J[Measure and settle if needed]
J --> K[Attach receipt and return response]
Deployment payment policy
Deployment payment policy supplies request-specific payment terms for compute deployments. The gateway uses the request host only to select a deployment, then obtains an authenticated policy for the exact host and path before it creates the session challenge (rust/…/deployment_policy.rs• L198-241, rust/…/gate.rs• L460-546).
The policy service returns the deployment identity, version, price, expiry, accepted scheme, and payout allocations. The gateway validates the deployment owner, resource identity, price split, and lifetime. It resolves the policy for every admission, so a deleted, expired, or replaced policy cannot fall back to an older local copy. Deployment hosts accept MPP session payment only. The static apex keeps the normal control-plane behavior (rust/…/deployment_policy.rs• L285-370, rust/…/gate.rs• L549-577).
The policy becomes part of the session binding. Its expiry stops new invocations, while the durable identity keeps already authorized funds valid for settlement. The gateway also uses bounded admission and a short deadline for policy lookup. This limits the effect of an unavailable policy service without allowing an untrusted caller to choose the policy origin or identity audience (rust/…/deployment_policy.rs• L139-170, rust/…/deployment_policy.rs• L215-241).
References: rust/…/deployment_policy.rs• L98-170 rust/…/deployment_policy.rs• L198-241 rust/…/deployment_policy.rs• L285-370 rust/…/gate.rs• L460-546
Subscription access
Subscription access gates an endpoint by a recurring plan instead of a per-call charge. The first subscription credential activates the plan on chain. Later requests can use a stateless authenticate credential for the active period (rust/…/gate.rs• L1196-1393).
The server emits the subscription challenge as the canonical activation challenge. It does not need to emit a companion authenticate challenge. After activation, it accepts an authenticate credential when the endpoint has a published plan and created time. Verification is stateless and does not broadcast a new transaction (rust/…/gate.rs• L1252-1341, rust/…/authenticate.rs• L19-79). Successful activation returns a receipt and forwards the request. Failed activation returns a new subscription challenge with retry information (rust/…/gate.rs• L1346-1391).
Subscription setup combines endpoint terms with operator defaults. The endpoint must provide a usable plan, price, currency, and period. The operator supplies the network, RPC URL, challenge-binding secret, realm, optional fee payer, and shared replay or proof store. The gateway can use Redis for that store when several instances must share subscription state. Otherwise it uses a process-wide memory store (rust/…/subscription.rs• L22-63, rust/…/subscription.rs• L244-347).
Subscription terms use fixed day or week periods. The server needs a published on-chain plan, a stable challenge-binding secret, a realm, a currency amount, and valid operator payment settings. The HTTP expiry can stop renewals even while the on-chain plan remains available. The authenticate period must be positive and no longer than one year (rust/…/subscription.rs• L201-360, rust/…/metering.rs• L1033-1108).
References: rust/…/gate.rs• L1196-1393 rust/…/subscription.rs• L22-63 rust/…/subscription.rs• L201-360 rust/…/subscription.rs• L644-661 rust/…/authenticate.rs• L19-98 rust/…/metering.rs• L1033-1174
Request pricing
Request pricing converts the endpoint's metering rules into the amount shown in a challenge and the amount used for verification. The price can depend on request properties, a path-selected variant, conditional tiers, or cumulative usage. The same resolver is used for quotes and post-response accounting so the advertised and applied rules stay aligned (rust/…/metering.rs• L150-200, rust/…/metering.rs• L786-811).
Model or resource variants can select different prices. If no variant matches, the endpoint can use its default dimensions or its default variant. For response-metered inference, the observed model can refine the variant after the provider reports it. Volume tiers use either one shared counter or one counter per wallet, based on the API accounting mode (rust/…/metering.rs• L318-338, rust/…/metering.rs• L813-881, rust/…/metering.rs• L1464-1477).
References: rust/…/metering.rs• L10-49 rust/…/metering.rs• L150-200 rust/…/metering.rs• L305-368 rust/…/metering.rs• L786-881 rust/…/metering.rs• L1217-1244 rust/…/metering.rs• L1464-1477
Provider proxying
Provider proxying sends an accepted request to the upstream service while keeping payment credentials and gateway-only headers inside the gateway. It resolves the endpoint's route, applies path changes, forwards safe headers and the body, adds provider authentication, and streams the provider response back to the caller (rust/…/proxy.rs• L103-138, rust/…/proxy.rs• L293-488). The shared upstream preparation step produces the route, filtered headers, and authentication for both the Axum request path and the Pingora data plane. Pingora then connects to the provider itself rather than sending paid traffic through the internal control plane (rust/…/http402.rs• L203-260).
The proxy supports direct provider keys, query parameters, HMAC signatures, OAuth2 client credentials, and access-token fetches. Provider credentials come from the server configuration and environment rather than from the caller. Cached provider tokens are reused until shortly before expiry (rust/…/proxy.rs• L612-716, rust/…/proxy.rs• L719-741, rust/…/proxy.rs• L1082-1133, rust/…/proxy.rs• L1250-1339).
The proxy removes Host, hop-by-hop headers, payment credentials, and payment challenge headers before forwarding. It also removes internal identity and deployment-policy headers that were not minted by the gate. This boundary keeps caller payment data from reaching or being logged by a third-party provider (rust/…/proxy.rs• L36-59, rust/…/payment.rs• L362-405). Endpoint routing can override the API-wide route. A direct respond route returns a local success response instead of making an upstream call.
Batch authorization reserves a channel before the provider call. The gateway commits that reservation only after a successful provider response and releases it on a failed response. When the complete response is small enough, the gateway stores it for idempotent replay. For a streaming response, an explicit completion signal marks the terminal successful frame. The gateway persists the batch or delegated-session outcome before it releases that frame. A failed, dropped, or incomplete stream releases the reservation instead of charging for a partial answer (rust/…/completion_stream.rs• L18-115, rust/…/completion_stream.rs• L161-209). Later on-chain claim and distribution remain an operator-worker task.
For response-metered requests, the production path asks the provider for an identity-encoded body and rebuilds the downstream content length after it collects the response. It removes transport framing headers while retaining valid response metadata. For a request with a body-signing provider contract, the Axum path can prepare the signature after it has the complete body. The streaming Pingora path detects this contract and routes the request through bounded buffering instead of signing an unknown or empty body (rust/…/proxy.rs• L122-138, rust/…/http402.rs• L234-260).
The production proxy keeps control-plane traffic separate from provider traffic. Pingora serves the public listener and sends control and discovery paths to an internal Axum service. It supports plain TCP or Rustls-backed TLS listeners and can stop through a caller-owned shutdown signal.
References: rust/…/proxy.rs• L36-138 rust/…/proxy.rs• L193-239 rust/…/proxy.rs• L293-488 rust/…/completion_stream.rs• L18-115 rust/…/completion_stream.rs• L161-209 rust/…/http402.rs• L187-265 rust/…/http402.rs• L741-765 rust/…/http402.rs• L830-875 rust/…/http402.rs• L936-958 rust/…/http402.rs• L1013-1019 rust/…/Cargo.toml• L15-40
Usage accounting
Usage accounting tracks the units that affect volume pricing. A counter is keyed by API, endpoint, billing period, and scope. The scope is either a shared pool or a wallet address, so later requests can move into the correct volume tier (rust/…/accounting.rs• L4-27, rust/…/metering.rs• L786-811).
The built-in store is in memory and suits development or one-process deployments. A restart removes its counters. The accounting interface leaves room for a durable store when usage must survive process replacement or be shared by multiple gateway instances (rust/…/accounting.rs• L17-65).
Usage-based x402 upto requests use a separate post-response path. The gateway can read provider usage from response headers, JSON, or observed token counts as the response streams. It selects the observed model when that model is needed for pricing. It clamps the charge to the channel ceiling and applies a configured missing-usage policy: refund, minimum, ceiling, or error (rust/…/metering.rs• L305-368).
Session channels and streaming
Session channels support repeated requests through a cumulative voucher watermark. The gateway verifies the opening challenge before it trusts the channel fields. It can resume an open channel from chain after a restart when reuse is enabled, while rejecting channels that do not belong to the configured recipient or currency (rust/…/session.rs• L1762-1800, rust/…/session.rs• L1901-1928, rust/…/session.rs• L2060-2154).
Session metering converts endpoint rules to integer micro-USD amounts and then to stablecoin base units. It rates cumulative observations instead of charging each stream chunk as a separate rounded amount. Invalid scales, inexact prices, missing required observations, and decreasing provider usage stop the metered path (rust/…/session_metering.rs• L13-53, rust/…/session_metering.rs• L343-422, rust/…/session_metering.rs• L584-629).
For a streamed response, the gateway observes output bytes, text, or provider token data as it arrives. It holds a chunk that crosses a payment threshold until the matching client voucher is durable. Delegated sessions use the gateway signer to authorize the new cumulative amount before releasing the chunk. A delegated request may read a bounded JSON body to identify its model variant. Streaming chat requests can ask the provider to include usage data so the final charge reflects delivered work (rust/…/payment.rs• L121-179, rust/…/payment.rs• L506-607, rust/…/session_stream.rs• L436-528).
The session lifecycle records activity separately from request handling. A delegated response reserves channel capacity and sends heartbeats while it is active. A centralized runloop later claims due channels, pushes accepted voucher watermarks, and closes idle channels. The runloop can be embedded in the gateway or left to an external worker. Shared lifecycle ownership prevents two gateway instances from closing or settling the same channel at once (rust/…/session.rs• L653-669, rust/…/session.rs• L811-1219, rust/…/session.rs• L1241-1265).
This sequence shows how a session response becomes a paid stream and then an on-chain settlement candidate.
sequenceDiagram
participant C as Client
participant G as Gateway
participant P as Provider
participant S as Session store
participant L as Lifecycle worker
C->>G: Open or use session credential
G->>S: Verify channel and reserve capacity
G->>P: Forward request
P-->>G: Stream response chunks
G->>G: Measure cumulative usage
alt Client voucher session
G-->>C: Wait for matching voucher before releasing threshold chunk
C->>G: Signed cumulative voucher
G->>S: Persist accepted watermark
else Delegated session
G->>S: Persist operator-signed usage authorization
end
G-->>C: Release response chunk
L->>S: Extend, settle, or close the channel
L-->>C: Receipt becomes available by channel poll
References: rust/…/session.rs• L653-669 rust/…/session.rs• L811-1219 rust/…/session.rs• L1241-1265 rust/…/session.rs• L1762-2225 rust/…/session_metering.rs• L343-422 rust/…/session_stream.rs• L127-223 rust/…/session_stream.rs• L355-528
For streamed responses, the gateway can meter data as it leaves the provider. For a delegated session or a response-metered x402 upto request, it buffers the response when needed. It rates actual use and persists the settlement before releasing the matching response bytes. A failed provider response releases the reservation or refunds the open channel without charging the caller (rust/…/gate.rs• L148-175, rust/…/payment.rs• L208-287, rust/…/http402.rs• L383-559, rust/…/http402.rs• L921-935).
The production proxy also records inference usage while a normal response streams. Response-metered payments use the buffered path so the final payment header is ready before the body reaches the caller.
References: rust/…/accounting.rs• L4-79 rust/…/metering.rs• L36-63 rust/…/metering.rs• L305-368 rust/…/metering.rs• L786-811 rust/…/session_metering.rs• L343-422 rust/…/gate.rs• L212-269 rust/…/payment.rs• L208-287 rust/…/http402.rs• L383-559 rust/…/http402.rs• L921-935 rust/…/http402.rs• L961-995
OpenAPI integration
OpenAPI integration makes the gateway discoverable without exposing the provider's private route or authentication contract. The server serves /openapi.json from an operator-supplied OpenAPI or Google Discovery document, or creates a document from the paywall when no source document is supplied.
The served document contains only operations declared by the gateway. It carries payment offers and metering data so a client can learn the available payment methods and pricing, including details that a live challenge cannot show. The server also removes upstream authentication metadata because the gateway supplies that authentication itself.
At request time, the server rewrites the document's public URL fields to the gateway origin. It uses --public-url when set. Otherwise it uses the request host and forwarded protocol. This lets clients call the gateway from the published document without knowing the provider URL.
This diagram shows how the provider description becomes a gateway-facing contract.
flowchart LR
A[Paywall endpoint rules] --> C[Filter and enrich]
B[Provider OpenAPI or Discovery document] --> C
C --> D[Remove upstream auth details]
D --> E[Rewrite public gateway URL]
E --> F[Served /openapi.json]
F --> G[Client discovers routes and payment offers]
References: rust/…/openapi.rs• L1-17 rust/…/openapi.rs• L80-197 rust/…/openapi.rs• L351-466 rust/…/openapi.rs• L637-690 rust/…/start.rs• L627-666 rust/…/start.rs• L1519-1532 rust/…/start.rs• L1849-1893
Receipts and telemetry
Receipts give the caller evidence of payment or channel activity after the gateway serves a request. MPP receipts use a payment receipt header and x402 responses use a payment response header. Delegated session responses can include the accepted cumulative channel amount and a channel receipt URL. The final session settlement signature remains available through the session receipt poll because sessions settle out of band at close (rust/…/gate.rs• L116-130, rust/…/gate.rs• L231-287, rust/…/session.rs• L1723-1729).
The client receipt view normalizes these protocol-specific forms. It recognizes MPP receipts and both current and legacy x402 response headers. It can decode base64 or direct JSON and extracts the best transaction signature or reference for display and links (rust/…/receipt.rs• L35-65, rust/…/receipt.rs• L67-181).
The gateway records challenge, collection, completion, settlement error, and upstream error events. Paid request completion is counted only after a successful response. Pingora excludes control-plane paths from debugger tracking, records real API exchanges even for short-circuit payment responses, and preserves payment headers on response, preparation, connection, and refund error paths. This separates money collected from a request that the provider failed to serve while still giving a charged caller proof of payment.
References: rust/…/gate.rs• L103-216 rust/…/session.rs• L1723-1729 rust/…/receipt.rs• L35-181 rust/…/telemetry.rs• L263-349 rust/…/http402.rs• L682-713 rust/…/http402.rs• L998-1078 rust/…/http402.rs• L1087-1164
Payment provider configuration
Payment provider configuration prepares the wallets, currencies, signer, RPC connection, and payment backends before the gateway accepts traffic. Startup loads the paywall, resolves its environment values, applies scheme defaults, validates the full API spec, and then builds the configured MPP and x402 services.
The operator settings define the payment recipient, accepted currencies, Solana network, RPC URL, fee sponsorship, challenge secret, and subscription realm. The signer is needed when the operator sponsors fees or must sign channel and voucher actions. Session prices are restricted to recognized USD-pegged stablecoins because the gateway converts USD values directly to token base units.
Startup checks the payment path before serving requests. It selects or creates a local signer in sandbox and throwaway networks, validates signer balances, prepares stable-token accounts for payout recipients, and fails early when required production accounts are missing. Sandbox mode can fund local wallets and use a local or hosted Surfpool RPC.
Payment backends are created only when an endpoint accepts their schemes. MPP charge servers are built per configured currency. x402 exact supports direct per-request settlement. x402 upto needs an operator signer because it opens and later settles a channel. A shared recent-blockhash cache reduces challenge latency without changing the payment payload. Subscription handlers additionally need a published plan, a configured RPC URL, a challenge-binding secret, and a realm. When a fee payer is configured, the challenge names the configured signer so the client and server use the same activation account (rust/…/subscription.rs• L279-347).
Subscription plans have a separate operator workflow. The gateway checks that the expected plan account is either present and owned by the subscriptions program or genuinely missing. It does not treat an RPC failure as a missing plan. When the operator approves publication, the gateway creates the plan, confirms it, and records its chain details for later challenge and access checks (rust/…/subscription.rs• L363-470, rust/…/subscription.rs• L473-556).
This startup sequence shows the dependency order that protects the request path.
flowchart TD
A[Load paywall] --> B[Resolve environment and scheme defaults]
B --> C[Validate endpoint and payment rules]
C --> D[Resolve network, RPC, recipient, and signer]
D --> E[Prepare wallets, token accounts, and plans]
E --> F[Build MPP and x402 backends]
F --> G[Start request enforcement and proxy]
References: rust/…/start.rs• L579-625 rust/…/start.rs• L721-869 rust/…/start.rs• L890-1077 rust/…/payments.rs• L23-87 rust/…/payments.rs• L181-293 rust/…/payments.rs• L375-454 rust/…/payments.rs• L550-677 rust/…/metering.rs• L677-718 rust/…/subscription.rs• L201-360 rust/…/subscription.rs• L363-556
Change checklist
When these files or sections are changed, remember to consider these:
- When payment schemes or pricing fields change in
pay_types, review scheme defaults, challenge offers, verification, and synthesizedx-payment-infotogether. - When deployment policy fields change, review host selection, per-request policy lookup, session binding, expiry behavior, payout splits, and the deployment session template together.
- When a payment header or receipt shape changes, update both the gateway response annotation and the protocol-neutral client receipt decoder.
- When endpoint path matching or routing changes, check payment lookup, proxy routing, OpenAPI filtering, and URL rewriting as one public contract.
- When a provider auth mode changes, confirm that its secret source is resolved before traffic starts and that caller payment headers remain stripped in both the Axum and Pingora paths.
- When body-signing auth changes, check the body-digest detector and bounded buffered route. Ensure the exact request bytes reach authentication preparation while ordinary requests keep the native streaming path.
- When response-metered proxying changes, keep identity encoding, transport-header filtering, body-size limits, usage extraction, settlement, and downstream content length aligned.
- When x402
uptousage fields change, review buffered responses, streamed responses, observed model selection, missing-usage policy, ceiling clamps, refunds, and terminal error paths. - When batch or completion settlement changes, keep reservation, explicit stream completion, provider success, commit or release, bounded replay capture, and later worker settlement aligned.
- When session channel or stream metering changes, keep cumulative integer rating, base-unit conversion, watermarks, capacity leases, voucher waits, lifecycle touches, delegated authorization, and idle close aligned.
- When session channel storage changes, review restart reuse, shared-instance lifecycle ownership, on-chain watermark reconciliation, and the session receipt poll together.
- When subscription or authenticate terms change, keep plan data, day/week period limits, challenge binding secret, realm, activation verification, and stateless access verification aligned.
- When subscription plan publication changes, preserve the distinction between a missing plan and an RPC failure. Do not broadcast a duplicate create transaction after a transport error.
- When operator currency or signer rules change, review startup funding, payout token accounts, session currency validation, subscription amount conversion, and x402 backend creation.
- When accounting scope or period rules change, review both tier selection and the persistence behavior of the accounting store.
- When production proxy TLS dependencies change, check both public TLS listeners and HTTPS provider connections. Keep the selected TLS path compatible with the runtime's other network dependencies.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A deployment policy is missing, expired, mismatched, or unavailable. | The deployment request is rejected instead of using stale terms or serving without payment. | The resolver validates the host, path, identity, allocation totals, expiry, and scheme on every admission (rust/…/deployment_policy.rs• L215-241, rust/…/deployment_policy.rs• L285-370). |
| A metered endpoint has no usable backend for an accepted scheme. | The gateway returns a server error instead of serving the resource for free. | Challenge construction fails closed when no challenge can be built (rust/…/gate.rs• L998-1007). |
| A payment credential does not match the current amount, resource, or split terms. | The request is rejected with 402 Payment Required and the provider is not called. | Verification rebuilds expected terms from the current endpoint rules (rust/…/gate.rs• L1055-1151, rust/…/gate.rs• L2023-2079). |
| A subscription endpoint lacks a plan, challenge-binding secret, realm, or valid amount. | The gateway cannot create a valid challenge or handler. | Handler construction validates these values before request handling (rust/…/subscription.rs• L201-360). |
| Subscription plan lookup fails because the RPC is unavailable. | Startup must stop rather than prompt the operator to create a duplicate plan. | Plan checks distinguish Missing, WrongOwner, and RPC errors (rust/…/subscription.rs• L422-470). |
| An authenticate credential uses missing plan data or an invalid period. | The stateless credential is not accepted for the subscription period. | Handler construction requires plan data and the access check enforces the period bounds (rust/…/authenticate.rs• L34-98). |
| A session credential echoes a challenge that this server did not issue. | The session action is rejected before its request fields are trusted. | The challenge echo is HMAC-verified and its decoded request is cached only with a full field match (rust/…/session.rs• L1762-1800). |
| A reusable session proof names an unknown, sealed, or pre-binding channel. | The request is rejected and retrying the same cached proof cannot restore access. | Session verification checks channel state, proof binding, signer role, payer, and channel signature (rust/…/session.rs• L2157-2215). |
| A stream reaches a voucher threshold but the matching commit does not arrive. | The threshold-crossing bytes remain withheld and the stream times out after 30 seconds. | The stream waits for the cumulative watermark before releasing the chunk (rust/…/session_stream.rs• L491-528). |
| A flat-price stream ends without its explicit completion signal. | Partial output is not charged and the reserved authorization is released. | The completion owner commits only after the terminal signal and releases on failure, drop, or EOF (rust/…/completion_stream.rs• L33-75, rust/…/completion_stream.rs• L176-209). |
| A delegated stream uses more capacity than its authorization allows. | The stream fails instead of delivering unpaid output. | Delegated settlement clamps repricing to the authorized ceiling and marks the authorization exhausted (rust/…/session_stream.rs• L265-301). |
| An active session is closed while a request or delegated stream still owns it. | The close is deferred or the request is rejected as the channel becomes unavailable. | Shared capacity reservation covers both serving and close. Stream leases release on drop (rust/…/session.rs• L653-669, rust/…/session.rs• L1195-1215). |
| A body-dependent upstream signature is prepared without the complete request body. | The provider receives an invalid signature or the paid request fails before the provider call. | The gateway identifies body-digest preparation and routes only those endpoints through bounded request buffering before authentication (rust/…/proxy.rs• L122-138, rust/…/http402.rs• L234-260). |
| Required provider auth environment data is absent or empty. | The gateway returns 502 Bad Gateway instead of sending a request with blank auth. | Auth injection fails loudly during upstream preparation (rust/…/proxy.rs• L626-716). |
| A response-metered request or response exceeds its buffer limit. | The request ends with 413 Payload Too Large for an oversized request body or 502 Bad Gateway for a failed response-metering read. Pending channel funds are released or refunded. | The buffered path bounds both bodies and drains payment state on the terminal path (rust/…/payment.rs• L446-465, rust/…/payment.rs• L217-260). |
| A batch-authorized provider response is not successful. | The channel reservation is released and the operator worker has no batch claim to settle. | The response path releases the batch before the response proceeds (rust/…/payment.rs• L288-337). |
Response usage is missing for an x402 upto charge. | The final charge follows the configured refund, minimum, ceiling, or error policy. | Usage extraction applies the endpoint's missing-usage policy and never exceeds the channel ceiling (rust/…/metering.rs• L340-359). |
| A required fee-payer signer or payout token account is unavailable. | Startup stops before the gateway accepts traffic. | Provider setup validates signer and account readiness during startup (rust/…/start.rs• L821-841, rust/…/payments.rs• L375-454). |
| A configured subscription fee-payer key differs from the signer that broadcasts activation. | The client builds an activation transaction for the wrong payer account and activation fails. | Subscription challenge data uses the configured fee-payer signer's public key when one is present (rust/…/subscription.rs• L311-333). |
| The served OpenAPI document does not match the gateway endpoint list. | Clients discover routes that return 404 or fail to discover callable routes. | The document is filtered to declared endpoints and unmatched operations produce warnings (rust/…/openapi.rs• L351-403, rust/…/openapi.rs• L521-563). |
Key files
| File | Why to read it |
|---|---|
| rust/…/gate.rs | Defines the shared request decision, payment challenge, credential verification, deployment policy dispatch, subscription access, settlement handoff, replay behavior, and receipt annotation model. |
| rust/…/payment.rs | Connects the Axum middleware to the shared gate. It also protects the internal identity boundary and coordinates request and response settlement. |
| rust/…/deployment_policy.rs | Defines authenticated per-deployment policy lookup and validation before a deployment session challenge. |
| rust/…/proxy.rs | Defines shared upstream preparation for route selection, header isolation, provider auth, body-dependent auth detection, token fetching, and response streaming. |
| rust/…/completion_stream.rs | Defines explicit completion and durable terminal settlement for live batch and delegated responses. |
| rust/…/http402.rs | Defines the production Pingora data plane, control-plane split, native upstream path, body-buffered auth path, batch commit and replay capture, response settlement, refunds, and final exchange logging. |
| rust/…/lib.rs | Shows how the public Pingora listener, TLS mode, worker count, and shutdown behavior are assembled. |
| rust/…/Cargo.toml | Shows the production proxy's Pingora and Rustls network boundary and its separation from the core gate. |
| rust/…/session.rs | Defines session challenge binding, channel actions, delegated authorization, restart reuse, lifecycle ownership, watermark settlement, and session receipt state. |
| rust/…/session_metering.rs | Defines exact cumulative usage rating and stablecoin base-unit conversion for session payments. |
| rust/…/session_stream.rs | Defines response-stream measurement, voucher backpressure, delegated stream authorization, and context-based repricing. |
| rust/…/metering.rs | Defines price resolution, variant selection, usage extraction, volume tiers, and upto charge calculation. |
| rust/…/accounting.rs | Defines the usage counter contract and the in-memory accounting behavior. |
| rust/…/openapi.rs | Defines the gateway-facing OpenAPI and Discovery document transforms. |
| rust/…/subscription.rs | Defines subscription amount conversion, plan requirements, shared proof storage, challenge construction, activation verification, fee-payer identity, and plan publication support. |
| rust/…/authenticate.rs | Defines stateless authenticate credentials for active subscriptions and their period and binding requirements. |
| rust/…/receipt.rs | Defines the client-side common view of MPP and x402 response receipts. |
| rust/…/start.rs | Shows startup validation, provider backend construction, HTTP route wiring, and the link between the gate and proxy. |
| rust/…/payments.rs | Shows signer, RPC, currency, funding, payout-account, and shared payment-backend setup. |
| rust/…/metering.rs | Defines the paywall contract for endpoints, routing, operator settings, subscriptions, schemes, metering, and accounting mode. |