UNPKG

17.3 kBTypeScriptView Raw
1/// <reference types="node" resolution-mode="require"/>
2/// <reference types="node" resolution-mode="require"/>
3/**
4 * ```ts
5 * import type { Config } from "arangojs/connection.js";
6 * ```
7 *
8 * The "connection" module provides connection and configuration related types
9 * for TypeScript.
10 *
11 * @packageDocumentation
12 */
13import { LinkedList } from "./lib/linkedList.js";
14import { Database } from "./database.js";
15import { ArangojsError, ArangojsResponse, RequestConfig, RequestFunction } from "./lib/request.js";
16/**
17 * Determines the behavior when multiple URLs are used:
18 *
19 * - `"NONE"`: No load balancing. All requests will be handled by the first
20 * URL in the list until a network error is encountered. On network error,
21 * arangojs will advance to using the next URL in the list.
22 *
23 * - `"ONE_RANDOM"`: Randomly picks one URL from the list initially, then
24 * behaves like `"NONE"`.
25 *
26 * - `"ROUND_ROBIN"`: Every sequential request uses the next URL in the list.
27 */
28export type LoadBalancingStrategy = "NONE" | "ROUND_ROBIN" | "ONE_RANDOM";
29/**
30 * Generic properties shared by all ArangoDB HTTP API responses.
31 */
32export type ArangoResponseMetadata = {
33 /**
34 * Indicates that the request was successful.
35 */
36 error: false;
37 /**
38 * Response status code, typically `200`.
39 */
40 code: number;
41};
42/**
43 * Extends the given base type `T` with the generic HTTP API response properties.
44 */
45export type ArangoApiResponse<T> = T & ArangoResponseMetadata;
46/**
47 * Credentials for HTTP Basic authentication.
48 */
49export type BasicAuthCredentials = {
50 /**
51 * Username to use for authentication, e.g. `"root"`.
52 */
53 username: string;
54 /**
55 * Password to use for authentication. Defaults to an empty string.
56 */
57 password?: string;
58};
59/**
60 * Credentials for HTTP Bearer token authentication.
61 */
62export type BearerAuthCredentials = {
63 /**
64 * Bearer token to use for authentication.
65 */
66 token: string;
67};
68/**
69 * Options for performing a request with arangojs.
70 */
71export type RequestOptions = {
72 /**
73 * @internal
74 *
75 * Identifier of a specific ArangoDB host to use when more than one is known.
76 */
77 hostUrl?: string;
78 /**
79 * HTTP method to use in order to perform the request.
80 *
81 * Default: `"GET"`
82 */
83 method?: string;
84 /**
85 * Request body data.
86 */
87 body?: any;
88 /**
89 * If set to `true`, the response body will not be interpreted as JSON and
90 * instead passed as-is.
91 */
92 expectBinary?: boolean;
93 /**
94 * If set to `true`, the request body will not be converted to JSON and
95 * instead passed as-is.
96 */
97 isBinary?: boolean;
98 /**
99 * Whether ArangoDB is allowed to perform a dirty read to respond to this
100 * request. If set to `true`, the response may reflect a dirty state from
101 * a non-authoritative server.
102 */
103 allowDirtyRead?: boolean;
104 /**
105 * If set to a positive number, the request will automatically be retried at
106 * most this many times if it results in a write-write conflict.
107 *
108 * Default: `config.retryOnConflict`
109 */
110 retryOnConflict?: number;
111 /**
112 * HTTP headers to pass along with this request in addition to the default
113 * headers generated by arangojs.
114 */
115 headers?: Headers | Record<string, string>;
116 /**
117 * Time in milliseconds after which arangojs will abort the request if the
118 * socket has not already timed out.
119 *
120 * See also `agentOptions.timeout` in {@link Config}.
121 */
122 timeout?: number;
123 /**
124 * Optional prefix path to prepend to the `path`.
125 */
126 basePath?: string;
127 /**
128 * URL path, relative to the `basePath` and server domain.
129 */
130 path?: string;
131 /**
132 * URL parameters to pass as part of the query string.
133 */
134 search?: URLSearchParams | Record<string, any>;
135};
136/**
137 * @internal
138 */
139type Task = {
140 hostUrl?: string;
141 stack?: () => string;
142 allowDirtyRead: boolean;
143 retryOnConflict: number;
144 resolve: (result: any) => void;
145 reject: (error: Error) => void;
146 transform?: (res: ArangojsResponse) => any;
147 retries: number;
148 options: {
149 method: string;
150 expectBinary: boolean;
151 timeout?: number;
152 pathname: string;
153 search?: URLSearchParams;
154 headers: Headers;
155 body: any;
156 };
157};
158/**
159 * Options for configuring arangojs.
160 */
161export type Config = {
162 /**
163 * Name of the database to use.
164 *
165 * Default: `"_system"`
166 */
167 databaseName?: string;
168 /**
169 * Base URL of the ArangoDB server or list of server URLs.
170 *
171 * When working with a cluster, the method {@link database.Database#acquireHostList}
172 * can be used to automatically pick up additional coordinators/followers at
173 * any point.
174 *
175 * When running ArangoDB on a unix socket, e.g. `/tmp/arangodb.sock`, the
176 * following URL formats are supported for unix sockets:
177 *
178 * - `unix:///tmp/arangodb.sock` (no SSL)
179 * - `http+unix:///tmp/arangodb.sock` (or `https+unix://` for SSL)
180 * - `http://unix:/tmp/arangodb.sock` (or `https://unix:` for SSL)
181 *
182 * Additionally `ssl` and `tls` are treated as synonymous with `https` and
183 * `tcp` is treated as synonymous with `http`, so the following URLs are
184 * considered identical:
185 *
186 * - `tcp://127.0.0.1:8529` and `http://127.0.0.1:8529`
187 * - `ssl://127.0.0.1:8529` and `https://127.0.0.1:8529`
188 * - `tcp+unix:///tmp/arangodb.sock` and `http+unix:///tmp/arangodb.sock`
189 * - `ssl+unix:///tmp/arangodb.sock` and `https+unix:///tmp/arangodb.sock`
190 * - `tcp://unix:/tmp/arangodb.sock` and `http://unix:/tmp/arangodb.sock`
191 * - `ssl://unix:/tmp/arangodb.sock` and `https://unix:/tmp/arangodb.sock`
192 *
193 * See also `auth` for passing authentication credentials.
194 *
195 * Default: `"http://127.0.0.1:8529"`
196 */
197 url?: string | string[];
198 /**
199 * Credentials to use for authentication.
200 *
201 * See also {@link database.Database#useBasicAuth} and
202 * {@link database.Database#useBearerAuth}.
203 *
204 * Default: `{ username: "root", password: "" }`
205 */
206 auth?: BasicAuthCredentials | BearerAuthCredentials;
207 /**
208 * Numeric representation of the ArangoDB version the driver should expect.
209 * The format is defined as `XYYZZ` where `X` is the major version, `Y` is
210 * the zero-filled two-digit minor version and `Z` is the zero-filled two-digit
211 * bugfix version, e.g. `30102` for 3.1.2, `20811` for 2.8.11.
212 *
213 * Depending on this value certain methods may become unavailable or change
214 * their behavior to remain compatible with different versions of ArangoDB.
215 *
216 * Default: `31100`
217 */
218 arangoVersion?: number;
219 /**
220 * Determines the behavior when multiple URLs are provided:
221 *
222 * - `"NONE"`: No load balancing. All requests will be handled by the first
223 * URL in the list until a network error is encountered. On network error,
224 * arangojs will advance to using the next URL in the list.
225 *
226 * - `"ONE_RANDOM"`: Randomly picks one URL from the list initially, then
227 * behaves like `"NONE"`.
228 *
229 * - `"ROUND_ROBIN"`: Every sequential request uses the next URL in the list.
230 *
231 * Default: `"NONE"`
232 */
233 loadBalancingStrategy?: LoadBalancingStrategy;
234 /**
235 * Determines the behavior when a request fails because the underlying
236 * connection to the server could not be opened
237 * (i.e. [`ECONNREFUSED` in Node.js](https://nodejs.org/api/errors.html#errors_common_system_errors)):
238 *
239 * - `false`: the request fails immediately.
240 *
241 * - `0`: the request is retried until a server can be reached but only a
242 * total number of times matching the number of known servers (including
243 * the initial failed request).
244 *
245 * - any other number: the request is retried until a server can be reached
246 * or the request has been retried a total of `maxRetries` number of times
247 * (not including the initial failed request).
248 *
249 * When working with a single server, the retries (if any) will be made to
250 * the same server.
251 *
252 * This setting currently has no effect when using arangojs in a browser.
253 *
254 * **Note**: Requests bound to a specific server (e.g. fetching query results)
255 * will never be retried automatically and ignore this setting.
256 *
257 * **Note**: To set the number of retries when a write-write conflict is
258 * encountered, see `retryOnConflict` instead.
259 *
260 * Default: `0`
261 */
262 maxRetries?: false | number;
263 /**
264 * Maximum number of parallel requests arangojs will perform. If any
265 * additional requests are attempted, they will be enqueued until one of the
266 * active requests has completed.
267 *
268 * **Note:** when using `ROUND_ROBIN` load balancing and passing an array of
269 * URLs in the `url` option, the default value of this option will be set to
270 * `3 * url.length` instead of `3`.
271 *
272 * Default: `3`
273 */
274 poolSize?: number;
275 /**
276 * (Browser only.) Determines whether credentials (e.g. cookies) will be sent
277 * with requests to the ArangoDB server.
278 *
279 * If set to `same-origin`, credentials will only be included with requests
280 * on the same URL origin as the invoking script. If set to `include`,
281 * credentials will always be sent. If set to `omit`, credentials will be
282 * excluded from all requests.
283 *
284 * Default: `same-origin`
285 */
286 credentials?: "omit" | "include" | "same-origin";
287 /**
288 * If set to `true`, requests will keep the underlying connection open until
289 * it times out or is closed. In browsers this prevents requests from being
290 * cancelled when the user navigates away from the page.
291 *
292 * Default: `true`
293 */
294 keepalive?: boolean;
295 /**
296 * Callback that will be invoked with the finished request object before it
297 * is finalized. In the browser the request may already have been sent.
298 *
299 * @param req - Request object or XHR instance used for this request.
300 */
301 beforeRequest?: (req: globalThis.Request) => void;
302 /**
303 * Callback that will be invoked when the server response has been received
304 * and processed or when the request has been failed without a response.
305 *
306 * The originating request will be available as the `request` property
307 * on either the error or response object.
308 *
309 * @param err - Error encountered when handling this request or `null`.
310 * @param res - Response object for this request, if no error occurred.
311 */
312 afterResponse?: (err: ArangojsError | null, res?: ArangojsResponse) => void;
313 /**
314 * If set to a positive number, requests will automatically be retried at
315 * most this many times if they result in a write-write conflict.
316 *
317 * Default: `0`
318 */
319 retryOnConflict?: number;
320 /**
321 * An object with additional headers to send with every request.
322 *
323 * If an `"authorization"` header is provided, it will be overridden when
324 * using {@link database.Database#useBasicAuth}, {@link database.Database#useBearerAuth} or
325 * the `auth` configuration option.
326 */
327 headers?: Headers | Record<string, string>;
328 /**
329 * If set to `true`, arangojs will generate stack traces every time a request
330 * is initiated and augment the stack traces of any errors it generates.
331 *
332 * **Warning**: This will cause arangojs to generate stack traces in advance
333 * even if the request does not result in an error. Generating stack traces
334 * may negatively impact performance.
335 */
336 precaptureStackTraces?: boolean;
337 /**
338 * Limits the number of values of server-reported response queue times that
339 * will be stored and accessible using {@link database.Database#queueTime}. If set to
340 * a finite value, older values will be discarded to make room for new values
341 * when that limit is reached.
342 *
343 * Default: `10`
344 */
345 responseQueueTimeSamples?: number;
346};
347/**
348 * Indicates whether the given value represents a {@link Connection}.
349 *
350 * @param connection - A value that might be a connection.
351 *
352 * @internal
353 */
354export declare function isArangoConnection(connection: any): connection is Connection;
355/**
356 * Represents a connection pool shared by one or more databases.
357 *
358 * @internal
359 */
360export declare class Connection {
361 protected _activeTasks: number;
362 protected _arangoVersion: number;
363 protected _headers: Headers;
364 protected _loadBalancingStrategy: LoadBalancingStrategy;
365 protected _maxRetries: number | false;
366 protected _taskPoolSize: number;
367 protected _requestConfig: RequestConfig;
368 protected _retryOnConflict: number;
369 protected _queue: LinkedList<Task>;
370 protected _databases: Map<string, Database>;
371 protected _hosts: RequestFunction[];
372 protected _hostUrls: string[];
373 protected _activeHostUrl: string;
374 protected _activeDirtyHostUrl: string;
375 protected _transactionId: string | null;
376 protected _precaptureStackTraces: boolean;
377 protected _queueTimes: LinkedList<[number, number]>;
378 protected _responseQueueTimeSamples: number;
379 /**
380 * @internal
381 *
382 * Creates a new `Connection` instance.
383 *
384 * @param config - An object with configuration options.
385 *
386 */
387 constructor(config?: Omit<Config, "databaseName">);
388 /**
389 * @internal
390 *
391 * Indicates that this object represents an ArangoDB connection.
392 */
393 get isArangoConnection(): true;
394 get queueTime(): {
395 getLatest: () => number | undefined;
396 getValues: () => [number, number][];
397 getAvg: () => number;
398 };
399 protected _runQueue(): Promise<void>;
400 setBearerAuth(auth: BearerAuthCredentials): void;
401 setBasicAuth(auth: BasicAuthCredentials): void;
402 setResponseQueueTimeSamples(responseQueueTimeSamples: number): void;
403 /**
404 * @internal
405 *
406 * Fetches a {@link database.Database} instance for the given database name from the
407 * internal cache, if available.
408 *
409 * @param databaseName - Name of the database.
410 */
411 database(databaseName: string): Database | undefined;
412 /**
413 * @internal
414 *
415 * Adds a {@link database.Database} instance for the given database name to the
416 * internal cache.
417 *
418 * @param databaseName - Name of the database.
419 * @param database - Database instance to add to the cache.
420 */
421 database(databaseName: string, database: Database): Database;
422 /**
423 * @internal
424 *
425 * Clears any {@link database.Database} instance stored for the given database name
426 * from the internal cache, if present.
427 *
428 * @param databaseName - Name of the database.
429 * @param database - Must be `null`.
430 */
431 database(databaseName: string, database: null): undefined;
432 /**
433 * @internal
434 *
435 * Replaces the host list with the given URLs.
436 *
437 * See {@link Connection#acquireHostList}.
438 *
439 * @param urls - URLs to use as host list.
440 */
441 setHostList(urls: string[]): void;
442 /**
443 * @internal
444 *
445 * Adds the given URL or URLs to the host list.
446 *
447 * See {@link Connection#acquireHostList}.
448 *
449 * @param urls - URL or URLs to add.
450 */
451 addToHostList(urls: string | string[]): string[];
452 /**
453 * @internal
454 *
455 * Sets the connection's active `transactionId`.
456 *
457 * While set, all requests will use this ID, ensuring the requests are executed
458 * within the transaction if possible. Setting the ID manually may cause
459 * unexpected behavior.
460 *
461 * See also {@link Connection#clearTransactionId}.
462 *
463 * @param transactionId - ID of the active transaction.
464 */
465 setTransactionId(transactionId: string): void;
466 /**
467 * @internal
468 *
469 * Clears the connection's active `transactionId`.
470 */
471 clearTransactionId(): void;
472 /**
473 * @internal
474 *
475 * Sets the header `headerName` with the given `value` or clears the header if
476 * `value` is `null`.
477 *
478 * @param headerName - Name of the header to set.
479 * @param value - Value of the header.
480 */
481 setHeader(headerName: string, value: string | null): void;
482 /**
483 * @internal
484 *
485 * Closes all open connections.
486 *
487 * See {@link database.Database#close}.
488 */
489 close(): void;
490 /**
491 * @internal
492 *
493 * Waits for propagation.
494 *
495 * See {@link database.Database#waitForPropagation}.
496 *
497 * @param request - Request to perform against each coordinator.
498 * @param timeout - Maximum number of milliseconds to wait for propagation.
499 */
500 waitForPropagation(request: RequestOptions, timeout?: number): Promise<void>;
501 /**
502 * @internal
503 *
504 * Performs a request using the arangojs connection pool.
505 */
506 request<T = ArangojsResponse>({ hostUrl, method, body, expectBinary, isBinary, allowDirtyRead, retryOnConflict, timeout, headers: requestHeaders, basePath, path, search: params, }: RequestOptions, transform?: (res: ArangojsResponse) => T): Promise<T>;
507}
508export {};
509//# sourceMappingURL=connection.d.ts.map
\No newline at end of file