Path: redb/redb.Core/Configuration/UserConfigurationService.cs
Snapshot: redb, 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
Page: https://redbase.app/src/dev-2026-12-06/redb/redb.Core/Configuration/UserConfigurationService.cs
----
#pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation)
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using redb.Core.Data;
using redb.Core.Models.Configuration;
using redb.Core.Models.Entities;
using redb.Core.Query;
namespace redb.Core.Configuration;
///
/// The user configuration service of every provider: the statements come from the dialect. PostgreSQL and SQLite used
/// to carry copies of this class with the same SQL written into them.
///
public class UserConfigurationService : IUserConfigurationService
{
private readonly IRedbService _redbService;
private readonly IRedbContext _context;
private readonly RedbServiceConfiguration _baseConfiguration;
private readonly ISqlDialect _sql;
// Cache for effective configurations (userId -> (config, expireTime))
private readonly ConcurrentDictionary _configCache = new();
private readonly TimeSpan _cacheTtl = TimeSpan.FromMinutes(5);
private class CachedConfiguration
{
public EffectiveUserConfiguration Configuration { get; set; } = null!;
public DateTime ExpiresAt { get; set; }
}
public UserConfigurationService(
IRedbService redbService,
IRedbContext context,
RedbServiceConfiguration baseConfiguration,
ISqlDialect sql)
{
_redbService = redbService ?? throw new ArgumentNullException(nameof(redbService));
_context = context ?? throw new ArgumentNullException(nameof(context));
_baseConfiguration = baseConfiguration ?? throw new ArgumentNullException(nameof(baseConfiguration));
_sql = sql ?? throw new ArgumentNullException(nameof(sql));
}
///
/// Get effective configuration for user.
///
public async Task GetEffectiveConfigurationAsync(long userId)
{
// Check cache
if (_configCache.TryGetValue(userId, out var cached))
{
if (DateTime.UtcNow < cached.ExpiresAt)
{
return cached.Configuration;
}
// Expired - remove
_configCache.TryRemove(userId, out _);
}
// Build configuration
var effective = await BuildEffectiveConfigurationAsync(userId);
// Cache it
_configCache[userId] = new CachedConfiguration
{
Configuration = effective,
ExpiresAt = DateTime.UtcNow.Add(_cacheTtl)
};
return effective;
}
///
/// Build effective configuration for user.
///
private async Task BuildEffectiveConfigurationAsync(long userId)
{
var effective = new EffectiveUserConfiguration
{
UserId = userId,
CreatedAt = DateTime.UtcNow
};
// Step 1: Base values from RedbServiceConfiguration
ApplyBaseConfiguration(effective);
// Step 2: For sys (userId=0) return base values (no limits)
if (userId == 0)
{
effective.ListCacheSize = null; // Unlimited
return effective;
}
// Step 3: Load Default User Configuration
var defaultConfig = await GetDefaultConfigurationAsync();
if (defaultConfig != null)
{
ApplyOverride(effective, defaultConfig.Props, "Default User Config", 10);
}
// Step 4: Load the configurations of the user's roles (their id, name and configuration in one statement)
var roles = await _context.QueryAsync(_sql.UsersRoles_SelectRolesByUser(), userId);
var roleConfigs = new List<(RedbObject config, string roleName)>();
foreach (var role in roles)
{
if (role.IdConfiguration == null)
continue;
var roleConfig = await _redbService.LoadAsync(role.IdConfiguration.Value);
if (roleConfig != null)
roleConfigs.Add((roleConfig, role.Name));
}
// Sort by priority and apply
foreach (var (config, roleName) in roleConfigs.OrderBy(rc => rc.config.Props.Priority))
{
ApplyOverride(effective, config.Props, $"Role:{roleName}", 20 + config.Props.Priority);
}
// Step 5: Load personal user configuration
var userConfigId = await _context.ExecuteScalarAsync(_sql.Users_SelectConfigurationId(), userId);
if (userConfigId.HasValue)
{
var userConfig = await _redbService.LoadAsync(userConfigId.Value);
if (userConfig != null)
{
ApplyOverride(effective, userConfig.Props, "User", 100);
}
}
return effective;
}
///
/// Apply base values from RedbServiceConfiguration.
///
private void ApplyBaseConfiguration(EffectiveUserConfiguration effective)
{
effective.PropsCacheSize = _baseConfiguration.PropsCacheMaxSize;
effective.ListCacheSize = 5000;
effective.PropsCacheTtl = _baseConfiguration.PropsCacheTtl;
effective.ListCacheTtl = _baseConfiguration.ListCacheTtl;
effective.MaxLoadDepth = _baseConfiguration.DefaultLoadDepth;
effective.MaxTreeDepth = _baseConfiguration.DefaultMaxTreeDepth;
effective.AlwaysCheckPermissionsOnLoad = _baseConfiguration.DefaultCheckPermissionsOnLoad;
effective.AlwaysCheckPermissionsOnSave = _baseConfiguration.DefaultCheckPermissionsOnSave;
effective.MaxRequestsPerMinute = null;
effective.MaxBatchSize = 1000;
effective.PropsSaveStrategy = _baseConfiguration.PropsSaveStrategy;
// Sources
effective.Sources.Add(new ConfigurationSource
{
ParameterName = "All",
Source = "RedbServiceConfiguration",
Priority = 0,
Value = "Base values"
});
}
///
/// Apply override from configuration (only non-null values).
///
private void ApplyOverride(
EffectiveUserConfiguration target,
UserConfigurationProps source,
string sourceName,
int priority)
{
// PropsCacheSize is not merged: the props cache has one process-wide limit (obsolete on the props).
if (source.ListCacheSize.HasValue)
{
target.ListCacheSize = source.ListCacheSize.Value;
target.Sources.Add(new ConfigurationSource
{
ParameterName = nameof(source.ListCacheSize),
Source = sourceName,
Priority = priority,
Value = source.ListCacheSize.Value.ToString()
});
}
if (source.PropsCacheTtlMinutes.HasValue)
{
target.PropsCacheTtl = TimeSpan.FromMinutes(source.PropsCacheTtlMinutes.Value);
target.Sources.Add(new ConfigurationSource
{
ParameterName = nameof(source.PropsCacheTtlMinutes),
Source = sourceName,
Priority = priority,
Value = source.PropsCacheTtlMinutes.Value.ToString()
});
}
if (source.ListCacheTtlMinutes.HasValue)
{
target.ListCacheTtl = TimeSpan.FromMinutes(source.ListCacheTtlMinutes.Value);
target.Sources.Add(new ConfigurationSource
{
ParameterName = nameof(source.ListCacheTtlMinutes),
Source = sourceName,
Priority = priority,
Value = source.ListCacheTtlMinutes.Value.ToString()
});
}
if (source.MaxLoadDepth.HasValue)
{
target.MaxLoadDepth = source.MaxLoadDepth.Value;
target.Sources.Add(new ConfigurationSource
{
ParameterName = nameof(source.MaxLoadDepth),
Source = sourceName,
Priority = priority,
Value = source.MaxLoadDepth.Value.ToString()
});
}
if (source.MaxTreeDepth.HasValue)
{
target.MaxTreeDepth = source.MaxTreeDepth.Value;
target.Sources.Add(new ConfigurationSource
{
ParameterName = nameof(source.MaxTreeDepth),
Source = sourceName,
Priority = priority,
Value = source.MaxTreeDepth.Value.ToString()
});
}
if (source.AlwaysCheckPermissionsOnLoad.HasValue)
{
target.AlwaysCheckPermissionsOnLoad = source.AlwaysCheckPermissionsOnLoad.Value;
target.Sources.Add(new ConfigurationSource
{
ParameterName = nameof(source.AlwaysCheckPermissionsOnLoad),
Source = sourceName,
Priority = priority,
Value = source.AlwaysCheckPermissionsOnLoad.Value.ToString()
});
}
if (source.AlwaysCheckPermissionsOnSave.HasValue)
{
target.AlwaysCheckPermissionsOnSave = source.AlwaysCheckPermissionsOnSave.Value;
target.Sources.Add(new ConfigurationSource
{
ParameterName = nameof(source.AlwaysCheckPermissionsOnSave),
Source = sourceName,
Priority = priority,
Value = source.AlwaysCheckPermissionsOnSave.Value.ToString()
});
}
if (source.MaxRequestsPerMinute.HasValue)
{
target.MaxRequestsPerMinute = source.MaxRequestsPerMinute.Value;
target.Sources.Add(new ConfigurationSource
{
ParameterName = nameof(source.MaxRequestsPerMinute),
Source = sourceName,
Priority = priority,
Value = source.MaxRequestsPerMinute.Value.ToString()
});
}
if (source.MaxBatchSize.HasValue)
{
target.MaxBatchSize = source.MaxBatchSize.Value;
target.Sources.Add(new ConfigurationSource
{
ParameterName = nameof(source.MaxBatchSize),
Source = sourceName,
Priority = priority,
Value = source.MaxBatchSize.Value.ToString()
});
}
if (source.PropsSaveStrategy.HasValue)
{
target.PropsSaveStrategy = source.PropsSaveStrategy.Value;
target.Sources.Add(new ConfigurationSource
{
ParameterName = nameof(source.PropsSaveStrategy),
Source = sourceName,
Priority = priority,
Value = source.PropsSaveStrategy.Value.ToString()
});
}
}
///
/// Get default user configuration (ID=-100).
///
public Task?> GetDefaultConfigurationAsync()
{
return _redbService.LoadAsync(DefaultUserConfigurationInitializer.DefaultConfigId);
}
///
/// Set user configuration.
///
public async Task SetUserConfigurationAsync(long userId, long? configId)
{
var exists = await _context.ExecuteScalarAsync(_sql.Users_ExistsById(), userId);
if (!exists.HasValue)
throw new ArgumentException($"User with ID {userId} not found");
await _context.ExecuteAsync(_sql.Users_UpdateConfiguration(), (object?)configId ?? DBNull.Value, userId);
// Invalidate cache
InvalidateCache(userId);
}
///
/// Set role configuration.
///
public async Task SetRoleConfigurationAsync(long roleId, long? configId)
{
var exists = await _context.ExecuteScalarAsync(_sql.Roles_ExistsById(), roleId);
if (!exists.HasValue)
throw new ArgumentException($"Role with ID {roleId} not found");
await _context.ExecuteAsync(_sql.Roles_UpdateConfiguration(), (object?)configId ?? DBNull.Value, roleId);
// Invalidate cache for all users with this role
var users = await _context.QueryAsync(_sql.UsersRoles_SelectUsersByRole(), roleId);
foreach (var user in users)
{
InvalidateCache(user.Id);
}
}
///
/// Create new configuration.
///
public async Task> CreateConfigurationAsync(
string name,
UserConfigurationProps props,
string? description = null)
{
if (string.IsNullOrWhiteSpace(name))
throw new ArgumentException("Configuration name cannot be empty", nameof(name));
if (props == null)
throw new ArgumentNullException(nameof(props));
// Set description
if (!string.IsNullOrWhiteSpace(description))
{
props.Description = description;
}
// Create RedbObject
var config = new RedbObject
{
name = name,
Props = props
};
// Save via IRedbService
await _redbService.SaveAsync(config);
return config;
}
///
/// Invalidate cache for user configuration.
///
public void InvalidateCache(long userId)
{
_configCache.TryRemove(userId, out _);
}
///
/// Clear all configuration cache.
///
public void ClearCache()
{
_configCache.Clear();
}
}