Gelb
Gelb

Reputation: 11

NATS does not raise an exception when disconnecting

I use an almost standard example of using NATS on python asyncio. I want to receive a message, process it, and send the result back to the queue, but when the NATS is disconnected (e.g. reboot gnats), the exception does not raise. I even did await asyncio.sleep (1, loop = loop) to change the context and the disconnect -> reconnect exception was thrown, but this does not happen. What am I doing wrong? May be it's a bug?

import asyncio
from nats.aio.client import Client as NATS
import time


async def run(loop):
    nc = NATS()

    await nc.connect(io_loop=loop)

    async def message_handler(msg):
        subject = msg.subject
        reply = msg.reply
        data = msg.data.decode()
        print("Received a message on '{subject} {reply}': {data}".format(
            subject=subject, reply=reply, data=data))

        # Working
        time.sleep(10)

        # If nats disconnects at this point, the exception will not be caused
        # and will be made attempt to send a message by nc.publish
        await asyncio.sleep(2, loop=loop)

        print("UNSLEEP")
        await nc.publish("test", "test payload".encode())
        print("PUBLISHED")

    # Simple publisher and async subscriber via coroutine.
    await nc.subscribe("foo", cb=message_handler)

    while True:
        await asyncio.sleep(1, loop=loop)

    await nc.close()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run(loop))
    loop.close()

Upvotes: 1

Views: 1191

Answers (1)

Andrew Svetlov
Andrew Svetlov

Reputation: 17376

NATs is built on top of TCP.

TCP has no reliable disconnection signal by definition. To solve it any messaging system should use a kind of ping messages and drop the connection if timeout occurs.

Strictly speaking you will get disconnection event sometimes, but it may take up to 2 hours (depends on your OS settings).

Upvotes: 1

Related Questions