From 6f6cf7bcbd81b304c8d31beb64883430fc8de1b3 Mon Sep 17 00:00:00 2001 From: Robert Stam Date: Wed, 25 Nov 2026 14:40:46 +0000 Subject: [PATCH] feat(serverless): add usage command with the billed usage per space Co-Authored-By: Claude Opus 5.5 --- docs/reference/qcloud_serverless.md | 6 +- docs/reference/qcloud_serverless_usage.md | 72 +++++ internal/cmd/output/format.go | 24 ++ internal/cmd/output/money_test.go | 17 + internal/cmd/serverless/serverless.go | 7 +- internal/cmd/serverless/usage/usage.go | 328 +++++++++++++++++++ internal/cmd/serverless/usage/usage_test.go | 341 ++++++++++++++++++++ internal/qcloudapi/client.go | 8 + internal/testutil/fake_metering.go | 20 ++ internal/testutil/server.go | 5 + 10 files changed, 826 insertions(+), 2 deletions(-) create mode 100644 docs/reference/qcloud_serverless_usage.md create mode 100644 internal/cmd/serverless/usage/usage.go create mode 100644 internal/cmd/serverless/usage/usage_test.go create mode 100644 internal/testutil/fake_metering.go diff --git a/docs/reference/qcloud_serverless.md b/docs/reference/qcloud_serverless.md index f5d4963..c799941 100644 --- a/docs/reference/qcloud_serverless.md +++ b/docs/reference/qcloud_serverless.md @@ -11,7 +11,7 @@ A space is hosted in a single cloud region and scales its search workers automatically, so there are no nodes, packages or disks to size. Use the commands in this group to manage spaces together with their API keys and backups, to explore the regions spaces can be created in, and to inspect the -account's serverless quota. +account's serverless quota and billed usage. ### Examples @@ -22,6 +22,9 @@ qcloud serverless cloud-region list # Show how many spaces the account can still create qcloud serverless quota +# Show the billed serverless usage of the current month per space +qcloud serverless usage + # List all serverless spaces qcloud serverless space list @@ -54,4 +57,5 @@ qcloud serverless space create --cloud-region eu-central-1 --wait * [qcloud serverless cloud-region](qcloud_serverless_cloud-region.md) - Explore cloud regions for serverless spaces * [qcloud serverless quota](qcloud_serverless_quota.md) - Show the serverless quota of the account * [qcloud serverless space](qcloud_serverless_space.md) - Manage serverless spaces +* [qcloud serverless usage](qcloud_serverless_usage.md) - Show the billed serverless usage per space diff --git a/docs/reference/qcloud_serverless_usage.md b/docs/reference/qcloud_serverless_usage.md new file mode 100644 index 0000000..97fc3e0 --- /dev/null +++ b/docs/reference/qcloud_serverless_usage.md @@ -0,0 +1,72 @@ +## qcloud serverless usage + +Show the billed serverless usage per space + +### Synopsis + +Show the billed serverless usage of the current account per space and billable item. + +Each row is one billable item of one space in one calendar month, as named on +the invoice (for example "Serverless Updated Data (GiB)"), with the quantity +consumed, the charge, the discount and the net charge. The net total of all +rows is shown below the table. Prepaid credits drawn for the period are not +subtracted. + +By default, the period is the current calendar month (UTC) up to now. Use +--month for a whole calendar month, or --since and --until for any other +period. When only --until is given, the period starts on the first day of its +month. Usage is reported per calendar month, so a period that starts or ends +within a month only includes the usage metered in that part of the month. + +For a parent billing account, the usage of all child accounts is included and +an ACCOUNT column is shown. Cluster usage and the prepaid credits drawn are +left out, also from --json. The API key needs the read:payment_information +permission. + +``` +qcloud serverless usage [flags] +``` + +### Examples + +``` +# Show the serverless usage of the current month so far +qcloud serverless usage + +# Show the usage of October 2026 +qcloud serverless usage --month 2026-10 + +# Show the usage of one space during the third quarter of 2026 +qcloud serverless usage --space 0e7a3c1d-5f2b-4c8e-9a6d-1b2c3d4e5f60 --since 2026-07-01 --until 2026-09-30 + +# Export the usage as JSON +qcloud serverless usage --month 2026-10 --json +``` + +### Options + +``` + -h, --help[=true|false] help for usage + --month string Calendar month in YYYY-MM format (UTC); cannot be combined with --since or --until + -s, --since string Start of the period (RFC3339, YYYY-MM-DD, or a duration ago such as 24h or 7d; default: first day of the month of --until) + --space string Only include the space with this ID + -u, --until string End of the period, exclusive (RFC3339, YYYY-MM-DD for the end of that day, or a duration ago such as 1h; default: now) +``` + +### Options inherited from parent commands + +``` + --account-id string Qdrant Cloud Account ID (env: QDRANT_CLOUD_ACCOUNT_ID) + --api-key string Management API Key (env: QDRANT_CLOUD_API_KEY) + -c, --config string Config file path (env: QDRANT_CLOUD_CONFIG, default ~/.config/qcloud/config.yaml) + --console-url string Qdrant Cloud web console base URL (env: QDRANT_CLOUD_CONSOLE_URL, default https://cloud.qdrant.io) + --context string Override the active context (env: QDRANT_CLOUD_CONTEXT) + --debug[=true|false] Enable debug logging to stderr + --endpoint string gRPC API endpoint (env: QDRANT_CLOUD_ENDPOINT, default grpc.cloud.qdrant.io:443) + --json[=true|false] Output as JSON +``` + +### SEE ALSO + +* [qcloud serverless](qcloud_serverless.md) - Manage Qdrant Cloud Serverless resources + diff --git a/internal/cmd/output/format.go b/internal/cmd/output/format.go index 4cf97de..3d0b81e 100644 --- a/internal/cmd/output/format.go +++ b/internal/cmd/output/format.go @@ -54,6 +54,30 @@ func USDMillicents(v uint64) string { return fmt.Sprintf("$%s.%02d", humanize.Comma(int64(cents/100)), cents%100) //nolint:gosec // dollars fit in int64 } +// Millicents formats an amount in millicents (1/1000 of the currency's minor +// unit) in the given ISO 4217 currency. USD and an empty currency are shown as +// dollars (e.g. "$1,234.56"); other currencies as the amount followed by the +// code (e.g. "1,234.56 EUR"). Fractions of a cent are rounded down, and a +// negative amount gets a leading minus sign. +func Millicents(v int64, currency string) string { + abs := uint64(v) //nolint:gosec // v is non-negative here, negated below otherwise + if v < 0 { + abs = uint64(-v) //nolint:gosec // -v is positive + } + + cents := abs / 1000 + sign := "" + if v < 0 && cents > 0 { + sign = "-" + } + + if currency == "" || currency == "USD" { + return sign + USDMillicents(abs) + } + + return fmt.Sprintf("%s%s.%02d %s", sign, humanize.Comma(int64(cents/100)), cents%100, currency) //nolint:gosec // amounts fit in int64 +} + // Rate formats a per-second rate with two decimals (e.g. "1.25/s"). func Rate(v float64) string { return strconv.FormatFloat(v, 'f', 2, 64) + "/s" diff --git a/internal/cmd/output/money_test.go b/internal/cmd/output/money_test.go index 2d462c2..38dc1f8 100644 --- a/internal/cmd/output/money_test.go +++ b/internal/cmd/output/money_test.go @@ -21,3 +21,20 @@ func TestUSDMillicents(t *testing.T) { assert.Equal(t, want, output.USDMillicents(in), "%d", in) } } + +func TestMillicents(t *testing.T) { + for _, tc := range []struct { + in int64 + currency string + want string + }{ + {0, "USD", "$0.00"}, + {1_234_567 * 1_000, "USD", "$12,345.67"}, + {50 * output.MillicentsPerUSD, "", "$50.00"}, + {-1_500 * 1_000, "USD", "-$15.00"}, + {1_234_567 * 1_000, "EUR", "12,345.67 EUR"}, + {-999, "EUR", "0.00 EUR"}, + } { + assert.Equal(t, tc.want, output.Millicents(tc.in, tc.currency), "%d %s", tc.in, tc.currency) + } +} diff --git a/internal/cmd/serverless/serverless.go b/internal/cmd/serverless/serverless.go index 0fd3fde..7b96a1a 100644 --- a/internal/cmd/serverless/serverless.go +++ b/internal/cmd/serverless/serverless.go @@ -6,6 +6,7 @@ import ( "github.com/qdrant/qcloud-cli/internal/cmd/serverless/cloudregion" "github.com/qdrant/qcloud-cli/internal/cmd/serverless/quota" "github.com/qdrant/qcloud-cli/internal/cmd/serverless/space" + "github.com/qdrant/qcloud-cli/internal/cmd/serverless/usage" "github.com/qdrant/qcloud-cli/internal/state" ) @@ -21,13 +22,16 @@ A space is hosted in a single cloud region and scales its search workers automatically, so there are no nodes, packages or disks to size. Use the commands in this group to manage spaces together with their API keys and backups, to explore the regions spaces can be created in, and to inspect the -account's serverless quota.`, +account's serverless quota and billed usage.`, Example: `# List the regions in which spaces can be created qcloud serverless cloud-region list # Show how many spaces the account can still create qcloud serverless quota +# Show the billed serverless usage of the current month per space +qcloud serverless usage + # List all serverless spaces qcloud serverless space list @@ -39,6 +43,7 @@ qcloud serverless space create --cloud-region eu-central-1 --wait`, space.NewCommand(s), cloudregion.NewCommand(s), quota.NewCommand(s), + usage.NewCommand(s), ) return cmd } diff --git a/internal/cmd/serverless/usage/usage.go b/internal/cmd/serverless/usage/usage.go new file mode 100644 index 0000000..cdec588 --- /dev/null +++ b/internal/cmd/serverless/usage/usage.go @@ -0,0 +1,328 @@ +package usage + +import ( + "cmp" + "errors" + "fmt" + "io" + "math" + "slices" + "strconv" + "strings" + "time" + + "github.com/spf13/cobra" + "google.golang.org/protobuf/types/known/timestamppb" + + meteringv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/metering/v1" + + "github.com/qdrant/qcloud-cli/internal/cmd/base" + "github.com/qdrant/qcloud-cli/internal/cmd/completion" + "github.com/qdrant/qcloud-cli/internal/cmd/output" + "github.com/qdrant/qcloud-cli/internal/cmd/util" + "github.com/qdrant/qcloud-cli/internal/state" +) + +// monthLayout is the format of the --month flag and of the MONTH column. +const monthLayout = "2006-01" + +// NewCommand creates the serverless usage command. +func NewCommand(s *state.State) *cobra.Command { + // The period is resolved in Fetch and shown by PrintText. + var start, end time.Time + + cmd := base.DescribeCmd[*meteringv1.GetUsageBreakdownResponse]{ + Use: "usage", + Short: "Show the billed serverless usage per space", + Long: `Show the billed serverless usage of the current account per space and billable item. + +Each row is one billable item of one space in one calendar month, as named on +the invoice (for example "Serverless Updated Data (GiB)"), with the quantity +consumed, the charge, the discount and the net charge. The net total of all +rows is shown below the table. Prepaid credits drawn for the period are not +subtracted. + +By default, the period is the current calendar month (UTC) up to now. Use +--month for a whole calendar month, or --since and --until for any other +period. When only --until is given, the period starts on the first day of its +month. Usage is reported per calendar month, so a period that starts or ends +within a month only includes the usage metered in that part of the month. + +For a parent billing account, the usage of all child accounts is included and +an ACCOUNT column is shown. Cluster usage and the prepaid credits drawn are +left out, also from --json. The API key needs the read:payment_information +permission.`, + Example: `# Show the serverless usage of the current month so far +qcloud serverless usage + +# Show the usage of October 2026 +qcloud serverless usage --month 2026-10 + +# Show the usage of one space during the third quarter of 2026 +qcloud serverless usage --space 0e7a3c1d-5f2b-4c8e-9a6d-1b2c3d4e5f60 --since 2026-07-01 --until 2026-09-30 + +# Export the usage as JSON +qcloud serverless usage --month 2026-10 --json`, + Args: cobra.NoArgs, + Fetch: func(s *state.State, cmd *cobra.Command, _ []string) (*meteringv1.GetUsageBreakdownResponse, error) { + var err error + start, end, err = readPeriod(cmd, time.Now().UTC()) + if err != nil { + return nil, err + } + + var spaceID string + if cmd.Flags().Changed("space") { + spaceID, _ = cmd.Flags().GetString("space") + if spaceID == "" { + return nil, errors.New("--space must not be empty") + } + } + + ctx := cmd.Context() + client, err := s.Client(ctx) + if err != nil { + return nil, err + } + + accountID, err := s.AccountID() + if err != nil { + return nil, err + } + + resp, err := client.Metering().GetUsageBreakdown(ctx, &meteringv1.GetUsageBreakdownRequest{ + AccountId: accountID, + StartTime: timestamppb.New(start), + EndTime: timestamppb.New(end), + }) + if err != nil { + return nil, fmt.Errorf("failed to get usage breakdown: %w", err) + } + + return spacesOnly(resp, spaceID), nil + }, + PrintText: func(_ *cobra.Command, w io.Writer, resp *meteringv1.GetUsageBreakdownResponse) error { + fmt.Fprintf(w, "Period: %s to %s\n", output.FullDateTime(start), output.FullDateTime(end)) + + rows := flatten(resp) + if len(rows) == 0 { + fmt.Fprintln(w, "No serverless usage in this period.") + return nil + } + + fmt.Fprintln(w) + + multiAccount := slices.ContainsFunc(rows, func(r row) bool { return r.accountID != rows[0].accountID }) + + t := output.NewTable[row](w) + t.AddField("MONTH", func(r row) string { return r.month }) + if multiAccount { + t.AddField("ACCOUNT", func(r row) string { return r.accountName }) + } + + t.AddField("SPACE", func(r row) string { return cmp.Or(r.space.GetSpaceName(), "-") }) + t.AddField("SPACE ID", func(r row) string { return r.space.GetSpaceId() }) + t.AddField("ITEM", func(r row) string { return r.space.GetBillableEntityType() }) + t.AddField("QUANTITY", func(r row) string { + return strings.TrimSpace(quantity(r.space.GetQuantity()) + " " + r.space.GetUnit()) + }) + t.AddField("AMOUNT", func(r row) string { + return output.Millicents(r.space.GetAmountMillicents(), r.space.GetCurrency()) + }) + t.AddField("DISCOUNT", func(r row) string { return discount(r.space) }) + t.AddField("NET", func(r row) string { return output.Millicents(net(r.space), r.space.GetCurrency()) }) + t.SetItems(rows) + t.Render() + + fmt.Fprintf(w, "\nTotal: %s\n", total(rows)) + return nil + }, + }.CobraCommand(s) + + util.AddTimeRangeFlags(cmd, 0) + cmd.Flags().Lookup("since").Usage = "Start of the period (RFC3339, YYYY-MM-DD, or a duration ago such as 24h or 7d; default: first day of the month of --until)" + cmd.Flags().Lookup("until").Usage = "End of the period, exclusive (RFC3339, YYYY-MM-DD for the end of that day, or a duration ago such as 1h; default: now)" + cmd.Flags().String("month", "", "Calendar month in YYYY-MM format (UTC); cannot be combined with --since or --until") + cmd.Flags().String("space", "", "Only include the space with this ID") + _ = cmd.RegisterFlagCompletionFunc("space", completion.SpaceIDCompletion(s)) + cmd.MarkFlagsMutuallyExclusive("month", "since") + cmd.MarkFlagsMutuallyExclusive("month", "until") + + return cmd +} + +// readPeriod resolves the period from --month, or from --since and --until. +// The end is cut to now, because usage is only metered up to now. +func readPeriod(cmd *cobra.Command, now time.Time) (time.Time, time.Time, error) { + if cmd.Flags().Changed("month") { + v, _ := cmd.Flags().GetString("month") + start, err := time.Parse(monthLayout, v) + if err != nil { + return time.Time{}, time.Time{}, fmt.Errorf("invalid --month %q: must be in YYYY-MM format", v) + } + + if !start.Before(now) { + return time.Time{}, time.Time{}, fmt.Errorf("invalid --month %q: must not be in the future", v) + } + + end := start.AddDate(0, 1, 0) + if end.After(now) { + end = now + } + + return start, end, nil + } + + since, until, err := util.ReadTimeRange(cmd, now) + if err != nil { + return time.Time{}, time.Time{}, err + } + + end := now + if until != nil && until.AsTime().Before(now) { + end = until.AsTime() + } + + var start time.Time + if since != nil { + start = since.AsTime() + } else { + start = monthStart(end) + if !start.Before(end) { + // --until is the first instant of a month: cover the month before it. + start = start.AddDate(0, -1, 0) + } + } + + if !start.Before(now) { + return time.Time{}, time.Time{}, errors.New("--since must be in the past") + } + + if !start.Before(end) { + return time.Time{}, time.Time{}, errors.New("--since must be before --until") + } + + return start, end, nil +} + +// monthStart returns the first instant of the UTC calendar month of t. +func monthStart(t time.Time) time.Time { + t = t.UTC() + return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, time.UTC) +} + +// spacesOnly returns a copy of resp with only the serverless space usage, +// optionally of a single space. Cluster usage and the credits drawn, which +// cover all usage of the account, are left out, as are the accounts and +// months without any space usage left. +func spacesOnly(resp *meteringv1.GetUsageBreakdownResponse, spaceID string) *meteringv1.GetUsageBreakdownResponse { + out := &meteringv1.GetUsageBreakdownResponse{} + for _, m := range resp.GetItems() { + month := &meteringv1.UsageBreakdownMonth{Year: m.GetYear(), Month: m.GetMonth()} + for _, a := range m.GetAccounts() { + var spaces []*meteringv1.UsageBreakdownSpace + for _, sp := range a.GetSpaces() { + if spaceID == "" || sp.GetSpaceId() == spaceID { + spaces = append(spaces, sp) + } + } + + if len(spaces) > 0 { + month.Accounts = append(month.Accounts, &meteringv1.UsageBreakdownAccount{ + AccountId: a.GetAccountId(), + AccountName: a.GetAccountName(), + Spaces: spaces, + }) + } + } + + if len(month.GetAccounts()) > 0 { + out.Items = append(out.Items, month) + } + } + + return out +} + +// row is one table row: the usage of one billable item of one space in a month. +type row struct { + month string + accountID string + accountName string + space *meteringv1.UsageBreakdownSpace +} + +// flatten turns the response into rows sorted by month, account, space name, +// space ID and billable item. +func flatten(resp *meteringv1.GetUsageBreakdownResponse) []row { + var rows []row + for _, m := range resp.GetItems() { + month := fmt.Sprintf("%04d-%02d", m.GetYear(), m.GetMonth()) + for _, a := range m.GetAccounts() { + for _, sp := range a.GetSpaces() { + rows = append(rows, row{month: month, accountID: a.GetAccountId(), accountName: a.GetAccountName(), space: sp}) + } + } + } + + slices.SortStableFunc(rows, func(a, b row) int { + return cmp.Or( + cmp.Compare(a.month, b.month), + cmp.Compare(a.accountName, b.accountName), + cmp.Compare(a.accountID, b.accountID), + cmp.Compare(a.space.GetSpaceName(), b.space.GetSpaceName()), + cmp.Compare(a.space.GetSpaceId(), b.space.GetSpaceId()), + cmp.Compare(a.space.GetBillableEntityType(), b.space.GetBillableEntityType()), + ) + }) + + return rows +} + +// net returns the charge of sp after its discount. +func net(sp *meteringv1.UsageBreakdownSpace) int64 { + return sp.GetAmountMillicents() - sp.GetDiscountAmountMillicents() +} + +// discount formats the discount of sp, with its percentage when known, or "-" +// when there is none. +func discount(sp *meteringv1.UsageBreakdownSpace) string { + if sp.DiscountAmountMillicents == nil && sp.DiscountAmountPercent == nil { + return "-" + } + + s := output.Millicents(sp.GetDiscountAmountMillicents(), sp.GetCurrency()) + if sp.DiscountAmountPercent != nil { + s += " (" + strconv.FormatFloat(sp.GetDiscountAmountPercent(), 'f', -1, 64) + "%)" + } + + return s +} + +// total formats the sum of the net charges of rows, one amount per currency. +func total(rows []row) string { + sums := map[string]int64{} + var currencies []string + for _, r := range rows { + c := r.space.GetCurrency() + if _, ok := sums[c]; !ok { + currencies = append(currencies, c) + } + + sums[c] += net(r.space) + } + + slices.Sort(currencies) + parts := make([]string, 0, len(currencies)) + for _, c := range currencies { + parts = append(parts, output.Millicents(sums[c], c)) + } + + return strings.Join(parts, ", ") +} + +// quantity formats a metered quantity with at most four decimals and no +// trailing zeros (e.g. "12.5", "1234567", "0.0001"). +func quantity(v float64) string { + return strconv.FormatFloat(math.Round(v*1e4)/1e4, 'f', -1, 64) +} diff --git a/internal/cmd/serverless/usage/usage_test.go b/internal/cmd/serverless/usage/usage_test.go new file mode 100644 index 0000000..458aa65 --- /dev/null +++ b/internal/cmd/serverless/usage/usage_test.go @@ -0,0 +1,341 @@ +package usage_test + +import ( + "encoding/json" + "fmt" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/protobuf/types/known/timestamppb" + + meteringv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/metering/v1" + + "github.com/qdrant/qcloud-cli/internal/testutil" +) + +const ( + spaceA = "0e7a3c1d-5f2b-4c8e-9a6d-1b2c3d4e5f60" + spaceB = "7f1e2d3c-4b5a-4968-8776-655443322110" +) + +func spaceUsage(id, name, item string, qty float64, unit string, amount int64) *meteringv1.UsageBreakdownSpace { + return &meteringv1.UsageBreakdownSpace{ + SpaceId: id, + SpaceName: name, + StartTime: timestamppb.New(time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)), + EndTime: timestamppb.New(time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC)), + AmountMillicents: amount, + Currency: "USD", + BillableEntityType: item, + Quantity: qty, + Unit: unit, + } +} + +func sampleBreakdown() *meteringv1.GetUsageBreakdownResponse { + discounted := spaceUsage(spaceB, "", "Serverless Search Requests", 1234567, "requests", 2_000_000) + discounted.DiscountAmountMillicents = new(int64(500_000)) + discounted.DiscountAmountPercent = new(25.0) + + return &meteringv1.GetUsageBreakdownResponse{ + Items: []*meteringv1.UsageBreakdownMonth{ + { + Year: 2026, + Month: 10, + Accounts: []*meteringv1.UsageBreakdownAccount{{ + AccountId: "test-account-id", + AccountName: "Acme", + Clusters: []*meteringv1.UsageBreakdownCluster{{ + ClusterId: "c0c0c0c0-0000-4000-8000-000000000000", + ClusterName: "prod-cluster", + AmountMillicents: 99_900_000, + Currency: "USD", + BillableEntityType: "Cluster", + }}, + Spaces: []*meteringv1.UsageBreakdownSpace{ + spaceUsage(spaceA, "products", "Serverless Stored Data (GiB-month)", 12.34567, "GiB-month", 1_234_000), + discounted, + }, + }}, + Funding: &meteringv1.UsageBreakdownFunding{ + CreditsDrawn: []*meteringv1.CreditDrawdown{{CreditContractId: "contract-1", AmountMillicents: 1_000}}, + }, + }, + { + // A month with cluster usage only is left out. + Year: 2026, + Month: 9, + Accounts: []*meteringv1.UsageBreakdownAccount{{ + AccountId: "test-account-id", + AccountName: "Acme", + Clusters: []*meteringv1.UsageBreakdownCluster{{ + ClusterId: "c0c0c0c0-0000-4000-8000-000000000000", ClusterName: "prod-cluster", Currency: "USD", + }}, + }}, + }, + }, + } +} + +func TestUsage_TextOutput(t *testing.T) { + env := testutil.NewTestEnv(t) + env.MeteringServer.GetUsageBreakdownCalls.Returns(sampleBreakdown(), nil) + + stdout, _, err := testutil.Exec(t, env, "serverless", "usage", "--month", "2026-10") + require.NoError(t, err) + + assert.Contains(t, stdout, "Period: 2026-10-01 00:00:00 UTC to 2026-11-01 00:00:00 UTC") + for _, h := range []string{"MONTH", "SPACE", "SPACE ID", "ITEM", "QUANTITY", "AMOUNT", "DISCOUNT", "NET"} { + assert.Contains(t, stdout, h) + } + + assert.NotContains(t, stdout, "ACCOUNT", "a single account has no ACCOUNT column") + assert.Contains(t, stdout, "2026-10") + assert.Contains(t, stdout, "products") + assert.Contains(t, stdout, spaceA) + assert.Contains(t, stdout, "Serverless Stored Data (GiB-month)") + assert.Contains(t, stdout, "12.3457 GiB-month") + assert.Contains(t, stdout, "$12.34") + assert.Contains(t, stdout, "1234567 requests") + assert.Contains(t, stdout, "$20.00") + assert.Contains(t, stdout, "$5.00 (25%)", "discount with percentage") + assert.Contains(t, stdout, "$15.00", "net charge after discount") + assert.Contains(t, stdout, "Total: $27.34") + assert.NotContains(t, stdout, "prod-cluster", "cluster usage is left out") + assert.NotContains(t, stdout, "2026-09", "months without space usage are left out") +} + +func TestUsage_TextOutput_SortsRowsAndMarksUnknownSpaceName(t *testing.T) { + env := testutil.NewTestEnv(t) + env.MeteringServer.GetUsageBreakdownCalls.Returns(sampleBreakdown(), nil) + + stdout, _, err := testutil.Exec(t, env, "serverless", "usage", "--month", "2026-10") + require.NoError(t, err) + + // The space without a name sorts first and shows "-". + assert.Regexp(t, `(?m)^2026-10\s+-\s+`+spaceB, stdout) + assert.Less(t, strings.Index(stdout, spaceB), strings.Index(stdout, spaceA)) +} + +func TestUsage_DefaultPeriodIsCurrentMonth(t *testing.T) { + env := testutil.NewTestEnv(t) + env.MeteringServer.GetUsageBreakdownCalls.Returns(&meteringv1.GetUsageBreakdownResponse{}, nil) + + before := time.Now().UTC() + stdout, _, err := testutil.Exec(t, env, "serverless", "usage") + require.NoError(t, err) + assert.Contains(t, stdout, "No serverless usage in this period.") + + req, ok := env.MeteringServer.GetUsageBreakdownCalls.Last() + require.True(t, ok) + assert.Equal(t, "test-account-id", req.GetAccountId()) + assert.Equal(t, time.Date(before.Year(), before.Month(), 1, 0, 0, 0, 0, time.UTC), req.GetStartTime().AsTime()) + assert.WithinRange(t, req.GetEndTime().AsTime(), before.Add(-time.Second), time.Now()) +} + +func TestUsage_MonthRequestsWholeMonth(t *testing.T) { + env := testutil.NewTestEnv(t) + env.MeteringServer.GetUsageBreakdownCalls.Returns(&meteringv1.GetUsageBreakdownResponse{}, nil) + + _, _, err := testutil.Exec(t, env, "serverless", "usage", "--month", "2026-02") + require.NoError(t, err) + + req, ok := env.MeteringServer.GetUsageBreakdownCalls.Last() + require.True(t, ok) + assert.Equal(t, time.Date(2026, 2, 1, 0, 0, 0, 0, time.UTC), req.GetStartTime().AsTime()) + assert.Equal(t, time.Date(2026, 3, 1, 0, 0, 0, 0, time.UTC), req.GetEndTime().AsTime()) +} + +func TestUsage_CurrentMonthIsCutToNow(t *testing.T) { + env := testutil.NewTestEnv(t) + env.MeteringServer.GetUsageBreakdownCalls.Returns(&meteringv1.GetUsageBreakdownResponse{}, nil) + + before := time.Now().UTC() + _, _, err := testutil.Exec(t, env, "serverless", "usage", "--month", before.Format("2006-01")) + require.NoError(t, err) + + req, ok := env.MeteringServer.GetUsageBreakdownCalls.Last() + require.True(t, ok) + assert.WithinRange(t, req.GetEndTime().AsTime(), before.Add(-time.Second), time.Now()) +} + +func TestUsage_SinceAndUntil(t *testing.T) { + env := testutil.NewTestEnv(t) + env.MeteringServer.GetUsageBreakdownCalls.Returns(&meteringv1.GetUsageBreakdownResponse{}, nil) + + _, _, err := testutil.Exec(t, env, "serverless", "usage", "--since", "2026-07-01", "--until", "2026-09-30T00:00:00Z") + require.NoError(t, err) + + req, ok := env.MeteringServer.GetUsageBreakdownCalls.Last() + require.True(t, ok) + assert.Equal(t, time.Date(2026, 7, 1, 0, 0, 0, 0, time.UTC), req.GetStartTime().AsTime()) + assert.Equal(t, time.Date(2026, 9, 30, 0, 0, 0, 0, time.UTC), req.GetEndTime().AsTime()) +} + +func TestUsage_OnlyUntilStartsAtItsMonth(t *testing.T) { + for _, tc := range []struct { + until string + wantStart time.Time + }{ + {"2026-09-15T12:00:00Z", time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC)}, + // The first instant of a month covers the month before it. + {"2026-09-01T00:00:00Z", time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC)}, + } { + t.Run(tc.until, func(t *testing.T) { + env := testutil.NewTestEnv(t) + env.MeteringServer.GetUsageBreakdownCalls.Returns(&meteringv1.GetUsageBreakdownResponse{}, nil) + + _, _, err := testutil.Exec(t, env, "serverless", "usage", "--until", tc.until) + require.NoError(t, err) + + req, ok := env.MeteringServer.GetUsageBreakdownCalls.Last() + require.True(t, ok) + assert.Equal(t, tc.wantStart, req.GetStartTime().AsTime()) + }) + } +} + +func TestUsage_SpaceFilter(t *testing.T) { + env := testutil.NewTestEnv(t) + env.MeteringServer.GetUsageBreakdownCalls.Returns(sampleBreakdown(), nil) + + stdout, _, err := testutil.Exec(t, env, "serverless", "usage", "--month", "2026-10", "--space", spaceA) + require.NoError(t, err) + assert.Contains(t, stdout, spaceA) + assert.NotContains(t, stdout, spaceB) + assert.Contains(t, stdout, "Total: $12.34") +} + +func TestUsage_SpaceFilterWithoutUsage(t *testing.T) { + env := testutil.NewTestEnv(t) + env.MeteringServer.GetUsageBreakdownCalls.Returns(sampleBreakdown(), nil) + + stdout, _, err := testutil.Exec(t, env, "serverless", "usage", "--month", "2026-10", "--space", "11111111-2222-4333-8444-555555555555") + require.NoError(t, err) + assert.Contains(t, stdout, "No serverless usage in this period.") +} + +func TestUsage_ParentAccountShowsAccountColumn(t *testing.T) { + env := testutil.NewTestEnv(t) + resp := sampleBreakdown() + resp.Items[0].Accounts = append(resp.Items[0].Accounts, &meteringv1.UsageBreakdownAccount{ + AccountId: "child-account-id", + AccountName: "Acme Child", + Spaces: []*meteringv1.UsageBreakdownSpace{ + spaceUsage("22222222-3333-4444-8555-666666666666", "child-space", "Serverless Stored Data (GiB-month)", 1, "GiB-month", 100_000), + }, + }) + env.MeteringServer.GetUsageBreakdownCalls.Returns(resp, nil) + + stdout, _, err := testutil.Exec(t, env, "serverless", "usage", "--month", "2026-10") + require.NoError(t, err) + assert.Contains(t, stdout, "ACCOUNT") + assert.Contains(t, stdout, "Acme Child") + assert.Contains(t, stdout, "child-space") + assert.Contains(t, stdout, "Total: $28.34") +} + +func TestUsage_TotalPerCurrency(t *testing.T) { + env := testutil.NewTestEnv(t) + eur := spaceUsage(spaceB, "eu-space", "Serverless Stored Data (GiB-month)", 1, "GiB-month", 300_000) + eur.Currency = "EUR" + env.MeteringServer.GetUsageBreakdownCalls.Returns(&meteringv1.GetUsageBreakdownResponse{ + Items: []*meteringv1.UsageBreakdownMonth{{ + Year: 2026, Month: 10, + Accounts: []*meteringv1.UsageBreakdownAccount{{ + AccountId: "test-account-id", AccountName: "Acme", + Spaces: []*meteringv1.UsageBreakdownSpace{ + spaceUsage(spaceA, "us-space", "Serverless Stored Data (GiB-month)", 1, "GiB-month", 100_000), + eur, + }, + }}, + }}, + }, nil) + + stdout, _, err := testutil.Exec(t, env, "serverless", "usage", "--month", "2026-10") + require.NoError(t, err) + assert.Contains(t, stdout, "3.00 EUR") + assert.Contains(t, stdout, "Total: 3.00 EUR, $1.00") +} + +func TestUsage_JSONOutput(t *testing.T) { + env := testutil.NewTestEnv(t) + env.MeteringServer.GetUsageBreakdownCalls.Returns(sampleBreakdown(), nil) + + stdout, _, err := testutil.Exec(t, env, "serverless", "usage", "--month", "2026-10", "--json") + require.NoError(t, err) + + var result struct { + Items []struct { + Year int `json:"year"` + Month int `json:"month"` + Funding json.RawMessage `json:"funding"` + Accounts []struct { + AccountID string `json:"accountId"` + Clusters []json.RawMessage `json:"clusters"` + Spaces []struct { + SpaceID string `json:"spaceId"` + AmountMillicents string `json:"amountMillicents"` + DiscountAmountMillicents string `json:"discountAmountMillicents"` + Unit string `json:"unit"` + } `json:"spaces"` + } `json:"accounts"` + } `json:"items"` + } + require.NoError(t, json.Unmarshal([]byte(stdout), &result)) + + require.Len(t, result.Items, 1, "months without space usage are left out") + m := result.Items[0] + assert.Equal(t, 2026, m.Year) + assert.Equal(t, 10, m.Month) + assert.Nil(t, m.Funding, "credits drawn are left out") + require.Len(t, m.Accounts, 1) + assert.Empty(t, m.Accounts[0].Clusters, "cluster usage is left out") + require.Len(t, m.Accounts[0].Spaces, 2) + assert.Equal(t, spaceA, m.Accounts[0].Spaces[0].SpaceID) + assert.Equal(t, "1234000", m.Accounts[0].Spaces[0].AmountMillicents) + assert.Equal(t, "GiB-month", m.Accounts[0].Spaces[0].Unit) + assert.Equal(t, "500000", m.Accounts[0].Spaces[1].DiscountAmountMillicents) +} + +func TestUsage_InputErrors(t *testing.T) { + future := time.Now().UTC().AddDate(0, 2, 0).Format("2006-01") + for _, tc := range []struct { + name string + args []string + want string + }{ + {"invalid month", []string{"--month", "2026-13"}, "YYYY-MM"}, + {"month as date", []string{"--month", "2026-10-01"}, "YYYY-MM"}, + {"future month", []string{"--month", future}, "must not be in the future"}, + {"month with since", []string{"--month", "2026-10", "--since", "2026-10-01"}, "none of the others can be"}, + {"month with until", []string{"--month", "2026-10", "--until", "2026-10-31"}, "none of the others can be"}, + {"invalid since", []string{"--since", "yesterday"}, "invalid --since"}, + {"since after until", []string{"--since", "2026-10-02", "--until", "2026-10-01T00:00:00Z"}, "--since must be before --until"}, + {"since in the future", []string{"--since", time.Now().UTC().AddDate(0, 0, 2).Format(time.DateOnly)}, "--since must be in the past"}, + {"empty space", []string{"--space", ""}, "--space must not be empty"}, + {"positional arg", []string{"extra"}, "unknown command"}, + } { + t.Run(tc.name, func(t *testing.T) { + env := testutil.NewTestEnv(t) + + _, _, err := testutil.Exec(t, env, append([]string{"serverless", "usage"}, tc.args...)...) + require.Error(t, err) + assert.Contains(t, err.Error(), tc.want) + assert.Equal(t, 0, env.MeteringServer.GetUsageBreakdownCalls.Count(), "no API call on invalid input") + }) + } +} + +func TestUsage_BackendError(t *testing.T) { + env := testutil.NewTestEnv(t) + env.MeteringServer.GetUsageBreakdownCalls.Returns(nil, fmt.Errorf("permission denied")) + + _, _, err := testutil.Exec(t, env, "serverless", "usage") + require.Error(t, err) + assert.Contains(t, err.Error(), "failed to get usage breakdown") + assert.Contains(t, err.Error(), "permission denied") +} diff --git a/internal/qcloudapi/client.go b/internal/qcloudapi/client.go index e3bdb91..2b6bd2a 100644 --- a/internal/qcloudapi/client.go +++ b/internal/qcloudapi/client.go @@ -20,6 +20,7 @@ import ( clusterv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/cluster/v1" hybridv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/hybrid/v1" iamv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/iam/v1" + meteringv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/metering/v1" monitoringv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/monitoring/v1" platformv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/platform/v1" serverlessmonitoringv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/serverless/monitoring/v1" @@ -43,6 +44,7 @@ type Client struct { auth authv1.AuthServiceClient iam iamv1.IAMServiceClient account accountv1.AccountServiceClient + metering meteringv1.MeteringServiceClient serverlessSpace spacev1.SpaceServiceClient serverlessSpaceApiKey spaceauthv1.SpaceApiKeyServiceClient serverlessBackup spacebackupv1.BackupServiceClient @@ -103,6 +105,7 @@ func newFromConn(conn *grpc.ClientConn) *Client { auth: authv1.NewAuthServiceClient(conn), iam: iamv1.NewIAMServiceClient(conn), account: accountv1.NewAccountServiceClient(conn), + metering: meteringv1.NewMeteringServiceClient(conn), serverlessSpace: spacev1.NewSpaceServiceClient(conn), serverlessSpaceApiKey: spaceauthv1.NewSpaceApiKeyServiceClient(conn), serverlessBackup: spacebackupv1.NewBackupServiceClient(conn), @@ -162,6 +165,11 @@ func (c *Client) Account() accountv1.AccountServiceClient { return c.account } +// Metering returns the MeteringService gRPC client. +func (c *Client) Metering() meteringv1.MeteringServiceClient { + return c.metering +} + // ServerlessSpace returns the serverless SpaceService gRPC client. func (c *Client) ServerlessSpace() spacev1.SpaceServiceClient { return c.serverlessSpace diff --git a/internal/testutil/fake_metering.go b/internal/testutil/fake_metering.go new file mode 100644 index 0000000..f3e8771 --- /dev/null +++ b/internal/testutil/fake_metering.go @@ -0,0 +1,20 @@ +package testutil + +import ( + "context" + + meteringv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/metering/v1" +) + +// FakeMeteringService is a test fake that implements MeteringServiceServer. +// Use the *Calls fields to configure responses and inspect captured requests. +type FakeMeteringService struct { + meteringv1.UnimplementedMeteringServiceServer + GetUsageBreakdownCalls MethodSpy[*meteringv1.GetUsageBreakdownRequest, *meteringv1.GetUsageBreakdownResponse] +} + +// GetUsageBreakdown records the call and dispatches via GetUsageBreakdownCalls. +func (f *FakeMeteringService) GetUsageBreakdown(ctx context.Context, req *meteringv1.GetUsageBreakdownRequest) (*meteringv1.GetUsageBreakdownResponse, error) { + f.GetUsageBreakdownCalls.record(req) + return f.GetUsageBreakdownCalls.dispatch(ctx, req, f.UnimplementedMeteringServiceServer.GetUsageBreakdown) +} diff --git a/internal/testutil/server.go b/internal/testutil/server.go index f744bc2..6aaea8e 100644 --- a/internal/testutil/server.go +++ b/internal/testutil/server.go @@ -20,6 +20,7 @@ import ( clusterv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/cluster/v1" hybridv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/hybrid/v1" iamv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/iam/v1" + meteringv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/metering/v1" monitoringv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/monitoring/v1" platformv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/platform/v1" serverlessmonitoringv1 "github.com/qdrant/qdrant-cloud-public-api/gen/go/qdrant/cloud/serverless/monitoring/v1" @@ -75,6 +76,7 @@ type TestEnv struct { AuthServer *FakeAuthService IAMServer *FakeIAMService AccountServer *FakeAccountService + MeteringServer *FakeMeteringService ServerlessSpaceServer *FakeServerlessSpaceService ServerlessSpaceApiKeyServer *FakeServerlessSpaceApiKeyService ServerlessBackupServer *FakeServerlessBackupService @@ -147,6 +149,7 @@ func newBaseTestEnv(t *testing.T, cfg *envConfig) *TestEnv { fakeAuth := &FakeAuthService{} fakeIAM := &FakeIAMService{} fakeAccount := &FakeAccountService{} + fakeMetering := &FakeMeteringService{} fakeServerlessSpace := &FakeServerlessSpaceService{} fakeServerlessSpaceApiKey := &FakeServerlessSpaceApiKeyService{} fakeServerlessBackup := &FakeServerlessBackupService{} @@ -168,6 +171,7 @@ func newBaseTestEnv(t *testing.T, cfg *envConfig) *TestEnv { authv1.RegisterAuthServiceServer(srv, fakeAuth) iamv1.RegisterIAMServiceServer(srv, fakeIAM) accountv1.RegisterAccountServiceServer(srv, fakeAccount) + meteringv1.RegisterMeteringServiceServer(srv, fakeMetering) spacev1.RegisterSpaceServiceServer(srv, fakeServerlessSpace) spaceauthv1.RegisterSpaceApiKeyServiceServer(srv, fakeServerlessSpaceApiKey) spacebackupv1.RegisterBackupServiceServer(srv, fakeServerlessBackup) @@ -231,6 +235,7 @@ func newBaseTestEnv(t *testing.T, cfg *envConfig) *TestEnv { AuthServer: fakeAuth, IAMServer: fakeIAM, AccountServer: fakeAccount, + MeteringServer: fakeMetering, ServerlessSpaceServer: fakeServerlessSpace, ServerlessSpaceApiKeyServer: fakeServerlessSpaceApiKey, ServerlessBackupServer: fakeServerlessBackup,