Path: redb-identity/src/redb.Identity.Core/Routes/Processors/AuditTargetEnqueueProcessor.cs
Snapshot: redb-identity, 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-identity
Page: https://redbase.app/src/dev-2026-12-06/redb-identity/src/redb.Identity.Core/Routes/Processors/AuditTargetEnqueueProcessor.cs
----
using System.Text.Json;
using Microsoft.Extensions.Logging;
using redb.Core.Query;
using redb.Identity.Contracts.Events;
using redb.Identity.Core.Configuration;
using redb.Identity.Core.Events;
using redb.Identity.Core.Metrics;
using redb.Identity.Core.Module;
using redb.Route.Abstractions;
using redb.Route.RedbCore.Extensions;
using redb.Route.Serialization;
namespace redb.Identity.Core.Routes.Processors;
///
/// Puts an event into the delivery outbox once for every enabled external audit target
/// (Identity:Audit:Targets). Runs in the events route after the audit row and the webhook rows;
/// the delivery worker sends the rows with its own parallelism, leases and retries, so a target that is
/// down or slow neither holds the events route nor loses the event.
///
/// The payload is the event as the targets have always received it (the JSON of
/// ); the worker rebuilds the message from it, headers included,
/// with .
///
///
internal sealed class AuditTargetEnqueueProcessor : IProcessor
{
internal const string Kind = "audit";
private readonly IRouteContext _context;
private readonly string? _redbName;
private readonly IReadOnlyList _targets;
private readonly ILogger _logger;
public AuditTargetEnqueueProcessor(IRouteContext context, string? redbName, IReadOnlyList targets, ILogger logger)
{
_context = context;
_redbName = redbName;
_targets = targets;
_logger = logger;
}
public async Task Process(IExchange exchange, CancellationToken ct = default)
{
if (exchange.In.Body is not IdentityEvent evt || _targets.Count == 0) return;
var payload = AuditTargetMessage.Payload(evt);
var eventId = Guid.TryParse(evt.EventId, out var parsed) ? parsed : Guid.NewGuid();
var entries = _targets
.Select(t => new OutboxEntry(Guid.NewGuid(), eventId, Kind, t.Name, evt.EventType, payload))
.ToList();
try
{
var redb = _context.GetRedbService(_redbName, exchange);
var dialect = _context.GetIdentityService(exchange);
await new IdentityEventStore(redb, dialect).InsertOutboxAsync(entries, ct).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.LogError(ex, "Audit targets: could not enqueue event {EventType} for {Count} target(s); the audit row is written, these deliveries are lost.",
evt.EventType, entries.Count);
_context.GetIdentityServiceOrDefault(exchange)?.DeliveryEnqueueFailures.Add(1,
new KeyValuePair("event_type", evt.EventType),
new KeyValuePair("kind", Kind));
}
}
///
/// The enabled targets of the configuration, checked: every one needs a name of at most 200
/// characters, unique among them, because its outbox rows are addressed by it.
///
internal static IReadOnlyList EnabledTargets(IdentityAuditOptions options)
{
if (!options.Enabled) return [];
var enabled = options.Targets.Where(t => t.Enabled && !string.IsNullOrEmpty(t.Uri)).ToList();
for (var i = 0; i < enabled.Count; i++)
{
var name = enabled[i].Name;
if (string.IsNullOrWhiteSpace(name) || name.Length > 200)
throw new InvalidOperationException(
$"redb.Identity: the audit target with Uri '{Scheme(enabled[i].Uri)}...' needs Identity:Audit:Targets:N:Name " +
"(at most 200 characters): its deliveries are kept in the outbox under that name.");
}
var duplicate = enabled.GroupBy(t => t.Name, StringComparer.Ordinal).FirstOrDefault(g => g.Count() > 1);
if (duplicate is not null)
throw new InvalidOperationException(
$"redb.Identity: two enabled audit targets are named '{duplicate.Key}'. Identity:Audit:Targets:N:Name must be unique.");
return enabled;
}
// Only the scheme of a target URI goes into a message: the rest may carry credentials.
private static string Scheme(string uri)
{
var colon = uri.IndexOf(':');
return colon > 0 ? uri[..colon] : "?";
}
}
///
/// The message an audit target receives, the same as before the outbox: the event as JSON bytes in the
/// body, and headers named for SQL parameter binding (event_id, event_type,
/// timestamp, user_id, client_id, ip_address, user_agent,
/// details) plus event-type.
///
internal static class AuditTargetMessage
{
///
/// The stored payload: the body exactly as the targets' Marshal step used to produce it, and the
/// details header exactly as the events route used to set it. The two encode nested values
/// differently (camelCase in the body, as declared in the header), so both are kept as written.
///
public static string Payload(IdentityEvent evt)
=> JsonSerializer.Serialize(new Stored(
JsonSerializer.Serialize(evt, JsonMessageSerializer.DefaultOptions),
evt.Details is { Count: > 0 } details ? JsonSerializer.Serialize(details) : null));
public static redb.Route.Core.Message Build(string payload)
{
var stored = JsonSerializer.Deserialize(payload)
?? throw new InvalidOperationException("redb.Identity: an audit outbox row holds no event.");
var evt = JsonSerializer.Deserialize(stored.Body, JsonMessageSerializer.DefaultOptions)
?? throw new InvalidOperationException("redb.Identity: an audit outbox row holds no event.");
var message = new redb.Route.Core.Message(System.Text.Encoding.UTF8.GetBytes(stored.Body)) { ContentType = "application/json" };
message.Headers["event-type"] = evt.EventType;
message.Headers["event_id"] = Guid.Parse(evt.EventId);
message.Headers["event_type"] = evt.EventType;
message.Headers["timestamp"] = evt.Timestamp;
message.Headers["user_id"] = evt.UserId ?? (object)DBNull.Value;
message.Headers["client_id"] = evt.ClientId ?? (object)DBNull.Value;
message.Headers["ip_address"] = evt.IpAddress ?? (object)DBNull.Value;
message.Headers["user_agent"] = evt.UserAgent ?? (object)DBNull.Value;
message.Headers["details"] = stored.Details ?? (object)DBNull.Value;
return message;
}
private sealed record Stored(
[property: System.Text.Json.Serialization.JsonPropertyName("body")] string Body,
[property: System.Text.Json.Serialization.JsonPropertyName("details")] string? Details);
}