cli: carlos usage, an app's bytes per instance this month
Reads the console's usage route and prints bytes and requests per instance for a UTC month (approved copy A-E), or the route's body with --json. A month before counting started prints the start line and exits 0. Reads up to 8 MiB through the new getJSONLimit; an answer past the limit is an error, never a truncated print. The 1 MiB getJSON path now shares that one reader.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+783
−3
apimode.go+24 −1approved_usage_copy_test.go+149 −0commands.go+1 −0docs/parity.md+11 −2docs/site/cli.md+26 −0parity/cli.tsv+1 −0parity/packages.tsv+1 −0parity/parity.tsv+1 −0usage_cmd.go+261 −0usage_cmd_test.go+308 −0
diff --git a/apimode.go b/apimode.go| index 09366515f..92b076beb 100644 |
| --- a/apimode.go |
| +++ b/apimode.go |
| @@ -799,6 +799,26 @@ func (s *apiSession) getJSON(ctx context.Context, path string) (int, []byte, err |
| // getJSONHeader is getJSON that also hands back the response headers, for |
| // the caller that reads one (Retry-After). |
| func (s *apiSession) getJSONHeader(ctx context.Context, path string) (int, http.Header, []byte, error) { |
| + return s.getJSONHeaderLimit(ctx, path, getJSONDefaultLimit) |
| +} |
| + |
| +// getJSONDefaultLimit is how much of an answer getJSON reads. |
| +const getJSONDefaultLimit = 1 << 20 |
| + |
| +// errResponseTooLarge is an answer longer than the caller's limit: never a |
| +// truncated body handed back as if it were whole. |
| +var errResponseTooLarge = errors.New("the console's answer is larger than this command reads") |
| + |
| +// getJSONLimit is getJSON for an answer that can pass 1 MiB: it reads at |
| +// most limit bytes and fails with errResponseTooLarge past them. |
| +func (s *apiSession) getJSONLimit(ctx context.Context, path string, limit int64) (int, []byte, error) { |
| + status, _, body, err := s.getJSONHeaderLimit(ctx, path, limit) |
| + return status, body, err |
| +} |
| + |
| +// getJSONHeaderLimit is the one GET reader: it reads limit+1 bytes so an |
| +// answer of exactly limit bytes is whole and one byte more is an error. |
| +func (s *apiSession) getJSONHeaderLimit(ctx context.Context, path string, limit int64) (int, http.Header, []byte, error) { |
| req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.c.base+path, nil) |
| if err != nil { |
| return 0, nil, nil, err |
| @@ -814,10 +834,13 @@ func (s *apiSession) getJSONHeader(ctx context.Context, path string) (int, http. |
| if merr := consoleMoved(s.c.base, res.StatusCode, res.Header.Get("Location")); merr != nil { |
| return res.StatusCode, res.Header, nil, offerConsoleMoved(merr) |
| } |
| - body, err := io.ReadAll(io.LimitReader(res.Body, 1<<20)) |
| + body, err := io.ReadAll(io.LimitReader(res.Body, limit+1)) |
| if err != nil { |
| return res.StatusCode, res.Header, nil, err |
| } |
| + if int64(len(body)) > limit { |
| + return res.StatusCode, res.Header, nil, errResponseTooLarge |
| + } |
| return res.StatusCode, res.Header, body, nil |
| } |
diff --git a/approved_usage_copy_test.go b/approved_usage_copy_test.go| new file mode 100644 |
| index 000000000..38d9beb46 |
| --- /dev/null |
| +++ b/approved_usage_copy_test.go |
| @@ -0,0 +1,149 @@ |
| +// approved_usage_copy_test.go |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "os" |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// The copy gate of `carlos usage` (instance usage plan Task 7). The approved |
| +// strings live in docs/superpowers/notes/instance-usage-copy.md; each test |
| +// here reads that file and checks the code and the docs against it, so a |
| +// change on either side fails until the other follows. |
| +const usageCopyPath = "docs/superpowers/notes/instance-usage-copy.md" |
| + |
| +// usageCopySection is the first fenced block under heading (a "## X." prefix). |
| +func usageCopySection(t *testing.T, heading string) string { |
| + t.Helper() |
| + raw, err := os.ReadFile(usageCopyPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, rest, ok := strings.Cut(string(raw), "\n## "+heading) |
| + if !ok { |
| + t.Fatalf("%s has no section %q", usageCopyPath, heading) |
| + } |
| + _, rest, ok = strings.Cut(rest, "\n```") |
| + if !ok { |
| + t.Fatalf("section %q has no fenced block", heading) |
| + } |
| + _, rest, _ = strings.Cut(rest, "\n") |
| + block, _, ok := strings.Cut(rest, "```") |
| + if !ok { |
| + t.Fatalf("section %q has an unclosed block", heading) |
| + } |
| + return block |
| +} |
| + |
| +func TestApprovedUsageHelp(t *testing.T) { |
| + if got, want := usageUsage, usageCopySection(t, "E. CLI usage text"); got != want { |
| + t.Fatalf("usageUsage = %q, want %q", got, want) |
| + } |
| + if usageMonthHelp != "month to show, YYYY-MM (default: this month)" || usageJSONHelp != "print the API's answer as JSON" { |
| + t.Fatalf("flag help = %q, %q", usageMonthHelp, usageJSONHelp) |
| + } |
| +} |
| + |
| +func TestApprovedUsageLines(t *testing.T) { |
| + var buf bytes.Buffer |
| + if err := printUsageStart(&buf, "2027-01"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, want := buf.String(), usageCopySection(t, "D. A month before counting started"); got != want { |
| + t.Fatalf("copy D = %q, want %q", got, want) |
| + } |
| + |
| + empty := usageAnswer{App: "patrix-sites", Month: "2027-01", From: "2027-01-01T00:00:00Z", To: "2027-02-01T00:00:00Z", ReadAt: "2027-01-14T13:05:00Z"} |
| + now := time.Date(2027, 1, 14, 13, 6, 0, 0, time.UTC) |
| + buf.Reset() |
| + if err := printUsage(&buf, empty, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, want := buf.String(), usageCopySection(t, "C. No traffic counted"); got != want { |
| + t.Fatalf("copy C = %q, want %q", got, want) |
| + } |
| + |
| + // Copy A and B: the headline, the caveat line and the table header. |
| + full := usageAnswer{App: "patrix-sites", Month: "2027-01", From: "2027-01-01T00:00:00Z", To: "2027-02-01T00:00:00Z", |
| + Instances: []usageInstance{{Host: "alpha.patrix.site", BytesOut: 15245075046, Requests: 1204331}, |
| + {Host: "beta.patrix.site", BytesOut: 327155712, Requests: 40112}}, |
| + Unattributed: usageTotals{BytesOut: 1, Requests: 1}, |
| + Total: usageTotals{BytesOut: 15573384192, Requests: 1244531}, ReadAt: "2027-01-14T13:05:30Z"} |
| + buf.Reset() |
| + if err := printUsage(&buf, full, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + a := usageCopySection(t, "A. Human output, current month") |
| + for _, line := range strings.Split(a, "\n")[:2] { |
| + if !strings.Contains(buf.String(), line+"\n") { |
| + t.Errorf("copy A line %q is not in the output:\n%s", line, buf.String()) |
| + } |
| + } |
| + if !strings.Contains(buf.String(), " Instance Sent Requests\n") || |
| + !strings.Contains(buf.String(), " Not tied to an instance ") { |
| + t.Errorf("copy A table header or unattributed row missing:\n%s", buf.String()) |
| + } |
| + |
| + past := full |
| + past.Month, past.From, past.To = "2026-12", "2026-12-01T00:00:00Z", "2027-01-01T00:00:00Z" |
| + past.Total = usageTotals{BytesOut: 10523451801, Requests: 802114} |
| + buf.Reset() |
| + if err := printUsage(&buf, past, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + b := usageCopySection(t, "B. Human output, a past month") |
| + if !strings.HasPrefix(buf.String(), b) { |
| + t.Fatalf("copy B = %q, want it to start with %q", buf.String(), b) |
| + } |
| +} |
| + |
| +func TestApprovedUsageDocsSection(t *testing.T) { |
| + want := usageCopySection(t, "H. Docs section") |
| + // The two indented examples become ```sh fences in docs/site/cli.md. |
| + cli, err := os.ReadFile("docs/site/cli.md") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + _, got, ok := strings.Cut(string(cli), "### carlos usage\n") |
| + if !ok { |
| + t.Fatal("docs/site/cli.md has no ### carlos usage") |
| + } |
| + got, _, _ = strings.Cut(got, "\n### ") |
| + got = "### carlos usage\n" + got |
| + // Reduce both to their prose lines: drop blank lines, indented examples |
| + // and fence lines, and compare the examples apart. |
| + prose := func(s string) (text string, examples []string) { |
| + var lines []string |
| + for _, l := range strings.Split(s, "\n") { |
| + switch { |
| + case strings.TrimSpace(l) == "" || strings.HasPrefix(l, "```"): |
| + case strings.HasPrefix(l, " "): |
| + examples = append(examples, strings.TrimSpace(l)) |
| + case strings.HasPrefix(l, "carlos usage") || strings.HasPrefix(l, "carlos services"): |
| + examples = append(examples, l) |
| + default: |
| + lines = append(lines, l) |
| + } |
| + } |
| + return strings.Join(lines, "\n"), examples |
| + } |
| + wt, we := prose(want) |
| + gt, ge := prose(got) |
| + if wt != gt { |
| + t.Fatalf("docs prose:\n%s\nwant:\n%s", gt, wt) |
| + } |
| + if strings.Join(we, "\n") != strings.Join(ge, "\n") { |
| + t.Fatalf("docs examples = %q, want %q", ge, we) |
| + } |
| +} |
| + |
| +func TestUsageCopyHasNoEmDash(t *testing.T) { |
| + for name, s := range map[string]string{"usageUsage": usageUsage, "needs console": usageNeedsConsole, "bad month": usageBadMonth} { |
| + if strings.ContainsRune(s, '—') { |
| + t.Errorf("%s has an em dash", name) |
| + } |
| + } |
| +} |
diff --git a/commands.go b/commands.go| index b9647ee97..20777fdfc 100644 |
| --- a/commands.go |
| +++ b/commands.go |
| @@ -163,6 +163,7 @@ func buildCommandRoot() *clireg.Node { |
| raw("geo", cust, runGeo), |
| raw("explain", cust, runExplain), |
| raw("analytics", cust, runAnalytics), |
| + rawErr("usage", cust, runUsage), |
| raw("protection", cust, runProtection), |
| channelsCommand(), |
| pipelineCommand(), |
diff --git a/docs/parity.md b/docs/parity.md| index fbb542482..b79642b5d 100644 |
| --- a/docs/parity.md |
| +++ b/docs/parity.md |
| @@ -12,10 +12,10 @@ CLI rows are checked against the command registry (`parity/cli.tsv`). |
| |---|---:| |
| | both | 48 | |
| | partial | 9 | |
| -| gap | 69 | |
| +| gap | 70 | |
| | cli-only | 21 | |
| | console-only | 19 | |
| -| Total | 166 | |
| +| Total | 167 | |
| ## account |
| @@ -182,6 +182,7 @@ CLI rows are checked against the command registry (`parity/cli.tsv`). |
| | analytics | both | `analytics` | `GET /a/{sqid}/apps/{app}/analytics`<br>`POST /a/{sqid}/apps/{app}/analytics/setting` | | | |
| | analytics-live | console-only | | `GET /a/{sqid}/apps/{app}/analytics/live` | | A live view that updates in the page. | |
| | protection | both | `protection` | `GET /a/{sqid}/apps/{app}/protection`<br>`POST /a/{sqid}/apps/{app}/protection/setting` | | | |
| +| usage | gap | `usage` | | [wp-instance-usage](#wp-instance-usage) | Bytes per instance; a console view is later. | |
| | protection-events | gap | | `GET /a/{sqid}/apps/{app}/protection`<br>`GET /a/{sqid}/apps/{app}/protection/data` | [wp-cli-verbs](#wp-cli-verbs) | What the guard did; the CLI shows only the mode. | |
| | activity | gap | | `GET /a/{sqid}/apps/{app}/activity` | [wp-cli-verbs](#wp-cli-verbs) | The audit trail; logs has platform events, not this. | |
| | geo | gap | `geo` | | [wp-settings](#wp-settings) | | |
| @@ -414,6 +415,14 @@ Discussion #1289. |
| - `platform-customers-list` (platform), CLI has `platform customers list`, `platform customers show` |
| +<a id="wp-instance-usage"></a> |
| + |
| +### wp-instance-usage: Usage by instance in the console |
| + |
| +No discussion filed yet. |
| + |
| +- `usage` (observe), CLI has `usage` |
| + |
| ## Outside customer parity |
| ### operator |
diff --git a/docs/site/cli.md b/docs/site/cli.md| index eb2bb5504..6bf87787a 100644 |
| --- a/docs/site/cli.md |
| +++ b/docs/site/cli.md |
| @@ -2209,6 +2209,32 @@ When the deployment has a GeoIP database, page views are also counted by |
| country. A visitor the database could not place counts as `unknown`. The |
| Analytics tab credits the database the counts came from. |
| +### carlos usage |
| + |
| +Bytes sent and requests served by each instance of an app, for one UTC |
| +month, counted at the edge as it serves the app. |
| + |
| +```sh |
| +carlos usage --app shop |
| +carlos usage --app shop --month 2027-01 --json |
| +``` |
| + |
| +The figures are what has been counted so far: they can be lower than what |
| +was served, never higher. A response that crosses midnight counts in the |
| +hour it finished. Bytes the edge cannot tie to one instance, such as some |
| +cached files served under a custom domain, are shown on their own line |
| +and never charged to an instance. |
| + |
| +To give a server read-only access to these figures and nothing else, mint |
| +a usage credential bound to the app: |
| + |
| +```sh |
| +carlos services create --role usage --app shop shop-usage |
| +``` |
| + |
| +Counting by instance starts at the beginning of the month after the |
| +console turns it on; earlier months are refused. |
| + |
| ### Headers your app receives |
| On a deployment with a GeoIP database, every request the edge passes to your |
diff --git a/parity/cli.tsv b/parity/cli.tsv| index 0c19e4936..74c1eff71 100644 |
| --- a/parity/cli.tsv |
| +++ b/parity/cli.tsv |
| @@ -350,6 +350,7 @@ system shares stop operator - - - - - |
| system status operator - - - - - |
| system update operator - - - - - |
| update customer - - - - - |
| +usage customer - - - - - |
| version customer - - - - - |
| version target customer - - - - - |
| vet customer - - - - - |
diff --git a/parity/packages.tsv b/parity/packages.tsv| index 20bdfa0b3..4dfd45067 100644 |
| --- a/parity/packages.tsv |
| +++ b/parity/packages.tsv |
| @@ -11,3 +11,4 @@ wp-db-run Database query and pull, non-interactive run, and door keys in the con |
| wp-terminal A browser terminal for run -it and console 741 |
| wp-import Instance import through the console 742 |
| wp-platform-customers The platform account's Customers section (platform accounts slice 3) 1289 |
| +wp-instance-usage Usage by instance in the console |
diff --git a/parity/parity.tsv b/parity/parity.tsv| index b6c9913a9..083e3e273 100644 |
| --- a/parity/parity.tsv |
| +++ b/parity/parity.tsv |
| @@ -105,6 +105,7 @@ availability observe both availability GET /a/{sqid}/apps/{app}/availability |
| analytics observe both analytics GET /a/{sqid}/apps/{app}/analytics ; POST /a/{sqid}/apps/{app}/analytics/setting |
| analytics-live observe console-only GET /a/{sqid}/apps/{app}/analytics/live A live view that updates in the page. |
| protection observe both protection GET /a/{sqid}/apps/{app}/protection ; POST /a/{sqid}/apps/{app}/protection/setting |
| +usage observe gap usage wp-instance-usage Bytes per instance; a console view is later. |
| protection-events observe gap GET /a/{sqid}/apps/{app}/protection ; GET /a/{sqid}/apps/{app}/protection/data wp-cli-verbs What the guard did; the CLI shows only the mode. |
| activity observe gap GET /a/{sqid}/apps/{app}/activity wp-cli-verbs The audit trail; logs has platform events, not this. |
| geo observe gap geo wp-settings |
diff --git a/usage_cmd.go b/usage_cmd.go| new file mode 100644 |
| index 000000000..e35632638 |
| --- /dev/null |
| +++ b/usage_cmd.go |
| @@ -0,0 +1,261 @@ |
| +// `carlos usage` — an app's bytes sent and requests served per instance for |
| +// one UTC month, read from the console's usage route. API mode only. |
| +package main |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "flag" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "net/url" |
| + "os" |
| + "strconv" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// The approved copy (docs/superpowers/notes/instance-usage-copy.md §E). |
| +const usageUsage = `usage: carlos usage --app <a> [flags] |
| + |
| +Bytes sent and requests served by each instance of an app in one UTC |
| +month, counted at the edge. Figures are what has been counted so far, so |
| +they can be lower than what was served but never higher. |
| + |
| +--month is YYYY-MM and defaults to this month. --json prints the answer |
| +as the API returns it. |
| +` |
| + |
| +const ( |
| + usageMonthHelp = "month to show, YYYY-MM (default: this month)" |
| + usageJSONHelp = "print the API's answer as JSON" |
| + |
| + usageNeedsConsole = "carlos usage needs a console. unset CARLOS_DEPLOYMENT_BUCKET and CARLOS_DEPLOYMENT_DIR, then set CARLOS_CONSOLE or run carlos login" |
| + usageNeedsApp = "carlos usage needs --app" |
| + usageBadMonth = "--month: want YYYY-MM, such as 2027-01" |
| +) |
| + |
| +// usageResponseLimit is the most bytes of an answer carlos usage reads: the |
| +// route's cap of 10,000 instances with 253-character hosts is about 3 MB. |
| +const usageResponseLimit = 8 << 20 |
| + |
| +// usageClock is the clock that decides which month is "this month". |
| +var usageClock = time.Now |
| + |
| +// usageAnswer is the route's 200 body (internal/console/apiusage.go). |
| +type usageAnswer struct { |
| + App string `json:"app"` |
| + Month string `json:"month"` |
| + From string `json:"from"` |
| + To string `json:"to"` |
| + Instances []usageInstance `json:"instances"` |
| + Unattributed usageTotals `json:"unattributed"` |
| + Total usageTotals `json:"total"` |
| + ReadAt string `json:"read_at"` |
| +} |
| + |
| +type usageInstance struct { |
| + Host string `json:"host"` |
| + BytesOut int64 `json:"bytes_out"` |
| + Requests int64 `json:"requests"` |
| +} |
| + |
| +type usageTotals struct { |
| + BytesOut int64 `json:"bytes_out"` |
| + Requests int64 `json:"requests"` |
| +} |
| + |
| +// runUsage is `carlos usage --app <a> [--month YYYY-MM] [--json]`. |
| +func runUsage(args []string) error { |
| + fs := flag.NewFlagSet("usage", flag.ContinueOnError) |
| + app := appFlag(fs, "app whose usage to read") |
| + month := fs.String("month", "", usageMonthHelp) |
| + asJSON := fs.Bool("json", false, usageJSONHelp) |
| + acctRaw, acctIDRaw, _ := accountFlags(fs) |
| + consoleFlag := consoleOption(fs, "console to read through (default: the only logged-in one)") |
| + fs.Usage = flagUsage(fs, usageUsage) |
| + if err := fs.Parse(args); err != nil { |
| + if errors.Is(err, flag.ErrHelp) { |
| + return nil |
| + } |
| + // The flag set has printed the problem and the usage already. |
| + return exitCode(2) |
| + } |
| + name := strings.TrimSpace(*app) |
| + if name == "" || fs.NArg() != 0 { |
| + fs.Usage() |
| + return exitCode(2) |
| + } |
| + if *month != "" && !validUsageMonth(*month) { |
| + return errors.New(usageBadMonth) |
| + } |
| + |
| + sess, err := resolveMode(*consoleFlag) |
| + if err != nil { |
| + return err |
| + } |
| + if sess == nil { |
| + return errors.New(usageNeedsConsole) |
| + } |
| + ctx := context.Background() |
| + acct := apiAccount(acctRaw, acctIDRaw) |
| + if acct.Seg == "" { |
| + // Its "account: ..." note is not part of the answer. |
| + orig := stdout |
| + stdout = os.Stderr |
| + acct, err = sess.defaultAccount(ctx) |
| + stdout = orig |
| + if err != nil { |
| + return err |
| + } |
| + } |
| + |
| + tail := "/usage" |
| + if *month != "" { |
| + tail += "?month=" + url.QueryEscape(*month) |
| + } |
| + status, body, err := sess.getJSONLimit(ctx, apiPath(acct, name, tail), usageResponseLimit) |
| + if err != nil { |
| + return err |
| + } |
| + if status == http.StatusConflict { |
| + var e struct { |
| + FirstMonth string `json:"first_month"` |
| + } |
| + if json.Unmarshal(body, &e) == nil && e.FirstMonth != "" { |
| + if *asJSON { |
| + return writeUsageBody(stdout, body) |
| + } |
| + return printUsageStart(stdout, e.FirstMonth) |
| + } |
| + } |
| + if status < 200 || status > 299 { |
| + return apiErrorFromBody(status, body) |
| + } |
| + if *asJSON { |
| + return writeUsageBody(stdout, body) |
| + } |
| + var ans usageAnswer |
| + if err := json.Unmarshal(body, &ans); err != nil { |
| + return fmt.Errorf("the console's usage answer does not parse: %w", err) |
| + } |
| + return printUsage(stdout, ans, usageClock().UTC()) |
| +} |
| + |
| +// validUsageMonth is the month flag's one form, YYYY-MM. |
| +func validUsageMonth(m string) bool { |
| + if len(m) != 7 { |
| + return false |
| + } |
| + _, err := time.Parse("2006-01", m) |
| + return err == nil |
| +} |
| + |
| +// writeUsageBody prints the route's body as received. |
| +func writeUsageBody(w io.Writer, body []byte) error { |
| + if _, err := w.Write(body); err != nil { |
| + return err |
| + } |
| + if len(body) == 0 || body[len(body)-1] != '\n' { |
| + _, err := io.WriteString(w, "\n") |
| + return err |
| + } |
| + return nil |
| +} |
| + |
| +// printUsageStart is copy D, from the 409's first_month (YYYY-MM). |
| +func printUsageStart(w io.Writer, firstMonth string) error { |
| + t, err := time.Parse("2006-01", firstMonth) |
| + if err != nil { |
| + return fmt.Errorf("the console's first_month %q is not YYYY-MM", firstMonth) |
| + } |
| + _, err = fmt.Fprintf(w, "Counting by instance starts on %s.\n", t.Format("2 January 2006")) |
| + return err |
| +} |
| + |
| +// printUsage renders copy A, B or C (§A-C): the state first, one line of |
| +// caveat, the table, the instance count. |
| +func printUsage(w io.Writer, a usageAnswer, now time.Time) error { |
| + from, err := time.Parse(time.RFC3339, a.From) |
| + if err != nil { |
| + return fmt.Errorf("the console's usage answer has no month start: %w", err) |
| + } |
| + to, err := time.Parse(time.RFC3339, a.To) |
| + if err != nil { |
| + return fmt.Errorf("the console's usage answer has no month end: %w", err) |
| + } |
| + readAt, err := time.Parse(time.RFC3339, a.ReadAt) |
| + if err != nil { |
| + return fmt.Errorf("the console's usage answer has no read time: %w", err) |
| + } |
| + from, to, readAt = from.UTC(), to.UTC(), readAt.UTC() |
| + current := a.Month == now.Format("2006-01") |
| + label := a.App + ", " + from.Format("January 2006") |
| + if current { |
| + label += " so far" |
| + } |
| + |
| + var b strings.Builder |
| + if len(a.Instances) == 0 && a.Unattributed.BytesOut == 0 && a.Unattributed.Requests == 0 { |
| + b.WriteString(label + ": nothing counted yet\n") |
| + _, err := io.WriteString(w, b.String()) |
| + return err |
| + } |
| + b.WriteString(fmt.Sprintf("%s: %s sent, %s requests\n", label, usageBytes(a.Total.BytesOut), commas(a.Total.Requests))) |
| + upTo := readAt |
| + if !current { |
| + if last := to.Add(-time.Minute); last.Before(readAt) { |
| + upTo = last |
| + } |
| + } |
| + b.WriteString("Counted up to " + upTo.Format("2 Jan 15:04") + " UTC. Traffic not yet counted is not shown.\n\n") |
| + |
| + type row struct{ name, sent, reqs string } |
| + var rows []row |
| + for _, in := range a.Instances { |
| + rows = append(rows, row{in.Host, usageBytes(in.BytesOut), commas(in.Requests)}) |
| + } |
| + if a.Unattributed.BytesOut != 0 || a.Unattributed.Requests != 0 { |
| + rows = append(rows, row{"Not tied to an instance", usageBytes(a.Unattributed.BytesOut), commas(a.Unattributed.Requests)}) |
| + } |
| + nameW, sentW, reqW := 25, len("Sent")+2, len("Requests") |
| + for _, r := range rows { |
| + nameW = max(nameW, len(r.name)+2) |
| + sentW = max(sentW, len(r.sent)+2) |
| + reqW = max(reqW, len(r.reqs)) |
| + } |
| + b.WriteString(strings.TrimRight(fmt.Sprintf(" %-*s%-*s%-*s", nameW, "Instance", sentW, "Sent", reqW, "Requests"), " ") + "\n") |
| + for _, r := range rows { |
| + b.WriteString(fmt.Sprintf(" %-*s%-*s%*s\n", nameW, r.name, sentW, r.sent, reqW, r.reqs)) |
| + } |
| + n := len(a.Instances) |
| + noun := "instances" |
| + if n == 1 { |
| + noun = "instance" |
| + } |
| + b.WriteString(fmt.Sprintf("\n %d %s\n", n, noun)) |
| + _, err = io.WriteString(w, b.String()) |
| + return err |
| +} |
| + |
| +func usageBytes(n int64) string { return humanBytes(&n) } |
| + |
| +// commas writes n with a comma between each group of three digits. |
| +func commas(n int64) string { |
| + s := strconv.FormatInt(n, 10) |
| + neg := strings.HasPrefix(s, "-") |
| + s = strings.TrimPrefix(s, "-") |
| + var out []byte |
| + for i := range len(s) { |
| + if i > 0 && (len(s)-i)%3 == 0 { |
| + out = append(out, ',') |
| + } |
| + out = append(out, s[i]) |
| + } |
| + if neg { |
| + return "-" + string(out) |
| + } |
| + return string(out) |
| +} |
diff --git a/usage_cmd_test.go b/usage_cmd_test.go| new file mode 100644 |
| index 000000000..d07054702 |
| --- /dev/null |
| +++ b/usage_cmd_test.go |
| @@ -0,0 +1,308 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// usageFake is a console that answers every request for /usage with one |
| +// status and body, and counts the requests it saw. |
| +type usageFake struct { |
| + hits atomic.Int32 |
| + query atomic.Value // the last raw query |
| +} |
| + |
| +func newUsageFake(t *testing.T, status int, body []byte) *usageFake { |
| + t.Helper() |
| + f := &usageFake{} |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + f.hits.Add(1) |
| + f.query.Store(r.URL.RawQuery) |
| + w.Header().Set("Content-Type", "application/json") |
| + w.WriteHeader(status) |
| + w.Write(body) |
| + })) |
| + t.Cleanup(srv.Close) |
| + clearDeploymentEnv(t) |
| + useTempCredentials(t) |
| + t.Setenv("CARLOS_CONSOLE", srv.URL) |
| + t.Setenv("CARLOS_SERVICE_TOKEN", "tok") |
| + return f |
| +} |
| + |
| +func usageNow(t *testing.T, s string) { |
| + t.Helper() |
| + at, err := time.Parse(time.RFC3339, s) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + orig := usageClock |
| + usageClock = func() time.Time { return at } |
| + t.Cleanup(func() { usageClock = orig }) |
| +} |
| + |
| +const usageJanBody = `{"app":"patrix-sites","month":"2027-01","from":"2027-01-01T00:00:00Z","to":"2027-02-01T00:00:00Z",` + |
| + `"instances":[{"host":"alpha.patrix.site","bytes_out":15245075046,"requests":1204331},` + |
| + `{"host":"beta.patrix.site","bytes_out":327155712,"requests":40112}],` + |
| + `"unattributed":{"bytes_out":1153434,"requests":88},` + |
| + `"total":{"bytes_out":15573384192,"requests":1244531},"read_at":"2027-01-14T13:05:30Z"}` + "\n" |
| + |
| +func TestUsageHumanOutput(t *testing.T) { |
| + newUsageFake(t, 200, []byte(usageJanBody)) |
| + usageNow(t, "2027-01-14T13:06:00Z") |
| + buf := captureStdout(t) |
| + if err := runUsage([]string{"--app", "patrix-sites", "--account", "ops"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + want := "patrix-sites, January 2027 so far: 14.5GB sent, 1,244,531 requests\n" + |
| + "Counted up to 14 Jan 13:05 UTC. Traffic not yet counted is not shown.\n" + |
| + "\n" + |
| + " Instance Sent Requests\n" + |
| + " alpha.patrix.site 14.2GB 1,204,331\n" + |
| + " beta.patrix.site 312.0MB 40,112\n" + |
| + " Not tied to an instance 1.1MB 88\n" + |
| + "\n" + |
| + " 2 instances\n" |
| + if got := buf.String(); got != want { |
| + t.Fatalf("output:\n%s\nwant:\n%s", got, want) |
| + } |
| +} |
| + |
| +func TestUsagePastMonthAndOneInstance(t *testing.T) { |
| + body := `{"app":"patrix-sites","month":"2026-12","from":"2026-12-01T00:00:00Z","to":"2027-01-01T00:00:00Z",` + |
| + `"instances":[{"host":"alpha.patrix.site","bytes_out":10523451801,"requests":802114}],` + |
| + `"unattributed":{"bytes_out":0,"requests":0},"total":{"bytes_out":10523451801,"requests":802114},"read_at":"2027-01-14T13:05:30Z"}` |
| + f := newUsageFake(t, 200, []byte(body)) |
| + usageNow(t, "2027-01-14T13:06:00Z") |
| + buf := captureStdout(t) |
| + if err := runUsage([]string{"--app", "patrix-sites", "--account", "ops", "--month", "2026-12"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if q, _ := f.query.Load().(string); q != "month=2026-12" { |
| + t.Fatalf("query = %q", q) |
| + } |
| + got := buf.String() |
| + for _, want := range []string{ |
| + "patrix-sites, December 2026: 9.8GB sent, 802,114 requests\n", |
| + "Counted up to 31 Dec 23:59 UTC. Traffic not yet counted is not shown.\n", |
| + "\n 1 instance\n", |
| + } { |
| + if !strings.Contains(got, want) { |
| + t.Fatalf("output %q lacks %q", got, want) |
| + } |
| + } |
| + if strings.Contains(got, "Not tied") { |
| + t.Fatalf("output has an unattributed row with none counted:\n%s", got) |
| + } |
| +} |
| + |
| +func TestUsageNothingCounted(t *testing.T) { |
| + body := `{"app":"patrix-sites","month":"2027-01","from":"2027-01-01T00:00:00Z","to":"2027-02-01T00:00:00Z",` + |
| + `"instances":[],"unattributed":{"bytes_out":0,"requests":0},"total":{"bytes_out":0,"requests":0},"read_at":"2027-01-02T00:00:00Z"}` |
| + newUsageFake(t, 200, []byte(body)) |
| + usageNow(t, "2027-01-02T00:01:00Z") |
| + buf := captureStdout(t) |
| + if err := runUsage([]string{"--app", "patrix-sites", "--account", "ops"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if want := "patrix-sites, January 2027 so far: nothing counted yet\n"; buf.String() != want { |
| + t.Fatalf("output = %q, want %q", buf.String(), want) |
| + } |
| +} |
| + |
| +func TestUsageJSONPassThrough(t *testing.T) { |
| + newUsageFake(t, 200, []byte(usageJanBody)) |
| + buf := captureStdout(t) |
| + if err := runUsage([]string{"--app", "patrix-sites", "--account", "ops", "--json"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if buf.String() != usageJanBody { |
| + t.Fatalf("--json = %q, want the body as received", buf.String()) |
| + } |
| +} |
| + |
| +func TestUsageBeforeStart(t *testing.T) { |
| + newUsageFake(t, 409, []byte(`{"error":"Counting by instance starts on 1 January 2027. Ask for 2027-01 or later.","first_month":"2027-01"}`)) |
| + buf := captureStdout(t) |
| + if err := runUsage([]string{"--app", "patrix-sites", "--account", "ops", "--month", "2026-11"}); err != nil { |
| + t.Fatalf("a month before counting is not an error: %v", err) |
| + } |
| + if want := "Counting by instance starts on 1 January 2027.\n"; buf.String() != want { |
| + t.Fatalf("output = %q, want %q", buf.String(), want) |
| + } |
| +} |
| + |
| +func TestUsageRouteErrorIsReturned(t *testing.T) { |
| + newUsageFake(t, 503, []byte(`{"error":"The console is still checking its hostname history. Try again in a minute."}`)) |
| + captureStdout(t) |
| + err := runUsage([]string{"--app", "patrix-sites", "--account", "ops"}) |
| + if err == nil || err.Error() != "The console is still checking its hostname history. Try again in a minute." { |
| + t.Fatalf("err = %v", err) |
| + } |
| +} |
| + |
| +func TestUsageRefusesBadMonth(t *testing.T) { |
| + f := newUsageFake(t, 200, []byte(usageJanBody)) |
| + captureStdout(t) |
| + for _, m := range []string{"2027-1", "2027-13", "january", "2027-01-01"} { |
| + if err := runUsage([]string{"--app", "a", "--account", "ops", "--month", m}); err == nil { |
| + t.Fatalf("--month %q was accepted", m) |
| + } |
| + } |
| + if n := f.hits.Load(); n != 0 { |
| + t.Fatalf("%d requests went out for a bad month", n) |
| + } |
| +} |
| + |
| +func TestUsageErrorsReturn(t *testing.T) { |
| + captureStdout(t) |
| + t.Run("no app", func(t *testing.T) { |
| + newUsageFake(t, 200, nil) |
| + var ee *exitError |
| + if err := runUsage([]string{"--account", "ops"}); !errors.As(err, &ee) { |
| + t.Fatalf("err = %v, want an exit code", err) |
| + } |
| + }) |
| + t.Run("unknown flag", func(t *testing.T) { |
| + newUsageFake(t, 200, nil) |
| + if err := runUsage([]string{"--app", "a", "--nope"}); err == nil { |
| + t.Fatal("an unknown flag was accepted") |
| + } |
| + }) |
| + t.Run("no session", func(t *testing.T) { |
| + clearDeploymentEnv(t) |
| + useTempCredentials(t) |
| + t.Setenv("CARLOS_DEPLOYMENT_DIR", t.TempDir()) |
| + if err := runUsage([]string{"--app", "a", "--account", "ops"}); err == nil { |
| + t.Fatal("direct mode was accepted") |
| + } |
| + }) |
| + t.Run("default account fails", func(t *testing.T) { |
| + f := newUsageFake(t, 500, []byte(`{"error":"memberships are down"}`)) |
| + err := runUsage([]string{"--app", "a"}) |
| + if err == nil { |
| + t.Fatal("a failed default account was accepted") |
| + } |
| + if f.hits.Load() == 0 { |
| + t.Fatal("the console was never asked for the account") |
| + } |
| + }) |
| +} |
| + |
| +// bigUsageBody is a valid answer with n instances on 253-character hosts. |
| +func bigUsageBody(n int) []byte { |
| + var b bytes.Buffer |
| + b.WriteString(`{"app":"a","month":"2027-01","from":"2027-01-01T00:00:00Z","to":"2027-02-01T00:00:00Z","instances":[`) |
| + suffix := strings.Repeat("x", 253-len("h00000.")-len(".io")) + ".io" |
| + for i := range n { |
| + if i > 0 { |
| + b.WriteString(",") |
| + } |
| + fmt.Fprintf(&b, `{"host":"h%05d.%s","bytes_out":%d,"requests":%d}`, i, suffix, i+1, i+1) |
| + } |
| + b.WriteString(`],"unattributed":{"bytes_out":0,"requests":0},"total":{"bytes_out":1,"requests":1},"read_at":"2027-01-14T13:05:30Z"}` + "\n") |
| + return b.Bytes() |
| +} |
| + |
| +func TestUsageLargeAnswer(t *testing.T) { |
| + big := bigUsageBody(10000) |
| + if len(big) <= 1<<20 { |
| + t.Fatalf("fixture is %d bytes, want over 1 MiB", len(big)) |
| + } |
| + newUsageFake(t, 200, big) |
| + usageNow(t, "2027-01-14T13:06:00Z") |
| + buf := captureStdout(t) |
| + if err := runUsage([]string{"--app", "a", "--account", "ops", "--json"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !bytes.Equal(buf.Bytes(), big) { |
| + t.Fatalf("--json printed %d bytes, want the %d received", buf.Len(), len(big)) |
| + } |
| + buf.Reset() |
| + if err := runUsage([]string{"--app", "a", "--account", "ops"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.HasSuffix(buf.String(), "\n 10000 instances\n") { |
| + t.Fatalf("human output ends %q", buf.String()[buf.Len()-40:]) |
| + } |
| + if !strings.Contains(buf.String(), "h09999.") { |
| + t.Fatal("the last instance is missing from the human output") |
| + } |
| +} |
| + |
| +func TestUsageOverLimitIsAnError(t *testing.T) { |
| + huge := bigUsageBody(30000) |
| + if len(huge) <= usageResponseLimit { |
| + t.Fatalf("fixture is %d bytes, want over %d", len(huge), usageResponseLimit) |
| + } |
| + newUsageFake(t, 200, huge) |
| + buf := captureStdout(t) |
| + for _, extra := range [][]string{nil, {"--json"}} { |
| + buf.Reset() |
| + err := runUsage(append([]string{"--app", "a", "--account", "ops"}, extra...)) |
| + if !errors.Is(err, errResponseTooLarge) { |
| + t.Fatalf("err = %v, want errResponseTooLarge", err) |
| + } |
| + if buf.Len() != 0 { |
| + t.Fatalf("printed %d bytes of an answer it could not read whole", buf.Len()) |
| + } |
| + } |
| +} |
| + |
| +func TestGetJSONLimitOverflow(t *testing.T) { |
| + const n = 100 |
| + for _, c := range []struct { |
| + size int |
| + ok bool |
| + }{{n - 1, true}, {n, true}, {n + 1, false}} { |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Write(bytes.Repeat([]byte("x"), c.size)) |
| + })) |
| + sess := &apiSession{c: newConsoleClient(srv.URL, "tok"), console: srv.URL} |
| + status, body, err := sess.getJSONLimit(context.Background(), "/x", n) |
| + srv.Close() |
| + if c.ok { |
| + if err != nil || status != 200 || len(body) != c.size { |
| + t.Fatalf("%d bytes at limit %d: status %d, %d bytes, err %v", c.size, n, status, len(body), err) |
| + } |
| + continue |
| + } |
| + if !errors.Is(err, errResponseTooLarge) || body != nil { |
| + t.Fatalf("%d bytes at limit %d: %d bytes, err %v, want errResponseTooLarge", c.size, n, len(body), err) |
| + } |
| + } |
| +} |
| + |
| +func TestUsageCommas(t *testing.T) { |
| + for n, want := range map[int64]string{0: "0", 88: "88", 999: "999", 1000: "1,000", 1244531: "1,244,531", 1000000: "1,000,000"} { |
| + if got := commas(n); got != want { |
| + t.Errorf("commas(%d) = %q, want %q", n, got, want) |
| + } |
| + } |
| +} |
| + |
| +func TestUsageWidensForLongHosts(t *testing.T) { |
| + host := strings.Repeat("a", 40) + ".example.com" |
| + a := usageAnswer{App: "a", Month: "2027-01", From: "2027-01-01T00:00:00Z", To: "2027-02-01T00:00:00Z", |
| + Instances: []usageInstance{{Host: host, BytesOut: 5, Requests: 7}}, ReadAt: "2027-01-02T00:00:00Z"} |
| + var buf bytes.Buffer |
| + now, _ := time.Parse(time.RFC3339, "2027-01-02T00:00:00Z") |
| + if err := printUsage(&buf, a, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + lines := strings.Split(buf.String(), "\n") |
| + if want := " " + host + " 5B"; !strings.HasPrefix(lines[4], " "+host+" 5B") { |
| + t.Fatalf("row = %q, want it to start with %q", lines[4], want) |
| + } |
| + if !strings.HasPrefix(lines[3], " Instance"+strings.Repeat(" ", len(host)+2-len("Instance"))+"Sent") { |
| + t.Fatalf("header = %q does not widen with the host", lines[3]) |
| + } |
| +} |