-
Notifications
You must be signed in to change notification settings - Fork 14
/
common.ts
266 lines (236 loc) · 8.07 KB
/
common.ts
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
/**
* JavaScript and Node.js SDK for OpenFGA
*
* API version: 1.x
* Website: https://openfga.dev
* Documentation: https://openfga.dev/docs
* Support: https://openfga.dev/community
* License: [Apache-2.0](https://github.com/openfga/js-sdk/blob/main/LICENSE)
*
* NOTE: This file was auto generated by OpenAPI Generator (https://openapi-generator.tech). DO NOT EDIT.
*/
import { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { Configuration } from "./configuration";
import type { Credentials } from "./credentials";
import {
FgaApiError,
FgaApiInternalError,
FgaApiAuthenticationError,
FgaApiNotFoundError,
FgaApiRateLimitExceededError,
FgaApiValidationError,
FgaError
} from "./errors";
import { setNotEnumerableProperty } from "./utils";
import { TelemetryAttribute, TelemetryAttributes } from "./telemetry/attributes";
import { MetricRecorder } from "./telemetry/metrics";
import { TelemetryHistograms } from "./telemetry/histograms";
/**
*
* @export
*/
export const DUMMY_BASE_URL = "https://example.com";
/**
*
* @export
* @interface RequestArgs
*/
export interface RequestArgs {
url: string;
options: any;
}
/**
*
* @export
*/
export const setBearerAuthToObject = async function (object: any, credentials: Credentials) {
const accessTokenHeader = await credentials.getAccessTokenHeader();
if (accessTokenHeader && !object[accessTokenHeader.name]) {
object[accessTokenHeader.name] = accessTokenHeader.value;
}
};
/**
*
* @export
*/
export const setSearchParams = function (url: URL, ...objects: any[]) {
const searchParams = new URLSearchParams(url.search);
for (const object of objects) {
for (const key in object) {
if (Array.isArray(object[key])) {
searchParams.delete(key);
for (const item of object[key]) {
searchParams.append(key, item);
}
} else {
searchParams.set(key, object[key]);
}
}
}
url.search = searchParams.toString();
};
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise.
*/
const isJsonMime = (mime: string): boolean => {
// eslint-disable-next-line no-control-regex
const jsonMime = new RegExp("^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$", "i");
return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === "application/json-patch+json");
};
/**
*
* @export
*/
export const serializeDataIfNeeded = function (value: any, requestOptions: any) {
const nonString = typeof value !== "string";
const needsSerialization = nonString
? isJsonMime(requestOptions.headers["Content-Type"])
: nonString;
return needsSerialization
? JSON.stringify(value !== undefined ? value : {})
: (value || "");
};
/**
*
* @export
*/
export const toPathString = function (url: URL) {
return url.pathname + url.search + url.hash;
};
type ObjectOrVoid = object | void;
interface StringIndexable {
[key: string]: any;
}
export type CallResult<T extends ObjectOrVoid> = T & {
$response: AxiosResponse<T>
};
export type PromiseResult<T extends ObjectOrVoid> = Promise<CallResult<T>>;
/**
* Returns true if this error is returned from axios
* source: https://github.com/axios/axios/blob/21a5ad34c4a5956d81d338059ac0dd34a19ed094/lib/helpers/isAxiosError.js#L12
* @param err
*/
function isAxiosError(err: any): boolean {
return err && typeof err === "object" && err.isAxiosError === true;
}
function randomTime(loopCount: number, minWaitInMs: number): number {
const min = Math.ceil(2 ** loopCount * minWaitInMs);
const max = Math.ceil(2 ** (loopCount + 1) * minWaitInMs);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
interface WrappedAxiosResponse<R> {
response?: AxiosResponse<R>;
retries: number;
}
export async function attemptHttpRequest<B, R>(
request: AxiosRequestConfig<B>,
config: {
maxRetry: number;
minWaitInMs: number;
},
axiosInstance: AxiosInstance,
): Promise<WrappedAxiosResponse<R> | undefined> {
let iterationCount = 0;
do {
iterationCount++;
try {
const response = await axiosInstance(request);
return {
response: response,
retries: iterationCount - 1,
};
} catch (err: any) {
if (!isAxiosError(err)) {
throw new FgaError(err);
}
const status = (err as any)?.response?.status;
if (status === 400 || status === 422) {
throw new FgaApiValidationError(err);
} else if (status === 401 || status === 403) {
throw new FgaApiAuthenticationError(err);
} else if (status === 404) {
throw new FgaApiNotFoundError(err);
} else if (status === 429 || status >= 500) {
if (iterationCount >= config.maxRetry) {
// We have reached the max retry limit
// Thus, we have no choice but to throw
if (status === 429) {
throw new FgaApiRateLimitExceededError(err);
} else {
throw new FgaApiInternalError(err);
}
}
await new Promise(r => setTimeout(r, randomTime(iterationCount, config.minWaitInMs)));
} else {
throw new FgaApiError(err);
}
}
} while(iterationCount < config.maxRetry + 1);
}
/**
* creates an axios request function
*/
export const createRequestFunction = function (axiosArgs: RequestArgs, axiosInstance: AxiosInstance, configuration: Configuration, credentials: Credentials, methodAttributes: Record<string, string | number> = {}) {
configuration.isValid();
const retryParams = axiosArgs.options?.retryParams ? axiosArgs.options?.retryParams : configuration.retryParams;
const maxRetry:number = retryParams ? retryParams.maxRetry : 0;
const minWaitInMs:number = retryParams ? retryParams.minWaitInMs : 0;
const start = performance.now();
return async (axios: AxiosInstance = axiosInstance) : PromiseResult<any> => {
await setBearerAuthToObject(axiosArgs.options.headers, credentials!);
const url = configuration.getBasePath() + axiosArgs.url;
const axiosRequestArgs = {...axiosArgs.options, url: url};
const wrappedResponse = await attemptHttpRequest(axiosRequestArgs, {
maxRetry,
minWaitInMs,
}, axios);
const response = wrappedResponse?.response;
const data = typeof response?.data === "undefined" ? {} : response?.data;
const result: CallResult<any> = { ...data };
setNotEnumerableProperty(result, "$response", response);
let attributes: StringIndexable = {};
attributes = TelemetryAttributes.fromRequest({
userAgent: configuration.baseOptions?.headers["User-Agent"],
httpMethod: axiosArgs.options?.method,
url,
resendCount: wrappedResponse?.retries,
start: start,
credentials: credentials,
attributes: methodAttributes,
});
attributes = TelemetryAttributes.fromResponse({
response,
attributes,
});
// only if hisogramQueryDuration set AND if response header contains fga-query-duration-ms
const serverRequestDuration = attributes[TelemetryAttribute.HttpServerRequestDuration];
if (configuration.telemetry?.metrics?.histogramQueryDuration && typeof serverRequestDuration !== "undefined") {
configuration.telemetry.recorder.histogram(
TelemetryHistograms.queryDuration,
parseInt(attributes[TelemetryAttribute.HttpServerRequestDuration] as string, 10),
TelemetryAttributes.prepare(
attributes,
configuration.telemetry.metrics.histogramQueryDuration.attributes
)
);
}
if (configuration.telemetry?.metrics?.histogramRequestDuration) {
configuration.telemetry.recorder.histogram(
TelemetryHistograms.requestDuration,
attributes[TelemetryAttribute.HttpClientRequestDuration],
TelemetryAttributes.prepare(
attributes,
configuration.telemetry.metrics.histogramRequestDuration.attributes
)
);
}
return result;
};
};