Skip to content

Commit

Permalink
Always set a stats collector
Browse files Browse the repository at this point in the history
  • Loading branch information
pnwpedro committed Oct 29, 2024
1 parent 5699da2 commit 71e2d1a
Show file tree
Hide file tree
Showing 13 changed files with 33 additions and 38 deletions.
4 changes: 2 additions & 2 deletions src/main/java/com/fauna/client/FaunaClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,8 @@ public Logger getLogger() {
return this.logger;
}

public Optional<StatsCollector> getStatsCollector() {
return Optional.ofNullable(this.statsCollector);
public StatsCollector getStatsCollector() {
return this.statsCollector;
}

public Optional<Long> getLastTransactionTs() {
Expand Down
13 changes: 2 additions & 11 deletions src/main/java/com/fauna/client/FaunaConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ public Handler getLogHandler() {

/**
* Gets the stats collector for the client.
* @return A log handler instance.
* @return A StatsCollector instance.
*/
public StatsCollector getStatsCollector() {
return statsCollector;
Expand All @@ -110,7 +110,7 @@ public static class Builder {
private int maxContentionRetries = 3;
private Duration clientTimeoutBuffer = Duration.ofSeconds(5);
private Handler logHandler = defaultLogHandler();
private StatsCollector statsCollector;
private StatsCollector statsCollector = new StatsCollectorImpl();

static Level getLogLevel(String debug) {
if (debug == null || debug.isBlank()) {
Expand Down Expand Up @@ -191,15 +191,6 @@ public Builder statsCollector(StatsCollector statsCollector) {
return this;
}

/**
* Set a default StatsCollector.
* @return The current Builder instance.
*/
public Builder defaultStatsCollector() {
this.statsCollector = new StatsCollectorImpl();
return this;
}

/**
* Builds and returns a new FaunaConfig instance.
*
Expand Down
4 changes: 1 addition & 3 deletions src/main/java/com/fauna/client/FaunaStream.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,7 @@ public void onNext(List<ByteBuffer> buffers) {
JsonParser parser = JSON_FACTORY.createParser(buffer);
StreamEvent<E> event = StreamEvent.parse(parser, dataCodec);

if (statsCollector != null) {
statsCollector.add(event.getStats());
}
statsCollector.add(event.getStats());

if (event.getType() == StreamEvent.EventType.ERROR) {
ErrorInfo error = event.getError();
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/fauna/client/ScopedFaunaClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class ScopedFaunaClient extends FaunaClient {


public ScopedFaunaClient(FaunaClient client, FaunaScope scope) {
super(client.getFaunaSecret(), client.getLogger(), client.getStatsCollector().orElse(null));
super(client.getFaunaSecret(), client.getLogger(), client.getStatsCollector().clone());
this.client = client;
this.requestBuilder = client.getRequestBuilder().scopedRequestBuilder(scope.getToken(client.getFaunaSecret()));
this.streamRequestBuilder = client.getStreamRequestBuilder().scopedRequestBuilder(scope.getToken(client.getFaunaSecret()));
Expand Down
6 changes: 6 additions & 0 deletions src/main/java/com/fauna/client/StatsCollector.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,10 @@ public interface StatsCollector {
* @return Stats object
*/
QueryStatsSummary readAndReset();

/**
* Clone the stats collector instance.
* @return A clone of the stats collector instance.
*/
StatsCollector clone();
}
5 changes: 5 additions & 0 deletions src/main/java/com/fauna/client/StatsCollectorImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -89,5 +89,10 @@ public QueryStatsSummary readAndReset() {
rateLimitedWriteQueryCount.getAndSet(0)
);
}

@Override
public StatsCollector clone() {
return new StatsCollectorImpl();
}
}

2 changes: 1 addition & 1 deletion src/main/java/com/fauna/response/QueryResponse.java
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ public static <T> QuerySuccess<T> parseResponse(HttpResponse<InputStream> respo
builder = handleField(builder, parser);
}

if (statsCollector != null && builder.stats != null) {
if (builder.stats != null) {
statsCollector.add(builder.stats);
}

Expand Down
6 changes: 3 additions & 3 deletions src/test/java/com/fauna/client/FaunaClientTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import static com.fauna.query.builder.Query.fql;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
Expand Down Expand Up @@ -81,7 +82,7 @@ static HttpResponse<InputStream> mockResponse(String body) {
void defaultClient() {
FaunaClient client = Fauna.client();
assertTrue(client.getHttpClient().connectTimeout().isEmpty());
assertTrue(client.getStatsCollector().isEmpty());
assertNotNull(client.getStatsCollector());
assertEquals(URI.create("https://db.fauna.com/query/1"),
client.getRequestBuilder().buildRequest(
fql("hello"), QueryOptions.builder().build(), DefaultCodecProvider.SINGLETON, 1L).uri());
Expand All @@ -104,11 +105,10 @@ void customConfigBuilder() {
void customConfigConstructor() {
FaunaConfig cfg = FaunaConfig.builder()
.secret("foo")
.defaultStatsCollector()
.build();
FaunaClient client = Fauna.client(cfg);
assertTrue(client.toString().startsWith("com.fauna.client.BaseFaunaClient"));
assertTrue(client.getStatsCollector().isPresent());
assertNotNull(client.getStatsCollector());
}

@Test
Expand Down
3 changes: 1 addition & 2 deletions src/test/java/com/fauna/client/FaunaConfigTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public void testDefaultFaunaConfig() {
assertEquals(Level.WARNING, config.getLogHandler().getLevel());
assertEquals("", config.getSecret());
assertEquals(3, config.getMaxContentionRetries());
assertNull(config.getStatsCollector());
assertNotNull(config.getStatsCollector());
}

@Test
Expand All @@ -38,7 +38,6 @@ public void testOverridingDefaultFaunaConfig() {
.logHandler(handler)
.maxContentionRetries(1)
.clientTimeoutBuffer(Duration.ofSeconds(1))
.defaultStatsCollector()
.build();
assertEquals("endpoint", config.getEndpoint());
assertEquals(Level.ALL, config.getLogHandler().getLevel());
Expand Down
6 changes: 2 additions & 4 deletions src/test/java/com/fauna/e2e/E2EPaginationTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -118,13 +118,12 @@ public void query_statsAreTrackedForExplicitPagination() {
var cfg = FaunaConfig.builder()
.secret("secret")
.endpoint("http://localhost:8443")
.defaultStatsCollector()
.build();
var client = Fauna.client(cfg);
PageIterator<Product> iter = client.paginate(fql("Product.all()"), Product.class);
iter.forEachRemaining(page -> {});

var stats = client.getStatsCollector().get().read();
var stats = client.getStatsCollector().read();
assertEquals(82, stats.getReadOps());
assertEquals(4, stats.getComputeOps());
}
Expand All @@ -134,15 +133,14 @@ public void query_statsAreTrackedForFlattenedPagination() {
var cfg = FaunaConfig.builder()
.secret("secret")
.endpoint("http://localhost:8443")
.defaultStatsCollector()
.build();
var client = Fauna.client(cfg);
PageIterator<Product> iter = client.paginate(fql("Product.all()"), Product.class);
Iterator<Product> productIter = iter.flatten();
for (Product p : (Iterable<Product>) () -> productIter) {
}

var stats = client.getStatsCollector().get().read();
var stats = client.getStatsCollector().read();
assertEquals(82, stats.getReadOps());
assertEquals(4, stats.getComputeOps());
}
Expand Down
6 changes: 2 additions & 4 deletions src/test/java/com/fauna/e2e/E2EQueryTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -284,14 +284,13 @@ public void query_trackStatsOnSuccess() {
var cfg = FaunaConfig.builder()
.secret("secret")
.endpoint("http://localhost:8443")
.defaultStatsCollector()
.build();
var client = Fauna.client(cfg);

var q = fql("Author.all().toArray()");

client.query(q, listOf(Author.class));
var stats = client.getStatsCollector().get().read();
var stats = client.getStatsCollector().read();
assertEquals(10, stats.getReadOps());
assertEquals(1, stats.getComputeOps());
}
Expand All @@ -301,13 +300,12 @@ public void query_trackStatsOnFailure() throws IOException {
var cfg = FaunaConfig.builder()
.secret("secret")
.endpoint("http://localhost:8443")
.defaultStatsCollector()
.build();
var client = Fauna.client(cfg);

var q = fql("Author.all().toArray()\nabort(null)");
assertThrows(AbortException.class, () -> client.query(q));
var stats = client.getStatsCollector().get().read();
var stats = client.getStatsCollector().read();
assertEquals(8, stats.getReadOps());
assertEquals(1, stats.getComputeOps());
}
Expand Down
7 changes: 3 additions & 4 deletions src/test/java/com/fauna/e2e/E2EStreamingTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,11 @@ public void query_streamOfProduct() throws InterruptedException {
var cfg = FaunaConfig.builder()
.secret("secret")
.endpoint("http://localhost:8443")
.defaultStatsCollector()
.build();
var streamClient = Fauna.client(cfg);

FaunaStream stream = streamClient.stream(fql("Product.all().toStream()"), Product.class);
var stats = streamClient.getStatsCollector().get().readAndReset();
FaunaStream<Product> stream = streamClient.stream(fql("Product.all().toStream()"), Product.class);
var stats = streamClient.getStatsCollector().readAndReset();
assertEquals(1, stats.getComputeOps());

InventorySubscriber inventory = new InventorySubscriber();
Expand Down Expand Up @@ -153,7 +152,7 @@ public void query_streamOfProduct() throws InterruptedException {
stream.close();
assertTrue(stream.isClosed());

stats = streamClient.getStatsCollector().get().read();
stats = streamClient.getStatsCollector().read();
assertEquals(11, stats.getReadOps());
assertEquals(events, stats.getComputeOps());
}
Expand Down
7 changes: 4 additions & 3 deletions src/test/java/com/fauna/response/QueryResponseTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import static org.mockito.Mockito.when;

import com.fauna.beans.ClassWithAttributes;
import com.fauna.client.StatsCollectorImpl;
import com.fauna.codec.Codec;
import com.fauna.codec.CodecProvider;
import com.fauna.codec.CodecRegistry;
Expand Down Expand Up @@ -55,7 +56,7 @@ public void getFromResponseBody_Success() throws IOException {
HttpResponse resp = mockResponse(body);
when(resp.statusCode()).thenReturn(200);

QuerySuccess<ClassWithAttributes> success = QueryResponse.parseResponse(resp, codec, null);
QuerySuccess<ClassWithAttributes> success = QueryResponse.parseResponse(resp, codec, new StatsCollectorImpl());

assertEquals(baz.getFirstName(), success.getData().getFirstName());
assertEquals("PersonWithAttributes", success.getStaticType().get());
Expand All @@ -68,14 +69,14 @@ public void handleResponseWithInvalidJsonThrowsClientResponseException() {
HttpResponse resp = mockResponse("{\"not valid json\"");
when(resp.statusCode()).thenReturn(400);

ClientResponseException exc = assertThrows(ClientResponseException.class, () -> QueryResponse.parseResponse(resp, codecProvider.get(Object.class), null));
ClientResponseException exc = assertThrows(ClientResponseException.class, () -> QueryResponse.parseResponse(resp, codecProvider.get(Object.class), new StatsCollectorImpl()));
assertEquals("ClientResponseException HTTP 400: Failed to handle error response.", exc.getMessage());
}

@Test
public void handleResponseWithEmptyFieldsDoesNotThrow() {
HttpResponse resp = mockResponse("{}");
QuerySuccess<Object> response = QueryResponse.parseResponse(resp, codecProvider.get(Object.class), null);
QuerySuccess<Object> response = QueryResponse.parseResponse(resp, codecProvider.get(Object.class), new StatsCollectorImpl());
assertEquals(QuerySuccess.class, response.getClass());
assertNull(response.getSchemaVersion());
assertNull(response.getSummary());
Expand Down

0 comments on commit 71e2d1a

Please sign in to comment.