Skip to content

Commit

Permalink
dotnet format lite client
Browse files Browse the repository at this point in the history
  • Loading branch information
Dustin Updyke committed Oct 25, 2024
1 parent f944d80 commit 330827d
Show file tree
Hide file tree
Showing 13 changed files with 59 additions and 69 deletions.
27 changes: 11 additions & 16 deletions src/Ghosts.Client.Lite/src/Infrastructure/ApplicationDetails.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public static class ApplicationDetails
{
private static readonly Logger _log = LogManager.GetCurrentClassLogger();

public static string Header =>
public static string Header =>
@" ('-. .-. .-') .-') _ .-')
( OO ) / ( OO ). ( OO) ) ( OO ).
,----. ,--. ,--. .-'),-----. (_)---\_)/ '._ (_)---\_)
Expand Down Expand Up @@ -65,7 +65,7 @@ public static string GetPath(string loc)
{
return Path.GetFullPath(Path.Combine(InstalledPath, loc));
}

public static bool IsLinux()
{
return RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
Expand Down Expand Up @@ -172,20 +172,15 @@ public static class LogFiles
public static string ClientUpdates => Clean(Path + "clientupdates.log");
}

public class ConfigurationUrls
public class ConfigurationUrls(string rootUrl)
{
public ConfigurationUrls(string rootUrl)
{
this._root = rootUrl;
}

private string _root;
public string Id => $"{this._root}/clientid";
public string Timeline => $"{this._root}/clienttimeline";
public string Results => $"{this._root}/clientresults";
public string Updates => $"{this._root}/clientupdates";
public string Survey => $"{this._root}/clientsurvey";
public string Socket => $"{this._root.Replace("/api","")}/clientHub";
private readonly string _root = rootUrl;
public string Id => $"{_root}/clientid";
public string Timeline => $"{_root}/clienttimeline";
public string Results => $"{_root}/clientresults";
public string Updates => $"{_root}/clientupdates";
public string Survey => $"{_root}/clientsurvey";
public string Socket => $"{_root.Replace("/api", "")}/clientHub";
}
}
}
}
6 changes: 3 additions & 3 deletions src/Ghosts.Client.Lite/src/Infrastructure/Comms/CheckId.cs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ private string Run()
}

var machine = new ResultMachine();

try
{
//call home
Expand Down Expand Up @@ -132,7 +132,7 @@ private string Run()
File.WriteAllText(IdFile, s);
return s;
}

public static void WriteId(string id)
{
if (!string.IsNullOrEmpty(id))
Expand All @@ -149,4 +149,4 @@ public static void WriteId(string id)
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,17 @@ namespace Ghosts.Client.Lite.Infrastructure.Comms.ClientSocket;

public class BackgroundTaskQueue
{
private ConcurrentQueue<QueueEntry> _workItems = new ();
private SemaphoreSlim _signal = new SemaphoreSlim(0);
private readonly ConcurrentQueue<QueueEntry> _workItems = new();
private readonly SemaphoreSlim _signal = new(0);

public IEnumerable<QueueEntry> GetAll()
{
return _workItems;
}

public void Enqueue(QueueEntry workItem)
{
if (workItem == null)
{
throw new ArgumentNullException(nameof(workItem));
}
ArgumentNullException.ThrowIfNull(workItem);

_workItems.Enqueue(workItem);
_signal.Release();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,13 @@

namespace Ghosts.Client.Lite.Infrastructure.Comms.ClientSocket;

public class Connection
public class Connection(ClientConfiguration.SocketsSettings options)
{
private int _attempts = 0;
private HubConnection _connection;
private readonly CancellationToken _ct = new();
public readonly BackgroundTaskQueue Queue = new();
private readonly ClientConfiguration.SocketsSettings _options;

public Connection(ClientConfiguration.SocketsSettings options)
{
this._options = options;
}
private readonly ClientConfiguration.SocketsSettings _options = options;

public async Task Run()
{
Expand All @@ -34,10 +29,13 @@ public async Task Run()
// Send a message to the server
while (_connection.State == HubConnectionState.Connected)
{
_ = new Timer(_ => {
Task.Run(async () => {
_ = new Timer(_ =>
{
Task.Run(async () =>
{
await ClientHeartbeat();
}, _ct).ContinueWith(task => {
}, _ct).ContinueWith(task =>
{
if (task.Exception != null)
{
// Log or handle the exception
Expand All @@ -50,18 +48,18 @@ public async Task Run()
{
Console.WriteLine("Peeking into queue...");

var item = await Queue.DequeueAsync(this._ct);
var item = await Queue.DequeueAsync(_ct);
if (item != null)
{
Console.WriteLine($"There was a {item.Type} in the queue: {item.Payload}");
if (item.Type == QueueEntry.Types.Heartbeat)
await this.ClientHeartbeat();
await ClientHeartbeat();

if (item.Type == QueueEntry.Types.Message)
await this.ClientMessage(item.Payload.ToString());
await ClientMessage(item.Payload.ToString());

if (item.Type == QueueEntry.Types.MessageSpecific)
await this.ClientMessageSpecific(item.Payload.ToString());
await ClientMessageSpecific(item.Payload.ToString());
}
else
{
Expand All @@ -87,7 +85,7 @@ async Task EstablishConnection(string url)
x.Headers = WebClientBuilder.GetHeaders(machine, true);
}).WithAutomaticReconnect()
.Build();

Console.WriteLine($"Connection state: {_connection.State}");

// Define how to handle incoming messages
Expand Down Expand Up @@ -130,25 +128,25 @@ async Task EstablishConnection(string url)
}
catch (Exception ex)
{
if(_attempts > 1)
if (_attempts > 1)
Console.WriteLine($"An error occurred at {url} while connecting: {ex.Message}");
}
}

private async Task ClientHeartbeat()
{
await _connection?.InvokeAsync("SendHeartbeat", $"Client heartbeat at {DateTime.UtcNow}", this._ct)!;
await _connection?.InvokeAsync("SendHeartbeat", $"Client heartbeat at {DateTime.UtcNow}", _ct)!;
}

private async Task ClientMessage(string message)
{
if(!string.IsNullOrEmpty(message))
await _connection?.InvokeAsync("SendMessage", $"Client message: {message}", this._ct)!;
if (!string.IsNullOrEmpty(message))
await _connection?.InvokeAsync("SendMessage", $"Client message: {message}", _ct)!;
}

private async Task ClientMessageSpecific(string message)
{
if(!string.IsNullOrEmpty(message))
await _connection?.InvokeAsync("SendSpecificMessage", $"Client specific message: {message}", this._ct)!;
if (!string.IsNullOrEmpty(message))
await _connection?.InvokeAsync("SendSpecificMessage", $"Client specific message: {message}", _ct)!;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ public enum Types

public object Payload { get; set; }
public Types Type { get; set; }
}
}
2 changes: 1 addition & 1 deletion src/Ghosts.Client.Lite/src/Infrastructure/Comms/Updates.cs
Original file line number Diff line number Diff line change
Expand Up @@ -430,4 +430,4 @@ internal static void PostSurvey()
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public async Task Execute(IJobExecutionContext context)
var handler = JsonConvert.DeserializeObject<TimelineHandler>(raw);
if (handler == null)
return;

await FileHandler.Run(handler);
}
}
Expand All @@ -36,7 +36,7 @@ public static async Task Run(TimelineHandler handler)
await Run(handler.HandlerType, timelineEvent);
}
}

public static async Task Run(HandlerType handler, TimelineEvent t)
{
var sizeMap = new Dictionary<string, int>
Expand All @@ -49,7 +49,7 @@ public static async Task Run(HandlerType handler, TimelineEvent t)
var rand = RandomFilename.Generate();

var defaultSaveDirectory = t.CommandArgs[0].ToString();
if (defaultSaveDirectory!.Contains("%"))
if (defaultSaveDirectory!.Contains('%'))
{
defaultSaveDirectory = Environment.ExpandEnvironmentVariables(defaultSaveDirectory);
}
Expand All @@ -64,7 +64,7 @@ public static async Task Run(HandlerType handler, TimelineEvent t)
savePathString = savePathString.Replace("\\", "/"); // Can't deserialize Windows path
var savePaths = JsonConvert.DeserializeObject<string[]>(savePathString);
defaultSaveDirectory = savePaths.PickRandom().Replace("/", "\\"); // Revert to Windows path
if (defaultSaveDirectory.Contains("%"))
if (defaultSaveDirectory.Contains('%'))
{
defaultSaveDirectory = Environment.ExpandEnvironmentVariables(defaultSaveDirectory);
}
Expand Down Expand Up @@ -101,7 +101,7 @@ public static async Task Run(HandlerType handler, TimelineEvent t)
_log.Trace(File.Exists(path));
var bitLength = new Random().Next(1000, sizeMap[handler.ToString()]);
var info = new UTF8Encoding(true).GetBytes(GenerateBits(bitLength));
await fs.WriteAsync(info, 0, info.Length);
await fs.WriteAsync(info);
}

// Report on file creation success
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public async Task Run(HandlerType handler, TimelineEvent t, string? url)
}
}

private HttpClient CreateHttpClient(HandlerType handler, string url)
private static HttpClient CreateHttpClient(HandlerType handler, string url)
{
var clientHandler = new HttpClientHandler
{
Expand Down Expand Up @@ -138,7 +138,7 @@ private HttpClient CreateHttpClient(HandlerType handler, string url)
return client;
}

private async Task<string> ReadContentAsync(HttpContent content)
private static async Task<string> ReadContentAsync(HttpContent content)
{
var encoding = content.Headers.ContentEncoding;
var contentStream = await content.ReadAsStreamAsync();
Expand Down
2 changes: 1 addition & 1 deletion src/Ghosts.Client.Lite/src/Infrastructure/Orchestrator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,4 @@ private static async Task ThreadLaunch(Timeline timeline, TimelineHandler handle
break;
}
}
}
}
4 changes: 2 additions & 2 deletions src/Ghosts.Client.Lite/src/Infrastructure/RandomFilename.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace Ghosts.Client.Lite.Infrastructure;

public static class RandomFilename
{
private static readonly Random _random = new ();
private static readonly Random _random = new();

public static string Generate()
{
Expand Down Expand Up @@ -61,4 +61,4 @@ public static string Generate()

return fileName;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace Ghosts.Client.Lite.Infrastructure.Services;
public static class LogWriter
{
private static readonly Logger _timelineLog = LogManager.GetLogger("TIMELINE");

public static void Timeline(TimeLineRecord result)
{
var o = JsonConvert.SerializeObject(result,
Expand All @@ -21,4 +21,4 @@ public static void Timeline(TimeLineRecord result)

_timelineLog.Info($"TIMELINE|{DateTime.UtcNow}|{o}");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,4 @@ public static IDictionary<string, string> GetHeaders(ResultMachine machine, bool
return dict;
}
}
}
}
6 changes: 3 additions & 3 deletions src/Ghosts.Client.Lite/src/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,10 +89,10 @@ private static async Task Run(string[] args)
var schedulerFactory = new StdSchedulerFactory();
var scheduler = await schedulerFactory.GetScheduler();
await scheduler.Start();

// Schedule timeline
await ScheduleTimeline(scheduler, timeline);

// Schedule memory cleanup job
await ScheduleMemoryCleanup(scheduler);

Expand Down Expand Up @@ -147,7 +147,7 @@ private static async Task ScheduleTimeline(IScheduler scheduler, Timeline timeli
}
}
}

private static async Task ScheduleMemoryCleanup(IScheduler scheduler)
{
var job = JobBuilder.Create<MemoryCleanupJob>()
Expand Down

0 comments on commit 330827d

Please sign in to comment.