Repository navigation
Run stream hooks on stream start and stop - #28
Merged
Merged
Conversation
--hook-start and --hook-stop run a shell command when a stream starts and when it stops -- the amplifier relay, the light, the notification a headless install has next to the player. The C++ CLI had no equivalent and no workaround: the control socket answers questions, it does not announce events. The environment contract is the Python sendspin-cli's, verbatim, so a hook script written against one player runs unchanged against the other: SENDSPIN_EVENT always, and SENDSPIN_SERVER_ID, SENDSPIN_SERVER_NAME, SENDSPIN_SERVER_URL (the URL this run dialled -- outbound only, as in Python) and SENDSPIN_CLIENT_NAME where known. An unknown is left unset rather than exported empty, and inherited SENDSPIN_* variables are cleared so a wrapper script's stale export cannot describe some other run. SENDSPIN_CLIENT_ID is reserved but not yet set: the library derives its id from the interface MAC and does not expose it, so the honest value arrives with a future --id flag. Nothing waits on a hook. The spawn is fork()/execve() with the environment built before the fork -- this process has the library's background threads, so the child may only touch async-signal-safe calls -- and the reap is a WNOHANG waitpid() polled from the main loop. A non-zero exit is one W hook: line, and a hook still running at shutdown is left to finish. The child's stdout is pointed at stderr, because with -o stdout the parent's stdout is carrying PCM. The hook fires on the stream lifecycle, not on the format being accepted, through a PlayerListener::on_stream_event seam shaped like AudioSink::on_frames_played: a stream the device refused is audio arriving and being discarded, so the hook window is exactly status's "stream: receiving". Verified end to end against a real aiosendspin server in both connection modes: inbound leaves SENDSPIN_SERVER_URL unset, outbound carries the dialled URL, and both events fired with the server's id and name. Co-Authored-By: Claude Fable 5 <[email protected]>
This was referenced Aug 27, 2026
A hook is forked and exec'd, and an exec carries more across than the
command it replaces: every descriptor the player has open, and any
signal it ignores rather than catches.
The descriptors are the damaging half. `--hook-start 'sleep 120'` with
--port 8929 leaves the child holding fd 7 -- the audio port's listening
socket -- and it keeps holding it after the player exits, so a restart
in that window logs
E sendspin.ws_server: ... bind at address 0.0.0.0:8929 : Address
already in use
while the player still says "listening on port 8929" at INFO: healthy to
look at, accepting nothing. The control socket's accepted peers go the
same way, and a `status` reader waits on an EOF that can no longer come.
Closed in the child rather than opened close-on-exec at each site,
because the sockets the library and its websocket dependency open are
not this process's to reach into. The limit comes from getrlimit()
before the fork, capped, since LimitNOFILE=infinity would otherwise ask
the stream path to close a million descriptors that were never open.
SIGPIPE is the other half: the player ignores it, and an ignored
disposition survives execve() where a caught one does not, so `... |
head -1` inside a hook reported a failed write where the same line in
any other shell ends the writer. Back to its default in the child.
The dup2() that keeps a hook's output out of the PCM stream is now
checked too -- unnoticed failure there is the one thing it exists to
prevent.
Both are tested by the consequence rather than the mechanism: a hook
whose `yes | head -n 1` must end 141 and not 1, and a hook that must
find an inherited descriptor already closed.
poll() erased the entry on any non-zero return, on the reasoning that the only error waitpid() can give it is ECHILD. EINTR is the other one, and erasing on it drops a hook that is still running: the child is never waited on again, and the zombie stays for the life of the daemon. It cannot happen today -- every handler here is installed through BSD-semantics signal() or with SA_RESTART, and WNOHANG does not block -- so this is the comment being made to claim only what is true, and the code to stop depending on a signal handler somewhere else keeping a promise it never made.
Both events describe one stream, so both should describe the same
server. The stop event gathered its own facts instead, and by the time
it fires there is nothing to gather: a stream ends because its
connection went, and get_server_information() answers nullopt once the
connection has been dropped. Against a real server, killing it mid-
stream gave the pair
START id=sendspin-cli-9737a2a9 name=TestServer url=ws://127.0.0.1:8927/sendspin
STOP id=unset name=unset url=ws://127.0.0.1:8927/sendspin
-- one event describing one connection with two of its three facts
erased and the third kept, because the URL comes from the dial rather
than from the connection. A --hook-stop that curls
$SENDSPIN_SERVER_ID has nothing to curl.
The facts are now taken once, when the stream starts, and handed to
both of its events. Nothing has to clear them between streams: the
library fires on_stream_end() only for a stream it fired
on_stream_start() for, so every stop is preceded by the start that
rewrote them. Gathering sits above the empty-command return so a run
that gave only --hook-stop still has them.
Same run after the change:
START id=sendspin-cli-ddcae366 name=TestServer url=ws://127.0.0.1:8927/sendspin
STOP id=sendspin-cli-ddcae366 name=TestServer url=ws://127.0.0.1:8927/sendspin
A stream's end is delivered by client.loop(), like every other listener callback: disconnect() only enqueues it. The main loop had already exited by then, so a player killed while a stream was playing ran no stop hook at all -- against a real server, SIGTERM mid-stream left the hook's output file holding nothing but its START line. For the amplifier this feature exists to switch, that is the whole failure it was meant to prevent, and it made the README's claim that the amplifier is on for exactly as long as `status` says `stream: receiving` false in the one case that matters. The loop is pumped after the disconnect until the listener reports the stream over. Pumped rather than fired from here on purpose: the listener stays the only producer of stream events, so the sink is cleared and `streaming()` falls on the same path as always, and there is no second way for a hook to run. The bound is 500 ms against a wait of about 50: one tick for the goodbye's close event to reach drop_connection() and enqueue the end, up to the library's 20 ms audio-write timeout for its sync task to go idle, one more tick to deliver the callback. Measured, it costs ten milliseconds against a shutdown that already takes five hundred. Past the bound it says so and goes -- an amplifier left on needs the line that explains it, and holding the process longer would not produce one. An idle player pays nothing: streaming() is false and the loop body never runs.
--help listed SENDSPIN_CLIENT_ID among the facts a hook is handed. Nothing sets it: config.client_id is deliberately left empty so the library derives an id from the interface MAC, and it does not expose what it derived, so add_env() drops the field on every event. A flag's own help promising a variable that cannot arrive is worse than saying nothing, and it is the text a reader trusts first. The README and the roadmap already scope it to a future --id flag and keep it; only --help stated it flatly. The HookContext field stays -- it is the wiring the flag will use, and its test is the proof the wiring works. The roadmap also claimed the Python CLI's environment contract "verbatim" while describing, two sentences later, the inherited SENDSPIN_* clearing that Python does not do. It is the vocabulary that is verbatim, which is how the README already puts it.
Contributor
There was a problem hiding this comment.
Pull request overview
Adds nonblocking stream lifecycle hooks with Python CLI-compatible environment variables.
Changes:
- Adds
--hook-start/--hook-stopflags and config keys. - Implements asynchronous hook spawning, environment isolation, and reaping.
- Wires hooks into stream events and documents/tests the feature.
Reviewed changes
Copilot reviewed 15 out of 15 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
CMakeLists.txt |
Builds hook implementation and tests. |
src/cli.h |
Defines hook options. |
src/cli.cpp |
Parses and documents hook flags. |
src/hooks.h |
Declares hook context and runner. |
src/hooks.cpp |
Implements hook execution and reaping. |
src/log.h |
Adds the hook log tag. |
src/main.cpp |
Connects hooks to stream lifecycle. |
src/player_listener.h |
Adds the stream-event callback. |
src/player_listener.cpp |
Emits start and stop events. |
tests/hooks_test.cpp |
Tests flags, environment, and processes. |
README.md |
Documents stream hooks. |
packaging/sendspin-cli.conf.example |
Adds example hook configuration. |
docs/wiki/Configuration.md |
Lists hook config keys. |
docs/wiki/Controlling-the-Player.md |
Documents operational usage. |
docs/ROADMAP.md |
Marks stream hooks shipped. |
Suppressed comments (1)
src/hooks.cpp:188
- This signal-failure path also writes the complete hook command at WARN level, which can expose credentials embedded in the command to normal operational logs. Keep the diagnostic useful by reporting the event and terminating signal without echoing the command.
cli_log(LogLevel::WARN, "The %s hook was killed by signal %d: %s",
hook.event.c_str(), WTERMSIG(status), hook.command.c_str());
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
It is the URL this run dialled. That reads as "the connected server's
URL", and the two come apart: -s leaves the inbound listener up, so a
server that dials in while an outbound attempt is outstanding or has
failed is a connection the player cannot tell from its own. Pointing -s
at a dead port and letting a server dial in gives a hook
SENDSPIN_SERVER_URL=ws://127.0.0.1:9999/sendspin
naming a server it never reached.
Nothing here can tell the two apart. SendspinClientListener has no
connect callback, the client exposes only is_connected() and a server id
and name, and start_server() is unconditional, so an inbound connection
is always possible on an -s run. Clearing the URL whenever the player is
disconnected looks like the fix and is not: a dial takes longer than one
10 ms tick to land, so the clear wipes the URL before the connection it
belongs to comes up, and an ordinary outbound run ends up exporting
nothing.
So the docs stop implying more than the value carries, and say which
variable to read instead: SENDSPIN_SERVER_ID comes from the connection
the stream arrived on and is right either way. The roadmap records what
would close it properly -- sendspin-cpp naming the live connection's
origin -- so the next person meets the reason rather than the symptom.
This was referenced Aug 28, 2026
Closed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes the top gap from the daemon-parity audit against the Python
sendspin-cli: stream hooks. This is the amplifier-relay / light / notification trigger a headless install wants, and there was no workaround — the control socket answers questions, it does not announce events.What it adds
--hook-start <command>and--hook-stop <command>(config keyshook-start/hook-stop) run a shell command through/bin/sh -cwhen a stream starts and when it stops.The environment contract is the Python CLI's, verbatim, so a hook script written against one player runs unchanged against the other:
SENDSPIN_EVENT(start|stop) always, andSENDSPIN_SERVER_ID,SENDSPIN_SERVER_NAME,SENDSPIN_SERVER_URL(the URL this run dialled — outbound only, matching Python where inbound leaves it unset) andSENDSPIN_CLIENT_NAMEwhere known. An unknown is left unset rather than exported empty, so[ -n "$SENDSPIN_SERVER_ID" ]means what it says, and inheritedSENDSPIN_*variables are cleared so a wrapper script's stale export cannot describe some other run.SENDSPIN_CLIENT_IDis reserved but not set yet: the library derives its id from the interface MAC and does not expose it, so the honest value arrives with a future--idflag (next audit gap).Design notes
fork()/execve()with argv and envp built before the fork — this process has the library's background threads, so the child may only touch async-signal-safe calls — and the reap is aWNOHANGwaitpid()polled from the main loop next to mDNS and the control socket. A non-zero exit or signal death is oneW hook:line, not a player failure. A hook still running at shutdown is left to finish: an amplifier half-switched is worse than an orphan.PlayerListener::on_stream_eventseam shaped likeAudioSink::on_frames_played. A stream the device refused is audio arriving and being discarded — the case where the amplifier being on matters most — so the hook window is exactlystatus'sstream: receiving.-o stdoutthe parent's stdout is carrying PCM and a hook'sechowould land mid-audio. Under-fboth end up in the logfile.Testing
tests/hooks_test.cpp: the flag surface (fields, empty-value refusal, config keys, subcommand warning) and the runner (env contract, unset-vs-empty, inherited-variable clearing, failing hooks reaped, several in flight). Full suite: 380/380 pass.aiosendspinserver in both connection modes: server-initiated (inbound) fires both hooks with the server's id and name and leavesSENDSPIN_SERVER_URLunset;-s-dialled (outbound) carries the dialled URL.Docs updated:
--help, README (flag list + a Stream hooks section), wikiConfiguration.mdkey table, wikiControlling-the-Player.md, the annotated example config, anddocs/ROADMAP.md(new item 22).🤖 Generated with Claude Code