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
- Variables
- func AccountAt(current string, failovers []Failover, hour time.Time) string
- func URLFromPoolPush(poolURL string) (string, error)
- func ValidConsumer(c string) bool
- type Collector
- type Config
- type Failover
- type Poster
- type Reading
- type RefusedError
- type Report
- type Row
- type Sender
- type Source
- type UnavailableError
Constants ¶
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 )
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.
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.
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 ¶
var Consumers = []string{ConsumerPRReview}
Consumers is every consumer, in the order a refusal names them.
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.
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.
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 ¶
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 ¶
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 ¶
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 (*Collector) Flush ¶
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.
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 ¶
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 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.
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).
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 {
}
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