Skip to content

Commit 0f1c12b

Browse files
committed
wip(6) add totalCreditsUsed
1 parent 0ac42ba commit 0f1c12b

File tree

10 files changed

+165
-106
lines changed

10 files changed

+165
-106
lines changed

components/dashboard/src/teams/TeamUsage.tsx

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ function TeamUsage() {
3737
const timestampStartOfCurrentMonth = startOfCurrentMonth.getTime();
3838
const [startDateOfBillMonth, setStartDateOfBillMonth] = useState(timestampStartOfCurrentMonth);
3939
const [endDateOfBillMonth, setEndDateOfBillMonth] = useState(Date.now());
40+
const [totalCreditsUsed, setTotalCreditsUsed] = useState<number>(0);
4041
const [isLoading, setIsLoading] = useState<boolean>(true);
4142

4243
useEffect(() => {
@@ -71,6 +72,7 @@ function TeamUsage() {
7172
}
7273
if (usagePage === undefined) {
7374
setIsLoading(true);
75+
setTotalCreditsUsed(0);
7476
}
7577
const attributionId = AttributionId.render({ kind: "team", teamId: team.id });
7678
const request: ListBilledUsageRequest = {
@@ -83,6 +85,7 @@ function TeamUsage() {
8385
try {
8486
const page = await getGitpodService().server.listBilledUsage(request);
8587
setUsagePage(page);
88+
setTotalCreditsUsed(Math.ceil(page.totalCreditsUsed));
8689
} catch (error) {
8790
if (error.code === ErrorCodes.PERMISSION_DENIED) {
8891
setErrorMessage("Access to usage details is restricted to team owners.");
@@ -177,13 +180,15 @@ function TeamUsage() {
177180
<div className="text-base text-gray-500 truncate">Previous Months</div>
178181
{getBillingHistory()}
179182
</div>
180-
<div className="flex flex-col truncate">
181-
<div className="text-base text-gray-500">Total usage</div>
182-
<div className="flex text-lg text-gray-600 font-semibold">
183-
<CreditsSvg className="my-auto mr-1" />
184-
<span>TODO Credits</span>
183+
{!isLoading && (
184+
<div className="flex flex-col truncate">
185+
<div className="text-base text-gray-500">Total usage</div>
186+
<div className="flex text-lg text-gray-600 font-semibold">
187+
<CreditsSvg className="my-auto mr-1" />
188+
<span>${totalCreditsUsed} Credits</span>
189+
</div>
185190
</div>
186-
</div>
191+
)}
187192
</div>
188193
</div>
189194
{!isLoading && usagePage === undefined && !errorMessage && (

components/gitpod-protocol/src/usage.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ export interface ListBilledUsageRequest {
5353

5454
export interface ListBilledUsageResponse {
5555
sessions: ExtendedBillableSession[];
56+
totalCreditsUsed: number;
5657
totalPages: number;
5758
total: number;
5859
perPage: number;

components/server/ee/src/workspace/gitpod-server-impl.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2202,6 +2202,7 @@ export class GitpodServerEEImpl extends GitpodServerImpl {
22022202
totalPages: response.getTotalPages(),
22032203
page: response.getPage(),
22042204
perPage: response.getPerPage(),
2205+
totalCreditsUsed: response.getTotalCreditsUsed(),
22052206
};
22062207
}
22072208

components/usage-api/go/v1/usage.pb.go

Lines changed: 96 additions & 86 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

components/usage-api/typescript/src/usage/v1/usage_pb.d.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,8 @@ export class ListBilledUsageResponse extends jspb.Message {
7373
setTotal(value: number): ListBilledUsageResponse;
7474
getPage(): number;
7575
setPage(value: number): ListBilledUsageResponse;
76+
getTotalCreditsUsed(): number;
77+
setTotalCreditsUsed(value: number): ListBilledUsageResponse;
7678

7779
serializeBinary(): Uint8Array;
7880
toObject(includeInstance?: boolean): ListBilledUsageResponse.AsObject;
@@ -91,6 +93,7 @@ export namespace ListBilledUsageResponse {
9193
totalPages: number,
9294
total: number,
9395
page: number,
96+
totalCreditsUsed: number,
9497
}
9598
}
9699

components/usage-api/typescript/src/usage/v1/usage_pb.js

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -574,7 +574,8 @@ proto.usage.v1.ListBilledUsageResponse.toObject = function(includeInstance, msg)
574574
perPage: jspb.Message.getFieldWithDefault(msg, 2, 0),
575575
totalPages: jspb.Message.getFieldWithDefault(msg, 3, 0),
576576
total: jspb.Message.getFieldWithDefault(msg, 4, 0),
577-
page: jspb.Message.getFieldWithDefault(msg, 5, 0)
577+
page: jspb.Message.getFieldWithDefault(msg, 5, 0),
578+
totalCreditsUsed: jspb.Message.getFieldWithDefault(msg, 6, 0)
578579
};
579580

580581
if (includeInstance) {
@@ -632,6 +633,10 @@ proto.usage.v1.ListBilledUsageResponse.deserializeBinaryFromReader = function(ms
632633
var value = /** @type {number} */ (reader.readInt64());
633634
msg.setPage(value);
634635
break;
636+
case 6:
637+
var value = /** @type {number} */ (reader.readInt64());
638+
msg.setTotalCreditsUsed(value);
639+
break;
635640
default:
636641
reader.skipField();
637642
break;
@@ -697,6 +702,13 @@ proto.usage.v1.ListBilledUsageResponse.serializeBinaryToWriter = function(messag
697702
f
698703
);
699704
}
705+
f = message.getTotalCreditsUsed();
706+
if (f !== 0) {
707+
writer.writeInt64(
708+
6,
709+
f
710+
);
711+
}
700712
};
701713

702714

@@ -810,6 +822,24 @@ proto.usage.v1.ListBilledUsageResponse.prototype.setPage = function(value) {
810822
};
811823

812824

825+
/**
826+
* optional int64 total_credits_used = 6;
827+
* @return {number}
828+
*/
829+
proto.usage.v1.ListBilledUsageResponse.prototype.getTotalCreditsUsed = function() {
830+
return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 6, 0));
831+
};
832+
833+
834+
/**
835+
* @param {number} value
836+
* @return {!proto.usage.v1.ListBilledUsageResponse} returns this
837+
*/
838+
proto.usage.v1.ListBilledUsageResponse.prototype.setTotalCreditsUsed = function(value) {
839+
return jspb.Message.setProto3IntField(this, 6, value);
840+
};
841+
842+
813843

814844

815845

components/usage-api/usage/v1/usage.proto

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ message ListBilledUsageResponse {
4545
int64 total_pages = 3;
4646
int64 total = 4;
4747
int64 page = 5;
48+
int64 total_credits_used = 6;
4849
}
4950

5051
message BilledSession {

components/usage/pkg/apiv1/usage.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ func (s *UsageService) ListBilledUsage(ctx context.Context, in *v1.ListBilledUsa
6565
var offset = perPage * (int64(math.Max(0, float64(page-1))))
6666
var limit = perPage
6767

68-
usageRecords, total, err := db.ListUsage(ctx, s.conn, db.AttributionID(in.GetAttributionId()), from, to, order, offset, limit)
68+
usageRecords, total, _, err := db.ListUsage(ctx, s.conn, db.AttributionID(in.GetAttributionId()), from, to, order, offset, limit)
6969
if err != nil {
7070
log.Log.
7171
WithField("attribution_id", in.AttributionId).

components/usage/pkg/db/workspace_instance_usage.go

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -65,13 +65,15 @@ const (
6565
AscendingOrder
6666
)
6767

68-
func ListUsage(ctx context.Context, conn *gorm.DB, attributionId AttributionID, from, to time.Time, sort Order, offset int64, limit int64) ([]WorkspaceInstanceUsage, int64, error) {
68+
func ListUsage(ctx context.Context, conn *gorm.DB, attributionId AttributionID, from, to time.Time, sort Order, offset int64, limit int64) ([]WorkspaceInstanceUsage, int64, float64, error) {
6969
db := conn.WithContext(ctx)
7070

71+
var totalCreditsUsed float64
7172
var count int64
72-
countResult := db.
73+
countResult, err := db.
7374
WithContext(ctx).
7475
Table((&WorkspaceInstanceUsage{}).TableName()).
76+
Select("sum(creditsUsed) as totalCreditsUsed", "count(*) as count").
7577
Order(fmt.Sprintf("startedAt %s", sort.ToSQL())).
7678
Where("attributionId = ?", attributionId).
7779
Where(
@@ -84,9 +86,13 @@ func ListUsage(ctx context.Context, conn *gorm.DB, attributionId AttributionID,
8486
// started before query range, still running
8587
Or("startedAt <= ? AND (stoppedAt > ? OR stoppedAt IS NULL)", from, to),
8688
).
87-
Count(&count)
88-
if countResult.Error != nil {
89-
return nil, 0, fmt.Errorf("failed to get count of usage records: %s", countResult.Error)
89+
Rows()
90+
if err != nil || !countResult.Next() {
91+
return nil, 0, 0, fmt.Errorf("failed to get count of usage records: %s", err)
92+
}
93+
err = countResult.Scan(&totalCreditsUsed, &count)
94+
if err != nil {
95+
return nil, 0, 0, fmt.Errorf("failed to get count of usage records: %s", err)
9096
}
9197

9298
var usageRecords []WorkspaceInstanceUsage
@@ -109,7 +115,7 @@ func ListUsage(ctx context.Context, conn *gorm.DB, attributionId AttributionID,
109115
Limit(int(limit)).
110116
Find(&usageRecords)
111117
if result.Error != nil {
112-
return nil, 0, fmt.Errorf("failed to get usage records: %s", result.Error)
118+
return nil, 0, 0, fmt.Errorf("failed to get usage records: %s", result.Error)
113119
}
114-
return usageRecords, count, nil
120+
return usageRecords, count, totalCreditsUsed, nil
115121
}

components/usage/pkg/db/workspace_instance_usage_test.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ func TestCreateUsageRecords_Updates(t *testing.T) {
6060
conn.Model(&db.WorkspaceInstanceUsage{}).Delete(update)
6161
})
6262

63-
list, total, err := db.ListUsage(context.Background(), conn, teamAttributionID, time.Date(2022, 7, 1, 0, 0, 0, 0, time.UTC), time.Date(2022, 8, 1, 0, 0, 0, 0, time.UTC), db.DescendingOrder, int64(0), int64(100))
63+
list, total, _, err := db.ListUsage(context.Background(), conn, teamAttributionID, time.Date(2022, 7, 1, 0, 0, 0, 0, time.UTC), time.Date(2022, 8, 1, 0, 0, 0, 0, time.UTC), db.DescendingOrder, int64(0), int64(100))
6464
require.NoError(t, err)
6565
require.Len(t, list, 1)
6666
require.Equal(t, int64(1), total)
@@ -92,7 +92,7 @@ func TestListUsage_Ordering(t *testing.T) {
9292
conn.Model(&db.WorkspaceInstanceUsage{}).Delete(instances)
9393
})
9494

95-
listed, _, err := db.ListUsage(context.Background(), conn, teamAttributionID, time.Date(2022, 7, 1, 0, 0, 0, 0, time.UTC), time.Date(2022, 8, 1, 0, 0, 0, 0, time.UTC), db.AscendingOrder, int64(0), int64(100))
95+
listed, _, _, err := db.ListUsage(context.Background(), conn, teamAttributionID, time.Date(2022, 7, 1, 0, 0, 0, 0, time.UTC), time.Date(2022, 8, 1, 0, 0, 0, 0, time.UTC), db.AscendingOrder, int64(0), int64(100))
9696
require.NoError(t, err)
9797

9898
require.Equal(t, []db.WorkspaceInstanceUsage{oldest, newest}, listed)
@@ -179,7 +179,7 @@ func TestListUsageInRange(t *testing.T) {
179179
instances := []db.WorkspaceInstanceUsage{startBeforeFinishBefore, startBeforeFinishInside, startInsideFinishInside, startInsideFinishInsideButDifferentAttributionID, startedInsideFinishedOutside, startedOutsideFinishedOutside, startedBeforeAndStillRunning, startedInsideAndStillRunning}
180180
dbtest.CreateWorkspaceInstanceUsageRecords(t, conn, instances...)
181181

182-
results, _, err := db.ListUsage(context.Background(), conn, attributionID, start, end, db.DescendingOrder, int64(0), int64(100))
182+
results, _, _, err := db.ListUsage(context.Background(), conn, attributionID, start, end, db.DescendingOrder, int64(0), int64(100))
183183
require.NoError(t, err)
184184

185185
require.Len(t, results, 5)
@@ -204,6 +204,7 @@ func TestListUsagePagination(t *testing.T) {
204204
Time: start.Add(5 * time.Hour),
205205
Valid: true,
206206
},
207+
CreditsUsed: float64(2),
207208
})
208209

209210
var instances []db.WorkspaceInstanceUsage
@@ -213,9 +214,10 @@ func TestListUsagePagination(t *testing.T) {
213214
}
214215
dbtest.CreateWorkspaceInstanceUsageRecords(t, conn, instances...)
215216

216-
results, total, err := db.ListUsage(context.Background(), conn, attributionID, start, end, db.DescendingOrder, int64(100), int64(50))
217+
results, total, totalCreditsUsed, err := db.ListUsage(context.Background(), conn, attributionID, start, end, db.DescendingOrder, int64(100), int64(50))
217218
require.NoError(t, err)
218219

219220
require.Len(t, results, 22)
220-
require.Equal(t, total, int64(122))
221+
require.Equal(t, float64(244), totalCreditsUsed)
222+
require.Equal(t, int64(122), total)
221223
}

0 commit comments

Comments
 (0)