Skip to content

[usage] Find running and stopped instances in ledger reconciler #12645

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
Sep 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
36 changes: 36 additions & 0 deletions components/usage/pkg/apiv1/usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,42 @@ func (s *UsageService) GetCostCenter(ctx context.Context, in *v1.GetCostCenterRe
}, nil
}

func (s *UsageService) ReconcileUsageWithLedger(ctx context.Context, req *v1.ReconcileUsageWithLedgerRequest) (*v1.ReconcileUsageWithLedgerResponse, error) {
from := req.GetFrom().AsTime()
to := req.GetTo().AsTime()

logger := log.
WithField("from", from).
WithField("to", to)

if to.Before(from) {
return nil, status.Errorf(codes.InvalidArgument, "To must not be before From")
}

stopped, err := db.FindStoppedWorkspaceInstancesInRange(ctx, s.conn, from, to)
if err != nil {
logger.WithError(err).Errorf("Failed to find stopped workspace instances.")
return nil, status.Errorf(codes.Internal, "failed to query for stopped instances")
}
logger.Infof("Found %d stopped workspace instances in range.", len(stopped))

running, err := db.FindRunningWorkspaceInstances(ctx, s.conn)
if err != nil {
logger.WithError(err).Errorf("Failed to find running workspace instances.")
return nil, status.Errorf(codes.Internal, "failed to query for running instances")
}
logger.Infof("Found %d running workspaces since the beginning of time.", len(running))

usageDrafts, err := db.FindAllDraftUsage(ctx, s.conn)
if err != nil {
logger.WithError(err).Errorf("Failed to find all draft usage records.")
return nil, status.Errorf(codes.Internal, "failed to find all draft usage records")
}
logger.Infof("Found %d draft usage records.", len(usageDrafts))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We'll also need to fetch the instances for the drafts and then combine the three slices of instances. But that's part of the next iteration I guess?


return &v1.ReconcileUsageWithLedgerResponse{}, nil
}

func NewUsageService(conn *gorm.DB, reportGenerator *ReportGenerator, contentSvc contentservice.Interface) *UsageService {
return &UsageService{
conn: conn,
Expand Down
38 changes: 38 additions & 0 deletions components/usage/pkg/apiv1/usage_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -556,3 +556,41 @@ func TestReportGenerator_GenerateUsageReportTable(t *testing.T) {
})
}
}

func TestUsageService_ReconcileUsageWithLedger(t *testing.T) {
dbconn := dbtest.ConnectForTests(t)
from := time.Date(2022, 05, 1, 0, 00, 00, 00, time.UTC)
to := time.Date(2022, 05, 1, 1, 00, 00, 00, time.UTC)

// stopped instances
dbtest.CreateWorkspaceInstances(t, dbconn, dbtest.NewWorkspaceInstance(t, db.WorkspaceInstance{
StoppingTime: db.NewVarcharTime(from.Add(1 * time.Minute)),
}))

// running instances
dbtest.CreateWorkspaceInstances(t, dbconn, dbtest.NewWorkspaceInstance(t, db.WorkspaceInstance{}))

// usage drafts
dbtest.CreateUsageRecords(t, dbconn, dbtest.NewUsage(t, db.Usage{
Kind: db.WorkspaceInstanceUsageKind,
Draft: true,
}))

srv := baseserver.NewForTests(t,
baseserver.WithGRPC(baseserver.MustUseRandomLocalAddress(t)),
)

v1.RegisterUsageServiceServer(srv.GRPC(), NewUsageService(dbconn, nil, nil))
baseserver.StartServerForTests(t, srv)

conn, err := grpc.Dial(srv.GRPCAddress(), grpc.WithTransportCredentials(insecure.NewCredentials()))
require.NoError(t, err)

client := v1.NewUsageServiceClient(conn)

_, err = client.ReconcileUsageWithLedger(context.Background(), &v1.ReconcileUsageWithLedgerRequest{
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doesn't assert the right instances were found because we don't yet update the records in any way. Once we start updating, the test here will be extended to do that.

From: timestamppb.New(from),
To: timestamppb.New(to),
})
require.NoError(t, err)
}
2 changes: 1 addition & 1 deletion components/usage/pkg/db/dbtest/usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func NewUsage(t *testing.T, record db.Usage) db.Usage {
Description: "some description",
CreditCents: 42,
EffectiveTime: db.VarcharTime{},
Kind: "workspaceinstance",
Kind: db.WorkspaceInstanceUsageKind,
WorkspaceInstanceID: uuid.New(),
}

Expand Down
9 changes: 8 additions & 1 deletion components/usage/pkg/db/usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,20 @@ import (
"gorm.io/gorm/clause"
)

type UsageKind string

const (
WorkspaceInstanceUsageKind UsageKind = "workspaceinstance"
InvoiceUsageKind = "invoice"
)

type Usage struct {
ID uuid.UUID `gorm:"primary_key;column:id;type:char;size:36;" json:"id"`
AttributionID AttributionID `gorm:"column:attributionId;type:varchar;size:255;" json:"attributionId"`
Description string `gorm:"column:description;type:varchar;size:255;" json:"description"`
CreditCents int64 `gorm:"column:creditCents;type:bigint;" json:"creditCents"`
EffectiveTime VarcharTime `gorm:"column:effectiveTime;type:varchar;size:255;" json:"effectiveTime"`
Kind string `gorm:"column:kind;type:char;size:10;" json:"kind"`
Kind UsageKind `gorm:"column:kind;type:char;size:10;" json:"kind"`
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

WorkspaceInstanceID uuid.UUID `gorm:"column:workspaceInstanceId;type:char;size:36;" json:"workspaceInstanceId"`
Draft bool `gorm:"column:draft;type:boolean;" json:"draft"`
Metadata datatypes.JSON `gorm:"column:metadata;type:text;size:65535" json:"metadata"`
Expand Down