Repository navigation
Description
What's needed?
Sync code can't call the async send(), as the data sourcing and resampler use cases in #76 show. A BroadcastSender never waits for a receiver to have room: a full receiver drops its oldest message instead. So sending doesn't need to be async.
Proposed solution
Add a sync send_nowait(message) method to BroadcastSender. The name follows the standard library: asyncio.Queue.put_nowait() is the sync version of put(). trio's MemorySendChannel.send_nowait() and anyio's MemoryObjectSendStream.send_nowait() work the same way.
def send_nowait(self, message: _T, /) -> None: ...- It does the same as
send(): full receivers drop their oldest message, so it never fails because a buffer is full. - Like
send(), it raisesSenderErrorif the channel is closed,SenderClosedErrorif the sender is closed, andSenderHasNoReceiversError(MakeNoReceiversErroraTransientSenderErrorand rename it toSenderHasNoReceiversError#599) if the channel has no receivers.
send_nowait() isn't added to the abstract Sender. Not every sender can send without waiting, for example one that sends over a network. trio's and anyio's abstract send channels don't have it either. An abstract interface for senders that have send_nowait() can come later with #76.
If broadcast channels get senders that can wait (#602), those could get a send_nowait() that raises an error instead of waiting.
This targets v2. It isn't a breaking change, so any v2 minor release can add it. The implementation is simple in v2: a broadcast sender wakes up its receivers by setting an asyncio.Event, which works from sync code. In v1, a broadcast sender notifies an asyncio.Condition. That needs the condition's lock, and a sync method can't wait to acquire it.
Alternatives and workarounds
Send from a task
Sync code running in the event loop's thread can call asyncio.create_task(sender.send(message)).
- Pros: it works today, without any change.
- Cons: it creates a task for every message. The message is only sent after the sync code returns to the event loop. Errors are lost unless something awaits the task.
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Activity
NoReceiversErroraTransientSenderErrorand rename it toSenderHasNoReceiversError#599BlockingBroadcastChannel#598[-]Add a sync `send_nowait()` to broadcast senders[/-][+]Add a sync `send_nowait()` to `BroadcastSender`[/+]BlockingBroadcastChannel#598