clj-bson-rpc.core

JSON-RPC 2.0 and BSON-RPC Connections over manifold duplex stream.

Practical applications include using aleph to establish TCP connection (+ TLS) between the client and the server.

After an RPC connection has been set on both sides, the RPC nodes are principally equal. The TCP client may provide services which the TCP server then uses and vice versa.

async-request!

(async-request! rpc-ctx method & params)

RPC Request in a clojure.core.async go-block.

  • rpc-ctx - The Context from connect-rpc!.
  • method - Remote method name - a keyword or string.
  • params - Parameters for the remote method.

Returns a channel which will receive:

  • The Result message from the RPC Peer Node or
  • :closed or
  • :send-failure

async-request-with-timeout!

(async-request-with-timeout! rpc-ctx timeout method & params)

RPC Request in a clojure.core.async go-block.

  • timeout - Milliseconds to wait for remote method return value.
  • Otherwise identical to async-request!

Returns a channel which will receive results identical to async-request! or possibly the value :timeout if waiting of result timed out.

close!

(close! rpc-ctx)

Utility for closing the connection from outside of request handler. Use close-connection! within response handler.

close-connection!

(close-connection!)(close-connection! response)

Call this function within your request or notification handler in order to disconnect current tcp connection. close-connection! does not return.

  • response - Response sent to a request (if within a request handler) just before disconnection. Defaults to nil if not provided.

close-connection-and-server!

(close-connection-and-server!)(close-connection-and-server! response)

Call this function within your request or notification handler in order to close both current connection and the server socket. close-connection-and-server! does not return.

  • response - Response sent to a request (if within a request handler) just before disconnection. Defaults to nil if not provided.

close-server!

(close-server!)(close-server! response)

Call this function within your request or notification handler in order to close server socket. Does not disconnect your current connection. close-server! does not return.

  • response - Response sent to a request (if within a request handler). Defaults to nil if not provided.

connect-bson-rpc!

(connect-bson-rpc! s)(connect-bson-rpc! s options)(connect-bson-rpc! s request-handlers notification-handlers)(connect-bson-rpc! s request-handlers notification-handlers options)

Connect rpc services and create a context for sending BSON-RPC (2.0) requests and notifications to the RPC Peer Node over TCP connection.

  • s - Manifold duplex stream connected to the rpc peer node. (e.g. from aleph.tcp/start-server to the handler or from aleph.tcp/client)
  • request-handlers
    • A Map of request handlers: {::String/Keyword ::Function}. These functions are exposed to be callable by the rpc peer node. Function return values are sent back to peer node and any thrown errors are sent as error responses to the peer node.
    • Alternatively this parameter accepts a function which takes rpc-ctx and returns an above-mentioned Map of request handlers. Necessary if any request handler needs to send notifications to peer during the processing of request. example function:
      (defn generate-request-handlers [rpc-ctx]
        {:quick-task quick-task
         :long-process (partial long-process rpc-ctx)})
      

      where the long-process will thus have the rpc-ctx and will be able to call (notify! rpc-ctx :report-progress details) or even (request! rpc-ctx ...)

  • notification-handlers
    • A Map of notification handlers: {::String/Keyword ::Function}. These functions will receive the named notifications sent by the peer node. Any errors thrown by these handlers will be delegated to a callback defined by (:notification-error-handler options)
    • Alternatively can be a function which takes rpc-ctx and returns a Map of handlers.
  • options - A Map of optional arguments. default-options are used as a baseline of which any or all values can be overridden with ones provided by options.

Valid keys for options:

  • :async-notification-handling - Boolean for async handling of notifications.
    • false -> Handler functions are guaranteed to be called in the message receiving order. Next incoming message can’t be processed until the handler function returns.
    • true -> Handlers executed in go-blocks -> random order.
  • :async-request-handling - Boolean for async handling of requests. Async handling allows multiple requests to processed in parallel (if client so wishes). Note that client can enforce synchronous processing simply by waiting the answer to previous request before calling new request.
    • Dispatching of responses is synchronous regardless of this setting. If :async-notification-handling was set to false then all notifications possibly sent by a (peer node) response handler will be processed by the time the response is returned.
  • :connection-closed-handler - Is called when peer closes the connection. One argument: rpc-ctx. Return value ignored.
  • :connection-id - ID to use in server logging to identify current connection.
  • :id-generator - Is called when a new ID for outgoing rpc request is needed. No arguments. Must return a string or integer which should be unique over the duration of the connection.
  • :idle-timeout - Timeout in milliseconds. idle-timeout-handler will be triggered if timeout is enabled and nothing has been received from peer node within idle-timeout. Disable by setting to nil.
  • :idle-timeout-handler - One argument: rpc-ctx. Return value ignored.
  • :invalid-id-response-handler - Two arguments: rpc-ctx and message. Return value ignored. Used if peer sends a response in which ID does not match with any sent requests waiting for a response.
  • :max-len - Incoming message max length.
  • :nil-id-error-handler - Is called when an error response with id: null is received from the peer node. (Normal error responses are marshalled to throw errors within request! calls.) Two arguments: rpc-ctx and message (::String). Return value ignored.
  • :notification-error-handler - Two arguments: rpc-ctx and thrown Exception object. Return value ignored.
  • :protocol-keyword - Affects the name of the keyword used in BSON message documents. Defaults to :bsonrpc if option is omitted. Having value “2.0” Rationale: BSON-RPC is derived from and closely matches JSON-RPC 2.0. (Support for Version 1.0 of the protocol not planned.)
  • :server - A java.io.Closeable object. Give if your handlers need the ability to close the server object.

Returns rpc-ctx to be used with request! and notify!.

connect-json-rpc!

(connect-json-rpc! s)(connect-json-rpc! s options)(connect-json-rpc! s request-handlers notification-handlers)(connect-json-rpc! s request-handlers notification-handlers options)

Connect rpc services and create a context for sending JSON-RPC 2.0 requests and notifications to the RPC Peer Node over TCP connection.

  • s - Manifold duplex stream connected to the rpc peer node. (e.g. from aleph.tcp/start-server to the handler or from aleph.tcp/client)
  • request-handlers
    • A Map of request handlers: {::String/Keyword ::Function}. These functions are exposed to be callable by the rpc peer node. Function return values are sent back to peer node and any thrown errors are sent as error responses to the peer node.
    • Alternatively this parameter accepts a function which takes rpc-ctx and returns an above-mentioned Map of request handlers. Necessary if any request handler needs to send notifications to peer during the processing of request. example function:
      (defn generate-request-handlers [rpc-ctx]
        {:quick-task quick-task
         :long-process (partial long-process rpc-ctx)})
      

      where the long-process will thus have the rpc-ctx and will be able to call (notify! rpc-ctx :report-progress details) or even (request! rpc-ctx ...)

  • notification-handlers
    • A Map of notification handlers: {::String/Keyword ::Function}. These functions will receive the named notifications sent by the peer node. Any errors thrown by these handlers will be delegated to a callback defined by (:notification-error-handler options)
    • Alternatively can be a function which takes rpc-ctx and returns a Map of handlers.
  • options - A Map of optional arguments. default-options are used as a baseline of which any or all values can be overridden with ones provided by options.

Valid keys for options:

  • :async-notification-handling - Boolean for async handling of notifications.
    • false -> Handler functions are guaranteed to be called in the message receiving order. Next incoming message can’t be processed until the handler function returns.
    • true -> Handlers executed in go-blocks -> random order.
  • :async-request-handling - Boolean for async handling of requests. Async handling allows multiple requests to processed in parallel (if client so wishes). Note that client can enforce synchronous processing simply by waiting the answer to previous request before calling new request.
    • Dispatching of responses is synchronous regardless of this setting. If :async-notification-handling was set to false then all notifications possibly sent by a (peer node) response handler will be processed by the time the response is returned.
  • :connection-closed-handler - Is called when peer closes the connection. One argument: rpc-ctx. Return value ignored.
  • :connection-id - ID to use in server logging to identify current connection.
  • :id-generator - Is called when a new ID for outgoing rpc request is needed. No arguments. Must return a string or integer which should be unique over the duration of the connection.
  • :idle-timeout - Timeout in milliseconds. idle-timeout-handler will be triggered if timeout is enabled and nothing has been received from peer node within idle-timeout. Disable by setting to nil.
  • :idle-timeout-handler - One argument: rpc-ctx. Return value ignored.
  • :invalid-id-response-handler - Two arguments: rpc-ctx and message. Return value ignored. Used if peer sends a response in which ID does not match with any sent requests waiting for a response.
  • :json-framing - One of the following keywords:
  • :json-key-fn - JSON Object keys decode converter. Provide custom converter, otherwise by default clojure.core/keyword is used. Use clojure.core/identity to keep keys as strings. Encoding keywords are always converted to strings.
  • :max-len - Incoming message max length. This option is ignored if :json-framing is :none
  • :nil-id-error-handler - Is called when an error response with id: null is received from the peer node. (Normal error responses are marshalled to throw errors within request! calls.) Two arguments: rpc-ctx and message (::String). Return value ignored.
  • :notification-error-handler - Two arguments: rpc-ctx and thrown Exception object. Return value ignored.
  • :protocol-keyword - Affects the name of the keyword used in JSON message documents. Defaults to :jsonrpc if option is omitted. Having value “2.0” as is required by the JSON-RPC 2.0 Specification. (Support for Version 1.0 of the protocol not planned.)
  • :server - A java.io.Closeable object. Give if your handlers need the ability to close the server object.

Returns rpc-ctx to be used with request! and notify!.

default-options

connect-rpc! default options. See connect-bson-rpc! and connect-json-rpc! for semantic explanations. These values are used for those options which are not provided in the options Map argument.

Defaults:

  • :async-notification-handling - Default value is false, which is based on an assumption that typically notifications are order-sensitive messages e.g. progress reports which must be handled in the exact order in which they are received.
  • :async-request-handling - Default value is true. Async handling allows handlers to execute even the most time-consuming tasks without blocking other incoming messages. Yet the client side can deside whether to call requests in tight sequential order or to call them in parallel.
  • :connection-closed-handler - Default handler stops the service for the current stream and closes the stream. (No effect on the server socket/object.)
  • :connection-id - Arbitrary unique ID to identify connection, shown in logging so that multiple connections with separate clients can be traced. nil -> generated integer id.
  • :id-generator - Default generator generates ‘id-1’, ‘id-2’, etc. ids for outbound requests.
  • :idle-timeout - Default value nil disables idle timeouts.
  • :idle-timeout-handler - Default handler stops the service for the current stream and closes the stream. (No effect on the the server socket/object.)
  • :invalid-id-response-handler - Default handler logs the error.
  • :json-framing - Default :none means JSON messages are streamed consequentially without framing.
  • :json-key-fn- Default clojure.core/keyword, JSON Object keys are keywordized.
  • :max-len - The max capacity defined in bson specification: 2 147 483 647 bytes (Max Int32)
  • :nil-id-error-handler - Default handler logs the error message sent by rpc peer node.
  • :notification-error-handler - Default handler logs the error.
  • :server - Default value nil

notify!

(notify! rpc-ctx method & params)

Send RPC Notification to peer. Return boolean success value.

  • rpc-ctx - Context returned by connect-rpc!
  • method - Remote notification handler name - a keyword or string.
  • params - Parameters for the notification handler.

request!

(request! rpc-ctx method & params)

RPC Request to the peer node. Waits for a response indefinitely.

  • rpc-ctx - Context returned by connect-rpc!.
  • method - Remote method name - a keyword or string.
  • params - Parameters for the remote method.

Returns: The return value from the remote method or Throws:

  • clojure.lang.ExceptionInfo with ex-data mappings:
    • {:type :rpc-peer :code :details } on peer node errors.
    • {:type :rpc-connection-closed} If either this node or peer node closed the connection.
    • {:type :rpc-buffer-overflow} Send buffer full.

request-with-timeout!

(request-with-timeout! rpc-ctx timeout method & params)

RPC Request to the peer node. Waits for the response for up to the timeout length of time.

  • timeout - Milliseconds to wait for remote method return value.
  • Otherwise identical to request!

Returns: The return value from the remote method or Throws: Identically to request! or {:type :rpc-response-timeout} when timeouted.