Skip to content

Commit

Permalink
Code clean ups (#29)
Browse files Browse the repository at this point in the history
* V4

* Clean ups
  • Loading branch information
nikita-petko committed Jul 3, 2024
1 parent 25182f6 commit 1107258
Show file tree
Hide file tree
Showing 27 changed files with 155 additions and 176 deletions.
9 changes: 4 additions & 5 deletions src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@
<!--Executes
the Git Commands to get the Hash and Branch-->
<Exec Command="git rev-parse HEAD" ConsoleToMSBuild="true"
StandardOutputImportance="low" IgnoreExitCode="true" Condition=" '$(CommitHash)' == '' " WorkingDirectory="$(SolutionDir)">
StandardOutputImportance="low" IgnoreExitCode="true" Condition=" '$(CommitHash)' == '' " WorkingDirectory="$(RootDirectory)">
<Output TaskParameter="ConsoleOutput" PropertyName="CommitHash" />
</Exec>
<Exec Command="git rev-parse --short HEAD" ConsoleToMSBuild="true"
StandardOutputImportance="low" IgnoreExitCode="true" Condition=" '$(CommitShortHash)' == '' " WorkingDirectory="$(SolutionDir)">
StandardOutputImportance="low" IgnoreExitCode="true" Condition=" '$(CommitShortHash)' == '' " WorkingDirectory="$(RootDirectory)">
<Output TaskParameter="ConsoleOutput" PropertyName="CommitShortHash" />
</Exec>
<Exec Command="git rev-parse --abbrev-ref HEAD" ConsoleToMSBuild="true"
StandardOutputImportance="low" IgnoreExitCode="true" Condition=" '$(CommitBranch)' == '' " WorkingDirectory="$(SolutionDir)">
StandardOutputImportance="low" IgnoreExitCode="true" Condition=" '$(CommitBranch)' == '' " WorkingDirectory="$(RootDirectory)">
<Output TaskParameter="ConsoleOutput" PropertyName="CommitBranch" />
</Exec>

Expand All @@ -50,8 +50,7 @@
</PropertyGroup>

<PropertyGroup Label="RootDirectory">
<RootDirectory Condition="'$(SolutionDir)' != ''">$(SolutionDir)</RootDirectory>
<RootDirectory Condition="'$(SolutionDir)' == ''">$(MSBuildThisFileDirectory)../</RootDirectory>
<RootDirectory>$(MSBuildThisFileDirectory)../</RootDirectory>
</PropertyGroup>

<PropertyGroup Label="PackageProperties" Condition="'$(IsTestProject)' != 'true'">
Expand Down
2 changes: 1 addition & 1 deletion src/configuration/configuration/Configuration.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<Description>C# adaptation for @mfdlabs/environment.</Description>

<Version>1.0.7</Version>
<Version>1.0.8</Version>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,7 @@ public abstract class EnvironmentProvider : BaseProvider
/// <inheritdoc cref="BaseProvider.SetRawValue{T}(string, T)"/>
protected override void SetRawValue<T>(string variable, T value)
{
var realValue = value.ToString();

if (typeof(T).IsArray)
realValue = string.Join(",", value as Array);

if (value is IDictionary dictionary)
realValue = string.Join("\n", dictionary.Keys.Cast<object>().Select(key => $"{key}={dictionary[key]}"));
var realValue = ConvertFrom(value, typeof(T));

Environment.SetEnvironmentVariable(variable, realValue);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,7 @@ protected override void SetRawValue<T>(string variable, T value)

_logger?.Debug("VaultProvider: Set value in vault at path '{0}/{1}/{2}'", Mount, Path, variable);

var realValue = value.ToString();

if (typeof(T).IsArray)
realValue = string.Join(",", (value as Array).Cast<object>().ToArray());
var realValue = ConvertFrom(value, typeof(T));

_cachedValues[variable] = realValue;

Expand Down
2 changes: 1 addition & 1 deletion src/configuration/core/Configuration.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<Description>Helpers for configuration in applications.</Description>

<Version>1.0.4</Version>
<Version>1.0.5</Version>
</PropertyGroup>

<ItemGroup>
Expand Down
28 changes: 10 additions & 18 deletions src/configuration/core/Extensions/ConfigurationExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,17 +159,13 @@ internal static void SafelyInvoke<TVal>(this Action<TVal> propertyChangeHandler,
var name = expression.GetPropertyName();
provider.PropertyChanged += (_, e) =>
{
if (e.PropertyName == name)
{
var newValue = getter(provider);
if (e.PropertyName != name) return;
if (newValue == null || !newValue.Equals(value))
{
propertyChangeHandler.SafelyInvoke(logger);
var newValue = getter(provider);
if (newValue != null && newValue.Equals(value)) return;
value = newValue;
}
}
propertyChangeHandler.SafelyInvoke(logger);
value = newValue;
};
}

Expand Down Expand Up @@ -237,17 +233,13 @@ internal static void SafelyInvoke<TVal>(this Action<TVal> propertyChangeHandler,
var name = GetPropertyName(expression);
provider.PropertyChanged += (_, e) =>
{
if (e.PropertyName == name)
{
var newValue = getter(provider);
if (e.PropertyName != name) return;
if (newValue == null || !newValue.Equals(value))
{
propertyChangeHandler.SafelyInvoke(newValue, logger);
var newValue = getter(provider);
if (newValue != null && newValue.Equals(value)) return;
value = newValue;
}
}
propertyChangeHandler.SafelyInvoke(newValue, logger);
value = newValue;
};
}

Expand Down
5 changes: 5 additions & 0 deletions src/file-system/file-system/ExponentialBackoff.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,21 @@ private static TimeSpan CalculateBackoff(uint attempt, uint maxAttempts, TimeSpa
{
if (maxAttempts > CeilingForMaxAttempts)
throw new ArgumentOutOfRangeException($"{maxAttempts} must be less than or equal to {CeilingForMaxAttempts}");

if (attempt > maxAttempts) attempt = maxAttempts;

var delay = baseDelay.Multiply(Math.Pow(2, attempt - 1));
if (delay > maxDelay || delay < TimeSpan.Zero) delay = maxDelay;

var random = nextRandomDouble();

delay = jitter switch
{
Jitter.Full => delay.Multiply(random),
Jitter.Equal => delay.Multiply(0.5 + random * 0.5),
_ => delay
};

return delay;
}
}
2 changes: 1 addition & 1 deletion src/file-system/file-system/FileSystem.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<Description>File system helpers and more!</Description>

<Version>1.0.4</Version>
<Version>1.0.5</Version>
</PropertyGroup>

<ItemGroup>
Expand Down
13 changes: 7 additions & 6 deletions src/floodcheckers/redis/BaseRedisFloodChecker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,7 @@ public IFloodCheckerStatus Check()
int limit = 0;
int count = 0;

if (!IsEnabled())
return new FloodCheckerStatus(false, limit, count, Category);
if (!IsEnabled()) return new FloodCheckerStatus(false, limit, count, Category);

try
{
Expand Down Expand Up @@ -221,9 +220,9 @@ public int GetCountOverLimit()
/// <param name="category">The category.</param>
protected virtual void RaiseOnFloodedEvent(string category)
{
if (GlobalFloodCheckerEventLogger != null)
if (RecordGlobalFloodedEvents?.Invoke() == true)
GlobalFloodCheckerEventLogger.RecordFloodCheckerIsFlooded(category);
if (GlobalFloodCheckerEventLogger == null || RecordGlobalFloodedEvents?.Invoke() != true) return;

GlobalFloodCheckerEventLogger.RecordFloodCheckerIsFlooded(category);
}

/// <summary>
Expand All @@ -239,6 +238,7 @@ protected int GetLimit()
if (windowPeriod < minimumWindowPeriod && windowPeriod.TotalMilliseconds > 0)
{
int factor = (int)Math.Ceiling(minimumWindowPeriod.TotalMilliseconds / windowPeriod.TotalMilliseconds);

limit *= factor;
}

Expand All @@ -258,7 +258,8 @@ protected TimeSpan GetWindowPeriod()
windowPeriod = TimeSpan.FromMilliseconds(
(int)Math.Ceiling(minimumWindowPeriod.TotalMilliseconds /
windowPeriod.TotalMilliseconds) *
windowPeriod.TotalMilliseconds);
windowPeriod.TotalMilliseconds
);

return windowPeriod;
}
Expand Down
2 changes: 1 addition & 1 deletion src/floodcheckers/redis/FloodCheckers.Redis.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<Description>Library for interacting with Redis based flood checkers!</Description>

<Version>1.0.4</Version>
<Version>1.0.5</Version>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,12 +123,10 @@ protected override void DoUpdateCount()

RedisClient.Execute(bucketKey, db => db.StringIncrement(bucketKey));

if (bucketKey != _LastBucketUpdated)
{
RedisClient.Execute(bucketKey, db => db.KeyExpire(bucketKey, GetBucketExpiryTimeSpan(window), CommandFlags.FireAndForget));
if (bucketKey == _LastBucketUpdated) return;

_LastBucketUpdated = bucketKey;
}
RedisClient.Execute(bucketKey, db => db.KeyExpire(bucketKey, GetBucketExpiryTimeSpan(window), CommandFlags.FireAndForget));
_LastBucketUpdated = bucketKey;
}

/// <inheritdoc cref="BaseRedisFloodChecker.DoReset"/>
Expand All @@ -141,8 +139,9 @@ protected override void DoReset()
RedisClient.Execute(currentBucketKey, db => db.KeyDelete(currentBucketKey));

var previousBucketKey = GetBucketKey(timeNow - window, window);
if (previousBucketKey != currentBucketKey)
RedisClient.Execute(previousBucketKey, db => db.KeyDelete(previousBucketKey));
if (previousBucketKey == currentBucketKey) return;

RedisClient.Execute(previousBucketKey, db => db.KeyDelete(previousBucketKey));
}

/// <inheritdoc cref="BaseRedisFloodChecker.DoGetCount"/>
Expand Down
8 changes: 3 additions & 5 deletions src/floodcheckers/redis/RedisRollingWindowFloodChecker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,10 @@ protected override void DoUpdateCount()

RedisClient.Execute(bucketKey, db => db.SortedSetAdd(bucketKey, Guid.NewGuid().ToString(), timeNow.Ticks, CommandFlags.FireAndForget));

if (bucketKey != _LastBucketUpdated)
{
RedisClient.Execute(bucketKey, db => db.KeyExpire(bucketKey, GetBucketExpiryTimeSpan(window), CommandFlags.FireAndForget));
if (bucketKey == _LastBucketUpdated) return;

_LastBucketUpdated = bucketKey;
}
RedisClient.Execute(bucketKey, db => db.KeyExpire(bucketKey, GetBucketExpiryTimeSpan(window), CommandFlags.FireAndForget));
_LastBucketUpdated = bucketKey;
}

/// <inheritdoc cref="BaseRedisFloodChecker.DoReset"/>
Expand Down
2 changes: 1 addition & 1 deletion src/grid/port-management/Grid.PortManagement.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<Description>Shared library for port allocation on grid-servers!</Description>

<Version>1.0.4</Version>
<Version>1.0.5</Version>
<RootNamespace>Grid</RootNamespace>
</PropertyGroup>

Expand Down
1 change: 1 addition & 0 deletions src/grid/port-management/Implementation/PortAllocator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ public int FindNextAvailablePort()
if (IsPortInUse(port))
{
_logger.Warning("Chosen random port, {0}, is already in use", port);

continue;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<PropertyGroup>
<Description>Shared library for core interaction with grid server processes!</Description>

<Version>1.0.4</Version>
<Version>1.0.5</Version>
<RootNamespace>Grid</RootNamespace>
</PropertyGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,27 +125,27 @@ public void WaitForServiceToBecomeAvailable(bool forceTry, Stopwatch stopwatch)
if (!forceTry && HasExited)
throw new Exception(string.Format("Failed to connect to port {0} because GridServer container has already exited.", Port));

using (var client = new TcpClient())
using var client = new TcpClient();

try
{
client.Client.Connect(_LocalHostIpAddress, Port);

Logger.Information(
"Port successfully opened, Port: {0}, Attempts: {1}, AttemptTime: {2}, TotalTime: {3}",
Port,
attempt,
sw.ElapsedMilliseconds,
stopwatch.ElapsedMilliseconds
);

return;
}
catch (Exception ex)
{
try
{
client.Client.Connect(_LocalHostIpAddress, Port);

Logger.Information(
"Port successfully opened, Port: {0}, Attempts: {1}, AttemptTime: {2}, TotalTime: {3}",
Port,
attempt,
sw.ElapsedMilliseconds,
stopwatch.ElapsedMilliseconds
);
return;
}
catch (Exception ex)
{
Logger.Debug("Failed to connect, Port: {0}, Attempts: {1}, AttemptTime: {2}. Error: {3}", Port, attempt, sw.ElapsedMilliseconds, ex);

innerException = ex.ToString();
}
Logger.Debug("Failed to connect, Port: {0}, Attempts: {1}, AttemptTime: {2}. Error: {3}", Port, attempt, sw.ElapsedMilliseconds, ex);

innerException = ex.ToString();
}

Thread.Sleep(_Settings.GridServerWaitForTcpSleepInterval);
Expand Down
Loading

0 comments on commit 1107258

Please sign in to comment.