# acefire6/phx_events ## Project Overview PHX Events (published on PyPI as phx-events) is an asynchronous Python library that sets up and manages a WebSocket connection to Phoenix Channels, the realtime communication layer of the Phoenix web framework. Targeting Python 3.9+ and built on the websockets and orjson packages, it lets Python applications subscribe to Phoenix topics, exchange channel messages, and react to server events from within an asyncio event loop. The core of the package is the PHXChannelsClient in phx_events/client.py, an async context manager that owns the WebSocket connection and its lifecycle. Applications register handlers for specific events with register_event_handler (accepting both synchronous functions and coroutine functions) and declare interest in channels with register_topic_subscription; calling start_processing runs the message loop, optionally offloading blocking sync handlers to a supplied ThreadPoolExecutor. Incoming payloads are parsed into typed representations defined in phx_events/phx_messages.py, such as ChannelMessage, PHXEventMessage, Event, and Topic, while topic_subscription.py models subscription state and handles topic registration/confirmation responses. Supporting modules round out the design: json_handler.py wraps orjson with custom serialization (including Decimal support and deep float handling), async_logger.py provides a logger that plays nicely with asyncio, exceptions.py defines the library's error types, and utils.py holds shared helpers. The client also supports sending messages back to the server, processing WebSocket traffic, and graceful shutdown. The repository is developer-oriented infrastructure rather than an application: it ships with a comprehensive pytest suite covering the client, message parsing, JSON handling, and shutdown behavior, pip-tools-managed requirements, mkdocs-based documentation, and pre-commit hooks with flake8, isort, and mypy configuration. Overall, PHX Events gives Python developers a small, typed, asyncio-first client for realtime Phoenix channel communication, with an extensible handler-registration API and robust message-processing plumbing. Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance. ## Submission Constraints (read carefully — the evaluation depends on these) This is a **closed-book** task. The graded test suite is **hidden** and will be injected into the workspace at evaluation time. To be scored correctly you MUST follow these rules: 1. **Do NOT create or modify any files under the test directories** (e.g. `tests/`, `test/`, `testing/`, or files named `test_*.py` / `conftest.py`). The grader injects its own test files at those paths; any file you place there will collide with the injected suite and cause the whole evaluation to score 0. Implement **only** the library/source code — never the tests. 2. **Your package MUST be importable by the name the tests use.** The hidden tests `import` your package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a valid `pyproject.toml` / `setup.py` / `setup.cfg` and lay out your modules so that `pip install -e .` succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0. 3. **Match the documented module paths and public API exactly** (names, signatures, and any literal error/exception strings). Internal helpers not listed in the API guide may be implemented however you like. ## Install / Reconstruction Contract Follow this contract before implementing the documented APIs: - **Project root**: `/workspace/repo` at runtime; the submitted repository root is `.`. - **Package/distribution name**: `phx-events` - **Package roots**: `.` - **Install strategy**: `editable-install` - **Import/entry**: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package. - **Provision commands**: ```bash python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2F0ZWQgaW5zdGFsbGVyIGNvbnRyb2xzIFBFUCA1MTcgYnVpbGQgZGVwZW5kZW5jaWVzIG9ubHkuIEl0IGRvZXMKICAgICMgbm90IHVwZ3JhZGUgcGlwL3NldHVwdG9vbHMgaW4gdGhlIG1lYXN1cmVkIHByb2plY3QncyBydW50aW1lIGVudmlyb25tZW50LgogICAgd2l0aCB0ZW1wZmlsZS5UZW1wb3JhcnlEaXJlY3RvcnkocHJlZml4PSdwcm9ncmFtZ2VuLWJ1aWxkLWluc3RhbGxlci0nKSBhcyBkaXJlY3Rvcnk6CiAgICAgICAgcnVubmVyID0gc3RyKFBhdGgoZGlyZWN0b3J5KSAvICdiaW4nIC8gJ3B5dGhvbicpCiAgICAgICAgZm9yIHNldHVwIGluIChbc3lzLmV4ZWN1dGFibGUsICctbScsICd2ZW52JywgZGlyZWN0b3J5XSwKICAgICAgICAgICAgICAgICAgICAgIFtydW5uZXIsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICctLW5vLWNhY2hlLWRpcicsICdwaXA9PTI1LjMnXSk6CiAgICAgICAgICAgIHJlc3VsdCA9IHJ1bihzZXR1cCkKICAgICAgICAgICAgaWYgcmVzdWx0LnJldHVybmNvZGU6CiAgICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0LnJldHVybmNvZGUKICAgICAgICBpZiBjb21tYW5kWzo0XSAhPSBbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCddIGFuZCBjb21tYW5kWzo0XSAhPSBbJ3B5dGhvbjMnLCAnLW0nLCAncGlwJywgJ2luc3RhbGwnXToKICAgICAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSB1bnN1cHBvcnRlZCBjb25zdHJhaW5lZCBpbnN0YWxsZXIgY29tbWFuZCcsIGZsdXNoPVRydWUpCiAgICAgICAgICAgIHJldHVybiAxCiAgICAgICAgdGFyZ2V0ID0gW3J1bm5lciwgJy1tJywgJ3BpcCcsICctLXB5dGhvbicsIHN5cy5leGVjdXRhYmxlLCAnaW5zdGFsbCcsCiAgICAgICAgICAgICAgICAgICctLWJ1aWxkLWNvbnN0cmFpbnQnLCBjb25zdHJhaW50XSArIGNvbW1hbmRbNDpdCiAgICAgICAgcmV0dXJuIHJ1bih0YXJnZXQpLnJldHVybmNvZGUKCmRlZiBpbnN0YWxsKGNvbW1hbmQsIHJ1bj1zdWJwcm9jZXNzLnJ1bik6CiAgICBmb3IgdmFyaWFibGUgaW4gKCdQUk9HUkFNR0VOX1JVTlRJTUVfQ09OU1RSQUlOVCcsICdQUk9HUkFNR0VOX1JVTlRJTUVfUkVQQUlSX0NPTlNUUkFJTlQnKToKICAgICAgICBydW50aW1lX2NvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCh2YXJpYWJsZSkKICAgICAgICBpZiBydW50aW1lX2NvbnN0cmFpbnQ6CiAgICAgICAgICAgIGNvbW1hbmQgPSBsaXN0KGNvbW1hbmQpICsgWyctYycsIHJ1bnRpbWVfY29uc3RyYWludF0KICAgIGNvbnN0cmFpbmVkID0gY29uc3RyYWluZWRfYnVpbGRfaW5zdGFsbChjb21tYW5kLCBydW4pCiAgICBpZiBjb25zdHJhaW5lZCBpcyBub3QgTm9uZToKICAgICAgICByZXR1cm4gY29uc3RyYWluZWQKICAgIHJlc3VsdCA9IHJ1bihjb21tYW5kLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHRleHQ9VHJ1ZSkKICAgIG91dHB1dCA9IHJlc3VsdC5zdGRvdXQgb3IgJycKICAgIHN5cy5zdGRvdXQud3JpdGUob3V0cHV0KQogICAgc3lzLnN0ZG91dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))' programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; } export -f programgen_pip_install programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel programgen_pip_install python3 -m pip install 'flit_core >=3.2,<4' ( programgen_install_report="$(mktemp)" trap 'rm -f "$programgen_install_report"' EXIT SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report" python3 -c 'exec("import json,subprocess,sys\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import canonicalize_name\nreport=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"'))\n\nrequested={canonicalize_name(name) for name in ()}\nrequirements=[]\nfor item in report.get('"'"'install'"'"', []):\n metadata=item.get('"'"'metadata'"'"', {})\n name=canonicalize_name(metadata.get('"'"'name'"'"', '"'"''"'"'))\n provided={canonicalize_name(value) for value in metadata.get('"'"'provides_extra'"'"', [])}\n selected={'"'"''"'"'} | (provided & requested)\n parsed=[Requirement(value) for value in metadata.get('"'"'requires_dist'"'"', [])]\n while True:\n added=set()\n for requirement in parsed:\n if requirement.marker is not None and not any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n continue\n if canonicalize_name(requirement.name)==name:\n if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('"'"'version'"'"', '"'"''"'"'), prereleases=True)):\n raise ValueError('"'"'local extra requires a different target distribution'"'"')\n extras={canonicalize_name(value) for value in requirement.extras}\n if not extras <= provided:\n raise ValueError('"'"'local extra refers to an undeclared extra'"'"')\n added.update(extras - selected)\n if not added:\n break\n selected.update(added)\n for requirement in parsed:\n if canonicalize_name(requirement.name)==name:\n continue\n if requirement.marker is None or any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n requirement.marker=None\n requirements.append(str(requirement))\nrequirements=list(dict.fromkeys(requirements))\nsubprocess.run([sys.executable, '"'"'-I'"'"', '"'"'/tmp/programgen-pip-compat-v1.py'"'"', sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None\n")' "$programgen_install_report" ) ``` - **Runtime setup**: ```bash { [ -e "$PWD"/README.md ] || { mkdir -p "$(dirname "$PWD"/README.md)"; : > "$PWD"/README.md; }; SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps; } ``` - **Project root for installation**: `.` - **Build-version environment**: `SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0`, `PDM_BUILD_SCM_VERSION=0.0.0`, `POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0`, `UV_DYNAMIC_VERSIONING_BYPASS=0.0.0` - **Test directory**: `tests`, `tests/test_client`, `tests/test_json_handler`, `tests/test_phx_messages` - **Test command**: `bash -lc 'set -uo pipefail run=(python3 -m pytest -vv --continue-on-collection-errors -o '"'"'addopts=-p no:hypothesispytest'"'"' tests/test_client/test_context_manager.py tests/test_client/test_event_processor.py tests/test_client/test_init.py tests/test_client/test_parse_message.py tests/test_client/test_process_topic_registration_responses.py tests/test_client/test_process_websocket_messages.py tests/test_client/test_register_event_handler.py tests/test_client/test_register_topic_subscription.py tests/test_client/test_send_message.py tests/test_client/test_shutdown.py tests/test_client/test_start_processing.py tests/test_client/test_subscribe_to_registered_topics.py tests/test_json_handler/test_decimal_serialiser.py tests/test_json_handler/test_deep_float_replace.py tests/test_json_handler/test_dumps.py tests/test_json_handler/test_loads.py tests/test_phx_messages/test_phx_event_message.py tests/test_phx_messages/test_phx_message.py tests/test_utils.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv --continue-on-collection-errors -o '"'"'addopts=-p no:hypothesispytest'"'"' tests/test_client/test_context_manager.py tests/test_client/test_event_processor.py tests/test_client/test_init.py tests/test_client/test_parse_message.py tests/test_client/test_process_topic_registration_responses.py tests/test_client/test_process_websocket_messages.py tests/test_client/test_register_event_handler.py tests/test_client/test_register_topic_subscription.py tests/test_client/test_send_message.py tests/test_client/test_shutdown.py tests/test_client/test_start_processing.py tests/test_client/test_subscribe_to_registered_topics.py tests/test_json_handler/test_decimal_serialiser.py tests/test_json_handler/test_deep_float_replace.py tests/test_json_handler/test_dumps.py tests/test_json_handler/test_loads.py tests/test_phx_messages/test_phx_event_message.py tests/test_phx_messages/test_phx_message.py tests/test_utils.py); fi collect=(python3 -m pytest -q -o '"'"'addopts=-p no:hypothesispytest'"'"' tests/test_client/test_context_manager.py tests/test_client/test_event_processor.py tests/test_client/test_init.py tests/test_client/test_parse_message.py tests/test_client/test_process_topic_registration_responses.py tests/test_client/test_process_websocket_messages.py tests/test_client/test_register_event_handler.py tests/test_client/test_register_topic_subscription.py tests/test_client/test_send_message.py tests/test_client/test_shutdown.py tests/test_client/test_start_processing.py tests/test_client/test_subscribe_to_registered_topics.py tests/test_json_handler/test_decimal_serialiser.py tests/test_json_handler/test_deep_float_replace.py tests/test_json_handler/test_dumps.py tests/test_json_handler/test_loads.py tests/test_phx_messages/test_phx_event_message.py tests/test_phx_messages/test_phx_message.py tests/test_utils.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"') fi "${run[@]}"; exit $?'` - **Test startup**: run the exact test command above from the project root after installation; hidden tests are injected separately. ## Environment & Project Structure - **Language**: python - **Build system**: python - **Test command**: `bash -lc set -uo pipefail run=(python3 -m pytest -vv --continue-on-collection-errors -o 'addopts=-p no:hypothesispytest' tests/test_client/test_context_manager.py tests/test_client/test_event_processor.py tests/test_client/test_init.py tests/test_client/test_parse_message.py tests/test_client/test_process_topic_registration_responses.py tests/test_client/test_process_websocket_messages.py tests/test_client/test_register_event_handler.py tests/test_client/test_register_topic_subscription.py tests/test_client/test_send_message.py tests/test_client/test_shutdown.py tests/test_client/test_start_processing.py tests/test_client/test_subscribe_to_registered_topics.py tests/test_json_handler/test_decimal_serialiser.py tests/test_json_handler/test_deep_float_replace.py tests/test_json_handler/test_dumps.py tests/test_json_handler/test_loads.py tests/test_phx_messages/test_phx_event_message.py tests/test_phx_messages/test_phx_message.py tests/test_utils.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv --continue-on-collection-errors -o 'addopts=-p no:hypothesispytest' tests/test_client/test_context_manager.py tests/test_client/test_event_processor.py tests/test_client/test_init.py tests/test_client/test_parse_message.py tests/test_client/test_process_topic_registration_responses.py tests/test_client/test_process_websocket_messages.py tests/test_client/test_register_event_handler.py tests/test_client/test_register_topic_subscription.py tests/test_client/test_send_message.py tests/test_client/test_shutdown.py tests/test_client/test_start_processing.py tests/test_client/test_subscribe_to_registered_topics.py tests/test_json_handler/test_decimal_serialiser.py tests/test_json_handler/test_deep_float_replace.py tests/test_json_handler/test_dumps.py tests/test_json_handler/test_loads.py tests/test_phx_messages/test_phx_event_message.py tests/test_phx_messages/test_phx_message.py tests/test_utils.py); fi collect=(python3 -m pytest -q -o 'addopts=-p no:hypothesispytest' tests/test_client/test_context_manager.py tests/test_client/test_event_processor.py tests/test_client/test_init.py tests/test_client/test_parse_message.py tests/test_client/test_process_topic_registration_responses.py tests/test_client/test_process_websocket_messages.py tests/test_client/test_register_event_handler.py tests/test_client/test_register_topic_subscription.py tests/test_client/test_send_message.py tests/test_client/test_shutdown.py tests/test_client/test_start_processing.py tests/test_client/test_subscribe_to_registered_topics.py tests/test_json_handler/test_decimal_serialiser.py tests/test_json_handler/test_deep_float_replace.py tests/test_json_handler/test_dumps.py tests/test_json_handler/test_loads.py tests/test_phx_messages/test_phx_event_message.py tests/test_phx_messages/test_phx_message.py tests/test_utils.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}') fi "${run[@]}"; exit $?` ### Project Directory Structure ``` .coveragerc .flake8 .github/actions/publish_docs/action.yml .github/dco.yml .github/dependabot.yml .github/workflows/lint_python.yml .github/workflows/lint_workflows.yml .github/workflows/publish_to_pypi.yml .github/workflows/release_docs.yml .github/workflows/run_tests.yml .gitignore .isort.cfg .pre-commit-config.yaml LICENSE NOTICE README.md docs/NAV.md docs/api.md docs/css/style.css docs/index.md docs/license.md docs/overrides/main.html mkdocs.yml mypy.ini phx_events/__init__.py phx_events/async_logger.py phx_events/client.py phx_events/exceptions.py phx_events/json_handler.py phx_events/phx_messages.py phx_events/topic_subscription.py phx_events/utils.py pyproject.toml pytest.ini requirements/core.in requirements/core.txt requirements/dev.in requirements/dev.txt requirements/dist.in requirements/dist.txt requirements/docs.in requirements/docs.txt ``` ## API Usage Guide Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely. ### Capability: JSON serialization with decimal-safe handling ## Purpose Phoenix channel payloads cross the WebSocket as JSON text, but two floating-point hazards need handling on both sides of that boundary. On **decode**, every JSON number with a decimal point arrives as a Python `float`, which can silently distort precision-sensitive values before they reach handlers. On **encode**, orjson refuses to serialize `Decimal` by default. `phx_events.json_handler` closes both gaps with a four-function pair built directly on `orjson`. ## Decoding: `loads` and `deep_float_replace` `loads(json, floats_to_decimal=True)` first delegates entirely to `orjson.loads` — there is no custom parser. orjson accepts `bytes`, `bytearray`, `memoryview`, or `str` (UTF-8 encoded); an input of any other type — a `list`, `int`, `dict` — raises orjson's `TypeError`, not a phx-events error, while `JSONDecodeError` is reserved for malformed JSON of an accepted type. The result is then optionally transformed: - **Default (`floats_to_decimal=True`)**: the parsed value is run through `deep_float_replace`, which walks the structure and converts every `float` to `Decimal(str(value))`. Going through `str` is the load-bearing detail: `Decimal(str(0.1))` yields exactly `Decimal('0.1')`, not the binary-float expansion `Decimal(0.1)` would produce. `Decimal(0.1) == Decimal('0.1')` is `False`, so tests that compare parsed output against `Decimal('...')` literals depend on this behavior. - **Opt-out (`floats_to_decimal=False`)**: the raw orjson result is returned untouched — plain `float`s, no traversal. This is the only way to get non-`Decimal` floats back from `loads`. `deep_float_replace` is a recursive, non-mutating transformer. It rebuilds any `dict` (recursing into **values** only — keys are never converted, even if a float sneaks in as a key) and any `list` (recursing into every element). Everything else is returned as-is, which means: - Nested dicts/lists at arbitrary depth are fully converted. - **Tuples and sets are not recursed into.** A tuple containing a float stays a tuple with a float inside (tuples pass through the `else` branch). This matters if upstream code builds tuples; lists are the sequence type the converter understands. - Integers, strings, booleans, `None`, and already-`Decimal` values pass through unchanged. A `Decimal` already in the tree is *not* re-processed (it isn't a float), so re-running `deep_float_replace` on converted output is idempotent. - Non-finite `float`s follow `Decimal(str(x))` semantics: `float('inf')` becomes `Decimal('Infinity')`, `nan` becomes `Decimal('NaN')` — reachable only via direct calls to `deep_float_replace`, since strict JSON parsing never yields a non-finite `float`. - The input object is never modified; a new dict/list tree is allocated. Large deep payloads pay a full-tree copy cost. ## Encoding: `dumps` and `decimal_serialiser` `dumps(obj)` is `orjson.dumps(obj, default=decimal_serialiser)` and returns **`bytes`** (orjson never returns `str`). It accepts exactly what orjson accepts — dict, list, tuple (serialized as a JSON array), str, int, float, bool, None, datetime, date, time, UUID, dataclasses, and subclasses of those. orjson serializes with `OPT_NON_STR_KEYS` **not** set, so dict keys must be strings or orjson raises `TypeError: Dict key must be str`. `decimal_serialiser` is the `default=` hook: it fires only when orjson hits an object it cannot serialize natively. If the object is a `Decimal`, it returns `float(str(_obj))` — so `Decimal('0.1')` encodes as the JSON number `0.1`, and `Decimal('1E+3')` as `1000.0`. The same rule means `Decimal('NaN')`/`Decimal('Infinity')` provide no escape hatch: they become the plain non-finite floats `float('nan')`/`float('inf')`, which orjson rejects just like native non-finite floats. Note the conversion is lossy at the text level: `Decimal('1.0000000000000000001')` becomes a double, and the JSON output is the shortest repr of that double. The `str()` round-trip exists so the *float* is constructed from the decimal's exact textual form rather than from the decimal's binary approximation. If the unserializable object is **not** a `Decimal`, `decimal_serialiser` raises a bare `TypeError` (no message). Practical consequences: - Any custom type (arbitrary objects, sets, custom classes) fails encoding with a plain `TypeError` — there is no fallback serialization path. Wrap or convert before calling `dumps`. - orjson's `default` hook only rescues `Decimal`; natively-serializable types never reach it, so `int`/`float` fields are untouched and never converted. ## How the halves compose The two directions are intentionally asymmetric. Encoding converts `Decimal → float` (orjson then renders the float); decoding converts `float → Decimal`. A `Decimal('0.1')` round-trips as `Decimal('0.1')` because each conversion routes through the decimal's string representation, and 0.1's shortest repr is `0.1`. Values whose decimal text is longer than a double's precision (e.g. `Decimal('1.0000000000000000001')`) do **not** survive a round-trip exactly — the encode step collapses them to double precision first. In the client's lifecycle, `loads` parses every inbound frame before event handlers run, so handlers see `Decimal` for any JSON fractional number by default; `dumps` serializes outbound `ChannelMessage` payload trees, where a `Decimal` anywhere in the payload is valid (barring non-finite values) and any other exotic type is not. ## Defaults, ordering, and edge-case summary - `floats_to_decimal=True` is the default; conversion is opt-out per call, never global. - Conversion order on decode is *parse fully, then transform* — a malformed JSON document fails before any float conversion happens. - Non-finite values fail on both sides of orjson's strict JSON contract. On decode, `NaN`/`Infinity` tokens are not valid JSON — orjson parses strict JSON only, so `loads` raises `JSONDecodeError` rather than yielding a non-finite `float` for `deep_float_replace`. On encode, orjson **rejects** serializing non-finite floats, and supplying them as `Decimal` does not help: `decimal_serialiser` converts `Decimal('NaN')`/`Decimal('Infinity')` to `float('nan')`/`float('inf')`, which orjson rejects identically — only a string (or omitting the value) avoids the error. - Errors on decode split two ways: orjson's `TypeError` for an input whose type is outside `bytes`/`bytearray`/`memoryview`/`str`, orjson's `JSONDecodeError` for malformed JSON of an accepted type. On encode, errors surface as `TypeError` with or without a message depending on whether it originates in `decimal_serialiser` or a str-key violation. - Both `dumps` and `decimal_serialiser` are thread-safe pure functions: no shared state, no I/O, no logging. #### Exact API Reference #### `phx_events.json_handler.decimal_serialiser` - **Import Path**: `from phx_events.json_handler import decimal_serialiser` - **Required Test Import Paths**: - phx_events.json_handler.decimal_serialiser - **Exact Test Import Statements**: - from phx_events import json_handler - **Kind**: function - **Signature**: ```python def decimal_serialiser(_obj: Any) -> float ``` #### `phx_events.json_handler.deep_float_replace` - **Import Path**: `from phx_events.json_handler import deep_float_replace` - **Required Test Import Paths**: - phx_events.json_handler.deep_float_replace - **Exact Test Import Statements**: - from phx_events import json_handler - **Kind**: function - **Signature**: ```python def deep_float_replace(obj: Any) -> Any ``` #### `phx_events.json_handler.dumps` - **Import Path**: `from phx_events.json_handler import dumps` - **Required Test Import Paths**: - phx_events.json_handler.dumps - **Exact Test Import Statements**: - from phx_events import json_handler - **Kind**: function - **Signature**: ```python def dumps(obj: Any) -> bytes ``` #### `phx_events.json_handler.loads` - **Import Path**: `from phx_events.json_handler import loads` - **Required Test Import Paths**: - phx_events.json_handler.loads - **Exact Test Import Statements**: - from phx_events import json_handler - **Kind**: function - **Signature**: ```python def loads(json: Union[bytes, bytearray, memoryview, str], floats_to_decimal: bool=True) -> Any ``` ### Capability: Phoenix message model and construction # Phoenix message model and construction This capability turns raw Phoenix channel traffic — a topic string, an event name, a ref, and a JSON payload — into typed, immutable Python values, and gives callers a deterministic way to build outgoing messages and refs. Everything else in the client (handler dispatch, topic subscription confirmation, reply correlation) keys off the distinctions these helpers establish, so getting the classification rules right is what makes the rest of the protocol behave. ## The data model `Topic` and `Event` are `typing.NewType` aliases over `str`. They exist for type checking only: no runtime conversion or validation happens, and any `str` is accepted wherever a `Topic` or `Event` is expected. `ChannelEvent` is `Union[PHXEvent, Event]` and `ChannelMessage` is `Union[PHXMessage, PHXEventMessage]`. `BasePHXMessage` is a frozen dataclass carrying `topic`, `ref`, and `payload`. Its `subtopic` cached property splits the topic on the *first* colon: `'game:1'` yields `'1'`, `'a:b:c'` yields `'b:c'`, and any topic without a colon (including an empty one) yields `None`. The value is computed once and stored in the instance `__dict__` on first access — `cached_property` writes there directly, which is how it coexists with the frozen dataclass — so repeated access returns the identical string without recomputation. `PHXMessage` adds `event: Event` (an arbitrary, unclassified string), while `PHXEventMessage` adds `event: PHXEvent`. `PHXEvent` is a `@unique` enum with exactly five members whose values are the lowercase Phoenix admin events: `phx_close`, `phx_error`, `phx_join`, `phx_reply`, `phx_leave`. Its `__str__` returns `self.value`, so string interpolation produces `'phx_reply'`, never `'PHXEvent.reply'`. Because both message classes are frozen, they get generated `__eq__` and `__hash__`. Equality is class-sensitive: a `PHXMessage` never equals a `PHXEventMessage` even when every field matches, and within the same class the generated comparison covers all declared fields — `topic`, `ref`, `payload`, and `event` — so two `PHXMessage` values with identical topic/ref/payload but different event strings are not equal. Hashing raises `TypeError` whenever the payload is a dict — effectively always, since `payload=None` becomes a fresh `{}` — independent of what that dict contains, so messages are not usable as dict keys or set members. ## Construction pipeline `make_message` is the single construction entry point and runs three ordered steps: 1. **Payload defaulting.** A `payload` of `None` becomes a fresh `{}` — a new dict per call, never a shared mutable default, and never `None` on the resulting message. A payload dict you supply is stored as-is with no defensive copy (`msg.payload is payload`), so mutating the caller's dict after construction is visible through the message. 2. **Event classification.** The `event` argument is normalized through `parse_event` exactly once. 3. **Class selection.** If the processed event is a `PHXEvent` member, a `PHXEventMessage` is built; otherwise a `PHXMessage` is built with the event left exactly as passed — unknown strings, empty strings, and odd casing are never rejected or rewritten. `ref` is passed through verbatim in every case. `make_message` does **not** auto-generate a ref when it is `None`; the constructed message simply carries `ref=None`. Call `generate_reference` explicitly when a ref is needed. `parse_event` attempts `PHXEvent(event)` and catches only `ValueError`, returning the original object unchanged when the string does not match a member. It is idempotent: passing an existing `PHXEvent` member returns that member. Matching is by enum *value*, so only the five exact lowercase `'phx_*'` strings classify — `'PHX_JOIN'` or `'join'` stays a plain event. The discriminator throughout the library is therefore `isinstance(processed_event, PHXEvent)`, and the function itself never raises for unknown strings (only `ValueError` is swallowed; other exceptions propagate). `generate_reference` formats the current wall-clock time as `'%Y%m%d%H%M%S'`, appends a colon, then the event via `str()`: for an enum member that is its value (`'20240101120000:phx_reply'`), for a plain event the raw string (`'20240101120000:game:update'`). Two calls within the same second produce **identical** refs — uniqueness is not guaranteed by the helper and rests on how callers use it. The timestamp is local time with no timezone marker. ## How this shows up in client workflows - **Inbound:** incoming frames are parsed into `ChannelMessage` objects; lifecycle handling checks for `PHXEvent.reply`, `PHXEvent.join`, etc., so a message whose event string failed to classify silently becomes a plain `PHXMessage` and will not match admin-event logic. - **Outbound:** the client composes join/leave traffic and stamps refs with `generate_reference`; the server echoes the ref in `phx_reply` messages, which is how replies are correlated back to requests. - **Handlers:** registered handlers receive a `ChannelMessage`; branch with `isinstance(msg, PHXEventMessage)` (or `isinstance(msg.event, PHXEvent)`) to separate Phoenix lifecycle events from application topic data. ## Test-sensitive edge cases - `payload=None` ⇒ `{}`; a `ref=None` stays `None`; no argument is coerced beyond the event. - A supplied payload dict is stored by reference, not copied; only the `None` default yields a fresh `{}` per call. - `make_message` performs no topic validation and no ref generation — both pass through untouched. - `subtopic` is `None` for colon-free topics and returns everything after the first colon otherwise. - `parse_event` returns the *same object* (not a copy) for unclassifiable input, and the same member for already-classified input. - Ref strings from `generate_reference` embed the event verbatim after the colon, so plain-event refs may themselves contain colons; only `subtopic` (on topics) applies first-colon splitting, never refs. - Members are constructed by value: `PHXEvent('phx_reply')` succeeds; `PHXEvent('reply')` raises `ValueError`. - Same-class equality includes `event`: two messages differing only in their event strings are not equal, and hashing fails for any dict payload. #### Exact API Reference #### `phx_events.utils.parse_event` - **Import Path**: `from phx_events.utils import parse_event` - **Required Test Import Paths**: - phx_events.utils.parse_event - **Exact Test Import Statements**: - from phx_events import utils - **Kind**: function - **Signature**: ```python def parse_event(event: ChannelEvent) -> ChannelEvent ``` #### `phx_events.utils.make_message` - **Import Path**: `from phx_events.utils import make_message` - **Required Test Import Paths**: - phx_events.utils.make_message - **Exact Test Import Statements**: - from phx_events import utils - from phx_events.utils import make_message - **Kind**: function - **Signature**: ```python def make_message(event: ChannelEvent, topic: Topic, ref: Optional[str]=None, payload: Optional[dict[str, Any]]=None) -> ChannelMessage ``` #### `phx_events.utils.generate_reference` - **Import Path**: `from phx_events.utils import generate_reference` - **Required Test Import Paths**: - phx_events.utils.generate_reference - **Exact Test Import Statements**: - from phx_events import utils - **Kind**: function - **Signature**: ```python def generate_reference(event: ChannelEvent) -> str ``` ### Capability: Asynchronous queue-based logging # Asynchronous queue-based logging ## Purpose `phx_events.async_logger` keeps log-record emission off the asyncio event-loop thread. Instead of formatting and writing a record inline (disk flushes, stderr writes, and third-party handlers can all block the loop), the emitting thread only performs a non-blocking enqueue onto an unbounded `queue.SimpleQueue`; a background `QueueListener` thread pulls records off that queue and dispatches them to the real handlers. The result: a coroutine that logs never stalls on I/O, and slow handlers cannot delay WebSocket message processing. ## Components and how they relate - `LocalQueueHandler` is a `QueueHandler` whose `emit` enqueues the record. It is deliberately asyncio-aware: an `asyncio.CancelledError` raised during enqueue is re-raised (cancellation must propagate to the awaiting coroutine, not be swallowed or silently logged), while any other enqueue failure is routed to `self.handleError(record)` — the standard logging failure path, which honors `logging.raiseExceptions` rather than letting the exception escape into application code. - `setup_queue_logging()` wires everything and returns `(logging.Logger, QueueListener)`: 1. Creates an unbounded `SimpleQueue` (so `enqueue`/`put` never blocks or raises on a full queue). 2. Gets the logger named `phx_events.async_logger` (its `__name__`). Despite the docstring saying "root logger", the handler reshuffling happens on this module logger, not the root. 3. Builds a fallback handler list starting with `logging.lastResort` (when it is not `None`), so records still reach stderr if the application never configured logging. `lastResort` behaves as a `WARNING`-level stderr handler, so an unconfigured app shows only WARNING+ records. 4. Attaches a fresh `LocalQueueHandler(queue)` to that logger, then moves pre-attached handlers: each is removed from the logger and appended to the listener's handler list (they come after `lastResort` in dispatch order). The transfer loop iterates the logger's handler list while removing from it, so this holds only for zero or one pre-attached handler; with two or more, every second handler is skipped — it stays attached to the logger (firing inline) and never reaches the listener. Re-invocation is unaffected, since the only pre-attached handler is then the single previous `LocalQueueHandler`. 5. Starts `QueueListener(queue, *handlers, respect_handler_level=True)` and returns the running listener. Because `respect_handler_level=True`, each moved handler applies its own level and formatter exactly as before — only the thread on which it runs changes. - At module import time the library executes `async_logger, queue_listener = setup_queue_logging()`. Importing `phx_events.async_logger` therefore has a side effect: a daemon listener thread is already running, and `async_logger` is the queue-feeding logger. `async_logger` must be importable as a module attribute (`from phx_events.async_logger import async_logger`). ## Realistic workflow The client imports the pre-built `async_logger` and derives per-instance loggers from it: `self.logger = async_logger.getChild(__name__)`. Child loggers propagate by default, so a record logged as `phx_events.async_logger.phx_events.client` bubbles up to the `phx_events.async_logger` logger, whose only handler is the `LocalQueueHandler`; the client logger's parent is asserted to be `async_logger` in the test suite. Applications should do the same (`async_logger.getChild("myapp")`) rather than attaching handlers to the client logger, which would run those handlers inline on the emitting thread. Typical sequence: 1. Before import (optional): attach real handlers to the `phx_events.async_logger` logger — or rely on `lastResort`; only handlers attached before import are transferred into the listener. After import, a handler added directly to `async_logger` fires inline on the emitting thread (records also still pass through `LocalQueueHandler`) — post-import handlers must go on the listener's handler tuple (`queue_listener.handlers`; rebind it, don't append). 2. Log anywhere, including inside coroutines and sync handlers offloaded to the client's `ThreadPoolExecutor`: the call is just a queue put — but only for records above the effective level (NOTSET inherits root's `WARNING` default). 3. At shutdown, call `queue_listener.stop()`: the listener drains the remaining queued records through the handlers and joins its thread. ## Ordering, state changes, and edge cases - **Ordering:** `SimpleQueue` is FIFO, so consumers observe records in emission order per process — but emission (formatting, I/O) happens later, on the listener thread. Timestamps in records, not log-call wall-clock, are preserved. - **State changes:** with zero or one handler pre-attached, those handlers are *removed* from the `phx_events.async_logger` logger and fire only via the listener; the logger itself keeps the single `LocalQueueHandler`. With two or more pre-attached, every second handler is skipped and left attached (firing inline). - **Shutdown:** records logged after `listener.stop()` (or if the listener thread dies) sit in the queue unconsumed — the queue is unbounded, so this is memory growth, not backpressure. Stop the listener only when logging is complete. - **Re-invocation:** `setup_queue_logging()` is intended to run once. Calling it again builds a second queue and listener thread and moves the previous `LocalQueueHandler` into the new listener; records can then be duplicated or stranded. Prefer the import-time `async_logger`/`queue_listener` pair. - **Failure containment:** handler exceptions inside the listener are contained by `QueueListener`/`handleError`; the logging call site is unaffected. Only cancellation is deliberately re-raised. - **Levels:** `setup_queue_logging()` never sets a level, so `async_logger` and every `getChild`-derived child are `NOTSET` and inherit their effective level from the root logger — `WARNING` by default. INFO/DEBUG calls are dropped at the logger-level check and never enqueued, regardless of downstream handler levels, unless you raise the level first (e.g. `async_logger.setLevel(logging.DEBUG)` or `logging.basicConfig(level=...)`) or log at WARNING+. The `LocalQueueHandler` itself has no level, so any record that reaches it is queued; remaining filtering is left to each downstream handler (`respect_handler_level=True`). - **Test-sensitive details:** logger name string `phx_events.async_logger`; client child logger names of the form `phx_events.async_logger.phx_events.client`; `client.logger.parent` identity; and the `async_logger`/`queue_listener` module attributes existing immediately after import. #### Exact API Reference #### `phx_events.async_logger.LocalQueueHandler` - **Import Path**: `from phx_events.async_logger import LocalQueueHandler` - **Signature**: ```python class LocalQueueHandler(QueueHandler): def emit(self, record: logging.LogRecord) -> None ``` #### `phx_events.async_logger.setup_queue_logging` - **Import Path**: `from phx_events.async_logger import setup_queue_logging` - **Signature**: ```python def setup_queue_logging() -> tuple[logging.Logger, QueueListener] ``` - **Behavior**: Move log handlers to a separate thread. #### `phx_events.async_logger.async_logger` - **Import Path**: `from phx_events.async_logger import async_logger` - **Required Test Import Paths**: - phx_events.async_logger.async_logger - **Exact Test Import Statements**: - from phx_events.async_logger import async_logger - **Kind**: module - **Behavior**: Module required during hidden-test collection. ### Capability: Topic subscription tracking and join replies ## Topic subscription tracking and join replies ### Purpose and data model Phoenix channels require an explicit join handshake per topic: the client sends a `phx_join` message and the server answers with a `phx_reply` whose payload carries the join outcome. This capability is the client-side bookkeeping that ties that asynchronous reply back to the coroutine that asked to join. Three small types carry the state: - `TopicRegistration` is the mutable, per-topic envelope the client stores. It always has a `status_updated_event: asyncio.Event`; `connection_ref: Optional[str]` records which connection the registration was made against, and `result: Optional[TopicSubscribeResult]` starts as `None`. - `TopicSubscribeResult` is the frozen, immutable outcome pair: a `status` plus the raw `result_message` (`PHXEventMessage`) that produced it, so the application can still inspect the full reply (topic, ref, payload) behind the status. - `SubscriptionStatus` is a `@unique` `IntEnum` with `FAILED = 0` and `SUCCESS = 1`. ### Registration workflow `register_topic_subscription(topic)` is synchronous and never touches the network. It checks the client's per-topic registry, allocates a fresh `TopicRegistration` (event unset, `result=None`, `connection_ref` bound to the current connection id), stores it keyed by the `Topic`, and queues the join message for transmission. It returns the registration immediately, so it is safe — and expected — to call it before `start_processing` begins draining the queues. Registering a `Topic` that already has a registration raises `PHXTopicTooManyRegistrationsError` (a `PHXClientError`) synchronously, before any state is mutated: the original `TopicRegistration` stays the single source of truth for that topic and a duplicate attempt leaves the client unchanged. Keep the returned registration; there is no lookup API that hands it back later. ### Join-reply processing and state transition While `start_processing` runs its message loop, every incoming `phx_reply` whose topic matches a stored `TopicRegistration` resolves the join outcome: payload status `'ok'` maps to `SubscriptionStatus.SUCCESS`; any other status maps to `SubscriptionStatus.FAILED`. The loop then builds `TopicSubscribeResult(status, reply)`, assigns it to `registration.result`, and sets `status_updated_event` — in that order. Because the result is in place before the event fires, code waking from `await registration.status_updated_event.wait()` can read `registration.result` without re-checking. The event stays set afterwards, and since `asyncio.Event` supports many waiters, any number of coroutines can await one registration concurrently. A failed join does not remove the registration or trigger a retry: the registration keeps `result.status == SubscriptionStatus.FAILED` and remains in the registry, so the application decides how to react — the client will not silently re-join for you. ### Ordering and synchronization constraints - Register before the reply can arrive; waiting on `status_updated_event` is only meaningful while the message loop runs. Awaiting it with no running loop blocks forever, because nothing will ever set the event. - `result` is `None` until the reply is processed; treat "event set" as the precondition for reading it. - The join `phx_reply` is matched by topic equality, not by message ref, so exactly one reply resolves exactly the registration for that topic. ### Edge cases and test-sensitive details - `SubscriptionStatus` values are plain ints (`0`/`1`), so `SUCCESS` is truthy and `FAILED` is falsy; tests compare enum identity/equality, so do not branch on truthiness. - `TopicSubscribeResult` is `frozen=True`: mutating it raises `FrozenInstanceError`, and dataclass equality compares `status` and `result_message` field by field. `TopicRegistration` is a plain mutable dataclass with defaults `connection_ref=None`, `result=None`; only `status_updated_event` is required. - `PHXTopicTooManyRegistrationsError` subclasses `PHXClientError`, so a broad `except PHXClientError` also catches it; assertions normally target the specific subclass, and it is raised from the registration call site, not from the message loop. #### Exact API Reference #### `phx_events.topic_subscription.SubscriptionStatus` - **Import Path**: `from phx_events.topic_subscription import SubscriptionStatus` - **Required Test Import Paths**: - phx_events.topic_subscription.SubscriptionStatus - **Exact Test Import Statements**: - from phx_events.topic_subscription import SubscriptionStatus - **Kind**: class - **Signature**: ```python class SubscriptionStatus(IntEnum): FAILED: SubscriptionStatus SUCCESS: SubscriptionStatus ``` #### `phx_events.exceptions.PHXTopicTooManyRegistrationsError` - **Import Path**: `from phx_events.exceptions import PHXTopicTooManyRegistrationsError` - **Required Test Import Paths**: - phx_events.exceptions.PHXTopicTooManyRegistrationsError - **Exact Test Import Statements**: - from phx_events.exceptions import PHXTopicTooManyRegistrationsError - **Kind**: exception - **Signature**: ```python class PHXTopicTooManyRegistrationsError(PHXClientError) ``` ### Capability: Event handler registration and dispatch # Event handler registration and dispatch **Purpose.** `register_event_handler` binds handler callables to Phoenix channel events so that, once the client is running, every matching inbound message is fanned out to those callables. Each event gets exactly one `EventHandlerConfig` - an unbounded `asyncio.Queue`, a `default_handlers` list, a `topic_handlers` mapping, and one long-lived processor task (`EventHandlerConfig.task`) built from `_event_processor` that drains the queue and dispatches. **Registration semantics.** The first call for an event creates the config and immediately spawns the processor task via `self._loop.create_task(self._event_processor(event))`; registration therefore must happen while the client's loop is running - inside the `async with` block is the intended place. Registering before the block either fails outright or leaves the processor task scheduled on a loop that never runs, so that event's queue is never drained and `start_processing` appears to hang for it. Later calls for the same event reuse the config and append: with `topic=None` handlers land in `default_handlers`; with a `Topic` they are extended onto `topic_handlers.setdefault(topic, [])`. Appending means registering the same callable twice makes it run twice. Topic dispatch is exact `Topic` string equality against `message.topic` - there is no wildcard or subtopic matching, so a handler registered for `rooms:lobby` never sees `rooms:kitchen`. **Start gating.** Every processor task begins with `await self._client_start_event.wait()`. That event is only set inside `start_processing`, after the executor pool is created and topic join messages are sent. Consequences: handlers registered before connecting cannot process anything early; sync handlers always find `self._executor_pool` populated (default `ThreadPoolExecutor()` when none is supplied); messages already sitting in a queue simply wait. **Message flow and ordering.** `process_websocket_messages` parses each frame and looks up the config by the parsed event. `phx_close`/`phx_error` frames raise `TopicClosedError` before any dispatch, and that raise is not contained: it propagates out of `process_websocket_messages`, ending frame processing - no further frames are read or dispatched, and it is not swallowed-and-logged the way handler exceptions are (gotcha 3). The per-`PHXEvent` dispatch outcomes follow directly: handlers registered for `PHXEvent.close` or `PHXEvent.error` can never execute because the raise happens first; `PHXEvent.reply` frames dispatch normally, and for topics with pending registrations they are additionally pushed into `_registration_queue`, so reply handlers and topic-registration processing both observe the frame; `PHXEvent.join` and `PHXEvent.leave` frames go through normal dispatch. If no config exists for the event, the message is dropped with a debug log; nothing is buffered for handlers registered later. Queues are FIFO and unbounded: `await queue.put(...)` never blocks, and the processor fully completes one message's handlers before dequeuing the next, so per-event ordering is preserved while handlers for a single message run concurrently. **Fan-out.** Per message the handler list is `default_handlers.copy()` plus `topic_handlers.get(message.topic, [])` - defaults always run, topic handlers only for that exact topic. Coroutine handlers (detected with `inspect.iscoroutinefunction`) become loop tasks; everything else is run as `partial(handler, message, self)` on the executor pool. All handlers receive `(message, client)`. **Failure isolation.** Handler results are consumed through `asyncio.as_completed`, and each awaited future is wrapped in `try/except Exception` that logs `Error executing handler - {exception=}` via `logger.exception`. One failing handler never prevents sibling handlers or subsequent messages; only a `BaseException` (e.g. `CancelledError`) escapes. A message matching zero handlers is still acknowledged with `queue.task_done()`. **Shutdown.** `shutdown` cancels every config's `task` (and the topic-registration task) whether or not processing ever started, so registered-but-unused events do not leak tasks. SIGTERM/SIGINT handlers installed by `start_processing` route through the same path. **Test-sensitive gotchas.** 1. Admin frames parse to `PHXEventMessage`, whose `event` is a `PHXEvent` enum member (values `'phx_close'`, `'phx_error'`, `'phx_join'`, `'phx_reply'`, `'phx_leave'`); registering with the raw string `'phx_reply'` will not match `PHXEvent.reply` because enum equality is identity-based - use the enum for `phx_*` events and `Event('...')` strings for custom events. Members do stringify to their `'phx_*'` value, but dispatch compares the member, not the string. Note the outcomes: `PHXEvent.close`/`PHXEvent.error` handlers never fire, while `PHXEvent.join`/`PHXEvent.leave`/`PHXEvent.reply` handlers fire normally. 2. The processor reads `self._event_handler_config[event]` once after the start gate; the config object is shared, so handlers appended after startup (from within the `async with` block) are picked up, and an event first registered after startup works too because its task was created at registration time. 3. Handler exceptions are logged, never propagated to the caller of `start_processing`; the `TopicClosedError` raised for `phx_close`/`phx_error` is the opposite - it escapes the message-processing loop instead of being logged and continued. 4. Registration appends rather than replaces; tests asserting call counts must account for repeated registration. 5. Register handlers inside `async with client:`, as the example below does. Registration placed above the block spawns the processor task where the client's loop is not running, leaving that event's queue silently undrained. **Usage.** ```python from phx_events.client import PHXChannelsClient from phx_events.phx_messages import Event, PHXEvent, Topic def audit(message, client): # runs in the executor pool client.logger.info(f'{message.event} on {message.topic}') async def react(message, client): # runs as a loop task await handle(message.topic, message.payload) client = PHXChannelsClient('ws://host/socket/websocket') async with client: # client loop running - register here client.register_event_handler(Event('ping'), [audit, react]) client.register_event_handler(PHXEvent.reply, [audit], topic=Topic('rooms:lobby')) client.register_topic_subscription(Topic('rooms:lobby')) await client.start_processing() # unblocks all processors ``` #### Exact API Reference #### `phx_events.phx_messages.EventHandlerConfig` - **Import Path**: `from phx_events.phx_messages import EventHandlerConfig` - **Required Test Import Paths**: - phx_events.phx_messages.EventHandlerConfig - **Exact Test Import Statements**: - from phx_events.phx_messages import EventHandlerConfig - **Kind**: class - **Signature**: ```python class EventHandlerConfig: queue: asyncio.Queue[ChannelMessage] default_handlers: list[ChannelHandlerFunction] topic_handlers: dict[Topic, list[ChannelHandlerFunction]] task: asyncio.Task[None] ``` - **Behavior**: Args: ### Capability: WebSocket connection and message pump ## Purpose and shape The connection-and-pump capability is the runtime core of `PHXChannelsClient`: it opens one WebSocket to a Phoenix Channels endpoint, serializes and sends the join frames your subscriptions imply, converts every incoming frame into a typed message, and routes each message either into topic-registration bookkeeping or into per-event handler queues. Everything else in the library (handlers, subscriptions, logging) consumes from queues this loop feeds. ## Connection setup `PHXChannelsClient(channel_socket_url, channel_auth_token=None, event_loop=None)` stores the URL and, when a token is given, appends `?token=` at construction time. The event loop defaults to `asyncio.get_event_loop()`. Construction opens nothing: registration state starts empty and the `_client_start_event` gate is unset, so no processing can begin until `start_processing` runs. ## Ordering inside start_processing `await client.start_processing(executor_pool=None)` performs a fixed sequence: 1. Bail out if `_topic_registration_status` is empty — it logs an error and returns without touching the network, so tests can assert no connection is attempted. 2. Adopt the supplied executor or create a `ThreadPoolExecutor` and enter it as a context manager. 3. `websockets.client.connect(self.channel_socket_url)` — the single connection for the client's lifetime. 4. Install SIGTERM/SIGINT loop signal handlers that call `shutdown(..., wait_for_completion=False)` with the live websocket and pool. 5. `_subscribe_to_registered_topics`: spawn `process_topic_registration_responses` as `_topic_registration_task`; build one `make_message(event=PHXEvent.join, topic=topic)` per registration, recording the join message's `ref` as that topic's `connection_ref`; then send all join frames concurrently (`asyncio.gather` over `partial(_send_message, websocket)`). 6. Set `_client_start_event`, unblocking event workers, then block in `process_websocket_messages`. Because step 6 happens after the joins are sent, a fast server reply is already queued for the registration consumer before any event handler can run — the reply path does not depend on handler workers being awake. ## Frame pump semantics `process_websocket_messages` iterates `async for socket_message in websocket`. Each frame goes through `_parse_message`: `json_handler.loads` (orjson) then `make_message(**message_dict)`, so an event string matching a `PHXEvent` value (`phx_close`, `phx_error`, `phx_join`, `phx_reply`, `phx_leave`) yields a frozen `PHXEventMessage`, while any other event string stays a plain `str` on `PHXMessage` via `parse_event`'s fallback. Every parsed message — `PHXMessage` or `PHXEventMessage` — also exposes `message.subtopic`: `None` when the topic contains no ':', otherwise the text after the first ':' only (`Topic('game:abc')` → `'abc'`; `'a:b:c'` → `'b:c'`). This is a cached derived field on the otherwise frozen message objects, computed lazily once per message instance, so handlers always receive this precomputed value and colon-less topics silently yield `None` rather than the full topic string. Per frame, in order: - `PHXEvent.close` → `raise TopicClosedError(topic=..., reason='Upstream closed')`. - `PHXEvent.error` → `raise TopicClosedError(topic=..., reason='Upstream error')`. Both exceptions propagate out of the pump and `start_processing`, ending the connection rather than being logged away. - Reply interception: only when the topic is registered, the event is `PHXEvent.reply`, and the topic's `status_updated_event` is not yet set is the message put on `_registration_queue`. The consumer maps `payload['status'] == 'ok'` to `SubscriptionStatus.SUCCESS` (anything else `FAILED`), stores a `TopicSubscribeResult`, sets the event to wake awaiting coroutines, and calls `task_done`. The `is_set()` guard means exactly one reply per topic is consumed this way; later replies fall through to normal dispatch. - Dispatch: `_event_handler_config.get(event)`; a missing config drops the message with a debug log (`no event handlers registered`) — never an error. Otherwise the message is awaited onto that event's queue. ## Worker behavior Each registered event owns an `EventHandlerConfig` whose task runs `_event_processor`: wait for `_client_start_event`, then loop over `queue.get()`. The handler set is `default_handlers.copy()` plus `topic_handlers.get(message.topic, [])` — a topic handler never suppresses a default one. Coroutine handlers become `self._loop.create_task(handler(message, client))`; sync handlers run through `self._loop.run_in_executor(self._executor_pool, partial(handler, message, client))`. All run concurrently via `asyncio.as_completed`, and any `Exception` a handler raises is logged (`logger.exception`) and swallowed, so one bad handler cannot kill the worker; `queue.task_done()` runs after every batch. ## Shutdown and edge cases `__aexit__` calls `shutdown('Leaving PHXChannelsClient context')`; the signal handlers call it with the live websocket. `shutdown` cancels the registration task and every worker task, schedules `websocket.close()` via `create_task`, and shuts the pool down with `wait=wait_for_completion, cancel_futures=not wait_for_completion` (defaults `True`/`False`). Non-obvious details: `make_message` without a `ref` leaves it `None`, so recorded `connection_ref` values are `None` unless a ref is supplied; `str(PHXEvent.close)` is `'phx_close'`, the wire value rather than the enum name; and registering the same topic twice raises `PHXTopicTooManyRegistrationsError` before any connection exists. #### Exact API Reference #### `phx_events.phx_messages.PHXEvent` - **Import Path**: `from phx_events.phx_messages import PHXEvent` - **Required Test Import Paths**: - phx_events.phx_messages.PHXEvent - **Exact Test Import Statements**: - from phx_events.phx_messages import Event, PHXEvent, PHXEventMessage, PHXMessage - from phx_events.phx_messages import Event, PHXEvent, Topic - from phx_events.phx_messages import PHXEvent, PHXEventMessage, PHXMessage - from phx_events.phx_messages import PHXEvent, PHXEventMessage, Topic - from phx_events.phx_messages import PHXEvent, Topic - **Kind**: class - **Signature**: ```python class PHXEvent(Enum): close: PHXEvent error: PHXEvent join: PHXEvent reply: PHXEvent leave: PHXEvent value: str def __str__(self) -> str ``` - **Behavior**: Phoenix Channels admin events #### `phx_events.phx_messages.Event` - **Import Path**: `from phx_events.phx_messages import Event` - **Required Test Import Paths**: - phx_events.phx_messages.Event - **Exact Test Import Statements**: - from phx_events.phx_messages import ChannelMessage, Event, Topic - from phx_events.phx_messages import Event, PHXEvent, PHXEventMessage, PHXMessage - from phx_events.phx_messages import Event, PHXEvent, Topic - from phx_events.phx_messages import Event, PHXMessage, Topic - from phx_events.phx_messages import Event, Topic - **Kind**: constant - **Signature**: ```python Event: Any ``` - **Behavior**: Module-level value required by the test import contract. ### Capability: Upstream error and topic closure handling ## Purpose Phoenix servers signal channel-level shutdown with two admin events: `phx_close` (the channel closed) and `phx_error` (an error occurred in the Elixir process). This capability converts those frames into a typed Python failure — `TopicClosedError(topic, reason)` — raised out of the message pump, so callers of `start_processing` observe channel shutdown instead of the frames being silently dropped. ## Where detection happens `process_websocket_messages` is the only consumer of the websocket iterator. Each incoming frame is parsed by `_parse_message` (orjson decode plus `make_message`) into a frozen `PHXEventMessage` whose `event` field is the `PHXEvent` enum (`close = 'phx_close'`, `error = 'phx_error'`). Detection is a two-branch check on that enum, evaluated per frame: 1. `event == PHXEvent.close` → log at INFO (`'Got Phoenix event {event} shutting down - {phx_message=}'`), then `raise TopicClosedError(topic=phx_message.topic, reason='Upstream closed')`. 2. `event == PHXEvent.error` → log at ERROR, then `raise TopicClosedError(topic=phx_message.topic, reason='Upstream error')`. Both reason strings are hardcoded literals. The server's payload — which in Phoenix may carry its own reason — is discarded; only `phx_message.topic` is carried into the exception. ## Ordering and what is skipped The close/error check runs before everything else in the loop body: - before the registration-queue push (which forwards only `phx_reply` frames for topics present in `_topic_registration_status` whose status event is not yet set), and - before per-event handler dispatch. Consequences: - A `phx_close`/`phx_error` frame is never routed to the queues backing `register_event_handler`. The raise preempts dispatch, so handlers registered for those events are unreachable in practice. - There is no filtering against `_topic_registration_status`: the raise applies to any topic, registered or not. - Non-admin events (`phx_join`, `phx_reply`, `phx_leave`, custom events) flow through unchanged. The `close` branch precedes the `error` branch, though only one event can match per frame. ## Exception shape and test-sensitive details `TopicClosedError` subclasses `PHXClientError`. Its `__init__` stores `.topic` and `.reason` and forwards both to `super().__init__(topic, reason)`, so `exc.args == (topic, reason)` and `str(exc)` renders as the tuple repr. Tests should assert on `exc.topic` and `exc.reason` attributes (or escape the regex in `pytest.raises(match=...)`); matching the rendered string is brittle because `topic` is a `Topic` `NewType` over `str` and reprs like a plain string. ## Propagation and state changes `start_processing` awaits `process_websocket_messages(websocket)` directly — not as a task — inside `async with client.connect(...)` inside `with self._executor_pool`. A raised `TopicClosedError` therefore unwinds both context managers: the socket closes and the executor pool shuts down, and the error surfaces to the caller of `start_processing`. Nothing on this path calls `shutdown`. Event-processor tasks, the topic-registration task, and the already-set `_client_start_event` are left as-is; cleanup happens only when the client context exits (`__aexit__` → `shutdown('Leaving PHXChannelsClient context')`) or via the SIGTERM/SIGINT handlers installed by `start_processing`. A client that catches the error and reuses the instance should be aware those tasks are still pending. ## Interaction with pending subscriptions The raise ends the message loop, which stops new reply forwarding — no further `phx_reply` frames are pushed to `_registration_queue` — but it does not cancel the registration task. `process_topic_registration_responses` keeps running as a pending task, so a reply already queued before the close/error frame can still be drained, setting the `Event` returned by `register_topic_subscription` if the event loop keeps running after the caller catches the error. Waiters hang only when the reply was never queued (e.g. `phx_close` arrives before the server's reply), and even then asyncio loop teardown cancels the pending task and releases them rather than leaving them suspended forever. Realistic clients should join the subscription event with a timeout and treat `TopicClosedError` from `start_processing` as terminal — the library does not reconnect or re-join automatically, and no retry logic exists around the raise. ## Edge cases - `phx_close` and `phx_error` are still valid `ChannelEvent` keys for `register_event_handler`, but registered handlers for them will never fire because of the precedence above. - The check uses the parsed enum, not the raw wire string; frames whose JSON `event` is anything else (including unknown strings) never trigger it. - `TopicClosedError` exposes only the exact closed topic string (`exc.topic`) and a hardcoded reason (`exc.reason`); it has no subtopic field, no prefix/scope information, and none of the server-supplied reason a Phoenix frame payload might carry, so any reasoning about related topics sharing a prefix must be done by the caller comparing `exc.topic` strings. #### Exact API Reference #### `phx_events.client.PHXChannelsClient` - **Import Path**: `from phx_events.client import PHXChannelsClient` - **Required Test Import Paths**: - phx_events.client.PHXChannelsClient - **Exact Test Import Statements**: - from phx_events.client import PHXChannelsClient - **Kind**: class - **Signature**: ```python class PHXChannelsClient: channel_socket_url: str logger: Logger _client_start_event: Event _event_handler_config: dict[ChannelEvent, EventHandlerConfig] _topic_registration_status: dict[Topic, TopicRegistration] _loop: AbstractEventLoop _executor_pool: Optional[Executor] _registration_queue: Queue _topic_registration_task: Optional[Task] def __init__(self, channel_socket_url: str, channel_auth_token: Optional[str]=None, event_loop: Optional[AbstractEventLoop]=None) async def __aenter__(self) -> 'PHXChannelsClient' async def __aexit__(self, exc_type: Optional[Type[BaseException]]=None, exc_value: Optional[BaseException]=None, traceback: Optional[TracebackType]=None) -> None async def _send_message(self, websocket: client.WebSocketClientProtocol, message: ChannelMessage) -> None def _parse_message(self, socket_message: Union[str, bytes]) -> ChannelMessage async def _event_processor(self, event: ChannelEvent) -> None def shutdown(self, reason: str, websocket: Optional[client.WebSocketClientProtocol]=None, executor_pool: Optional[Executor]=None, wait_for_completion: bool=True) -> None def register_event_handler(self, event: ChannelEvent, handlers: list[ChannelHandlerFunction], topic: Optional[Topic]=None) -> None async def process_topic_registration_responses(self) -> None def register_topic_subscription(self, topic: Topic) -> Event async def process_websocket_messages(self, websocket: client.WebSocketClientProtocol) -> None async def _subscribe_to_registered_topics(self, websocket: client.WebSocketClientProtocol) -> None async def start_processing(self, executor_pool: Optional[Executor]=None) -> None ``` - **Behavior**: Provides the main functionality for running a client with asynchronous handlers #### `phx_events.exceptions.TopicClosedError` - **Import Path**: `from phx_events.exceptions import TopicClosedError` - **Required Test Import Paths**: - phx_events.exceptions.TopicClosedError - **Exact Test Import Statements**: - from phx_events.exceptions import TopicClosedError - **Kind**: exception - **Signature**: ```python class TopicClosedError(PHXClientError): def __init__(self, topic: Topic, reason: str) topic: Any reason: Any ``` #### `phx_events.phx_messages.BasePHXMessage` - **Import Path**: `from phx_events.phx_messages import BasePHXMessage` - **Signature**: ```python class BasePHXMessage: topic: Topic ref: Optional[str] payload: dict[str, Any] @cached_property def subtopic(self) -> Optional[str] ``` #### `phx_events.phx_messages.ChannelMessage` - **Import Path**: `from phx_events.phx_messages import ChannelMessage` - **Required Test Import Paths**: - phx_events.phx_messages.ChannelMessage - **Exact Test Import Statements**: - from phx_events.phx_messages import ChannelMessage, Event, Topic - **Kind**: constant - **Signature**: ```python ChannelMessage: Any ``` - **Behavior**: Module-level value required by the test import contract. #### `phx_events.phx_messages.Topic` - **Import Path**: `from phx_events.phx_messages import Topic` - **Required Test Import Paths**: - phx_events.phx_messages.Topic - **Exact Test Import Statements**: - from phx_events.phx_messages import ChannelMessage, Event, Topic - from phx_events.phx_messages import Event, PHXEvent, Topic - from phx_events.phx_messages import Event, PHXMessage, Topic - from phx_events.phx_messages import Event, Topic - from phx_events.phx_messages import PHXEvent, PHXEventMessage, Topic - from phx_events.phx_messages import PHXEvent, Topic - from phx_events.phx_messages import Topic - **Kind**: constant - **Signature**: ```python Topic: Any ``` - **Behavior**: Module-level value required by the test import contract. #### `phx_events.json_handler` - **Import Path**: `from phx_events import json_handler` - **Required Test Import Paths**: - phx_events.json_handler - **Exact Test Import Statements**: - from phx_events import json_handler - **Kind**: module - **Behavior**: Module required during hidden-test collection. #### `phx_events.phx_messages.PHXEventMessage` - **Import Path**: `from phx_events.phx_messages import PHXEventMessage` - **Required Test Import Paths**: - phx_events.phx_messages.PHXEventMessage - **Exact Test Import Statements**: - from phx_events.phx_messages import Event, PHXEvent, PHXEventMessage, PHXMessage - from phx_events.phx_messages import PHXEvent, PHXEventMessage, PHXMessage - from phx_events.phx_messages import PHXEvent, PHXEventMessage, Topic - **Kind**: class - **Signature**: ```python class PHXEventMessage(BasePHXMessage): event: PHXEvent topic: Topic ref: Optional[str] payload: dict[str, Any] @cached_property def subtopic(self) -> Optional[str] ``` #### `phx_events.phx_messages.PHXMessage` - **Import Path**: `from phx_events.phx_messages import PHXMessage` - **Required Test Import Paths**: - phx_events.phx_messages.PHXMessage - **Exact Test Import Statements**: - from phx_events.phx_messages import Event, PHXEvent, PHXEventMessage, PHXMessage - from phx_events.phx_messages import Event, PHXMessage, Topic - from phx_events.phx_messages import PHXEvent, PHXEventMessage, PHXMessage - **Kind**: class - **Signature**: ```python class PHXMessage(BasePHXMessage): event: Event topic: Topic ref: Optional[str] payload: dict[str, Any] @cached_property def subtopic(self) -> Optional[str] ``` #### `phx_events.utils` - **Import Path**: `from phx_events import utils` - **Required Test Import Paths**: - phx_events.utils - **Exact Test Import Statements**: - from phx_events import utils - **Kind**: module - **Behavior**: Module required during hidden-test collection. ## Detailed Implementation Nodes ### Node: JSON serialization with decimal-safe handling ## Functional constraints - `dumps(obj) -> bytes`: exact wrapper over `orjson.dumps(obj, default=decimal_serialiser)`. Returns `bytes`. orjson type support applies unchanged; dict keys must be `str` (no `OPT_NON_STR_KEYS`); non-serializable non-`Decimal` objects raise bare `TypeError` from the default hook. - `decimal_serialiser(_obj) -> float`: `float(str(_obj))` for `Decimal` input (text-exact float construction, e.g. `Decimal('0.1')` → `0.1`); bare `raise TypeError` otherwise. Never receives natively serializable types (orjson only calls `default` for unknown types). `Decimal('NaN')`/`Decimal('Infinity')` convert to the non-finite floats orjson rejects on output. - `loads(json, floats_to_decimal=True) -> Any`: `orjson.loads` accepts `bytes`/`bytearray`/`memoryview`/`str`; any other input type raises orjson's `TypeError`, and malformed JSON of an accepted type raises orjson's `JSONDecodeError` — both before any conversion. When `floats_to_decimal` is true, result passes through `deep_float_replace`; when false, returned verbatim with native `float`s. - `deep_float_replace(obj) -> Any`: returns a **new** tree; input is not mutated. `float` → `Decimal(str(v))` (so `Decimal(0.1)`-style binary artifacts are avoided). Recurses into `dict` values (keys untouched) and `list` items; tuples/sets are *not* traversed. Ints, strings, bools, `None`, existing `Decimal`s pass through; conversion is idempotent. Non-finite floats (direct calls only — `loads` cannot yield them) become `Decimal('Infinity')`/`Decimal('NaN')`. - Round-trip: `Decimal('0.1')` → `dumps` → `loads` → `Decimal('0.1')`; decimals exceeding double precision are truncated to float repr at encode time. - Both functions are pure/stateless; safe under asyncio and threads. ## Example ```python from decimal import Decimal from phx_events import json_handler payload = {"price": Decimal("0.1"), "qty": [Decimal("3"), 2]} json_handler.dumps(payload) # b'{"price":0.1,"qty":[3.0,2]}' json_handler.loads(b'{"price":0.1}') # {'price': Decimal('0.1')} json_handler.loads(b'{"p":0.1}', floats_to_decimal=False) # {'p': 0.1} (plain float) deep = {"a": [0.1, {"b": 0.2}]} json_handler.deep_float_replace(deep) # {'a': [Decimal('0.1'), {'b': Decimal('0.2')}]} (input unchanged) ``` ### Node: Phoenix message model and construction ## Functional constraints - `make_message(event, topic, ref=None, payload=None)` — order: payload defaulting (`None` → fresh `{}`, never shared, never `None` on result) → event classification via `parse_event` (once) → class selection. A `PHXEvent` result yields `PHXEventMessage`; anything else yields `PHXMessage` with the event object passed through unmodified (no validation; empty/odd-cased strings allowed). `ref` passes through verbatim (`None` stays `None`; no auto-generation). A supplied payload dict is stored by reference with no defensive copy; only `None` produces a fresh `{}`. No topic/ref validation; `Topic`/`Event` are erased `str` at runtime. - `parse_event(event)` — classifies only the five exact enum values `phx_close`, `phx_error`, `phx_join`, `phx_reply`, `phx_leave`; unknown strings and any non-classifiable input are returned as the same object. Idempotent on `PHXEvent` members. Catches `ValueError` only; discriminator is `isinstance(result, PHXEvent)`. - `generate_reference(event)` — `'%Y%m%d%H%M%S'` wall-clock (local time) + `':'` + `str(event)`; `PHXEvent.__str__` returns the member value. Second resolution: calls in the same second collide; no uniqueness guarantee. - Message classes are frozen dataclasses: equality is class-sensitive (`PHXMessage` ≠ `PHXEventMessage` with identical fields); within the same class `__eq__` compares all declared fields — `topic`, `ref`, `payload`, and `event`. Hashing fails with `TypeError` whenever the payload is a dict (effectively always, since `None` becomes `{}`), regardless of the dict's values. `subtopic` (cached once per instance) is `None` when the topic has no `':'`, else everything after the first colon (`'a:b:c'` → `'b:c'`). - `PHXEvent` members are built by value (`PHXEvent('phx_reply')`); unknown values raise `ValueError`. ## Example ```python from phx_events import utils from phx_events.phx_messages import PHXEvent, PHXEventMessage, Topic ref = utils.generate_reference(PHXEvent.join) # '20240101120000:phx_join' msg = utils.make_message( event='phx_reply', # classified at build time topic=Topic('game:1'), ref=ref, payload={'status': 'ok'}, ) assert isinstance(msg, PHXEventMessage) # 'phx_reply' became PHXEvent.reply assert msg.subtopic == '1' plain = utils.make_message('game:update', Topic('game:1')) assert not isinstance(plain.event, PHXEvent) # unknown events stay plain PHXMessage ``` ### Node: Asynchronous queue-based logging ## Functional constraints - `LocalQueueHandler` subclasses `QueueHandler`; `emit(record)` enqueues the `LogRecord` onto the shared `SimpleQueue` and never blocks (unbounded queue). `asyncio.CancelledError` is re-raised; every other enqueue exception is reported via `handleError(record)` — `emit` must not propagate ordinary failures to the caller. - `setup_queue_logging()` returns `(logger, running_listener)`: the logger is named `phx_events.async_logger`, its only handler is the new `LocalQueueHandler`, and pre-attached handlers are removed and transferred to the `QueueListener` — guaranteed only for zero or one pre-attached handler; with two or more, the transfer loop (which removes from the list it is iterating) skips every second handler, leaving it attached to the logger and firing inline. - `logging.lastResort` (when not `None`) is prepended to the listener's handlers as a stderr fallback, so unconfigured applications still emit WARNING+ records. - The listener runs with `respect_handler_level=True`: each transferred handler keeps applying its own level and formatter, just on the listener thread instead of the logging thread. `queue_listener.handlers` is an immutable tuple (the listener stores its `*args` handlers as a tuple), so post-import handlers are added by rebinding: `queue_listener.handlers = (*queue_listener.handlers, handler)` — `.append` raises `AttributeError`. - The queue logger is never given a level: `async_logger` and its children are `NOTSET` and inherit root's effective level (`WARNING` by default), so INFO/DEBUG calls are dropped before enqueue unless the level is raised, e.g. `async_logger.setLevel(logging.DEBUG)`. - Importing `phx_events.async_logger` itself calls `setup_queue_logging()` once and exposes the results as module attributes `async_logger` (queue-feeding logger) and `queue_listener` (already-started daemon thread); importing is the supported way to obtain them, and a second call creates duplicate queues/threads. - Only handlers attached to the logger before import are transferred into the listener; a handler added to `async_logger` after import runs inline on the logging thread while records also still pass through `LocalQueueHandler`. - Client-side loggers must be derived via `async_logger.getChild(...)` so records propagate to the single queue handler; the resulting child name is `phx_events.async_logger.` and `client.logger.parent is async_logger`. - Call `queue_listener.stop()` once at shutdown to drain queued records and join the thread; after that, further records remain buffered in the queue (unbounded memory, no error). ### Usage ```python import logging from phx_events.async_logger import async_logger, queue_listener # async_logger ("phx_events.async_logger") feeds LocalQueueHandler -> SimpleQueue; # the already-running QueueListener thread does formatting/emission off-loop. async_logger.setLevel(logging.DEBUG) # NOTSET would inherit root's WARNING, dropping INFO/DEBUG log = async_logger.getChild("app.jobs") # name: phx_events.async_logger.app.jobs log.info("queued without blocking the event loop") # enqueue only; FIFO dispatch later # Attach a real handler post-import: rebind the listener's handler tuple (not a list — # .append raises AttributeError). It then fires on the listener thread, never inline. handler = logging.FileHandler("phx.log") handler.setLevel(logging.DEBUG) # honoured (respect_handler_level=True) queue_listener.handlers = (*queue_listener.handlers, handler) queue_listener.stop() # drain queue, then join the thread ``` ### Node: Topic subscription tracking and join replies ### Functional constraints - One `TopicRegistration` per `Topic` per client instance; a second `register_topic_subscription` for the same topic raises `PHXTopicTooManyRegistrationsError` before any state changes. - Registration is local-only: it stores the envelope and queues the `phx_join`; it never awaits and returns the registration immediately. - Only the reply-processing loop writes `TopicRegistration.result` (a frozen `TopicSubscribeResult` holding a `SubscriptionStatus` plus the raw `PHXEventMessage`) and then sets `status_updated_event`. Readers must wait on the event before touching `result`, which is `None` until then. - `SUCCESS` iff the reply payload status is `'ok'`; any other payload status resolves `FAILED`. No retry and no automatic removal of failed registrations. - `SubscriptionStatus` is `@unique IntEnum`: `FAILED = 0`, `SUCCESS = 1`. Compare statuses as enums, not by truthiness (both values hash/compare as ints). - Await `status_updated_event.wait()` only while `start_processing` is running; with no loop the event is never set and the coroutine hangs. Multiple concurrent waiters are fine because the event stays set. - `TopicRegistration` fields: `status_updated_event` (required `asyncio.Event`), `connection_ref: Optional[str]`, `result: Optional[TopicSubscribeResult]`. Example: ```python async with PHXChannelsClient('ws://localhost:4000/socket/websocket') as client: registration = client.register_topic_subscription(Topic('rooms:lobby')) loop_task = asyncio.create_task(client.start_processing()) await registration.status_updated_event.wait() result = registration.result if result.status is SubscriptionStatus.SUCCESS: print('joined', result.result_message.topic) try: client.register_topic_subscription(Topic('rooms:lobby')) except PHXTopicTooManyRegistrationsError: print('duplicate topic registration rejected') await client.shutdown() loop_task.cancel() ``` ### Node: Event handler registration and dispatch # Functional constraints - `register_event_handler(event, handlers, topic=None)` appends `handlers`: `topic=None` goes to `default_handlers`, otherwise `topic_handlers.setdefault(topic, []).extend(...)`. - First registration per event creates an unbounded `asyncio.Queue`, empty handler containers, and starts the `_event_processor` task immediately via `self._loop.create_task(...)`; registration must therefore happen while that loop is running - inside the `async with` block. Registering outside it schedules the processor task on a loop that never runs, leaving the event's queue permanently undrained. - Processors block on `_client_start_event` until `start_processing` sets it (after executor creation and topic joins); only then do they consume the queue. - Dispatch key is the parsed event: admin events are `PHXEvent` members (parsed as `PHXEventMessage.event`), custom events are `Event` strings. The registration key must match. - `phx_close`/`phx_error` frames raise `TopicClosedError` before any dispatch; the raise is not caught in the dispatch path and terminates `process_websocket_messages`, so `PHXEvent.close`/`PHXEvent.error` handlers never run while `PHXEvent.join`/`PHXEvent.leave`/`PHXEvent.reply` frames dispatch normally (reply also feeds the registration queue for pending topic registrations). - Per message: run `default_handlers` plus `topic_handlers[message.topic]` (exact equality). Async handlers become `loop.create_task`; sync handlers run via `run_in_executor(self._executor_pool, partial(handler, message, self))`. - One message's handlers complete before the next queue item is pulled; handlers within a message run concurrently via `asyncio.as_completed`. - Any `Exception` from a handler is caught and logged with `logger.exception`; the processor loop never exits except by cancellation (`shutdown` cancels every config task). - `queue.task_done()` runs after each message even when zero handlers matched. # Usage ```python from phx_events.client import PHXChannelsClient from phx_events.phx_messages import Event, PHXEvent, Topic def audit(message, client): # runs in the executor pool client.logger.info(f'{message.event} on {message.topic}') async def react(message, client): # runs as a loop task await handle(message.topic, message.payload) client = PHXChannelsClient('ws://host/socket/websocket') async with client: # client loop running - register here client.register_event_handler(Event('ping'), [audit, react]) client.register_event_handler(PHXEvent.reply, [audit], topic=Topic('rooms:lobby')) client.register_topic_subscription(Topic('rooms:lobby')) await client.start_processing() # unblocks all processors ``` ### Node: WebSocket connection and message pump ## Functional constraints - One connection per `start_processing` call via `websockets.client.connect(channel_socket_url)`; `channel_auth_token` becomes a `?token=` query parameter appended at construction. - `start_processing` returns without connecting when no topics are registered; otherwise it defaults the pool to `ThreadPoolExecutor` and installs SIGTERM/SIGINT handlers that trigger `shutdown(..., wait_for_completion=False)`. - Outbound frames: one `phx_join` per registered topic, all sent concurrently; `_send_message` is `json_handler.dumps(message)` → `await websocket.send(json)`. - Pump loop: `async for frame in websocket` → `make_message(**json_handler.loads(frame))`; an event string matching a `PHXEvent` value produces `PHXEventMessage`, anything else keeps the raw `str` event on `PHXMessage`. - Every parsed message exposes `message.subtopic`, a cached derived field: `None` for topics without ':', otherwise the text after the first ':' only (`Topic('game:abc')` → `'abc'`; `'a:b:c'` → `'b:c'`); it is a `cached_property` computed lazily once per message instance on the otherwise frozen message objects, and colon-less topics silently yield `None` rather than the full topic string. - `phx_close` raises `TopicClosedError(topic, reason='Upstream closed')`; `phx_error` raises `TopicClosedError(topic, reason='Upstream error')` — the loop exits by exception, not by return. - Registration replies are intercepted only while `status_updated_event` is unset; the consumer derives `SubscriptionStatus` from `payload['status'] == 'ok'`, stores the `TopicSubscribeResult`, and sets the event. - Events with no `EventHandlerConfig` are dropped with a debug log; known events are awaited onto their queue. - Workers gate on `_client_start_event` (set only after joins are sent); each message fans out to default handlers plus the message topic's handlers; coroutine handlers run as tasks, sync handlers in the executor; handler exceptions are logged and swallowed; `queue.task_done()` each iteration. - `shutdown` cancels the registration task and all worker tasks, schedules `websocket.close()`, and calls `executor_pool.shutdown(wait, cancel_futures=not wait)`. ## Usage example ```python client = PHXChannelsClient('ws://127.0.0.1:4000/socket/websocket', channel_auth_token='s3cret') joined = client.register_topic_subscription(Topic('game:abc')) client.register_event_handler(Event('game:update'), [on_update]) async def main(): async with client: pump = asyncio.create_task(client.start_processing()) await joined.wait() # set when the join phx_reply is processed result = client._topic_registration_status[Topic('game:abc')].result print(result.status) # SubscriptionStatus.SUCCESS await pump # exits via TopicClosedError or signal-triggered shutdown asyncio.run(main()) ``` ### Node: Upstream error and topic closure handling ## Functional constraints - Detection lives in `PHXChannelsClient.process_websocket_messages`; it inspects `message.event` after `_parse_message` produces a `PHXEventMessage` (orjson decode → `make_message`). - `PHXEvent.close` (`'phx_close'`) → `TopicClosedError(topic, reason='Upstream closed')`, logged at INFO; `PHXEvent.error` (`'phx_error'`) → `TopicClosedError(topic, reason='Upstream error')`, logged at ERROR. The reason strings are literals; the message payload is ignored. - The check precedes registration-queue handling (a frame is pushed to `_registration_queue` only if it is `phx_reply`, its topic is present in `_topic_registration_status`, and that topic's status event is still unset) and handler-queue dispatch; closure/error frames never reach `register_event_handler` queues, so handlers registered for `phx_close`/`phx_error` are unreachable. - No topic filtering: the raise applies whether or not the topic appears in `_topic_registration_status`. - `TopicClosedError` extends `PHXClientError`; `.topic` and `.reason` are set as attributes and also become `args == (topic, reason)`. - The error propagates synchronously out of `start_processing`: the websocket context manager closes, the executor pool shuts down, and the caller sees the exception. `shutdown` is not invoked on this path, so event-processor and registration tasks persist until the client context exits or signals fire. - The raise ends the message loop, so no new `phx_reply` frames are forwarded to `_registration_queue`, but it does not cancel the registration task (created in `_subscribe_to_registered_topics` and left pending): a reply already queued may still be drained and set the `Event` returned by `register_topic_subscription` if the loop keeps running after the error is caught. Waiters hang only when the reply was never queued (e.g. `phx_close` arrives before the reply); asyncio loop teardown cancels the pending task, releasing them. Guard the returned event with a timeout. ## Usage ```python import asyncio from phx_events.client import PHXChannelsClient from phx_events.exceptions import TopicClosedError from phx_events.phx_messages import Topic async def main() -> None: client = PHXChannelsClient('ws://localhost:4000/socket/websocket') client.register_topic_subscription(Topic('game:default')) try: await client.start_processing() except TopicClosedError as exc: print(exc.topic, exc.reason) # game:default Upstream closed asyncio.run(main()) ```