using System.Text.Json; using System.Text.Json.Serialization; namespace Fleet.Core; /// 节点 ID(带类型前缀的 ULID)。MoShiro 中的 AgentId 就是 NodeId。 [JsonConverter(typeof(NodeIdJsonConverter))] public readonly record struct NodeId(string Value) { public override string ToString() => Value; } /// 强类型字符串 ID 的 JSON 转换器基类(源生成友好,不使用反射)。 public abstract class StringIdJsonConverter : JsonConverter { protected abstract TId Create(string value); protected abstract string GetValue(TId id); public sealed override TId Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => Create(reader.GetString() ?? throw new JsonException("id must be a string")); public sealed override void Write(Utf8JsonWriter writer, TId value, JsonSerializerOptions options) => writer.WriteStringValue(GetValue(value)); public sealed override TId ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => Create(reader.GetString() ?? throw new JsonException("id must be a string")); public sealed override void WriteAsPropertyName(Utf8JsonWriter writer, TId value, JsonSerializerOptions options) => writer.WritePropertyName(GetValue(value)); } public sealed class NodeIdJsonConverter : StringIdJsonConverter { protected override NodeId Create(string value) => new(value); protected override string GetValue(NodeId id) => id.Value; }