Skip to content

Commit

Permalink
Feature/enable cancellation of get evidence (#28)
Browse files Browse the repository at this point in the history
* Added timeout to evidence code model and corrected a random typo #26

* moved default value to settings, added same timeout setuå for harvest of open data #26
  • Loading branch information
erlendoksvoll authored Jan 19, 2023
1 parent aca6f1c commit a955755
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 11 deletions.
7 changes: 7 additions & 0 deletions Dan.Common/Models/EvidenceCode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -131,4 +131,11 @@ public class EvidenceCode
[DataMember(Name = "deprecationWarning")]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string? DeprecationWarning { get; set; }

/// <summary>
/// Optional setting for custom timeout (in seconds) in evidencecodes when harvesting data
/// </summary>
[DataMember(Name = "timeout")]
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public int? Timeout { get; set; }
}
2 changes: 2 additions & 0 deletions Dan.Core/Config/Settings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,8 @@ public static string GetConsentRedirectUrl(string accreditationId, string hmac)

public const int MaxReferenceLength = 50;

public static int DefaultHarvestTaskCancellation = 35;

private static string GetSetting(string settingKey)
{
var value = ConfigurationHelper.ConfigurationRoot[settingKey];
Expand Down
2 changes: 1 addition & 1 deletion Dan.Core/FuncEvidenceHarvester.cs
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ public async Task<HttpResponseData> RunAsync(
using (var t = _logger.Timer("consent-log-usage"))
{
_logger.LogInformation(
"Start logging consent based harvest aid={accreditaionId} evidenceCode={evidenceCode}",
"Start logging consent based harvest aid={accreditationId} evidenceCode={evidenceCode}",
accreditation.AccreditationId, evidenceCode.EvidenceCodeName);
await LogConsentBasedHarvest(evidenceCode, accreditation);
_logger.LogInformation(
Expand Down
44 changes: 34 additions & 10 deletions Dan.Core/Services/EvidenceHarvesterService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,11 @@ public async Task<Evidence> HarvestOpenData(EvidenceCode evidenceCode, string id

var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.TryAddWithoutValidation("Content-Type", "application/json");

var timeoutSeconds = evidenceCode.Timeout ??= Settings.DefaultHarvestTaskCancellation;

using var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(60));
cts.CancelAfter(TimeSpan.FromSeconds(timeoutSeconds));

var evidenceHarvesterRequest = new EvidenceHarvesterRequest()
{
Expand All @@ -81,10 +84,19 @@ public async Task<Evidence> HarvestOpenData(EvidenceCode evidenceCode, string id
_log.LogInformation("Start harvesting evidence values for open data evidenceCode={evidenceCodeName} and identifier {identifier}", evidenceCode.EvidenceCodeName, identifier == "" ? "(empty)" : identifier);
request.JsonContent(evidenceHarvesterRequest);
request.SetPolicyExecutionContext(new Context(request.Key(CacheArea.Absolute)));
var client = _httpClientFactory.CreateClient("SafeHttpClient");
harvestedEvidence = (await EvidenceSourceHelper.DoRequest<List<EvidenceValue>>(
request,
() => client.SendAsync(request, cts.Token)))!;

try
{
var client = _httpClientFactory.CreateClient("SafeHttpClient");
harvestedEvidence = (await EvidenceSourceHelper.DoRequest<List<EvidenceValue>>(
request,
() => client.SendAsync(request, cts.Token)))!;
}
catch (TaskCanceledException)
{
_log.LogError("Harvesting evidence values for open data evidenceCode={evidenceCodeName} and identifier {identifier} was cancelled", evidenceCode.EvidenceCodeName, identifier == "" ? "(empty)" : identifier);
throw new ServiceNotAvailableException($"The request was cancelled after exceeding max duration ({timeoutSeconds} seconds)");
}

_log.LogInformation("Completed harvesting evidence values for open data evidenceCode={evidenceCodeName} and identifier {identifier}", evidenceCode.EvidenceCodeName, identifier == "" ? "(empty)" : identifier);
}
Expand All @@ -104,8 +116,11 @@ private async Task<List<EvidenceValue>> HarvestEvidenceValues(EvidenceCode evide

var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.TryAddWithoutValidation("Content-Type", "application/json");

var timeoutSeconds = evidenceCode.Timeout ??= Settings.DefaultHarvestTaskCancellation;

using var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(30));
cts.CancelAfter(TimeSpan.FromSeconds(timeoutSeconds));

var evidenceHarvesterRequest = new EvidenceHarvesterRequest()
{
Expand Down Expand Up @@ -137,10 +152,19 @@ private async Task<List<EvidenceValue>> HarvestEvidenceValues(EvidenceCode evide
request.JsonContent(evidenceHarvesterRequest);

request.SetPolicyExecutionContext(new Context(request.Key(CacheArea.Absolute)));
var client = _httpClientFactory.CreateClient("SafeHttpClient");
return (await EvidenceSourceHelper.DoRequest<List<EvidenceValue>>(
request,
() => client.SendAsync(request, cts.Token)))!;

try
{
var client = _httpClientFactory.CreateClient("SafeHttpClient");
return (await EvidenceSourceHelper.DoRequest<List<EvidenceValue>>(
request,
() => client.SendAsync(request, cts.Token)))!;
}
catch (TaskCanceledException)
{
_log.LogError("Harvesting evidence values for open data evidenceCode={evidenceCodeName} and subject {subject} was cancelled", evidenceCode.EvidenceCodeName, accreditation.SubjectParty.GetAsString(true));
throw new ServiceNotAvailableException($"The request was cancelled after exceeding max duration of {timeoutSeconds} seconds)");
}
}

private async Task<string> GetAccessToken(EvidenceCode evidenceCode, Accreditation accreditation, EvidenceHarvesterOptions evidenceHarvesterOptions)
Expand Down

0 comments on commit a955755

Please sign in to comment.