UNPKG

diffusion

Version:

Diffusion JavaScript client

1,361 lines 564 kB
export {}; /** * @module diffusion */ /// <reference types="node" /> /** * The top-level Diffusion API. * * Provides access to Session connections and global namespaces. */ /** * The version of this client library in the form major.minor.patch */ export declare const version: string; /** * The build version of this client library */ export declare const build: string; /** * Set the level of logging used by Diffusion. This will default to silent. * Log levels are strings that represent different degrees of information to * be logged. Available options are: * * * silent * * error * * warn * * info * * debug * * trace * * @param level the log level to use */ export declare function log(level: LogLevel | keyof typeof LogLevel): void; /** * Connect to a specified Diffusion server. This will return a {@link * Promise} that will complete successfully if a session can be connected, or * fail if an error was encountered. * * If the result is successful, the fulfilled handler will be called with a * {@link Session} instance. This session will be in a connected state and * may be used for subsequent API calls. * * If the result fails, the rejected handler will be called with an error * reason. * * If `sessionName` and `workerJs` is supplied, then the call will create a * shared session inside a shared WebWorker. If a shared session with that name * already exists, this function will return an instance of the existing * session. Shared sessions can only be created when running in a browser * environment that supports the SharedWorker. For more information regarding * shared sessions, see {@link connectShared}. * * **Example:** * ``` * diffusion.connect('example.server.com').then((session) => { * // Connected with a session * console.log('Connected!', session); * }).catch((error) => { * // Connection failed * console.log('Failed to connect', error); * }); * ``` * * @param options the options to construct the session with. If a string is * supplied, it will be interpreted as the `host` option. * @param sessionName the name of the shared session * @param workerJs the location of the diffusion worker script * @returns a {@link Promise} for this operation * * @throws a {@link NullValueError} if only one of `sessionName` or `workerJs` is `undefined` * or if `options` is `undefined` * @throws an {@link IllegalArgumentError} if the options are invalid. */ export declare function connect(options: Options | string, sessionName?: string, workerJs?: string): Promise<Session>; /** * Connect to a specified Diffusion server using a shared WebWorker session. * This will return a {@link Promise} that will complete successfully if a * session can be connected, or fail if an error was encountered. Shared * sessions can only be created when running in a browser environment that * supports the SharedWorker. * * Shared sessions are identified by a name. If a shared session with that name * already exists, this function will return an instance of the existing * session. Otherwise the call will fail. Sessions can only be shared across * scripts originating from a single domain. Otherwise the browser will create * independent shared workers resulting in one shared session for each domain. * * The shared session will stay alive as long as there is an open browser tab * that initiated a connection through the shared session. When the last tab is * closed the shared worker holding the shared session will be terminated. The * shared session is also expected to be terminated when the only tab holding a * reference to the session is reloaded or experiences a page navigation. The * exact behavior may be browser dependent. * * The `workerJs` argument must be set to the URL of the `diffusion-worker.js` * supplied with the JavaScript distribution. The same-origin policy of * the shared worker requires the calling script and the `diffusion-worker.js` * to reside on the same domain. * * If the result is successful, the fulfilled handler will be called with a * {@link Session} instance. This session will be in a connected state and * may be used for subsequent API calls. * * If the result fails, the rejected handler will be called with an error * reason. * * **Example:** * ``` * const options = { * host : 'localhost', * port : '8080', * principal : 'admin', * credentials : 'password' * }; * * diffusion.connect(options, 'some-session', 'diffusion-worker.js').then((session) => { * console.log('Connected creating new shared session', session); * }).catch((error) => { * console.log('Failed to connect', error); * }); * * diffusion.connectShared('some-session', 'diffusion-worker.js').then((session) => { * console.log('Connected to existing shared session', session); * }.catch((error) => { * console.log('Failed to connect shared', error); * }); * ``` * * @param sessionName the name of the shared session * @param workerJs the location of the diffusion worker script * @returns a {@link Promise} for this operation * @throws an {@link IllegalArgumentError} if the options are invalid. */ export declare function connectShared(sessionName: string, workerJs: string): Promise<Session>; /** * Escapes special characters in a string that is to be used within a topic * property or a session filter. * <P> * This is a convenience method which inserts an escape character '\' before * any of the special characters ' " or \. * * @param s the string to be escaped * @returns the string value with escape characters inserted as appropriate * * @since 6.1 */ export declare function escape(s: string): string; /** * Utility method which converts a string of the format required by the * {@link PropertyKeys.ROLES $Roles} session property into a mutable set of * strings. * * @param s the string with quoted roles separated by whitespace or * commas * * @return set of roles * @throws an error if the argument is `null` or `undefined` * @throws an {@link IllegalArgumentError} if the input is not correctly quoted * * @since 6.2 */ export declare function stringToRoles(s: string): Set<string>; /** * Utility method which converts a set of authorisation roles to the string * format required by the {@link PropertyKeys.ROLES $Roles} session property. * * @param roles a set of roles * @return a string representing the supplied roles, formatted as * required by the {@link PropertyKeys.ROLES $Roles} session * property * * @since 6.2 */ export declare function rolesToString(roles: Set<string> | string[]): string; /** * Returns an update constraint factory. * * @function diffusion#updateConstraints * @return {diffusion.topicUpdate.UpdateConstraintFactory} update constraint * factory * @since 6.2 */ export declare function updateConstraints(): UpdateConstraintFactory; /** * Create a new {@link BranchMappingTableBuilder}. * * @since 6.7 * @see SessionTrees */ export declare function newBranchMappingTableBuilder(): BranchMappingTableBuilder; /** * Create a new {@link SessionMetricCollectorBuilder}. * * @since 6.7 */ export declare function newSessionMetricCollectorBuilder(): SessionMetricCollectorBuilder; /** * Create a new {@link TopicMetricCollectorBuilder}. * * @since 6.7 */ export declare function newTopicMetricCollectorBuilder(): TopicMetricCollectorBuilder; /** * Access to the selectors namespace */ export declare const selectors: TopicSelectors; export declare function newRemoteServerBuilder(): RemoteServerBuilder; export declare function newRemoteServerBuilder(type: RemoteServerType.PRIMARY_INITIATOR): PrimaryInitiatorBuilder; export declare function newRemoteServerBuilder(type: RemoteServerType.SECONDARY_ACCEPTOR): SecondaryAcceptorBuilder; export declare function newRemoteServerBuilder(type: RemoteServerType.SECONDARY_INITIATOR): SecondaryInitiatorBuilder; export declare function newRemoteServerBuilder(type?: RemoteServerType): RemoteServerBuilder | PrimaryInitiatorBuilder | SecondaryAcceptorBuilder | SecondaryInitiatorBuilder; /** * Create a new {@link SessionEventParametersBuilder}. * * @return the builder * * @since 6.11 */ export declare function newSessionEventParametersBuilder(): SessionEventParametersBuilder; /** * Access to the datatypes namespace */ export declare const datatypes: DataTypes; /** * Access to the topics namespace */ export declare const topics: TopicsNamespace; /** * Access to the topicUpdate namespace */ export declare const topicUpdate: TopicUpdateNamespace; /** * The ErrorReason enum */ export declare const errors: { [key: string]: ErrorReasonType; }; /** * Access to PropertyKeys */ export declare const clients: ClientControlOptionsNamespace; /** * Access to the locks namespace */ export declare const locks: SessionLockOptionsNamespace; /** * Access to the Buffer API that is packaged with diffusion. * * This can be used in browsers that don't have a native Buffer class. It allows * the creation of buffers for use with {@link BinaryDataType binary} datatypes. * * @example * ``` * const buf = diffusion.buffer.from('Hello World', 'utf8') * ``` * * @deprecated since version 6.11. Buffer has been replaced by Uint8Array.This * will be removed in a future release. */ export declare const buffer: { prototype: Buffer; poolSize: number; new (str: string, encoding?: string | undefined): Buffer; new (size: number): Buffer; new (array: Uint8Array): Buffer; new (arrayBuffer: ArrayBuffer): Buffer; new (array: any[]): Buffer; new (buffer: Buffer): Buffer; from(arrayBuffer: ArrayBuffer, byteOffset?: number | undefined, length?: number | undefined): Buffer; from(data: string | any[] | ArrayBuffer | Buffer): Buffer; from(str: string, encoding?: string | undefined): Buffer; isBuffer(obj: any): obj is Buffer; isEncoding(encoding: string): boolean; byteLength(string: string | DataView | ArrayBuffer | Buffer, encoding?: string | undefined): number; concat(list: Buffer[], totalLength?: number | undefined): Buffer; compare(buf1: Buffer, buf2: Buffer): number; alloc(size: number, fill?: string | number | Buffer | undefined, encoding?: string | undefined): Buffer; allocUnsafe(size: number): Buffer; allocUnsafeSlow(size: number): Buffer; }; /** * @module diffusion.errors */ /** * An ErrorReport from the server. */ export interface ErrorReport { /** * The error message */ message: string; /** * The line at which the problem was found */ line: number; /** * The column at which the problem was found */ column: number; } /** * @module Session */ /** * A typed array that can be passed as credentials */ export declare type TypedArray = Int8Array | Int16Array | Int32Array | Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | Float32Array | Float64Array; /** * A reconnection strategy */ export declare type ReconnectStrategy = (reconnect: () => void, abort: () => void) => void; /** * Defines a retry strategy. * * A retry strategy will be applied when an initial to attempt to open a session * fails with a transient session establishment exception. * * A retry strategy will be applied when recovering by a * {@link RecoverableUpdateStream} following a recoverable exception. * * The strategy is defined in terms of the number of milliseconds between * retries and the maximum number of retries to attempt. * * If no properties are defined, it means that no retries will be attempted. * * If `interval` is defined but `attempts` is not, it means that unlimited retries * will be attempted. * * @since 6.10 */ export interface RetryStrategy { /** * The number of milliseconds before the first retry and between subsequent retries */ interval?: number; /** * The number of retry attempts */ attempts?: number; } /** * Additional options that can be passed to the {@link connect} function affecting * the underlying TLS configuratio. These options are passed directly to * `tls.createSecureContext()`. For more information, see the documentation for * the `tls.createSecureContext()` function in the Node.js documentation. */ export interface ExtraTlsOptions { /** * Optionally override the trusted CA certificates. */ ca?: string | Uint8Array | Array<string | Uint8Array> | undefined; /** * Cert chains in PEM format. */ cert?: string | Uint8Array | Array<string | Uint8Array> | undefined; /** * Cipher suite specification, replacing the default. */ ciphers?: string | undefined; /** * Name of an OpenSSL engine which can provide the client certificate. */ clientCertEngine?: string | undefined; /** * PEM formatted CRLs (Certificate Revocation Lists). */ crl?: string | Uint8Array | Array<string | Uint8Array> | undefined; /** * Diffie Hellman parameters, required for Perfect Forward Secrecy. */ dhparam?: string | Uint8Array | undefined; /** * A string describing a named curve or a colon separated list of curve * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key * agreement. */ ecdhCurve?: string | undefined; /** * Attempt to use the server's cipher suite preferences instead of the * client's. */ honorCipherOrder?: boolean | undefined; /** * Private keys in PEM format. */ key?: string | Uint8Array | Uint8Array[] | undefined; /** * Shared passphrase used for a single private key and/or a PFX. */ passphrase?: string | undefined; /** * PFX or PKCS12 encoded private key and certificate chain. */ pfx?: string | Uint8Array | Array<string | Uint8Array> | undefined; /** * Optionally affect the OpenSSL protocol behavior, which is not * usually necessary. */ secureOptions?: number | undefined; /** * Legacy mechanism to select the TLS protocol version to use. */ secureProtocol?: string | undefined; /** * Opaque identifier used by servers to ensure session state is not * shared between applications. */ sessionIdContext?: string | undefined; /** * If true the server will reject any connection which is not * authorized with the list of supplied CAs. */ rejectUnauthorized?: boolean | undefined; } /** * Provide Session configuration options. * * <h5>Connection:</h5> * There are several option values that can be configured to change how * Diffusion establishes a connection. These options are used to derive a * connection URL in the format: <code>{protocol}://{host}:{port}/{path}</code>. * The protocol used is determined by the chosen transports and whether secure * connections are enabled. * * <table> * <thead> * <tr> * <th>Option</th> * <th>Default value</th> * <th>Description</th> * </tr> * </thead> * <tbody> * <tr> * <td>host</td> * <td><code>localhost</code></td> * <td>The hostname to connect to.</td> * </tr> * <tr> * <td>port</td> * <td><code>80</code> or <code>443</code></td> * <td>The port to connect to. The default value is the default secure port if * secure connections are enabled, otherwise the default value is the default * insecure port. * <p> * In case the client is being run in a page served via <code>https</code> * (<code>http</code>), the default secure (insecure) port is the port of the * URI of the current page, otherwise the default secure (insecure) port is * <code>443</code> (<code>80</code>). * </tr> * <tr> * <td>path</td> * <td><code>/diffusion</code></td> * <td>The URL path to apply after the hostname/port. This allows additional context to be provided, such as might be * used by load balancers.</td> * </tr> * <tr> * <td>secure</td> * <td><code>true</code></td> * <td>Determines if secure transports will be used. If the port is not * explicitly specified this value defaults to <code>true</code>. If the port is * explicitly specified the default value is <code>true</code> only if the port is * equal to the default secure port, otherwise <code>false</code>. * <p> * In case the client is being run in a page served via <code>https</code>, the * default secure port is the port of the URI of the current page, otherwise the * default secure port is <code>443</code>.</td> * </tr> * </tbody> * </table> * * <h5>Reconnection:</h5> * * Reconnection is enabled by default. The <code>reconnect</code> key accepts several different option values. * <table> * <thead> * <tr> * <th>Option type</th> * <th>Default value</th> * <th>Description</th> * </tr> * </thead> * <tbody> * <tr> * <td><code>boolean</code></td> * <td><code>true</code></td> * <td>Enables or disables reconnection. If set to <code>true</code>, reconnection will be enabled using the default * timeout value and a periodic back-off strategy.</td> * </tr> * <tr> * <td><code>number</code></td> * <td><code>60000</code></td> * <td>Passing a number will enable reconnection with the default strategy and the reconnection timeout set to the * specified value. The reconnection timeout determines how long, in milliseconds, the client will remain in a * <code>disconnected</code> state before the client is closed.</td> * </tr> * <tr> * <td><code>function</code></td> * <td><pre> * function(reconnect, abort) { * setTimeout(reconnect, 5000); * }</pre></td> * <td>A strategy function that will be called when the client enters a <code>disconnected</code> state, and * subsequently if attempts to reconnect fail. Two arguments are provided, <code>reconnect</code> and <code>abort</code> * - these are functions to be called within the strategy. The <code>reconnect</code> argument will initiate a * reconnect attempt. <code>abort</code> may be called to abort reconnection, in which case the client will be closed. * </td> * </tr> * <tr> * <td><pre> * { * timeout : &lt;number&gt;, * strategy : &lt;function&gt; * }</pre></td> * <td><pre> * { * timeout : 60000, * strategy : function(reconnect, abort) { * setTimeout(reconnect, 5000); * } * }</pre></td> * <td>An object containing both the timeout and strategy options as specified above, allowing both to be set together. * </td> * </tr> * </tbody> * </table> * * <h5>Transports:</h5> * * The <code>transports</code> property configures how the session should connect. It can be set to either a * <code>string</code>, or an <code>array</code> of strings to provide a transport cascading capability. * * <table> * <thead> * <tr> * <th>Transport key</th> * <th>Description</th> * </tr> * </thead> * <tbody> * <tr> * <td><code>ws</code>, <code>WS</code>, <code>WEBSOCKET</code></td> * <td>The WebSocket transport. A single, long-lived WebSocket connection will be used to send and receive data.</td> * </tr> * <tr> * <td><code>xhr</code>, <code>XHR</code>, <code>HTTP_POLLING</code></td> * <td>An XHR-based polling transport. Data will be queued on the client and server, and sent in batches.</td> * </tr> * </tbody> * </table> * The client will use the transports in the order provided, for example: * <code>transports: ['WS', 'XHR']</code> indicates that the client will attempt to connect with the WebSocket * transport, and if the connection fails, the client will attempt to connect with the HTTP Polling transport. When no * <code>transports</code> value is provided the client will default to using the WebSocket transport. Any string values * that do not have an associated transport will be ignored. * * When the diffusion client is run in a browser environment, `transports` will * default to `['WEBSOCKET', 'XHR']`. When run in Node, `transports` will * default to `['WEBSOCKET']`. * * <h5>Properties:</h5> * * Supplied session properties will be provided to the server when a session * is created using this session factory. The supplied properties will be * validated during authentication and may be discarded or changed. * * The specified properties will be added to any existing properties set for * this session factory. If any of the keys have been previously declared * then they will be overwritten with the new values. * * For details of how session properties are used see {@link Session}. */ export interface Options { /** * The hostname to connect to (default `'localhost'`) */ host?: string; /** * The port to connect to (default `443`) */ port?: number | string; /** * The request path used for connections (default `/diffusion`) */ path?: string; /** * Whether to use secure connections. */ secure?: boolean; /** * The principal name this session should connect with. Used for authentication. */ principal?: string; /** * A password string to authenticate with, a buffer containing custom * credentials in binary format, a typed array, or a regular * array of octets. */ credentials?: string | TypedArray | number[]; /** * The timeout in milliseconds used when connecting to the server. (default `10000`) */ connectionTimeout?: number; /** * A retry strategy that defines the behaviour for the initial connection * attempt. * * The default connection strategy will attempt each transport once before * cascading to the next transport. */ retry?: RetryStrategy; /** * Reconnection options. (default `true`) */ reconnect?: boolean | number | ReconnectStrategy | { timeout?: number; strategy?: ReconnectStrategy; }; /** * The transports to be used for connection establishment. (default `"WEBSOCKET"`) */ transports?: string | string[]; /** * The maximum size of messages that may be received from the server. (default `2147483647`) */ maxMessageSize?: number; /** * An object of key-value pairs that define the user-defined session properties. * * Property values will be sent as `string` values. Non-string properties must * implement the `toString()` method to allow conversion. * * For details of how session properties are used see {@link Session}. */ properties?: { [key: string]: any; }; /** * An optional HTTP/HTTPS proxy agent. (default `undefined`) * * If this is set, then the client will attempt to connect to the Diffusion * server via a proxy server. * * The proxy agent will be passed to the WebSocket constructor as the * `agent` option. See https://www.npmjs.com/package/https-proxy-agent for * an example of a proxy agent. * * This option is used for web socket connections and is intended for Node * based clients only. Browser based clients will automatically use the * browser's proxy settings. * * **Example:** * ``` * const HttpsProxyAgent = require('https-proxy-agent'); * const url = require('url'); * const diffusion = require('diffusion'); * * const agent = new HttpsProxyAgent(url.parse('https://proxy.example.com:80')); * * diffusion.connect({ * host: 'https://diffusion.foo.com', * httpProxyAgent: agent * }).then((session) => { * // connected through proxy server * }); * ``` */ httpProxyAgent?: any; /** * An optional TLS options object. (default `undefined`) * This option is used for secure web socket connections and is intended for * Node based clients only. Browser based clients will automatically use the * browser's TLS settings. * * See https://nodejs.org/api/tls.html#tlscreatesecurecontextoptions for * more information. */ tlsOptions?: ExtraTlsOptions; } /** * Alias for the Options interface to keep compatibility with old TypeScript definitions */ export declare type SessionOptions = Options; /** * @module Session */ /** * A session ID */ export interface SessionId { /** * Convert the session ID to a string * * @return a string representation of the session ID */ toString(): string; } /** * A client session to a server or cluster of servers. * * A new session can be created by connecting to a server using * {@link connect diffusion.connect}, specifying the server URL. The session * factory can be configured to control the behavior the session. * * The session provides a variety of operations to the application. These are * grouped into feature interfaces, such as {@link Topics} and * {@link Messages}, exposed to the application through properties on the Session * object. * * <h3>Session lifecycle</h3> * * Each session is managed by a server. The server assigns the session a * {@link Session.sessionId unique identity}, and manages the session's topic * subscriptions, security details, and <a href="#session-properties">session * properties</a>. * * A session can be terminated using {@link close}. A session may also be * terminated by the server because of an error, a time out, or because it's * authentication has expired. It can also be terminated by other privileged * sessions using the {@link ClientControl} feature. * * A client can become disconnected from the server, and reconnect to the server * without loss of the session. Reconnection can be configured using * {@link Options.reconnect the session options}. The server * must be configured to allow reconnection. * * If a session is connected to a server that belongs to a cluster with session * replication enabled, and then becomes disconnected, it will attempt to * reconnect to the original server. A properly configured load balancer can * detect that the original server is unavailable and re-route the reconnection * request to a second server in the cluster. The second server can recover * session data and continue the session. This process is known as "fail over". * Unlike reconnection, in-flight messages can be lost during failover, and the * application will be unsubscribed and re-subscribed to topics. * * The current state of the session can be retrieved with {@link isClosed} and * {@link isConnected}. Listeners can be registered with {@link on} which will be * notified when the session state changes. * * <H3>Session properties</H3> * * For each session, the server stores a set of session properties that describe * various attributes of the session. * * There are two types of session property. Fixed properties are assigned by the * server. User-defined properties are proposed by the application, but may * be changed during authentication. * * Many operations use session filter expressions (see section Session Filters) * that use session properties to select sessions. * * A session may obtain its own session properties using * {@link Session.getSessionProperties}. * * A privileged client can monitor other sessions, including changes to their * session properties, using a {@link ClientControl.addSessionEventListener * session event listener}. When registering to receive session properties, * special key values of {@link PropertyKeys.ALL_FIXED_PROPERTIES * ALL_FIXED_PROPERTIES} and {@link PropertyKeys.ALL_USER_PROPERTIES * ALL_USER_PROPERTIES} can be used. * * Each property is identified by a key. Most properties have a single string * value. The exception is the $Roles fixed property which has a set of string * values. * * Fixed properties are identified by keys with a '$' prefix. The available * fixed session properties are: * * <table> * <tr> * <td><b>Key</b></td> * <td><b>Description</b></td> * </tr> * <tr> * <td><code>$ClientIP</code></td> * <td>The Internet address of the client in string format.</td> * </tr> * <tr> * <td><code>$ClientType</code></td> * <td>The client type of the session. One of <code>ANDROID</code>, <code>C</code>, * <code>DOTNET</code>, <code>IOS</code>, <code>JAVA</code>, <code>JAVASCRIPT_BROWSER</code>, * <code>MQTT</code>, <code>PYTHON</code>, or <code>OTHER</code>.</td> * </tr> * <tr> * <td><code>$Connector</code></td> * <td>The configuration name of the server connector that the client connected * to.</td> * </tr> * <tr> * <td><code>$Country</code></td> * <td>The country code for the country where the client's Internet address was * allocated (for example, <code>NZ</code> for New Zealand). If the country code could not * be determined, this will be a zero length string.</td> * </tr> * <tr> * <tr> * <td><code>$Environment</code></td> * <td>The environment in which the client is running. For possible values see the <a href= * "https://docs.diffusiondata.com/docs/latest/manual/html/developerguide/client/basics/uci_session_properties.html">user manual</a>. * The browser name and version are determined by the <a href="https://www.npmjs.com/package/ua-parser-js">UA-Parser</a> library.</td> * </tr> * <tr> * <td><code>$ExpiryTime</code></td> * <td>The time at which the session is due to expire, specified in milliseconds * since the epoch. This may be set by authenticators. If not present, the * session will not expire.</td> * </tr> * <td><code>$GatewayType</code></td> * <td>Gateway client type. Only set for gateway client sessions. * If present it indicates the type of gateway client (e.g. Kafka).</td> * </tr> * <tr> * <td><code>$GatewayId</code></td> * <td>The identity of a gateway client session. * Only present if the $GatewayType session property is present.</td> * </tr> * <tr> * <td><code>$Language</code></td> * <td>The language code for the official language of the country where the * client's Internet address was allocated (for example, <code>en</code> for English). If * the language could not be determined or is not applicable, this will be a * zero length string.</td> * </tr> * <tr> * <td><code>$Latitude</code></td> * <td>The client's latitude, if available. This will be the string * representation of a floating point number and will be <code>NaN</code> if not * available.</td> * </tr> * <tr> * <td><code>$Longitude</code></td> * <td>The client's longitude, if available. This will be the string * representation of a floating point number and will be <code>NaN</code> if not * available.</td> * </tr> * <td><code>$MQTTClientId</code></td> * <td>The MQTT client identifier. Only set for MQTT sessions. If * present, the value of the <code>$ClientType</code> session property will be * <code>MQTT</code>.</td> * </tr> * <tr> * <td><code>$Principal</code></td> * <td>The security principal associated with the client session.</td> * </tr> * <tr> * <td><code>$Roles</code></td> * <td>Authorisation roles assigned to the session. This is a set of roles * represented as quoted strings (for example, `"role1","role2"`). The * utility method {@link stringToRoles} can be used to parse * the string value into a set of roles.</td> * </tr> * <tr> * <td><code>$ServerName</code></td> * <td>The name of the server to which the session is connected.</td> * </tr> * <tr> * <td><code>$SessionId</code></td> * <td>The session identifier. Equivalent to {@link Session.sessionId}.</td> * </tr> * <tr> * <td><code>$StartTime</code></td> * <td>The session's start time in milliseconds since the epoch.</td> * </tr> * <tr> * <td><code>$Transport</code></td> * <td>The session transport type. One of <code>WEBSOCKET</code>, * <code>HTTP_LONG_POLL</code>, <code>TCP</code>, or <code>OTHER</code>.</td> * </tr> * </table> * * All user-defined property keys are non-empty strings and are case-sensitve. * The characters ' ', '\t', '\r', '\n', '"', ''', '(', ')' are not allowed. * * Session properties are initially associated with a session as follows:<br> * * 1. When a client starts a new session or {@link Security.reauthenticate * re-authenticates}, it can optionally propose * user-defined session properties (see {@link Options}.properties). * Session properties proposed in this way must be accepted by the * authenticator. This safeguard prevents abuse by a rogue, unprivileged client. * 2. The server allocates all fixed property values. * 3. The new session is authenticated by registered authenticators. An * authenticator that accepts a session can veto or change the user-defined * session properties and add new user-defined session properties. The * authenticator can also change certain fixed properties, such as the * expiry time (`EXPIRY_TIME`). * * Once a session is established, its user-defined session properties can be * modified by clients with `VIEW_SESSION` and `MODIFY_SESSION` * permissions using {@link ClientControl.setSessionProperties}. * A privileged client can also modify its own session properties. * * If a session re-authenticates (see {@link Security.reauthenticate * reauthenticate}), the authenticator that allows the re-authentication can * modify the user-defined session properties and a subset of the fixed * properties as mentioned above. * * <H3>Session filters</H3> * * Session filters are a mechanism of addressing a set of sessions by the values * of their session properties. * * Session filters are specified using a Domain Specific Language (DSL). For a full and * detailed description of the session filters DSL see the * <a href="https://docs.diffusiondata.com/docs/latest/manual/html/developerguide/client/basics/uci_session_filtering.html"> * user manual</a>. * * <h2>Events</h2> * * <h3 id="event-disconnect"><code>disconnect</code></h3> * * Emitted when a connected session has lost connection to the server, and * {@link Options} `reconnect` is enabled. The provided reason will * contain the specific cause of the session disconnect. * * **Parameters:** * * `reason`: {@link CloseReason} - the cause of the session disconnect * * <h3 id="event-reconnect"><code>reconnect</code></h3> * * Emitted when a disconnected session has successfully reconnected. * * <h3 id="event-close"><code>close</code></h3> * * Emitted when a session is closed. This can occur because it was closed by the * user, closed by the server, failed to connect, or the session encountered an * error. The provided close reason will contain the specific cause of the * session close. * * **Parameters:** * * `reason`: {@link CloseReason} - the cause of the session close * * <h3 id="event-error"><code>error</code></h3> * * Emitted when a session error has occurred. A session error occurs when the * client cannot parse communication from the server. This occurs if a component * between the two - for example, a proxy or load balancer - alters the * communication. * * **Parameters:** * * `error`: any - the error that occurred */ export interface Session extends Stream, Topics, Ping { /** * The unique id assigned to this session by the server. */ readonly sessionId: SessionId; /** * The connection options used to establish this session */ readonly options: Options; /** * Exposes remote servers capabilities via {@link Session.remoteServers} */ readonly remoteServers: RemoteServers; /** * Exposes system authentication capabilities via a {@link Session.security} */ readonly security: Security; /** * Exposes session trees capabilities via {@link Session.sessionTrees} */ readonly sessionTrees: SessionTrees; /** * Exposes topic control capabilities via {@link Session.topics} */ readonly topics: TopicControl; /** * Exposes topic update capabilities via {@link Session.topicUpdate} */ readonly topicUpdate: TopicUpdate; /** * Exposes topic views capabilities via {@link Session.topicViews} */ readonly topicViews: TopicViews; /** * Exposes time series capabilities via {@link Session.timeseries} */ readonly timeseries: TimeSeries; /** * Exposes messaging capabilities via {@link Session.messages} */ readonly messages: Messages; /** * Exposes topic notification capabilities via {@link Session.notifications} */ readonly notifications: TopicNotifications; /** * Exposes client control capabilities via {@link ClientControl} */ readonly clients: ClientControl; /** * Exposes metric collector management capabilities via {@link Metrics} */ readonly metrics: Metrics; /** * Close this session's connection to the server. * * Calling this repeatedly will have no effect. * * @return this session */ close(): Session; /** * Close this session's connection to the server and return a {@link Promise} * that will completes when the session is closed. * * @return a {@link Promise} that completes with the close reason returned * by the server. Only the {@link Promise} of the first call to * `closeSession` is guaranteed to complete. The {@link Promise} * will not resolve if the session is already closed. */ closeSession(): Promise<CloseReason>; /** * Indicates if this session is currently closed, or in the process of * closing. * * This will not return `true` if the session is disconnected * but attempting to reconnect. * * @return whether the session is currently closed. */ isClosed(): boolean; /** * Indicates if this session is currently connected. * * This is orthogonal to {@link Session.isClosed}, as a session may * be disconnected and attempting to reconnect. * * @return whether the session is currently connected or not. */ isConnected(): boolean; /** * Returns the principal name that this session is associated with. * * @return the principal for this session */ getPrincipal(): string; /** * Returns the values of the session's fixed session properties. * * All current fixed property values are returned, except the value of the * `ROLES` property. User-defined session properties are not returned. * * @return a Promise that resolves when a response is received * from the server. * <p> * If the Promise completes normally, the current * session properties will be returned (excluding the value of the * `ROLES` property). * <p> * Otherwise, the Promise will be rejected. Common reasons for failure include: * * <ul> * <li>the session is closed. * </ul> * @since 6.12 */ getSessionProperties(): Promise<SessionProperties>; /** * Attempt to acquire a {@link SessionLock session lock}. * * This method returns a Promise that will resolve normally if * the server assigns the requested lock to the session. Otherwise, the * Promise will fail with an error indicating why the lock could not * be acquired. * * @param lockName the name of the session lock * @param scope preferred scope, defaults to * `UNLOCK_ON_SESSION_LOSS` . The scope of a lock controls * when it will be released automatically. If a session * makes multiple requests for a lock using different * scopes, and the server assigns the lock to the session * fulfilling the requests, the lock will be given the * weakest scope (`UNLOCK_ON_SESSION_LOSS` ). * @return a Promise that resolves when a response is received * from the server. * <p> * If this session has successfully acquired the session * lock, or this session already owns the session lock, the * Promise will resolve normally with a SessionLock result. * <p> * If the Promise resolves with an error, this session does * not own the session lock. * * @since 6.2 */ lock(lockName: string, scope?: SessionLockScope): Promise<SessionLock>; /** * Updates the session with missing features that may have been loaded * asynchronously. This method only has an effect when running the client * as a modular client in the browser. */ updateFeatures(): void; } /** * @module diffusion.clients */ /** * A type containing information about the reason for a session being closed * * Documentation of the CloseReason values can be found under {@link CloseReasonEnum}. */ export interface CloseReason { /** * The close reason's id * * @deprecated since 6.8 * <p> * This member is deprecated and will be removed in the future. */ id: number; /** * The close reason's description * * @deprecated since 6.8 * <p> * This member is deprecated and will be removed in the future. */ message: string; } /** * Enum representing the reason that the session has been closed. * * **Example:** * ``` * diffusion.connect({...}).then(function(session) {...}, function(err) { * switch(err) { * case diffusion.clients.CloseReason.CLOSED_BY_CLIENT: * // Do something * case diffusion.clients.CloseReason.ACCESS_DENIED: * // Do something else * ... * } * }); * ``` * */ export declare const CloseReasonEnum: { [key: string]: CloseReason; }; /** * The server's view of why a client session was closed. */ export declare enum ClientCloseReason { /** * The connection to the client was lost - possibly dropped by the client. * Recoverable. * * A client may be closed for may reasons that are presented as * CONNECTION_LOST. * * During connection the connection can be lost. The server might have * received a connection or reconnection request from a client already * connected. The server might have received a reconnection request without * a client ID. The connection may not have been authorised because the * credentials are wrong. The maximum number of clients might already be * connected. * * Once connected the connection can be lost for different reasons. If the * client closes its connection while the server is writing a message to the * client. With the chunked encoding based connection the HTTP response is * completed by the server. If the client does not open a new request within * a timeout the client will be closed. If a poll request times out and the * server finds that the connection has already been closed by the client. */ CONNECTION_LOST = 0, /** * An unexpected IO Exception occurred. Recoverable. * * While trying to perform an I/O operation an exception was generated. This * often means that Diffusion attempted to read from a closed TCP * connection. * * When Diffusion is handling SSL connections if there is a problem * encrypting or decrypting a message the client will be closed for this * reason. */ IO_EXCEPTION = 1, /** * The client had become unresponsive. Recoverable. * * The client has either failed to respond to a ping message in a timely * manner or the client has failed to open an HTTP poll for messages. The * client does not appear to be receiving messages. */ CLIENT_UNRESPONSIVE = 2, /** * The maximum outbound queue size was reached for the client. Not * recoverable. * * Messages sent to the client are placed in a queue. This queue has a * maximum allowed size. If the queue limit is reached the client is closed * and the queue discarded. The queue is intended to protect against slow * patches, reaching the queue limit is taken to mean that the client cannot * keep up with the number of messages sent to it. */ MESSAGE_QUEUE_LIMIT_REACHED = 3, /** * The client requested close. Not recoverable (unless TEST_RECONNECT is * true). */ CLOSED_BY_CLIENT = 4, /** * The client sent a message that exceeded the maximum message size. * * The server has a maximum message size. If a client sends a message larger * than this the server is unable to process it. When this happens the * message is discarded and the client is closed. */ MESSAGE_TOO_LARGE = 5, /** * An internal error occurred. */ INTERNAL_ERROR = 6, /** * An inbound message with an invalid format was received. * * A message received by the server is not a valid Diffusion message. The * server is unable to process this and closes the client that sent it. */ INVALID_INBOUND_MESSAGE = 7, /** * The client connection was aborted by the server, possibly because the * connection was disallowed. * * This may be because the connection was disallowed. Abort messages are * also sent to clients that have unrecognised client IDs. This may be * because the server closed the client previously but the client is unaware * of this and tried to continue interacting with the server. */ ABORTED = 8, /** * Loss of messages from the client has been detected. For example, whilst * waiting for the arrival of missing messages in a sequence of messages a * timeout has occurred. * * HTTP based transports use multiple TCP connections. This can cause the * messages to be received out of order. To reorder the messages those sent * to the server may contain a sequence number indicating the correct order. * * If a message is received out of order there is a short time for the * earlier messages to be received. If the messages are not received in this * time the client is closed. * * Missing, invalid or duplicate sequence numbers will also close the client * for this reason. * * This cannot be recovered from as the client and the server are in * inconsistent states. */ LOST_MESSAGES = 9, /** * A control session initiated the client close. */ CLOSED_BY_CONTROLLER = 11, /** * The client has failed over to a different server. * <P> * The session is still open but is now connected to a different Diffusion * server. This server has evicted its view of the client from its set of * local clients. */ FAILED_OVER = 12, /** * The session had an {@link EXPIRY_TIME} specified which * expired before the session {@link Security.reauthenticate * re-authenticated}. * * @since 6.12 */ EXPIRED = 13, /** * The session's authentication was revoked by a privileged user. * * @since 6.12 */ REVOKED = 14, /** * The session has been closed to make way for a new session. * * This is used by MQTT. See MQTT-3.1.4-3. * * @since 6.12 */ SESSION_TAKEN_OVER = 15 } /** * @module diffusion.datatypes */ /// <reference types="node" /> /** * Read-only interface for values that are internally represented as binary * data. * * This interface provides access to copies of the binary data, making instances * effectively immutable. Methods of derived interfaces and classes that relax * this restriction and expose access to the internal data should be clearly * documented. * * @since 5.7 */ export interface Bytes { /** * Get the number of bytes * * @return The length of the data in bytes */ length(): number; /** * Get a copy of the buffer containing this value. * * @return This value in binary form * * @deprecated since version 6.11. Buffer has been replaced by Uint8Array. This * will be removed in a future release. */ asBuffer(): Buffer; /** * Get a copy of the array containing this value. * * @return This value in binary form */ asArray(): Uint8Array; /** * Copy the binary data to a provided buffer. * * @param target the buffer to copy data to * @param offset the position in the target buffer at which data will be copied */ copyTo(target: Uint8Array, offset?: number): void; } /** * @module diffusion.datatypes */ /// <reference types="node" /> /** * A data type is specified for a particular value type. It provides methods to * convert values to and from binary. Diffusion provides several {@link DataType} * implementations. * * A data type can optionally support incremental changes to values, represented * by one or more types of <em>delta</em>. A delta is the difference between two * values. For large or composite values that change in small steps, it is more * efficient to transmit an initial value followed by a delta for each change * than to transmit a complete value for each change. The data type provides an * implementation of {@link DeltaType} for each type of delta it * supports via {@link DataType.deltaType}. * * @since 5.7 * * @param <ValueType> the value type of the data type * @param <SourceType> the type(s) from which a value can be constructed * @param <CBORType> the binary type containing the CBOR data */ export interface DataType<ValueType, SourceType, CBORType> { /** * The external type identifier. * * @return the name of th