All Downloads are FREE. Search and download functionalities are using the official Maven repository.

tech.figure.eventstream.stream.apis.WebsocketApi.kt Maven / Gradle / Ivy

/**
 * Tendermint RPC
 *
 * Tendermint supports the following RPC protocols:  * URI over HTTP * JSONRPC over HTTP * JSONRPC over websockets  ## Configuration  RPC can be configured by tuning parameters under `[rpc]` table in the `$TMHOME/config/config.toml` file or by using the `--rpc.X` command-line flags.  Default rpc listen address is `tcp://0.0.0.0:26657`. To set another address, set the `laddr` config parameter to desired value. CORS (Cross-Origin Resource Sharing) can be enabled by setting `cors_allowed_origins`, `cors_allowed_methods`, `cors_allowed_headers` config parameters.  ## Arguments  Arguments which expect strings or byte arrays may be passed as quoted strings, like `\"abc\"` or as `0x`-prefixed strings, like `0x616263`.  ## URI/HTTP  A REST like interface.      curl localhost:26657/block?height=5  ## JSONRPC/HTTP  JSONRPC requests can be POST'd to the root RPC endpoint via HTTP.      curl --header \"Content-Type: application/json\" --request POST --data '{\"method\": \"block\", \"params\": [\"5\"], \"id\": 1}' localhost:26657  ## JSONRPC/websockets  JSONRPC requests can be also made via websocket. The websocket endpoint is at `/websocket`, e.g. `localhost:26657/websocket`. Asynchronous RPC functions like event `subscribe` and `unsubscribe` are only available via websockets.  Example using https://github.com/hashrocket/ws:      ws ws://localhost:26657/websocket     > { \"jsonrpc\": \"2.0\", \"method\": \"subscribe\", \"params\": [\"tm.event='NewBlock'\"], \"id\": 1 } 
 *
 * The version of the OpenAPI document: Master
 * 
 *
 * Please note:
 * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * Do not edit this file manually.
 */

@file:Suppress(
    "ArrayInDataClass",
    "EnumEntryName",
    "RemoveRedundantQualifierName",
    "UnusedImport"
)

package tech.figure.eventstream.stream.apis

import tech.figure.eventstream.stream.models.EmptyResponse
import tech.figure.eventstream.stream.models.ErrorResponse

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import tech.figure.eventstream.stream.infrastructure.ApiClient
import tech.figure.eventstream.stream.infrastructure.ClientException
import tech.figure.eventstream.stream.infrastructure.ClientError
import tech.figure.eventstream.stream.infrastructure.ServerException
import tech.figure.eventstream.stream.infrastructure.ServerError
import tech.figure.eventstream.stream.infrastructure.MultiValueMap
import tech.figure.eventstream.stream.infrastructure.RequestConfig
import tech.figure.eventstream.stream.infrastructure.RequestMethod
import tech.figure.eventstream.stream.infrastructure.ResponseType
import tech.figure.eventstream.stream.infrastructure.Success
import tech.figure.eventstream.stream.infrastructure.toMultiValue

class WebsocketApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
    companion object {
        @JvmStatic
        val defaultBasePath: String by lazy {
            System.getProperties().getProperty("tech.figure.eventstream.stream.baseUrl", "https://rpc.cosmos.network")
        }
    }

    /**
    * Subscribe for events via WebSocket.
    * To tell which events you want, you need to provide a query. query is a string, which has a form: \"condition AND condition ...\" (no OR at the moment). condition has a form: \"key operation operand\". key is a string with a restricted set of possible symbols ( \\t\\n\\r\\\\()\"'=>< are not allowed). operation can be \"=\", \"<\", \"<=\", \">\", \">=\", \"CONTAINS\" AND \"EXISTS\". operand can be a string (escaped with single quotes), number, date or time.  Examples:       tm.event = 'NewBlock'               # new blocks       tm.event = 'CompleteProposal'       # node got a complete proposal       tm.event = 'Tx' AND tx.hash = 'XYZ' # single transaction       tm.event = 'Tx' AND tx.height = 5   # all txs of the fifth block       tx.height = 5                       # all txs of the fifth block  Tendermint provides a few predefined keys: tm.event, tx.hash and tx.height. Note for transactions, you can define additional keys by providing events with DeliverTx response.  import (     abci \"github.com/tendermint/tendermint/abci/types\"     \"github.com/tendermint/tendermint/libs/pubsub/query\" )  abci.ResponseDeliverTx{   Events: []abci.Event{       {           Type: \"rewards.withdraw\",           Attributes: abci.EventAttribute{               {Key: []byte(\"address\"), Value: []byte(\"AddrA\"), Index: true},               {Key: []byte(\"source\"), Value: []byte(\"SrcX\"), Index: true},               {Key: []byte(\"amount\"), Value: []byte(\"...\"), Index: true},               {Key: []byte(\"balance\"), Value: []byte(\"...\"), Index: true},           },       },       {           Type: \"rewards.withdraw\",           Attributes: abci.EventAttribute{               {Key: []byte(\"address\"), Value: []byte(\"AddrB\"), Index: true},               {Key: []byte(\"source\"), Value: []byte(\"SrcY\"), Index: true},               {Key: []byte(\"amount\"), Value: []byte(\"...\"), Index: true},               {Key: []byte(\"balance\"), Value: []byte(\"...\"), Index: true},           },       },       {           Type: \"transfer\",           Attributes: abci.EventAttribute{               {Key: []byte(\"sender\"), Value: []byte(\"AddrC\"), Index: true},               {Key: []byte(\"recipient\"), Value: []byte(\"AddrD\"), Index: true},               {Key: []byte(\"amount\"), Value: []byte(\"...\"), Index: true},           },       },   }, }  All events are indexed by a composite key of the form {eventType}.{evenAttrKey}. In the above examples, the following keys would be indexed:    - rewards.withdraw.address    - rewards.withdraw.source    - rewards.withdraw.amount    - rewards.withdraw.balance    - transfer.sender    - transfer.recipient    - transfer.amount  Multiple event types with duplicate keys are allowed and are meant to categorize unique and distinct events. In the above example, all events indexed under the key `rewards.withdraw.address` will have the following values stored and queryable:     - AddrA    - AddrB  To create a query for txs where address AddrA withdrew rewards: query.MustParse(\"tm.event = 'Tx' AND rewards.withdraw.address = 'AddrA'\")  To create a query for txs where address AddrA withdrew rewards from source Y: query.MustParse(\"tm.event = 'Tx' AND rewards.withdraw.address = 'AddrA' AND rewards.withdraw.source = 'Y'\")  To create a query for txs where AddrA transferred funds: query.MustParse(\"tm.event = 'Tx' AND transfer.sender = 'AddrA'\")  The following queries would return no results: query.MustParse(\"tm.event = 'Tx' AND transfer.sender = 'AddrZ'\") query.MustParse(\"tm.event = 'Tx' AND rewards.withdraw.address = 'AddrZ'\") query.MustParse(\"tm.event = 'Tx' AND rewards.withdraw.source = 'W'\")  See list of all possible events here https://godoc.org/github.com/tendermint/tendermint/types#pkg-constants  For complete query syntax, check out https://godoc.org/github.com/tendermint/tendermint/libs/pubsub/query.  ```go import rpchttp \"github.com/tendermint/rpc/client/http\" import \"github.com/tendermint/tendermint/types\"  client := rpchttp.New(\"tcp:0.0.0.0:26657\", \"/websocket\") err := client.Start() if err != nil {   handle error } defer client.Stop() ctx, cancel := context.WithTimeout(context.Background(), 1 * time.Second) defer cancel() query := \"tm.event = 'Tx' AND tx.height = 3\" txs, err := client.Subscribe(ctx, \"test-client\", query) if err != nil {   handle error }  go func() {  for e := range txs {    fmt.Println(\"got \", e.Data.(types.EventDataTx))    } }() ```  NOTE: if you're not reading events fast enough, Tendermint might terminate the subscription. 
    * @param query query is a string, which has a form: \"condition AND condition ...\" (no OR at the moment). condition has a form: \"key operation operand\". key is a string with a restricted set of possible symbols ( \\t\\n\\r\\\\()\"'=>< are not allowed). operation can be \"=\", \"<\", \"<=\", \">\", \">=\", \"CONTAINS\". operand can be a string (escaped with single quotes), number, date or time.  
    * @return EmptyResponse
    * @throws UnsupportedOperationException If the API returns an informational or redirection response
    * @throws ClientException If the API returns a client error response
    * @throws ServerException If the API returns a server error response
    */
    @Suppress("UNCHECKED_CAST")
    @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
    suspend fun subscribe(query: kotlin.String) : EmptyResponse = withContext(Dispatchers.IO) {
        val localVariableConfig = subscribeRequestConfig(query = query)

        val localVarResponse = request(
            localVariableConfig
        )

        return@withContext when (localVarResponse.responseType) {
            ResponseType.Success -> (localVarResponse as Success<*>).data as EmptyResponse
            ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
            ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
            ResponseType.ClientError -> {
                val localVarError = localVarResponse as ClientError<*>
                throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
            }
            ResponseType.ServerError -> {
                val localVarError = localVarResponse as ServerError<*>
                throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
            }
        }
    }

    /**
    * To obtain the request config of the operation subscribe
    *
    * @param query query is a string, which has a form: \"condition AND condition ...\" (no OR at the moment). condition has a form: \"key operation operand\". key is a string with a restricted set of possible symbols ( \\t\\n\\r\\\\()\"'=>< are not allowed). operation can be \"=\", \"<\", \"<=\", \">\", \">=\", \"CONTAINS\". operand can be a string (escaped with single quotes), number, date or time.  
    * @return RequestConfig
    */
    fun subscribeRequestConfig(query: kotlin.String) : RequestConfig {
        val localVariableBody = null
        val localVariableQuery: MultiValueMap = mutableMapOf>()
            .apply {
                put("query", listOf(query.toString()))
            }
        val localVariableHeaders: MutableMap = mutableMapOf()

        return RequestConfig(
            method = RequestMethod.GET,
            path = "/subscribe",
            query = localVariableQuery,
            headers = localVariableHeaders,
            body = localVariableBody
        )
    }

    /**
    * Unsubscribe from event on Websocket
    * ```go client := rpchttp.New(\"tcp:0.0.0.0:26657\", \"/websocket\") err := client.Start() if err != nil {    handle error } defer client.Stop() query := \"tm.event = 'Tx' AND tx.height = 3\" err = client.Unsubscribe(context.Background(), \"test-client\", query) if err != nil {    handle error } ``` 
    * @param query query is a string, which has a form: \"condition AND condition ...\" (no OR at the moment). condition has a form: \"key operation operand\". key is a string with a restricted set of possible symbols ( \\t\\n\\r\\\\()\"'=>< are not allowed). operation can be \"=\", \"<\", \"<=\", \">\", \">=\", \"CONTAINS\". operand can be a string (escaped with single quotes), number, date or time.  
    * @return EmptyResponse
    * @throws UnsupportedOperationException If the API returns an informational or redirection response
    * @throws ClientException If the API returns a client error response
    * @throws ServerException If the API returns a server error response
    */
    @Suppress("UNCHECKED_CAST")
    @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
    suspend fun unsubscribe(query: kotlin.String) : EmptyResponse = withContext(Dispatchers.IO) {
        val localVariableConfig = unsubscribeRequestConfig(query = query)

        val localVarResponse = request(
            localVariableConfig
        )

        return@withContext when (localVarResponse.responseType) {
            ResponseType.Success -> (localVarResponse as Success<*>).data as EmptyResponse
            ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
            ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
            ResponseType.ClientError -> {
                val localVarError = localVarResponse as ClientError<*>
                throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
            }
            ResponseType.ServerError -> {
                val localVarError = localVarResponse as ServerError<*>
                throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
            }
        }
    }

    /**
    * To obtain the request config of the operation unsubscribe
    *
    * @param query query is a string, which has a form: \"condition AND condition ...\" (no OR at the moment). condition has a form: \"key operation operand\". key is a string with a restricted set of possible symbols ( \\t\\n\\r\\\\()\"'=>< are not allowed). operation can be \"=\", \"<\", \"<=\", \">\", \">=\", \"CONTAINS\". operand can be a string (escaped with single quotes), number, date or time.  
    * @return RequestConfig
    */
    fun unsubscribeRequestConfig(query: kotlin.String) : RequestConfig {
        val localVariableBody = null
        val localVariableQuery: MultiValueMap = mutableMapOf>()
            .apply {
                put("query", listOf(query.toString()))
            }
        val localVariableHeaders: MutableMap = mutableMapOf()

        return RequestConfig(
            method = RequestMethod.GET,
            path = "/unsubscribe",
            query = localVariableQuery,
            headers = localVariableHeaders,
            body = localVariableBody
        )
    }

    /**
    * Unsubscribe from all events via WebSocket
    * Unsubscribe from all events via WebSocket 
    * @return EmptyResponse
    * @throws UnsupportedOperationException If the API returns an informational or redirection response
    * @throws ClientException If the API returns a client error response
    * @throws ServerException If the API returns a server error response
    */
    @Suppress("UNCHECKED_CAST")
    @Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
    suspend fun unsubscribeAll() : EmptyResponse = withContext(Dispatchers.IO) {
        val localVariableConfig = unsubscribeAllRequestConfig()

        val localVarResponse = request(
            localVariableConfig
        )

        return@withContext when (localVarResponse.responseType) {
            ResponseType.Success -> (localVarResponse as Success<*>).data as EmptyResponse
            ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
            ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
            ResponseType.ClientError -> {
                val localVarError = localVarResponse as ClientError<*>
                throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
            }
            ResponseType.ServerError -> {
                val localVarError = localVarResponse as ServerError<*>
                throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
            }
        }
    }

    /**
    * To obtain the request config of the operation unsubscribeAll
    *
    * @return RequestConfig
    */
    fun unsubscribeAllRequestConfig() : RequestConfig {
        val localVariableBody = null
        val localVariableQuery: MultiValueMap = mutableMapOf()
        val localVariableHeaders: MutableMap = mutableMapOf()

        return RequestConfig(
            method = RequestMethod.GET,
            path = "/unsubscribe_all",
            query = localVariableQuery,
            headers = localVariableHeaders,
            body = localVariableBody
        )
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy