-
Notifications
You must be signed in to change notification settings - Fork 748
[NSJ -> STJ]Migrate AutoComplete #7298
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Nigusu-Allehu
wants to merge
5
commits into
dev
Choose a base branch
from
dev-nyenework-autocomplete-stj
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| // 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. | ||
|
|
||
| #if !NET9_0_OR_GREATER | ||
| namespace System.Diagnostics.CodeAnalysis | ||
| { | ||
| [AttributeUsage(AttributeTargets.Property, Inherited = false)] | ||
| internal sealed class FeatureSwitchDefinitionAttribute : Attribute | ||
| { | ||
| public FeatureSwitchDefinitionAttribute(string switchName) => SwitchName = switchName; | ||
| public string SwitchName { get; } | ||
| } | ||
| } | ||
| #endif |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| // 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.Diagnostics.CodeAnalysis; | ||
| using NuGet.Common; | ||
|
|
||
| namespace NuGet.Shared | ||
| { | ||
| internal static class NuGetFeatureFlags | ||
| { | ||
| internal const string UseLegacyJsonDeserializationSwitchName = "NuGet.UseLegacyJsonDeserialization"; | ||
| internal const string UseLegacyJsonDeserializationEnvVar = "NUGET_USE_LEGACY_JSON_DESERIALIZATION"; | ||
|
|
||
| private static readonly Lazy<bool> _isLegacyJsonDeserializationEnabledByEnvironment = | ||
| new Lazy<bool>(() => IsLegacyJsonDeserializationEnabledByEnvironment(EnvironmentVariableWrapper.Instance)); | ||
|
|
||
| /// <summary>Feature switch for legacy (Newtonsoft) JSON deserialization. Defaults to <see langword="false"/> (STJ is the default).</summary> | ||
| [FeatureSwitchDefinition(UseLegacyJsonDeserializationSwitchName)] | ||
| internal static bool UseLegacyJsonDeserializationFeatureSwitch { get; } = | ||
| AppContext.TryGetSwitch(UseLegacyJsonDeserializationSwitchName, out bool value) && value; | ||
|
|
||
| /// <summary>Returns <see langword="true"/> when env var <c>NUGET_USE_LEGACY_JSON_DESERIALIZATION</c> is <c>true</c>.</summary> | ||
| /// <param name="env"> | ||
| /// Pass <see langword="null"/> (or omit) in production code to use the cached <see cref="Lazy{T}"/> value, | ||
| /// avoiding repeated allocations on .NET Framework. Pass an explicit <see cref="IEnvironmentVariableReader"/> | ||
| /// only in tests to override the value. | ||
| /// </param> | ||
| internal static bool IsLegacyJsonDeserializationEnabledByEnvironment(IEnvironmentVariableReader? env = null) | ||
| { | ||
| if (env is null) | ||
| { | ||
| return _isLegacyJsonDeserializationEnabledByEnvironment.Value; | ||
| } | ||
|
|
||
| string? envValue = env.GetEnvironmentVariable(UseLegacyJsonDeserializationEnvVar); | ||
| return string.Equals(envValue, "true", StringComparison.OrdinalIgnoreCase); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| // 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.Text.Json.Serialization; | ||
|
|
||
| namespace NuGet.Protocol.Model | ||
| { | ||
| internal sealed class AutoCompleteModel | ||
| { | ||
| [JsonPropertyName("data")] | ||
| public string[]? Data { get; set; } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -8,19 +8,25 @@ | |
| using System.Globalization; | ||
| using System.Linq; | ||
| using System.Net; | ||
| using System.Text.Json; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Newtonsoft.Json.Linq; | ||
| using NuGet.Common; | ||
| using NuGet.Protocol.Core.Types; | ||
| using NuGet.Protocol.Model; | ||
| using NuGet.Protocol.Utility; | ||
| using NuGet.Shared; | ||
| using NuGet.Versioning; | ||
|
|
||
| namespace NuGet.Protocol | ||
| { | ||
| public class AutoCompleteResourceV3 : AutoCompleteResource | ||
| { | ||
| private readonly RegistrationResourceV3 _regResource; | ||
| private readonly ServiceIndexResourceV3 _serviceIndex; | ||
| private readonly HttpSource _client; | ||
| internal readonly RegistrationResourceV3 _regResource; | ||
| internal readonly ServiceIndexResourceV3 _serviceIndex; | ||
| internal readonly HttpSource _client; | ||
| private readonly IEnvironmentVariableReader _environmentVariableReader; | ||
|
|
||
| public AutoCompleteResourceV3(HttpSource client, ServiceIndexResourceV3 serviceIndex, RegistrationResourceV3 regResource) | ||
| : base() | ||
|
|
@@ -30,31 +36,69 @@ public AutoCompleteResourceV3(HttpSource client, ServiceIndexResourceV3 serviceI | |
| _client = client; | ||
| } | ||
|
|
||
| internal AutoCompleteResourceV3(HttpSource client, ServiceIndexResourceV3 serviceIndex, RegistrationResourceV3 regResource, IEnvironmentVariableReader environmentVariableReader) | ||
| : base() | ||
| { | ||
| _regResource = regResource; | ||
| _serviceIndex = serviceIndex; | ||
| _client = client; | ||
| _environmentVariableReader = environmentVariableReader; | ||
| } | ||
|
|
||
| public override async Task<IEnumerable<string>> IdStartsWith( | ||
| string packageIdPrefix, | ||
| bool includePrerelease, | ||
| Common.ILogger log, | ||
| CancellationToken token) | ||
| { | ||
| var searchUrl = _serviceIndex.GetServiceEntryUri(ServiceTypes.SearchAutocompleteService); | ||
|
|
||
| if (searchUrl == null) | ||
| if (NuGetFeatureFlags.UseLegacyJsonDeserializationFeatureSwitch || NuGetFeatureFlags.IsLegacyJsonDeserializationEnabledByEnvironment(_environmentVariableReader)) | ||
| { | ||
| throw new FatalProtocolException(Strings.Protocol_MissingSearchService); | ||
| return await IdStartsWithNsjAsync(packageIdPrefix, includePrerelease, log, token); | ||
| } | ||
| else | ||
| { | ||
| return await IdStartsWithStjAsync(packageIdPrefix, includePrerelease, log, token); | ||
| } | ||
| } | ||
|
|
||
| // Construct the query | ||
| var queryUrl = new UriBuilder(searchUrl.AbsoluteUri); | ||
| var queryString = | ||
| "q=" + WebUtility.UrlEncode(packageIdPrefix) + | ||
| "&prerelease=" + includePrerelease.ToString(CultureInfo.CurrentCulture).ToLowerInvariant() + | ||
| "&semVerLevel=2.0.0"; | ||
| private async Task<IEnumerable<string>> IdStartsWithStjAsync( | ||
| string packageIdPrefix, | ||
| bool includePrerelease, | ||
| Common.ILogger log, | ||
| CancellationToken token) | ||
| { | ||
| var queryUri = BuildQueryUri(packageIdPrefix, includePrerelease); | ||
| Common.ILogger logger = log ?? Common.NullLogger.Instance; | ||
|
|
||
| queryUrl.Query = queryString; | ||
| AutoCompleteModel results = await _client.ProcessStreamAsync( | ||
| new HttpSourceRequest(queryUri, logger), | ||
| async stream => | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't know what the team code style is, if they link lamdas defined ahead of the method call or within it. |
||
| { | ||
| if (stream == null) | ||
| { | ||
| return null; | ||
| } | ||
|
|
||
| return await JsonSerializer.DeserializeAsync(stream, JsonContext.Default.AutoCompleteModel, token); | ||
| }, | ||
| logger, | ||
| token); | ||
|
|
||
| token.ThrowIfCancellationRequested(); | ||
|
|
||
| return results?.Data?.Where(item => item != null && item.StartsWith(packageIdPrefix, StringComparison.OrdinalIgnoreCase)) | ||
| ?? []; | ||
| } | ||
|
|
||
| private async Task<IEnumerable<string>> IdStartsWithNsjAsync( | ||
| string packageIdPrefix, | ||
| bool includePrerelease, | ||
| Common.ILogger log, | ||
| CancellationToken token) | ||
| { | ||
| var queryUri = BuildQueryUri(packageIdPrefix, includePrerelease); | ||
| Common.ILogger logger = log ?? Common.NullLogger.Instance; | ||
|
|
||
| var queryUri = queryUrl.Uri; | ||
| var results = await _client.GetJObjectAsync( | ||
| new HttpSourceRequest(queryUri, logger), | ||
| logger, | ||
|
|
@@ -83,6 +127,25 @@ public override async Task<IEnumerable<string>> IdStartsWith( | |
| return outputs.Where(item => item.StartsWith(packageIdPrefix, StringComparison.OrdinalIgnoreCase)); | ||
| } | ||
|
|
||
| private Uri BuildQueryUri(string packageIdPrefix, bool includePrerelease) | ||
| { | ||
| var searchUrl = _serviceIndex.GetServiceEntryUri(ServiceTypes.SearchAutocompleteService); | ||
|
|
||
| if (searchUrl == null) | ||
| { | ||
| throw new FatalProtocolException(Strings.Protocol_MissingSearchService); | ||
| } | ||
|
|
||
| // Construct the query | ||
| var queryUrl = new UriBuilder(searchUrl.AbsoluteUri); | ||
| queryUrl.Query = | ||
| "q=" + WebUtility.UrlEncode(packageIdPrefix) + | ||
| "&prerelease=" + includePrerelease.ToString(CultureInfo.CurrentCulture).ToLowerInvariant() + | ||
| "&semVerLevel=2.0.0"; | ||
|
|
||
| return queryUrl.Uri; | ||
| } | ||
|
|
||
| public override async Task<IEnumerable<NuGetVersion>> VersionStartsWith( | ||
| string packageId, | ||
| string versionPrefix, | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
50 changes: 50 additions & 0 deletions
50
test/NuGet.Core.Tests/NuGet.Protocol.Tests/NuGetFeatureFlagsTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| // 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.Collections.Generic; | ||
| using NuGet.Shared; | ||
| using Test.Utility; | ||
| using Xunit; | ||
|
|
||
| namespace NuGet.Protocol.Tests | ||
| { | ||
| public class NuGetFeatureFlagsTests | ||
| { | ||
| [Fact] | ||
| public void UseLegacyJsonDeserializationFeatureSwitch_Default_ReturnsFalse() | ||
| { | ||
| Assert.False(NuGetFeatureFlags.UseLegacyJsonDeserializationFeatureSwitch); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void IsLegacyJsonDeserializationEnabledByEnvironment_WhenEnvVarNotSet_ReturnsFalse() | ||
| { | ||
| Assert.False(NuGetFeatureFlags.IsLegacyJsonDeserializationEnabledByEnvironment(TestEnvironmentVariableReader.EmptyInstance)); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData("true")] | ||
| [InlineData("True")] | ||
| [InlineData("TRUE")] | ||
| public void IsLegacyJsonDeserializationEnabledByEnvironment_WhenEnvVarSetToTrue_ReturnsTrue(string value) | ||
| { | ||
| var env = new TestEnvironmentVariableReader( | ||
| new Dictionary<string, string> { [NuGetFeatureFlags.UseLegacyJsonDeserializationEnvVar] = value }); | ||
|
|
||
| Assert.True(NuGetFeatureFlags.IsLegacyJsonDeserializationEnabledByEnvironment(env)); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData("false")] | ||
| [InlineData("0")] | ||
| [InlineData("1")] | ||
| [InlineData("anything")] | ||
| public void IsLegacyJsonDeserializationEnabledByEnvironment_WhenEnvVarSetToFalseOrUnrecognized_ReturnsFalse(string value) | ||
| { | ||
| var env = new TestEnvironmentVariableReader( | ||
| new Dictionary<string, string> { [NuGetFeatureFlags.UseLegacyJsonDeserializationEnvVar] = value }); | ||
|
|
||
| Assert.False(NuGetFeatureFlags.IsLegacyJsonDeserializationEnabledByEnvironment(env)); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am surprised that
AutoCompleteModelis always non-null. Is that correct?Does this library not have nullable enabled?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not yet. It's #nullable disabled for now, but it's a work in progress