Files
MoShiro/backend/fleet/src/Fleet.Core/StringId.cs
T
justme 2e146d4da7
ci/woodpecker/push/main-amd64-build Pipeline was successful
refactor!: rename the project from Monitor to MoShiro [CI]
Namespaces, assemblies, solution, binaries, images, systemd units, config paths, environment variables, protocol methods and the Linux user are all renamed. Breaking: existing databases, node identities and installed units must be recreated.
2026-10-07 02:03:25 +08:00

39 lines
1.5 KiB
C#

using System.Text.Json;
using System.Text.Json.Serialization;
namespace Fleet.Core;
/// <summary>节点 ID(带类型前缀的 ULID)。MoShiro 中的 AgentId 就是 NodeId。</summary>
[JsonConverter(typeof(NodeIdJsonConverter))]
public readonly record struct NodeId(string Value)
{
public override string ToString() => Value;
}
/// <summary>强类型字符串 ID 的 JSON 转换器基类(源生成友好,不使用反射)。</summary>
public abstract class StringIdJsonConverter<TId> : JsonConverter<TId>
{
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<NodeId>
{
protected override NodeId Create(string value) => new(value);
protected override string GetValue(NodeId id) => id.Value;
}