Skip to content

Commit

Permalink
Fix for ApiDataProvider (QuantConnect#6461)
Browse files Browse the repository at this point in the history
- Avoid race condition while downloading data.
- Reused http client for downloads
  • Loading branch information
Martin-Molinero authored Jul 5, 2022
1 parent 3f407cd commit 64f0a9e
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 12 deletions.
7 changes: 3 additions & 4 deletions Api/Api.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ namespace QuantConnect.Api
/// </summary>
public class Api : IApi, IDownloadProvider
{
private readonly HttpClient _client = new HttpClient();
private string _dataFolder;

/// <summary>
Expand Down Expand Up @@ -877,9 +878,7 @@ public bool DownloadData(string filePath, string organizationId)
{
// Download the file
var uri = new Uri(dataLink.Url);

using var client = new HttpClient();
using var dataStream = client.GetStreamAsync(uri);
using var dataStream = _client.GetStreamAsync(uri);

using var fileStream = new FileStream(filePath, FileMode.Create);
dataStream.Result.CopyTo(fileStream);
Expand Down Expand Up @@ -997,7 +996,7 @@ public virtual string Download(string address, IEnumerable<KeyValuePair<string,
/// <filterpriority>2</filterpriority>
public virtual void Dispose()
{
// NOP
_client.DisposeSafely();
}

/// <summary>
Expand Down
15 changes: 7 additions & 8 deletions Engine/DataFeeds/BaseDownloaderDataProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,17 +51,16 @@ protected Stream DownloadOnce(string key, Action<string> download)
_currentDownloads.TryRemove(key, out _);
return base.Fetch(key);
}

// this is rare
_currentDownloads.TryGetValue(key, out var existingKey);
lock (existingKey ?? new object())
{
return base.Fetch(key);
}
}
}

return base.Fetch(key);
// even though we should not download in this path, we need to wait for any download in progress to be finished
// in this case it would be present in the '_currentDownloads' collection with it's lock taken
_currentDownloads.TryGetValue(key, out var existingKey);
lock (existingKey ?? new object())
{
return base.Fetch(key);
}
}

/// <summary>
Expand Down

0 comments on commit 64f0a9e

Please sign in to comment.