Skip to content

Commit

Permalink
Make EdgeDBClient implement AutoCloseable
Browse files Browse the repository at this point in the history
  • Loading branch information
quinchs committed Sep 13, 2023
1 parent 94a3f56 commit 2a54501
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/driver/src/main/java/com/edgedb/driver/EdgeDBClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
/**
* Represents a client pool used to interact with EdgeDB.
*/
public final class EdgeDBClient implements StatefulClient, EdgeDBQueryable {
public final class EdgeDBClient implements StatefulClient, EdgeDBQueryable, AutoCloseable {
private static final Logger logger = LoggerFactory.getLogger(EdgeDBClient.class);

private static final class PooledClient {
Expand Down Expand Up @@ -115,6 +115,10 @@ private EdgeDBClient(@NotNull EdgeDBClient other, Session session) {
this.clientAvailability = other.clientAvailability;
}

public int getClientCount() {
return this.clientCount.get();
}

private @NotNull ClientFactory createClientFactory() throws ConfigurationException {
if(config.getClientType() == ClientType.TCP) {
return EdgeDBTCPClient::new;
Expand Down Expand Up @@ -321,6 +325,15 @@ public CompletionStage<List<Json>> queryJsonElements(@NotNull String query, @Nul
);
}

@Override
public void close() throws Exception {
int count = clientCount.get();
while(!clients.isEmpty() && count > 0) {
clients.poll().client.disconnect().toCompletableFuture().get();
count = clientCount.decrementAndGet();
}
}

private synchronized CompletionStage<BaseEdgeDBClient> getClient() {
logger.trace("polling cached clients...");
var cachedClient = clients.poll();
Expand Down
29 changes: 29 additions & 0 deletions src/driver/src/test/java/ClientTests.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import com.edgedb.driver.EdgeDBClient;
import com.edgedb.driver.exceptions.EdgeDBException;
import org.junit.jupiter.api.Test;

import java.io.IOException;

import static org.assertj.core.api.Assertions.assertThat;

public class ClientTests {
@Test
public void testAutoClose() throws Exception {
EdgeDBClient client;
try {
client = new EdgeDBClient();
} catch (IOException | EdgeDBException e) {
throw new RuntimeException(e);
}

var result = client.querySingle(String.class, "SELECT 'Hello, Java'")
.toCompletableFuture().get();

assertThat(result).isEqualTo("Hello, Java");
assertThat(client.getClientCount()).isEqualTo(1);

client.close();

assertThat(client.getClientCount()).isEqualTo(0);
}
}

0 comments on commit 2a54501

Please sign in to comment.