Skip to content

Commit 7c072a2

Browse files
Updated requested code changes
1 parent b3fe033 commit 7c072a2

File tree

3 files changed

+49
-11
lines changed

3 files changed

+49
-11
lines changed

src/LCT.APICommunications/ApiConstant.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
// SPDX-License-Identifier: MIT
55
// --------------------------------------------------------------------------------------------------------------------
66

7+
using System.Collections.Generic;
8+
79
namespace LCT.APICommunications
810
{
911
/// <summary>
@@ -74,8 +76,6 @@ public static class ApiConstant
7476
public const string ArtifactoryRepoName = "ArtifactoryRepoName";
7577
public const string JfrogArtifactoryApiSearchAql = $"/api/search/aql";
7678
public const int APIRetryCount = 3;
77-
public const int APIRetryIntervalFirst = 5; // in seconds
78-
public const int APIRetryIntervalSecond = 10; // in seconds
79-
public const int APIRetryIntervalThird = 30; // in seconds
79+
public static readonly List<int> APIRetryIntervals = [5, 10, 30]; // in seconds
8080
}
8181
}

src/LCT.APICommunications/RetryHttpClientHandler.cs

+28-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using log4net;
22
using Polly;
33
using System;
4+
using System.Linq;
45
using System.Net;
56
using System.Net.Http;
67
using System.Reflection;
@@ -12,6 +13,7 @@ public class RetryHttpClientHandler : DelegatingHandler
1213
{
1314
private readonly AsyncPolicy<HttpResponseMessage> _retryPolicy;
1415
private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
16+
private bool _initialRetryLogged = false;
1517
public RetryHttpClientHandler()
1618
{
1719
// Define the retry policy (retry on 5xx, 408, and transient errors)
@@ -28,15 +30,35 @@ public RetryHttpClientHandler()
2830
onRetry: (outcome, timespan, attempt, context) =>
2931
{
3032
Logger.Debug($"Retry attempt {attempt} due to: {(outcome.Exception != null ? outcome.Exception.Message : $"{outcome.Result.StatusCode}")}");
31-
Logger.Warn($"Retry attempt {attempt} will be triggered in {timespan.TotalSeconds} seconds due to: {(outcome.Exception != null ? outcome.Exception.Message : $"{outcome.Result.StatusCode}")}");
33+
if (!_initialRetryLogged && context["LogWarnings"] as bool? != false)
34+
{
35+
Logger.Warn($"Retry attempt triggered due to: {(outcome.Exception != null ? outcome.Exception.Message : $"{outcome.Result.StatusCode}")}");
36+
}
37+
context["RetryAttempt"] = attempt;
38+
_initialRetryLogged = true;
39+
3240
});
3341
}
3442
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
3543
{
36-
return await _retryPolicy.ExecuteAsync(async () =>
44+
var context = new Context
45+
{
46+
["LogWarnings"] = !request.Headers.TryGetValues("LogWarnings", out var logWarningsValues) || !bool.TryParse(logWarningsValues.FirstOrDefault(), out var logWarnings) || logWarnings
47+
};
48+
49+
var response = await _retryPolicy.ExecuteAsync(async (ctx) =>
3750
{
3851
return await base.SendAsync(request, cancellationToken); // Pass the request to the next handler (HttpClient)
39-
});
52+
}, context);
53+
54+
if (_initialRetryLogged)
55+
{
56+
var attempt = context.ContainsKey("RetryAttempt") ? context["RetryAttempt"] : 0;
57+
Logger.Debug($"Retry attempt successful after {attempt} attempts.");
58+
_initialRetryLogged = false;
59+
}
60+
61+
return response;
4062
}
4163
public static async Task ExecuteWithRetryAsync(Func<Task> action)
4264
{
@@ -53,11 +75,10 @@ public static async Task ExecuteWithRetryAsync(Func<Task> action)
5375
}
5476
private static TimeSpan GetRetryInterval(int attempt)
5577
{
56-
// Define retry intervals as constants or values
57-
var retryIntervals = new[] { ApiConstant.APIRetryIntervalFirst, ApiConstant.APIRetryIntervalSecond, ApiConstant.APIRetryIntervalThird }; // Retry intervals for 1st, 2nd, and 3rd attempts
58-
if (attempt >= 1 && attempt <= retryIntervals.Length)
59-
return TimeSpan.FromSeconds(retryIntervals[attempt - 1]);
78+
if (attempt >= 1 && attempt <= ApiConstant.APIRetryIntervals.Count)
79+
return TimeSpan.FromSeconds(ApiConstant.APIRetryIntervals[attempt - 1]);
6080
return TimeSpan.Zero; // Default if out of range
6181
}
82+
6283
}
6384
}

src/LCT.APICommunications/SW360Apicommunication.cs

+18-1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,13 @@
2121

2222
namespace LCT.APICommunications
2323
{
24+
public static class HttpClientExtensions
25+
{
26+
public static void SetLogWarnings(this HttpClient client, bool logWarnings)
27+
{
28+
client.DefaultRequestHeaders.Add("LogWarnings", logWarnings.ToString());
29+
}
30+
}
2431
/// <summary>
2532
/// Communicatest with SW360 API
2633
/// </summary>
@@ -98,7 +105,7 @@ public async Task<HttpResponseMessage> GetProjectsByTag(string projectTag)
98105

99106
public async Task<HttpResponseMessage> GetProjectById(string projectId)
100107
{
101-
HttpClient httpClient = GetHttpClient();
108+
HttpClient httpClient = GetHttpClient();
102109
HttpResponseMessage obj = new HttpResponseMessage();
103110
var result = obj;
104111
string projectsByTagUrl = $"{sw360ProjectsApi}/{projectId}";
@@ -163,12 +170,14 @@ public async Task<string> GetReleases()
163170
public async Task<string> TriggerFossologyProcess(string releaseId, string sw360link)
164171
{
165172
HttpClient httpClient = GetHttpClient();
173+
httpClient.SetLogWarnings(false);
166174
string url = $"{sw360ReleaseApi}/{releaseId}{ApiConstant.FossTriggerAPIPrefix}{sw360link}{ApiConstant.FossTriggerAPISuffix}";
167175
return await httpClient.GetStringAsync(url);
168176
}
169177
public async Task<HttpResponseMessage> CheckFossologyProcessStatus(string link)
170178
{
171179
HttpClient httpClient = GetHttpClient();
180+
httpClient.SetLogWarnings(false);
172181
return await httpClient.GetAsync(link);
173182
}
174183
public async Task<string> GetComponents()
@@ -187,13 +196,15 @@ public async Task<HttpResponseMessage> GetReleaseByExternalId(string purlId, str
187196
public async Task<HttpResponseMessage> GetComponentByExternalId(string purlId, string externalIdKey = "")
188197
{
189198
HttpClient httpClient = GetHttpClient();
199+
httpClient.SetLogWarnings(false);
190200
string componentByExternalIdUrl = $"{sw360ComponentByExternalId}{externalIdKey}{purlId}";
191201
return await httpClient.GetAsync(componentByExternalIdUrl);
192202
}
193203

194204
public async Task<HttpResponseMessage> GetReleaseById(string releaseId)
195205
{
196206
HttpClient httpClient = GetHttpClient();
207+
httpClient.SetLogWarnings(false);
197208
string url = $"{sw360ReleaseApi}/{releaseId}";
198209
return await httpClient.GetAsync(url);
199210
}
@@ -224,18 +235,21 @@ public async Task<HttpResponseMessage> UpdateLinkedRelease(string projectId, str
224235
public async Task<HttpResponseMessage> CreateComponent(CreateComponent createComponentContent)
225236
{
226237
HttpClient httpClient = GetHttpClient();
238+
httpClient.SetLogWarnings(false);
227239
return await httpClient.PostAsJsonAsync(sw360ComponentApi, createComponentContent);
228240
}
229241

230242
public async Task<HttpResponseMessage> CreateRelease(Releases createReleaseContent)
231243
{
232244
HttpClient httpClient = GetHttpClient();
245+
httpClient.SetLogWarnings(false);
233246
return await httpClient.PostAsJsonAsync(sw360ReleaseApi, createReleaseContent);
234247
}
235248

236249
public async Task<string> GetReleaseOfComponentById(string componentId)
237250
{
238251
HttpClient httpClient = GetHttpClient();
252+
httpClient.SetLogWarnings(false);
239253
string componentUrl = $"{sw360ComponentApi}/{componentId}";
240254
return await httpClient.GetStringAsync(componentUrl);
241255
}
@@ -266,6 +280,7 @@ public void DownloadAttachmentUsingWebClient(string attachmentDownloadLink, stri
266280
public async Task<HttpResponseMessage> UpdateRelease(string releaseId, HttpContent httpContent)
267281
{
268282
HttpClient httpClient = GetHttpClient();
283+
httpClient.SetLogWarnings(false);
269284
string releaseApi = $"{sw360ReleaseApi}/{releaseId}";
270285
return await httpClient.PatchAsync(releaseApi, httpContent);
271286
}
@@ -301,12 +316,14 @@ public async Task<HttpResponseMessage> GetComponentDetailsByUrl(string component
301316
public async Task<string> GetComponentByName(string componentName)
302317
{
303318
HttpClient httpClient = GetHttpClient();
319+
httpClient.SetLogWarnings(false);
304320
string url = $"{sw360ComponentApi}{ApiConstant.ComponentNameUrl}{componentName}";
305321
return await httpClient.GetStringAsync(url);
306322
}
307323
public async Task<HttpResponseMessage> GetComponentUsingName(string componentName)
308324
{
309325
HttpClient httpClient = GetHttpClient();
326+
httpClient.SetLogWarnings(false);
310327
string url = $"{sw360ComponentApi}{ApiConstant.ComponentNameUrl}{componentName}";
311328
return await httpClient.GetAsync(url);
312329
}

0 commit comments

Comments
 (0)