Skip to content

Commit 161ad73

Browse files
MayueCifzhenlei520Mayue
authoredJan 5, 2023
Refactor/caller (#391)
* feat: Support for updatable configuration * test: Fix bad unit tests * feat: stack sdk * feat:modify for pr * feat:udpate unit test * feat:udpate unit test * feat:update parameter name Co-authored-by: zhenlei520 <wangzhenlei520@gmail.com> Co-authored-by: Mayue <mayue@lonsid.cn>
1 parent b0ec3d2 commit 161ad73

File tree

14 files changed

+132
-61
lines changed

14 files changed

+132
-61
lines changed
 

‎src/Contrib/Data/Orm/EFCore/Masa.Contrib.Data.EFCore.Tests/DbContextTest.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ public async Task TestDisabledSoftDelete()
204204
var dataFilter = serviceProvider.GetRequiredService<IDataFilter>();
205205
using (dataFilter.Disable<ISoftDelete>())
206206
{
207-
var count = await dbContext.Set<Student>().IgnoreQueryFilters().CountAsync();
207+
var count = await dbContext.Set<Student>().CountAsync();
208208
Assert.IsTrue(count == 1);
209209
}
210210
}

‎src/Contrib/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/CallerOptionsExtensions.cs

+44-17
Original file line numberDiff line numberDiff line change
@@ -6,33 +6,60 @@ namespace Masa.Contrib.Service.Caller.HttpClient;
66
public static class CallerOptionsExtensions
77
{
88
public static IHttpClientBuilder UseHttpClient(this CallerOptions callerOptions,
9-
Func<MasaHttpClientBuilder>? clientBuilder = null)
10-
=> callerOptions.UseHttpClient(Microsoft.Extensions.Options.Options.DefaultName, clientBuilder);
9+
Func<MasaHttpClientBuilder>? clientBuilder = null,
10+
bool alwaysGetNewestHttpClient = false)
11+
=> callerOptions.UseHttpClient(Microsoft.Extensions.Options.Options.DefaultName, clientBuilder, alwaysGetNewestHttpClient);
1112

1213
public static IHttpClientBuilder UseHttpClient(this CallerOptions callerOptions,
1314
string name,
14-
Func<MasaHttpClientBuilder>? clientBuilder = null)
15+
Func<MasaHttpClientBuilder>? clientBuilder = null,
16+
bool alwaysGetNewestHttpClient = false)
1517
{
16-
var builder = clientBuilder == null ? new MasaHttpClientBuilder() : clientBuilder.Invoke();
17-
var httpClientBuilder = callerOptions.Services.AddHttpClient(name, httpClient
18-
=> builder.ConfigureHttpClient(httpClient));
19-
20-
AddCallerExtensions.AddCaller(callerOptions, name, serviceProvider
21-
=> new HttpClientCaller(serviceProvider, name, builder.Prefix));
22-
return httpClientBuilder;
18+
return callerOptions.UseHttpClient(name, masaHttpClientBuilder =>
19+
{
20+
var builder = clientBuilder == null ? new MasaHttpClientBuilder() : clientBuilder.Invoke();
21+
masaHttpClientBuilder.BaseAddress = builder.BaseAddress;
22+
masaHttpClientBuilder.Prefix = builder.Prefix;
23+
masaHttpClientBuilder.Configure = builder.Configure;
24+
}, alwaysGetNewestHttpClient);
2325
}
2426

2527
public static IHttpClientBuilder UseHttpClient(this CallerOptions callerOptions,
26-
Action<MasaHttpClientBuilder>? clientBuilder)
27-
=> callerOptions.UseHttpClient(Microsoft.Extensions.Options.Options.DefaultName, clientBuilder);
28+
Action<MasaHttpClientBuilder>? clientBuilder,
29+
bool alwaysGetNewestHttpClient = false)
30+
=> callerOptions.UseHttpClient(Microsoft.Extensions.Options.Options.DefaultName, clientBuilder, alwaysGetNewestHttpClient);
2831

2932
public static IHttpClientBuilder UseHttpClient(this CallerOptions callerOptions,
3033
string name,
31-
Action<MasaHttpClientBuilder>? clientBuilder)
34+
Action<MasaHttpClientBuilder>? clientBuilder,
35+
bool alwaysGetNewestHttpClient = false)
3236
{
33-
MasaHttpClientBuilder builder = new MasaHttpClientBuilder();
34-
clientBuilder?.Invoke(builder);
35-
36-
return callerOptions.UseHttpClient(name, () => builder);
37+
if (alwaysGetNewestHttpClient)
38+
{
39+
var httpClientBuilder = callerOptions.Services.AddHttpClient(name);
40+
AddCallerExtensions.AddCaller(callerOptions, name, serviceProvider
41+
=>
42+
{
43+
var masaHttpClientBuilder = new MasaHttpClientBuilder();
44+
clientBuilder?.Invoke(masaHttpClientBuilder);
45+
var httpClient = serviceProvider.GetRequiredService<IHttpClientFactory>().CreateClient(name);
46+
masaHttpClientBuilder.ConfigureHttpClient(httpClient);
47+
return new HttpClientCaller(httpClient, serviceProvider, masaHttpClientBuilder.Prefix);
48+
});
49+
return httpClientBuilder;
50+
}
51+
else
52+
{
53+
var masaHttpClientBuilder = new MasaHttpClientBuilder();
54+
clientBuilder?.Invoke(masaHttpClientBuilder);
55+
var httpClientBuilder = callerOptions.Services.AddHttpClient(name, httpClient => masaHttpClientBuilder.ConfigureHttpClient(httpClient));
56+
AddCallerExtensions.AddCaller(callerOptions, name, serviceProvider
57+
=>
58+
{
59+
var httpClient = serviceProvider.GetRequiredService<IHttpClientFactory>().CreateClient(name);
60+
return new HttpClientCaller(httpClient, serviceProvider, masaHttpClientBuilder.Prefix);
61+
});
62+
return httpClientBuilder;
63+
}
3764
}
3865
}

‎src/Contrib/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/HttpClientCaller.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@ public class HttpClientCaller : AbstractCaller
99
private readonly string _prefix;
1010
private readonly bool _prefixIsNullOrEmpty;
1111

12-
public HttpClientCaller(IServiceProvider serviceProvider,
13-
string name,
12+
public HttpClientCaller(System.Net.Http.HttpClient httpClient,
13+
IServiceProvider serviceProvider,
1414
string prefix)
1515
: base(serviceProvider)
1616
{
17-
_httpClient = serviceProvider.GetRequiredService<IHttpClientFactory>().CreateClient(name);
17+
_httpClient = httpClient;
1818
_prefix = prefix;
1919
_prefixIsNullOrEmpty = string.IsNullOrEmpty(_prefix);
2020
}

‎src/Contrib/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/HttpClientCallerBase.cs

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Copyright (c) MASA Stack All rights reserved.
1+
// Copyright (c) MASA Stack All rights reserved.
22
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
33

44
namespace Masa.Contrib.Service.Caller.HttpClient;
@@ -9,6 +9,8 @@ public abstract class HttpClientCallerBase : CallerBase
99

1010
protected virtual string Prefix { get; set; } = string.Empty;
1111

12+
protected virtual bool IsSupportUpdate { get; set; } = false;
13+
1214
protected HttpClientCallerBase()
1315
{
1416

@@ -27,7 +29,7 @@ protected virtual IHttpClientBuilder UseHttpClient()
2729
httpClientBuilder.Prefix = Prefix;
2830
httpClientBuilder.BaseAddress = BaseAddress;
2931
httpClientBuilder.Configure = ConfigureHttpClient;
30-
});
32+
}, IsSupportUpdate);
3133
}
3234

3335
protected virtual void ConfigureHttpClient(System.Net.Http.HttpClient httpClient)

‎src/Contrib/Service/Caller/Masa.Contrib.Service.Caller.HttpClient/MasaHttpClientBuilder.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ public MasaHttpClientBuilder(string baseAddress, string prefix, Action<System.Ne
3535
Configure = configure;
3636
}
3737

38-
public virtual void ConfigureHttpClient(System.Net.Http.HttpClient httpClient)
38+
internal void ConfigureHttpClient(System.Net.Http.HttpClient httpClient)
3939
{
4040
if (!string.IsNullOrEmpty(BaseAddress))
4141
httpClient.BaseAddress = new Uri(BaseAddress);

‎src/Contrib/Service/Caller/Tests/Masa.Contrib.Service.Caller.Tests/CallerTest.cs

+1-4
Original file line numberDiff line numberDiff line change
@@ -252,12 +252,9 @@ public async Task TestConfigRequestMessageByHttpClientCallerAsync()
252252
})
253253
.Verifiable();
254254

255-
httpClientFactory.Setup(factory => factory.CreateClient(It.IsAny<string>())).Returns(magicHttpClient);
256-
services.AddSingleton(httpClientFactory.Object);
257255
var serviceProvider = services.BuildServiceProvider();
258-
string name = "<Custom-Alias>";
259256
string prefix = "<Replace-Your-Service-Prefix>";
260-
var caller = new HttpClientCaller(serviceProvider, name, prefix);
257+
var caller = new HttpClientCaller(magicHttpClient, serviceProvider, prefix);
261258

262259
var excuteCount = 0;
263260
caller.ConfigRequestMessage(httpRequestMessage =>

‎src/Contrib/Service/Caller/Tests/Masa.Contrib.Service.Caller.Tests/CustomHttpClientCaller.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
// Copyright (c) MASA Stack All rights reserved.
1+
// Copyright (c) MASA Stack All rights reserved.
22
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
33

44
namespace Masa.Contrib.Service.Caller.Tests;
55

66
public class CustomHttpClientCaller : HttpClientCaller
77
{
8-
public CustomHttpClientCaller(IServiceProvider serviceProvider, string name, string baseApi)
9-
: base(serviceProvider, name, baseApi)
8+
public CustomHttpClientCaller(System.Net.Http.HttpClient httpClient, IServiceProvider serviceProvider, string baseApi)
9+
: base(httpClient, serviceProvider, baseApi)
1010
{
1111
}
1212

‎src/Contrib/Service/Caller/Tests/Masa.Contrib.Service.Caller.Tests/HttpClientCallerTest.cs

+33-10
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public void TestGetRequestUri(string prefix, string methods, string result)
3131
var services = new ServiceCollection();
3232
services.AddCaller(opt => opt.UseHttpClient());
3333
var serviceProvider = services.BuildServiceProvider();
34-
var caller = new CustomHttpClientCaller(serviceProvider, string.Empty, prefix);
34+
var caller = new CustomHttpClientCaller(serviceProvider.GetRequiredService<IHttpClientFactory>().CreateClient(), serviceProvider, prefix);
3535
Assert.IsTrue(caller.GetResult(methods) == result);
3636
}
3737

@@ -63,12 +63,9 @@ public async Task TestRequestDataIsXmlAsync()
6363
})
6464
.Verifiable();
6565

66-
httpClientFactory.Setup(factory => factory.CreateClient(It.IsAny<string>())).Returns(magicHttpClient);
67-
services.AddSingleton(httpClientFactory.Object);
6866
var serviceProvider = services.BuildServiceProvider();
69-
string name = "<Custom-Alias>";
7067
string prefix = "<Replace-Your-Service-Prefix>";
71-
var caller = new HttpClientCaller(serviceProvider, name, prefix);
68+
var caller = new HttpClientCaller(magicHttpClient, serviceProvider, prefix);
7269

7370
var res = await caller.PostAsync<BaseResponse>("Hello", new RegisterUser("Jim", "123456"));
7471
Assert.IsNotNull(res);
@@ -92,7 +89,6 @@ public async Task TestRequestMessageReturnOnceAsync()
9289
}).Verifiable();
9390
services.AddSingleton(_ => requestMessage.Object);
9491
services.AddSingleton<IResponseMessage, DefaultXmlResponseMessage>();
95-
Mock<IHttpClientFactory> httpClientFactory = new();
9692
var handlerMock = new Mock<HttpMessageHandler>();
9793
var magicHttpClient = new System.Net.Http.HttpClient(handlerMock.Object)
9894
{
@@ -113,12 +109,9 @@ public async Task TestRequestMessageReturnOnceAsync()
113109
})
114110
.Verifiable();
115111

116-
httpClientFactory.Setup(factory => factory.CreateClient(It.IsAny<string>())).Returns(magicHttpClient);
117-
services.AddSingleton(httpClientFactory.Object);
118112
var serviceProvider = services.BuildServiceProvider();
119-
string name = "<Custom-Alias>";
120113
string prefix = "<Replace-Your-Service-Prefix>";
121-
var caller = new HttpClientCaller(serviceProvider, name, prefix);
114+
var caller = new HttpClientCaller(magicHttpClient, serviceProvider, prefix);
122115

123116
var res = await caller.PostAsync<BaseResponse>("Hello", registerUser);
124117
Assert.IsNotNull(res);
@@ -292,4 +285,34 @@ public async Task TestResponseIsDateTimeAsync()
292285
Assert.IsNotNull(res2);
293286
Assert.IsTrue(res2.ToString("yyyy-MM-dd HH:mm:ss") == date.ToString("yyyy-MM-dd HH:mm:ss"));
294287
}
288+
289+
[TestMethod]
290+
public void TestChangeableBaseAddress()
291+
{
292+
var services = new ServiceCollection();
293+
var key = "caller_test";
294+
var baiduAddress = "http://www.baidu.com";
295+
var githubAddress = "http://github.com";
296+
Environment.SetEnvironmentVariable(key, baiduAddress);
297+
var index = 0;
298+
services.AddCaller(options =>
299+
{
300+
options.UseHttpClient(clientBuilder =>
301+
{
302+
Assert.AreEqual(string.Empty, clientBuilder.BaseAddress);
303+
clientBuilder.BaseAddress = Environment.GetEnvironmentVariable(key)!;
304+
if (index == 0) Assert.AreEqual(baiduAddress, clientBuilder.BaseAddress.ToString());
305+
else if (index == 1) Assert.AreEqual(githubAddress, clientBuilder.BaseAddress.ToString());
306+
}, true);
307+
});
308+
var serviceProvider = services.BuildServiceProvider();
309+
start:
310+
using (var scope = serviceProvider.CreateScope())
311+
{
312+
var caller = scope.ServiceProvider.GetRequiredService<ICaller>();
313+
Environment.SetEnvironmentVariable(key, githubAddress);
314+
index++;
315+
if (index == 1) goto start;
316+
}
317+
}
295318
}

‎src/Contrib/StackSdks/Masa.Contrib.StackSdks.Auth/ServiceCollectionExtensions.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -18,21 +18,21 @@ public static IServiceCollection AddAuthClient(this IServiceCollection services,
1818

1919
public static IServiceCollection AddAuthClient(this IServiceCollection services, string authServiceBaseAddress, RedisConfigurationOptions redisOptions)
2020
{
21-
ArgumentNullException.ThrowIfNull(authServiceBaseAddress, nameof(authServiceBaseAddress));
21+
MasaArgumentException.ThrowIfNullOrEmpty(authServiceBaseAddress);
2222

2323
return services.AddAuthClient(callerOptions =>
2424
{
2525
callerOptions.UseHttpClient(DEFAULT_CLIENT_NAME, builder =>
2626
{
27-
builder.Configure = opt => opt.BaseAddress = new Uri(authServiceBaseAddress);
27+
builder.BaseAddress = authServiceBaseAddress;
2828
});
2929
callerOptions.DisableAutoRegistration = true;
3030
}, redisOptions);
3131
}
3232

3333
public static IServiceCollection AddAuthClient(this IServiceCollection services, Action<CallerOptions> callerOptions, RedisConfigurationOptions redisOptions)
3434
{
35-
ArgumentNullException.ThrowIfNull(callerOptions, nameof(callerOptions));
35+
MasaArgumentException.ThrowIfNull(callerOptions);
3636
if (services.All(service => service.ServiceType != typeof(IMultiEnvironmentUserContext)))
3737
throw new Exception("Please add IMultiEnvironmentUserContext first.");
3838

‎src/Contrib/StackSdks/Masa.Contrib.StackSdks.Mc/ServiceCollectionExtensions.cs

+16-5
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,7 @@ public static class ServiceCollectionExtensions
88
{
99
public static IServiceCollection AddMcClient(this IServiceCollection services, string mcServiceBaseAddress)
1010
{
11-
if (string.IsNullOrWhiteSpace(mcServiceBaseAddress))
12-
{
13-
throw new ArgumentNullException(nameof(mcServiceBaseAddress));
14-
}
11+
MasaArgumentException.ThrowIfNullOrEmpty(mcServiceBaseAddress);
1512

1613
return services.AddMcClient(callerOptions =>
1714
{
@@ -23,9 +20,23 @@ public static IServiceCollection AddMcClient(this IServiceCollection services, s
2320
});
2421
}
2522

23+
public static IServiceCollection AddMcClient(this IServiceCollection services, Func<Task<string>> mcServiceBaseAddressFunc)
24+
{
25+
MasaArgumentException.ThrowIfNull(mcServiceBaseAddressFunc);
26+
27+
return services.AddMcClient(callerOptions =>
28+
{
29+
callerOptions.UseHttpClient(DEFAULT_CLIENT_NAME, async builder =>
30+
{
31+
builder.BaseAddress = await mcServiceBaseAddressFunc.Invoke();
32+
}, true).AddHttpMessageHandler<HttpClientAuthorizationDelegatingHandler>();
33+
callerOptions.DisableAutoRegistration = true;
34+
});
35+
}
36+
2637
public static IServiceCollection AddMcClient(this IServiceCollection services, Action<CallerOptions> callerOptions)
2738
{
28-
ArgumentNullException.ThrowIfNull(callerOptions, nameof(callerOptions));
39+
MasaArgumentException.ThrowIfNull(callerOptions);
2940

3041
if (services.Any(service => service.ServiceType == typeof(IMcClient)))
3142
return services;

‎src/Contrib/StackSdks/Masa.Contrib.StackSdks.Pm/ServiceCollectionExtensions.cs

+18-7
Original file line numberDiff line numberDiff line change
@@ -8,31 +8,42 @@ public static class ServiceCollectionExtensions
88
{
99
public static IServiceCollection AddPmClient(this IServiceCollection services, string pmServiceBaseAddress)
1010
{
11-
if (string.IsNullOrWhiteSpace(pmServiceBaseAddress))
12-
{
13-
throw new ArgumentNullException(nameof(pmServiceBaseAddress));
14-
}
11+
MasaArgumentException.ThrowIfNullOrEmpty(pmServiceBaseAddress);
1512

1613
return services.AddPmClient(callerOptions =>
1714
{
1815
callerOptions.UseHttpClient(DEFAULT_CLIENT_NAME, builder =>
1916
{
20-
builder.Configure = opt => opt.BaseAddress = new Uri(pmServiceBaseAddress);
17+
builder.BaseAddress = pmServiceBaseAddress;
2118
});
2219
callerOptions.DisableAutoRegistration = true;
2320
});
2421
}
2522

23+
public static IServiceCollection AddPmClient(this IServiceCollection services, Func<Task<string>> pmServiceBaseAddressFunc)
24+
{
25+
MasaArgumentException.ThrowIfNull(pmServiceBaseAddressFunc);
26+
27+
return services.AddPmClient(callerOptions =>
28+
{
29+
callerOptions.UseHttpClient(DEFAULT_CLIENT_NAME, async builder =>
30+
{
31+
builder.BaseAddress = await pmServiceBaseAddressFunc.Invoke();
32+
}, true);
33+
callerOptions.DisableAutoRegistration = true;
34+
});
35+
}
36+
2637
public static IServiceCollection AddPmClient(this IServiceCollection services, Action<CallerOptions> callerOptions)
2738
{
28-
ArgumentNullException.ThrowIfNull(callerOptions, nameof(callerOptions));
39+
MasaArgumentException.ThrowIfNull(callerOptions);
2940

3041
if (services.Any(service => service.ServiceType == typeof(IPmClient)))
3142
return services;
3243

3344
services.AddCaller(callerOptions.Invoke);
3445

35-
services.AddSingleton<IPmClient>(serviceProvider =>
46+
services.AddScoped<IPmClient>(serviceProvider =>
3647
{
3748
var callProvider = serviceProvider.GetRequiredService<ICallerFactory>().Create(DEFAULT_CLIENT_NAME);
3849
var pmCaching = new PmClient(callProvider);

‎src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Auth.Tests/AuthClientTest.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,14 @@ public void TestAddAuthClientNoAddMasaIdentity()
2929
public void TestAddAuthClientShouldThrowArgumentNullException()
3030
{
3131
var services = new ServiceCollection();
32-
Assert.ThrowsException<ArgumentNullException>(() => services.AddAuthClient(authServiceBaseAddress: null!, new()));
32+
Assert.ThrowsException<MasaArgumentException>(() => services.AddAuthClient(authServiceBaseAddress: null!, new()));
3333
}
3434

3535
[TestMethod]
3636
public void TestAddAuthClientShouldThrowArgumentNullException2()
3737
{
3838
var services = new ServiceCollection();
39-
Assert.ThrowsException<ArgumentNullException>(() => services.AddAuthClient(callerOptions: null!, new()));
39+
Assert.ThrowsException<MasaArgumentException>(() => services.AddAuthClient(callerOptions: null!, new()));
4040
}
4141
}
4242

‎src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Mc.Tests/McClientTest.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,13 @@ public void TestAddMcClient()
2020
public void TestAddMcClientShouldThrowArgumentNullException()
2121
{
2222
var services = new ServiceCollection();
23-
Assert.ThrowsException<ArgumentNullException>(() => services.AddMcClient(mcServiceBaseAddress: null!));
23+
Assert.ThrowsException<MasaArgumentException>(() => services.AddMcClient(mcServiceBaseAddress: null!));
2424
}
2525

2626
[TestMethod]
2727
public void TestAddMcClientShouldThrowArgumentNullException2()
2828
{
2929
var services = new ServiceCollection();
30-
Assert.ThrowsException<ArgumentNullException>(() => services.AddMcClient(callerOptions: null!));
30+
Assert.ThrowsException<MasaArgumentException>(() => services.AddMcClient(callerOptions: null!));
3131
}
3232
}

‎src/Contrib/StackSdks/Tests/Masa.Contrib.StackSdks.Pm.Tests/PmClientTest.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ public void TestAddPmClientShouldThrowArgumentNullException()
4141
{
4242
var services = new ServiceCollection();
4343

44-
Assert.ThrowsException<ArgumentNullException>(() => services.AddPmClient(""));
44+
Assert.ThrowsException<MasaArgumentException>(() => services.AddPmClient(""));
4545
}
4646

4747
[TestMethod]

0 commit comments

Comments
 (0)
Please sign in to comment.