Skip to content

Commit

Permalink
Gateway: Simplify return value of join/join_gateway (#157)
Browse files Browse the repository at this point in the history
Replaces the annoying dual-return (i.e., created `Call` *and* `Result<x>`) with a single `Return<Call/ConnectionInfo>`. Users are now informed via that a `Call` is created -- thus, cleanup in event of connection failure is now their responsibility.

Tested using `cargo make ready`.

Closes #65.
  • Loading branch information
FelixMcFelix authored Jan 9, 2023
1 parent 427f3f8 commit ff9b0cd
Show file tree
Hide file tree
Showing 8 changed files with 30 additions and 452 deletions.
417 changes: 0 additions & 417 deletions examples/serenity/voice/src/main-skip.rs

This file was deleted.

10 changes: 5 additions & 5 deletions examples/serenity/voice/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,11 +161,11 @@ async fn join(ctx: &Context, msg: &Message) -> CommandResult {
.expect("Songbird Voice client placed in at initialisation.")
.clone();

let (handler_lock, _success) = manager.join(guild_id, connect_to).await;

// Attach an event handler to see notifications of all track errors.
let mut handler = handler_lock.lock().await;
handler.add_global_event(TrackEvent::Error.into(), TrackErrorNotifier);
if let Ok(handler_lock) = manager.join(guild_id, connect_to).await {
// Attach an event handler to see notifications of all track errors.
let mut handler = handler_lock.lock().await;
handler.add_global_event(TrackEvent::Error.into(), TrackErrorNotifier);
}

Ok(())
}
Expand Down
6 changes: 2 additions & 4 deletions examples/serenity/voice_cached_audio/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,11 +233,9 @@ async fn join(ctx: &Context, msg: &Message) -> CommandResult {
.expect("Songbird Voice client placed in at initialisation.")
.clone();

let (handler_lock, success_reader) = manager.join(guild_id, connect_to).await;
if let Ok(handler_lock) = manager.join(guild_id, connect_to).await {
let call_lock_for_evt = Arc::downgrade(&handler_lock);

let call_lock_for_evt = Arc::downgrade(&handler_lock);

if let Ok(_reader) = success_reader {
let mut handler = handler_lock.lock().await;
check_msg(
msg.channel_id
Expand Down
4 changes: 1 addition & 3 deletions examples/serenity/voice_events_queue/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,9 +174,7 @@ async fn join(ctx: &Context, msg: &Message) -> CommandResult {
.expect("Songbird Voice client placed in at initialisation.")
.clone();

let (handle_lock, success) = manager.join(guild_id, connect_to).await;

if let Ok(_channel) = success {
if let Ok(handle_lock) = manager.join(guild_id, connect_to).await {
check_msg(
msg.channel_id
.say(&ctx.http, &format!("Joined {}", connect_to.mention()))
Expand Down
4 changes: 1 addition & 3 deletions examples/serenity/voice_receive/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,9 +253,7 @@ async fn join(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
.expect("Songbird Voice client placed in at initialisation.")
.clone();

let (handler_lock, conn_result) = manager.join(guild_id, connect_to).await;

if let Ok(_) = conn_result {
if let Ok(handler_lock) = manager.join(guild_id, connect_to).await {
// NOTE: this skips listening for the actual connection result.
let mut handler = handler_lock.lock().await;

Expand Down
6 changes: 2 additions & 4 deletions examples/twilight/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,8 @@ async fn join(msg: Message, state: State) -> Result<(), Box<dyn Error + Send + S
let channel_id =
NonZeroU64::new(channel_id).ok_or("Joined voice channel must have nonzero ID.")?;

let (_handle, success) = state.songbird.join(guild_id, channel_id).await;

let content = match success {
Ok(()) => format!("Joined <#{}>!", channel_id),
let content = match state.songbird.join(guild_id, channel_id).await {
Ok(_handle) => format!("Joined <#{}>!", channel_id),
Err(e) => format!("Failed to join <#{}>! Why: {:?}", channel_id, e),
};

Expand Down
3 changes: 1 addition & 2 deletions src/input/adapters/cached/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,7 @@ impl Display for CodecCacheError {
Self::Parse(p) => f.write_fmt(format_args!("failed to parse audio format: {p}")),
Self::Opus(o) => f.write_fmt(format_args!("failed to create Opus encoder: {o}")),
Self::MetadataEncoding(m) => f.write_fmt(format_args!(
"failed to convert track metadata to JSON: {}",
m
"failed to convert track metadata to JSON: {m}"
)),
Self::MetadataTooLarge => f.write_str("track metadata was too large, >= 32kiB"),
Self::CreatePanicked => f.write_str("sync thread panicked while creating stream"),
Expand Down
32 changes: 18 additions & 14 deletions src/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -216,11 +216,13 @@ impl Songbird {
///
/// Twilight users should read the caveats mentioned in [`process`].
///
/// NOTE: an `Err(..)` value will still create a [`Call`] accessible via [`get`].
///
/// [`Call`]: Call
/// [`get`]: Songbird::get
/// [`process`]: #method.process
#[inline]
pub async fn join<C, G>(&self, guild_id: G, channel_id: C) -> (Arc<Mutex<Call>>, JoinResult<()>)
pub async fn join<C, G>(&self, guild_id: G, channel_id: C) -> JoinResult<Arc<Mutex<Call>>>
where
C: Into<ChannelId>,
G: Into<GuildId>,
Expand All @@ -233,20 +235,18 @@ impl Songbird {
&self,
guild_id: GuildId,
channel_id: ChannelId,
) -> (Arc<Mutex<Call>>, JoinResult<()>) {
) -> JoinResult<Arc<Mutex<Call>>> {
let call = self.get_or_insert(guild_id);

let stage_1 = {
let mut handler = call.lock().await;
handler.join(channel_id).await
};

let result = match stage_1 {
Ok(chan) => chan.await,
match stage_1 {
Ok(chan) => chan.await.map(|_| call),
Err(e) => Err(e),
};

(call, result)
}
}

/// Partially connects to a target by retrieving its relevant [`Call`] and
Expand All @@ -255,13 +255,16 @@ impl Songbird {
/// This method returns the handle and the connection info needed for other libraries
/// or drivers, such as lavalink, and does not actually start or run a voice call.
///
/// NOTE: an `Err(..)` value will still create a [`Call`] accessible via [`get`].
///
/// [`Call`]: Call
/// [`get`]: Songbird::get
#[inline]
pub async fn join_gateway<C, G>(
&self,
guild_id: G,
channel_id: C,
) -> (Arc<Mutex<Call>>, JoinResult<ConnectionInfo>)
) -> JoinResult<(ConnectionInfo, Arc<Mutex<Call>>)>
where
C: Into<ChannelId>,
G: Into<GuildId>,
Expand All @@ -273,20 +276,21 @@ impl Songbird {
&self,
guild_id: GuildId,
channel_id: ChannelId,
) -> (Arc<Mutex<Call>>, JoinResult<ConnectionInfo>) {
) -> JoinResult<(ConnectionInfo, Arc<Mutex<Call>>)> {
let call = self.get_or_insert(guild_id);

let stage_1 = {
let mut handler = call.lock().await;
handler.join_gateway(channel_id).await
};

let result = match stage_1 {
Ok(chan) => chan.await.map_err(|_| JoinError::Dropped),
match stage_1 {
Ok(chan) => chan
.await
.map_err(|_| JoinError::Dropped)
.map(|info| (info, call)),
Err(e) => Err(e),
};

(call, result)
}
}

/// Retrieves the [handler][`Call`] for the given target and leaves the
Expand Down

0 comments on commit ff9b0cd

Please sign in to comment.