UNPKG

@dasf/dasf-messaging

Version:

Typescript bindings for the DASF RPC messaging protocol.

460 lines (441 loc) 16.1 kB
import { JsonConvert } from 'json2typescript'; import { JSONSchema7 } from 'json-schema'; /** A class in the API suitable for RPC via DASF */ export declare class ClassApiInfo { /** The name of the class that is used as identifier in the RPC. */ name: string; /** The JSON Schema for the constructor of the class. */ rpcSchema: JSONSchema7; /** The list of methods that this class provides. */ methods: FunctionApiInfo[]; } /** * Connection to a DASF Backend module via websocket * * To create a connection to a remove message broker, provide an instance of * :class:`DASFUrlBuilder` * * **Example** * * ``` * import { DASFConnection, WebsocketUrlBuilder } from '@dasf/dasf-messaging' * const connection = new DASFConnection( * new WebsocketUrlBuilder( * 'ws://localhost:8080/ws', * 'some-topic' * ) * ) * * // send request via the connection and log the response * connection.sendRequest({func_name: 'version_info'}).then( * (response) => console.log(response) * ) * ``` */ export declare class DASFConnection { private outgoingChannel; private incomingChannel; private DASFProducerURL; private DASFConsumerURL; private consumeTopic; jsonCoder: JsonConvert; private contextCounter; private responseResolvers; private progressCallbacks; private responseRejectHandler; private finishedContexts; private contextResponseFragments; private pendingRequests; private waitingForPong; private connectionTimeout; private connectionError; private onConnectionError?; private startedReconnectOutgoing; private startedReconnectIncoming; /** * @param urlBuilder - A builder for the consumer and producer websocket url * @param onConnectionError - A callback for the case when no connection could be established */ constructor(urlBuilder: DASFUrlBuilder, onConnectionError?: (errorMsg: string) => void); private connect; private isConnected; private isConnecting; /** * Do something as soon as the websocket connection has been established * * This property returns a promise that resolves with the established * connection. You can use this to do something right after the connection has * been created. * * ``` * import { DASFConnection, WebsocketUrlBuilder } from '@dasf/dasf-messaging' * const connection = new DASFConnection( * new WebsocketUrlBuilder( * 'ws://localhost:8080/ws', * 'some-topic' * ) * ) * * // log to the console when the connection has been connected * connection.connected.then( * (connection: DASFConnection) => console.log("Websocket connection has been established.") * ).catch( * (error: Error) => console.log(error) * ) * ``` * * */ get connected(): Promise<DASFConnection>; private assureConnected; hasPendingRequests(): boolean; private sendPendingRequests; protected registerListener(): void; private checkConnection; /** Send a request to the backend module and retrieve the response * * This high-level implementation of :meth:`sendMessage` takes an object and * sends it as a :class:`DASFModuleRequest` of type * :attr:`MessageType.Request` to the backend module (as soon as * the websocket connection has been established). The result * is a promise that resolves to the response of the backend module. * * **Example** * * ``` * import { DASFConnection, WebsocketUrlBuilder } from '@dasf/dasf-messaging' * const connection = new DASFConnection( * new WebsocketUrlBuilder( * 'ws://localhost:8080/ws', * 'some-topic' * ) * ) * * // send request via the connection and log the response * connection.sendRequest({func_name: 'version_info'}).then( * (response) => console.log(response) * ) * ``` * * @param data - The object that is sent as payload of the request to the * backend module * @param onProgress - A callback to use when we receive progress reports * while processing the request in the backend module. * * @returns The promise resolving to the deserialized response of the backend * module */ sendRequest(data: object, onProgress?: (value: { message: DASFProgressReport; props?: object; }) => void): Promise<unknown>; /** Send a generic message to the backend module * * This low-level implementation takes a generic :class:`DASFModuleRequest` * and sends it to the backend module (as soon as the websocket connection * has been established). The result is a promise that resolves to the * response of the backend module. * * @param requestMessage - The message you want to send * @param onProgress - A callback to use when we receive progress reports * while processing the request in the backend module. * * @returns The promise resolving to the response of the backend module */ sendMessage(requestMessage: DASFModuleRequest, onProgress?: (value: { message: DASFProgressReport; props?: object; }) => void): Promise<DASFModuleResponse>; private acknowledgeMessage; /** Close all connections * * This method closes the connections to the outgoing and incoming websocket. * * **Example** * * ``` * import { DASFConnection, WebsocketUrlBuilder } from '@dasf/dasf-messaging' * const connection = new DASFConnection( * new WebsocketUrlBuilder( * 'ws://localhost:8080/ws', * 'some-topic' * ) * ) * * // send request via the connection and log the response * connection.sendRequest({func_name: 'version_info'}).then( * (response) => { * console.log(response) * // close the connection upon receival * connection.close() * } * ) * * ``` */ close(): void; /** Get information on requests for this module * * This method retrieves the JSONSchema representation for requests to this * module. It is one large schema object that can be used to validate a * request for the :func:`sendRequest` method. * * @returns A promise that resolves to the JSONSchema for a request to this topic */ getModuleInfo(): Promise<JSONSchema7>; /** Get api information for this backend module * * This method retrieves the api info, namely the individual JSONSchema * representations for the functions and classes in the backend module. * Different from :func:`getModuleInfo`, this method does not only provide a * single JSONSchema, but rather one JSONSchema for each method/function in * the backend module. * * @returns an object representing the api of the backend module. */ getApiInfo(): Promise<ModuleApiInfo>; private sendInfoRequest; private hasConnectionError; } /** A request to a DASF backend module * * This class can be used to create a request that is sent via the message * broker to a DASF backend module. */ export declare class DASFModuleRequest { /** The request data. * * usually encoded as byte64 string. */ payload: string; /** An identifier for the request to handle identify the response handler */ context: string; /** Properties of the request * * the properties of the request may be derived from the * :ref:`PropertyKeys` enum. */ properties?: DASFRequestProperties; private static createMessage; /** Shortcut to create a request message * * This static method creates a :class:`DASFModuleRequest` with the * :ref:`MessageType` `MessageType.Request` * * @param data - Optional data as javascript object that will be * json-serialized and added as :attr:`payload` to the request. * * @returns The :class:`DASFModuleRequest` of type `MessageType.Request` */ static createRequestMessage(data?: object): DASFModuleRequest; /** Shortcut to create a Ping message * * This static method creates a :class:`DASFModuleRequest` with the * :ref:`MessageType` `MessageType.Ping` * * @returns The :class:`DASFModuleRequest` of type `MessageType.Ping` */ static createPingMessage(): DASFModuleRequest; /** Shortcut to create a Pong message * * This static method creates a :class:`DASFModuleRequest` with the * :ref:`MessageType` `MessageType.Pong` * * @returns The :class:`DASFModuleRequest` of type `MessageType.Pong` */ static createPongMessage(): DASFModuleRequest; /** Shortcut to create an Info message * * This static method creates a :class:`DASFModuleRequest` with the * :ref:`MessageType` `MessageType.Info` to get the information on the * backend module, see also :meth:`DASFConnection.getModuleInfo` * * @returns The :class:`DASFModuleRequest` of type `MessageType.Info` */ static createInfoMessage(): DASFModuleRequest; /** Shortcut to create an Info message * * This static method creates a :class:`DASFModuleRequest` with the * :ref:`MessageType` `MessageType.Info` to get the information on the * backend module, see also :meth:`DASFConnection.getApiInfo` * * @returns The :class:`DASFModuleRequest` of type `MessageType.ApiInfo` */ static createApiInfoMessage(): DASFModuleRequest; /** Shortcut to the the messagetype of the properties */ getMessageType(): MessageType; } /** A response of a backend module. */ export declare class DASFModuleResponse { /** The id of the message assigned by the message broker */ messageId: string; /** The response data. * * usually encoded as byte64 string. */ payload: string; /** The time when this message has been published to the message broker. */ publishTime: string; /** Properties of the response * * the properties of the response may be derived from the * :ref:`PropertyKeys` enum. */ properties?: DASFResponseProperties; /** Shortcut to the the messagetype of the properties */ getMessageType(): MessageType; /** Shortcut to the the request context of the properties */ getRequestContext(): string; /** Get the original id of the request */ getRequestMessageId(): string; /** Check if the response is fragmented or not. */ isFragmented(): boolean; /** Get the id of this fragment. */ getFragmentId(): number; /** Get the total number of fragments */ getNumberOfFragments(): number; } /** A tree-like structured progress report. * * This class can be used to handle a progress report from the backend module. * It is submitted to the `onProgress` callback of the * :meth:`DASFConnection.sendRequest` when a response arrives with the * :ref:`message type <MessageType>` ``MessageType.Progress`` */ export declare class DASFProgressReport { report_type: string; /** ID for the report. */ report_id: string; /** The description of the process. */ step_message: string; /** The number of subprocesses in this report. */ steps: number; /** Status of the underlying process. */ status: Status; /** Child reports within the tree */ children?: DASFProgressReport[]; hasError(): boolean; hasSuccess(): boolean; isRunning(): boolean; isComplete(): boolean; } export declare type DASFRequestProperties = DASFRequestPropertiesBase & { response_topic?: string; }; declare type DASFRequestPropertiesBase = { messageType: MessageType; requestContext?: string; }; export declare type DASFResponseProperties = DASFRequestPropertiesBase & { requestMessageId?: string; source_topic?: string; fragment?: number; num_fragments?: number; status?: Status; info?: string; api_info?: string; }; /** * Interface providing DASF connection urls and parameters */ export declare interface DASFUrlBuilder { /** * Which topic is used? */ topic: string; /** * The topic on that the consumer listens. * Needed to get the results for the backend module. */ consumeTopic: string; /** * A url that allows to create a consumer with the DASF * web socket api. */ DASFConsumerURL: string; /** See DASFConsumerURL for an explanation. */ DASFProducerURL: string; } /** A function in the API suitable for RPC via DASF */ export declare class FunctionApiInfo { /** The name of the function that is used as identifier in the RPC. */ name: string; /** The JSON Schema for the function. */ rpcSchema: JSONSchema7; /** The JSON Schema for the return value. */ returnSchema: JSONSchema7; } /** Message types for a :class:`DASFModuleRequest` */ export declare enum MessageType { Ping = "ping", Pong = "pong", Info = "info", ApiInfo = "api_info", Request = "request", Response = "response", Log = "log", Progress = "progress" } /** An model that represants the API of a backend module. */ export declare class ModuleApiInfo { /** The RPC-enabled classes that this module contains. */ classes: ClassApiInfo[]; /** The RPC-enabled functions that this module contains. */ functions: FunctionApiInfo[]; /** The aggregated JSON schema for an RPC call to this module. */ rpcSchema: JSONSchema7; } /** Valid keys for the request properties * * see :attr:`DASFModuleRequest.properties` */ export declare enum PropertyKeys { ResponseTopic = "response_topic", RequestContext = "requestContext", RequestMessageId = "requestMessageId", MessageType = "messageType", SourceTopic = "source_topic", Fragment = "fragment", NumFragments = "num_fragments", Status = "status" } /** * Default url builder for apache pulsar implementation based on host:port, namespace and topic */ export declare class PulsarUrlBuilder implements DASFUrlBuilder { private static readonly BASE_DASF_URL; readonly topic: string; readonly consumeTopic: string; readonly DASFConsumerURL: string; readonly DASFProducerURL: string; constructor(host: string, port: string, namespace: string, topic: string, protocol?: string); protected buildUrl(host: string, port: string, namespace: string, type: Type, topic: string, protocol: string): string; protected generateConsumeTopic(topic: string): string; protected generateSubscriptionPrefix(): string; protected generateRequestToken(): string; } /** Status flag of a request :class:`DASFModuleRequest` */ export declare enum Status { Success = "success", Error = "error", Running = "running" } declare enum Type { producer = "producer", consumer = "consumer" } /** * Url builder for predefined websocket url */ export declare class WebsocketUrlBuilder implements DASFUrlBuilder { readonly topic: string; readonly consumeTopic: string; readonly DASFConsumerURL: string; readonly DASFProducerURL: string; constructor(websocketUrl: string, topic: string, producerUrl?: string, consumerUrl?: string); protected buildUrl(websocketUrl: string, topic: string): string; protected generateConsumeTopic(topic: string): string; protected generateSubscriptionPrefix(): string; protected generateRequestToken(): string; } export { }