This repository has been archived by the owner on Dec 18, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 228
/
NuGetv2Feed.cs
246 lines (223 loc) · 10.4 KB
/
NuGetv2Feed.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Framework.Runtime.Internal;
using NuGet;
namespace Microsoft.Framework.PackageManager.Restore.NuGet
{
public class NuGetv2Feed : IPackageFeed
{
private static readonly XNamespace _defaultNamespace = XNamespace.Get("http://www.w3.org/2005/Atom");
private static readonly XName _xnameEntry = XName.Get("entry", _defaultNamespace.NamespaceName);
private static readonly XName _xnameTitle = XName.Get("title", _defaultNamespace.NamespaceName);
private static readonly XName _xnameContent = XName.Get("content", _defaultNamespace.NamespaceName);
private static readonly XName _xnameLink = XName.Get("link", _defaultNamespace.NamespaceName);
private static readonly XName _xnameProperties = XName.Get("properties", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
private static readonly XName _xnameId = XName.Get("Id", "http://schemas.microsoft.com/ado/2007/08/dataservices");
private static readonly XName _xnameVersion = XName.Get("Version", "http://schemas.microsoft.com/ado/2007/08/dataservices");
private readonly string _baseUri;
private readonly Reports _reports;
private readonly HttpSource _httpSource;
private readonly TimeSpan _cacheAgeLimitList;
private readonly TimeSpan _cacheAgeLimitNupkg;
private readonly bool _ignoreFailure;
private bool _ignored;
private readonly Dictionary<string, Task<IEnumerable<PackageInfo>>> _packageVersionsCache = new Dictionary<string, Task<IEnumerable<PackageInfo>>>();
private readonly Dictionary<string, Task<NupkgEntry>> _nupkgCache = new Dictionary<string, Task<NupkgEntry>>();
public string Source
{
get
{
return _httpSource.BaseUri;
}
}
internal NuGetv2Feed(
HttpSource httpSource,
bool noCache,
Reports reports,
bool ignoreFailure)
{
_baseUri = httpSource.BaseUri;
_reports = reports;
_httpSource = httpSource;
_ignoreFailure = ignoreFailure;
if (noCache)
{
_cacheAgeLimitList = TimeSpan.Zero;
_cacheAgeLimitNupkg = TimeSpan.Zero;
}
else
{
_cacheAgeLimitList = TimeSpan.FromMinutes(30);
_cacheAgeLimitNupkg = TimeSpan.FromHours(24);
}
}
public Task<IEnumerable<PackageInfo>> FindPackagesByIdAsync(string id)
{
lock (_packageVersionsCache)
{
Task<IEnumerable<PackageInfo>> task;
if (_packageVersionsCache.TryGetValue(id, out task))
{
return task;
}
return _packageVersionsCache[id] = FindPackagesByIdAsyncCore(id);
}
}
public async Task<IEnumerable<PackageInfo>> FindPackagesByIdAsyncCore(string id)
{
for (int retry = 0; retry != 3; ++retry)
{
if (_ignored)
{
return new List<PackageInfo>();
}
try
{
var uri = $"{_baseUri}FindPackagesById()?id='{id}'";
var results = new List<PackageInfo>();
var page = 1;
while (true)
{
// TODO: Pages for a package Id are cached separately.
// So we will get inaccurate data when a page shrinks.
// However, (1) In most cases the pages grow rather than shrink;
// (2) cache for pages is valid for only 30 min.
// So we decide to leave current logic and observe.
using (var data = await _httpSource.GetAsync(uri,
cacheKey: $"list_{id}_page{page}",
cacheAgeLimit: retry == 0 ? _cacheAgeLimitList : TimeSpan.Zero,
ensureValidContents: stream => EnsureValidFindPackagesResponse(stream, uri)))
{
try
{
var doc = XDocument.Load(data.Stream);
var result = doc.Root
.Elements(_xnameEntry)
.Select(x => BuildModel(id, x));
results.AddRange(result);
// Example of what this looks like in the odata feed:
// <link rel="next" href="{nextLink}" />
var nextUri = (from e in doc.Root.Elements(_xnameLink)
let attr = e.Attribute("rel")
where attr != null && string.Equals(attr.Value, "next", StringComparison.OrdinalIgnoreCase)
select e.Attribute("href") into nextLink
where nextLink != null
select nextLink.Value).FirstOrDefault();
// Stop if there's nothing else to GET
if (string.IsNullOrEmpty(nextUri))
{
break;
}
uri = nextUri;
page++;
}
catch (XmlException)
{
_reports.Information.WriteLine(
$"XML file {data.CacheFileName} is corrupt".Yellow().Bold());
throw;
}
}
}
return results;
}
catch (Exception ex)
{
if (retry == 2)
{
// Fail silently by returning empty result list
if (_ignoreFailure)
{
_ignored = true;
_reports.Information.WriteLine(
$"Failed to retrieve information from remote source '{_baseUri}'".Yellow().Bold());
return new List<PackageInfo>();
}
_reports.Error.WriteLine(
$"Error: FindPackagesById: {id}{Environment.NewLine} {ex.Message}".Red().Bold());
throw;
}
else
{
_reports.Information.WriteLine(
$"Warning: FindPackagesById: {id}{Environment.NewLine} {ex.Message}".Yellow().Bold());
}
}
}
return null;
}
public PackageInfo BuildModel(string id, XElement element)
{
var properties = element.Element(_xnameProperties);
var idElement = properties.Element(_xnameId);
var titleElement = element.Element(_xnameTitle);
return new PackageInfo
{
// If 'Id' element exist, use its value as accurate package Id
// Otherwise, use the value of 'title' if it exist
// Use the given Id as final fallback if all elements above don't exist
Id = idElement?.Value ?? titleElement?.Value ?? id,
Version = SemanticVersion.Parse(properties.Element(_xnameVersion).Value),
ContentUri = element.Element(_xnameContent).Attribute("src").Value,
};
}
public async Task<Stream> OpenNuspecStreamAsync(PackageInfo package)
{
return await PackageUtilities.OpenNuspecStreamFromNupkgAsync(package, OpenNupkgStreamAsync, _reports.Information);
}
public async Task<Stream> OpenRuntimeStreamAsync(PackageInfo package)
{
return await PackageUtilities.OpenRuntimeStreamFromNupkgAsync(package, OpenNupkgStreamAsync, _reports.Information);
}
public async Task<Stream> OpenNupkgStreamAsync(PackageInfo package)
{
Task<NupkgEntry> task;
lock (_nupkgCache)
{
if (!_nupkgCache.TryGetValue(package.ContentUri, out task))
{
task = _nupkgCache[package.ContentUri] = PackageUtilities.OpenNupkgStreamAsync(
_httpSource, package, _cacheAgeLimitNupkg, _reports);
}
}
var result = await task;
if (result == null)
{
return null;
}
// Acquire the lock on a file before we open it to prevent this process
// from opening a file deleted by the logic in HttpSource.GetAsync() in another process
return await ConcurrencyUtilities.ExecuteWithFileLocked(result.TempFileName, _ =>
{
return Task.FromResult(
new FileStream(result.TempFileName, FileMode.Open, FileAccess.Read,
FileShare.ReadWrite | FileShare.Delete));
});
}
private static void EnsureValidFindPackagesResponse(Stream stream, string uri)
{
var message = $"Response from {uri} is not a valid NuGet v2 service response.";
try
{
var xDoc = XDocument.Load(stream);
if (!_defaultNamespace.Equals(xDoc.Root.Name.Namespace))
{
throw new InvalidDataException(
$"{message} Namespace of root element is not {_defaultNamespace.NamespaceName}.");
}
}
catch (XmlException e)
{
throw new InvalidDataException(message, innerException: e);
}
}
}
}