Răsfoiți Sursa

Pipeline MPD commands instead of blocking on them

MPD answers next/previous only after the new song is open, which from a sleeping NFS disk can exceed the 2 s socket timeout: the command took effect but the  client dropped the connection, and the UI froze meanwhile. Only the handshake blocks now; replies are handled as they arrive, and the connection is given up after 30 s without an owed answer.
k4be 2 săptămâni în urmă
părinte
comite
2c0338e7d3
3 a modificat fișierele cu 194 adăugiri și 94 ștergeri
  1. 137 79
      radio/mpd.py
  2. 24 7
      tests/fake_mpd.py
  3. 33 8
      tests/test_ui.py

+ 137 - 79
radio/mpd.py

@@ -1,9 +1,12 @@
 """MPD connection on the GLib main loop.
 """MPD connection on the GLib main loop.
 
 
 The connection sits in "idle", so changes arrive as events instead of being
 The connection sits in "idle", so changes arrive as events instead of being
-polled; a command first leaves idle, does its work and goes back. Commands are
-synchronous with a timeout, like libmpdclient's. Reconnects every 3 s.
+polled; a command first leaves idle, does its work and goes back. Only the
+handshake blocks: commands are pipelined and their responses handled as they
+arrive, so a slow server (a song opening from a sleeping NFS disk) never
+stalls the UI. Reconnects every 3 s.
 """
 """
+import collections
 import socket
 import socket
 
 
 from gi.repository import GLib
 from gi.repository import GLib
@@ -11,6 +14,9 @@ from gi.repository import GLib
 from . import state as st
 from . import state as st
 
 
 CONNECT_TIMEOUT_S = 2.0
 CONNECT_TIMEOUT_S = 2.0
+# how long the server may sit on an answer before the connection is given up;
+# libmpdclient's default, as next/play wait until the new song is open
+RESPONSE_TIMEOUT_S = 30
 RECONNECT_S = 3
 RECONNECT_S = 3
 IDLE_SUBSYSTEMS = "playlist player mixer options"
 IDLE_SUBSYSTEMS = "playlist player mixer options"
 
 
@@ -57,7 +63,10 @@ def format_title(song):
 
 
 
 
 class Connection(object):
 class Connection(object):
-    """Blocking line protocol; any socket trouble raises ConnectionLost"""
+    """Line protocol; any socket trouble raises ConnectionLost.
+
+    The handshake reads blocking (with a timeout); afterwards read_lines() is
+    called only when the socket is readable, so it never waits."""
 
 
     def __init__(self, host, port):
     def __init__(self, host, port):
         if host.startswith("/"):
         if host.startswith("/"):
@@ -96,36 +105,28 @@ class Connection(object):
         except (OSError, socket.timeout) as e:
         except (OSError, socket.timeout) as e:
             raise ConnectionLost(str(e) or "write failed")
             raise ConnectionLost(str(e) or "write failed")
 
 
+    def _recv(self):
+        try:
+            chunk = self.sock.recv(4096)
+        except socket.timeout:
+            raise ConnectionLost("timeout")
+        except OSError as e:
+            raise ConnectionLost(str(e))
+        if not chunk:
+            raise ConnectionLost("connection closed")
+        self.buf += chunk
+
     def read_line(self):
     def read_line(self):
         while b"\n" not in self.buf:
         while b"\n" not in self.buf:
-            try:
-                chunk = self.sock.recv(4096)
-            except socket.timeout:
-                raise ConnectionLost("timeout")
-            except OSError as e:
-                raise ConnectionLost(str(e))
-            if not chunk:
-                raise ConnectionLost("connection closed")
-            self.buf += chunk
+            self._recv()
         line, self.buf = self.buf.split(b"\n", 1)
         line, self.buf = self.buf.split(b"\n", 1)
         return line.decode("utf-8", "replace")
         return line.decode("utf-8", "replace")
 
 
-    def read_response(self):
-        """Lines up to OK, as (key, value) pairs; ACK raises ServerError"""
-        pairs = []
-        while True:
-            line = self.read_line()
-            if line == "OK":
-                return pairs
-            if line.startswith("ACK "):
-                raise ServerError(_ack_message(line))
-            key, sep, value = line.partition(": ")
-            if sep:
-                pairs.append((key, value))
-
-    def command(self, line):
-        self.send(line)
-        return self.read_response()
+    def read_lines(self):
+        """One read from a readable socket: the complete lines it finished"""
+        self._recv()
+        *lines, self.buf = self.buf.split(b"\n")
+        return [line.decode("utf-8", "replace") for line in lines]
 
 
 
 
 class MpdClient(object):
 class MpdClient(object):
@@ -138,17 +139,21 @@ class MpdClient(object):
         self.log = log
         self.log = log
         self.conn = None
         self.conn = None
         self.watch_id = 0
         self.watch_id = 0
+        self.timeout_id = 0
         self.was_connected = False
         self.was_connected = False
+        # one handler per request sent and not yet answered, oldest first;
+        # each gets the response's (key, value) pairs, or a ServerError
+        self.pending = collections.deque()
+        self.pairs = []
+        self.idling = False     # "idle" sent and no "noidle" after it yet
         # not directly: the owner must finish construction first
         # not directly: the owner must finish construction first
         self.retry_id = GLib.idle_add(self._try_connect)
         self.retry_id = GLib.idle_add(self._try_connect)
 
 
     def close(self):
     def close(self):
-        if self.watch_id:
-            GLib.source_remove(self.watch_id)
-            self.watch_id = 0
-        if self.retry_id:
-            GLib.source_remove(self.retry_id)
-            self.retry_id = 0
+        for attr in ("watch_id", "retry_id", "timeout_id"):
+            if getattr(self, attr):
+                GLib.source_remove(getattr(self, attr))
+                setattr(self, attr, 0)
         if self.conn:
         if self.conn:
             self.conn.close()
             self.conn.close()
             self.conn = None
             self.conn = None
@@ -156,12 +161,16 @@ class MpdClient(object):
     # ---- connection ---------------------------------------------------------
     # ---- connection ---------------------------------------------------------
 
 
     def _drop(self, why):
     def _drop(self, why):
-        if self.watch_id:
-            GLib.source_remove(self.watch_id)
-            self.watch_id = 0
+        for attr in ("watch_id", "timeout_id"):
+            if getattr(self, attr):
+                GLib.source_remove(getattr(self, attr))
+                setattr(self, attr, 0)
         if self.conn:
         if self.conn:
             self.conn.close()
             self.conn.close()
             self.conn = None
             self.conn = None
+        self.pending.clear()
+        self.pairs = []
+        self.idling = False
         self.state.connected = False
         self.state.connected = False
         if self.was_connected and why:
         if self.was_connected and why:
             self.log("MPD: %s" % why)
             self.log("MPD: %s" % why)
@@ -181,49 +190,102 @@ class MpdClient(object):
         self.state.connected = True
         self.state.connected = True
         self.was_connected = True
         self.was_connected = True
         self.log("Połączono z MPD: %s" % self.host)
         self.log("Połączono z MPD: %s" % self.host)
-        if self._run(self._refresh):
-            self.watch_id = GLib.io_add_watch(
-                self.conn.fileno(), GLib.PRIORITY_DEFAULT,
-                GLib.IO_IN | GLib.IO_HUP | GLib.IO_ERR, self._on_readable)
-            self._enter_idle()
-        return False
-
-    def _run(self, fn, *args):
-        """Call fn; True if the connection survived it"""
+        self.watch_id = GLib.io_add_watch(
+            self.conn.fileno(), GLib.PRIORITY_DEFAULT,
+            GLib.IO_IN | GLib.IO_HUP | GLib.IO_ERR, self._on_readable)
         try:
         try:
-            fn(*args)
-        except ServerError as e:
-            self.log("MPD: %s" % e)
+            self._queue_refresh()
         except ConnectionLost as e:
         except ConnectionLost as e:
             self._drop(str(e))
             self._drop(str(e))
-            return False
-        return True
+        return False
+
+    # ---- requests -----------------------------------------------------------
+
+    def _send(self, line, handler):
+        """Raises ConnectionLost"""
+        self.conn.send(line)
+        self.pending.append(handler)
+        self._arm_timeout()
+
+    def _arm_timeout(self):
+        if self.timeout_id:
+            GLib.source_remove(self.timeout_id)
+            self.timeout_id = 0
+        # only an answer to a command is owed; idle may wait forever
+        if self.pending and not (self.idling and len(self.pending) == 1):
+            self.timeout_id = GLib.timeout_add_seconds(RESPONSE_TIMEOUT_S,
+                                                       self._on_timeout)
+
+    def _on_timeout(self):
+        self.timeout_id = 0
+        self._drop("timeout")
+        return False
+
+    def _leave_idle(self):
+        # if the idle answer is already on its way the server ignores this,
+        # so either way exactly one response comes back for the idle
+        if self.idling:
+            self.idling = False
+            self.conn.send("noidle")
 
 
     def _enter_idle(self):
     def _enter_idle(self):
-        if self.conn:
-            try:
-                self.conn.send("idle " + IDLE_SUBSYSTEMS)
-            except ConnectionLost as e:
-                self._drop(str(e))
+        self._send("idle " + IDLE_SUBSYSTEMS, self._on_idle)
+        self.idling = True
+        self._arm_timeout()
+
+    def _queue_refresh(self):
+        self._send("status", self._on_status)
+        self._send("currentsong", self._on_song)
 
 
     def _on_readable(self, fd, cond):
     def _on_readable(self, fd, cond):
         if cond & (GLib.IO_HUP | GLib.IO_ERR):
         if cond & (GLib.IO_HUP | GLib.IO_ERR):
             self.watch_id = 0
             self.watch_id = 0
             self._drop("connection closed")
             self._drop("connection closed")
             return False
             return False
-        # the idle response: "changed: ..." lines, then OK
-        if not self._run(self.conn.read_response):
-            return False    # _drop() removed this watch
-        if not self._run(self._refresh):
-            return False
-        self._enter_idle()
+        try:
+            for line in self.conn.read_lines():
+                self._on_line(line)
+            if self.conn and not self.pending:
+                self._enter_idle()
+        except ConnectionLost as e:
+            self._drop(str(e))
         return self.conn is not None
         return self.conn is not None
 
 
-    # ---- state ----------------------------------------------------------------
-
-    def _refresh(self):
+    def _on_line(self, line):
+        if line == "OK":
+            result = self.pairs
+        elif line.startswith("ACK "):
+            result = ServerError(_ack_message(line))
+        else:
+            key, sep, value = line.partition(": ")
+            if sep:
+                self.pairs.append((key, value))
+            return
+        self.pairs = []
+        if not self.pending:
+            raise ConnectionLost("unexpected response")
+        handler = self.pending.popleft()
+        self._arm_timeout()
+        handler(result)
+
+    # ---- responses ----------------------------------------------------------
+
+    def _on_command(self, result):
+        if isinstance(result, ServerError):
+            self.log("MPD: %s" % result)
+
+    def _on_idle(self, result):
+        self.idling = False
+        # left for a command: the refresh queued after it covers any change
+        if not self.pending:
+            self._queue_refresh()
+
+    def _on_status(self, result):
+        if isinstance(result, ServerError):
+            self.log("MPD: %s" % result)
+            return
         s = self.state
         s = self.state
-        status = dict(self.conn.command("status"))
+        status = dict(result)
 
 
         s.state = {"play": st.PLAY_PLAYING, "pause": st.PLAY_PAUSED,
         s.state = {"play": st.PLAY_PLAYING, "pause": st.PLAY_PAUSED,
                    "stop": st.PLAY_STOPPED}.get(status.get("state"), st.PLAY_UNKNOWN)
                    "stop": st.PLAY_STOPPED}.get(status.get("state"), st.PLAY_UNKNOWN)
@@ -245,11 +307,13 @@ class MpdClient(object):
         s.repeat = status.get("repeat") == "1"
         s.repeat = status.get("repeat") == "1"
         s.random = status.get("random") == "1"
         s.random = status.get("random") == "1"
 
 
+    def _on_song(self, result):
+        s = self.state
         s.title = ""
         s.title = ""
         # as the firmware: a stopped player shows no title
         # as the firmware: a stopped player shows no title
-        if s.state != st.PLAY_STOPPED:
+        if not isinstance(result, ServerError) and s.state != st.PLAY_STOPPED:
             song = {}
             song = {}
-            for key, value in self.conn.command("currentsong"):
+            for key, value in result:
                 song.setdefault(key.lower(), value)     # first value of each tag
                 song.setdefault(key.lower(), value)     # first value of each tag
             if song:
             if song:
                 s.title = format_title(song)
                 s.title = format_title(song)
@@ -259,20 +323,14 @@ class MpdClient(object):
         if not self.conn:
         if not self.conn:
             self.log("Brak połączenia z MPD")
             self.log("Brak połączenia z MPD")
             return
             return
-        # leave idle; any event it reports is covered by the refresh below
         try:
         try:
-            self.conn.send("noidle")
-            self.conn.read_response()
-        except ServerError:
-            pass
+            self._leave_idle()
+            line = _COMMANDS.get(cmd)
+            if line:
+                self._send(line, self._on_command)
+            self._queue_refresh()
         except ConnectionLost as e:
         except ConnectionLost as e:
             self._drop(str(e))
             self._drop(str(e))
-            return
-        line = _COMMANDS.get(cmd)
-        if line and not self._run(self.conn.command, line):
-            return
-        if self._run(self._refresh):
-            self._enter_idle()
 
 
 
 
 def _int(text, default):
 def _int(text, default):

+ 24 - 7
tests/fake_mpd.py

@@ -1,14 +1,16 @@
 #!/usr/bin/env python3
 #!/usr/bin/env python3
 """Minimal MPD server for exercising the UI's commands without touching a real
 """Minimal MPD server for exercising the UI's commands without touching a real
 player. Records every command received to the file given as the second
 player. Records every command received to the file given as the second
-argument. Usage: fake_mpd.py PORT LOGFILE [IDLE_EVENT_SECONDS]
+argument. Usage: fake_mpd.py PORT LOGFILE [IDLE_EVENT_SECONDS [NEXT_DELAY_SECONDS]]
 """
 """
 import socketserver
 import socketserver
 import sys
 import sys
 import threading
 import threading
+import time
 
 
 log_path = sys.argv[2]
 log_path = sys.argv[2]
-idle_event_s = float(sys.argv[3]) if len(sys.argv) > 3 else None
+idle_event_s = float(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[3] else None
+delay_s = float(sys.argv[4]) if len(sys.argv) > 4 else 0
 
 
 
 
 class Player:
 class Player:
@@ -30,7 +32,15 @@ class Handler(socketserver.StreamRequestHandler):
         self.wfile.write(text.encode())
         self.wfile.write(text.encode())
         self.wfile.flush()
         self.wfile.flush()
 
 
+    def idle_event(self):
+        with self.lock:
+            if self.idling:
+                self.idling = False
+                self.send("changed: player\nOK\n")
+
     def handle(self):
     def handle(self):
+        self.lock = threading.Lock()
+        self.idling = False
         self.send("OK MPD 0.21.4\n")
         self.send("OK MPD 0.21.4\n")
         announced = False
         announced = False
         for raw in self.rfile:
         for raw in self.rfile:
@@ -41,12 +51,21 @@ class Handler(socketserver.StreamRequestHandler):
             if cmd == "idle":
             if cmd == "idle":
                 # normally answered by the following noidle; optionally
                 # normally answered by the following noidle; optionally
                 # announce a change once per connection, as a real server would
                 # announce a change once per connection, as a real server would
+                with self.lock:
+                    self.idling = True
                 if idle_event_s is not None and not announced:
                 if idle_event_s is not None and not announced:
                     announced = True
                     announced = True
-                    threading.Timer(
-                        idle_event_s, self.send, ["changed: player\nOK\n"]
-                    ).start()
+                    threading.Timer(idle_event_s, self.idle_event).start()
+                continue
+            if cmd == "noidle":
+                # as MPD: ignored unless idle, then the idle gets its answer
+                with self.lock:
+                    if self.idling:
+                        self.idling = False
+                        self.send("OK\n")
                 continue
                 continue
+            if delay_s and cmd in ("next", "previous"):
+                time.sleep(delay_s)     # opening a song from a sleeping disk
             if cmd == "status":
             if cmd == "status":
                 self.send(
                 self.send(
                     f"volume: {player.volume}\nrepeat: 1\nrandom: 1\nsingle: 0\n"
                     f"volume: {player.volume}\nrepeat: 1\nrandom: 1\nsingle: 0\n"
@@ -62,8 +81,6 @@ class Handler(socketserver.StreamRequestHandler):
                     "nie zmieści się w jednej linii wyświetlacza\n"
                     "nie zmieści się w jednej linii wyświetlacza\n"
                     f"Pos: {player.song}\nId: 3\nOK\n"
                     f"Pos: {player.song}\nId: 3\nOK\n"
                 )
                 )
-            elif cmd == "noidle":
-                self.send("OK\n")
             elif cmd == "volume":
             elif cmd == "volume":
                 player.volume += int(line.split(" ")[1].strip('"'))
                 player.volume += int(line.split(" ")[1].strip('"'))
                 self.send("OK\n")
                 self.send("OK\n")

+ 33 - 8
tests/test_ui.py

@@ -50,13 +50,14 @@ def run_loop_until(cond, timeout_s=5.0):
 
 
 
 
 class FakeMpd(object):
 class FakeMpd(object):
-    def __init__(self, idle_event_s=None):
+    def __init__(self, idle_event_s=None, delay_s=None):
         self.port = free_port()
         self.port = free_port()
         fd, self.log_path = tempfile.mkstemp(prefix="fake_mpd_")
         fd, self.log_path = tempfile.mkstemp(prefix="fake_mpd_")
         os.close(fd)
         os.close(fd)
         cmd = [sys.executable, os.path.join(HERE, "fake_mpd.py"), str(self.port), self.log_path]
         cmd = [sys.executable, os.path.join(HERE, "fake_mpd.py"), str(self.port), self.log_path]
-        if idle_event_s is not None:
-            cmd.append(str(idle_event_s))
+        cmd.append("" if idle_event_s is None else str(idle_event_s))
+        if delay_s is not None:
+            cmd.append(str(delay_s))
         self.proc = subprocess.Popen(cmd)
         self.proc = subprocess.Popen(cmd)
         end = time.monotonic() + 5
         end = time.monotonic() + 5
         while time.monotonic() < end:
         while time.monotonic() < end:
@@ -123,7 +124,11 @@ class TestMpdClient(unittest.TestCase):
         self.log = []
         self.log = []
         self.client = mpd.MpdClient("127.0.0.1", self.server.port, self.state,
         self.client = mpd.MpdClient("127.0.0.1", self.server.port, self.state,
                                     lambda: None, self.log.append)
                                     lambda: None, self.log.append)
-        self.assertTrue(run_loop_until(lambda: self.state.connected))
+        self.assertTrue(run_loop_until(self.settled))
+
+    def settled(self):
+        """Connected, every answer in and back in idle"""
+        return self.state.connected and self.client.idling and len(self.client.pending) == 1
 
 
     def tearDown(self):
     def tearDown(self):
         self.client.close()
         self.client.close()
@@ -143,14 +148,17 @@ class TestMpdClient(unittest.TestCase):
         for cmd in (mpd.NEXT, mpd.VOLUME_UP, mpd.VOLUME_DOWN, mpd.TOGGLE, mpd.PREV,
         for cmd in (mpd.NEXT, mpd.VOLUME_UP, mpd.VOLUME_DOWN, mpd.TOGGLE, mpd.PREV,
                     mpd.STOP, mpd.PLAY, mpd.REFRESH):
                     mpd.STOP, mpd.PLAY, mpd.REFRESH):
             self.client.command(cmd)
             self.client.command(cmd)
-        sent = [c for c in self.server.commands()
-                if c not in ("status", "currentsong", "noidle")]
-        self.assertEqual(sent, ["next", "volume +1", "volume -1", "pause", "previous",
-                                "stop", "play"])
+        expected = ["next", "volume +1", "volume -1", "pause", "previous", "stop", "play"]
+
+        def sent():
+            return [c for c in self.server.commands()
+                    if c not in ("status", "currentsong", "noidle")]
+        self.assertTrue(run_loop_until(lambda: sent() == expected and self.settled()))
         self.assertTrue(self.state.connected)
         self.assertTrue(self.state.connected)
 
 
     def test_stopped_has_no_title(self):
     def test_stopped_has_no_title(self):
         self.client.command(mpd.STOP)
         self.client.command(mpd.STOP)
+        self.assertTrue(run_loop_until(self.settled))
         self.assertEqual(self.state.state, st.PLAY_STOPPED)
         self.assertEqual(self.state.state, st.PLAY_STOPPED)
         self.assertEqual(self.state.title, "")
         self.assertEqual(self.state.title, "")
 
 
@@ -177,6 +185,23 @@ class TestMpdClient(unittest.TestCase):
                                     lambda: None, self.log.append)
                                     lambda: None, self.log.append)
         self.assertTrue(run_loop_until(lambda: self.server.commands().count("status") >= 2))
         self.assertTrue(run_loop_until(lambda: self.server.commands().count("status") >= 2))
 
 
+    def test_slow_command_keeps_connection(self):
+        # longer than the handshake timeout, as a song opening from a sleeping disk
+        self.tearDown()
+        self.server = FakeMpd(delay_s=mpd.CONNECT_TIMEOUT_S + 1)
+        self.state = st.RadioState()
+        self.client = mpd.MpdClient("127.0.0.1", self.server.port, self.state,
+                                    lambda: None, self.log.append)
+        self.assertTrue(run_loop_until(self.settled))
+        song = self.state.song_pos
+        start = time.monotonic()
+        self.client.command(mpd.NEXT)
+        self.assertLess(time.monotonic() - start, 0.5)     # did not wait for it
+        self.assertTrue(run_loop_until(lambda: self.state.song_pos == song + 1,
+                                       mpd.CONNECT_TIMEOUT_S + 3))
+        self.assertTrue(self.state.connected)
+        self.assertFalse(any(line.startswith("MPD: ") for line in self.log))
+
 
 
 @unittest.skipUnless(have_panel_lib(), "panel library not built (make lib)")
 @unittest.skipUnless(have_panel_lib(), "panel library not built (make lib)")
 class TestPanel(unittest.TestCase):
 class TestPanel(unittest.TestCase):