diff --git a/src/Tgstation.Server.Host.Console/PosixSignalChecker.cs b/src/Tgstation.Server.Host.Console/PosixSignalChecker.cs index a2ffceb69f..e037b5936f 100644 --- a/src/Tgstation.Server.Host.Console/PosixSignalChecker.cs +++ b/src/Tgstation.Server.Host.Console/PosixSignalChecker.cs @@ -31,7 +31,7 @@ namespace Tgstation.Server.Host.Console } /// - public async Task CheckSignals(Func startChild, CancellationToken cancellationToken) + public async ValueTask CheckSignals(Func startChild, CancellationToken cancellationToken) { var (childPid, _) = startChild?.Invoke(null) ?? throw new ArgumentNullException(nameof(startChild)); var signalTcs = new TaskCompletionSource(); diff --git a/src/Tgstation.Server.Host.Service/Program.cs b/src/Tgstation.Server.Host.Service/Program.cs index bb12d5c8f7..9e6deaeb63 100644 --- a/src/Tgstation.Server.Host.Service/Program.cs +++ b/src/Tgstation.Server.Host.Service/Program.cs @@ -116,7 +116,7 @@ namespace Tgstation.Server.Host.Service } if (Configure) - await RunConfigure(CancellationToken.None); // DCT: None available + await RunConfigure(CancellationToken.None); // DCT: None available bool stopped = false; if (Uninstall) @@ -281,7 +281,7 @@ namespace Tgstation.Server.Host.Service /// /// The for the operation. /// A representing the running operation. - async Task RunConfigure(CancellationToken cancellationToken) + async ValueTask RunConfigure(CancellationToken cancellationToken) { using var loggerFactory = LoggerFactory.Create(builder => { diff --git a/src/Tgstation.Server.Host.Service/ServerService.cs b/src/Tgstation.Server.Host.Service/ServerService.cs index 978aee638e..8f5554304f 100644 --- a/src/Tgstation.Server.Host.Service/ServerService.cs +++ b/src/Tgstation.Server.Host.Service/ServerService.cs @@ -90,7 +90,7 @@ namespace Tgstation.Server.Host.Service } /// - public async Task CheckSignals(Func startChildAndGetPid, CancellationToken cancellationToken) + public async ValueTask CheckSignals(Func startChildAndGetPid, CancellationToken cancellationToken) { await using (commandPipeServer = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable)) await using (readyPipeServer = new AnonymousPipeServerStream(PipeDirection.In, HandleInheritability.Inheritable)) diff --git a/src/Tgstation.Server.Host.Watchdog/ISignalChecker.cs b/src/Tgstation.Server.Host.Watchdog/ISignalChecker.cs index 8ab3b06df6..b23295dd0f 100644 --- a/src/Tgstation.Server.Host.Watchdog/ISignalChecker.cs +++ b/src/Tgstation.Server.Host.Watchdog/ISignalChecker.cs @@ -14,7 +14,7 @@ namespace Tgstation.Server.Host.Watchdog /// /// An to start the main process. It accepts an optional additional command line argument as a paramter and returns it's and lifetime . /// The for the operation. - /// A representing the running operation. - Task CheckSignals(Func startChild, CancellationToken cancellationToken); + /// A representing the running operation. + ValueTask CheckSignals(Func startChild, CancellationToken cancellationToken); } } diff --git a/src/Tgstation.Server.Host.Watchdog/IWatchdog.cs b/src/Tgstation.Server.Host.Watchdog/IWatchdog.cs index a9c5dfb4a7..dadff2c41b 100644 --- a/src/Tgstation.Server.Host.Watchdog/IWatchdog.cs +++ b/src/Tgstation.Server.Host.Watchdog/IWatchdog.cs @@ -20,7 +20,7 @@ namespace Tgstation.Server.Host.Watchdog /// If the should just run the host configuration wizard and exit. /// The arguments for the . /// The for the operation. - /// A resulting in if there were no errors, otherwise. - Task RunAsync(bool runConfigure, string[] args, CancellationToken cancellationToken); + /// A resulting in if there were no errors, otherwise. + ValueTask RunAsync(bool runConfigure, string[] args, CancellationToken cancellationToken); } } diff --git a/src/Tgstation.Server.Host.Watchdog/NoopSignalChecker.cs b/src/Tgstation.Server.Host.Watchdog/NoopSignalChecker.cs index 409eed8fbc..fa5dd56f94 100644 --- a/src/Tgstation.Server.Host.Watchdog/NoopSignalChecker.cs +++ b/src/Tgstation.Server.Host.Watchdog/NoopSignalChecker.cs @@ -10,11 +10,11 @@ namespace Tgstation.Server.Host.Watchdog public sealed class NoopSignalChecker : ISignalChecker { /// - public Task CheckSignals(Func startChild, CancellationToken cancellationToken) + public ValueTask CheckSignals(Func startChild, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(startChild); startChild(null); - return Task.CompletedTask; + return ValueTask.CompletedTask; } } } diff --git a/src/Tgstation.Server.Host.Watchdog/Watchdog.cs b/src/Tgstation.Server.Host.Watchdog/Watchdog.cs index 21d60f5203..a13dc2f5f1 100644 --- a/src/Tgstation.Server.Host.Watchdog/Watchdog.cs +++ b/src/Tgstation.Server.Host.Watchdog/Watchdog.cs @@ -46,7 +46,7 @@ namespace Tgstation.Server.Host.Watchdog /// #pragma warning disable CA1502 // TODO: Decomplexify #pragma warning disable CA1506 - public async Task RunAsync(bool runConfigure, string[] args, CancellationToken cancellationToken) + public async ValueTask RunAsync(bool runConfigure, string[] args, CancellationToken cancellationToken) { logger.LogInformation("Host watchdog starting..."); int currentProcessId; diff --git a/src/Tgstation.Server.Host/Components/Byond/ByondInstallerBase.cs b/src/Tgstation.Server.Host/Components/Byond/ByondInstallerBase.cs index 698f2a5563..2478acdc1f 100644 --- a/src/Tgstation.Server.Host/Components/Byond/ByondInstallerBase.cs +++ b/src/Tgstation.Server.Host/Components/Byond/ByondInstallerBase.cs @@ -66,7 +66,7 @@ namespace Tgstation.Server.Host.Components.Byond public abstract string GetDreamDaemonName(Version version, out bool supportsCli, out bool supportsMapThreads); /// - public async ValueTask CleanCache(CancellationToken cancellationToken) + public async Task CleanCache(CancellationToken cancellationToken) { try { diff --git a/src/Tgstation.Server.Host/Components/Byond/IByondInstaller.cs b/src/Tgstation.Server.Host/Components/Byond/IByondInstaller.cs index e678068d62..9c35337830 100644 --- a/src/Tgstation.Server.Host/Components/Byond/IByondInstaller.cs +++ b/src/Tgstation.Server.Host/Components/Byond/IByondInstaller.cs @@ -59,7 +59,7 @@ namespace Tgstation.Server.Host.Components.Byond /// Attempts to cleans the BYOND cache folder for the system. /// /// The for the operation. - /// A representing the running operation. - ValueTask CleanCache(CancellationToken cancellationToken); + /// A representing the running operation. + Task CleanCache(CancellationToken cancellationToken); } } diff --git a/src/Tgstation.Server.Host/Components/Chat/ChatManager.cs b/src/Tgstation.Server.Host/Components/Chat/ChatManager.cs index 7c27d08d39..ecb0fa6498 100644 --- a/src/Tgstation.Server.Host/Components/Chat/ChatManager.cs +++ b/src/Tgstation.Server.Host/Components/Chat/ChatManager.cs @@ -178,7 +178,7 @@ namespace Tgstation.Server.Host.Components.Chat } /// - public async Task ChangeChannels(long connectionId, IEnumerable newChannels, CancellationToken cancellationToken) + public async ValueTask ChangeChannels(long connectionId, IEnumerable newChannels, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(newChannels); @@ -261,7 +261,7 @@ namespace Tgstation.Server.Host.Components.Chat } /// - public async Task ChangeSettings(Models.ChatBot newSettings, CancellationToken cancellationToken) + public async ValueTask ChangeSettings(Models.ChatBot newSettings, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(newSettings); @@ -412,7 +412,7 @@ namespace Tgstation.Server.Host.Components.Chat AddMessageTask(task); Task callbackTask; - Func finalUpdateAction = null; + Func finalUpdateAction = null; async Task CallbackTask(string errorMessage, string dreamMakerOutput) { await task; @@ -423,10 +423,10 @@ namespace Tgstation.Server.Host.Components.Chat dreamMakerOutput)), callbacks.Count); - finalUpdateAction = active => ValueTaskExtensions.WhenAll(callbackResults.Select(finalizerCallback => finalizerCallback(active))); + finalUpdateAction = active => ValueTaskExtensions.WhenAll(callbackResults.Select(finalizerCallback => finalizerCallback(active))).AsTask(); } - async ValueTask CompletionTask(bool active) + async Task CompletionTask(bool active) { try { @@ -438,14 +438,14 @@ namespace Tgstation.Server.Host.Components.Chat return; } - AddMessageTask(finalUpdateAction(active).AsTask()); + AddMessageTask(finalUpdateAction(active)); } return (errorMessage, dreamMakerOutput) => { callbackTask = CallbackTask(errorMessage, dreamMakerOutput); AddMessageTask(callbackTask); - return active => AddMessageTask(CompletionTask(active).AsTask()); + return active => AddMessageTask(CompletionTask(active)); }; } @@ -455,7 +455,7 @@ namespace Tgstation.Server.Host.Components.Chat foreach (var tgsCommand in commandFactory.GenerateCommands()) builtinCommands.Add(tgsCommand.Name.ToUpperInvariant(), tgsCommand); var initialChatBots = activeChatBots.ToList(); - await Task.WhenAll(initialChatBots.Select(x => ChangeSettings(x, cancellationToken))); + await ValueTaskExtensions.WhenAll(initialChatBots.Select(x => ChangeSettings(x, cancellationToken))); initialProviderConnectionsTask = InitialConnection(); chatHandler = MonitorMessages(handlerCts.Token); } @@ -495,7 +495,7 @@ namespace Tgstation.Server.Host.Components.Chat } /// - public async Task UpdateTrackingContexts(CancellationToken cancellationToken) + public async ValueTask UpdateTrackingContexts(CancellationToken cancellationToken) { var logMessageSent = 0; async Task UpdateTrackingContext(IChatTrackingContext channelSink, IEnumerable channels) @@ -589,8 +589,8 @@ namespace Tgstation.Server.Host.Components.Chat /// The of the to delete. /// If the provider should be removed from and should be update. /// The for the operation. - /// A resulting in the being removed if it exists, otherwise. - async Task RemoveProviderChannels(long connectionId, bool removeProvider, CancellationToken cancellationToken) + /// A resulting in the being removed if it exists, otherwise. + async ValueTask RemoveProviderChannels(long connectionId, bool removeProvider, CancellationToken cancellationToken) { logger.LogTrace("RemoveProviderChannels {connectionId}...", connectionId); IProvider provider; @@ -936,7 +936,7 @@ namespace Tgstation.Server.Host.Components.Chat { logger.LogTrace("Starting processing loop..."); var messageTasks = new Dictionary>(); - Task activeProcessingTask = Task.CompletedTask; + ValueTask activeProcessingTask = ValueTask.CompletedTask; try { Task updatedTask = null; @@ -956,7 +956,7 @@ namespace Tgstation.Server.Host.Components.Chat if (!messageTasks.ContainsKey(providerKvp.Value)) messageTasks.Add( providerKvp.Value, - providerKvp.Value.NextMessage(cancellationToken).AsTask()); + providerKvp.Value.NextMessage(cancellationToken)); if (messageTasks.Count == 0) { @@ -981,7 +981,7 @@ namespace Tgstation.Server.Host.Components.Chat var message = await completedMessageTaskKvp.Value; var messageNumber = Interlocked.Increment(ref messagesProcessed); - async Task WrapProcessMessage() + async ValueTask WrapProcessMessage() { var localActiveProcessingTask = activeProcessingTask; using (LogContext.PushProperty(SerilogContextHelper.ChatMessageIterationContextProperty, messageNumber)) diff --git a/src/Tgstation.Server.Host/Components/Chat/IChatManager.cs b/src/Tgstation.Server.Host/Components/Chat/IChatManager.cs index f5ef9da42f..769ab7b251 100644 --- a/src/Tgstation.Server.Host/Components/Chat/IChatManager.cs +++ b/src/Tgstation.Server.Host/Components/Chat/IChatManager.cs @@ -24,8 +24,8 @@ namespace Tgstation.Server.Host.Components.Chat /// /// The new . /// The for the operation. - /// A representing the running operation. Will complete immediately if the property of is . - Task ChangeSettings(Models.ChatBot newSettings, CancellationToken cancellationToken); + /// A representing the running operation. Will complete immediately if the property of is . + ValueTask ChangeSettings(Models.ChatBot newSettings, CancellationToken cancellationToken); /// /// Disconnects and deletes a given connection. @@ -41,8 +41,8 @@ namespace Tgstation.Server.Host.Components.Chat /// The of the connection. /// An of the new list of s. /// The for the operation. - /// A representing the running operation. - Task ChangeChannels(long connectionId, IEnumerable newChannels, CancellationToken cancellationToken); + /// A representing the running operation. + ValueTask ChangeChannels(long connectionId, IEnumerable newChannels, CancellationToken cancellationToken); /// /// Queue a chat to a given set of . @@ -85,7 +85,7 @@ namespace Tgstation.Server.Host.Components.Chat /// Force an update with the active channels on all active s. /// /// The for the operation. - /// A representing the running operation. - Task UpdateTrackingContexts(CancellationToken cancellationToken); + /// A representing the running operation. + ValueTask UpdateTrackingContexts(CancellationToken cancellationToken); } } diff --git a/src/Tgstation.Server.Host/Components/Chat/Providers/DiscordProvider.cs b/src/Tgstation.Server.Host/Components/Chat/Providers/DiscordProvider.cs index b30af6e0c9..fa6098c6e0 100644 --- a/src/Tgstation.Server.Host/Components/Chat/Providers/DiscordProvider.cs +++ b/src/Tgstation.Server.Host/Components/Chat/Providers/DiscordProvider.cs @@ -260,7 +260,7 @@ namespace Tgstation.Server.Host.Components.Chat.Providers var embeds = ConvertEmbed(message.Embed); var channelsClient = serviceProvider.GetRequiredService(); - async Task SendToChannel(Snowflake channelId) + async ValueTask SendToChannel(Snowflake channelId) { var result = await channelsClient.CreateMessageAsync( channelId, @@ -312,7 +312,7 @@ namespace Tgstation.Server.Host.Components.Chat.Providers if (unmappedTextChannels.Any()) { Logger.LogDebug("Dispatching to {count} unmapped channels...", unmappedTextChannels.Count()); - await Task.WhenAll( + await ValueTaskExtensions.WhenAll( unmappedTextChannels.Select( x => SendToChannel(x.ID))); } @@ -430,7 +430,7 @@ namespace Tgstation.Server.Host.Components.Chat.Providers var updatedMessageText = $"DM: Deployment {completionString}!"; IMessage updatedMessage = null; - async Task CreateUpdatedMessage() + async ValueTask CreateUpdatedMessage() { var createUpdatedMessageResponse = await channelsClient.CreateMessageAsync( new Snowflake(channelId), diff --git a/src/Tgstation.Server.Host/Components/Chat/Providers/IProvider.cs b/src/Tgstation.Server.Host/Components/Chat/Providers/IProvider.cs index ed39d40000..641372c318 100644 --- a/src/Tgstation.Server.Host/Components/Chat/Providers/IProvider.cs +++ b/src/Tgstation.Server.Host/Components/Chat/Providers/IProvider.cs @@ -39,12 +39,12 @@ namespace Tgstation.Server.Host.Components.Chat.Providers void InitialMappingComplete(); /// - /// Get a resulting in the next the recieves or on a disconnect. + /// Get a resulting in the next the recieves or on a disconnect. /// /// The for the operation. - /// A resulting in the next available or if the needed to reconnect. + /// A resulting in the next available or if the needed to reconnect. /// Note that private messages will come in the form of s not returned in . - ValueTask NextMessage(CancellationToken cancellationToken); + Task NextMessage(CancellationToken cancellationToken); /// /// Gracefully disconnects the provider. Permanently stops the reconnection timer. diff --git a/src/Tgstation.Server.Host/Components/Chat/Providers/IrcProvider.cs b/src/Tgstation.Server.Host/Components/Chat/Providers/IrcProvider.cs index b978687a71..c4449e00ea 100644 --- a/src/Tgstation.Server.Host/Components/Chat/Providers/IrcProvider.cs +++ b/src/Tgstation.Server.Host/Components/Chat/Providers/IrcProvider.cs @@ -595,8 +595,8 @@ namespace Tgstation.Server.Host.Components.Chat.Providers /// Run SASL authentication on . /// /// The for the operation. - /// A representing the running operation. - async Task SaslAuthenticate(CancellationToken cancellationToken) + /// A representing the running operation. + async ValueTask SaslAuthenticate(CancellationToken cancellationToken) { client.WriteLine("CAP REQ :sasl", Priority.Critical); // needs to be put in the buffer before anything else cancellationToken.ThrowIfCancellationRequested(); @@ -665,8 +665,8 @@ namespace Tgstation.Server.Host.Components.Chat.Providers /// Attempt to disconnect from IRC immediately. /// /// The for the operation. - /// A representing the running operation. - async Task HardDisconnect(CancellationToken cancellationToken) + /// A representing the running operation. + async ValueTask HardDisconnect(CancellationToken cancellationToken) { if (!Connected) { diff --git a/src/Tgstation.Server.Host/Components/Chat/Providers/Provider.cs b/src/Tgstation.Server.Host/Components/Chat/Providers/Provider.cs index 90430565ef..88cd5b2e2c 100644 --- a/src/Tgstation.Server.Host/Components/Chat/Providers/Provider.cs +++ b/src/Tgstation.Server.Host/Components/Chat/Providers/Provider.cs @@ -144,7 +144,7 @@ namespace Tgstation.Server.Host.Components.Chat.Providers } /// - public async ValueTask NextMessage(CancellationToken cancellationToken) + public async Task NextMessage(CancellationToken cancellationToken) { while (true) { @@ -171,7 +171,7 @@ namespace Tgstation.Server.Host.Components.Chat.Providers { stopOldTimerTask = StopReconnectionTimer(); reconnectCts = new CancellationTokenSource(); - reconnectTask = ReconnectionLoop(reconnectInterval, connectNow, reconnectCts.Token).AsTask(); + reconnectTask = ReconnectionLoop(reconnectInterval, connectNow, reconnectCts.Token); } return stopOldTimerTask; @@ -260,8 +260,8 @@ namespace Tgstation.Server.Host.Components.Chat.Providers /// The amount of minutes to wait between reconnection attempts. /// If a connection attempt should be immediately made. /// The for the operation. - /// A representing the running operation. - async ValueTask ReconnectionLoop(uint reconnectInterval, bool connectNow, CancellationToken cancellationToken) + /// A representing the running operation. + async Task ReconnectionLoop(uint reconnectInterval, bool connectNow, CancellationToken cancellationToken) { do { diff --git a/src/Tgstation.Server.Host/Components/Deployment/DreamMaker.cs b/src/Tgstation.Server.Host/Components/Deployment/DreamMaker.cs index 6793fdfb7f..30f6a555df 100644 --- a/src/Tgstation.Server.Host/Components/Deployment/DreamMaker.cs +++ b/src/Tgstation.Server.Host/Components/Deployment/DreamMaker.cs @@ -422,8 +422,8 @@ namespace Tgstation.Server.Host.Components.Deployment /// /// The to retrieve previous deployment s from. /// The for the operation. - /// A resulting in the average of the 10 previous deployments or if there are none. - async Task CalculateExpectedDeploymentTime(IDatabaseContext databaseContext, CancellationToken cancellationToken) + /// A resulting in the average of the 10 previous deployments or if there are none. + async ValueTask CalculateExpectedDeploymentTime(IDatabaseContext databaseContext, CancellationToken cancellationToken) { var previousCompileJobs = await databaseContext .CompileJobs @@ -462,8 +462,8 @@ namespace Tgstation.Server.Host.Components.Deployment /// The optional estimated of the compilation. /// Whether or not the 's current commit exists on the remote repository. /// The for the operation. - /// A resulting in the completed . - async Task Compile( + /// A resulting in the completed . + async ValueTask Compile( Models.RevisionInformation revisionInformation, Api.Models.Internal.DreamMakerSettings dreamMakerSettings, DreamDaemonLaunchParameters launchParameters, @@ -557,8 +557,8 @@ namespace Tgstation.Server.Host.Components.Deployment /// The to use. /// The to use. /// The for the operation. - /// A representing the running operation. - async Task RunCompileJob( + /// A representing the running operation. + async ValueTask RunCompileJob( JobProgressReporter progressReporter, Models.CompileJob job, Api.Models.Internal.DreamMakerSettings dreamMakerSettings, @@ -711,8 +711,8 @@ namespace Tgstation.Server.Host.Components.Deployment /// The to report progress of the operation. /// A representing the duration to give progress over if any. /// The for the operation. - /// A representing the running operation. - async Task ProgressTask(JobProgressReporter progressReporter, TimeSpan? estimatedDuration, CancellationToken cancellationToken) + /// A representing the running operation. + async ValueTask ProgressTask(JobProgressReporter progressReporter, TimeSpan? estimatedDuration, CancellationToken cancellationToken) { double? lastReport = estimatedDuration.HasValue ? 0 : null; progressReporter.ReportProgress(lastReport); @@ -774,8 +774,8 @@ namespace Tgstation.Server.Host.Components.Deployment /// If the API validation is required to complete the deployment. /// If output should be logged to the DreamDaemon Diagnostics folder. /// The for the operation. - /// A representing the running operation. - async Task VerifyApi( + /// A representing the running operation. + async ValueTask VerifyApi( uint timeout, DreamDaemonSecurity securityLevel, Models.CompileJob job, @@ -856,8 +856,8 @@ namespace Tgstation.Server.Host.Components.Deployment /// The path to the DreamMaker executable. /// The for the operation. /// The for the operation. - /// A representing the running operation. - async Task RunDreamMaker(string dreamMakerPath, Models.CompileJob job, CancellationToken cancellationToken) + /// A representing the running operation. + async ValueTask RunDreamMaker(string dreamMakerPath, Models.CompileJob job, CancellationToken cancellationToken) { await using var dm = processExecutor.LaunchProcess( dreamMakerPath, @@ -887,8 +887,8 @@ namespace Tgstation.Server.Host.Components.Deployment /// /// The for the operation. /// The for the operation. - /// A representing the running operation. - async Task ModifyDme(Models.CompileJob job, CancellationToken cancellationToken) + /// A representing the running operation. + async ValueTask ModifyDme(Models.CompileJob job, CancellationToken cancellationToken) { var dmeFileName = String.Join('.', job.DmeName, DmeExtension); var dmePath = ioManager.ConcatPath(job.DirectoryName.ToString(), dmeFileName); diff --git a/src/Tgstation.Server.Host/Components/Deployment/SwappableDmbProvider.cs b/src/Tgstation.Server.Host/Components/Deployment/SwappableDmbProvider.cs index e496453222..b3d8505e65 100644 --- a/src/Tgstation.Server.Host/Components/Deployment/SwappableDmbProvider.cs +++ b/src/Tgstation.Server.Host/Components/Deployment/SwappableDmbProvider.cs @@ -74,8 +74,8 @@ namespace Tgstation.Server.Host.Components.Deployment /// Make the active by replacing the live link with our . /// /// The for the operation. - /// A representing the running operation. - public async Task MakeActive(CancellationToken cancellationToken) + /// A representing the running operation. + public async ValueTask MakeActive(CancellationToken cancellationToken) { if (Interlocked.Exchange(ref swapped, 1) != 0) throw new InvalidOperationException("Already swapped!"); diff --git a/src/Tgstation.Server.Host/Components/Instance.cs b/src/Tgstation.Server.Host/Components/Instance.cs index f812c51e74..879478a207 100644 --- a/src/Tgstation.Server.Host/Components/Instance.cs +++ b/src/Tgstation.Server.Host/Components/Instance.cs @@ -317,7 +317,7 @@ namespace Tgstation.Server.Host.Components var hasDbChanges = false; RevisionInformation currentRevInfo = null; Models.Instance attachedInstance = null; - async Task UpdateRevInfo(string currentHead, bool onOrigin, IEnumerable updatedTestMerges) + async ValueTask UpdateRevInfo(string currentHead, bool onOrigin, IEnumerable updatedTestMerges) { if (currentRevInfo == null) { diff --git a/src/Tgstation.Server.Host/Components/InstanceFactory.cs b/src/Tgstation.Server.Host/Components/InstanceFactory.cs index 9667a9f6e8..6d9d7a8b61 100644 --- a/src/Tgstation.Server.Host/Components/InstanceFactory.cs +++ b/src/Tgstation.Server.Host/Components/InstanceFactory.cs @@ -419,7 +419,7 @@ namespace Tgstation.Server.Host.Components public Task StartAsync(CancellationToken cancellationToken) { CheckSystemCompatibility(); - return byondInstaller.CleanCache(cancellationToken).AsTask(); + return byondInstaller.CleanCache(cancellationToken); } /// diff --git a/src/Tgstation.Server.Host/Components/InstanceManager.cs b/src/Tgstation.Server.Host/Components/InstanceManager.cs index eeae580d05..ec66af63b1 100644 --- a/src/Tgstation.Server.Host/Components/InstanceManager.cs +++ b/src/Tgstation.Server.Host/Components/InstanceManager.cs @@ -460,7 +460,7 @@ namespace Tgstation.Server.Host.Components var instanceFactoryStopTask = instanceFactory.StopAsync(cancellationToken); await jobService.StopAsync(cancellationToken); - async Task OfflineInstanceImmediate(IInstance instance, CancellationToken cancellationToken) + async ValueTask OfflineInstanceImmediate(IInstance instance, CancellationToken cancellationToken) { try { @@ -472,7 +472,7 @@ namespace Tgstation.Server.Host.Components } } - await Task.WhenAll(instances.Select(x => OfflineInstanceImmediate(x.Value.Instance, cancellationToken))); + await ValueTaskExtensions.WhenAll(instances.Select(x => OfflineInstanceImmediate(x.Value.Instance, cancellationToken))); await instanceFactoryStopTask; await swarmServiceController.Shutdown(cancellationToken); @@ -490,7 +490,7 @@ namespace Tgstation.Server.Host.Components } /// - public async Task ProcessBridgeRequest(BridgeParameters parameters, CancellationToken cancellationToken) + public async ValueTask ProcessBridgeRequest(BridgeParameters parameters, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(parameters); @@ -650,8 +650,8 @@ namespace Tgstation.Server.Host.Components /// Initializes the connection to the TGS swarm. /// /// The for the operation. - /// A representing the running operation. - async Task InitializeSwarm(CancellationToken cancellationToken) + /// A representing the running operation. + async ValueTask InitializeSwarm(CancellationToken cancellationToken) { SwarmRegistrationResult registrationResult; do diff --git a/src/Tgstation.Server.Host/Components/Interop/Bridge/IBridgeDispatcher.cs b/src/Tgstation.Server.Host/Components/Interop/Bridge/IBridgeDispatcher.cs index 2a7a9e00d7..82de2d6631 100644 --- a/src/Tgstation.Server.Host/Components/Interop/Bridge/IBridgeDispatcher.cs +++ b/src/Tgstation.Server.Host/Components/Interop/Bridge/IBridgeDispatcher.cs @@ -13,7 +13,7 @@ namespace Tgstation.Server.Host.Components.Interop.Bridge /// /// The to handle. /// The for the operation. - /// A resulting in the for the request or if the request could not be dispatched. - Task ProcessBridgeRequest(BridgeParameters parameters, CancellationToken cancellationToken); + /// A resulting in the for the request or if the request could not be dispatched. + ValueTask ProcessBridgeRequest(BridgeParameters parameters, CancellationToken cancellationToken); } } diff --git a/src/Tgstation.Server.Host/Components/Interop/Chunker.cs b/src/Tgstation.Server.Host/Components/Interop/Chunker.cs index 7363f3aee8..d6a0c7c024 100644 --- a/src/Tgstation.Server.Host/Components/Interop/Chunker.cs +++ b/src/Tgstation.Server.Host/Components/Interop/Chunker.cs @@ -63,9 +63,9 @@ namespace Tgstation.Server.Host.Components.Interop /// The callback that generates a for a given error. /// The . /// The for the operation. - /// A resulting in the for the chunked request. - protected async Task ProcessChunk( - Func> completionCallback, + /// A resulting in the for the chunked request. + protected async ValueTask ProcessChunk( + Func> completionCallback, Func chunkErrorCallback, ChunkData chunk, CancellationToken cancellationToken) diff --git a/src/Tgstation.Server.Host/Components/Repository/Repository.cs b/src/Tgstation.Server.Host/Components/Repository/Repository.cs index 928d873ae4..46cc06fd8e 100644 --- a/src/Tgstation.Server.Host/Components/Repository/Repository.cs +++ b/src/Tgstation.Server.Host/Components/Repository/Repository.cs @@ -535,7 +535,7 @@ namespace Tgstation.Server.Host.Components.Repository if (postWriteHandler.NeedsPostWrite(src)) postWriteHandler.HandleWrite(dest); - return Task.CompletedTask; + return ValueTask.CompletedTask; }, ioMananger.ResolvePath(), path, @@ -992,8 +992,8 @@ namespace Tgstation.Server.Host.Components.Repository /// The password for the . /// If any events created should be marked as part of the deployment pipeline. /// The for the operation. - /// A representing the running operation. - async Task UpdateSubmodules( + /// A representing the running operation. + async ValueTask UpdateSubmodules( JobProgressReporter progressReporter, string username, string password, diff --git a/src/Tgstation.Server.Host/Components/Session/SessionController.cs b/src/Tgstation.Server.Host/Components/Session/SessionController.cs index f4b340e4f5..d3749f0e9f 100644 --- a/src/Tgstation.Server.Host/Components/Session/SessionController.cs +++ b/src/Tgstation.Server.Host/Components/Session/SessionController.cs @@ -362,7 +362,7 @@ namespace Tgstation.Server.Host.Components.Session } /// - public async Task ProcessBridgeRequest(BridgeParameters parameters, CancellationToken cancellationToken) + public async ValueTask ProcessBridgeRequest(BridgeParameters parameters, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(parameters); @@ -439,7 +439,7 @@ namespace Tgstation.Server.Host.Components.Session (completedResponse, cancellationToken) => { fullResponse = completedResponse; - return Task.FromResult(null); + return ValueTask.FromResult(null); }, error => { @@ -574,7 +574,7 @@ namespace Tgstation.Server.Host.Components.Session cancellationToken); /// - public Task CreateDump(string outputFile, CancellationToken cancellationToken) => process.CreateDump(outputFile, cancellationToken); + public ValueTask CreateDump(string outputFile, CancellationToken cancellationToken) => process.CreateDump(outputFile, cancellationToken); /// /// The for . @@ -660,8 +660,8 @@ namespace Tgstation.Server.Host.Components.Session /// /// The to handle. /// The for the operation. - /// A resulting in the for the request or if the request could not be dispatched. - async Task ProcessBridgeCommand(BridgeParameters parameters, CancellationToken cancellationToken) + /// A resulting in the for the request or if the request could not be dispatched. + async ValueTask ProcessBridgeCommand(BridgeParameters parameters, CancellationToken cancellationToken) { var response = new BridgeResponse(); switch (parameters.CommandType) @@ -828,8 +828,8 @@ namespace Tgstation.Server.Host.Components.Session /// /// The to send. /// The for the operation. - /// A resulting in the of the topic request. - async Task SendTopicRequest(TopicParameters parameters, CancellationToken cancellationToken) + /// A resulting in the of the topic request. + async ValueTask SendTopicRequest(TopicParameters parameters, CancellationToken cancellationToken) { parameters.AccessIdentifier = ReattachInformation.AccessIdentifier; @@ -971,8 +971,8 @@ namespace Tgstation.Server.Host.Components.Session /// The sanitized topic query string to send. /// If this is a priority message. If so, the topic will make 5 attempts to send unless BYOND reboots or exits. /// The for the operation. - /// A resulting in the of the topic request. - async Task SendRawTopic(string queryString, bool priority, CancellationToken cancellationToken) + /// A resulting in the of the topic request. + async ValueTask SendRawTopic(string queryString, bool priority, CancellationToken cancellationToken) { if (disposed) { diff --git a/src/Tgstation.Server.Host/Components/Session/SessionControllerFactory.cs b/src/Tgstation.Server.Host/Components/Session/SessionControllerFactory.cs index 97fee0a95e..3bc79939c7 100644 --- a/src/Tgstation.Server.Host/Components/Session/SessionControllerFactory.cs +++ b/src/Tgstation.Server.Host/Components/Session/SessionControllerFactory.cs @@ -239,6 +239,7 @@ namespace Tgstation.Server.Host.Components.Session } /// + #pragma warning disable CA1506 // TODO: Decomplexify public async ValueTask LaunchNew( IDmbProvider dmbProvider, IByondExecutableLock currentByondLock, @@ -283,7 +284,7 @@ namespace Tgstation.Server.Host.Components.Session dmbProvider.CompileJob.Id); PortBindTest(launchParameters.Port.Value); - await CheckPagerIsNotRunning(cancellationToken); + await CheckPagerIsNotRunning(); string outputFilePath = null; var preserveLogFile = true; @@ -393,6 +394,7 @@ namespace Tgstation.Server.Host.Components.Session throw; } } +#pragma warning restore CA1506 /// public async ValueTask Reattach( @@ -647,9 +649,8 @@ namespace Tgstation.Server.Host.Components.Session /// /// Make sure the BYOND pager is not running. /// - /// The for the operation. - /// A representing the running operation. - async Task CheckPagerIsNotRunning(CancellationToken cancellationToken) + /// A representing the running operation. + async ValueTask CheckPagerIsNotRunning() { if (!platformIdentifier.IsWindows) return; @@ -658,12 +659,12 @@ namespace Tgstation.Server.Host.Components.Session if (otherProcess == null) return; - var otherUsernameTask = otherProcess.GetExecutingUsername(cancellationToken); - await using var ourProcess = processExecutor.GetCurrentProcess(); - var ourUserName = await ourProcess.GetExecutingUsername(cancellationToken); - var otherUserName = await otherUsernameTask; + var otherUsername = otherProcess.GetExecutingUsername(); - if (otherUserName.Equals(ourUserName, StringComparison.Ordinal)) + await using var ourProcess = processExecutor.GetCurrentProcess(); + var ourUsername = ourProcess.GetExecutingUsername(); + + if (otherUsername.Equals(ourUsername, StringComparison.Ordinal)) throw new JobException(ErrorCode.DeploymentPagerRunning); } } diff --git a/src/Tgstation.Server.Host/Components/Session/SessionPersistor.cs b/src/Tgstation.Server.Host/Components/Session/SessionPersistor.cs index 5b44e93c54..5c3819f8be 100644 --- a/src/Tgstation.Server.Host/Components/Session/SessionPersistor.cs +++ b/src/Tgstation.Server.Host/Components/Session/SessionPersistor.cs @@ -95,7 +95,7 @@ namespace Tgstation.Server.Host.Components.Session Models.ReattachInformation result = null; TimeSpan? topicTimeout = null; - async Task KillProcess(Models.ReattachInformation reattachInfo) + async ValueTask KillProcess(Models.ReattachInformation reattachInfo) { try { diff --git a/src/Tgstation.Server.Host/Components/StaticFiles/Configuration.cs b/src/Tgstation.Server.Host/Components/StaticFiles/Configuration.cs index 067869b539..2b19803126 100644 --- a/src/Tgstation.Server.Host/Components/StaticFiles/Configuration.cs +++ b/src/Tgstation.Server.Host/Components/StaticFiles/Configuration.cs @@ -219,7 +219,7 @@ namespace Tgstation.Server.Host.Components.StaticFiles generalConfiguration.GetCopyDirectoryTaskThrottle(), cancellationToken); - await Task.WhenAll(dmeExistsTask, headFileExistsTask, tailFileExistsTask, copyTask); + await Task.WhenAll(dmeExistsTask, headFileExistsTask, tailFileExistsTask, copyTask.AsTask()); if (!dmeExistsTask.Result && !headFileExistsTask.Result && !tailFileExistsTask.Result) return null; @@ -396,26 +396,7 @@ namespace Tgstation.Server.Host.Components.StaticFiles /// public async ValueTask SymlinkStaticFilesTo(string destination, CancellationToken cancellationToken) { - async Task> GetIgnoreFiles() - { - var ignoreFileBytes = await ioManager.ReadAllBytes(StaticIgnorePath(), cancellationToken); - var ignoreFileText = Encoding.UTF8.GetString(ignoreFileBytes); - - var results = new List { StaticIgnoreFile }; - - // we don't want to lose trailing whitespace on linux - using (var reader = new StringReader(ignoreFileText)) - { - cancellationToken.ThrowIfCancellationRequested(); - var line = await reader.ReadLineAsync(); - if (!String.IsNullOrEmpty(line)) - results.Add(line); - } - - return results; - } - - IReadOnlyList ignoreFiles; + List ignoreFiles; async ValueTask SymlinkBase(bool files) { @@ -458,7 +439,20 @@ namespace Tgstation.Server.Host.Components.StaticFiles using (await SemaphoreSlimContext.Lock(semaphore, cancellationToken)) { await EnsureDirectories(cancellationToken); - ignoreFiles = await GetIgnoreFiles(); + var ignoreFileBytes = await ioManager.ReadAllBytes(StaticIgnorePath(), cancellationToken); + var ignoreFileText = Encoding.UTF8.GetString(ignoreFileBytes); + + ignoreFiles = new List { StaticIgnoreFile }; + + // we don't want to lose trailing whitespace on linux + using (var reader = new StringReader(ignoreFileText)) + { + cancellationToken.ThrowIfCancellationRequested(); + var line = await reader.ReadLineAsync(); + if (!String.IsNullOrEmpty(line)) + ignoreFiles.Add(line); + } + await ValueTaskExtensions.WhenAll(SymlinkBase(true), SymlinkBase(false)); } } @@ -705,7 +699,7 @@ namespace Tgstation.Server.Host.Components.StaticFiles /// /// The for the operation. /// A representing the running operation. - async Task EnsureDirectories(CancellationToken cancellationToken) + Task EnsureDirectories(CancellationToken cancellationToken) { async Task ValidateStaticFolder() { @@ -721,7 +715,7 @@ namespace Tgstation.Server.Host.Components.StaticFiles return; await ioManager.CreateDirectory(CodeModificationsSubdirectory, cancellationToken); - await Task.WhenAll( + await ValueTaskExtensions.WhenAll( ioManager.WriteAllBytes( ioManager.ConcatPath( CodeModificationsSubdirectory, @@ -736,7 +730,7 @@ namespace Tgstation.Server.Host.Components.StaticFiles cancellationToken)); } - await Task.WhenAll( + return Task.WhenAll( ValidateCodeModsFolder(), ioManager.CreateDirectory(EventScriptsSubdirectory, cancellationToken), ValidateStaticFolder()); diff --git a/src/Tgstation.Server.Host/Components/Watchdog/WatchdogBase.cs b/src/Tgstation.Server.Host/Components/Watchdog/WatchdogBase.cs index a7eb583a7d..3847e26077 100644 --- a/src/Tgstation.Server.Host/Components/Watchdog/WatchdogBase.cs +++ b/src/Tgstation.Server.Host/Components/Watchdog/WatchdogBase.cs @@ -395,8 +395,8 @@ namespace Tgstation.Server.Host.Components.Watchdog } /// - public Task StopAsync(CancellationToken cancellationToken) => - TerminateNoLock(false, !releaseServers, cancellationToken); + public async Task StopAsync(CancellationToken cancellationToken) => + await TerminateNoLock(false, !releaseServers, cancellationToken); /// public async ValueTask Terminate(bool graceful, CancellationToken cancellationToken) @@ -1002,8 +1002,8 @@ namespace Tgstation.Server.Host.Components.Watchdog /// If the termination will be delayed until a reboot is detected in the active server's DMAPI and this function will return immediately. /// If the termination will be announced using . /// The for the operation. - /// A representing the running operation. - async Task TerminateNoLock(bool graceful, bool announce, CancellationToken cancellationToken) + /// A representing the running operation. + async ValueTask TerminateNoLock(bool graceful, bool announce, CancellationToken cancellationToken) { if (Status == WatchdogStatus.Offline) return; diff --git a/src/Tgstation.Server.Host/Components/Watchdog/WindowsWatchdog.cs b/src/Tgstation.Server.Host/Components/Watchdog/WindowsWatchdog.cs index fd1ab5fb18..cdc5307352 100644 --- a/src/Tgstation.Server.Host/Components/Watchdog/WindowsWatchdog.cs +++ b/src/Tgstation.Server.Host/Components/Watchdog/WindowsWatchdog.cs @@ -331,8 +331,8 @@ namespace Tgstation.Server.Host.Components.Watchdog /// Create the initial link to the live game directory using . /// /// The for the operation. - /// A representing the running operation. - Task InitialLink(CancellationToken cancellationToken) + /// A representing the running operation. + ValueTask InitialLink(CancellationToken cancellationToken) { Logger.LogTrace("Symlinking compile job..."); return ActiveSwappable.MakeActive(cancellationToken); diff --git a/src/Tgstation.Server.Host/IO/BufferedFileStreamProvider.cs b/src/Tgstation.Server.Host/IO/BufferedFileStreamProvider.cs index bf578ac7d4..a369f41047 100644 --- a/src/Tgstation.Server.Host/IO/BufferedFileStreamProvider.cs +++ b/src/Tgstation.Server.Host/IO/BufferedFileStreamProvider.cs @@ -95,14 +95,14 @@ namespace Tgstation.Server.Host.IO /// /// The for the operation. /// A representing the running operation. - public Task EnsureBuffered(CancellationToken cancellationToken) => GetResultInternal(cancellationToken); + public Task EnsureBuffered(CancellationToken cancellationToken) => GetResultInternal(cancellationToken).AsTask(); /// /// Gets the shared and its . /// /// The for the operation. /// A resulting in and its . - async Task<(MemoryStream, long)> GetResultInternal(CancellationToken cancellationToken) + async ValueTask<(MemoryStream, long)> GetResultInternal(CancellationToken cancellationToken) { if (!buffered) using (await SemaphoreSlimContext.Lock(semaphore, cancellationToken)) diff --git a/src/Tgstation.Server.Host/IO/DefaultIOManager.cs b/src/Tgstation.Server.Host/IO/DefaultIOManager.cs index 23d36cafd5..8416ca9bf3 100644 --- a/src/Tgstation.Server.Host/IO/DefaultIOManager.cs +++ b/src/Tgstation.Server.Host/IO/DefaultIOManager.cs @@ -68,9 +68,9 @@ namespace Tgstation.Server.Host.IO } /// - public async Task CopyDirectory( + public async ValueTask CopyDirectory( IEnumerable ignore, - Func postCopyCallback, + Func postCopyCallback, string src, string dest, int? taskThrottle, @@ -93,7 +93,7 @@ namespace Tgstation.Server.Host.IO public string ConcatPath(params string[] paths) => Path.Combine(paths); /// - public async Task CopyFile(string src, string dest, CancellationToken cancellationToken) + public async ValueTask CopyFile(string src, string dest, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(src); ArgumentNullException.ThrowIfNull(dest); @@ -197,7 +197,7 @@ namespace Tgstation.Server.Host.IO TaskScheduler.Current); /// - public async Task ReadAllBytes(string path, CancellationToken cancellationToken) + public async ValueTask ReadAllBytes(string path, CancellationToken cancellationToken) { path = ResolvePath(path); await using var file = new FileStream( @@ -220,7 +220,7 @@ namespace Tgstation.Server.Host.IO public virtual string ResolvePath(string path) => Path.GetFullPath(path ?? throw new ArgumentNullException(nameof(path))); /// - public async Task WriteAllBytes(string path, byte[] contents, CancellationToken cancellationToken) + public async ValueTask WriteAllBytes(string path, byte[] contents, CancellationToken cancellationToken) { await using var file = CreateAsyncSequentialWriteStream(path); await file.WriteAsync(contents, cancellationToken); @@ -345,7 +345,7 @@ namespace Tgstation.Server.Host.IO string src, string dest, IEnumerable ignore, - Func postCopyCallback, + Func postCopyCallback, SemaphoreSlim semaphore, CancellationToken cancellationToken) { diff --git a/src/Tgstation.Server.Host/IO/IIOManager.cs b/src/Tgstation.Server.Host/IO/IIOManager.cs index 16be142e7d..045036e98c 100644 --- a/src/Tgstation.Server.Host/IO/IIOManager.cs +++ b/src/Tgstation.Server.Host/IO/IIOManager.cs @@ -54,10 +54,10 @@ namespace Tgstation.Server.Host.IO /// The destination directory path. /// The optional maximum number of simultaneous tasks allowed to execute. /// The for the operation. - /// A representing the running operation. - Task CopyDirectory( + /// A representing the running operation. + ValueTask CopyDirectory( IEnumerable ignore, - Func postCopyCallback, + Func postCopyCallback, string src, string dest, int? taskThrottle, @@ -84,8 +84,8 @@ namespace Tgstation.Server.Host.IO /// /// The path of the file to read. /// A for the operation. - /// A that results in the contents of a file at . - Task ReadAllBytes(string path, CancellationToken cancellationToken); + /// A that results in the contents of a file at . + ValueTask ReadAllBytes(string path, CancellationToken cancellationToken); /// /// Returns directory names in a given . @@ -116,8 +116,8 @@ namespace Tgstation.Server.Host.IO /// The path of the file to write. /// The contents of the file. /// A for the operation. - /// A representing the running operation. - Task WriteAllBytes(string path, byte[] contents, CancellationToken cancellationToken); + /// A representing the running operation. + ValueTask WriteAllBytes(string path, byte[] contents, CancellationToken cancellationToken); /// /// Copy a file from to . @@ -125,8 +125,8 @@ namespace Tgstation.Server.Host.IO /// The source file to copy. /// The destination path. /// A for the operation. - /// A representing the running operation. - Task CopyFile(string src, string dest, CancellationToken cancellationToken); + /// A representing the running operation. + ValueTask CopyFile(string src, string dest, CancellationToken cancellationToken); /// /// Gets the directory portion of a given . diff --git a/src/Tgstation.Server.Host/Setup/SetupWizard.cs b/src/Tgstation.Server.Host/Setup/SetupWizard.cs index 40656cad2e..a1a5717e8c 100644 --- a/src/Tgstation.Server.Host/Setup/SetupWizard.cs +++ b/src/Tgstation.Server.Host/Setup/SetupWizard.cs @@ -137,8 +137,8 @@ namespace Tgstation.Server.Host.Setup /// The question . /// The optional default response if the user doesn't enter anything. /// The for the operation. - /// A resulting in if the user replied yes, otherwise. - async Task PromptYesNo(string question, bool? defaultResponse, CancellationToken cancellationToken) + /// A resulting in if the user replied yes, otherwise. + async ValueTask PromptYesNo(string question, bool? defaultResponse, CancellationToken cancellationToken) { do { @@ -167,8 +167,8 @@ namespace Tgstation.Server.Host.Setup /// Prompts the user to enter the port to host TGS on. /// /// The for the operation. - /// A resulting in the hosting port, or to use the default. - async Task PromptForHostingPort(CancellationToken cancellationToken) + /// A resulting in the hosting port, or to use the default. + async ValueTask PromptForHostingPort(CancellationToken cancellationToken) { await console.WriteAsync(null, true, cancellationToken); await console.WriteAsync("What port would you like to connect to TGS on?", true, cancellationToken); @@ -198,8 +198,8 @@ namespace Tgstation.Server.Host.Setup /// The database name (or path in the case of a database). /// Whether or not the database exists. /// The for the operation. - /// A representing the running operation. - async Task TestDatabaseConnection( + /// A representing the running operation. + async ValueTask TestDatabaseConnection( DbConnection testConnection, DatabaseConfiguration databaseConfiguration, string databaseName, @@ -290,8 +290,8 @@ namespace Tgstation.Server.Host.Setup /// /// The path to the potential SQLite database file. /// The for the operation. - /// A resulting in the SQLite database path to store in the configuration. - async Task ValidateNonExistantSqliteDBName(string databaseName, CancellationToken cancellationToken) + /// A resulting in the SQLite database path to store in the configuration. + async ValueTask ValidateNonExistantSqliteDBName(string databaseName, CancellationToken cancellationToken) { var dbPathIsRooted = Path.IsPathRooted(databaseName); var resolvedPath = ioManager.ResolvePath( @@ -343,8 +343,8 @@ namespace Tgstation.Server.Host.Setup /// /// If this is the user's first time here. /// The for the operation. - /// A resulting in the input . - async Task PromptDatabaseType(bool firstTime, CancellationToken cancellationToken) + /// A resulting in the input . + async ValueTask PromptDatabaseType(bool firstTime, CancellationToken cancellationToken) { if (firstTime) { @@ -392,9 +392,9 @@ namespace Tgstation.Server.Host.Setup /// Prompts the user to create a . /// /// The for the operation. - /// A resulting in the new . + /// A resulting in the new . #pragma warning disable CA1502 // TODO: Decomplexify - async Task ConfigureDatabase(CancellationToken cancellationToken) + async ValueTask ConfigureDatabase(CancellationToken cancellationToken) { bool firstTime = true; do @@ -656,8 +656,8 @@ namespace Tgstation.Server.Host.Setup /// Prompts the user to create a . /// /// The for the operation. - /// A resulting in the new . - async Task ConfigureGeneral(CancellationToken cancellationToken) + /// A resulting in the new . + async ValueTask ConfigureGeneral(CancellationToken cancellationToken) { var newGeneralConfiguration = new GeneralConfiguration { @@ -714,8 +714,8 @@ namespace Tgstation.Server.Host.Setup /// Prompts the user to create a . /// /// The for the operation. - /// A resulting in the new . - async Task ConfigureLogging(CancellationToken cancellationToken) + /// A resulting in the new . + async ValueTask ConfigureLogging(CancellationToken cancellationToken) { var fileLoggingConfiguration = new FileLoggingConfiguration(); await console.WriteAsync(null, true, cancellationToken); @@ -771,7 +771,7 @@ namespace Tgstation.Server.Host.Setup } while (true); - async Task PromptLogLevel(string question) + async ValueTask PromptLogLevel(string question) { do { @@ -799,8 +799,8 @@ namespace Tgstation.Server.Host.Setup /// Prompts the user to create a . /// /// The for the operation. - /// A resulting in the new . - async Task ConfigureElasticsearch(CancellationToken cancellationToken) + /// A resulting in the new . + async ValueTask ConfigureElasticsearch(CancellationToken cancellationToken) { var elasticsearchConfiguration = new ElasticsearchConfiguration(); await console.WriteAsync(null, true, cancellationToken); @@ -851,8 +851,8 @@ namespace Tgstation.Server.Host.Setup /// Prompts the user to create a . /// /// The for the operation. - /// A resulting in the new . - async Task ConfigureControlPanel(CancellationToken cancellationToken) + /// A resulting in the new . + async ValueTask ConfigureControlPanel(CancellationToken cancellationToken) { var config = new ControlPanelConfiguration { @@ -881,8 +881,8 @@ namespace Tgstation.Server.Host.Setup /// Prompts the user to create a . /// /// The for the operation. - /// A resulting in the new . - async Task ConfigureSwarm(CancellationToken cancellationToken) + /// A resulting in the new . + async ValueTask ConfigureSwarm(CancellationToken cancellationToken) { var enable = await PromptYesNo("Enable swarm mode?", false, cancellationToken); if (!enable) @@ -896,7 +896,7 @@ namespace Tgstation.Server.Host.Setup } while (String.IsNullOrWhiteSpace(identifer)); - async Task ParseAddress(string question) + async ValueTask ParseAddress(string question) { var first = true; Uri address; @@ -956,8 +956,8 @@ namespace Tgstation.Server.Host.Setup /// The to save. /// The to save. /// The for the operation. - /// A representing the running operation. - async Task SaveConfiguration( + /// A representing the running operation. + async ValueTask SaveConfiguration( string userConfigFileName, ushort? hostingPort, DatabaseConfiguration databaseConfiguration, @@ -1027,8 +1027,8 @@ namespace Tgstation.Server.Host.Setup /// /// The path to the settings json to build. /// The for the operation. - /// A representing the running operation. - async Task RunWizard(string userConfigFileName, CancellationToken cancellationToken) + /// A representing the running operation. + async ValueTask RunWizard(string userConfigFileName, CancellationToken cancellationToken) { // welcome message await console.WriteAsync($"Welcome to {Constants.CanonicalPackageName}!", true, cancellationToken); @@ -1067,8 +1067,8 @@ namespace Tgstation.Server.Host.Setup /// Check if it should and run the if necessary. /// /// The for the operation. - /// A representing the running operation. - async Task CheckRunWizard(CancellationToken cancellationToken) + /// A representing the running operation. + async ValueTask CheckRunWizard(CancellationToken cancellationToken) { var setupWizardMode = generalConfiguration.SetupWizardMode; if (setupWizardMode == SetupWizardMode.Never) diff --git a/src/Tgstation.Server.Host/Swarm/ISwarmOperations.cs b/src/Tgstation.Server.Host/Swarm/ISwarmOperations.cs index a2cae0c47c..a1c0a276cd 100644 --- a/src/Tgstation.Server.Host/Swarm/ISwarmOperations.cs +++ b/src/Tgstation.Server.Host/Swarm/ISwarmOperations.cs @@ -23,8 +23,8 @@ namespace Tgstation.Server.Host.Swarm /// /// The . /// The for the operation. - /// A resulting in if the node is able to update, otherwise. - Task PrepareUpdateFromController(SwarmUpdateRequest updateRequest, CancellationToken cancellationToken); + /// A resulting in if the node is able to update, otherwise. + ValueTask PrepareUpdateFromController(SwarmUpdateRequest updateRequest, CancellationToken cancellationToken); /// /// Validate a given . @@ -39,23 +39,23 @@ namespace Tgstation.Server.Host.Swarm /// The that is registering. /// The registration . /// The for the operation. - /// A resulting in if the registration was successful, otherwise. - Task RegisterNode(Api.Models.Internal.SwarmServer node, Guid registrationId, CancellationToken cancellationToken); + /// A resulting in if the registration was successful, otherwise. + ValueTask RegisterNode(Api.Models.Internal.SwarmServer node, Guid registrationId, CancellationToken cancellationToken); /// /// Attempt to unregister a node with a given with the controller. /// /// The registration . /// The for the operation. - /// A representing the running operation. - Task UnregisterNode(Guid registrationId, CancellationToken cancellationToken); + /// A representing the running operation. + ValueTask UnregisterNode(Guid registrationId, CancellationToken cancellationToken); /// /// Notify the controller that the node with the given is ready to commit or notify the node of the controller telling it to commit. /// /// The registration . /// The for the operation. - /// A representing the running operation. - Task RemoteCommitRecieved(Guid registrationId, CancellationToken cancellationToken); + /// A representing the running operation. + ValueTask RemoteCommitRecieved(Guid registrationId, CancellationToken cancellationToken); } } diff --git a/src/Tgstation.Server.Host/Swarm/ISwarmService.cs b/src/Tgstation.Server.Host/Swarm/ISwarmService.cs index c8d3866320..9b86389540 100644 --- a/src/Tgstation.Server.Host/Swarm/ISwarmService.cs +++ b/src/Tgstation.Server.Host/Swarm/ISwarmService.cs @@ -24,15 +24,15 @@ namespace Tgstation.Server.Host.Swarm /// The to relay to other nodes. /// The to update to. /// The for the operation. - /// A resulting in if the update should proceed, otherwise. - Task PrepareUpdate(ISeekableFileStreamProvider fileStreamProvider, Version version, CancellationToken cancellationToken); + /// A resulting in if the update should proceed, otherwise. + ValueTask PrepareUpdate(ISeekableFileStreamProvider fileStreamProvider, Version version, CancellationToken cancellationToken); /// /// Signal to the swarm that an update is ready to be applied. /// /// The for the operation. - /// A resulting in the . - Task CommitUpdate(CancellationToken cancellationToken); + /// A resulting in the . + ValueTask CommitUpdate(CancellationToken cancellationToken); /// /// Gets the list of s in the swarm, including the current one. diff --git a/src/Tgstation.Server.Host/Swarm/ISwarmServiceController.cs b/src/Tgstation.Server.Host/Swarm/ISwarmServiceController.cs index 5912232e04..34babd945b 100644 --- a/src/Tgstation.Server.Host/Swarm/ISwarmServiceController.cs +++ b/src/Tgstation.Server.Host/Swarm/ISwarmServiceController.cs @@ -12,14 +12,14 @@ namespace Tgstation.Server.Host.Swarm /// Attempt to register with the swarm controller if not one, sets up the database otherwise. /// /// The for the operation. - /// A resulting in the . - Task Initialize(CancellationToken cancellationToken); + /// A resulting in the . + ValueTask Initialize(CancellationToken cancellationToken); /// /// Deregister with the swarm controller or put clients into querying state. /// /// The for the operation. - /// A representing the running operation. - Task Shutdown(CancellationToken cancellationToken); + /// A representing the running operation. + ValueTask Shutdown(CancellationToken cancellationToken); } } diff --git a/src/Tgstation.Server.Host/Swarm/ISwarmUpdateAborter.cs b/src/Tgstation.Server.Host/Swarm/ISwarmUpdateAborter.cs index e3f59893f6..8d69505f27 100644 --- a/src/Tgstation.Server.Host/Swarm/ISwarmUpdateAborter.cs +++ b/src/Tgstation.Server.Host/Swarm/ISwarmUpdateAborter.cs @@ -10,8 +10,8 @@ namespace Tgstation.Server.Host.Swarm /// /// Attempt to abort an uncommitted update. /// - /// A representing the running operation. + /// A representing the running operation. /// This method does not accept a because aborting an update should never be cancelled. - Task AbortUpdate(); + ValueTask AbortUpdate(); } } diff --git a/src/Tgstation.Server.Host/Swarm/SwarmService.cs b/src/Tgstation.Server.Host/Swarm/SwarmService.cs index 317f97463e..7340d4b25d 100644 --- a/src/Tgstation.Server.Host/Swarm/SwarmService.cs +++ b/src/Tgstation.Server.Host/Swarm/SwarmService.cs @@ -16,6 +16,7 @@ using Microsoft.Extensions.Options; using Newtonsoft.Json; using Tgstation.Server.Api.Models.Response; +using Tgstation.Server.Common.Extensions; using Tgstation.Server.Common.Http; using Tgstation.Server.Host.Configuration; using Tgstation.Server.Host.Core; @@ -211,7 +212,7 @@ namespace Tgstation.Server.Host.Swarm public void Dispose() => serverHealthCheckCancellationTokenSource?.Dispose(); /// - public async Task AbortUpdate() + public async ValueTask AbortUpdate() { if (!SwarmMode) return; @@ -239,7 +240,7 @@ namespace Tgstation.Server.Host.Swarm } /// - public async Task CommitUpdate(CancellationToken cancellationToken) + public async ValueTask CommitUpdate(CancellationToken cancellationToken) { if (!SwarmMode) return SwarmCommitResult.ContinueUpdateNonCommitted; @@ -311,7 +312,7 @@ namespace Tgstation.Server.Host.Swarm // on the controller, we first need to signal for nodes to go ahead // if anything fails at this point, there's nothing we can do logger.LogDebug("Sending remote commit message to nodes..."); - async Task SendRemoteCommitUpdate(SwarmServerResponse swarmServer) + async ValueTask SendRemoteCommitUpdate(SwarmServerResponse swarmServer) { using var request = PrepareSwarmRequest( swarmServer, @@ -332,12 +333,13 @@ namespace Tgstation.Server.Host.Swarm } } - Task task; + ValueTask task; lock (swarmServers) - task = Task.WhenAll( + task = ValueTaskExtensions.WhenAll( swarmServers .Where(x => !x.Controller) - .Select(SendRemoteCommitUpdate)); + .Select(SendRemoteCommitUpdate) + .ToList()); await task; return SwarmCommitResult.MustCommitUpdate; @@ -354,7 +356,7 @@ namespace Tgstation.Server.Host.Swarm } /// - public Task PrepareUpdate(ISeekableFileStreamProvider fileStreamProvider, Version version, CancellationToken cancellationToken) + public ValueTask PrepareUpdate(ISeekableFileStreamProvider fileStreamProvider, Version version, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(fileStreamProvider); @@ -371,7 +373,7 @@ namespace Tgstation.Server.Host.Swarm } /// - public async Task PrepareUpdateFromController(SwarmUpdateRequest updateRequest, CancellationToken cancellationToken) + public async ValueTask PrepareUpdateFromController(SwarmUpdateRequest updateRequest, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(updateRequest); @@ -385,7 +387,7 @@ namespace Tgstation.Server.Host.Swarm } /// - public async Task Initialize(CancellationToken cancellationToken) + public async ValueTask Initialize(CancellationToken cancellationToken) { if (SwarmMode) logger.LogInformation( @@ -418,11 +420,11 @@ namespace Tgstation.Server.Host.Swarm } /// - public async Task Shutdown(CancellationToken cancellationToken) + public async ValueTask Shutdown(CancellationToken cancellationToken) { logger.LogTrace("Begin Shutdown"); - async Task SendUnregistrationRequest(SwarmServerResponse swarmServer) + async ValueTask SendUnregistrationRequest(SwarmServerResponse swarmServer) { using var httpClient = httpClientFactory.CreateClient(); using var request = PrepareSwarmRequest( @@ -478,13 +480,14 @@ namespace Tgstation.Server.Host.Swarm if (updateOperation == null) { logger.LogInformation("Unregistering nodes..."); - Task task; + ValueTask task; lock (swarmServers) { - task = Task.WhenAll( + task = ValueTaskExtensions.WhenAll( swarmServers .Where(x => !x.Controller) - .Select(SendUnregistrationRequest)); + .Select(SendUnregistrationRequest) + .ToList()); swarmServers.RemoveRange(1, swarmServers.Count - 1); registrationIdsAndTimes.Clear(); } @@ -527,7 +530,7 @@ namespace Tgstation.Server.Host.Swarm } /// - public async Task RegisterNode(Api.Models.Internal.SwarmServer node, Guid registrationId, CancellationToken cancellationToken) + public async ValueTask RegisterNode(Api.Models.Internal.SwarmServer node, Guid registrationId, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(node); @@ -586,7 +589,7 @@ namespace Tgstation.Server.Host.Swarm } /// - public async Task RemoteCommitRecieved(Guid registrationId, CancellationToken cancellationToken) + public async ValueTask RemoteCommitRecieved(Guid registrationId, CancellationToken cancellationToken) { var localUpdateOperation = updateOperation; if (!swarmController) @@ -635,7 +638,7 @@ namespace Tgstation.Server.Host.Swarm } /// - public async Task UnregisterNode(Guid registrationId, CancellationToken cancellationToken) + public async ValueTask UnregisterNode(Guid registrationId, CancellationToken cancellationToken) { logger.LogTrace("UnregisterNode {registrationId}", registrationId); await AbortUpdate(); @@ -667,14 +670,14 @@ namespace Tgstation.Server.Host.Swarm /// /// Sends out remote abort update requests. /// - /// A representing the running operation. + /// A representing the running operation. /// The aborted should be cleared out before calling this. This method does not accept a because aborting an update should never be cancelled. - Task RemoteAbortUpdate() + ValueTask RemoteAbortUpdate() { logger.LogInformation("Aborting swarm update!"); using var httpClient = httpClientFactory.CreateClient(); - async Task SendRemoteAbort(SwarmServerResponse swarmServer) + async ValueTask SendRemoteAbort(SwarmServerResponse swarmServer) { using var request = PrepareSwarmRequest( swarmServer, @@ -706,10 +709,11 @@ namespace Tgstation.Server.Host.Swarm }); lock (swarmServers) - return Task.WhenAll( + return ValueTaskExtensions.WhenAll( swarmServers .Where(x => !x.Controller) - .Select(SendRemoteAbort)); + .Select(SendRemoteAbort) + .ToList()); } /// @@ -753,8 +757,8 @@ namespace Tgstation.Server.Host.Swarm /// The containing the update package if this is the initiating server, otherwise. /// The . Must always have populated. If is , it must be fully populated. /// The for the operation. - /// A resulting in the . - async Task PrepareUpdateImpl(ISeekableFileStreamProvider initiatorProvider, SwarmUpdateRequest updateRequest, CancellationToken cancellationToken) + /// A resulting in the . + async ValueTask PrepareUpdateImpl(ISeekableFileStreamProvider initiatorProvider, SwarmUpdateRequest updateRequest, CancellationToken cancellationToken) { if (!SwarmMode) { @@ -916,8 +920,8 @@ namespace Tgstation.Server.Host.Swarm /// The . Must always have populated. If is , it must be fully populated. /// The current . /// The for the operation. - /// A resulting in the . - async Task ControllerDistributedPrepareUpdate( + /// A resulting in the . + async ValueTask ControllerDistributedPrepareUpdate( ISeekableFileStreamProvider initiatorProvider, SwarmUpdateRequest updateRequest, SwarmUpdateOperation currentUpdateOperation, @@ -1056,8 +1060,8 @@ namespace Tgstation.Server.Host.Swarm /// The containing the server update package. /// An of the involved . /// The for the operation. - /// A resulting in a new of unique s keyed by their . - async Task> CreateDownloadTickets( + /// A resulting in a new of unique s keyed by their . + async ValueTask> CreateDownloadTickets( ISeekableFileStreamProvider initiatorProvider, IReadOnlyCollection involvedServers, CancellationToken cancellationToken) @@ -1093,8 +1097,8 @@ namespace Tgstation.Server.Host.Swarm /// Ping each node to see that they are still running. /// /// The for the operation. - /// A representing the running operation. - async Task HealthCheckNodes(CancellationToken cancellationToken) + /// A representing the running operation. + async ValueTask HealthCheckNodes(CancellationToken cancellationToken) { using var httpClient = httpClientFactory.CreateClient(); @@ -1102,7 +1106,7 @@ namespace Tgstation.Server.Host.Swarm lock (swarmServers) currentSwarmServers = swarmServers.ToList(); - async Task HealthRequestForServer(SwarmServerResponse swarmServer) + async ValueTask HealthRequestForServer(SwarmServerResponse swarmServer) { using var request = PrepareSwarmRequest( swarmServer, @@ -1131,7 +1135,7 @@ namespace Tgstation.Server.Host.Swarm } } - await Task.WhenAll( + await ValueTaskExtensions.WhenAll( currentSwarmServers .Where(node => !node.Controller && registrationIdsAndTimes.TryGetValue(node.Identifier, out var registrationAndTime) @@ -1170,8 +1174,8 @@ namespace Tgstation.Server.Host.Swarm /// Ping the swarm controller to see that it is still running. If need be, reregister. /// /// The for the operation. - /// A representing the running operation. - async Task HealthCheckController(CancellationToken cancellationToken) + /// A representing the running operation. + async ValueTask HealthCheckController(CancellationToken cancellationToken) { using var httpClient = httpClientFactory.CreateClient(); @@ -1227,8 +1231,8 @@ namespace Tgstation.Server.Host.Swarm /// Attempt to register the node with the controller. /// /// The for the operation. - /// A resulting in the . - async Task RegisterWithController(CancellationToken cancellationToken) + /// A resulting in the . + async ValueTask RegisterWithController(CancellationToken cancellationToken) { logger.LogInformation("Attempting to register with swarm controller at {controllerAddress}...", swarmConfiguration.ControllerAddress); var requestedRegistrationId = Guid.NewGuid(); @@ -1289,8 +1293,8 @@ namespace Tgstation.Server.Host.Swarm /// Sends the controllers list of nodes to all nodes. /// /// The for the operation. - /// A representing the running operation. - async Task SendUpdatedServerListToNodes(CancellationToken cancellationToken) + /// A representing the running operation. + async ValueTask SendUpdatedServerListToNodes(CancellationToken cancellationToken) { List currentSwarmServers; lock (swarmServers) @@ -1308,7 +1312,7 @@ namespace Tgstation.Server.Host.Swarm logger.LogDebug("Sending updated server list to all {nodeCount} nodes...", currentSwarmServers.Count - 1); using var httpClient = httpClientFactory.CreateClient(); - async Task UpdateRequestForServer(SwarmServerResponse swarmServer) + async ValueTask UpdateRequestForServer(SwarmServerResponse swarmServer) { using var request = PrepareSwarmRequest( swarmServer, @@ -1336,10 +1340,11 @@ namespace Tgstation.Server.Host.Swarm } } - await Task.WhenAll( + await ValueTaskExtensions.WhenAll( currentSwarmServers .Where(x => !x.Controller) - .Select(UpdateRequestForServer)); + .Select(UpdateRequestForServer) + .ToList()); } /// diff --git a/src/Tgstation.Server.Host/System/IProcess.cs b/src/Tgstation.Server.Host/System/IProcess.cs index afe5f497ec..aec3f0d7a3 100644 --- a/src/Tgstation.Server.Host/System/IProcess.cs +++ b/src/Tgstation.Server.Host/System/IProcess.cs @@ -39,8 +39,7 @@ namespace Tgstation.Server.Host.System /// /// Get the name of the account executing the . /// - /// The for the operation. - /// A resulting in the name of the account executing the . - Task GetExecutingUsername(CancellationToken cancellationToken); + /// The name of the account executing the . + string GetExecutingUsername(); } } diff --git a/src/Tgstation.Server.Host/System/IProcessBase.cs b/src/Tgstation.Server.Host/System/IProcessBase.cs index 472b1cf63a..8fc0bd4484 100644 --- a/src/Tgstation.Server.Host/System/IProcessBase.cs +++ b/src/Tgstation.Server.Host/System/IProcessBase.cs @@ -34,7 +34,7 @@ namespace Tgstation.Server.Host.System /// /// The full path to the output file. /// The for the operation. - /// A representing the running operation. - Task CreateDump(string outputFile, CancellationToken cancellationToken); + /// A representing the running operation. + ValueTask CreateDump(string outputFile, CancellationToken cancellationToken); } } diff --git a/src/Tgstation.Server.Host/System/IProcessFeatures.cs b/src/Tgstation.Server.Host/System/IProcessFeatures.cs index 2b5f6a3f84..abfaca6b7b 100644 --- a/src/Tgstation.Server.Host/System/IProcessFeatures.cs +++ b/src/Tgstation.Server.Host/System/IProcessFeatures.cs @@ -12,9 +12,8 @@ namespace Tgstation.Server.Host.System /// Get the name of the user executing a given . /// /// The . - /// The for the operation. /// The name of the user executing . - Task GetExecutingUsername(global::System.Diagnostics.Process process, CancellationToken cancellationToken); + string GetExecutingUsername(global::System.Diagnostics.Process process); /// /// Suspend a given . @@ -34,7 +33,7 @@ namespace Tgstation.Server.Host.System /// The to dump. /// The full path to the output file. /// The for the operation. - /// A representing the running operation. - Task CreateDump(global::System.Diagnostics.Process process, string outputFile, CancellationToken cancellationToken); + /// A representing the running operation. + ValueTask CreateDump(global::System.Diagnostics.Process process, string outputFile, CancellationToken cancellationToken); } } diff --git a/src/Tgstation.Server.Host/System/PosixProcessFeatures.cs b/src/Tgstation.Server.Host/System/PosixProcessFeatures.cs index 1332203311..0e1dab1d3c 100644 --- a/src/Tgstation.Server.Host/System/PosixProcessFeatures.cs +++ b/src/Tgstation.Server.Host/System/PosixProcessFeatures.cs @@ -60,11 +60,11 @@ namespace Tgstation.Server.Host.System } /// - public Task GetExecutingUsername(global::System.Diagnostics.Process process, CancellationToken cancellationToken) + public string GetExecutingUsername(global::System.Diagnostics.Process process) => throw new NotSupportedException(); /// - public async Task CreateDump(global::System.Diagnostics.Process process, string outputFile, CancellationToken cancellationToken) + public async ValueTask CreateDump(global::System.Diagnostics.Process process, string outputFile, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(process); ArgumentNullException.ThrowIfNull(outputFile); diff --git a/src/Tgstation.Server.Host/System/Process.cs b/src/Tgstation.Server.Host/System/Process.cs index ac122ce0ff..ccda2f2153 100644 --- a/src/Tgstation.Server.Host/System/Process.cs +++ b/src/Tgstation.Server.Host/System/Process.cs @@ -202,15 +202,15 @@ namespace Tgstation.Server.Host.System } /// - public async Task GetExecutingUsername(CancellationToken cancellationToken) + public string GetExecutingUsername() { - var result = await processFeatures.GetExecutingUsername(handle, cancellationToken); + var result = processFeatures.GetExecutingUsername(handle); logger.LogTrace("PID {pid} Username: {username}", Id, result); return result; } /// - public Task CreateDump(string outputFile, CancellationToken cancellationToken) + public ValueTask CreateDump(string outputFile, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(outputFile); diff --git a/src/Tgstation.Server.Host/System/WindowsProcessFeatures.cs b/src/Tgstation.Server.Host/System/WindowsProcessFeatures.cs index 8aed17b22e..efbb029e0a 100644 --- a/src/Tgstation.Server.Host/System/WindowsProcessFeatures.cs +++ b/src/Tgstation.Server.Host/System/WindowsProcessFeatures.cs @@ -93,7 +93,7 @@ namespace Tgstation.Server.Host.System } /// - public Task GetExecutingUsername(global::System.Diagnostics.Process process, CancellationToken cancellationToken) + public string GetExecutingUsername(global::System.Diagnostics.Process process) { string query = $"SELECT * FROM Win32_Process WHERE ProcessId = {process?.Id ?? throw new ArgumentNullException(nameof(process))}"; using var searcher = new ManagementObjectSearcher(query); @@ -106,21 +106,21 @@ namespace Tgstation.Server.Host.System ?.ToString(); if (!Int32.TryParse(returnString, out var returnVal)) - return Task.FromResult($"BAD RETURN PARSE: {returnString}"); + return $"BAD RETURN PARSE: {returnString}"; if (returnVal == 0) { // return DOMAIN\user string owner = argList.Last() + "\\" + argList.First(); - return Task.FromResult(owner); + return owner; } } - return Task.FromResult("NO OWNER"); + return "NO OWNER"; } /// - public async Task CreateDump(global::System.Diagnostics.Process process, string outputFile, CancellationToken cancellationToken) + public async ValueTask CreateDump(global::System.Diagnostics.Process process, string outputFile, CancellationToken cancellationToken) { try { diff --git a/src/Tgstation.Server.Host/Transfer/FileTransferService.cs b/src/Tgstation.Server.Host/Transfer/FileTransferService.cs index 22dee33c7c..263bd2ba9c 100644 --- a/src/Tgstation.Server.Host/Transfer/FileTransferService.cs +++ b/src/Tgstation.Server.Host/Transfer/FileTransferService.cs @@ -163,7 +163,7 @@ namespace Tgstation.Server.Host.Transfer } /// - public async Task> RetrieveDownloadStream(FileTicketResponse ticket, CancellationToken cancellationToken) + public async ValueTask> RetrieveDownloadStream(FileTicketResponse ticket, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(ticket); @@ -217,7 +217,7 @@ namespace Tgstation.Server.Host.Transfer } /// - public async Task SetUploadStream(FileTicketResponse ticket, Stream stream, CancellationToken cancellationToken) + public async ValueTask SetUploadStream(FileTicketResponse ticket, Stream stream, CancellationToken cancellationToken) { ArgumentNullException.ThrowIfNull(ticket); diff --git a/src/Tgstation.Server.Host/Transfer/IFileTransferStreamHandler.cs b/src/Tgstation.Server.Host/Transfer/IFileTransferStreamHandler.cs index ecfea79f51..75603c8684 100644 --- a/src/Tgstation.Server.Host/Transfer/IFileTransferStreamHandler.cs +++ b/src/Tgstation.Server.Host/Transfer/IFileTransferStreamHandler.cs @@ -18,15 +18,15 @@ namespace Tgstation.Server.Host.Transfer /// The . /// The with uploaded data. /// The for the operation. - /// if the upload completed successfully, otherwise. - Task SetUploadStream(FileTicketResponse ticket, Stream stream, CancellationToken cancellationToken); + /// A resulting in if the upload completed successfully, otherwise. + ValueTask SetUploadStream(FileTicketResponse ticket, Stream stream, CancellationToken cancellationToken); /// /// Gets the the for a given associated with a pending download. /// /// The . /// The for the operation. - /// A containing either a containing the data to download or an to return. - Task> RetrieveDownloadStream(FileTicketResponse ticket, CancellationToken cancellationToken); + /// A resulting in a containing either a containing the data to download or an to return. + ValueTask> RetrieveDownloadStream(FileTicketResponse ticket, CancellationToken cancellationToken); } } diff --git a/src/Tgstation.Server.Host/Utils/IPortAllocator.cs b/src/Tgstation.Server.Host/Utils/IPortAllocator.cs index 865107bb1a..29d234ec62 100644 --- a/src/Tgstation.Server.Host/Utils/IPortAllocator.cs +++ b/src/Tgstation.Server.Host/Utils/IPortAllocator.cs @@ -14,7 +14,7 @@ namespace Tgstation.Server.Host.Utils /// The port to check first. Will not allocate a port lower than this. /// If only should be checked and no others. /// The for the operation. - /// A resulting in the first available port on success, on failure. - Task GetAvailablePort(ushort basePort, bool checkOne, CancellationToken cancellationToken); + /// A resulting in the first available port on success, on failure. + ValueTask GetAvailablePort(ushort basePort, bool checkOne, CancellationToken cancellationToken); } } diff --git a/src/Tgstation.Server.Host/Utils/PortAllocator.cs b/src/Tgstation.Server.Host/Utils/PortAllocator.cs index 9b125103d0..c2337135bc 100644 --- a/src/Tgstation.Server.Host/Utils/PortAllocator.cs +++ b/src/Tgstation.Server.Host/Utils/PortAllocator.cs @@ -58,7 +58,7 @@ namespace Tgstation.Server.Host.Utils } /// - public async Task GetAvailablePort(ushort basePort, bool checkOne, CancellationToken cancellationToken) + public async ValueTask GetAvailablePort(ushort basePort, bool checkOne, CancellationToken cancellationToken) { logger.LogTrace("Port allocation >= {basePort} requested...", basePort); diff --git a/tests/Tgstation.Server.Host.Console.Tests/TestProgram.cs b/tests/Tgstation.Server.Host.Console.Tests/TestProgram.cs index 0fc337843c..6276353b2a 100644 --- a/tests/Tgstation.Server.Host.Console.Tests/TestProgram.cs +++ b/tests/Tgstation.Server.Host.Console.Tests/TestProgram.cs @@ -17,7 +17,7 @@ namespace Tgstation.Server.Host.Console.Tests { var mockServer = new Mock(); var args = Array.Empty(); - mockServer.Setup(x => x.RunAsync(false, args, It.IsAny())).Returns(Task.FromResult(true)).Verifiable(); + mockServer.Setup(x => x.RunAsync(false, args, It.IsAny())).Returns(ValueTask.FromResult(true)).Verifiable(); var mockServerFactory = new Mock(); mockServerFactory.Setup(x => x.CreateWatchdog(It.IsNotNull(), It.IsNotNull())).Returns(mockServer.Object).Verifiable(); Program.WatchdogFactory = mockServerFactory.Object; diff --git a/tests/Tgstation.Server.Host.Service.Tests/TestServerService.cs b/tests/Tgstation.Server.Host.Service.Tests/TestServerService.cs index 7c5ae3bed2..e1f604a533 100644 --- a/tests/Tgstation.Server.Host.Service.Tests/TestServerService.cs +++ b/tests/Tgstation.Server.Host.Service.Tests/TestServerService.cs @@ -35,7 +35,7 @@ namespace Tgstation.Server.Host.Service.Tests var mockWatchdog = new Mock(); var args = Array.Empty(); CancellationToken cancellationToken = default; - Task signalCheckerTask = null; + ValueTask? signalCheckerTask = null; var childStarted = false; ISignalChecker signalChecker = null; @@ -47,7 +47,7 @@ namespace Tgstation.Server.Host.Service.Tests childStarted = true; return (123, Task.CompletedTask); }, cancellationToken); - }).Returns(Task.FromResult(true)).Verifiable(); + }).Returns(ValueTask.FromResult(true)).Verifiable(); var mockWatchdogFactory = new Mock(); mockWatchdogFactory.Setup(x => x.CreateWatchdog(It.IsNotNull(), It.IsNotNull())) @@ -67,7 +67,7 @@ namespace Tgstation.Server.Host.Service.Tests } mockWatchdogFactory.VerifyAll(); - Assert.IsTrue(signalCheckerTask.IsCompleted); + Assert.IsTrue(signalCheckerTask.Value.IsCompleted); } } } diff --git a/tests/Tgstation.Server.Host.Tests/IO/TestIOManager.cs b/tests/Tgstation.Server.Host.Tests/IO/TestIOManager.cs index f92ffaa04d..f8b7a9b7c9 100644 --- a/tests/Tgstation.Server.Host.Tests/IO/TestIOManager.cs +++ b/tests/Tgstation.Server.Host.Tests/IO/TestIOManager.cs @@ -88,28 +88,28 @@ namespace Tgstation.Server.Host.IO.Tests null, tempPath2, throttle, - default)); + default).AsTask()); await Assert.ThrowsExceptionAsync(() => ioManager.CopyDirectory( null, null, tempPath1, null, throttle, - default)); + default).AsTask()); await Assert.ThrowsExceptionAsync(() => ioManager.CopyDirectory( null, null, null, null, throttle, - default)); + default).AsTask()); await Assert.ThrowsExceptionAsync(() => ioManager.CopyDirectory( null, null, tempPath1, tempPath2, -1, - default)); + default).AsTask()); } [TestMethod] diff --git a/tests/Tgstation.Server.Host.Tests/Setup/TestSetupWizard.cs b/tests/Tgstation.Server.Host.Tests/Setup/TestSetupWizard.cs index 3b9da3b2b3..823036a10b 100644 --- a/tests/Tgstation.Server.Host.Tests/Setup/TestSetupWizard.cs +++ b/tests/Tgstation.Server.Host.Tests/Setup/TestSetupWizard.cs @@ -104,10 +104,10 @@ namespace Tgstation.Server.Host.Setup.Tests return $"{paths[0]}/{paths[1]}"; }).Verifiable(); mockIOManager.Setup(x => x.FileExists(It.IsNotNull(), It.IsAny())).Returns(Task.FromResult(true)).Verifiable(); - mockIOManager.Setup(x => x.ReadAllBytes(It.IsNotNull(), It.IsAny())).Returns(Task.FromResult(Encoding.UTF8.GetBytes("less profane"))).Verifiable(); + mockIOManager.Setup(x => x.ReadAllBytes(It.IsNotNull(), It.IsAny())).Returns(ValueTask.FromResult(Encoding.UTF8.GetBytes("less profane"))).Verifiable(); mockIOManager .Setup(x => x.WriteAllBytes(It.IsNotNull(), It.IsNotNull(), It.IsAny())) - .Returns(Task.CompletedTask) + .Returns(ValueTask.CompletedTask) .Verifiable(); var mockSuccessCommand = new Mock(); @@ -306,7 +306,7 @@ namespace Tgstation.Server.Host.Setup.Tests await RunWizard(); //second run - mockIOManager.Setup(x => x.ReadAllBytes(It.IsNotNull(), It.IsAny())).Returns(Task.FromResult(Encoding.UTF8.GetBytes(String.Empty))).Verifiable(); + mockIOManager.Setup(x => x.ReadAllBytes(It.IsNotNull(), It.IsAny())).Returns(ValueTask.FromResult(Encoding.UTF8.GetBytes(String.Empty))).Verifiable(); await RunWizard(); //third run diff --git a/tests/Tgstation.Server.Host.Tests/Swarm/TestSwarmProtocol.cs b/tests/Tgstation.Server.Host.Tests/Swarm/TestSwarmProtocol.cs index 5845fe177e..2ae9c2e0ff 100644 --- a/tests/Tgstation.Server.Host.Tests/Swarm/TestSwarmProtocol.cs +++ b/tests/Tgstation.Server.Host.Tests/Swarm/TestSwarmProtocol.cs @@ -10,6 +10,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; +using Tgstation.Server.Common.Extensions; using Tgstation.Server.Host.Configuration; using Tgstation.Server.Host.Core; using Tgstation.Server.Host.IO; @@ -206,7 +207,7 @@ namespace Tgstation.Server.Host.Swarm.Tests await TestSimultaneousPrepareDifferentVersionsFails(false); } - static async Task TestSimultaneousPrepareDifferentVersionsFails(bool prepControllerFirst) + static async ValueTask TestSimultaneousPrepareDifferentVersionsFails(bool prepControllerFirst) { await using var controller = GenNode(); await using var node1 = GenNode(controller); @@ -219,7 +220,7 @@ namespace Tgstation.Server.Host.Swarm.Tests Assert.AreEqual(SwarmRegistrationResult.Success, await controller.TryInit()); Assert.AreEqual(SwarmRegistrationResult.Success, await node1.TryInit()); - Task controllerPrepareTask = null, nodePrepareTask; + ValueTask controllerPrepareTask = ValueTask.FromResult(SwarmPrepareResult.SuccessProviderNotRequired), nodePrepareTask; if (prepControllerFirst) controllerPrepareTask = controller.Service.PrepareUpdate(updateFileStreamProvider, new Version(4, 3, 2), default); @@ -230,7 +231,7 @@ namespace Tgstation.Server.Host.Swarm.Tests await Task.Yield(); - await Task.WhenAll(controllerPrepareTask, nodePrepareTask); + await ValueTaskExtensions.WhenAll(controllerPrepareTask, nodePrepareTask); Task nodeCommitTask = null, controllerCommitTask = null; @@ -248,13 +249,13 @@ namespace Tgstation.Server.Host.Swarm.Tests if (controllerPrepped != SwarmPrepareResult.Failure) { Assert.AreEqual(SwarmPrepareResult.SuccessHoldProviderUntilCommit, controllerPrepped); - controllerCommitTask = controller.Service.CommitUpdate(default); + controllerCommitTask = controller.Service.CommitUpdate(default).AsTask(); } if (nodePrepped != SwarmPrepareResult.Failure) { Assert.AreEqual(SwarmPrepareResult.SuccessHoldProviderUntilCommit, nodePrepped); - nodeCommitTask = node1.Service.CommitUpdate(default); + nodeCommitTask = node1.Service.CommitUpdate(default).AsTask(); } await Task.Yield(); diff --git a/tests/Tgstation.Server.Host.Tests/Swarm/TestableSwarmNode.cs b/tests/Tgstation.Server.Host.Tests/Swarm/TestableSwarmNode.cs index 31b39a83c2..c293318381 100644 --- a/tests/Tgstation.Server.Host.Tests/Swarm/TestableSwarmNode.cs +++ b/tests/Tgstation.Server.Host.Tests/Swarm/TestableSwarmNode.cs @@ -237,7 +237,7 @@ namespace Tgstation.Server.Host.Swarm.Tests throw new TaskCanceledException(); }).Verifiable(); - Task Invoke() => Service.Initialize(default); + Task Invoke() => Service.Initialize(default).AsTask(); SwarmRegistrationResult? result; if (cancel) diff --git a/tests/Tgstation.Server.Host.Tests/System/TestProcessFeatures.cs b/tests/Tgstation.Server.Host.Tests/System/TestProcessFeatures.cs index 066370977c..a32b9e389c 100644 --- a/tests/Tgstation.Server.Host.Tests/System/TestProcessFeatures.cs +++ b/tests/Tgstation.Server.Host.Tests/System/TestProcessFeatures.cs @@ -3,7 +3,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Runtime.InteropServices; -using System.Threading.Tasks; using Tgstation.Server.Host.IO; @@ -26,12 +25,12 @@ namespace Tgstation.Server.Host.System.Tests } [TestMethod] - public async Task TestGetUsername() + public void TestGetUsername() { if (!new PlatformIdentifier().IsWindows) Assert.Inconclusive("This test is buggy on linux and not required"); - var username = await features.GetExecutingUsername(global::System.Diagnostics.Process.GetCurrentProcess(), default); + var username = features.GetExecutingUsername(global::System.Diagnostics.Process.GetCurrentProcess()); Assert.IsTrue(username.Contains(Environment.UserName), $"Exepcted a string containing \"{Environment.UserName}\", got \"{username}\""); } } diff --git a/tests/Tgstation.Server.Tests/Live/Instance/ConfigurationTest.cs b/tests/Tgstation.Server.Tests/Live/Instance/ConfigurationTest.cs index 1008406cd7..56a879c98d 100644 --- a/tests/Tgstation.Server.Tests/Live/Instance/ConfigurationTest.cs +++ b/tests/Tgstation.Server.Tests/Live/Instance/ConfigurationTest.cs @@ -11,6 +11,7 @@ using Tgstation.Server.Api.Models; using Tgstation.Server.Api.Models.Request; using Tgstation.Server.Client; using Tgstation.Server.Client.Components; +using Tgstation.Server.Common.Extensions; using Tgstation.Server.Host.IO; namespace Tgstation.Server.Tests.Live.Instance @@ -92,11 +93,11 @@ namespace Tgstation.Server.Tests.Live.Instance await configurationClient.CreateDirectory(staticDir, cancellationToken); } - public Task SetupDMApiTests(CancellationToken cancellationToken) + public ValueTask SetupDMApiTests(CancellationToken cancellationToken) { // just use an I/O manager here var ioManager = new DefaultIOManager(); - return Task.WhenAll( + return ValueTaskExtensions.WhenAll( ioManager.CopyDirectory( Enumerable.Empty(), null, @@ -176,7 +177,7 @@ namespace Tgstation.Server.Tests.Live.Instance public Task RunPreWatchdog(CancellationToken cancellationToken) => Task.WhenAll( SequencedApiTests(cancellationToken), - SetupDMApiTests(cancellationToken), + SetupDMApiTests(cancellationToken).AsTask(), TestPregeneratedFilesExist(cancellationToken)); } } diff --git a/tests/Tgstation.Server.Tests/Live/Instance/TestBridgeHandler.cs b/tests/Tgstation.Server.Tests/Live/Instance/TestBridgeHandler.cs index bb23bbdc63..53e0c43a51 100644 --- a/tests/Tgstation.Server.Tests/Live/Instance/TestBridgeHandler.cs +++ b/tests/Tgstation.Server.Tests/Live/Instance/TestBridgeHandler.cs @@ -43,7 +43,7 @@ namespace Tgstation.Server.Tests.Live.Instance this.accessIdentifier = accessIdentifier; } - public async Task ProcessBridgeRequest(BridgeParameters parameters, CancellationToken cancellationToken) + public async ValueTask ProcessBridgeRequest(BridgeParameters parameters, CancellationToken cancellationToken) { try {