@algolia/client-common 4.14.2 → 5.0.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/dist/client-common.cjs.js +803 -91
  2. package/dist/client-common.esm.node.js +774 -0
  3. package/dist/index.d.ts +10 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/src/cache/createBrowserLocalStorageCache.d.ts +3 -0
  6. package/dist/src/cache/createBrowserLocalStorageCache.d.ts.map +1 -0
  7. package/dist/src/cache/createFallbackableCache.d.ts +3 -0
  8. package/dist/src/cache/createFallbackableCache.d.ts.map +1 -0
  9. package/dist/src/cache/createMemoryCache.d.ts +3 -0
  10. package/dist/src/cache/createMemoryCache.d.ts.map +1 -0
  11. package/dist/src/cache/createNullCache.d.ts +3 -0
  12. package/dist/src/cache/createNullCache.d.ts.map +1 -0
  13. package/dist/src/cache/index.d.ts +5 -0
  14. package/dist/src/cache/index.d.ts.map +1 -0
  15. package/dist/src/constants.d.ts +7 -0
  16. package/dist/src/constants.d.ts.map +1 -0
  17. package/dist/src/createAlgoliaAgent.d.ts +3 -0
  18. package/dist/src/createAlgoliaAgent.d.ts.map +1 -0
  19. package/dist/src/createAuth.d.ts +6 -0
  20. package/dist/src/createAuth.d.ts.map +1 -0
  21. package/dist/src/createEchoRequester.d.ts +7 -0
  22. package/dist/src/createEchoRequester.d.ts.map +1 -0
  23. package/dist/src/createRetryablePromise.d.ts +14 -0
  24. package/dist/src/createRetryablePromise.d.ts.map +1 -0
  25. package/dist/src/getAlgoliaAgent.d.ts +8 -0
  26. package/dist/src/getAlgoliaAgent.d.ts.map +1 -0
  27. package/dist/src/transporter/createStatefulHost.d.ts +3 -0
  28. package/dist/src/transporter/createStatefulHost.d.ts.map +1 -0
  29. package/dist/src/transporter/createTransporter.d.ts +3 -0
  30. package/dist/src/transporter/createTransporter.d.ts.map +1 -0
  31. package/dist/src/transporter/errors.d.ts +21 -0
  32. package/dist/src/transporter/errors.d.ts.map +1 -0
  33. package/dist/src/transporter/helpers.d.ts +9 -0
  34. package/dist/src/transporter/helpers.d.ts.map +1 -0
  35. package/dist/src/transporter/index.d.ts +7 -0
  36. package/dist/src/transporter/index.d.ts.map +1 -0
  37. package/dist/src/transporter/responses.d.ts +5 -0
  38. package/dist/src/transporter/responses.d.ts.map +1 -0
  39. package/dist/src/transporter/stackTrace.d.ts +4 -0
  40. package/dist/src/transporter/stackTrace.d.ts.map +1 -0
  41. package/dist/src/types/Cache.d.ts +47 -0
  42. package/dist/src/types/Cache.d.ts.map +1 -0
  43. package/dist/src/types/CreateClient.d.ts +12 -0
  44. package/dist/src/types/CreateClient.d.ts.map +1 -0
  45. package/dist/src/types/CreateRetryablePromise.d.ts +19 -0
  46. package/dist/src/types/CreateRetryablePromise.d.ts.map +1 -0
  47. package/dist/src/types/Host.d.ts +33 -0
  48. package/dist/src/types/Host.d.ts.map +1 -0
  49. package/dist/src/types/Requester.d.ts +66 -0
  50. package/dist/src/types/Requester.d.ts.map +1 -0
  51. package/dist/src/types/Transporter.d.ts +128 -0
  52. package/dist/src/types/Transporter.d.ts.map +1 -0
  53. package/dist/src/types/index.d.ts +7 -0
  54. package/dist/src/types/index.d.ts.map +1 -0
  55. package/index.ts +9 -0
  56. package/package.json +24 -15
  57. package/src/__tests__/cache/browser-local-storage-cache.test.ts +134 -0
  58. package/src/__tests__/cache/fallbackable-cache.test.ts +126 -0
  59. package/src/__tests__/cache/memory-cache.test.ts +90 -0
  60. package/src/__tests__/cache/null-cache.test.ts +49 -0
  61. package/src/__tests__/create-retryable-promise.test.ts +86 -0
  62. package/src/cache/createBrowserLocalStorageCache.ts +74 -0
  63. package/src/cache/createFallbackableCache.ts +53 -0
  64. package/src/cache/createMemoryCache.ts +56 -0
  65. package/src/cache/createNullCache.ts +34 -0
  66. package/src/cache/index.ts +4 -0
  67. package/src/constants.ts +7 -0
  68. package/src/createAlgoliaAgent.ts +20 -0
  69. package/src/createAuth.ts +25 -0
  70. package/src/createEchoRequester.ts +59 -0
  71. package/src/createRetryablePromise.ts +52 -0
  72. package/src/getAlgoliaAgent.ts +25 -0
  73. package/src/transporter/createStatefulHost.ts +24 -0
  74. package/src/transporter/createTransporter.ts +347 -0
  75. package/src/transporter/errors.ts +51 -0
  76. package/src/transporter/helpers.ts +119 -0
  77. package/src/transporter/index.ts +6 -0
  78. package/src/transporter/responses.ts +23 -0
  79. package/src/transporter/stackTrace.ts +30 -0
  80. package/src/types/Cache.ts +61 -0
  81. package/src/types/CreateClient.ts +23 -0
  82. package/src/types/CreateRetryablePromise.ts +21 -0
  83. package/src/types/Host.ts +38 -0
  84. package/src/types/Requester.ts +72 -0
  85. package/src/types/Transporter.ts +153 -0
  86. package/src/types/index.ts +6 -0
  87. package/dist/client-common.d.ts +0 -102
  88. package/dist/client-common.esm.js +0 -89
  89. package/index.js +0 -2
@@ -0,0 +1,56 @@
1
+ import type { Cache, CacheEvents, MemoryCacheOptions } from '../types';
2
+
3
+ export function createMemoryCache(
4
+ options: MemoryCacheOptions = { serializable: true }
5
+ ): Cache {
6
+ let cache: Record<string, any> = {};
7
+
8
+ return {
9
+ get<TValue>(
10
+ key: Record<string, any> | string,
11
+ defaultValue: () => Promise<TValue>,
12
+ events: CacheEvents<TValue> = {
13
+ miss: (): Promise<void> => Promise.resolve(),
14
+ }
15
+ ): Promise<TValue> {
16
+ const keyAsString = JSON.stringify(key);
17
+
18
+ if (keyAsString in cache) {
19
+ return Promise.resolve(
20
+ options.serializable
21
+ ? JSON.parse(cache[keyAsString])
22
+ : cache[keyAsString]
23
+ );
24
+ }
25
+
26
+ const promise = defaultValue();
27
+
28
+ return promise
29
+ .then((value: TValue) => events.miss(value))
30
+ .then(() => promise);
31
+ },
32
+
33
+ set<TValue>(
34
+ key: Record<string, any> | string,
35
+ value: TValue
36
+ ): Promise<TValue> {
37
+ cache[JSON.stringify(key)] = options.serializable
38
+ ? JSON.stringify(value)
39
+ : value;
40
+
41
+ return Promise.resolve(value);
42
+ },
43
+
44
+ delete(key: Record<string, unknown> | string): Promise<void> {
45
+ delete cache[JSON.stringify(key)];
46
+
47
+ return Promise.resolve();
48
+ },
49
+
50
+ clear(): Promise<void> {
51
+ cache = {};
52
+
53
+ return Promise.resolve();
54
+ },
55
+ };
56
+ }
@@ -0,0 +1,34 @@
1
+ import type { Cache, CacheEvents } from '../types';
2
+
3
+ export function createNullCache(): Cache {
4
+ return {
5
+ get<TValue>(
6
+ _key: Record<string, any> | string,
7
+ defaultValue: () => Promise<TValue>,
8
+ events: CacheEvents<TValue> = {
9
+ miss: (): Promise<void> => Promise.resolve(),
10
+ }
11
+ ): Promise<TValue> {
12
+ const value = defaultValue();
13
+
14
+ return value
15
+ .then((result) => Promise.all([result, events.miss(result)]))
16
+ .then(([result]) => result);
17
+ },
18
+
19
+ set<TValue>(
20
+ _key: Record<string, any> | string,
21
+ value: TValue
22
+ ): Promise<TValue> {
23
+ return Promise.resolve(value);
24
+ },
25
+
26
+ delete(_key: Record<string, any> | string): Promise<void> {
27
+ return Promise.resolve();
28
+ },
29
+
30
+ clear(): Promise<void> {
31
+ return Promise.resolve();
32
+ },
33
+ };
34
+ }
@@ -0,0 +1,4 @@
1
+ export * from './createBrowserLocalStorageCache';
2
+ export * from './createFallbackableCache';
3
+ export * from './createMemoryCache';
4
+ export * from './createNullCache';
@@ -0,0 +1,7 @@
1
+ export const DEFAULT_CONNECT_TIMEOUT_BROWSER = 1000;
2
+ export const DEFAULT_READ_TIMEOUT_BROWSER = 2000;
3
+ export const DEFAULT_WRITE_TIMEOUT_BROWSER = 30000;
4
+
5
+ export const DEFAULT_CONNECT_TIMEOUT_NODE = 2000;
6
+ export const DEFAULT_READ_TIMEOUT_NODE = 5000;
7
+ export const DEFAULT_WRITE_TIMEOUT_NODE = 30000;
@@ -0,0 +1,20 @@
1
+ import type { AlgoliaAgentOptions, AlgoliaAgent } from './types';
2
+
3
+ export function createAlgoliaAgent(version: string): AlgoliaAgent {
4
+ const algoliaAgent = {
5
+ value: `Algolia for JavaScript (${version})`,
6
+ add(options: AlgoliaAgentOptions): AlgoliaAgent {
7
+ const addedAlgoliaAgent = `; ${options.segment}${
8
+ options.version !== undefined ? ` (${options.version})` : ''
9
+ }`;
10
+
11
+ if (algoliaAgent.value.indexOf(addedAlgoliaAgent) === -1) {
12
+ algoliaAgent.value = `${algoliaAgent.value}${addedAlgoliaAgent}`;
13
+ }
14
+
15
+ return algoliaAgent;
16
+ },
17
+ };
18
+
19
+ return algoliaAgent;
20
+ }
@@ -0,0 +1,25 @@
1
+ import type { AuthMode, Headers, QueryParameters } from './types';
2
+
3
+ export function createAuth(
4
+ appId: string,
5
+ apiKey: string,
6
+ authMode: AuthMode = 'WithinHeaders'
7
+ ): {
8
+ readonly headers: () => Headers;
9
+ readonly queryParameters: () => QueryParameters;
10
+ } {
11
+ const credentials = {
12
+ 'x-algolia-api-key': apiKey,
13
+ 'x-algolia-application-id': appId,
14
+ };
15
+
16
+ return {
17
+ headers(): Headers {
18
+ return authMode === 'WithinHeaders' ? credentials : {};
19
+ },
20
+
21
+ queryParameters(): QueryParameters {
22
+ return authMode === 'WithinQueryParameters' ? credentials : {};
23
+ },
24
+ };
25
+ }
@@ -0,0 +1,59 @@
1
+ import type { EchoResponse, EndRequest, Requester, Response } from './types';
2
+
3
+ export type EchoRequesterParams = {
4
+ getURL: (url: string) => URL;
5
+ status?: number;
6
+ };
7
+
8
+ function getUrlParams({
9
+ host,
10
+ searchParams: urlSearchParams,
11
+ pathname,
12
+ }: URL): Pick<EchoResponse, 'algoliaAgent' | 'host' | 'path' | 'searchParams'> {
13
+ const algoliaAgent = urlSearchParams.get('x-algolia-agent') || '';
14
+ const searchParams = {};
15
+
16
+ for (const [k, v] of urlSearchParams) {
17
+ if (k === 'x-algolia-agent') {
18
+ continue;
19
+ }
20
+
21
+ searchParams[k] = v;
22
+ }
23
+
24
+ return {
25
+ host,
26
+ algoliaAgent,
27
+ searchParams:
28
+ Object.keys(searchParams).length === 0 ? undefined : searchParams,
29
+ path: pathname,
30
+ };
31
+ }
32
+
33
+ export function createEchoRequester({
34
+ getURL,
35
+ status = 200,
36
+ }: EchoRequesterParams): Requester {
37
+ function send(request: EndRequest): Promise<Response> {
38
+ const { host, searchParams, algoliaAgent, path } = getUrlParams(
39
+ getURL(request.url)
40
+ );
41
+
42
+ const content: EchoResponse = {
43
+ ...request,
44
+ data: request.data ? JSON.parse(request.data) : undefined,
45
+ path,
46
+ host,
47
+ algoliaAgent: encodeURI(algoliaAgent),
48
+ searchParams,
49
+ };
50
+
51
+ return Promise.resolve({
52
+ content: JSON.stringify(content),
53
+ isTimedOut: false,
54
+ status,
55
+ });
56
+ }
57
+
58
+ return { send };
59
+ }
@@ -0,0 +1,52 @@
1
+ import type { CreateRetryablePromiseOptions } from './types/CreateRetryablePromise';
2
+
3
+ export const DEFAULT_MAX_RETRIES = 50;
4
+ export const DEFAULT_TIMEOUT = (retryCount: number): number =>
5
+ Math.min(retryCount * 200, 5000);
6
+
7
+ /**
8
+ * Return a promise that retry a task until it meets the condition.
9
+ *
10
+ * @param createRetryablePromiseOptions - The createRetryablePromise options.
11
+ * @param createRetryablePromiseOptions.func - The function to run, which returns a promise.
12
+ * @param createRetryablePromiseOptions.validate - The validator function. It receives the resolved return of `func`.
13
+ * @param createRetryablePromiseOptions.maxRetries - The maximum number of retries. 50 by default.
14
+ * @param createRetryablePromiseOptions.timeout - The function to decide how long to wait between retries.
15
+ */
16
+ export function createRetryablePromise<TResponse>({
17
+ func,
18
+ validate,
19
+ maxRetries = DEFAULT_MAX_RETRIES,
20
+ timeout = DEFAULT_TIMEOUT,
21
+ }: CreateRetryablePromiseOptions<TResponse>): Promise<TResponse> {
22
+ let retryCount = 0;
23
+ const retry = (): Promise<TResponse> => {
24
+ return new Promise<TResponse>((resolve, reject) => {
25
+ func()
26
+ .then((response) => {
27
+ const isValid = validate(response);
28
+ if (isValid) {
29
+ resolve(response);
30
+ } else if (retryCount + 1 >= maxRetries) {
31
+ reject(
32
+ new Error(
33
+ `The maximum number of retries exceeded. (${
34
+ retryCount + 1
35
+ }/${maxRetries})`
36
+ )
37
+ );
38
+ } else {
39
+ retryCount += 1;
40
+ setTimeout(() => {
41
+ retry().then(resolve).catch(reject);
42
+ }, timeout(retryCount));
43
+ }
44
+ })
45
+ .catch((error) => {
46
+ reject(error);
47
+ });
48
+ });
49
+ };
50
+
51
+ return retry();
52
+ }
@@ -0,0 +1,25 @@
1
+ import { createAlgoliaAgent } from './createAlgoliaAgent';
2
+ import type { AlgoliaAgentOptions, AlgoliaAgent } from './types';
3
+
4
+ export type GetAlgoliaAgent = {
5
+ algoliaAgents: AlgoliaAgentOptions[];
6
+ client: string;
7
+ version: string;
8
+ };
9
+
10
+ export function getAlgoliaAgent({
11
+ algoliaAgents,
12
+ client,
13
+ version,
14
+ }: GetAlgoliaAgent): AlgoliaAgent {
15
+ const defaultAlgoliaAgent = createAlgoliaAgent(version).add({
16
+ segment: client,
17
+ version,
18
+ });
19
+
20
+ algoliaAgents.forEach((algoliaAgent) =>
21
+ defaultAlgoliaAgent.add(algoliaAgent)
22
+ );
23
+
24
+ return defaultAlgoliaAgent;
25
+ }
@@ -0,0 +1,24 @@
1
+ import type { Host, StatefulHost } from '../types';
2
+
3
+ // By default, API Clients at Algolia have expiration delay of 5 mins.
4
+ // In the JavaScript client, we have 2 mins.
5
+ const EXPIRATION_DELAY = 2 * 60 * 1000;
6
+
7
+ export function createStatefulHost(
8
+ host: Host,
9
+ status: StatefulHost['status'] = 'up'
10
+ ): StatefulHost {
11
+ const lastUpdate = Date.now();
12
+
13
+ function isUp(): boolean {
14
+ return status === 'up' || Date.now() - lastUpdate > EXPIRATION_DELAY;
15
+ }
16
+
17
+ function isTimedOut(): boolean {
18
+ return (
19
+ status === 'timed out' && Date.now() - lastUpdate <= EXPIRATION_DELAY
20
+ );
21
+ }
22
+
23
+ return { ...host, status, lastUpdate, isUp, isTimedOut };
24
+ }
@@ -0,0 +1,347 @@
1
+ import type {
2
+ EndRequest,
3
+ Host,
4
+ Request,
5
+ RequestOptions,
6
+ Response,
7
+ StackFrame,
8
+ TransporterOptions,
9
+ Transporter,
10
+ QueryParameters,
11
+ } from '../types';
12
+
13
+ import { createStatefulHost } from './createStatefulHost';
14
+ import { RetryError } from './errors';
15
+ import {
16
+ deserializeFailure,
17
+ deserializeSuccess,
18
+ serializeData,
19
+ serializeHeaders,
20
+ serializeUrl,
21
+ } from './helpers';
22
+ import { isRetryable, isSuccess } from './responses';
23
+ import {
24
+ stackTraceWithoutCredentials,
25
+ stackFrameWithoutCredentials,
26
+ } from './stackTrace';
27
+
28
+ type RetryableOptions = {
29
+ hosts: Host[];
30
+ getTimeout: (retryCount: number, timeout: number) => number;
31
+ };
32
+
33
+ export function createTransporter({
34
+ hosts,
35
+ hostsCache,
36
+ baseHeaders,
37
+ baseQueryParameters,
38
+ algoliaAgent,
39
+ timeouts,
40
+ requester,
41
+ requestsCache,
42
+ responsesCache,
43
+ }: TransporterOptions): Transporter {
44
+ async function createRetryableOptions(
45
+ compatibleHosts: Host[]
46
+ ): Promise<RetryableOptions> {
47
+ const statefulHosts = await Promise.all(
48
+ compatibleHosts.map((compatibleHost) => {
49
+ return hostsCache.get(compatibleHost, () => {
50
+ return Promise.resolve(createStatefulHost(compatibleHost));
51
+ });
52
+ })
53
+ );
54
+ const hostsUp = statefulHosts.filter((host) => host.isUp());
55
+ const hostsTimedOut = statefulHosts.filter((host) => host.isTimedOut());
56
+
57
+ // Note, we put the hosts that previously timed out on the end of the list.
58
+ const hostsAvailable = [...hostsUp, ...hostsTimedOut];
59
+ const compatibleHostsAvailable =
60
+ hostsAvailable.length > 0 ? hostsAvailable : compatibleHosts;
61
+
62
+ return {
63
+ hosts: compatibleHostsAvailable,
64
+ getTimeout(timeoutsCount: number, baseTimeout: number): number {
65
+ /**
66
+ * Imagine that you have 4 hosts, if timeouts will increase
67
+ * on the following way: 1 (timed out) > 4 (timed out) > 5 (200).
68
+ *
69
+ * Note that, the very next request, we start from the previous timeout.
70
+ *
71
+ * 5 (timed out) > 6 (timed out) > 7 ...
72
+ *
73
+ * This strategy may need to be reviewed, but is the strategy on the our
74
+ * current v3 version.
75
+ */
76
+ const timeoutMultiplier =
77
+ hostsTimedOut.length === 0 && timeoutsCount === 0
78
+ ? 1
79
+ : hostsTimedOut.length + 3 + timeoutsCount;
80
+
81
+ return timeoutMultiplier * baseTimeout;
82
+ },
83
+ };
84
+ }
85
+
86
+ async function retryableRequest<TResponse>(
87
+ request: Request,
88
+ requestOptions: RequestOptions,
89
+ isRead = true
90
+ ): Promise<TResponse> {
91
+ const stackTrace: StackFrame[] = [];
92
+
93
+ /**
94
+ * First we prepare the payload that do not depend from hosts.
95
+ */
96
+ const data = serializeData(request, requestOptions);
97
+ const headers = serializeHeaders(
98
+ baseHeaders,
99
+ request.headers,
100
+ requestOptions.headers
101
+ );
102
+
103
+ // On `GET`, the data is proxied to query parameters.
104
+ const dataQueryParameters: QueryParameters =
105
+ request.method === 'GET'
106
+ ? {
107
+ ...request.data,
108
+ ...requestOptions.data,
109
+ }
110
+ : {};
111
+
112
+ const queryParameters: QueryParameters = {
113
+ 'x-algolia-agent': algoliaAgent.value,
114
+ ...baseQueryParameters,
115
+ ...request.queryParameters,
116
+ ...dataQueryParameters,
117
+ };
118
+
119
+ if (requestOptions && requestOptions.queryParameters) {
120
+ for (const key of Object.keys(requestOptions.queryParameters)) {
121
+ // We want to keep `undefined` and `null` values,
122
+ // but also avoid stringifying `object`s, as they are
123
+ // handled in the `serializeUrl` step right after.
124
+ if (
125
+ !requestOptions.queryParameters[key] ||
126
+ Object.prototype.toString.call(
127
+ requestOptions.queryParameters[key]
128
+ ) === '[object Object]'
129
+ ) {
130
+ queryParameters[key] = requestOptions.queryParameters[key];
131
+ } else {
132
+ queryParameters[key] = requestOptions.queryParameters[key].toString();
133
+ }
134
+ }
135
+ }
136
+
137
+ let timeoutsCount = 0;
138
+
139
+ const retry = async (
140
+ retryableHosts: Host[],
141
+ getTimeout: (timeoutsCount: number, timeout: number) => number
142
+ ): Promise<TResponse> => {
143
+ /**
144
+ * We iterate on each host, until there is no host left.
145
+ */
146
+ const host = retryableHosts.pop();
147
+ if (host === undefined) {
148
+ throw new RetryError(stackTraceWithoutCredentials(stackTrace));
149
+ }
150
+
151
+ let responseTimeout = requestOptions.timeout;
152
+ if (responseTimeout === undefined) {
153
+ responseTimeout = isRead ? timeouts.read : timeouts.write;
154
+ }
155
+
156
+ const payload: EndRequest = {
157
+ data,
158
+ headers,
159
+ method: request.method,
160
+ url: serializeUrl(host, request.path, queryParameters),
161
+ connectTimeout: getTimeout(timeoutsCount, timeouts.connect),
162
+ responseTimeout: getTimeout(timeoutsCount, responseTimeout),
163
+ };
164
+
165
+ /**
166
+ * The stackFrame is pushed to the stackTrace so we
167
+ * can have information about onRetry and onFailure
168
+ * decisions.
169
+ */
170
+ const pushToStackTrace = (response: Response): StackFrame => {
171
+ const stackFrame: StackFrame = {
172
+ request: payload,
173
+ response,
174
+ host,
175
+ triesLeft: retryableHosts.length,
176
+ };
177
+
178
+ stackTrace.push(stackFrame);
179
+
180
+ return stackFrame;
181
+ };
182
+
183
+ const response = await requester.send(payload);
184
+
185
+ if (isRetryable(response)) {
186
+ const stackFrame = pushToStackTrace(response);
187
+
188
+ // If response is a timeout, we increase the number of timeouts so we can increase the timeout later.
189
+ if (response.isTimedOut) {
190
+ timeoutsCount++;
191
+ }
192
+ /**
193
+ * Failures are individually sent to the logger, allowing
194
+ * the end user to debug / store stack frames even
195
+ * when a retry error does not happen.
196
+ */
197
+ // eslint-disable-next-line no-console -- this will be fixed by exposing a `logger` to the transporter
198
+ console.log(
199
+ 'Retryable failure',
200
+ stackFrameWithoutCredentials(stackFrame)
201
+ );
202
+
203
+ /**
204
+ * We also store the state of the host in failure cases. If the host, is
205
+ * down it will remain down for the next 2 minutes. In a timeout situation,
206
+ * this host will be added end of the list of hosts on the next request.
207
+ */
208
+ await hostsCache.set(
209
+ host,
210
+ createStatefulHost(host, response.isTimedOut ? 'timed out' : 'down')
211
+ );
212
+
213
+ return retry(retryableHosts, getTimeout);
214
+ }
215
+
216
+ if (isSuccess(response)) {
217
+ return deserializeSuccess(response);
218
+ }
219
+
220
+ pushToStackTrace(response);
221
+ throw deserializeFailure(response, stackTrace);
222
+ };
223
+
224
+ /**
225
+ * Finally, for each retryable host perform request until we got a non
226
+ * retryable response. Some notes here:
227
+ *
228
+ * 1. The reverse here is applied so we can apply a `pop` later on => more performant.
229
+ * 2. We also get from the retryable options a timeout multiplier that is tailored
230
+ * for the current context.
231
+ */
232
+ const compatibleHosts = hosts.filter(
233
+ (host) =>
234
+ host.accept === 'readWrite' ||
235
+ (isRead ? host.accept === 'read' : host.accept === 'write')
236
+ );
237
+ const options = await createRetryableOptions(compatibleHosts);
238
+
239
+ return retry([...options.hosts].reverse(), options.getTimeout);
240
+ }
241
+
242
+ function createRequest<TResponse>(
243
+ request: Request,
244
+ requestOptions: RequestOptions = {}
245
+ ): Promise<TResponse> {
246
+ /**
247
+ * A read request is either a `GET` request, or a request that we make
248
+ * via the `read` transporter (e.g. `search`).
249
+ */
250
+ const isRead = request.useReadTransporter || request.method === 'GET';
251
+ if (!isRead) {
252
+ /**
253
+ * On write requests, no cache mechanisms are applied, and we
254
+ * proxy the request immediately to the requester.
255
+ */
256
+ return retryableRequest<TResponse>(request, requestOptions, isRead);
257
+ }
258
+
259
+ const createRetryableRequest = (): Promise<TResponse> => {
260
+ /**
261
+ * Then, we prepare a function factory that contains the construction of
262
+ * the retryable request. At this point, we may *not* perform the actual
263
+ * request. But we want to have the function factory ready.
264
+ */
265
+ return retryableRequest<TResponse>(request, requestOptions);
266
+ };
267
+
268
+ /**
269
+ * Once we have the function factory ready, we need to determine of the
270
+ * request is "cacheable" - should be cached. Note that, once again,
271
+ * the user can force this option.
272
+ */
273
+ const cacheable = requestOptions.cacheable || request.cacheable;
274
+
275
+ /**
276
+ * If is not "cacheable", we immediately trigger the retryable request, no
277
+ * need to check cache implementations.
278
+ */
279
+ if (cacheable !== true) {
280
+ return createRetryableRequest();
281
+ }
282
+
283
+ /**
284
+ * If the request is "cacheable", we need to first compute the key to ask
285
+ * the cache implementations if this request is on progress or if the
286
+ * response already exists on the cache.
287
+ */
288
+ const key = {
289
+ request,
290
+ requestOptions,
291
+ transporter: {
292
+ queryParameters: baseQueryParameters,
293
+ headers: baseHeaders,
294
+ },
295
+ };
296
+
297
+ /**
298
+ * With the computed key, we first ask the responses cache
299
+ * implementation if this request was been resolved before.
300
+ */
301
+ return responsesCache.get(
302
+ key,
303
+ () => {
304
+ /**
305
+ * If the request has never resolved before, we actually ask if there
306
+ * is a current request with the same key on progress.
307
+ */
308
+ return requestsCache.get(key, () =>
309
+ /**
310
+ * Finally, if there is no request in progress with the same key,
311
+ * this `createRetryableRequest()` will actually trigger the
312
+ * retryable request.
313
+ */
314
+ requestsCache
315
+ .set(key, createRetryableRequest())
316
+ .then(
317
+ (response) => Promise.all([requestsCache.delete(key), response]),
318
+ (err) =>
319
+ Promise.all([requestsCache.delete(key), Promise.reject(err)])
320
+ )
321
+ .then(([_, response]) => response)
322
+ );
323
+ },
324
+ {
325
+ /**
326
+ * Of course, once we get this response back from the server, we
327
+ * tell response cache to actually store the received response
328
+ * to be used later.
329
+ */
330
+ miss: (response) => responsesCache.set(key, response),
331
+ }
332
+ );
333
+ }
334
+
335
+ return {
336
+ hostsCache,
337
+ requester,
338
+ timeouts,
339
+ algoliaAgent,
340
+ baseHeaders,
341
+ baseQueryParameters,
342
+ hosts,
343
+ request: createRequest,
344
+ requestsCache,
345
+ responsesCache,
346
+ };
347
+ }