Skip to content

[usage] Add billInstancesAfter config setting #11882

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions components/usage/cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ import (
"bytes"
"encoding/json"
"fmt"
"os"
"path"
"time"

"github.com/gitpod-io/gitpod/common-go/log"
"github.com/gitpod-io/gitpod/usage/pkg/server"
"github.com/spf13/cobra"
"os"
"path"
)

func init() {
Expand Down Expand Up @@ -66,5 +68,9 @@ func parseConfig(path string) (server.Config, error) {
return server.Config{}, fmt.Errorf("failed to parse config from %s: %w", path, err)
}

if cfg.BillInstancesAfter == nil {
cfg.BillInstancesAfter = &time.Time{}
}

return cfg, nil
}
20 changes: 14 additions & 6 deletions components/usage/pkg/apiv1/billing.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,33 @@ package apiv1
import (
"context"
"fmt"
"math"
"time"

"github.com/gitpod-io/gitpod/common-go/log"
v1 "github.com/gitpod-io/gitpod/usage-api/v1"
"github.com/gitpod-io/gitpod/usage/pkg/db"
"github.com/gitpod-io/gitpod/usage/pkg/stripe"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"math"
)

func NewBillingService(stripeClient *stripe.Client) *BillingService {
func NewBillingService(stripeClient *stripe.Client, billInstancesAfter time.Time) *BillingService {
return &BillingService{
stripeClient: stripeClient,
stripeClient: stripeClient,
billInstancesAfter: billInstancesAfter,
}
}

type BillingService struct {
stripeClient *stripe.Client
stripeClient *stripe.Client
billInstancesAfter time.Time

v1.UnimplementedBillingServiceServer
}

func (s *BillingService) UpdateInvoices(ctx context.Context, in *v1.UpdateInvoicesRequest) (*v1.UpdateInvoicesResponse, error) {
credits, err := creditSummaryForTeams(in.GetSessions())
credits, err := s.creditSummaryForTeams(in.GetSessions())
if err != nil {
log.Log.WithError(err).Errorf("Failed to compute credit summary.")
return nil, status.Errorf(codes.InvalidArgument, "failed to compute credit summary")
Expand All @@ -44,10 +48,14 @@ func (s *BillingService) UpdateInvoices(ctx context.Context, in *v1.UpdateInvoic
return &v1.UpdateInvoicesResponse{}, nil
}

func creditSummaryForTeams(sessions []*v1.BilledSession) (map[string]int64, error) {
func (s *BillingService) creditSummaryForTeams(sessions []*v1.BilledSession) (map[string]int64, error) {
creditsPerTeamID := map[string]float64{}

for _, session := range sessions {
if session.StartTime.AsTime().Before(s.billInstancesAfter) {
continue
}

attributionID, err := db.ParseAttributionID(session.AttributionId)
if err != nil {
return nil, fmt.Errorf("failed to parse attribution ID: %w", err)
Expand Down
53 changes: 42 additions & 11 deletions components/usage/pkg/apiv1/billing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,36 @@
package apiv1

import (
"testing"
"time"

v1 "github.com/gitpod-io/gitpod/usage-api/v1"
"github.com/gitpod-io/gitpod/usage/pkg/db"
"github.com/gitpod-io/gitpod/usage/pkg/stripe"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"testing"
timestamppb "google.golang.org/protobuf/types/known/timestamppb"
)

func TestCreditSummaryForTeams(t *testing.T) {
teamID_A, teamID_B := uuid.New().String(), uuid.New().String()
teamAttributionID_A, teamAttributionID_B := db.NewTeamAttributionID(teamID_A), db.NewTeamAttributionID(teamID_B)

scenarios := []struct {
Name string
Sessions []*v1.BilledSession
Expected map[string]int64
Name string
Sessions []*v1.BilledSession
BillSessionsAfter time.Time
Expected map[string]int64
}{
{
Name: "no instances in report, no summary",
Sessions: []*v1.BilledSession{},
Expected: map[string]int64{},
Name: "no instances in report, no summary",
BillSessionsAfter: time.Time{},
Sessions: []*v1.BilledSession{},
Expected: map[string]int64{},
},
{
Name: "skips user attributions",
Name: "skips user attributions",
BillSessionsAfter: time.Time{},
Sessions: []*v1.BilledSession{
{
AttributionId: string(db.NewUserAttributionID(uuid.New().String())),
Expand All @@ -36,7 +43,8 @@ func TestCreditSummaryForTeams(t *testing.T) {
Expected: map[string]int64{},
},
{
Name: "two workspace instances",
Name: "two workspace instances",
BillSessionsAfter: time.Time{},
Sessions: []*v1.BilledSession{
{
// has 1 day and 23 hours of usage
Expand All @@ -55,7 +63,8 @@ func TestCreditSummaryForTeams(t *testing.T) {
},
},
{
Name: "multiple teams",
Name: "multiple teams",
BillSessionsAfter: time.Time{},
Sessions: []*v1.BilledSession{
{
// has 12 hours of usage
Expand All @@ -74,11 +83,33 @@ func TestCreditSummaryForTeams(t *testing.T) {
teamID_B: 240,
},
},
{
Name: "two instances, same team, one of which started too early to be considered",
BillSessionsAfter: time.Now().AddDate(0, 0, -2),
Sessions: []*v1.BilledSession{
{
// has 12 hours of usage, started yesterday
AttributionId: string(teamAttributionID_A),
Credits: (12) * 10,
StartTime: timestamppb.New(time.Now().AddDate(0, 0, -1)),
},
{
// has 1 day of usage, but started three days ago
AttributionId: string(teamAttributionID_A),
Credits: (24) * 10,
StartTime: timestamppb.New(time.Now().AddDate(0, 0, -3)),
},
},
Expected: map[string]int64{
teamID_A: 120,
},
},
}

for _, s := range scenarios {
t.Run(s.Name, func(t *testing.T) {
actual, err := creditSummaryForTeams(s.Sessions)
svc := NewBillingService(&stripe.Client{}, s.BillSessionsAfter)
actual, err := svc.creditSummaryForTeams(s.Sessions)
require.NoError(t, err)
require.Equal(t, s.Expected, actual)
})
Expand Down
10 changes: 7 additions & 3 deletions components/usage/pkg/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ type Config struct {

ContentServiceAddress string `json:"contentServiceAddress,omitempty"`

// billInstancesAfter sets the date after which instances should be considered for billing -
// instances started before `billInstancesAfter` will not be considered by the billing controller.
BillInstancesAfter *time.Time `json:"billInstancesAfter,omitempty"`

Server *baseserver.Configuration `json:"server,omitempty"`
}

Expand Down Expand Up @@ -113,7 +117,7 @@ func Start(cfg Config) error {
}
defer ctrl.Stop()

err = registerGRPCServices(srv, conn, stripeClient, reportGenerator, contentService)
err = registerGRPCServices(srv, conn, stripeClient, reportGenerator, contentService, *cfg.BillInstancesAfter)
if err != nil {
return fmt.Errorf("failed to register gRPC services: %w", err)
}
Expand All @@ -131,12 +135,12 @@ func Start(cfg Config) error {
return nil
}

func registerGRPCServices(srv *baseserver.Server, conn *gorm.DB, stripeClient *stripe.Client, reportGenerator *apiv1.ReportGenerator, contentSvc contentservice.Interface) error {
func registerGRPCServices(srv *baseserver.Server, conn *gorm.DB, stripeClient *stripe.Client, reportGenerator *apiv1.ReportGenerator, contentSvc contentservice.Interface, billInstancesAfter time.Time) error {
v1.RegisterUsageServiceServer(srv.GRPC(), apiv1.NewUsageService(conn, reportGenerator, contentSvc))
if stripeClient == nil {
v1.RegisterBillingServiceServer(srv.GRPC(), &apiv1.BillingServiceNoop{})
} else {
v1.RegisterBillingServiceServer(srv.GRPC(), apiv1.NewBillingService(stripeClient))
v1.RegisterBillingServiceServer(srv.GRPC(), apiv1.NewBillingService(stripeClient, billInstancesAfter))
}
return nil
}