Skip to content

Commit

Permalink
Send raw events (DSharpPlus#1521)
Browse files Browse the repository at this point in the history
* Rename WsSendAsync to SendRawPayloadAsync; Expose SendRawPayloadAsync through SendPayloadAsync

* Docs

* Change parameter name
  • Loading branch information
OoLunar authored Mar 23, 2023
1 parent 2ab57e9 commit fee6a62
Show file tree
Hide file tree
Showing 6 changed files with 50 additions and 22 deletions.
2 changes: 1 addition & 1 deletion DSharpPlus.Lavalink/LavalinkGuildConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ internal async Task SendVoiceUpdateAsync()
}
};
var vsj = JsonConvert.SerializeObject(vsd, Formatting.None);
await (this.Channel.Discord as DiscordClient).WsSendAsync(vsj).ConfigureAwait(false);
await (this.Channel.Discord as DiscordClient).SendRawPayloadAsync(vsj).ConfigureAwait(false);
}

/// <summary>
Expand Down
4 changes: 2 additions & 2 deletions DSharpPlus.Lavalink/LavalinkNodeConnection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,7 @@ internal async Task StartAsync()
{ throw; }
catch (Exception ex)
{
if(!this.Configuration.SocketAutoReconnect || this._backoff == MaximumBackoff)
if (!this.Configuration.SocketAutoReconnect || this._backoff == MaximumBackoff)
{
this.Discord.Logger.LogCritical(LavalinkEvents.LavalinkConnectionError, ex, "Failed to connect to Lavalink.");
throw ex;
Expand Down Expand Up @@ -340,7 +340,7 @@ public async Task<LavalinkGuildConnection> ConnectAsync(DiscordChannel channel)
}
};
var vsj = JsonConvert.SerializeObject(vsd, Formatting.None);
await (channel.Discord as DiscordClient).WsSendAsync(vsj).ConfigureAwait(false);
await (channel.Discord as DiscordClient).SendRawPayloadAsync(vsj).ConfigureAwait(false);
var vstu = await vstut.Task.ConfigureAwait(false);
var vsru = await vsrut.Task.ConfigureAwait(false);
await this.SendPayloadAsync(new LavalinkVoiceUpdate(vstu, vsru)).ConfigureAwait(false);
Expand Down
4 changes: 2 additions & 2 deletions DSharpPlus.VoiceNext/VoiceNextExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public async Task<VoiceNextConnection> ConnectAsync(DiscordChannel channel)
}
};
var vsj = JsonConvert.SerializeObject(vsd, Formatting.None);
await (channel.Discord as DiscordClient).WsSendAsync(vsj).ConfigureAwait(false);
await (channel.Discord as DiscordClient).SendRawPayloadAsync(vsj).ConfigureAwait(false);

var vstu = await vstut.Task.ConfigureAwait(false);
var vstup = new VoiceStateUpdatePayload
Expand Down Expand Up @@ -159,7 +159,7 @@ private async Task Vnc_VoiceDisconnected(DiscordGuild guild)
}
};
var vsj = JsonConvert.SerializeObject(vsd, Formatting.None);
await (guild.Discord as DiscordClient).WsSendAsync(vsj).ConfigureAwait(false);
await (guild.Discord as DiscordClient).SendRawPayloadAsync(vsj).ConfigureAwait(false);
}

private Task Client_VoiceStateUpdate(DiscordClient client, VoiceStateUpdateEventArgs e)
Expand Down
58 changes: 43 additions & 15 deletions DSharpPlus/Clients/DiscordClient.WebSocket.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,8 @@ public sealed partial class DiscordClient

#region Connection Semaphore

private static ConcurrentDictionary<ulong, SocketLock> SocketLocks { get; } = new ConcurrentDictionary<ulong, SocketLock>();
private ManualResetEventSlim SessionLock { get; } = new ManualResetEventSlim(true);
private static ConcurrentDictionary<ulong, SocketLock> _socketLocks { get; } = new ConcurrentDictionary<ulong, SocketLock>();
private ManualResetEventSlim _sessionLock { get; } = new ManualResetEventSlim(true);

#endregion

Expand Down Expand Up @@ -187,7 +187,7 @@ async Task SocketOnDisconnect(IWebSocketClient sender, SocketCloseEventArgs e)
{
// release session and connection
this.ConnectionLock.Set();
this.SessionLock.Set();
this._sessionLock.Set();

if (!this._disposed)
this._cancelTokenSource.Cancel();
Expand Down Expand Up @@ -269,8 +269,8 @@ internal async Task OnReconnectAsync()
internal async Task OnInvalidateSessionAsync(bool data)
{
// begin a session if one is not open already
if (this.SessionLock.Wait(0))
this.SessionLock.Reset();
if (this._sessionLock.Wait(0))
this._sessionLock.Reset();

// we are sending a fresh resume/identify, so lock the socket
var socketLock = this.GetSocketLock();
Expand All @@ -295,9 +295,9 @@ internal async Task OnHelloAsync(GatewayHello hello)
{
this.Logger.LogTrace(LoggerEvents.WebSocketReceive, "Received HELLO (OP10)");

if (this.SessionLock.Wait(0))
if (this._sessionLock.Wait(0))
{
this.SessionLock.Reset();
this._sessionLock.Reset();
this.GetSocketLock().UnlockAfter(TimeSpan.FromSeconds(5));
}
else
Expand Down Expand Up @@ -381,7 +381,7 @@ internal async Task InternalUpdateStatusAsync(DiscordActivity activity, UserStat

var statusstr = JsonConvert.SerializeObject(status_update);

await this.WsSendAsync(statusstr).ConfigureAwait(false);
await this.SendRawPayloadAsync(statusstr).ConfigureAwait(false);

if (!this._presences.ContainsKey(this.CurrentUser.Id))
{
Expand Down Expand Up @@ -442,7 +442,7 @@ internal async Task SendHeartbeatAsync(long seq)
Data = seq
};
var heartbeat_str = JsonConvert.SerializeObject(heartbeat);
await this.WsSendAsync(heartbeat_str).ConfigureAwait(false);
await this.SendRawPayloadAsync(heartbeat_str).ConfigureAwait(false);

this._lastHeartbeat = DateTimeOffset.Now;

Expand Down Expand Up @@ -470,7 +470,7 @@ internal async Task SendIdentifyAsync(StatusUpdate status)
Data = identify
};
var payloadstr = JsonConvert.SerializeObject(payload);
await this.WsSendAsync(payloadstr).ConfigureAwait(false);
await this.SendRawPayloadAsync(payloadstr).ConfigureAwait(false);

this.Logger.LogDebug(LoggerEvents.Intents, "Registered gateway intents ({Intents})", this.Configuration.Intents);
}
Expand All @@ -490,27 +490,55 @@ internal async Task SendResumeAsync()
};
var resumestr = JsonConvert.SerializeObject(resume_payload);

await this.WsSendAsync(resumestr).ConfigureAwait(false);
await this.SendRawPayloadAsync(resumestr).ConfigureAwait(false);
}

internal async Task InternalUpdateGatewayAsync()
{
var info = await this.GetGatewayInfoAsync().ConfigureAwait(false);
this.GatewayInfo = info;
this.GatewayUri = new Uri(info.Url);
}

internal async Task WsSendAsync(string payload)
internal async Task SendRawPayloadAsync(string jsonPayload)
{
this.Logger.LogTrace(LoggerEvents.GatewayWsTx, payload);
await this._webSocketClient.SendMessageAsync(payload).ConfigureAwait(false);
this.Logger.LogTrace(LoggerEvents.GatewayWsTx, jsonPayload);
await this._webSocketClient.SendMessageAsync(jsonPayload).ConfigureAwait(false);
}

#nullable enable
/// <summary>
/// Sends a raw payload to the gateway. This method is not recommended for use unless you know what you're doing.
/// </summary>
/// <param name="opCode">The opcode to send to the Discord gateway.</param>
/// <param name="data">The data to deserialize.</param>
/// <typeparam name="T">The type of data that the object belongs to.</typeparam>
/// <returns>A task representing the payload being sent.</returns>
[Obsolete("This method should not be used unless you know what you're doing. Instead, look towards the other explicitly implemented methods which come with client-side validation.")]
public Task SendPayloadAsync<T>(GatewayOpCode opCode, T data) => this.SendPayloadAsync(opCode, (object?)data);

/// <inheritdoc cref="SendPayloadAsync{T}(GatewayOpCode, T)"/>
/// <param name="data">The data to deserialize.</param>
/// <param name="opCode">The opcode to send to the Discord gateway.</param>
[Obsolete("This method should not be used unless you know what you're doing. Instead, look towards the other explicitly implemented methods which come with client-side validation.")]
public Task SendPayloadAsync(GatewayOpCode opCode, object? data = null)
{
var payload = new GatewayPayload
{
OpCode = opCode,
Data = data
};

var payloadString = DiscordJson.SerializeObject(payload);
return this.SendRawPayloadAsync(payloadString);
}
#nullable disable
#endregion

#region Semaphore Methods

private SocketLock GetSocketLock()
=> SocketLocks.GetOrAdd(this.CurrentApplication.Id, appId => new SocketLock(appId, this.GatewayInfo.SessionBucket.MaxConcurrency));
=> _socketLocks.GetOrAdd(this.CurrentApplication.Id, appId => new SocketLock(appId, this.GatewayInfo.SessionBucket.MaxConcurrency));

#endregion
}
Expand Down
2 changes: 1 addition & 1 deletion DSharpPlus/Entities/Guild/DiscordGuild.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1412,7 +1412,7 @@ public async Task RequestMembersAsync(string query = "", int limit = 0, bool? pr
};

var payloadStr = JsonConvert.SerializeObject(payload, Formatting.None);
await client.WsSendAsync(payloadStr).ConfigureAwait(false);
await client.SendRawPayloadAsync(payloadStr).ConfigureAwait(false);
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion DSharpPlus/Net/Abstractions/Gateway/GatewayOpCode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ namespace DSharpPlus.Net.Abstractions
/// <summary>
/// Specifies an OP code in a gateway payload.
/// </summary>
internal enum GatewayOpCode : int
public enum GatewayOpCode : int
{
/// <summary>
/// Used for dispatching events.
Expand Down

0 comments on commit fee6a62

Please sign in to comment.