sunpengfei
2025-08-14 fa61e2ee70365d2dd2eb59d834c0995c2fef46b8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
using Consul;
using Furion;
using Furion.DatabaseAccessor;
using Furion.DataEncryption;
using Furion.DistributedIDGenerator;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Furion.HttpRemote;
using Mapster;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Routing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using static System.Collections.Specialized.BitVector32;
 
namespace FlexJobApi.Core
{
    /// <summary>
    /// 资源工具
    /// </summary>
    public static class ResourceUtils
    {
        /// <summary>
        /// 生成动态控制器
        /// </summary>
        public static async Task BuildDynamicControllersAsync()
        {
            var traceId = App.GetTraceId() ?? IDGen.NextID().ToString();
            var scopeFactory = App.GetService<IServiceScopeFactory>();
            var serviceScope = scopeFactory.CreateScope();
            var provider = serviceScope.ServiceProvider.GetRequiredService<IDynamicApiRuntimeChangeProvider>();
            var rep = serviceScope.ServiceProvider.GetRequiredService<IRepository<Resource>>();
            var xmlDoc = await XmlDocUtils.GetXmlDocAsync();
            var enumWebApiMethods = await EnumUtils.GetModel<EnumResourceMethod>();
            var resourceControllers = await EnumUtils.GetModel<EnumResourceController>();
            var requests = App.Assemblies
                .SelectMany(it => it.GetTypes())
                .Where(it => !it.IsAbstract && typeof(IBaseRequest).IsAssignableFrom(it))
                .ToList();
            var models = new List<ResourceModel>();
            foreach (var request in requests)
            {
                var resourceAttribute = request.GetCustomAttribute<ResourceAttribute>();
                if (resourceAttribute == null) throw Oops.Oh(EnumErrorCodeType.s404, $"请给资源{request.Name}分配服务特性Resource");
 
                foreach (var controller in resourceAttribute.Controllers)
                {
                    var requestXmlDoc = await request.GetXmlDocMemberAsync(xmlDoc);
                    var resourceController = controller.GetCustomAttribute<EnumResourceController, ResourceControllerAttribute>();
                    var resourceService = resourceController.Service.GetCustomAttribute<EnumResourceService, ResourceServiceAttribute>();
 
                    var model = new ResourceModel();
                    model.TraceId = traceId;
                    model.ApplicationName = resourceService.ApplicationName;
                    model.Controller = controller;
                    model.ControllerSummary = resourceControllers.GetDescription(controller);
                    model.ActionName = Regex.Replace(request.Name, @"(Command|Query)$", "", RegexOptions.None);
                    model.ActionSummary = requestXmlDoc?.Summary;
                    model.Service = resourceController.Service;
                    model.ServiceName = resourceService.ServiceName;
                    model.RouteArea = resourceService.RouteArea;
                    model.Route = $"/api/{resourceService.RouteArea ?? "main"}/{controller}/{model.ActionName}";
                    model.Method =
                        resourceAttribute.Method.HasValue
                        ? resourceAttribute.Method.Value
                        : request.BaseType?.IsGenericType == true && request.BaseType.GetGenericTypeDefinition() == typeof(PagedListQuery<,>)
                        ? EnumResourceMethod.Post
                        : new List<string> { "Post", "Add", "Create", "Insert", "Submit" }.Any(it => request.Name.StartsWith(it, StringComparison.OrdinalIgnoreCase))
                        ? EnumResourceMethod.Post
                        : new List<string> { "GetAll", "GetList", "Get", "Find", "Fetch", "Query" }.Any(it => request.Name.StartsWith(it, StringComparison.OrdinalIgnoreCase))
                        ? EnumResourceMethod.Get
                        : new List<string> { "Put", "Update ", "Set" }.Any(it => request.Name.StartsWith(it, StringComparison.OrdinalIgnoreCase))
                        ? EnumResourceMethod.Put
                        : new List<string> { "Delete", "Remove ", "Clear" }.Any(it => request.Name.StartsWith(it, StringComparison.OrdinalIgnoreCase))
                        ? EnumResourceMethod.Delete
                        : EnumResourceMethod.Post;
                    model.FileUpload = resourceAttribute.FileUpload;
                    model.Code = requestXmlDoc?.Name;
                    model.Name = $"{model.ControllerSummary}-{model.ActionSummary}";
                    model.AllowAnonymous = resourceAttribute.AllowAnonymous;
                    model.RequestTypeName = request.Name;
                    model.RequestTypeFullName = request.FullName;
                    var iRequestType = request.GetInterface("IRequest`1");
                    if (iRequestType != null && iRequestType.IsGenericType)
                    {
                        var responseType = iRequestType.GenericTypeArguments[0];
                        model.ResponseTypeName = responseType.GetCSharpFriendlyName();
                        model.ResponseTypeFullName = responseType.FullName;
                    }
                    models.Add(model);
 
                    await App.GetRequiredService<IDistributedCache>().SetStringAsync($"ResourceModel|{model.RequestTypeFullName}", model.ToJson());
                }
            }
 
            var resources = await SaveResourcesAsync(models, rep);
 
            DynamicControllersHotPlug(resources, provider);
 
            await rep.SaveNowAsync();
        }
 
        /// <summary>
        /// 保存资源
        /// </summary>
        /// <param name="models"></param>
        /// <param name="traceId"></param>
        /// <param name="rep"></param>
        /// <returns></returns>
        private static async Task<List<Resource>> SaveResourcesAsync(List<ResourceModel> models, IRepository<Resource> rep = null)
        {
            rep = rep ?? Db.GetRepository<Resource>();
            var resources = await rep.AsQueryable()
                .Where(it => !it.IsExpired)
                .ToListAsync();
            foreach (var model in models)
            {
                var resource = resources.FirstOrDefault(it => it.Route == model.Route && it.Method == model.Method);
                if (resource == null)
                {
                    resource = new Resource();
                    resource.Id = IDGen.NextID();
                    resource.CreatedTime = DateTimeOffset.Now;
                    model.Adapt(resource);
                    await rep.InsertAsync(resource);
                    resources.Add(resource);
                }
                else
                {
                    var resourceBakModel = new ResourceModel();
                    resource.Adapt(resourceBakModel);
                    resourceBakModel.TraceId = model.TraceId;
                    resourceBakModel.DynamicAssemblyName = model.DynamicAssemblyName;
                    if (resourceBakModel.ToJson() != model.ToJson())
                    {
                        model.Adapt(resource);
                        resource.UpdatedTime = DateTimeOffset.Now;
                        await rep.UpdateAsync(resource);
                    }
                }
            }
 
            var expiredResources = resources.Where(it => !models.Any(m => m.Route == it.Route && m.Method == it.Method)).ToList();
            foreach (var expiredResource in expiredResources)
            {
                resources.Remove(expiredResource);
                await rep.DeleteAsync(expiredResource);
            }
 
            return resources.Where(it => !it.IsExpired).ToList();
        }
 
        /// <summary>
        /// 动态控制器热插
        /// </summary>
        /// <param name="resources"></param>
        /// <param name="provider"></param>
        public static void DynamicControllersHotPlug(List<Resource> resources, IDynamicApiRuntimeChangeProvider provider = null)
        {
            provider = provider ?? App.GetRequiredService<IDynamicApiRuntimeChangeProvider>();
            var controllers = resources
                .GroupBy(it => new
                {
                    it.ApplicationName,
                    it.Controller,
                    it.ControllerSummary,
                    it.RouteArea
                })
                .Select(it => new
                {
                    it.Key,
                    Actions = it.ToList()
                })
                .ToList();
            foreach (var controller in controllers)
            {
                var code = $@"
using FlexJobApi.Core;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.ComponentModel;
 
 
namespace {controller.Key.ApplicationName}.{controller.Key.Controller}
{{
    /// <summary>
    /// {controller.Key.ControllerSummary}
    /// </summary>
    [Route(""api/{controller.Key.RouteArea}/[controller]"")]
    public class {controller.Key.Controller}AppService(IMediator mediator) : IDynamicApiController
    {{
        private readonly IMediator mediator = mediator;";
 
                foreach (var action in controller.Actions)
                {
                    var result = action.ResponseTypeName.IsNull() ? "Task" : $"Task<{action.ResponseTypeName}>";
                    code += @$"
 
        /// <summary>
        /// {action.ActionSummary}
        /// </summary>
        /// <param name=""request""></param>
        /// <returns></returns>";
                    if (action.AllowAnonymous)
                    {
                        code += $@"
        [AllowAnonymous]";
                    }
                    code += $@"
        [Http{action.Method}]";
                    if (action.FileUpload)
                    {
                        code += @"
        [Consumes(""multipart/form-data"")]";
                    }
                    code += @$"
        public {result} {action.ActionName}(";
                    if (action.FileUpload)
                    {
                        code += "[FromForm] ";
                    }
                    code += $@"{action.RequestTypeName} request)
        {{
            return mediator.Send(request);
        }}";
                }
 
                code += @"
    }
}
";
                try
                {
                    var dynamicAssembly = App.CompileCSharpClassCode(code);
                    provider.AddAssembliesWithNotifyChanges(dynamicAssembly);
                    var dynamicAssemblyName = dynamicAssembly.GetName().Name;
                    foreach (var action in controller.Actions)
                    {
                        action.DynamicAssemblyName = dynamicAssemblyName;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(code);
                    throw;
                }
            }
 
        }
 
        /// <summary>
        /// 动态控制器热拔
        /// </summary>
        /// <param name="resource"></param>
        /// <param name="provider"></param>
        public static void DynamicControllerHotPluck(Resource resource, IDynamicApiRuntimeChangeProvider provider = null)
        {
            provider = provider ?? App.GetRequiredService<IDynamicApiRuntimeChangeProvider>();
            provider.RemoveAssembliesWithNotifyChanges(resource.DynamicAssemblyName);
        }
 
        /// <summary>
        /// 获取C#友好名称
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private static string GetCSharpFriendlyName(this Type type)
        {
            // 处理可空类型
            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
            {
                Type underlyingType = Nullable.GetUnderlyingType(type)!;
                return $"{GetCSharpFriendlyName(underlyingType)}?";
            }
 
            // 处理基础类型
            if (type.FullName.IsNotNull())
            {
                var baseTypes = new Dictionary<string, string>
                {
                    { "System.Byte", "byte" },
                    { "System.SByte", "sbyte" },
                    { "System.Int16", "short" },
                    { "System.UInt16", "ushort" },
                    { "System.Int32", "int" },
                    { "System.UInt32", "uint" },
                    { "System.Int64", "long" },
                    { "System.UInt64", "ulong" },
                    { "System.Single", "float" },
                    { "System.Double", "double" },
                    { "System.Decimal", "decimal" },
                    { "System.Char", "char" },
                    { "System.Boolean", "bool" },
                    { "System.String", "string" },
                    { "System.Object", "object" }
                };
                if (baseTypes.TryGetValue(type.FullName, out string? friendlyName) && friendlyName.IsNotNull())
                {
                    return friendlyName;
                }
            }
 
            // 处理非泛型类型
            if (!type.IsGenericType)
            {
                return type.Name;
            }
 
            // 处理泛型类型
            string genericTypeName = type.GetGenericTypeDefinition().Name;
            if (genericTypeName.Contains('`'))
                genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`'));
 
            string[] genericArgs = type.GetGenericArguments()
               .Select(GetCSharpFriendlyName)
               .ToArray();
 
            return $"{genericTypeName}<{string.Join(", ", genericArgs)}>";
        }
    }
}