diff --git a/Directory.Packages.props b/Directory.Packages.props index 149302d32b..6cea4748e3 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -58,6 +58,7 @@ + diff --git a/docs/data/api.md b/docs/data/api.md index ecdcafd8e8..6ea38fa27a 100644 --- a/docs/data/api.md +++ b/docs/data/api.md @@ -6,6 +6,8 @@ navigation_title: REST API {{dbuild}} includes a REST API server (`Elastic.Documentation.Api`) that powers search, AI assistance, and content change feeds for the documentation site. +The server describes itself in an OpenAPI document at `/docs/_api/v1/openapi.json`, generated from its endpoints. It lists every endpoint with its parameters, request bodies, responses, and error codes. Requests through `www.elastic.co` need the cookie `feature_search_or_askai_enabled=true`; without it, the CDN answers `403`. + ## Endpoints | Endpoint | Description | @@ -53,7 +55,7 @@ The response has `totalHits` and `results`. Each result has its `operation`, plu ### Errors -A request these resources can't answer returns `{ "errorType": "...", "message": "..." }`. The status is `404` when `errorType` ends in `_not_found`: `operation_not_found`, `api_not_found`, or `group_not_found`. Invalid arguments return `400` with `invalid_arguments`. +The API operations resources report errors like every other endpoint; see [Errors](#errors). ## Ask AI provider @@ -67,6 +69,55 @@ Each deployment of the API server picks its Ask AI provider with the `DOCUMENTAT The value is case-insensitive. Any other value stops the Ask AI service with a configuration error. LLM Gateway needs `LLM_GATEWAY_FUNCTION_URL` and `LLM_GATEWAY_SERVICE_ACCOUNT`. Agent Builder needs `DOCUMENTATION_KIBANA_URL` and `DOCUMENTATION_KIBANA_APIKEY`. A deployment that uses Agent Builder, such as Codex, must set `DOCUMENTATION_ASK_AI_PROVIDER=AgentBuilder`. -:::{note} -A formal OpenAPI specification should be generated from the API server as a follow-up. This page will be updated with full endpoint details, request/response schemas, and authentication requirements once the spec is available. -::: +## Errors + +Every error is an [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) problem, served as `application/problem+json`: + +```json +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "Pass q or endpoint, not both.", + "traceId": "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01" +} +``` + +- `type` identifies the problem and links to its section below. Match on it, not on `title` or `detail`. +- `title` is the same for every occurrence of a type. +- `detail` explains this occurrence, for people. +- `traceId` names the request's trace. Quote it when you report a problem. + +Errors from the CDN, such as the `403` for a missing cookie, aren't problems and aren't JSON. + +### Invalid arguments [invalid-arguments] + +`400`. A parameter is missing, doesn't parse, or contradicts another one. `detail` says which. + +### Not found [not-found] + +`404`. No endpoint matches the path. + +### API operation not found [operation-not-found] + +`404`. No API operation has that id, or serves that endpoint, in the requested API and version. + +### API not found [api-not-found] + +`404`. No API has that key, or it has no operations in the requested version. + +### API group not found [group-not-found] + +`404`. The API has no group with that name. + +### Internal error [internal-error] + +`500`. An unexpected failure. `detail` doesn't include its cause; use `traceId` to report it. + +### Search unavailable [search-unavailable] + +`503`. Elasticsearch timed out or is overloaded. Retry after the seconds in the `Retry-After` header. + +### Feedback unavailable [feedback-unavailable] + +`503`. Feedback could not be stored. Retry later. diff --git a/src/api/Elastic.Documentation.Api/ApiProblems.cs b/src/api/Elastic.Documentation.Api/ApiProblems.cs new file mode 100644 index 0000000000..6783f30d93 --- /dev/null +++ b/src/api/Elastic.Documentation.Api/ApiProblems.cs @@ -0,0 +1,98 @@ +// 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 Elastic.Documentation.Search; +using Microsoft.AspNetCore.Http; + +namespace Elastic.Documentation.Api; + +/// +/// The RFC 9457 problem types of the docs API. Every error answers application/problem+json whose +/// type is one of these, resolving to its section of the REST API page (docs/data/api.md). +/// +public static class ApiProblems +{ + private const string TypeBase = "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#"; + + public const string InvalidArguments = "invalid-arguments"; + public const string NotFound = "not-found"; + public const string InternalError = "internal-error"; + public const string SearchUnavailable = "search-unavailable"; + public const string FeedbackUnavailable = "feedback-unavailable"; + + // A title is the same for every occurrence of a type (RFC 9457 ยง3.1.3); what varies goes in detail. + private static readonly Dictionary Titles = new(StringComparer.Ordinal) + { + [InvalidArguments] = "Invalid arguments", + [NotFound] = "Not found", + ["operation-not-found"] = "API operation not found", + ["api-not-found"] = "API not found", + ["group-not-found"] = "API group not found", + [InternalError] = "Internal error", + [SearchUnavailable] = "Search unavailable", + [FeedbackUnavailable] = "Feedback unavailable" + }; + + /// The absolute type URI of a problem type, such as . + public static string TypeUri(string type) => TypeBase + type; + + /// A problem response of a known type. + public static IResult Problem(int statusCode, string type, string detail) => + Results.Problem(detail: detail, statusCode: statusCode, title: Titles[type], type: TypeUri(type)); + + /// The status an unhandled exception answers with. + public static int StatusCodeFor(Exception exception) => exception switch + { + // A parameter that does not bind, such as a missing q or a since that is not a date. + BadHttpRequestException badRequest => badRequest.StatusCode, + // Transient by construction (timeout, overload): tell clients and the CDN to retry. + SearchUnavailableException => StatusCodes.Status503ServiceUnavailable, + _ => StatusCodes.Status500InternalServerError + }; + + /// + /// Gives the problems ASP.NET writes itself (unhandled exceptions, bodyless status codes) a type of this API. + /// Problems this API builds with already carry one and pass through unchanged. + /// + public static void Customize(ProblemDetailsContext context) + { + var problem = context.ProblemDetails; + switch (context.Exception) + { + case BadHttpRequestException badRequest: + Apply(problem, InvalidArguments, badRequest.Message); + return; + case SearchUnavailableException unavailable: + Apply(problem, SearchUnavailable, unavailable.Message); + context.HttpContext.Response.Headers.RetryAfter = "5"; + return; + case not null: + // Never the exception's own message: it can name internals. + Apply(problem, InternalError, "An unexpected error occurred."); + return; + } + + if (problem.Type is not null && problem.Type.StartsWith(TypeBase, StringComparison.Ordinal)) + return; + switch (problem.Status) + { + case StatusCodes.Status400BadRequest: + Apply(problem, InvalidArguments, "A parameter is missing or does not parse."); + break; + case StatusCodes.Status404NotFound: + Apply(problem, NotFound, "No endpoint matches this path."); + break; + case StatusCodes.Status500InternalServerError: + Apply(problem, InternalError, "An unexpected error occurred."); + break; + } + } + + private static void Apply(Microsoft.AspNetCore.Mvc.ProblemDetails problem, string type, string detail) + { + problem.Type = TypeUri(type); + problem.Title = Titles[type]; + problem.Detail = detail; + } +} diff --git a/src/api/Elastic.Documentation.Api/Elastic.Documentation.Api.csproj b/src/api/Elastic.Documentation.Api/Elastic.Documentation.Api.csproj index 5393faea94..6a5dbcd140 100644 --- a/src/api/Elastic.Documentation.Api/Elastic.Documentation.Api.csproj +++ b/src/api/Elastic.Documentation.Api/Elastic.Documentation.Api.csproj @@ -30,6 +30,7 @@ + diff --git a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs index e3b80c8e39..84d3fda199 100644 --- a/src/api/Elastic.Documentation.Api/MappingsExtensions.cs +++ b/src/api/Elastic.Documentation.Api/MappingsExtensions.cs @@ -24,8 +24,9 @@ public static class MappingsExtension public static void MapElasticDocsApiEndpoints(this IEndpointRouteBuilder group) { - _ = group.MapGet("/", () => Results.Empty); - _ = group.MapPost("/", () => Results.Empty); + // Empty answers for a probe of the group root; not part of the API's contract. + _ = group.MapGet("/", () => Results.Empty).ExcludeFromDescription(); + _ = group.MapPost("/", () => Results.Empty).ExcludeFromDescription(); MapAskAiEndpoint(group); MapNavigationSearch(group); MapFullSearch(group); @@ -37,239 +38,298 @@ public static void MapElasticDocsApiEndpoints(this IEndpointRouteBuilder group) private static void MapAskAiEndpoint(IEndpointRouteBuilder group) { var askAiGroup = group.MapGroup("/ask-ai"); - _ = askAiGroup.MapPost("/stream", async ( - HttpContext context, - AskAiRequest askAiRequest, - IAskAiService askAiService, - IStreamTransformer streamTransformer, - ILogger logger, - Cancel ctx - ) => - { - context.Response.ContentType = "text/event-stream"; - context.Response.Headers.CacheControl = "no-cache"; - context.Response.Headers.Connection = "keep-alive"; - - logger.LogInformation( - "Starting AskAI chat with {AgentProvider} and {AgentId}", - streamTransformer.AgentProvider, - streamTransformer.AgentId - ); - 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); - if (askAiRequest.ConversationId is not null) - _ = activity?.SetTag("gen_ai.conversation.id", askAiRequest.ConversationId.ToString()); - - var inputMessages = new[] { new InputMessage("user", [new MessagePart("text", askAiRequest.Message)]) }; - var inputMessagesJson = JsonSerializer.Serialize(inputMessages, ApiJsonContext.Default.InputMessageArray); - _ = activity?.SetTag("gen_ai.input.messages", inputMessagesJson); - logger.LogInformation("AskAI input message: <{ask_ai.input.message}>", SanitizeForLog(askAiRequest.Message)); - logger.LogInformation("Streaming AskAI response"); - - Stream transformedStream; - try + _ = askAiGroup + .MapPost("/stream", async ( + HttpContext context, + AskAiRequest askAiRequest, + IAskAiService askAiService, + IStreamTransformer streamTransformer, + ILogger logger, + Cancel ctx + ) => { - 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()); - - transformedStream = await streamTransformer.TransformAsync( - response.Stream, - response.GeneratedConversationId, - activity, - ctx + context.Response.ContentType = "text/event-stream"; + context.Response.Headers.CacheControl = "no-cache"; + context.Response.Headers.Connection = "keep-alive"; + + logger.LogInformation( + "Starting AskAI chat with {AgentProvider} and {AgentId}", + streamTransformer.AgentProvider, + streamTransformer.AgentId ); - } - 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); - }); + 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); + if (askAiRequest.ConversationId is not null) + _ = activity?.SetTag("gen_ai.conversation.id", askAiRequest.ConversationId.ToString()); + + var inputMessages = new[] { new InputMessage("user", [new MessagePart("text", askAiRequest.Message)]) }; + var inputMessagesJson = JsonSerializer.Serialize(inputMessages, ApiJsonContext.Default.InputMessageArray); + _ = activity?.SetTag("gen_ai.input.messages", inputMessagesJson); + logger.LogInformation("AskAI input message: <{ask_ai.input.message}>", SanitizeForLog(askAiRequest.Message)); + logger.LogInformation("Streaming AskAI response"); + + 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()); + + 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); + }) + .WithTags(AskAiTag) + .WithName("ask-ai-stream") + .WithSummary("Stream an Ask AI answer as server-sent events") + .Produces(StatusCodes.Status200OK, contentType: "text/event-stream") + .ProducesErrors(StatusCodes.Status400BadRequest); // UUID validation is automatic via Guid type deserialization (returns 400 if invalid) - _ = askAiGroup.MapPost("/message-feedback", async ( - HttpContext context, - AskAiMessageFeedbackRequest request, - IAskAiMessageFeedbackService feedbackService, - ILogger logger, - Cancel ctx - ) => - { - var euid = TryGetEuid(context); - - 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()); - - logger.LogInformation( - "Recording message feedback for message {MessageId} in conversation {ConversationId}: {Reaction}", - request.MessageId, - request.ConversationId, - request.Reaction - ); - - var record = new AskAiMessageFeedbackRecord(request.MessageId, request.ConversationId, request.Reaction, euid); - - if (!await feedbackService.RecordFeedbackAsync(record, ctx)) - return Results.StatusCode(StatusCodes.Status503ServiceUnavailable); - return Results.NoContent(); - }).DisableAntiforgery(); + _ = askAiGroup + .MapPost("/message-feedback", async ( + HttpContext context, + AskAiMessageFeedbackRequest request, + IAskAiMessageFeedbackService feedbackService, + ILogger logger, + Cancel ctx + ) => + { + var euid = TryGetEuid(context); + + 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()); + + logger.LogInformation( + "Recording message feedback for message {MessageId} in conversation {ConversationId}: {Reaction}", + request.MessageId, + request.ConversationId, + request.Reaction + ); + + var record = new AskAiMessageFeedbackRecord(request.MessageId, request.ConversationId, request.Reaction, euid); + + if (!await feedbackService.RecordFeedbackAsync(record, ctx)) + return FeedbackUnavailable(); + return Results.NoContent(); + }) + .DisableAntiforgery() + .WithTags(AskAiTag) + .WithName("ask-ai-message-feedback") + .WithSummary("Record a reaction to an Ask AI answer") + .Produces(StatusCodes.Status204NoContent) + .ProducesErrors(StatusCodes.Status400BadRequest, StatusCodes.Status503ServiceUnavailable); } private static void MapNavigationSearch(IEndpointRouteBuilder group) { var searchGroup = group.MapGroup("/navigation-search"); - _ = searchGroup.MapGet("/", async ( - [FromQuery(Name = "q")] string query, - [FromQuery(Name = "page")] int? pageNumber, - [FromQuery(Name = "type")] string? typeFilter, - [FromQuery(Name = "api_key")] string? apiKey, - [FromQuery(Name = "api_tree")] string? apiTree, - INavigationSearchService navigationSearchService, - Cancel ctx - ) => - { - if (!ApiPageParameters.TryParse(apiKey, apiTree, out var apiPage)) - return Results.BadRequest(); - - var request = new NavigationSearchRequest + _ = searchGroup + .MapGet("/", async ( + [FromQuery(Name = "q")] string query, + [FromQuery(Name = "page")] int? pageNumber, + [FromQuery(Name = "type")] string? typeFilter, + [FromQuery(Name = "api_key")] string? apiKey, + [FromQuery(Name = "api_tree")] string? apiTree, + INavigationSearchService navigationSearchService, + Cancel ctx + ) => { - Query = query, - PageNumber = pageNumber ?? 1, - TypeFilter = typeFilter, - ApiPage = apiPage - }; - var response = await navigationSearchService.NavigationSearchAsync(request, ctx); - return Results.Ok(response); - }); + if (!ApiPageParameters.TryParse(apiKey, apiTree, out var apiPage)) + return Invalid("api_key must be a lowercase API key, and api_tree 'main' or a major version with api_key."); + + var request = new NavigationSearchRequest + { + Query = query, + PageNumber = pageNumber ?? 1, + TypeFilter = typeFilter, + ApiPage = apiPage + }; + var response = await navigationSearchService.NavigationSearchAsync(request, ctx); + return Results.Ok(response); + }) + .WithTags(SearchTag) + .WithName("navigation-search") + .WithSummary("Search page titles and the navigation") + .Produces() + .ProducesErrors(StatusCodes.Status400BadRequest, StatusCodes.Status503ServiceUnavailable); } private static void MapFullSearch(IEndpointRouteBuilder group) { var searchGroup = group.MapGroup("/search"); - _ = searchGroup.MapGet("/", async ( - [FromQuery(Name = "q")] string query, - [FromQuery(Name = "page")] int? pageNumber, - [FromQuery(Name = "size")] int? pageSize, - [FromQuery(Name = "type")] string[]? typeFilter, - [FromQuery(Name = "section")] string[]? sectionFilter, - [FromQuery(Name = "deployment")] string[]? deploymentFilter, - [FromQuery(Name = "product")] string[]? productFilter, - [FromQuery(Name = "version")] string? versionFilter, - [FromQuery(Name = "sort")] string? sortBy, - IFullSearchService searchService, - Cancel ctx - ) => - { - var request = new FullSearchRequest + _ = searchGroup + .MapGet("/", async ( + [FromQuery(Name = "q")] string query, + [FromQuery(Name = "page")] int? pageNumber, + [FromQuery(Name = "size")] int? pageSize, + [FromQuery(Name = "type")] string[]? typeFilter, + [FromQuery(Name = "section")] string[]? sectionFilter, + [FromQuery(Name = "deployment")] string[]? deploymentFilter, + [FromQuery(Name = "product")] string[]? productFilter, + [FromQuery(Name = "version")] string? versionFilter, + [FromQuery(Name = "sort")] string? sortBy, + IFullSearchService searchService, + Cancel ctx + ) => { - Query = query, - PageNumber = pageNumber ?? 1, - PageSize = pageSize ?? 20, - TypeFilter = typeFilter, - SectionFilter = sectionFilter, - DeploymentFilter = deploymentFilter, - ProductFilter = productFilter, - VersionFilter = versionFilter, - SortBy = sortBy ?? "relevance" - }; - var response = await searchService.SearchAsync(request, ctx); - return Results.Ok(response); - }); + var request = new FullSearchRequest + { + Query = query, + PageNumber = pageNumber ?? 1, + PageSize = pageSize ?? 20, + TypeFilter = typeFilter, + SectionFilter = sectionFilter, + DeploymentFilter = deploymentFilter, + ProductFilter = productFilter, + VersionFilter = versionFilter, + SortBy = sortBy ?? "relevance" + }; + var response = await searchService.SearchAsync(request, ctx); + return Results.Ok(response); + }) + .WithTags(SearchTag) + .WithName("search") + .WithSummary("Search the documentation") + .Produces() + .ProducesErrors(StatusCodes.Status400BadRequest, StatusCodes.Status503ServiceUnavailable); } private static void MapChanges(IEndpointRouteBuilder group) => - group.MapGet("/changes", async ( - [FromQuery(Name = "since")] DateTimeOffset since, - [FromQuery(Name = "cursor")] string? cursor, - [FromQuery(Name = "size")] int? pageSize, - IChangesService changesService, - Cancel ctx - ) => - { - var request = new ChangesRequest { Since = since, PageSize = pageSize ?? ChangesDefaults.PageSize, Cursor = cursor }; - var response = await changesService.GetChangesAsync(request, ctx); - return Results.Ok(response); - }); + group + .MapGet("/changes", async ( + [FromQuery(Name = "since")] DateTimeOffset since, + [FromQuery(Name = "cursor")] string? cursor, + [FromQuery(Name = "size")] int? pageSize, + IChangesService changesService, + Cancel ctx + ) => + { + // A cursor this endpoint did not return would otherwise restart the feed from its first page. + if (cursor is not null && !ChangesService.IsValidCursor(cursor)) + return Invalid("cursor is not a nextCursor that /changes returned."); + var request = new ChangesRequest { Since = since, PageSize = pageSize ?? ChangesDefaults.PageSize, Cursor = cursor }; + var response = await changesService.GetChangesAsync(request, ctx); + return Results.Ok(response); + }) + .WithTags(ChangesTag) + .WithName("list-changes") + .WithSummary("List the pages that changed since a date") + .Produces() + .ProducesErrors(StatusCodes.Status400BadRequest, StatusCodes.Status503ServiceUnavailable); // The APIs API Explorer publishes and, under each, its operations. An operation is always addressed inside its // API: many operation ids and routes exist in several APIs (elasticsearch and elasticsearch-serverless share // most), so a lookup across APIs could only guess. The MCP tools answer the same lookups. private static void MapApiOperations(IEndpointRouteBuilder group) { - var apis = group.MapGroup("/apis"); - _ = apis.MapGet( - "/", - async (ApiReferenceService apiReference, Cancel ctx) => ToResult(await apiReference.ListAsync(null, null, null, ctx)) - ); - _ = apis.MapGet( - "/{api}", - async (string api, ApiReferenceService apiReference, Cancel ctx) => ToResult(await apiReference.GetApiAsync(api, ctx)) - ); - _ = apis.MapGet( - "/{api}/groups", - async ( - string api, - [FromQuery(Name = "version")] string? version, - [FromQuery(Name = "include_deprecated")] bool? includeDeprecated, - ApiReferenceService apiReference, - Cancel ctx - ) => ToResult(await apiReference.ListGroupsAsync(api, version, includeDeprecated ?? false, ctx)) - ); - _ = apis.MapGet( - "/{api}/operations", - async ( - string api, - [FromQuery(Name = "version")] string? version, - [FromQuery(Name = "group")] string? apiGroupName, - [FromQuery(Name = "q")] string? query, - [FromQuery(Name = "endpoint")] string? endpoint, - [FromQuery(Name = "include_deprecated")] bool? includeDeprecated, - [FromQuery(Name = "view")] string? view, - [FromQuery(Name = "include_body")] bool? includeBody, - [FromQuery(Name = "page")] int? pageNumber, - [FromQuery(Name = "size")] int? pageSize, - ApiReferenceService apiReference, - Cancel ctx - ) => ToResult( - await apiReference.QueryAsync( - new ApiOperationQuery - { - Api = api, - Version = version, - Group = apiGroupName, - Q = query, - Endpoint = endpoint, - IncludeDeprecated = includeDeprecated ?? false, - View = view, - IncludeBody = includeBody ?? false, - Page = pageNumber ?? 1, - Size = pageSize ?? 10 - }, - ctx + var apis = group.MapGroup("/apis").WithTags(ApiReferenceTag); + _ = apis + .MapGet( + "/", + async (ApiReferenceService apiReference, Cancel ctx) => ToResult(await apiReference.ListAsync(null, null, null, ctx)) + ) + .WithName("list-apis") + .WithSummary("List every API") + .Produces() + .ProducesErrors(); + _ = apis + .MapGet( + "/{api}", + async (string api, ApiReferenceService apiReference, Cancel ctx) => ToResult(await apiReference.GetApiAsync(api, ctx)) + ) + .WithName("get-api") + .WithSummary("Read one API") + .Produces() + .ProducesErrors(StatusCodes.Status404NotFound); + _ = apis + .MapGet( + "/{api}/groups", + async ( + string api, + [FromQuery(Name = "version")] string? version, + [FromQuery(Name = "include_deprecated")] bool? includeDeprecated, + ApiReferenceService apiReference, + Cancel ctx + ) => ToResult(await apiReference.ListGroupsAsync(api, version, includeDeprecated ?? false, ctx)) + ) + .WithName("list-api-groups") + .WithSummary("Count one API's operations by group") + .Produces() + .ProducesErrors(StatusCodes.Status400BadRequest, StatusCodes.Status404NotFound); + _ = apis + .MapGet( + "/{api}/operations", + async ( + string api, + [FromQuery(Name = "version")] string? version, + [FromQuery(Name = "group")] string? apiGroupName, + [FromQuery(Name = "q")] string? query, + [FromQuery(Name = "endpoint")] string? endpoint, + [FromQuery(Name = "include_deprecated")] bool? includeDeprecated, + [FromQuery(Name = "view")] string? view, + [FromQuery(Name = "include_body")] bool? includeBody, + [FromQuery(Name = "page")] int? pageNumber, + [FromQuery(Name = "size")] int? pageSize, + ApiReferenceService apiReference, + Cancel ctx + ) => ToResult( + await apiReference.QueryAsync( + new ApiOperationQuery + { + Api = api, + Version = version, + Group = apiGroupName, + Q = query, + Endpoint = endpoint, + IncludeDeprecated = includeDeprecated ?? false, + View = view, + IncludeBody = includeBody ?? false, + Page = pageNumber ?? 1, + Size = pageSize ?? 10 + }, + ctx + ) ) ) - ); - _ = apis.MapGet( - "/{api}/operations/{operationId}", - async ( - string api, - string operationId, - [FromQuery(Name = "version")] string? version, - [FromQuery(Name = "include_body")] bool? includeBody, - ApiReferenceService apiReference, - Cancel ctx - ) => ToResult(await apiReference.GetOperationAsync(api, operationId, version, includeBody ?? false, ctx)) - ); + .WithName("list-api-operations") + .WithSummary("Search, look up by endpoint, or list one API's operations") + .Produces() + .ProducesErrors(StatusCodes.Status400BadRequest, StatusCodes.Status404NotFound, StatusCodes.Status503ServiceUnavailable); + _ = apis + .MapGet( + "/{api}/operations/{operationId}", + async ( + string api, + string operationId, + [FromQuery(Name = "version")] string? version, + [FromQuery(Name = "include_body")] bool? includeBody, + ApiReferenceService apiReference, + Cancel ctx + ) => ToResult(await apiReference.GetOperationAsync(api, operationId, version, includeBody ?? false, ctx)) + ) + .WithName("get-api-operation") + .WithSummary("Read one operation of an API") + .Produces() + .ProducesErrors(StatusCodes.Status400BadRequest, StatusCodes.Status404NotFound); } private static IResult ToResult(ApiReferenceReply reply) => reply switch @@ -280,52 +340,95 @@ Cancel ctx ApiOperationResponse r => Results.Ok(r), ApiListResponse r => Results.Ok(r), ApiOperationListResponse r => Results.Ok(r), - ApiReferenceRejection r when r.ErrorType.EndsWith("_not_found", StringComparison.Ordinal) => Results.NotFound(r), - ApiReferenceRejection r => Results.BadRequest(r) + // The service names types in snake case for MCP; problem type fragments use kebab case. + ApiReferenceRejection r => + ApiProblems.Problem( + r.IsNotFound ? StatusCodes.Status404NotFound : StatusCodes.Status400BadRequest, + r.ErrorType.Replace('_', '-'), + r.Message + ) }; + private const string SearchTag = "Search"; + private const string AskAiTag = "Ask AI"; + private const string ChangesTag = "Changes"; + private const string FeedbackTag = "Page feedback"; + private const string ApiReferenceTag = "API reference"; + + private static IResult Invalid(string message) => + ApiProblems.Problem(StatusCodes.Status400BadRequest, ApiProblems.InvalidArguments, message); + + private static IResult FeedbackUnavailable() => + ApiProblems.Problem( + StatusCodes.Status503ServiceUnavailable, + ApiProblems.FeedbackUnavailable, + "The feedback could not be stored. Try again later." + ); + + /// Declares the error responses of an endpoint as problem details; any endpoint can fail with 500. + private static RouteHandlerBuilder ProducesErrors(this RouteHandlerBuilder builder, params int[] statusCodes) + { + foreach (var statusCode in statusCodes.Append(StatusCodes.Status500InternalServerError)) + _ = builder.ProducesProblem(statusCode); + return builder; + } + private static void MapPageFeedback(IEndpointRouteBuilder group) { - _ = group.MapPut("/page-feedback/{feedbackId:guid}", async ( - Guid feedbackId, - PageFeedbackRequest request, - HttpContext context, - IPageFeedbackService feedbackService, - ILogger logger, - Cancel ctx - ) => - { - if (!IsValidPageFeedback(request)) - return Results.BadRequest(); - - var record = PageFeedbackRecord.From(feedbackId, request, TryGetEuid(context)); - var pageUrlForLog = SanitizeForLog(request.PageUrl); - if (!await feedbackService.UpsertFeedbackAsync(record, ctx)) + _ = group + .MapPut("/page-feedback/{feedbackId:guid}", async ( + Guid feedbackId, + PageFeedbackRequest request, + HttpContext context, + IPageFeedbackService feedbackService, + ILogger logger, + Cancel ctx + ) => { - logger.LogWarning("Failed to record page feedback {FeedbackId} for {PageUrl}", feedbackId, pageUrlForLog); - return Results.StatusCode(StatusCodes.Status503ServiceUnavailable); - } - - logger.LogDebug("Recorded page feedback {FeedbackId} for {PageUrl}", feedbackId, pageUrlForLog); - return Results.NoContent(); - }).DisableAntiforgery(); - - _ = group.MapDelete("/page-feedback/{feedbackId:guid}", async ( - Guid feedbackId, - IPageFeedbackService feedbackService, - ILogger logger, - Cancel ctx - ) => - { - if (!await feedbackService.DeleteFeedbackAsync(feedbackId, ctx)) + if (!IsValidPageFeedback(request)) + return Invalid("The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment."); + + var record = PageFeedbackRecord.From(feedbackId, request, TryGetEuid(context)); + var pageUrlForLog = SanitizeForLog(request.PageUrl); + if (!await feedbackService.UpsertFeedbackAsync(record, ctx)) + { + logger.LogWarning("Failed to record page feedback {FeedbackId} for {PageUrl}", feedbackId, pageUrlForLog); + return FeedbackUnavailable(); + } + + logger.LogDebug("Recorded page feedback {FeedbackId} for {PageUrl}", feedbackId, pageUrlForLog); + return Results.NoContent(); + }) + .DisableAntiforgery() + .WithTags(FeedbackTag) + .WithName("put-page-feedback") + .WithSummary("Record or update feedback on a page") + .Produces(StatusCodes.Status204NoContent) + .ProducesErrors(StatusCodes.Status400BadRequest, StatusCodes.Status503ServiceUnavailable); + + _ = group + .MapDelete("/page-feedback/{feedbackId:guid}", async ( + Guid feedbackId, + IPageFeedbackService feedbackService, + ILogger logger, + Cancel ctx + ) => { - logger.LogWarning("Failed to delete page feedback {FeedbackId}", feedbackId); - return Results.StatusCode(StatusCodes.Status503ServiceUnavailable); - } - - logger.LogInformation("Deleted page feedback {FeedbackId}", feedbackId); - return Results.NoContent(); - }).DisableAntiforgery(); + if (!await feedbackService.DeleteFeedbackAsync(feedbackId, ctx)) + { + logger.LogWarning("Failed to delete page feedback {FeedbackId}", feedbackId); + return FeedbackUnavailable(); + } + + logger.LogInformation("Deleted page feedback {FeedbackId}", feedbackId); + return Results.NoContent(); + }) + .DisableAntiforgery() + .WithTags(FeedbackTag) + .WithName("delete-page-feedback") + .WithSummary("Delete feedback on a page") + .Produces(StatusCodes.Status204NoContent) + .ProducesErrors(StatusCodes.Status503ServiceUnavailable); } private static bool IsValidPageFeedback(PageFeedbackRequest request) => diff --git a/src/api/Elastic.Documentation.Api/Program.cs b/src/api/Elastic.Documentation.Api/Program.cs index 22348eac21..5fef579537 100644 --- a/src/api/Elastic.Documentation.Api/Program.cs +++ b/src/api/Elastic.Documentation.Api/Program.cs @@ -55,27 +55,17 @@ _ = app.Environment.IsDevelopment() ? app.UseDeveloperExceptionPage() - : app.UseExceptionHandler(err => err.Run(async context => + : app.UseExceptionHandler(new ExceptionHandlerOptions { - var ex = context.Features.Get()?.Error; - 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); - })); + // No handler: with AddProblemDetails the middleware writes the problem, typed by ApiProblems.Customize. + StatusCodeSelector = ApiProblems.StatusCodeFor, + // A parameter that does not bind is the client's mistake, not an error worth logging. + SuppressDiagnosticsCallback = context => context.Exception is BadHttpRequestException + }); + + // Some binding failures, such as a number that does not parse, end in an empty 400 instead of throwing; + // with AddProblemDetails, status code pages give every bodyless error a problem body like the rest. + _ = app.UseStatusCodePages(); var api = app.MapGroup(SystemEnvironmentVariables.Instance.ApiPrefix); @@ -85,6 +75,7 @@ var v1 = api.MapGroup("/v1"); v1.MapElasticDocsApiEndpoints(); + _ = v1.MapOpenApi("/openapi.json"); Console.WriteLine("API endpoints mapped"); Console.WriteLine("Application startup completed successfully"); diff --git a/src/api/Elastic.Documentation.Api/SerializationContext.cs b/src/api/Elastic.Documentation.Api/SerializationContext.cs index c238b75603..4760a9b8ea 100644 --- a/src/api/Elastic.Documentation.Api/SerializationContext.cs +++ b/src/api/Elastic.Documentation.Api/SerializationContext.cs @@ -18,9 +18,6 @@ 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))] @@ -49,7 +46,13 @@ public sealed record ApiError(string ErrorType, string Message); [JsonSerializable(typeof(Search.ApiReference.ApiOperationCollectionResponse))] [JsonSerializable(typeof(Search.ApiReference.ApiSummary))] [JsonSerializable(typeof(Search.ApiReference.ApiOperationListResponse))] -[JsonSerializable(typeof(Search.ApiReference.ApiReferenceRejection))] -[JsonSerializable(typeof(ApiError))] +// Route and query parameter types: the OpenAPI document describes them, and under Native AOT +// it can only describe types this context knows. +[JsonSerializable(typeof(string))] +[JsonSerializable(typeof(string[]))] +[JsonSerializable(typeof(bool?))] +[JsonSerializable(typeof(int?))] +[JsonSerializable(typeof(Guid))] +[JsonSerializable(typeof(DateTimeOffset))] [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 4f9b2b00bd..7d29a728b1 100644 --- a/src/api/Elastic.Documentation.Api/ServicesExtension.cs +++ b/src/api/Elastic.Documentation.Api/ServicesExtension.cs @@ -15,9 +15,12 @@ using Elastic.Documentation.Search; using Elastic.Ingest.Elasticsearch; using Elastic.Transport; +using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NetEscapades.EnumGenerators; +using OpenApiInfo = Microsoft.OpenApi.OpenApiInfo; +using OpenApiServer = Microsoft.OpenApi.OpenApiServer; namespace Elastic.Documentation.Api; @@ -59,6 +62,21 @@ private static void AddElasticDocsApiServices(this IServiceCollection services, { options.SerializerOptions.TypeInfoResolverChain.Insert(0, ApiJsonContext.Default); }); + // Every error answers RFC 9457 problem details; binding failures throw, so they get a precise detail. + _ = services.AddProblemDetails(options => options.CustomizeProblemDetails = ApiProblems.Customize); + _ = services.Configure(options => options.ThrowOnBadRequest = true); + _ = services.AddOpenApi(options => options.AddDocumentTransformer((document, _, _) => + { + document.Info = new OpenApiInfo + { + Title = "Elastic Docs API", + Version = "v1", + Description = "Search, Ask AI, change feeds, feedback and the API reference behind elastic.co/docs. " + + "Requests through www.elastic.co need the cookie feature_search_or_askai_enabled=true; without it the CDN answers 403." + }; + document.Servers = [new OpenApiServer { Url = "https://www.elastic.co" }]; + return Task.CompletedTask; + })); // Register AppEnvironment as a singleton for dependency injection _ = services.AddSingleton(new AppEnvironment { Current = appEnv }); diff --git a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs index 15bcb005c1..3cd90a0b48 100644 --- a/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs +++ b/src/services/search/Elastic.Documentation.Search/ApiReference/ApiReferenceService.cs @@ -15,8 +15,18 @@ public readonly union ApiReferenceReply( ApiReferenceRejection ); -/// A call the API reference cannot answer. ends in _not_found when nothing matched. -public sealed record ApiReferenceRejection(string ErrorType, string Message); +/// A call the API reference cannot answer: invalid arguments, or nothing to answer with. +public sealed record ApiReferenceRejection(string ErrorType, string Message) +{ + /// Nothing matched, as opposed to arguments that can never match. + public bool IsNotFound { get; private init; } + + /// Arguments that can never match, whatever the index holds. + public static ApiReferenceRejection Invalid(string message) => new("invalid_arguments", message); + + /// Valid arguments that nothing in the index matches. + public static ApiReferenceRejection NotFound(string errorType, string message) => new(errorType, message) { IsNotFound = true }; +} /// Searches, reads and lists the operations of the REST API reference. The MCP tools and the docs API share it. public class ApiReferenceService(IApiGateway apiGateway) @@ -26,8 +36,7 @@ public class ApiReferenceService(IApiGateway apiGateway) public const int MaxPageSize = 50; private const string UngroupedName = "Other"; - private static readonly ApiReferenceRejection VersionNeedsApi = new( - "invalid_arguments", + private static readonly ApiReferenceRejection VersionNeedsApi = ApiReferenceRejection.Invalid( "version needs api: pass the API key the version belongs to." ); @@ -68,11 +77,11 @@ CancellationToken ct if (VersionWithoutApi(api, version)) return VersionNeedsApi; if (ToOperationKey(operationId, endpoint) is not { } key) - return new ApiReferenceRejection("invalid_arguments", "Pass exactly one of an operation id or an endpoint."); + return ApiReferenceRejection.Invalid("Pass exactly one of an operation id or an endpoint."); var detail = await apiGateway.GetOperationAsync(new ApiOperationLookup(ToScope(api, version), key), ct); if (detail is null) - return new ApiReferenceRejection( + return ApiReferenceRejection.NotFound( "operation_not_found", $"No API operation matches {operationId ?? endpoint}{(api is null ? "" : $" in {api}")}." ); @@ -96,19 +105,19 @@ public async Task QueryAsync(ApiOperationQuery query, Cancell { // Every lookup is inside one API, so an operation id or a route can never match in two of them. if (ToScope(query.Api, query.Version) is not { } scope) - return new ApiReferenceRejection("invalid_arguments", "Pass an API key, such as 'elasticsearch'."); + return ApiReferenceRejection.Invalid("Pass an API key, such as 'elasticsearch'."); var hasQuery = !string.IsNullOrWhiteSpace(query.Q); var hasEndpoint = !string.IsNullOrWhiteSpace(query.Endpoint); if (hasQuery && hasEndpoint) - return new ApiReferenceRejection("invalid_arguments", "Pass q or endpoint, not both."); + return ApiReferenceRejection.Invalid("Pass q or endpoint, not both."); if (query.View is not (null or "basic" or "full")) - return new ApiReferenceRejection("invalid_arguments", "view is 'basic' or 'full'."); + return ApiReferenceRejection.Invalid("view is 'basic' or 'full'."); if (query.Full && !hasEndpoint) - return new ApiReferenceRejection("invalid_arguments", "view=full needs endpoint."); + return ApiReferenceRejection.Invalid("view=full needs endpoint."); if (query.IncludeBody && !query.Full) - return new ApiReferenceRejection("invalid_arguments", "include_body needs view=full."); + return ApiReferenceRejection.Invalid("include_body needs view=full."); if (!string.IsNullOrWhiteSpace(query.Group) && (hasQuery || hasEndpoint)) - return new ApiReferenceRejection("invalid_arguments", "group filters a listing; pass it without q or endpoint."); + return ApiReferenceRejection.Invalid("group filters a listing; pass it without q or endpoint."); var page = Math.Max(1, query.Page); var size = Math.Clamp(query.Size, 1, MaxPageSize); @@ -154,7 +163,7 @@ .. hits.Hits.Select( var group = query.Group.Trim(); listed = listed.Where(o => string.Equals(o.Group ?? UngroupedName, group, StringComparison.OrdinalIgnoreCase)).ToList(); if (!listed.Any()) - return new ApiReferenceRejection("group_not_found", $"API '{scope.Key}' has no group '{group}'."); + return ApiReferenceRejection.NotFound("group_not_found", $"API '{scope.Key}' has no group '{group}'."); } var sorted = listed.OrderBy(o => o.Path, StringComparer.Ordinal).ThenBy(o => o.Method, StringComparer.Ordinal).ToList(); return new ApiOperationCollectionResponse @@ -173,9 +182,7 @@ public Task GetOperationAsync( CancellationToken ct ) => string.IsNullOrWhiteSpace(api) - ? Task.FromResult( - new ApiReferenceRejection("invalid_arguments", "Pass an API key, such as 'elasticsearch'.") - ) + ? Task.FromResult(ApiReferenceRejection.Invalid("Pass an API key, such as 'elasticsearch'.")) : GetAsync(api, operationId, null, version, includeBody, ct); /// Reads one API by its key. @@ -183,7 +190,9 @@ public async Task GetApiAsync(string api, CancellationToken c { var apis = await apiGateway.ListApisAsync(ct); var key = api.Trim().ToLowerInvariant(); - return apis.FirstOrDefault(a => a.Key == key) is { } found ? found : new ApiReferenceRejection("api_not_found", $"No API '{api}'."); + return apis.FirstOrDefault(a => a.Key == key) is { } found + ? found + : ApiReferenceRejection.NotFound("api_not_found", $"No API '{api}'."); } /// @@ -193,7 +202,7 @@ public async Task GetApiAsync(string api, CancellationToken c public async Task ListGroupsAsync(string api, string? version, bool includeDeprecated, CancellationToken ct) { if (ToScope(api, version) is not { } scope) - return new ApiReferenceRejection("invalid_arguments", "Pass an API key, such as 'elasticsearch'."); + return ApiReferenceRejection.Invalid("Pass an API key, such as 'elasticsearch'."); var operations = await apiGateway.ListOperationsAsync(scope, ct); return operations.Count == 0 ? ApiNotFound(scope) @@ -213,7 +222,10 @@ public async Task ListAsync(string? api, string? version, str } private static ApiReferenceRejection ApiNotFound(ApiScope scope) => - new("api_not_found", $"No operations found for API '{scope.Key}'{(scope.Version is null ? "" : $" version '{scope.Version}'")}."); + ApiReferenceRejection.NotFound( + "api_not_found", + $"No operations found for API '{scope.Key}'{(scope.Version is null ? "" : $" version '{scope.Version}'")}." + ); private static ApiOperationItem ToItem(ApiOperationSummary operation, ApiOperationDetail? detail, bool includeBody) => new() { Operation = operation, Versions = detail?.Versions, Fields = detail?.Fields, Body = includeBody ? detail?.Body : null }; @@ -233,7 +245,7 @@ internal static ApiReferenceReply GroupOperations( { groups = [.. groups.Where(g => string.Equals(g.Key, group.Trim(), StringComparison.OrdinalIgnoreCase))]; if (groups.Count == 0) - return new ApiReferenceRejection( + return ApiReferenceRejection.NotFound( "group_not_found", $"API '{scope.Key}' has no group '{group}'. List the API without group to see its groups." ); diff --git a/src/services/search/Elastic.Documentation.Search/ChangesService.cs b/src/services/search/Elastic.Documentation.Search/ChangesService.cs index 394688ee99..972313ef08 100644 --- a/src/services/search/Elastic.Documentation.Search/ChangesService.cs +++ b/src/services/search/Elastic.Documentation.Search/ChangesService.cs @@ -157,6 +157,9 @@ private static ChangesResult BuildResult(EsSearchResponse response, int pageSize return new ChangesResult { Pages = pages, NextCursor = nextCursor }; } + /// Whether is a nextCursor this service returned, so a caller can reject one it did not. + public static bool IsValidCursor(string cursor) => DecodeCursor(cursor) is not null; + private static ChangesPageCursor? DecodeCursor(string? cursor) { if (string.IsNullOrWhiteSpace(cursor)) diff --git a/tests/Elastic.Documentation.Api.Tests/.snapshots/http/page-feedback-validation.verified.responses b/tests/Elastic.Documentation.Api.Tests/.snapshots/http/page-feedback-validation.verified.responses index 47128444c6..d06a627a08 100644 --- a/tests/Elastic.Documentation.Api.Tests/.snapshots/http/page-feedback-validation.verified.responses +++ b/tests/Elastic.Documentation.Api.Tests/.snapshots/http/page-feedback-validation.verified.responses @@ -3,108 +3,360 @@ status: 204 No Content ## missing page url: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## empty page url: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## blank page url: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## page url without a leading slash: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## page url that is protocol relative: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## page url that is absolute: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## page url over 2048 characters: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## page url of exactly 2048 characters: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 204 No Content ## page url null: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## page url a number: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "Failed to read parameter \"PageFeedbackRequest request\" from the request body as JSON.", + "traceId": "{trace-id}" +} ## missing page title: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## blank page title: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## page title over 500 characters: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## page title of exactly 500 characters: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 204 No Content ## missing reaction: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## unspecified reaction: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## unknown reaction: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "Failed to read parameter \"PageFeedbackRequest request\" from the request body as JSON.", + "traceId": "{trace-id}" +} ## reaction in upper case: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "Failed to read parameter \"PageFeedbackRequest request\" from the request body as JSON.", + "traceId": "{trace-id}" +} ## reaction as a number: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 204 No Content ## comment without reasons: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## comment over 2000 characters: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## comment of exactly 2000 characters: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 204 No Content ## reasons without a set version: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## reasons with set version zero: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## reasons with negative set version: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## set version without reasons: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## empty reasons with a set version: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## empty reasons alone: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 204 No Content ## reason that does not exist: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "Failed to read parameter \"PageFeedbackRequest request\" from the request body as JSON.", + "traceId": "{trace-id}" +} ## reason that belongs to the other reaction: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## thumbs down with a matching reason: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 204 No Content ## thumbs down with a thumbs up reason: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## another reason on thumbs down: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 204 No Content ## unspecified reason: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "Failed to read parameter \"PageFeedbackRequest request\" from the request body as JSON.", + "traceId": "{trace-id}" +} ## reasons null items: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "Failed to read parameter \"PageFeedbackRequest request\" from the request body as JSON.", + "traceId": "{trace-id}" +} ## duplicate reasons: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 204 No Content @@ -114,33 +366,129 @@ status: 204 No Content ## empty object: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## json null: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "Implicit body inferred for parameter \"request\" but no body was provided. Did you mean to use a Service instead?", + "traceId": "{trace-id}" +} ## body is a json array: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "Failed to read parameter \"PageFeedbackRequest request\" from the request body as JSON.", + "traceId": "{trace-id}" +} ## body is not json: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "Failed to read parameter \"PageFeedbackRequest request\" from the request body as JSON.", + "traceId": "{trace-id}" +} ## empty body: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "Implicit body inferred for parameter \"request\" but no body was provided. Did you mean to use a Service instead?", + "traceId": "{trace-id}" +} ## truncated json: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "Failed to read parameter \"PageFeedbackRequest request\" from the request body as JSON.", + "traceId": "{trace-id}" +} ## wrong content type: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 415 Unsupported Media Type +content-type: application/problem+json + +{ + "type": "https://tools.ietf.org/html/rfc9110#section-15.5.16", + "title": "Unsupported Media Type", + "status": 415, + "traceId": "{trace-id}" +} ## feedback id that is not a guid: PUT /docs/_api/v1/page-feedback/not-a-guid status: 404 Not Found +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#not-found", + "title": "Not found", + "status": 404, + "detail": "No endpoint matches this path.", + "traceId": "{trace-id}" +} ## unsupported method: POST /docs/_api/v1/page-feedback/{{$guid}} status: 405 Method Not Allowed +content-type: application/problem+json + +{ + "type": "https://tools.ietf.org/html/rfc9110#section-15.5.6", + "title": "Method Not Allowed", + "status": 405, + "traceId": "{trace-id}" +} ## delete with an id that is not a guid: DELETE /docs/_api/v1/page-feedback/not-a-guid status: 404 Not Found +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#not-found", + "title": "Not found", + "status": 404, + "detail": "No endpoint matches this path.", + "traceId": "{trace-id}" +} ## get is not mapped: GET /docs/_api/v1/page-feedback/{{$guid}} status: 405 Method Not Allowed +content-type: application/problem+json + +{ + "type": "https://tools.ietf.org/html/rfc9110#section-15.5.6", + "title": "Method Not Allowed", + "status": 405, + "traceId": "{trace-id}" +} diff --git a/tests/Elastic.Documentation.Api.Tests/.snapshots/http/page-feedback.verified.responses b/tests/Elastic.Documentation.Api.Tests/.snapshots/http/page-feedback.verified.responses index cca2e1993d..27ccfd33e5 100644 --- a/tests/Elastic.Documentation.Api.Tests/.snapshots/http/page-feedback.verified.responses +++ b/tests/Elastic.Documentation.Api.Tests/.snapshots/http/page-feedback.verified.responses @@ -3,6 +3,15 @@ status: 204 No Content ## a thumbs down needs a reason: PUT /docs/_api/v1/page-feedback/{{$guid}} status: 400 Bad Request +content-type: application/problem+json + +{ + "type": "https://docs-v3-preview.elastic.dev/elastic/docs-builder/tree/main/data/api#invalid-arguments", + "title": "Invalid arguments", + "status": 400, + "detail": "The page feedback is invalid. Check pageUrl, pageTitle, reaction, reasons and comment.", + "traceId": "{trace-id}" +} ## feedback is deleted: DELETE /docs/_api/v1/page-feedback/{{$guid}} status: 204 No Content diff --git a/tests/Elastic.Documentation.Api.Tests/ApiErrorResponseTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiErrorResponseTests.cs index dd011c1985..1b755e36af 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiErrorResponseTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiErrorResponseTests.cs @@ -19,6 +19,7 @@ public class ApiErrorResponseTests { private static readonly SwappableService Search = new(); private static readonly SwappableService Feedback = new(); + private static readonly SwappableService Changes = new(); private static readonly Lazy SharedFactory = new(() => ApiWebApplicationFactory.WithMockedServices(replacements => { @@ -53,14 +54,17 @@ public async Task Search_BackendUnavailable_IsARetryable503() using (response) { response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + response.Content.Headers.ContentType!.MediaType.Should().Be("application/problem+json"); response.Headers.RetryAfter!.Delta.Should().Be(TimeSpan.FromSeconds(5)); - body.GetProperty("errorType").GetString().Should().Be("search_unavailable"); - body.GetProperty("message").GetString().Should().Contain("MaxTimeoutReached"); + body.GetProperty("status").GetInt32().Should().Be(503); + body.GetProperty("title").GetString().Should().Be("Search unavailable"); + body.GetProperty("type").GetString().Should().Be(ApiProblems.TypeUri("search-unavailable")); + body.GetProperty("detail").GetString().Should().Contain("MaxTimeoutReached"); } } [Test] - public async Task Search_UnexpectedFailure_IsA500WithABodyThatHidesTheException() + public async Task Search_UnexpectedFailure_IsA500ProblemThatHidesTheException() { var (response, body) = await SearchThrowing(new InvalidOperationException("secret detail")); @@ -68,8 +72,8 @@ public async Task Search_UnexpectedFailure_IsA500WithABodyThatHidesTheException( { 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"); + body.GetProperty("type").GetString().Should().Be(ApiProblems.TypeUri("internal-error")); + body.GetProperty("detail").GetString().Should().NotContain("secret detail"); } } @@ -92,5 +96,45 @@ public async Task MessageFeedback_ReportsWhetherTheFeedbackWasStored(bool stored response.StatusCode.Should().Be(expected); A.CallTo(() => feedback.RecordFeedbackAsync(A._, A._)).MustHaveHappenedOnceExactly(); + if (!stored) + JsonElement + .Parse(await response.Content.ReadAsStringAsync(Ct)) + .GetProperty("type") + .GetString() + .Should() + .Be(ApiProblems.TypeUri("feedback-unavailable")); + } + + private static async Task<(HttpStatusCode Status, JsonElement Body)> Get(string pathAndQuery) + { + Search.Current = A.Fake(); + Changes.Current = A.Fake(); + using var client = SharedFactory.Value.CreateClient(); + using var response = await client.GetAsync($"/docs/_api/v1{pathAndQuery}", Ct); + return (response.StatusCode, JsonElement.Parse(await response.Content.ReadAsStringAsync(Ct))); + } + + [Test] + [Arguments("/search")] + [Arguments("/search?q=x&size=many")] + [Arguments("/changes?since=yesterday")] + [Arguments("/changes")] + public async Task ParameterThatDoesNotBind_IsA400Problem(string pathAndQuery) + { + var (status, body) = await Get(pathAndQuery); + + status.Should().Be(HttpStatusCode.BadRequest); + body.GetProperty("type").GetString().Should().Be(ApiProblems.TypeUri("invalid-arguments")); + body.GetProperty("detail").GetString().Should().NotBeNullOrWhiteSpace(); + } + + [Test] + public async Task Changes_CursorItDidNotReturn_IsA400InsteadOfTheFirstPage() + { + var (status, body) = await Get("/changes?since=2026-01-01T00:00:00Z&cursor=not-a-cursor"); + + status.Should().Be(HttpStatusCode.BadRequest); + body.GetProperty("detail").GetString().Should().Be("cursor is not a nextCursor that /changes returned."); + A.CallTo(Changes.Current).MustNotHaveHappened(); } } diff --git a/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs b/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs index 1e4dc73794..4e84abc02c 100644 --- a/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/ApiOperationsEndpointTests.cs @@ -106,8 +106,8 @@ public async Task InvalidArguments_AreABadRequestWithoutQueryingTheIndex(string var (status, body) = await Get(gateway, pathAndQuery); status.Should().Be(HttpStatusCode.BadRequest); - body.GetProperty("errorType").GetString().Should().Be("invalid_arguments"); - body.GetProperty("message").GetString().Should().Be(message); + body.GetProperty("type").GetString().Should().Be(ApiProblems.TypeUri("invalid-arguments")); + body.GetProperty("detail").GetString().Should().Be(message); A.CallTo(gateway).MustNotHaveHappened(); } @@ -180,9 +180,9 @@ public async Task Listing_FiltersByGroupHidesDeprecatedSortsByPathAndPages() } [Test] - [Arguments("/apis/nope/operations", "api_not_found")] - [Arguments("/apis/elasticsearch/operations?group=nope", "group_not_found")] - [Arguments("/apis/nope/groups", "api_not_found")] + [Arguments("/apis/nope/operations", "api-not-found")] + [Arguments("/apis/elasticsearch/operations?group=nope", "group-not-found")] + [Arguments("/apis/nope/groups", "api-not-found")] public async Task Listing_UnknownApiOrGroup_IsNotFound(string pathAndQuery, string errorType) { var gateway = A.Fake(); @@ -193,7 +193,7 @@ public async Task Listing_UnknownApiOrGroup_IsNotFound(string pathAndQuery, stri var (status, body) = await Get(gateway, pathAndQuery); status.Should().Be(HttpStatusCode.NotFound); - body.GetProperty("errorType").GetString().Should().Be(errorType); + body.GetProperty("type").GetString().Should().Be(ApiProblems.TypeUri(errorType)); } [Test] @@ -232,8 +232,8 @@ public async Task Operation_UnknownId_IsNotFound() var (status, body) = await Get(gateway, "/apis/elasticsearch/operations/nope"); status.Should().Be(HttpStatusCode.NotFound); - body.GetProperty("errorType").GetString().Should().Be("operation_not_found"); - body.GetProperty("message").GetString().Should().Be("No API operation matches nope in elasticsearch."); + body.GetProperty("type").GetString().Should().Be(ApiProblems.TypeUri("operation-not-found")); + body.GetProperty("detail").GetString().Should().Be("No API operation matches nope in elasticsearch."); } private static readonly ApiSummary Elasticsearch = new() @@ -259,7 +259,7 @@ public async Task Apis_ListsEveryApiAndReadsOneByKey() oneStatus.Should().Be(HttpStatusCode.OK); one.GetProperty("title").GetString().Should().Be("Elasticsearch API"); missingStatus.Should().Be(HttpStatusCode.NotFound); - missing.GetProperty("errorType").GetString().Should().Be("api_not_found"); + missing.GetProperty("type").GetString().Should().Be(ApiProblems.TypeUri("api-not-found")); } [Test] diff --git a/tests/Elastic.Documentation.Api.Tests/Fixtures/ApiWebApplicationFactory.cs b/tests/Elastic.Documentation.Api.Tests/Fixtures/ApiWebApplicationFactory.cs index ca3d5afa9f..284aac2e78 100644 --- a/tests/Elastic.Documentation.Api.Tests/Fixtures/ApiWebApplicationFactory.cs +++ b/tests/Elastic.Documentation.Api.Tests/Fixtures/ApiWebApplicationFactory.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information using System.Diagnostics; +using System.Text.Json.Serialization.Metadata; using Elastic.Documentation.Api; using Elastic.Documentation.Api.OpenTelemetry; using Elastic.Documentation.ServiceDefaults; @@ -99,6 +100,15 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) _ = logging.AddInMemoryExporter(ExportedLogRecords); }); + // The API publishes with Native AOT, where its JSON options have no reflection fallback. + // Drop the fallback here too, so a type missing from ApiJsonContext fails a test instead of production. + _ = services.PostConfigure(options => + { + var reflection = options.SerializerOptions.TypeInfoResolverChain.OfType().ToList(); + foreach (var resolver in reflection) + _ = options.SerializerOptions.TypeInfoResolverChain.Remove(resolver); + }); + // Apply test-specific service replacements (if any) _configureServices?.Invoke(services); }); diff --git a/tests/Elastic.Documentation.Api.Tests/NavigationSearchEndpointTests.cs b/tests/Elastic.Documentation.Api.Tests/NavigationSearchEndpointTests.cs index c8a910c2e7..b4f0422eba 100644 --- a/tests/Elastic.Documentation.Api.Tests/NavigationSearchEndpointTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/NavigationSearchEndpointTests.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information using System.Net; +using System.Text.Json; using AwesomeAssertions; using Elastic.Documentation.Api.Tests.Fixtures; using Elastic.Documentation.Search; @@ -30,7 +31,7 @@ public static void DisposeSharedFactory() SharedFactory.Value.Dispose(); } - private static async Task<(HttpStatusCode Status, NavigationSearchRequest? Received)> Get(string queryString) + private static async Task<(HttpStatusCode Status, NavigationSearchRequest? Received, string Body)> Get(string queryString) { NavigationSearchRequest? received = null; var service = A.Fake(); @@ -45,13 +46,13 @@ public static void DisposeSharedFactory() $"/docs/_api/v1/navigation-search/?q=knn&type=api{queryString}", TestContext.Current!.Execution.CancellationToken ); - return (response.StatusCode, received); + return (response.StatusCode, received, await response.Content.ReadAsStringAsync(TestContext.Current!.Execution.CancellationToken)); } [Test] public async Task Get_NoTreeParameters_SearchesWithoutScope() { - var (status, received) = await Get(""); + var (status, received, _) = await Get(""); status.Should().Be(HttpStatusCode.OK); received.Should().NotBeNull(); @@ -61,7 +62,7 @@ public async Task Get_NoTreeParameters_SearchesWithoutScope() [Test] public async Task Get_KeyAlone_SearchesFromThatApiWithoutScope() { - var (status, received) = await Get("&api_key=elasticsearch"); + var (status, received, _) = await Get("&api_key=elasticsearch"); status.Should().Be(HttpStatusCode.OK); received.Should().NotBeNull(); @@ -73,7 +74,7 @@ public async Task Get_KeyAlone_SearchesFromThatApiWithoutScope() [Arguments("8")] public async Task Get_KeyAndTree_SearchesInThatTree(string tree) { - var (status, received) = await Get($"&api_key=elasticsearch&api_tree={tree}"); + var (status, received, _) = await Get($"&api_key=elasticsearch&api_tree={tree}"); status.Should().Be(HttpStatusCode.OK); received.Should().NotBeNull(); @@ -90,9 +91,10 @@ public async Task Get_KeyAndTree_SearchesInThatTree(string tree) [Arguments("&api_key=&api_tree=8")] public async Task Get_IncompleteOrMalformedScope_ReturnsBadRequestWithoutSearching(string queryString) { - var (status, received) = await Get(queryString); + var (status, received, body) = await Get(queryString); status.Should().Be(HttpStatusCode.BadRequest); received.Should().BeNull(); + JsonElement.Parse(body).GetProperty("type").GetString().Should().Be(ApiProblems.TypeUri("invalid-arguments")); } } diff --git a/tests/Elastic.Documentation.Api.Tests/OpenApiDocumentTests.cs b/tests/Elastic.Documentation.Api.Tests/OpenApiDocumentTests.cs new file mode 100644 index 0000000000..3cc492a413 --- /dev/null +++ b/tests/Elastic.Documentation.Api.Tests/OpenApiDocumentTests.cs @@ -0,0 +1,126 @@ +// 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.Text.Json; +using AwesomeAssertions; +using Elastic.Documentation.Api.Tests.Fixtures; + +namespace Elastic.Documentation.Api.Tests; + +public class OpenApiDocumentTests +{ + private static readonly Lazy SharedFactory = new(() => new ApiWebApplicationFactory()); + + [After(Class)] + public static void DisposeSharedFactory() + { + if (SharedFactory.IsValueCreated) + SharedFactory.Value.Dispose(); + } + + private static async Task Document() + { + using var client = SharedFactory.Value.CreateClient(); + using var response = await client.GetAsync("/docs/_api/v1/openapi.json", TestContext.Current!.Execution.CancellationToken); + response.StatusCode.Should().Be(HttpStatusCode.OK); + return JsonElement.Parse(await response.Content.ReadAsStringAsync(TestContext.Current!.Execution.CancellationToken)); + } + + [Test] + public async Task Document_DescribesEveryEndpointWithItsStatusCodes() + { + var document = await Document(); + + var operations = document + .GetProperty("paths") + .EnumerateObject() + .SelectMany( + path => path + .Value + .EnumerateObject() + .Where(op => op.Name is "get" or "post" or "put" or "delete") + .Select( + op => + $"{op.Name.ToUpperInvariant()} {path.Name} {string.Join(",", op.Value.GetProperty("responses").EnumerateObject().Select(r => r.Name).Order())}" + ) + ) + .Order() + .ToList(); + + operations.Should().Equal( + "DELETE /docs/_api/v1/page-feedback/{feedbackId} 204,500,503", + "GET /docs/_api/v1/apis 200,500", + "GET /docs/_api/v1/apis/{api} 200,404,500", + "GET /docs/_api/v1/apis/{api}/groups 200,400,404,500", + "GET /docs/_api/v1/apis/{api}/operations 200,400,404,500,503", + "GET /docs/_api/v1/apis/{api}/operations/{operationId} 200,400,404,500", + "GET /docs/_api/v1/changes 200,400,500,503", + "GET /docs/_api/v1/navigation-search 200,400,500,503", + "GET /docs/_api/v1/search 200,400,500,503", + "POST /docs/_api/v1/ask-ai/message-feedback 204,400,500,503", + "POST /docs/_api/v1/ask-ai/stream 200,400,500", + "PUT /docs/_api/v1/page-feedback/{feedbackId} 204,400,500,503" + ); + } + + [Test] + public async Task Document_NamesEveryOperationOnce() + { + var document = await Document(); + + var ids = document + .GetProperty("paths") + .EnumerateObject() + .SelectMany(path => path.Value.EnumerateObject().Where(op => op.Name is "get" or "post" or "put" or "delete")) + .Select(op => op.Value.TryGetProperty("operationId", out var id) ? id.GetString() : null) + .ToList(); + + // API Explorer turns these into page slugs and the api-operations ids, such as docs-api:search. + ids.Should().NotContainNulls().And.OnlyHaveUniqueItems().And.HaveCount(12); + ids.Should().Contain(["search", "get-api-operation", "list-api-operations"]); + } + + [Test] + public async Task Document_DescribesEveryErrorAsProblemDetails() + { + var document = await Document(); + + var errorContent = document + .GetProperty("paths") + .EnumerateObject() + .SelectMany(path => path.Value.EnumerateObject().Where(op => op.Name is "get" or "post" or "put" or "delete")) + .SelectMany(op => op.Value.GetProperty("responses").EnumerateObject().Where(r => r.Name[0] is '4' or '5')) + .SelectMany( + r => r + .Value + .GetProperty("content") + .EnumerateObject() + .Select(c => $"{c.Name} {c.Value.GetProperty("schema").GetProperty("$ref").GetString()}") + ) + .Distinct() + .ToList(); + + errorContent.Should().Equal("application/problem+json #/components/schemas/ProblemDetails"); + document + .GetProperty("components") + .GetProperty("schemas") + .GetProperty("ProblemDetails") + .GetProperty("properties") + .EnumerateObject() + .Select(p => p.Name) + .Should() + .Contain(["type", "title", "status", "detail", "instance"]); + } + + [Test] + public async Task Document_NamesTheApiAndThePublicServer() + { + var document = await Document(); + + document.GetProperty("info").GetProperty("title").GetString().Should().Be("Elastic Docs API"); + document.GetProperty("info").GetProperty("description").GetString().Should().Contain("feature_search_or_askai_enabled=true"); + document.GetProperty("servers")[0].GetProperty("url").GetString().Should().Be("https://www.elastic.co"); + } +} diff --git a/tests/Elastic.Documentation.Api.Tests/PageFeedbackEndpointTests.cs b/tests/Elastic.Documentation.Api.Tests/PageFeedbackEndpointTests.cs index 49fac90dd2..90c54e5c41 100644 --- a/tests/Elastic.Documentation.Api.Tests/PageFeedbackEndpointTests.cs +++ b/tests/Elastic.Documentation.Api.Tests/PageFeedbackEndpointTests.cs @@ -4,6 +4,8 @@ using System.Net; using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; using AwesomeAssertions; using Elastic.Documentation.Api.PageFeedback; using Elastic.Documentation.Api.Tests.Fixtures; @@ -17,7 +19,7 @@ namespace Elastic.Documentation.Api.Tests; // The tests share one host and install their own feedback service on it, so they run one after another. [NotInParallel(nameof(PageFeedbackEndpointTests))] -public class PageFeedbackEndpointTests +public partial class PageFeedbackEndpointTests { private static readonly SwappableService FeedbackService = new(); @@ -35,6 +37,9 @@ public static void DisposeSharedFactory() } // The id is replaced by its own text, so a record stored under another id than the request's fails the snapshot. + [GeneratedRegex("\"traceId\": \"[^\"]+\"")] + private static partial Regex TraceId(); + private static SnapshotOptions ScrubFeedbackId(Guid feedbackId) => new SnapshotOptions().Scrub(text => text.Replace(feedbackId.ToString(), "{feedback-id}", StringComparison.OrdinalIgnoreCase)); @@ -58,6 +63,8 @@ public async Task Run(SnapshotFile file) await HttpFileTest.RunAsync( file, new HttpFileSnapshotOptions { Client = client }, + // Every problem carries the request's trace id, which differs on each run. + new SnapshotOptions().Scrub(text => TraceId().Replace(text, "\"traceId\": \"{trace-id}\"")), cancellationToken: TestContext.Current!.Execution.CancellationToken ); } @@ -210,6 +217,8 @@ public async Task Put_CommentExceedsLimit_ReturnsBadRequest() response.StatusCode.Should().Be(HttpStatusCode.BadRequest); A.CallTo(() => feedbackService.UpsertFeedbackAsync(A._, A._)).MustNotHaveHappened(); + var body = JsonElement.Parse(await response.Content.ReadAsStringAsync(TestContext.Current!.Execution.CancellationToken)); + body.GetProperty("type").GetString().Should().Be(ApiProblems.TypeUri("invalid-arguments")); } [Test] @@ -262,6 +271,8 @@ public async Task Put_InvalidFeedback_ReturnsBadRequest(string payload) response.StatusCode.Should().Be(HttpStatusCode.BadRequest); A.CallTo(() => feedbackService.UpsertFeedbackAsync(A._, A._)).MustNotHaveHappened(); + var body = JsonElement.Parse(await response.Content.ReadAsStringAsync(TestContext.Current!.Execution.CancellationToken)); + body.GetProperty("type").GetString().Should().Be(ApiProblems.TypeUri("invalid-arguments")); } [Test] @@ -277,6 +288,8 @@ public async Task Put_PersistenceFails_ReturnsServiceUnavailable() using var response = await client.SendAsync(request, TestContext.Current!.Execution.CancellationToken); response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); + var body = JsonElement.Parse(await response.Content.ReadAsStringAsync(TestContext.Current!.Execution.CancellationToken)); + body.GetProperty("type").GetString().Should().Be(ApiProblems.TypeUri("feedback-unavailable")); } [Test]