Bundle: redb-route / redb.Route.Core (redb.Route.Core.txt), 18 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/redb.Route.Core/Extensions/RedbContextDslExtensions.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.Core/Extensions/RedbContextDslExtensions.cs ---- using System.Reflection; using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.RedbCore.Repositories; namespace redb.Route.RedbCore.Extensions; /// /// Context-level redb bridge: scheme synchronization at context startup and named idempotent /// repositories in the context registry — the pieces a packaged module declares in /// context.xml (they run before any route starts, on the engine's fail-fast /// OnContextStarting hook) and a C# host calls directly. /// public static class RedbContextDslExtensions { /// /// Synchronizes the redb scheme for when the context starts — /// before any route accepts traffic, failing the start when the scheme cannot be brought up /// (the engine's OnContextStarting semantics). /// /// Route context. /// The props CLR type whose scheme to synchronize. /// Named ; null/empty — the default one. public static IRouteContext SyncRedbScheme(this IRouteContext context, Type propsType, string? storage = null) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(propsType); // Reflection once at registration; the listener invokes a prepared delegate. var sync = (Func)SyncHelperDef .MakeGenericMethod(propsType) .CreateDelegate(typeof(Func)); context.AddLifecycleListener(new StartupAction(async ctx => { var redb = string.IsNullOrEmpty(storage) ? ctx.GetRedbService() : ctx.GetRedbService(storage); await sync(redb).ConfigureAwait(false); })); return context; } /// /// Registers a in the context registry under /// , as is — the name /// IdempotentConsumer(keyExpression, repositoryName) and the markup's /// <idempotentConsumer repository="…"> look up. Built lazily when the context /// starts (the repository needs the context's service provider for per-exchange scoping). /// /// Route context. /// Registry name of the repository. /// Idempotency-entry lifetime; null — keep forever. /// Logical processor name partitioning the entries; default — the registry name. /// /// The named redb instance the entries are kept in (context.RegisterRedbService, or a Tsak Redb /// section); null for the context's default redb, as resolves it. /// public static IRouteContext AddRedbIdempotentRepository( this IRouteContext context, string name, TimeSpan? ttl = null, string? processorName = null, string? storage = null) { ArgumentNullException.ThrowIfNull(context); ArgumentException.ThrowIfNullOrEmpty(name); context.AddLifecycleListener(new StartupAction(async ctx => { var options = new RedbIdempotentOptions { ProcessorName = processorName ?? name, Ttl = ttl, }; if (string.IsNullOrEmpty(storage)) { // The context's default redb: a scope of the context's service provider per operation. var scopeFactory = ctx.GetServiceProvider()?.GetService() ?? throw new InvalidOperationException( $"AddRedbIdempotentRepository('{name}'): the context has no service provider — " + "the repository resolves a scoped IRedbService per exchange and needs DI."); ctx.AddIdempotentRepository(name, new RedbIdempotentRepository(scopeFactory, options)); return; } // A named instance: a scope of it per operation, from the same source the redb steps of that storage use. Func openScope = () => ctx.CreateRedbScope(storage); // Opened once at start, so a storage name that resolves to nothing fails the start, not the first message. await using (openScope().ConfigureAwait(false)) { } ctx.AddIdempotentRepository(name, new RedbIdempotentRepository(openScope, options)); })); return context; } // ── helpers ────────────────────────────────────────────────────── private static readonly MethodInfo SyncHelperDef = typeof(RedbContextDslExtensions) .GetMethod(nameof(SyncHelper), BindingFlags.NonPublic | BindingFlags.Static)!; private static Task SyncHelper(IRedbService redb) where TProps : class => redb.SyncSchemeAsync(); /// A lifecycle listener wrapping one startup action (fail-fast by the hook's contract). private sealed class StartupAction(Func action) : IRouteLifecycleListener { public Task OnContextStarting(IRouteContext context, CancellationToken ct) => action(context); } } Path: redb-route/redb.Route.Core/Extensions/RedbQueryOutput.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.Core/Extensions/RedbQueryOutput.cs ---- namespace redb.Route.RedbCore.Extensions; /// What RedbQuery puts into its target — one terminal operation of the redb query. public enum RedbQueryOutput { /// ToListAsync: the list of RedbObject<TProps> (the default). List, /// FirstOrDefaultAsync: the first object in the query's order, or null when nothing matched. First, /// CountAsync: the number of matches, an . Count, /// AnyAsync: whether anything matched, a . Any, } Path: redb-route/redb.Route.Core/Extensions/RedbRouteExtensions.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.Core/Extensions/RedbRouteExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Route.Abstractions; using redb.Route.Controllers; namespace redb.Route.RedbCore.Extensions; /// /// Extension methods for accessing from route pipeline. /// Provides typed integration points: Process, SetBody, SetHeader with (IRedbService, IExchange). /// When exchange has a DI scope (), a scoped /// is resolved per exchange; otherwise falls back to the route context singleton. /// public static class RedbRouteExtensions { // ── Context helpers ────────────────────────────────────────────── private const string RegistryPrefix = "redb:"; private const string FactoryPrefix = "redb-factory:"; private const string ScopeCachePrefix = "__redb_scope:"; // Reserved cache key for the DEFAULT (unnamed) per-exchange redb scope. The '\0' suffix // can never collide with a named instance ("__redb_scope:{name}") and is still disposed by // Exchange.ReleaseScopes() (which drops every key starting with ScopeCachePrefix). private const string DefaultScopeKey = ScopeCachePrefix + "\0"; /// /// Resolves the default from context service locator → DI fallback. /// public static IRedbService GetRedbService(this IRouteContext context) { ArgumentNullException.ThrowIfNull(context); return context.GetService() ?? context.GetServiceProvider()?.GetService(typeof(IRedbService)) as IRedbService ?? throw new InvalidOperationException( "IRedbService is not registered. Call services.AddRedb() / services.AddRedbPro(), " + "or register a named instance via context.RegisterRedbService(name, instance)."); } /// /// Resolves a named . /// /// Scoping model for named instances: /// Named IRedbService is stateful (like EF DbContext) and must NOT be shared across /// concurrent exchanges. When is provided, a per-exchange /// scoped instance is created from the registered /// (placed in registry by TsakContextManager under "redb-factory:{name}" key). /// The scope is cached in and auto-disposed when /// the exchange completes (). /// /// /// Resolution priority: /// /// Cached scope in exchange.Properties (same exchange, second call) /// New scope from factory in registry (first call with exchange) /// New scope opened from the registered instance through (first call with exchange, /// no factory: a host outside Tsak whose instance was built through a container) /// Singleton fallback from registry (no exchange, or an instance built without a container) /// /// /// Falls back to the default (unnamed) service if the name is null or empty. /// /// Route context. /// /// Registry name (e.g. "my-db" or "#my-db" — leading # is stripped automatically). /// /// /// Current exchange for per-exchange scoping. When provided, the resolved service is /// tied to the exchange lifecycle (thread-safe). Pass null for singleton fallback /// (seed/diagnostics only — not safe under concurrency). Parallel code without an exchange opens a scope of its /// own per call with . /// public static IRedbService GetRedbService(this IRouteContext context, string name, IExchange? exchange = null) { ArgumentNullException.ThrowIfNull(context); // Even when no name is supplied, prefer the per-exchange ServiceProvider so the // resolved IRedbService is tied to the exchange's DI scope (per-request scope) and // not captured as a captive singleton from the root provider — which would force all // concurrent requests through a single NpgsqlConnection and surface as // "A command is already in progress" / "connection is already in state 'Copy'". if (string.IsNullOrEmpty(name)) return ResolveScopedRedb(context, exchange); var cleanName = name.TrimStart('#'); // When exchange is provided, prefer per-exchange scoped instance (thread-safe). if (exchange != null) { var cacheKey = ScopeCachePrefix + cleanName; // 1. Already cached in this exchange? if (exchange.Properties.TryGetValue(cacheKey, out var cached)) { if (cached is ExchangeRedbScope own) return own.Service; if (cached is IServiceScope cachedScope) return cachedScope.ServiceProvider.GetRequiredService(); } // 2. Factory registered? Create a new scope and cache it. if (context.GetFromRegistry(FactoryPrefix + cleanName) is { } factory) { var scope = factory.CreateScope(); exchange.Properties[cacheKey] = scope; return scope.ServiceProvider.GetRequiredService(); } // 3. No published factory: a host outside Tsak registered the instance itself. An instance built // through a container opens a scope of the same database for this exchange, as the factory does. if (context.GetFromRegistry(RegistryPrefix + cleanName) is { CanCreateScope: true } instance) { var redbScope = instance.CreateScope(); exchange.Properties[cacheKey] = new ExchangeRedbScope(redbScope); // disposed by Exchange.ReleaseScopes() return redbScope.Service; } } // 4. Singleton fallback: no exchange (start-up code), or an instance built without a container. return context.GetFromRegistry(RegistryPrefix + cleanName) ?? throw new InvalidOperationException( $"Named IRedbService '{name}' is not found in context registry. " + "Register it via context.RegisterRedbService(name, instance) or configure in Redb section."); } /// /// Registers a named in the context registry. /// Business routes use this to provide their own redb instance (different DB, provider, etc.). /// /// Route context. /// Unique name for this redb instance (e.g. "orders-db"). /// The redb service instance to register. public static IRouteContext RegisterRedbService(this IRouteContext context, string name, IRedbService redbService) { ArgumentNullException.ThrowIfNull(context); ArgumentException.ThrowIfNullOrEmpty(name); ArgumentNullException.ThrowIfNull(redbService); context.AddToRegistry(RegistryPrefix + name.TrimStart('#'), redbService); return context; } /// Whether a default resolves on , as finds it. internal static bool IsDefaultRedbRegistered(IRouteContext context) => context.GetService() is not null || context.GetServiceProvider()?.GetService(typeof(IRedbService)) is IRedbService; /// Whether the named instance is published on : a scope factory (Tsak) or a registered instance. internal static bool IsNamedRedbRegistered(IRouteContext context, string name) { var cleanName = name.TrimStart('#'); return context.GetFromRegistry(FactoryPrefix + cleanName) is not null || context.GetFromRegistry(RegistryPrefix + cleanName) is not null; } /// /// Opens a scope with its own , for code that runs without an exchange and may run in /// parallel: an observer, a background job, a store call made outside a route step. Every call opens a new scope, /// so parallel callers never share a connection. The caller owns the scope and disposes it (await using). /// /// Named ( set): the scope factory a host published for the name (Tsak does, one /// per named instance), otherwise a scope opened from the instance registered with /// (). Default (no name): a scope opened /// from the service registered on the context, otherwise a scope of the context's service provider. /// /// /// A service built without a DI container has no scope to open: the call throws /// instead of handing out the shared instance, which is exactly the /// contention this method exists to avoid. Single-threaded start-up code (scheme sync, seeding) keeps using /// without an exchange. /// /// /// A scope opened inside an ambient transaction takes part in it. Work that must survive the route's rollback /// (an audit record, a budget counter) opens its scope under a suppressing TransactionScope. /// /// /// Route context. /// Registry name of a named instance (a leading # is stripped); null or empty for the default service. public static RedbScope CreateRedbScope(this IRouteContext context, string? name = null) { ArgumentNullException.ThrowIfNull(context); if (string.IsNullOrEmpty(name)) return CreateDefaultRedbScope(context); var cleanName = name.TrimStart('#'); if (context.GetFromRegistry(FactoryPrefix + cleanName) is { } factory) return OpenRedbScope(factory, $"named IRedbService '{cleanName}'"); var instance = context.GetFromRegistry(RegistryPrefix + cleanName) ?? throw new InvalidOperationException( $"Named IRedbService '{name}' is not found in context registry. " + "Register it via context.RegisterRedbService(name, instance) or configure in Redb section."); if (!instance.CanCreateScope) throw new InvalidOperationException( $"Named IRedbService '{cleanName}' was registered as an instance built without a DI container, so no scope " + "can be opened for it. Build the service through a container (services.AddRedb...) before " + "RegisterRedbService, or do the work on an exchange."); return instance.CreateScope(); } private static RedbScope CreateDefaultRedbScope(IRouteContext context) { // The service registered on the context first: it is what code without an exchange gets from GetRedbService(). if (context.GetService() is { } registered) { if (!registered.CanCreateScope) throw new InvalidOperationException( "The IRedbService registered on the route context was built without a DI container, so no scope can " + "be opened for it. Register it through a container (services.AddRedb...), or do the work on an exchange."); return registered.CreateScope(); } if (context.GetServiceProvider()?.GetService() is { } factory) return OpenRedbScope(factory, "the route context's service provider"); throw new InvalidOperationException( "IRedbService is not registered. Call services.AddRedb() / services.AddRedbPro(), " + "or register a named instance via context.RegisterRedbService(name, instance)."); } private static RedbScope OpenRedbScope(IServiceScopeFactory factory, string source) { var scope = factory.CreateScope(); var handedOver = false; try { var service = scope.ServiceProvider.GetService() ?? throw new InvalidOperationException($"The scope factory of {source} does not provide IRedbService."); var redbScope = new RedbScope(service, scope); handedOver = true; return redbScope; } finally { // A failed resolution must not strand the scope it opened. if (!handedOver) scope.Dispose(); } } /// /// Resolves a PER-REQUEST scoped for a controller — its own DB /// connection, tied to the controller's current . /// /// Use this in controllers instead of Context.GetRedbService(): the latter resolves a /// captive singleton (one shared, non-thread-safe connection) from the root provider, which under /// concurrent requests surfaces as "A command is already in progress" / "Connection is busy". /// /// public static IRedbService Redb(this RedbController controller) { ArgumentNullException.ThrowIfNull(controller); return controller.Context.GetRedbService(string.Empty, controller.Exchange); } // ── Process with IRedbService ──────────────────────────────────── /// /// Processes the exchange with access to (async). /// Resolves a scoped service per exchange when DI scope is available. /// /// Route definition. /// Async action receiving the redb service and exchange. public static IRouteDefinition ProcessWithRedb( this IRouteDefinition route, Func action) { ArgumentNullException.ThrowIfNull(action); return route.Process(async (exchange, ct) => { var redb = ResolveRedbService(route, exchange); await action(redb, exchange, ct).ConfigureAwait(false); }); } /// /// Processes the exchange with access to (sync). /// Resolves a scoped service per exchange when DI scope is available. /// /// Route definition. /// Action receiving the redb service and exchange. public static IRouteDefinition ProcessWithRedb( this IRouteDefinition route, Action action) { ArgumentNullException.ThrowIfNull(action); return route.Process(exchange => { var redb = ResolveRedbService(route, exchange); action(redb, exchange); }); } // ── SetBody with IRedbService ──────────────────────────────────── /// /// Sets the exchange body using . /// Resolves a scoped service per exchange when DI scope is available. /// /// Route definition. /// Factory that produces the body from service and exchange. public static IRouteDefinition SetBodyFromRedb( this IRouteDefinition route, Func factory) { ArgumentNullException.ThrowIfNull(factory); return route.SetBody(exchange => { var redb = ResolveRedbService(route, exchange); return factory(redb, exchange); }); } // ── SetHeader with IRedbService ────────────────────────────────── /// /// Sets a header using . /// Resolves a scoped service per exchange when DI scope is available. /// /// Route definition. /// Header key. /// Factory that produces the header value from service and exchange. public static IRouteDefinition SetHeaderFromRedb( this IRouteDefinition route, string headerName, Func factory) { ArgumentNullException.ThrowIfNull(factory); return route.SetHeader(headerName, exchange => { var redb = ResolveRedbService(route, exchange); return factory(redb, exchange); }); } // ── Named Process with IRedbService ───────────────────────────── /// /// Processes the exchange with access to a named (async). /// Resolves a per-exchange scoped service when a factory is registered; see /// for scoping details. /// /// Route definition. /// Named redb instance (e.g. "orders-db"). /// Async action receiving the redb service and exchange. public static IRouteDefinition ProcessWithRedb( this IRouteDefinition route, string name, Func action) { ArgumentNullException.ThrowIfNull(action); return route.Process(async (exchange, ct) => { var redb = ResolveNamedRedbService(route, exchange, name); await action(redb, exchange, ct).ConfigureAwait(false); }); } /// /// Processes the exchange with access to a named (sync). /// Resolves a per-exchange scoped service when a factory is registered; see /// for scoping details. /// /// Route definition. /// Named redb instance (e.g. "orders-db"). /// Action receiving the redb service and exchange. public static IRouteDefinition ProcessWithRedb( this IRouteDefinition route, string name, Action action) { ArgumentNullException.ThrowIfNull(action); return route.Process(exchange => { var redb = ResolveNamedRedbService(route, exchange, name); action(redb, exchange); }); } // ── Named SetBody with IRedbService ────────────────────────────── /// /// Sets the exchange body using a named . /// Resolves a per-exchange scoped service when a factory is registered; see /// for scoping details. /// /// Route definition. /// Named redb instance (e.g. "orders-db"). /// Factory that produces the body from service and exchange. public static IRouteDefinition SetBodyFromRedb( this IRouteDefinition route, string name, Func factory) { ArgumentNullException.ThrowIfNull(factory); return route.SetBody(exchange => { var redb = ResolveNamedRedbService(route, exchange, name); return factory(redb, exchange); }); } // ── Named SetHeader with IRedbService ──────────────────────────── /// /// Sets a header using a named . /// Resolves a per-exchange scoped service when a factory is registered; see /// for scoping details. /// /// Route definition. /// Named redb instance (e.g. "orders-db"). /// Header key. /// Factory that produces the header value from service and exchange. public static IRouteDefinition SetHeaderFromRedb( this IRouteDefinition route, string name, string headerName, Func factory) { ArgumentNullException.ThrowIfNull(factory); return route.SetHeader(headerName, exchange => { var redb = ResolveNamedRedbService(route, exchange, name); return factory(redb, exchange); }); } // ── Private helpers ────────────────────────────────────────────── internal static IRedbService ResolveRedbService(IRouteDefinition route, IExchange exchange) { // Fast path: if the exchange's own DI scope already carries redb, return it WITHOUT // resolving the route context. GetContext() walks the Parent chain, so it must not run // when the exchange can already satisfy the request — a scopeless exchange is the only // case that actually needs the context fallback below. if (exchange?.ServiceProvider?.GetService() is { } scoped) return scoped; var context = route.GetContext() ?? throw new InvalidOperationException( "RouteContext is not available. Ensure the route builder has been configured."); return ResolveScopedRedb(context, exchange); } /// /// Resolves the default (unnamed) as a PER-EXCHANGE scoped instance /// (its own DB connection) — never a captive singleton resolved from the root provider. /// /// IRedbService wraps a single, non-thread-safe DB connection (EF-DbContext model). Sharing /// one instance across concurrent exchanges/branches/requests surfaces as /// "A command is already in progress" / "Connection is busy". This resolver guarantees isolation: /// /// use the exchange's own DI scope if it already carries IRedbService; /// otherwise create a dedicated scope from the context provider's /// (redb is registered Scoped, so this yields a fresh /// instance with its own connection), cached on the exchange and disposed by /// Exchange.ReleaseScopes(); /// only when there is NO exchange (seed/diagnostics — single-threaded bootstrap) fall back /// to the unscoped singleton. /// /// /// /// /// A cached on an exchange. The exchange releases every kept under /// a __redb_scope: key when it ends, so the scope is presented as one; is the service /// the scope was opened for. /// private sealed class ExchangeRedbScope : IServiceScope, IAsyncDisposable { private readonly RedbScope _scope; public ExchangeRedbScope(RedbScope scope) => _scope = scope; public IRedbService Service => _scope.Service; public IServiceProvider ServiceProvider => _scope.ServiceProvider ?? NoServices.Instance; public void Dispose() => _scope.Dispose(); public ValueTask DisposeAsync() => _scope.DisposeAsync(); } private sealed class NoServices : IServiceProvider { public static readonly NoServices Instance = new(); public object? GetService(Type serviceType) => null; } private static IRedbService ResolveScopedRedb(IRouteContext context, IExchange? exchange) { if (exchange != null) { // 1. Exchange's own scope already resolves redb. if (exchange.ServiceProvider?.GetService() is { } scoped) return scoped; // 2. Dedicated scope cached from a previous call in this same exchange. if (exchange.Properties.TryGetValue(DefaultScopeKey, out var cached)) { if (cached is ExchangeRedbScope own) return own.Service; if (cached is IServiceScope cachedScope) return cachedScope.ServiceProvider.GetRequiredService(); } // 3. Create a dedicated per-exchange scope from the context provider's scope factory. // The very fact that the unscoped singleton resolves at all proves redb is registered // in this provider — so a fresh scope from it yields a per-exchange instance + own connection. if (context.GetServiceProvider()?.GetService() is { } factory) { var scope = factory.CreateScope(); if (scope.ServiceProvider.GetService() is { } fromScope) { exchange.Properties[DefaultScopeKey] = scope; // disposed by Exchange.ReleaseScopes() return fromScope; } scope.Dispose(); // this provider has no default redb — fall through to the registry/singleton } // 4. No provider scope: a service registered on the context (a host outside Tsak) opens a scope // of the same database for this exchange when it was built through a container. if (context.GetService() is { CanCreateScope: true } registered) { var redbScope = registered.CreateScope(); exchange.Properties[DefaultScopeKey] = new ExchangeRedbScope(redbScope); // disposed by Exchange.ReleaseScopes() return redbScope.Service; } } // No exchange, or no scope can be opened (a service built without a container): the unscoped singleton. // Safe only for single-threaded seed/diagnostics. return context.GetRedbService(); } /// /// Resolves a named IRedbService with per-exchange scoping. /// Uses the exchange to cache/create a scoped instance — see . /// private static IRedbService ResolveNamedRedbService(IRouteDefinition route, IExchange exchange, string name) { var context = route.GetContext() ?? throw new InvalidOperationException( "RouteContext is not available. Ensure the route builder has been configured."); return context.GetRedbService(name, exchange); } } Path: redb-route/redb.Route.Core/Extensions/RedbStorageDslExtensions.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.Core/Extensions/RedbStorageDslExtensions.cs ---- using System.Reflection; using redb.Core; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Core.Serialization; using redb.Route.Abstractions; using redb.Route.Expressions; namespace redb.Route.RedbCore.Extensions; /// /// Declarative storage verbs over — the string/Type-parameterized /// counterparts of the lambda verbs in , designed for the XML /// markup (a lambda cannot live in markup) and equally usable from C#. /// /// Every verb resolves the service per exchange through /// — the same /// scoped model the lambda verbs use — and participates in an ambient redb transaction opened by /// BeginRedbTransaction() like any other redb call on that service. /// /// public static class RedbStorageDslExtensions { // ── Get (typed) ────────────────────────────────────────────────── /// /// Loads a RedbObject<TProps> by id and stores it into the target /// (body by default). /// /// Route definition. /// The props CLR type (markup: resolved via the bean type resolver). /// Expression producing the object id (e.g. ${header.orderId}). /// Materialization depth for nested objects. /// Named ; null/empty — the default one. /// Where the result goes: body (default), header:Name, property:Name. public static IRouteDefinition RedbGet( this IRouteDefinition route, Type propsType, string idExpression, int depth = 10, string? storage = null, string? target = null) { ArgumentNullException.ThrowIfNull(propsType); ArgumentException.ThrowIfNullOrEmpty(idExpression); // Reflection once at definition time, a compiled delegate per message. var load = (Func>)LoadHelperDef .MakeGenericMethod(propsType) .CreateDelegate(typeof(Func>)); var idExpr = new StringExpression(idExpression); var store = ParseTarget(target); return route.Process(async (exchange, ct) => { var redb = Resolve(route, exchange, storage); var id = idExpr.Evaluate(exchange); store(exchange, await load(redb, id, depth)); }); } // ── Get (raw JSON, no CLR type) ────────────────────────────────── /// /// Loads the whole object as raw JSON by id — the in-database materializer /// (get_object_json) serializes the full tree; no props CLR type is needed, so a /// pure-markup module without any assembly can read redb objects. The JSON string goes to /// the target (body by default); a missing object stores null (or throws, per the redb /// configuration's ThrowOnObjectNotFound). /// public static IRouteDefinition RedbGetJson( this IRouteDefinition route, string idExpression, int depth = 10, string? storage = null, string? target = null) { ArgumentException.ThrowIfNullOrEmpty(idExpression); var idExpr = new StringExpression(idExpression); var store = ParseTarget(target); return route.Process(async (exchange, ct) => { var redb = Resolve(route, exchange, storage); var id = idExpr.Evaluate(exchange); store(exchange, await redb.LoadJsonAsync(id, depth)); }); } // ── Save ───────────────────────────────────────────────────────── /// /// Saves the exchange body to redb storage and puts the saved object's id into the exchange /// body's object (the body keeps the saved ; a JSON body is /// materialized first). Body cases: /// /// an — saved as is ( optional); /// a JSON string — deserialized to RedbObject<TProps> via /// (required for this case), then saved. /// /// /// Route definition. /// The props CLR type; required only when the body is JSON. /// Save through the declared unique keys (SaveByUniqueAsync) — /// requires . /// Named ; null/empty — the default one. public static IRouteDefinition RedbSave( this IRouteDefinition route, Type? propsType = null, bool byUnique = false, string? storage = null) { if (byUnique && propsType is null) throw new ArgumentException( "RedbSave(byUnique: true) needs the props type — SaveByUniqueAsync is typed.", nameof(propsType)); var saveByUnique = byUnique ? (Func>)SaveByUniqueHelperDef .MakeGenericMethod(propsType!) .CreateDelegate(typeof(Func>)) : null; return route.Process(async (exchange, ct) => { var redb = Resolve(route, exchange, storage); var obj = MaterializeBody(exchange, propsType); if (saveByUnique is not null) await saveByUnique(redb, obj); else await redb.SaveAsync(obj); exchange.In.Body = obj; // the saved object (with its id) is the step's result }); } // ── Query ──────────────────────────────────────────────────────── /// /// A server-side query: the condition string is translated onto /// redb Where over props, onto redb WhereRedb over /// the base fields of the stored object (Id, ParentId, ValueGuid, /// ValueString, DateCreate…), both by /// (comparisons, AND/OR/NOT, contains/startsWith/endsWith; value-side subtrees — headers, /// functions, date arithmetic — fold per message into constants; the untranslatable refuses /// at route build). The two conditions combine with AND: the storage cannot mix base fields /// and props inside one OR. The result list of RedbObject<TProps> goes to the target. /// Order of application: whereRedb → where → filter spec → orderBy/orderByRedb → skip → take. /// /// Route definition. /// The props CLR type to query. /// Condition over props in the route language; null — no condition. /// Props property path to order by; null — storage order. /// Order direction for or . /// Row limit. /// Rows to skip. /// Registry name of an — the /// full-LINQ escape hatch for what the string cannot say. /// Named ; null/empty — the default one. /// Where the list goes: body (default), header:Name, property:Name. /// Condition over the base fields of the stored object; null — no condition. /// Base field to order by, instead of . /// What goes to the target: the list (default), the first object or /// null, the number of matches, or whether anything matched. public static IRouteDefinition RedbQuery( this IRouteDefinition route, Type propsType, string? where = null, string? orderBy = null, bool descending = false, int? take = null, int? skip = null, string? filter = null, string? storage = null, string? target = null, string? whereRedb = null, string? orderByRedb = null, RedbQueryOutput outputType = RedbQueryOutput.List) { ArgumentNullException.ThrowIfNull(propsType); // Only a list pulls every matching row into memory; one object, a count or a yes/no does not. if (outputType == RedbQueryOutput.List && where is null && whereRedb is null && filter is null && orderBy is null && orderByRedb is null && take is null && skip is null) throw new ArgumentException( "RedbQuery without where/whereRedb/filter/orderBy/orderByRedb/take/skip would be a full unbounded scan — say what you want.", nameof(where)); if (orderBy is not null && orderByRedb is not null) throw new ArgumentException( "RedbQuery orders by one key: orderBy (a props path) or orderByRedb (a base field), not both.", nameof(orderByRedb)); if (outputType == RedbQueryOutput.First && take is not null) throw new ArgumentException( "RedbQuery outputType First reads one object — take does not apply (skip and ordering do).", nameof(take)); if (outputType is RedbQueryOutput.Count or RedbQueryOutput.Any && (orderBy is not null || orderByRedb is not null || take is not null || skip is not null)) throw new ArgumentException( $"RedbQuery outputType {outputType} answers for all the matches — orderBy/orderByRedb/take/skip do not apply.", nameof(outputType)); // Everything translatable is translated NOW — a broken condition fails the route build. var props = Query.QueryRoot.Props(propsType); var wherePlan = where is null ? null : Query.RedbQueryTranslator.TranslateWhere(props, where); var whereRedbPlan = whereRedb is null ? null : Query.RedbQueryTranslator.TranslateWhere(Query.QueryRoot.Base, whereRedb); var orderPlan = orderBy is not null ? Query.RedbQueryTranslator.TranslateOrderBy(props, orderBy) : orderByRedb is not null ? Query.RedbQueryTranslator.TranslateOrderBy(Query.QueryRoot.Base, orderByRedb) : null; var store = ParseTarget(target); var execute = (Func>)QueryHelperDef .MakeGenericMethod(propsType) .CreateDelegate(typeof(Func>), new QueryPlan { Where = wherePlan, WhereRedb = whereRedbPlan, OrderBy = orderPlan, OrderByBase = orderByRedb is not null, Descending = descending, Take = take, Skip = skip, FilterName = filter, Output = outputType, }); return route.Process(async (exchange, ct) => { var redb = Resolve(route, exchange, storage); var context = route.GetContext() ?? throw new InvalidOperationException("RouteContext is not available."); store(exchange, await execute(redb, exchange, context)); }); } // ── Delete ─────────────────────────────────────────────────────── /// /// Deletes an object by id (no props type needed). The body is left untouched; the outcome /// (true — deleted, false — not found) goes into the redbDeleted header. /// public static IRouteDefinition RedbDelete( this IRouteDefinition route, string idExpression, string? storage = null) { ArgumentException.ThrowIfNullOrEmpty(idExpression); var idExpr = new StringExpression(idExpression); return route.Process(async (exchange, ct) => { var redb = Resolve(route, exchange, storage); var id = idExpr.Evaluate(exchange); exchange.In.Headers["redbDeleted"] = await redb.DeleteAsync(id); }); } // ── helpers ────────────────────────────────────────────────────── private static IRedbService Resolve(IRouteDefinition route, IExchange exchange, string? storage) => string.IsNullOrEmpty(storage) ? RedbRouteExtensions.ResolveRedbService(route, exchange) : (route.GetContext() ?? throw new InvalidOperationException( "RouteContext is not available. Ensure the route builder has been configured.")) .GetRedbService(storage, exchange); private static readonly MethodInfo LoadHelperDef = typeof(RedbStorageDslExtensions) .GetMethod(nameof(LoadHelper), BindingFlags.NonPublic | BindingFlags.Static)!; private static async Task LoadHelper(IRedbService redb, long id, int depth) where TProps : class, new() => await redb.LoadAsync(id, depth); private static readonly MethodInfo SaveByUniqueHelperDef = typeof(RedbStorageDslExtensions) .GetMethod(nameof(SaveByUniqueHelper), BindingFlags.NonPublic | BindingFlags.Static)!; private static Task SaveByUniqueHelper(IRedbService redb, IRedbObject obj) where TProps : class, new() => redb.SaveByUniqueAsync((RedbObject)obj); private static readonly MethodInfo QueryHelperDef = typeof(QueryPlan) .GetMethod(nameof(QueryPlan.ExecuteAsync), BindingFlags.NonPublic | BindingFlags.Instance)!; /// /// One query's translated pieces; is the typed island /// every untyped part flows into (closed per step via CreateDelegate over this instance). /// private sealed class QueryPlan { public Func? Where; public Func? WhereRedb; public System.Linq.Expressions.LambdaExpression? OrderBy; public bool OrderByBase; public bool Descending; public int? Take; public int? Skip; public string? FilterName; public RedbQueryOutput Output; private object? _spec; private MethodInfo? _orderMethod; internal async Task ExecuteAsync( IRedbService redb, IExchange exchange, IRouteContext context) where TProps : class, new() { var query = redb.Query(); if (WhereRedb is not null) query = query.WhereRedb((System.Linq.Expressions.Expression>)WhereRedb(exchange)); if (Where is not null) query = query.Where((System.Linq.Expressions.Expression>)Where(exchange)); if (FilterName is not null) { var spec = _spec ??= context.GetFromRegistry(FilterName) ?? throw new InvalidOperationException( $"filter '{FilterName}' is not in the context registry."); if (spec is not Query.IRedbQuerySpec typedSpec) throw new InvalidOperationException( $"filter '{FilterName}' is {spec.GetType().Name}, not IRedbQuerySpec<{typeof(TProps).Name}>."); query = typedSpec.Apply(query); } if (OrderBy is not null) { // The selector is typed Func (Func for a base field) // with the member's own key type (the provider's ordering parser reads a plain // property access, not a boxing Convert), so the generic OrderBy / OrderByRedb is // closed once over that key type. var method = (OrderByBase, Descending) switch { (false, false) => "OrderBy", (false, true) => "OrderByDescending", (true, false) => "OrderByRedb", (true, true) => "OrderByDescendingRedb", }; _orderMethod ??= typeof(redb.Core.Query.IRedbQueryable) .GetMethod(method)! .MakeGenericMethod(OrderBy.ReturnType); query = (redb.Core.Query.IRedbQueryable)_orderMethod.Invoke(query, [OrderBy])!; } if (Skip is { } skip) query = query.Skip(skip); if (Take is { } take) query = query.Take(take); return Output switch { RedbQueryOutput.First => await query.FirstOrDefaultAsync().ConfigureAwait(false), RedbQueryOutput.Count => await query.CountAsync().ConfigureAwait(false), RedbQueryOutput.Any => await query.AnyAsync().ConfigureAwait(false), _ => await query.ToListAsync().ConfigureAwait(false), }; } } private static readonly SystemTextJsonRedbSerializer JsonSerializer = new(); private static IRedbObject MaterializeBody(IExchange exchange, Type? propsType) { var body = exchange.In.Body; switch (body) { case IRedbObject redbObject: return redbObject; case string json when propsType is not null: return JsonSerializer.DeserializeRedbDynamic(json, propsType) ?? throw new InvalidOperationException( $"RedbSave: the body JSON did not deserialize to RedbObject<{propsType.Name}>."); case string: throw new InvalidOperationException( "RedbSave: the body is a JSON string but no props type was given — " + "pass the type (markup: type=\"...\") so the object can be materialized."); default: throw new InvalidOperationException( $"RedbSave: unsupported body {body?.GetType().Name ?? "null"} — " + "expected an IRedbObject or a JSON string."); } } /// /// Parses body / header:Name / property:Name at DEFINITION time, so a /// typo fails the route build rather than the first message. /// private static Action ParseTarget(string? target) { if (string.IsNullOrEmpty(target) || target == "body") return static (exchange, value) => exchange.In.Body = value; if (target.StartsWith("header:", StringComparison.Ordinal) && target.Length > "header:".Length) { var name = target["header:".Length..]; return (exchange, value) => exchange.In.Headers[name] = value; } if (target.StartsWith("property:", StringComparison.Ordinal) && target.Length > "property:".Length) { var name = target["property:".Length..]; return (exchange, value) => exchange.Properties[name] = value; } throw new ArgumentException( $"Unknown target '{target}' — expected 'body', 'header:Name' or 'property:Name'.", nameof(target)); } } Path: redb-route/redb.Route.Core/Extensions/ServiceCollectionExtensions.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.Core/Extensions/ServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Extensions; using redb.Route.RedbCore.Repositories; using redb.Route.RedbCore.Sql; namespace redb.Route.RedbCore; /// /// Extension methods for registering the redb.Route.Core bridge in a DI container. /// public static class ServiceCollectionExtensions { /// /// Registers the redb.Route ↔ redb.Core bridge services. /// Optionally configures as the /// implementation. /// Registers the sql: data source redb () on the route context. /// /// /// services.AddRedbRoute(route => /// { /// route.Services.AddRedbRouteCore(core => /// { /// core.UseIdempotentRepository(o => o.Ttl = TimeSpan.FromDays(7)); /// }); /// route.AddRouteBuilder<MyRoutes>(); /// }); /// /// /// public static IServiceCollection AddRedbRouteCore( this IServiceCollection services, Action? configure = null) { services.TryAddEnumerable(ServiceDescriptor.Singleton()); var builder = new RedbCoreConfigurationBuilder(services); configure?.Invoke(builder); return services; } } /// Registers the sql: data source redb on the context the host starts. internal sealed class RedbSqlDataSourceConfigurator : IRouteContextConfigurator { public void Configure(RouteContext context) => context.AddRedbSqlDataSource(); } /// /// Fluent builder for configuring the redb.Route.Core bridge. /// public sealed class RedbCoreConfigurationBuilder { private readonly IServiceCollection _services; internal RedbCoreConfigurationBuilder(IServiceCollection services) => _services = services; /// The service collection. public IServiceCollection Services => _services; /// /// Registers as . /// Requires IRedbService to be registered (via AddRedb() or AddRedbPro()). /// /// Configure processor name and TTL. public RedbCoreConfigurationBuilder UseIdempotentRepository( Action? configure = null) { var options = new RedbIdempotentOptions(); configure?.Invoke(options); _services.AddSingleton(options); _services.AddSingleton(); return this; } } Path: redb-route/redb.Route.Core/Models/IdempotentEntryProps.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.Core/Models/IdempotentEntryProps.cs ---- using redb.Core.Attributes; namespace redb.Route.RedbCore.Models; /// /// Props model for idempotent message tracking. /// Stored via — works on any redb-supported database /// (PostgreSQL, SQL Server, SQLite) without raw DDL. /// [RedbScheme("Route Idempotent Entry")] public class IdempotentEntryProps { /// Route/processor scope identifier. public string ProcessorName { get; set; } = string.Empty; /// Unique message key (correlation ID, dedup key). public string MessageKey { get; set; } = string.Empty; /// Timestamp when the entry was created (UTC). public DateTimeOffset CreatedAt { get; set; } /// Whether processing has been confirmed (two-phase commit). public bool Confirmed { get; set; } /// /// The id of the claim that holds the key, handed out by Lease and checked by the token Confirm and /// Release. Null for a key taken by Add and for entries written before 4.8.0. /// public string? ClaimId { get; set; } } Path: redb-route/redb.Route.Core/Query/IRedbQuerySpec.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.Core/Query/IRedbQuerySpec.cs ---- using redb.Core.Query; namespace redb.Route.RedbCore.Query; /// /// The full-LINQ escape hatch of RedbQuery/<redbQuery>: a named /// specification the route references by its registry name (filter="#activeOrders") /// when the condition string cannot say what the query needs — joins of conditions the /// translator refuses, provider-specific operators, reusable business filters. Register the /// instance in the context registry (a <bean> does it from markup). /// /// The props type the specification filters. public interface IRedbQuerySpec where TProps : class, new() { /// Applies the specification to the query and returns the narrowed query. IRedbQueryable Apply(IRedbQueryable query); } Path: redb-route/redb.Route.Core/Query/RedbQueryTranslator.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.Core/Query/RedbQueryTranslator.cs ---- using System.Globalization; using System.Reflection; using redb.Core.Models.Contracts; using redb.Core.Query.Mapping; using redb.Core.Utils; using redb.Route.Abstractions; using redb.Route.Expressions.Ast; using SysExpression = System.Linq.Expressions.Expression; namespace redb.Route.RedbCore.Query; /// /// What a condition string is translated against: the props type (where=, redb /// Where) or the base fields of the stored object (whereRedb=, redb /// WhereRedb over ). One translator serves both; the root /// decides which identifiers are storage members and how the refusals name them. /// internal sealed class QueryRoot { private readonly Func _find; private QueryRoot(Type type, string noun, string attribute, bool nested, Func find, IEnumerable candidates) { Type = type; Noun = noun; Attribute = attribute; Nested = nested; _find = find; Candidates = string.Join(", ", candidates); } /// The lambda parameter type. public Type Type { get; } /// How a member is called in a refusal: "props property" or "base field". public string Noun { get; } /// The attribute the condition came from, for the refusal prefix. public string Attribute { get; } /// Whether a member path may walk further (Customer.Name); base fields are flat. public bool Nested { get; } /// The member names, for a refusal that helps fix a typo. public string Candidates { get; } /// The root member by name (case-insensitive), or null when the name is not one. public PropertyInfo? Find(string name) => _find(name); /// The props of : every public instance property, paths nest. public static QueryRoot Props(Type propsType) => new(propsType, "props property", "where", nested: true, name => FindProperty(propsType, name), propsType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(p => p.Name)); private static readonly PropertyInfo[] BaseFields = typeof(IRedbObject) .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => BaseFieldMapper.IsBaseField(p.Name) && p.Name != nameof(IRedbObject.ValueBytes)) .ToArray(); /// /// The base fields of a stored object — exactly the members the core maps to columns /// (). The core maps an unknown name to _id without a /// word, so nothing outside that list may reach it. ValueBytes is left out: a byte /// array has no comparison a condition string could express. /// public static QueryRoot Base { get; } = new(typeof(IRedbObject), "base field", "whereRedb", nested: false, name => BaseFields.FirstOrDefault(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)), BaseFields.Select(p => p.Name)); private static PropertyInfo? FindProperty(Type type, string name) => type.GetProperty(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase); } /// /// Translates a route-language condition string into a server-side redb LINQ predicate — the /// visitor over the engine's ONE expression AST (no parser of its own, §9 of the language /// catalog). The split rule: a subtree that references a storage member of the root (a props /// property, or a base field for whereRedb) is TRANSLATED into the LINQ expression; a /// subtree that does not (headers, body, functions, arithmetic — anything the engine can /// evaluate) is FOLDED per message through the AST's own and /// enters the query as a constant. What is neither — an unknown identifier, arithmetic over a /// storage member, an untranslatable function — refuses LOUDLY at route build, never by /// silently filtering on the client. /// internal static class RedbQueryTranslator { /// The engine's value roots — never storage members (the tokenizer's reserved words). private static readonly HashSet EngineRoots = new(StringComparer.OrdinalIgnoreCase) { "body", "header", "property", "jpath", "xpath", "logical" }; /// The string functions translated onto storage members (everything else stays value-side). private static readonly Dictionary StringFunctions = new(StringComparer.OrdinalIgnoreCase) { ["contains"] = nameof(string.Contains), ["startsWith"] = nameof(string.StartsWith), ["endsWith"] = nameof(string.EndsWith) }; /// /// Builds the per-message predicate factory: parse and translate ONCE at definition time, /// produce an Expression<Func<TRoot, bool>> per message (value-side /// subtrees are evaluated against the exchange right then). /// public static Func TranslateWhere(QueryRoot root, string where) { var ast = Parse(where); var parameter = SysExpression.Parameter(root.Type, "p"); var build = BuildBool(ast, root, parameter, where); return exchange => SysExpression.Lambda(build(exchange), parameter); } /// /// An ordering key selector over a member path — static, nothing per-message in it. Typed /// exactly Func<TRoot, TKey> with the member's own key type: the provider's /// ordering parser reads a property access, not a boxing Convert (an end-to-end finding). /// public static System.Linq.Expressions.LambdaExpression TranslateOrderBy(QueryRoot root, string path) { var parameter = SysExpression.Parameter(root.Type, "p"); if (!TryMember(Parse(path), root, parameter, out var member)) throw new InvalidOperationException( $"orderBy '{path}' is not a {root.Noun} path of {root.Type.Name} — ordering happens server-side " + $"(available: {root.Candidates})."); return SysExpression.Lambda( typeof(Func<,>).MakeGenericType(root.Type, member!.Type), member, parameter); } // ── the visitor ────────────────────────────────────────────────── private static AstNode Parse(string expression) { var tokens = new Tokenizer(expression).GetAllTokens(); return new Parser(tokens).Parse(); } /// A subtree that must come out boolean. private static Func BuildBool( AstNode node, QueryRoot root, System.Linq.Expressions.ParameterExpression parameter, string source) { switch (node) { case BinaryOperationNode { Operator: "AND" or "OR" } logical: { var left = BuildBool(logical.Left, root, parameter, source); var right = BuildBool(logical.Right, root, parameter, source); return logical.Operator == "AND" ? x => SysExpression.AndAlso(left(x), right(x)) : x => SysExpression.OrElse(left(x), right(x)); } case UnaryOperationNode { Operator: "NOT" or "!" } not: { var operand = BuildBool(not.Operand, root, parameter, source); return x => SysExpression.Not(operand(x)); } case BinaryOperationNode { Operator: "==" or "!=" or ">" or "<" or ">=" or "<=" } comparison: return BuildComparison(comparison, root, parameter, source); case InOperationNode membership: return BuildMembership(membership, root, parameter, source); case FunctionCallNode function when StringFunctions.ContainsKey(function.Name): return BuildStringFunction(function, root, parameter, source); default: { // A bool member standing alone — or a value-only subtree, folded to a // per-message boolean constant (a header gate inside AND is legitimate). if (TryMember(node, root, parameter, out var member)) { if (member!.Type != typeof(bool)) throw Refuse(root, source, $"'{node}' is a {member.Type.Name} {root.Noun} where a condition is expected" + (member.Type == typeof(bool?) ? $" (compare it: {node} == true)" : "")); return _ => member; } if (ContainsMemberRef(node, root)) throw Refuse(root, source, $"'{node}' mixes {root.Noun} members into an operation the storage cannot run " + "server-side (arithmetic and unknown functions stay on the value side, or use filter=\"#spec\")"); ValidateValueSide(node, root, source); return x => SysExpression.Constant( System.Convert.ToBoolean(node.Evaluate(x) ?? false, CultureInfo.InvariantCulture)); } } } private static Func BuildComparison( BinaryOperationNode comparison, QueryRoot root, System.Linq.Expressions.ParameterExpression parameter, string source) { var leftIsMember = TryMember(comparison.Left, root, parameter, out var leftMember); var rightIsMember = TryMember(comparison.Right, root, parameter, out var rightMember); if (leftIsMember && rightIsMember) return _ => MakeBinary(comparison.Operator, leftMember!, rightMember!); if (!leftIsMember && !rightIsMember) { // No member reference at all — a per-message gate; still refuse when a member // is buried inside arithmetic (that is the silent-mistranslation trap). if (ContainsMemberRef(comparison, root)) throw Refuse(root, source, $"'{comparison}' uses a {root.Noun} inside an expression the storage " + "cannot run server-side (move it to a plain comparison, or use filter=\"#spec\")"); ValidateValueSide(comparison, root, source); return x => SysExpression.Constant( System.Convert.ToBoolean(comparison.Evaluate(x) ?? false, CultureInfo.InvariantCulture)); } var (member, valueNode, op) = leftIsMember ? (leftMember!, comparison.Right, comparison.Operator) : (rightMember!, comparison.Left, Mirror(comparison.Operator)); if (member.Type == typeof(string) && op is ">" or "<" or ">=" or "<=") throw Refuse(root, source, $"ordering comparison '{op}' on a string {root.Noun} is not supported " + "(compare equality, or use filter=\"#spec\")"); if (ContainsMemberRef(valueNode, root)) throw Refuse(root, source, $"'{valueNode}' mixes a {root.Noun} into the value side of a comparison " + $"(compare a {root.Noun} against a value, or use filter=\"#spec\")"); ValidateValueSide(valueNode, root, source); return x => MakeBinary(op, member, ConstantOfType(valueNode.Evaluate(x), member.Type, root, source)); } /// /// member in list → Enumerable.Contains(T[], member), the shape the storage turns /// into an SQL IN for props and base fields alike. The list is evaluated per message and /// each element converted to the member's type the way a single comparison converts its value. /// An empty (or missing) list is decided here as a constant — nothing found for in, /// everything for not in — so it never reaches the storage as {"$in": []}, whose /// meaning is decided in SQL we do not see from here. /// private static Func BuildMembership( InOperationNode membership, QueryRoot root, System.Linq.Expressions.ParameterExpression parameter, string source) { if (ContainsMemberRef(membership.List, root)) throw Refuse(root, source, $"'{membership}' has a {root.Noun} on the right of in; the right side is a list " + "of values — a collection the message carries (header.codes) or a literal ('a','b')"); if (!TryMember(membership.Value, root, parameter, out var member)) { // No member on either side: a per-message gate, like any other header condition. if (ContainsMemberRef(membership.Value, root)) throw Refuse(root, source, $"'{membership.Value}' uses a {root.Noun} inside an expression the storage " + "cannot run server-side (put the member alone on the left of in, or use filter=\"#spec\")"); ValidateValueSide(membership, root, source); return x => SysExpression.Constant( System.Convert.ToBoolean(membership.Evaluate(x) ?? false, CultureInfo.InvariantCulture)); } ValidateValueSide(membership.List, root, source); var contains = typeof(Enumerable).GetMethods(BindingFlags.Public | BindingFlags.Static) .First(m => m.Name == nameof(Enumerable.Contains) && m.GetParameters().Length == 2) .MakeGenericMethod(member!.Type); return x => { var raw = membership.List.Evaluate(x); var items = raw switch { null => [], string => throw Refuse(root, source, $"'{membership}': the right side of in is a string, and a string " + "is not split into a list — reference a collection or write ('a','b')"), System.Collections.IEnumerable e => e.Cast().ToList(), _ => throw Refuse(root, source, $"'{membership}': the right side of in is a {raw.GetType().Name}, not a collection"), }; if (items.Count == 0) return SysExpression.Constant(membership.Negated); var typed = Array.CreateInstance(member.Type, items.Count); for (var i = 0; i < items.Count; i++) typed.SetValue(ConvertToType(items[i], member.Type, root, source), i); SysExpression test = SysExpression.Call(contains, SysExpression.Constant(typed), member); return membership.Negated ? SysExpression.Not(test) : test; }; } private static Func BuildStringFunction( FunctionCallNode function, QueryRoot root, System.Linq.Expressions.ParameterExpression parameter, string source) { if (function.Arguments.Count != 2) throw Refuse(root, source, $"{function.Name}() takes ({root.Noun}, value)"); if (!TryMember(function.Arguments[0], root, parameter, out var member)) throw Refuse(root, source, $"{function.Name}(): the first argument must be a {root.Noun}"); if (member!.Type != typeof(string)) throw Refuse(root, source, $"{function.Name}(): '{function.Arguments[0]}' is {member.Type.Name}, not string"); if (ContainsMemberRef(function.Arguments[1], root)) throw Refuse(root, source, $"{function.Name}(): the value argument must not reference a {root.Noun}"); ValidateValueSide(function.Arguments[1], root, source); var method = typeof(string).GetMethod(StringFunctions[function.Name], [typeof(string)])!; var valueNode = function.Arguments[1]; return x => SysExpression.Call(member, method, ConstantOfType(valueNode.Evaluate(x), typeof(string), root, source)); } // ── member-path resolution and classification ──────────────────── /// /// Resolves the node as a member chain of the root (Status, Customer.Name; /// ValueGuid for base fields) when its root identifier is a member of the root /// (engine roots never are). Segment lookup is case-insensitive; a wrong segment refuses /// loudly with the candidates. /// private static bool TryMember( AstNode node, QueryRoot root, System.Linq.Expressions.ParameterExpression parameter, out SysExpression? member) { member = null; var segments = new Stack(); var current = node; while (current is PropertyAccessNode access) { segments.Push(access.PropertyName); current = access.Object; } if (current is not IdentifierNode identifier) return false; // The tokenizer keeps dots inside one identifier (`Customer.Name` is a single token). var rootSegments = identifier.Name.Split('.'); if (EngineRoots.Contains(rootSegments[0])) return false; foreach (var segment in rootSegments.Skip(1).Reverse()) segments.Push(segment); var property = root.Find(rootSegments[0]); if (property is null) return false; if (segments.Count > 0 && !root.Nested) throw new InvalidOperationException( $"'{node}': {root.Noun}s are flat — '{property.Name}' has no members to walk into."); SysExpression expr = SysExpression.Property(parameter, property); foreach (var segment in segments) { var next = expr.Type.GetProperty(segment, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase) ?? throw new InvalidOperationException( $"'{segment}' is not a property of {expr.Type.Name} (path '{node}'); available: " + string.Join(", ", expr.Type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Select(p => p.Name))); expr = SysExpression.Property(expr, next); } member = expr; return true; } /// /// A value-side subtree may reference only the engine's roots — a bare identifier that is /// neither a member nor engine is almost certainly a typo, and folding it to null would /// filter silently wrong. Refuse loudly instead. /// private static void ValidateValueSide(AstNode node, QueryRoot root, string source) { switch (node) { case IdentifierNode id when !EngineRoots.Contains(RootOf(id.Name)): throw Refuse(root, source, $"'{id.Name}' is neither a {root.Noun} of {root.Type.Name} (available: " + root.Candidates + ") nor an engine value (header./body/property.)"); case BinaryOperationNode binary: ValidateValueSide(binary.Left, root, source); ValidateValueSide(binary.Right, root, source); break; case UnaryOperationNode unary: ValidateValueSide(unary.Operand, root, source); break; case FunctionCallNode function: foreach (var argument in function.Arguments) ValidateValueSide(argument, root, source); break; case PropertyAccessNode access: ValidateValueSide(Root(access), root, source); break; case InOperationNode membership: ValidateValueSide(membership.Value, root, source); ValidateValueSide(membership.List, root, source); break; case ListLiteralNode list: foreach (var item in list.Items) ValidateValueSide(item, root, source); break; } } // Every node kind that can hold an operand must be walked here. A kind missing from this switch // makes a member inside it invisible, and the expression is then folded into a per-message // constant that silently ignores the member — exactly what happened to 'in' before it was added. private static bool ContainsMemberRef(AstNode node, QueryRoot root) => node switch { IdentifierNode id => !EngineRoots.Contains(RootOf(id.Name)) && root.Find(RootOf(id.Name)) is not null, PropertyAccessNode access => ContainsMemberRef(Root(access), root), BinaryOperationNode binary => ContainsMemberRef(binary.Left, root) || ContainsMemberRef(binary.Right, root), UnaryOperationNode unary => ContainsMemberRef(unary.Operand, root), FunctionCallNode function => function.Arguments.Any(a => ContainsMemberRef(a, root)), InOperationNode membership => ContainsMemberRef(membership.Value, root) || ContainsMemberRef(membership.List, root), ListLiteralNode list => list.Items.Any(i => ContainsMemberRef(i, root)), _ => false, }; private static AstNode Root(PropertyAccessNode access) { AstNode current = access; while (current is PropertyAccessNode a) current = a.Object; return current; } /// The engine resolves dotted identifiers itself (header.x is ONE identifier). private static string RootOf(string identifier) { var dot = identifier.IndexOf('.'); return dot < 0 ? identifier : identifier[..dot]; } // ── expression assembly ────────────────────────────────────────── private static SysExpression MakeBinary(string op, SysExpression left, SysExpression right) => op switch { "==" => SysExpression.Equal(left, right), "!=" => SysExpression.NotEqual(left, right), ">" => SysExpression.GreaterThan(left, right), "<" => SysExpression.LessThan(left, right), ">=" => SysExpression.GreaterThanOrEqual(left, right), "<=" => SysExpression.LessThanOrEqual(left, right), _ => throw new InvalidOperationException($"operator '{op}' is not translatable."), }; private static string Mirror(string op) => op switch { ">" => "<", "<" => ">", ">=" => "<=", "<=" => ">=", _ => op, }; /// /// A folded value as a typed constant of the member's type (invariant conversion). A /// reaches a member the way C# converts /// it implicitly; text parses invariantly. /// private static SysExpression ConstantOfType(object? value, Type targetType, QueryRoot root, string source) => SysExpression.Constant(ConvertToType(value, targetType, root, source), targetType); /// /// The conversion behind , shared with the elements of an in /// list so a list element converts exactly as a single compared value does. /// private static object? ConvertToType(object? value, Type targetType, QueryRoot root, string source) { if (value is null) { if (targetType.IsValueType && Nullable.GetUnderlyingType(targetType) is null) throw Refuse(root, source, $"null compared against a non-nullable {targetType.Name}"); return null; } var underlying = Nullable.GetUnderlyingType(targetType) ?? targetType; object converted = value.GetType() == underlying ? value : underlying switch { _ when underlying == typeof(Guid) => Guid.Parse(value.ToString()!), _ when underlying.IsEnum => Enum.Parse(underlying, value.ToString()!, ignoreCase: true), _ when underlying == typeof(DateTime) => System.Convert.ToDateTime(value, CultureInfo.InvariantCulture), _ when underlying == typeof(DateTimeOffset) => value switch { DateTime dateTime => new DateTimeOffset(dateTime), _ => DateTimeOffset.Parse(value.ToString()!, CultureInfo.InvariantCulture), }, _ => RedbDecimal.ChangeType(value, underlying, CultureInfo.InvariantCulture), }; return converted; } private static InvalidOperationException Refuse(QueryRoot root, string source, string reason) => new($"{root.Attribute} '{source}': {reason}."); } Path: redb-route/redb.Route.Core/README.md 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.Core/README.md ---- # redb.Route.Core Bridge package connecting redb.Route ESB with [redb.Core](https://github.com/redbase-app/redb) props storage. Provides persistent idempotent repository backed by redb.Core and typed access to `IRedbService` from route pipelines. [![NuGet](https://img.shields.io/nuget/v/redb.Route.Core?label=NuGet&color=blue)](https://www.nuget.org/packages/redb.Route.Core) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue)](../../LICENSE) ## Installation ```bash dotnet add package redb.Route.Core ``` ## Usage ### Access IRedbService from Routes ```csharp using redb.Route.RedbCore.Extensions; r.From("direct://save") .ProcessWithRedb(async (redb, exchange, ct) => { var order = (RedbObject)exchange.In.Body!; await redb.SaveAsync(order, ct); }); ``` The service is scoped to the exchange: parallel exchanges never share a connection. `ProcessWithRedb("orders-db", ...)` does the same for a named database registered with `context.RegisterRedbService`. Code that runs **without** an exchange and may run in parallel (an observer, a background job) opens a scope of its own per call: ```csharp await using var scope = context.CreateRedbScope("audit-db"); await scope.Service.SaveAsync(record, ct); ``` **Which service you get where, hosts, transactions: docs/REDB_SERVICE_GUIDE.md.** ### Query storage from a route: props and base fields `RedbQuery` runs a server-side query and puts the list of `RedbObject` into the target. A condition is a string in the route language: members of the stored object, compared against values that come from the message (`header.x`, `body`, `property.x`, functions): - `where` filters on props, the same as redb `Where`; - `whereRedb` filters on the base fields of the stored object, the same as redb `WhereRedb`: `Id`, `ParentId`, `SchemeId`, `OwnerId`, `WhoChangeId`, `Key`, `Name`, `Note`, `Hash`, `ValueLong`, `ValueString`, `ValueGuid`, `ValueBool`, `ValueDouble`, `ValueNumeric`, `ValueDatetime`, `ValueUnique`, `DateCreate`, `DateModify`, `DateBegin`, `DateComplete`. These are columns of the object table and usually indexed, so this is the condition that cuts the most rows before props are read. A member can also be compared with another member, in either order: `where="Price > Cost"`, `where="Cost == Price"`. A member inside arithmetic on the other side (`Price > Cost * 2`) is refused when the route is built; such a condition goes into a specification, `filter="#spec"`. A list of keys is one query, not a loop: `member in list` and `member not in list` become an SQL `IN` in the storage, for props and base fields alike. The list is a collection the message carries or a literal in parentheses: ``` whereRedb="ValueString in header.codes" whereRedb="Id not in (7, 9)" where="Status in ('open','held')" ``` Each element converts to the member's type exactly as a single compared value does, so a header of strings works against an `int` field. An empty or missing list finds nothing (`not in`: keeps everything); it is decided in the route and never reaches the storage as an empty `IN`. The member goes on the left — a member on the right of `in` is refused when the route is built. When both are written they combine with AND, because the storage cannot mix base fields and props inside one OR. `orderBy` orders by a props path and `orderByRedb` by a base field; a query takes one or the other. An unknown member, arithmetic over a member or an unsupported function is refused when the route is built, never filtered in memory. `outputType` picks what goes to the target: | `outputType` | redb call | Target gets | |---|---|---| | `List` (default) | `ToListAsync` | `List>` | | `First` | `FirstOrDefaultAsync` | the first object in the query's order, or `null` | | `Count` | `CountAsync` | `int` | | `Any` | `AnyAsync` | `bool` | `First` takes ordering and `skip`, not `take`. `Count` and `Any` answer for all the matches, so ordering, `take` and `skip` are refused with them. Only `List` needs a condition or a limit: it is the one output that loads every matching row. ```csharp r.From("direct://incident-by-key") .RedbQuery(typeof(Incident), whereRedb: "ValueGuid == header.correlationId", where: "Status != 'closed'", orderByRedb: "DateCreate", descending: true, outputType: RedbQueryOutput.First, target: "property:incident"); ``` The same in Route-XML: ```xml ``` ### Persistent Idempotent Repository Store idempotent message keys in redb.Core instead of in-memory: ```csharp using redb.Route.Core; using redb.Route.RedbCore.Extensions; var context = new RouteContext(); context.AddRedbIdempotentRepository("orders-inbound", ttl: TimeSpan.FromDays(7)); context.AddRoutes(r => { r.From("kafka://orders?groupId=svc&brokers=localhost:9092") .IdempotentConsumer(ex => ex.In.GetHeader("messageId")!, "orders-inbound") .To("direct://process") .EndIdempotentConsumer(); }); ``` The repository opens a scope of its own for every check, so it is safe under parallel consumers; inside `.Transacted()` the key commits with the work. A claim (`Claim`, which the AS2 receiver uses to tell a resend in flight from a done one) counts as abandoned once it is older than the caller's timeout, measured on the clock of the node that asks. Keep that timeout far above the clock skew between your nodes and above the longest lock wait a save can meet; an insert that waits for more than a tenth of it is stamped again before it commits, so a claim never appears already old. To keep the keys in a named redb instance instead of the context's default one, name it with `storage`: ```csharp context.RegisterRedbService("local", localRedb); context.AddRedbIdempotentRepository("orders-inbound", ttl: TimeSpan.FromDays(7), storage: "local"); ``` In `context.xml` the `storage` of the `` block applies to both `` and ``: ```xml ``` A storage name that resolves to no instance fails the context start. ## Key Classes | Class | Description | |-------|-------------| | `RedbRouteExtensions` | `ProcessWithRedb`, `SetBodyFromRedb`, `GetRedbService`, `CreateRedbScope`, `RegisterRedbService` | | `RedbIdempotentRepository` | `IIdempotentRepository` backed by redb.Core props storage | | `RedbIdempotentOptions` | Configuration for repository scheme name and TTL | | `RedbSqlConnectionFactory` | The `sql:` data source `redb` / `redb:`: a `sql:` step on the connection of the exchange's redb service, in its transaction (see the redb.Route.Sql README) | | `IdempotentEntryProps` | redb.Core scheme for idempotent entries | ## Part of [redb.Route](../README.md) — ESB & EIP Framework for .NET Path: redb-route/redb.Route.Core/RedbUniqueKey.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.Core/RedbUniqueKey.cs ---- using System.Security.Cryptography; using System.Text; namespace redb.Route.RedbCore; /// /// Normalizes an application-composed business key so it fits the redb object key column /// _objects._value_unique (440 characters, enforced in C# by the core on every provider) /// and MSSQL's _objects._name (nvarchar(450)). A short key passes through untouched and /// stays readable; an over-long one keeps a readable prefix and gets a SHA-256 tail computed /// over the FULL original, so distinct long keys stay distinct and the mapping is deterministic. /// Shared by and the redb.Route.Llm stores /// (client-supplied keys — conversation ids, message keys — have no length contract). /// public static class RedbUniqueKey { /// The hard cap of _objects._value_unique. public const int MaxLength = 440; /// Deterministic 440-safe form of . public static string Normalize(string raw) { ArgumentNullException.ThrowIfNull(raw); if (raw.Length <= MaxLength) return raw; var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(raw))); var cut = MaxLength - hash.Length - 1; // Never split a surrogate pair: a prefix ending in a lone high surrogate is not // encodable to UTF-8 and the provider would reject the save of the whole row. if (char.IsHighSurrogate(raw[cut - 1])) cut--; return $"{raw[..cut]}#{hash}"; } } Path: redb-route/redb.Route.Core/Repositories/RedbIdempotentOptions.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.Core/Repositories/RedbIdempotentOptions.cs ---- namespace redb.Route.RedbCore.Repositories; /// /// Configuration options for . /// public sealed class RedbIdempotentOptions { /// Scope identifier (route ID or processor name). Allows multiple routes to share one scheme. public string ProcessorName { get; set; } = string.Empty; /// Auto-cleanup: delete entries older than TTL. Null = no cleanup. public TimeSpan? Ttl { get; set; } } Path: redb-route/redb.Route.Core/Repositories/RedbIdempotentRepository.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.Core/Repositories/RedbIdempotentRepository.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Core; using redb.Core.Data; using redb.Core.Exceptions; using redb.Core.Models.Contracts; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.RedbCore.Models; namespace redb.Route.RedbCore.Repositories; /// /// Idempotent repository backed by redb.Core props storage. /// Works on any redb-supported database (PostgreSQL, SQL Server, SQLite) via /// without raw DDL — the scheme is managed automatically /// through . /// /// Opens a fresh scope per operation, so it is safe for concurrent use from multiple route /// threads: from an , or from any source of , such as a named /// redb instance of the route context (context.CreateRedbScope(name)). /// /// /// Identity strategy: each entry stores its composite identity /// "{ProcessorName}:{MessageKey}" twice: in the indexed /// column (readable, O(log n) lookups via IX__objects__name) and in /// , which the core guards with the per-scheme UNIQUE /// index UIX__objects__scheme_unique on every provider. A composite longer than /// 440 characters (client keys can be arbitrary) is normalized to a readable prefix plus a /// SHA-256 tail so it fits both columns on every provider. /// /// /// Cluster safety: concurrent calls for one key race to insert the /// same ValueUnique; the database lets exactly one row through and the loser's typed /// is treated as «already processed» — first wins, /// nobody crashes, at-most-once holds across threads and cluster nodes. Entries created by /// older versions carry no ValueUnique; the Name lookups still find them, so no /// backfill is required. /// /// public sealed class RedbIdempotentRepository : IIdempotentRepository { private readonly Func _openScope; private readonly RedbIdempotentOptions _options; private bool _schemeEnsured; // Higher retry budget: multi-process TFM runs cause heavy cross-table contention on MsSql private const int MaxRetries = 5; private const int BaseDelayMs = 200; /// Creates a repository over the of the scopes opens. public RedbIdempotentRepository(IServiceScopeFactory scopeFactory, RedbIdempotentOptions options) : this(OpenFrom(scopeFactory ?? throw new ArgumentNullException(nameof(scopeFactory))), options) { } /// /// Creates a repository over the redb scopes opens, one per operation; the repository /// disposes each. A named instance of a route context: () => context.CreateRedbScope("orders"). /// public RedbIdempotentRepository(Func openScope, RedbIdempotentOptions options) { ArgumentNullException.ThrowIfNull(openScope); ArgumentNullException.ThrowIfNull(options); _openScope = openScope; _options = options; } private static Func OpenFrom(IServiceScopeFactory scopeFactory) => () => { var scope = scopeFactory.CreateScope(); try { return new RedbScope(scope.ServiceProvider.GetRequiredService(), scope); } catch { scope.Dispose(); throw; } }; /// /// True: inside an ambient transaction redb writes on the transaction's connection (core AmbientConnectionRegistry, /// on every provider — SQLite through a transaction of its own enlisted with the scope), so the key commits and rolls /// back with the work of the .Transacted() block. /// public bool JoinsAmbientTransaction => true; /// /// Composite identity name for a (processor, key) pair. Stored in the indexed /// _objects._name column for fast lookup and in _objects._value_unique /// for the database-enforced uniqueness guarantee. /// private string ComposeName(string key) => ComposeEntryName(_options.ProcessorName, key); /// /// "{processorName}:{key}", normalized by the shared /// helper (440-char cap, SHA-256 tail for over-long composites). Internal so tests can /// compute the stored identity without copying the format. /// internal static string ComposeEntryName(string processorName, string key) => RedbUniqueKey.Normalize($"{processorName}:{key}"); /// public Task Add(string key, CancellationToken ct = default) => Add(key, restampAfter: null, claimId: null, ct); /// /// ; with , an insert that took longer than /// that is stamped again in its own transaction before it commits, so the entry never becomes visible already aged /// by a lock wait (a claim stamped before an insert that then waits would look abandoned the moment it appears). /// is the entry's . /// private async Task Add(string key, TimeSpan? restampAfter, string? claimId, CancellationToken ct) { ArgumentNullException.ThrowIfNull(key); await EnsureSchemeAsync().ConfigureAwait(false); if (_options.Ttl.HasValue) await CleanupExpiredAsync(ct).ConfigureAwait(false); var entryName = ComposeName(key); return await DeadlockRetryHelper.ExecuteWithRetryAsync(async () => { using var scope = _openScope(); var redb = scope.Service; // Indexed lookup by composite name (IX__objects__name). // Defensive Props filter guards against any name collision from foreign schemes // that happen to share the same name format. var existing = await redb.Query() .WhereRedb(x => x.Name == entryName) .ToListAsync() .ConfigureAwait(false); if (existing.Any(e => IsEntryOf(e, key))) return false; var entry = new RedbObject { name = entryName, ValueUnique = entryName, Props = new IdempotentEntryProps { ProcessorName = _options.ProcessorName, MessageKey = key, CreatedAt = DateTimeOffset.UtcNow, Confirmed = false, ClaimId = claimId } }; try { if (restampAfter is not { } threshold) await redb.SaveAsync(entry).ConfigureAwait(false); else await redb.Context.ExecuteAtomicAsync(async () => { await redb.SaveAsync(entry).ConfigureAwait(false); var now = DateTimeOffset.UtcNow; if (now - entry.Props.CreatedAt <= threshold) return; entry.Props.CreatedAt = now; await redb.SaveAsync(entry).ConfigureAwait(false); }, ct).ConfigureAwait(false); } catch (RedbUniqueViolationException) { // Lost the creation race: a concurrent Add committed this key between our // lookup and insert. First wins — the message is already claimed. return false; } return true; }, MaxRetries, BaseDelayMs); } /// public async Task Confirm(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); await EnsureSchemeAsync().ConfigureAwait(false); var entryName = ComposeName(key); await DeadlockRetryHelper.ExecuteWithRetryAsync(async () => { using var scope = _openScope(); var redb = scope.Service; var items = await redb.Query() .WhereRedb(x => x.Name == entryName) .ToListAsync() .ConfigureAwait(false); foreach (var item in items) { if (!IsEntryOf(item, key)) continue; item.Props.Confirmed = true; await redb.SaveAsync(item).ConfigureAwait(false); } }, MaxRetries, BaseDelayMs); } /// public async Task Remove(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); await EnsureSchemeAsync().ConfigureAwait(false); var entryName = ComposeName(key); await DeadlockRetryHelper.ExecuteWithRetryAsync(async () => { using var scope = _openScope(); var redb = scope.Service; var items = await redb.Query() .WhereRedb(x => x.Name == entryName) .ToListAsync() .ConfigureAwait(false); foreach (var item in items) { if (!IsEntryOf(item, key)) continue; await redb.DeleteAsync(item).ConfigureAwait(false); } }, MaxRetries, BaseDelayMs); } /// /// /// Confirms the entry only while its is . The entry is /// read and then saved; a takeover between the two replaces the entry under a new object, and the save of the old one /// then loses on ValueUnique and answers false. When the save lands between the takeover's delete and its insert, /// the old entry comes back confirmed (the default missing-object strategy inserts it again), the takeover's insert /// loses and answers in flight, and the next claim finds the message processed, which it was. /// public async Task Confirm(string key, string? token, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); if (token is null) { await Confirm(key, ct).ConfigureAwait(false); return true; } await EnsureSchemeAsync().ConfigureAwait(false); var entryName = ComposeName(key); return await DeadlockRetryHelper.ExecuteWithRetryAsync(async () => { using var scope = _openScope(); var redb = scope.Service; var held = (await redb.Query() .WhereRedb(x => x.Name == entryName) .ToListAsync() .ConfigureAwait(false)) .FirstOrDefault(e => IsEntryOf(e, key) && e.Props.ClaimId == token); if (held is null) return false; if (held.Props.Confirmed) return true; held.Props.Confirmed = true; try { await redb.SaveAsync(held).ConfigureAwait(false); } catch (RedbUniqueViolationException) { return false; } return true; }, MaxRetries, BaseDelayMs).ConfigureAwait(false); } /// /// /// Deletes the entry only while its is , by its object /// id: an entry a takeover put in its place is another object and stays. /// public async Task Release(string key, string? token, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); if (token is null) { await Remove(key, ct).ConfigureAwait(false); return true; } await EnsureSchemeAsync().ConfigureAwait(false); var entryName = ComposeName(key); return await DeadlockRetryHelper.ExecuteWithRetryAsync(async () => { using var scope = _openScope(); var redb = scope.Service; var held = (await redb.Query() .WhereRedb(x => x.Name == entryName) .ToListAsync() .ConfigureAwait(false)) .FirstOrDefault(e => IsEntryOf(e, key) && e.Props.ClaimId == token); return held is not null && await redb.DeleteAsync(held.Id).ConfigureAwait(false); }, MaxRetries, BaseDelayMs).ConfigureAwait(false); } /// public async Task Contains(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); await EnsureSchemeAsync().ConfigureAwait(false); var entryName = ComposeName(key); return await DeadlockRetryHelper.ExecuteWithRetryAsync(async () => { using var scope = _openScope(); var redb = scope.Service; var items = await redb.Query() .WhereRedb(x => x.Name == entryName) .ToListAsync() .ConfigureAwait(false); return items.Any(e => IsEntryOf(e, key)); }, MaxRetries, BaseDelayMs); } /// public async Task Clear(CancellationToken ct = default) { await EnsureSchemeAsync().ConfigureAwait(false); await DeadlockRetryHelper.ExecuteWithRetryAsync(async () => { using var scope = _openScope(); var redb = scope.Service; // Bulk clear is scope-wide; name-prefix filter not used (would require LIKE), // so we fall back to the Props-level scan here. var items = await redb.Query() .Where(e => e.ProcessorName == _options.ProcessorName) .ToListAsync() .ConfigureAwait(false); if (items.Count > 0) await redb.DeleteAsync((IEnumerable)items).ConfigureAwait(false); }, MaxRetries, BaseDelayMs); } /// public async Task Claim(string key, TimeSpan? abandonedAfter, CancellationToken ct = default) => (await Lease(key, abandonedAfter, ct).ConfigureAwait(false)).Outcome; /// /// /// The token is a new random id kept in the entry's . /// Answered from the entry's and . /// An abandoned claim is taken over by deleting the entry that was read, by its object id, and inserting a new one: a /// caller that read the same stale entry deletes nothing that is new (its delete finds no object, or its insert loses /// on ValueUnique) and answers . Inside an ambient transaction both run /// on the transaction's connection, as does. /// /// The age is against this node's clock, so /// must stay far above the clock skew between nodes. An insert that waits on locks /// for longer than a tenth of is stamped again before it commits: a claim stamped /// before such a wait would look abandoned the moment it became visible, and another node would take it over. /// /// public async Task Lease(string key, TimeSpan? abandonedAfter, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); var token = Guid.NewGuid().ToString("N"); var claim = await ClaimAsync(key, abandonedAfter, token, ct).ConfigureAwait(false); return new IdempotentLease(claim, claim is IdempotentClaim.Claimed or IdempotentClaim.TakenOver ? token : null); } private async Task ClaimAsync(string key, TimeSpan? abandonedAfter, string token, CancellationToken ct) { TimeSpan? restamp = abandonedAfter is { } after ? after / 10 : null; if (await Add(key, restamp, token, ct).ConfigureAwait(false)) return IdempotentClaim.Claimed; var entryName = ComposeName(key); var held = await DeadlockRetryHelper.ExecuteWithRetryAsync(async () => { using var scope = _openScope(); var items = await scope.Service.Query() .WhereRedb(x => x.Name == entryName) .ToListAsync() .ConfigureAwait(false); return items.FirstOrDefault(e => IsEntryOf(e, key)); }, MaxRetries, BaseDelayMs).ConfigureAwait(false); if (held is null) // Released between the insert and the read: claim it again. return await Add(key, restamp, token, ct).ConfigureAwait(false) ? IdempotentClaim.Claimed : IdempotentClaim.InFlight; if (held.Props.Confirmed) return IdempotentClaim.Confirmed; if (abandonedAfter is not { } age || DateTimeOffset.UtcNow - held.Props.CreatedAt <= age) return IdempotentClaim.InFlight; // Read again right before the delete: a holder that confirmed meanwhile, or another caller that already took the // claim over, keeps its entry. The delete by id cannot itself test the flag, so a confirmation landing between // this read and the delete is still lost; that window is the at-least-once of a takeover. var heldId = held.Id; var outcome = await DeadlockRetryHelper.ExecuteWithRetryAsync(async () => { using var scope = _openScope(); var current = await scope.Service.Query() .WhereRedb(x => x.Id == heldId) .ToListAsync() .ConfigureAwait(false); if (current.Count != 1 || current[0].Props is not { } now || now.CreatedAt != held.Props.CreatedAt) return IdempotentClaim.InFlight; if (now.Confirmed) return IdempotentClaim.Confirmed; return await scope.Service.DeleteAsync(heldId).ConfigureAwait(false) ? IdempotentClaim.TakenOver : IdempotentClaim.InFlight; }, MaxRetries, BaseDelayMs).ConfigureAwait(false); if (outcome != IdempotentClaim.TakenOver) return outcome; // A new entry: ValueUnique lets one caller through. return await Add(key, restamp, token, ct).ConfigureAwait(false) ? IdempotentClaim.TakenOver : IdempotentClaim.InFlight; } /// /// Whether is the entry of for this processor. An entry another caller is /// deleting at that moment can come back without its props: it is passed over, as one already gone. /// private bool IsEntryOf(RedbObject entry, string key) => entry.Props is { } props && props.ProcessorName == _options.ProcessorName && props.MessageKey == key; private async Task EnsureSchemeAsync() { if (_schemeEnsured) return; using var scope = _openScope(); var redb = scope.Service; await redb.SyncSchemeAsync().ConfigureAwait(false); _schemeEnsured = true; } private async Task CleanupExpiredAsync(CancellationToken ct) { if (_options.Ttl is not { } ttl) return; var cutoff = DateTimeOffset.UtcNow.Subtract(ttl); await DeadlockRetryHelper.ExecuteWithRetryAsync(async () => { using var scope = _openScope(); var redb = scope.Service; var expired = await redb.Query() .Where(e => e.ProcessorName == _options.ProcessorName && e.CreatedAt < cutoff) .ToListAsync() .ConfigureAwait(false); if (expired.Count > 0) await redb.DeleteAsync((IEnumerable)expired).ConfigureAwait(false); }, MaxRetries, BaseDelayMs); } } Path: redb-route/redb.Route.Core/Sql/RedbSqlConnectionFactory.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.Core/Sql/RedbSqlConnectionFactory.cs ---- using System.Data.Common; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using redb.Route.Sql.Connection; namespace redb.Route.RedbCore.Sql; /// /// The sql: data source redb: a step with dataSource=redb (the default redb service) or /// dataSource=redb:orders (the named one) runs its statement on the connection that service works on for the /// exchange, in the transaction redb's own commands run in. Inside .Transacted() the statement and every redb step /// of the block commit or roll back together, on one connection, without a distributed transaction; outside a /// transaction the statement runs in autocommit. /// /// The service is the one the redb steps of the same exchange get (), /// borrowed through IRedbConnection.LeaseAsync for the time of the statement and given back right after it. /// /// public sealed class RedbSqlConnectionFactory : ISqlConnectionFactory { /// The data source name the factory is registered under. public const string DataSourceName = "redb"; private readonly IRouteContext _context; private readonly string? _name; /// The factory of the default redb service on . /// The route context whose redb services lend their connection. public RedbSqlConnectionFactory(IRouteContext context) : this(context, name: null) { } private RedbSqlConnectionFactory(IRouteContext context, string? name) { _context = context ?? throw new ArgumentNullException(nameof(context)); _name = name; } /// public bool LendsConnection => true; /// Refused: the data source lends redb's connection per exchange and opens none of its own. public Task CreateConnectionAsync(bool readOnly = false, CancellationToken ct = default) => throw new NotSupportedException( $"dataSource={Describe(_name)} lends the connection of a redb service to one sql: step of an exchange and " + "opens no connection of its own. Use it on a sql: producer; a component that keeps a connection outside an " + "exchange (the polling sql: consumer, the SQL idempotent or claim-check repository) needs a data source with " + "a connection string."); /// /// The factory of the default service (no qualifier) or the named one (redb:orders). Throws when the service /// is not registered on the context, so a route with a missing or misspelled name fails at start. /// public ISqlConnectionFactory ForQualifier(string? qualifier) { var name = string.IsNullOrEmpty(qualifier) ? null : qualifier.TrimStart('#'); if (name is null) { if (!RedbRouteExtensions.IsDefaultRedbRegistered(_context)) throw new InvalidOperationException( "dataSource=redb runs the statement on the connection of the default redb service, and no IRedbService " + "is registered. Call services.AddRedb() / services.AddRedbPro(), or name a registered instance with " + "dataSource=redb:."); return _name is null ? this : new RedbSqlConnectionFactory(_context, null); } if (!RedbRouteExtensions.IsNamedRedbRegistered(_context, name)) throw new InvalidOperationException( $"dataSource=redb:{name} runs the statement on the connection of the redb service '{name}', and no such " + "service is registered on the route context. Register it via context.RegisterRedbService(name, instance) " + "or configure it in the Redb section."); return string.Equals(_name, name, StringComparison.Ordinal) ? this : new RedbSqlConnectionFactory(_context, name); } /// /// Borrows the connection of the exchange's redb service. is ignored: the statement runs /// where redb works, never on a replica. /// public async Task LeaseAsync(IExchange exchange, bool readOnly = false, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(exchange); var redb = _context.GetRedbService(_name ?? string.Empty, exchange); var lease = await redb.Context.Db.LeaseAsync(ct).ConfigureAwait(false); return SqlConnectionLease.Borrowed(lease.Connection, lease.Transaction, lease.DisposeAsync); } private static string Describe(string? name) => name is null ? DataSourceName : DataSourceName + ":" + name; } Path: redb-route/redb.Route.Core/Sql/RedbSqlDataSourceExtensions.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.Core/Sql/RedbSqlDataSourceExtensions.cs ---- using redb.Route.Abstractions; namespace redb.Route.RedbCore.Sql; /// Registers the sql: data source redb () on a route context. public static class RedbSqlDataSourceExtensions { /// /// Registers under redb, so sql: steps take /// dataSource=redb and dataSource=redb:<name>. Does nothing when an object is already registered /// under that name. AddRedbRouteCore calls it for the contexts it configures. /// /// Route context. public static IRouteContext AddRedbSqlDataSource(this IRouteContext context) { ArgumentNullException.ThrowIfNull(context); if (context.GetFromRegistry(RedbSqlConnectionFactory.DataSourceName) is null) context.AddToRegistry(RedbSqlConnectionFactory.DataSourceName, new RedbSqlConnectionFactory(context)); return context; } } Path: redb-route/redb.Route.Core/Transactions/RedbTransactedAction.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.Core/Transactions/RedbTransactedAction.cs ---- using redb.Core.Data; using redb.Route.Abstractions; namespace redb.Route.RedbCore.Transactions; /// /// Adapter that bridges to the route-pipeline /// contract used by TransactedProcessor and /// BeginTransactionProcessor. /// /// Allows an explicit redb-level transaction to be enrolled in the standard /// exchange.Properties["TRANSACT_ACTION"] dictionary so that it commits or rolls back /// alongside other transports (Kafka, Redis, etc.) via the existing pipeline machinery, /// instead of forcing route authors to write try/catch blocks around /// . /// /// /// On the underlying is committed and disposed; /// on it is rolled back and disposed. The instance is single-use. /// /// /// Note: / /// do not accept a , so the token passed to /// is intentionally ignored. /// /// public sealed class RedbTransactedAction : ITransactedAction { private readonly IRedbTransaction _tx; private int _completed; /// Creates a new adapter wrapping the given redb transaction. /// An open redb transaction. Must not be null. /// Thrown when is null. public RedbTransactedAction(IRedbTransaction tx) { _tx = tx ?? throw new ArgumentNullException(nameof(tx)); } /// The wrapped redb transaction (for diagnostics / advanced scenarios). public IRedbTransaction Transaction => _tx; /// public async Task Commit(CancellationToken ct = default) { if (Interlocked.Exchange(ref _completed, 1) != 0) return; try { if (_tx.IsActive) await _tx.CommitAsync().ConfigureAwait(false); } finally { await _tx.DisposeAsync().ConfigureAwait(false); } } /// public async Task Rollback(CancellationToken ct = default) { if (Interlocked.Exchange(ref _completed, 1) != 0) return; try { if (_tx.IsActive) await _tx.RollbackAsync().ConfigureAwait(false); } finally { await _tx.DisposeAsync().ConfigureAwait(false); } } } Path: redb-route/redb.Route.Core/Transactions/RedbTransactedActionExtensions.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.Core/Transactions/RedbTransactedActionExtensions.cs ---- using System.Collections.Concurrent; using redb.Core; using redb.Route.Abstractions; using redb.Route.RedbCore.Extensions; using redb.Route.Transactions; namespace redb.Route.RedbCore.Transactions; /// /// DSL extensions for opening an explicit redb transaction inside a route pipeline /// and enrolling it in the standard commit/rollback flow. /// /// Pairs with the existing .Transacted(...) / .BeginTransaction(...) / /// .CommitTransaction() / .RollbackTransaction() primitives: /// when a RedbTransactedAction is registered in exchange.Properties["TRANSACT_ACTION"], /// it is committed or rolled back together with all other transports at the standard /// boundary. /// /// /// Resolution model: the underlying is resolved through /// , /// so anonymous singletons, named singletons, and named per-exchange scoped factories all work /// (the same model used by ProcessWithRedb(name, ...)). /// /// public static class RedbTransactedActionExtensions { /// /// Property-key prefix used when registering a in /// exchange.Properties["TRANSACT_ACTION"]. The full key is "redb:{name}" /// (or "redb:" for the default unnamed instance). /// public const string ActionKeyPrefix = "redb:"; /// /// Opens an explicit on the default /// and enrolls it as an in the exchange so that the /// surrounding (or imperative Commit/RollbackTransaction) /// will close it. /// [Obsolete("Use .Transacted() instead: under an ambient transaction scope redb enlists automatically " + "via core's AmbientConnectionRegistry, so BeginRedbTransaction is a no-op there and only opens " + "its own transaction when no ambient scope is active.")] public static IRouteDefinition BeginRedbTransaction(this IRouteDefinition route) => BeginRedbTransactionCore(route, name: null); /// /// Opens an explicit on a named /// (per-exchange scoped when a factory is registered, see /// ) /// and enrolls it as an in the exchange. /// /// Route definition. /// Named redb instance (e.g. "orders-db"). [Obsolete("Use .Transacted() instead: under an ambient transaction scope redb enlists automatically " + "via core's AmbientConnectionRegistry, so BeginRedbTransaction is a no-op there and only opens " + "its own transaction when no ambient scope is active.")] public static IRouteDefinition BeginRedbTransaction(this IRouteDefinition route, string name) { ArgumentException.ThrowIfNullOrEmpty(name); return BeginRedbTransactionCore(route, name); } private static IRouteDefinition BeginRedbTransactionCore(IRouteDefinition route, string? name) { ArgumentNullException.ThrowIfNull(route); return route.Process(async (exchange, ct) => { var context = route.GetContext() ?? throw new InvalidOperationException( "RouteContext is not available. Ensure the route builder has been configured."); // Under an ambient TransactionScope (.Transacted()), redb already writes into that // transaction via core's AmbientConnectionRegistry, and redb.Context.BeginTransactionAsync() // is rejected there (core 5dc3741e). Attach without opening: nothing to enroll — the scope // owns commit/rollback. Only the legacy path (no ambient scope, e.g. .Transacted(Suppress) // or no transaction at all) opens its own redb transaction. if (System.Transactions.Transaction.Current is not null) return; // Always resolve a PER-EXCHANGE scoped redb (its own connection) — never a captive // singleton. The unnamed path routes through the scoped resolver (see GetRedbService). var redb = context.GetRedbService(name ?? string.Empty, exchange); var actionKey = ActionKeyPrefix + (name ?? string.Empty); // Idempotency: if a redb tx with this key is already enrolled in this exchange, // do not open a second one (Required-like semantics on the redb side). var actions = GetOrCreateActionsBag(exchange); if (actions.ContainsKey(actionKey)) return; var tx = await redb.Context.BeginTransactionAsync().ConfigureAwait(false); actions[actionKey] = new RedbTransactedAction(tx); }); } private static ConcurrentDictionary GetOrCreateActionsBag(IExchange exchange) { if (exchange.Properties.TryGetValue(TransactedProcessor.TransactActionPropertyKey, out var raw) && raw is ConcurrentDictionary existing) { return existing; } var bag = new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); exchange.Properties[TransactedProcessor.TransactActionPropertyKey] = bag; return bag; } } Path: redb-route/redb.Route.Core/Xml/RedbXmlContributions.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.Core/Xml/RedbXmlContributions.cs ---- using System.Globalization; using System.Xml.Linq; using redb.Route.Abstractions; using redb.Route.Components.Bean; using redb.Route.RedbCore.Extensions; using redb.Route.RedbCore.Transactions; using redb.Route.Xml; namespace redb.Route.RedbCore.Xml; /// /// The redb storage elements of the route markup (contributions of this /// package): <redbGet>, <redbSave>, <redbDelete>, /// <redbQuery> in routes and the <redb> bridge block in /// context.xml. Parse, schema shape and C# printing live together per element. /// internal static class RedbXml { internal static Type? ResolveType(XElement element, string typeName, XmlParseContext context) { var resolver = context.RouteContext.GetService() ?? DefaultBeanTypeResolver.Instance; var type = resolver.Resolve(typeName); if (type is null) context.AddError(element, $"props type '{typeName}' was not found in the loaded assemblies."); return type; } internal static string? OptionalArgs(XElement element, out int? depth, out string? storage, out string? target) { depth = element.Attribute("depth")?.Value is { } d ? int.Parse(d, CultureInfo.InvariantCulture) : null; storage = element.Attribute("storage")?.Value; target = element.Attribute("target")?.Value; return null; } /// The element's text content (CDATA included), null when there is none. internal static string? Text(XElement element) { var text = string.Concat(element.Nodes().OfType().Select(t => t.Value)); return string.IsNullOrWhiteSpace(text) ? null : text.Trim(); } } /// The <redbGet> element: typed load with type=, raw-JSON load without. public sealed class RedbGetXmlContribution : IXmlElementContribution { /// public IReadOnlyList GeneratedUsings => ["redb.Route.RedbCore.Extensions"]; /// public string Name => "redbGet"; /// public XmlElementKind Kind => XmlElementKind.Step; /// public ElementSpec Spec => ElementSpec.Leaf(Name, new AttributeSpec("id", AttributeType.Expression, Required: true), new AttributeSpec("type", AttributeType.TypeName), new AttributeSpec("depth", AttributeType.Int), new AttributeSpec("storage", AttributeType.String), new AttributeSpec("target", AttributeType.String)); /// public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context) { var id = context.RequiredAttr(element, "id"); if (id is null) return current; RedbXml.OptionalArgs(element, out var depth, out var storage, out var target); if (element.Attribute("type")?.Value is { } typeName) { var type = RedbXml.ResolveType(element, typeName, context); return type is null ? current : current.RedbGet(type, id, depth ?? 10, storage, target); } return current.RedbGetJson(id, depth ?? 10, storage, target); } /// public void Print(XElement element, XmlCodeWriter code) { RedbXml.OptionalArgs(element, out var depth, out var storage, out var target); var args = new List(); if (element.Attribute("type")?.Value is { } typeName) args.Add(XmlCodeWriter.TypeRef(typeName)); args.Add(XmlCodeWriter.Str(element.Attribute("id")!.Value)); if (depth is { } d) args.Add($"depth: {d}"); if (storage is not null) args.Add($"storage: {XmlCodeWriter.Str(storage)}"); if (target is not null) args.Add($"target: {XmlCodeWriter.Str(target)}"); code.Verb(element, element.Attribute("type") is null ? "RedbGetJson" : "RedbGet", [.. args]); } } /// The <redbSave> element: saves the body (JSON is materialized via type=). public sealed class RedbSaveXmlContribution : IXmlElementContribution { /// public IReadOnlyList GeneratedUsings => ["redb.Route.RedbCore.Extensions"]; /// public string Name => "redbSave"; /// public XmlElementKind Kind => XmlElementKind.Step; /// public ElementSpec Spec => ElementSpec.Leaf(Name, new AttributeSpec("type", AttributeType.TypeName), new AttributeSpec("byUnique", AttributeType.Bool), new AttributeSpec("storage", AttributeType.String)); /// public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context) { Type? type = null; if (element.Attribute("type")?.Value is { } typeName) { type = RedbXml.ResolveType(element, typeName, context); if (type is null) return current; } var byUnique = context.Convert(element, "byUnique") ?? false; if (byUnique && type is null) { context.AddError(element, "byUnique=\"true\" needs type= — the unique-key save is typed."); return current; } return current.RedbSave(type, byUnique, element.Attribute("storage")?.Value); } /// public void Print(XElement element, XmlCodeWriter code) { var args = new List(); if (element.Attribute("type")?.Value is { } typeName) args.Add(XmlCodeWriter.TypeRef(typeName)); if (element.Attribute("byUnique")?.Value == "true") args.Add("byUnique: true"); if (element.Attribute("storage")?.Value is { } storage) args.Add($"storage: {XmlCodeWriter.Str(storage)}"); code.Verb(element, "RedbSave", [.. args]); } } /// /// The <redbQuery> element: a server-side query — the where string (props) /// and the whereRedb string (base fields of the stored object) ride the engine's ONE /// expression AST into redb LINQ, filter="#spec" is the full-LINQ escape hatch. A /// condition the translator refuses is a positioned load error. /// public sealed class RedbQueryXmlContribution : IXmlElementContribution { /// public IReadOnlyList GeneratedUsings => ["redb.Route.RedbCore.Extensions"]; /// public string Name => "redbQuery"; /// public XmlElementKind Kind => XmlElementKind.Step; /// public ElementSpec Spec => new(Name, Kind, [ new AttributeSpec("type", AttributeType.TypeName, Required: true), new AttributeSpec("where", AttributeType.Expression), new AttributeSpec("orderBy", AttributeType.String), new AttributeSpec("descending", AttributeType.Bool), new AttributeSpec("take", AttributeType.Int), new AttributeSpec("skip", AttributeType.Int), new AttributeSpec("filter", AttributeType.Reference), new AttributeSpec("storage", AttributeType.String), new AttributeSpec("target", AttributeType.String), // The base fields of the stored object (Id, ParentId, ValueGuid, DateCreate...) — redb // WhereRedb / OrderByRedb; ANDed with where=, since one OR cannot mix the two. new AttributeSpec("whereRedb", AttributeType.Expression), new AttributeSpec("orderByRedb", AttributeType.String), // The terminal operation: the list (default), FirstOrDefault, Count or Any. new AttributeSpec("outputType", AttributeType.Enum, EnumValues: ["List", "First", "Count", "Any"]), ], // The condition may live as the element's text instead of the where attribute — a // CDATA block frees it from < escaping. Exactly one of the two forms. [], AllowsTextContent: true); /// public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context) { var typeName = context.RequiredAttr(element, "type"); if (typeName is null) return current; var type = RedbXml.ResolveType(element, typeName, context); if (type is null) return current; var whereAttribute = context.Attr(element, "where"); var whereInline = RedbXml.Text(element); if (whereAttribute is not null && whereInline is not null) { context.AddError(element, " takes the condition either as where= or as the element's text (CDATA welcome), not both."); return current; } var output = context.Convert(element, "outputType"); if (output is null && context.Attr(element, "outputType") is not null) return current; // the malformed value is already a positioned error try { return current.RedbQuery(type, where: whereAttribute ?? whereInline, orderBy: context.Attr(element, "orderBy"), descending: context.Convert(element, "descending") ?? false, take: context.Convert(element, "take"), skip: context.Convert(element, "skip"), filter: context.Attr(element, "filter"), storage: context.Attr(element, "storage"), target: context.Attr(element, "target"), whereRedb: context.Attr(element, "whereRedb"), orderByRedb: context.Attr(element, "orderByRedb"), outputType: output ?? RedbQueryOutput.List); } catch (Exception ex) when (ex is InvalidOperationException or ArgumentException) { // The translator's refusals (and the unbounded-scan guard) become positioned // document errors — collected with the rest, not a crash mid-parse. context.AddError(element, ex.Message); return current; } } /// public void Print(XElement element, XmlCodeWriter code) { var args = new List { XmlCodeWriter.TypeRef(element.Attribute("type")!.Value) }; if ((element.Attribute("where")?.Value ?? RedbXml.Text(element)) is { } where) args.Add($"where: {XmlCodeWriter.Str(where)}"); if (element.Attribute("orderBy")?.Value is { } orderBy) args.Add($"orderBy: {XmlCodeWriter.Str(orderBy)}"); if (element.Attribute("descending")?.Value == "true") args.Add("descending: true"); if (element.Attribute("take")?.Value is { } take) args.Add($"take: {take}"); if (element.Attribute("skip")?.Value is { } skip) args.Add($"skip: {skip}"); if (element.Attribute("filter")?.Value is { } filter) args.Add($"filter: {XmlCodeWriter.Str(filter)}"); if (element.Attribute("storage")?.Value is { } storage) args.Add($"storage: {XmlCodeWriter.Str(storage)}"); if (element.Attribute("target")?.Value is { } target) args.Add($"target: {XmlCodeWriter.Str(target)}"); if (element.Attribute("whereRedb")?.Value is { } whereRedb) args.Add($"whereRedb: {XmlCodeWriter.Str(whereRedb)}"); if (element.Attribute("orderByRedb")?.Value is { } orderByRedb) args.Add($"orderByRedb: {XmlCodeWriter.Str(orderByRedb)}"); if (element.Attribute("outputType")?.Value is { } outputType) args.Add($"outputType: RedbQueryOutput.{Enum.Parse(outputType, ignoreCase: true)}"); code.Verb(element, "RedbQuery", [.. args]); } } /// The <redbDelete> element: deletes by id, no props type needed. public sealed class RedbDeleteXmlContribution : IXmlElementContribution { /// public IReadOnlyList GeneratedUsings => ["redb.Route.RedbCore.Extensions"]; /// public string Name => "redbDelete"; /// public XmlElementKind Kind => XmlElementKind.Step; /// public ElementSpec Spec => ElementSpec.Leaf(Name, new AttributeSpec("id", AttributeType.Expression, Required: true), new AttributeSpec("storage", AttributeType.String)); /// public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context) { var id = context.RequiredAttr(element, "id"); return id is null ? current : current.RedbDelete(id, element.Attribute("storage")?.Value); } /// public void Print(XElement element, XmlCodeWriter code) { var args = new List { XmlCodeWriter.Str(element.Attribute("id")!.Value) }; if (element.Attribute("storage")?.Value is { } storage) args.Add($"storage: {XmlCodeWriter.Str(storage)}"); code.Verb(element, "RedbDelete", [.. args]); } } /// /// The <redb> block of context.xml: scheme synchronization at context /// startup and named idempotent repositories — the context-level face of the bridge. /// public sealed class RedbContextXmlContribution : IXmlContextContribution { /// public string Name => "redb"; /// public XmlElementKind Kind => XmlElementKind.ContextLevel; /// public ElementSpec Spec => new(Name, Kind, [new AttributeSpec("storage", AttributeType.String)], [ ElementSpec.Child("syncScheme", allowsSteps: false, new AttributeSpec("type", AttributeType.TypeName, Required: true)), ElementSpec.Child("idempotentRepository", allowsSteps: false, // Registers a redb idempotent repository under this bare name — the key // and a consumer's idempotentRepository= look up. new AttributeSpec("name", AttributeType.String, Required: true) { Registers = $"{typeof(Repositories.RedbIdempotentRepository).FullName}, {typeof(Repositories.RedbIdempotentRepository).Assembly.GetName().Name}", }, new AttributeSpec("ttl", AttributeType.Duration), new AttributeSpec("processorName", AttributeType.String)), ], AllowsSteps: false); /// public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context) { context.AddError(element, " is a context-level block — put it inside , not in a route."); return current; } /// public void ApplyContext(XElement element, Route.Core.RouteContext context, XmlParseContext parseContext) { var storage = element.Attribute("storage")?.Value; foreach (var child in element.Elements()) { switch (child.Name.LocalName) { case "syncScheme": if (parseContext.RequiredAttr(child, "type") is { } typeName && RedbXml.ResolveType(child, typeName, parseContext) is { } type) context.SyncRedbScheme(type, storage); break; case "idempotentRepository": if (parseContext.RequiredAttr(child, "name") is { } name) context.AddRedbIdempotentRepository(name, parseContext.Convert(child, "ttl"), parseContext.Attr(child, "processorName"), storage); break; default: parseContext.AddError(child, $"unknown child <{child.Name.LocalName}> (valid: , )."); break; } } } } Path: redb-route/redb.Route.Core/redb.Route.Core.csproj 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.Core/redb.Route.Core.csproj ---- redb.Route.Core Bridge package connecting redb.Route ESB framework with redb.Core typed props storage. Provides RedbIdempotentRepository, typed access to IRedbService from route pipelines, and extension methods for redb.Core integration. esb;messaging;redb;core;props;bridge;idempotent README.md