From b470410798382f06159686b1f23b54adc9faa80d Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 15:35:15 +0100 Subject: [PATCH 1/3] Harden the docs API error paths and drop dead startup code A search backend that is temporarily unavailable now answers 503 with Retry-After, and every unhandled error has a JSON body. /search clamps page and size once in FullSearchService. Ask AI message feedback answers 503 when it could not be stored. The Ask AI activity sources are created once, and the stream activity ends when the call throws. Startup no longer builds the service provider to log, and the unused parameter providers, validator and named HTTP client are gone. Co-Authored-By: Claude Opus 5.5 --- ...lasticsearchAskAiMessageFeedbackGateway.cs | 24 +-- .../AskAi/IAskAiMessageFeedbackGateway.cs | 3 +- .../Aws/IParameterProvider.cs | 14 -- .../Aws/LambdaExtensionParameterProvider.cs | 73 -------- .../Aws/LocalParameterProvider.cs | 77 -------- .../MappingsExtensions.cs | 44 +++-- src/api/Elastic.Documentation.Api/Program.cs | 24 ++- .../SerializationContext.cs | 4 + .../ServicesExtension.cs | 175 +++++------------- .../Validation/IValidator.cs | 12 -- .../Tools/SearchTools.cs | 4 +- .../FullSearchService.cs | 7 +- .../ServicesExtension.cs | 11 -- .../ApiErrorResponseTests.cs | 96 ++++++++++ .../Fixtures/ApiWebApplicationFactory.cs | 6 - .../FullSearchServiceTests.cs | 41 ++++ 16 files changed, 260 insertions(+), 355 deletions(-) delete mode 100644 src/api/Elastic.Documentation.Api/Aws/IParameterProvider.cs delete mode 100644 src/api/Elastic.Documentation.Api/Aws/LambdaExtensionParameterProvider.cs delete mode 100644 src/api/Elastic.Documentation.Api/Aws/LocalParameterProvider.cs delete mode 100644 src/api/Elastic.Documentation.Api/Validation/IValidator.cs create mode 100644 tests/Elastic.Documentation.Api.Tests/ApiErrorResponseTests.cs create mode 100644 tests/Elastic.Documentation.Api.Tests/FullSearchServiceTests.cs diff --git a/src/api/Elastic.Documentation.Api/Adapters/AskAi/ElasticsearchAskAiMessageFeedbackGateway.cs b/src/api/Elastic.Documentation.Api/Adapters/AskAi/ElasticsearchAskAiMessageFeedbackGateway.cs index 6b76413eac..74e7cd12c0 100644 --- a/src/api/Elastic.Documentation.Api/Adapters/AskAi/ElasticsearchAskAiMessageFeedbackGateway.cs +++ b/src/api/Elastic.Documentation.Api/Adapters/AskAi/ElasticsearchAskAiMessageFeedbackGateway.cs @@ -22,7 +22,7 @@ ILogger logger { private readonly string _indexName = $"ask-ai-message-feedback-{appEnvironment.Current.ToStringFast(true)}"; - public async Task RecordFeedbackAsync(AskAiMessageFeedbackRecord record, CancellationToken ctx) + public async Task RecordFeedbackAsync(AskAiMessageFeedbackRecord record, CancellationToken ctx) { var feedbackId = Guid.NewGuid(); var document = new MessageFeedbackDocument @@ -47,18 +47,18 @@ public async Task RecordFeedbackAsync(AskAiMessageFeedbackRecord record, Cancell record.MessageId, response.ApiCallDetails.HttpStatusCode ); + return false; } - else - { - logger.LogInformation( - "Message feedback recorded: {Reaction} for message {MessageId} in conversation {ConversationId}. ES _id: {EsId}, Index: {Index}", - record.Reaction, - record.MessageId, - record.ConversationId, - feedbackId, - _indexName - ); - } + + logger.LogInformation( + "Message feedback recorded: {Reaction} for message {MessageId} in conversation {ConversationId}. ES _id: {EsId}, Index: {Index}", + record.Reaction, + record.MessageId, + record.ConversationId, + feedbackId, + _indexName + ); + return true; } } diff --git a/src/api/Elastic.Documentation.Api/AskAi/IAskAiMessageFeedbackGateway.cs b/src/api/Elastic.Documentation.Api/AskAi/IAskAiMessageFeedbackGateway.cs index 070be0179a..49df6804d4 100644 --- a/src/api/Elastic.Documentation.Api/AskAi/IAskAiMessageFeedbackGateway.cs +++ b/src/api/Elastic.Documentation.Api/AskAi/IAskAiMessageFeedbackGateway.cs @@ -15,7 +15,8 @@ public interface IAskAiMessageFeedbackService /// /// The feedback record to store. /// Cancellation token. - Task RecordFeedbackAsync(AskAiMessageFeedbackRecord record, CancellationToken ctx); + /// false when the feedback could not be stored. + Task RecordFeedbackAsync(AskAiMessageFeedbackRecord record, CancellationToken ctx); } /// diff --git a/src/api/Elastic.Documentation.Api/Aws/IParameterProvider.cs b/src/api/Elastic.Documentation.Api/Aws/IParameterProvider.cs deleted file mode 100644 index 887dd12341..0000000000 --- a/src/api/Elastic.Documentation.Api/Aws/IParameterProvider.cs +++ /dev/null @@ -1,14 +0,0 @@ -// Licensed to Elasticsearch B.V under one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - -namespace Elastic.Documentation.Api.Aws; - -/// -/// Abstraction for retrieving configuration parameters. -/// Infrastructure concern: Used by other Infrastructure adapters to get configuration. -/// -public interface IParameterProvider -{ - Task GetParam(string name, bool withDecryption = true, Cancel ctx = default); -} diff --git a/src/api/Elastic.Documentation.Api/Aws/LambdaExtensionParameterProvider.cs b/src/api/Elastic.Documentation.Api/Aws/LambdaExtensionParameterProvider.cs deleted file mode 100644 index a27c50cd7b..0000000000 --- a/src/api/Elastic.Documentation.Api/Aws/LambdaExtensionParameterProvider.cs +++ /dev/null @@ -1,73 +0,0 @@ -// Licensed to Elasticsearch B.V under one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - -using System.Net.Http.Json; -using System.Text.Json; -using System.Text.Json.Serialization; -using Microsoft.Extensions.Logging; - -namespace Elastic.Documentation.Api.Aws; - -public class LambdaExtensionParameterProvider( - IHttpClientFactory httpClientFactory, - AppEnvironment appEnvironment, - ILogger logger -) : IParameterProvider -{ - public const string HttpClientName = "AwsParametersAndSecretsLambdaExtensionClient"; - private readonly HttpClient _httpClient = httpClientFactory.CreateClient(HttpClientName); - - public async Task GetParam(string name, bool withDecryption = true, Cancel ctx = default) - { - try - { - var prefix = $"/elastic-docs-v3/{appEnvironment.Current.ToStringFast(true)}/"; - var prefixedName = prefix + name.TrimStart('/'); - logger.LogInformation("Retrieving parameter '{Name}' from Lambda Extension (SSM Parameter Store).", prefixedName); - var response = await _httpClient.GetFromJsonAsync( - $"/systemsmanager/parameters/get?name={Uri.EscapeDataString(prefixedName)}&withDecryption={withDecryption.ToString().ToLowerInvariant()}", - AwsJsonContext.Default.ParameterResponse, - ctx - ); - return response?.Parameter?.Value ?? throw new InvalidOperationException($"Parameter value for '{name}' is null."); - } - catch (HttpRequestException httpEx) - { - logger.LogError(httpEx, "HTTP request failed for parameter '{Name}'. Status: {StatusCode}.", name, httpEx.StatusCode); - throw; - } - catch (JsonException jsonEx) - { - logger.LogError(jsonEx, "JSON deserialization failed for parameter '{Name}'.", name); - throw; - } - catch (Exception ex) - { - logger.LogError(ex, "An unexpected error occurred while retrieving parameter '{Name}'.", name); - throw; - } - } -} - -internal sealed class ParameterResponse -{ - public required Parameter Parameter { get; set; } -} - -internal sealed class Parameter -{ - [JsonPropertyName("ARN")] - public required string Arn { get; set; } - public required string Name { get; set; } - public required string Type { get; set; } - public required string Value { get; set; } - public required int Version { get; set; } - public string? Selector { get; set; } - public DateTime LastModifiedDate { get; set; } - public required string DataType { get; set; } -} - -[JsonSerializable(typeof(ParameterResponse))] -[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.Unspecified)] -internal sealed partial class AwsJsonContext : JsonSerializerContext; diff --git a/src/api/Elastic.Documentation.Api/Aws/LocalParameterProvider.cs b/src/api/Elastic.Documentation.Api/Aws/LocalParameterProvider.cs deleted file mode 100644 index 08024a64c0..0000000000 --- a/src/api/Elastic.Documentation.Api/Aws/LocalParameterProvider.cs +++ /dev/null @@ -1,77 +0,0 @@ -// Licensed to Elasticsearch B.V under one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - -using Microsoft.Extensions.Configuration; - -namespace Elastic.Documentation.Api.Aws; - -public class LocalParameterProvider : IParameterProvider -{ - private readonly string? _elasticUrlFromSecret; - private readonly string? _elasticApiKeyFromSecret; - private readonly string? _llmGatewayUrlFromSecret; - private readonly string? _llmGatewayServiceAccountPath; - - public LocalParameterProvider() - { - // Build a new ConfigurationBuilder to read user secrets - var configBuilder = new ConfigurationBuilder(); - _ = configBuilder.AddUserSecrets("docs-builder"); - var userSecretsConfig = configBuilder.Build(); - - _elasticUrlFromSecret = userSecretsConfig["Parameters:ElasticsearchUrl"]; - _elasticApiKeyFromSecret = userSecretsConfig["Parameters:ElasticsearchApiKey"]; - _llmGatewayUrlFromSecret = userSecretsConfig["Parameters:LlmGatewayUrl"]; - _llmGatewayServiceAccountPath = userSecretsConfig["Parameters:LlmGatewayServiceAccountPath"]; - } - - public async Task GetParam(string name, bool withDecryption = true, Cancel ctx = default) - { - switch (name) - { - case "llm-gateway-service-account": - { - var serviceAccountKeyPath = GetEnv("LLM_GATEWAY_SERVICE_ACCOUNT_KEY_PATH", _llmGatewayServiceAccountPath); - if (!File.Exists(serviceAccountKeyPath)) - throw new ArgumentException($"Service account key file not found at '{serviceAccountKeyPath}'."); - var serviceAccountKey = await File.ReadAllTextAsync(serviceAccountKeyPath, ctx); - return serviceAccountKey; - } - case "llm-gateway-function-url": - { - return GetEnv("LLM_GATEWAY_FUNCTION_URL", _llmGatewayUrlFromSecret); - } - case "docs-elasticsearch-url": - { - return GetEnv("DOCUMENTATION_ELASTIC_URL", _elasticUrlFromSecret); - } - case "docs-elasticsearch-apikey": - { - return GetEnv("DOCUMENTATION_ELASTIC_APIKEY", _elasticApiKeyFromSecret); - } - case "docs-kibana-url": - { - return GetEnv("DOCUMENTATION_KIBANA_URL"); - } - case "docs-kibana-apikey": - { - return GetEnv("DOCUMENTATION_KIBANA_APIKEY"); - } - default: - { - throw new ArgumentException($"Parameter '{name}' not found in {nameof(LocalParameterProvider)}"); - } - } - } - - private static string GetEnv(string name, string? defaultValue = null) - { - var value = Environment.GetEnvironmentVariable(name); - if (!string.IsNullOrEmpty(value)) - return value; - if (defaultValue != null) - return defaultValue; - throw new ArgumentException($"Environment variable '{name}' not found."); - } -} diff --git a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs index 2669804557..e3b80c8e39 100644 --- a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs +++ b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs @@ -18,6 +18,10 @@ namespace Elastic.Documentation.Api; public static class MappingsExtension { + // An ActivitySource stays registered with the runtime until disposed, so create each one once. + private static readonly ActivitySource AskAiActivitySource = new(TelemetryConstants.AskAiSourceName); + private static readonly ActivitySource AskAiFeedbackActivitySource = new(TelemetryConstants.AskAiFeedbackSourceName); + public static void MapElasticDocsApiEndpoints(this IEndpointRouteBuilder group) { _ = group.MapGet("/", () => Results.Empty); @@ -46,13 +50,12 @@ Cancel ctx context.Response.Headers.CacheControl = "no-cache"; context.Response.Headers.Connection = "keep-alive"; - var askAiActivitySource = new ActivitySource(TelemetryConstants.AskAiSourceName); logger.LogInformation( "Starting AskAI chat with {AgentProvider} and {AgentId}", streamTransformer.AgentProvider, streamTransformer.AgentId ); - var activity = askAiActivitySource.StartActivity($"chat {streamTransformer.AgentProvider}", ActivityKind.Client); + var activity = AskAiActivitySource.StartActivity($"chat {streamTransformer.AgentProvider}", ActivityKind.Client); _ = activity?.SetTag("gen_ai.operation.name", "chat"); _ = activity?.SetTag("gen_ai.provider.name", streamTransformer.AgentProvider); _ = activity?.SetTag("gen_ai.agent.id", streamTransformer.AgentId); @@ -65,18 +68,29 @@ Cancel ctx logger.LogInformation("AskAI input message: <{ask_ai.input.message}>", SanitizeForLog(askAiRequest.Message)); logger.LogInformation("Streaming AskAI response"); - var response = await askAiService.AskAi(askAiRequest, ctx); + Stream transformedStream; + try + { + var response = await askAiService.AskAi(askAiRequest, ctx); - var conversationId = response.GeneratedConversationId ?? askAiRequest.ConversationId; - if (conversationId is not null) - _ = activity?.SetTag("gen_ai.conversation.id", conversationId.ToString()); + var conversationId = response.GeneratedConversationId ?? askAiRequest.ConversationId; + if (conversationId is not null) + _ = activity?.SetTag("gen_ai.conversation.id", conversationId.ToString()); - var transformedStream = await streamTransformer.TransformAsync( - response.Stream, - response.GeneratedConversationId, - activity, - ctx - ); + transformedStream = await streamTransformer.TransformAsync( + response.Stream, + response.GeneratedConversationId, + activity, + ctx + ); + } + catch (Exception ex) + { + // The transformer ends the activity once it owns the stream; until then this handler must. + _ = activity?.SetStatus(ActivityStatusCode.Error, ex.Message); + activity?.Dispose(); + throw; + } await transformedStream.CopyToAsync(context.Response.Body, ctx); }); @@ -91,8 +105,7 @@ Cancel ctx { var euid = TryGetEuid(context); - var feedbackActivitySource = new ActivitySource(TelemetryConstants.AskAiFeedbackSourceName); - using var activity = feedbackActivitySource.StartActivity("record message-feedback", ActivityKind.Internal); + using var activity = AskAiFeedbackActivitySource.StartActivity("record message-feedback", ActivityKind.Internal); _ = activity?.SetTag("gen_ai.conversation.id", request.ConversationId); _ = activity?.SetTag("ask_ai.message.id", request.MessageId); _ = activity?.SetTag("ask_ai.feedback.reaction", request.Reaction.ToString().ToLowerInvariant()); @@ -106,7 +119,8 @@ Cancel ctx var record = new AskAiMessageFeedbackRecord(request.MessageId, request.ConversationId, request.Reaction, euid); - await feedbackService.RecordFeedbackAsync(record, ctx); + if (!await feedbackService.RecordFeedbackAsync(record, ctx)) + return Results.StatusCode(StatusCodes.Status503ServiceUnavailable); return Results.NoContent(); }).DisableAntiforgery(); } diff --git a/src/api/Elastic.Documentation.Api/Program.cs b/src/api/Elastic.Documentation.Api/Program.cs index 10cfba7cbf..22348eac21 100644 --- a/src/api/Elastic.Documentation.Api/Program.cs +++ b/src/api/Elastic.Documentation.Api/Program.cs @@ -6,6 +6,7 @@ using Elastic.Documentation.Api.OpenTelemetry; using Elastic.Documentation.Configuration; using Elastic.Documentation.Configuration.Assembler; +using Elastic.Documentation.Search; using Elastic.Documentation.Search.Common; using Elastic.Documentation.ServiceDefaults; using Elastic.Documentation.ServiceDefaults.Telemetry; @@ -54,13 +55,26 @@ _ = app.Environment.IsDevelopment() ? app.UseDeveloperExceptionPage() - : app.UseExceptionHandler(err => err.Run(context => + : app.UseExceptionHandler(err => err.Run(async context => { var ex = context.Features.Get()?.Error; - if (ex != null) - logger.LogError(ex, "Unhandled exception on {Method} {Path}", context.Request.Method, context.Request.Path); - context.Response.StatusCode = 500; - return Task.CompletedTask; + ApiError error; + if (ex is SearchUnavailableException) + { + // Transient by construction (timeout, overload): tell clients and the CDN to retry instead of failing. + logger.LogWarning(ex, "Search unavailable on {Method} {Path}", context.Request.Method, context.Request.Path); + context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable; + context.Response.Headers.RetryAfter = "5"; + error = new ApiError("search_unavailable", ex.Message); + } + else + { + if (ex != null) + logger.LogError(ex, "Unhandled exception on {Method} {Path}", context.Request.Method, context.Request.Path); + context.Response.StatusCode = StatusCodes.Status500InternalServerError; + error = new ApiError("internal_error", "An unexpected error occurred."); + } + await context.Response.WriteAsJsonAsync(error, ApiJsonContext.Default.ApiError); })); var api = app.MapGroup(SystemEnvironmentVariables.Instance.ApiPrefix); diff --git a/src/api/Elastic.Documentation.Api/SerializationContext.cs b/src/api/Elastic.Documentation.Api/SerializationContext.cs index 6e51fafd17..c238b75603 100644 --- a/src/api/Elastic.Documentation.Api/SerializationContext.cs +++ b/src/api/Elastic.Documentation.Api/SerializationContext.cs @@ -18,6 +18,9 @@ public record InputMessage(string Role, MessagePart[] Parts); public record OutputMessage(string Role, MessagePart[] Parts, string FinishReason); +/// The body of an error response: a stable and a message for people. +public sealed record ApiError(string ErrorType, string Message); + [JsonSerializable(typeof(AskAiRequest))] [JsonSerializable(typeof(AskAiMessageFeedbackRequest))] [JsonSerializable(typeof(Reaction))] @@ -47,5 +50,6 @@ public record OutputMessage(string Role, MessagePart[] Parts, string FinishReaso [JsonSerializable(typeof(Search.ApiReference.ApiSummary))] [JsonSerializable(typeof(Search.ApiReference.ApiOperationListResponse))] [JsonSerializable(typeof(Search.ApiReference.ApiReferenceRejection))] +[JsonSerializable(typeof(ApiError))] [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] public partial class ApiJsonContext : JsonSerializerContext; diff --git a/src/api/Elastic.Documentation.Api/ServicesExtension.cs b/src/api/Elastic.Documentation.Api/ServicesExtension.cs index f979096883..4f9b2b00bd 100644 --- a/src/api/Elastic.Documentation.Api/ServicesExtension.cs +++ b/src/api/Elastic.Documentation.Api/ServicesExtension.cs @@ -41,24 +41,14 @@ public class AppEnvironment public static class ServicesExtension { - private static ILogger? GetLogger(IServiceCollection services) - { - using var serviceProvider = services.BuildServiceProvider(); - var loggerFactory = serviceProvider.GetService(); - return loggerFactory?.CreateLogger(typeof(ServicesExtension)); - } - public static void AddElasticDocsApiServices(this IServiceCollection services, string? appEnvironment) { if (AppEnvExtensions.TryParse(appEnvironment, out var parsedEnvironment, true)) AddElasticDocsApiServices(services, parsedEnvironment); else { - var logger = GetLogger(services); - logger?.LogWarning( - "Unable to parse environment {AppEnvironment} into AppEnvironment. Using default AppEnvironment.Dev", - appEnvironment - ); + // No logger exists before the host is built; Program.cs reports startup on the console too. + Console.WriteLine($"Unable to parse environment '{appEnvironment}' into AppEnvironment. Using default AppEnvironment.Dev"); AddElasticDocsApiServices(services, AppEnv.Dev); } } @@ -70,13 +60,6 @@ private static void AddElasticDocsApiServices(this IServiceCollection services, options.SerializerOptions.TypeInfoResolverChain.Insert(0, ApiJsonContext.Default); }); - // Configure HttpClient for streaming optimization - _ = services.AddHttpClient("StreamingHttpClient", client => - { - // Disable response buffering for streaming - client.DefaultRequestHeaders.Connection.Add("keep-alive"); - client.Timeout = TimeSpan.FromMinutes(10); // Longer timeout for streaming - }); // Register AppEnvironment as a singleton for dependency injection _ = services.AddSingleton(new AppEnvironment { Current = appEnv }); _ = services.AddSingleton( @@ -85,119 +68,72 @@ private static void AddElasticDocsApiServices(this IServiceCollection services, ) ); AddDistributedCache(services, appEnv); - AddAskAiServices(services, appEnv); + AddAskAiServices(services); AddPageFeedbackServices(services); - AddSearchServices(services, appEnv); + _ = services.AddSearchServices(); + _ = services.AddApiReferenceServices(); } - // Note: IParameterProvider is no longer needed - all options now read from IConfiguration (env vars) - // The LambdaExtensionParameterProvider and LocalParameterProvider can be removed in a future cleanup - private static void AddDistributedCache(IServiceCollection services, AppEnv appEnv) { - var logger = GetLogger(services); - switch (appEnv) { case AppEnv.Dev: - { - logger?.LogInformation("Configuring InMemoryDistributedCache for environment {AppEnvironment}", appEnv); - _ = services.AddSingleton(); - logger?.LogInformation("InMemoryDistributedCache registered for local development"); - break; - } + _ = services.AddSingleton(); + break; case AppEnv.Prod: case AppEnv.Staging: case AppEnv.Edge: + _ = services.AddSingleton(); + // L1: in-memory, L2: DynamoDB + _ = services.AddSingleton(sp => { - logger?.LogInformation("Configuring DynamoDB distributed cache for environment {AppEnvironment}", appEnv); - try - { - // Register AWS DynamoDB client - _ = services.AddSingleton(); - logger?.LogInformation("AmazonDynamoDB client registered"); - - // Register multi-layer cache (L1: in-memory + L2: DynamoDB) - _ = services.AddSingleton(sp => - { - var dynamoDb = sp.GetRequiredService(); - var tableName = $"docs-api-cache-{appEnv.ToStringFast(true)}"; - var dynamoLogger = sp.GetRequiredService>(); - var multiLogger = sp.GetRequiredService>(); - - var dynamoCache = new DynamoDbDistributedCache(dynamoDb, tableName, dynamoLogger); - var multiLayerCache = new MultiLayerCache(dynamoCache, multiLogger); - logger?.LogInformation("Multi-layer cache registered with DynamoDB table: {TableName}", tableName); - return multiLayerCache; - }); - } - catch (Exception ex) - { - logger?.LogError(ex, "Failed to configure distributed cache for environment {AppEnvironment}", appEnv); - throw; - } - break; - } + var tableName = $"docs-api-cache-{appEnv.ToStringFast(true)}"; + var dynamoCache = new DynamoDbDistributedCache( + sp.GetRequiredService(), + tableName, + sp.GetRequiredService>() + ); + return new MultiLayerCache(dynamoCache, sp.GetRequiredService>()); + }); + break; default: - { - throw new ArgumentOutOfRangeException(nameof(appEnv), appEnv, "Unsupported environment for distributed cache."); - } + throw new ArgumentOutOfRangeException(nameof(appEnv), appEnv, "Unsupported environment for distributed cache."); } } - private static void AddAskAiServices(IServiceCollection services, AppEnv appEnv) + private static void AddAskAiServices(IServiceCollection services) { - var logger = GetLogger(services); - logger?.LogInformation("Configuring AskAi services for environment {AppEnvironment}", appEnv); - - try - { - // Register GcpIdTokenProvider with distributed cache dependency - // Clean: Let DI handle everything automatically - _ = services.AddSingleton(); - logger?.LogInformation("GcpIdTokenProvider registered with distributed cache support"); - - // Register options - DI auto-resolves IConfiguration from primary constructor - _ = services.AddSingleton(); - logger?.LogInformation("LlmGatewayOptions registered successfully"); - - _ = services.AddSingleton(); - logger?.LogInformation("KibanaOptions registered successfully"); - - _ = services.AddSingleton(); - - _ = services.AddScoped(); - _ = services.AddScoped(); - _ = services.AddScoped(); - _ = services.AddScoped(); - - _ = services.AddScoped( - sp => - sp.GetRequiredService().Provider switch - { - AskAiProvider.AgentBuilder => sp.GetRequiredService(), - _ => sp.GetRequiredService() - } - ); - _ = services.AddScoped( - sp => - sp.GetRequiredService().Provider switch - { - AskAiProvider.AgentBuilder => sp.GetRequiredService(), - _ => sp.GetRequiredService() - } - ); - logger?.LogInformation("Ask AI services registered; provider comes from {Key}", AskAiProviderOptions.ConfigurationKey); + _ = services.AddSingleton(); + _ = services.AddSingleton(); + _ = services.AddSingleton(); + _ = services.AddSingleton(); + + _ = services.AddScoped(); + _ = services.AddScoped(); + _ = services.AddScoped(); + _ = services.AddScoped(); + + // The provider comes from AskAiProviderOptions.ConfigurationKey and is fixed per deployment. + _ = services.AddScoped( + sp => + sp.GetRequiredService().Provider switch + { + AskAiProvider.AgentBuilder => sp.GetRequiredService(), + _ => sp.GetRequiredService() + } + ); + _ = services.AddScoped( + sp => + sp.GetRequiredService().Provider switch + { + AskAiProvider.AgentBuilder => sp.GetRequiredService(), + _ => sp.GetRequiredService() + } + ); - // Register message feedback service (singleton for connection reuse) - _ = services.AddSingleton(); - logger?.LogInformation("AskAiMessageFeedbackService (Elasticsearch) registered successfully"); - } - catch (Exception ex) - { - logger?.LogError(ex, "Failed to configure AskAi services for environment {AppEnvironment}", appEnv); - throw; - } + // Singleton for connection reuse + _ = services.AddSingleton(); } private static void AddPageFeedbackServices(IServiceCollection services) @@ -213,15 +149,4 @@ private static void AddPageFeedbackServices(IServiceCollection services) _ = services.AddSingleton(); _ = services.AddHostedService(); } - - private static void AddSearchServices(IServiceCollection services, AppEnv appEnv) - { - var logger = GetLogger(services); - logger?.LogInformation("Configuring Search services for environment {AppEnvironment}", appEnv); - - // Use the shared search service for DI registration - _ = services.AddSearchServices(); - _ = services.AddApiReferenceServices(); - logger?.LogInformation("Full search service registered with hybrid RRF support"); - } } diff --git a/src/api/Elastic.Documentation.Api/Validation/IValidator.cs b/src/api/Elastic.Documentation.Api/Validation/IValidator.cs deleted file mode 100644 index 3948cd2783..0000000000 --- a/src/api/Elastic.Documentation.Api/Validation/IValidator.cs +++ /dev/null @@ -1,12 +0,0 @@ -// Licensed to Elasticsearch B.V under one or more agreements. -// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. -// See the LICENSE file in the project root for more information - -namespace Elastic.Documentation.Api.Validation; - -public interface IValidator -{ - ValidationResult Validate(T t); -} - -public abstract record ValidationResult(bool IsValid, string Message); diff --git a/src/api/Elastic.Documentation.Mcp.Remote/Tools/SearchTools.cs b/src/api/Elastic.Documentation.Mcp.Remote/Tools/SearchTools.cs index fc8e25d0a1..2a38190c44 100644 --- a/src/api/Elastic.Documentation.Mcp.Remote/Tools/SearchTools.cs +++ b/src/api/Elastic.Documentation.Mcp.Remote/Tools/SearchTools.cs @@ -44,8 +44,8 @@ public Task SemanticSearch( var request = new FullSearchRequest { Query = query, - PageNumber = Math.Max(1, pageNumber), - PageSize = Math.Clamp(pageSize, 1, 50), + PageNumber = pageNumber, + PageSize = pageSize, ProductFilter = productFilter != null ? [productFilter] : null, SectionFilter = sectionFilter != null ? [sectionFilter] : null, IncludeHighlighting = false diff --git a/src/services/search/Elastic.Documentation.Search/FullSearchService.cs b/src/services/search/Elastic.Documentation.Search/FullSearchService.cs index 3fc56558d8..c44a331e00 100644 --- a/src/services/search/Elastic.Documentation.Search/FullSearchService.cs +++ b/src/services/search/Elastic.Documentation.Search/FullSearchService.cs @@ -22,6 +22,9 @@ public partial class FullSearchService( ILogger logger ) : IFullSearchService, IDisposable { + /// The largest page any caller gets; the site asks for at most 50. + public const int MaxPageSize = 50; + public async Task SearchAsync(FullSearchRequest request, Cancel ctx = default) { SearchResponse resp; @@ -31,8 +34,8 @@ public async Task SearchAsync(FullSearchRequest request, Can new SearchRequest { Query = request.Query, - PageNumber = request.PageNumber, - PageSize = request.PageSize, + PageNumber = Math.Max(1, request.PageNumber), + PageSize = Math.Clamp(request.PageSize, 1, MaxPageSize), TypeFilter = request.TypeFilter ?? [], SectionFilter = request.SectionFilter ?? [], ProductFilter = request.ProductFilter ?? [], diff --git a/src/services/search/Elastic.Documentation.Search/ServicesExtension.cs b/src/services/search/Elastic.Documentation.Search/ServicesExtension.cs index ce27d1d195..5c3354ef2d 100644 --- a/src/services/search/Elastic.Documentation.Search/ServicesExtension.cs +++ b/src/services/search/Elastic.Documentation.Search/ServicesExtension.cs @@ -25,9 +25,6 @@ public static class ServicesExtension /// public static IServiceCollection AddSearchServices(this IServiceCollection services) { - var logger = GetLogger(services); - logger?.LogInformation("Configuring Search services"); - _ = services.AddSingleton(); // ProductsConfiguration already implements IProductNameLookup; surface it via the @@ -58,7 +55,6 @@ public static IServiceCollection AddSearchServices(this IServiceCollection servi // Docs-specific adapters preserve the existing API/MCP wire format. _ = services.AddScoped(); _ = services.AddScoped(); - logger?.LogInformation("Full search services registered with hybrid RRF support"); // Changes feed (cursor-paginated changes since a given date) _ = services.AddSingleton(); @@ -77,11 +73,4 @@ public static IServiceCollection AddApiReferenceServices(this IServiceCollection _ = services.AddScoped(); return services; } - - private static ILogger? GetLogger(IServiceCollection services) - { - using var serviceProvider = services.BuildServiceProvider(); - var loggerFactory = serviceProvider.GetService(); - return loggerFactory?.CreateLogger(typeof(ServicesExtension)); - } } diff --git a/tests/Elastic.Documentation.Api.Tests/ApiErrorResponseTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiErrorResponseTests.cs new file mode 100644 index 0000000000..dd011c1985 --- /dev/null +++ b/tests/Elastic.Documentation.Api.Tests/ApiErrorResponseTests.cs @@ -0,0 +1,96 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +using System.Net; +using System.Net.Http.Json; +using System.Text.Json; +using AwesomeAssertions; +using Elastic.Documentation.Api.AskAi; +using Elastic.Documentation.Api.Tests.Fixtures; +using Elastic.Documentation.Search; +using FakeItEasy; + +namespace Elastic.Documentation.Api.Tests; + +// The tests share one host and swap the services it resolves, so they run one after another. +[NotInParallel(nameof(ApiErrorResponseTests))] +public class ApiErrorResponseTests +{ + private static readonly SwappableService Search = new(); + private static readonly SwappableService Feedback = new(); + + private static readonly Lazy SharedFactory = new(() => ApiWebApplicationFactory.WithMockedServices(replacements => + { + _ = replacements.Replace(_ => Search.Current); + _ = replacements.Replace(_ => Feedback.Current); + })); + + [After(Class)] + public static void DisposeSharedFactory() + { + if (SharedFactory.IsValueCreated) + SharedFactory.Value.Dispose(); + } + + private static CancellationToken Ct => TestContext.Current!.Execution.CancellationToken; + + private static async Task<(HttpResponseMessage Response, JsonElement Body)> SearchThrowing(Exception exception) + { + var search = A.Fake(); + _ = A.CallTo(() => search.SearchAsync(A._, A._)).ThrowsAsync(exception); + Search.Current = search; + using var client = SharedFactory.Value.CreateClient(); + var response = await client.GetAsync("/docs/_api/v1/search/?q=health", Ct); + return (response, JsonElement.Parse(await response.Content.ReadAsStringAsync(Ct))); + } + + [Test] + public async Task Search_BackendUnavailable_IsARetryable503() + { + var (response, body) = await SearchThrowing(SearchUnavailableException.Transient("MaxTimeoutReached")); + + using (response) + { + response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + response.Headers.RetryAfter!.Delta.Should().Be(TimeSpan.FromSeconds(5)); + body.GetProperty("errorType").GetString().Should().Be("search_unavailable"); + body.GetProperty("message").GetString().Should().Contain("MaxTimeoutReached"); + } + } + + [Test] + public async Task Search_UnexpectedFailure_IsA500WithABodyThatHidesTheException() + { + var (response, body) = await SearchThrowing(new InvalidOperationException("secret detail")); + + using (response) + { + response.StatusCode.Should().Be(HttpStatusCode.InternalServerError); + response.Headers.RetryAfter.Should().BeNull(); + body.GetProperty("errorType").GetString().Should().Be("internal_error"); + body.GetProperty("message").GetString().Should().NotContain("secret detail"); + } + } + + [Test] + [Arguments(true, HttpStatusCode.NoContent)] + [Arguments(false, HttpStatusCode.ServiceUnavailable)] + public async Task MessageFeedback_ReportsWhetherTheFeedbackWasStored(bool stored, HttpStatusCode expected) + { + var feedback = A.Fake(); + _ = A.CallTo(() => feedback.RecordFeedbackAsync(A._, A._)).Returns(stored); + Feedback.Current = feedback; + using var client = SharedFactory.Value.CreateClient(); + + using var response = await client.PostAsJsonAsync( + "/docs/_api/v1/ask-ai/message-feedback", + new AskAiMessageFeedbackRequest(Guid.NewGuid(), Guid.NewGuid(), Reaction.ThumbsUp), + ApiJsonContext.Default.AskAiMessageFeedbackRequest, + Ct + ); + + response.StatusCode.Should().Be(expected); + A.CallTo(() => feedback.RecordFeedbackAsync(A._, A._)).MustHaveHappenedOnceExactly(); + } +} diff --git a/tests/Elastic.Documentation.Api.Tests/Fixtures/ApiWebApplicationFactory.cs b/tests/Elastic.Documentation.Api.Tests/Fixtures/ApiWebApplicationFactory.cs index ab97786c5f..ca3d5afa9f 100644 --- a/tests/Elastic.Documentation.Api.Tests/Fixtures/ApiWebApplicationFactory.cs +++ b/tests/Elastic.Documentation.Api.Tests/Fixtures/ApiWebApplicationFactory.cs @@ -4,7 +4,6 @@ using System.Diagnostics; using Elastic.Documentation.Api; -using Elastic.Documentation.Api.Aws; using Elastic.Documentation.Api.OpenTelemetry; using Elastic.Documentation.ServiceDefaults; using FakeItEasy; @@ -100,11 +99,6 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) _ = logging.AddInMemoryExporter(ExportedLogRecords); }); - // Mock IParameterProvider to avoid AWS dependencies in all tests - var mockParameterProvider = A.Fake(); - A.CallTo(() => mockParameterProvider.GetParam(A._, A._, A._)).Returns(Task.FromResult("mock-value")); - _ = services.AddSingleton(mockParameterProvider); - // Apply test-specific service replacements (if any) _configureServices?.Invoke(services); }); diff --git a/tests/Elastic.Documentation.Api.Tests/FullSearchServiceTests.cs b/tests/Elastic.Documentation.Api.Tests/FullSearchServiceTests.cs new file mode 100644 index 0000000000..9779b66745 --- /dev/null +++ b/tests/Elastic.Documentation.Api.Tests/FullSearchServiceTests.cs @@ -0,0 +1,41 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +using AwesomeAssertions; +using Elastic.Documentation.Search; +using Elastic.Documentation.Search.Contract; +using FakeItEasy; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Elastic.Documentation.Api.Tests; + +public class FullSearchServiceTests +{ + [Test] + [Arguments(0, 0, 1, 1)] + [Arguments(-3, -5, 1, 1)] + [Arguments(2, 20, 2, 20)] + [Arguments(1, 100000, 1, FullSearchService.MaxPageSize)] + public async Task SearchAsync_ClampsPageAndSizeBeforeQueryingTheIndex(int page, int size, int expectedPage, int expectedSize) + { + SearchRequest? received = null; + var inner = A.Fake>(); + _ = A + .CallTo(() => inner.SearchAsync(A._, A._)) + .Invokes((SearchRequest request, CancellationToken _) => received = request) + .Throws(new OperationCanceledException("stop after the request is captured")); + using var service = new FullSearchService(inner, A.Fake(), NullLogger.Instance); + + var search = + () => service.SearchAsync( + new FullSearchRequest { Query = "health", PageNumber = page, PageSize = size }, + TestContext.Current!.Execution.CancellationToken + ); + + _ = await search.Should().ThrowAsync(); + received.Should().NotBeNull(); + received.PageNumber.Should().Be(expectedPage); + received.PageSize.Should().Be(expectedSize); + } +} From 7abcc8c9921e65a1cdcf439294f853b5bf691982 Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 16:46:57 +0100 Subject: [PATCH 2/3] Test the Ask AI feedback write result and the stream activity on failure The gateway test drives the real gateway through an in-memory transport, so returning true on a failed write fails it. The stream tests fail AskAi and the transformer in turn and check the chat activity was ended with an error; without the handler's catch, the activity is never exported. Co-Authored-By: Claude Opus 5.5 --- .../AskAiMessageFeedbackGatewayTests.cs | 42 ++++++++++ .../AskAiStreamFailureTests.cs | 82 +++++++++++++++++++ 2 files changed, 124 insertions(+) create mode 100644 tests/Elastic.Documentation.Api.Tests/AskAiMessageFeedbackGatewayTests.cs create mode 100644 tests/Elastic.Documentation.Api.Tests/AskAiStreamFailureTests.cs diff --git a/tests/Elastic.Documentation.Api.Tests/AskAiMessageFeedbackGatewayTests.cs b/tests/Elastic.Documentation.Api.Tests/AskAiMessageFeedbackGatewayTests.cs new file mode 100644 index 0000000000..f806c6b196 --- /dev/null +++ b/tests/Elastic.Documentation.Api.Tests/AskAiMessageFeedbackGatewayTests.cs @@ -0,0 +1,42 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +using System.Text; +using AwesomeAssertions; +using Elastic.Documentation.Api.Adapters.AskAi; +using Elastic.Documentation.Api.AskAi; +using Elastic.Transport; +using Microsoft.Extensions.Logging.Abstractions; + +namespace Elastic.Documentation.Api.Tests; + +public class AskAiMessageFeedbackGatewayTests +{ + [Test] + [Arguments(201, true)] + [Arguments(200, true)] + [Arguments(400, false)] + [Arguments(503, false)] + public async Task RecordFeedbackAsync_ReportsWhetherElasticsearchStoredTheFeedback(int statusCode, bool stored) + { + var transport = new DistributedTransport( + new TransportConfiguration( + new SingleNodePool(new Uri("http://localhost:9200")), + new InMemoryRequestInvoker(Encoding.UTF8.GetBytes("""{"result":"created"}"""), statusCode) + ) + ); + var gateway = new ElasticsearchAskAiMessageFeedbackGateway( + transport, + new AppEnvironment { Current = AppEnv.Dev }, + NullLogger.Instance + ); + + var result = await gateway.RecordFeedbackAsync( + new AskAiMessageFeedbackRecord(Guid.NewGuid(), Guid.NewGuid(), Reaction.ThumbsUp), + TestContext.Current!.Execution.CancellationToken + ); + + result.Should().Be(stored); + } +} diff --git a/tests/Elastic.Documentation.Api.Tests/AskAiStreamFailureTests.cs b/tests/Elastic.Documentation.Api.Tests/AskAiStreamFailureTests.cs new file mode 100644 index 0000000000..00f3910a79 --- /dev/null +++ b/tests/Elastic.Documentation.Api.Tests/AskAiStreamFailureTests.cs @@ -0,0 +1,82 @@ +// Licensed to Elasticsearch B.V under one or more agreements. +// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. +// See the LICENSE file in the project root for more information + +using System.Diagnostics; +using System.Text; +using AwesomeAssertions; +using Elastic.Documentation.Api.AskAi; +using Elastic.Documentation.Api.Tests.Fixtures; +using FakeItEasy; +using Microsoft.Extensions.DependencyInjection; +using TUnit.Core.Interfaces; + +namespace Elastic.Documentation.Api.Tests; + +/// +/// Until the stream transformer takes the chat activity, the handler owns it. A failure before that point must +/// still end the activity, with an error status, or the span never finishes and is never exported. +/// +public class AskAiStreamFailureTests : IAsyncInitializer, IAsyncDisposable +{ + // The API exports spans only when an OTLP endpoint is configured, as in EuidEnrichmentTests. + public Task InitializeAsync() + { + Environment.SetEnvironmentVariable("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4318"); + return Task.CompletedTask; + } + + public ValueTask DisposeAsync() + { + GC.SuppressFinalize(this); + Environment.SetEnvironmentVariable("OTEL_EXPORTER_OTLP_ENDPOINT", null); + return ValueTask.CompletedTask; + } + + [Test] + [Arguments(true)] + [Arguments(false)] + public async Task Stream_FailureBeforeTheTransformerOwnsTheActivity_EndsItWithAnError(bool askAiFails) + { + // Every factory's listener sees every Ask AI span in the process, so find this test's span by its failure. + var failure = $"{(askAiFails ? "provider down" : "transform failed")} {Guid.NewGuid()}"; + using var factory = ApiWebApplicationFactory.WithMockedServices(services => + { + var askAi = A.Fake(); + if (askAiFails) + _ = A.CallTo(() => askAi.AskAi(A._, A._)).ThrowsAsync(new InvalidOperationException(failure)); + else + _ = A.CallTo(() => askAi.AskAi(A._, A._)).Returns( + new AskAiGatewayResponse(new MemoryStream(), GeneratedConversationId: Guid.NewGuid()) + ); + _ = services.AddSingleton(askAi); + + var transformer = A.Fake(); + _ = A.CallTo(() => transformer.AgentProvider).Returns("test-provider"); + _ = A.CallTo(() => transformer.AgentId).Returns("test-agent"); + _ = A.CallTo(() => transformer.TransformAsync(A._, A._, A._, A._)).ThrowsAsync( + new InvalidOperationException(failure) + ); + _ = services.AddSingleton(transformer); + }); + using var client = factory.CreateClient(); + + using var response = await client.PostAsync( + "/docs/_api/v1/ask-ai/stream", + new StringContent("""{"message":"test question","conversationId":null}""", Encoding.UTF8, "application/json"), + TestContext.Current!.Execution.CancellationToken + ); + + response.IsSuccessStatusCode.Should().BeFalse(); + // Exported means ended: an activity that is never stopped never reaches the exporter. + factory + .ExportedActivities + .Where(a => a.Source.Name == TelemetryConstants.AskAiSourceName && a.StatusDescription == failure) + .Should() + .ContainSingle() + .Which + .Status + .Should() + .Be(ActivityStatusCode.Error); + } +} From 12207a5176e86b94bbba2dcaa0678bc046184f53 Mon Sep 17 00:00:00 2001 From: Andrea De Pirro Date: Tue, 17 Nov 2026 16:47:52 +0100 Subject: [PATCH 3/3] Run the tests that read Ask AI spans one at a time Every factory's listener sees every Ask AI span in the process, so EuidEnrichmentTests could read the span of a parallel AskAiStreamFailureTests run, which has no euid. Co-Authored-By: Claude Opus 5.5 --- .../Elastic.Documentation.Api.Tests/AskAiStreamFailureTests.cs | 2 ++ tests/Elastic.Documentation.Api.Tests/EuidEnrichmentTests.cs | 2 ++ 2 files changed, 4 insertions(+) diff --git a/tests/Elastic.Documentation.Api.Tests/AskAiStreamFailureTests.cs b/tests/Elastic.Documentation.Api.Tests/AskAiStreamFailureTests.cs index 00f3910a79..3e2cb30e21 100644 --- a/tests/Elastic.Documentation.Api.Tests/AskAiStreamFailureTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/AskAiStreamFailureTests.cs @@ -17,6 +17,8 @@ namespace Elastic.Documentation.Api.Tests; /// Until the stream transformer takes the chat activity, the handler owns it. A failure before that point must /// still end the activity, with an error status, or the span never finishes and is never exported. /// +// Every factory listens to every Ask AI span in the process; tests that read those spans run one at a time. +[NotInParallel("ask-ai-spans")] public class AskAiStreamFailureTests : IAsyncInitializer, IAsyncDisposable { // The API exports spans only when an OTLP endpoint is configured, as in EuidEnrichmentTests. diff --git a/tests/Elastic.Documentation.Api.Tests/EuidEnrichmentTests.cs b/tests/Elastic.Documentation.Api.Tests/EuidEnrichmentTests.cs index f94a653dfc..c209427c78 100644 --- a/tests/Elastic.Documentation.Api.Tests/EuidEnrichmentTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/EuidEnrichmentTests.cs @@ -18,6 +18,8 @@ namespace Elastic.Documentation.Api.Tests; /// Integration tests for euid cookie enrichment in OpenTelemetry traces and logging. /// Uses WebApplicationFactory to test the real API configuration with mocked AskAi services. /// +// Every factory listens to every Ask AI span in the process; tests that read those spans run one at a time. +[NotInParallel("ask-ai-spans")] public class EuidEnrichmentTests : IAsyncInitializer, IAsyncDisposable { private const string OtlpEndpoint = "http://localhost:4318";