Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Incomplete Ready, DownloadUsersAsync, and optimize AlwaysDownloadUsers #1548

Merged
merged 5 commits into from
Jun 18, 2020
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/Discord.Net.WebSocket/DiscordSocketClient.Events.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,13 @@ public event Func<Exception, Task> Disconnected
remove { _disconnectedEvent.Remove(value); }
}
private readonly AsyncEvent<Func<Exception, Task>> _disconnectedEvent = new AsyncEvent<Func<Exception, Task>>();
/// <summary> Fired when guild data has finished downloading. </summary>
/// <summary>
/// Fired when guild data has finished downloading.
/// </summary>
/// <remarks>
/// It is possible that some guilds might be unsynced if <see cref="DiscordSocketConfig.MaxWaitBetweenGuildAvailablesBeforeReady" />
/// was not long enough to receive all GUILD_AVAILABLEs before READY.
/// </remarks>
public event Func<Task> Ready
{
add { _readyEvent.Add(value); }
Expand Down
11 changes: 7 additions & 4 deletions src/Discord.Net.WebSocket/DiscordSocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ private DiscordSocketClient(DiscordSocketConfig config, API.DiscordSocketApiClie

GuildAvailable += g =>
{
if (ConnectionState == ConnectionState.Connected && AlwaysDownloadUsers && !g.HasAllMembers)
if (_guildDownloadTask?.IsCompleted == true && ConnectionState == ConnectionState.Connected && AlwaysDownloadUsers && !g.HasAllMembers)
{
var _ = g.DownloadUsersAsync();
}
Expand Down Expand Up @@ -368,15 +368,15 @@ private async Task ProcessUserDownloadsAsync(IEnumerable<SocketGuild> guilds)
{
var cachedGuilds = guilds.ToImmutableArray();

const short batchSize = 50;
const short batchSize = 100; //TODO: Gateway Intents will limit to a maximum of 1 guild_id
ulong[] batchIds = new ulong[Math.Min(batchSize, cachedGuilds.Length)];
Task[] batchTasks = new Task[batchIds.Length];
int batchCount = (cachedGuilds.Length + (batchSize - 1)) / batchSize;

for (int i = 0, k = 0; i < batchCount; i++)
{
bool isLast = i == batchCount - 1;
int count = isLast ? (batchIds.Length - (batchCount - 1) * batchSize) : batchSize;
int count = isLast ? (cachedGuilds.Length - (batchCount - 1) * batchSize) : batchSize;

for (int j = 0; j < count; j++, k++)
{
Expand Down Expand Up @@ -576,6 +576,9 @@ private async Task ProcessMessageAsync(GatewayOpCode opCode, int? seq, string ty
}
else if (_connection.CancelToken.IsCancellationRequested)
return;

if (BaseConfig.AlwaysDownloadUsers)
_ = DownloadUsersAsync(Guilds.Where(x => x.IsAvailable && !x.HasAllMembers));

await TimedInvokeAsync(_readyEvent, nameof(Ready)).ConfigureAwait(false);
await _gatewayLogger.InfoAsync("Ready").ConfigureAwait(false);
Expand Down Expand Up @@ -1742,7 +1745,7 @@ private async Task WaitForGuildsAsync(CancellationToken cancelToken, Logger logg
try
{
await logger.DebugAsync("GuildDownloader Started").ConfigureAwait(false);
while ((_unavailableGuildCount != 0) && (Environment.TickCount - _lastGuildAvailableTime < 2000))
while ((_unavailableGuildCount != 0) && (Environment.TickCount - _lastGuildAvailableTime < BaseConfig.MaxWaitBetweenGuildAvailablesBeforeReady))
await Task.Delay(500, cancelToken).ConfigureAwait(false);
await logger.DebugAsync("GuildDownloader Stopped").ConfigureAwait(false);
}
Expand Down
26 changes: 26 additions & 0 deletions src/Discord.Net.WebSocket/DiscordSocketConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,32 @@ public class DiscordSocketConfig : DiscordRestConfig
/// </summary>
public bool GuildSubscriptions { get; set; } = true;

/// <summary>
/// Gets or sets the maximum wait time in milliseconds between GUILD_AVAILABLE events before firing READY.
///
/// If zero, READY will fire as soon as it is received and all guilds will be unavailable.
/// </summary>
/// <remarks>
/// <para>This property is measured in milliseconds, negative values will throw an exception.</para>
/// <para>If a guild is not received before READY, it will be unavailable.</para>
/// </remarks>
/// <returns>
/// The maximum wait time in milliseconds between GUILD_AVAILABLE events before firing READY.
/// </returns>
/// <exception cref="System.ArgumentException">Value must be at least 0.</exception>
public int MaxWaitBetweenGuildAvailablesBeforeReady {
get
{
return _maxWaitForGuildAvailable;
}
set
{
Preconditions.AtLeast(value, 0, nameof(MaxWaitBetweenGuildAvailablesBeforeReady));
_maxWaitForGuildAvailable = value;
}
}
private int _maxWaitForGuildAvailable = 10000;

/// <summary>
/// Initializes a default configuration.
/// </summary>
Expand Down