001/* 002 * Copyright 2015-2022 Transmogrify LLC, 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.pyranid; 018 019import org.jspecify.annotations.NonNull; 020import org.jspecify.annotations.Nullable; 021 022import javax.annotation.concurrent.ThreadSafe; 023import java.time.Duration; 024import java.util.Objects; 025import java.util.Optional; 026import java.util.UUID; 027 028import static java.util.Objects.requireNonNull; 029 030/** 031 * Contract for collecting operational metrics from Pyranid. 032 * <p> 033 * The default collector is {@link #disabledInstance()}, which performs no work. {@link #inMemoryInstance()} returns a 034 * fresh counter-only collector useful for tests and ad-hoc inspection through {@link #snapshot()}. 035 * <p> 036 * Implementations must be thread-safe, non-blocking, and failure-tolerant. Pyranid catches and discards collector 037 * exceptions so metrics collection cannot affect database behavior. 038 * 039 * @author <a href="https://www.revetkn.com">Mark Allen</a> 040 * @since 4.2.0 041 */ 042@ThreadSafe 043public interface MetricsCollector { 044 /** 045 * Called immediately before Pyranid attempts to acquire a statement-scoped {@link java.sql.Connection}. 046 * <p> 047 * Statement-scoped connections are used for standalone statement execution and stream opening outside a physical 048 * {@link Transaction}. 049 * 050 * @param ctx statement context for the operation that needs a connection 051 */ 052 default void willAcquireStatementConnection(@NonNull StatementContext<?> ctx) { 053 // No-op by default 054 } 055 056 /** 057 * Called after Pyranid successfully acquires a statement-scoped {@link java.sql.Connection}. 058 * 059 * @param ctx statement context for the operation that acquired a connection 060 * @param acquisitionDuration elapsed time spent acquiring the connection 061 */ 062 default void didAcquireStatementConnection(@NonNull StatementContext<?> ctx, 063 @NonNull Duration acquisitionDuration) { 064 // No-op by default 065 } 066 067 /** 068 * Called after Pyranid fails to acquire a statement-scoped {@link java.sql.Connection}. 069 * 070 * @param ctx statement context for the operation that needed a connection 071 * @param databaseType database type known at the time of failure 072 * @param acquisitionDuration elapsed time spent attempting to acquire the connection 073 * @param throwable failure that prevented connection acquisition 074 */ 075 default void didFailToAcquireStatementConnection(@NonNull StatementContext<?> ctx, 076 @NonNull DatabaseType databaseType, 077 @NonNull Duration acquisitionDuration, 078 @NonNull Throwable throwable) { 079 // No-op by default 080 } 081 082 /** 083 * Called after Pyranid successfully releases a statement-scoped {@link java.sql.Connection}. 084 * 085 * @param ctx statement context for the operation that used the connection 086 * @param heldDuration elapsed time between successful acquisition and release 087 */ 088 default void didReleaseStatementConnection(@NonNull StatementContext<?> ctx, 089 @NonNull Duration heldDuration) { 090 // No-op by default 091 } 092 093 /** 094 * Called after Pyranid fails to release a statement-scoped {@link java.sql.Connection}. 095 * 096 * @param ctx statement context for the operation that used the connection 097 * @param heldDuration elapsed time between successful acquisition and the failed release attempt 098 * @param throwable failure that prevented connection release 099 */ 100 default void didFailToReleaseStatementConnection(@NonNull StatementContext<?> ctx, 101 @NonNull Duration heldDuration, 102 @NonNull Throwable throwable) { 103 // No-op by default 104 } 105 106 /** 107 * Called immediately before Pyranid attempts to acquire the JDBC connection backing a physical transaction. 108 * <p> 109 * Pyranid transactions acquire their JDBC connection lazily, so this callback is emitted only when transaction work 110 * first needs database access. 111 * 112 * @param transaction transaction that needs a physical connection 113 * @param databaseType database type known at the time of acquisition 114 */ 115 default void willAcquireTransactionConnection(@NonNull Transaction transaction, 116 @NonNull DatabaseType databaseType) { 117 // No-op by default 118 } 119 120 /** 121 * Called after Pyranid successfully acquires the JDBC connection backing a physical transaction. 122 * 123 * @param transaction transaction that acquired the connection 124 * @param databaseType database type known at the time of acquisition 125 * @param acquisitionDuration elapsed time spent acquiring the connection 126 */ 127 default void didAcquireTransactionConnection(@NonNull Transaction transaction, 128 @NonNull DatabaseType databaseType, 129 @NonNull Duration acquisitionDuration) { 130 // No-op by default 131 } 132 133 /** 134 * Called after Pyranid fails to acquire the JDBC connection backing a physical transaction. 135 * 136 * @param transaction transaction that needed a connection 137 * @param databaseType database type known at the time of failure 138 * @param acquisitionDuration elapsed time spent attempting to acquire the connection 139 * @param throwable failure that prevented connection acquisition 140 */ 141 default void didFailToAcquireTransactionConnection(@NonNull Transaction transaction, 142 @NonNull DatabaseType databaseType, 143 @NonNull Duration acquisitionDuration, 144 @NonNull Throwable throwable) { 145 // No-op by default 146 } 147 148 /** 149 * Called after Pyranid successfully releases the JDBC connection backing a physical transaction. 150 * 151 * @param transaction transaction that owned the connection 152 * @param databaseType database type known at the time of release 153 * @param heldDuration elapsed time between successful acquisition and release 154 */ 155 default void didReleaseTransactionConnection(@NonNull Transaction transaction, 156 @NonNull DatabaseType databaseType, 157 @NonNull Duration heldDuration) { 158 // No-op by default 159 } 160 161 /** 162 * Called after Pyranid fails to release the JDBC connection backing a physical transaction. 163 * 164 * @param transaction transaction that owned the connection 165 * @param databaseType database type known at the time of failure 166 * @param heldDuration elapsed time between successful acquisition and the failed release attempt 167 * @param throwable failure that prevented connection release 168 */ 169 default void didFailToReleaseTransactionConnection(@NonNull Transaction transaction, 170 @NonNull DatabaseType databaseType, 171 @NonNull Duration heldDuration, 172 @NonNull Throwable throwable) { 173 // No-op by default 174 } 175 176 /** 177 * Called when Pyranid enters a closure-based transaction. 178 * <p> 179 * This is a logical transaction event and may occur even if user code never performs database work and no physical JDBC 180 * transaction is begun. 181 * 182 * @param transaction transaction passed to the closure through Pyranid APIs 183 * @param isolation requested transaction isolation 184 * @param databaseType database type known at transaction entry 185 */ 186 default void didEnterTransactionClosure(@NonNull Transaction transaction, 187 @NonNull TransactionIsolation isolation, 188 @NonNull DatabaseType databaseType) { 189 // No-op by default 190 } 191 192 /** 193 * Called when Pyranid exits a closure-based transaction. 194 * 195 * @param transaction transaction that is exiting 196 * @param outcome logical transaction outcome 197 * @param databaseType database type known at transaction exit 198 * @param logicalDuration elapsed time from transaction entry to exit, including user code, physical transaction work, 199 * cleanup, and post-transaction operations 200 * @param thrown exception or error that caused the transaction to exit abnormally, or {@code null} when the 201 * transaction completed without a reported failure 202 */ 203 default void didExitTransactionClosure(@NonNull Transaction transaction, 204 @NonNull TransactionClosureOutcome outcome, 205 @NonNull DatabaseType databaseType, 206 @NonNull Duration logicalDuration, 207 @Nullable Throwable thrown) { 208 // No-op by default 209 } 210 211 /** 212 * Called after Pyranid successfully begins a physical JDBC transaction. 213 * 214 * @param transaction transaction whose physical JDBC transaction began 215 * @param isolation requested transaction isolation 216 * @param databaseType database type known at transaction begin 217 */ 218 default void didBeginPhysicalTransaction(@NonNull Transaction transaction, 219 @NonNull TransactionIsolation isolation, 220 @NonNull DatabaseType databaseType) { 221 // No-op by default 222 } 223 224 /** 225 * Called after Pyranid fails while beginning a physical JDBC transaction. 226 * 227 * @param transaction transaction whose physical JDBC transaction failed to begin 228 * @param isolation requested transaction isolation 229 * @param phase begin phase that failed 230 * @param databaseType database type known at the time of failure 231 * @param throwable failure that prevented the physical transaction from beginning 232 */ 233 default void didFailToBeginPhysicalTransaction(@NonNull Transaction transaction, 234 @NonNull TransactionIsolation isolation, 235 @NonNull PhysicalTransactionBeginFailurePhase phase, 236 @NonNull DatabaseType databaseType, 237 @NonNull Throwable throwable) { 238 // No-op by default 239 } 240 241 /** 242 * Called after Pyranid successfully commits a physical JDBC transaction. 243 * <p> 244 * The duration measures the commit attempt, not the transaction lifetime. Its clock starts immediately before 245 * {@link java.sql.Connection#commit()}, after user work, connection-lock acquisition, and pre-commit validation. 246 * 247 * @param transaction transaction that committed 248 * @param databaseType database type known at commit time 249 * @param physicalDuration elapsed time for the JDBC commit call and immediate success bookkeeping 250 */ 251 default void didCommitPhysicalTransaction(@NonNull Transaction transaction, 252 @NonNull DatabaseType databaseType, 253 @NonNull Duration physicalDuration) { 254 // No-op by default 255 } 256 257 /** 258 * Called after Pyranid fails to commit a physical JDBC transaction. 259 * <p> 260 * Reported when the JDBC commit call throws. It does not establish that the driver never received the commit, nor 261 * that the commit did not succeed. A completion that refuses the commit before issuing it, such as pre-commit 262 * validation or a savepoint-scope ownership conflict, fails the transaction without reaching this callback. 263 * 264 * @param transaction transaction whose commit failed 265 * @param databaseType database type known at commit time 266 * @param physicalDuration elapsed time from immediately before the JDBC commit call through failure reporting, 267 * including error classification and wrapping; excludes preceding transaction work 268 * @param throwable failure that prevented commit from completing normally 269 */ 270 default void didFailToCommitPhysicalTransaction(@NonNull Transaction transaction, 271 @NonNull DatabaseType databaseType, 272 @NonNull Duration physicalDuration, 273 @NonNull Throwable throwable) { 274 // No-op by default 275 } 276 277 /** 278 * Called after Pyranid successfully rolls back a physical JDBC transaction. 279 * <p> 280 * The duration starts immediately before {@link java.sql.Connection#rollback()}; it excludes preceding user work 281 * and connection-lock acquisition, rather than measuring the transaction lifetime. 282 * 283 * @param transaction transaction that rolled back 284 * @param databaseType database type known at rollback time 285 * @param physicalDuration elapsed time for the JDBC rollback call and immediate success bookkeeping 286 */ 287 default void didRollbackPhysicalTransaction(@NonNull Transaction transaction, 288 @NonNull DatabaseType databaseType, 289 @NonNull Duration physicalDuration) { 290 // No-op by default 291 } 292 293 /** 294 * Called after Pyranid fails to roll back a physical JDBC transaction. 295 * <p> 296 * Reported when the JDBC rollback call throws. A failure in success diagnostics after the driver acknowledges 297 * rollback does not reach this callback or change the known rolled-back outcome. 298 * 299 * @param transaction transaction whose rollback failed 300 * @param databaseType database type known at rollback time 301 * @param physicalDuration elapsed time from immediately before the JDBC rollback call through failure reporting, 302 * including error wrapping; excludes preceding transaction work and success diagnostics 303 * @param throwable failure from the JDBC rollback call, wrapped when appropriate 304 */ 305 default void didFailToRollbackPhysicalTransaction(@NonNull Transaction transaction, 306 @NonNull DatabaseType databaseType, 307 @NonNull Duration physicalDuration, 308 @NonNull Throwable throwable) { 309 // No-op by default 310 } 311 312 /** 313 * Called after a post-transaction operation runs. 314 * 315 * @param transaction transaction whose post-transaction operation ran 316 * @param result transaction result visible to the post-transaction operation 317 * @param databaseType database type known at post-transaction execution time 318 * @param duration elapsed time spent running the post-transaction operation 319 * @param throwable failure thrown by the post-transaction operation, or {@code null} when it completed normally 320 */ 321 default void didRunPostTransactionOperation(@NonNull Transaction transaction, 322 @NonNull TransactionResult result, 323 @NonNull DatabaseType databaseType, 324 @NonNull Duration duration, 325 @Nullable Throwable throwable) { 326 // No-op by default 327 } 328 329 /** 330 * Called after Pyranid successfully creates a transaction savepoint. 331 * 332 * @param transaction transaction that created the savepoint 333 * @param databaseType database type known at savepoint creation time 334 */ 335 default void didCreateSavepoint(@NonNull Transaction transaction, 336 @NonNull DatabaseType databaseType) { 337 // No-op by default 338 } 339 340 /** 341 * Called after Pyranid successfully rolls back to a transaction savepoint. 342 * 343 * @param transaction transaction that rolled back to the savepoint 344 * @param databaseType database type known at savepoint rollback time 345 */ 346 default void didRollbackToSavepoint(@NonNull Transaction transaction, 347 @NonNull DatabaseType databaseType) { 348 // No-op by default 349 } 350 351 /** 352 * Called after Pyranid successfully releases a transaction savepoint. 353 * 354 * @param transaction transaction that released the savepoint 355 * @param databaseType database type known at savepoint release time 356 */ 357 default void didReleaseSavepoint(@NonNull Transaction transaction, 358 @NonNull DatabaseType databaseType) { 359 // No-op by default 360 } 361 362 /** 363 * Called once when Pyranid starts a statement attempt, before connection acquisition and preparation. 364 * Each call is paired with exactly one {@link #didExecuteStatement} or {@link #didFailToExecuteStatement}, 365 * including acquisition, preparation and stream-opening failures. A stream's pair ends when its cursor closes, 366 * including exhaustion or explicit early closure; stream-specific callbacks are additional events. 367 * 368 * @param ctx statement context for the attempt about to begin 369 */ 370 default void willExecuteStatement(@NonNull StatementContext<?> ctx) { 371 // No-op by default 372 } 373 374 /** 375 * Called once after a statement executes and maps successfully, at resource closure. 376 * A stream reports when its cursor closes; a later consumer callback failure is reported by 377 * {@link #didCloseStream}, rather than changing a statement event already emitted at exhaustion. 378 * This does not prove a surrounding transaction committed. Non-stream release/parameter-cleanup failures and 379 * statement-logger failures may still propagate after this event; connection release has its own callbacks. 380 * 381 * @param ctx statement context for the executed statement 382 * @param statementLog diagnostic statement log for the execution 383 * @param result statement execution result 384 */ 385 default void didExecuteStatement(@NonNull StatementContext<?> ctx, 386 @NonNull StatementLog<?> statementLog, 387 @NonNull StatementResult result) { 388 // No-op by default 389 } 390 391 /** 392 * Called once after a statement attempt fails, including failures during acquisition, preparation, 393 * execution, mapping or stream cleanup. This pairs with {@link #willExecuteStatement}; non-stream cleanup and 394 * statement-logger failures follow the separate reporting boundaries described by {@link #didExecuteStatement}. 395 * 396 * @param ctx statement context for the failed statement 397 * @param statementLog diagnostic statement log for the failed execution 398 * @param databaseType database type known at statement failure time 399 * @param throwable failure thrown while executing the statement 400 */ 401 default void didFailToExecuteStatement(@NonNull StatementContext<?> ctx, 402 @NonNull StatementLog<?> statementLog, 403 @NonNull DatabaseType databaseType, 404 @NonNull Throwable throwable) { 405 // No-op by default 406 } 407 408 /** 409 * Called immediately before Pyranid opens a streaming statement. 410 * 411 * @param ctx statement context for the stream about to open 412 */ 413 default void willOpenStream(@NonNull StatementContext<?> ctx) { 414 // No-op by default 415 } 416 417 /** 418 * Called after Pyranid successfully opens a streaming statement. 419 * 420 * @param ctx statement context for the opened stream 421 * @param openDuration elapsed time spent opening the stream 422 */ 423 default void didOpenStream(@NonNull StatementContext<?> ctx, 424 @NonNull Duration openDuration) { 425 // No-op by default 426 } 427 428 /** 429 * Called after Pyranid fails to open a streaming statement. 430 * 431 * @param ctx statement context for the stream that failed to open 432 * @param databaseType database type known at stream-open failure time 433 * @param openDuration elapsed time spent attempting to open the stream 434 * @param throwable failure that prevented the stream from opening 435 */ 436 default void didFailToOpenStream(@NonNull StatementContext<?> ctx, 437 @NonNull DatabaseType databaseType, 438 @NonNull Duration openDuration, 439 @NonNull Throwable throwable) { 440 // No-op by default 441 } 442 443 /** 444 * Called after an opened stream reaches a terminal state. 445 * <p> 446 * Pyranid does not emit this callback for streams that fail before they open; those failures are reported through 447 * {@link #didFailToOpenStream(StatementContext, DatabaseType, Duration, Throwable)}. 448 * 449 * @param ctx statement context for the stream 450 * @param outcome terminal stream outcome 451 * @param rowsConsumed number of rows consumed from the stream 452 * @param streamDuration elapsed time between stream-open start and terminal close handling 453 * @param throwable failure associated with the terminal outcome, or {@code null} when no failure is available 454 */ 455 default void didCloseStream(@NonNull StatementContext<?> ctx, 456 @NonNull StreamTerminalOutcome outcome, 457 @NonNull Long rowsConsumed, 458 @NonNull Duration streamDuration, 459 @Nullable Throwable throwable) { 460 // No-op by default 461 } 462 463 /** 464 * Called immediately before Pyranid attempts to open a notification session. 465 * <p> 466 * Argument validation, ambient-transaction rejection, database-type resolution, and backend-specific channel 467 * validation occur before this callback. Exactly one of 468 * {@link #didOpenNotificationSession(DatabaseType, UUID, Duration)} or 469 * {@link #didFailToOpenNotificationSession(DatabaseType, UUID, Duration, Throwable)} follows it. 470 * 471 * @param databaseType database type resolved for the notification session 472 * @param notificationSessionId identifier for this notification-session invocation 473 * @since 4.6.0 474 */ 475 default void willOpenNotificationSession(@NonNull DatabaseType databaseType, 476 @NonNull UUID notificationSessionId) { 477 // No-op by default 478 } 479 480 /** 481 * Called after Pyranid successfully opens a notification session and registers every requested channel. 482 * <p> 483 * This callback occurs before the application operation is dispatched. It does not indicate that application 484 * reconciliation or readiness work has completed. 485 * 486 * @param databaseType database type resolved for the notification session 487 * @param notificationSessionId identifier for this notification-session invocation 488 * @param openDuration elapsed time from the corresponding 489 * {@link #willOpenNotificationSession(DatabaseType, UUID)} callback through successful 490 * channel registration 491 * @since 4.6.0 492 */ 493 default void didOpenNotificationSession(@NonNull DatabaseType databaseType, 494 @NonNull UUID notificationSessionId, 495 @NonNull Duration openDuration) { 496 // No-op by default 497 } 498 499 /** 500 * Called after Pyranid fails to open a notification session. 501 * <p> 502 * This is the terminal lifecycle callback for an invocation that never reached 503 * {@link #didOpenNotificationSession(DatabaseType, UUID, Duration)}. It is not followed by 504 * {@link #didCloseNotificationSession(DatabaseType, UUID, NotificationSessionOutcome, Duration, Throwable)}. 505 * Pyranid emits it after selecting the opening failure and before cleaning up any acquired candidate connection. 506 * 507 * @param databaseType database type resolved for the notification session 508 * @param notificationSessionId identifier for this notification-session invocation 509 * @param openDuration elapsed time from the corresponding 510 * {@link #willOpenNotificationSession(DatabaseType, UUID)} callback through the opening 511 * failure 512 * @param throwable failure that prevented the notification session from opening 513 * @since 4.6.0 514 */ 515 default void didFailToOpenNotificationSession(@NonNull DatabaseType databaseType, 516 @NonNull UUID notificationSessionId, 517 @NonNull Duration openDuration, 518 @NonNull Throwable throwable) { 519 // No-op by default 520 } 521 522 /** 523 * Called when Pyranid delivers a nonempty notification batch to application code. 524 * <p> 525 * Empty receive results and notifications discarded during setup or cleanup are not reported. 526 * 527 * @param databaseType database type resolved for the notification session 528 * @param notificationSessionId identifier for the notification session that delivered the batch 529 * @param notificationCount number of notifications in the delivered batch 530 * @since 4.6.0 531 */ 532 default void didDeliverNotificationBatch(@NonNull DatabaseType databaseType, 533 @NonNull UUID notificationSessionId, 534 @NonNull Long notificationCount) { 535 // No-op by default 536 } 537 538 /** 539 * Called when a receive operation detects terminal uncertainty or loss of an opened notification connection. 540 * <p> 541 * This callback is emitted at most once for a notification session. It does not report setup failures, failures 542 * from ordinary database operations performed by application code, or cleanup-only failures. 543 * 544 * @param databaseType database type resolved for the notification session 545 * @param notificationSessionId identifier for the notification session whose connection was lost 546 * @param throwable terminal connection failure 547 * @since 4.6.0 548 */ 549 default void didLoseNotificationConnection(@NonNull DatabaseType databaseType, 550 @NonNull UUID notificationSessionId, 551 @NonNull Throwable throwable) { 552 // No-op by default 553 } 554 555 /** 556 * Called after an opened notification session reaches a terminal state and cleanup completes. 557 * <p> 558 * Every invocation that emits {@link #didOpenNotificationSession(DatabaseType, UUID, Duration)} emits this callback 559 * exactly once. Invocations that fail before opening terminate through 560 * {@link #didFailToOpenNotificationSession(DatabaseType, UUID, Duration, Throwable)} instead. 561 * 562 * @param databaseType database type resolved for the notification session 563 * @param notificationSessionId identifier for the notification session 564 * @param outcome terminal notification-session outcome 565 * @param sessionDuration elapsed time from the corresponding 566 * {@link #willOpenNotificationSession(DatabaseType, UUID)} callback through completed 567 * cleanup 568 * @param throwable selected failure for {@link NotificationSessionOutcome#FAILED}, or {@code null} for 569 * {@link NotificationSessionOutcome#CALLBACK_RETURNED} and 570 * {@link NotificationSessionOutcome#INTERRUPTED} 571 * @since 4.6.0 572 */ 573 default void didCloseNotificationSession(@NonNull DatabaseType databaseType, 574 @NonNull UUID notificationSessionId, 575 @NonNull NotificationSessionOutcome outcome, 576 @NonNull Duration sessionDuration, 577 @Nullable Throwable throwable) { 578 // No-op by default 579 } 580 581 /** 582 * Returns a notification counter snapshot if this collector supports in-process inspection. 583 * <p> 584 * Implementations may read counters independently without cross-counter atomicity. Callers that need 585 * invariant-consistent snapshots should drain in-flight work before reading. 586 * 587 * @return a notification metrics snapshot, if supported 588 * @since 4.6.0 589 */ 590 @NonNull 591 default Optional<NotificationSnapshot> notificationSnapshot() { 592 return Optional.empty(); 593 } 594 595 /** 596 * Returns a counter snapshot if this collector supports in-process inspection. 597 * <p> 598 * Implementations may read counters independently without cross-counter atomicity. Callers that need invariant-consistent 599 * snapshots should drain in-flight work before reading. 600 * 601 * @return a metrics snapshot, if supported 602 */ 603 @NonNull 604 default Optional<Snapshot> snapshot() { 605 return Optional.empty(); 606 } 607 608 /** 609 * Best-effort reset for test and ad-hoc use. 610 * <p> 611 * Concurrent updates may race with reset operations. Production rolling-window semantics should be implemented outside 612 * this interface. 613 */ 614 default void reset() { 615 // No-op by default 616 } 617 618 /** 619 * Returns the shared no-op metrics collector. 620 * 621 * @return no-op metrics collector used when metrics collection is disabled 622 */ 623 @NonNull 624 static MetricsCollector disabledInstance() { 625 return DisabledMetricsCollector.defaultInstance(); 626 } 627 628 /** 629 * Creates a fresh in-memory counter collector. 630 * <p> 631 * This collector is intended for tests and lightweight local inspection through {@link #snapshot()} and 632 * {@link #notificationSnapshot()}. 633 * 634 * @return new in-memory metrics collector 635 */ 636 @NonNull 637 static MetricsCollector inMemoryInstance() { 638 return InMemoryMetricsCollector.defaultInstance(); 639 } 640 641 /** 642 * Terminal outcome for an opened notification session. 643 * 644 * @since 4.6.0 645 */ 646 enum NotificationSessionOutcome { 647 /** 648 * The application callback returned and notification-session cleanup completed normally. 649 */ 650 CALLBACK_RETURNED, 651 652 /** 653 * Cooperative interruption ended the notification session and cleanup completed normally. 654 */ 655 INTERRUPTED, 656 657 /** 658 * Setup after opening, notification receive, application callback, or cleanup failed. 659 */ 660 FAILED 661 } 662 663 /** 664 * Counter snapshot for notification metrics. 665 * <p> 666 * Implementations may read counters independently without cross-counter atomicity. Callers that need 667 * invariant-consistent snapshots should drain in-flight work before reading. 668 * <p> 669 * Instances are immutable value objects created through {@link #of(Long, Long, Long, Long, Long, Long, Long)}. 670 * Future releases may add counters and accessors while retaining this factory with defined defaults for any 671 * newly added values. 672 * 673 * @since 4.6.0 674 */ 675 @ThreadSafe 676 final class NotificationSnapshot { 677 @NonNull 678 private final Long sessionsStarted; 679 @NonNull 680 private final Long sessionsOpened; 681 @NonNull 682 private final Long sessionsCallbackReturned; 683 @NonNull 684 private final Long sessionsInterrupted; 685 @NonNull 686 private final Long sessionsFailed; 687 @NonNull 688 private final Long batchesDelivered; 689 @NonNull 690 private final Long notificationsDelivered; 691 692 private NotificationSnapshot(@NonNull Long sessionsStarted, 693 @NonNull Long sessionsOpened, 694 @NonNull Long sessionsCallbackReturned, 695 @NonNull Long sessionsInterrupted, 696 @NonNull Long sessionsFailed, 697 @NonNull Long batchesDelivered, 698 @NonNull Long notificationsDelivered) { 699 this.sessionsStarted = requireNonNull(sessionsStarted); 700 this.sessionsOpened = requireNonNull(sessionsOpened); 701 this.sessionsCallbackReturned = requireNonNull(sessionsCallbackReturned); 702 this.sessionsInterrupted = requireNonNull(sessionsInterrupted); 703 this.sessionsFailed = requireNonNull(sessionsFailed); 704 this.batchesDelivered = requireNonNull(batchesDelivered); 705 this.notificationsDelivered = requireNonNull(notificationsDelivered); 706 } 707 708 /** 709 * Creates a notification metrics snapshot. 710 * 711 * @param sessionsStarted valid, type-resolved notification-session invocations that entered measured setup 712 * @param sessionsOpened notification sessions that completed channel registration 713 * @param sessionsCallbackReturned opened notification sessions whose callbacks returned and cleanup completed normally 714 * @param sessionsInterrupted opened notification sessions that ended through clean cooperative interruption 715 * @param sessionsFailed notification-session invocations that failed before opening or after opening 716 * @param batchesDelivered nonempty notification batches delivered to application code 717 * @param notificationsDelivered notifications contained in delivered batches 718 * @return notification metrics snapshot 719 * @throws NullPointerException if any counter is null 720 * @since 4.6.0 721 */ 722 @NonNull 723 public static NotificationSnapshot of(@NonNull Long sessionsStarted, 724 @NonNull Long sessionsOpened, 725 @NonNull Long sessionsCallbackReturned, 726 @NonNull Long sessionsInterrupted, 727 @NonNull Long sessionsFailed, 728 @NonNull Long batchesDelivered, 729 @NonNull Long notificationsDelivered) { 730 return new NotificationSnapshot(sessionsStarted, sessionsOpened, sessionsCallbackReturned, sessionsInterrupted, 731 sessionsFailed, batchesDelivered, notificationsDelivered); 732 } 733 734 /** 735 * @return valid, type-resolved notification-session invocations that entered measured setup 736 * @since 4.6.0 737 */ 738 @NonNull 739 public Long sessionsStarted() { 740 return this.sessionsStarted; 741 } 742 743 /** 744 * @return notification sessions that completed channel registration 745 * @since 4.6.0 746 */ 747 @NonNull 748 public Long sessionsOpened() { 749 return this.sessionsOpened; 750 } 751 752 /** 753 * @return opened notification sessions whose callbacks returned and cleanup completed normally 754 * @since 4.6.0 755 */ 756 @NonNull 757 public Long sessionsCallbackReturned() { 758 return this.sessionsCallbackReturned; 759 } 760 761 /** 762 * @return opened notification sessions that ended through clean cooperative interruption 763 * @since 4.6.0 764 */ 765 @NonNull 766 public Long sessionsInterrupted() { 767 return this.sessionsInterrupted; 768 } 769 770 /** 771 * @return notification-session invocations that failed before opening or after opening 772 * @since 4.6.0 773 */ 774 @NonNull 775 public Long sessionsFailed() { 776 return this.sessionsFailed; 777 } 778 779 /** 780 * @return nonempty notification batches delivered to application code 781 * @since 4.6.0 782 */ 783 @NonNull 784 public Long batchesDelivered() { 785 return this.batchesDelivered; 786 } 787 788 /** 789 * @return notifications contained in delivered batches 790 * @since 4.6.0 791 */ 792 @NonNull 793 public Long notificationsDelivered() { 794 return this.notificationsDelivered; 795 } 796 797 @Override 798 public boolean equals(@Nullable Object object) { 799 if (this == object) 800 return true; 801 802 if (!(object instanceof NotificationSnapshot notificationSnapshot)) 803 return false; 804 805 return sessionsStarted().equals(notificationSnapshot.sessionsStarted()) 806 && sessionsOpened().equals(notificationSnapshot.sessionsOpened()) 807 && sessionsCallbackReturned().equals(notificationSnapshot.sessionsCallbackReturned()) 808 && sessionsInterrupted().equals(notificationSnapshot.sessionsInterrupted()) 809 && sessionsFailed().equals(notificationSnapshot.sessionsFailed()) 810 && batchesDelivered().equals(notificationSnapshot.batchesDelivered()) 811 && notificationsDelivered().equals(notificationSnapshot.notificationsDelivered()); 812 } 813 814 @Override 815 public int hashCode() { 816 return Objects.hash(sessionsStarted(), sessionsOpened(), sessionsCallbackReturned(), sessionsInterrupted(), 817 sessionsFailed(), batchesDelivered(), notificationsDelivered()); 818 } 819 820 @Override 821 @NonNull 822 public String toString() { 823 return "NotificationSnapshot[" + 824 "sessionsStarted=" + sessionsStarted() + 825 ", sessionsOpened=" + sessionsOpened() + 826 ", sessionsCallbackReturned=" + sessionsCallbackReturned() + 827 ", sessionsInterrupted=" + sessionsInterrupted() + 828 ", sessionsFailed=" + sessionsFailed() + 829 ", batchesDelivered=" + batchesDelivered() + 830 ", notificationsDelivered=" + notificationsDelivered() + 831 ']'; 832 } 833 } 834 835 /** 836 * Logical outcome for a closure-based transaction. 837 */ 838 enum TransactionClosureOutcome { 839 /** 840 * The transaction used a physical JDBC transaction and commit completed normally. 841 */ 842 COMMITTED, 843 844 /** 845 * The transaction used a physical JDBC transaction and was rolled back, including a recognized commit-time 846 * serialization failure whose follow-up rollback completed normally. 847 */ 848 ROLLED_BACK, 849 850 /** 851 * The transaction closure exited without ever acquiring a JDBC connection. 852 */ 853 NO_PHYSICAL_TX, 854 855 /** 856 * The transaction failed before Pyranid could report a normal commit or rollback outcome. 857 */ 858 FAILED 859 } 860 861 /** 862 * Physical transaction begin phase that failed. 863 */ 864 enum PhysicalTransactionBeginFailurePhase { 865 /** 866 * Connection acquisition from the configured {@link javax.sql.DataSource} failed. 867 */ 868 ACQUIRE_CONNECTION, 869 870 /** 871 * Reading the connection's initial autocommit setting failed. 872 */ 873 READ_INITIAL_AUTOCOMMIT, 874 875 /** 876 * Reading the connection's initial transaction isolation failed. 877 */ 878 READ_INITIAL_ISOLATION, 879 880 /** 881 * Reading the connection's initial read-only setting failed. 882 */ 883 READ_INITIAL_READ_ONLY, 884 885 /** 886 * Disabling autocommit for the transaction failed. 887 */ 888 SET_AUTOCOMMIT_FALSE, 889 890 /** 891 * Applying the requested transaction isolation failed. 892 */ 893 SET_ISOLATION, 894 895 /** 896 * Applying the requested read-only setting failed. 897 */ 898 SET_READ_ONLY 899 } 900 901 /** 902 * Terminal outcome for an opened stream. 903 */ 904 enum StreamTerminalOutcome { 905 /** 906 * Stream iteration reached the end of the result set and cleanup completed without an iteration or callback failure. 907 */ 908 COMPLETED_NORMALLY, 909 910 /** 911 * The stream was closed before all rows were consumed. 912 */ 913 EARLY_CLOSE, 914 915 /** 916 * The caller-provided stream callback failed. 917 */ 918 CALLBACK_FAILURE, 919 920 /** 921 * Result-set iteration failed while the stream was open. 922 */ 923 ITERATION_FAILURE, 924 925 /** 926 * The stream failed before it opened. 927 * <p> 928 * Pyranid normally reports this through {@link #didFailToOpenStream(StatementContext, DatabaseType, Duration, 929 * Throwable)} instead of {@link #didCloseStream(StatementContext, StreamTerminalOutcome, Long, Duration, Throwable)}. 930 */ 931 OPEN_FAILURE 932 } 933 934 /** 935 * Counter snapshot for collectors that support in-process inspection. 936 * <p> 937 * Implementations may read counters independently without cross-counter atomicity. Callers that need invariant-consistent 938 * snapshots should drain in-flight work before reading. 939 * 940 * @param connectionsAcquiredStatementScope statement-scoped connection acquisitions that completed normally 941 * @param connectionsAcquiredTransactionScope transaction-scoped connection acquisitions that completed normally 942 * @param connectionsFailedStatementScope statement-scoped connection acquisitions that failed 943 * @param connectionsFailedTransactionScope transaction-scoped connection acquisitions that failed 944 * @param connectionReleaseFailuresStatementScope statement-scoped connection releases that failed 945 * @param connectionReleaseFailuresTransactionScope transaction-scoped connection releases that failed 946 * @param transactionClosuresEntered closure-based transactions entered 947 * @param transactionClosuresExited closure-based transactions exited 948 * @param transactionClosuresCommitted closure-based transactions that committed 949 * @param transactionClosuresRolledBack closure-based transactions that rolled back 950 * @param transactionClosuresNoPhysical closure-based transactions that exited without a physical JDBC transaction 951 * @param transactionClosuresFailed closure-based transactions that failed before a normal commit or rollback outcome 952 * @param physicalTransactionsBegun physical JDBC transactions begun 953 * @param physicalTransactionsBeginFailed physical JDBC transactions that failed while beginning 954 * @param physicalTransactionsCommitted physical JDBC transactions committed 955 * @param physicalTransactionsCommitFailed physical JDBC transactions whose commit failed 956 * @param physicalTransactionsRolledBack physical JDBC transactions rolled back 957 * @param physicalTransactionsRollbackFailed physical JDBC transactions whose rollback failed 958 * @param savepointsCreated transaction savepoints created 959 * @param savepointsRolledBack transaction savepoints rolled back to 960 * @param savepointsReleased transaction savepoints released 961 * @param statementsExecuted statements that executed successfully 962 * @param statementsFailed statements that failed during execution 963 * @param streamsOpened streams that opened successfully 964 * @param streamsOpenFailures streams that failed before opening 965 * @param streamsClosedNormally opened streams that reached the end of the result set 966 * @param streamsEarlyClosed opened streams that closed before all rows were consumed 967 * @param streamsCallbackFailed opened streams whose caller-provided callback failed 968 * @param streamsIterationFailed opened streams whose result-set iteration failed 969 * @param postTransactionOperationsRun post-transaction operations that ran 970 * @param postTransactionOperationsFailed post-transaction operations that failed 971 */ 972 @ThreadSafe 973 record Snapshot(@NonNull Long connectionsAcquiredStatementScope, 974 @NonNull Long connectionsAcquiredTransactionScope, 975 @NonNull Long connectionsFailedStatementScope, 976 @NonNull Long connectionsFailedTransactionScope, 977 @NonNull Long connectionReleaseFailuresStatementScope, 978 @NonNull Long connectionReleaseFailuresTransactionScope, 979 @NonNull Long transactionClosuresEntered, 980 @NonNull Long transactionClosuresExited, 981 @NonNull Long transactionClosuresCommitted, 982 @NonNull Long transactionClosuresRolledBack, 983 @NonNull Long transactionClosuresNoPhysical, 984 @NonNull Long transactionClosuresFailed, 985 @NonNull Long physicalTransactionsBegun, 986 @NonNull Long physicalTransactionsBeginFailed, 987 @NonNull Long physicalTransactionsCommitted, 988 @NonNull Long physicalTransactionsCommitFailed, 989 @NonNull Long physicalTransactionsRolledBack, 990 @NonNull Long physicalTransactionsRollbackFailed, 991 @NonNull Long savepointsCreated, 992 @NonNull Long savepointsRolledBack, 993 @NonNull Long savepointsReleased, 994 @NonNull Long statementsExecuted, 995 @NonNull Long statementsFailed, 996 @NonNull Long streamsOpened, 997 @NonNull Long streamsOpenFailures, 998 @NonNull Long streamsClosedNormally, 999 @NonNull Long streamsEarlyClosed, 1000 @NonNull Long streamsCallbackFailed, 1001 @NonNull Long streamsIterationFailed, 1002 @NonNull Long postTransactionOperationsRun, 1003 @NonNull Long postTransactionOperationsFailed) { 1004 } 1005}