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