From d85f5cff164f161c613d6ea212ea1e6b6fcdf92f Mon Sep 17 00:00:00 2001 From: Paul Irwin Date: Mon, 26 Oct 2026 15:46:14 -0600 Subject: [PATCH] Add a search page to the web UI (closes #92) The dashboard gains a Search page that queries any index through the Azure SDK rather than the searcher directly, so it shows exactly what an application would get. It covers query type (including semantic), search mode, $filter, $orderby, $select, search fields, facets, highlighting, scoring profiles, $top and $count, and renders results as cards with scores, highlights, captions, answers and facets. Request and Response tabs show the raw HTTP exchange the SDK made, with server-side JSON syntax highlighting. The SDK only accepts https endpoints, so it is handed one and its transport rewrites each request onto whichever binding Kestrel reports, over loopback with certificate validation skipped. The exchange is recorded by a pipeline policy so the headers are the ones the SDK sent. Two bugs surfaced along the way: - GET /indexes threw on $select, because [EnableQuery] treated the repository's IAsyncEnumerable as a single entity. The SDK's GetIndexNamesAsync sends $select=name, so it failed outright. - The Docker image shipped without blazor.web.js. The SDK only restores the package carrying it when it sees .razor files, and the Dockerfile restores from the project file alone. The dashboard prerendered but never went interactive. RequiresAspNetWebAssets is now set explicitly. Co-Authored-By: Claude Opus 5.5 --- .../DashboardIntegrationTests.cs | 38 ++ .../EmulatorIntegrationTests.cs | 28 + .../SearchPageTests.cs | 157 +++++ .../AzureSearchEmulator.csproj | 6 + .../Components/Layout/MainLayout.razor | 4 + .../Components/Pages/Search.razor | 631 ++++++++++++++++++ .../Components/Shared/Headers.razor | 17 + .../Components/Shared/HttpExchangeView.razor | 50 ++ .../Components/Shared/JsonView.razor | 69 ++ AzureSearchEmulator/Components/_Imports.razor | 2 + .../Controllers/IndexesController.cs | 18 +- .../Dashboard/DocumentValueFormatter.cs | 70 ++ .../Dashboard/EmulatorClientFactory.cs | 113 ++++ .../Dashboard/HighlightMarkup.cs | 24 + .../Dashboard/HttpExchangeRecorder.cs | 117 ++++ .../Dashboard/JsonHighlighter.cs | 190 ++++++ .../Dashboard/LoopbackEndpoint.cs | 67 ++ .../Dashboard/SearchQueryForm.cs | 172 +++++ AzureSearchEmulator/Program.cs | 4 + AzureSearchEmulator/wwwroot/css/dashboard.css | 566 +++++++++++++++- README.md | 4 + 21 files changed, 2344 insertions(+), 3 deletions(-) create mode 100644 AzureSearchEmulator.UnitTests/SearchPageTests.cs create mode 100644 AzureSearchEmulator/Components/Pages/Search.razor create mode 100644 AzureSearchEmulator/Components/Shared/Headers.razor create mode 100644 AzureSearchEmulator/Components/Shared/HttpExchangeView.razor create mode 100644 AzureSearchEmulator/Components/Shared/JsonView.razor create mode 100644 AzureSearchEmulator/Dashboard/DocumentValueFormatter.cs create mode 100644 AzureSearchEmulator/Dashboard/EmulatorClientFactory.cs create mode 100644 AzureSearchEmulator/Dashboard/HighlightMarkup.cs create mode 100644 AzureSearchEmulator/Dashboard/HttpExchangeRecorder.cs create mode 100644 AzureSearchEmulator/Dashboard/JsonHighlighter.cs create mode 100644 AzureSearchEmulator/Dashboard/LoopbackEndpoint.cs create mode 100644 AzureSearchEmulator/Dashboard/SearchQueryForm.cs diff --git a/AzureSearchEmulator.IntegrationTests/DashboardIntegrationTests.cs b/AzureSearchEmulator.IntegrationTests/DashboardIntegrationTests.cs index 0af895f..8b9192a 100644 --- a/AzureSearchEmulator.IntegrationTests/DashboardIntegrationTests.cs +++ b/AzureSearchEmulator.IntegrationTests/DashboardIntegrationTests.cs @@ -38,6 +38,27 @@ public async Task Root_ServesTheDashboard() Assert.Contains("Running normally", html); } + /// + /// The search page renders only once its circuit connects (issue #92), so the static response + /// carries the layout rather than results; what this guards is the route existing alongside the + /// API's own routes and the navigation reaching it. + /// + [Fact] + public async Task Search_ServesThePage() + { + await factory.WaitUntilServingAsync(); + using var client = factory.CreateHttpClient(); + + var response = await client.GetAsync("/search", TestContext.Current.CancellationToken); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal("text/html", response.Content.Headers.ContentType?.MediaType); + + var html = await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken); + + Assert.Contains("href=\"search\" class=\"topnav-link active\"", html); + } + [Fact] public async Task Dashboard_StylesheetIsServed() { @@ -50,6 +71,23 @@ public async Task Dashboard_StylesheetIsServed() Assert.Equal("text/css", response.Content.Headers.ContentType?.MediaType); } + /// + /// Without Blazor's script the pages still prerender, so the dashboard looks fine, but nothing + /// interactive ever starts and the search page, which is not prerendered, stays blank. The + /// script comes from a package the SDK can leave out of a publish while dotnet run keeps + /// working, so it is checked here against the built image (issue #92). + /// + [Fact] + public async Task Dashboard_BlazorScriptIsServed() + { + await factory.WaitUntilServingAsync(); + using var client = factory.CreateHttpClient(); + + var response = await client.GetAsync("/_framework/blazor.web.js", TestContext.Current.CancellationToken); + + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + /// /// The container has a writable indexes volume and no malformed definitions, so a healthy /// answer here is the real thing rather than a check that cannot fail — the unit tests cover diff --git a/AzureSearchEmulator.IntegrationTests/EmulatorIntegrationTests.cs b/AzureSearchEmulator.IntegrationTests/EmulatorIntegrationTests.cs index 3241f37..3240143 100644 --- a/AzureSearchEmulator.IntegrationTests/EmulatorIntegrationTests.cs +++ b/AzureSearchEmulator.IntegrationTests/EmulatorIntegrationTests.cs @@ -37,6 +37,34 @@ public async Task CreateIndex_ShouldSucceed() await indexClient.DeleteIndexAsync(indexName, TestContext.Current.CancellationToken); } + /// + /// The SDK lists names with $select=name, which the listing endpoint used to throw on + /// (found while building the dashboard's search page, issue #92). + /// + [Fact] + public async Task GetIndexNames_ShouldListCreatedIndex() + { + const string indexName = "test-get-index-names"; + var indexClient = factory.CreateSearchIndexClient(); + await CreateIndexAsync(indexClient, indexName); + + try + { + var names = new List(); + + await foreach (var name in indexClient.GetIndexNamesAsync(TestContext.Current.CancellationToken)) + { + names.Add(name); + } + + Assert.Contains(indexName, names); + } + finally + { + await indexClient.DeleteIndexAsync(indexName, TestContext.Current.CancellationToken); + } + } + [Fact] public async Task UploadDocuments_ShouldSucceed() { diff --git a/AzureSearchEmulator.UnitTests/SearchPageTests.cs b/AzureSearchEmulator.UnitTests/SearchPageTests.cs new file mode 100644 index 0000000..a2fe985 --- /dev/null +++ b/AzureSearchEmulator.UnitTests/SearchPageTests.cs @@ -0,0 +1,157 @@ +using Azure.Search.Documents.Models; +using AzureSearchEmulator.Dashboard; +using Xunit; + +namespace AzureSearchEmulator.UnitTests; + +/// +/// Tests for the pieces behind the dashboard's search page (issue #92) that do not need a running +/// emulator: how its inputs become SDK options, how it reaches itself, and how it renders JSON and +/// highlights. +/// +public class SearchPageTests +{ + [Theory] + [InlineData(new[] { "http://localhost:5123" }, "http://localhost:5123/")] + [InlineData(new[] { "https://+:8443" }, "https://localhost:8443/")] + [InlineData(new[] { "http://*:80" }, "http://localhost/")] + [InlineData(new[] { "http://0.0.0.0:8080" }, "http://127.0.0.1:8080/")] + [InlineData(new[] { "http://[::]:8080" }, "http://localhost:8080/")] + [InlineData(new[] { "https://localhost:5001", "http://localhost:5000" }, "http://localhost:5000/")] + public void LoopbackEndpoint_ConnectsToABinding(string[] addresses, string expected) + { + Assert.Equal(new Uri(expected), LoopbackEndpoint.Resolve(addresses)); + } + + [Fact] + public void LoopbackEndpoint_WithNoUsableBinding_IsNull() + { + Assert.Null(LoopbackEndpoint.Resolve([])); + Assert.Null(LoopbackEndpoint.Resolve(["unix:/tmp/emulator.sock"])); + } + + [Fact] + public void SplitList_KeepsCommasInsideFunctionsAndQuotes() + { + var items = SearchQueryForm.SplitList("geo.distance(location, geography'POINT(-122 47)') asc, rating desc,, name "); + + Assert.Equal(["geo.distance(location, geography'POINT(-122 47)') asc", "rating desc", "name"], items); + } + + [Fact] + public void SplitFacets_KeepsParametersWithTheirField() + { + var facets = SearchQueryForm.SplitFacets("category, rating,interval:1, tags,count:5,sort:value"); + + Assert.Equal(["category", "rating,interval:1", "tags,count:5,sort:value"], facets); + } + + [Fact] + public void ToSearchOptions_OmitsBlankInputs() + { + var options = new SearchQueryForm { Filter = " " }.ToSearchOptions(); + + Assert.Null(options.Filter); + Assert.Null(options.Skip); + Assert.Null(options.SemanticSearch); + Assert.Empty(options.OrderBy); + Assert.Empty(options.Facets); + Assert.Equal(SearchQueryForm.DefaultTop, options.Size); + Assert.True(options.IncludeTotalCount); + } + + [Fact] + public void ToSearchOptions_CarriesEveryInput() + { + var form = new SearchQueryForm + { + QueryType = "semantic", + SearchMode = "all", + Filter = "rating ge 4", + OrderBy = "rating desc, name", + Select = "id, name", + SearchFields = "name", + Facets = "category", + Highlight = "description", + ScoringProfile = "boost", + SemanticConfiguration = "default", + Top = 5, + Skip = 10, + IncludeTotalCount = false + }; + + var options = form.ToSearchOptions(); + + Assert.Equal(SearchQueryType.Semantic, options.QueryType); + Assert.Equal(SearchMode.All, options.SearchMode); + Assert.Equal("rating ge 4", options.Filter); + Assert.Equal(["rating desc", "name"], options.OrderBy); + Assert.Equal(["id", "name"], options.Select); + Assert.Equal(["name"], options.SearchFields); + Assert.Equal(["category"], options.Facets); + Assert.Equal(["description"], options.HighlightFields); + Assert.Equal("boost", options.ScoringProfile); + Assert.Equal("default", options.SemanticSearch.SemanticConfigurationName); + Assert.Equal(5, options.Size); + Assert.Equal(10, options.Skip); + Assert.False(options.IncludeTotalCount); + } + + [Fact] + public void JsonHighlighter_ClassifiesTokens() + { + var tokens = JsonHighlighter.Tokenize("""{"name": "Fancy \"Inn\"", "rating": -4.5e1, "open": true, "tags": null}"""); + + Assert.Contains(new JsonToken(JsonTokenKind.Key, "\"name\""), tokens); + Assert.Contains(new JsonToken(JsonTokenKind.String, "\"Fancy \\\"Inn\\\"\""), tokens); + Assert.Contains(new JsonToken(JsonTokenKind.Number, "-4.5e1"), tokens); + Assert.Contains(new JsonToken(JsonTokenKind.Boolean, "true"), tokens); + Assert.Contains(new JsonToken(JsonTokenKind.Null, "null"), tokens); + Assert.Contains(new JsonToken(JsonTokenKind.Punctuation, "{"), tokens); + } + + [Theory] + [InlineData("""{"a": [1, 2, {"b": "c"}]}""")] + [InlineData("""{"unterminated": "oops""")] + [InlineData("not json at all")] + public void JsonHighlighter_TokensReproduceTheInput(string json) + { + var tokens = JsonHighlighter.Tokenize(json); + + Assert.Equal(json, string.Concat(tokens.Select(i => i.Text))); + } + + [Fact] + public void JsonHighlighter_Format_IndentsWithoutEscapingMarkup() + { + var formatted = JsonHighlighter.Format("""{"text":"a b"}"""); + + Assert.Equal("{\n \"text\": \"a b\"\n}", formatted.ReplaceLineEndings("\n")); + } + + [Fact] + public void JsonHighlighter_Format_LeavesInvalidJsonAlone() + { + Assert.Equal("oops", JsonHighlighter.Format("oops")); + } + + [Fact] + public void HighlightMarkup_EncodesDocumentTextButKeepsEmphasis() + { + var markup = HighlightMarkup.Render(" the hotel & spa"); + + Assert.Equal("<script>x</script> the hotel & spa", markup.Value); + } + + [Fact] + public void DocumentValueFormatter_SummarisesVectors() + { + var vector = Enumerable.Range(0, 1536).Select(i => (object)(double)i).ToArray(); + + Assert.Equal("[1536 numbers]", DocumentValueFormatter.Format(vector)); + Assert.Equal("[1,2,3]", DocumentValueFormatter.Format(new object[] { 1, 2, 3 })); + Assert.Equal("[\"a\",\"b\"]", DocumentValueFormatter.Format(new object[] { "a", "b" })); + Assert.Equal("4.5", DocumentValueFormatter.Format(4.5)); + Assert.Equal("null", DocumentValueFormatter.Format(null)); + } +} diff --git a/AzureSearchEmulator/AzureSearchEmulator.csproj b/AzureSearchEmulator/AzureSearchEmulator.csproj index 68425df..1c11d6a 100644 --- a/AzureSearchEmulator/AzureSearchEmulator.csproj +++ b/AzureSearchEmulator/AzureSearchEmulator.csproj @@ -21,9 +21,15 @@ Paul Irwin logo.png README.md + + true + diff --git a/AzureSearchEmulator/Components/Layout/MainLayout.razor b/AzureSearchEmulator/Components/Layout/MainLayout.razor index 9bfc2f1..fb90392 100644 --- a/AzureSearchEmulator/Components/Layout/MainLayout.razor +++ b/AzureSearchEmulator/Components/Layout/MainLayout.razor @@ -15,6 +15,10 @@ Local development service +
diff --git a/AzureSearchEmulator/Components/Pages/Search.razor b/AzureSearchEmulator/Components/Pages/Search.razor new file mode 100644 index 0000000..24eee9f --- /dev/null +++ b/AzureSearchEmulator/Components/Pages/Search.razor @@ -0,0 +1,631 @@ +@page "/search" +@using System.Text.Json +@using Azure +@using Azure.Search.Documents.Models +@using AzureSearchEmulator.Dashboard +@using SdkSearchIndex = Azure.Search.Documents.Indexes.Models.SearchIndex +@using SdkSearchField = Azure.Search.Documents.Indexes.Models.SearchField +@using SdkFieldType = Azure.Search.Documents.Indexes.Models.SearchFieldDataType +@* Not prerendered: every load queries the emulator through the SDK, and prerendering would run each + of those twice — once for the static pass and again when the circuit takes over. *@ +@rendermode @(new InteractiveServerRenderMode(prerender: false)) +@inject EmulatorClientFactory Clients +@inject NavigationManager Navigation + +Search · Azure Search Emulator + +

Search an index

+ +@if (_loadError is not null) +{ +
+

Could not list indexes

+

@_loadError

+
+} +else if (_indexNames is null) +{ +
+ +

Loading indexes…

+
+} +else if (_indexNames.Count == 0) +{ +
+

No indexes yet

+

+ Create an index through the REST API or an Azure SDK client pointed at this emulator, and + it will be listed here to search. +

+
+} +else +{ +
+
+ + + +
+ +
+ Query options +
+ + + @if (_form.IsSemantic) + { + + } + @if (_index?.ScoringProfiles.Count > 0) + { + + } + + + + + + + + +
+
+
+ + @if (_exchange is not null || _error is not null) + { +
+
+ + @if (_exchange is not null) + { + + + } +
+ +
+ @switch (_tab) + { + case ResultsTab.Request when _exchange is not null: + + break; + case ResultsTab.Response when _exchange is not null: + + break; + default: + @RenderResults() + break; + } +
+
+ } +} + +@code { + private enum ResultsTab + { + Results, + Request, + Response + } + + /// What the page needs to know about the selected index to offer its options. + private sealed record IndexDetails( + string Name, + string? KeyField, + string? TitleField, + IReadOnlyList ScoringProfiles, + IReadOnlyList SemanticConfigurations); + + private sealed record ResultsView( + long? TotalCount, + IReadOnlyList> Items, + IDictionary> Facets, + IReadOnlyList Answers, + int Skip); + + [SupplyParameterFromQuery(Name = "index")] + public string? IndexQuery { get; set; } + + [SupplyParameterFromQuery(Name = "q")] + public string? SearchQuery { get; set; } + + private readonly SearchQueryForm _form = new(); + + private IReadOnlyList? _indexNames; + private string? _loadError; + private string? _indexName; + private IndexDetails? _index; + + private bool _searching; + private ResultsView? _results; + private string? _error; + private HttpExchange? _exchange; + private ResultsTab _tab; + + protected override async Task OnInitializedAsync() + { + try + { + var names = new List(); + + await foreach (var name in Clients.CreateIndexClient().GetIndexNamesAsync()) + { + names.Add(name); + } + + names.Sort(StringComparer.OrdinalIgnoreCase); + _indexNames = names; + } + catch (Exception ex) when (ex is RequestFailedException or HttpRequestException or InvalidOperationException) + { + _loadError = ex.Message; + return; + } + + if (_indexNames.Count == 0) + { + return; + } + + _form.SearchText = SearchQuery ?? ""; + + var initial = _indexNames.FirstOrDefault(i => string.Equals(i, IndexQuery, StringComparison.OrdinalIgnoreCase)) + ?? _indexNames[0]; + + await SelectIndexAsync(initial); + } + + private async Task IndexChangedAsync(ChangeEventArgs e) + { + if (e.Value is string name && name != _indexName) + { + await SelectIndexAsync(name); + } + } + + /// + /// Switches to an index and searches it straight away, so choosing an index shows what is in it + /// without a second click. + /// + private async Task SelectIndexAsync(string name) + { + _indexName = name; + _index = null; + _results = null; + _exchange = null; + _error = null; + + try + { + var response = await Clients.CreateIndexClient().GetIndexAsync(name); + _index = Describe(response.Value); + } + catch (RequestFailedException ex) + { + _error = ex.Message; + return; + } + + // Options naming things on the previous index would fail against this one. + _form.ScoringProfile = ""; + _form.SemanticConfiguration = _index.SemanticConfigurations.FirstOrDefault() ?? ""; + + if (_form.IsSemantic && _index.SemanticConfigurations.Count == 0) + { + _form.QueryType = "simple"; + } + + _form.Skip = 0; + await RunSearchAsync(); + } + + private async Task SubmitAsync() + { + _form.Skip = 0; + await RunSearchAsync(); + } + + private async Task PageAsync(int direction) + { + _form.Skip = Math.Max(0, _form.Skip + direction * Math.Max(1, _form.Top)); + await RunSearchAsync(); + } + + private async Task RunSearchAsync() + { + if (_indexName is null || _searching) + { + return; + } + + _searching = true; + _error = null; + + var recorder = new HttpExchangeRecorder(); + var client = Clients.CreateSearchClient(_indexName, recorder); + var searchText = string.IsNullOrWhiteSpace(_form.SearchText) ? "*" : _form.SearchText; + + try + { + var response = await client.SearchAsync(searchText, _form.ToSearchOptions()); + var results = response.Value; + + // Only the first page, which arrived with the response. Enumerating further would have + // the SDK follow continuation links with requests of its own, and the page shows one + // request at a time. + IReadOnlyList> items = []; + + await foreach (var page in results.GetResultsAsync().AsPages()) + { + items = page.Values; + break; + } + + _results = new ResultsView( + results.TotalCount, + items, + results.Facets ?? new Dictionary>(), + results.SemanticSearch?.Answers ?? [], + _form.Skip); + + UpdateAddress(); + } + catch (RequestFailedException ex) + { + _results = null; + _error = ErrorMessage(recorder.LastExchange) ?? ex.Message; + } + catch (HttpRequestException ex) + { + _results = null; + _error = ex.Message; + } + finally + { + _exchange = recorder.LastExchange; + _searching = false; + } + } + + /// + /// Keeps the index and query in the address bar, so a reload or a copied link comes back to the + /// same search. + /// + private void UpdateAddress() + { + var address = Navigation.GetUriWithQueryParameters(new Dictionary + { + ["index"] = _indexName, + ["q"] = string.IsNullOrWhiteSpace(_form.SearchText) ? null : _form.SearchText + }); + + if (address != Navigation.Uri) + { + Navigation.NavigateTo(address, replace: true); + } + } + + /// + /// The message from the emulator's error envelope. The SDK's own exception message appends the + /// status, headers and raw content, all of which the Response tab already shows properly. + /// + private static string? ErrorMessage(HttpExchange? exchange) + { + if (exchange?.Response?.Body is not { Length: > 0 } body) + { + return null; + } + + try + { + using var document = JsonDocument.Parse(body); + + return document.RootElement.TryGetProperty("error", out var error) + && error.TryGetProperty("message", out var message) + && message.ValueKind == JsonValueKind.String + ? message.GetString() + : null; + } + catch (JsonException) + { + return null; + } + } + + private static IndexDetails Describe(SdkSearchIndex index) + { + var key = index.Fields.FirstOrDefault(i => i.IsKey == true)?.Name; + var semanticTitle = index.SemanticSearch?.Configurations.FirstOrDefault()?.PrioritizedFields?.TitleField?.FieldName; + + return new IndexDetails( + index.Name, + key, + semanticTitle ?? FindTitleField(index.Fields, key), + index.ScoringProfiles.Select(i => i.Name).ToList(), + index.SemanticSearch?.Configurations.Select(i => i.Name).ToList() ?? []); + } + + /// + /// A string field that looks like a title or name, to head each result card with when no semantic + /// configuration names one. Without either, the card is headed with the document key. + /// + private static string? FindTitleField(IList fields, string? key) + { + var candidates = fields + .Where(i => i.Type == SdkFieldType.String && i.Name != key && i.IsHidden != true) + .Select(i => i.Name) + .ToList(); + + return candidates.FirstOrDefault(i => i.Contains("title", StringComparison.OrdinalIgnoreCase)) + ?? candidates.FirstOrDefault(i => i.Contains("name", StringComparison.OrdinalIgnoreCase)); + } + + private RenderFragment RenderResults() => __builder => + { + if (_error is not null) + { + + return; + } + + if (_results is null) + { + return; + } + + var results = _results; + var first = results.Skip + 1; + var last = results.Skip + results.Items.Count; + +

+ @if (results.Items.Count == 0) + { + No documents matched. + } + else + { + Showing @first–@last + @if (results.TotalCount is { } total) + { + of @total.ToString("N0") + } + } + @if (_exchange is not null) + { + · @_exchange.Duration.TotalMilliseconds.ToString("0") ms + } +

+ + @foreach (var answer in results.Answers) + { +
+

Semantic answer

+

@HighlightMarkup.Render(answer.Highlights ?? answer.Text ?? "")

+
+ } + + @if (results.Facets.Count > 0) + { +
+ @foreach (var (field, values) in results.Facets) + { +
+

@field

+
    + @foreach (var facet in values) + { +
  • + @FacetLabel(facet) + @facet.Count +
  • + } +
+
+ } +
+ } + +
    + @foreach (var result in results.Items) + { + @RenderResult(result) + } +
+ + @if (results.Skip > 0 || HasNextPage(results)) + { +
+ + +
+ } + }; + + private RenderFragment RenderResult(SearchResult result) => __builder => + { + var document = result.Document; + var key = _index?.KeyField is { } keyField && document.TryGetValue(keyField, out var keyValue) + ? DocumentValueFormatter.Format(keyValue) + : null; + var title = _index?.TitleField is { } titleField && document.TryGetValue(titleField, out var titleValue) && titleValue is string s + ? s + : null; + +
  • +
    +
    +

    @(title ?? key ?? "(no key)")

    + @if (title is not null && key is not null) + { + @key + } +
    +
    + @if (result.SemanticSearch?.RerankerScore is { } reranker) + { + reranker @reranker.ToString("0.###") + } + @if (result.Score is { } score) + { + score @score.ToString("0.####") + } +
    +
    + + @if (result.SemanticSearch?.Captions is { Count: > 0 } captions) + { + @foreach (var caption in captions) + { +

    @HighlightMarkup.Render(caption.Highlights ?? caption.Text ?? "")

    + } + } + + @if (result.Highlights is { Count: > 0 } highlights) + { +
    + @foreach (var (field, fragments) in highlights) + { +
    @field
    + @foreach (var fragment in fragments) + { +
    @HighlightMarkup.Render(fragment)
    + } + } +
    + } + +
    + @foreach (var (name, value) in document) + { + // Both are already in the card's heading. + if ((name == _index?.TitleField && title is not null) || (name == _index?.KeyField && key is not null)) + { + continue; + } + +
    @name
    +
    @DocumentValueFormatter.Format(value)
    + } +
    +
  • + }; + + private bool HasNextPage(ResultsView results) => + results.TotalCount is { } total + ? results.Skip + results.Items.Count < total + : results.Items.Count > 0 && results.Items.Count == _form.Top; + + /// + /// Range buckets are open at the ends: the first has no lower bound and the last no upper one. + /// + private static string FacetLabel(FacetResult facet) => facet switch + { + { Value: { } value } => DocumentValueFormatter.Format(value), + { From: null, To: { } to } => $"< {DocumentValueFormatter.Format(to)}", + { From: { } from, To: null } => $"≥ {DocumentValueFormatter.Format(from)}", + _ => $"{DocumentValueFormatter.Format(facet.From)} – {DocumentValueFormatter.Format(facet.To)}" + }; +} diff --git a/AzureSearchEmulator/Components/Shared/Headers.razor b/AzureSearchEmulator/Components/Shared/Headers.razor new file mode 100644 index 0000000..a9c1840 --- /dev/null +++ b/AzureSearchEmulator/Components/Shared/Headers.razor @@ -0,0 +1,17 @@ +@* Collapsed by default: the body is what a reader is usually after, and the SDK sends enough + headers to push it below the fold. *@ +
    + Headers (@Items.Count) +
    + @foreach (var (name, value) in Items) + { +
    @name
    +
    @value
    + } +
    +
    + +@code { + [Parameter, EditorRequired] + public IReadOnlyList> Items { get; set; } = []; +} diff --git a/AzureSearchEmulator/Components/Shared/HttpExchangeView.razor b/AzureSearchEmulator/Components/Shared/HttpExchangeView.razor new file mode 100644 index 0000000..c0d0d99 --- /dev/null +++ b/AzureSearchEmulator/Components/Shared/HttpExchangeView.razor @@ -0,0 +1,50 @@ +@using AzureSearchEmulator.Dashboard + +@* One side of a recorded SDK round trip, laid out as the HTTP message it was (issue #92). *@ +@if (ShowResponse) +{ + @if (Exchange.Response is { } response) + { +
    + @response.Status @response.ReasonPhrase + @FormatDuration(Exchange.Duration) +
    + + @if (!string.IsNullOrEmpty(response.Body)) + { + + } + else + { +

    No response body.

    + } + } + else + { +

    No response was received.

    + } +} +else +{ +
    + @Exchange.Method + @Exchange.PathAndQuery +
    + + @if (!string.IsNullOrEmpty(Exchange.RequestBody)) + { + + } +} + +@code { + [Parameter, EditorRequired] + public HttpExchange Exchange { get; set; } = null!; + + [Parameter] + public bool ShowResponse { get; set; } + + private static string StatusClass(int status) => status < 400 ? "is-healthy" : "is-unhealthy"; + + private static string FormatDuration(TimeSpan duration) => $"{duration.TotalMilliseconds:0} ms"; +} diff --git a/AzureSearchEmulator/Components/Shared/JsonView.razor b/AzureSearchEmulator/Components/Shared/JsonView.razor new file mode 100644 index 0000000..00a802f --- /dev/null +++ b/AzureSearchEmulator/Components/Shared/JsonView.razor @@ -0,0 +1,69 @@ +@using AzureSearchEmulator.Dashboard +@inject IJSRuntime JS + +@* Indented, syntax-coloured JSON (issue #92). Formatting and tokenizing happen once per change of + Json rather than on every render, since the search page re-renders on every interaction with its + form. *@ +
    +
    @foreach (var token in _tokens)
    +{
    +    if (token.Kind == JsonTokenKind.Plain)
    +    {
    +        @token.Text
    +    }
    +    else
    +    {
    +        @token.Text
    +    }
    +}
    + +
    + +@code { + [Parameter, EditorRequired] + public string Json { get; set; } = ""; + + private string? _rendered; + private string _formatted = ""; + private IReadOnlyList _tokens = []; + private bool _copied; + + protected override void OnParametersSet() + { + if (Json == _rendered) + { + return; + } + + _rendered = Json; + _formatted = JsonHighlighter.Format(Json); + _tokens = JsonHighlighter.Tokenize(_formatted); + _copied = false; + } + + private async Task CopyAsync() + { + try + { + // Straight to the browser's clipboard API, so the dashboard still ships no script of + // its own. It is only available to secure contexts, which localhost counts as. + await JS.InvokeVoidAsync("navigator.clipboard.writeText", _formatted); + _copied = true; + } + catch (JSException) + { + // Served from a non-localhost http:// address, where the clipboard is off limits. The + // text can still be selected by hand. + } + } + + private static string TokenClass(JsonTokenKind kind) => kind switch + { + JsonTokenKind.Key => "tok-key", + JsonTokenKind.String => "tok-string", + JsonTokenKind.Number => "tok-number", + JsonTokenKind.Boolean => "tok-literal", + JsonTokenKind.Null => "tok-literal", + _ => "tok-punct" + }; +} diff --git a/AzureSearchEmulator/Components/_Imports.razor b/AzureSearchEmulator/Components/_Imports.razor index fff5ff8..121e418 100644 --- a/AzureSearchEmulator/Components/_Imports.razor +++ b/AzureSearchEmulator/Components/_Imports.razor @@ -1,8 +1,10 @@ @using System.Net.Http @using Microsoft.AspNetCore.Components.Routing @using Microsoft.AspNetCore.Components.Web +@using Microsoft.JSInterop @using static Microsoft.AspNetCore.Components.Web.RenderMode @using Microsoft.Extensions.Diagnostics.HealthChecks @using AzureSearchEmulator.Components @using AzureSearchEmulator.Components.Layout @using AzureSearchEmulator.Health +@using AzureSearchEmulator.Components.Shared diff --git a/AzureSearchEmulator/Controllers/IndexesController.cs b/AzureSearchEmulator/Controllers/IndexesController.cs index d2ce1c5..686bc0a 100644 --- a/AzureSearchEmulator/Controllers/IndexesController.cs +++ b/AzureSearchEmulator/Controllers/IndexesController.cs @@ -28,13 +28,27 @@ public class IndexesController( /// Azure Search SDK expects and dropping [EnableQuery], so it is left as-is: a /// listing is a survey rather than the definition a client edits and writes back, and the /// round-trip that issue #41 is about goes through the single-index routes. + /// + /// Materialized into a queryable rather than returned as the repository's async stream: + /// [EnableQuery] does not recognise an as a + /// collection, and applied $select to the stream as though it were a single index — + /// which threw, so SearchIndexClient.GetIndexNamesAsync, which sends + /// $select=name, failed against the emulator. + /// /// [HttpGet] [EnableQuery] [Route("indexes")] - public IAsyncEnumerable Get() + public async Task> Get() { - return searchIndexRepository.GetAll(); + var indexes = new List(); + + await foreach (var index in searchIndexRepository.GetAll()) + { + indexes.Add(index); + } + + return indexes.AsQueryable(); } /// diff --git a/AzureSearchEmulator/Dashboard/DocumentValueFormatter.cs b/AzureSearchEmulator/Dashboard/DocumentValueFormatter.cs new file mode 100644 index 0000000..4e452a3 --- /dev/null +++ b/AzureSearchEmulator/Dashboard/DocumentValueFormatter.cs @@ -0,0 +1,70 @@ +using System.Collections; +using System.Globalization; +using System.Text.Encodings.Web; +using System.Text.Json; + +namespace AzureSearchEmulator.Dashboard; + +/// +/// Turns a field value from an SDK search result into the text the search page shows for it +/// (issue #92). +/// +public static class DocumentValueFormatter +{ + /// + /// Collections of numbers longer than this are summarised instead of listed. Anything that long + /// is a vector in practice, and a few hundred dimensions of floats tell a reader nothing beyond + /// how many there are. + /// + public const int MaxListedNumbers = 8; + + private static readonly JsonSerializerOptions JsonOptions = new() + { + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping + }; + + public static string Format(object? value) => value switch + { + null => "null", + string s => s, + bool b => b ? "true" : "false", + DateTimeOffset d => d.ToString("O", CultureInfo.InvariantCulture), + IFormattable f when IsNumber(value) => f.ToString(null, CultureInfo.InvariantCulture), + IEnumerable list and not IDictionary when IsLongNumberList(list, out var count) => $"[{count} numbers]", + _ => ToJson(value) + }; + + private static bool IsLongNumberList(IEnumerable list, out int count) + { + count = 0; + + foreach (var item in list) + { + if (!IsNumber(item)) + { + return false; + } + + count++; + } + + return count > MaxListedNumbers; + } + + private static bool IsNumber(object? value) => + value is int or long or double or float or decimal or short or byte or sbyte; + + private static string ToJson(object value) + { + try + { + return JsonSerializer.Serialize(value, JsonOptions); + } + catch (Exception ex) when (ex is NotSupportedException or JsonException or InvalidOperationException) + { + // Geography values and the like deserialize to SDK types System.Text.Json has no + // converter for; their ToString is at least recognisable. + return value.ToString() ?? ""; + } + } +} diff --git a/AzureSearchEmulator/Dashboard/EmulatorClientFactory.cs b/AzureSearchEmulator/Dashboard/EmulatorClientFactory.cs new file mode 100644 index 0000000..809059a --- /dev/null +++ b/AzureSearchEmulator/Dashboard/EmulatorClientFactory.cs @@ -0,0 +1,113 @@ +using Azure; +using Azure.Core.Pipeline; +using Azure.Search.Documents; +using Azure.Search.Documents.Indexes; +using Microsoft.AspNetCore.Hosting.Server; +using Microsoft.AspNetCore.Hosting.Server.Features; + +namespace AzureSearchEmulator.Dashboard; + +/// +/// Creates Azure SDK clients that talk to this emulator, for the dashboard's search page +/// (issue #92). +/// +/// +/// +/// The page goes through the SDK and the HTTP API rather than calling the searcher directly so that +/// what it shows is what an application would get: the same parsing, the same error envelope, the +/// same response shape, and a raw request and response that can be copied into a real client. +/// +/// +/// The SDK refuses any endpoint that is not https, which the emulator's default plain-HTTP binding +/// cannot satisfy. So the SDK is handed an https URI on the right port and the transport rewrites +/// each request onto whichever binding picks. That transport also +/// skips certificate validation, which the SDK itself never allows: the connection is from this +/// process to its own listener, so there is no one to authenticate, and the certificate the +/// emulator serves is frequently one this process has no reason to trust — the integration tests' +/// throwaway certificate, or a host's dev certificate mounted into a container. +/// +/// +public sealed class EmulatorClientFactory : IDisposable +{ + // The emulator ignores keys, but the SDK will not build a client without one. + private static readonly AzureKeyCredential Credential = new("dashboard"); + + private readonly IServer _server; + private readonly HttpClient _httpClient; + + // Resolved on first use rather than in the constructor: Kestrel only knows its addresses once it + // has started, and PublicationOnly keeps a failure from being cached for the process lifetime. + private readonly Lazy _loopback; + + public EmulatorClientFactory(IServer server) + { + _server = server; + _loopback = new Lazy(ResolveLoopback, LazyThreadSafetyMode.PublicationOnly); + _httpClient = new HttpClient(new LoopbackRewriteHandler(() => _loopback.Value) + { + InnerHandler = new SocketsHttpHandler + { + SslOptions = { RemoteCertificateValidationCallback = (_, _, _, _) => true } + } + }); + } + + /// + /// The URI handed to the SDK. Only the path and query of the requests it builds survive the + /// rewrite, so the host is nominal. + /// + private static Uri SdkEndpoint { get; } = new("https://localhost"); + + public SearchIndexClient CreateIndexClient() => + new(SdkEndpoint, Credential, CreateOptions(null)); + + /// The index (or alias) to query. + /// + /// Captures the raw exchange for the page to show. Per client rather than shared, so that two + /// users searching at once each see their own request. + /// + public SearchClient CreateSearchClient(string indexName, HttpExchangeRecorder? recorder) => + new(SdkEndpoint, indexName, Credential, CreateOptions(recorder)); + + private SearchClientOptions CreateOptions(HttpExchangeRecorder? recorder) + { + var options = new SearchClientOptions + { + Transport = new HttpClientTransport(_httpClient), + // A failed query from the page should show its error immediately, not after the SDK's + // backoff has retried a request that is going to fail the same way every time. + Retry = { MaxRetries = 0 } + }; + + if (recorder is not null) + { + options.AddPolicy(recorder, Azure.Core.HttpPipelinePosition.PerRetry); + } + + return options; + } + + private Uri ResolveLoopback() + { + var addresses = _server.Features.Get()?.Addresses ?? []; + + return LoopbackEndpoint.Resolve(addresses) + ?? throw new InvalidOperationException( + "The emulator is not listening on any HTTP or HTTPS address the dashboard can reach."); + } + + public void Dispose() => _httpClient.Dispose(); + + private sealed class LoopbackRewriteHandler(Func loopback) : DelegatingHandler + { + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (request.RequestUri is { } uri) + { + request.RequestUri = new Uri(loopback(), uri.PathAndQuery); + } + + return base.SendAsync(request, cancellationToken); + } + } +} diff --git a/AzureSearchEmulator/Dashboard/HighlightMarkup.cs b/AzureSearchEmulator/Dashboard/HighlightMarkup.cs new file mode 100644 index 0000000..ed0affa --- /dev/null +++ b/AzureSearchEmulator/Dashboard/HighlightMarkup.cs @@ -0,0 +1,24 @@ +using System.Net; +using Microsoft.AspNetCore.Components; + +namespace AzureSearchEmulator.Dashboard; + +/// +/// Renders hit-highlight fragments and semantic captions with their emphasis intact (issue #92). +/// +/// +/// The fragments are document text with <em> tags spliced in, and document text is +/// whatever was indexed — so it cannot be handed to the page as markup. Everything is encoded, and +/// only the exact tags the emulator inserts are turned back into elements. +/// +public static class HighlightMarkup +{ + public static MarkupString Render(string fragment) + { + var encoded = WebUtility.HtmlEncode(fragment) + .Replace("<em>", "", StringComparison.Ordinal) + .Replace("</em>", "", StringComparison.Ordinal); + + return new MarkupString(encoded); + } +} diff --git a/AzureSearchEmulator/Dashboard/HttpExchangeRecorder.cs b/AzureSearchEmulator/Dashboard/HttpExchangeRecorder.cs new file mode 100644 index 0000000..f3da577 --- /dev/null +++ b/AzureSearchEmulator/Dashboard/HttpExchangeRecorder.cs @@ -0,0 +1,117 @@ +using System.Diagnostics; +using Azure.Core; +using Azure.Core.Pipeline; + +namespace AzureSearchEmulator.Dashboard; + +/// +/// One HTTP round trip as the SDK made it, for the search page's request and response views +/// (issue #92). +/// +/// Null when the request never got an answer, such as a refused connection. +public record HttpExchange( + string Method, + string PathAndQuery, + IReadOnlyList> RequestHeaders, + string? RequestBody, + HttpExchangeResponse? Response, + TimeSpan Duration); + +public record HttpExchangeResponse( + int Status, + string ReasonPhrase, + IReadOnlyList> Headers, + string? Body); + +/// +/// An SDK pipeline policy that keeps the most recent request and response passing through it. +/// +/// +/// Recorded inside the SDK's pipeline rather than in an beneath it, +/// so that the headers are the ones the SDK sent and the address is the one it addressed — not the +/// loopback binding quietly rewrites it to. It sits per retry, +/// after the policies that stamp the api-key, user agent and request id, and before the one that +/// buffers the response body, so by the time the next policy returns the body is in memory and can +/// be read without taking it away from the SDK's own deserialization. +/// +public sealed class HttpExchangeRecorder : HttpPipelinePolicy +{ + public HttpExchange? LastExchange { get; private set; } + + public override void Process(HttpMessage message, ReadOnlyMemory pipeline) => + ProcessAsync(message, pipeline, async: false).AsTask().GetAwaiter().GetResult(); + + public override ValueTask ProcessAsync(HttpMessage message, ReadOnlyMemory pipeline) => + ProcessAsync(message, pipeline, async: true); + + private async ValueTask ProcessAsync(HttpMessage message, ReadOnlyMemory pipeline, bool async) + { + var request = message.Request; + var requestBody = await ReadRequestBodyAsync(request.Content, async, message.CancellationToken); + var started = Stopwatch.GetTimestamp(); + + try + { + if (async) + { + await ProcessNextAsync(message, pipeline); + } + else + { + ProcessNext(message, pipeline); + } + } + finally + { + LastExchange = new HttpExchange( + request.Method.Method, + request.Uri.ToUri().PathAndQuery, + ToList(request.Headers), + requestBody, + message.HasResponse ? ToResponse(message.Response) : null, + Stopwatch.GetElapsedTime(started)); + } + } + + private static async ValueTask ReadRequestBodyAsync(RequestContent? content, bool async, CancellationToken cancellationToken) + { + if (content is null) + { + return null; + } + + using var stream = new MemoryStream(); + + if (async) + { + await content.WriteToAsync(stream, cancellationToken); + } + else + { + content.WriteTo(stream, cancellationToken); + } + + return System.Text.Encoding.UTF8.GetString(stream.GetBuffer(), 0, (int)stream.Length); + } + + private static HttpExchangeResponse ToResponse(Azure.Response response) + { + string? body; + + try + { + body = response.Content.ToString(); + } + catch (InvalidOperationException) + { + // Content throws when the body was left as a live stream instead of being buffered. + // Nothing the page sends opts out of buffering, so this is defensive. + body = null; + } + + return new HttpExchangeResponse(response.Status, response.ReasonPhrase, ToList(response.Headers), body); + } + + private static List> ToList(IEnumerable headers) => + headers.Select(i => KeyValuePair.Create(i.Name, i.Value)).ToList(); +} diff --git a/AzureSearchEmulator/Dashboard/JsonHighlighter.cs b/AzureSearchEmulator/Dashboard/JsonHighlighter.cs new file mode 100644 index 0000000..78265f2 --- /dev/null +++ b/AzureSearchEmulator/Dashboard/JsonHighlighter.cs @@ -0,0 +1,190 @@ +using System.Text; +using System.Text.Encodings.Web; +using System.Text.Json; + +namespace AzureSearchEmulator.Dashboard; + +public enum JsonTokenKind +{ + Plain, + Punctuation, + Key, + String, + Number, + Boolean, + Null +} + +public readonly record struct JsonToken(JsonTokenKind Kind, string Text); + +/// +/// Indents JSON and splits it into classified runs for the search page's request and response views +/// (issue #92). +/// +/// +/// Done on the server, in a few dozen lines, rather than by shipping a syntax-highlighting library +/// to the browser: the dashboard deliberately carries no client-side assets beyond Blazor's own +/// script, and JSON is a small enough grammar that classifying it is simpler than integrating +/// something that would. +/// +public static class JsonHighlighter +{ + /// + /// Bodies longer than this are shown indented but uncoloured. A page of results with vector + /// fields selected runs to tens of thousands of numbers, and a span apiece is a render tree too + /// large to be worth building and sending over the circuit for a view nobody reads number by + /// number. + /// + public const int MaxHighlightedLength = 256 * 1024; + + private static readonly JsonWriterOptions WriterOptions = new() + { + Indented = true, + // Only ever rendered as text by Blazor, which does its own HTML encoding. The default + // encoder would turn the tags in highlights into and make the raw + // response harder to read than the one on the wire. + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping + }; + + /// + /// Re-indents , or returns it unchanged when it does not parse — an error + /// body from somewhere other than the emulator is still worth showing as it arrived. + /// + public static string Format(string json) + { + try + { + using var document = JsonDocument.Parse(json); + using var buffer = new MemoryStream(); + + using (var writer = new Utf8JsonWriter(buffer, WriterOptions)) + { + document.WriteTo(writer); + } + + return Encoding.UTF8.GetString(buffer.GetBuffer(), 0, (int)buffer.Length); + } + catch (JsonException) + { + return json; + } + } + + /// + /// Splits already-formatted JSON into tokens. Concatenating the tokens' text always reproduces + /// the input exactly, whether or not it is valid JSON. + /// + public static IReadOnlyList Tokenize(string json) + { + var tokens = new List(); + + if (json.Length > MaxHighlightedLength) + { + tokens.Add(new JsonToken(JsonTokenKind.Plain, json)); + return tokens; + } + + var i = 0; + + while (i < json.Length) + { + var c = json[i]; + var start = i; + + if (c == '"') + { + i = SkipString(json, i); + var kind = NextNonWhitespace(json, i) == ':' ? JsonTokenKind.Key : JsonTokenKind.String; + Add(tokens, kind, json[start..i]); + } + else if (c is '-' || char.IsAsciiDigit(c)) + { + while (i < json.Length && (char.IsAsciiDigit(json[i]) || json[i] is '-' or '+' or '.' or 'e' or 'E')) + { + i++; + } + + Add(tokens, JsonTokenKind.Number, json[start..i]); + } + else if (c is '{' or '}' or '[' or ']' or ',' or ':') + { + i++; + Add(tokens, JsonTokenKind.Punctuation, json[start..i]); + } + else if (TryLiteral(json, i, "true") || TryLiteral(json, i, "false")) + { + i += c == 't' ? 4 : 5; + Add(tokens, JsonTokenKind.Boolean, json[start..i]); + } + else if (TryLiteral(json, i, "null")) + { + i += 4; + Add(tokens, JsonTokenKind.Null, json[start..i]); + } + else + { + i++; + Add(tokens, JsonTokenKind.Plain, json[start..i]); + } + } + + return tokens; + } + + /// + /// Returns the index just past the string starting at , or the end of the + /// input for a string that is never closed. + /// + private static int SkipString(string json, int start) + { + var i = start + 1; + + while (i < json.Length) + { + switch (json[i]) + { + case '\\': + i += 2; + break; + case '"': + return i + 1; + default: + i++; + break; + } + } + + return json.Length; + } + + private static char? NextNonWhitespace(string json, int from) + { + for (var i = from; i < json.Length; i++) + { + if (!char.IsWhiteSpace(json[i])) + { + return json[i]; + } + } + + return null; + } + + private static bool TryLiteral(string json, int at, string literal) => + string.CompareOrdinal(json, at, literal, 0, literal.Length) == 0; + + /// + /// Appends a token, folding it into the previous one when both are plain text so whitespace and + /// unrecognised characters do not each become a span of their own. + /// + private static void Add(List tokens, JsonTokenKind kind, string text) + { + if (kind == JsonTokenKind.Plain && tokens.Count > 0 && tokens[^1].Kind == JsonTokenKind.Plain) + { + tokens[^1] = tokens[^1] with { Text = tokens[^1].Text + text }; + return; + } + + tokens.Add(new JsonToken(kind, text)); + } +} diff --git a/AzureSearchEmulator/Dashboard/LoopbackEndpoint.cs b/AzureSearchEmulator/Dashboard/LoopbackEndpoint.cs new file mode 100644 index 0000000..ff06485 --- /dev/null +++ b/AzureSearchEmulator/Dashboard/LoopbackEndpoint.cs @@ -0,0 +1,67 @@ +namespace AzureSearchEmulator.Dashboard; + +/// +/// Picks the address the dashboard's own SDK clients use to reach the emulator they run inside +/// (issue #92). +/// +/// +/// The addresses come from Kestrel's bindings rather than from the browser's view of the page, +/// because the URL a user typed is not necessarily one the process can reach: behind the +/// container's port mapping or an Aspire proxy it names a port on the host, not inside the +/// container. Every binding Kestrel reports is one it is listening on, so connecting back over +/// loopback always works. +/// +public static class LoopbackEndpoint +{ + /// + /// Returns a connectable base URI for one of , or null when there is + /// none. + /// + /// + /// Plain HTTP is preferred when it is bound: it saves a TLS handshake on a call that never + /// leaves the process's own network stack. Wildcard hosts are listening addresses, not + /// destinations, so they are swapped for loopback. + /// + public static Uri? Resolve(IEnumerable addresses) + { + var candidates = addresses + .Select(Parse) + .OfType() + .OrderBy(i => i.Scheme == Uri.UriSchemeHttp ? 0 : 1) + .ToList(); + + return candidates.FirstOrDefault(); + } + + private static Uri? Parse(string address) + { + // Kestrel reports wildcard bindings as "+", "*", "0.0.0.0" or "[::]", and the first two are + // not valid URI hosts, so they are replaced before parsing rather than after. + var schemeEnd = address.IndexOf("://", StringComparison.Ordinal); + + if (schemeEnd < 0) + { + return null; + } + + var hostStart = schemeEnd + 3; + var portStart = address.LastIndexOf(':'); + var host = portStart > hostStart ? address[hostStart..portStart] : address[hostStart..].TrimEnd('/'); + var rest = portStart > hostStart ? address[portStart..] : string.Empty; + + var loopbackHost = host switch + { + "+" or "*" or "[::]" => "localhost", + "0.0.0.0" => "127.0.0.1", + _ => host + }; + + if (!Uri.TryCreate($"{address[..hostStart]}{loopbackHost}{rest}", UriKind.Absolute, out var uri) + || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps)) + { + return null; + } + + return new Uri(uri.GetLeftPart(UriPartial.Authority)); + } +} diff --git a/AzureSearchEmulator/Dashboard/SearchQueryForm.cs b/AzureSearchEmulator/Dashboard/SearchQueryForm.cs new file mode 100644 index 0000000..4e1a039 --- /dev/null +++ b/AzureSearchEmulator/Dashboard/SearchQueryForm.cs @@ -0,0 +1,172 @@ +using Azure.Search.Documents; +using Azure.Search.Documents.Models; + +namespace AzureSearchEmulator.Dashboard; + +/// +/// The search page's inputs, as typed (issue #92). +/// +/// +/// Each text box takes the parameter's syntax as the REST API documents it, so a query that works +/// here can be pasted into a client unchanged and vice versa. Blank means "not sent" rather than +/// "sent empty": an empty $filter is a syntax error, not an absent filter. +/// +public class SearchQueryForm +{ + public const int DefaultTop = 10; + + public string SearchText { get; set; } = ""; + + /// simple, full or semantic. + public string QueryType { get; set; } = "simple"; + + /// any or all. + public string SearchMode { get; set; } = "any"; + + public string Filter { get; set; } = ""; + + public string OrderBy { get; set; } = ""; + + public string Select { get; set; } = ""; + + public string SearchFields { get; set; } = ""; + + public string Facets { get; set; } = ""; + + public string Highlight { get; set; } = ""; + + public string ScoringProfile { get; set; } = ""; + + public string SemanticConfiguration { get; set; } = ""; + + public int Top { get; set; } = DefaultTop; + + public int Skip { get; set; } + + public bool IncludeTotalCount { get; set; } = true; + + public bool IsSemantic => QueryType == "semantic"; + + public SearchOptions ToSearchOptions() + { + var options = new SearchOptions + { + Size = Top, + Skip = Skip > 0 ? Skip : null, + IncludeTotalCount = IncludeTotalCount, + Filter = NullIfBlank(Filter), + ScoringProfile = NullIfBlank(ScoringProfile), + QueryType = QueryType switch + { + "full" => SearchQueryType.Full, + "semantic" => SearchQueryType.Semantic, + _ => SearchQueryType.Simple + }, + SearchMode = SearchMode == "all" ? Azure.Search.Documents.Models.SearchMode.All : Azure.Search.Documents.Models.SearchMode.Any + }; + + // The SDK takes these as lists and joins them back with commas on the wire, so the split + // only has to agree with that join, not interpret the expressions. + AddAll(options.OrderBy, SplitList(OrderBy)); + AddAll(options.Select, SplitList(Select)); + AddAll(options.SearchFields, SplitList(SearchFields)); + AddAll(options.HighlightFields, SplitList(Highlight)); + AddAll(options.Facets, SplitFacets(Facets)); + + if (IsSemantic) + { + options.SemanticSearch = new SemanticSearchOptions + { + SemanticConfigurationName = NullIfBlank(SemanticConfiguration), + QueryCaption = new QueryCaption(QueryCaptionType.Extractive), + QueryAnswer = new QueryAnswer(QueryAnswerType.Extractive) + }; + } + + return options; + } + + /// + /// Splits a comma-separated list on the commas that separate its items. + /// + /// + /// Commas inside parentheses or quotes belong to the item: geo.distance(location, + /// geography'POINT(-122 47)') asc, rating desc is two $orderby clauses, not three. + /// + public static IReadOnlyList SplitList(string value) + { + var result = new List(); + var depth = 0; + var inQuote = false; + var start = 0; + + for (var i = 0; i <= value.Length; i++) + { + var c = i < value.Length ? value[i] : ','; + + switch (c) + { + case '\'': + inQuote = !inQuote; + break; + case '(' when !inQuote: + depth++; + break; + case ')' when !inQuote && depth > 0: + depth--; + break; + case ',' when (!inQuote && depth == 0) || i == value.Length: + var item = value[start..i].Trim(); + + if (item.Length > 0) + { + result.Add(item); + } + + start = i + 1; + break; + } + } + + return result; + } + + /// + /// Splits a comma-separated list of facet expressions. + /// + /// + /// A facet expression carries its own parameters after commas — rating,count:5,sort:value + /// — so the list cannot simply be split on commas. A segment containing a colon is a parameter + /// and stays with the field before it, which lets category, rating,interval:1 mean the two + /// facets it reads as. + /// + public static IReadOnlyList SplitFacets(string facets) + { + var result = new List(); + + foreach (var segment in facets.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + if (segment.Contains(':') && result.Count > 0) + { + result[^1] += "," + segment; + } + else + { + result.Add(segment); + } + } + + return result; + } + + private static void AddAll(IList target, IEnumerable items) + { + foreach (var item in items) + { + target.Add(item); + } + } + + private static string? NullIfBlank(string value) => + string.IsNullOrWhiteSpace(value) ? null : value.Trim(); +} diff --git a/AzureSearchEmulator/Program.cs b/AzureSearchEmulator/Program.cs index b7f39d4..50aa300 100644 --- a/AzureSearchEmulator/Program.cs +++ b/AzureSearchEmulator/Program.cs @@ -1,6 +1,7 @@ using System.Text.Json; using AzureSearchEmulator; using AzureSearchEmulator.Components; +using AzureSearchEmulator.Dashboard; using AzureSearchEmulator.ErrorHandling; using AzureSearchEmulator.Health; using AzureSearchEmulator.Indexing; @@ -162,6 +163,9 @@ builder.Services.AddSingleton(TimeProvider.System); builder.Services.AddScoped(); +// The search page's SDK clients, which call back into this process over loopback (issue #92). +builder.Services.AddSingleton(); + // The dashboard (issue #90). Blazor rather than a separate SPA so the whole UI ships inside the // same assembly as the emulator — no second build step, no static bundle to keep in sync, and // nothing extra for `dotnet tool install` to pull down. The interactive server render mode means diff --git a/AzureSearchEmulator/wwwroot/css/dashboard.css b/AzureSearchEmulator/wwwroot/css/dashboard.css index 54b1b55..12ee48e 100644 --- a/AzureSearchEmulator/wwwroot/css/dashboard.css +++ b/AzureSearchEmulator/wwwroot/css/dashboard.css @@ -23,6 +23,16 @@ --unhealthy: #b3261e; --unhealthy-soft: #fceceb; + --mark: #fff0a8; + --mark-text: #3d3200; + + --code-bg: #f7f8fa; + --tok-key: #0b4fa8; + --tok-string: #0f7a3d; + --tok-number: #a64d00; + --tok-literal: #8a2fb3; + --tok-punct: #6b7380; + --radius: 14px; --shadow: 0 1px 2px rgb(16 24 40 / 6%), 0 8px 24px rgb(16 24 40 / 6%); } @@ -44,6 +54,16 @@ --unhealthy: #f2857e; --unhealthy-soft: #2b1615; + --mark: #5a4a00; + --mark-text: #fff3bf; + + --code-bg: #12161c; + --tok-key: #8cbcff; + --tok-string: #8fdba8; + --tok-number: #f2b37a; + --tok-literal: #d4a3f5; + --tok-punct: #7f8896; + --shadow: 0 1px 2px rgb(0 0 0 / 40%), 0 8px 24px rgb(0 0 0 / 30%); } } @@ -93,7 +113,7 @@ p { /* Layout ------------------------------------------------------------------ */ .shell { - max-width: 880px; + max-width: 1040px; margin: 0 auto; padding: 0 24px 48px; min-height: 100vh; @@ -103,9 +123,42 @@ p { } .masthead { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 16px; padding: 28px 0 4px; } +.topnav { + display: flex; + gap: 4px; + padding: 4px; + border: 1px solid var(--border); + border-radius: 11px; + background: var(--bg-elevated); +} + +.topnav-link { + padding: 6px 14px; + border-radius: 8px; + color: var(--text-muted); + font-size: 0.875rem; + font-weight: 600; + text-decoration: none; +} + +.topnav-link:hover { + color: var(--text); +} + +.topnav-link.active { + background: var(--bg); + color: var(--accent); + box-shadow: inset 0 0 0 1px var(--border-strong); +} + .brand { display: inline-flex; align-items: center; @@ -400,7 +453,518 @@ p { } } +/* Search ------------------------------------------------------------------ */ + +code { + font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace; + font-size: 0.9em; +} + +.empty-state { + align-items: flex-start; +} + +.error-text { + font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace; + font-size: 0.8125rem; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.search-row { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 12px; +} + +.field { + display: flex; + flex-direction: column; + gap: 5px; + min-width: 0; +} + +.field > span { + color: var(--text-muted); + font-size: 0.75rem; + font-weight: 600; + letter-spacing: 0.02em; +} + +.field > span code { + font-weight: 500; + opacity: 0.8; +} + +.field.grow { + flex: 1 1 280px; +} + +.index-field { + flex: 0 1 220px; +} + +.field input:not([type="checkbox"]), +.field select { + width: 100%; + height: 40px; + padding: 8px 11px; + border: 1px solid var(--border-strong); + border-radius: 9px; + background: var(--bg); + color: var(--text); + font: inherit; + font-size: 0.9375rem; +} + +.field input:focus-visible, +.field select:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 0; + border-color: transparent; +} + +.field input::placeholder { + color: var(--text-muted); + opacity: 0.7; +} + +.checkbox-field { + flex-direction: row; + align-items: center; + align-self: end; + gap: 8px; + padding-bottom: 9px; +} + +.checkbox-field input { + width: 16px; + height: 16px; + margin: 0; + accent-color: var(--accent); +} + +.button-primary { + height: 40px; + padding: 0 20px; + border-color: var(--accent); + background: var(--accent); + color: #fff; +} + +.button-primary:hover:not(:disabled) { + color: #fff; + filter: brightness(1.08); +} + +@media (prefers-color-scheme: dark) { + .button-primary, + .button-primary:hover:not(:disabled) { + color: #0b1220; + } +} + +.options summary { + width: fit-content; + color: var(--text-muted); + font-size: 0.875rem; + font-weight: 600; + cursor: pointer; +} + +.options summary:hover { + color: var(--accent); +} + +.options-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); + gap: 14px 16px; + margin-top: 14px; +} + +.span-2 { + grid-column: span 2; +} + +.tabs { + display: flex; + gap: 4px; + margin: -4px 0 4px; + border-bottom: 1px solid var(--border); +} + +.tab { + display: inline-flex; + align-items: center; + gap: 8px; + margin-bottom: -1px; + padding: 8px 14px; + border: 0; + border-bottom: 2px solid transparent; + background: none; + color: var(--text-muted); + font: inherit; + font-size: 0.875rem; + font-weight: 600; + cursor: pointer; +} + +.tab:hover { + color: var(--text); +} + +.tab[aria-selected="true"] { + border-bottom-color: var(--accent); + color: var(--text); +} + +.tab-count { + padding: 1px 8px; + border-radius: 999px; + background: var(--bg); + border: 1px solid var(--border); + color: var(--status-color, var(--text-muted)); + font-size: 0.75rem; + font-variant-numeric: tabular-nums; +} + +.results-panel[aria-busy="true"] .tab-panel { + opacity: 0.55; + transition: opacity 150ms ease; +} + +.tab-panel { + display: flex; + flex-direction: column; + gap: 14px; + min-width: 0; +} + +.results-summary { + color: var(--text-muted); + font-size: 0.875rem; +} + +.results-summary strong { + color: var(--text); + font-variant-numeric: tabular-nums; +} + +.callout { + display: flex; + flex-direction: column; + gap: 6px; + padding: 14px 16px; + border: 1px solid var(--border); + border-left: 4px solid var(--status-color); + border-radius: 11px; + background: var(--status-soft); +} + +.callout-title { + font-weight: 650; +} + +.eyebrow { + color: var(--text-muted); + font-size: 0.6875rem; + font-weight: 650; + letter-spacing: 0.06em; + text-transform: uppercase; +} + +.answer { + padding: 12px 16px; + border: 1px solid var(--border); + border-left: 4px solid var(--accent); + border-radius: 11px; + background: var(--bg); +} + +mark { + padding: 0 2px; + border-radius: 3px; + background: var(--mark); + color: var(--mark-text); +} + +.facets { + display: flex; + flex-direction: column; + gap: 10px; + padding: 12px 14px; + border: 1px solid var(--border); + border-radius: 11px; + background: var(--bg); +} + +.facet { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 6px 12px; +} + +.facet-name { + min-width: 96px; + font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace; + font-size: 0.8125rem; + font-weight: 600; +} + +.chips { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin: 0; + padding: 0; + list-style: none; +} + +.chip { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 2px 4px 2px 10px; + border: 1px solid var(--border-strong); + border-radius: 999px; + background: var(--bg-elevated); + font-size: 0.8125rem; +} + +.chip-count { + padding: 0 7px; + border-radius: 999px; + background: var(--bg); + color: var(--text-muted); + font-size: 0.75rem; + font-variant-numeric: tabular-nums; +} + +.results { + display: flex; + flex-direction: column; + gap: 10px; + margin: 0; + padding: 0; + list-style: none; +} + +.result { + display: flex; + flex-direction: column; + gap: 10px; + padding: 14px 16px; + border: 1px solid var(--border); + border-radius: 11px; + background: var(--bg-elevated); +} + +.result:hover { + border-color: var(--border-strong); +} + +.result-head { + display: flex; + flex-wrap: wrap; + align-items: flex-start; + justify-content: space-between; + gap: 8px 16px; +} + +.result-title { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 4px 10px; + min-width: 0; +} + +.result-heading { + font-size: 1rem; + font-weight: 650; + overflow-wrap: anywhere; +} + +.result-key { + color: var(--text-muted); + font-size: 0.75rem; +} + +.scores { + display: flex; + gap: 6px; +} + +.score { + padding: 2px 9px; + border-radius: 999px; + background: color-mix(in srgb, var(--accent) 12%, transparent); + color: var(--accent); + font-size: 0.75rem; + font-weight: 600; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.caption { + padding-left: 12px; + border-left: 3px solid var(--border-strong); + color: var(--text-muted); + font-size: 0.9rem; +} + +.highlights, +.fields { + display: grid; + grid-template-columns: minmax(90px, max-content) minmax(0, 1fr); + gap: 4px 16px; + margin: 0; + font-size: 0.875rem; +} + +.highlights dt, +.fields dt { + color: var(--text-muted); + font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace; + font-size: 0.8125rem; +} + +.highlights dd, +.fields dd { + grid-column: 2; + margin: 0; + overflow-wrap: anywhere; +} + +.fields dd { + display: -webkit-box; + -webkit-box-orient: vertical; + -webkit-line-clamp: 3; + overflow: hidden; +} + +.fields dd.is-null { + color: var(--text-muted); + font-style: italic; +} + +.highlights { + padding: 10px 12px; + border-radius: 9px; + background: var(--bg); +} + +.pager { + display: flex; + justify-content: center; + gap: 8px; +} + +/* HTTP exchange ----------------------------------------------------------- */ + +.http-head { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 6px 12px; +} + +.http-method { + padding: 2px 9px; + border-radius: 6px; + background: var(--accent); + color: var(--bg-elevated); + font-size: 0.75rem; + font-weight: 700; + letter-spacing: 0.04em; +} + +.http-url { + font-size: 0.8125rem; + overflow-wrap: anywhere; +} + +.http-status { + color: var(--status-color); + font-weight: 700; +} + +.http-headers summary { + width: fit-content; + color: var(--text-muted); + font-size: 0.8125rem; + font-weight: 600; + cursor: pointer; +} + +.http-headers dl { + display: grid; + grid-template-columns: minmax(120px, max-content) minmax(0, 1fr); + gap: 3px 16px; + margin: 8px 0 0; + font-family: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace; + font-size: 0.75rem; +} + +.http-headers dt { + color: var(--text-muted); +} + +.http-headers dd { + margin: 0; + overflow-wrap: anywhere; +} + +.code-block { + position: relative; +} + +.code-block .copy { + position: absolute; + top: 8px; + right: 8px; + padding: 3px 10px; + font-size: 0.75rem; +} + +.code { + max-height: 640px; + margin: 0; + padding: 14px 16px; + overflow: auto; + border: 1px solid var(--border); + border-radius: 11px; + background: var(--code-bg); + font-size: 0.8125rem; + line-height: 1.5; + tab-size: 2; +} + +.tok-key { color: var(--tok-key); } +.tok-string { color: var(--tok-string); } +.tok-number { color: var(--tok-number); } +.tok-literal { color: var(--tok-literal); font-weight: 600; } +.tok-punct { color: var(--tok-punct); } + @media (max-width: 620px) { + .span-2 { + grid-column: auto; + } + + .highlights, + .fields { + grid-template-columns: minmax(0, 1fr); + } + + .highlights dd, + .fields dd { + grid-column: 1; + margin-bottom: 6px; + } + .shell { padding: 0 16px 32px; } diff --git a/README.md b/README.md index 151ed4d..768c14d 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,10 @@ dashboard showing whether the emulator is running correctly: the version and env running as, how long it has been up, where it is storing indexes, and the result of each health check. It refreshes on its own every few seconds. +The **Search** page queries any index through the Azure SDK, with the usual options — query type, +`$filter`, `$orderby`, `$select`, facets, highlighting, scoring profiles and semantic configurations +— and shows the results alongside the exact request the SDK sent and the response it got back. + The emulator is a local development tool, so the UI has no authentication. Do not expose it on an address other machines can reach.