Path: redb-route/redb.Route.Http/Rest/RestDefinition.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Http/Rest/RestDefinition.cs ---- using System.Text.RegularExpressions; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.Http.Rest; /// /// REST DSL (Apache Camel rest() parity) on top of the HTTP consumer and the shared Kestrel host: /// every verb becomes an ordinary route From("http://host:port/base/path?methods=GET&inOut=true"), /// so path templates, method dispatch (405), CORS, TLS and everything else stay where they already are. /// The DSL adds the declarative layer: path parameters as header.id, query as header.query.page, /// Consumes / Produces with 415 on mismatch, JSON binding to CLR types, and an OpenAPI 3.0 /// document generated from the declarations. /// /// /// this.Rest("/api/orders", o => o.Port = 8080) /// .Get("/{id}").To("direct:get-order") /// .Post().Consumes("application/json").Type<Order>().To("direct:create-order") /// .Put("/{id}/status").To("direct:set-status") /// .Delete("/{id}").To("direct:cancel-order"); /// /// /// public sealed class RestDefinition { private static readonly Regex PathParameter = new(@"\{(\w+)\}", RegexOptions.Compiled); private readonly RouteBuilder _builder; private readonly List _verbs = []; private bool _openApiRegistered; internal RestDefinition(RouteBuilder builder, string basePath, RestOptions options) { _builder = builder; BasePath = "/" + basePath.Trim('/'); Options = options; } /// Common path prefix of the verbs (/api/orders). public string BasePath { get; } /// Settings of this declaration. public RestOptions Options { get; } /// Verbs declared so far (completed with To / Route). public IReadOnlyList Verbs => _verbs; /// Declares a GET operation. public RestVerbDefinition Get(string path = "") => new(this, "GET", path); /// Declares a POST operation. public RestVerbDefinition Post(string path = "") => new(this, "POST", path); /// Declares a PUT operation. public RestVerbDefinition Put(string path = "") => new(this, "PUT", path); /// Declares a DELETE operation. public RestVerbDefinition Delete(string path = "") => new(this, "DELETE", path); /// Declares a PATCH operation. public RestVerbDefinition Patch(string path = "") => new(this, "PATCH", path); /// Declares a HEAD operation. public RestVerbDefinition Head(string path = "") => new(this, "HEAD", path); /// Creates the HTTP route of a finished verb; returns the route so inline steps can follow. internal IRouteDefinition Complete(RestVerbDefinition verb) { _verbs.Add(verb); EnsureOpenApiRoute(); var key = verb.RouteId ?? $"{verb.Method} {verb.FullPath}"; var routeId = verb.RouteId ?? GeneratedId(key); var route = _builder.From(ConsumerUri(verb.FullPath, verb.Method)).RouteId(routeId); Append(route, new RestRequestDefinition(verb, Options)); if (verb.Target is not null) { route.To(verb.Target); Append(route, new RestResponseDefinition(verb, Options)); return route; } // Inline steps live in their own direct route, so the response step can still run after them. // The name carries a fingerprint (GeneratedId): sanitizing alone maps "/{id}" and "/id" to the // same text, and a direct endpoint registered twice silently keeps the last handler. var inner = $"direct://{GeneratedId(key)}"; route.To(inner); Append(route, new RestResponseDefinition(verb, Options)); return _builder.From(inner).RouteId(routeId + "-handler"); } /// Path the OpenAPI document is served at ( or {basePath}/openapi.json). public string OpenApiPath => Options.OpenApiPath ?? JoinPath(BasePath, "openapi.json"); private void EnsureOpenApiRoute() { if (_openApiRegistered || !Options.OpenApi) return; _openApiRegistered = true; var route = _builder.From(ConsumerUri(OpenApiPath, "GET")).RouteId(GeneratedId($"openapi {BasePath}")); Append(route, new OpenApiDocumentDefinition(this)); } private string ConsumerUri(string path, string method) { var uri = new System.Text.StringBuilder($"http://{Options.Host}:{Options.Port}{path}?methods={method}&inOut=true"); void Add(string key, string? value) { if (value is not null) uri.Append('&').Append(key).Append('=').Append(Uri.EscapeDataString(value)); } if (Options.InboundAuth != HttpAuthScheme.None) Add("inboundAuth", Options.InboundAuth.ToString().ToLowerInvariant()); Add("inboundUsername", Options.InboundUsername); Add("inboundPassword", Options.InboundPassword); Add("inboundRealm", Options.InboundRealm); Add("tokenValidator", Options.TokenValidator); if (!string.IsNullOrWhiteSpace(Options.ExtraConsumerOptions)) uri.Append('&').Append(Options.ExtraConsumerOptions.TrimStart('&')); return uri.ToString(); } private static void Append(IRouteDefinition route, IProcessorDefinition step) { step.Parent = route; route.Outputs.Add(step); } /// /// A generated route id: rest-GET-api-orders-id-1a2b3c4d. It carries no '/' and no space, because the worker /// API and the dashboard address a route by one path segment. The fingerprint keeps /{id} and /id /// apart, which sanitizing alone maps to the same text, and it is the same in every process, so the id survives a /// restart. /// internal static string GeneratedId(string key) => $"rest-{Sanitize(key)}-{Fingerprint(key)}"; private static string Sanitize(string routeId) => Regex.Replace(routeId, @"[^A-Za-z0-9_.-]+", "-").Trim('-'); /// Eight hex digits of the route id's SHA-256: stable across processes, distinct for ids that sanitize alike. private static string Fingerprint(string routeId) => Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(routeId)))[..8].ToLowerInvariant(); internal static string JoinPath(string basePath, string path) { var tail = path.Trim('/'); return tail.Length == 0 ? basePath : $"{basePath.TrimEnd('/')}/{tail}"; } internal static IReadOnlyList PathParameterNames(string template) => PathParameter.Matches(template).Select(m => m.Groups[1].Value).ToList(); }