ledger

package
v0.133.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: Apache-2.0 Imports: 10 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package ledger is the canonical client for the fleet's token ledger (baditaflorin/go-fleet-token-ledger, ADR-0033). Any service that wants to meter a call charges tokens against the CALLER's own balance before doing expensive work — never invent a bespoke per-service rate limiter or balance table; see CLAUDE.md's cardinal rule: change the library, not every service.

Attribution — forward the caller's credential, not your own

A metered charge must land on the account of the human/agent that made the original request, not on the service doing the metering. Build a Credential from the inbound request with CredentialFromRequest (which forwards the exact token middleware.TokenAuthKeystore already verified for that request) and pass it to Charge — never use this service's own FLEET_API_KEY here. This mirrors how go-fleet-mcp-gateway forwards the caller's own Authorization/X-API-Key to upstream services (ADR-0032): one revoke still kills access everywhere, ledger included.

Wire format

POST /v1/charge   Authorization: Bearer <caller's own token>
                  body {"amount":N,"reason":"..."}
                  200 → charged, deducted from the caller's balance
                  402 → insufficient balance; x402-shaped
                        PaymentRequirements body (proxy verbatim to
                        your own caller with WritePaymentRequired)

GET  /v1/balance  Authorization: Bearer <caller's own token>
                  200 → {"account","balance"}, no state mutated.
                  Use this for a read-only "does this account have
                  anything at all" check — never repurpose Charge as
                  a probe, it spends the caller's balance on every call.

Environment

LEDGER_SERVICE_URL   base URL (default: http://localhost:18314)

Production URL is the fleet-token-ledger registry entry (services.json); see private fleet-state/OPS.md for topology.

Index

Constants

This section is empty.

Variables

View Source
var ErrInsufficientBalance = errors.New("ledger: insufficient balance")

ErrInsufficientBalance means the ledger returned 402. Use errors.As(err, &pr) to recover the *PaymentRequired body (already x402-shaped) and either inspect Balance/Required or proxy it verbatim to your own caller via WritePaymentRequired.

View Source
var ErrLedgerUnavailable = errors.New("ledger: unavailable")

ErrLedgerUnavailable means the charge call failed transport-wise (network error or an unexpected non-200/402 status). The client never decides your degrade policy — fail open (serve anyway) or fail closed (503) is a per-caller judgment call.

View Source
var ErrNoCredential = errors.New("ledger: no caller credential to forward")

ErrNoCredential means CredentialFromRequest found no forwardable token on the inbound request (e.g. it was authenticated via the private-mesh trust path, which requires none). Charge refuses to proceed rather than silently charging an empty-string account — that would pool every such caller's usage into one shared bucket.

Functions

func WritePaymentRequired

func WritePaymentRequired(w http.ResponseWriter, pr *PaymentRequired)

WritePaymentRequired proxies a *PaymentRequired straight through to w — the canonical way to pass the ledger's 402 on to your own caller without re-deriving its shape.

Types

type BalanceResult

type BalanceResult struct {
	Account string `json:"account"`
	Balance int64  `json:"balance"`
}

BalanceResult is what a successful (200) balance read returns.

type ChargeResult

type ChargeResult struct {
	Account string `json:"account"`
	Charged int64  `json:"charged"`
	Balance int64  `json:"balance"`
}

ChargeResult is what a successful (200) charge returns.

type Client

type Client struct {
	BaseURL    string
	HTTPClient *http.Client
	UserAgent  string
}

Client is a minimal, timeout-bounded HTTP client for the token ledger. Construct one per process and reuse — don't churn HTTPClient instances.

func New

func New() *Client

New returns a Client wired from env vars.

func (*Client) Balance

func (c *Client) Balance(ctx context.Context, cred Credential) (int64, error)

Balance reads the caller's current balance, attributed to cred, without spending anything. Returns ErrNoCredential if cred is empty and ErrLedgerUnavailable for network/non-200 failures. Callers that only need to know "is there anything left" (e.g. an overflow/allow-through check) should use this instead of attempting a Charge as a probe — Charge mutates the caller's balance on every call, Balance never does.

func (*Client) Charge

func (c *Client) Charge(ctx context.Context, cred Credential, amount int64, reason string) (*ChargeResult, error)

Charge deducts amount tokens for reason, attributed to the caller identified by cred. Returns ErrNoCredential if cred is empty, ErrInsufficientBalance (wrapping *PaymentRequired — use errors.As) on 402, and ErrLedgerUnavailable for network/5xx failures.

type Credential

type Credential string

Credential is the caller's own fleet API token, lifted from the inbound request that triggered the metered work — never this service's own FLEET_API_KEY. Build one with CredentialFromRequest.

func CredentialFromRequest

func CredentialFromRequest(r *http.Request) Credential

CredentialFromRequest forwards the SAME token server.WithKeystoreAuth/WithKeystoreAuthMesh already verified for r, via middleware.ExtractToken (the fleet's supported credential headers: Authorization: Bearer or X-API-Key. Empty when r was authenticated via the private-mesh trust path, which carries no token at all — Charge rejects an empty Credential with ErrNoCredential rather than guessing an account to charge.

type PaymentRequired

type PaymentRequired struct {
	Balance  int64
	Required int64
	Body     []byte
}

PaymentRequired is the ledger's 402 response. Balance/Required are pulled out for callers that want to reason about them programmatically; Body is the exact response bytes so WritePaymentRequired can proxy them through byte-for-byte without this client re-deriving the x402 shape (which may grow fields as real settlement providers land — see ADR-0033).

func (*PaymentRequired) Error

func (p *PaymentRequired) Error() string

func (*PaymentRequired) Unwrap

func (p *PaymentRequired) Unwrap() error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL