Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 51 additions & 11 deletions ayon_api/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@
import logging
import os
import re
import signal
import threading
import time
import typing
from typing import Any, Callable
import weakref
Expand Down Expand Up @@ -493,7 +493,10 @@ def _validate_ref(self) -> None:
# when nothing was received for this amount of time.
_PING_INTERVAL: float = 5.0
# Connection is considered dead if nothing (not even pong) was received
# for this amount of time.
# while waiting on the socket for this amount of time. Wall-clock time
# is not used, the thread might not run for a long time (e.g. DCC main
# thread holds the GIL while rendering) while server messages are
# waiting in the socket.
_RECV_TIMEOUT: float = 15.0
# Timeout for opening websocket connection and for the auth check request.
_CONNECT_TIMEOUT: float = 5.0
Expand Down Expand Up @@ -531,9 +534,8 @@ class _LoopState:
auth_required: bool = False
# Some message was received with current websocket connection
received_message: bool = False
# When last frame (message, ping or pong) was received
# ('time.monotonic')
last_received: float = 0.0
# Receive timeouts in a row with current websocket connection
recv_timeouts: int = 0
# Connection state reported via events
# - 'None' means unknown (nothing was reported yet)
connected: bool | None = None
Expand Down Expand Up @@ -568,10 +570,19 @@ class EventHub:
Callbacks are triggered in the websocket thread! Use own queue
to process them in main thread, especially if a callback
touches Qt widgets.
SIGPIPE is blocked in the websocket thread (see '_thread_loop').
Threads and subprocesses started from a callback inherit the
blocked signal, e.g. 'yes | head' prints 'Broken pipe' instead
of exiting quietly.

Internal topics:
- 'connection.opened' first message received after (re)connection.
- 'connection.closed' connection was lost or could not be created.
- 'connection.interrupted' connection was lost and is reconnected

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Listeners that resync on connection.closed won't see short drops anymore, core needed a follow-up for its folders cache for exactly this (also listens to connection.interrupted now). Maybe say here and in the changelog that it should be handled like closed by anything caching server data.

without reporting it as closed. Events might have been missed,
'connection.opened' is emitted once reconnected. Anything that
caches server data and resyncs on 'connection.closed' should
handle it the same way.
- 'auth.failed' server rejected the token.

Args:
Expand All @@ -581,6 +592,7 @@ class EventHub:
# Topics emitted by the hub itself
TOPIC_CONNECTION_OPENED: str = "connection.opened"
TOPIC_CONNECTION_CLOSED: str = "connection.closed"
TOPIC_CONNECTION_INTERRUPTED: str = "connection.interrupted"
TOPIC_AUTH_FAILED: str = "auth.failed"
# Topic sent by server
TOPIC_SERVER_RESTART_REQUESTED: str = "server.restart_requested"
Expand Down Expand Up @@ -941,11 +953,34 @@ def _on_connection_lost(
if stop_event.is_set():
return

reason = exc if exc is not None else "Closed by server"
# Working connection can be closed by the server when the client
# did not answer its pings (host held the GIL for a long time),
# by a proxy or a network hiccup. Report it as lost only if
# reconnecting fails. Server restart is reported right away, the
# restart overlay is hidden only by 'connection.opened'.
# Connection closed because the token was removed (logout) is
# reported as closed right away too.
if (
received_message
and not state.server_is_restarting
and self._connection.access_token
):
self._log.info(
"Websocket connection closed, reconnecting: %s", reason
)
# State is unknown until reconnected, 'connection.opened' is
# emitted on first message
with self._state_lock:
state.connected = None
self.emit_event(Event(self.TOPIC_CONNECTION_INTERRUPTED))
self._wait(stop_event, _RECONNECT_DELAYS[0])
return

# Log only first failure, reconnection attempts would spam the log
if state.connected is not False:
self._log.warning(
"Lost connection to AYON server websocket: %s",
exc if exc is not None else "Closed by server",
"Lost connection to AYON server websocket: %s", reason
)
self._set_connected(False)

Expand Down Expand Up @@ -973,6 +1008,11 @@ def _wait(self, stop_event: threading.Event, timeout: float) -> None:
wake_event.clear()

def _thread_loop(self, stop_event: threading.Event) -> None:
# Writing to a connection closed by the server raises SIGPIPE.
# Python ignores it, but some hosts reset it to the default
# action which terminates the process (e.g. Silhouette on Linux).
if hasattr(signal, "pthread_sigmask"):
signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGPIPE})

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Callbacks run in this thread, so threads and subprocesses started from a callback inherit the blocked SIGPIPE too (checked on Rocky 9: yes | head started from the hub thread prints Broken pipe instead of exiting quietly). Low risk and core does the same, maybe just a line in the Warnings of the class docstring.

try:
self._loop(stop_event)
except Exception:
Expand Down Expand Up @@ -1004,7 +1044,7 @@ def _loop(self, stop_event: threading.Event) -> None:
break
self._ws_connection = ws_con
state.received_message = False
state.last_received = time.monotonic()
state.recv_timeouts = 0
state.auth_required = True

if state.auth_required:
Expand All @@ -1023,8 +1063,8 @@ def _loop(self, stop_event: threading.Event) -> None:
try:
op_code, message = ws_con.recv_data(control_frame=True)
except WebSocketTimeoutException as exc:
elapsed = time.monotonic() - state.last_received
if elapsed >= _RECV_TIMEOUT:
state.recv_timeouts += 1
if state.recv_timeouts * _PING_INTERVAL >= _RECV_TIMEOUT:
# Server did not respond to ping
self._on_connection_lost(stop_event, exc)
continue
Expand All @@ -1040,7 +1080,7 @@ def _loop(self, stop_event: threading.Event) -> None:
self._on_connection_lost(stop_event, exc)
continue

state.last_received = time.monotonic()
state.recv_timeouts = 0
if op_code == ABNF.OPCODE_CLOSE:
self._on_connection_lost(stop_event)
continue
Expand Down
13 changes: 13 additions & 0 deletions tests/test_event_hub_lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,19 @@ def test_token_change_wakes_hub_after_auth_failure(con, sockets, hubs):
assert sockets[-1].tokens == ["token-b"]


def test_reset_token_reports_connection_closed(con, sockets, hubs):
"""Logout is reported as closed, not as interrupted connection."""
hub = con.get_event_hub()
recorder = _start_hub(hub, hubs)
assert wait_for(lambda: recorder.count(EventHub.TOPIC_CONNECTION_OPENED))

con.reset_token()

assert wait_for(lambda: recorder.count(EventHub.TOPIC_CONNECTION_CLOSED))
assert recorder.count(EventHub.TOPIC_CONNECTION_INTERRUPTED) == 0
assert hub.get_connection_state() is False


def test_stopped_hub_is_garbage_collected(sockets):
con = ServerAPI("http://server-a:0", "token-a", create_session=False)
hub = con.get_event_hub()
Expand Down
135 changes: 103 additions & 32 deletions tests/test_event_hub_ping.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,30 +12,27 @@
from ayon_api.events import EventHub

HEARTBEAT = (ABNF.OPCODE_TEXT, json.dumps({"topic": "heartbeat"}))
RESTART = (
ABNF.OPCODE_TEXT,
json.dumps({"topic": "server.restart_requested"}),
)
CLOSE = (ABNF.OPCODE_CLOSE, b"")
PONG = (ABNF.OPCODE_PONG, b"")
SERVER_PING = (ABNF.OPCODE_PING, b"")
TIMEOUT = "timeout"


class FakeClock:
def __init__(self) -> None:
self.value = 1000.0

def monotonic(self) -> float:
return self.value


class FakeWebSocket:
"""Replays scripted results of 'recv_data'.

Timeout moves the clock forward by the socket timeout as a real
socket would. When the script is exhausted the test is stopped.
When the script is exhausted the connection is closed, or the test is
stopped if this is the last connection.

"""
def __init__(self, clock, responses, stop_event) -> None:
self._clock = clock
def __init__(self, responses, stop_event, is_last) -> None:
self._responses = list(responses)
self._stop_event = stop_event
self._is_last = is_last
self.pings = 0

def send(self, data) -> None:
Expand All @@ -49,11 +46,11 @@ def abort(self) -> None:

def recv_data(self, control_frame: bool = False):
if not self._responses:
self._stop_event.set()
raise ConnectionError("End of test")
if self._is_last:
self._stop_event.set()
raise ConnectionError("End of script")
response = self._responses.pop(0)
if response == TIMEOUT:
self._clock.value += events_module._PING_INTERVAL
raise WebSocketTimeoutException("timed out")
return response

Expand All @@ -74,21 +71,32 @@ def on_event(self, event) -> None:

@pytest.fixture
def run_hub(monkeypatch):
"""Run event hub loop with scripted websocket responses."""
clock = FakeClock()
monkeypatch.setattr(events_module, "time", clock)
"""Run event hub loop with scripted websocket responses.

Each item of 'scripts' is a list of responses of one connection,
'None' means that the connection attempt fails.

"""
monkeypatch.setattr(events_module, "_RECONNECT_DELAYS", (0.0,))

def _run_hub(responses):
def _run_hub(*scripts):
stop_event = threading.Event()
fake_ws = FakeWebSocket(clock, responses, stop_event)
connections = [fake_ws]
connections = [
None if responses is None else FakeWebSocket(
responses, stop_event, idx == len(scripts) - 1
)
for idx, responses in enumerate(scripts)
]
remaining = list(connections)

def create_ws_connection():
if connections:
return connections.pop(0)
stop_event.set()
raise ConnectionError("End of test")
if not remaining:
stop_event.set()
raise ConnectionError("End of test")
ws_con = remaining.pop(0)
if ws_con is None:
raise ConnectionError("Connection refused")
return ws_con

hub = EventHub(FakeConnection())
monkeypatch.setattr(
Expand All @@ -98,7 +106,7 @@ def create_ws_connection():
recorder = EventsRecorder()
hub.add_callback("connection.*", recorder.on_event, connect=False)
hub._loop(stop_event)
return recorder.topics, fake_ws
return recorder.topics, connections

return _run_hub

Expand All @@ -111,30 +119,93 @@ def test_busy_server_without_heartbeat_is_connected(run_hub):

"""
responses = [HEARTBEAT] + [TIMEOUT, PONG] * 10
topics, fake_ws = run_hub(responses)
topics, (fake_ws,) = run_hub(responses)

assert topics == ["connection.opened"]
assert fake_ws.pings == 10


def test_server_ping_keeps_connection_alive(run_hub):
responses = [HEARTBEAT] + [TIMEOUT, TIMEOUT, SERVER_PING] * 5
topics, fake_ws = run_hub(responses)
topics, _ = run_hub(responses)

assert topics == ["connection.opened"]


def test_no_response_to_ping_is_connection_lost(run_hub):
def test_no_response_to_ping_interrupts_connection(run_hub):
"""Working connection that stopped responding is reconnected silently."""
responses = [HEARTBEAT, TIMEOUT, TIMEOUT, TIMEOUT]
topics, fake_ws = run_hub(responses)
topics, (fake_ws,) = run_hub(responses)

assert topics == ["connection.opened", "connection.closed"]
assert topics == ["connection.opened", "connection.interrupted"]
assert fake_ws.pings == 2


class StalledClock:
"""Clock jumping forward on each read, as if the GIL was held."""

def __init__(self, stall: float) -> None:
self._stall = stall
self._value = 1000.0

def monotonic(self) -> float:
self._value += self._stall
return self._value


def test_timeouts_are_counted_not_measured(run_hub, monkeypatch):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one also passes against develop's wall-clock code, so it doesn't guard the change. Jumping time.monotonic forward a few minutes on each TIMEOUT (like a GIL stall) would make the old code report closed. Patching both constants to their default values doesn't do anything either.

"""Time spent outside of socket wait does not count as silence.

Host might hold the GIL for minutes, messages waiting in the socket
are received once the thread runs again.

"""
# Wall-clock based detection would report the connection as lost
# on first timeout. Module does not import 'time' anymore.
monkeypatch.setattr(
events_module, "time", StalledClock(300.0), raising=False
)
responses = [HEARTBEAT] + [TIMEOUT, TIMEOUT, HEARTBEAT] * 5
topics, (fake_ws,) = run_hub(responses)

assert topics == ["connection.opened"]


def test_interrupted_connection_reports_opened_on_reconnect(run_hub):
topics, _ = run_hub([HEARTBEAT, CLOSE], [HEARTBEAT])

assert topics == [
"connection.opened",
"connection.interrupted",
"connection.opened",
]


def test_failed_reconnect_reports_closed(run_hub):
"""Connection is reported as lost when reconnection fails."""
topics, _ = run_hub([HEARTBEAT, CLOSE], None)

assert topics == [
"connection.opened",
"connection.interrupted",
"connection.closed",
]


def test_server_restart_reports_closed(run_hub):
"""Server restart is reported right away, not as interruption."""
topics, _ = run_hub([HEARTBEAT, RESTART, CLOSE], [HEARTBEAT])

assert topics == [
"connection.opened",
"connection.closed",
"connection.opened",
]


def test_pong_does_not_report_connected(run_hub):
"""Pong does not tell if client is authorized."""
responses = [PONG, PONG]
topics, fake_ws = run_hub(responses)
topics, _ = run_hub(responses)

assert "connection.opened" not in topics
Loading