Skip to content

Refactor ConfigureKestrelEndpoints to Reduce Cognitive Complexity #597

@ziagham

Description

@ziagham

What version of FlowSynx?

1.2.2

Describe the issue

The ConfigureKestrelEndpoints method currently has a Cognitive Complexity of 19, which exceeds our allowed limit of 15.

File: src/FlowSynx/Extensions/WebApplicationBuilderExtensions.cs
Method: ConfigureKestrelEndpoints
Current Complexity: 19
Expected Complexity: 15

Proposed Refactoring

private static void ConfigureKestrelEndpoints(
    WebApplicationBuilder builder,
    EndpointConfiguration config,
    ILogger logger)
{
    builder.WebHost.ConfigureKestrel((_, options) =>
    {
        var httpPort = config.Http?.Port ?? 6262;
        int? httpsPort = GetHttpsPort(config, httpPort);

        options.ListenAnyIP(httpPort);

        if (httpsPort.HasValue)
        {
            ConfigureHttps(options, httpsPort.Value, config.Https, logger, httpPort);
        }
        else
        {
            logger.LogInformation("Configuring HTTP endpoint only: HTTP {HttpPort}", httpPort);
        }
    });
}

private static int? GetHttpsPort(EndpointConfiguration config, int httpPort)
{
    if (config.Https?.Enabled != true) return null;

    var httpsPort = config.Https.Port ?? 6263;
    if (httpsPort == httpPort)
        throw new InvalidOperationException($"HTTP and HTTPS endpoint ports cannot be the same: {httpPort}");

    return httpsPort;
}

private static void ConfigureHttps(
    KestrelServerOptions options,
    int httpsPort,
    HttpsEndpointConfiguration? httpsConfig,
    ILogger logger,
    int httpPort)
{
    options.ListenAnyIP(httpsPort, listenOptions =>
    {
        var cert = httpsConfig?.Certificate;
        if (cert != null)
        {
            if (!string.IsNullOrWhiteSpace(cert.Password))
                listenOptions.UseHttps(cert.Path, cert.Password);
            else
                listenOptions.UseHttps(cert.Path);
        }
        else
        {
            listenOptions.UseHttps();
        }
    });

    logger.LogInformation("Configuring HTTP and HTTPS endpoints: HTTP {HttpPort}, HTTPS {HttpsPort}", httpPort, httpsPort);
}

Rational

  • Extract nested conditionals into smaller helper methods.
  • Reduce nested if statements by using early returns or guards.
  • Simplify certificate configuration logic.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions