1

I am making APIs to subscribe and unsubscribe from nats streaming server (stan). The subscribe works fine, but I am not able to unsubscribe.

Connecting to nats streaming,

const stanSubscribe = nats.connect('test-cluster', 'clientId');
stanSubscribe.on('connect', async () => {
    console.log('Subscriber connected to nats server');
});

Calling this function from the API,

 await helper.subscribeToTopic(topic, queueName);
subscribeToTopic: async function(topic, queueName) {
    console.log('subscriber function start');
    const options = stanSubscribe.subscriptionOptions().setManualAckMode(true);
    let subscribe = stanSubscribe.subscribe(topic, queueName, options);
    console.log(`subscribed: ${subscribe}`);
    subscribe.on('message', async (subMessage) => {
        console.log('Recieved the message, queue name = [' + queueName + '] sequence = [' + subMessage.getSequence() + '] - ' + subMessage.getData());
    });
    console.log('subscriber function end');
}

But the part that is not working is unsubscribing, when the unsubscribe API is called, I get the subject name (topic) and clientId,

Now, in the unsubscribe API, this is what I am doing since I have the clientId and subject,

try {
    const options = stanSubscribe.subscriptionOptions().setManualAckMode(true);
    let sub = stanSubscribe.subscribe(topic, queueName, options);
    sub.unsubscribe();
    
    sub.on('unsubscribed', () => {
        console.log(`unsubscribed from queue: ${queueName} from topic: ${topic}`);
    });

    if (sub.isClosed()) {
        console.log(`subscription is closed for queueName: ${queueName} from topic: ${topic}`);
    }
} catch (error) {
    console.log(`error: ${error}`);
}

I am not getting any error in the catch block, but from nats streaming, and the error is,

Error: stan: invalid subscription
    at Object.callback (D:\services\webhooks\node_modules\node-nats-streaming\lib\stan.js:858:26)
    at Object.callback (D:\services\webhooks\node_modules\nats\lib\nats.js:2081:16)
    at Client.processMsg (D:\services\webhooks\node_modules\nats\lib\nats.js:1467:13)
    at Client.processInbound (D:\services\webhooks\node_modules\nats\lib\nats.js:1340:14)
    at Socket.<anonymous> (D:\services\webhooks\node_modules\nats\lib\nats.js:852:10)
    at Socket.emit (events.js:315:20)
    at addChunk (_stream_readable.js:309:12)
    at readableAddChunk (_stream_readable.js:284:9)
    at Socket.Readable.push (_stream_readable.js:223:10)
    at TCP.onStreamRead (internal/stream_base_commons.js:188:23)

and because of this, it is not unsubscribing.

Any help would be much appreciated, thanks.

Ashwin Pandey
  • 125
  • 13

0 Answers0