UNPKG

diffusion

Version:

Diffusion JavaScript client

1,370 lines 539 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 * Result} 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 Result} 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): Result<Session>; /** * Connect to a specified Diffusion server using a shared WebWorker session. * This will return a {@link Result} 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 Result} for this operation * @throws an {@link IllegalArgumentError} if the options are invalid. */ export declare function connectShared(sessionName: string, workerJs: string): Result<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 or a time out, or 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 assigned by the application. * * Many operations use session filter expressions (see section Session Filters) * that use session properties to select sessions. * * 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>$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>$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> * <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, 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. * * 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.changePrincipal * changePrincipal}), 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 Result} * that will completes when the session is closed. * * @return a {@link Result} that completes with the close reason returned * by the server. Only the {@link Result} of the first call to * `closeSession` is guaranteed to complete. The {@link Result} * will not resolve if the session is already closed. */ closeSession(): Result<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; /** * 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): Result<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.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 this datatype */ name(): string; /** * Parse a value from binary. * * @param input the binary data * @param offset the offset to start reading from the provided buffer (default = `0`) * @param length the length of the data to read (default = `input.length`) * @returns an instance of this data type value * @throws an {@link InvalidDataError} error if the data is invalid for this type */ readValue(input: Uint8Array, offset?: number, length?: number): ValueType | null; readValue(input: CBORType): ValueType | null; /** * Serialise a value to binary * * @param value the value to serialise. For primitive and JSON datatypes * the value can be `undefined` or `null`. In this case a * `null` value will be serialised. * @returns the serialised value as a buffer * @throws an {@link IllegalArgumentError} if the value cannot be serialised * * @deprecated since version 6.11. Buffer has been replaced by Uint8Array. * Use <code>writeValueToArray</code> instead. This will be removed * in a future release. */ writeValue(value: SourceType | undefined | null): Buffer; /** * Serialise a value to binary * * @param value the value to serialise. For primitive and JSON datatypes * the value can be `undefined` or `null`. In this case a * `null` value will be serialised. * @returns the serialised value as a buffer * @throws an {@link IllegalArgumentError} if the value cannot be serialised */ writeValueToArray(value: SourceType | undefined | null): Uint8Array; /** * Test whether this data type is compatible with `valueType`. Compatibility * with a `valueType` means than any valid binary representation of a * `value` can be {@link DataType.readAs read as} an * instance of `valueType`. * * Every data type should be compatible with the following: * * * `Value Type` &ndash; the class corresponding to the data type's value * type. * * For a data type with a value type of `X`, `readAs(X, buffer)` is * equivalent to `readValue(buffer)`. * * @param valueType the type to check * @return `true` if a binary representation created by this data * type can read as an instance * of `valueType` * @since 6.0 */ canReadAs(valueType: new (...args: any[]) => any): boolean; /** * Create a value of a compatible class from binary. * * @param valueType the type of the result * @param buffer the binary data * @param offset the offset to start reading from the provided buffer (default = `0`) * @param length the length of the data to read (default = `input.length`) * @return the value in the form of the specified type * @throws an {@link InvalidDataError} if `valueType` is incompatible with this data * type, or `buffer` does not represent a valid value. * @since 6.0 */ readAs<T>(valueType: new (...args: any[]) => T, buffer: Uint8Array, offset?: number, length?: number): T | null; readAs<T>(valueType: new (...args: any[]) => T, buffer: CBORType): T | null; /** * Obtain a {@link DeltaType} by name or delta type. * * **Example:** * ``` * // Get by name * var deltas = datatype.deltaType("binary"); * ``` * * **Example:** * ``` * // Get by type * var deltas = datatype.deltaType(delta); * ``` * * @param name the name, as returned by {@link DeltaType.name} * @returns the delta type */ deltaType(name?: string): DeltaType<ValueType, SourceType, CBORType>; } /** * A placeholder data type that can represent any of the other datatypes. * * The sole purpose of this data type is to allow creating polymorphic streams * that can accept any data type. * * **Example:** * ``` * // Get the Any datatype and create a stream * var anyType = diffusion.datatypes.any(); * var stream = session.addStream('some_topic', anyType); * ``` */ export interface AnyDataType { /** * The external type identifier. * * @return the name of this datatype */ name(): string; } /** * @module diffusion.datatypes */ /** * Diffusion datatype implementations. * * Datatypes are accessed via the `diffusion` singleton. * * **Example:** * ``` * // Get the JSON datatype * var json = diffusion.datatypes.json(); * ``` * * **Example:** * ``` * // Get a datatype via name * var json = diffusion.datatypes.get('json'); * ``` * @namespace diffusion.datatypes * @since 5.7 */ export interface DataTypes { /** * Get the binary data type * * @return the Binary data type */ binary(): BinaryDataType; /** * Get the JSON data type * * @return the JSON data type */ json(): JSONDataType; /** * Get the Int64 data type * * @return the Int64 data type */ int64(): Int64DataType; /** * Get the string data type * * @return the String data type */ string(): StringDataType; /** * Get the double data type * * @return the Double data type */ double(): DoubleDataType; /** * Get the record V2 data type * * @return the RecordV2 data type */ recordv2(): RecordV2DataType; /** * Get the Any data type * * @return the Any data type */ any(): AnyDataType; /** * Get the timeseries data type * * @param valueType the value type of the timeseries data type * @return a timeseries data type */ timeseries<ValueType, SourceType>(valueType: DataType<ValueType, SourceType, any>): DataType<Event<ValueType>, Event<SourceType>, Bytes>; /** * Obtain a {@link DataType} implementation by type * name, topic type, or value class * * @param name the type name as returned by {@link DataType.name}, the value * or a topic type. * @return the data type or `null` if no datatype was found */ get(name: any): DataType<any, any, any> | null; /** * Obtain a {@link DataType} implementation by value class. * * For {@link DoubleDataType}, the associated value class is `Number`. * * @param valueClass the class * @return the data type * @throws an {@link IllegalArgumentError} if there is no data type for provided class */ getByClass(valueClass: new (...args: any[]) => any): DataType<any, any, any>; } /** * @module diffusion.datatypes */ /// <reference types="node" /> /** * Optional extension provided by {@link DataType} implementations that support * incremental changes to values. * * A data type can optionally support incremental changes to values, represented * by one or more types of delta. 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. * * Each implementation specifies a `value` type and a `delta` type. * Two values, oldValue and new Value, can be compared to produce a delta using * {@link DeltaType.diff}. The delta can be separately applied to oldValue to * create newValue using {@link DeltaType.apply}. * * <h5>Deferred parsing</h5> * Implementations can choose not to fully validate values when they are read, * but instead defer parsing until it is required. Consequently, all methods * that accept values may throw an error. * * @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 * * @since 5.7 */ export interface DeltaType<Val