InsightsLogWriteArgsBuilder

CSharp · Console

/Program.cs

namespace Demo.InsightsLog
{
    using FluentValidation;
    using System;
    using System.Collections.Generic;
    using System.Linq;

    internal static class Program
    {
        private static void Main(string[] args)
        {
            // Arrange & Act
            InsightsLogWriteArgs res = InsightsLog.InsightsLogWriteArgs.Create()
                .WithTenantId(100002) // 使用有效的租户ID
                .WithOperatorId(10000) // 使用有效的操作人ID
                .WithTraceId(Guid.NewGuid()) // 的TraceId
                .WithField(new InsightsLogWriteArgs.NameValue("ACTION_LABEL", "来源动作")) // 添加单个字段
                .WithFields(new List<InsightsLogWriteArgs.NameValue>() // 或者直接添加多个字段
                {
                    new InsightsLogWriteArgs.NameValue("ACTION_NAME", "来源动作编码" ),
                    new InsightsLogWriteArgs.NameValue("PAGE_LABEL", "来源页面" ),
                    new InsightsLogWriteArgs.NameValue("PAGE_NAME", "来源页面编码" ),
                    new InsightsLogWriteArgs.NameValue("VERSION", "前端版本" ),
                    new InsightsLogWriteArgs.NameValue("USER_AGENT", "终端内核" ),
                    new InsightsLogWriteArgs.NameValue("IP", "IP地址" ),
                }).Build();

            // Assert
            IsNotNull(res, nameof(res)); // 控制台断言:对象不能为空
            AreEqual(100002, res.TenantId, nameof(res.TenantId));
            AreEqual(10000, res.OperatorId, nameof(res.OperatorId));
            IsTrue(res.TraceId != Guid.Empty, nameof(res.TraceId));
            AreEqual(7, res.LogFieldProperties.Count, nameof(res.LogFieldProperties));
            IsTrue(res.LogFieldProperties.Any(x => x.Name == "ACTION_LABEL" && x.Value == "来源动作"), "ACTION_LABEL");
            IsTrue(res.LogFieldProperties.Any(x => x.Name == "ACTION_NAME" && x.Value == "来源动作编码"), "ACTION_NAME");
            IsTrue(res.LogFieldProperties.Any(x => x.Name == "PAGE_LABEL" && x.Value == "来源页面"), "PAGE_LABEL");
            IsTrue(res.LogFieldProperties.Any(x => x.Name == "PAGE_NAME" && x.Value == "来源页面编码"), "PAGE_NAME");
            IsTrue(res.LogFieldProperties.Any(x => x.Name == "VERSION" && x.Value == "前端版本"), "VERSION");
            IsTrue(res.LogFieldProperties.Any(x => x.Name == "USER_AGENT" && x.Value == "终端内核"), "USER_AGENT");
            IsTrue(res.LogFieldProperties.Any(x => x.Name == "IP" && x.Value == "IP地址"), "IP");

            Console.WriteLine("All assertions passed."); // 控制台输出:断言全部通过
        }

        private static void IsNotNull(object value, string name)
        {
            if (value == null)
                throw new InvalidOperationException($"{name} should not be null.");
        }

        private static void IsTrue(bool condition, string name)
        {
            if (!condition)
                throw new InvalidOperationException($"{name} should be true.");
        }

        private static void AreEqual<T>(T expected, T actual, string name)
        {
            if (!Equals(expected, actual))
                throw new InvalidOperationException($"{name} expected: {expected}, actual: {actual}.");
        }
    }

    public sealed class OperateResult<T>
    {
        public bool Ok { get; private set; } // 调用是否成功

        public T Content { get; private set; } // 成功结果内容

        public string Error { get; private set; } // 失败错误信息

        public static OperateResult<T> Success(T content)
        {
            OperateResult<T> result = new OperateResult<T>
            {
                Ok = true,
                Content = content,
                Error = string.Empty
            };

            return result;
        }
    }

    public sealed class InsightsLogWriteResult
    {
        public InsightsLogWriteResult(long offset)
        {
            Offset = offset; // 消息偏移量
        }

        public long Offset { get; private set; } // Kafka offset
    }

    public sealed class InsightsLogWriteArgs
    {
        public static ITenantIdStep Create()
        {
            return InsightsLogWriteArgsBuilder.Create(); // 统一从 Step Builder 进入
        }

        public int TenantId { get; set; } // 租户ID

        public int OperatorId { get; set; } // 操作人ID

        public Guid TraceId { get; set; } // 链路追踪ID

        public IList<NameValue> LogFieldProperties { get; set; } = new List<NameValue>(); // 动态字段集合

        public sealed class NameValue
        {
            public NameValue()
            {
            }

            public NameValue(string name, string value)
            {
                Name = name; // 字段名
                Value = value; // 字段值
            }

            public string Name { get; set; }

            public string Value { get; set; }
        }
    }

    public interface ITenantIdStep
    {
        IOperatorIdStep WithTenantId(int tenantId); // 第一步:设置 TenantId 后进入第二步
    }

    public interface IOperatorIdStep
    {
        ITraceIdStep WithOperatorId(int operatorId); // 第二步:设置 OperatorId 后进入第三步
    }

    public interface ITraceIdStep
    {
        IFieldStep WithTraceId(Guid traceId); // 第三步:设置 TraceId 后进入字段阶段
    }

    public interface IFieldStep
    {
        IFieldStep WithField(InsightsLogWriteArgs.NameValue item); // 支持链式追加单个字段

        IFieldStep WithFields(IEnumerable<InsightsLogWriteArgs.NameValue> fields); // 支持链式追加多个字段

        InsightsLogWriteArgs Build(); // 触发最终校验并返回结果
    }

    public sealed class InsightsLogWriteArgsBuilder : ITenantIdStep, IOperatorIdStep, ITraceIdStep, IFieldStep
    {
        private readonly InsightsLogWriteArgs _args = new InsightsLogWriteArgs();

        private InsightsLogWriteArgsBuilder()
        {
        }

        public static ITenantIdStep Create()
        {
            return new InsightsLogWriteArgsBuilder(); // Builder 对外仅暴露第一步
        }

        public IOperatorIdStep WithTenantId(int tenantId)
        {
            _args.TenantId = tenantId; // 写入租户ID
            return this;
        }

        public ITraceIdStep WithOperatorId(int operatorId)
        {
            _args.OperatorId = operatorId; // 写入操作人ID
            return this;
        }

        public IFieldStep WithTraceId(Guid traceId)
        {
            _args.TraceId = traceId; // 写入TraceId
            return this;
        }

        public IFieldStep WithField(InsightsLogWriteArgs.NameValue item)
        {
            _args.LogFieldProperties.Add(item); // 追加单个字段
            return this;
        }

        public IFieldStep WithFields(IEnumerable<InsightsLogWriteArgs.NameValue> fields)
        {
            foreach (InsightsLogWriteArgs.NameValue item in fields)
            {
                _args.LogFieldProperties.Add(item); // 逐个追加字段
            }

            return this;
        }

        public InsightsLogWriteArgs Build()
        {
            InsightsLogWriteArgsValidator validator = new InsightsLogWriteArgsValidator(); // 构造验证器
            validator.ValidateAndThrow(_args); // 不合法直接抛出异常

            return _args; // 返回最终对象
        }
    }

    public sealed class InsightsLogWriteArgsValidator : AbstractValidator<InsightsLogWriteArgs>
    {
        public InsightsLogWriteArgsValidator()
        {
            RuleFor(x => x.TenantId).GreaterThan(0).WithMessage("租户ID必须大于0"); // 规则1:TenantId 必须大于0
            RuleFor(x => x.OperatorId).GreaterThan(0).WithMessage("操作人ID必须大于0"); // 规则2:OperatorId 必须大于0
            RuleFor(x => x.TraceId).NotEqual(Guid.Empty).WithMessage("TraceID不能是空GUID"); // 规则3:TraceId 不能为默认值
            RuleFor(x => x.LogFieldProperties)
                .NotNull() // 规则4:字段集合不能为 null
                .WithMessage("日志字段映射不能为NULL")
                .Must(dict => dict?.Any() == true) // 规则5:字段集合至少 1 条
                .WithMessage("日志字段映射必须包含一个元素");
        }
    }
}
;