Path: redb/redb.Core/Models/Configuration/RedbServiceConfiguration.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/Models/Configuration/RedbServiceConfiguration.cs
----
#pragma warning disable CS0618 // implements or uses the deprecated object permissions and roles (RedbDeprecation)
using System;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Serialization;
using redb.Core.Configuration;
using redb.Core.Caching;
namespace redb.Core.Models.Configuration
{
///
/// RedbService behavior configuration.
///
public class RedbServiceConfiguration
{
// === CONNECTION SETTINGS ===
///
/// PostgreSQL connection string. Required for automatic IRedbContext registration.
/// If not set, user must register IRedbContext manually.
///
public string? ConnectionString { get; set; }
///
/// Cache domain name for isolating scheme caches between different databases.
/// If not set, computed from connection string hash.
/// Use explicit name when connecting to same DB from multiple services.
///
public string? CacheDomain { get; set; }
// === OBJECT DELETION SETTINGS ===
///
/// Strategy for handling ID after object deletion.
///
[JsonConverter(typeof(ObjectIdResetStrategyJsonConverter))]
public ObjectIdResetStrategy IdResetStrategy { get; set; } = ObjectIdResetStrategy.Manual;
///
/// Strategy for handling non-existent objects on UPDATE.
///
[JsonConverter(typeof(MissingObjectStrategyJsonConverter))]
public MissingObjectStrategy MissingObjectStrategy { get; set; } = MissingObjectStrategy.AutoSwitchToInsert;
// === DEFAULT SECURITY SETTINGS ===
///
/// Check permissions by default when loading objects.
///
[Obsolete(RedbDeprecation.PermissionsAndRoles)]
public bool DefaultCheckPermissionsOnLoad { get; set; } = false;
///
/// Check permissions by default when saving objects.
///
[Obsolete(RedbDeprecation.PermissionsAndRoles)]
public bool DefaultCheckPermissionsOnSave { get; set; } = false;
///
/// Check permissions by default when deleting objects.
///
[Obsolete(RedbDeprecation.PermissionsAndRoles)]
public bool DefaultCheckPermissionsOnDelete { get; set; } = true;
///
/// Check permissions by default when executing queries. Read by the free providers only, which filter the loaded
/// page row by row; the queries of redb Pro are not filtered by permissions.
///
[Obsolete(RedbDeprecation.PermissionsAndRoles)]
public bool DefaultCheckPermissionsOnQuery { get; set; } = false;
// === SCHEME SETTINGS ===
///
/// Strictly delete extra fields when synchronizing schemes by default.
///
public bool DefaultStrictDeleteExtra { get; set; } = true;
///
/// Lets the sync delete a structure or change its type for a Props class of the same version as the one the
/// database recorded (). Off by default: such a class adds
/// what it lacks, leaves the rest and warns, so only a class of a higher version takes data away. On in the
/// Development profile, where a programmer changes a type on a local database without raising the version;
/// without it the type would not be migrated and the property would read and write the wrong column.
///
public bool DefaultDestructiveSyncAtEqualVersion { get; set; }
///
/// Automatically synchronize schemes when saving objects.
///
public bool AutoSyncSchemesOnSave { get; set; } = true;
// === OBJECT LOADING SETTINGS ===
///
/// Default depth for loading nested objects.
///
private int _defaultLoadDepth = 10;
public int DefaultLoadDepth
{
get => _defaultLoadDepth;
set
{
if (value < 1)
throw new ArgumentOutOfRangeException(nameof(DefaultLoadDepth), "Minimum 1");
if (value > 100)
throw new ArgumentOutOfRangeException(nameof(DefaultLoadDepth), "Maximum 100");
_defaultLoadDepth = value;
}
}
///
/// Maximum depth for tree structures.
///
private int _defaultMaxTreeDepth = 50;
public int DefaultMaxTreeDepth
{
get => _defaultMaxTreeDepth;
set
{
if (value < 1)
throw new ArgumentOutOfRangeException(nameof(DefaultMaxTreeDepth), "Minimum 1");
if (value > 1000)
throw new ArgumentOutOfRangeException(nameof(DefaultMaxTreeDepth), "Maximum 1000");
_defaultMaxTreeDepth = value;
}
}
///
/// Throw exception if object not found in LoadAsync.
/// false (default) - returns null for a single object and skips it in a batch load
/// true - throws InvalidOperationException
///
public bool ThrowOnObjectNotFound { get; set; } = false;
// === PERFORMANCE SETTINGS ===
///
/// The query planner (Pro, all three providers: PostgreSQL, SQL Server, SQLite). On by default.
///
/// Where it applies, a query is read in the streams form: the objects of the scheme drive the
/// statement and every Props field is a join of its own to its rows of _values, with no
/// GROUP BY. The filter, the ordering and the page, a count, an existence check, aggregates,
/// GroupBy and windows run in that one statement, so a page or a count does not pivot every
/// object of the scheme first.
///
///
/// A field of a nested class is one value row per object and reads through the streams form.
/// The aggregate pivot remains for array element forms (field[], field[0],
/// aggregates over elements), classes inside arrays, the first step of WhereHasAncestor and
/// WhereHasDescendant, and tree-window fields that are arrays. There the planner may narrow
/// the object set before the aggregate. It only ever narrows to a superset: results never
/// change, and a filter it cannot analyse runs as without it.
///
/// Set it to false to read every query in the aggregate pivot form. For one block of code, without touching
/// concurrent requests: using (redb.WithQueryPlanner(false)) { ... } ().
///
public bool EnablePvtPrefilter { get; set; } = true;
private string? _stringCollation;
///
/// Unicode-aware case folding for case-insensitive text operations
/// (ContainsIgnoreCase, StartsWithIgnoreCase, EndsWithIgnoreCase,
/// ToLower, ToUpper).
///
///
/// Why it exists. Case folding is driven by the database's own rules, and those cover
/// only ASCII in two of the three providers. On PostgreSQL created with LC_CTYPE=C,
/// 'Привет' ILIKE '%привет%' is false and lower('Привет') returns the string
/// unchanged. On SQLite this is unconditional: LIKE, lower(), upper() and
/// COLLATE NOCASE are ASCII-only in every database. MSSQL is unaffected because its
/// default collation is case-insensitive for all scripts.
///
///
///
/// What it fixes. Every script whose case mapping is one character to one character:
/// Cyrillic, Greek, Hungarian, Polish, Czech, French, most of German. There is no per-language
/// work; one setting covers all of them.
///
///
///
/// What it does NOT fix, and cannot, because no collation can:
/// foldings that change length (German ß against SS: upper() expands it,
/// pattern matching does not, so the two disagree); language-dependent foldings (Turkish
/// İ does not fold to i, and Turkish wants I→ı where every other
/// locale wants I→i); and insensitivity to diacritics (Müller against
/// muller), which is a different feature and is rejected outright by PostgreSQL for
/// pattern matching. See COLLATION.md.
///
///
///
/// Cost on PostgreSQL. Pro with on pushes an ignore-case
/// search onto _values as (_String COLLATE "und-x-icu") ILIKE, which the stock trigram
/// index over bare _String cannot serve: the search reads every row, silently. It needs an
/// index over the same collation,
/// CREATE INDEX ... USING gin ((_String COLLATE "und-x-icu") gin_trgm_ops); start-up logs a
/// Warning while it is missing. The free forms read no trigram index in either case. On a database
/// with a UTF-8 ctype plain ILIKE already folds every script and the setting is not needed; under
/// ctype C pg_trgm builds no trigram from non-ASCII text, so no index serves a non-ASCII pattern.
///
///
/// Default is null: behaviour is exactly what it was, on every provider.
///
public string? StringCollation
{
get => _stringCollation;
set
{
var normalised = string.IsNullOrWhiteSpace(value) ? null : value.Trim();
if (normalised != null)
Core.Query.CollationNameValidator.Validate(normalised);
_stringCollation = normalised;
}
}
///
/// PostgreSQL Pro with on: build at start-up the trigram index that serves an
/// ignore-case search under ,
/// IX__values__String_pattern_<collation> ON _values USING gin ((_String COLLATE "<collation>") gin_trgm_ops),
/// when the database has none. On a database with ctype C it serves patterns with ASCII letters only: pg_trgm
/// builds no trigram from other text there.
///
///
/// The build is CREATE INDEX CONCURRENTLY on a connection of its own under the schema lock: reads and
/// writes go on, start-up waits for it (minutes on a large _values). An index left INVALID by an
/// interrupted build is dropped and built again. Nothing is built with
/// off or without the right to create an index: start-up logs a Warning and goes on. The free provider and Pro
/// with the planner off read no trigram index; there the option logs one Warning and builds nothing.
///
///
/// Default is false: start-up only checks for the index and warns while it is missing.
///
public bool CreateStringCollationIndex { get; set; } = false;
///
/// V4 (LAZY Л2): lazy references. With the option on, the JSON builders emit a STUB for
/// every reference whose structure carries the `virtual` marker (`_structures._lazy`),
/// regardless of depth; first access to the stub's Props loads exactly that object.
/// The option travels to the builders as a session flag of the context's connection
/// (PostgreSQL GUC `redb.lazy_refs`, MSSQL SESSION_CONTEXT, a connection flag of the
/// SQLite native extension) - no builder signature changes (plan decision 5).
/// Per-query override: `WithLazyReferences(bool)`; with the Pro packages the override has no
/// effect and this global option applies. Default is false: behaviour is exactly what it was.
///
public bool EnableLazyReferences { get; set; } = false;
///
/// V4 (review): what the Props getter of an UNLOADED reference does. Blocking
/// (default) loads the object synchronously - a hidden database round trip that waits for
/// the query on the calling thread (the load itself runs on the thread pool, so a host with a
/// SynchronizationContext does not deadlock). Throw refuses with
/// and names the explicit way
/// (LoadPropsAsync, LoadReferencesAsync, a larger depth): for Blazor WebAssembly,
/// which cannot block at all, and for UI hosts where a synchronous query on property access
/// is a defect. The async APIs work in both modes.
///
public LazyReferenceAccessMode LazyReferenceAccess { get; set; } = LazyReferenceAccessMode.Blocking;
///
/// What a lazy load - the Props of a reference stub, RedbListItem.Object - does when no live redb scope reads
/// it. A data object owns no connection: the load runs on the scope of whoever reads it (owner decision 2026-09-15).
/// Refuse (default) throws ; FreshScope opens a
/// scope and a pooled connection per such load.
///
public LazyLoadWithoutScopeMode LazyLoadWithoutScope { get; set; } = LazyLoadWithoutScopeMode.Refuse;
///
/// Apply the versioned SQL module (functions and, from V4, schema upgrades) automatically at
/// start-up when the database reports a different module version than this build requires.
///
///
/// true (default) keeps the long-standing behaviour: pull, restart, the database
/// follows. When the connected role is not allowed to — the DBA revoked owner rights after the
/// initial installation — start-up stops with
/// naming the script for the DBA, rather than a raw driver error.
///
///
///
/// false is for installations where the policy is "only the DBA changes the schema":
/// start-up then checks the version and stops with the same exception without trying.
/// SQLite ignores this setting — the database file belongs to the process and there is no
/// DBA to defer to.
///
///
public bool AutoApplyDatabaseUpgrades { get; set; } = true;
///
/// How long start-up waits for the schema lock that another process holds. Processes starting against one
/// database (the nodes of a cluster, the replicas of a service) take it in turn to create or upgrade the schema
/// and to synchronize the schemes; the one that waits finds the work done when it gets the lock. The default
/// covers building the indexes of a large table. Past it start-up stops with
/// .
///
public TimeSpan SchemaLockTimeout { get; set; } = TimeSpan.FromMinutes(15);
private TimeSpan? _bulkInsertTimeout;
///
/// How long one bulk load of a save may run: the SqlBulkCopy of SQL Server and the binary COPY of
/// PostgreSQL that AddNewObjectsAsync and the batch save use for large sets. null (the default)
/// keeps the driver's value: 30 seconds on SQL Server, which the connection string's Command Timeout
/// does not reach. means no limit. Small sets that go as INSERT statements, and
/// every statement on SQLite, keep the timeout of the connection string.
///
public TimeSpan? BulkInsertTimeout
{
get => _bulkInsertTimeout;
set
{
if (value < TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(BulkInsertTimeout), value,
"BulkInsertTimeout cannot be negative: TimeSpan.Zero means no limit, null keeps the driver's value.");
_bulkInsertTimeout = value;
}
}
///
/// Enable transparent whole-object (Props) caching, validated by object hash.
/// Default is false.
///
public bool EnablePropsCache { get; set; } = false;
///
/// When list items are handed out (list reads, item lookups), load their linked objects
/// () in ONE batch up front, so touching
/// the property later is a field read: no database call, no blocked thread. Lists are
/// dictionaries by design (dozens of rows), so the batch is one cheap SELECT; disable only
/// when a list is unusually large AND its objects are rarely needed. Default: enabled -
/// the lazy sync getter blocks a thread per touch, and a hot loop over fresh items froze
/// a production process (2026-09-09).
///
public bool PreloadListItemLinkedObjects { get; set; } = true;
///
/// Sample bound for SQLite's ANALYZE in IMaintenanceProvider.AnalyzeAsync
/// (PRAGMA analysis_limit; 0 = unbounded full scan). PostgreSQL and MSSQL ignore it.
/// The bounded form turns a minutes-long full-file ANALYZE into seconds while producing
/// estimates just as good for redb's query shapes. Default: 1000 (SQLite's own
/// recommended ballpark).
///
public int MaintenanceAnalysisLimit { get; set; } = 1000;
///
/// SQLite: keep the planner statistics of the file at start-up. A file with no statistics for _objects
/// and _values and at least 10 000 value rows is analyzed once, bounded by
/// ; a file that has statistics gets PRAGMA optimize, which analyzes
/// again only the tables whose row count changed a lot since. Without statistics SQLite costs every index lookup
/// at a few rows and may drive a large table where a small set should drive it.
/// A file that cannot be written (read-only, or locked by another process) is left as it is with a Warning.
/// PostgreSQL and SQL Server ignore it. Default: true.
///
public bool KeepSqlitePlannerStatistics { get; set; } = true;
///
/// At start-up, compare the indexes of the database with those of the base schema and of the Pro modules in use,
/// and log one Warning naming every index that is missing, INVALID or defined otherwise
/// ( gives the full report). Nothing is created at start-up: an
/// operator may have dropped an index on purpose; or
/// redb indexes repair builds the missing ones. One catalog read. Turn it off where indexes were dropped
/// on purpose and the line is noise. Default: true.
///
public bool CheckBaseIndexesOnStart { get; set; } = true;
///
/// Maximum number of objects in Props cache.
/// On overflow the least recently used tenth is evicted at once; a working set above the limit
/// is logged as a warning
///
private int _propsCacheMaxSize = 10000;
public int PropsCacheMaxSize
{
get => _propsCacheMaxSize;
set
{
if (value <= 0)
throw new ArgumentOutOfRangeException(nameof(PropsCacheMaxSize), "Must be greater than 0");
if (value > 10_000_000)
throw new ArgumentOutOfRangeException(nameof(PropsCacheMaxSize), "Maximum 10,000,000");
_propsCacheMaxSize = value;
}
}
///
/// Lifetime of Props cache entry.
/// After expiration - entry considered stale
///
private TimeSpan _propsCacheTtl = TimeSpan.FromMinutes(60);
public TimeSpan PropsCacheTtl
{
get => _propsCacheTtl;
set
{
if (value <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(PropsCacheTtl), "TTL must be greater than 0");
if (value > TimeSpan.FromDays(7))
throw new ArgumentOutOfRangeException(nameof(PropsCacheTtl), "Maximum 7 days");
_propsCacheTtl = value;
}
}
///
/// Skip hash validation in DB before cache access.
/// true - for monolithic apps (faster, trust cache)
/// false - for distributed systems (safer, check freshness)
/// Default false (safe)
///
///
/// The zero-DB shortcut applies OUTSIDE transactions only: inside an active transaction
/// (explicit or ambient) a load always consults the database hash, so the canonical
/// ExecuteAtomicAsync + LockForUpdateAsync + re-read pattern stays correct even with this
/// flag on (bug report п.1, 2026-09-02). The flag remains a single-writer trade-off: outside
/// transactions, changes committed by ANOTHER process stay invisible until the TTL expires.
///
public bool SkipHashValidationOnCacheCheck { get; set; } = false;
///
/// Controls what LoadAsync<TProps> does when the loaded object belongs to a different
/// scheme than TProps maps to. The check itself always runs (garbage never reaches the
/// cache); this flag only chooses the reaction:
///
/// - false (default) — return null. A soft-deleted object (scheme -10)
/// therefore reads as null, which is what callers that soft-delete expect.
/// - true — throw RedbSchemeMismatchException, to surface a genuine type mistake
/// loudly.
///
/// The untyped LoadAsync(objectId) is never affected.
///
public bool ThrowOnSchemeMismatch { get; set; } = false;
// === LIST CACHE SETTINGS ===
///
/// Enable caching of lists and their items.
///
public bool EnableListCache { get; set; } = true;
///
/// Lifetime of list cache entry (TTL).
/// Eventual consistency: other clients see changes after TTL
///
private TimeSpan _listCacheTtl = TimeSpan.FromMinutes(5);
public TimeSpan ListCacheTtl
{
get => _listCacheTtl;
set
{
if (value <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(ListCacheTtl), "TTL must be greater than 0");
if (value > TimeSpan.FromDays(7))
throw new ArgumentOutOfRangeException(nameof(ListCacheTtl), "Maximum 7 days");
_listCacheTtl = value;
}
}
///
/// Enable scheme metadata caching (OBSOLETE - use MetadataCache).
///
//[Obsolete("Use MetadataCache.EnableMetadataCache instead")]
public bool EnableMetadataCache { get; set; } = true;
///
/// Metadata cache lifetime in minutes (OBSOLETE - use MetadataCache).
///
//[Obsolete("Use MetadataCache.Schemes.LifetimeMinutes instead")]
private int _metadataCacheLifetimeMinutes = 30;
public int MetadataCacheLifetimeMinutes
{
get => _metadataCacheLifetimeMinutes;
set
{
if (value < 1)
throw new ArgumentOutOfRangeException(nameof(MetadataCacheLifetimeMinutes), "Minimum 1 minute");
if (value > 10080)
throw new ArgumentOutOfRangeException(nameof(MetadataCacheLifetimeMinutes), "Maximum 10080 minutes (7 days)");
_metadataCacheLifetimeMinutes = value;
}
}
///
/// Warm up scheme metadata cache during RedbService initialization.
/// Calls warmup_all_metadata_caches() in InitializeAsync()
/// Recommended for production (predictable performance)
/// Default: true
///
public bool WarmupMetadataCacheOnInit { get; set; } = true;
// === STARTUP SETTINGS ===
///
/// Automatically create database schema on startup via IHostedService.
/// When true, RedbInitHostedService calls InitializeAsync(ensureCreated: true)
/// before other hosted services that depend on the schema.
/// Default: false (explicit opt-in).
///
public bool EnsureCreated { get; set; } = false;
// === METADATA CACHING SETTINGS (NEW) ===
//public MetadataCacheConfiguration MetadataCache { get; set; } = new();
// === VALIDATION SETTINGS ===
///
/// Enable scheme validation before synchronization.
///
public bool EnableSchemaValidation { get; set; } = true;
///
/// Enable data validation when saving.
///
public bool EnableDataValidation { get; set; } = true;
// === AUDIT SETTINGS ===
///
/// Automatically set modification date when saving.
///
public bool AutoSetModifyDate { get; set; } = true;
///
/// Automatically recompute hash when saving.
///
public bool AutoRecomputeHash { get; set; } = true;
// === SECURITY CONTEXT SETTINGS ===
// Security context priority removed - simple GetEffectiveUser() logic used
///
/// System user ID for operations without permission checks.
///
public long SystemUserId { get; set; } = 0;
// === PROPS SAVE SETTINGS ===
///
/// How a save writes the Props of an object: DeleteInsert (default) or ChangeTracking (redb Pro).
///
[JsonConverter(typeof(PropsSaveStrategyJsonConverter))]
public PropsSaveStrategy PropsSaveStrategy { get; set; } = PropsSaveStrategy.DeleteInsert;
// === SERIALIZATION SETTINGS ===
///
/// JSON serialization settings for arrays.
///
public JsonSerializationOptions JsonOptions { get; set; } = new JsonSerializationOptions();
// === METHODS ===
///
/// Copy every setting of into this instance, the connection identity
/// (, ) included.
///
public void CopyFrom(RedbServiceConfiguration source)
{
ArgumentNullException.ThrowIfNull(source);
ConnectionString = source.ConnectionString;
CacheDomain = source.CacheDomain;
CopyBehaviourFrom(source);
}
///
/// Copy every setting of into this instance except the connection identity
/// (, ): what a temporary scope may change on a
/// running service. This is the one list of the behaviour settings - Clone, CopyFrom and ApplyTemporary
/// all go through it; a new setting is added here (RedbServiceConfigurationCopyTests fails otherwise).
///
public void CopyBehaviourFrom(RedbServiceConfiguration source)
{
ArgumentNullException.ThrowIfNull(source);
IdResetStrategy = source.IdResetStrategy;
MissingObjectStrategy = source.MissingObjectStrategy;
DefaultCheckPermissionsOnLoad = source.DefaultCheckPermissionsOnLoad;
DefaultCheckPermissionsOnSave = source.DefaultCheckPermissionsOnSave;
DefaultCheckPermissionsOnDelete = source.DefaultCheckPermissionsOnDelete;
DefaultCheckPermissionsOnQuery = source.DefaultCheckPermissionsOnQuery;
DefaultStrictDeleteExtra = source.DefaultStrictDeleteExtra;
DefaultDestructiveSyncAtEqualVersion = source.DefaultDestructiveSyncAtEqualVersion;
AutoSyncSchemesOnSave = source.AutoSyncSchemesOnSave;
DefaultLoadDepth = source.DefaultLoadDepth;
DefaultMaxTreeDepth = source.DefaultMaxTreeDepth;
ThrowOnObjectNotFound = source.ThrowOnObjectNotFound;
EnablePvtPrefilter = source.EnablePvtPrefilter;
StringCollation = source.StringCollation;
CreateStringCollationIndex = source.CreateStringCollationIndex;
EnableLazyReferences = source.EnableLazyReferences;
LazyReferenceAccess = source.LazyReferenceAccess;
LazyLoadWithoutScope = source.LazyLoadWithoutScope;
AutoApplyDatabaseUpgrades = source.AutoApplyDatabaseUpgrades;
SchemaLockTimeout = source.SchemaLockTimeout;
BulkInsertTimeout = source.BulkInsertTimeout;
EnablePropsCache = source.EnablePropsCache;
PreloadListItemLinkedObjects = source.PreloadListItemLinkedObjects;
MaintenanceAnalysisLimit = source.MaintenanceAnalysisLimit;
KeepSqlitePlannerStatistics = source.KeepSqlitePlannerStatistics;
CheckBaseIndexesOnStart = source.CheckBaseIndexesOnStart;
PropsCacheMaxSize = source.PropsCacheMaxSize;
PropsCacheTtl = source.PropsCacheTtl;
SkipHashValidationOnCacheCheck = source.SkipHashValidationOnCacheCheck;
ThrowOnSchemeMismatch = source.ThrowOnSchemeMismatch;
EnableListCache = source.EnableListCache;
ListCacheTtl = source.ListCacheTtl;
EnableMetadataCache = source.EnableMetadataCache;
MetadataCacheLifetimeMinutes = source.MetadataCacheLifetimeMinutes;
WarmupMetadataCacheOnInit = source.WarmupMetadataCacheOnInit;
EnsureCreated = source.EnsureCreated;
EnableSchemaValidation = source.EnableSchemaValidation;
EnableDataValidation = source.EnableDataValidation;
AutoSetModifyDate = source.AutoSetModifyDate;
AutoRecomputeHash = source.AutoRecomputeHash;
SystemUserId = source.SystemUserId;
PropsSaveStrategy = source.PropsSaveStrategy;
JsonOptions = new JsonSerializationOptions
{
WriteIndented = source.JsonOptions.WriteIndented,
UseUnsafeRelaxedJsonEscaping = source.JsonOptions.UseUnsafeRelaxedJsonEscaping
};
}
///
/// Create configuration copy.
///
public RedbServiceConfiguration Clone()
{
// CFG-1: one list of settings (CopyFrom); a hand-written copy here had fallen five settings behind.
var copy = new RedbServiceConfiguration();
copy.CopyFrom(this);
return copy;
}
///
/// Get configuration description.
///
public string GetDescription()
{
return $"RedbService Configuration: " +
$"LoadDepth={DefaultLoadDepth}, " +
$"TreeDepth={DefaultMaxTreeDepth}, " +
$"Cache={EnableMetadataCache}, " +
// $"Security={DefaultSecurityPriority}, " +
$"IdReset={IdResetStrategy}, " +
$"MissingObj={MissingObjectStrategy}";
}
///
/// Check if configuration is safe for production
///
public bool IsProductionSafe()
{
return DefaultCheckPermissionsOnLoad &&
DefaultCheckPermissionsOnSave &&
DefaultCheckPermissionsOnDelete &&
EnableSchemaValidation &&
EnableDataValidation &&
DefaultLoadDepth <= 10 &&
!JsonOptions.WriteIndented;
}
///
/// Check if configuration is optimized for performance
///
public bool IsPerformanceOptimized()
{
return !DefaultCheckPermissionsOnLoad &&
!DefaultCheckPermissionsOnSave &&
!DefaultCheckPermissionsOnDelete &&
(EnableMetadataCache/* || MetadataCache.EnableMetadataCache*/) && // Support for new and old settings
DefaultLoadDepth <= 5 &&
DefaultMaxTreeDepth <= 10 &&
!JsonOptions.WriteIndented;
//&& MetadataCache.Warmup.EnableWarmup; // Additional performance check
}
///
/// Gets effective cache domain name.
/// Returns explicit CacheDomain if set, otherwise computes from connection string.
///
public string GetEffectiveCacheDomain()
{
if (!string.IsNullOrEmpty(CacheDomain))
return CacheDomain;
if (string.IsNullOrEmpty(ConnectionString))
return "default";
// Compute short hash from connection string (sanitized - without password)
var sanitized = SanitizeConnectionString(ConnectionString);
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(sanitized));
return Convert.ToHexString(hash)[..16].ToLowerInvariant();
}
///
/// Computes cache domain from a connection string (SHA256 hash, password-stripped).
/// Used by contexts and key generators that don't have access to full configuration.
///
public static string ComputeCacheDomain(string connectionString)
{
if (string.IsNullOrEmpty(connectionString))
return "default";
var sanitized = SanitizeConnectionString(connectionString);
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(sanitized));
return Convert.ToHexString(hash)[..16].ToLowerInvariant();
}
///
/// Removes sensitive info (password) from connection string for hashing.
///
private static string SanitizeConnectionString(string connectionString)
{
// Remove password= or pwd= from connection string
var result = System.Text.RegularExpressions.Regex.Replace(
connectionString,
@"(password|pwd)\s*=\s*[^;]*;?",
"",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
return result.ToLowerInvariant().Trim();
}
}
///
/// Object ID handling strategy after deletion
///
public enum ObjectIdResetStrategy
{
///
/// Manual ID reset (current behavior)
///
Manual,
///
/// Automatic ID reset when deleting via DeleteAsync(RedbObject)
///
AutoResetOnDelete,
///
/// Automatic creation of new object when trying to save deleted object
///
AutoCreateNewOnSave
}
///
/// Strategy for handling non-existent objects on UPDATE
///
public enum MissingObjectStrategy
{
///
/// Throw exception (current behavior)
///
ThrowException,
///
/// Automatically switch to INSERT
///
AutoSwitchToInsert,
///
/// Return null/false without error
///
ReturnNull
}
///
/// How a save writes the Props of an object (DeleteInsert or ChangeTracking)
///
public enum PropsSaveStrategy
{
///
/// Simple strategy - always DELETE + INSERT all properties
/// Reliable, but inefficient for large objects
///
DeleteInsert,
///
/// Efficient strategy - compare with DB and update only changed properties
/// Recommended by default
///
ChangeTracking
}
///
/// JSON serialization settings
///
public class JsonSerializationOptions
{
///
/// Format JSON with indentation
///
public bool WriteIndented { get; set; } = false;
///
/// Use unsafe relaxed JavaScript encoding
///
public bool UseUnsafeRelaxedJsonEscaping { get; set; } = true;
}
}