Skip to content

Commit

Permalink
pyln: handle (ignore) notifications, and add notify_msg to send them.
Browse files Browse the repository at this point in the history
We also sanity check that response id matches our request.

Signed-off-by: Rusty Russell <[email protected]>
Changelog-Added: pyln: pyln.client handles and can send progress notifications.
  • Loading branch information
rustyrussell committed Oct 23, 2020
1 parent 572c849 commit 806f208
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
15 changes: 12 additions & 3 deletions contrib/pyln-client/pyln/client/lightning.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,17 +316,26 @@ def call(self, method, payload=None):

# FIXME: we open a new socket for every readobj call...
sock = UnixSocket(self.socket_path)
this_id = self.next_id
self._writeobj(sock, {
"jsonrpc": "2.0",
"method": method,
"params": payload,
"id": self.next_id,
"id": this_id,
})
self.next_id += 1
resp, _ = self._readobj(sock)
sock.close()
buf = b''
while True:
resp, buf = self._readobj(sock, buf)
# FIXME: We should offer a callback for notifications.
if 'method' not in resp or 'id' in resp:
break

self.logger.debug("Received response for %s call: %r", method, resp)
if 'id' in resp and resp['id'] != this_id:
raise ValueError("Malformed response, id is not {}: {}.".format(this_id, resp))
sock.close()

if not isinstance(resp, dict):
raise ValueError("Malformed response, response is not a dictionary %s." % resp)
elif "error" in resp:
Expand Down
20 changes: 20 additions & 0 deletions contrib/pyln-client/pyln/client/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -608,6 +608,26 @@ def log(self, message: str, level: str = 'info') -> None:
for line in message.split('\n'):
self.notify('log', {'level': level, 'message': line})

def notify_message(self, request: Request, message: str,
level: str = 'info') -> None:
"""Send a notification message to sender of this request"""
self.notify("message", {"id": request.id,
"level": level,
"message": message})

def notify_progress(self, request: Request,
progress: int, progress_total: int,
stage: Optional[int] = None,
stage_total: Optional[int] = None) -> None:
"""Send a progerss message to sender of this request: if more than one stage, set stage and stage_total"""
d: Dict[str, Any] = {"id": request.id,
"num": progress,
"total": progress_total}
if stage_total is not None:
d['stage'] = {"num": stage, "total": stage_total}

self.notify("progress", d)

def _parse_request(self, jsrequest: Dict[str, JSONType]) -> Request:
i = jsrequest.get('id', None)
if not isinstance(i, int) and i is not None:
Expand Down

0 comments on commit 806f208

Please sign in to comment.