Skip to content

Commit

Permalink
Removing nullability from all CancellationTokens and using default in…
Browse files Browse the repository at this point in the history
…stead of null

Resolves #213
  • Loading branch information
soxtoby committed Oct 12, 2024
1 parent 95fc691 commit 481b491
Show file tree
Hide file tree
Showing 50 changed files with 399 additions and 401 deletions.
2 changes: 1 addition & 1 deletion SlackNet.Bot/BotMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,5 +86,5 @@ public HubIdentifier Hub
/// <summary>
/// Allows message sending to be cancelled, if it hasn't already been sent.
/// </summary>
public CancellationToken? CancellationToken { get; set; }
public CancellationToken CancellationToken { get; set; }
}
6 changes: 3 additions & 3 deletions SlackNet.Bot/IMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public interface IMessage
IList<Block> Blocks { get; set; }
bool IsInThread { get; }
bool MentionsBot { get; }
Task ReplyWith(string text, bool createThread = false, CancellationToken? cancellationToken = null);
Task ReplyWith(BotMessage message, bool createThread = false, CancellationToken? cancellationToken = null);
Task ReplyWith(Func<Task<BotMessage>> createReply, bool createThread = false, CancellationToken? cancellationToken = null);
Task ReplyWith(string text, bool createThread = false, CancellationToken cancellationToken = default);
Task ReplyWith(BotMessage message, bool createThread = false, CancellationToken cancellationToken = default);
Task ReplyWith(Func<Task<BotMessage>> createReply, bool createThread = false, CancellationToken cancellationToken = default);
}
14 changes: 6 additions & 8 deletions SlackNet.Bot/SlackBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public interface ISlackBot : IObserver<BotMessage>
/// <summary>
/// Connect to Slack.
/// </summary>
Task Connect(CancellationToken? cancellationToken = null);
Task Connect(CancellationToken cancellationToken = default);

/// <summary>
/// Transform stream of incoming messages.
Expand Down Expand Up @@ -98,7 +98,7 @@ public interface ISlackBot : IObserver<BotMessage>
/// <summary>
/// Send a message to Slack as the bot.
/// </summary>
Task Send(BotMessage message, CancellationToken? cancellationToken = null);
Task Send(BotMessage message, CancellationToken cancellationToken = default);

/// <summary>
/// Show typing indicator in Slack while performing some action.
Expand Down Expand Up @@ -210,7 +210,7 @@ public SlackBot(ISlackRtmClient rtmClient, ISlackApiClient apiClient, IScheduler
.Where(m => m.User != Id)
.SelectMany(CreateSlackMessage);
_outgoingWithMiddlewareApplied = _outgoingMessages
.LimitFrequency(TimeSpan.FromSeconds(1), m => m.CancellationToken ?? CancellationToken.None, _scheduler);
.LimitFrequency(TimeSpan.FromSeconds(1), m => m.CancellationToken, _scheduler);
}

/// <summary>
Expand All @@ -226,7 +226,7 @@ public SlackBot(ISlackRtmClient rtmClient, ISlackApiClient apiClient, IScheduler
/// <summary>
/// Connect to Slack.
/// </summary>
public async Task Connect(CancellationToken? cancellationToken = null)
public async Task Connect(CancellationToken cancellationToken = default)
{
// If already connected, client will throw
var connection = _rtm.Connect(cancellationToken: cancellationToken);
Expand Down Expand Up @@ -451,11 +451,9 @@ private async Task<IReadOnlyList<User>> FetchUsers()
/// <summary>
/// Send a message to Slack as the bot.
/// </summary>
public async Task Send(BotMessage message, CancellationToken? cancellationToken = null)
public async Task Send(BotMessage message, CancellationToken cancellationToken = default)
{
var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(
message.CancellationToken ?? CancellationToken.None,
cancellationToken ?? CancellationToken.None);
var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(message.CancellationToken, cancellationToken);
message.CancellationToken = linkedTokenSource.Token;

var sent = _sentMessages.FirstOrDefaultAsync(m => m.Message == message)
Expand Down
6 changes: 3 additions & 3 deletions SlackNet.Bot/SlackMessage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ public class SlackMessage(ISlackBot bot) : IMessage
|| Text.IndexOf(bot.Name, StringComparison.OrdinalIgnoreCase) >= 0
|| Conversation?.IsIm == true;

public Task ReplyWith(string text, bool createThread = false, CancellationToken? cancellationToken = null) =>
public Task ReplyWith(string text, bool createThread = false, CancellationToken cancellationToken = default) =>
ReplyWith(new BotMessage { Text = text }, createThread, cancellationToken);

public async Task ReplyWith(Func<Task<BotMessage>> createReply, bool createThread = false, CancellationToken? cancellationToken = null)
public async Task ReplyWith(Func<Task<BotMessage>> createReply, bool createThread = false, CancellationToken cancellationToken = default)
{
await bot.WhileTyping(Conversation.Id, async () =>
{
Expand All @@ -45,7 +45,7 @@ await bot.WhileTyping(Conversation.Id, async () =>
}).ConfigureAwait(false);
}

public async Task ReplyWith(BotMessage message, bool createThread = false, CancellationToken? cancellationToken = null)
public async Task ReplyWith(BotMessage message, bool createThread = false, CancellationToken cancellationToken = default)
{
if (message == null) throw new ArgumentNullException(nameof(message));

Expand Down
22 changes: 11 additions & 11 deletions SlackNet.Tests/ApiLintTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ private static IEnumerable<Type> ParameterTypes(MethodInfo method)
private static void LastParamShouldBeOptionalCancellationToken(MethodInfo method)
{
var lastParam = method.GetParameters().Last();
lastParam.ParameterType.ShouldBe(typeof(CancellationToken?), $"{method.DeclaringType!.Name}.{method.Name} is missing CancellationToken param");
lastParam.ParameterType.ShouldBe(typeof(CancellationToken), $"{method.DeclaringType!.Name}.{method.Name} is missing CancellationToken param");
lastParam.DefaultValue.ShouldBeNull($"{method.DeclaringType.Name}.{method.Name} CancellationToken param isn't null by default");
}

Expand Down Expand Up @@ -145,7 +145,7 @@ private static object DummyValue(ParameterInfo param) => ArgumentFactories.TryGe
{ typeof(IEnumerable<ExternalFileReference>), _ => Enumerable.Empty<ExternalFileReference>() },
{ typeof(FileUpload), _ => new FileUpload(string.Empty, string.Empty) },
{ typeof(IEnumerable<FileUpload>), _ => Enumerable.Empty<FileUpload>() },
{ typeof(CancellationToken?), _ => null },
{ typeof(CancellationToken), _ => null },
};

private static IEnumerable<Type> ApiClasses => typeof(ApiApi).Assembly
Expand All @@ -163,47 +163,47 @@ public void Reset()
Args = null;
}

public Task Get(string apiMethod, Args args, CancellationToken? cancellationToken)
public Task Get(string apiMethod, Args args, CancellationToken cancellationToken)
{
SlackMethod = apiMethod;
Args = args;
return Task.FromResult(0);
}

public Task<T> Get<T>(string apiMethod, Args args, CancellationToken? cancellationToken) where T : class
public Task<T> Get<T>(string apiMethod, Args args, CancellationToken cancellationToken) where T : class
{
SlackMethod = apiMethod;
Args = args;
return Task.FromResult(Activator.CreateInstance<T>());
}

public Task Post(string apiMethod, Args args, HttpContent content, CancellationToken? cancellationToken)
public Task Post(string apiMethod, Args args, HttpContent content, CancellationToken cancellationToken)
{
SlackMethod = apiMethod;
Args = args;
return Task.FromResult(0);
}

public Task Post(string apiMethod, Args args, CancellationToken? cancellationToken) =>
public Task Post(string apiMethod, Args args, CancellationToken cancellationToken) =>
Post<object>(apiMethod, args, cancellationToken);

public Task<T> Post<T>(string apiMethod, Args args, CancellationToken? cancellationToken) where T : class
public Task<T> Post<T>(string apiMethod, Args args, CancellationToken cancellationToken) where T : class
{
SlackMethod = apiMethod;
Args = args;
return Task.FromResult(Activator.CreateInstance<T>());
}

public Task<T> Post<T>(string apiMethod, Args args, HttpContent content, CancellationToken? cancellationToken) where T : class
public Task<T> Post<T>(string apiMethod, Args args, HttpContent content, CancellationToken cancellationToken) where T : class
{
SlackMethod = apiMethod;
Args = args;
return Task.FromResult(Activator.CreateInstance<T>());
}

public Task Respond(string responseUrl, IReadOnlyMessage message, CancellationToken? cancellationToken) => throw new NotImplementedException();
public Task Respond(string responseUrl, IReadOnlyMessage message, CancellationToken cancellationToken) => throw new NotImplementedException();

public Task PostToWebhook(string webhookUrl, Message message, CancellationToken? cancellationToken) => throw new NotImplementedException();
public Task PostToWebhook(string webhookUrl, Message message, CancellationToken cancellationToken) => throw new NotImplementedException();

public ISlackApiClient WithAccessToken(string accessToken) => this;

Expand Down Expand Up @@ -247,6 +247,6 @@ public Task<T> Post<T>(string apiMethod, Args args, HttpContent content, Cancell

class FakeHttp : IHttp
{
public Task<T> Execute<T>(HttpRequestMessage requestMessage, CancellationToken? cancellationToken = null) => Task.FromResult(Activator.CreateInstance<T>());
public Task<T> Execute<T>(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default) => Task.FromResult(Activator.CreateInstance<T>());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -921,7 +921,7 @@ private THandler SecondRequestInstance<THandler>() where THandler : TrackedClass

protected class TestHttp : IHttp
{
public Task<T> Execute<T>(HttpRequestMessage requestMessage, CancellationToken? cancellationToken = null) => throw new NotImplementedException();
public Task<T> Execute<T>(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default) => throw new NotImplementedException();
}

protected class TestJsonSettings() : SlackJsonSettings(new JsonSerializerSettings());
Expand Down Expand Up @@ -999,21 +999,21 @@ protected class TestApiClient : ISlackApiClient
public IUserProfileApi UserProfile { get; }
public IViewsApi Views { get; }
public IWorkflowsApi Workflows { get; }
public Task Get(string apiMethod, Dictionary<string, object> args, CancellationToken? cancellationToken) => throw new NotImplementedException();
public Task<T> Get<T>(string apiMethod, Dictionary<string, object> args, CancellationToken? cancellationToken) where T : class => throw new NotImplementedException();
public Task Post(string apiMethod, Dictionary<string, object> args, CancellationToken? cancellationToken) => throw new NotImplementedException();
public Task<T> Post<T>(string apiMethod, Dictionary<string, object> args, CancellationToken? cancellationToken) where T : class => throw new NotImplementedException();
public Task Post(string apiMethod, Dictionary<string, object> args, HttpContent content, CancellationToken? cancellationToken) => throw new NotImplementedException();
public Task<T> Post<T>(string apiMethod, Dictionary<string, object> args, HttpContent content, CancellationToken? cancellationToken) where T : class => throw new NotImplementedException();
public Task Respond(string responseUrl, IReadOnlyMessage message, CancellationToken? cancellationToken) => throw new NotImplementedException();
public Task PostToWebhook(string webhookUrl, Message message, CancellationToken? cancellationToken) => throw new NotImplementedException();
public Task Get(string apiMethod, Dictionary<string, object> args, CancellationToken cancellationToken) => throw new NotImplementedException();
public Task<T> Get<T>(string apiMethod, Dictionary<string, object> args, CancellationToken cancellationToken) where T : class => throw new NotImplementedException();
public Task Post(string apiMethod, Dictionary<string, object> args, CancellationToken cancellationToken) => throw new NotImplementedException();
public Task<T> Post<T>(string apiMethod, Dictionary<string, object> args, CancellationToken cancellationToken) where T : class => throw new NotImplementedException();
public Task Post(string apiMethod, Dictionary<string, object> args, HttpContent content, CancellationToken cancellationToken) => throw new NotImplementedException();
public Task<T> Post<T>(string apiMethod, Dictionary<string, object> args, HttpContent content, CancellationToken cancellationToken) where T : class => throw new NotImplementedException();
public Task Respond(string responseUrl, IReadOnlyMessage message, CancellationToken cancellationToken) => throw new NotImplementedException();
public Task PostToWebhook(string webhookUrl, Message message, CancellationToken cancellationToken) => throw new NotImplementedException();
public ISlackApiClient WithAccessToken(string accessToken) => throw new NotImplementedException();
}

protected class TestSocketModeClient : ISlackSocketModeClient
{
public void Dispose() => throw new NotImplementedException();
public Task Connect(SocketModeConnectionOptions connectionOptions = null, CancellationToken? cancellationToken = null) => throw new NotImplementedException();
public Task Connect(SocketModeConnectionOptions connectionOptions = null, CancellationToken cancellationToken = default) => throw new NotImplementedException();
public void Disconnect() { throw new NotImplementedException(); }
public bool Connected { get; }
}
Expand Down
20 changes: 10 additions & 10 deletions SlackNet.Tests/SlackBotTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public async Task AddOutgoingMiddleware_AppliedToOutgoingMessages()

_sut.OnNext(new BotMessage { Text = "foo" });

await _api.Chat.Received().PostMessage(Arg.Is<Message>(m => m.Text == "foo++"), Arg.Any<CancellationToken?>()).ConfigureAwait(false);
await _api.Chat.Received().PostMessage(Arg.Is<Message>(m => m.Text == "foo++"), Arg.Any<CancellationToken>()).ConfigureAwait(false);
}

[Test]
Expand Down Expand Up @@ -162,7 +162,7 @@ public async Task IncomingMessage_CanReply()
_incomingMessages.OnNext(new MessageEvent());
await observer.Messages[0].Value.Value.ReplyWith("foo").ConfigureAwait(false);

await _api.Chat.Received().PostMessage(Arg.Is<Message>(m => m.Text == "foo"), Arg.Any<CancellationToken?>()).ConfigureAwait(false);
await _api.Chat.Received().PostMessage(Arg.Is<Message>(m => m.Text == "foo"), Arg.Any<CancellationToken>()).ConfigureAwait(false);
}

[Test]
Expand Down Expand Up @@ -372,7 +372,7 @@ public async Task Send_ReplyInChannel()

await _sut.Send(new BotMessage { ReplyTo = slackMessage, CreateThread = false }).ConfigureAwait(false);

await _api.Chat.Received().PostMessage(Arg.Is<Message>(message => message.ThreadTs == null), Arg.Any<CancellationToken?>()).ConfigureAwait(false);
await _api.Chat.Received().PostMessage(Arg.Is<Message>(message => message.ThreadTs == null), Arg.Any<CancellationToken>()).ConfigureAwait(false);
}

[Test]
Expand All @@ -388,7 +388,7 @@ public async Task Send_ReplyInExistingThread()

await _sut.Send(new BotMessage { ReplyTo = slackMessage, CreateThread = false }).ConfigureAwait(false);

await _api.Chat.Received().PostMessage(Arg.Is<Message>(message => message.ThreadTs == slackMessage.ThreadTs), Arg.Any<CancellationToken?>()).ConfigureAwait(false);
await _api.Chat.Received().PostMessage(Arg.Is<Message>(message => message.ThreadTs == slackMessage.ThreadTs), Arg.Any<CancellationToken>()).ConfigureAwait(false);
}

[Test]
Expand All @@ -403,7 +403,7 @@ public async Task Send_ReplyInNewThread()

await _sut.Send(new BotMessage { ReplyTo = slackMessage, CreateThread = true }).ConfigureAwait(false);

await _api.Chat.Received().PostMessage(Arg.Is<Message>(message => message.ThreadTs == slackMessage.Ts), Arg.Any<CancellationToken?>()).ConfigureAwait(false);
await _api.Chat.Received().PostMessage(Arg.Is<Message>(message => message.ThreadTs == slackMessage.Ts), Arg.Any<CancellationToken>()).ConfigureAwait(false);
}

[Test]
Expand All @@ -419,7 +419,7 @@ public async Task Send_ReplyInDifferentConversation()

await _sut.Send(new BotMessage { ReplyTo = slackMessage, Conversation = new Conversation { Id = "other_channel" } }).ConfigureAwait(false);

await _api.Chat.Received().PostMessage(Arg.Is<Message>(message => message.ThreadTs == null && message.Channel == "other_channel"), Arg.Any<CancellationToken?>()).ConfigureAwait(false);
await _api.Chat.Received().PostMessage(Arg.Is<Message>(message => message.ThreadTs == null && message.Channel == "other_channel"), Arg.Any<CancellationToken>()).ConfigureAwait(false);
}

[Test]
Expand All @@ -430,19 +430,19 @@ public async Task Send_MessagesLimitedTo1PerSecond()
var sent1 = _sut.Send(new BotMessage { Text = "foo" });
var sent2 = _sut.Send(new BotMessage { Text = "bar" });

await _api.Chat.Received().PostMessage(Arg.Is<Message>(message => message.Text == "foo"), Arg.Any<CancellationToken?>()).ConfigureAwait(false);
await _api.Chat.DidNotReceive().PostMessage(Arg.Is<Message>(message => message.Text == "bar"), Arg.Any<CancellationToken?>()).ConfigureAwait(false);
await _api.Chat.Received().PostMessage(Arg.Is<Message>(message => message.Text == "foo"), Arg.Any<CancellationToken>()).ConfigureAwait(false);
await _api.Chat.DidNotReceive().PostMessage(Arg.Is<Message>(message => message.Text == "bar"), Arg.Any<CancellationToken>()).ConfigureAwait(false);

_scheduler.AdvanceBy(TimeSpan.FromSeconds(1).Ticks);

await _api.Chat.Received().PostMessage(Arg.Is<Message>(message => message.Text == "bar"), Arg.Any<CancellationToken?>()).ConfigureAwait(false);
await _api.Chat.Received().PostMessage(Arg.Is<Message>(message => message.Text == "bar"), Arg.Any<CancellationToken>()).ConfigureAwait(false);
}

[Test]
public async Task Send_PostMessageFails_ExceptionPropagated()
{
var expectedException = new SlackException(new ErrorResponse());
_api.Chat.PostMessage(Arg.Any<Message>(), Arg.Any<CancellationToken?>()).Throws(expectedException);
_api.Chat.PostMessage(Arg.Any<Message>(), Arg.Any<CancellationToken>()).Throws(expectedException);
await Connect().ConfigureAwait(false);

_sut.Send(new BotMessage())
Expand Down
6 changes: 3 additions & 3 deletions SlackNet/Http.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ namespace SlackNet;

public interface IHttp
{
Task<T> Execute<T>(HttpRequestMessage requestMessage, CancellationToken? cancellationToken = null);
Task<T> Execute<T>(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default);
}

class Http(Func<HttpClient> getHttpClient, SlackJsonSettings jsonSettings, ILogger logger) : IHttp
{
private readonly ILogger _log = logger.ForSource<Http>();

public async Task<T> Execute<T>(HttpRequestMessage requestMessage, CancellationToken? cancellationToken = null)
public async Task<T> Execute<T>(HttpRequestMessage requestMessage, CancellationToken cancellationToken = default)
{
HttpResponseMessage response;

Expand All @@ -26,7 +26,7 @@ public async Task<T> Execute<T>(HttpRequestMessage requestMessage, CancellationT

try
{
response = await getHttpClient().SendAsync(requestMessage, cancellationToken ?? CancellationToken.None).ConfigureAwait(false);
response = await getHttpClient().SendAsync(requestMessage, cancellationToken).ConfigureAwait(false);
requestLog
.WithContext("ResponseStatus", response.StatusCode)
.WithContext("ResponseReason", response.ReasonPhrase)
Expand Down
Loading

0 comments on commit 481b491

Please sign in to comment.