From 3d489bf2eeae8f2dbdc5518fb9eec93da918b4e2 Mon Sep 17 00:00:00 2001 From: fiatjaf Date: Sun, 18 Apr 2021 10:29:22 -0300 Subject: [PATCH] make it so LNbitsWallet reconnects if the listener stream goes off. --- lnbits/wallets/lnbits.py | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/lnbits/wallets/lnbits.py b/lnbits/wallets/lnbits.py index 5ac3e2459..13ea8046e 100644 --- a/lnbits/wallets/lnbits.py +++ b/lnbits/wallets/lnbits.py @@ -1,3 +1,4 @@ +import trio # type: ignore import json import httpx from os import getenv @@ -116,16 +117,25 @@ class LNbitsWallet(Wallet): async def paid_invoices_stream(self) -> AsyncGenerator[str, None]: url = f"{self.endpoint}/api/v1/payments/sse" - async with httpx.AsyncClient(timeout=None, headers=self.key) as client: - async with client.stream("GET", url) as r: - async for line in r.aiter_lines(): - if line.startswith("data:"): - try: - data = json.loads(line[5:]) - except json.decoder.JSONDecodeError: - continue + while True: + try: + async with httpx.AsyncClient(timeout=None, headers=self.key) as client: + async with client.stream("GET", url) as r: + async for line in r.aiter_lines(): + if line.startswith("data:"): - if type(data) is not dict: - continue + try: + data = json.loads(line[5:]) + except json.decoder.JSONDecodeError: + continue - yield data["payment_hash"] # payment_hash + if type(data) is not dict: + continue + + yield data["payment_hash"] # payment_hash + + except (OSError, httpx.ReadError, httpx.ConnectError): + pass + + print("lost connection to lnbits /payments/sse, retrying in 5 seconds") + await trio.sleep(5)