001/* 002 * Copyright 2022-2026 Revetware LLC. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.soklet; 018 019import org.jspecify.annotations.NonNull; 020import org.jspecify.annotations.Nullable; 021 022import javax.annotation.concurrent.NotThreadSafe; 023import javax.annotation.concurrent.ThreadSafe; 024import java.net.InetSocketAddress; 025import java.time.Duration; 026import java.util.Arrays; 027import java.util.Collections; 028import java.util.LinkedHashMap; 029import java.util.List; 030import java.util.Locale; 031import java.util.Map; 032import java.util.Objects; 033import java.util.Optional; 034import java.util.concurrent.atomic.AtomicLong; 035import java.util.concurrent.atomic.DoubleAdder; 036import java.util.concurrent.atomic.LongAdder; 037import java.util.function.Predicate; 038 039import static java.util.Objects.requireNonNull; 040 041/** 042 * Contract for collecting operational metrics from Soklet. 043 * <p> 044 * Soklet's standard implementation, available via {@link #defaultInstance()}, supports detailed histogram collection, 045 * connection accept/reject counters, immutable snapshots (via {@link #snapshot()}), and provides Prometheus 046 * (text format v0.0.4) / OpenMetrics (1.0) export helpers for convenience. 047 * To disable metrics collection without a custom implementation, use {@link #disabledInstance()}. 048 * <p> 049 * For observed HTTP GET/DELETE requests on 2025 MCP session endpoints, the default 050 * collector uses the selected configured endpoint path for the HTTP route, including 051 * rejected requests. It never uses query values or session IDs as route labels. 052 * Custom HTTP callbacks receive the original request and a null {@link ResourceMethod}, 053 * because these operations are handled by the MCP transport. 054 * <p> 055 * Snapshot dimension keys retain nullable route accessors: a route is present exactly 056 * when {@link RouteType#MATCHED} applies. This keeps these frequently used keys as 057 * simple dimension carriers without allocating an Optional for each lookup. Their 058 * public constructors preserve the direct-construction contract of earlier record 059 * keys. The newer {@link HttpResponseStreamTerminationKey#fromDimensions(HttpServerRouteStatusKey, StreamTerminationReason)} 060 * factory composes an existing route/status key with a terminal reason; it does not 061 * replace the constructors of the established dimension keys. 062 * <p> 063 * If you prefer OpenTelemetry, Micrometer, or another metrics system for monitoring, you might choose to create your own 064 * implementation of this interface. 065 * <p> 066 * Example configuration: 067 * <pre><code> 068 * SokletConfig config = SokletConfig.withHttpServer(HttpServer.fromPort(8080)) 069 * // This is already the default; specifying it here is optional 070 * .metricsCollector(MetricsCollector.defaultInstance()) 071 * .build(); 072 * </code></pre> 073 * <p> 074 * To disable metrics collection entirely, specify Soklet's no-op implementation: 075 * <pre><code> 076 * SokletConfig config = SokletConfig.withHttpServer(HttpServer.fromPort(8080)) 077 * // Use this instead of null to disable metrics collection 078 * .metricsCollector(MetricsCollector.disabledInstance()) 079 * .build(); 080 * </code></pre> 081 * <p> 082 * <p>All methods must be: 083 * <ul> 084 * <li><strong>Thread-safe</strong> — called concurrently from multiple request threads</li> 085 * <li><strong>Non-blocking</strong> — should not perform I/O or acquire locks that might contend</li> 086 * <li><strong>Failure-tolerant</strong> — exceptions are caught and logged, never break request handling</li> 087 * </ul> 088 * <p> 089 * Example usage: 090 * <pre><code> 091 * {@literal @}GET("/metrics") 092 * public MarshaledResponse getMetrics(@NonNull MetricsCollector metricsCollector) { 093 * SnapshotTextOptions options = SnapshotTextOptions 094 * .fromMetricsFormat(MetricsFormat.PROMETHEUS); 095 * 096 * String body = metricsCollector.snapshotText(options).orElse(null); 097 * 098 * if (body == null) 099 * return MarshaledResponse.fromStatusCode(204); 100 * 101 * return MarshaledResponse.withStatusCode(200) 102 * .headers(Map.of("Content-Type", List.of("text/plain; charset=UTF-8"))) 103 * .body(body.getBytes(StandardCharsets.UTF_8)) 104 * .build(); 105 * } 106 * </code></pre> 107 * <p> 108 * See <a href="https://www.soklet.com/docs/metrics-collection">https://www.soklet.com/docs/metrics-collection</a> for detailed documentation. 109 * 110 * @author <a href="https://www.revetkn.com">Mark Allen</a> 111 */ 112@ThreadSafe 113public interface MetricsCollector { 114 /** 115 * Called when a server is about to accept a new TCP connection. 116 * 117 * @param serverType the server type that is accepting the connection 118 * @param remoteAddress the best-effort remote address, or {@code null} if unavailable 119 */ 120 default void willAcceptConnection(@NonNull ServerType serverType, 121 @Nullable InetSocketAddress remoteAddress) { 122 // No-op by default 123 } 124 125 /** 126 * Called after a server accepts a new TCP connection. 127 * 128 * @param serverType the server type that accepted the connection 129 * @param remoteAddress the best-effort remote address, or {@code null} if unavailable 130 */ 131 default void didAcceptConnection(@NonNull ServerType serverType, 132 @Nullable InetSocketAddress remoteAddress) { 133 // No-op by default 134 } 135 136 /** 137 * Called after a server fails to accept a new TCP connection. 138 * 139 * @param serverType the server type that failed to accept the connection 140 * @param remoteAddress the best-effort remote address, or {@code null} if unavailable 141 * @param reason the failure reason 142 * @param throwable an optional underlying cause, or {@code null} if not applicable 143 */ 144 default void didFailToAcceptConnection(@NonNull ServerType serverType, 145 @Nullable InetSocketAddress remoteAddress, 146 @NonNull ConnectionRejectionReason reason, 147 @Nullable Throwable throwable) { 148 // No-op by default 149 } 150 151 /** 152 * Called when a request is about to be accepted for application-level handling. 153 * 154 * @param serverType the server type that received the request 155 * @param remoteAddress the best-effort remote address, or {@code null} if unavailable 156 * @param requestTarget the raw request target (path + query) if known, or {@code null} if unavailable 157 */ 158 default void willAcceptRequest(@NonNull ServerType serverType, 159 @Nullable InetSocketAddress remoteAddress, 160 @Nullable String requestTarget) { 161 // No-op by default 162 } 163 164 /** 165 * Called after a request is accepted for application-level handling. 166 * 167 * @param serverType the server type that received the request 168 * @param remoteAddress the best-effort remote address, or {@code null} if unavailable 169 * @param requestTarget the raw request target (path + query) if known, or {@code null} if unavailable 170 */ 171 default void didAcceptRequest(@NonNull ServerType serverType, 172 @Nullable InetSocketAddress remoteAddress, 173 @Nullable String requestTarget) { 174 // No-op by default 175 } 176 177 /** 178 * Called when a request fails to be accepted before application-level handling begins. 179 * SSE request acceptance/rejection counts are not mutually exclusive: a parsed 180 * request can be accepted for handling and later rejected at handshake admission. 181 * Do not derive a request total by adding those counters. 182 * 183 * @param serverType the server type that received the request 184 * @param remoteAddress the best-effort remote address, or {@code null} if unavailable 185 * @param requestTarget the raw request target (path + query) if known, or {@code null} if unavailable 186 * @param reason the rejection reason 187 * @param throwable an optional underlying cause, or {@code null} if not applicable 188 */ 189 default void didFailToAcceptRequest(@NonNull ServerType serverType, 190 @Nullable InetSocketAddress remoteAddress, 191 @Nullable String requestTarget, 192 @NonNull RequestRejectionReason reason, 193 @Nullable Throwable throwable) { 194 // No-op by default 195 } 196 197 /** 198 * Called when a server transport records a low-level failure or timeout outside normal application request handling. 199 * 200 * @param serverType the server type whose transport recorded the failure 201 * @param reason the transport failure reason 202 * @param throwable an optional underlying cause, or {@code null} if not applicable 203 */ 204 default void didRecordTransportFailure(@NonNull ServerType serverType, 205 @NonNull TransportFailureReason reason, 206 @Nullable Throwable throwable) { 207 // No-op by default 208 } 209 210 /** 211 * Called after Soklet records an immutable semantic MCP metrics event. 212 * <p> 213 * Events expose only dimensions valid for their transition. Implementations 214 * must not block and must be safe for concurrent invocation. Exceptions are 215 * contained and surfaced through {@link LogEventType#METRICS_COLLECTOR_FAILED}; 216 * they never alter MCP request handling or its wire result. 217 * <p> 218 * The built-in MCP server retains at most 4,096 pending semantic records. 219 * At capacity it omits new ordinary records, while server lifecycle records 220 * reclaim an ordinary record. Withheld transition records share that bound. 221 * Eligible records keep their enqueue order; an independent operation may 222 * deliver while another transition is withheld. Records within a transition 223 * retain their order. Counters and gauges may be incomplete after overflow. 224 * Collector delivery must remain nonblocking. Final records, including ServerStopped, 225 * may arrive after run()/close() returns and after application shutdown cleanup; 226 * lifecycle completion is not a semantic-metrics flush barrier. 227 * <p> 228 * The default collector counts delivered 229 * {@link McpMetricsEvent.SubscriptionMaintenance} records by endpoint, work 230 * and outcome in {@link McpMetricsSnapshot#getSubscriptionMaintenance()}. 231 * These counts include coalescing and stale-result discards, rather than 232 * measuring unique subscriptions or started maintenance attempts. 233 * 234 * @param event immutable MCP metrics event 235 */ 236 default void didRecordMcpMetricsEvent(@NonNull McpMetricsEvent event) { 237 // No-op by default 238 } 239 240 /** 241 * Called when Soklet is about to read or parse a request into a valid {@link Request}. 242 * 243 * @param serverType the server type that received the request 244 * @param remoteAddress the best-effort remote address, or {@code null} if unavailable 245 * @param requestTarget the raw request target (path + query) if known, or {@code null} if unavailable 246 */ 247 default void willReadRequest(@NonNull ServerType serverType, 248 @Nullable InetSocketAddress remoteAddress, 249 @Nullable String requestTarget) { 250 // No-op by default 251 } 252 253 /** 254 * Called when a request was successfully read or parsed into a valid {@link Request}. 255 * 256 * @param serverType the server type that received the request 257 * @param remoteAddress the best-effort remote address, or {@code null} if unavailable 258 * @param requestTarget the raw request target (path + query) if known, or {@code null} if unavailable 259 */ 260 default void didReadRequest(@NonNull ServerType serverType, 261 @Nullable InetSocketAddress remoteAddress, 262 @Nullable String requestTarget) { 263 // No-op by default 264 } 265 266 /** 267 * Called when a request could not be read or parsed into a valid {@link Request}. 268 * 269 * @param serverType the server type that received the request 270 * @param remoteAddress the best-effort remote address, or {@code null} if unavailable 271 * @param requestTarget the raw request target (path + query) if known, or {@code null} if unavailable 272 * @param reason the failure reason 273 * @param throwable an optional underlying cause, or {@code null} if not applicable 274 */ 275 default void didFailToReadRequest(@NonNull ServerType serverType, 276 @Nullable InetSocketAddress remoteAddress, 277 @Nullable String requestTarget, 278 @NonNull RequestReadFailureReason reason, 279 @Nullable Throwable throwable) { 280 // No-op by default 281 } 282 283 /** 284 * Called when request handling begins. The resource method may be null, including 285 * for HTTP GET/DELETE requests handled by a 2025 MCP session endpoint. 286 * 287 * @param serverType the server type that received the request 288 * @param request the actual request 289 * @param resourceMethod the resolved HTTP resource method, or null when none applies 290 */ 291 default void didStartRequestHandling(@NonNull ServerType serverType, 292 @NonNull Request request, 293 @Nullable ResourceMethod resourceMethod) { 294 // No-op by default 295 } 296 297 /** 298 * Called after application request processing and response handoff. Admitted HTTP streams 299 * continue asynchronously; their terminal observations arrive through {@link #didTerminateResponseStream}. 300 */ 301 default void didFinishRequestHandling(@NonNull ServerType serverType, 302 @NonNull Request request, 303 @Nullable ResourceMethod resourceMethod, 304 @NonNull MarshaledResponse marshaledResponse, 305 @NonNull Duration duration, 306 @NonNull List<@NonNull Throwable> throwables) { 307 // No-op by default 308 } 309 310 /** 311 * Called once before an admitted HTTP response stream is offered for writing, before 312 * its producer starts and before {@link #didFinishRequestHandling}. This enrolls the original 313 * dispatched {@link Request} object by identity for a paired 314 * {@link #didTerminateResponseStream} callback; it does not mean headers or body bytes 315 * have reached the client. Finite replacements and suppressed bodies are not enrolled. 316 * <p> 317 * A custom transport that invokes this method must report one terminal callback with 318 * the exact same handle instance and original dispatched request, including failures before body production. Record elapsed 319 * request time from entry into the framework request handler using a monotonic clock. 320 * If termination occurs before handling finish, collectors must retain at most one pending 321 * terminal observation and return without waiting. Unenrolled streams are accounted at 322 * handling handoff by the default collector. Collector decorators must forward this callback 323 * to retain accounting through stream termination. Callback failures are contained by the transport. 324 * 325 * @param streamingResponseHandle the admitted HTTP response stream 326 */ 327 default void willWriteResponseStream(@NonNull StreamingResponseHandle streamingResponseHandle) { 328 // No-op by default 329 } 330 331 /** 332 * Called once after an admitted HTTP response stream terminates. The built-in transport delivers 333 * this after metrics handling finish and before lifecycle stream observers; custom transports may 334 * report an early terminal outcome as described by {@link #willWriteResponseStream}. 335 * Finite replacements and suppressed bodies do not invoke it. 336 * The handle retains the original dispatch request. Failures are isolated from transport completion. 337 * 338 * @param streamingResponseHandle the admitted HTTP response stream 339 * @param streamTermination its logical terminal outcome; its duration covers the stream only 340 * @param requestDuration monotonic duration from request processing entry to logical transport termination, 341 * excluding observer queue delay and subsequent resource cleanup 342 * @param responseBodySizeInBytes payload bytes accepted by socket writes (including partial writes), 343 * excluding HTTP framing; simulator values count accepted materialized bytes 344 */ 345 default void didTerminateResponseStream(@NonNull StreamingResponseHandle streamingResponseHandle, 346 @NonNull StreamTermination streamTermination, @NonNull Duration requestDuration, 347 @NonNull Long responseBodySizeInBytes) { 348 // No-op by default 349 } 350 351 /** 352 * Called before response data is written. 353 */ 354 default void willWriteResponse(@NonNull ServerType serverType, 355 @NonNull Request request, 356 @Nullable ResourceMethod resourceMethod, 357 @NonNull MarshaledResponse marshaledResponse) { 358 // No-op by default 359 } 360 361 /** 362 * Called after the response is handed to transport. For streaming HTTP responses this is 363 * not body completion; use {@link #didTerminateResponseStream} for terminal observations. 364 */ 365 default void didWriteResponse(@NonNull ServerType serverType, 366 @NonNull Request request, 367 @Nullable ResourceMethod resourceMethod, 368 @NonNull MarshaledResponse marshaledResponse, 369 @NonNull Duration responseWriteDuration) { 370 // No-op by default 371 } 372 373 /** 374 * Called after response data fails to write. 375 */ 376 default void didFailToWriteResponse(@NonNull ServerType serverType, 377 @NonNull Request request, 378 @Nullable ResourceMethod resourceMethod, 379 @NonNull MarshaledResponse marshaledResponse, 380 @NonNull Duration responseWriteDuration, 381 @NonNull Throwable throwable) { 382 // No-op by default 383 } 384 385 386 /** 387 * Called before an SSE connection is established. 388 */ 389 default void willEstablishSseConnection(@NonNull Request request, 390 @Nullable ResourceMethod resourceMethod) { 391 // No-op by default 392 } 393 394 /** 395 * Called after an SSE connection is established. 396 * <p> 397 * If client initialization fails after the accepted response has been written, the built-in SSE server 398 * invokes this callback immediately before the paired termination callbacks. Such a connection never 399 * becomes available to a broadcaster. The termination retains its elected reason and cause. 400 */ 401 default void didEstablishSseConnection(@NonNull SseConnection sseConnection) { 402 // No-op by default 403 } 404 405 /** 406 * Called if an SSE connection fails to establish before an accepted response has been written. 407 * <p> 408 * Capacity rejection is {@link SseConnection.HandshakeFailureReason#CAPACITY_EXCEEDED}; request processing, 409 * response preparation and accepted-handshake response writing failures use 410 * {@link SseConnection.HandshakeFailureReason#INTERNAL_ERROR} with their cause. 411 * A routine peer disconnect while writing a rejection retains its rejection reason and records the write cause. 412 * {@link SseConnection.HandshakeFailureReason#HANDSHAKE_REJECTED} 413 * also covers finite route/method mismatch responses on the SSE listener, 414 * including HEAD and OPTIONS; an event-source method need not have run. 415 * Failure during client initialization after acceptance uses the stream-termination callbacks. 416 * 417 * @param connectionHandshakeFailureReason the handshake failure reason 418 * @param throwable an optional underlying cause, or {@code null} if not applicable 419 */ 420 default void didFailToEstablishSseConnection(@NonNull Request request, 421 @Nullable ResourceMethod resourceMethod, 422 SseConnection.@NonNull HandshakeFailureReason connectionHandshakeFailureReason, 423 @Nullable Throwable throwable) { 424 // No-op by default 425 } 426 427 /** 428 * Called before an SSE connection is terminated. 429 */ 430 default void willTerminateSseConnection(@NonNull SseConnection sseConnection, 431 @NonNull StreamTermination streamTermination) { 432 // No-op by default 433 } 434 435 /** 436 * Called after an SSE connection is terminated. 437 */ 438 default void didTerminateSseConnection(@NonNull SseConnection sseConnection, 439 @NonNull StreamTermination streamTermination) { 440 // No-op by default 441 } 442 443 /** 444 * Called before an SSE event is written. 445 */ 446 default void willWriteSseEvent(@NonNull SseConnection sseConnection, 447 @NonNull SseEvent sseEvent) { 448 // No-op by default 449 } 450 451 /** 452 * Called after an SSE event is written. 453 * 454 * @param sseConnection the connection the event was written to 455 * @param sseEvent the event that was written 456 * @param writeDuration how long it took to write the event 457 * @param deliveryLag elapsed time between enqueue and write start, or {@code null} if unknown 458 * @param payloadBytes size of the serialized payload in bytes, or {@code null} if unknown 459 * @param queueDepth number of queued elements remaining at write time, or {@code null} if unknown 460 */ 461 default void didWriteSseEvent(@NonNull SseConnection sseConnection, 462 @NonNull SseEvent sseEvent, 463 @NonNull Duration writeDuration, 464 @Nullable Duration deliveryLag, 465 @Nullable Integer payloadBytes, 466 @Nullable Integer queueDepth) { 467 // No-op by default 468 } 469 470 /** 471 * Called after an SSE event fails to write. 472 * 473 * @param sseConnection the connection the event was written to 474 * @param sseEvent the event that was written 475 * @param writeDuration how long it took to attempt the write 476 * @param throwable the failure cause 477 * @param deliveryLag elapsed time between enqueue and write start, or {@code null} if unknown 478 * @param payloadBytes size of the serialized payload in bytes, or {@code null} if unknown 479 * @param queueDepth number of queued elements remaining at write time, or {@code null} if unknown 480 */ 481 default void didFailToWriteSseEvent(@NonNull SseConnection sseConnection, 482 @NonNull SseEvent sseEvent, 483 @NonNull Duration writeDuration, 484 @NonNull Throwable throwable, 485 @Nullable Duration deliveryLag, 486 @Nullable Integer payloadBytes, 487 @Nullable Integer queueDepth) { 488 // No-op by default 489 } 490 491 /** 492 * Called before an SSE comment is written. 493 */ 494 default void willWriteSseComment(@NonNull SseConnection sseConnection, 495 @NonNull SseComment sseComment) { 496 // No-op by default 497 } 498 499 /** 500 * Called after an SSE comment is written. 501 * 502 * @param sseConnection the connection the comment was written to 503 * @param sseComment the comment that was written 504 * @param writeDuration how long it took to write the comment 505 * @param deliveryLag elapsed time between enqueue and write start, or {@code null} if unknown 506 * @param payloadBytes size of the serialized payload in bytes, or {@code null} if unknown 507 * @param queueDepth number of queued elements remaining at write time, or {@code null} if unknown 508 */ 509 default void didWriteSseComment(@NonNull SseConnection sseConnection, 510 @NonNull SseComment sseComment, 511 @NonNull Duration writeDuration, 512 @Nullable Duration deliveryLag, 513 @Nullable Integer payloadBytes, 514 @Nullable Integer queueDepth) { 515 // No-op by default 516 } 517 518 /** 519 * Called after an SSE comment fails to write. 520 * 521 * @param sseConnection the connection the comment was written to 522 * @param sseComment the comment that was written 523 * @param writeDuration how long it took to attempt the write 524 * @param throwable the failure cause 525 * @param deliveryLag elapsed time between enqueue and write start, or {@code null} if unknown 526 * @param payloadBytes size of the serialized payload in bytes, or {@code null} if unknown 527 * @param queueDepth number of queued elements remaining at write time, or {@code null} if unknown 528 */ 529 default void didFailToWriteSseComment(@NonNull SseConnection sseConnection, 530 @NonNull SseComment sseComment, 531 @NonNull Duration writeDuration, 532 @NonNull Throwable throwable, 533 @Nullable Duration deliveryLag, 534 @Nullable Integer payloadBytes, 535 @Nullable Integer queueDepth) { 536 // No-op by default 537 } 538 539 /** 540 * Called after an SSE event is dropped before it can be enqueued for delivery. 541 * 542 * @param sseConnection the connection the event was targeting 543 * @param sseEvent the event that was dropped 544 * @param reason the drop reason 545 * @param payloadBytes size of the serialized payload in bytes, or {@code null} if unknown 546 * @param queueDepth number of queued elements at drop time, or {@code null} if unknown 547 */ 548 default void didDropSseEvent(@NonNull SseConnection sseConnection, 549 @NonNull SseEvent sseEvent, 550 @NonNull SseEventDropReason reason, 551 @Nullable Integer payloadBytes, 552 @Nullable Integer queueDepth) { 553 // No-op by default 554 } 555 556 /** 557 * Called after an SSE comment is dropped before it can be enqueued for delivery. 558 * 559 * @param sseConnection the connection the comment was targeting 560 * @param sseComment the comment that was dropped 561 * @param reason the drop reason 562 * @param payloadBytes size of the serialized payload in bytes, or {@code null} if unknown 563 * @param queueDepth number of queued elements at drop time, or {@code null} if unknown 564 */ 565 default void didDropSseComment(@NonNull SseConnection sseConnection, 566 @NonNull SseComment sseComment, 567 @NonNull SseEventDropReason reason, 568 @Nullable Integer payloadBytes, 569 @Nullable Integer queueDepth) { 570 // No-op by default 571 } 572 573 /** 574 * Called after a broadcast attempt for a Server-Sent Event payload. 575 * All counts are non-null, including zero when no connections were targeted. 576 * 577 * @param resourcePathDeclaration the route declaration that was broadcast to 578 * @param attempted number of connections targeted 579 * @param enqueued number of connections for which enqueue succeeded 580 * @param dropped number of connections for which enqueue failed 581 */ 582 default void didBroadcastSseEvent(@NonNull ResourcePathDeclaration resourcePathDeclaration, 583 @NonNull Integer attempted, 584 @NonNull Integer enqueued, 585 @NonNull Integer dropped) { 586 // No-op by default 587 } 588 589 /** 590 * Called after a broadcast attempt for a Server-Sent Event comment payload. 591 * All counts are non-null, including zero when no connections were targeted. 592 * 593 * @param resourcePathDeclaration the route declaration that was broadcast to 594 * @param commentType the comment type 595 * @param attempted number of connections targeted 596 * @param enqueued number of connections for which enqueue succeeded 597 * @param dropped number of connections for which enqueue failed 598 */ 599 default void didBroadcastSseComment(@NonNull ResourcePathDeclaration resourcePathDeclaration, 600 SseComment.@NonNull CommentType commentType, 601 @NonNull Integer attempted, 602 @NonNull Integer enqueued, 603 @NonNull Integer dropped) { 604 // No-op by default 605 } 606 607 /** 608 * Returns a snapshot of metrics collected so far, if supported. 609 * 610 * @return an optional metrics snapshot 611 */ 612 @NonNull 613 default Optional<@NonNull Snapshot> snapshot() { 614 return Optional.empty(); 615 } 616 617 /** 618 * Returns a text snapshot of metrics collected so far, if supported. 619 * <p> 620 * The default collector supports Prometheus (text format v0.0.4) and OpenMetrics (1.0) text exposition formats. 621 * Its OpenMetrics histogram {@code le} labels use canonical floating-point 622 * formatting (for example, {@code 128.0} and {@code 1e+06}); Prometheus 623 * retains integer finite-boundary labels. Both formats use {@code +Inf} 624 * for the overflow bucket. Thresholds and units are unchanged. 625 * 626 * @param options the snapshot rendering options 627 * @return a textual metrics snapshot, or {@link Optional#empty()} if unsupported 628 */ 629 @NonNull 630 default Optional<@NonNull String> snapshotText(@NonNull SnapshotTextOptions options) { 631 requireNonNull(options); 632 return Optional.empty(); 633 } 634 635 /** 636 * Resets cumulative in-memory metrics for a new observation window, if 637 * supported. 638 * <p> 639 * Implementations that track live work must preserve current gauge values 640 * and any request or connection identity state needed to match later 641 * lifecycle callbacks. A reset must not cause a matching terminal callback 642 * to underflow a live gauge. The default collector follows this contract; 643 * this default implementation is a no-op. 644 */ 645 default void reset() { 646 // No-op by default 647 } 648 649 /** 650 * Text format to use for {@link #snapshotText(SnapshotTextOptions)}. 651 * <p> 652 * This controls serialization only; the underlying metrics data is unchanged. 653 * <p> 654 * This type may gain reviewed constants in Soklet 4.x; use a forward-compatible default when switching over its values. 655 * 656 */ 657 enum MetricsFormat { 658 /** 659 * Prometheus text exposition format (v0.0.4). 660 */ 661 PROMETHEUS, 662 /** 663 * OpenMetrics text exposition format (1.0), including OpenMetrics 664 * counter-family naming, structurally complete histogram points, 665 * canonical floating-point {@code le} labels, and the {@code # EOF} trailer. 666 */ 667 OPEN_METRICS_1_0 668 } 669 670 /** 671 * Options for rendering a textual metrics snapshot. 672 * <p> 673 * Use {@link #withMetricsFormat(MetricsFormat)} to obtain a builder and customize output. 674 * <p> 675 * Key options: 676 * <ul> 677 * <li>{@code metricFilter} allows per-sample filtering by name and labels</li> 678 * <li>{@code histogramFormat} controls bucket vs count/sum output</li> 679 * <li>{@code includeZeroBuckets} drops empty bucket samples when false</li> 680 * </ul> 681 * The default collector supplies {@code metricFilter} with the exact 682 * serialized label values for the selected format. A finite histogram 683 * boundary can therefore have an integer {@code le} value in Prometheus 684 * and a canonical floating-point value in OpenMetrics. 685 */ 686 @ThreadSafe 687 final class SnapshotTextOptions { 688 @NonNull 689 private final MetricsFormat metricsFormat; 690 @Nullable 691 private final Predicate<@NonNull MetricSample> metricFilter; 692 @NonNull 693 private final HistogramFormat histogramFormat; 694 @NonNull 695 private final Boolean includeZeroBuckets; 696 697 private SnapshotTextOptions(@NonNull Builder builder) { 698 requireNonNull(builder); 699 700 this.metricsFormat = requireNonNull(builder.metricsFormat); 701 this.metricFilter = builder.metricFilter; 702 this.histogramFormat = requireNonNull(builder.histogramFormat); 703 this.includeZeroBuckets = builder.includeZeroBuckets == null ? true : builder.includeZeroBuckets; 704 } 705 706 /** 707 * Begins building options with the specified format. 708 * 709 * @param metricsFormat the text exposition format 710 * @return a builder seeded with the format 711 */ 712 @NonNull 713 public static Builder withMetricsFormat(@NonNull MetricsFormat metricsFormat) { 714 return new Builder(metricsFormat); 715 } 716 717 /** 718 * Creates options with the specified format and defaults for all other fields. 719 * 720 * @param metricsFormat the text exposition format 721 * @return a {@link SnapshotTextOptions} instance 722 */ 723 @NonNull 724 public static SnapshotTextOptions fromMetricsFormat(@NonNull MetricsFormat metricsFormat) { 725 return withMetricsFormat(metricsFormat).build(); 726 } 727 728 /** 729 * The text exposition format to emit. 730 * 731 * @return the metrics format 732 */ 733 @NonNull 734 public MetricsFormat getMetricsFormat() { 735 return this.metricsFormat; 736 } 737 738 /** 739 * Optional filter for rendered samples. 740 * 741 * @return the filter, if present 742 */ 743 @NonNull 744 public Optional<@NonNull Predicate<@NonNull MetricSample>> getMetricFilter() { 745 return Optional.ofNullable(this.metricFilter); 746 } 747 748 /** 749 * The histogram rendering strategy. 750 * 751 * @return the histogram format 752 */ 753 @NonNull 754 public HistogramFormat getHistogramFormat() { 755 return this.histogramFormat; 756 } 757 758 /** 759 * Whether zero-count buckets should be emitted. 760 * 761 * @return {@code true} if zero-count buckets are included 762 */ 763 @NonNull 764 public Boolean getIncludeZeroBuckets() { 765 return this.includeZeroBuckets; 766 } 767 768 /** 769 * Supported histogram rendering strategies. 770 * <p> 771 * This type may gain reviewed constants in Soklet 4.x; use a forward-compatible default when switching over its values. 772 * 773 */ 774 public enum HistogramFormat { 775 /** 776 * Emit full histogram series (buckets, count, and sum). 777 */ 778 FULL_BUCKETS, 779 /** 780 * Emit only {@code _count} and {@code _sum} samples. OpenMetrics 781 * output additionally retains the required {@code le="+Inf"} bucket. 782 */ 783 COUNT_SUM_ONLY, 784 /** 785 * Suppress histogram output entirely. 786 */ 787 NONE 788 } 789 790 /** 791 * A single text-format sample with its label set. 792 * <p> 793 * Filters receive these instances for each rendered sample. For histogram buckets, 794 * the sample name includes {@code _bucket} and the labels include {@code le}. 795 * Label maps are immutable and preserve insertion order. 796 * When rendering OpenMetrics, rejecting a histogram's required 797 * {@code le="+Inf"} bucket omits that label-set's entire histogram point; 798 * rejecting exactly one of its {@code _count}/{@code _sum} pair omits both. 799 */ 800 @ThreadSafe 801 public static final class MetricSample { 802 @NonNull 803 private final String name; 804 @NonNull 805 private final Map<@NonNull String, @NonNull String> labels; 806 807 /** 808 * Creates a metrics sample definition. 809 * 810 * @param name the sample name (e.g. {@code soklet_http_request_duration_nanos_bucket}) 811 * @param labels the sample labels 812 */ 813 public MetricSample(@NonNull String name, 814 @NonNull Map<@NonNull String, @NonNull String> labels) { 815 this.name = requireNonNull(name); 816 this.labels = Collections.unmodifiableMap(new LinkedHashMap<>(requireNonNull(labels))); 817 } 818 819 /** 820 * The name for this sample. 821 * 822 * @return the sample name 823 */ 824 @NonNull 825 public String getName() { 826 return this.name; 827 } 828 829 /** 830 * The label set for this sample. 831 * 832 * @return immutable labels 833 */ 834 @NonNull 835 public Map<@NonNull String, @NonNull String> getLabels() { 836 return this.labels; 837 } 838 } 839 840 /** 841 * Builder for {@link SnapshotTextOptions}. 842 * <p> 843 * Defaults are {@link HistogramFormat#FULL_BUCKETS} and {@code includeZeroBuckets=true}. 844 */ 845 @NotThreadSafe 846 public static final class Builder { 847 @NonNull 848 private final MetricsFormat metricsFormat; 849 @Nullable 850 private Predicate<@NonNull MetricSample> metricFilter; 851 @NonNull 852 private HistogramFormat histogramFormat; 853 @Nullable 854 private Boolean includeZeroBuckets; 855 856 private Builder(@NonNull MetricsFormat metricsFormat) { 857 this.metricsFormat = requireNonNull(metricsFormat); 858 this.histogramFormat = HistogramFormat.FULL_BUCKETS; 859 this.includeZeroBuckets = true; 860 } 861 862 /** 863 * Sets an optional per-sample filter. 864 * 865 * @param metricFilter the filter to apply, or {@code null} to disable filtering (the default) 866 * @return this builder 867 */ 868 @NonNull 869 public Builder metricFilter( 870 @Nullable Predicate<@NonNull MetricSample> metricFilter) { 871 this.metricFilter = metricFilter; 872 return this; 873 } 874 875 /** 876 * Sets how histograms are rendered in the text snapshot. 877 * 878 * @param histogramFormat the histogram format 879 * @return this builder 880 */ 881 @NonNull 882 public Builder histogramFormat(@NonNull HistogramFormat histogramFormat) { 883 this.histogramFormat = requireNonNull(histogramFormat); 884 return this; 885 } 886 887 /** 888 * Controls whether zero-count buckets are emitted. 889 * 890 * @param includeZeroBuckets {@code true} to include zero-count buckets, {@code false} to omit them, 891 * or {@code null} to restore the default of {@code true} 892 * @return this builder 893 */ 894 @NonNull 895 public Builder includeZeroBuckets(@Nullable Boolean includeZeroBuckets) { 896 this.includeZeroBuckets = includeZeroBuckets; 897 return this; 898 } 899 900 /** 901 * Builds a {@link SnapshotTextOptions} instance. 902 * 903 * @return the built options 904 */ 905 @NonNull 906 public SnapshotTextOptions build() { 907 return new SnapshotTextOptions(this); 908 } 909 } 910 } 911 912 /** 913 * Immutable snapshot of collected metrics. 914 * <p> 915 * Durations are in nanoseconds, sizes are in bytes, and queue depths are raw counts. 916 * Histogram values are captured as {@link HistogramSnapshot} instances. 917 * Connection counts report total accepted/rejected connections for the HTTP and SSE servers. 918 * Transport failures are reported by server type and low-level failure reason. 919 * Request read failures and request rejections are reported separately for HTTP and SSE traffic. 920 * Instances are typically produced by {@link MetricsCollector#snapshot()} but can also be built 921 * manually via {@link #builder()}. 922 * 923 * @author <a href="https://www.revetkn.com">Mark Allen</a> 924 */ 925 @ThreadSafe 926 final class Snapshot { 927 @NonNull 928 private final Long activeRequests; 929 @NonNull 930 private final Long activeSseStreams; 931 @NonNull 932 private final McpMetricsSnapshot mcpMetrics; 933 @NonNull 934 private final Long httpConnectionsAccepted; 935 @NonNull 936 private final Long httpConnectionsRejected; 937 @NonNull 938 private final Long sseConnectionsAccepted; 939 @NonNull 940 private final Long sseConnectionsRejected; 941 @NonNull 942 private final Map<@NonNull TransportFailureKey, @NonNull Long> transportFailures; 943 @NonNull 944 private final Map<@NonNull RequestReadFailureKey, @NonNull Long> httpRequestReadFailures; 945 @NonNull 946 private final Map<@NonNull RequestRejectionKey, @NonNull Long> httpRequestRejections; 947 @NonNull 948 private final Map<@NonNull RequestReadFailureKey, @NonNull Long> sseRequestReadFailures; 949 @NonNull 950 private final Map<@NonNull RequestRejectionKey, @NonNull Long> sseRequestRejections; 951 @NonNull 952 private final Map<@NonNull HttpServerRouteStatusKey, @NonNull HistogramSnapshot> httpRequestDurations; 953 @NonNull 954 private final Map<@NonNull HttpServerRouteStatusKey, @NonNull HistogramSnapshot> httpHandlerDurations; 955 @NonNull 956 private final Map<@NonNull HttpServerRouteStatusKey, @NonNull HistogramSnapshot> httpTimeToFirstByte; 957 @NonNull 958 private final Map<@NonNull HttpServerRouteKey, @NonNull HistogramSnapshot> httpRequestBodyBytes; 959 @NonNull 960 private final Map<@NonNull HttpServerRouteStatusKey, @NonNull HistogramSnapshot> httpResponseBodyBytes; 961 @NonNull 962 private final Map<@NonNull HttpResponseStreamTerminationKey, @NonNull Long> httpResponseStreamTerminations; 963 @NonNull 964 private final Map<@NonNull SseEventRouteKey, @NonNull Long> sseHandshakesAccepted; 965 @NonNull 966 private final Map<@NonNull SseEventRouteHandshakeFailureKey, @NonNull Long> sseHandshakesRejected; 967 @NonNull 968 private final Map<@NonNull SseEventRouteEnqueueOutcomeKey, @NonNull Long> sseEventEnqueueOutcomes; 969 @NonNull 970 private final Map<@NonNull SseCommentRouteEnqueueOutcomeKey, @NonNull Long> sseCommentEnqueueOutcomes; 971 @NonNull 972 private final Map<@NonNull SseEventRouteDropKey, @NonNull Long> sseEventDrops; 973 @NonNull 974 private final Map<@NonNull SseCommentRouteDropKey, @NonNull Long> sseCommentDrops; 975 @NonNull 976 private final Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> sseTimeToFirstEvent; 977 @NonNull 978 private final Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> sseEventWriteDurations; 979 @NonNull 980 private final Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> sseEventDeliveryLag; 981 @NonNull 982 private final Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> sseEventSizes; 983 @NonNull 984 private final Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> sseQueueDepth; 985 @NonNull 986 private final Map<@NonNull SseCommentRouteKey, @NonNull HistogramSnapshot> sseCommentDeliveryLag; 987 @NonNull 988 private final Map<@NonNull SseCommentRouteKey, @NonNull HistogramSnapshot> sseCommentSizes; 989 @NonNull 990 private final Map<@NonNull SseCommentRouteKey, @NonNull HistogramSnapshot> sseCommentQueueDepth; 991 @NonNull 992 private final Map<@NonNull SseStreamRouteTerminationKey, @NonNull HistogramSnapshot> sseStreamDurations; 993 994 /** 995 * Acquires an "empty" builder for {@link Snapshot} instances. 996 * 997 * @return the builder 998 */ 999 @NonNull 1000 public static Builder builder() { 1001 return new Builder(); 1002 } 1003 1004 private Snapshot(@NonNull Builder builder) { 1005 requireNonNull(builder); 1006 1007 this.activeRequests = requireNonNull(builder.activeRequests); 1008 this.activeSseStreams = requireNonNull(builder.activeSseStreams); 1009 this.mcpMetrics = requireNonNull(builder.mcpMetrics); 1010 this.httpConnectionsAccepted = requireNonNull(builder.httpConnectionsAccepted); 1011 this.httpConnectionsRejected = requireNonNull(builder.httpConnectionsRejected); 1012 this.sseConnectionsAccepted = requireNonNull(builder.sseConnectionsAccepted); 1013 this.sseConnectionsRejected = requireNonNull(builder.sseConnectionsRejected); 1014 this.transportFailures = copyOrEmpty(builder.transportFailures); 1015 this.httpRequestReadFailures = copyOrEmpty(builder.httpRequestReadFailures); 1016 this.httpRequestRejections = copyOrEmpty(builder.httpRequestRejections); 1017 this.sseRequestReadFailures = copyOrEmpty(builder.sseRequestReadFailures); 1018 this.sseRequestRejections = copyOrEmpty(builder.sseRequestRejections); 1019 this.httpRequestDurations = copyOrEmpty(builder.httpRequestDurations); 1020 this.httpHandlerDurations = copyOrEmpty(builder.httpHandlerDurations); 1021 this.httpTimeToFirstByte = copyOrEmpty(builder.httpTimeToFirstByte); 1022 this.httpRequestBodyBytes = copyOrEmpty(builder.httpRequestBodyBytes); 1023 this.httpResponseBodyBytes = copyOrEmpty(builder.httpResponseBodyBytes); 1024 this.httpResponseStreamTerminations = copyStreamTerminations(builder.httpResponseStreamTerminations); 1025 this.sseHandshakesAccepted = copyOrEmpty(builder.sseHandshakesAccepted); 1026 this.sseHandshakesRejected = copyOrEmpty(builder.sseHandshakesRejected); 1027 this.sseEventEnqueueOutcomes = copyOrEmpty(builder.sseEventEnqueueOutcomes); 1028 this.sseCommentEnqueueOutcomes = copyOrEmpty(builder.sseCommentEnqueueOutcomes); 1029 this.sseEventDrops = copyOrEmpty(builder.sseEventDrops); 1030 this.sseCommentDrops = copyOrEmpty(builder.sseCommentDrops); 1031 this.sseTimeToFirstEvent = copyOrEmpty(builder.sseTimeToFirstEvent); 1032 this.sseEventWriteDurations = copyOrEmpty(builder.sseEventWriteDurations); 1033 this.sseEventDeliveryLag = copyOrEmpty(builder.sseEventDeliveryLag); 1034 this.sseEventSizes = copyOrEmpty(builder.sseEventSizes); 1035 this.sseQueueDepth = copyOrEmpty(builder.sseQueueDepth); 1036 this.sseCommentDeliveryLag = copyOrEmpty(builder.sseCommentDeliveryLag); 1037 this.sseCommentSizes = copyOrEmpty(builder.sseCommentSizes); 1038 this.sseCommentQueueDepth = copyOrEmpty(builder.sseCommentQueueDepth); 1039 this.sseStreamDurations = copyOrEmpty(builder.sseStreamDurations); 1040 } 1041 1042 /** 1043 * Returns the number of active HTTP requests. 1044 * 1045 * @return the active HTTP request count 1046 */ 1047 @NonNull 1048 public Long getActiveRequests() { 1049 return this.activeRequests; 1050 } 1051 1052 /** 1053 * Returns the number of active server-sent event streams. 1054 * 1055 * @return the active SSE stream count 1056 */ 1057 @NonNull 1058 public Long getActiveSseStreams() { 1059 return this.activeSseStreams; 1060 } 1061 1062 /** 1063 * Returns the immutable MCP metrics aggregate. 1064 * <p> 1065 * This value is non-null and contains zero or empty values when no MCP 1066 * metrics have been recorded. 1067 * 1068 * @return MCP metrics aggregate 1069 */ 1070 @NonNull 1071 public McpMetricsSnapshot getMcpMetrics() { 1072 return this.mcpMetrics; 1073 } 1074 1075 1076 /** 1077 * Returns the total number of accepted HTTP connections. 1078 * 1079 * @return total accepted HTTP connections 1080 */ 1081 @NonNull 1082 public Long getHttpConnectionsAccepted() { 1083 return this.httpConnectionsAccepted; 1084 } 1085 1086 /** 1087 * Returns the total number of rejected HTTP connections. 1088 * 1089 * @return total rejected HTTP connections 1090 */ 1091 @NonNull 1092 public Long getHttpConnectionsRejected() { 1093 return this.httpConnectionsRejected; 1094 } 1095 1096 /** 1097 * Returns the total number of accepted SSE connections. 1098 * 1099 * @return total accepted SSE connections 1100 */ 1101 @NonNull 1102 public Long getSseConnectionsAccepted() { 1103 return this.sseConnectionsAccepted; 1104 } 1105 1106 /** 1107 * Returns the total number of rejected SSE connections. 1108 * 1109 * @return total rejected SSE connections 1110 */ 1111 @NonNull 1112 public Long getSseConnectionsRejected() { 1113 return this.sseConnectionsRejected; 1114 } 1115 1116 1117 /** 1118 * Returns transport failure counters keyed by server type and failure reason. 1119 * 1120 * @return transport failure counters 1121 */ 1122 @NonNull 1123 public Map<@NonNull TransportFailureKey, @NonNull Long> getTransportFailures() { 1124 return this.transportFailures; 1125 } 1126 1127 /** 1128 * Returns HTTP request read failure counters keyed by failure reason. 1129 * 1130 * @return HTTP request read failure counters 1131 */ 1132 @NonNull 1133 public Map<@NonNull RequestReadFailureKey, @NonNull Long> getHttpRequestReadFailures() { 1134 return this.httpRequestReadFailures; 1135 } 1136 1137 /** 1138 * Returns HTTP request rejection counters keyed by rejection reason. 1139 * 1140 * @return HTTP request rejection counters 1141 */ 1142 @NonNull 1143 public Map<@NonNull RequestRejectionKey, @NonNull Long> getHttpRequestRejections() { 1144 return this.httpRequestRejections; 1145 } 1146 1147 /** 1148 * Returns SSE request read failure counters keyed by failure reason. 1149 * 1150 * @return SSE request read failure counters 1151 */ 1152 @NonNull 1153 public Map<@NonNull RequestReadFailureKey, @NonNull Long> getSseRequestReadFailures() { 1154 return this.sseRequestReadFailures; 1155 } 1156 1157 /** 1158 * Returns SSE request rejection counters keyed by rejection reason. 1159 * 1160 * @return SSE request rejection counters 1161 */ 1162 @NonNull 1163 public Map<@NonNull RequestRejectionKey, @NonNull Long> getSseRequestRejections() { 1164 return this.sseRequestRejections; 1165 } 1166 1167 1168 /** 1169 * Returns HTTP request duration histograms keyed by server route and status class. 1170 * 1171 * @return HTTP request duration histograms 1172 */ 1173 @NonNull 1174 public Map<@NonNull HttpServerRouteStatusKey, @NonNull HistogramSnapshot> getHttpRequestDurations() { 1175 return this.httpRequestDurations; 1176 } 1177 1178 /** 1179 * Returns HTTP handler duration histograms keyed by server route and status class. 1180 * 1181 * @return HTTP handler duration histograms 1182 */ 1183 @NonNull 1184 public Map<@NonNull HttpServerRouteStatusKey, @NonNull HistogramSnapshot> getHttpHandlerDurations() { 1185 return this.httpHandlerDurations; 1186 } 1187 1188 /** 1189 * Returns HTTP time-to-first-byte approximation histograms keyed by server 1190 * route and status class. 1191 * <p> 1192 * The default collector measures from handler start until Soklet begins the 1193 * response-write path. It does not measure the instant at which the first byte 1194 * reaches the network. 1195 * 1196 * @return HTTP response-write-start latency histograms 1197 */ 1198 @NonNull 1199 public Map<@NonNull HttpServerRouteStatusKey, @NonNull HistogramSnapshot> getHttpTimeToFirstByte() { 1200 return this.httpTimeToFirstByte; 1201 } 1202 1203 /** 1204 * Returns HTTP request body size histograms keyed by server route. 1205 * <p> 1206 * Sizes reflect the body as handlers observe it: with request decompression enabled (see 1207 * {@link RequestDecompressionPolicy}), that is the decompressed size, not the wire-compressed size. 1208 * Custom collectors that require the encoded payload size can use 1209 * {@link Request#getEncodedBodySizeInBytes()} from request lifecycle callbacks. 1210 * 1211 * @return HTTP request body size histograms 1212 */ 1213 @NonNull 1214 public Map<@NonNull HttpServerRouteKey, @NonNull HistogramSnapshot> getHttpRequestBodyBytes() { 1215 return this.httpRequestBodyBytes; 1216 } 1217 1218 /** 1219 * Returns HTTP response body size histograms keyed by server route and status class. 1220 * 1221 * @return HTTP response body size histograms 1222 */ 1223 @NonNull 1224 public Map<@NonNull HttpServerRouteStatusKey, @NonNull HistogramSnapshot> getHttpResponseBodyBytes() { 1225 return this.httpResponseBodyBytes; 1226 } 1227 1228 /** @return immutable cumulative admitted HTTP stream counts by route, wire status class and reason */ 1229 @NonNull 1230 public Map<@NonNull HttpResponseStreamTerminationKey, @NonNull Long> getHttpResponseStreamTerminations() { 1231 return this.httpResponseStreamTerminations; 1232 } 1233 1234 @NonNull 1235 private static Map<@NonNull HttpResponseStreamTerminationKey, @NonNull Long> copyStreamTerminations( 1236 @Nullable Map<@NonNull HttpResponseStreamTerminationKey, @NonNull Long> counts) { 1237 if (counts == null || counts.isEmpty()) return Collections.emptyMap(); 1238 Map<HttpResponseStreamTerminationKey, Long> copy = new LinkedHashMap<>(); 1239 counts.forEach((key, value) -> { 1240 requireNonNull(key, "HTTP stream termination key is required."); 1241 requireNonNull(value, "HTTP stream termination count is required."); 1242 if (value < 0L) throw new IllegalArgumentException("HTTP stream termination count must be nonnegative."); 1243 copy.put(key, value); 1244 }); 1245 return Collections.unmodifiableMap(copy); 1246 } 1247 1248 /** 1249 * Returns SSE handshake acceptance counters keyed by route. 1250 * 1251 * @return SSE handshake acceptance counters 1252 */ 1253 @NonNull 1254 public Map<@NonNull SseEventRouteKey, @NonNull Long> getSseHandshakesAccepted() { 1255 return this.sseHandshakesAccepted; 1256 } 1257 1258 /** 1259 * Returns SSE handshake rejection counters keyed by route and failure reason. 1260 * 1261 * @return SSE handshake rejection counters 1262 */ 1263 @NonNull 1264 public Map<@NonNull SseEventRouteHandshakeFailureKey, @NonNull Long> getSseHandshakesRejected() { 1265 return this.sseHandshakesRejected; 1266 } 1267 1268 /** 1269 * Returns SSE event enqueue outcome counters keyed by route and outcome. 1270 * 1271 * @return SSE event enqueue outcome counters 1272 */ 1273 @NonNull 1274 public Map<@NonNull SseEventRouteEnqueueOutcomeKey, @NonNull Long> getSseEventEnqueueOutcomes() { 1275 return this.sseEventEnqueueOutcomes; 1276 } 1277 1278 /** 1279 * Returns SSE comment enqueue outcome counters keyed by route, comment type, and outcome. 1280 * 1281 * @return SSE comment enqueue outcome counters 1282 */ 1283 @NonNull 1284 public Map<@NonNull SseCommentRouteEnqueueOutcomeKey, @NonNull Long> getSseCommentEnqueueOutcomes() { 1285 return this.sseCommentEnqueueOutcomes; 1286 } 1287 1288 /** 1289 * Returns SSE event drop counters keyed by route and drop reason. 1290 * 1291 * @return SSE event drop counters 1292 */ 1293 @NonNull 1294 public Map<@NonNull SseEventRouteDropKey, @NonNull Long> getSseEventDrops() { 1295 return this.sseEventDrops; 1296 } 1297 1298 /** 1299 * Returns SSE comment drop counters keyed by route, comment type, and drop reason. 1300 * 1301 * @return SSE comment drop counters 1302 */ 1303 @NonNull 1304 public Map<@NonNull SseCommentRouteDropKey, @NonNull Long> getSseCommentDrops() { 1305 return this.sseCommentDrops; 1306 } 1307 1308 /** 1309 * Returns SSE time-to-first-event histograms keyed by route. 1310 * 1311 * @return SSE time-to-first-event histograms 1312 */ 1313 @NonNull 1314 public Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> getSseTimeToFirstEvent() { 1315 return this.sseTimeToFirstEvent; 1316 } 1317 1318 /** 1319 * Returns SSE event write duration histograms keyed by route. 1320 * 1321 * @return SSE event write duration histograms 1322 */ 1323 @NonNull 1324 public Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> getSseEventWriteDurations() { 1325 return this.sseEventWriteDurations; 1326 } 1327 1328 /** 1329 * Returns SSE event delivery lag histograms keyed by route. 1330 * 1331 * @return SSE event delivery lag histograms 1332 */ 1333 @NonNull 1334 public Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> getSseEventDeliveryLag() { 1335 return this.sseEventDeliveryLag; 1336 } 1337 1338 /** 1339 * Returns SSE event size histograms keyed by route. 1340 * 1341 * @return SSE event size histograms 1342 */ 1343 @NonNull 1344 public Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> getSseEventSizes() { 1345 return this.sseEventSizes; 1346 } 1347 1348 /** 1349 * Returns SSE queue depth histograms keyed by route. 1350 * 1351 * @return SSE queue depth histograms 1352 */ 1353 @NonNull 1354 public Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> getSseQueueDepth() { 1355 return this.sseQueueDepth; 1356 } 1357 1358 /** 1359 * Returns SSE comment delivery lag histograms keyed by route and comment type. 1360 * 1361 * @return SSE comment delivery lag histograms 1362 */ 1363 @NonNull 1364 public Map<@NonNull SseCommentRouteKey, @NonNull HistogramSnapshot> getSseCommentDeliveryLag() { 1365 return this.sseCommentDeliveryLag; 1366 } 1367 1368 /** 1369 * Returns SSE comment size histograms keyed by route and comment type. 1370 * 1371 * @return SSE comment size histograms 1372 */ 1373 @NonNull 1374 public Map<@NonNull SseCommentRouteKey, @NonNull HistogramSnapshot> getSseCommentSizes() { 1375 return this.sseCommentSizes; 1376 } 1377 1378 /** 1379 * Returns SSE comment queue depth histograms keyed by route and comment type. 1380 * 1381 * @return SSE comment queue depth histograms 1382 */ 1383 @NonNull 1384 public Map<@NonNull SseCommentRouteKey, @NonNull HistogramSnapshot> getSseCommentQueueDepth() { 1385 return this.sseCommentQueueDepth; 1386 } 1387 1388 /** 1389 * Returns SSE stream duration histograms keyed by route and termination reason. 1390 * 1391 * @return SSE stream duration histograms 1392 */ 1393 @NonNull 1394 public Map<@NonNull SseStreamRouteTerminationKey, @NonNull HistogramSnapshot> getSseStreamDurations() { 1395 return this.sseStreamDurations; 1396 } 1397 1398 1399 @NonNull 1400 private static <K, V> Map<K, V> copyOrEmpty(@Nullable Map<K, V> map) { 1401 return map == null ? Map.of() : Map.copyOf(map); 1402 } 1403 1404 /** 1405 * Builder used to construct instances of {@link Snapshot}. 1406 * <p> 1407 * This class is intended for use by a single thread. 1408 * 1409 * @author <a href="https://www.revetkn.com">Mark Allen</a> 1410 */ 1411 @NotThreadSafe 1412 public static final class Builder { 1413 @NonNull 1414 private Long activeRequests; 1415 @NonNull 1416 private Long activeSseStreams; 1417 @NonNull 1418 private McpMetricsSnapshot mcpMetrics; 1419 @NonNull 1420 private Long httpConnectionsAccepted; 1421 @NonNull 1422 private Long httpConnectionsRejected; 1423 @NonNull 1424 private Long sseConnectionsAccepted; 1425 @NonNull 1426 private Long sseConnectionsRejected; 1427 @Nullable 1428 private Map<@NonNull TransportFailureKey, @NonNull Long> transportFailures; 1429 @Nullable 1430 private Map<@NonNull RequestReadFailureKey, @NonNull Long> httpRequestReadFailures; 1431 @Nullable 1432 private Map<@NonNull RequestRejectionKey, @NonNull Long> httpRequestRejections; 1433 @Nullable 1434 private Map<@NonNull RequestReadFailureKey, @NonNull Long> sseRequestReadFailures; 1435 @Nullable 1436 private Map<@NonNull RequestRejectionKey, @NonNull Long> sseRequestRejections; 1437 @Nullable 1438 private Map<@NonNull HttpServerRouteStatusKey, @NonNull HistogramSnapshot> httpRequestDurations; 1439 @Nullable 1440 private Map<@NonNull HttpServerRouteStatusKey, @NonNull HistogramSnapshot> httpHandlerDurations; 1441 @Nullable 1442 private Map<@NonNull HttpServerRouteStatusKey, @NonNull HistogramSnapshot> httpTimeToFirstByte; 1443 @Nullable 1444 private Map<@NonNull HttpServerRouteKey, @NonNull HistogramSnapshot> httpRequestBodyBytes; 1445 @Nullable 1446 private Map<@NonNull HttpServerRouteStatusKey, @NonNull HistogramSnapshot> httpResponseBodyBytes; 1447 @Nullable 1448 private Map<@NonNull HttpResponseStreamTerminationKey, @NonNull Long> httpResponseStreamTerminations; 1449 @Nullable 1450 private Map<@NonNull SseEventRouteKey, @NonNull Long> sseHandshakesAccepted; 1451 @Nullable 1452 private Map<@NonNull SseEventRouteHandshakeFailureKey, @NonNull Long> sseHandshakesRejected; 1453 @Nullable 1454 private Map<@NonNull SseEventRouteEnqueueOutcomeKey, @NonNull Long> sseEventEnqueueOutcomes; 1455 @Nullable 1456 private Map<@NonNull SseCommentRouteEnqueueOutcomeKey, @NonNull Long> sseCommentEnqueueOutcomes; 1457 @Nullable 1458 private Map<@NonNull SseEventRouteDropKey, @NonNull Long> sseEventDrops; 1459 @Nullable 1460 private Map<@NonNull SseCommentRouteDropKey, @NonNull Long> sseCommentDrops; 1461 @Nullable 1462 private Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> sseTimeToFirstEvent; 1463 @Nullable 1464 private Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> sseEventWriteDurations; 1465 @Nullable 1466 private Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> sseEventDeliveryLag; 1467 @Nullable 1468 private Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> sseEventSizes; 1469 @Nullable 1470 private Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> sseQueueDepth; 1471 @Nullable 1472 private Map<@NonNull SseCommentRouteKey, @NonNull HistogramSnapshot> sseCommentDeliveryLag; 1473 @Nullable 1474 private Map<@NonNull SseCommentRouteKey, @NonNull HistogramSnapshot> sseCommentSizes; 1475 @Nullable 1476 private Map<@NonNull SseCommentRouteKey, @NonNull HistogramSnapshot> sseCommentQueueDepth; 1477 @Nullable 1478 private Map<@NonNull SseStreamRouteTerminationKey, @NonNull HistogramSnapshot> sseStreamDurations; 1479 1480 private Builder() { 1481 this.activeRequests = 0L; 1482 this.activeSseStreams = 0L; 1483 this.mcpMetrics = McpMetricsSnapshot.emptyInstance(); 1484 this.httpConnectionsAccepted = 0L; 1485 this.httpConnectionsRejected = 0L; 1486 this.sseConnectionsAccepted = 0L; 1487 this.sseConnectionsRejected = 0L; 1488 } 1489 1490 /** 1491 * Sets the active HTTP request count. 1492 * 1493 * @param activeRequests the active HTTP request count 1494 * @return this builder 1495 */ 1496 @NonNull 1497 public Builder activeRequests(@NonNull Long activeRequests) { 1498 this.activeRequests = requireNonNull(activeRequests); 1499 return this; 1500 } 1501 1502 /** 1503 * Sets the active server-sent event stream count. 1504 * 1505 * @param activeSseStreams the active SSE stream count 1506 * @return this builder 1507 */ 1508 @NonNull 1509 public Builder activeSseStreams(@NonNull Long activeSseStreams) { 1510 this.activeSseStreams = requireNonNull(activeSseStreams); 1511 return this; 1512 } 1513 1514 /** 1515 * Sets the immutable MCP metrics aggregate. 1516 * 1517 * @param mcpMetrics MCP metrics aggregate 1518 * @return this builder 1519 */ 1520 @NonNull 1521 public Builder mcpMetrics(@NonNull McpMetricsSnapshot mcpMetrics) { 1522 this.mcpMetrics = requireNonNull(mcpMetrics); 1523 return this; 1524 } 1525 1526 1527 /** 1528 * Sets the total number of accepted HTTP connections. 1529 * 1530 * @param httpConnectionsAccepted total accepted HTTP connections 1531 * @return this builder 1532 */ 1533 @NonNull 1534 public Builder httpConnectionsAccepted(@NonNull Long httpConnectionsAccepted) { 1535 this.httpConnectionsAccepted = requireNonNull(httpConnectionsAccepted); 1536 return this; 1537 } 1538 1539 /** 1540 * Sets the total number of rejected HTTP connections. 1541 * 1542 * @param httpConnectionsRejected total rejected HTTP connections 1543 * @return this builder 1544 */ 1545 @NonNull 1546 public Builder httpConnectionsRejected(@NonNull Long httpConnectionsRejected) { 1547 this.httpConnectionsRejected = requireNonNull(httpConnectionsRejected); 1548 return this; 1549 } 1550 1551 /** 1552 * Sets the total number of accepted SSE connections. 1553 * 1554 * @param sseConnectionsAccepted total accepted SSE connections 1555 * @return this builder 1556 */ 1557 @NonNull 1558 public Builder sseConnectionsAccepted(@NonNull Long sseConnectionsAccepted) { 1559 this.sseConnectionsAccepted = requireNonNull(sseConnectionsAccepted); 1560 return this; 1561 } 1562 1563 /** 1564 * Sets the total number of rejected SSE connections. 1565 * 1566 * @param sseConnectionsRejected total rejected SSE connections 1567 * @return this builder 1568 */ 1569 @NonNull 1570 public Builder sseConnectionsRejected(@NonNull Long sseConnectionsRejected) { 1571 this.sseConnectionsRejected = requireNonNull(sseConnectionsRejected); 1572 return this; 1573 } 1574 1575 1576 /** 1577 * Replaces all previously configured transport failure counters keyed by server type and failure reason. 1578 * <p> 1579 * Passing {@code null} or an empty map clears these counters; the default is an empty map. 1580 * 1581 * @param transportFailures the replacement transport failure counters, or {@code null} to clear them 1582 * @return this builder 1583 */ 1584 @NonNull 1585 public Builder transportFailures( 1586 @Nullable Map<@NonNull TransportFailureKey, @NonNull Long> transportFailures) { 1587 this.transportFailures = transportFailures; 1588 return this; 1589 } 1590 1591 /** 1592 * Replaces all previously configured HTTP request read failure counters keyed by failure reason. 1593 * <p> 1594 * Passing {@code null} or an empty map clears these counters; the default is an empty map. 1595 * 1596 * @param httpRequestReadFailures the replacement HTTP request read failure counters, or {@code null} to clear them 1597 * @return this builder 1598 */ 1599 @NonNull 1600 public Builder httpRequestReadFailures( 1601 @Nullable Map<@NonNull RequestReadFailureKey, @NonNull Long> httpRequestReadFailures) { 1602 this.httpRequestReadFailures = httpRequestReadFailures; 1603 return this; 1604 } 1605 1606 /** 1607 * Replaces all previously configured HTTP request rejection counters keyed by rejection reason. 1608 * <p> 1609 * Passing {@code null} or an empty map clears these counters; the default is an empty map. 1610 * 1611 * @param httpRequestRejections the replacement HTTP request rejection counters, or {@code null} to clear them 1612 * @return this builder 1613 */ 1614 @NonNull 1615 public Builder httpRequestRejections( 1616 @Nullable Map<@NonNull RequestRejectionKey, @NonNull Long> httpRequestRejections) { 1617 this.httpRequestRejections = httpRequestRejections; 1618 return this; 1619 } 1620 1621 /** 1622 * Replaces all previously configured SSE request read failure counters keyed by failure reason. 1623 * <p> 1624 * Passing {@code null} or an empty map clears these counters; the default is an empty map. 1625 * 1626 * @param sseRequestReadFailures the replacement SSE request read failure counters, or {@code null} to clear them 1627 * @return this builder 1628 */ 1629 @NonNull 1630 public Builder sseRequestReadFailures( 1631 @Nullable Map<@NonNull RequestReadFailureKey, @NonNull Long> sseRequestReadFailures) { 1632 this.sseRequestReadFailures = sseRequestReadFailures; 1633 return this; 1634 } 1635 1636 /** 1637 * Replaces all previously configured SSE request rejection counters keyed by rejection reason. 1638 * <p> 1639 * Passing {@code null} or an empty map clears these counters; the default is an empty map. 1640 * 1641 * @param sseRequestRejections the replacement SSE request rejection counters, or {@code null} to clear them 1642 * @return this builder 1643 */ 1644 @NonNull 1645 public Builder sseRequestRejections( 1646 @Nullable Map<@NonNull RequestRejectionKey, @NonNull Long> sseRequestRejections) { 1647 this.sseRequestRejections = sseRequestRejections; 1648 return this; 1649 } 1650 1651 1652 /** 1653 * Replaces all previously configured HTTP request duration histograms keyed by server route and status class. 1654 * <p> 1655 * Passing {@code null} or an empty map clears these histograms; the default is an empty map. 1656 * 1657 * @param httpRequestDurations the replacement HTTP request duration histograms, or {@code null} to clear them 1658 * @return this builder 1659 */ 1660 @NonNull 1661 public Builder httpRequestDurations( 1662 @Nullable Map<@NonNull HttpServerRouteStatusKey, @NonNull HistogramSnapshot> httpRequestDurations) { 1663 this.httpRequestDurations = httpRequestDurations; 1664 return this; 1665 } 1666 1667 /** 1668 * Replaces all previously configured HTTP handler duration histograms keyed by server route and status class. 1669 * <p> 1670 * Passing {@code null} or an empty map clears these histograms; the default is an empty map. 1671 * 1672 * @param httpHandlerDurations the replacement HTTP handler duration histograms, or {@code null} to clear them 1673 * @return this builder 1674 */ 1675 @NonNull 1676 public Builder httpHandlerDurations( 1677 @Nullable Map<@NonNull HttpServerRouteStatusKey, @NonNull HistogramSnapshot> httpHandlerDurations) { 1678 this.httpHandlerDurations = httpHandlerDurations; 1679 return this; 1680 } 1681 1682 /** 1683 * Replaces all previously configured HTTP time-to-first-byte approximation 1684 * histograms keyed by server route and status class. The default collector 1685 * measures from handler start until Soklet begins the response-write path, 1686 * not until the first byte reaches the network. 1687 * <p> 1688 * Passing {@code null} or an empty map clears these histograms; the default is an empty map. 1689 * 1690 * @param httpTimeToFirstByte the replacement HTTP time-to-first-byte histograms, or {@code null} to clear them 1691 * @return this builder 1692 */ 1693 @NonNull 1694 public Builder httpTimeToFirstByte( 1695 @Nullable Map<@NonNull HttpServerRouteStatusKey, @NonNull HistogramSnapshot> httpTimeToFirstByte) { 1696 this.httpTimeToFirstByte = httpTimeToFirstByte; 1697 return this; 1698 } 1699 1700 /** 1701 * Replaces all previously configured HTTP request body size histograms keyed by server route. 1702 * <p> 1703 * Passing {@code null} or an empty map clears these histograms; the default is an empty map. 1704 * 1705 * @param httpRequestBodyBytes the replacement HTTP request body size histograms, or {@code null} to clear them 1706 * @return this builder 1707 */ 1708 @NonNull 1709 public Builder httpRequestBodyBytes( 1710 @Nullable Map<@NonNull HttpServerRouteKey, @NonNull HistogramSnapshot> httpRequestBodyBytes) { 1711 this.httpRequestBodyBytes = httpRequestBodyBytes; 1712 return this; 1713 } 1714 1715 /** 1716 * Replaces all previously configured HTTP response body size histograms keyed by server route and status class. 1717 * <p> 1718 * Passing {@code null} or an empty map clears these histograms; the default is an empty map. 1719 * 1720 * @param httpResponseBodyBytes the replacement HTTP response body size histograms, or {@code null} to clear them 1721 * @return this builder 1722 */ 1723 @NonNull 1724 public Builder httpResponseBodyBytes( 1725 @Nullable Map<@NonNull HttpServerRouteStatusKey, @NonNull HistogramSnapshot> httpResponseBodyBytes) { 1726 this.httpResponseBodyBytes = httpResponseBodyBytes; 1727 return this; 1728 } 1729 1730 /** 1731 * Replaces admitted HTTP stream termination counts with a defensive copy. Zero counts are retained. 1732 * @param httpResponseStreamTerminations counts, or {@code null} or empty to clear; keys and values 1733 * must be nonnull and counts nonnegative 1734 * @return this builder 1735 */ 1736 @NonNull 1737 public Builder httpResponseStreamTerminations( 1738 @Nullable Map<@NonNull HttpResponseStreamTerminationKey, @NonNull Long> httpResponseStreamTerminations) { 1739 this.httpResponseStreamTerminations = copyStreamTerminations(httpResponseStreamTerminations); 1740 return this; 1741 } 1742 1743 /** 1744 * Replaces all previously configured SSE handshake acceptance counters keyed by route. 1745 * <p> 1746 * Passing {@code null} or an empty map clears these counters; the default is an empty map. 1747 * 1748 * @param sseHandshakesAccepted the replacement SSE handshake acceptance counters, or {@code null} to clear them 1749 * @return this builder 1750 */ 1751 @NonNull 1752 public Builder sseHandshakesAccepted( 1753 @Nullable Map<@NonNull SseEventRouteKey, @NonNull Long> sseHandshakesAccepted) { 1754 this.sseHandshakesAccepted = sseHandshakesAccepted; 1755 return this; 1756 } 1757 1758 /** 1759 * Replaces all previously configured SSE handshake rejection counters keyed by route and failure reason. 1760 * <p> 1761 * Passing {@code null} or an empty map clears these counters; the default is an empty map. 1762 * 1763 * @param sseHandshakesRejected the replacement SSE handshake rejection counters, or {@code null} to clear them 1764 * @return this builder 1765 */ 1766 @NonNull 1767 public Builder sseHandshakesRejected( 1768 @Nullable Map<@NonNull SseEventRouteHandshakeFailureKey, @NonNull Long> sseHandshakesRejected) { 1769 this.sseHandshakesRejected = sseHandshakesRejected; 1770 return this; 1771 } 1772 1773 /** 1774 * Replaces all previously configured SSE event enqueue outcome counters keyed by route and outcome. 1775 * <p> 1776 * Passing {@code null} or an empty map clears these counters; the default is an empty map. 1777 * 1778 * @param sseEventEnqueueOutcomes the replacement SSE event enqueue outcome counters, or {@code null} to clear them 1779 * @return this builder 1780 */ 1781 @NonNull 1782 public Builder sseEventEnqueueOutcomes( 1783 @Nullable Map<@NonNull SseEventRouteEnqueueOutcomeKey, @NonNull Long> sseEventEnqueueOutcomes) { 1784 this.sseEventEnqueueOutcomes = sseEventEnqueueOutcomes; 1785 return this; 1786 } 1787 1788 /** 1789 * Replaces all previously configured SSE comment enqueue outcome counters keyed by route, comment type, and outcome. 1790 * <p> 1791 * Passing {@code null} or an empty map clears these counters; the default is an empty map. 1792 * 1793 * @param sseCommentEnqueueOutcomes the replacement SSE comment enqueue outcome counters, or {@code null} to clear them 1794 * @return this builder 1795 */ 1796 @NonNull 1797 public Builder sseCommentEnqueueOutcomes( 1798 @Nullable Map<@NonNull SseCommentRouteEnqueueOutcomeKey, @NonNull Long> sseCommentEnqueueOutcomes) { 1799 this.sseCommentEnqueueOutcomes = sseCommentEnqueueOutcomes; 1800 return this; 1801 } 1802 1803 /** 1804 * Replaces all previously configured SSE event drop counters keyed by route and drop reason. 1805 * <p> 1806 * Passing {@code null} or an empty map clears these counters; the default is an empty map. 1807 * 1808 * @param sseEventDrops the replacement SSE event drop counters, or {@code null} to clear them 1809 * @return this builder 1810 */ 1811 @NonNull 1812 public Builder sseEventDrops( 1813 @Nullable Map<@NonNull SseEventRouteDropKey, @NonNull Long> sseEventDrops) { 1814 this.sseEventDrops = sseEventDrops; 1815 return this; 1816 } 1817 1818 /** 1819 * Replaces all previously configured SSE comment drop counters keyed by route, comment type, and drop reason. 1820 * <p> 1821 * Passing {@code null} or an empty map clears these counters; the default is an empty map. 1822 * 1823 * @param sseCommentDrops the replacement SSE comment drop counters, or {@code null} to clear them 1824 * @return this builder 1825 */ 1826 @NonNull 1827 public Builder sseCommentDrops( 1828 @Nullable Map<@NonNull SseCommentRouteDropKey, @NonNull Long> sseCommentDrops) { 1829 this.sseCommentDrops = sseCommentDrops; 1830 return this; 1831 } 1832 1833 /** 1834 * Replaces all previously configured SSE time-to-first-event histograms keyed by route. 1835 * <p> 1836 * Passing {@code null} or an empty map clears these histograms; the default is an empty map. 1837 * 1838 * @param sseTimeToFirstEvent the replacement SSE time-to-first-event histograms, or {@code null} to clear them 1839 * @return this builder 1840 */ 1841 @NonNull 1842 public Builder sseTimeToFirstEvent( 1843 @Nullable Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> sseTimeToFirstEvent) { 1844 this.sseTimeToFirstEvent = sseTimeToFirstEvent; 1845 return this; 1846 } 1847 1848 /** 1849 * Replaces all previously configured SSE event write duration histograms keyed by route. 1850 * <p> 1851 * Passing {@code null} or an empty map clears these histograms; the default is an empty map. 1852 * 1853 * @param sseEventWriteDurations the replacement SSE event write duration histograms, or {@code null} to clear them 1854 * @return this builder 1855 */ 1856 @NonNull 1857 public Builder sseEventWriteDurations( 1858 @Nullable Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> sseEventWriteDurations) { 1859 this.sseEventWriteDurations = sseEventWriteDurations; 1860 return this; 1861 } 1862 1863 /** 1864 * Replaces all previously configured SSE event delivery lag histograms keyed by route. 1865 * <p> 1866 * Passing {@code null} or an empty map clears these histograms; the default is an empty map. 1867 * 1868 * @param sseEventDeliveryLag the replacement SSE event delivery lag histograms, or {@code null} to clear them 1869 * @return this builder 1870 */ 1871 @NonNull 1872 public Builder sseEventDeliveryLag( 1873 @Nullable Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> sseEventDeliveryLag) { 1874 this.sseEventDeliveryLag = sseEventDeliveryLag; 1875 return this; 1876 } 1877 1878 /** 1879 * Replaces all previously configured SSE event size histograms keyed by route. 1880 * <p> 1881 * Passing {@code null} or an empty map clears these histograms; the default is an empty map. 1882 * 1883 * @param sseEventSizes the replacement SSE event size histograms, or {@code null} to clear them 1884 * @return this builder 1885 */ 1886 @NonNull 1887 public Builder sseEventSizes( 1888 @Nullable Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> sseEventSizes) { 1889 this.sseEventSizes = sseEventSizes; 1890 return this; 1891 } 1892 1893 /** 1894 * Replaces all previously configured SSE queue depth histograms keyed by route. 1895 * <p> 1896 * Passing {@code null} or an empty map clears these histograms; the default is an empty map. 1897 * 1898 * @param sseQueueDepth the replacement SSE queue depth histograms, or {@code null} to clear them 1899 * @return this builder 1900 */ 1901 @NonNull 1902 public Builder sseQueueDepth( 1903 @Nullable Map<@NonNull SseEventRouteKey, @NonNull HistogramSnapshot> sseQueueDepth) { 1904 this.sseQueueDepth = sseQueueDepth; 1905 return this; 1906 } 1907 1908 /** 1909 * Replaces all previously configured SSE comment delivery lag histograms keyed by route and comment type. 1910 * <p> 1911 * Passing {@code null} or an empty map clears these histograms; the default is an empty map. 1912 * 1913 * @param sseCommentDeliveryLag the replacement SSE comment delivery lag histograms, or {@code null} to clear them 1914 * @return this builder 1915 */ 1916 @NonNull 1917 public Builder sseCommentDeliveryLag( 1918 @Nullable Map<@NonNull SseCommentRouteKey, @NonNull HistogramSnapshot> sseCommentDeliveryLag) { 1919 this.sseCommentDeliveryLag = sseCommentDeliveryLag; 1920 return this; 1921 } 1922 1923 /** 1924 * Replaces all previously configured SSE comment size histograms keyed by route and comment type. 1925 * <p> 1926 * Passing {@code null} or an empty map clears these histograms; the default is an empty map. 1927 * 1928 * @param sseCommentSizes the replacement SSE comment size histograms, or {@code null} to clear them 1929 * @return this builder 1930 */ 1931 @NonNull 1932 public Builder sseCommentSizes( 1933 @Nullable Map<@NonNull SseCommentRouteKey, @NonNull HistogramSnapshot> sseCommentSizes) { 1934 this.sseCommentSizes = sseCommentSizes; 1935 return this; 1936 } 1937 1938 /** 1939 * Replaces all previously configured SSE comment queue depth histograms keyed by route and comment type. 1940 * <p> 1941 * Passing {@code null} or an empty map clears these histograms; the default is an empty map. 1942 * 1943 * @param sseCommentQueueDepth the replacement SSE comment queue depth histograms, or {@code null} to clear them 1944 * @return this builder 1945 */ 1946 @NonNull 1947 public Builder sseCommentQueueDepth( 1948 @Nullable Map<@NonNull SseCommentRouteKey, @NonNull HistogramSnapshot> sseCommentQueueDepth) { 1949 this.sseCommentQueueDepth = sseCommentQueueDepth; 1950 return this; 1951 } 1952 1953 /** 1954 * Replaces all previously configured SSE stream duration histograms keyed by route and termination reason. 1955 * <p> 1956 * Passing {@code null} or an empty map clears these histograms; the default is an empty map. 1957 * 1958 * @param sseStreamDurations the replacement SSE stream duration histograms, or {@code null} to clear them 1959 * @return this builder 1960 */ 1961 @NonNull 1962 public Builder sseStreamDurations( 1963 @Nullable Map<@NonNull SseStreamRouteTerminationKey, @NonNull HistogramSnapshot> sseStreamDurations) { 1964 this.sseStreamDurations = sseStreamDurations; 1965 return this; 1966 } 1967 1968 1969 /** 1970 * Builds a {@link Snapshot} instance. 1971 * 1972 * @return the built snapshot 1973 */ 1974 @NonNull 1975 public Snapshot build() { 1976 return new Snapshot(this); 1977 } 1978 } 1979 } 1980 1981 /** 1982 * A thread-safe histogram with fixed bucket boundaries. 1983 * <p> 1984 * Negative values are ignored. Buckets use inclusive upper bounds, and snapshots include 1985 * an overflow bucket represented by a {@link HistogramSnapshot#getBucketBoundary(Integer)} of 1986 * {@link Long#MAX_VALUE}. 1987 * The sum uses floating-point accumulation and can grow beyond the signed 1988 * {@code long} range. Rounding depends on magnitude and accumulation order; 1989 * very small additions to a large total can be rounded away. 1990 * <p> 1991 * A captured snapshot's sample count equals its final cumulative bucket. 1992 * Recording, snapshot reads and reset remain concurrent observations: 1993 * buckets, sum and min/max do not form an atomic transaction. Records 1994 * overlapping reset may be discarded or represented partly across those 1995 * fields. Coordinate writers with reset for an exact observation-window 1996 * boundary; previously captured snapshots remain immutable. 1997 * 1998 * @author <a href="https://www.revetkn.com">Mark Allen</a> 1999 */ 2000 @ThreadSafe 2001 final class Histogram { 2002 private final long @NonNull [] bucketBoundaries; 2003 @NonNull 2004 private final LongAdder @NonNull [] bucketCounts; 2005 @NonNull 2006 private final DoubleAdder sum; 2007 @NonNull 2008 private final AtomicLong min; 2009 @NonNull 2010 private final AtomicLong max; 2011 2012 /** 2013 * Creates a histogram with the provided bucket boundaries. 2014 * 2015 * @param bucketBoundaries inclusive upper bounds for buckets 2016 */ 2017 public Histogram(long @NonNull [] bucketBoundaries) { 2018 requireNonNull(bucketBoundaries); 2019 2020 this.bucketBoundaries = bucketBoundaries.clone(); 2021 Arrays.sort(this.bucketBoundaries); 2022 this.bucketCounts = new LongAdder[this.bucketBoundaries.length + 1]; 2023 for (int i = 0; i < this.bucketCounts.length; i++) 2024 this.bucketCounts[i] = new LongAdder(); 2025 this.sum = new DoubleAdder(); 2026 this.min = new AtomicLong(Long.MAX_VALUE); 2027 this.max = new AtomicLong(Long.MIN_VALUE); 2028 } 2029 2030 /** 2031 * Records a value into the histogram. 2032 * 2033 * @param value the value to record 2034 */ 2035 public void record(@NonNull Long value) { 2036 record(requireNonNull(value).longValue()); 2037 } 2038 2039 // Internal collectors retain the allocation-free primitive path. 2040 void record(long value) { 2041 if (value < 0) 2042 return; 2043 2044 this.sum.add((double) value); 2045 updateMin(value); 2046 updateMax(value); 2047 2048 int bucketIndex = bucketIndex(value); 2049 this.bucketCounts[bucketIndex].increment(); 2050 } 2051 2052 /** 2053 * Captures an immutable snapshot of the histogram. 2054 * Its count equals the final captured cumulative bucket, including 2055 * during concurrent recording or reset. Other fields may reflect 2056 * different instants; see the class concurrency contract. 2057 * 2058 * @return the histogram snapshot 2059 */ 2060 @NonNull 2061 public HistogramSnapshot snapshot() { 2062 long[] boundariesWithOverflow = Arrays.copyOf(this.bucketBoundaries, this.bucketBoundaries.length + 1); 2063 boundariesWithOverflow[boundariesWithOverflow.length - 1] = Long.MAX_VALUE; 2064 2065 long[] cumulativeCounts = new long[this.bucketCounts.length]; 2066 long cumulative = 0; 2067 for (int i = 0; i < this.bucketCounts.length; i++) { 2068 cumulative += this.bucketCounts[i].sum(); 2069 cumulativeCounts[i] = cumulative; 2070 } 2071 2072 long countSnapshot = cumulative; 2073 double sumSnapshot = this.sum.sum(); 2074 long minSnapshot = this.min.get(); 2075 long maxSnapshot = this.max.get(); 2076 2077 // Long.MAX_VALUE is both the empty sentinel and a valid sample. 2078 if (minSnapshot == Long.MAX_VALUE && countSnapshot == 0) 2079 minSnapshot = 0; 2080 if (maxSnapshot == Long.MIN_VALUE) 2081 maxSnapshot = 0; 2082 2083 return new HistogramSnapshot(boundariesWithOverflow, cumulativeCounts, countSnapshot, sumSnapshot, minSnapshot, maxSnapshot); 2084 } 2085 2086 /** 2087 * Resets all bucket counts, the sum and min/max values. 2088 * This does not establish an atomic boundary with concurrent records 2089 * or snapshots. With writers quiescent, all histogram state is cleared. 2090 */ 2091 public void reset() { 2092 this.sum.reset(); 2093 this.min.set(Long.MAX_VALUE); 2094 this.max.set(Long.MIN_VALUE); 2095 for (LongAdder bucket : this.bucketCounts) 2096 bucket.reset(); 2097 } 2098 2099 private int bucketIndex(long value) { 2100 for (int i = 0; i < this.bucketBoundaries.length; i++) 2101 if (value <= this.bucketBoundaries[i]) 2102 return i; 2103 2104 return this.bucketBoundaries.length; 2105 } 2106 2107 private void updateMin(long value) { 2108 long current; 2109 while (value < (current = this.min.get())) { 2110 if (this.min.compareAndSet(current, value)) 2111 break; 2112 } 2113 } 2114 2115 private void updateMax(long value) { 2116 long current; 2117 while (value > (current = this.max.get())) { 2118 if (this.max.compareAndSet(current, value)) 2119 break; 2120 } 2121 } 2122 } 2123 2124 /** 2125 * Immutable snapshot of a {@link Histogram}. 2126 * <p> 2127 * Bucket counts are cumulative. Boundaries are inclusive upper bounds, and the final 2128 * boundary is {@link Long#MAX_VALUE} to represent the overflow bucket. Units are the same 2129 * as values passed to {@link Histogram#record(Long)}. 2130 * The sum is an approximate floating-point total; counts, boundaries and 2131 * min/max remain integer values. All public scalar values and inputs are 2132 * nonnull references. Constructor bucket lists are defensively copied. 2133 * 2134 * @author <a href="https://www.revetkn.com">Mark Allen</a> 2135 */ 2136 @ThreadSafe 2137 final class HistogramSnapshot { 2138 private final long @NonNull [] bucketBoundaries; 2139 private final long @NonNull [] bucketCumulativeCounts; 2140 private final long count; 2141 private final double sum; 2142 private final long min; 2143 private final long max; 2144 2145 /** 2146 * Creates an immutable histogram snapshot. 2147 * 2148 * @param bucketBoundaries inclusive upper bounds for buckets, including overflow 2149 * @param bucketCumulativeCounts cumulative counts for each bucket 2150 * @param count total number of samples recorded 2151 * @param sum finite, nonnegative floating-point sum of recorded values 2152 * @param min smallest recorded value (or 0 if none) 2153 * @param max largest recorded value (or 0 if none) 2154 * @throws NullPointerException if an argument or bucket-list element is null 2155 * @throws IllegalArgumentException if the bucket lists differ in size, or the sum is not finite and nonnegative 2156 */ 2157 public HistogramSnapshot(@NonNull List<@NonNull Long> bucketBoundaries, 2158 @NonNull List<@NonNull Long> bucketCumulativeCounts, 2159 @NonNull Long count, @NonNull Double sum, 2160 @NonNull Long min, @NonNull Long max) { 2161 this(primitiveValues(bucketBoundaries), primitiveValues(bucketCumulativeCounts), 2162 requireNonNull(count), requireNonNull(sum), requireNonNull(min), requireNonNull(max)); 2163 } 2164 2165 // Owns arrays captured by Histogram or copied from the public constructor's lists. 2166 private HistogramSnapshot(long @NonNull [] bucketBoundaries, 2167 long @NonNull [] bucketCumulativeCounts, 2168 long count, double sum, long min, long max) { 2169 requireNonNull(bucketBoundaries); 2170 requireNonNull(bucketCumulativeCounts); 2171 2172 if (bucketBoundaries.length != bucketCumulativeCounts.length) 2173 throw new IllegalArgumentException("Bucket boundaries and cumulative counts must be the same length"); 2174 if (!Double.isFinite(sum) || sum < 0D) 2175 throw new IllegalArgumentException("Histogram sum must be finite and nonnegative"); 2176 2177 this.bucketBoundaries = bucketBoundaries; 2178 this.bucketCumulativeCounts = bucketCumulativeCounts; 2179 this.count = count; 2180 this.sum = sum == 0D ? 0D : sum; 2181 this.min = min; 2182 this.max = max; 2183 } 2184 2185 private static long @NonNull [] primitiveValues(@NonNull List<@NonNull Long> values) { 2186 requireNonNull(values); 2187 long[] result = new long[values.size()]; 2188 for (int index = 0; index < result.length; index++) 2189 result[index] = requireNonNull(values.get(index)); 2190 return result; 2191 } 2192 2193 /** 2194 * Number of histogram buckets, including the overflow bucket. 2195 * 2196 * @return the bucket count 2197 */ 2198 @NonNull 2199 public Integer getBucketCount() { 2200 return this.bucketBoundaries.length; 2201 } 2202 2203 /** 2204 * The inclusive upper bound for the bucket at the given index. 2205 * 2206 * @param index the bucket index 2207 * @return the bucket boundary 2208 */ 2209 @NonNull 2210 public Long getBucketBoundary(@NonNull Integer index) { 2211 return this.bucketBoundaries[requireNonNull(index)]; 2212 } 2213 2214 /** 2215 * The cumulative count for the bucket at the given index. 2216 * 2217 * @param index the bucket index 2218 * @return the cumulative count 2219 */ 2220 @NonNull 2221 public Long getBucketCumulativeCount(@NonNull Integer index) { 2222 return this.bucketCumulativeCounts[requireNonNull(index)]; 2223 } 2224 2225 /** 2226 * Total number of recorded values. 2227 * For snapshots captured by {@link Histogram#snapshot()}, this equals 2228 * the final cumulative bucket. Independently constructed snapshots 2229 * retain the count supplied to their constructor. 2230 * 2231 * @return the count 2232 */ 2233 @NonNull 2234 public Long getCount() { 2235 return this.count; 2236 } 2237 2238 /** 2239 * Approximate floating-point sum of recorded values, in their original units. 2240 * Rounding can lose small additions to a large total and can depend on 2241 * concurrent accumulation order. This is an operational metric, not 2242 * an exact-accounting total. Empty histograms return {@code 0.0}. 2243 * 2244 * @return the finite, nonnegative sum without signed-long saturation 2245 */ 2246 @NonNull 2247 public Double getSum() { 2248 return this.sum; 2249 } 2250 2251 /** 2252 * Smallest recorded value, or 0 if no values were recorded. 2253 * 2254 * @return the minimum value 2255 */ 2256 @NonNull 2257 public Long getMin() { 2258 return this.min; 2259 } 2260 2261 /** 2262 * Largest recorded value, or 0 if no values were recorded. 2263 * 2264 * @return the maximum value 2265 */ 2266 @NonNull 2267 public Long getMax() { 2268 return this.max; 2269 } 2270 2271 /** 2272 * Returns an approximate percentile based on bucket boundaries. 2273 * 2274 * @param percentile percentile between 0 and 100 2275 * @return the approximated percentile value 2276 */ 2277 @NonNull 2278 public Long getPercentile(@NonNull Double percentile) { 2279 requireNonNull(percentile); 2280 if (percentile <= 0.0) 2281 return this.min; 2282 if (percentile >= 100.0) 2283 return this.max; 2284 if (this.count == 0) 2285 return 0L; 2286 2287 long threshold = (long) Math.ceil((percentile / 100.0) * this.count); 2288 2289 for (int i = 0; i < this.bucketCumulativeCounts.length; i++) { 2290 if (this.bucketCumulativeCounts[i] < threshold) 2291 continue; 2292 2293 long boundary = this.bucketBoundaries[i]; 2294 return boundary == Long.MAX_VALUE ? this.max : boundary; 2295 } 2296 2297 return this.bucketBoundaries[this.bucketBoundaries.length - 1]; 2298 } 2299 2300 /** 2301 * Returns a diagnostic summary of this histogram snapshot. 2302 * 2303 * @return histogram summary 2304 */ 2305 @Override 2306 @NonNull 2307 public String toString() { 2308 return String.format(Locale.ROOT, "%s{count=%d, min=%d, max=%d, sum=%s, bucketBoundaries=%s}", 2309 getClass().getSimpleName(), this.count, this.min, this.max, this.sum, Arrays.toString(this.bucketBoundaries)); 2310 } 2311 } 2312 2313 /** 2314 * Low-level server transport failure reasons. 2315 * 2316 * <p> 2317 * This type may gain reviewed constants in Soklet 4.x; use a forward-compatible default when switching over its values. 2318 * 2319 * @author <a href="https://www.revetkn.com">Mark Allen</a> 2320 */ 2321 enum TransportFailureReason { 2322 /** 2323 * A request header/body read timed out. 2324 */ 2325 REQUEST_READ_TIMEOUT, 2326 /** 2327 * A request exceeded configured transport limits. 2328 */ 2329 REQUEST_TOO_LARGE, 2330 /** 2331 * A request could not be parsed by the transport. 2332 */ 2333 MALFORMED_REQUEST, 2334 /** 2335 * A socket read failed. 2336 */ 2337 READ_ERROR, 2338 /** 2339 * A response write failed. 2340 */ 2341 WRITE_ERROR, 2342 /** 2343 * A non-streaming response made no write progress before its idle timeout. 2344 */ 2345 RESPONSE_WRITE_IDLE_TIMEOUT, 2346 /** 2347 * A response-ready callback failed before the response could be written. 2348 */ 2349 RESPONSE_READY_ERROR, 2350 /** 2351 * A request-timeout callback failed. 2352 */ 2353 REQUEST_READ_TIMEOUT_ERROR, 2354 /** 2355 * A response-write-idle-timeout callback failed. 2356 */ 2357 RESPONSE_WRITE_IDLE_TIMEOUT_ERROR, 2358 /** 2359 * The listening socket failed while attempting to accept a connection. 2360 */ 2361 ACCEPT_LOOP_ERROR, 2362 /** 2363 * A successfully accepted socket could not be handed off to a connection event loop before request handling began. 2364 */ 2365 CONNECTION_SETUP_ERROR, 2366 /** 2367 * A transport event-loop task failed. 2368 */ 2369 TASK_ERROR, 2370 /** 2371 * A timeout scheduler task failed. 2372 */ 2373 TIMEOUT_TASK_ERROR, 2374 /** 2375 * A selection-key dispatch failed. 2376 */ 2377 SELECTION_KEY_ERROR, 2378 /** 2379 * A connection registration failed. 2380 */ 2381 REGISTER_ERROR, 2382 /** 2383 * A socket write made no progress before its timeout. 2384 */ 2385 WRITE_TIMEOUT, 2386 /** 2387 * A transport event-loop terminated after an unrecoverable error. 2388 */ 2389 EVENT_LOOP_TERMINATED, 2390 /** 2391 * The transport reported a failure that Soklet does not classify. 2392 */ 2393 UNKNOWN 2394 } 2395 2396 /** 2397 * Indicates whether a request was matched to a {@link ResourcePathDeclaration}. 2398 * 2399 * <p> 2400 * This type may gain reviewed constants in Soklet 4.x; use a forward-compatible default when switching over its values. 2401 * 2402 * @author <a href="https://www.revetkn.com">Mark Allen</a> 2403 */ 2404 enum RouteType { 2405 /** 2406 * The request matched a {@link ResourcePathDeclaration}. 2407 */ 2408 MATCHED, 2409 /** 2410 * The request did not match any {@link ResourcePathDeclaration}. 2411 */ 2412 UNMATCHED 2413 } 2414 2415 /** 2416 * Outcomes for a Server-Sent Event enqueue attempt. 2417 * 2418 * <p> 2419 * This type may gain reviewed constants in Soklet 4.x; use a forward-compatible default when switching over its values. 2420 * 2421 * @author <a href="https://www.revetkn.com">Mark Allen</a> 2422 */ 2423 enum SseEventEnqueueOutcome { 2424 /** 2425 * An enqueue attempt to a connection was made. 2426 */ 2427 ATTEMPTED, 2428 /** 2429 * An enqueue attempt succeeded. 2430 */ 2431 ENQUEUED, 2432 /** 2433 * An enqueue attempt failed because the payload was dropped. 2434 */ 2435 DROPPED 2436 } 2437 2438 /** 2439 * Reasons a Server-Sent Event payload or comment was dropped before it could be written. 2440 * 2441 * <p> 2442 * This type may gain reviewed constants in Soklet 4.x; use a forward-compatible default when switching over its values. 2443 * 2444 * @author <a href="https://www.revetkn.com">Mark Allen</a> 2445 */ 2446 enum SseEventDropReason { 2447 /** 2448 * The per-connection write queue was full. 2449 */ 2450 QUEUE_FULL 2451 } 2452 2453 /** 2454 * Key for transport failures grouped by server type and reason. 2455 * 2456 * @author <a href="https://www.revetkn.com">Mark Allen</a> 2457 */ 2458 @ThreadSafe 2459 final class TransportFailureKey { 2460 @NonNull 2461 private final ServerType serverType; 2462 @NonNull 2463 private final TransportFailureReason reason; 2464 2465 /** 2466 * Creates a transport failure key. 2467 * 2468 * @param serverType server that recorded the failure 2469 * @param reason fixed transport failure reason 2470 */ 2471 public TransportFailureKey(@NonNull ServerType serverType, 2472 @NonNull TransportFailureReason reason) { 2473 this.serverType = requireNonNull(serverType); 2474 this.reason = requireNonNull(reason); 2475 } 2476 2477 /** @return server that recorded the failure */ 2478 @NonNull 2479 public ServerType getServerType() { 2480 return this.serverType; 2481 } 2482 2483 /** @return fixed transport failure reason */ 2484 @NonNull 2485 public TransportFailureReason getReason() { 2486 return this.reason; 2487 } 2488 2489 /** @return whether both transport-failure dimensions are equal */ 2490 @Override 2491 public boolean equals(@Nullable Object other) { 2492 if (this == other) 2493 return true; 2494 if (!(other instanceof TransportFailureKey key)) 2495 return false; 2496 return this.serverType == key.serverType && this.reason == key.reason; 2497 } 2498 2499 /** @return value-based hash code */ 2500 @Override 2501 public int hashCode() { 2502 return Objects.hash(this.serverType, this.reason); 2503 } 2504 2505 /** @return diagnostic rendering of the transport-failure dimensions */ 2506 @Override 2507 @NonNull 2508 public String toString() { 2509 return "TransportFailureKey{serverType=" + this.serverType 2510 + ", reason=" + this.reason + "}"; 2511 } 2512 } 2513 2514 /** 2515 * Key for request read failures grouped by reason. 2516 * 2517 * @author <a href="https://www.revetkn.com">Mark Allen</a> 2518 */ 2519 @ThreadSafe 2520 final class RequestReadFailureKey { 2521 @NonNull 2522 private final RequestReadFailureReason reason; 2523 2524 /** 2525 * Creates a request read failure key. 2526 * 2527 * @param reason fixed request read failure reason 2528 */ 2529 public RequestReadFailureKey(@NonNull RequestReadFailureReason reason) { 2530 this.reason = requireNonNull(reason); 2531 } 2532 2533 /** @return fixed request read failure reason */ 2534 @NonNull 2535 public RequestReadFailureReason getReason() { 2536 return this.reason; 2537 } 2538 2539 /** @return whether both keys have the same reason */ 2540 @Override 2541 public boolean equals(@Nullable Object other) { 2542 return this == other || (other instanceof RequestReadFailureKey key 2543 && this.reason == key.reason); 2544 } 2545 2546 /** @return value-based hash code */ 2547 @Override 2548 public int hashCode() { 2549 return this.reason.hashCode(); 2550 } 2551 2552 /** @return diagnostic rendering of the request-read failure reason */ 2553 @Override 2554 @NonNull 2555 public String toString() { 2556 return "RequestReadFailureKey{reason=" + this.reason + "}"; 2557 } 2558 } 2559 2560 /** 2561 * Key for request rejections grouped by reason. 2562 * 2563 * @author <a href="https://www.revetkn.com">Mark Allen</a> 2564 */ 2565 @ThreadSafe 2566 final class RequestRejectionKey { 2567 @NonNull 2568 private final RequestRejectionReason reason; 2569 2570 /** 2571 * Creates a request rejection key. 2572 * 2573 * @param reason fixed request rejection reason 2574 */ 2575 public RequestRejectionKey(@NonNull RequestRejectionReason reason) { 2576 this.reason = requireNonNull(reason); 2577 } 2578 2579 /** @return fixed request rejection reason */ 2580 @NonNull 2581 public RequestRejectionReason getReason() { 2582 return this.reason; 2583 } 2584 2585 /** @return whether both keys have the same reason */ 2586 @Override 2587 public boolean equals(@Nullable Object other) { 2588 return this == other || (other instanceof RequestRejectionKey key 2589 && this.reason == key.reason); 2590 } 2591 2592 /** @return value-based hash code */ 2593 @Override 2594 public int hashCode() { 2595 return this.reason.hashCode(); 2596 } 2597 2598 /** @return diagnostic rendering of the request-rejection reason */ 2599 @Override 2600 @NonNull 2601 public String toString() { 2602 return "RequestRejectionKey{reason=" + this.reason + "}"; 2603 } 2604 } 2605 2606 /** 2607 * Key for metrics grouped by HTTP method and route match information. 2608 * 2609 * @author <a href="https://www.revetkn.com">Mark Allen</a> 2610 */ 2611 @ThreadSafe 2612 final class HttpServerRouteKey { 2613 @NonNull 2614 private final HttpMethod method; 2615 @NonNull 2616 private final RouteType routeType; 2617 @Nullable 2618 private final ResourcePathDeclaration resourcePathDeclaration; 2619 2620 /** 2621 * Creates an HTTP route key. 2622 * 2623 * @param method HTTP method 2624 * @param routeType whether a route matched 2625 * @param resourcePathDeclaration matched route, or {@code null} when unmatched 2626 */ 2627 public HttpServerRouteKey(@NonNull HttpMethod method, 2628 @NonNull RouteType routeType, 2629 @Nullable ResourcePathDeclaration resourcePathDeclaration) { 2630 this.method = requireNonNull(method); 2631 validateRouteDimensions(routeType, resourcePathDeclaration); 2632 this.routeType = routeType; 2633 this.resourcePathDeclaration = resourcePathDeclaration; 2634 } 2635 2636 /** @return HTTP method */ 2637 @NonNull 2638 public HttpMethod getHttpMethod() { 2639 return this.method; 2640 } 2641 2642 /** @return whether a route matched */ 2643 @NonNull 2644 public RouteType getRouteType() { 2645 return this.routeType; 2646 } 2647 2648 /** @return matched route, or {@code null} when unmatched */ 2649 @Nullable 2650 public ResourcePathDeclaration getResourcePathDeclaration() { 2651 return this.resourcePathDeclaration; 2652 } 2653 2654 /** @return whether all HTTP route dimensions are equal */ 2655 @Override 2656 public boolean equals(@Nullable Object other) { 2657 if (this == other) 2658 return true; 2659 if (!(other instanceof HttpServerRouteKey key)) 2660 return false; 2661 return this.method == key.method && this.routeType == key.routeType 2662 && Objects.equals(this.resourcePathDeclaration, key.resourcePathDeclaration); 2663 } 2664 2665 /** @return value-based hash code */ 2666 @Override 2667 public int hashCode() { 2668 return Objects.hash(this.method, this.routeType, this.resourcePathDeclaration); 2669 } 2670 2671 /** @return diagnostic rendering of the HTTP route dimensions */ 2672 @Override 2673 @NonNull 2674 public String toString() { 2675 return "HttpServerRouteKey{method=" + this.method + ", routeType=" 2676 + this.routeType + ", route=" + this.resourcePathDeclaration + "}"; 2677 } 2678 } 2679 2680 /** Immutable admitted HTTP response stream termination dimensions. Diagnostics redact application dimensions. */ 2681 @ThreadSafe 2682 final class HttpResponseStreamTerminationKey { 2683 @NonNull private final HttpServerRouteStatusKey httpServerRouteStatusKey; 2684 @NonNull private final StreamTerminationReason reason; 2685 2686 private HttpResponseStreamTerminationKey(@NonNull HttpServerRouteStatusKey httpServerRouteStatusKey, 2687 @NonNull StreamTerminationReason streamTerminationReason) { 2688 this.httpServerRouteStatusKey = requireNonNull(httpServerRouteStatusKey); 2689 this.reason = requireNonNull(streamTerminationReason); 2690 } 2691 2692 /** 2693 * @param httpServerRouteStatusKey HTTP method, route and actual wire status class 2694 * @param streamTerminationReason logical terminal reason 2695 * @return immutable dimensions 2696 */ 2697 @NonNull 2698 public static HttpResponseStreamTerminationKey fromDimensions(@NonNull HttpServerRouteStatusKey httpServerRouteStatusKey, 2699 @NonNull StreamTerminationReason streamTerminationReason) { 2700 return new HttpResponseStreamTerminationKey(httpServerRouteStatusKey, streamTerminationReason); 2701 } 2702 2703 /** @return HTTP method, route and actual wire status class */ 2704 @NonNull public HttpServerRouteStatusKey getHttpServerRouteStatusKey() { return this.httpServerRouteStatusKey; } 2705 /** @return logical terminal reason */ 2706 @NonNull public StreamTerminationReason getReason() { return this.reason; } 2707 /** @return whether both dimensions are equal */ 2708 @Override public boolean equals(@Nullable Object other) { 2709 return this == other || (other instanceof HttpResponseStreamTerminationKey key 2710 && this.httpServerRouteStatusKey.equals(key.httpServerRouteStatusKey) && this.reason == key.reason); 2711 } 2712 /** @return value based hash code */ 2713 @Override public int hashCode() { return Objects.hash(this.httpServerRouteStatusKey, this.reason); } 2714 /** @return diagnostic rendering with application dimensions redacted */ 2715 @Override @NonNull public String toString() { 2716 return "HttpResponseStreamTerminationKey{httpServerRouteStatusKey=<redacted>, reason=" + this.reason + "}"; 2717 } 2718 } 2719 2720 /** 2721 * Key for metrics grouped by HTTP method, route match information, and status class (e.g. 2xx). 2722 * 2723 * @author <a href="https://www.revetkn.com">Mark Allen</a> 2724 */ 2725 @ThreadSafe 2726 final class HttpServerRouteStatusKey { 2727 @NonNull 2728 private final HttpMethod method; 2729 @NonNull 2730 private final RouteType routeType; 2731 @Nullable 2732 private final ResourcePathDeclaration resourcePathDeclaration; 2733 @NonNull 2734 private final String statusClass; 2735 2736 /** 2737 * Creates an HTTP route and status key. 2738 * 2739 * @param method HTTP method 2740 * @param routeType whether a route matched 2741 * @param resourcePathDeclaration matched route, or {@code null} when unmatched 2742 * @param statusClass one of {@code 1xx}, {@code 2xx}, {@code 3xx}, {@code 4xx}, 2743 * {@code 5xx}, or {@code unknown} 2744 * @throws IllegalArgumentException if the route dimensions disagree or the 2745 * status class is outside this bounded vocabulary 2746 */ 2747 public HttpServerRouteStatusKey(@NonNull HttpMethod method, 2748 @NonNull RouteType routeType, 2749 @Nullable ResourcePathDeclaration resourcePathDeclaration, 2750 @NonNull String statusClass) { 2751 this.method = requireNonNull(method); 2752 validateRouteDimensions(routeType, resourcePathDeclaration); 2753 this.routeType = routeType; 2754 this.resourcePathDeclaration = resourcePathDeclaration; 2755 this.statusClass = requireStatusClass(statusClass); 2756 } 2757 2758 /** @return HTTP method */ 2759 @NonNull 2760 public HttpMethod getHttpMethod() { 2761 return this.method; 2762 } 2763 2764 /** @return whether a route matched */ 2765 @NonNull 2766 public RouteType getRouteType() { 2767 return this.routeType; 2768 } 2769 2770 /** @return matched route, or {@code null} when unmatched */ 2771 @Nullable 2772 public ResourcePathDeclaration getResourcePathDeclaration() { 2773 return this.resourcePathDeclaration; 2774 } 2775 2776 /** @return HTTP status class */ 2777 @NonNull 2778 public String getStatusClass() { 2779 return this.statusClass; 2780 } 2781 2782 /** @return whether all HTTP route and status dimensions are equal */ 2783 @Override 2784 public boolean equals(@Nullable Object other) { 2785 if (this == other) 2786 return true; 2787 if (!(other instanceof HttpServerRouteStatusKey key)) 2788 return false; 2789 return this.method == key.method && this.routeType == key.routeType 2790 && Objects.equals(this.resourcePathDeclaration, key.resourcePathDeclaration) 2791 && this.statusClass.equals(key.statusClass); 2792 } 2793 2794 /** @return value-based hash code */ 2795 @Override 2796 public int hashCode() { 2797 return Objects.hash(this.method, this.routeType, this.resourcePathDeclaration, 2798 this.statusClass); 2799 } 2800 2801 /** @return diagnostic rendering of the HTTP route and status dimensions */ 2802 @Override 2803 @NonNull 2804 public String toString() { 2805 return "HttpServerRouteStatusKey{method=" + this.method 2806 + ", routeType=" + this.routeType + ", route=" + this.resourcePathDeclaration 2807 + ", statusClass=" + this.statusClass + "}"; 2808 } 2809 } 2810 2811 /** 2812 * Key for metrics grouped by Server-Sent Event comment type and route match information. 2813 * 2814 * @author <a href="https://www.revetkn.com">Mark Allen</a> 2815 */ 2816 @ThreadSafe 2817 final class SseCommentRouteKey { 2818 @NonNull 2819 private final RouteType routeType; 2820 @Nullable 2821 private final ResourcePathDeclaration resourcePathDeclaration; 2822 private final SseComment.@NonNull CommentType commentType; 2823 2824 /** 2825 * Creates an SSE comment route key. 2826 * 2827 * @param routeType whether a route matched 2828 * @param resourcePathDeclaration matched route, or {@code null} when unmatched 2829 * @param commentType SSE comment type 2830 */ 2831 public SseCommentRouteKey(@NonNull RouteType routeType, 2832 @Nullable ResourcePathDeclaration resourcePathDeclaration, 2833 SseComment.@NonNull CommentType commentType) { 2834 validateRouteDimensions(routeType, resourcePathDeclaration); 2835 this.routeType = routeType; 2836 this.resourcePathDeclaration = resourcePathDeclaration; 2837 this.commentType = requireNonNull(commentType); 2838 } 2839 2840 /** @return whether a route matched */ 2841 @NonNull 2842 public RouteType getRouteType() { 2843 return this.routeType; 2844 } 2845 2846 /** @return matched route, or {@code null} when unmatched */ 2847 @Nullable 2848 public ResourcePathDeclaration getResourcePathDeclaration() { 2849 return this.resourcePathDeclaration; 2850 } 2851 2852 /** @return SSE comment type */ 2853 public SseComment.@NonNull CommentType getCommentType() { 2854 return this.commentType; 2855 } 2856 2857 /** @return whether all SSE comment route dimensions are equal */ 2858 @Override 2859 public boolean equals(@Nullable Object other) { 2860 if (this == other) 2861 return true; 2862 if (!(other instanceof SseCommentRouteKey key)) 2863 return false; 2864 return this.routeType == key.routeType 2865 && Objects.equals(this.resourcePathDeclaration, key.resourcePathDeclaration) 2866 && this.commentType == key.commentType; 2867 } 2868 2869 /** @return value-based hash code */ 2870 @Override 2871 public int hashCode() { 2872 return Objects.hash(this.routeType, this.resourcePathDeclaration, this.commentType); 2873 } 2874 2875 /** @return diagnostic rendering of the SSE comment route dimensions */ 2876 @Override 2877 @NonNull 2878 public String toString() { 2879 return "SseCommentRouteKey{routeType=" + this.routeType + ", route=" 2880 + this.resourcePathDeclaration + ", commentType=" + this.commentType + "}"; 2881 } 2882 } 2883 2884 /** 2885 * Key for metrics grouped by Server-Sent Event route match information. 2886 * 2887 * @author <a href="https://www.revetkn.com">Mark Allen</a> 2888 */ 2889 @ThreadSafe 2890 final class SseEventRouteKey { 2891 @NonNull 2892 private final RouteType routeType; 2893 @Nullable 2894 private final ResourcePathDeclaration resourcePathDeclaration; 2895 2896 /** 2897 * Creates an SSE event route key. 2898 * 2899 * @param routeType whether a route matched 2900 * @param resourcePathDeclaration matched route, or {@code null} when unmatched 2901 */ 2902 public SseEventRouteKey(@NonNull RouteType routeType, 2903 @Nullable ResourcePathDeclaration resourcePathDeclaration) { 2904 validateRouteDimensions(routeType, resourcePathDeclaration); 2905 this.routeType = routeType; 2906 this.resourcePathDeclaration = resourcePathDeclaration; 2907 } 2908 2909 /** @return whether a route matched */ 2910 @NonNull 2911 public RouteType getRouteType() { 2912 return this.routeType; 2913 } 2914 2915 /** @return matched route, or {@code null} when unmatched */ 2916 @Nullable 2917 public ResourcePathDeclaration getResourcePathDeclaration() { 2918 return this.resourcePathDeclaration; 2919 } 2920 2921 /** @return whether both SSE event route dimensions are equal */ 2922 @Override 2923 public boolean equals(@Nullable Object other) { 2924 if (this == other) 2925 return true; 2926 if (!(other instanceof SseEventRouteKey key)) 2927 return false; 2928 return this.routeType == key.routeType 2929 && Objects.equals(this.resourcePathDeclaration, key.resourcePathDeclaration); 2930 } 2931 2932 /** @return value-based hash code */ 2933 @Override 2934 public int hashCode() { 2935 return Objects.hash(this.routeType, this.resourcePathDeclaration); 2936 } 2937 2938 /** @return diagnostic rendering of the SSE event route dimensions */ 2939 @Override 2940 @NonNull 2941 public String toString() { 2942 return "SseEventRouteKey{routeType=" + this.routeType + ", route=" 2943 + this.resourcePathDeclaration + "}"; 2944 } 2945 } 2946 2947 /** 2948 * Key for metrics grouped by Server-Sent Event route match information and handshake failure reason. 2949 * 2950 * @author <a href="https://www.revetkn.com">Mark Allen</a> 2951 */ 2952 @ThreadSafe 2953 final class SseEventRouteHandshakeFailureKey { 2954 @NonNull 2955 private final RouteType routeType; 2956 @Nullable 2957 private final ResourcePathDeclaration resourcePathDeclaration; 2958 private final SseConnection.@NonNull HandshakeFailureReason 2959 handshakeFailureReason; 2960 2961 /** 2962 * Creates an SSE handshake failure key. 2963 * 2964 * @param routeType whether a route matched 2965 * @param resourcePathDeclaration matched route, or {@code null} when unmatched 2966 * @param handshakeFailureReason fixed handshake failure reason 2967 */ 2968 public SseEventRouteHandshakeFailureKey(@NonNull RouteType routeType, 2969 @Nullable ResourcePathDeclaration resourcePathDeclaration, 2970 SseConnection.@NonNull HandshakeFailureReason 2971 handshakeFailureReason) { 2972 validateRouteDimensions(routeType, resourcePathDeclaration); 2973 this.routeType = routeType; 2974 this.resourcePathDeclaration = resourcePathDeclaration; 2975 this.handshakeFailureReason = requireNonNull(handshakeFailureReason); 2976 } 2977 2978 /** @return whether a route matched */ 2979 @NonNull 2980 public RouteType getRouteType() { 2981 return this.routeType; 2982 } 2983 2984 /** @return matched route, or {@code null} when unmatched */ 2985 @Nullable 2986 public ResourcePathDeclaration getResourcePathDeclaration() { 2987 return this.resourcePathDeclaration; 2988 } 2989 2990 /** @return fixed handshake failure reason */ 2991 public SseConnection.@NonNull HandshakeFailureReason 2992 getHandshakeFailureReason() { 2993 return this.handshakeFailureReason; 2994 } 2995 2996 /** @return whether all SSE handshake-failure dimensions are equal */ 2997 @Override 2998 public boolean equals(@Nullable Object other) { 2999 if (this == other) 3000 return true; 3001 if (!(other instanceof SseEventRouteHandshakeFailureKey key)) 3002 return false; 3003 return this.routeType == key.routeType 3004 && Objects.equals(this.resourcePathDeclaration, key.resourcePathDeclaration) 3005 && this.handshakeFailureReason == key.handshakeFailureReason; 3006 } 3007 3008 /** @return value-based hash code */ 3009 @Override 3010 public int hashCode() { 3011 return Objects.hash(this.routeType, this.resourcePathDeclaration, 3012 this.handshakeFailureReason); 3013 } 3014 3015 /** @return diagnostic rendering of the SSE handshake-failure dimensions */ 3016 @Override 3017 @NonNull 3018 public String toString() { 3019 return "SseEventRouteHandshakeFailureKey{routeType=" 3020 + this.routeType + ", route=" + this.resourcePathDeclaration 3021 + ", handshakeFailureReason=" + this.handshakeFailureReason 3022 + "}"; 3023 } 3024 } 3025 3026 /** 3027 * Key for metrics grouped by Server-Sent Event route match information and enqueue outcome. 3028 * 3029 * @author <a href="https://www.revetkn.com">Mark Allen</a> 3030 */ 3031 @ThreadSafe 3032 final class SseEventRouteEnqueueOutcomeKey { 3033 @NonNull 3034 private final RouteType routeType; 3035 @Nullable 3036 private final ResourcePathDeclaration resourcePathDeclaration; 3037 @NonNull 3038 private final SseEventEnqueueOutcome outcome; 3039 3040 /** 3041 * Creates an SSE enqueue outcome key. 3042 * 3043 * @param routeType whether a route matched 3044 * @param resourcePathDeclaration matched route, or {@code null} when unmatched 3045 * @param outcome fixed enqueue outcome 3046 */ 3047 public SseEventRouteEnqueueOutcomeKey(@NonNull RouteType routeType, 3048 @Nullable ResourcePathDeclaration resourcePathDeclaration, 3049 @NonNull SseEventEnqueueOutcome outcome) { 3050 validateRouteDimensions(routeType, resourcePathDeclaration); 3051 this.routeType = routeType; 3052 this.resourcePathDeclaration = resourcePathDeclaration; 3053 this.outcome = requireNonNull(outcome); 3054 } 3055 3056 /** @return whether a route matched */ 3057 @NonNull 3058 public RouteType getRouteType() { 3059 return this.routeType; 3060 } 3061 3062 /** @return matched route, or {@code null} when unmatched */ 3063 @Nullable 3064 public ResourcePathDeclaration getResourcePathDeclaration() { 3065 return this.resourcePathDeclaration; 3066 } 3067 3068 /** @return fixed enqueue outcome */ 3069 @NonNull 3070 public SseEventEnqueueOutcome getOutcome() { 3071 return this.outcome; 3072 } 3073 3074 /** @return whether all SSE enqueue-outcome dimensions are equal */ 3075 @Override 3076 public boolean equals(@Nullable Object other) { 3077 if (this == other) 3078 return true; 3079 if (!(other instanceof SseEventRouteEnqueueOutcomeKey key)) 3080 return false; 3081 return this.routeType == key.routeType 3082 && Objects.equals(this.resourcePathDeclaration, key.resourcePathDeclaration) 3083 && this.outcome == key.outcome; 3084 } 3085 3086 /** @return value-based hash code */ 3087 @Override 3088 public int hashCode() { 3089 return Objects.hash(this.routeType, this.resourcePathDeclaration, this.outcome); 3090 } 3091 3092 /** @return diagnostic rendering of the SSE enqueue-outcome dimensions */ 3093 @Override 3094 @NonNull 3095 public String toString() { 3096 return "SseEventRouteEnqueueOutcomeKey{routeType=" 3097 + this.routeType + ", route=" + this.resourcePathDeclaration + ", outcome=" 3098 + this.outcome + "}"; 3099 } 3100 } 3101 3102 /** 3103 * Key for metrics grouped by Server-Sent Event comment type, route match information, and enqueue outcome. 3104 * 3105 * @author <a href="https://www.revetkn.com">Mark Allen</a> 3106 */ 3107 @ThreadSafe 3108 final class SseCommentRouteEnqueueOutcomeKey { 3109 @NonNull 3110 private final RouteType routeType; 3111 @Nullable 3112 private final ResourcePathDeclaration resourcePathDeclaration; 3113 private final SseComment.@NonNull CommentType commentType; 3114 @NonNull 3115 private final SseEventEnqueueOutcome eventEnqueueOutcome; 3116 3117 /** 3118 * Creates an SSE comment enqueue outcome key. 3119 * 3120 * @param routeType whether a route matched 3121 * @param resourcePathDeclaration matched route, or {@code null} when unmatched 3122 * @param commentType SSE comment type 3123 * @param eventEnqueueOutcome fixed enqueue outcome 3124 */ 3125 public SseCommentRouteEnqueueOutcomeKey( 3126 @NonNull RouteType routeType, 3127 @Nullable ResourcePathDeclaration resourcePathDeclaration, 3128 SseComment.@NonNull CommentType commentType, 3129 @NonNull SseEventEnqueueOutcome eventEnqueueOutcome) { 3130 validateRouteDimensions(routeType, resourcePathDeclaration); 3131 this.routeType = routeType; 3132 this.resourcePathDeclaration = resourcePathDeclaration; 3133 this.commentType = requireNonNull(commentType); 3134 this.eventEnqueueOutcome = requireNonNull(eventEnqueueOutcome); 3135 } 3136 3137 /** @return whether a route matched */ 3138 @NonNull 3139 public RouteType getRouteType() { 3140 return this.routeType; 3141 } 3142 3143 /** @return matched route, or {@code null} when unmatched */ 3144 @Nullable 3145 public ResourcePathDeclaration getResourcePathDeclaration() { 3146 return this.resourcePathDeclaration; 3147 } 3148 3149 /** @return SSE comment type */ 3150 public SseComment.@NonNull CommentType getCommentType() { 3151 return this.commentType; 3152 } 3153 3154 /** @return fixed enqueue outcome */ 3155 @NonNull 3156 public SseEventEnqueueOutcome getEventEnqueueOutcome() { 3157 return this.eventEnqueueOutcome; 3158 } 3159 3160 /** @return whether all SSE comment enqueue dimensions are equal */ 3161 @Override 3162 public boolean equals(@Nullable Object other) { 3163 if (this == other) 3164 return true; 3165 if (!(other instanceof SseCommentRouteEnqueueOutcomeKey key)) 3166 return false; 3167 return this.routeType == key.routeType 3168 && Objects.equals(this.resourcePathDeclaration, key.resourcePathDeclaration) 3169 && this.commentType == key.commentType 3170 && this.eventEnqueueOutcome == key.eventEnqueueOutcome; 3171 } 3172 3173 /** @return value-based hash code */ 3174 @Override 3175 public int hashCode() { 3176 return Objects.hash(this.routeType, this.resourcePathDeclaration, this.commentType, 3177 this.eventEnqueueOutcome); 3178 } 3179 3180 /** @return diagnostic rendering of the SSE comment enqueue dimensions */ 3181 @Override 3182 @NonNull 3183 public String toString() { 3184 return "SseCommentRouteEnqueueOutcomeKey{routeType=" 3185 + this.routeType + ", route=" + this.resourcePathDeclaration + ", commentType=" 3186 + this.commentType + ", outcome=" + this.eventEnqueueOutcome + "}"; 3187 } 3188 } 3189 3190 /** 3191 * Key for metrics grouped by Server-Sent Event route match information and drop reason. 3192 * 3193 * @author <a href="https://www.revetkn.com">Mark Allen</a> 3194 */ 3195 @ThreadSafe 3196 final class SseEventRouteDropKey { 3197 @NonNull 3198 private final RouteType routeType; 3199 @Nullable 3200 private final ResourcePathDeclaration resourcePathDeclaration; 3201 @NonNull 3202 private final SseEventDropReason dropReason; 3203 3204 /** 3205 * Creates an SSE event drop key. 3206 * 3207 * @param routeType whether a route matched 3208 * @param resourcePathDeclaration matched route, or {@code null} when unmatched 3209 * @param dropReason fixed drop reason 3210 */ 3211 public SseEventRouteDropKey(@NonNull RouteType routeType, 3212 @Nullable ResourcePathDeclaration resourcePathDeclaration, 3213 @NonNull SseEventDropReason dropReason) { 3214 validateRouteDimensions(routeType, resourcePathDeclaration); 3215 this.routeType = routeType; 3216 this.resourcePathDeclaration = resourcePathDeclaration; 3217 this.dropReason = requireNonNull(dropReason); 3218 } 3219 3220 /** @return whether a route matched */ 3221 @NonNull 3222 public RouteType getRouteType() { 3223 return this.routeType; 3224 } 3225 3226 /** @return matched route, or {@code null} when unmatched */ 3227 @Nullable 3228 public ResourcePathDeclaration getResourcePathDeclaration() { 3229 return this.resourcePathDeclaration; 3230 } 3231 3232 /** @return fixed drop reason */ 3233 @NonNull 3234 public SseEventDropReason getDropReason() { 3235 return this.dropReason; 3236 } 3237 3238 /** @return whether all SSE event-drop dimensions are equal */ 3239 @Override 3240 public boolean equals(@Nullable Object other) { 3241 if (this == other) 3242 return true; 3243 if (!(other instanceof SseEventRouteDropKey key)) 3244 return false; 3245 return this.routeType == key.routeType 3246 && Objects.equals(this.resourcePathDeclaration, key.resourcePathDeclaration) 3247 && this.dropReason == key.dropReason; 3248 } 3249 3250 /** @return value-based hash code */ 3251 @Override 3252 public int hashCode() { 3253 return Objects.hash(this.routeType, this.resourcePathDeclaration, this.dropReason); 3254 } 3255 3256 /** @return diagnostic rendering of the SSE event-drop dimensions */ 3257 @Override 3258 @NonNull 3259 public String toString() { 3260 return "SseEventRouteDropKey{routeType=" + this.routeType 3261 + ", route=" + this.resourcePathDeclaration + ", dropReason=" 3262 + this.dropReason + "}"; 3263 } 3264 } 3265 3266 /** 3267 * Key for metrics grouped by Server-Sent Event comment type, route match information, and drop reason. 3268 * 3269 * @author <a href="https://www.revetkn.com">Mark Allen</a> 3270 */ 3271 @ThreadSafe 3272 final class SseCommentRouteDropKey { 3273 @NonNull 3274 private final RouteType routeType; 3275 @Nullable 3276 private final ResourcePathDeclaration resourcePathDeclaration; 3277 private final SseComment.@NonNull CommentType commentType; 3278 @NonNull 3279 private final SseEventDropReason eventDropReason; 3280 3281 /** 3282 * Creates an SSE comment drop key. 3283 * 3284 * @param routeType whether a route matched 3285 * @param resourcePathDeclaration matched route, or {@code null} when unmatched 3286 * @param commentType SSE comment type 3287 * @param eventDropReason fixed drop reason 3288 */ 3289 public SseCommentRouteDropKey(@NonNull RouteType routeType, 3290 @Nullable ResourcePathDeclaration resourcePathDeclaration, 3291 SseComment.@NonNull CommentType commentType, 3292 @NonNull SseEventDropReason eventDropReason) { 3293 validateRouteDimensions(routeType, resourcePathDeclaration); 3294 this.routeType = routeType; 3295 this.resourcePathDeclaration = resourcePathDeclaration; 3296 this.commentType = requireNonNull(commentType); 3297 this.eventDropReason = requireNonNull(eventDropReason); 3298 } 3299 3300 /** @return whether a route matched */ 3301 @NonNull 3302 public RouteType getRouteType() { 3303 return this.routeType; 3304 } 3305 3306 /** @return matched route, or {@code null} when unmatched */ 3307 @Nullable 3308 public ResourcePathDeclaration getResourcePathDeclaration() { 3309 return this.resourcePathDeclaration; 3310 } 3311 3312 /** @return SSE comment type */ 3313 public SseComment.@NonNull CommentType getCommentType() { 3314 return this.commentType; 3315 } 3316 3317 /** @return fixed drop reason */ 3318 @NonNull 3319 public SseEventDropReason getEventDropReason() { 3320 return this.eventDropReason; 3321 } 3322 3323 /** @return whether all SSE comment-drop dimensions are equal */ 3324 @Override 3325 public boolean equals(@Nullable Object other) { 3326 if (this == other) 3327 return true; 3328 if (!(other instanceof SseCommentRouteDropKey key)) 3329 return false; 3330 return this.routeType == key.routeType 3331 && Objects.equals(this.resourcePathDeclaration, key.resourcePathDeclaration) 3332 && this.commentType == key.commentType 3333 && this.eventDropReason == key.eventDropReason; 3334 } 3335 3336 /** @return value-based hash code */ 3337 @Override 3338 public int hashCode() { 3339 return Objects.hash(this.routeType, this.resourcePathDeclaration, this.commentType, 3340 this.eventDropReason); 3341 } 3342 3343 /** @return diagnostic rendering of the SSE comment-drop dimensions */ 3344 @Override 3345 @NonNull 3346 public String toString() { 3347 return "SseCommentRouteDropKey{routeType=" + this.routeType 3348 + ", route=" + this.resourcePathDeclaration + ", commentType=" 3349 + this.commentType + ", dropReason=" + this.eventDropReason + "}"; 3350 } 3351 } 3352 3353 /** 3354 * Key for metrics grouped by Server-Sent Event stream route match information and termination reason. 3355 * 3356 * @author <a href="https://www.revetkn.com">Mark Allen</a> 3357 */ 3358 @ThreadSafe 3359 final class SseStreamRouteTerminationKey { 3360 @NonNull 3361 private final RouteType routeType; 3362 @Nullable 3363 private final ResourcePathDeclaration resourcePathDeclaration; 3364 @NonNull 3365 private final StreamTerminationReason terminationReason; 3366 3367 /** 3368 * Creates an SSE stream termination key. 3369 * 3370 * @param routeType whether a route matched 3371 * @param resourcePathDeclaration matched route, or {@code null} when unmatched 3372 * @param terminationReason fixed stream termination reason 3373 */ 3374 public SseStreamRouteTerminationKey(@NonNull RouteType routeType, 3375 @Nullable ResourcePathDeclaration resourcePathDeclaration, 3376 @NonNull StreamTerminationReason terminationReason) { 3377 validateRouteDimensions(routeType, resourcePathDeclaration); 3378 this.routeType = routeType; 3379 this.resourcePathDeclaration = resourcePathDeclaration; 3380 this.terminationReason = requireNonNull(terminationReason); 3381 } 3382 3383 /** @return whether a route matched */ 3384 @NonNull 3385 public RouteType getRouteType() { 3386 return this.routeType; 3387 } 3388 3389 /** @return matched route, or {@code null} when unmatched */ 3390 @Nullable 3391 public ResourcePathDeclaration getResourcePathDeclaration() { 3392 return this.resourcePathDeclaration; 3393 } 3394 3395 /** @return fixed stream termination reason */ 3396 @NonNull 3397 public StreamTerminationReason getTerminationReason() { 3398 return this.terminationReason; 3399 } 3400 3401 /** @return whether all SSE stream-termination dimensions are equal */ 3402 @Override 3403 public boolean equals(@Nullable Object other) { 3404 if (this == other) 3405 return true; 3406 if (!(other instanceof SseStreamRouteTerminationKey key)) 3407 return false; 3408 return this.routeType == key.routeType 3409 && Objects.equals(this.resourcePathDeclaration, key.resourcePathDeclaration) 3410 && this.terminationReason == key.terminationReason; 3411 } 3412 3413 /** @return value-based hash code */ 3414 @Override 3415 public int hashCode() { 3416 return Objects.hash(this.routeType, this.resourcePathDeclaration, 3417 this.terminationReason); 3418 } 3419 3420 /** @return diagnostic rendering of the SSE termination dimensions */ 3421 @Override 3422 @NonNull 3423 public String toString() { 3424 return "SseStreamRouteTerminationKey{routeType=" + this.routeType 3425 + ", route=" + this.resourcePathDeclaration + ", terminationReason=" 3426 + this.terminationReason + "}"; 3427 } 3428 } 3429 3430 @NonNull 3431 private static String requireStatusClass(@NonNull String statusClass) { 3432 requireNonNull(statusClass); 3433 return switch (statusClass) { 3434 case "1xx", "2xx", "3xx", "4xx", "5xx", "unknown" -> statusClass; 3435 default -> throw new IllegalArgumentException("Unsupported HTTP status class."); 3436 }; 3437 } 3438 3439 private static void validateRouteDimensions(@NonNull RouteType routeType, 3440 @Nullable ResourcePathDeclaration resourcePathDeclaration) { 3441 requireNonNull(routeType); 3442 if (routeType == RouteType.MATCHED && resourcePathDeclaration == null) 3443 throw new IllegalArgumentException( 3444 "Route must be provided when RouteType is MATCHED"); 3445 if (routeType == RouteType.UNMATCHED && resourcePathDeclaration != null) 3446 throw new IllegalArgumentException( 3447 "Route must be null when RouteType is UNMATCHED"); 3448 } 3449 3450 3451 /** 3452 * Acquires a threadsafe {@link MetricsCollector} instance with sensible defaults. 3453 * <p> 3454 * This method is guaranteed to return a new instance. 3455 * 3456 * Each aggregate map retains at most 8,192 keys in approximate least-recently-used order. 3457 * Evicted keys restart their cumulative counts from zero on the next observation. 3458 * 3459 * @return a {@code MetricsCollector} with default settings 3460 */ 3461 @NonNull 3462 static MetricsCollector defaultInstance() { 3463 return DefaultMetricsCollector.defaultInstance(); 3464 } 3465 3466 /** 3467 * Acquires a threadsafe {@link MetricsCollector} instance that performs no work. 3468 * <p> 3469 * This method is useful when you want to explicitly disable metrics collection without writing your own implementation. 3470 * <p> 3471 * The returned instance is guaranteed to be a JVM-wide singleton. 3472 * 3473 * @return a no-op {@code MetricsCollector} 3474 */ 3475 @NonNull 3476 static MetricsCollector disabledInstance() { 3477 return DisabledMetricsCollector.defaultInstance(); 3478 } 3479}