22using System . Text . Json ;
33using AStar . Dev . Admin . Api . Client . Sdk . Models ;
44using AStar . Dev . Api . HealthChecks ;
5- using Microsoft . Extensions . Logging ;
5+ using AStar . Dev . Functional . Extensions ;
6+ using AStar . Dev . Logging . Extensions ;
67using Microsoft . Identity . Web ;
78
89namespace AStar . Dev . Admin . Api . Client . Sdk . AdminApi ;
910
1011/// <summary>
1112/// The <see href="AdminApiClient"></see> class.
1213/// </summary>
13- public sealed class AdminApiClient ( HttpClient httpClient , ITokenAcquisition tokenAcquisitionService , ILogger < AdminApiClient > logger ) : IApiClient
14+ public sealed class AdminApiClient ( HttpClient httpClient , ITokenAcquisition tokenAcquisitionService , ILoggerAstar < AdminApiClient > logger ) : IApiClient
1415{
1516 private static readonly JsonSerializerOptions JsonSerializerOptions = new ( JsonSerializerDefaults . Web ) ;
1617
1718 /// <inheritdoc />
1819 public async Task < HealthStatusResponse > GetHealthAsync ( CancellationToken cancellationToken = default )
1920 {
20- logger . LogInformation ( "Checking the {ApiName} Health Status." , Constants . ApiName ) ;
21+ logger . LogHealthCheckStart ( Constants . ApiName ) ;
2122
2223 try
2324 {
24- logger . LogInformation ( "Checking the {ApiName} Health Status." , Constants . ApiName ) ;
25+ var response = await httpClient . GetAsync ( "/health/ready" , cancellationToken ) ;
2526
26- HttpResponseMessage response = await httpClient . GetAsync ( "/health/ready" , cancellationToken ) ;
27+ return response . IsSuccessStatusCode
28+ ? ( await JsonSerializer . DeserializeAsync < HealthStatusResponse > ( await response . Content . ReadAsStreamAsync ( cancellationToken ) , JsonSerializerOptions , cancellationToken ) ) !
29+ : ReturnLoggedFailure ( response ) ;
30+ }
31+ catch ( HttpRequestException ex )
32+ {
33+ logger . LogException ( ex ) ;
34+
35+ return new ( ) { Status = $ "Could not get a response from the { Constants . ApiName } ." } ;
36+ }
37+ }
38+
39+ /// <inheritdoc />
40+ public async Task < Result < string , HealthStatusResponse > > GetHealthCheckAsync ( CancellationToken cancellationToken = new ( ) )
41+ {
42+ logger . LogHealthCheckStart ( Constants . ApiName ) ;
43+
44+ try
45+ {
46+ var response = await httpClient . GetAsync ( "/health/ready" , cancellationToken ) ;
2747
2848 return response . IsSuccessStatusCode
2949 ? ( await JsonSerializer . DeserializeAsync < HealthStatusResponse > ( await response . Content . ReadAsStreamAsync ( cancellationToken ) , JsonSerializerOptions , cancellationToken ) ) !
3050 : ReturnLoggedFailure ( response ) ;
3151 }
3252 catch ( HttpRequestException ex )
3353 {
34- logger . LogError ( 500 , ex , "Error: {ErrorMessage}" , ex . Message ) ;
54+ logger . LogException ( ex ) ;
3555
36- return new ( ) { Status = $ "Could not get a response from the { Constants . ApiName } .", } ;
56+ return new HealthStatusResponse { Status = $ "Could not get a response from the { Constants . ApiName } ." } ;
3757 }
3858 }
3959
4060 /// <summary>
4161 /// The GetSiteConfigurationAsync method will get the User Configuration.
4262 /// </summary>
4363 /// <returns>The Site Configuration - populated or empty</returns>
44- public async Task < IEnumerable < SiteConfiguration > > GetSiteConfigurationAsync ( )
64+ public async Task < Result < string , IEnumerable < SiteConfiguration > > > GetSiteConfigurationAsync ( )
4565 {
46- string token = await tokenAcquisitionService . GetAccessTokenForUserAsync ( [ "api://2ca26585-5929-4aae-86a7-a00c3fc2d061/ToDoList.Write" , ] ) ;
66+ var token = await tokenAcquisitionService . GetAccessTokenForUserAsync ( [ "api://2ca26585-5929-4aae-86a7-a00c3fc2d061/ToDoList.Write" ] ) ;
4767
48- // logger.LogDebug("Token: {Token}", token);
49- httpClient . DefaultRequestHeaders . Authorization = new ( "Bearer" , token ) ;
50- HttpResponseMessage response = await httpClient . GetAsync ( "site-configurations?version=1.0" ) ;
68+ httpClient . AddBearerToken ( token ) ;
69+ var response = await GetSafelyAsync < IEnumerable < SiteConfiguration > > ( "site-configurations?version=1.0" ) ;
5170
52- return ( await response . Content . ReadFromJsonAsync < IEnumerable < SiteConfiguration > > ( ) ) ! ;
71+ return response . IsSuccess
72+ ? response
73+ : ReturnLoggedFailure ( "GetSiteConfiguration" , response . Error ) ;
74+ }
75+
76+ private async Task < Result < string , TResponse > > GetSafelyAsync < TResponse > ( string uri )
77+ {
78+ try
79+ {
80+ var response = await httpClient . GetAsync ( uri ) ;
81+
82+ if ( response . IsSuccessStatusCode )
83+ {
84+ return ( await response . Content . ReadFromJsonAsync < TResponse > ( ) ) ! ;
85+ }
86+
87+ logger . LogApiCallFailed ( "AStar.Dev.Admin.Api" , uri , $ "StatusCode: { response . StatusCode } , ResponseCode: { response . ReasonPhrase } ") ;
88+
89+ return Result < string , TResponse > . Failure ( $ "Call to { uri } failed with { ( response . ReasonPhrase ?? response ? . ReasonPhrase ) } ") ! ;
90+ }
91+ catch ( Exception ex )
92+ {
93+ logger . LogException ( ex ) ;
94+
95+ return Result < string , TResponse > . Failure ( ex . Message ) ! ;
96+ }
5397 }
5498
5599 private HealthStatusResponse ReturnLoggedFailure ( HttpResponseMessage response )
56100 {
57- logger . LogInformation ( "The {ApiName} Health failed - {FailureReason}." , Constants . ApiName , response . ReasonPhrase ) ;
101+ logger . LogHealthCheckFailure ( Constants . ApiName , response . ReasonPhrase ?? "Failure reason not known" ) ;
102+
103+ return new ( ) { Status = $ "Health Check failed - { response . ReasonPhrase } ." } ;
104+ }
105+
106+ private string ReturnLoggedFailure ( string endpointName , string ? reasonPhrase )
107+ {
108+ logger . LogApiCallFailed ( Constants . ApiName , endpointName , reasonPhrase ?? "Failure reason not known" ) ;
58109
59- return new ( ) { Status = $ "Health Check failed - { response . ReasonPhrase } .", } ;
110+ return $ "Call to { endpointName } failed - { reasonPhrase } .";
60111 }
61112
62113 //
@@ -134,4 +185,4 @@ private HealthStatusResponse ReturnLoggedFailure(HttpResponseMessage response)
134185 // .WebDeserialisationSettings)
135186 // : new UserConfiguration();
136187 // }
137- }
188+ }
0 commit comments