-
Notifications
You must be signed in to change notification settings - Fork 749
Expand file tree
/
Copy pathServiceIndexResourceV3.cs
More file actions
336 lines (290 loc) · 12.1 KB
/
ServiceIndexResourceV3.cs
File metadata and controls
336 lines (290 loc) · 12.1 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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// 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.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using Newtonsoft.Json.Linq;
using NuGet.Configuration;
using NuGet.Packaging;
using NuGet.Protocol.Core.Types;
using NuGet.Protocol.Events;
using NuGet.Protocol.Model;
using NuGet.Protocol.Utility;
using NuGet.Versioning;
namespace NuGet.Protocol
{
/// <summary>
/// Stores/caches a service index json file.
/// </summary>
public class ServiceIndexResourceV3 : INuGetResource
{
private readonly string _json;
private readonly ServiceIndexModel _model;
private readonly IDictionary<string, List<ServiceIndexEntry>> _index;
private readonly DateTime _requestTime;
private static readonly IReadOnlyList<ServiceIndexEntry> _emptyEntries = new List<ServiceIndexEntry>();
private static readonly SemanticVersion _defaultVersion = new SemanticVersion(0, 0, 0);
internal ServiceIndexResourceV3(JObject index, DateTime requestTime, PackageSource packageSource)
{
_json = index.ToString();
_index = MakeLookup(index, packageSource);
_requestTime = requestTime;
}
public ServiceIndexResourceV3(JObject index, DateTime requestTime) : this(index, requestTime, null) { }
internal ServiceIndexResourceV3(ServiceIndexModel model, DateTime requestTime, PackageSource packageSource)
{
_model = model;
_index = MakeLookup(model, packageSource);
_requestTime = requestTime;
}
/// <summary>
/// Time the index was requested
/// </summary>
public virtual DateTime RequestTime
{
get { return _requestTime; }
}
/// <summary>
/// All service index entries.
/// </summary>
public virtual IReadOnlyList<ServiceIndexEntry> Entries
{
get
{
return _index.SelectMany(e => e.Value).ToList();
}
}
public virtual string Json
{
get { return _json ?? JsonSerializer.Serialize(_model, JsonContext.Default.ServiceIndexModel); }
}
/// <summary>
/// Get the list of service entries that best match the current clientVersion and type.
/// </summary>
public virtual IReadOnlyList<ServiceIndexEntry> GetServiceEntries(params string[] orderedTypes)
{
var clientVersion = MinClientVersionUtility.GetNuGetClientVersion();
return GetServiceEntries(clientVersion, orderedTypes);
}
/// <summary>
/// Get the list of service entries that best match the clientVersion and type.
/// </summary>
public virtual IReadOnlyList<ServiceIndexEntry> GetServiceEntries(NuGetVersion clientVersion, params string[] orderedTypes)
{
if (clientVersion == null)
{
throw new ArgumentNullException(nameof(clientVersion));
}
foreach (var type in orderedTypes)
{
List<ServiceIndexEntry> entries;
if (_index.TryGetValue(type, out entries))
{
var compatible = GetBestVersionMatchForType(clientVersion, entries);
if (compatible.Count > 0)
{
return compatible;
}
}
}
return _emptyEntries;
}
private IReadOnlyList<ServiceIndexEntry> GetBestVersionMatchForType(NuGetVersion clientVersion, List<ServiceIndexEntry> entries)
{
var bestMatch = entries.FirstOrDefault(e => e.ClientVersion <= clientVersion);
if (bestMatch == null)
{
// No compatible version
return _emptyEntries;
}
else
{
// Find all entries with the same version.
return entries.Where(e => e.ClientVersion == bestMatch.ClientVersion).ToList();
}
}
/// <summary>
/// Get the best match service URI.
/// </summary>
public virtual Uri GetServiceEntryUri(params string[] orderedTypes)
{
var clientVersion = MinClientVersionUtility.GetNuGetClientVersion();
return GetServiceEntryUris(clientVersion, orderedTypes).FirstOrDefault();
}
/// <summary>
/// Get the list of service URIs that best match the current clientVersion and type.
/// </summary>
public virtual IReadOnlyList<Uri> GetServiceEntryUris(params string[] orderedTypes)
{
var clientVersion = MinClientVersionUtility.GetNuGetClientVersion();
return GetServiceEntryUris(clientVersion, orderedTypes);
}
/// <summary>
/// Get the list of service URIs that best match the clientVersion and type.
/// </summary>
public virtual IReadOnlyList<Uri> GetServiceEntryUris(NuGetVersion clientVersion, params string[] orderedTypes)
{
if (clientVersion == null)
{
throw new ArgumentNullException(nameof(clientVersion));
}
return GetServiceEntries(clientVersion, orderedTypes).Select(e => e.Uri).ToList();
}
private static IDictionary<string, List<ServiceIndexEntry>> MakeLookup(ServiceIndexModel index, PackageSource packageSource)
{
var result = new Dictionary<string, List<ServiceIndexEntry>>(StringComparer.Ordinal);
if (index?.Resources is null)
{
return result;
}
foreach (var resource in index.Resources)
{
var id = resource.Id;
if (string.IsNullOrEmpty(id) || !Uri.TryCreate(id, UriKind.Absolute, out Uri uri))
{
continue;
}
if (packageSource != null && uri.Scheme == Uri.UriSchemeHttp && packageSource.IsHttps)
{
ProtocolDiagnostics.RaiseEvent(new ProtocolDiagnosticServiceIndexEntryEvent(source: packageSource.Source, httpsSourceHasHttpResource: true));
}
var types = GetStringValues(resource.Type).ToArray();
var clientVersions = new List<SemanticVersion>();
if (resource.ClientVersion.ValueKind == JsonValueKind.Undefined)
{
clientVersions.Add(_defaultVersion);
}
else
{
foreach (var versionString in GetStringValues(resource.ClientVersion))
{
if (SemanticVersion.TryParse(versionString, out SemanticVersion semVer))
{
clientVersions.Add(semVer);
}
}
}
foreach (var type in types)
{
foreach (var clientVersion in clientVersions)
{
if (!result.TryGetValue(type, out List<ServiceIndexEntry> entries))
{
entries = new List<ServiceIndexEntry>();
result.Add(type, entries);
}
entries.Add(new ServiceIndexEntry(uri, type, clientVersion));
}
}
}
foreach (var type in result.Keys.ToArray())
{
result[type] = result[type].OrderByDescending(e => e.ClientVersion).ToList();
}
return result;
}
private static IEnumerable<string> GetStringValues(JsonElement element)
{
if (element.ValueKind == JsonValueKind.Array)
{
foreach (var item in element.EnumerateArray())
{
if (item.ValueKind == JsonValueKind.String)
{
yield return item.GetString();
}
}
}
else if (element.ValueKind == JsonValueKind.String)
{
yield return element.GetString();
}
}
private static IDictionary<string, List<ServiceIndexEntry>> MakeLookup(JObject index, PackageSource packageSource)
{
var result = new Dictionary<string, List<ServiceIndexEntry>>(StringComparer.Ordinal);
JToken resources;
if (index.TryGetValue("resources", out resources))
{
foreach (var resource in resources)
{
var id = GetValues(resource["@id"]).SingleOrDefault();
Uri uri;
if (string.IsNullOrEmpty(id) || !Uri.TryCreate(id, UriKind.Absolute, out uri))
{
// Skip invalid or missing @ids
continue;
}
// Capture if the resource is http & the source is https
if (packageSource != null && uri.Scheme == Uri.UriSchemeHttp && packageSource.IsHttps)
{
ProtocolDiagnostics.RaiseEvent(new ProtocolDiagnosticServiceIndexEntryEvent(source: packageSource.Source, httpsSourceHasHttpResource: true));
}
var types = GetValues(resource["@type"]).ToArray();
var clientVersionToken = resource["clientVersion"];
var clientVersions = new List<SemanticVersion>();
if (clientVersionToken == null)
{
// For non-versioned services assume all clients are compatible
clientVersions.Add(_defaultVersion);
}
else
{
// Parse supported versions
foreach (var versionString in GetValues(clientVersionToken))
{
SemanticVersion version;
if (SemanticVersion.TryParse(versionString, out version))
{
clientVersions.Add(version);
}
}
}
// Create service entries
foreach (var type in types)
{
foreach (var version in clientVersions)
{
List<ServiceIndexEntry> entries;
if (!result.TryGetValue(type, out entries))
{
entries = new List<ServiceIndexEntry>();
result.Add(type, entries);
}
entries.Add(new ServiceIndexEntry(uri, type, version));
}
}
}
}
// Order versions desc for faster lookup later.
foreach (var type in result.Keys.ToArray())
{
result[type] = result[type].OrderByDescending(e => e.ClientVersion).ToList();
}
return result;
}
/// <summary>
/// Read string values from an array or string.
/// Returns an empty enumerable if the value is null.
/// </summary>
private static IEnumerable<string> GetValues(JToken token)
{
if (token?.Type == JTokenType.Array)
{
foreach (var entry in token)
{
if (entry.Type == JTokenType.String)
{
yield return entry.ToObject<string>();
}
}
}
else if (token?.Type == JTokenType.String)
{
yield return token.ToObject<string>();
}
}
}
}