package com.atlassian.stash.internal.jdbc;

import javax.annotation.Nonnull;
import java.sql.Connection;
import java.util.function.BiConsumer;

/**
 * Tracks leased connections and allows iterating over them.
 *
 * @since 4.0
 */
public interface ConnectionTracker {

    /**
     * Streams {@link #register registered} connections, and the threads that acquired them, to the provided consumer.
     *
     * @param consumer the consumer to receive the connection/thread pairs
     */
    void forEach(BiConsumer<Connection, Thread> consumer);

    /**
     * Retrieves a count of the currently-tracked connections. This should be a close approximation of the number of
     * connections that are currently leased from the underlying database pool.
     *
     * @return the number of tracked connections
     */
    int getConnectionCount();

    /**
     * Registers the provided {@code Connection} for tracking and returns the tracked connection.
     * <p>
     * It is <i>not</i> safe to assume that the provided connection is the returned connection. Exactly how the two
     * relate to each other is <i>not</i> part of this contract. After calling this method, the provided connection
     * should not be used further; only the returned connection should be used.
     *
     * @param connection the connection to track
     * @return the tracked connection
     */
    @Nonnull
    Connection register(@Nonnull Connection connection);
}
