Repository navigation
Publish an OpenAPI document for the docs API and answer errors as RFC 9457 problems - #4896
Conversation
Docs preview (local build)Handbook preview: https://docs-v3-preview.elastic.dev/elastic/docs-builder/pull/4896/ Sample changed pages: |
The copy follows #4896, where every error is now an RFC 9457 problem. Co-Authored-By: Claude Opus 5.5 <[email protected]>
3c8c1a7 to
52977d7
Compare
The copy follows #4896, where every error is now an RFC 9457 problem. Co-Authored-By: Claude Opus 5.5 <[email protected]>
52977d7 to
4b45de0
Compare
The copy follows #4896, where every error is now an RFC 9457 problem. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1c780b3 to
6be5357
Compare
| ### 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). |
There was a problem hiding this comment.
Severity: P3 (Low)
The page now has two headings called "Errors": this ### Errors and the new ## Errors further down. [Errors](#errors) will resolve to the first one, which is this subsection, so the link points back to itself instead of to the problem-type reference. Give the new section a custom anchor (for example ## Errors [problems]) and link to that.
Generated by Libra. Specialist: libra-complexity. React with 👍 or 👎 to give feedback on this comment.
| .WithName("list-apis") | ||
| .WithSummary("List every API") | ||
| .Produces<ApiListResponse>() | ||
| .ProducesErrors(); |
There was a problem hiding this comment.
Severity: P3 (Low)
Declare 503 for the other API-reference endpoints too. Listing APIs, reading an API, listing groups, and reading an operation all reach ApiGateway.Search, which throws SearchUnavailableException on timeout or overload. The middleware returns a retryable 503, but these operations omit it from the new OpenAPI contract; only the operations collection declares it. Add 503 to their response metadata and update the document assertions.
Generated by Libra. React with 👍 or 👎 to give feedback on this comment.
| [FromQuery(Name = "include_deprecated")] bool? includeDeprecated, | ||
| ApiReferenceService apiReference, |
There was a problem hiding this comment.
Severity: P3 (Low)
An empty cursor (/changes?since=...&cursor=) now returns 400. Minimal APIs bind cursor= to "", not null, so cursor is not null passes, and IsValidCursor("") is false because DecodeCursor returns null for blank input. Before this change a blank cursor meant the first page. A client that always sends the parameter and leaves it empty for the first request will now fail. Use !string.IsNullOrWhiteSpace(cursor) && !ChangesService.IsValidCursor(cursor) so only a non-empty cursor the endpoint never returned is rejected.
Generated by Libra. Specialist: libra-complexity. React with 👍 or 👎 to give feedback on this comment.
| : app.UseExceptionHandler(new ExceptionHandlerOptions | ||
| { | ||
| var ex = context.Features.Get<IExceptionHandlerFeature>()?.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, |
There was a problem hiding this comment.
Severity: P3 (Low)
Keep a problem-writing fallback for SSE requests. The Ask AI clients use fetchEventSource, which sends Accept: text/event-stream, but the default AddProblemDetails writer does not accept that media type. With the custom exception writer removed, binding failures and provider exceptions before streaming return an empty 400/500 instead of the declared problem document. Add a writer/fallback that covers these requests and test with the actual SSE Accept header.
Generated by Libra. React with 👍 or 👎 to give feedback on this comment.
| : app.UseExceptionHandler(new ExceptionHandlerOptions | ||
| { | ||
| var ex = context.Features.Get<IExceptionHandlerFeature>()?.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 | ||
| }); |
There was a problem hiding this comment.
Severity: P3 (Low)
The old handler logged SearchUnavailableException as a warning, on purpose, because it is a transient timeout or overload. With no custom handler, ExceptionHandlerMiddleware now logs every exception that isn't suppressed at Error level, and SuppressDiagnosticsCallback only suppresses BadHttpRequestException. Every 503 caused by Elasticsearch overload will now show up as an unhandled error, which can trigger error alerts during load spikes. Either suppress diagnostics for SearchUnavailableException too and log it as a warning yourself, or confirm that the change in log level is intended.
Generated by Libra. Specialist: libra-complexity. React with 👍 or 👎 to give feedback on this comment.
|
|
||
| status.Should().Be(HttpStatusCode.BadRequest); | ||
| body.GetProperty("detail").GetString().Should().Be("cursor is not a nextCursor that /changes returned."); | ||
| A.CallTo(Changes.Current).MustNotHaveHappened(); |
There was a problem hiding this comment.
Severity: P3 (Low)
Inject Changes.Current into the test host before asserting that it was not called. SharedFactory replaces only the search and feedback services, so /changes resolves the production IChangesService, while this assertion checks an unrelated fake. It can never detect backend work before cursor rejection. Add an IChangesService replacement alongside the existing service swaps.
Generated by Libra. React with 👍 or 👎 to give feedback on this comment.
The API serves its OpenAPI document at /docs/_api/v1/openapi.json, generated
from the endpoints, which now declare their tags, summaries and response
types. Every error answers { errorType, message }: navigation search and page
feedback 400s, the feedback 503s, parameters that do not bind, and a /changes
cursor the endpoint did not return, which used to restart the feed. API
reference rejections say whether nothing matched instead of relying on a
_not_found suffix. ApiJsonContext gains the parameter types, without which
the document fails under Native AOT, and the test host drops the reflection
fallback so such gaps fail a test.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Without operation ids, API Explorer derives page slugs and ids from the paths, such as docs-api:docs-_api-v1-search. Names give it docs-api:search. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Errors are application/problem+json with a type URI per problem, a fixed title, the occurrence in detail, and the request's traceId. AddProblemDetails writes them; ApiProblems.Customize types the problems ASP.NET writes itself, so the exception handler and status code pages no longer need custom writers. Each type resolves to its section of the REST API page. ApiError is gone, and the spec describes every error as ProblemDetails. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
6be5357 to
638f314
Compare
The copy follows #4896, where every error is now an RFC 9457 problem. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The docs API now describes itself:
GET /docs/_api/v1/openapi.jsonserves an OpenAPI 3.2 document generated from the endpoints. Every error is now an RFC 9457 problem (application/problem+json), including errors that used to come back empty.Affects: API
Closes: elastic/docs-eng-team#1205
Stack: third layer of #4895, on top of #4894 (hardening) and #4887 (API operations).
Prompt summary: After hardening the docs API (#4894), make every error use one body and declare each endpoint's response types (review findings 8 and 9), and publish an OpenAPI spec as described in elastic/docs-eng-team#1205. Then adopt RFC 9457 for that error body, before anything outside the unreleased CLI command reads it.
Why
The API had no contract: clients copied routes and shapes by hand. Errors came in several shapes:
{errorType, message}from the API operations endpoints./changescursor silently restarted the feed."Not found" was inferred from an
_not_foundsuffix on the error type.What
OpenAPI document
Microsoft.AspNetCore.OpenApi(11.0.0, MIT; it needsMicrosoft.OpenApi[3.11.0, 4.0.0), which the repo already pins).MapOpenApiserves the document at/docs/_api/v1/openapi.json.ProducesErrorshelper. Every endpoint also lists 500.bool?.ApiJsonContextnow registers the route and query parameter types.OpenApiDocumentTestsinstead of production.search,get-api-operation, ...). API Explorer uses them for page slugs, such asoperation-search.RFC 9457 problems
Every error is a problem:
type,title,status,detail, plus the request'straceId.type(fragment of…/docs-builder/tree/main/data/api)#invalid-arguments#not-found,#operation-not-found,#api-not-found,#group-not-found#internal-error#search-unavailable(withRetry-After),#feedback-unavailabletyperesolves to its own section ofdocs/data/api.md, which this PR adds with a custom anchor per type. The local build renders all eight anchors. They usedocs-v3-preview.elastic.dev, where docs-builder's docs live today. Clients match ontype, so moving them later is a breaking change; the base URL is one constant inApiProblemsif a permanent home is preferred before release.titleis the same for every occurrence of a type (RFC 9457 §3.1.3), and what varies goes indetail. A 500 never includes the exception message.AddProblemDetailswrites every problem.ApiProblems.Customizegives a type to the problems ASP.NET writes itself.UseExceptionHandlerhas no custom writer; itsStatusCodeSelectormaps binding failures to 400,SearchUnavailableExceptionto 503 withRetry-After, and everything else to 500.UseStatusCodePagescovers bodyless errors, such assize=many, which fails binding without throwing.SuppressDiagnosticsCallback)./changescursor the endpoint didn't return. That last case is now a 400 instead of silently restarting the feed.ApiReferenceRejectiongainsIsNotFoundthroughInvalid(...)andNotFound(type, ...)factories, replacing the_not_foundsuffix check. Its snake_case type, which MCP keeps, maps to the kebab-case fragment.ProducesProblemdescribes every error asapplication/problem+jsonwith theProblemDetailsschema.traceId, which differs on every request.docs/data/api.mdlinks the spec, documents each problem type, and drops the "OpenAPI as a follow-up" note.Verify
Locally: 290 API tests and 76 MCP tests pass. The AOT publish has no trim or AOT warnings. The native binary serves the document and answers problems for a bad parameter, a missing parameter and an unknown path.
Out of scope: listing this document in API Explorer is the next PR in the stack.
🤖 Generated with Claude Code