This repository was archived by the owner on Mar 31, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathNuGetPackageExplorerToCsvDriver.cs
More file actions
313 lines (276 loc) · 15 KB
/
NuGetPackageExplorerToCsvDriver.cs
File metadata and controls
313 lines (276 loc) · 15 KB
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
// 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.Xml;
using NuGet.Packaging.Core;
using NuGetPe;
namespace NuGet.Insights.Worker.NuGetPackageExplorerToCsv
{
public class NuGetPackageExplorerToCsvDriver :
ICatalogLeafToCsvDriver<NuGetPackageExplorerRecord, NuGetPackageExplorerFile>,
ICsvResultStorage<NuGetPackageExplorerRecord>,
ICsvResultStorage<NuGetPackageExplorerFile>
{
public const int FileBufferSize = 4 * 1024 * 1024;
private readonly CatalogClient _catalogClient;
private readonly FlatContainerClient _flatContainerClient;
private readonly Func<HttpClient> _httpClientFactory;
private readonly FileDownloader _fileDownloader;
private readonly TemporaryFileProvider _temporaryFileProvider;
private readonly IOptions<NuGetInsightsWorkerSettings> _options;
private readonly ILogger<NuGetPackageExplorerToCsvDriver> _logger;
public NuGetPackageExplorerToCsvDriver(
CatalogClient catalogClient,
FlatContainerClient flatContainerClient,
Func<HttpClient> httpClientFactory,
FileDownloader fileDownloader,
TemporaryFileProvider temporaryFileProvider,
IOptions<NuGetInsightsWorkerSettings> options,
ILogger<NuGetPackageExplorerToCsvDriver> logger)
{
_catalogClient = catalogClient;
_flatContainerClient = flatContainerClient;
_httpClientFactory = httpClientFactory;
_fileDownloader = fileDownloader;
_temporaryFileProvider = temporaryFileProvider;
_options = options;
_logger = logger;
}
public bool SingleMessagePerId => false;
string ICsvResultStorage<NuGetPackageExplorerRecord>.ResultContainerName => _options.Value.NuGetPackageExplorerContainerName;
string ICsvResultStorage<NuGetPackageExplorerFile>.ResultContainerName => _options.Value.NuGetPackageExplorerFileContainerName;
public Task InitializeAsync()
{
return Task.CompletedTask;
}
public Task DestroyAsync()
{
return Task.CompletedTask;
}
public async Task<DriverResult<CsvRecordSets<NuGetPackageExplorerRecord, NuGetPackageExplorerFile>>> ProcessLeafAsync(CatalogLeafScan leafScan)
{
(var record, var files) = await ProcessLeafInternalAsync(leafScan);
return DriverResult.Success(new CsvRecordSets<NuGetPackageExplorerRecord, NuGetPackageExplorerFile>(
record != null ? [record] : [],
files ?? []));
}
private async Task<(NuGetPackageExplorerRecord, IReadOnlyList<NuGetPackageExplorerFile>)> ProcessLeafInternalAsync(CatalogLeafScan leafScan)
{
var scanId = Guid.NewGuid();
var scanTimestamp = DateTimeOffset.UtcNow;
if (leafScan.LeafType == CatalogLeafType.PackageDelete)
{
var leaf = (PackageDeleteCatalogLeaf)await _catalogClient.GetCatalogLeafAsync(leafScan.LeafType, leafScan.Url);
return (
new NuGetPackageExplorerRecord(scanId, scanTimestamp, leaf),
[new NuGetPackageExplorerFile(scanId, scanTimestamp, leaf)]
);
}
else
{
var leaf = (PackageDetailsCatalogLeaf)await _catalogClient.GetCatalogLeafAsync(leafScan.LeafType, leafScan.Url);
var tempDir = Path.GetFullPath(Path.Combine(Path.GetTempPath(), "npe"));
if (!Directory.Exists(tempDir))
{
Directory.CreateDirectory(tempDir);
}
var tempFileName = TempStreamWriter.GetTempFileNameFactory(
leafScan.PackageId,
leafScan.PackageVersion,
"npe",
".nupkg")();
var tempPath = Path.Combine(tempDir, tempFileName);
try
{
var exists = await DownloadToFileAsync(leaf, leafScan.AttemptCount, tempPath);
if (!exists)
{
// Ignore packages where the .nupkg is missing. A subsequent scan will produce a deleted record.
return (null, null);
}
_logger.LogInformation(
"Loading ZIP package for {Id} {Version} on attempt {AttemptCount}.",
leaf.PackageId,
leaf.PackageVersion,
leafScan.AttemptCount);
ZipPackage zipPackage;
try
{
zipPackage = new ZipPackage(tempPath);
}
catch (Exception ex) when (ex is InvalidDataException
|| ex is ArgumentException
|| ex is PackagingException
|| ex is XmlException
|| ex is InvalidOperationException
|| ex.Message.Contains("Enabling license acceptance requires a license or a licenseUrl to be specified.", StringComparison.Ordinal)
|| ex.Message.Contains("Authors is required.", StringComparison.Ordinal)
|| ex.Message.Contains("Description is required.", StringComparison.Ordinal)
|| ex.Message.Contains("Url cannot be empty.", StringComparison.Ordinal)
|| (ex.Message.Contains("Assembly reference ", StringComparison.Ordinal) && ex.Message.Contains(" contains invalid characters.", StringComparison.Ordinal)))
{
_logger.LogWarning(ex, "Package {Id} {Version} had invalid metadata.", leaf.PackageId, leaf.PackageVersion);
return MakeSingleItem(scanId, scanTimestamp, leaf, NuGetPackageExplorerResultType.InvalidMetadata);
}
using (zipPackage)
{
var symbolValidator = new SymbolValidator(zipPackage, zipPackage.Source, rootFolder: null, _httpClientFactory(), _temporaryFileProvider);
SymbolValidatorResult symbolValidatorResult;
using (var cts = new CancellationTokenSource())
{
var delayTask = Task.Delay(TimeSpan.FromMinutes(4), cts.Token);
_logger.LogInformation(
"Starting symbol validation for {Id} {Version} on attempt {AttemptCount}.",
leaf.PackageId,
leaf.PackageVersion,
leafScan.AttemptCount);
var symbolValidatorTask = symbolValidator.Validate(cts.Token);
var resultTask = await Task.WhenAny(delayTask, symbolValidatorTask);
if (resultTask == delayTask)
{
cts.Cancel();
if (leafScan.AttemptCount > 3)
{
_logger.LogWarning("Package {Id} {Version} had its symbol validation timeout.", leaf.PackageId, leaf.PackageVersion);
return MakeSingleItem(scanId, scanTimestamp, leaf, NuGetPackageExplorerResultType.Timeout);
}
else
{
throw new TimeoutException("The NuGetPackageExplorer symbol validator task timed out.");
}
}
else
{
symbolValidatorResult = await symbolValidatorTask;
cts.Cancel();
}
}
_logger.LogInformation(
"Loading signature data for {Id} {Version} on attempt {AttemptCount}.",
leaf.PackageId,
leaf.PackageVersion,
leafScan.AttemptCount);
await zipPackage.LoadSignatureDataAsync();
using var fileStream = zipPackage.GetStream();
var record = new NuGetPackageExplorerRecord(scanId, scanTimestamp, leaf)
{
SourceLinkResult = symbolValidatorResult.SourceLinkResult,
DeterministicResult = symbolValidatorResult.DeterministicResult,
CompilerFlagsResult = symbolValidatorResult.CompilerFlagsResult,
IsSignedByAuthor = zipPackage.PublisherSignature != null,
};
var files = new List<NuGetPackageExplorerFile>();
try
{
_logger.LogInformation(
"Getting all files for {Id} {Version} on attempt {AttemptCount}.",
leaf.PackageId,
leaf.PackageVersion,
leafScan.AttemptCount);
foreach (var file in symbolValidator.GetAllFiles())
{
var compilerFlags = file.DebugData?.CompilerFlags.ToDictionary(k => k.Key, v => v.Value);
var sourceUrls = file.DebugData?.Sources.Where(x => x.Url != null).Select(x => x.Url);
var sourceUrlRepoInfo = sourceUrls != null ? SourceUrlRepoParser.GetSourceRepoInfo(sourceUrls) : null;
files.Add(new NuGetPackageExplorerFile(scanId, scanTimestamp, leaf)
{
Path = file.Path,
Extension = file.Extension,
HasCompilerFlags = file.DebugData?.HasCompilerFlags,
HasSourceLink = file.DebugData?.HasSourceLink,
HasDebugInfo = file.DebugData?.HasDebugInfo,
PdbType = file.DebugData?.PdbType,
CompilerFlags = KustoDynamicSerializer.Serialize(compilerFlags),
SourceUrlRepoInfo = KustoDynamicSerializer.Serialize(sourceUrlRepoInfo),
});
}
}
catch (Exception ex) when (ex is FileNotFoundException || ex is FormatException)
{
// handles https://github.com/NuGetPackageExplorer/NuGetPackageExplorer/issues/1505
_logger.LogWarning(ex, "Could not get symbol validator files for {Id} {Version}.", leaf.PackageId, leaf.PackageVersion);
return MakeSingleItem(scanId, scanTimestamp, leaf, NuGetPackageExplorerResultType.InvalidMetadata);
}
if (files.Count == 0)
{
record.ResultType = NuGetPackageExplorerResultType.NothingToValidate;
// Add a marker "nothing to validate" record to the files table so that all tables have the
// same set of identities.
files.Add(new NuGetPackageExplorerFile(scanId, scanTimestamp, leaf)
{
ResultType = NuGetPackageExplorerResultType.NothingToValidate,
});
}
return (record, files);
}
}
finally
{
if (File.Exists(tempPath))
{
try
{
File.Delete(tempPath);
}
catch (Exception ex)
{
// Best effort.
_logger.LogError(ex, "Could not delete {TempPath} during NuGet Package Explorer clean up.", tempPath);
}
}
}
}
}
private async Task<bool> DownloadToFileAsync(PackageDetailsCatalogLeaf leaf, int attemptCount, string path)
{
var contentUrl = await _flatContainerClient.GetPackageContentUrlAsync(leaf.PackageId, leaf.PackageVersion);
_logger.LogInformation(
"Downloading .nupkg for {Id} {Version} on attempt {AttemptCount}.",
leaf.PackageId,
leaf.PackageVersion,
attemptCount);
var result = await _fileDownloader.DownloadUrlToFileAsync(
contentUrl,
allowNotFound: true,
requireContentLength: true,
async (networkStream, contentLength) =>
{
using var hasher = IncrementalHash.CreateNone();
using var destination = new FileStream(
path,
FileMode.Create,
FileAccess.ReadWrite,
FileShare.Read,
bufferSize: 4096,
FileOptions.Asynchronous);
await destination.SetLengthAndWriteAsync(contentLength);
await networkStream.CopyToSlowAsync(
destination,
contentLength,
bufferSize: FileBufferSize,
hasher: hasher,
logger: _logger);
return TempStreamResult.Success(destination, hasher.Output, NullAsyncDisposable.Instance);
},
CancellationToken.None);
if (!result.HasValue)
{
return false;
}
await using (result.Value.Body)
{
return true;
}
}
private static (NuGetPackageExplorerRecord, NuGetPackageExplorerFile[]) MakeSingleItem(
Guid scanId,
DateTimeOffset scanTimestamp,
PackageDetailsCatalogLeaf leaf,
NuGetPackageExplorerResultType type)
{
return (
new NuGetPackageExplorerRecord(scanId, scanTimestamp, leaf) { ResultType = type },
new[] { new NuGetPackageExplorerFile(scanId, scanTimestamp, leaf) { ResultType = type } }
);
}
}
}