consumerusage

package
v0.243.0 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 17 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 consumerusage pushes the Claude usage of a NON-officer muster's agent instances — a muster running PR-review lanes, say — to HQ, per (session, UTC hour, pool account), labelled with the muster's CONSUMER, so HQ can split each pooled account's spend into officers, the consumers that push here, and everything else (docs/officers.md, "Consumer usage to HQ").

THE SOURCE is the one the officer usage collector reads (internal/officers/usage): each instance pod's ccd counting its own transcripts on GET /v1/usage. muster-server counts nothing itself.

THE SINK is HQ's PUT <base>/api/v1/claude-pool/consumer-usage, with the pool push's bearer token (MUSTER_CC_USAGE_PUSH_TOKEN). HQ upserts each row on (instance, consumer, session, hour) and replaces its counts, so a push is the whole of the window and re-pushing is idempotent.

🔴 AN OFFICER INSTANCE IS NEVER PUSHED HERE: its usage goes to its officer's HQ through internal/officers/usage, and pushing it here as well would count it twice at HQ. The caller's instance list (internal/api) leaves officer instances out; this package never sees them.

Index

Constants

View Source
const (
	// DefaultInterval is the officer usage collector's cadence.
	DefaultInterval = 10 * time.Minute
	// Window is how far back each push reaches, as the officer collector's:
	// a muster restart or an HQ outage of up to a day loses nothing.
	Window = 25 * time.Hour
	// DefaultRequestTimeout bounds one read, and one push with its retries.
	DefaultRequestTimeout = 30 * time.Second
	// FlushTimeout bounds the push before a scale-to-zero, read and push
	// together.
	FlushTimeout = 10 * time.Second
)
View Source
const (
	MaxRows = 1000
	MaxBody = 256 << 10 // bytes
)

MaxRows and MaxBody bound one push, as HQ does (413 past either): a window with more is sent in several pushes (Batches), each upserted on its own.

View Source
const (
	PoolUsageSuffix     = "/claude-pool/usage"
	ConsumerUsageSuffix = "/claude-pool/consumer-usage"
)

PoolUsageSuffix is the path the pool push's URL (MUSTER_CC_USAGE_PUSH_URL) ends in, and ConsumerUsageSuffix the route this package PUTs to: the same HQ, the same base, the sibling path.

View Source
const (
	// ConsumerPRReview is a muster running pull-request review lanes.
	ConsumerPRReview = "pr-review"
)

The consumers a muster may push as. A closed set, because HQ refuses a consumer it does not know, and a typo would otherwise be found only in HQ's logs. Officers are not a consumer: they have their own route.

Variables

View Source
var Consumers = []string{ConsumerPRReview}

Consumers is every consumer, in the order a refusal names them.

View Source
var DefaultBackoff = []time.Duration{2 * time.Second, 5 * time.Second}

DefaultBackoff is the waits before each retry of a push HQ answered 5xx or did not answer: two retries, the whole within FlushTimeout with fast answers.

View Source
var ErrUnsupported = errors.New("consumerusage: the instance's ccd does not serve GET /v1/usage (its image predates it)")

ErrUnsupported is an instance whose ccd does not serve GET /v1/usage (an image that predates it). It is skipped quietly.

View Source
var SessionPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)

SessionPattern is the session id HQ accepts. ccd's sessions are Claude Code session ids (UUIDs, 36 characters); a row whose session does not match is not sent (HQ would refuse the whole push over it).

Functions

func AccountAt

func AccountAt(current string, failovers []Failover, hour time.Time) string

AccountAt is the account an instance was on at the end of the UTC hour starting at hour — the LAST account it ran on in that hour: the From of the earliest failover at or after the hour's end, or current (the account it is on now) when there is none. An instance never failed over is on current for every hour, which is the officer push's rule (the row's account at push time); a failover inside the hour attributes the whole hour to the account it moved TO, as a job is counted on the account its last turn ran on.

func URLFromPoolPush

func URLFromPoolPush(poolURL string) (string, error)

URLFromPoolPush is the consumer-usage URL derived from the pool push's URL: its path's PoolUsageSuffix replaced by ConsumerUsageSuffix, scheme, host and base path kept. A URL whose path does not end in PoolUsageSuffix, or that carries a query or a fragment, is refused: there is no base to derive.

func ValidConsumer

func ValidConsumer(c string) bool

ValidConsumer reports whether c is one of Consumers.

Types

type Collector

type Collector struct {
	// contains filtered or unexported fields
}

Collector is the consumer usage collector.

func New

func New(cfg Config) (*Collector, error)

New builds a collector.

func (*Collector) Flush

func (c *Collector) Flush(ctx context.Context, instance string)

Flush pushes instance's usage once, now: it is about to be scaled to zero or destroyed. Bounded by FlushTimeout; best-effort — counted and logged, nothing returned for the stop to fail on.

func (*Collector) Run

func (c *Collector) Run(ctx context.Context)

Run ticks every Interval until ctx ends.

func (*Collector) Tick

func (c *Collector) Tick(ctx context.Context)

Tick pushes every listed instance's usage, one at a time. When HQ does not take a push (5xx or no answer, after its retries) the rest of the tick is skipped: the next tick's pushes cover it, and an HQ that is down is not sent one retried push per instance.

type Config

type Config struct {
	// Consumer is the muster's consumer (ValidConsumer); Instance its label.
	Consumer, Instance string
	// Instances is THE list of this muster's instances whose usage is pushed:
	// up, on a pool account, and never an officer's.
	Instances func(ctx context.Context) ([]string, error)
	Source    Source
	Poster    Poster
	Logger    *log.Logger
	Now       func() time.Time
	Interval  time.Duration
	// RequestTimeout bounds one read, and one push with its retries.
	RequestTimeout time.Duration
}

Config is New's input. Zero durations take the defaults.

type Failover

type Failover struct {
	From, To string
	At       time.Time
}

Failover is one move of an instance from one pool account to another (internal/ccfailover's record: an agent's account changes ONLY by a failover, and every failover is recorded).

type Poster

type Poster interface {
	Put(ctx context.Context, r Report) error
}

Poster is the HQ side (*Sender).

type Reading

type Reading struct {
	// Account is the pool account the instance is on now.
	Account string
	// Failovers are the instance's account moves (any order), from which each
	// hour's account is told (AccountAt).
	Failovers []Failover
	Buckets   []cctranscript.UsageBucket
}

Reading is one instance's usage as its Source read it.

type RefusedError

type RefusedError struct{ Status int }

RefusedError is HQ refusing a push (a 4xx, or a redirect, which is never followed). It is not retried: the same push would be refused again.

func (*RefusedError) Error

func (e *RefusedError) Error() string

type Report

type Report struct {
	// Instance is the muster's label (MUSTER_CC_USAGE_PUSH_INSTANCE, as the
	// pool push's source_instance).
	Instance string `json:"instance"`
	Consumer string `json:"consumer"`
	Hours    []Row  `json:"hours"`
}

Report is one push's body. Hours is never null.

func Batches

func Batches(instance, consumer string, rows []Row) []Report

Batches splits rows, in order, into the reports of instance and consumer that HQ takes: each at most MaxRows rows and MaxBody bytes encoded. HQ upserts each row on its own key, so pushing the window in several reports is the same as pushing it in one.

type Row

type Row struct {
	// Hour is the UTC hour, RFC 3339, on the hour.
	Hour string `json:"hour"`
	// Account is the pool account the instance was on at the END of the hour
	// (AccountAt).
	Account             string `json:"account"`
	Session             string `json:"session"`
	Turns               int64  `json:"turns"`
	APICalls            int64  `json:"api_calls"`
	InputTokens         int64  `json:"input_tokens"`
	OutputTokens        int64  `json:"output_tokens"`
	CacheReadTokens     int64  `json:"cache_read_tokens"`
	CacheCreationTokens int64  `json:"cache_creation_tokens"`
}

Row is one (session, hour) of one instance on the wire, in the contract's field order.

func Rows

func Rows(buckets []cctranscript.UsageBucket, current string, failovers []Failover) (rows []Row, invalid int)

Rows is buckets as contract rows, each attributed by AccountAt: sorted by hour then session. A bucket whose session HQ would refuse, whose hour is not on the hour, or whose account is empty is left out and counted in invalid.

type Sender

type Sender struct {
	URL, Token string
	Client     *http.Client
	// Backoff is the wait before each retry of a 5xx or an unanswered push;
	// nil is DefaultBackoff, empty (non-nil) is no retry.
	Backoff []time.Duration
	// Sleep waits d or until ctx ends (production: a timer); a test records.
	Sleep func(ctx context.Context, d time.Duration) error
}

Sender PUTs a Report to URL with Token as a bearer.

🔴 THE TOKEN IS IN ONE HEADER AND NOWHERE ELSE: no error carries the URL, the body or HQ's answer, and a redirect is never followed (it would re-send the bearer elsewhere).

func (*Sender) Put

func (s *Sender) Put(ctx context.Context, r Report) error

Put sends r: nil on a 2xx; *RefusedError on a 4xx or a redirect, at once; *UnavailableError once a 5xx or an unanswered attempt has been retried after each Backoff wait (or ctx ended during one).

type Source

type Source interface {
	Read(ctx context.Context, instance string, since time.Time) (Reading, error)
}

Source reads instance's usage since since (production: its ccd's GET /v1/usage through the agent gateway, and its failover history). An image without the route is ErrUnsupported.

type UnavailableError

type UnavailableError struct {
	Status   int
	Attempts int
}

UnavailableError is HQ not taking a push after every retry: a 5xx (Status), or no answer (Status 0: a transport error or a timeout).

func (*UnavailableError) Error

func (e *UnavailableError) Error() string

Jump to

Keyboard shortcuts

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