-
Notifications
You must be signed in to change notification settings - Fork 399
Expand file tree
/
Copy pathutils.ts
More file actions
304 lines (274 loc) · 8.13 KB
/
utils.ts
File metadata and controls
304 lines (274 loc) · 8.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import { useRegionsQuery } from '@linode/queries';
import { capitalize, readableBytes } from '@linode/utilities';
import { object, string } from 'yup';
import { regionSelectGlobalOption } from 'src/components/RegionSelect/constants';
import { useObjectStorageEndpoints } from 'src/queries/object-storage/queries';
import type { QuotaIncreaseFormFields } from './QuotasIncreaseForm';
import type {
Filter,
Profile,
Quota,
QuotaType,
QuotaUsage,
Region,
} from '@linode/api-v4';
import type { SelectOption } from '@linode/ui';
import type { UseQueryResult } from '@tanstack/react-query';
const INCLUDED_OBJ_QUOTA_TYPES = [
'obj-bytes',
'obj-objects',
'obj-buckets',
'obj-total-ingress-throughput',
'obj-total-egress-throughput',
'obj-total-concurrent-requests',
];
const INCLUDED_OBJ_GLOBAL_QUOTA_TYPES = ['keys'];
export const QUOTA_ROW_MIN_HEIGHT = 58;
type UseGetLocationsForQuotaService =
| {
isFetchingRegions: boolean;
regions: Region[];
s3Endpoints: null;
service: Exclude<QuotaType, 'object-storage'>;
}
| {
isFetchingS3Endpoints: boolean;
regions: null;
s3Endpoints: { label: string; value: string }[];
service: Extract<QuotaType, 'object-storage'>;
};
/**
* Function to get either:
* - The region(s) for a given quota service (linode, lke, ...)
* - The s3 endpoint(s) (object-storage)
*/
export const useGetLocationsForQuotaService = (
service: QuotaType
): UseGetLocationsForQuotaService => {
const { data: regions, isFetching: isFetchingRegions } = useRegionsQuery();
// In order to get the s3 endpoints, we need to query the object storage service
// It will only show quotas for assigned endpoints (endpoints relevant to a region a user ever created a resource in).
const { data: s3Endpoints, isFetching: isFetchingS3Endpoints } =
useObjectStorageEndpoints(service === 'object-storage');
if (service === 'object-storage') {
return {
isFetchingS3Endpoints,
regions: null,
s3Endpoints: [
...(s3Endpoints ?? [])
.map((s3Endpoint) => {
if (!s3Endpoint.s3_endpoint) {
return null;
}
return {
label: `${s3Endpoint.s3_endpoint} (Standard ${s3Endpoint.endpoint_type})`,
value: s3Endpoint.s3_endpoint,
};
})
.filter((item) => item !== null),
],
service: 'object-storage',
};
}
return {
isFetchingRegions,
regions: [regionSelectGlobalOption, ...(regions ?? [])],
s3Endpoints: null,
service,
};
};
interface GetQuotasFiltersProps {
location: null | SelectOption<Quota['region_applied']>;
service: SelectOption<QuotaType>;
}
export interface QuotaWithUsage extends Quota {
usage: null | QuotaUsage;
}
export const getQuotaVisibilityFilter = (service: QuotaType) => {
return {
isVisible(quota: Quota) {
if (service === 'object-storage') {
return (
INCLUDED_OBJ_QUOTA_TYPES.includes(quota.quota_type) ||
INCLUDED_OBJ_GLOBAL_QUOTA_TYPES.includes(quota.quota_type)
);
}
return true;
},
};
};
export const getQuotaMapper = (service: QuotaType) => {
return {
mapQuota(quota: Quota, usage: null | QuotaUsage): QuotaWithUsage {
if (service === 'object-storage') {
return {
...quota,
quota_name: quota.quota_name.replace(' (per endpoint)', ''),
usage,
};
}
return {
...quota,
usage,
};
},
};
};
/**
* Function to get the filters for the quotas query
*/
export const getQuotasFilters = ({
location,
service,
}: GetQuotasFiltersProps): Filter => {
return {
region_applied:
service.value !== 'object-storage' ? location?.value : undefined,
s3_endpoint:
service.value === 'object-storage' ? location?.value : undefined,
};
};
/**
* Function to get the error for a given quota usage query
*/
export const getQuotaError = (
quotaUsageQueries: UseQueryResult<QuotaUsage, Error>[],
index: number
) => {
return Array.isArray(quotaUsageQueries[index].error) &&
quotaUsageQueries[index].error[0]?.reason
? quotaUsageQueries[index].error[0].reason
: 'An unexpected error occurred';
};
interface GetQuotaIncreaseFormDefaultValuesProps {
convertedMetrics: {
limit: number;
metric: string;
};
neededIn: string;
profile: Profile | undefined;
quantity: number;
quota: Quota;
selectedService: SelectOption<QuotaType>;
}
/**
* Function to get the default values for the quota increase form
*/
export const getQuotaIncreaseMessage = ({
convertedMetrics,
neededIn,
profile,
quantity,
quota,
selectedService,
}: GetQuotaIncreaseFormDefaultValuesProps): QuotaIncreaseFormFields => {
const regionAppliedLabel = quota.s3_endpoint ? 'Endpoint' : 'Region';
const regionAppliedValue = quota.s3_endpoint ?? quota.region_applied;
if (!profile) {
return {
description: '',
neededIn: 'Fewer than 7 days',
notes: '',
quantity: '0',
summary: `Increase ${selectedService.label} Quota`,
};
}
return {
description:
`**User**: ${profile.username}<br>\n**Email**: ${
profile.email
}<br>\n**Quota Name**: ${
quota.quota_name
}<br>\n**Current Quota**: ${convertedMetrics.limit?.toLocaleString()} ${
convertedMetrics.metric
}<br>\n**New Quota Requested**: ${quantity?.toLocaleString()} ${
convertedMetrics.metric
}<br>\n**Needed in**: ${neededIn}<br>\n` +
(regionAppliedValue
? `**${regionAppliedLabel}**: ${regionAppliedValue}`
: ''),
neededIn: 'Fewer than 7 days',
notes: '',
quantity: String(quantity),
summary: `Increase ${selectedService.label} Quota`,
};
};
interface ConvertResourceMetricProps {
initialLimit: number;
initialResourceMetric: string;
initialUsage: number;
}
/**
* Function to convert the resource metric to a human readable format
*/
export const convertResourceMetric = ({
initialResourceMetric,
initialUsage,
initialLimit,
}: ConvertResourceMetricProps): {
convertedLimit: number;
convertedResourceMetric: string;
convertedUsage: number;
} => {
if (initialResourceMetric === 'byte') {
const limitReadable = readableBytes(initialLimit);
return {
convertedUsage: readableBytes(initialUsage, {
unit: limitReadable.unit,
}).value,
convertedResourceMetric: capitalize(limitReadable.unit),
convertedLimit: limitReadable.value,
};
}
if (initialResourceMetric === 'byte_per_second') {
return {
convertedUsage: 0,
convertedResourceMetric: 'Gbps',
convertedLimit: readableBytes(initialLimit, {
unit: 'GB',
base10: true,
}).value,
};
}
return {
convertedUsage: initialUsage,
convertedLimit: initialLimit,
convertedResourceMetric: capitalize(initialResourceMetric),
};
};
/**
* Function to pluralize the resource metric
* If the unit is 'byte', we need to return the unit without an 's' (ex: 'GB', 'MB', 'TB')
* Otherwise, we need to return the unit with an 's' (ex: 'Buckets', 'Objects')
*
* Note: the value should be the raw values in bytes, not an existing conversion
*/
export const pluralizeMetric = (value: number, unit: string) => {
if (unit === 'byte_per_second') {
return unit;
}
if (unit !== 'byte') {
return value > 1 ? `${unit}s` : unit;
}
return unit;
};
export const getQuotaIncreaseFormSchema = (currentLimit: number) =>
object({
description: string().required('Description is required.'),
neededIn: string().required('Needed in is required.'),
notes: string()
.required('Description is required.')
.max(255, 'Description must be less than 255 characters.'),
quantity: string()
.required('Quantity is required')
.test(
'is-greater-than-limit',
`Quantity must be greater than the current quota of ${currentLimit.toLocaleString()}.`,
(value) => {
const num = parseFloat(value);
return !isNaN(num) && num > currentLimit;
}
),
// .matches(/^\d*\.?\d*$/, 'Must be a valid number'), // allows decimals
summary: string().required('Summary is required.'),
});