Skip to content

Commit

Permalink
Initial RPC support (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
Auralytical authored Aug 16, 2018
1 parent 09f1dfb commit 6d5f183
Show file tree
Hide file tree
Showing 59 changed files with 960 additions and 253 deletions.
12 changes: 6 additions & 6 deletions src/Wumpus.Net.Bot/WumpusBotClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,19 +83,19 @@ public WumpusBotClient(
Gateway.EtfSerializer.UnknownProperty += path => _logger.Debug($"Unknown ETF property \"{path}\"");
Gateway.EtfSerializer.FailedProperty += path => _logger.Debug($"Failed to deserialize ETF \"{path}\"");

Gateway.ReceivedPayload += (payload, bytes) =>
Gateway.ReceivedPayload += (payload, info) =>
{
if (payload.Operation == GatewayOperation.Dispatch)
_logger.Debug($"<~ {payload.DispatchType.Value} ({bytes.Length} bytes)");
_logger.Debug($"<~ {payload.DispatchType.Value} ({info.CompressedBytes} -> {info.UncompressedBytes} bytes)");
else
_logger.Debug($"<~ {payload.Operation} ({bytes.Length} bytes)");
_logger.Debug($"<~ {payload.Operation} ({info.CompressedBytes} -> {info.UncompressedBytes} bytes)");
};
Gateway.SentPayload += (payload, bytes) =>
Gateway.SentPayload += (payload, info) =>
{
if (payload.Operation == GatewayOperation.Dispatch)
_logger.Debug($"~> {payload.DispatchType.Value} ({bytes.Length} bytes)");
_logger.Debug($"~> {payload.DispatchType.Value} ({info.UncompressedBytes} bytes)");
else
_logger.Debug($"~> {payload.Operation} ({bytes.Length} bytes)");
_logger.Debug($"~> {payload.Operation} ({info.UncompressedBytes} bytes)");
};

State.Guilds.Updated += g => _logger.Verbose($"Updated guild {g.Name}");
Expand Down
2 changes: 1 addition & 1 deletion src/Wumpus.Net.Core/Entities/Channels/Channel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public class Channel

/// <summary> The id of the <see cref="Guild"/>. </summary>
[ModelProperty("guild_id")]
public Optional<Snowflake> GuildId { get; set; }
public Optional<Snowflake?> GuildId { get; set; }
/// <summary> Sorting position of the <see cref="Channel"/>. </summary>
[ModelProperty("position")]
public Optional<int> Position { get; set; }
Expand Down
2 changes: 1 addition & 1 deletion src/Wumpus.Net.Core/Entities/Messages/Message.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public class Message
public Snowflake Id { get; set; }
// TODO: Undocumented (https://github.com/discordapp/discord-api-docs/issues/582)
[ModelProperty("guild_id")]
public Optional<Snowflake> GuildId { get; set; }
public Optional<Snowflake?> GuildId { get; set; }
/// <summary> Id of the <see cref="Channel"/> the <see cref="Message"/> was in. </summary>
[ModelProperty("channel_id")]
public Snowflake ChannelId { get; set; }
Expand Down
2 changes: 1 addition & 1 deletion src/Wumpus.Net.Core/Entities/Presences/Presence.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public class Presence
public User User { get; set; }
/// <summary> Id of the <see cref="Guild"/>. </summary>
[ModelProperty("guild_id")]
public Optional<Snowflake> GuildId { get; set; }
public Optional<Snowflake?> GuildId { get; set; }
/// <summary> Either "idle", "dnd", "online", or "offline". </summary>
[ModelProperty("status")]
public Optional<UserStatus> Status { get; set; }
Expand Down
2 changes: 1 addition & 1 deletion src/Wumpus.Net.Core/Entities/Voices/VoiceState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public class VoiceState
{
/// <summary> The <see cref="Guild"/> id this <see cref="VoiceState"/> is for. </summary>
[ModelProperty("guild_id")]
public Optional<Snowflake> GuildId { get; set; }
public Optional<Snowflake?> GuildId { get; set; }
/// <summary> The <see cref="Channel"/> id this <see cref="User"/> is connected to. </summary>
[ModelProperty("channel_id")]
public Optional<Snowflake?> ChannelId { get; set; }
Expand Down
16 changes: 16 additions & 0 deletions src/Wumpus.Net.Core/PayloadInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;

namespace Wumpus
{
public struct PayloadInfo
{
public int UncompressedBytes { get; }
public int CompressedBytes { get; }

internal PayloadInfo(int uncompressedBytes, int compressedBytes)
{
UncompressedBytes = uncompressedBytes;
CompressedBytes = compressedBytes;
}
}
}
1 change: 1 addition & 0 deletions src/Wumpus.Net.Core/Wumpus.Net.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@
<ItemGroup>
<PackageReference Include="Voltaic.Core" Version="0.2.3-*" />
<PackageReference Include="Voltaic.Serialization.Json" Version="0.2.1-*" />
<PackageReference Include="Voltaic.Serialization.Etf" Version="0.2.1-*" />
</ItemGroup>
</Project>
2 changes: 1 addition & 1 deletion src/Wumpus.Net.Gateway/Events/MessageDeleteBulkEvent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class MessageDeleteBulkEvent
public Snowflake[] Ids { get; set; }
// TODO: Undocumented (https://github.com/discordapp/discord-api-docs/issues/582)
[ModelProperty("guild_id")]
public Optional<Snowflake> GuildId { get; set; }
public Optional<Snowflake?> GuildId { get; set; }
/// <summary> The id of the <see cref="Entities.Channel"/>. </summary>
[ModelProperty("channel_id")]
public Snowflake ChannelId { get; set; }
Expand Down
2 changes: 1 addition & 1 deletion src/Wumpus.Net.Gateway/Events/MessageDeleteEvent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public class MessageDeleteEvent
public Snowflake Id { get; set; }
// TODO: Undocumented (https://github.com/discordapp/discord-api-docs/issues/582)
[ModelProperty("guild_id")]
public Optional<Snowflake> GuildId { get; set; }
public Optional<Snowflake?> GuildId { get; set; }
/// <summary> The id of the <see cref="Entities.Channel"/>. </summary>
[ModelProperty("channel_id")]
public Snowflake ChannelId { get; set; }
Expand Down
1 change: 0 additions & 1 deletion src/Wumpus.Net.Gateway/Wumpus.Net.Gateway.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="System.Net.WebSockets.Client" Version="4.3.1" />
<PackageReference Include="Voltaic.Serialization.Etf" Version="0.2.1-*" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../Wumpus.Net.Core/Wumpus.Net.Core.csproj" />
Expand Down
33 changes: 15 additions & 18 deletions src/Wumpus.Net.Gateway/WumpusGatewayClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,6 @@ public enum ConnectionState
Disconnecting
}

public enum StopReason
{
Unknown,
AuthFailed,
ShardsTooSmall,
UrlNotFound,
Exception,
Canceled
}

public class WumpusGatewayClient : IDisposable
{
public const int ApiVersion = 6;
Expand All @@ -60,8 +50,8 @@ public class WumpusGatewayClient : IDisposable
public event Action<SerializationException> DeserializationError;

// Raw events
public event Action<GatewayPayload, ReadOnlyMemory<byte>> ReceivedPayload;
public event Action<GatewayPayload, ReadOnlyMemory<byte>> SentPayload;
public event Action<GatewayPayload, PayloadInfo> ReceivedPayload;
public event Action<GatewayPayload, PayloadInfo> SentPayload;

// Gateway events
public event Action<HelloEvent> GatewayHello;
Expand Down Expand Up @@ -189,7 +179,7 @@ private async Task RunTaskAsync(UpdateStatusParams initialPresence, Cancellation
{
try
{
runCancelToken.ThrowIfCancellationRequested();
cancelToken.ThrowIfCancellationRequested();
var readySignal = new TaskCompletionSource<bool>();
_receivedData = true;

Expand Down Expand Up @@ -307,9 +297,7 @@ private Task RunSendAsync(ClientWebSocket client, CancellationToken cancelToken)
{
cancelToken.ThrowIfCancellationRequested();
var payload = _sendQueue.Take(cancelToken);
var writer = EtfSerializer.Write(payload);
await client.SendAsync(writer.AsSegment(), WebSocketMessageType.Binary, true, cancelToken);
SentPayload?.Invoke(payload, writer.AsReadOnlyMemory());
await SendAsync(client, cancelToken, payload).ConfigureAwait(false);
}
});
}
Expand Down Expand Up @@ -337,7 +325,7 @@ private async Task WhenAny(IEnumerable<Task> tasks)
}
private async Task WhenAny(IEnumerable<Task> tasks, int millis, string errorText)
{
var timeoutTask = Task.Delay(ConnectionTimeoutMillis);
var timeoutTask = Task.Delay(millis);
var task = await Task.WhenAny(tasks.Append(timeoutTask)).ConfigureAwait(false);
if (task == timeoutTask)
throw new TimeoutException(errorText);
Expand Down Expand Up @@ -381,6 +369,8 @@ private bool IsRecoverable(Exception ex)
case TimeoutException _: // Caused by missing heartbeat ack
return true;
}
if (ex.InnerException != null)
return IsRecoverable(ex.InnerException);
return false;
}

Expand Down Expand Up @@ -459,7 +449,7 @@ private async Task<GatewayPayload> ReceiveAsync(ClientWebSocket client, TaskComp

// Handle result
HandleEvent(payload, readySignal); // Must be before event so slow user handling can't trigger our timeouts
ReceivedPayload?.Invoke(payload, _compressed.Buffer.AsReadOnlyMemory());
ReceivedPayload?.Invoke(payload, new PayloadInfo(_decompressed.Buffer.Length, _compressed.Buffer.Length));
return payload;
}
private void HandleEvent(GatewayPayload evnt, TaskCompletionSource<bool> readySignal)
Expand Down Expand Up @@ -537,6 +527,13 @@ public void Send(GatewayPayload payload)
if (!_runCts.IsCancellationRequested)
_sendQueue?.Add(payload);
}
private async Task SendAsync(ClientWebSocket client, CancellationToken cancelToken, GatewayPayload payload)
{
var writer = EtfSerializer.Write(payload);
await client.SendAsync(writer.AsSegment(), WebSocketMessageType.Binary, true, cancelToken);
SentPayload?.Invoke(payload, new PayloadInfo(writer.Length, writer.Length));
}

private void SendIdentify(UpdateStatusParams initialPresence)
{
if (_sessionId is null) // IDENTITY
Expand Down
1 change: 0 additions & 1 deletion src/Wumpus.Net.Rest/Wumpus.Net.Rest.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="RestEase" Version="1.4.5" />
<PackageReference Include="Voltaic.Serialization.Json" Version="0.2.1-*" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../Wumpus.Net.Core/Wumpus.Net.Core.csproj" />
Expand Down
2 changes: 1 addition & 1 deletion src/Wumpus.Net.Rest/WumpusRestException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
using System.Net;
using Voltaic;

namespace Wumpus.Net
namespace Wumpus
{
public class WumpusRestException : Exception
{
Expand Down
16 changes: 16 additions & 0 deletions src/Wumpus.Net.Rpc/Entities/DeviceModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using Voltaic;
using Voltaic.Serialization;

namespace Wumpus.Entities
{
/// <summary> xxx </summary>
public class DeviceModel
{
/// <summary> xxx </summary>
[ModelProperty("name")]
public Utf8String Name { get; set; }
/// <summary> xxx </summary>
[ModelProperty("url")]
public Utf8String Url { get; set; }
}
}
17 changes: 17 additions & 0 deletions src/Wumpus.Net.Rpc/Entities/DeviceType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using Voltaic;
using Voltaic.Serialization;

namespace Wumpus.Entities
{
/// <summary> xxx </summary>
[ModelStringEnum]
public enum DeviceType
{
/// <summary> xxx </summary>
[ModelEnumValue("AUDIO_INPUT")] AudioInput,
/// <summary> xxx </summary>
[ModelEnumValue("AUDIO_OUTPUT")] AudioOutput,
/// <summary> xxx </summary>
[ModelEnumValue("VIDEO_INPUT")] VideoInput
}
}
16 changes: 16 additions & 0 deletions src/Wumpus.Net.Rpc/Entities/DeviceVendor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using Voltaic;
using Voltaic.Serialization;

namespace Wumpus.Entities
{
/// <summary> xxx </summary>
public class DeviceVendor
{
/// <summary> xxx </summary>
[ModelProperty("name")]
public Utf8String Name { get; set; }
/// <summary> xxx </summary>
[ModelProperty("url")]
public Utf8String Url { get; set; }
}
}
7 changes: 0 additions & 7 deletions src/Wumpus.Net.Rpc/Entities/ExtendedVoiceState.cs

This file was deleted.

34 changes: 3 additions & 31 deletions src/Wumpus.Net.Rpc/Entities/RpcChannel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,41 +4,13 @@
namespace Wumpus.Entities
{
/// <summary> xxx </summary>
public class RpcChannel
public class RpcChannel : Channel
{
//Shared
/// <summary> xxx </summary>
[ModelProperty("id")]
public Snowflake Id { get; set; }
/// <summary> xxx </summary>
[ModelProperty("type")]
public ChannelType Type { get; set; }

//GuildChannel
/// <summary> xxx </summary>
[ModelProperty("guild_id")]
public Optional<Snowflake> GuildId { get; set; }
/// <summary> xxx </summary>
[ModelProperty("name")]
public Optional<Utf8String> Name { get; set; }
/// <summary> xxx </summary>
[ModelProperty("position")]
public Optional<int> Position { get; set; }

//IMessageChannel
[ModelProperty("voice_states")]
public VoiceState[] VoiceStates { get; set; }
/// <summary> xxx </summary>
[ModelProperty("messages")]
public Message[] Messages { get; set; }

//VoiceChannel
/// <summary> xxx </summary>
[ModelProperty("bitrate")]
public Optional<int> Bitrate { get; set; }
/// <summary> xxx </summary>
[ModelProperty("user_limit")]
public Optional<int> UserLimit { get; set; }
/// <summary> xxx </summary>
[ModelProperty("voice_states")]
public RpcVoiceState[] VoiceStates { get; set; }
}
}
4 changes: 1 addition & 3 deletions src/Wumpus.Net.Rpc/Entities/RpcGuild.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace Wumpus.Entities
{
/// <summary> xxx </summary>
[IgnoreProperties("members")]
public class RpcGuild
{
/// <summary> xxx </summary>
Expand All @@ -16,8 +17,5 @@ public class RpcGuild
/// <summary> xxx </summary>
[ModelProperty("icon_url")]
public Utf8String IconUrl { get; set; }
/// <summary> xxx </summary>
[ModelProperty("members")]
public GuildMember[] Members { get; set; }
}
}
17 changes: 0 additions & 17 deletions src/Wumpus.Net.Rpc/Entities/RpcGuildMember.cs

This file was deleted.

23 changes: 0 additions & 23 deletions src/Wumpus.Net.Rpc/Entities/RpcMessage.cs

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
namespace Wumpus.Entities
{
/// <summary> xxx </summary>
public class RpcConfig
public class RpcServerConfig
{
/// <summary> xxx </summary>
[ModelProperty("cdn_host")]
Expand Down
Loading

0 comments on commit 6d5f183

Please sign in to comment.