Path: redb-identity/src/redb.Identity.Core/Routes/Processors/ScopeManagementProcessor.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/ScopeManagementProcessor.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Core;
using redb.Core.Models.Entities;
using redb.Core.Services;
using redb.Identity.Contracts.Common;
using redb.Identity.Contracts.Scopes;
using redb.Identity.Core.Models;
using redb.Identity.Core.Module;
using redb.Identity.Core.Services;
using redb.Route.Abstractions;
using redb.Route.RedbCore.Extensions;
using redb.Identity.Contracts.Routes;
namespace redb.Identity.Core.Routes.Processors;
///
/// CRUD management processor for OAuth scopes.
/// Dispatches on the "operation" header: create, read, update, delete, list.
///
internal sealed class ScopeManagementProcessor : IProcessor
{
private readonly IRouteContext _context;
private readonly string? _redbName;
public ScopeManagementProcessor(IRouteContext context, string? redbName = null)
{
_context = context;
_redbName = redbName;
}
public async Task Process(IExchange exchange, CancellationToken ct = default)
{
var redb = _context.GetRedbService(_redbName, exchange);
var operation = exchange.In.GetHeader("operation")
?? throw new InvalidOperationException("Missing 'operation' header");
switch (operation)
{
case "create":
await Create(redb, exchange, ct);
break;
case "read":
await Read(redb, exchange, ct);
break;
case "update":
await Update(redb, exchange, ct);
break;
case "delete":
await Delete(redb, exchange, ct);
break;
case "list":
await List(redb, exchange, ct);
break;
default:
exchange.Out ??= new redb.Route.Core.Message();
exchange.Out.Body = new ErrorResponse { Error = "invalid_operation", ErrorDescription = $"Unknown operation: {operation}" };
break;
}
}
private async Task Create(IRedbService _redb, IExchange exchange, CancellationToken ct)
{
var request = exchange.In.Body as CreateScopeRequest;
// Validate scope name
var err = IdentityProcessorHelpers.ValidateIdentifier(request?.Name, "Name");
if (err != null) { SetError(exchange, "validation_error", err); return; }
err = IdentityProcessorHelpers.ValidateDisplayName(request!.DisplayName, "DisplayName");
if (err != null) { SetError(exchange, "validation_error", err); return; }
err = IdentityProcessorHelpers.ValidateDescription(request.Description, "Description");
if (err != null) { SetError(exchange, "validation_error", err); return; }
// Check uniqueness (one probe of the [RedbUnique] index; the DB still guards the race)
var existing = await _redb.GetByUniqueAsync(p => p.ScopeName, request.Name);
if (existing != null)
{
SetError(exchange, "duplicate", $"Scope '{request.Name}' already exists");
return;
}
var obj = new RedbObject(new ScopeProps
{
ScopeName = request.Name,
Description = request.Description,
Resources = request.Resources
});
obj.Name = request.DisplayName ?? request.Name;
try
{
await _redb.SaveAsync(obj);
}
catch (redb.Core.Exceptions.RedbUniqueViolationException violation)
{
IdentityProcessorHelpers.CountUniqueViolation(_context, exchange, violation);
// Concurrent writer won the race — the [RedbUnique] ScopeName index rejected
// this insert (V4-UNIQUE). Same error as the app-level check above.
SetError(exchange, "duplicate", $"Scope '{request.Name}' already exists");
return;
}
exchange.Out ??= new redb.Route.Core.Message();
exchange.Out.Body = MapToResponse(obj);
exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ScopeCreated;
exchange.Properties["identity-event-data"] = new { Name = request.Name };
}
private async Task Read(IRedbService _redb, IExchange exchange, CancellationToken ct)
{
RedbObject? scope = null;
if (exchange.In.Body is Dictionary dict)
{
if (dict.TryGetValue("id", out var idVal) && idVal != null
&& long.TryParse(idVal.ToString(), out var id) && id > 0)
scope = (await _redb.LoadAsync(id));
else if (dict.TryGetValue("name", out var nVal) && nVal is string name
&& !string.IsNullOrEmpty(name))
scope = await _redb.GetByUniqueAsync(p => p.ScopeName, name);
else
throw new InvalidOperationException("Either 'id' or 'name' required");
}
else
{
throw new InvalidOperationException("Expected body with 'id' or 'name'");
}
if (scope is null)
{
exchange.Out ??= new redb.Route.Core.Message();
exchange.Out.Body = new ErrorResponse { Error = "not_found", ErrorDescription = "Scope not found" };
return;
}
exchange.Out ??= new redb.Route.Core.Message();
exchange.Out.Body = MapToResponse(scope);
}
private async Task Update(IRedbService _redb, IExchange exchange, CancellationToken ct)
{
var request = exchange.In.Body as UpdateScopeRequest;
if (request is null || !long.TryParse(request.Id, out var objectId) || objectId <= 0)
{
SetError(exchange, "validation_error", "Id is required");
return;
}
var scope = (await _redb.LoadAsync(objectId));
if (scope is null)
{
exchange.Out ??= new redb.Route.Core.Message();
exchange.Out.Body = new ErrorResponse { Error = "not_found", ErrorDescription = $"Scope {request.Id} not found" };
return;
}
if (request.DisplayName != null)
{
var err = IdentityProcessorHelpers.ValidateDisplayName(request.DisplayName, "DisplayName");
if (err != null) { SetError(exchange, "validation_error", err); return; }
scope.Name = request.DisplayName;
}
if (request.Description != null)
{
var err = IdentityProcessorHelpers.ValidateDescription(request.Description, "Description");
if (err != null) { SetError(exchange, "validation_error", err); return; }
scope.Props.Description = request.Description;
}
if (request.Resources != null) scope.Props.Resources = request.Resources;
await _redb.SaveAsync(scope);
exchange.Out ??= new redb.Route.Core.Message();
exchange.Out.Body = MapToResponse(scope);
exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ScopeUpdated;
exchange.Properties["identity-event-data"] = new { scope.Props.ScopeName };
}
private async Task Delete(IRedbService _redb, IExchange exchange, CancellationToken ct)
{
if (exchange.In.Body is not Dictionary dict
|| !dict.TryGetValue("id", out var idVal) || idVal == null
|| !long.TryParse(idVal.ToString(), out var id) || id <= 0)
{
SetError(exchange, "validation_error", "Id is required");
return;
}
var bg = _context.GetIdentityServiceOrDefault(exchange);
// Delete only a record of this resource: the typed load answers null for an unknown id
// and for the id of a record of another resource alike.
if (await _redb.LoadAsync(id) is null)
{
SetError(exchange, "not_found", $"Scope {id} not found");
return;
}
await IdentityDeletionHelper.DeleteAsync(_redb, bg, id);
exchange.Out ??= new redb.Route.Core.Message();
exchange.Out.Body = new SuccessResponse();
exchange.Properties["identity-event-type"] = IdentityAuditEventIds.ScopeDeleted;
exchange.Properties["identity-event-data"] = new { Id = id };
}
private async Task List(IRedbService _redb, IExchange exchange, CancellationToken ct)
{
var request = exchange.In.Body as ListRequest ?? new ListRequest();
var query = _redb.Query()
.OrderByRedb(o => o.Id);
var total = await query.CountAsync();
var count = Math.Min(request.Count, 100);
var items = await query
.Skip(request.Offset)
.Take(count)
.ToListAsync();
exchange.Out ??= new redb.Route.Core.Message();
exchange.Out.Body = new PagedResult
{
Items = items.Select(MapToResponse).ToList(),
Total = total,
Offset = request.Offset,
Count = request.Count
};
}
private static void SetError(IExchange exchange, string error, string description)
=> IdentityProcessorHelpers.SetError(exchange, error, description);
private static ScopeResponse MapToResponse(RedbObject scope) => new()
{
Id = scope.Id.ToString(),
Name = scope.Props.ScopeName,
DisplayName = scope.Name,
Description = scope.Props.Description,
Resources = scope.Props.Resources
};
}