Skip to content

Commit

Permalink
Update to net8.0
Browse files Browse the repository at this point in the history
  • Loading branch information
OoLunar committed Jun 28, 2024
1 parent 0477634 commit 89ca3fa
Show file tree
Hide file tree
Showing 18 changed files with 82 additions and 88 deletions.
36 changes: 20 additions & 16 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,44 @@ root = true
# All files
[*]
indent_style = space
charset = utf-8

# XML project files
[*.{config,csproj,nuspec,proj,projitems,props,resx,ruleset,shproj,targets,vbproj,vcxproj,vcxproj.filters,vsct,vsixmanifest}]
[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,projitems,shproj}]
indent_size = 2

# XML config files
[*.{props,targets,ruleset,config,nuspec,resx,vsixmanifest,vsct}]
indent_size = 2

# Code files
[*.cs]
indent_size = 4
insert_final_newline = true
charset = utf-8

###############################
# .NET Coding Conventions #
###############################
[*.{cs,vb}]

# Suppress CS1591: Missing XML comment for publicly visible type or member
dotnet_diagnostic.CS1591.severity = none

# Suppress IDE0058: Expression value is never used
dotnet_diagnostic.IDE0058.severity = none

# Disable require license header
dotnet_diagnostic.IDE0073.severity = none

# Organize usings
dotnet_sort_system_directives_first = true:error

# Using directive is unnecessary.
dotnet_diagnostic.IDE0005.severity = error

# Use regular consturctors over primary constructors
csharp_style_prefer_primary_constructors = false

# Yell at people when they don't include the file header template
dotnet_diagnostic.IDE0073.severity = error

Expand Down Expand Up @@ -69,9 +86,6 @@ dotnet_style_prefer_conditional_expression_over_return = true:error

# Style Definitions
dotnet_naming_style.pascal_case_style.capitalization = pascal_case
dotnet_naming_style.camel_case_with_underscore.capitalization = camel_case
dotnet_naming_style.camel_case_with_underscore.required_prefix = _
dotnet_naming_style.camel_case_with_underscore.word_separator =

# Use PascalCase for constant fields
dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = error
Expand All @@ -98,18 +112,8 @@ dotnet_naming_style.async_suffix.capitalization = pascal_case
dotnet_naming_symbols.async_methods.applicable_kinds = method
dotnet_naming_symbols.async_methods.required_modifiers = async

# Enforce private or internal properties/fields to start with a '_' and be camelcased
dotnet_naming_rule.camel_case_private_internal_fields_with_underscore.severity = suggestion
dotnet_naming_rule.camel_case_private_internal_fields_with_underscore.symbols = private_internal_fields
dotnet_naming_rule.camel_case_private_internal_fields_with_underscore.style = camel_case_with_underscore
dotnet_naming_symbols.private_internal_fields.applicable_kinds = field, property
dotnet_naming_symbols.private_internal_fields.applicable_accessibilities = private, internal
dotnet_naming_symbols.private_internal_fields.required_modifiers = private, internal
dotnet_naming_symbols.private_internal_fields.required_prefix = _
dotnet_naming_symbols.private_internal_fields.required_style = camel_case

# Don't force namespaces to match their folder names
dotnet_diagnostic.IDE0130.severity = none
dotnet_style_namespace_match_folder = false

###############################
# C# Coding Conventions #
Expand Down
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
<PackageProjectUrl>https://github.com/OoLunar/HyperSharp</PackageProjectUrl>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
<ProjectRoot>$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildProjectDirectory), "HyperSharp.sln"))</ProjectRoot>
<ProjectRoot>$(MSBuildThisFileDirectory)</ProjectRoot>
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/OoLunar/HyperSharp</RepositoryUrl>
Expand Down
4 changes: 2 additions & 2 deletions benchmarks/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public static void Main(string[] args)
fileStream.Write(Encoding.UTF8.GetBytes(GetHumanizedNanoSeconds(summary.TotalTime.TotalNanoseconds)));

// baseline first, then order by success, then by name
BenchmarkReport[] array = summary.Reports.OrderBy(report => !summary.IsBaseline(report.BenchmarkCase)).ThenBy(report => !report.Success).ThenBy(report => report.BenchmarkCase.Descriptor.WorkloadMethodDisplayInfo).ToArray();
BenchmarkReport[] array = [.. summary.Reports.OrderBy(report => !summary.IsBaseline(report.BenchmarkCase)).ThenBy(report => !report.Success).ThenBy(report => report.BenchmarkCase.Descriptor.WorkloadMethodDisplayInfo)];
for (int i = 0; i < array.Length; i++)
{
BenchmarkReport report = array[i];
Expand Down Expand Up @@ -181,7 +181,7 @@ public static ServiceProvider CreateServiceProvider()
}

hyperConfiguration.ListeningEndpoint = new IPEndPoint(address, configuration.GetValue("server:port", 8080));
hyperConfiguration.AddResponders(new[] { typeof(HelloWorldValueTaskResponder) });
hyperConfiguration.AddResponders([typeof(HelloWorldValueTaskResponder)]);
});

services.AddSingleton(services =>
Expand Down
2 changes: 2 additions & 0 deletions examples/HyperSharp.Example.Intro/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ public static async Task Main()

loggingBuilder.AddSerilog(configuration.CreateLogger());
});

// Add HyperSharp to the service collection.
services.AddHyperSharp();

// Build the service provider and get the HyperServer instance.
Expand Down
2 changes: 1 addition & 1 deletion src/HyperSharp.Responders/HyperSharp.Responders.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<IsPackable>true</IsPackable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../HyperSharp.Results/HyperSharp.Results.csproj" />
<ProjectReference Include="$(ProjectRoot)/src/HyperSharp.Results/HyperSharp.Results.csproj" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="8.0.1" />
</ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/HyperSharp.Responders/ResponderBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public ResponderBuilder(Type type, bool isSyncronous, IEnumerable<Type> dependen
Type = type;
IsSyncronous = isSyncronous;
Dependencies = new(dependencies);
RequiredBy = new();
RequiredBy = [];
}
}
}
8 changes: 4 additions & 4 deletions src/HyperSharp.Results/Error.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace HyperSharp.Results
[JsonConverter(typeof(ErrorJsonConverter))]
public record Error
{
private static readonly Error[] _empty = Array.Empty<Error>();
private static readonly Error[] _empty = [];

/// <summary>
/// A summary of the error.
Expand Down Expand Up @@ -56,7 +56,7 @@ public Error(string message)
public Error(string message, Error error)
{
Message = message;
Errors = new Error[1] { error };
Errors = [error];
}

/// <summary>
Expand Down Expand Up @@ -90,7 +90,7 @@ public Error(Exception exception, Error error)
{
Message = exception.Message;
Exception = exception;
Errors = new Error[1] { error };
Errors = [error];
}

/// <summary>
Expand Down Expand Up @@ -127,7 +127,7 @@ public Error(string message, Exception exception, Error error)
{
Message = message;
Exception = exception;
Errors = new Error[1] { error };
Errors = [error];
}

/// <summary>
Expand Down
3 changes: 1 addition & 2 deletions src/HyperSharp.Results/Result.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json.Serialization;
Expand All @@ -12,7 +11,7 @@ namespace HyperSharp.Results
[JsonConverter(typeof(ResultJsonConverter))]
public readonly record struct Result
{
internal static readonly Error[] _emptyErrors = Array.Empty<Error>();
internal static readonly Error[] _emptyErrors = [];

/// <summary>
/// The value of the result. Check <see cref="HasValue"/> before accessing.
Expand Down
2 changes: 1 addition & 1 deletion src/HyperSharp.Routing/HyperSharp.Routing.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@
<PackageId>OoLunar.HyperSharp.Routing</PackageId>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="../HyperSharp/HyperSharp.csproj" />
<ProjectReference Include="$(ProjectRoot)/src/HyperSharp/HyperSharp.csproj" />
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
</PropertyGroup>
<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@ namespace HyperSharp.Protocol
{
public readonly partial record struct HyperStatus
{
#if {{NetVersion}}_OR_GREATER
/// <inheritdoc cref="global::System.Net.HttpStatusCode.{{Code}}" />
public static HyperStatus {{Code}}() => new(global::System.Net.HttpStatusCode.{{Code}}, new HyperHeaderCollection(), null);
Expand All @@ -39,8 +37,6 @@ public readonly partial record struct HyperStatus
/// <param name="headers">The headers of the response.</param>
/// <param name="body">The body of the response.</param>
public static HyperStatus {{Code}}(HyperHeaderCollection headers, object? body) => new(global::System.Net.HttpStatusCode.{{Code}}, headers, body);
#endif
}
}
Expand All @@ -64,7 +60,7 @@ public bool Execute(IConfiguration configuration)
return false;
}

Dictionary<NuGetFramework, (string, string)> nuGetFrameworks = new();
Dictionary<NuGetFramework, (string, string)> nuGetFrameworks = [];
foreach (string sdkVersion in Directory.GetDirectories(Path.Combine(dotnetRoot, "shared/Microsoft.NETCore.App/")))
{
string msBuildDependenciesJsonPath = Path.Combine(sdkVersion, "Microsoft.NETCore.App.runtimeconfig.json");
Expand Down Expand Up @@ -102,7 +98,7 @@ public bool Execute(IConfiguration configuration)
nuGetFrameworks.Add(NuGetFramework.Parse(targetFrameworkMoniker), (msBuildDependenciesJsonPath, targetFrameworkMoniker));
}

foreach (KeyValuePair<NuGetFramework, (string, string)> kvp in nuGetFrameworks.OrderByDescending(framework => framework.Key, new NuGetFrameworkSorter()))
foreach (KeyValuePair<NuGetFramework, (string, string)> kvp in nuGetFrameworks.OrderByDescending(framework => framework.Key, NuGetFrameworkSorter.Instance))
{
NuGetFramework nuGetFramework = kvp.Key;
string msBuildDependenciesJsonPath = kvp.Value.Item1;
Expand Down
58 changes: 29 additions & 29 deletions src/HyperSharp/HyperServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,43 +144,43 @@ private async Task HandleConnectionAsync(Ulid id, NetworkStream networkStream)
{
cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_mainCancellationTokenSource!.Token);
}

// Ensure all connections will close after the configured timeout.
cancellationTokenSource.CancelAfter(Configuration.Timeout);

// Start parsing the HTTP Headers.
Result<HyperContext> context = await HyperHeaderParser.TryParseHeadersAsync(Configuration.MaxHeaderSize, connection, cancellationTokenSource.Token);
if (!cancellationTokenSource.IsCancellationRequested)
if (cancellationTokenSource.IsCancellationRequested)
{
if (context.IsSuccess)
{
// Execute any registered responders.
HyperLogging.HttpReceivedRequest(_logger, connection.Id, context.Value!.Route, null);
Result<HyperStatus> status = await Configuration.RespondersDelegate(context.Value, cancellationTokenSource.Token);
if (!context.Value.HasResponded)
{
HyperLogging.HttpResponding(_logger, connection.Id, status.Value, null);
HyperStatus response = status.Status switch
{
_ when cancellationTokenSource.IsCancellationRequested => HyperStatus.InternalServerError(),
ResultStatus.IsSuccess | ResultStatus.HasValue => status.Value,
ResultStatus.IsSuccess => HyperStatus.OK(),
ResultStatus.HasValue => HyperStatus.InternalServerError(status.Value.Headers, status.Value.Body),
ResultStatus.None => HyperStatus.InternalServerError(),
_ => throw new NotImplementedException("Unimplemented result status, please open a GitHub issue as this is a bug.")
};

await context.Value.RespondAsync(response, HyperSerializers.JsonAsync, cancellationTokenSource.Token);
HyperLogging.HttpResponded(_logger, connection.Id, response, null);
}
}
else
{
HyperLogging.HttpInvalidHeaders(_logger, connection.Id, context.Errors, null);
}
// Intentionally don't pass the cancellation token to RespondAsync, since we want to respond with a 500.
await context.Value!.RespondAsync(HyperStatus.InternalServerError(), HyperSerializers.JsonAsync, CancellationToken.None);
}
else if (!context.IsSuccess)
{
// If the headers are invalid, log the errors and close the connection without responding.
HyperLogging.HttpInvalidHeaders(_logger, connection.Id, context.Errors, null);
}
else
{
// Intentionally don't pass the cancellation token to RespondAsync, since we want to respond with a 500.
await context.Value!.RespondAsync(HyperStatus.InternalServerError(), HyperSerializers.JsonAsync, CancellationToken.None);
// Execute any registered responders.
HyperLogging.HttpReceivedRequest(_logger, connection.Id, context.Value!.Route, null);
Result<HyperStatus> status = await Configuration.RespondersDelegate(context.Value, cancellationTokenSource.Token);
if (!context.Value.HasResponded)
{
HyperLogging.HttpResponding(_logger, connection.Id, status.Value, null);
HyperStatus response = status.Status switch
{
_ when cancellationTokenSource.IsCancellationRequested => HyperStatus.InternalServerError(),
ResultStatus.IsSuccess | ResultStatus.HasValue => status.Value,
ResultStatus.IsSuccess => HyperStatus.OK(),
ResultStatus.HasValue => HyperStatus.InternalServerError(status.Value.Headers, status.Value.Body),
ResultStatus.None => HyperStatus.InternalServerError(),
_ => throw new NotImplementedException("Unimplemented result status, please open a GitHub issue as this is a bug.")
};

await context.Value.RespondAsync(response, HyperSerializers.JsonAsync, cancellationTokenSource.Token);
HyperLogging.HttpResponded(_logger, connection.Id, response, null);
}
}

HyperLogging.ConnectionClosing(_logger, connection.Id, null);
Expand Down
2 changes: 1 addition & 1 deletion src/HyperSharp/Protocol/HyperContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ public class HyperContext
/// <summary>
/// Any metadata associated with the request, explicitly set by the registered responders.
/// </summary>
public Dictionary<string, string> Metadata { get; init; } = new();
public Dictionary<string, string> Metadata { get; init; } = [];

/// <summary>
/// Whether or not the request has been responded to.
Expand Down
10 changes: 5 additions & 5 deletions src/HyperSharp/Protocol/HyperHeaderCollection.Static.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,19 @@ static HyperHeaderCollection()
}

// https://developers.cloudflare.com/rules/transform/request-header-modification/reference/header-format
private static readonly char[] _validHeaderNameCharacters = new char[]
{
private static readonly char[] _validHeaderNameCharacters =
[
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_'
};
];

private static readonly char[] _validHeaderNameValues = new char[] {
private static readonly char[] _validHeaderNameValues = [
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_',
' ', ':', ';', '.', ',', '\\', '/', '"', '\'', '!', '?', '(', ')', '{', '}', '[', ']', '@', '<', '>', '=', '+', '*', '#', '$', '&', '`', '|', '~', '^', '%'
};
];

/// <summary>
/// Validates that the header name does not contain invalid characters.
Expand Down
4 changes: 2 additions & 2 deletions src/HyperSharp/Protocol/HyperHeaderParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ public static async ValueTask<Result<HyperContext>> TryParseHeadersAsync(int max
{
throw new ArgumentOutOfRangeException(nameof(maxHeaderSize), "Max header size must be greater than zero.");
}
ArgumentNullException.ThrowIfNull(connection);

ArgumentNullException.ThrowIfNull(connection);
ReadResult readResult = await connection.StreamReader.ReadAsync(cancellationToken);
if (readResult.IsCanceled)
{
Expand All @@ -54,7 +54,7 @@ public static async ValueTask<Result<HyperContext>> TryParseHeadersAsync(int max
connection.StreamReader.AdvanceTo(sequencePosition);
readResult = await connection.StreamReader.ReadAsync(cancellationToken);

HyperHeaderCollection headers = new();
HyperHeaderCollection headers = [];
while (!readResult.IsCompleted && !readResult.IsCanceled)
{
if (readResult.Buffer.Length > maxHeaderSize)
Expand Down
Loading

0 comments on commit 89ca3fa

Please sign in to comment.