Path: redb/redb.Core/Serialization/SystemTextJsonRedbSerializer.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/Serialization/SystemTextJsonRedbSerializer.cs ---- using System; using System.Threading; using System.Text.Json; using System.Text.Json.Serialization; using redb.Core.Models.Entities; using redb.Core.Models.Contracts; using redb.Core.Utils; using redb.Core.Caching; namespace redb.Core.Serialization { // Implementation using System.Text.Json // Requirement: C# property names match JSON names (snake_case), so no custom NamingPolicy public class SystemTextJsonRedbSerializer : IRedbObjectSerializer { /// /// A type resolver set by the application, if any: it takes precedence over the per-domain resolution. /// private static Func? _typeResolver; /// The cache domain of the redb service initialized last; a name, never the service itself. private static string? _lastInitializedDomain; /// /// Set the type resolver function for polymorphic deserialization. Without one, a scheme id resolves in the /// cache domain of the redb service current for the calling flow, else of the service initialized last. /// public static void SetTypeResolver(Func resolver) { _typeResolver = resolver ?? throw new ArgumentNullException(nameof(resolver)); } /// Records the domain of a service that has just initialized (the fallback of ). internal static void SetInitializedDomain(string domain) => Volatile.Write(ref _lastInitializedDomain, domain); /// /// Resolve CLR type by scheme ID: a scheme id is a per-database fact, so it resolves in the domain of the /// service the calling flow reads through. Held as a domain name, the resolution keeps no service alive. /// internal static Type? ResolveType(long schemeId) { if (_typeResolver is { } resolver) return resolver(schemeId); var domain = RedbAmbientScope.CurrentDomain ?? Volatile.Read(ref _lastInitializedDomain); return domain == null ? null : new GlobalMetadataCache(domain).GetClrType(schemeId); } // The options cache the metadata of every type they handled, Props types of modules included: the caches of // System.Text.Json are cleared when a collectible AssemblyLoadContext unloads (CollectibleContextCleanup). static SystemTextJsonRedbSerializer() => CollectibleContextCleanup.EnsureWatching(); /// /// Public serialization options for use in other components /// (e.g., for polymorphic TreeRedbObject deserialization) /// public static readonly JsonSerializerOptions Options = new() { PropertyNameCaseInsensitive = true, ReadCommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault, // Ignore empty arrays/null/default when serializing Converters = { new NullToDefaultConverterFactory(), // null → default(T) for value types (int, long, etc) new ValueTupleDictionaryConverterFactory(), // Dictionary with ValueTuple/Class keys (Base64) new RedbObjectStubWriteConverterFactory(), // V4 (L.4): writing never triggers lazy loading; a stub writes base fields only new PolymorphicRedbObjectConverter(), // Polymorphic IRedbObject deserialization based on scheme_id new PostgresDateTimeOffsetConverter(), // DateTimeOffset from PostgreSQL timestamptz new PostgresNullableDateTimeOffsetConverter(), // Nullable DateTimeOffset from PostgreSQL new PostgresInfinityDateTimeConverter(), // FIX: PostgreSQL "-infinity" support new PostgresInfinityNullableDateTimeConverter(), // FIX: PostgreSQL "-infinity" support for nullable DateTime new JsonStringEnumConverter(), // Enum as strings support new FlexibleTimeSpanConverter(), // TimeSpan from its Ticks new FlexibleNullableTimeSpanConverter(), // nullable TimeSpan support new FlexibleDateOnlyConverter(), // DateOnly from DateTime strings support new FlexibleNullableDateOnlyConverter(), // nullable DateOnly support new FlexibleTimeOnlyConverter(), // TimeOnly from its Ticks new FlexibleNullableTimeOnlyConverter() // nullable TimeOnly support } }; public RedbObject Deserialize(string json) where TProps : class, new() { var obj = JsonSerializer.Deserialize>(json, Options); if (obj == null) { throw new InvalidOperationException("Failed to deserialize get_object_json payload to RedbObject."); } // The root of a get_object_json payload is the object redb loaded: loaded by definition, with or without // Props (a scheme without properties, an object saved with null Props). The converter takes null Props for // "not loaded" - right for the nested references it also reads, wrong for the root. obj._propsLoaded = true; return obj; } public IRedbObject DeserializeDynamic(string json, Type propsType) { // Create generic type RedbObject<propsType> via reflection var redbObjectType = typeof(RedbObject<>).MakeGenericType(propsType); // Deserialize JSON to this type var deserializedObj = JsonSerializer.Deserialize(json, redbObjectType, Options); if (deserializedObj == null) { throw new InvalidOperationException($"Failed to deserialize get_object_json payload to RedbObject<{propsType.Name}>."); } // The root is loaded by definition (see Deserialize). redbObjectType.GetField("_propsLoaded")?.SetValue(deserializedObj, true); // Return as IRedbObject return (IRedbObject)deserializedObj; } public RedbObject? DeserializeRedbDynamic(string json, Type propsType) { // Simply deserialize to RedbObject<TProps> // Conversion to TreeRedbObject will happen in PostgresTreeQueryProvider var redbObjectType = typeof(RedbObject<>).MakeGenericType(propsType); var redbObj = JsonSerializer.Deserialize(json, redbObjectType, Options) as RedbObject; return redbObj; } } /// /// Polymorphic converter for IRedbObject /// Automatically determines type based on scheme_id from JSON and deserializes to RedbObject<TProps> /// Used for nested objects (e.g., RedbListItem.Object) /// public class PolymorphicRedbObjectConverter : JsonConverter { public override IRedbObject? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { // 1. Read JSON to JsonElement for analysis using var jsonDoc = JsonDocument.ParseValue(ref reader); var jsonElement = jsonDoc.RootElement; // 2. Extract scheme_id to determine type if (!jsonElement.TryGetProperty("scheme_id", out var schemeIdProp)) { // No scheme_id → cannot determine type return null; } var schemeId = schemeIdProp.GetInt64(); // 3. Get real C# type via type resolver var propsType = SystemTextJsonRedbSerializer.ResolveType(schemeId); if (propsType == null) { // Type not registered → skip return null; } // 4. Create RedbObject<TProps> dynamically via reflection var redbObjectType = typeof(RedbObject<>).MakeGenericType(propsType); // 5. Deserialize JSON to concrete type // CRITICAL: Use new JsonSerializerOptions WITHOUT this converter // Otherwise infinite recursion occurs with nested IRedbObject var optionsWithoutThisConverter = new JsonSerializerOptions(options); optionsWithoutThisConverter.Converters.Clear(); foreach (var converter in options.Converters) { if (converter is not PolymorphicRedbObjectConverter) { optionsWithoutThisConverter.Converters.Add(converter); } } var obj = JsonSerializer.Deserialize(jsonElement.GetRawText(), redbObjectType, optionsWithoutThisConverter); return obj as IRedbObject; } public override void Write(Utf8JsonWriter writer, IRedbObject? value, JsonSerializerOptions options) { if (value == null) { writer.WriteNullValue(); return; } // IRedbObject serialization may lead to circular references // For safety return null (navigation properties are not serialized) writer.WriteNullValue(); } } /// /// Flexible converter for DateOnly - supports DateTime strings /// public class FlexibleDateOnlyConverter : JsonConverter { public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { var dateString = reader.GetString(); if (Utils.RedbTemporalFormat.TryParseDateOnly(dateString, out var dateOnly)) { return dateOnly; } } throw new JsonException($"Unable to convert '{reader.GetString()}' to DateOnly."); } public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options) { writer.WriteStringValue(Utils.RedbTemporalFormat.ToText(value)); } } /// /// Flexible converter for nullable DateOnly /// public class FlexibleNullableDateOnlyConverter : JsonConverter { public override DateOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) return null; if (reader.TokenType == JsonTokenType.String) { var dateString = reader.GetString(); if (string.IsNullOrEmpty(dateString)) return null; if (Utils.RedbTemporalFormat.TryParseDateOnly(dateString, out var dateOnly)) { return dateOnly; } } throw new JsonException($"Unable to convert '{reader.GetString()}' to DateOnly?."); } public override void Write(Utf8JsonWriter writer, DateOnly? value, JsonSerializerOptions options) { if (value.HasValue) writer.WriteStringValue(Utils.RedbTemporalFormat.ToText(value.Value)); else writer.WriteNullValue(); } } /// /// TimeOnly from the object JSON of the modules: its Ticks, as _values._Long stores it. /// public class FlexibleTimeOnlyConverter : JsonConverter { public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt64(out var ticks)) return new TimeOnly(ticks); throw new JsonException($"Unable to convert a {reader.TokenType} token to TimeOnly: it is stored as Ticks."); } public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options) => writer.WriteNumberValue(value.Ticks); } /// /// Nullable TimeOnly from the object JSON of the modules: its Ticks, or null. /// public class FlexibleNullableTimeOnlyConverter : JsonConverter { public override TimeOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) return null; if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt64(out var ticks)) return new TimeOnly(ticks); throw new JsonException($"Unable to convert a {reader.TokenType} token to TimeOnly?: it is stored as Ticks."); } public override void Write(Utf8JsonWriter writer, TimeOnly? value, JsonSerializerOptions options) { if (value.HasValue) writer.WriteNumberValue(value.Value.Ticks); else writer.WriteNullValue(); } } /// /// TimeSpan from the object JSON of the modules: its Ticks, as _values._Long stores it. /// public class FlexibleTimeSpanConverter : JsonConverter { public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt64(out var ticks)) return TimeSpan.FromTicks(ticks); throw new JsonException($"Unable to convert a {reader.TokenType} token to TimeSpan: it is stored as Ticks."); } public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options) => writer.WriteNumberValue(value.Ticks); } /// /// Nullable TimeSpan from the object JSON of the modules: its Ticks, or null. /// public class FlexibleNullableTimeSpanConverter : JsonConverter { public override TimeSpan? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) return null; if (reader.TokenType == JsonTokenType.Number && reader.TryGetInt64(out var ticks)) return TimeSpan.FromTicks(ticks); throw new JsonException($"Unable to convert a {reader.TokenType} token to TimeSpan?: it is stored as Ticks."); } public override void Write(Utf8JsonWriter writer, TimeSpan? value, JsonSerializerOptions options) { if (value.HasValue) writer.WriteNumberValue(value.Value.Ticks); else writer.WriteNullValue(); } } /// /// DateTimeOffset converter for PostgreSQL timestamptz. /// public class PostgresDateTimeOffsetConverter : JsonConverter { public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { var stringValue = reader.GetString(); // PostgreSQL infinity support if (stringValue == "-infinity") return DateTimeOffset.MinValue; if (stringValue == "infinity") return DateTimeOffset.MaxValue; // Parse standard ISO8601 with timezone. Invariant culture: the wire form is always // ISO, and the ambient culture must never influence how a stored value is read. if (DateTimeOffset.TryParse(stringValue, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out var result)) { return result.ToUniversalTime(); } } if (reader.TokenType == JsonTokenType.Null) throw new JsonException("Cannot convert null to DateTimeOffset"); return JsonSerializer.Deserialize(ref reader, options); } public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) { if (value == DateTimeOffset.MinValue) writer.WriteStringValue("-infinity"); else if (value == DateTimeOffset.MaxValue) writer.WriteStringValue("infinity"); else writer.WriteStringValue(value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffzzz", System.Globalization.CultureInfo.InvariantCulture)); } } /// /// Nullable DateTimeOffset converter for PostgreSQL timestamptz. /// public class PostgresNullableDateTimeOffsetConverter : JsonConverter { public override DateTimeOffset? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) return null; if (reader.TokenType == JsonTokenType.String) { var stringValue = reader.GetString(); if (stringValue == "-infinity") return DateTimeOffset.MinValue; if (stringValue == "infinity") return DateTimeOffset.MaxValue; if (DateTimeOffset.TryParse(stringValue, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out var result)) { return result.ToUniversalTime(); } } return JsonSerializer.Deserialize(ref reader, options); } public override void Write(Utf8JsonWriter writer, DateTimeOffset? value, JsonSerializerOptions options) { if (value == null) writer.WriteNullValue(); else if (value == DateTimeOffset.MinValue) writer.WriteStringValue("-infinity"); else if (value == DateTimeOffset.MaxValue) writer.WriteStringValue("infinity"); else writer.WriteStringValue(value.Value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffffffzzz", System.Globalization.CultureInfo.InvariantCulture)); } } /// /// FIX FOR "-infinity" PROBLEM: DateTime converter for handling PostgreSQL "-infinity" /// Solves problem: The JSON value could not be converted to System.DateTime /// public class PostgresInfinityDateTimeConverter : JsonConverter { public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { var stringValue = reader.GetString(); // HANDLE PostgreSQL "-infinity" if (stringValue == "-infinity") { return DateTime.MinValue; } // HANDLE PostgreSQL "infinity" if (stringValue == "infinity") { return DateTime.MaxValue; } // Regular DateTime deserialization. Parsed as DateTimeOffset and reduced to the UTC // instant, so the stored clock reading comes back unchanged regardless of the // reader's time zone — REDB's contract is that DateTime carries no zone. if (DateTimeOffset.TryParse(stringValue, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out var dateTimeOffset)) { return Utils.DateTimeConverter.DenormalizeFromStorage(dateTimeOffset); } throw new JsonException($"Cannot parse '{stringValue}' as DateTimeOffset."); } if (reader.TokenType == JsonTokenType.Null) { throw new JsonException("Cannot convert null to DateTime"); } // Try standard deserialization var result = JsonSerializer.Deserialize(ref reader, options); return result; } public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) { // REVERSE CONVERSION: DateTime.MinValue → "-infinity" for PostgreSQL if (value == DateTime.MinValue) { writer.WriteStringValue("-infinity"); } else if (value == DateTime.MaxValue) { writer.WriteStringValue("infinity"); } else { // Standard serialization writer.WriteStringValue(value.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", System.Globalization.CultureInfo.InvariantCulture)); } } } /// /// FIX FOR "-infinity" PROBLEM: Nullable DateTime converter for handling PostgreSQL "-infinity" /// public class PostgresInfinityNullableDateTimeConverter : JsonConverter { public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) { return null; } if (reader.TokenType == JsonTokenType.String) { var stringValue = reader.GetString(); // HANDLE PostgreSQL "-infinity" if (stringValue == "-infinity") { return DateTime.MinValue; } // HANDLE PostgreSQL "infinity" if (stringValue == "infinity") { return DateTime.MaxValue; } // Standard DateTime deserialization if (DateTimeOffset.TryParse(stringValue, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind, out var dateTime)) { // FIXED: Return UTC instead of Local return Utils.DateTimeConverter.DenormalizeFromStorage(dateTime); } } // Try standard deserialization return JsonSerializer.Deserialize(ref reader, options); } public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options) { if (!value.HasValue) { writer.WriteNullValue(); return; } // REVERSE CONVERSION: DateTime.MinValue → "-infinity" for PostgreSQL if (value.Value == DateTime.MinValue) { writer.WriteStringValue("-infinity"); } else if (value.Value == DateTime.MaxValue) { writer.WriteStringValue("infinity"); } else { // Standard serialization writer.WriteStringValue(value.Value.ToString("yyyy-MM-ddTHH:mm:ss.fffffffK", System.Globalization.CultureInfo.InvariantCulture)); } } } /// /// Factory that creates converters to handle JSON null → default(T) for non-nullable value types. /// Fixes MSSQL deserialization where null values are explicitly included in JSON. /// public class NullToDefaultConverterFactory : JsonConverterFactory { private static readonly HashSet SupportedTypes = new() { typeof(int), typeof(long), typeof(short), typeof(byte), typeof(uint), typeof(ulong), typeof(ushort), typeof(sbyte), typeof(float), typeof(double), typeof(decimal), typeof(bool), typeof(char) }; public override bool CanConvert(Type typeToConvert) { return SupportedTypes.Contains(typeToConvert); } public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) { var converterType = typeof(NullToDefaultConverter<>).MakeGenericType(typeToConvert); return (JsonConverter?)Activator.CreateInstance(converterType); } } /// /// Converter that returns default(T) when JSON contains null for a non-nullable value type. /// public class NullToDefaultConverter : JsonConverter where T : struct { public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) { return default; } // Handle numeric types if (typeof(T) == typeof(int)) return (T)(object)reader.GetInt32(); if (typeof(T) == typeof(long)) return (T)(object)reader.GetInt64(); if (typeof(T) == typeof(short)) return (T)(object)reader.GetInt16(); if (typeof(T) == typeof(byte)) return (T)(object)reader.GetByte(); if (typeof(T) == typeof(uint)) return (T)(object)reader.GetUInt32(); if (typeof(T) == typeof(ulong)) return (T)(object)reader.GetUInt64(); if (typeof(T) == typeof(ushort)) return (T)(object)reader.GetUInt16(); if (typeof(T) == typeof(sbyte)) return (T)(object)reader.GetSByte(); if (typeof(T) == typeof(float)) return (T)(object)reader.GetSingle(); if (typeof(T) == typeof(double)) return (T)(object)reader.GetDouble(); if (typeof(T) == typeof(decimal)) return (T)(object)reader.GetDecimal(); if (typeof(T) == typeof(bool)) return (T)(object)reader.GetBoolean(); if (typeof(T) == typeof(char)) { var str = reader.GetString(); return (T)(object)(str?.Length > 0 ? str[0] : default(char)); } throw new JsonException($"Unsupported type {typeof(T).Name}"); } public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { // Direct writes only. The old body called JsonSerializer.Serialize(writer, value, // options) with the SAME options - which resolve back to this converter: infinite // recursion, StackOverflow, dead process. It lay dormant because the write side of // these options only ever met models whose value-type members were all default // (skipped by WhenWritingDefault before reaching the converter); the first non-zero // int serialized through them (RedbObject.ToString) blew up. if (typeof(T) == typeof(int)) { writer.WriteNumberValue((int)(object)value!); return; } if (typeof(T) == typeof(long)) { writer.WriteNumberValue((long)(object)value!); return; } if (typeof(T) == typeof(short)) { writer.WriteNumberValue((short)(object)value!); return; } if (typeof(T) == typeof(byte)) { writer.WriteNumberValue((byte)(object)value!); return; } if (typeof(T) == typeof(uint)) { writer.WriteNumberValue((uint)(object)value!); return; } if (typeof(T) == typeof(ulong)) { writer.WriteNumberValue((ulong)(object)value!); return; } if (typeof(T) == typeof(ushort)) { writer.WriteNumberValue((ushort)(object)value!); return; } if (typeof(T) == typeof(sbyte)) { writer.WriteNumberValue((sbyte)(object)value!); return; } if (typeof(T) == typeof(float)) { writer.WriteNumberValue((float)(object)value!); return; } if (typeof(T) == typeof(double)) { writer.WriteNumberValue((double)(object)value!); return; } if (typeof(T) == typeof(decimal)) { writer.WriteNumberValue((decimal)(object)value!); return; } if (typeof(T) == typeof(bool)) { writer.WriteBooleanValue((bool)(object)value!); return; } if (typeof(T) == typeof(char)) { writer.WriteStringValue(value!.ToString()); return; } throw new JsonException($"Unsupported type {typeof(T).Name}"); } } }