Skip to content

Commit

Permalink
v2.9.2024.0203 修正net40的客户端调用
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Feb 3, 2024
1 parent d7b93bf commit 2f6eb8d
Show file tree
Hide file tree
Showing 19 changed files with 108 additions and 107 deletions.
2 changes: 1 addition & 1 deletion StarAgent/StarAgent.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="NewLife.Agent" Version="10.6.2024.101" />
<PackageReference Include="NewLife.Agent" Version="10.6.2024.203" />
</ItemGroup>

<ItemGroup>
Expand Down
7 changes: 4 additions & 3 deletions Stardust.Extensions/Caches/CacheDirectoryContents.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace Stardust.Extensions.Caches;

class CacheDirectoryContents : IDirectoryContents, IEnumerable<IFileInfo>, IEnumerable
{
private IEnumerable<IFileInfo> _entries;
private IEnumerable<IFileInfo>? _entries;

private readonly String _directory;

Expand All @@ -22,7 +22,7 @@ class CacheDirectoryContents : IDirectoryContents, IEnumerable<IFileInfo>, IEnum
public Boolean Exists => Directory.Exists(_directory);

/// <summary>索引信息文件。列出扩展显示的文件内容</summary>
public String IndexInfoFile { get; set; }
public String? IndexInfoFile { get; set; }

public CacheDirectoryContents(String directory)
: this(directory, ExclusionFilters.Sensitive)
Expand All @@ -47,6 +47,7 @@ IEnumerator IEnumerable.GetEnumerator()
return _entries.GetEnumerator();
}

[MemberNotNull(nameof(_entries))]
private void EnsureInitialized()
{
try
Expand All @@ -67,7 +68,7 @@ private void EnsureInitialized()
var fi = _directory.CombinePath(IndexInfoFile).GetBasePath().AsFile();
if (fi.Exists)
{
var csv = new CsvDb<FileInfoModel>((x, y) => x.Name.EqualIgnoreCase(y.Name))
var csv = new CsvDb<FileInfoModel>((x, y) => x != null && y != null && x.Name.EqualIgnoreCase(y.Name))
{
FileName = fi.FullName
};
Expand Down
23 changes: 12 additions & 11 deletions Stardust.Extensions/Caches/CacheFileProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,25 +27,25 @@ class CacheFileProvider : IFileProvider
private readonly ExclusionFilters _filters;

/// <summary>根目录</summary>
public String Root { get; }
public String? Root { get; }

/// <summary>服务端地址。本地文件不存在时,将从这里下载</summary>
public String[] Servers { get; set; }
public String[]? Servers { get; set; }

/// <summary>目标服务器地址。下载文件带有sh脚本时,把其中的源服务器地址替换为目标服务器地址</summary>
public String TargetServer { get; set; }
public String? TargetServer { get; set; }

/// <summary>获取服务器地址的委托。方便实时更新</summary>
public Func<String[]> GetServers { get; set; }
public Func<String[]>? GetServers { get; set; }

/// <summary>索引信息文件。列出扩展显示的文件内容</summary>
public String IndexInfoFile { get; set; }
public String? IndexInfoFile { get; set; }

/// <summary>超时时间</summary>
public TimeSpan Timeout { get; set; } = TimeSpan.FromSeconds(5);

/// <summary>APM追踪</summary>
public ITracer Tracer { get; set; }
public ITracer? Tracer { get; set; }
#endregion

/// <summary>
Expand All @@ -56,7 +56,7 @@ class CacheFileProvider : IFileProvider
/// <param name="filters"></param>
/// <exception cref="ArgumentException"></exception>
/// <exception cref="DirectoryNotFoundException"></exception>
public CacheFileProvider(String root, String server, ExclusionFilters filters = ExclusionFilters.Sensitive)
public CacheFileProvider(String root, String? server, ExclusionFilters filters = ExclusionFilters.Sensitive)
{
if (!Path.IsPathRooted(root)) throw new ArgumentException("The path must be absolute.", nameof(root));

Expand All @@ -67,8 +67,9 @@ public CacheFileProvider(String root, String server, ExclusionFilters filters =
_filters = filters;
}

private String GetFullPath(String path)
private String? GetFullPath(String path)
{
if (Root.IsNullOrEmpty()) return null;
if (PathNavigatesAboveRoot(path)) return null;

String fullPath;
Expand Down Expand Up @@ -110,13 +111,13 @@ public IFileInfo GetFileInfo(String subpath)
else if (fi.LastWriteTime.AddMonths(1) < DateTime.Now)
_ = Task.Run(() => DownloadFile(subpath, fullPath));
}
if (!fi.Exists) return new NotFoundFileInfo(subpath);
if (fi == null || !fi.Exists) return new NotFoundFileInfo(subpath);

var fileInfo = new FileInfo(fullPath);
return IsExcluded(fileInfo, _filters) ? new NotFoundFileInfo(subpath) : new PhysicalFileInfo(fileInfo);
}

async Task<String> DownloadFile(String subpath, String fullPath)
async Task<String?> DownloadFile(String subpath, String fullPath)
{
var span = DefaultSpan.Current;
var svrs = GetServers?.Invoke() ?? Servers;
Expand Down Expand Up @@ -233,7 +234,7 @@ public IDirectoryContents GetDirectoryContents(String subpath)
return NotFoundDirectoryContents.Singleton;
}

async Task<String> DownloadDirectory(String subpath, String fullPath, String[] svrs)
async Task<String?> DownloadDirectory(String subpath, String fullPath, String[] svrs)
{
var span = DefaultSpan.Current;
foreach (var item in svrs)
Expand Down
8 changes: 4 additions & 4 deletions Stardust.Extensions/Caches/FileCacheExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public static class FileCacheExtensions
/// <param name="getWhiteIP"></param>
/// <param name="uplinkServer">上级地址,用于下载本地不存在的文件</param>
/// <returns></returns>
public static void UseFileCache(this IApplicationBuilder app, String requestPath, String localPath, Func<String> getWhiteIP = null, String uplinkServer = null)
public static void UseFileCache(this IApplicationBuilder app, String requestPath, String localPath, Func<String>? getWhiteIP = null, String? uplinkServer = null)
{
var cacheRoot = localPath.GetBasePath().EnsureDirectory(false);
XTrace.WriteLine("FileCache: {0}", cacheRoot);
Expand All @@ -37,7 +37,7 @@ public static void UseFileCache(this IApplicationBuilder app, String requestPath
if (uplinkServer.IsNullOrEmpty())
{
var set = NewLife.Setting.Current;
provider.GetServers = () => set.PluginServer?.Split(",");
provider.GetServers = () => set.PluginServer?.Split(",") ?? new String[0];
}
else
{
Expand All @@ -63,7 +63,7 @@ public static void UseFileCache(this IApplicationBuilder app, String requestPath
});
}

static void OnPrepareResponse(StaticFileResponseContext ctx, Func<String> getWhiteIP)
static void OnPrepareResponse(StaticFileResponseContext ctx, Func<String>? getWhiteIP)
{
var ip = ctx.Context.GetUserHost();
if (ip.IsNullOrEmpty() || !ValidIP(ip, getWhiteIP))
Expand All @@ -74,7 +74,7 @@ static void OnPrepareResponse(StaticFileResponseContext ctx, Func<String> getWhi
}
}

static Boolean ValidIP(String ip, Func<String> getWhiteIP)
static Boolean ValidIP(String ip, Func<String>? getWhiteIP)
{
if (ip.IsNullOrEmpty()) return false;

Expand Down
4 changes: 2 additions & 2 deletions Stardust.Extensions/Caches/FileInfoModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace Stardust.Extensions.Caches;

class FileInfoModel : IFileInfo
{
public String Name { get; set; }
public String Name { get; set; } = null!;

public Boolean Exists { get; set; }

Expand All @@ -16,7 +16,7 @@ class FileInfoModel : IFileInfo

public Int64 Length { get; set; }

public String PhysicalPath { get; set; }
public String? PhysicalPath { get; set; }

public Stream CreateReadStream() => throw new NotImplementedException();
}
12 changes: 6 additions & 6 deletions Stardust.Extensions/StarFactoryExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public static class StarFactoryExtensions
/// <param name="appId">应用标识。为空时读取star.config,初始值为入口程序集名称</param>
/// <param name="secret">应用密钥。为空时读取star.config,初始值为空</param>
/// <returns></returns>
public static StarFactory AddStardust(this IServiceCollection services, String server = null, String appId = null, String secret = null)
public static StarFactory AddStardust(this IServiceCollection services, String? server = null, String? appId = null, String? secret = null)
{
var star = new StarFactory(server, appId, secret);

Expand All @@ -43,13 +43,13 @@ public static StarFactory AddStardust(this IServiceCollection services, String s
services.AddSingleton(star);
services.AddSingleton(p => star.Tracer ?? DefaultTracer.Instance ?? (DefaultTracer.Instance ??= new DefaultTracer()));
//services.AddSingleton(p => star.Config);
services.AddSingleton(p => star.Service);
services.AddSingleton(p => star.Service!);

// 替换为混合配置提供者,优先本地配置
//services.Replace(new ServiceDescriptor(typeof(IConfigProvider), p => star.Config, ServiceLifetime.Singleton));
//var old = services.LastOrDefault(e => e.ServiceType == typeof(IConfigProvider))?.ImplementationInstance as IConfigProvider;
//old ??= JsonConfigProvider.LoadAppSettings();
services.Replace(new ServiceDescriptor(typeof(IConfigProvider), p => star.GetConfig(), ServiceLifetime.Singleton));
services.Replace(new ServiceDescriptor(typeof(IConfigProvider), p => star.GetConfig()!, ServiceLifetime.Singleton));

// 分布式缓存
//services.Replace(new ServiceDescriptor(typeof(CacheService), p => new RedisCacheService(p), ServiceLifetime.Singleton));
Expand All @@ -61,7 +61,7 @@ public static StarFactory AddStardust(this IServiceCollection services, String s
services.AddSingleton(serviceProvider =>
{
var server = serviceProvider.GetRequiredService<IServer>();
return server.Features.Get<IServerAddressesFeature>();
return server.Features.Get<IServerAddressesFeature>()!;
});

return star;
Expand Down Expand Up @@ -96,12 +96,12 @@ public static IApplicationBuilder UseStardust(this IApplicationBuilder app)
/// <param name="tag">特性标签</param>
/// <param name="health">健康监测接口地址</param>
/// <returns></returns>
public static IApplicationBuilder RegisterService(this IApplicationBuilder app, String serviceName, String address = null, String tag = null, String health = null)
public static IApplicationBuilder RegisterService(this IApplicationBuilder app, String serviceName, String? address = null, String? tag = null, String? health = null)
{
var star = app.ApplicationServices.GetRequiredService<StarFactory>();
if (star == null) throw new InvalidOperationException("未注册StarFactory,需要AddStardust注册。");

if (serviceName.IsNullOrEmpty()) serviceName = AssemblyX.Entry.Name;
if (serviceName.IsNullOrEmpty()) serviceName = AssemblyX.Entry?.Name!;

// 启动的时候注册服务
var lifetime = app.ApplicationServices.GetRequiredService<IHostApplicationLifetime>();
Expand Down
6 changes: 3 additions & 3 deletions Stardust.Extensions/TracerMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class TracerMiddleware
private readonly RequestDelegate _next;

/// <summary>跟踪器</summary>
public static ITracer Tracer { get; set; }
public static ITracer? Tracer { get; set; }

/// <summary>支持作为标签数据的内容类型</summary>
public static String[] TagTypes { get; set; } = new[] {
Expand All @@ -35,7 +35,7 @@ public class TracerMiddleware
public async Task Invoke(HttpContext ctx)
{
//!! 以下代码不能封装为独立方法,因为有异步存在,代码被拆分为状态机,导致这里建立的埋点span无法关联页面接口内的下级埋点
ISpan span = null;
ISpan? span = null;
if (Tracer != null && !ctx.WebSockets.IsWebSocketRequest)
{
var action = GetAction(ctx);
Expand Down Expand Up @@ -162,7 +162,7 @@ public async Task Invoke(HttpContext ctx)
};
private static readonly String[] CubeActions = new[] { "index", "detail", "add", "edit", "delete", "deleteSelect", "deleteAll", "ExportCsv", "Info", "SetEnable", "EnableSelect", "DisableSelect", "DeleteSelect" };

private static String GetAction(HttpContext ctx)
private static String? GetAction(HttpContext ctx)
{
var p = ctx.Request.Path + "";
if (p.EndsWithIgnoreCase(ExcludeSuffixes)) return null;
Expand Down
109 changes: 54 additions & 55 deletions Stardust.Extensions/WebHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,77 +2,76 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;

namespace NewLife.Web
namespace NewLife.Web;

/// <summary>网页工具类</summary>
static class WebHelper
{
/// <summary>网页工具类</summary>
static class WebHelper
#region Http请求
/// <summary>获取原始请求Url,支持反向代理</summary>
/// <param name="request"></param>
/// <returns></returns>
public static Uri GetRawUrl(this HttpRequest request)
{
#region Http请求
/// <summary>获取原始请求Url,支持反向代理</summary>
/// <param name="request"></param>
/// <returns></returns>
public static Uri GetRawUrl(this HttpRequest request)
Uri? uri = null;

// 取请求头
if (uri == null)
{
Uri uri = null;
var url = request.GetEncodedUrl();
uri = new Uri(url);
}

// 取请求头
if (uri == null)
{
var url = request.GetEncodedUrl();
uri = new Uri(url);
}
return GetRawUrl(uri, k => request.Headers[k]);
}

return GetRawUrl(uri, k => request.Headers[k]);
}
private static Uri GetRawUrl(Uri uri, Func<String, String?> headers)
{
var str = headers("HTTP_X_REQUEST_URI");
if (str.IsNullOrEmpty()) str = headers("X-Request-Uri");

private static Uri GetRawUrl(Uri uri, Func<String, String> headers)
if (str.IsNullOrEmpty())
{
var str = headers("HTTP_X_REQUEST_URI");
if (str.IsNullOrEmpty()) str = headers("X-Request-Uri");
// 阿里云CDN默认支持 X-Client-Scheme: https
var scheme = headers("HTTP_X_CLIENT_SCHEME");
if (scheme.IsNullOrEmpty()) scheme = headers("X-Client-Scheme");

if (str.IsNullOrEmpty())
{
// 阿里云CDN默认支持 X-Client-Scheme: https
var scheme = headers("HTTP_X_CLIENT_SCHEME");
if (scheme.IsNullOrEmpty()) scheme = headers("X-Client-Scheme");
// nginx
if (scheme.IsNullOrEmpty()) scheme = headers("HTTP_X_FORWARDED_PROTO");
if (scheme.IsNullOrEmpty()) scheme = headers("X-Forwarded-Proto");

// nginx
if (scheme.IsNullOrEmpty()) scheme = headers("HTTP_X_FORWARDED_PROTO");
if (scheme.IsNullOrEmpty()) scheme = headers("X-Forwarded-Proto");
if (!scheme.IsNullOrEmpty()) str = scheme + "://" + uri.ToString().Substring("://");
}

if (!scheme.IsNullOrEmpty()) str = scheme + "://" + uri.ToString().Substring("://");
}
if (!str.IsNullOrEmpty()) uri = new Uri(uri, str);

if (!str.IsNullOrEmpty()) uri = new Uri(uri, str);
return uri;
}

return uri;
}
/// <summary>获取用户主机</summary>
/// <param name="context"></param>
/// <returns></returns>
public static String? GetUserHost(this HttpContext context)
{
var request = context.Request;

/// <summary>获取用户主机</summary>
/// <param name="context"></param>
/// <returns></returns>
public static String GetUserHost(this HttpContext context)
var str = "";
if (str.IsNullOrEmpty()) str = request.Headers["HTTP_X_FORWARDED_FOR"];
if (str.IsNullOrEmpty()) str = request.Headers["X-Real-IP"];
if (str.IsNullOrEmpty()) str = request.Headers["X-Forwarded-For"];
if (str.IsNullOrEmpty()) str = request.Headers["REMOTE_ADDR"];
//if (str.IsNullOrEmpty()) str = request.Headers["Host"];
if (str.IsNullOrEmpty())
{
var request = context.Request;

var str = "";
if (str.IsNullOrEmpty()) str = request.Headers["HTTP_X_FORWARDED_FOR"];
if (str.IsNullOrEmpty()) str = request.Headers["X-Real-IP"];
if (str.IsNullOrEmpty()) str = request.Headers["X-Forwarded-For"];
if (str.IsNullOrEmpty()) str = request.Headers["REMOTE_ADDR"];
//if (str.IsNullOrEmpty()) str = request.Headers["Host"];
if (str.IsNullOrEmpty())
var addr = context.Connection?.RemoteIpAddress;
if (addr != null)
{
var addr = context.Connection?.RemoteIpAddress;
if (addr != null)
{
if (addr.IsIPv4MappedToIPv6) addr = addr.MapToIPv4();
str = addr + "";
}
if (addr.IsIPv4MappedToIPv6) addr = addr.MapToIPv4();
str = addr + "";
}

return str;
}
#endregion

return str;
}
#endregion
}
2 changes: 1 addition & 1 deletion Stardust/AppClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -681,7 +681,7 @@ public async Task<PublishServiceInfo> RegisterAsync(String serviceName, String a
/// <param name="tag">特性标签</param>
/// <param name="health">健康监测接口地址</param>
/// <returns></returns>
public PublishServiceInfo Register(String serviceName, Func<String> addressCallback, String? tag = null, String? health = null)
public PublishServiceInfo Register(String serviceName, Func<String?> addressCallback, String? tag = null, String? health = null)
{
if (addressCallback == null) throw new ArgumentNullException(nameof(addressCallback));

Expand Down
Loading

0 comments on commit 2f6eb8d

Please sign in to comment.