stompit

repository·master·Indexed 41 days ago

https://github.com/gdaws/stompit

A stream-oriented STOMP client library for Node.js compatible with STOMP 1.0, 1.1, and 1.2 servers. It provides features such as server failover via stompit.ConnectFailover, persistent subscriptions, and connection management through stompit.ChannelPool and stompit.Channel.

Tokens
8.8K
Snippets
25
Records
42
Agent score
50%

What's inside stompit

  1. How to use stompit.ChannelPool to manage STOMP channels

    master

    The stompit.ChannelPool class manages a pool of STOMP channels to optimize connection reuse and limit concurrent channel allocation. Instead of manually managing connections, you request a channel from the pool, perform your operations (send/subscribe), and the pool handles the lifecycle based on idle events.

    Requesting a channel

    Use channelPool.channel(callback) to request an unused channel. The channel is passed to the callback as the second argument.

    Important Lifecycle Note: The pool determines if a channel is available for reuse or should be closed based on the idle event. This event is emitted when all send and subscribe operations on that channel are completed. If you perform a single send operation and no other operations are active, the channel will immediately emit idle and may be returned to the pool or closed.

    channelPool.channel(function(error, channel) {
      // Use the channel here
    });
  2. Use stompit.Channel for connectionless messaging

    master

    The stompit.Channel class provides a connectionless abstraction for reliable message sending and subscriptions. Unlike a standard stompit.Client, a Channel manages connections automatically based on its configuration.

    Connection Management

    You can control how the Channel manages its underlying connections using the alwaysConnected option in the constructor:

    • alwaysConnected: false (Default): On-demand mode. A connection is maintained only while there are active operations (e.g., sending messages or open subscriptions). The connection is dropped once the last operation completes.
    • alwaysConnected: true: The Channel maintains an open connection at all times.

    To completely stop all operations and disconnect the underlying client (even in alwaysConnected mode), call channel.close().

    const channel = new stompit.Channel(connectFailover, { alwaysConnected: true });
  3. Configure connection options for stompit.connect

    master

    The options object passed to stompit.connect controls the connection behavior.

    General Options

    • host (string): Remote host address. Default: "localhost".
    • port (integer): Remote port address. Default: 61613.
    • timeout (integer): Timeout for the transport connect operation. Default: 3000.
    • connectHeaders (object): Headers to be sent in the connect frame. Default: {}.
    • path (string): Use unix domain socket and use path as the destination address.
    • ssl (boolean): Use a secure connection. Default: false.
    • connect (function): Override the transport factory constructor used.
    • heartbeatDelayMargin (integer): Add milliseconds for server heart-beat wait interval. Default: 100.
    • heartbeatOutputMargin (integer): Subtract milliseconds for client heart-beat start interval. Default: 0.

    Note: Since net.connect and tls.connect are used under the hood, any undocumented options available to those Node.js functions are also applicable.

  4. Configure stompit.ChannelPool options

    master

    When instantiating new stompit.ChannelPool(connectFailover, [options]), you can provide an options object to tune the pool's behavior regarding channel limits and idle timeouts.

    OptionTypeDefaultDescription
    minChannelsinteger1The minimum number of channels created. The pool will not drop below this number during its lifecycle.
    minFreeChannelsinteger1The minimum number of spare (idle) channels to maintain. More channels are created as existing ones become busy.
    maxChannelsintegerInfinityThe maximum number of channels allocated concurrently. If this limit is reached, new requests for channels are queued until a busy channel becomes idle.
    freeExcessTimeoutinteger0The number of milliseconds a channel can remain idle before it is closed and deallocated.
  5. Configure SSL/TLS options for stompit.connect

    master

    When the ssl option is set to true in stompit.connect, you can provide the following security credentials:

    • pfx (string or Buffer): Private key, certificate, and CA certs of the client in PFX or PKC12 format.
    • key (string or Buffer): Private key of the client in PEM format.
    • passphrase (string): Passphrase for the private key.
    • cert (string or Buffer): Client certificate file in PEM format.
    • ca (Array<string | Buffer>): Array of trusted certificates in PEM format.
  6. Configure stompit.ConnectFailover options

    master

    When instantiating stompit.ConnectFailover, you can pass an options object to customize the reconnection strategy.

    OptionTypeDefaultDescription
    initialReconnectDelayinteger10Delay in milliseconds for the first reconnect attempt.
    maxReconnectDelayinteger30000Maximum delay in milliseconds for any reconnect attempt.
    useExponentialBackOffbooleantrueWhether to use an exponential increase in reconnect delay.
    maxReconnectsinteger-1Maximum number of consecutive failed reconnects allowed. -1 means infinite.
    randomizebooleantrueWhether to randomly choose a server from the list when reconnecting.
    connectFunctionfunctionstompit.connectOverride the client factory constructor used for connections.
  7. Send and receive messages with stompit

    master

    stompit is a STOMP client library for Node.js compatible with STOMP 1.0, 1.1, and 1.2. It uses a stream-oriented API and supports any stream.Duplex transport (e.g., tls.TLSSocket).

    To use the client, follow these steps:

    1. Define connectOptions including host, port, and connectHeaders (for authentication and heartbeats).
    2. Call stompit.connect() to establish a connection.
    3. Use client.send(sendHeaders) to create a writable stream for sending messages.
    4. Use client.subscribe(subscribeHeaders, callback) to listen for incoming messages.
    5. Within the subscription callback, use message.readString() to consume the message body.
    6. Acknowledge the message using client.ack(message) if using client-side acknowledgment modes.
    7. Disconnect using client.disconnect() when finished.
    const stompit = require('stompit');
    
    const connectOptions = {
      'host': 'localhost',
      'port': 61613,
      'connectHeaders':{
        'host': '/',
        'login': 'username',
        'passcode': 'password',
        'heart-beat': '5000,5000'
      }
    };
    
    stompit.connect(connectOptions, function(error, client) {
      
      if (error) {
        console.log('connect error ' + error.message);
        return;
      }
      
      const sendHeaders = {
        'destination': '/queue/test',
        'content-type': 'text/plain'
      };
      
      const frame = client.send(sendHeaders);
      frame.write('hello');
      frame.end();
      
      const subscribeHeaders = {
        'destination': '/queue/test',
        'ack': 'client-individual'
      };
      
      client.subscribe(subscribeHeaders, function(error, message) {
        
        if (error) {
          console.log('subscribe error ' + error.message);
          return;
        }
        
        message.readString('utf-8', function(error, body) {
          
          if (error) {
            console.log('read message error ' + error.message);
            return;
          }
          
          console.log('received message: ' + body);
          
          client.ack(message);
          
          client.disconnect();
        });
      });
    });
  8. Send a message with channel.send()

    master

    Use channel.send(headers, body, [callback]) to transmit a message.

    The body argument is flexible and accepts:

    • A string
    • A Buffer
    • A function that returns a new, unused stream.Readable object. Note that if the body is a function, it may be called multiple times (once for the initial transmission and again for each re-transmission).
    channel.send({ 'destination': '/queue/test' }, 'Hello World', (error) => {
      if (error) console.error(error);
    });
  9. Connect to a STOMP broker with stompit.connect()

    master

    Use stompit.connect(options, [connectionListener]) to establish a connection to a STOMP broker. The options object defines the connection parameters (such as host, port, and credentials), and an optional connectionListener can be provided to handle connection events.

    // Example usage pattern
    stompit.connect(options, (error, client) => {
      if (error) {
        // handle error
      }
      // use client
    });
  10. Use transactions in stompit

    master

    Transactions allow you to group multiple operations together.

    client.begin([headers])

    Creates a new transaction.

    transaction.send(headers, [options])

    Sends a message within the context of the transaction. Behaves identically to client.send.

    transaction.commit([options])

    Commits the transaction. Use the onReceipt option to receive confirmation from the server that the commit was successful. If an error occurs during commit, the server terminates the connection and the client emits an error event.

    transaction.abort([options])

    Aborts the transaction.

    const transaction = client.begin({ 'transaction': 'tx-123' });
    
    transaction.send({ 'destination': '/queue/test' }, { 'content': 'part 1' });
    transaction.send({ 'destination': '/queue/test' }, { 'content': 'part 2' });
    
    transaction.commit({ onReceipt: () => console.log('Transaction committed') });