smart-energy-monitor/software/flow/node_modules/@influxdata/influxdb-client/dist/index.d.ts

1198 lines
43 KiB
TypeScript

/**
* ChunkCombiner is a simplified platform-neutral manipulation of Uint8arrays
* that allows to process text data on the fly. The implementation can be optimized
* for the target platform (node vs browser).
*/
interface ChunkCombiner {
/**
* Concatenates first and second chunk.
* @param first - first chunk
* @param second - second chunk
* @returns first + second
*/
concat(first: Uint8Array, second: Uint8Array): Uint8Array;
/**
* Converts chunk into a string.
* @param chunk - chunk
* @param start - start index
* @param end - end index
* @returns string representation of chunk slice
*/
toUtf8String(chunk: Uint8Array, start: number, end: number): string;
/**
* Creates a new chunk from the supplied chunk.
* @param chunk - chunk to copy
* @param start - start index
* @param end - end index
* @returns a copy of a chunk slice
*/
copy(chunk: Uint8Array, start: number, end: number): Uint8Array;
}
/**
* Creates a chunk combiner instance that uses UTF-8
* TextDecoder to decode Uint8Arrays into strings.
*/
declare function createTextDecoderCombiner(): ChunkCombiner;
/**
* Allows to cancel a running execution.
*/
interface Cancellable {
/**
* Cancels execution.
*/
cancel(): void;
isCancelled(): boolean;
}
/**
* Type of HTTP headers.
*/
type HttpHeaders = {
[header: string]: string | string[] | undefined;
};
/**
* Informs about a start of response processing.
* @param headers - response HTTP headers
* @param statusCode - response status code
*/
type ResponseStartedFn = (headers: HttpHeaders, statusCode?: number) => void;
/**
* Observes communication with the server.
*/
interface CommunicationObserver<T> {
/**
* Data chunk received, can be called multiple times.
* @param data - data
* @returns when `false` value is returned and {@link CommunicationObserver.useResume} is defined,
* future calls to `next` are paused until resume is called.
*/
next(data: T): void | boolean;
/**
* Communication ended with an error.
*/
error(error: Error): void;
/**
* Communication was successful.
*/
complete(): void;
/**
* Informs about a start of response processing.
*/
responseStarted?: ResponseStartedFn;
/**
* Setups cancelllable for this communication.
*/
useCancellable?: (cancellable: Cancellable) => void;
/**
* Setups a callback that resumes reading of next data, it is called whenever
* {@link CommunicationObserver.next} returns `false`.
*
* @param resume - a function that will resume reading of next data when called
*/
useResume?: (resume: () => void) => void;
}
/**
* ChunksToLines is a transformation that accepts Uint8Array instances
* and emmits strings representing CSV lines.
* @param target - target to emmit CSV lines to
* @param chunkCombiner - chunk combiner
* @returns communication obrver to accept Uint8Arrays
*/
declare function chunksToLines(target: CommunicationObserver<string>, chunkCombiner?: ChunkCombiner): CommunicationObserver<Uint8Array>;
/**
* ChunksToLinesIterable is a transformation that accepts
* an iterable of Uint8Array instances and returns iterable of lines.
* @param source - iterable of transport buffers
* @param chunkCombiner - chunk combiner
* @returns iterable of lines
*/
declare function chunksToLinesIterable(source: AsyncIterable<Uint8Array>, chunkCombiner?: ChunkCombiner): AsyncIterableIterator<string>;
/**
* Type of query result column, see {@link https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/#data-types }
*/
type ColumnType = 'boolean' | 'unsignedLong' | 'long' | 'double' | 'string' | 'base64Binary' | 'dateTime:RFC3339' | 'duration' | string;
/**
* FluxTableColumn describes {@link http://bit.ly/flux-spec#table | flux table} column.
*/
interface FluxTableColumn {
/**
* Label (e.g., "_start", "_stop", "_time").
*/
label: string;
/**
* The data type of column (e.g., "string", "long", "dateTime:RFC3339").
*/
dataType: ColumnType;
/**
* Boolean flag indicating if the column is a part of the table's group key.
*/
group: boolean;
/**
* Default value to be used for rows whose string value is an empty string.
*/
defaultValue: string;
/**
* Index of this column in a row array.
*/
index: number;
/**
* Get returns a JavaScript object of this column in the supplied result row, using default deserializers.
* @param row - a data row
* @returns column value
*/
get: (row: string[]) => any;
}
/**
* A dictionary of serializers of particular types returned by a flux query.
* See {@link https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/#data-types }
*/
declare const typeSerializers: Record<ColumnType, (val: string) => any>;
declare const UNKNOWN_COLUMN: FluxTableColumn;
/**
* Creates a new flux table column.
* @returns column instance
*/
declare function newFluxTableColumn(): FluxTableColumn;
/**
* Creates a flux table column from a partial FluxTableColumn.
* @param object - source object
* @returns column instance
*/
declare function createFluxTableColumn(object: Partial<FluxTableColumn>): FluxTableColumn;
/**
* serializeDateTimeAsDate changes type serializers to return JavaScript Date instances
* for 'dateTime:RFC3339' query result data type. Empty value is converted to null.
* @remarks
* Please note that the result has millisecond precision whereas InfluxDB returns dateTime
* in nanosecond precision.
*/
declare function serializeDateTimeAsDate(): void;
/**
* serializeDateTimeAsNumber changes type serializers to return milliseconds since epoch
* for 'dateTime:RFC3339' query result data type. Empty value is converted to null.
* @remarks
* Please note that the result has millisecond precision whereas InfluxDB returns dateTime
* in nanosecond precision.
*/
declare function serializeDateTimeAsNumber(): void;
/**
* serializeDateTimeAsString changes type serializers to return string values
* for `dateTime:RFC3339` query result data type. Empty value is converted to null.
*/
declare function serializeDateTimeAsString(): void;
/**
* Represents metadata of a {@link http://bit.ly/flux-spec#table | flux table}.
*/
interface FluxTableMetaData {
/**
* Table columns.
*/
columns: Array<FluxTableColumn>;
/**
* Gets columns by name
* @param label - column label
* @param errorOnMissingColumn - throw error on missing column (by default), return UNKNOWN_COLUMN when false
* @returns table column
* @throws IllegalArgumentError if column is not found
**/
column(label: string, errorOnMissingColumn?: boolean): FluxTableColumn;
/**
* Creates an object out of the supplied row with the help of column descriptors.
* @param row - a row with data for each column
*/
toObject(row: string[]): {
[key: string]: any;
};
/**
* Gets column values out of the supplied row.
* @param row - a row with data for each column
* @param column - column name
* @returns column value, undefined for unknown column
*/
get(row: string[], column: string): any;
}
/**
* Created FluxTableMetaData from the columns supplied.
* @param columns - columns
* @returns - instance
*/
declare function createFluxTableMetaData(columns: FluxTableColumn[]): FluxTableMetaData;
/** Wraps values and associated metadata of a query result row */
interface Row {
values: string[];
tableMeta: FluxTableMetaData;
}
/**
* Observes results of a flux query.
*/
interface FluxResultObserver<T> {
/**
* Inform about a next record in a table.
* @param row - flux result
* @param tableMeta - actual table metata for the row supplied
* @returns when `false` value is returned and {@link FluxResultObserver.useResume} is defined,
* future calls to `next` are paused until resume is called.
*/
next(row: T, tableMeta: FluxTableMetaData): void | boolean;
/**
* Signalizes processing error.
*/
error(error: Error): void;
/**
* Signalizes completition.
*/
complete(): void;
/**
* Setups cancellable that can abort flux result processing.
*/
useCancellable?: (cancellable: Cancellable) => void;
/**
* Setups a callback that resumes reading of next data, it is called whenever
* {@link FluxResultObserver.next} returns `false`.
*
* @param resume - a function that will resume reading of next data when called
*/
useResume?: (resume: () => void) => void;
}
/**
* LinesToTables creates a transformation that accepts (flux) annotated CSV lines
* and emits rows together with table metadata.
*/
declare function linesToTables(consumer: FluxResultObserver<string[]>): CommunicationObserver<string>;
/**
* LinesToRowsIterable is a transformation that accepts
* an iterable of flux annotated CSV lines and returns
* an iterable of rows (row values and table metadata).
*/
declare function linesToRowsIterable(source: AsyncIterable<string>): AsyncIterableIterator<Row>;
/**
* Optimized tokenizer of a single CSV line.
*/
declare class LineSplitter {
/** returned value when reused */
reusedValues: string[];
/** last length of elements in */
lastSplitLength: number;
private _reuse;
/**
* Reuse returned array between consecutive calls.
*/
get reuse(): boolean;
set reuse(val: boolean);
/**
* Sets the reuse flag and returns this.
*/
withReuse(): LineSplitter;
/**
* Splits the supplied line to elements that are separated by
* comma with values possibly escaped within double quotes ("value")
* @param line - line
* @returns array of splitted parts
*/
splitLine(line: string | undefined | null): string[];
private getValue;
}
/**
* StringToLines is a transformation that emmits strings for each CSV
* line in the supplied source string.
* @param source - source string
* @param target - target to emmit CSV lines to
* @returns communication obrver to accept Uint8Arrays
*/
declare function stringToLines(source: string, target: CommunicationObserver<string>): void;
declare global {
interface SymbolConstructor {
readonly observable: symbol;
}
}
/** Symbol.observable or a string "\@\@observable". Used for interop */
declare const symbolObservable: typeof Symbol.observable | "@@observable";
/** Type of {@link Observer.next} */
type ObserverNext<T> = (value: T) => void;
/** Type of {@link Observer.error} */
type ObserverError = (e: any) => void;
/** Type of {@link Observer.complete} */
type ObserverComplete = () => void;
/** Observer mimics Observer from ECMAScript TC39 Observable proposal */
interface Observer<T> {
next: ObserverNext<T>;
error: ObserverError;
complete: ObserverComplete;
}
interface Subscribable<T> {
subscribe(observer: Partial<Observer<T>>): Subscription;
}
/**
* An observable that aligns with the
* {@link https://github.com/tc39/proposal-observable | TC39 observable proposal} and
* can be consumed by other observable libraries like
* {@link https://github.com/ReactiveX/rxjs | rx js} or
* {@link https://github.com/zenparsing/zen-observable | zen-observable}.
*/
interface Observable<T> {
subscribe(): Subscription;
subscribe(observer: Partial<Observer<T>>): Subscription;
subscribe(next: ObserverNext<T>, error?: ObserverError, complete?: ObserverComplete): Subscription;
[Symbol.observable](): Subscribable<T>;
}
/** Subscription mimics Subscription from ECMAScript TC39 Observable proposal */
interface Subscription {
readonly closed: boolean;
unsubscribe(): void;
}
/**
* A factory that returns async iterables.
*/
type IterableResultExecutor = () => AsyncIterable<Uint8Array>;
/**
* AnnotatedCSVResponse provides various ways of how to
* process data from an annotated CSV response stream,
* which is returned as a result of a flux script execution.
*/
interface AnnotatedCSVResponse {
/**
* IterateLines returns iterable of CSV response lines suitable for `for-await` loop consumption.
* @returns iterable of lines
*/
iterateLines(): AsyncIterable<string>;
/**
* IterateRows returns iterable of response table rows suitable for `for-await` loop consumption.
* @returns iterable of rows
*/
iterateRows(): AsyncIterable<Row>;
/**
* Lines creates a cold observable of the CSV response lines.
* @returns observable of CSV result lines
*/
lines(): Observable<string>;
/**
* Rows creates a cold observable of the CSV response rows.
* @returns observable of CSV result rows
*/
rows(): Observable<Row>;
/**
* ConsumesLines consumes result lines (including empty and annotation lines)
* through the supplied consumer. See [annotated-csv](https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/).
* @param consumer - csv result lines and error consumer
*/
consumeLines(consumer: CommunicationObserver<string>): void;
/**
* ConsumeRows consumes result rows through the supplied consumer.
*
* @param consumer - csv result lines and error consumer
*/
consumeRows(consumer: FluxResultObserver<string[]>): void;
/**
* CollectRows collects all the result rows in the returned Promise.
* This method is suitable to collect simple results. Use with caution,
* a possibly huge stream of results is copied to memory.
*
* @param rowMapper - maps the supplied row to an item that is then collected,
* undefined return values are not collected. If no rowMapper is supplied,
* `row => tableMeta.toObject(row.values)` is used.
* @returns Promise of mapped results
*/
collectRows<T>(rowMapper?: (values: string[], tableMeta: FluxTableMetaData) => T | undefined): Promise<Array<T>>;
/**
* CollectLines collects all result lines in the returned Promise.
* This method is suitable to collect simple results. Use with caution,
* a possibly huge stream of lines is copied to memory.
*
* @returns Promise of returned csv lines
*/
collectLines(): Promise<Array<string>>;
}
/** APIExecutor executes the API and passes its response to the supplied consumer */
type APIExecutor = (consumer: CommunicationObserver<Uint8Array>) => void;
/**
* Options for sending a request message.
*/
interface SendOptions {
/** HTTP method (POST, PUT, GET, PATCH ...) */
method: string;
/** Request HTTP headers. */
headers?: {
[key: string]: string;
};
/** When specified, message body larger than the treshold is gzipped */
gzipThreshold?: number;
/** Abort signal */
signal?: AbortSignal;
}
/**
* Simpified platform-neutral transport layer for communication with InfluxDB.
*/
interface Transport {
/**
* Send data to the server and receive communication events via callbacks.
*
* @param path - HTTP request path
* @param requestBody - HTTP request body
* @param options - send options
* @param callbacks - communication callbacks to received data in Uint8Array
*/
send(path: string, requestBody: string, options: SendOptions, callbacks?: Partial<CommunicationObserver<Uint8Array>>): void;
/**
* Sends data to the server and receives decoded result. The type of the result depends on
* response's content-type (deserialized json, text).
* @param path - HTTP request path
* @param requestBody - request body
* @param options - send options
* @returns response data
*/
request(path: string, requestBody: any, options: SendOptions, responseStarted?: ResponseStartedFn): Promise<any>;
/**
* Sends requestBody and returns response chunks in an async iterable
* that can be easily consumed in an `for-await` loop.
*
* @param path - HTTP request path
* @param requestBody - request body
* @param options - send options
* @returns async iterable
*/
iterate(path: string, requestBody: any, options: SendOptions): AsyncIterableIterator<Uint8Array>;
/**
* Combines response chunks to create a single response object.
*/
readonly chunkCombiner: ChunkCombiner;
}
/**
* Settings that control the way of how a {@link Point} is serialized
* to a protocol line.
*/
interface PointSettings {
/** default tags to add to every point */
defaultTags?: {
[key: string]: string;
};
/** convertTime serializes Point's timestamp to a line protocol value */
convertTime?: (value: string | number | Date | undefined) => string | undefined;
}
/**
* Point defines values of a single measurement.
*/
declare class Point {
private name;
private tags;
/** escaped field values */
fields: {
[key: string]: string;
};
private time;
/**
* Create a new Point with specified a measurement name.
*
* @param measurementName - the measurement name
*/
constructor(measurementName?: string);
/**
* Sets point's measurement.
*
* @param name - measurement name
* @returns this
*/
measurement(name: string): Point;
/**
* Adds a tag. The caller has to ensure that both name and value are not empty
* and do not end with backslash.
*
* @param name - tag name
* @param value - tag value
* @returns this
*/
tag(name: string, value: string): Point;
/**
* Adds a boolean field.
*
* @param field - field name
* @param value - field value
* @returns this
*/
booleanField(name: string, value: boolean | any): Point;
/**
* Adds an integer field.
*
* @param name - field name
* @param value - field value
* @returns this
* @throws NaN or out of int64 range value is supplied
*/
intField(name: string, value: number | any): Point;
/**
* Adds an unsigned integer field.
*
* @param name - field name
* @param value - field value
* @returns this
* @throws NaN out of range value is supplied
*/
uintField(name: string, value: number | any): Point;
/**
* Adds a number field.
*
* @param name - field name
* @param value - field value
* @returns this
* @throws NaN/Infinity/-Infinity is supplied
*/
floatField(name: string, value: number | any): Point;
/**
* Adds a string field.
*
* @param name - field name
* @param value - field value
* @returns this
*/
stringField(name: string, value: string | any): Point;
/**
* Sets point timestamp. Timestamp can be specified as a Date (preferred), number, string
* or an undefined value. An undefined value instructs to assign a local timestamp using
* the client's clock. An empty string can be used to let the server assign
* the timestamp. A number value represents time as a count of time units since epoch, the
* exact time unit then depends on the {@link InfluxDB.getWriteApi | precision} of the API
* that writes the point.
*
* Beware that the current time in nanoseconds can't precisely fit into a JS number,
* which can hold at most 2^53 integer number. Nanosecond precision numbers are thus supplied as
* a (base-10) string. An application can also use ES2020 BigInt to represent nanoseconds,
* BigInt's `toString()` returns the required high-precision string.
*
* Note that InfluxDB requires the timestamp to fit into int64 data type.
*
* @param value - point time
* @returns this
*/
timestamp(value: Date | number | string | undefined): Point;
/**
* Creates an InfluxDB protocol line out of this instance.
* @param settings - settings control serialization of a point timestamp and can also add default tags,
* nanosecond timestamp precision is used when no `settings` or no `settings.convertTime` is supplied.
* @returns an InfluxDB protocol line out of this instance
*/
toLineProtocol(settings?: Partial<PointSettings>): string | undefined;
toString(): string;
}
/**
* Asynchronous API that writes time-series data into InfluxDB.
* This API always buffers points/lines to create batches under the hood
* to optimize data transfer to InfluxDB server, use `flush` to send
* the buffered data to InfluxDB immediately.
*/
interface WriteApi extends PointSettings {
/**
* Instructs to use the following default tags when writing points.
* Not applicable for writing records/lines.
* @param tags - default tags
* @returns this
*/
useDefaultTags(tags: {
[key: string]: string;
}): WriteApi;
/**
* Write a line of [Line Protocol](https://bit.ly/2QL99fu).
*
* @param record - line of InfluxDB Line Protocol
*/
writeRecord(record: string): void;
/**
* Write lines of [Line Protocol](https://bit.ly/2QL99fu).
*
* @param records - lines in InfluxDB Line Protocol
*/
writeRecords(records: Array<string>): void;
/**
* Write point.
*
* @param point - point to write
*/
writePoint(point: Point): void;
/**
* Write points.
*
* @param points - points to write
*/
writePoints(points: ArrayLike<Point>): void;
/**
* Flushes pending writes to the server.
* @param withRetryBuffer - flush also all the scheduled retries
* @returns completition promise
*/
flush(withRetryBuffer?: boolean): Promise<void>;
/**
* Flushes this writer and cancels retries of write operations that failed.
* @returns completition promise
*/
close(): Promise<void>;
/**
* Unlike close, dispose simply quits without trying to flush
* the buffered data.
* @returns count of points that were not written to InfluxDB
*/
dispose(): number;
/**
* HTTP path and query parameters of InfluxDB query API. It is
* automatically initialized to `/api/v2/write?org=...`,
* but it can be changed after the API is obtained.
*/
path: string;
}
/**
* Option for the communication with InfluxDB server.
*/
interface ConnectionOptions {
/** base URL */
url: string;
/** authentication token */
token?: string;
/**
* socket timeout, 10000 milliseconds by default in node.js
* @defaultValue 10000
*/
timeout?: number;
/**
* TransportOptions supply extra options for the transport layer, they differ between node.js and browser/deno.
* Node.js transport accepts options specified in {@link https://nodejs.org/api/http.html#http_http_request_options_callback | http.request } or
* {@link https://nodejs.org/api/https.html#https_https_request_options_callback | https.request }. For example, an `agent` property can be set to
* {@link https://www.npmjs.com/package/proxy-http-agent | setup HTTP/HTTPS proxy }, {@link https://nodejs.org/api/tls.html#tls_tls_connect_options_callback | rejectUnauthorized }
* property can disable TLS server certificate verification. Additionally,
* {@link https://github.com/follow-redirects/follow-redirects | follow-redirects } property can be also specified
* in order to follow redirects in node.js.
* {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch | fetch } is used under the hood in browser/deno.
* For example,
* {@link https://developer.mozilla.org/en-US/docs/Web/API/fetch | redirect } property can be set to 'error' to abort request if a redirect occurs.
*/
transportOptions?: {
[key: string]: any;
};
/**
* Default HTTP headers to send with every request.
*/
headers?: Record<string, string>;
/**
* Full HTTP web proxy URL including schema, for example http://your-proxy:8080.
*/
proxyUrl?: string;
}
/** default connection options */
declare const DEFAULT_ConnectionOptions: Partial<ConnectionOptions>;
/**
* Options that configure strategy for retrying failed requests.
*/
interface RetryDelayStrategyOptions {
/** add `random(retryJitter)` milliseconds delay when retrying HTTP calls */
retryJitter: number;
/** minimum delay when retrying write (milliseconds) */
minRetryDelay: number;
/** maximum delay when retrying write (milliseconds) */
maxRetryDelay: number;
/** base for the exponential retry delay */
exponentialBase: number;
/**
* randomRetry indicates whether the next retry delay is deterministic (false) or random (true).
* The deterministic delay starts with `minRetryDelay * exponentialBase` and it is multiplied
* by `exponentialBase` until it exceeds `maxRetryDelay`.
* When random is `true`, the next delay is computed as a random number between next retry attempt (upper)
* and the lower number in the deterministic sequence. `random(retryJitter)` is added to every returned value.
*/
randomRetry: boolean;
}
/**
* Options that configure strategy for retrying failed InfluxDB write operations.
*/
interface WriteRetryOptions extends RetryDelayStrategyOptions {
/**
* WriteFailed is called to inform about write errors.
* @param this - the instance of the API that failed
* @param error - write error
* @param lines - failed lines
* @param attempt - count of already failed attempts to write the lines (1 ... maxRetries+1)
* @param expires - expiration time for the lines to be retried in millis since epoch
* @returns a Promise to force the API to use it as a result of the flush operation,
* void/undefined to continue with default retry mechanism
*/
writeFailed(this: WriteApi, error: Error, lines: Array<string>, attempt: number, expires: number): Promise<void> | void;
/**
* WriteSuccess is informed about successfully written lines.
* @param this - the instance of the API in use
* @param lines - written lines
*/
writeSuccess(this: WriteApi, lines: Array<string>): void;
/**
* WriteRetrySkipped is informed about lines that were removed from the retry buffer
* to keep the size of the retry buffer under the configured limit (maxBufferLines).
* @param entry - lines that were skipped
*/
writeRetrySkipped(entry: {
lines: Array<string>;
expires: number;
}): void;
/** max count of retries after the first write fails */
maxRetries: number;
/** max time (millis) that can be spent with retries */
maxRetryTime: number;
/** the maximum size of retry-buffer (in lines) */
maxBufferLines: number;
}
/**
* Options used by {@link WriteApi} .
*/
interface WriteOptions extends WriteRetryOptions {
/** max number of records/lines to send in a batch */
batchSize: number;
/** delay between data flushes in milliseconds, at most `batch size` records are sent during flush */
flushInterval: number;
/** default tags, unescaped */
defaultTags?: Record<string, string>;
/** HTTP headers that will be sent with every write request */
headers?: {
[key: string]: string;
};
/** When specified, write bodies larger than the threshold are gzipped */
gzipThreshold?: number;
/** max size of a batch in bytes */
maxBatchBytes: number;
/** InfluxDB Enterprise write consistency as explained in https://docs.influxdata.com/enterprise_influxdb/v1.9/concepts/clustering/#write-consistency */
consistency?: 'any' | 'one' | 'quorum' | 'all';
}
/** default RetryDelayStrategyOptions */
declare const DEFAULT_RetryDelayStrategyOptions: {
retryJitter: number;
minRetryDelay: number;
maxRetryDelay: number;
exponentialBase: number;
randomRetry: boolean;
};
/** default writeOptions */
declare const DEFAULT_WriteOptions: WriteOptions;
/**
* Options used by {@link InfluxDB} .
*/
interface ClientOptions extends ConnectionOptions {
/** supplies and overrides default writing options */
writeOptions?: Partial<WriteOptions>;
/** specifies custom transport */
transport?: Transport;
}
/**
* Timestamp precision used in write operations.
* See {@link https://docs.influxdata.com/influxdb/latest/api/#operation/PostWrite }
*/
type WritePrecisionType = 'ns' | 'us' | 'ms' | 's';
/**
* Strategy for calculating retry delays.
*/
interface RetryDelayStrategy {
/**
* Returns delay for a next retry
* @param error - reason for retrying
* @param failedAttempts - a count of already failed attempts, 1 being the first
* @returns milliseconds to wait before retrying
*/
nextDelay(error?: Error, failedAttempts?: number): number;
/** Implementation should reset its state, this is mandatory to call upon success. */
success(): void;
}
/**
* Interface for errors to inform that an associated operation can be retried.
*/
interface RetriableDecision {
/**
* Informs whether this can be retried.
*/
canRetry(): boolean;
/**
* Get the delay in milliseconds to retry the action.
* @returns 0 to let the implementation decide, miliseconds delay otherwise
*/
retryAfter(): number;
}
/** isStatusCodeRetriable checks whether the supplied HTTP status code is retriable. */
declare function isStatusCodeRetriable(statusCode: number): boolean;
/** IllegalArgumentError is thrown when illegal argument is supplied. */
declare class IllegalArgumentError extends Error {
constructor(message: string);
}
/**
* A general HTTP error.
*/
declare class HttpError extends Error implements RetriableDecision {
readonly statusCode: number;
readonly statusMessage: string | undefined;
readonly body?: string | undefined;
readonly contentType?: string | null | undefined;
private _retryAfter;
/** application error code, when available */
code: string | undefined;
/** json error response */
json: any;
constructor(statusCode: number, statusMessage: string | undefined, body?: string | undefined, retryAfter?: string | undefined | null, contentType?: string | null | undefined, message?: string);
private setRetryAfter;
canRetry(): boolean;
retryAfter(): number;
}
/**
* Tests the error in order to know if an HTTP call can be retried.
* @param error - error to test
* @returns true for a retriable error
*/
declare function canRetryHttpCall(error: any): boolean;
/**
* Gets retry delay from the supplied error, possibly using random number up to retryJitter.
*/
declare function getRetryDelay(error?: Error, retryJitter?: number): number;
/** RequestTimedOutError indicates request timeout in the communication with the server */
declare class RequestTimedOutError extends Error implements RetriableDecision {
constructor();
canRetry(): boolean;
retryAfter(): number;
}
/** AbortError indicates that the communication with the server was aborted */
declare class AbortError extends Error implements RetriableDecision {
constructor();
canRetry(): boolean;
retryAfter(): number;
}
/**
* Provides functions escape specific parts in InfluxDB line protocol.
*/
declare const escape: {
/**
* Measurement escapes measurement names.
*/
measurement: (value: string) => string;
/**
* Quoted escapes quoted values, such as database names.
*/
quoted: (value: string) => string;
/**
* TagEscaper escapes tag keys, tag values, and field keys.
*/
tag: (value: string) => string;
};
declare function useProcessHrtime(use: boolean): boolean;
/**
* Exposes functions that creates strings that represent a timestamp that
* can be used in the line protocol. Micro and nano timestamps are emulated
* depending on the js platform in use.
*/
declare const currentTime: {
s: () => string;
ms: () => string;
us: () => string;
ns: () => string;
seconds: () => string;
millis: () => string;
micros: () => string;
nanos: () => string;
};
/**
* dateToProtocolTimestamp provides converters for JavaScript Date to InfluxDB Write Protocol Timestamp. Keys are supported precisions.
*/
declare const dateToProtocolTimestamp: {
s: (d: Date) => string;
ms: (d: Date) => string;
us: (d: Date) => string;
ns: (d: Date) => string;
};
/**
* convertTimeToNanos converts Point's timestamp to a string.
* @param value - supported timestamp value
* @returns line protocol value
*/
declare function convertTimeToNanos(value: string | number | Date | undefined): string | undefined;
/**
* Logging interface.
*/
interface Logger {
error(message: string, err?: any): void;
warn(message: string, err?: any): void;
}
/**
* Logger that logs to console.out
*/
declare const consoleLogger: Logger;
declare const Log: Logger;
/**
* Sets custom logger.
* @param logger - logger to use
* @returns previous logger
*/
declare function setLogger(logger: Logger): Logger;
/** Property that offers a function that returns flux-sanitized value of an object. */
declare const FLUX_VALUE: unique symbol;
/**
* A flux parameter can print its (sanitized) flux value.
*/
interface FluxParameterLike {
[FLUX_VALUE](): string;
}
/**
* Represents a parameterized query.
*/
interface ParameterizedQuery {
/**
* Returns flux query with sanitized parameters.
*/
toString(): string;
}
/**
* Creates a flux string literal.
*/
declare function fluxString(value: any): FluxParameterLike;
/**
* Sanitizes float value to avoid injections.
* @param value - InfluxDB float literal
* @returns sanitized float value
* @throws Error if the the value cannot be sanitized
*/
declare function sanitizeFloat(value: any): string;
/**
* Creates a flux float literal.
*/
declare function fluxFloat(value: any): FluxParameterLike;
/**
* Sanitizes integer value to avoid injections.
* @param value - InfluxDB integer literal
* @returns sanitized integer value
* @throws Error if the the value cannot be sanitized
*/
declare function sanitizeInteger(value: any): string;
/**
* Creates a flux integer literal.
*/
declare function fluxInteger(value: any): FluxParameterLike;
/**
* Creates flux date-time literal.
*/
declare function fluxDateTime(value: any): FluxParameterLike;
/**
* Creates flux date-time literal.
*/
declare function fluxDuration(value: any): FluxParameterLike;
/**
* Creates flux regexp literal out of a regular expression. See
* https://docs.influxdata.com/flux/latest/data-types/basic/regexp/#regular-expression-syntax
* for details.
*/
declare function fluxRegExp(value: any): FluxParameterLike;
/**
* Creates flux boolean literal.
*/
declare function fluxBool(value: any): FluxParameterLike;
/**
* Assumes that the supplied value is flux expression or literal that does not need sanitizing.
*
* @param value - any value
* @returns the supplied value as-is
*/
declare function fluxExpression(value: any): FluxParameterLike;
/**
* Escapes content of the supplied parameter so that it can be safely embedded into flux query.
* @param value - parameter value
* @returns sanitized flux value or an empty string if it cannot be converted
*/
declare function toFluxValue(value: any): string;
/**
* Flux is a tagged template that sanitizes supplied parameters
* to avoid injection attacks in flux.
*/
declare function flux(strings: TemplateStringsArray, ...values: any): ParameterizedQuery;
/** QueryOptions contains QueryApi configuration options. */
interface QueryOptions {
/**
* Specifies the name of the organization executing the query. Takes either the ID or Name interchangeably.
*/
org: string;
/**
* Type of the query, default is "flux"
*/
type?: 'flux';
/**
* Requests gzip encoded response.
*/
gzip?: boolean;
/**
* Specifies the time that should be reported as "now" in the query. RFC3339 value must be returned,
* for example `new Date().toISOString()`.
*/
now?: () => string;
/**
* HTTP headers that will be sent with every query request.
*/
headers?: {
[key: string]: string;
};
}
/**
* Query InfluxDB. Provides methods that notify about result lines of the executed query.
* See {@link https://docs.influxdata.com/influxdb/latest/api/#operation/PostQuery }
*/
interface QueryApi {
/**
* Returns a new query API with extra options applied.
* @param options - query options to use
* @returns queryApi instance with the supplied options
*/
with(options: Partial<QueryOptions>): QueryApi;
/**
* Response returns an AnnotatedCSVResponse instance that executes
* the query when asked for data.
*
* @param query - query
* @returns response with various methods to process data from the returned annotated
* CSV response data stream
*/
response(query: string | ParameterizedQuery): AnnotatedCSVResponse;
/**
* IterateLines executes the supplied query and returns results in
* an async iterable of annotated CSV lines.
* Async iterables are best consumed by `for-await` loop.
*
* @param query - query
* @returns async iterable of CSV result lines
*/
iterateLines(query: string | ParameterizedQuery): AsyncIterable<string>;
/**
* IterateRows executes the supplied query and returns results in
* an async iterable of row data and table metadata pairs.
* Async iterables are best consumed by `for-await` loop.
*
* @param query - query
* @returns async iterable of CSV result lines
*/
iterateRows(query: string | ParameterizedQuery): AsyncIterable<Row>;
/**
* Creates a cold observable of the lines returned by the given query.
*
* @param query - query
* @returns observable of CSV result lines
*/
lines(query: string | ParameterizedQuery): Observable<string>;
/**
* Creates a cold observable of the rows returned by the given query.
*
* @param query - query
* @returns observable of result rows
*/
rows(query: string | ParameterizedQuery): Observable<Row>;
/**
* Executes the query and receives result lines (including empty and annotation lines)
* through the supplied consumer. See [annotated-csv](https://docs.influxdata.com/influxdb/latest/reference/syntax/annotated-csv/).
*
* @param query - query
* @param consumer - csv result lines and error consumer
*/
queryLines(query: string | ParameterizedQuery, consumer: CommunicationObserver<string>): void;
/**
* Executes the query and receives table metadata and rows through the supplied consumer.
*
* @param query - query
* @param consumer - result rows and error consumer
*/
queryRows(query: string | ParameterizedQuery, consumer: FluxResultObserver<string[]>): void;
/**
* QueryRaw executes a query and returns the full response as a string.
* Use with caution, a possibly huge stream is copied to memory.
*
* @param query - query
* @returns Promise of response text
*/
queryRaw(query: string | ParameterizedQuery): Promise<string>;
/**
* CollectRows executes the query and collects all the results in the returned Promise.
* This method is suitable to collect simple results. Use with caution,
* a possibly huge stream of results is copied to memory.
*
* @param query - query
* @param rowMapper - maps the supplied row to an item that is then collected,
* undefined return values are not collected. If no rowMapper is supplied,
* `row => tableMeta.toObject(row.values)` is used.
* @returns Promise of mapped results
*/
collectRows<T>(query: string | ParameterizedQuery, rowMapper?: (values: string[], tableMeta: FluxTableMetaData) => T | undefined): Promise<Array<T>>;
/**
* CollectLines executes the query and collects all result lines in the returned Promise.
* This method is suitable to collect simple results. Use with caution,
* a possibly huge stream of lines is copied to memory.
*
* @param query - query
* @returns Promise of returned csv lines
*/
collectLines(query: string | ParameterizedQuery): Promise<Array<string>>;
}
/**
* InfluxDB entry point that configures communication with InfluxDB server
* and provide APIs to write and query data.
*/
declare class InfluxDB {
private _options;
readonly transport: Transport;
readonly processCSVResponse: (executor: APIExecutor, iterableResultExecutor: IterableResultExecutor) => AnnotatedCSVResponse;
/**
* Creates influxdb client options from an options object or url.
* @param options - client options
*/
constructor(options: ClientOptions | string);
/**
* Creates WriteApi for the supplied organization and bucket. BEWARE that returned instances must be closed
* in order to flush the remaining data and close already scheduled retry executions.
*
* @remarks
* Use {@link WriteOptions} to customize retry strategy options, data chunking
* and flushing options. See {@link DEFAULT_WriteOptions} to see the defaults.
*
* See also {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/write.mjs | write example},
* {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/writeAdvanced.mjs | writeAdvanced example},
* and {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/index.html | browser example}.
*
* @param org - Specifies the destination organization for writes. Takes either the ID or Name interchangeably.
* @param bucket - The destination bucket for writes.
* @param precision - Timestamp precision for line items.
* @param writeOptions - Custom write options.
* @returns WriteApi instance
*/
getWriteApi(org: string, bucket: string, precision?: WritePrecisionType, writeOptions?: Partial<WriteOptions>): WriteApi;
/**
* Creates QueryApi for the supplied organization .
*
* @remarks
* See also {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/query.ts | query.ts example},
* {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/queryWithParams.mjs | queryWithParams.mjs example},
* {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/rxjs-query.ts | rxjs-query.ts example},
* and {@link https://github.com/influxdata/influxdb-client-js/blob/master/examples/index.html | browser example},
*
* @param org - organization or query options
* @returns QueryApi instance
*/
getQueryApi(org: string | QueryOptions): QueryApi;
}
export { APIExecutor, AbortError, AnnotatedCSVResponse, Cancellable, ChunkCombiner, ClientOptions, ColumnType, CommunicationObserver, ConnectionOptions, DEFAULT_ConnectionOptions, DEFAULT_RetryDelayStrategyOptions, DEFAULT_WriteOptions, FLUX_VALUE, FluxParameterLike, FluxResultObserver, FluxTableColumn, FluxTableMetaData, HttpHeaders as Headers, HttpError, HttpHeaders, IllegalArgumentError, InfluxDB, IterableResultExecutor, LineSplitter, Log, Logger, Observable, Observer, ObserverComplete, ObserverError, ObserverNext, ParameterizedQuery, Point, PointSettings, QueryApi, QueryOptions, RequestTimedOutError, ResponseStartedFn, RetriableDecision, RetryDelayStrategy, RetryDelayStrategyOptions, Row, SendOptions, Subscribable, Subscription, Transport, UNKNOWN_COLUMN, WriteApi, WriteOptions, WritePrecisionType, WriteRetryOptions, canRetryHttpCall, chunksToLines, chunksToLinesIterable, consoleLogger, convertTimeToNanos, createFluxTableColumn, createFluxTableMetaData, createTextDecoderCombiner, currentTime, dateToProtocolTimestamp, escape, flux, fluxBool, fluxDateTime, fluxDuration, fluxExpression, fluxFloat, fluxInteger, fluxRegExp, fluxString, getRetryDelay, isStatusCodeRetriable, linesToRowsIterable, linesToTables, newFluxTableColumn, sanitizeFloat, sanitizeInteger, serializeDateTimeAsDate, serializeDateTimeAsNumber, serializeDateTimeAsString, setLogger, stringToLines, symbolObservable, toFluxValue, typeSerializers, useProcessHrtime };