Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/dashboard/src/usage/download/get-usage-records.ts
2500 views
1
/**
2
* Copyright (c) 2023 Gitpod GmbH. All rights reserved.
3
* Licensed under the GNU Affero General Public License (AGPL).
4
* See License.AGPL.txt in the project root for license information.
5
*/
6
7
import { ListUsageRequest, Ordering, Usage } from "@gitpod/gitpod-protocol/lib/usage";
8
import { getGitpodService } from "../../service/service";
9
10
type GetAllUsageRecordsArgs = Pick<ListUsageRequest, "attributionId" | "from" | "to"> & {
11
signal?: AbortSignal;
12
onProgress?: (percentage: number) => void;
13
};
14
15
export const getAllUsageRecords = async ({
16
attributionId,
17
from,
18
to,
19
signal,
20
onProgress,
21
}: GetAllUsageRecordsArgs): Promise<Usage[]> => {
22
let page = 1;
23
let totalPages: number | null = null;
24
let records: Usage[] = [];
25
26
while (totalPages === null || page <= totalPages) {
27
if (signal?.aborted === true) {
28
return [];
29
}
30
31
const timer = new Promise((r) => setTimeout(r, 1000));
32
33
const resp = await getUsagePage({
34
attributionId,
35
from,
36
to,
37
page,
38
});
39
records = records.concat(resp.usageEntriesList);
40
totalPages = resp.pagination?.totalPages ?? 0;
41
42
if (totalPages > 0) {
43
onProgress && onProgress(Math.ceil((page / totalPages) * 100));
44
}
45
46
// ensure we only call once per second
47
// TODO: consider starting timer here to ensure 1s between call completing and next call vs. 1s between start and next call
48
await timer;
49
50
page = page + 1;
51
}
52
53
return records;
54
};
55
56
type GetUsagePageArgs = Pick<ListUsageRequest, "attributionId" | "from" | "to"> & {
57
page: number;
58
};
59
const getUsagePage = async ({ attributionId, from, to, page }: GetUsagePageArgs) => {
60
const request: ListUsageRequest = {
61
attributionId,
62
from,
63
to,
64
order: Ordering.ORDERING_DESCENDING,
65
pagination: {
66
perPage: 1000,
67
page,
68
},
69
};
70
71
return await getGitpodService().server.listUsage(request);
72
};
73
74