Skip to content

v1.7.0

Latest

Choose a tag to compare

@CypherPotato CypherPotato released this 18 Oct 03:03
· 14 commits to main since this release

v1.7

This release introduces custom route matching, the HTTP QUERY method, atomic request-context values, a safer default request size limit, and a hardened Cadente HTTP/1.1 parser. It also discontinues three extension packages.

Packages in this release: Sisk.HttpServer 1.7.0, Sisk.Cadente 1.7.0, Sisk.Cadente.CoreEngine 1.7.0, Sisk.IniConfiguration 1.7.0 and Sisk.IniConfiguration.Core 1.7.0. Sisk.Documenting, Sisk.Documenting.Html and Sisk.Monitoring ship as 1.7.0-rc3, and Sisk.ModelContextProtocol ships as 1.7.0-rc1.

Breaking changes

  • Breaking: Route.UseRegex is now read-only and marked [Obsolete]. It returns true only when the route is a RegexRoute. Code that set UseRegex = true on a Route no longer compiles, and binaries compiled against earlier versions fail with MissingMethodException when they call the removed setter. Create a RegexRoute instead. The RouteAttribute.UseRegex property and the [RegexRoute] attribute keep working.

    // before
    router.Map(new Route(RouteMethod.Get, @"^/items/(?<id>\d+)$", action) { UseRegex = true });
    
    // after
    router.Map(new RegexRoute(RouteMethod.Get, @"^/items/(?<id>\d+)$", action));
  • Breaking: the default value of HttpServerConfiguration.MaximumContentLength changed from 0 (unlimited) to 100 MB. The limit is enforced on HttpRequest.RawBody, on the stream returned by HttpRequest.GetRequestStream(), and on the maximum WebSocket message size. Requests that declare a Content-Length above the limit receive 413 Content Too Large. Chunked or streamed bodies that exceed the limit throw InsufficientMemoryException while being read, which the server reports as 500 Internal Server Error unless the application handles it. Set the property to 0 to restore the previous unlimited behavior.

    using var app = HttpServer.CreateBuilder()
        .UseConfiguration(config => config.MaximumContentLength = 0)
        .Build();

    Applications configured through UsePortableConfiguration(...) with a JSON file are not affected when the Server section is present: the parser always assigns Server.MaximumContentLength, which defaults to 0 when the property is omitted.

  • Breaking: Router now throws ArgumentException when the server starts if two or more routes share the same Name. The check runs together with the existing route collision check and is controlled by Router.CheckForRouteCollisions, which is enabled by default. Applications that registered routes with duplicate names must rename them or disable the check.

  • Breaking: static routes are always evaluated before dynamic routes (RegexRoute, PrefixRoute and custom Route subclasses), regardless of the order in which they were registered. In earlier versions a regular expression route registered first could shadow a static route registered later. Applications that relied on registration order to give a dynamic route precedence over a static route must adjust their patterns.

  • Breaking: HttpFileServer.CreateServingRoute(...) now returns a PrefixRoute instead of a RegexRoute, which also applies to routes registered through Router.MapFileSystem(...). File server routes no longer participate in HttpServerConfiguration.ForceTrailingSlash rewrites.

  • Breaking: RouteMethod.Any now includes the new RouteMethod.Query flag, so routes mapped with Any also answer QUERY requests. Because Any is a constant, its numeric value changed from 446 to 958; code that persisted or compared the raw value must be recompiled.

  • Breaking: CORS preflight handling now respects Route.UseCors. When the matched route has UseCors = false, the automatic OPTIONS response no longer carries CORS headers. Routes explicitly mapped with RouteMethod.Options take precedence over the automatic preflight response.

Custom route matching

Route.Match(string requestPath, Router router) is now virtual and returns a RouteMatch object with the match result and the extracted parameters. Subclasses can override it to implement any matching strategy. RegexRoute and the new PrefixRoute are built on this mechanism.

public sealed class ExtensionRoute : Route
{
    private readonly string extension;

    public ExtensionRoute(string extension, RouteAction action)
        : base(RouteMethod.Get, "/", action)
    {
        this.extension = extension;
    }

    public override bool IsStatic => false;

    public override RouteMatch Match(string requestPath, Router router)
    {
        return requestPath.EndsWith(extension, StringComparison.OrdinalIgnoreCase)
            ? new RouteMatch(true, null)
            : RouteMatch.NotMatched;
    }
}

router.Map(new ExtensionRoute(".md", request => new HttpResponse("markdown")));
  • Added PrefixRoute, which matches every request path that starts with the configured prefix.
  • Added RouteMatch with Success, Parameters and the static RouteMatch.NotMatched instance.
  • Added the protected virtual method Route.OnPathModified() and the virtual properties Route.IsStatic and Route.AllowRewrites, so subclasses control collision checks, ordering and trailing-slash rewrites.
  • Added a parameterless constructor to RegexRoute.
  • Changed the route collision check to compare only static routes, which removes false collision errors between regular expression routes and static routes.

HTTP QUERY method

Added support for the HTTP QUERY method in Sisk.HttpServer and Sisk.Cadente.

router.MapQuery("/search", request =>
{
    string filter = request.Body;
    return new HttpResponse(filter)
    {
        Headers = new() { AcceptQuery = "application/json" }
    };
});
  • Added RouteMethod.Query, Router.MapQuery(...), Route.Query(...) and the [RouteQuery] attribute.
  • Added HttpHeaderCollection.AcceptQuery and HttpKnownHeaderNames.AcceptQuery.

Request context

  • Added HttpContext.Interlocked, an HttpContextInterlocked instance with Add, Exchange, CompareExchange and Inspect methods for atomic numeric values stored in the request context. It is useful for counters shared between request handlers and the route action.

    public override HttpResponse? Execute(HttpRequest request, HttpContext context)
    {
        context.Interlocked.Add("attempts", 1);
        return null;
    }
  • HttpContext now implements IDisposable and is disposed by the server at the end of the request.

  • Fixed an issue where HttpListenerAbstractEngine.ContextAbortedToken threw HttpEngineException; it now returns CancellationToken.None.

Server and request pipeline

  • Changed the HttpListener engine to dispatch each accepted context to the thread pool. Previously a request could be handled inline on the accept callback and wait for the next incoming request before completing.
  • Fixed an issue where request bodies were buffered in a MemoryStream preallocated with the declared Content-Length, which allowed a client to force large allocations before the body was read.
  • Fixed an issue where an exception thrown by ForwardingResolver.OnResolveClientAddress was raised a second time while writing the access log, which terminated the process with the default engine and left the server locked when AsyncRequestProcessing was false.
  • Changed HttpServerHandler exception handling at the end of a request: exceptions thrown by OnHttpRequestClose, OnException or by log formatting are written to ErrorsLogsStream and never escape the engine callback. When ThrowExceptions is enabled, handler exceptions raised by server lifecycle events are wrapped in an InvalidOperationException with the original exception as InnerException.
  • Fixed an issue where HttpRequestEventSource flushed the output stream outside the serialized send section, which could interleave with concurrent writes.
  • Fixed an issue where + characters in request paths were decoded as spaces by HttpFileServerHandler.
  • Added .toon, .xcss and .slnx to the plain text file extensions recognized by the file server.

CORS

  • Fixed an issue where preflight requests ignored Route.UseCors and explicit OPTIONS routes.
  • Added the Vary: Origin response header when AllowOrigin is set to the automatic value or when AllowOrigins contains a list of origins.

Logging

  • Added the %{$name} access log format term, which prints the value stored under name in HttpContext.RequestBag.
  • Changed the %ri access log term to use the client address resolved at the start of the request instead of invoking the ForwardingResolver again.
  • Added the helper methods LogStream.SafeWriteToFile(...) and LogStream.SafeAppendToFile(...), with synchronous and asynchronous overloads for text and line arrays. They create missing directories, serialize concurrent writes to the same file and return false instead of throwing on I/O failures.
  • Added the helper methods PathHelper.EnsureDirectoryExistance(...) and PathHelper.EnsureFileDirectoryExistance(...).

Cadente

Sisk.Cadente and Sisk.Cadente.CoreEngine target net9.0 and net10.0.

  • Added support for pipelined keep-alive requests with buffered connection I/O.
  • Added HttpHostContext.HttpResponse.WriteInlineContent(ReadOnlySpan<byte>) and WriteInlineContentAsync(ReadOnlyMemory<byte>, CancellationToken).
  • Changed HttpServer.ListeningPrefixes to report the https scheme for listening hosts configured with SSL.
  • Fixed a security issue where request targets containing bytes outside %x21-7E were accepted. A target such as /admin\x80x was routed to /admin, and a line feed inside the target forged extra lines in the error log. These requests are now rejected.
  • Fixed an issue where request methods that are not valid HTTP tokens reached the core and produced a 500 response through FormatException. They are now rejected by the parser.
  • Fixed an issue where a request whose header block exceeded the 8 KB read buffer closed the connection silently. Cadente now answers 431 Request Header Fields Too Large with Connection: close.
  • Fixed an issue where requests with Transfer-Encoding values other than a single chunked token, or with conflicting Content-Length headers, were accepted.
  • Fixed an issue where the request body byte counter overflowed for bodies larger than 2 GB, and where draining a large body could consume bytes of the next pipelined request (#51).

Packaging

  • Sisk.HttpServer targets net8.0, net9.0 and net10.0.
  • Sisk.Cadente and Sisk.Cadente.CoreEngine now publish portable .snupkg symbol packages instead of embedding debug symbols in the assemblies. Sisk.HttpServer keeps embedded symbols.

Extensions

Discontinued packages

The following packages are no longer maintained. Their latest versions are marked as deprecated on NuGet with no replacement, and their source code is kept in the repository for historical reference only.

  • Removed Sisk.BasicAuth from the supported packages. The BasicAuthenticateRequestHandler shipped since 1.5.2 does not decode the Base64 credentials sent by standard HTTP clients, so authenticated requests are rejected with 400. Applications should implement Basic authentication with a custom IRequestHandler.
  • Removed Sisk.SslProxy from the supported packages. It no longer compiles against the current Sisk.Cadente API. Use the native TLS support of Sisk.Cadente instead.
  • Removed Sisk.ServiceProvider from the supported packages. It targets net6.0 and net7.0 only and has not been updated since 2024. Its configuration features are available through HttpServer.CreateBuilder() and UsePortableConfiguration(...) in Sisk.HttpServer.

Sisk.Documenting and Sisk.Documenting.Html (1.7.0-rc3)

  • Added parameter examples to documented endpoints.
  • Added LlmsApiExporter.FooterText to append custom text to the generated llms.txt output.
  • Changed the HTML documentation layout with endpoint navigation, a search dialog and collapsible content.
  • Fixed an issue where endpoint and group element IDs could be empty, collide with each other or be invalid CSS selectors, which aborted the page script with a SyntaxError. Endpoint IDs are now derived from the method and route path. Anchors produced by the previous ID scheme no longer resolve.
  • Fixed an issue where endpoints with the same name but different paths were collapsed into a single entry.
  • Fixed an issue where endpoint names, paths and groups were written to the search results without HTML escaping.
  • Fixed an issue where Markdown descriptions were not rendered as CommonMark.

Sisk.Monitoring (1.7.0-rc3)

  • Added HTTP traffic, latency, route and exception telemetry to the dashboard.
  • Reduced the cost of Counter.Increment and Meter.Increment. Counter kept one entry per increment and scanned the whole list on every call, and Meter rebuilt an array with every bucket key on every call, so both became slower as data accumulated. Increments are now amortized O(1) and Meter.Increment no longer allocates.

Sisk.ModelContextProtocol (1.7.0-rc1)

  • Added skills support to McpProvider.
  • Updated the streamable HTTP transport to the current Model Context Protocol revision.

Sisk.IniConfiguration (1.7.0)

  • Updated the package version to match the core release. There are no code changes. Because of the new core default, omitting Server.MaximumContentLength in the INI file now results in a 100 MB limit.