From 82c5ed1398ed8bc3fcdc356cfdb6d48a05a3da68 Mon Sep 17 00:00:00 2001 From: Slav Babanin Date: Fri, 4 Dec 2026 15:21:56 -0700 Subject: [PATCH 1/8] Add the telemetry POC counter store, registry, and sampler Add com.mongodb.internal.telemetry in driver-core. The package holds the ApiCounter registry, the TelemetryStore global counter store, and the TelemetrySampler background job. The sampler drains the counters on an interval, resets them, and writes one JSON line to System.out. The line imitates a delivery channel. The store uses one LongAdder per ApiCounter ordinal. Increment never throws and never allocates. A drain returns the deltas and omits zero counters. A broken counter cannot break an instrumented call. The system properties mongodb.telemetryPoc.enabled and mongodb.telemetryPoc.intervalMs control the kill switch and the sample interval. POC scope: one global static store serves all clients. The real design uses one store per MongoClient. Tests cover 16-thread exactness, drain-and-reset deltas, zero suppression, the kill switch, fault injection, and the sampler output. --- .../internal/telemetry/ApiCounter.java | 63 +++++++ .../internal/telemetry/TelemetrySampler.java | 98 ++++++++++ .../internal/telemetry/TelemetryStore.java | 148 +++++++++++++++ .../internal/telemetry/package-info.java | 26 +++ .../telemetry/TelemetrySamplerTest.java | 91 +++++++++ .../telemetry/TelemetryStoreTest.java | 176 ++++++++++++++++++ 6 files changed, 602 insertions(+) create mode 100644 driver-core/src/main/com/mongodb/internal/telemetry/ApiCounter.java create mode 100644 driver-core/src/main/com/mongodb/internal/telemetry/TelemetrySampler.java create mode 100644 driver-core/src/main/com/mongodb/internal/telemetry/TelemetryStore.java create mode 100644 driver-core/src/main/com/mongodb/internal/telemetry/package-info.java create mode 100644 driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetrySamplerTest.java create mode 100644 driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetryStoreTest.java diff --git a/driver-core/src/main/com/mongodb/internal/telemetry/ApiCounter.java b/driver-core/src/main/com/mongodb/internal/telemetry/ApiCounter.java new file mode 100644 index 0000000000..ad16767ad5 --- /dev/null +++ b/driver-core/src/main/com/mongodb/internal/telemetry/ApiCounter.java @@ -0,0 +1,63 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.telemetry; + +/** + * One counter key of the telemetry POC registry. The registry covers the two Product P0 questions: query construction and bulk writes. + *

+ * Append new values at the end only. Never reuse an ordinal. The ordinal is the array index of the counter store. A changed ordinal + * breaks the index. + *

+ * This class is not part of the public API and may be removed or changed at any time. + */ +public enum ApiCounter { + /** + * The user built a query with a typed builder helper, for example {@code Filters.eq}. + */ + QUERY_BUILDERS("queryBuilders"), + /** + * The user passed a raw filter, as a {@code Document} or a {@code BsonDocument}, to a query method. + */ + QUERY_RAW("queryRaw"), + /** + * The user called the client-level bulk write API. + */ + BULK_WRITE_CLIENT("bulkWriteClient"), + /** + * The user called the collection-level bulk write API. + */ + BULK_WRITE_COLLECTION("bulkWriteCollection"), + /** + * The user started a legacy ordered or unordered bulk operation. + */ + BULK_WRITE_LEGACY("bulkWriteLegacy"); + + private final String key; + + ApiCounter(final String key) { + this.key = key; + } + + /** + * Gets the key name of the counter. The sampler writes this name into the log line. + * + * @return the key name + */ + public String key() { + return key; + } +} diff --git a/driver-core/src/main/com/mongodb/internal/telemetry/TelemetrySampler.java b/driver-core/src/main/com/mongodb/internal/telemetry/TelemetrySampler.java new file mode 100644 index 0000000000..733ac4bdda --- /dev/null +++ b/driver-core/src/main/com/mongodb/internal/telemetry/TelemetrySampler.java @@ -0,0 +1,98 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.telemetry; + +import com.mongodb.internal.thread.DaemonThreadFactory; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.Map; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * The sampler of the telemetry POC. The sampler drains {@link TelemetryStore} on a fixed interval. It writes one JSON line to + * {@code System.out} when at least one counter is non-zero. The line imitates a delivery channel. + *

+ * The line format is: + * {@code {"driver":"java","ts":"","intervalMs":,"apiUsage":{"queryBuilders":12,...}}} + *

+ * This class is not part of the public API and may be removed or changed at any time. + */ +public final class TelemetrySampler implements AutoCloseable { + + private final ScheduledExecutorService executor; + private final long intervalMs; + + /** + * Starts a sampler that samples on the given interval. The sampler runs on one daemon thread. + * + * @param intervalMs the sample interval in milliseconds + * @return the sampler + */ + public static TelemetrySampler start(final long intervalMs) { + ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory("mongodb-telemetry-poc")); + TelemetrySampler sampler = new TelemetrySampler(executor, intervalMs); + executor.scheduleAtFixedRate(sampler::sample, intervalMs, intervalMs, TimeUnit.MILLISECONDS); + return sampler; + } + + TelemetrySampler(final ScheduledExecutorService executor, final long intervalMs) { + this.executor = executor; + this.intervalMs = intervalMs; + } + + /** + * Drains the store and writes one JSON line. The method omits the line when every counter is zero. The method never throws. + */ + void sample() { + try { + Map deltas = TelemetryStore.drain(); + if (!deltas.isEmpty()) { + System.out.println(toJsonLine(deltas)); + } + } catch (final Throwable t) { + // The sampler must not throw. The scheduled task stops on an uncaught exception. + } + } + + String toJsonLine(final Map deltas) { + StringBuilder json = new StringBuilder("{\"driver\":\"java\",\"ts\":\"") + .append(Instant.now().truncatedTo(ChronoUnit.SECONDS)) + .append("\",\"intervalMs\":") + .append(intervalMs) + .append(",\"apiUsage\":{"); + boolean first = true; + for (Map.Entry entry : deltas.entrySet()) { + if (!first) { + json.append(','); + } + first = false; + json.append('"').append(entry.getKey()).append("\":").append(entry.getValue()); + } + return json.append("}}").toString(); + } + + /** + * Stops the sampler. The store keeps the counters. The counters wait for the next drain. + */ + @Override + public void close() { + executor.shutdownNow(); + } +} diff --git a/driver-core/src/main/com/mongodb/internal/telemetry/TelemetryStore.java b/driver-core/src/main/com/mongodb/internal/telemetry/TelemetryStore.java new file mode 100644 index 0000000000..f898a8a872 --- /dev/null +++ b/driver-core/src/main/com/mongodb/internal/telemetry/TelemetryStore.java @@ -0,0 +1,148 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.telemetry; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.concurrent.atomic.LongAdder; + +/** + * The counter store of the telemetry POC. The store holds one {@link LongAdder} for each {@link ApiCounter} value. + *

+ * An instrumented call site reports one API use with {@link #increment}. The method never throws. The method does not allocate. A broken + * counter cannot break the instrumented API. + *

+ * {@link #drain} reads the counters and resets them. The result holds the deltas since the previous drain. The result omits a counter + * with delta zero. + *

+ * POC scope: one global static store serves all clients. The real design uses one store per {@code MongoClient}. See + * {@code java-driver-telemetry-implementation.md}. + *

+ * This class is not part of the public API and may be removed or changed at any time. + */ +public final class TelemetryStore { + + /** + * The system property that disables the complete feature. The value {@code false} turns every counter into a no-op. + */ + public static final String ENABLED_PROPERTY = "mongodb.telemetryPoc.enabled"; + + /** + * The system property that sets the sample interval in milliseconds. The default is 3600000. + */ + public static final String INTERVAL_PROPERTY = "mongodb.telemetryPoc.intervalMs"; + + /** + * The default sample interval: one hour. + */ + public static final long DEFAULT_INTERVAL_MS = 3600000L; + + private static volatile boolean enabled = parseEnabledProperty(); + + /** + * The counters, indexed by {@link ApiCounter} ordinal. The array is visible to tests in this package. A test can corrupt one element + * for fault injection. + */ + static final LongAdder[] counters = new LongAdder[ApiCounter.values().length]; + + static { + try { + for (int i = 0; i < counters.length; i++) { + counters[i] = new LongAdder(); + } + if (enabled) { + TelemetrySampler.start(parseIntervalProperty()); + } + } catch (final Throwable t) { + // The class init must not fail. A failed class init makes every instrumented call site throw. + } + } + + private TelemetryStore() { + } + + /** + * Gets the state of the kill switch. + * + * @return true when the instrumentation is enabled + */ + public static boolean isEnabled() { + return enabled; + } + + /** + * Reports one API use. The method never throws and never allocates. + * + * @param counter the counter to increment + */ + public static void increment(final ApiCounter counter) { + if (!enabled) { + return; + } + try { + counters[counter.ordinal()].increment(); + } catch (final Throwable t) { + // A broken counter must not break the instrumented API. Do not propagate the failure. + } + } + + /** + * Reads every counter and resets it. The result holds the delta since the previous drain. The result omits a counter with delta + * zero. An interval with no use gives an empty result. + * + * @return the non-zero deltas, keyed by counter name, in registry order + */ + public static Map drain() { + Map deltas = new LinkedHashMap<>(); + for (ApiCounter counter : ApiCounter.values()) { + try { + long delta = counters[counter.ordinal()].sumThenReset(); + if (delta != 0) { + deltas.put(counter.key(), delta); + } + } catch (final Throwable t) { + // A broken counter loses its delta. The other counters keep theirs. + } + } + return deltas; + } + + /** + * Sets the kill switch. Tests use this method. A production user sets the system property before the first use of the store. + * + * @param value the new state of the kill switch + */ + static void setEnabledForTest(final boolean value) { + enabled = value; + } + + private static boolean parseEnabledProperty() { + try { + return Boolean.parseBoolean(System.getProperty(ENABLED_PROPERTY, "true")); + } catch (final Throwable t) { + return true; + } + } + + private static long parseIntervalProperty() { + try { + return Long.parseLong(System.getProperty(INTERVAL_PROPERTY, String.valueOf(DEFAULT_INTERVAL_MS))); + } catch (final NumberFormatException e) { + return DEFAULT_INTERVAL_MS; + } + } +} diff --git a/driver-core/src/main/com/mongodb/internal/telemetry/package-info.java b/driver-core/src/main/com/mongodb/internal/telemetry/package-info.java new file mode 100644 index 0000000000..00b21cc7ea --- /dev/null +++ b/driver-core/src/main/com/mongodb/internal/telemetry/package-info.java @@ -0,0 +1,26 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * This package holds the API-usage counters of the instrumentation POC. The package is not part of the public API. It may change or be + * removed at any time. + */ +@Internal +@NonNullApi +package com.mongodb.internal.telemetry; + +import com.mongodb.annotations.Internal; +import com.mongodb.lang.NonNullApi; diff --git a/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetrySamplerTest.java b/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetrySamplerTest.java new file mode 100644 index 0000000000..792a54d175 --- /dev/null +++ b/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetrySamplerTest.java @@ -0,0 +1,91 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.telemetry; + +import org.bson.BsonDocument; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class TelemetrySamplerTest { + + private final PrintStream originalOut = System.out; + + @BeforeEach + public void clearStore() { + TelemetryStore.drain(); + } + + @AfterEach + public void restoreStore() { + TelemetryStore.drain(); + } + + @Test + public void toJsonLineWritesTheDeltasInRegistryOrder() { + TelemetrySampler sampler = new TelemetrySampler(null, 2000); + Map deltas = new LinkedHashMap<>(); + deltas.put("queryBuilders", 12L); + deltas.put("queryRaw", 8L); + BsonDocument parsed = BsonDocument.parse(sampler.toJsonLine(deltas)); + assertEquals("java", parsed.getString("driver").getValue()); + assertEquals(2000, parsed.getNumber("intervalMs").longValue()); + assertTrue(parsed.getString("ts").getValue().endsWith("Z")); + BsonDocument apiUsage = parsed.getDocument("apiUsage"); + assertEquals(12, apiUsage.getNumber("queryBuilders").longValue()); + assertEquals(8, apiUsage.getNumber("queryRaw").longValue()); + } + + @Test + public void theSamplerWritesOneLinePerIntervalWithTheExactDelta() throws Exception { + long intervalMs = 1000; + ByteArrayOutputStream captured = new ByteArrayOutputStream(); + System.setOut(new PrintStream(captured, true, StandardCharsets.UTF_8)); + try (TelemetrySampler sampler = TelemetrySampler.start(intervalMs)) { + runWorkload(); + Thread.sleep(intervalMs * 2 + 500); + } finally { + System.setOut(originalOut); + } + String[] lines = captured.toString(StandardCharsets.UTF_8).split(System.lineSeparator()); + assertEquals(1, lines.length); + BsonDocument parsed = BsonDocument.parse(lines[0]); + assertEquals("java", parsed.getString("driver").getValue()); + assertEquals(intervalMs, parsed.getNumber("intervalMs").longValue()); + BsonDocument apiUsage = parsed.getDocument("apiUsage"); + assertEquals(50, apiUsage.getNumber("queryBuilders").longValue()); + assertEquals(30, apiUsage.getNumber("queryRaw").longValue()); + } + + private static void runWorkload() { + for (int i = 0; i < 50; i++) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); + } + for (int i = 0; i < 30; i++) { + TelemetryStore.increment(ApiCounter.QUERY_RAW); + } + } +} diff --git a/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetryStoreTest.java b/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetryStoreTest.java new file mode 100644 index 0000000000..d3b58bf96c --- /dev/null +++ b/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetryStoreTest.java @@ -0,0 +1,176 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.telemetry; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Map; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.LongAdder; + +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public class TelemetryStoreTest { + + @BeforeEach + public void clearStore() { + assertTrue(TelemetryStore.isEnabled()); + TelemetryStore.drain(); + } + + @AfterEach + public void restoreStore() { + for (int i = 0; i < TelemetryStore.counters.length; i++) { + if (TelemetryStore.counters[i] == null || TelemetryStore.counters[i].getClass() != LongAdder.class) { + TelemetryStore.counters[i] = new LongAdder(); + } + } + TelemetryStore.setEnabledForTest(true); + TelemetryStore.drain(); + } + + @Test + public void sixteenThreadsGiveTheExactTotalOnOneCounter() throws Exception { + int threads = 16; + int incrementsPerThread = 1000; + runInParallel(threads, () -> { + for (int i = 0; i < incrementsPerThread; i++) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); + } + }); + Map deltas = TelemetryStore.drain(); + assertEquals(threads * (long) incrementsPerThread, deltas.get("queryBuilders")); + } + + @Test + public void sixteenThreadsGiveTheExactTotalOnDistinctCounters() throws Exception { + int threads = 16; + ApiCounter[] counters = ApiCounter.values(); + runInParallel(threads, () -> { + for (ApiCounter counter : counters) { + TelemetryStore.increment(counter); + } + }); + Map deltas = TelemetryStore.drain(); + for (ApiCounter counter : counters) { + assertEquals(threads, deltas.get(counter.key()), counter.key()); + } + } + + @Test + public void drainGivesTheDeltaAndResets() { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); + TelemetryStore.increment(ApiCounter.QUERY_RAW); + Map deltas = TelemetryStore.drain(); + assertEquals(2L, deltas.get("queryBuilders")); + assertEquals(1L, deltas.get("queryRaw")); + } + + @Test + public void theSecondDrainInTheSameIntervalIsEmpty() { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); + TelemetryStore.drain(); + assertTrue(TelemetryStore.drain().isEmpty()); + } + + @Test + public void zeroSuppressionOmitsEveryZeroCounter() { + TelemetryStore.increment(ApiCounter.BULK_WRITE_CLIENT); + Map deltas = TelemetryStore.drain(); + assertEquals(1, deltas.size()); + assertEquals(1L, deltas.get("bulkWriteClient")); + } + + @Test + public void theKillSwitchMakesIncrementANoOp() { + TelemetryStore.setEnabledForTest(false); + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); + TelemetryStore.increment(ApiCounter.QUERY_RAW); + assertTrue(TelemetryStore.drain().isEmpty()); + } + + @Test + public void aBrokenCounterDoesNotBreakTheInstrumentedCall() { + TelemetryStore.counters[ApiCounter.QUERY_BUILDERS.ordinal()] = new ThrowingLongAdder(); + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); + TelemetryStore.increment(ApiCounter.QUERY_RAW); + Map deltas = TelemetryStore.drain(); + assertEquals(1L, deltas.get("queryRaw")); + } + + @Test + public void aNullCounterDoesNotBreakTheInstrumentedCall() { + TelemetryStore.counters[ApiCounter.QUERY_BUILDERS.ordinal()] = null; + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); + TelemetryStore.increment(ApiCounter.QUERY_RAW); + Map deltas = TelemetryStore.drain(); + assertEquals(1L, deltas.get("queryRaw")); + } + + private static void runInParallel(final int threads, final Runnable task) throws Exception { + CountDownLatch startGate = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(threads); + try { + for (int i = 0; i < threads; i++) { + executor.submit(() -> { + startGate.await(); + task.run(); + return null; + }); + } + startGate.countDown(); + executor.shutdown(); + assertTrue(executor.awaitTermination(30, SECONDS)); + } finally { + executor.shutdownNow(); + } + } + + private static final class ThrowingLongAdder extends LongAdder { + @Override + public void increment() { + throw new IllegalStateException("fault injection"); + } + + @Override + public void add(final long x) { + throw new IllegalStateException("fault injection"); + } + + @Override + public long sum() { + throw new IllegalStateException("fault injection"); + } + + @Override + public long sumThenReset() { + throw new IllegalStateException("fault injection"); + } + + @Override + public long longValue() { + throw new IllegalStateException("fault injection"); + } + } +} From 8a187f96020299177458e22efd61114f7a01cea4 Mon Sep 17 00:00:00 2001 From: Slav Babanin Date: Fri, 4 Dec 2026 15:25:02 -0700 Subject: [PATCH 2/8] Count query builder helper calls in Filters Instrument the static helper methods of Filters with the queryBuilders counter. Each helper call counts one use. The instrumented methods are the leaf methods: a method that constructs the filter product or calls a private helper. The delegating overloads stay uninstrumented. This rule makes one helper call count exactly one use, also for a nested expression such as and(eq("x", 1), lt("y", 3)). Filters lives in driver-core and has no MongoClient reference. A per-client store cannot bind to a Filters call. The POC therefore uses the global static store. The findings file records the options for the real design. --- .../com/mongodb/client/model/Filters.java | 46 +++++++++++++ .../model/FiltersUsageCountersTest.java | 65 +++++++++++++++++++ 2 files changed, 111 insertions(+) create mode 100644 driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java diff --git a/driver-core/src/main/com/mongodb/client/model/Filters.java b/driver-core/src/main/com/mongodb/client/model/Filters.java index c516fe2893..3504a1cbe0 100644 --- a/driver-core/src/main/com/mongodb/client/model/Filters.java +++ b/driver-core/src/main/com/mongodb/client/model/Filters.java @@ -21,6 +21,8 @@ import com.mongodb.client.model.search.SearchCollector; import com.mongodb.client.model.search.SearchOperator; import com.mongodb.client.model.search.SearchOptions; +import com.mongodb.internal.telemetry.ApiCounter; +import com.mongodb.internal.telemetry.TelemetryStore; import com.mongodb.lang.Nullable; import org.bson.BsonArray; import org.bson.BsonBoolean; @@ -86,6 +88,7 @@ public static Bson eq(@Nullable final TItem value) { * @mongodb.driver.manual reference/operator/query/eq $eq */ public static Bson eq(final String fieldName, @Nullable final TItem value) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new SimpleEncodingFilter<>(fieldName, value); } @@ -99,6 +102,7 @@ public static Bson eq(final String fieldName, @Nullable final TItem valu * @mongodb.driver.manual reference/operator/query/ne $ne */ public static Bson ne(final String fieldName, @Nullable final TItem value) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$ne", fieldName, value); } @@ -112,6 +116,7 @@ public static Bson ne(final String fieldName, @Nullable final TItem valu * @mongodb.driver.manual reference/operator/query/gt $gt */ public static Bson gt(final String fieldName, final TItem value) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$gt", fieldName, value); } @@ -125,6 +130,7 @@ public static Bson gt(final String fieldName, final TItem value) { * @mongodb.driver.manual reference/operator/query/lt $lt */ public static Bson lt(final String fieldName, final TItem value) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$lt", fieldName, value); } @@ -138,6 +144,7 @@ public static Bson lt(final String fieldName, final TItem value) { * @mongodb.driver.manual reference/operator/query/gte $gte */ public static Bson gte(final String fieldName, final TItem value) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$gte", fieldName, value); } @@ -151,6 +158,7 @@ public static Bson gte(final String fieldName, final TItem value) { * @mongodb.driver.manual reference/operator/query/lte $lte */ public static Bson lte(final String fieldName, final TItem value) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$lte", fieldName, value); } @@ -179,6 +187,7 @@ public static Bson in(final String fieldName, final TItem... values) { * @mongodb.driver.manual reference/operator/query/in $in */ public static Bson in(final String fieldName, final Iterable values) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new IterableOperatorFilter<>(fieldName, "$in", values); } @@ -207,6 +216,7 @@ public static Bson nin(final String fieldName, final TItem... values) { * @mongodb.driver.manual reference/operator/query/nin $nin */ public static Bson nin(final String fieldName, final Iterable values) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new IterableOperatorFilter<>(fieldName, "$nin", values); } @@ -227,6 +237,7 @@ public static Bson nin(final String fieldName, final Iterable val * @mongodb.driver.manual reference/operator/query/and $and */ public static Bson and(final Iterable filters) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new AndFilter(filters); } @@ -258,6 +269,7 @@ public static Bson and(final Bson... filters) { * @mongodb.driver.manual reference/operator/query/or $or */ public static Bson or(final Iterable filters) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OrNorFilter(OrNorFilter.Operator.OR, filters); } @@ -290,6 +302,7 @@ public static Bson or(final Bson... filters) { * @mongodb.driver.manual reference/operator/query/not $not */ public static Bson not(final Bson filter) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new NotFilter(filter); } @@ -312,6 +325,7 @@ public static Bson nor(final Bson... filters) { * @mongodb.driver.manual reference/operator/query/nor $nor */ public static Bson nor(final Iterable filters) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OrNorFilter(OrNorFilter.Operator.NOR, filters); } @@ -337,6 +351,7 @@ public static Bson exists(final String fieldName) { */ public static Bson exists(final String fieldName, final boolean exists) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$exists", fieldName, BsonBoolean.valueOf(exists)); } @@ -349,6 +364,7 @@ public static Bson exists(final String fieldName, final boolean exists) { * @mongodb.driver.manual reference/operator/query/type $type */ public static Bson type(final String fieldName, final BsonType type) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$type", fieldName, new BsonInt32(type.getValue())); } @@ -361,6 +377,7 @@ public static Bson type(final String fieldName, final BsonType type) { * @mongodb.driver.manual reference/operator/query/type $type */ public static Bson type(final String fieldName, final String type) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$type", fieldName, new BsonString(type)); } @@ -375,6 +392,7 @@ public static Bson type(final String fieldName, final String type) { * @mongodb.driver.manual reference/operator/query/mod $mod */ public static Bson mod(final String fieldName, final long divisor, final long remainder) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$mod", fieldName, new BsonArray(asList(new BsonInt64(divisor), new BsonInt64(remainder)))); } @@ -401,6 +419,7 @@ public static Bson regex(final String fieldName, final String pattern) { * @mongodb.driver.manual reference/operator/query/regex $regex */ public static Bson regex(final String fieldName, final String pattern, @Nullable final String options) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); notNull("pattern", pattern); return new SimpleFilter(fieldName, new BsonRegularExpression(pattern, options)); } @@ -414,6 +433,7 @@ public static Bson regex(final String fieldName, final String pattern, @Nullable * @mongodb.driver.manual reference/operator/query/regex $regex */ public static Bson regex(final String fieldName, final Pattern pattern) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); notNull("pattern", pattern); return new SimpleEncodingFilter<>(fieldName, pattern); } @@ -448,6 +468,7 @@ public static Bson text(final String search) { * @since 3.2 */ public static Bson text(final String search, final TextSearchOptions textSearchOptions) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); notNull("search", search); notNull("textSearchOptions", textSearchOptions); return new TextFilter(search, textSearchOptions); @@ -461,6 +482,7 @@ public static Bson text(final String search, final TextSearchOptions textSearchO * @mongodb.driver.manual reference/operator/query/where $where */ public static Bson where(final String javaScriptExpression) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); notNull("javaScriptExpression", javaScriptExpression); return new BsonDocument("$where", new BsonString(javaScriptExpression)); } @@ -476,6 +498,7 @@ public static Bson where(final String javaScriptExpression) { * @mongodb.driver.manual reference/operator/query/expr/ $expr */ public static Bson expr(final TExpression expression) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new SimpleEncodingFilter<>("$expr", expression); } @@ -504,6 +527,7 @@ public static Bson all(final String fieldName, final TItem... values) { * @mongodb.driver.manual reference/operator/query/all $all */ public static Bson all(final String fieldName, final Iterable values) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new IterableOperatorFilter<>(fieldName, "$all", values); } @@ -517,6 +541,7 @@ public static Bson all(final String fieldName, final Iterable val * @mongodb.driver.manual reference/operator/query/elemMatch $elemMatch */ public static Bson elemMatch(final String fieldName, final Bson filter) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new Bson() { @Override public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { @@ -534,6 +559,7 @@ public BsonDocument toBsonDocument(final Class documentCl * @mongodb.driver.manual reference/operator/query/size $size */ public static Bson size(final String fieldName, final int size) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$size", fieldName, size); } @@ -548,6 +574,7 @@ public static Bson size(final String fieldName, final int size) { * @since 3.2 */ public static Bson bitsAllClear(final String fieldName, final long bitmask) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$bitsAllClear", fieldName, bitmask); } @@ -562,6 +589,7 @@ public static Bson bitsAllClear(final String fieldName, final long bitmask) { * @since 3.2 */ public static Bson bitsAllSet(final String fieldName, final long bitmask) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$bitsAllSet", fieldName, bitmask); } @@ -576,6 +604,7 @@ public static Bson bitsAllSet(final String fieldName, final long bitmask) { * @since 3.2 */ public static Bson bitsAnyClear(final String fieldName, final long bitmask) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$bitsAnyClear", fieldName, bitmask); } @@ -590,6 +619,7 @@ public static Bson bitsAnyClear(final String fieldName, final long bitmask) { * @since 3.2 */ public static Bson bitsAnySet(final String fieldName, final long bitmask) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$bitsAnySet", fieldName, bitmask); } @@ -604,6 +634,7 @@ public static Bson bitsAnySet(final String fieldName, final long bitmask) { * @mongodb.server.release 2.4 */ public static Bson geoWithin(final String fieldName, final Geometry geometry) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new GeometryOperatorFilter<>("$geoWithin", fieldName, geometry); } @@ -618,6 +649,7 @@ public static Bson geoWithin(final String fieldName, final Geometry geometry) { * @mongodb.server.release 2.4 */ public static Bson geoWithin(final String fieldName, final Bson geometry) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new GeometryOperatorFilter<>("$geoWithin", fieldName, geometry); } @@ -638,6 +670,7 @@ public static Bson geoWithin(final String fieldName, final Bson geometry) { */ public static Bson geoWithinBox(final String fieldName, final double lowerLeftX, final double lowerLeftY, final double upperRightX, final double upperRightY) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); BsonDocument box = new BsonDocument("$box", new BsonArray(asList(new BsonArray(asList(new BsonDouble(lowerLeftX), new BsonDouble(lowerLeftY))), @@ -659,6 +692,7 @@ public static Bson geoWithinBox(final String fieldName, final double lowerLeftX, * @since 3.1 */ public static Bson geoWithinPolygon(final String fieldName, final List> points) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); BsonArray pointsArray = new BsonArray(points.size()); for (List point : points) { pointsArray.add(new BsonArray(asList(new BsonDouble(point.get(0)), new BsonDouble(point.get(1))))); @@ -682,6 +716,7 @@ public static Bson geoWithinPolygon(final String fieldName, final List("$geoIntersects", fieldName, geometry); } @@ -736,6 +773,7 @@ public static Bson geoIntersects(final String fieldName, final Bson geometry) { * @mongodb.server.release 2.4 */ public static Bson geoIntersects(final String fieldName, final Geometry geometry) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new GeometryOperatorFilter<>("$geoIntersects", fieldName, geometry); } @@ -753,6 +791,7 @@ public static Bson geoIntersects(final String fieldName, final Geometry geometry */ public static Bson near(final String fieldName, final Point geometry, @Nullable final Double maxDistance, @Nullable final Double minDistance) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new GeometryOperatorFilter<>("$near", fieldName, geometry, maxDistance, minDistance); } @@ -770,6 +809,7 @@ public static Bson near(final String fieldName, final Point geometry, @Nullable */ public static Bson near(final String fieldName, final Bson geometry, @Nullable final Double maxDistance, @Nullable final Double minDistance) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new GeometryOperatorFilter<>("$near", fieldName, geometry, maxDistance, minDistance); } @@ -788,6 +828,7 @@ public static Bson near(final String fieldName, final Bson geometry, @Nullable f */ public static Bson near(final String fieldName, final double x, final double y, @Nullable final Double maxDistance, @Nullable final Double minDistance) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return createNearFilterDocument(fieldName, x, y, maxDistance, minDistance, "$near"); } @@ -806,6 +847,7 @@ public static Bson near(final String fieldName, final double x, final double y, */ public static Bson nearSphere(final String fieldName, final Point geometry, @Nullable final Double maxDistance, @Nullable final Double minDistance) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new GeometryOperatorFilter<>("$nearSphere", fieldName, geometry, maxDistance, minDistance); } @@ -824,6 +866,7 @@ public static Bson nearSphere(final String fieldName, final Point geometry, @Nul */ public static Bson nearSphere(final String fieldName, final Bson geometry, @Nullable final Double maxDistance, @Nullable final Double minDistance) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new GeometryOperatorFilter<>("$nearSphere", fieldName, geometry, maxDistance, minDistance); } @@ -843,6 +886,7 @@ public static Bson nearSphere(final String fieldName, final Bson geometry, @Null */ public static Bson nearSphere(final String fieldName, final double x, final double y, @Nullable final Double maxDistance, @Nullable final Double minDistance) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return createNearFilterDocument(fieldName, x, y, maxDistance, minDistance, "$nearSphere"); } @@ -856,6 +900,7 @@ public static Bson nearSphere(final String fieldName, final double x, final doub * @mongodb.driver.manual reference/operator/query/jsonSchema/ $jsonSchema */ public static Bson jsonSchema(final Bson schema) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new SimpleEncodingFilter<>("$jsonSchema", schema); } @@ -866,6 +911,7 @@ public static Bson jsonSchema(final Bson schema) { * @since 4.2 */ public static Bson empty() { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new BsonDocument(); } diff --git a/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java b/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java new file mode 100644 index 0000000000..12a8cdd88d --- /dev/null +++ b/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java @@ -0,0 +1,65 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.client.model; + +import com.mongodb.internal.telemetry.TelemetryStore; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class FiltersUsageCountersTest { + + @BeforeEach + @AfterEach + public void clearStore() { + TelemetryStore.drain(); + } + + @Test + public void oneHelperCallCountsOneUse() { + assertNotNull(Filters.eq("x", 1)); + assertEquals(1L, TelemetryStore.drain().get("queryBuilders")); + } + + @Test + public void aDelegatingOverloadCountsOneUse() { + assertNotNull(Filters.eq(1)); + assertNotNull(Filters.and(Filters.eq("x", 1))); + assertNotNull(Filters.or()); + assertNotNull(Filters.exists("x")); + assertNotNull(Filters.text("search")); + assertNotNull(Filters.in("x", 1, 2)); + assertNotNull(Filters.nin("x", 1, 2)); + assertNotNull(Filters.all("x", 1, 2)); + assertNotNull(Filters.regex("x", "pattern")); + // 9 delegating calls count 9 uses. The nested eq("x", 1) counts 1 more. + Map deltas = TelemetryStore.drain(); + assertEquals(10L, deltas.get("queryBuilders")); + } + + @Test + public void nestedHelperCallsCountEveryUse() { + assertNotNull(Filters.and(Filters.eq("x", 1), Filters.lt("y", 3))); + Map deltas = TelemetryStore.drain(); + assertEquals(3L, deltas.get("queryBuilders")); + } +} From 12f78cb20f35e8120e8fae6e47b41d8fee96ceb5 Mon Sep 17 00:00:00 2001 From: Slav Babanin Date: Fri, 4 Dec 2026 15:29:53 -0700 Subject: [PATCH 3/8] Count raw query uses and bulk writes at the sync and legacy call sites Instrument MongoCollectionImpl with the queryRaw counter. A query method counts one raw use when the caller passes a Document or a BsonDocument filter. The check is one instanceof pair at the entry. The method does not walk the document. A hand-built document counts as raw. The counter measures the paradigm, not the correctness. The no-filter overloads of find, countDocuments, and distinct now call the private helpers directly. A synthetic empty filter must not count as a raw query. Update-side methods stay out of scope. The Product question covers query construction only. Instrument the private bulkWrite choke of MongoCollectionImpl with the bulkWriteCollection counter. Instrument the private bulkWrite choke of MongoClusterImpl with the bulkWriteClient counter. Instrument initializeOrderedBulkOperation and initializeUnorderedBulkOperation of DBCollection with the bulkWriteLegacy counter. Tests use TestOperationExecutor, so they need no server. One test uses a lazy client: the initialize methods build the bulk operation without server access. --- .../src/main/com/mongodb/DBCollection.java | 4 + .../DBCollectionUsageCountersTest.java | 41 +++++ .../client/internal/MongoClusterImpl.java | 3 + .../client/internal/MongoCollectionImpl.java | 53 +++++- .../MongoCollectionImplUsageCountersTest.java | 151 ++++++++++++++++++ 5 files changed, 244 insertions(+), 8 deletions(-) create mode 100644 driver-legacy/src/test/unit/com/mongodb/DBCollectionUsageCountersTest.java create mode 100644 driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java diff --git a/driver-legacy/src/main/com/mongodb/DBCollection.java b/driver-legacy/src/main/com/mongodb/DBCollection.java index fdfa0767b8..e18d33d5c0 100644 --- a/driver-legacy/src/main/com/mongodb/DBCollection.java +++ b/driver-legacy/src/main/com/mongodb/DBCollection.java @@ -54,6 +54,8 @@ import com.mongodb.internal.operation.ReadOperationCursor; import com.mongodb.internal.operation.RenameCollectionOperation; import com.mongodb.internal.operation.WriteOperation; +import com.mongodb.internal.telemetry.ApiCounter; +import com.mongodb.internal.telemetry.TelemetryStore; import com.mongodb.lang.Nullable; import org.bson.BsonDocument; import org.bson.BsonDocumentReader; @@ -2018,6 +2020,7 @@ void setObjectFactory(final DBCollectionObjectFactory factory) { * @since 2.12 */ public BulkWriteOperation initializeOrderedBulkOperation() { + TelemetryStore.increment(ApiCounter.BULK_WRITE_LEGACY); return new BulkWriteOperation(true, this); } @@ -2034,6 +2037,7 @@ public BulkWriteOperation initializeOrderedBulkOperation() { * @mongodb.driver.manual reference/method/db.collection.initializeUnorderedBulkOp/ initializeUnorderedBulkOp() */ public BulkWriteOperation initializeUnorderedBulkOperation() { + TelemetryStore.increment(ApiCounter.BULK_WRITE_LEGACY); return new BulkWriteOperation(false, this); } diff --git a/driver-legacy/src/test/unit/com/mongodb/DBCollectionUsageCountersTest.java b/driver-legacy/src/test/unit/com/mongodb/DBCollectionUsageCountersTest.java new file mode 100644 index 0000000000..66aca0ecac --- /dev/null +++ b/driver-legacy/src/test/unit/com/mongodb/DBCollectionUsageCountersTest.java @@ -0,0 +1,41 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb; + +import com.mongodb.internal.telemetry.TelemetryStore; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +public class DBCollectionUsageCountersTest { + + /** + * The client connects lazily. The initialize methods build the bulk operation without server access. The test needs no running + * server. + */ + @Test + public void initializeOrderedAndUnorderedBulkOperationCountOneUseEach() { + TelemetryStore.drain(); + try (MongoClient client = new MongoClient(new ServerAddress("localhost", 27017))) { + DBCollection collection = client.getDB("telemetryPoc").getCollection("coll"); + assertNotNull(collection.initializeOrderedBulkOperation()); + assertNotNull(collection.initializeUnorderedBulkOperation()); + } + assertEquals(2L, TelemetryStore.drain().get("bulkWriteLegacy")); + } +} diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java index 9052670411..446216dc55 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java @@ -60,6 +60,8 @@ import com.mongodb.internal.operation.ReadOperation; import com.mongodb.internal.operation.WriteOperation; import com.mongodb.internal.session.ServerSessionPool; +import com.mongodb.internal.telemetry.ApiCounter; +import com.mongodb.internal.telemetry.TelemetryStore; import com.mongodb.internal.thread.AsyncClientExecutor; import com.mongodb.lang.Nullable; import org.bson.BsonDocument; @@ -407,6 +409,7 @@ private ClientBulkWriteResult executeBulkWrite( @Nullable final ClientSession clientSession, final List clientWriteModels, @Nullable final ClientBulkWriteOptions options) { + TelemetryStore.increment(ApiCounter.BULK_WRITE_CLIENT); isTrue("`autoEncryptionSettings` is null, as bulkWrite does not currently support automatic encryption", autoEncryptionSettings == null); return operationExecutor.execute(operations.clientBulkWriteOperation(clientWriteModels, options), readConcern, clientSession); } diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java index 2641616a2d..cead694fb6 100755 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java @@ -65,6 +65,8 @@ import com.mongodb.internal.client.model.changestream.ChangeStreamLevel; import com.mongodb.internal.operation.IndexHelper; import com.mongodb.internal.operation.Operations; +import com.mongodb.internal.telemetry.ApiCounter; +import com.mongodb.internal.telemetry.TelemetryStore; import com.mongodb.internal.operation.WriteOperation; import com.mongodb.lang.Nullable; import org.bson.BsonDocument; @@ -212,7 +214,8 @@ public MongoCollection withTimeout(final long timeout, final TimeUnit @Override public long countDocuments() { - return countDocuments(new BsonDocument()); + // Bypass the filter-taking overloads. A synthetic empty filter must not count as a raw query. + return executeCount(null, new BsonDocument(), new CountOptions()); } @Override @@ -222,12 +225,15 @@ public long countDocuments(final Bson filter) { @Override public long countDocuments(final Bson filter, final CountOptions options) { + countRawQueryUse(filter); return executeCount(null, filter, options); } @Override public long countDocuments(final ClientSession clientSession) { - return countDocuments(clientSession, new BsonDocument()); + // Bypass the filter-taking overloads. A synthetic empty filter must not count as a raw query. + notNull("clientSession", clientSession); + return executeCount(clientSession, new BsonDocument(), new CountOptions()); } @Override @@ -238,6 +244,7 @@ public long countDocuments(final ClientSession clientSession, final Bson filter) @Override public long countDocuments(final ClientSession clientSession, final Bson filter, final CountOptions options) { notNull("clientSession", clientSession); + countRawQueryUse(filter); return executeCount(clientSession, filter, options); } @@ -257,26 +264,41 @@ private long executeCount(@Nullable final ClientSession clientSession, final Bso .execute(operations.countDocuments(filter, options), readPreference, readConcern, clientSession); } + /** + * Counts one query use when the filter is a raw document. The check is one instanceof pair. The method does not walk or analyze the + * document. A hand-built document counts as raw. The counter measures the paradigm, not the correctness. + */ + private static void countRawQueryUse(@Nullable final Bson filter) { + if (filter instanceof Document || filter instanceof BsonDocument) { + TelemetryStore.increment(ApiCounter.QUERY_RAW); + } + } + @Override public DistinctIterable distinct(final String fieldName, final Class resultClass) { - return distinct(fieldName, new BsonDocument(), resultClass); + // Bypass the filter-taking overloads. A synthetic empty filter must not count as a raw query. + return createDistinctIterable(null, fieldName, new BsonDocument(), resultClass); } @Override public DistinctIterable distinct(final String fieldName, final Bson filter, final Class resultClass) { + countRawQueryUse(filter); return createDistinctIterable(null, fieldName, filter, resultClass); } @Override public DistinctIterable distinct(final ClientSession clientSession, final String fieldName, final Class resultClass) { - return distinct(clientSession, fieldName, new BsonDocument(), resultClass); + // Bypass the filter-taking overloads. A synthetic empty filter must not count as a raw query. + notNull("clientSession", clientSession); + return createDistinctIterable(clientSession, fieldName, new BsonDocument(), resultClass); } @Override public DistinctIterable distinct(final ClientSession clientSession, final String fieldName, final Bson filter, final Class resultClass) { notNull("clientSession", clientSession); + countRawQueryUse(filter); return createDistinctIterable(clientSession, fieldName, filter, resultClass); } @@ -288,12 +310,14 @@ private DistinctIterable createDistinctIterable(@Nullable fin @Override public FindIterable find() { - return find(new BsonDocument(), documentClass); + // Bypass the filter-taking overloads. A synthetic empty filter must not count as a raw query. + return createFindIterable(null, new BsonDocument(), documentClass); } @Override public FindIterable find(final Class resultClass) { - return find(new BsonDocument(), resultClass); + // Bypass the filter-taking overloads. A synthetic empty filter must not count as a raw query. + return createFindIterable(null, new BsonDocument(), resultClass); } @Override @@ -303,19 +327,22 @@ public FindIterable find(final Bson filter) { @Override public FindIterable find(final Bson filter, final Class resultClass) { + countRawQueryUse(filter); return createFindIterable(null, filter, resultClass); } @Override public FindIterable find(final ClientSession clientSession) { + // Bypass the filter-taking overloads. A synthetic empty filter must not count as a raw query. notNull("clientSession", clientSession); - return find(clientSession, new BsonDocument(), documentClass); + return createFindIterable(clientSession, new BsonDocument(), documentClass); } @Override public FindIterable find(final ClientSession clientSession, final Class resultClass) { + // Bypass the filter-taking overloads. A synthetic empty filter must not count as a raw query. notNull("clientSession", clientSession); - return find(clientSession, new BsonDocument(), resultClass); + return createFindIterable(clientSession, new BsonDocument(), resultClass); } @Override @@ -328,6 +355,7 @@ public FindIterable find(final ClientSession clientSession, final Bso public FindIterable find(final ClientSession clientSession, final Bson filter, final Class resultClass) { notNull("clientSession", clientSession); + countRawQueryUse(filter); return createFindIterable(clientSession, filter, resultClass); } @@ -479,6 +507,7 @@ private BulkWriteResult executeBulkWrite(@Nullable final ClientSession clientSes final List> requests, final BulkWriteOptions options) { notNull("requests", requests); + TelemetryStore.increment(ApiCounter.BULK_WRITE_COLLECTION); return getExecutor(timeoutSettings) .execute(operations.bulkWrite(requests, options), readConcern, clientSession); } @@ -548,6 +577,7 @@ public DeleteResult deleteOne(final Bson filter) { @Override public DeleteResult deleteOne(final Bson filter, final DeleteOptions options) { + countRawQueryUse(filter); return executeDelete(null, filter, options, false); } @@ -559,6 +589,7 @@ public DeleteResult deleteOne(final ClientSession clientSession, final Bson filt @Override public DeleteResult deleteOne(final ClientSession clientSession, final Bson filter, final DeleteOptions options) { notNull("clientSession", clientSession); + countRawQueryUse(filter); return executeDelete(clientSession, filter, options, false); } @@ -569,6 +600,7 @@ public DeleteResult deleteMany(final Bson filter) { @Override public DeleteResult deleteMany(final Bson filter, final DeleteOptions options) { + countRawQueryUse(filter); return executeDelete(null, filter, options, true); } @@ -580,6 +612,7 @@ public DeleteResult deleteMany(final ClientSession clientSession, final Bson fil @Override public DeleteResult deleteMany(final ClientSession clientSession, final Bson filter, final DeleteOptions options) { notNull("clientSession", clientSession); + countRawQueryUse(filter); return executeDelete(clientSession, filter, options, true); } @@ -729,6 +762,7 @@ public TDocument findOneAndDelete(final ClientSession clientSession, final Bson @Nullable private TDocument executeFindOneAndDelete(@Nullable final ClientSession clientSession, final Bson filter, final FindOneAndDeleteOptions options) { + countRawQueryUse(filter); return getExecutor(operations.createTimeoutSettings(options)) .execute(operations.findOneAndDelete(filter, options), readConcern, clientSession); } @@ -762,6 +796,7 @@ public TDocument findOneAndReplace(final ClientSession clientSession, final Bson @Nullable private TDocument executeFindOneAndReplace(@Nullable final ClientSession clientSession, final Bson filter, final TDocument replacement, final FindOneAndReplaceOptions options) { + countRawQueryUse(filter); return getExecutor(operations.createTimeoutSettings(options)) .execute(operations.findOneAndReplace(filter, replacement, options), readConcern, clientSession); } @@ -795,6 +830,7 @@ public TDocument findOneAndUpdate(final ClientSession clientSession, final Bson @Nullable private TDocument executeFindOneAndUpdate(@Nullable final ClientSession clientSession, final Bson filter, final Bson update, final FindOneAndUpdateOptions options) { + countRawQueryUse(filter); return getExecutor(operations.createTimeoutSettings(options)) .execute(operations.findOneAndUpdate(filter, update, options), readConcern, clientSession); } @@ -828,6 +864,7 @@ public TDocument findOneAndUpdate(final ClientSession clientSession, final Bson @Nullable private TDocument executeFindOneAndUpdate(@Nullable final ClientSession clientSession, final Bson filter, final List update, final FindOneAndUpdateOptions options) { + countRawQueryUse(filter); return getExecutor(operations.createTimeoutSettings(options)) .execute(operations.findOneAndUpdate(filter, update, options), readConcern, clientSession); } diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java new file mode 100644 index 0000000000..a8ac9162e0 --- /dev/null +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java @@ -0,0 +1,151 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.client.internal; + +import com.mongodb.MongoClientSettings; +import com.mongodb.MongoNamespace; +import com.mongodb.ReadConcern; +import com.mongodb.ReadPreference; +import com.mongodb.bulk.BulkWriteResult; +import com.mongodb.client.model.DeleteOptions; +import com.mongodb.client.model.InsertOneModel; +import com.mongodb.internal.telemetry.TelemetryStore; +import org.bson.BsonDocument; +import org.bson.BsonInt32; +import org.bson.Document; +import org.bson.UuidRepresentation; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS; +import static com.mongodb.WriteConcern.ACKNOWLEDGED; +import static com.mongodb.internal.bulk.WriteRequest.Type.DELETE; +import static com.mongodb.client.model.Filters.eq; +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.assertTrue; + +public class MongoCollectionImplUsageCountersTest { + + private MongoCollectionImpl collection; + + @BeforeEach + public void setUp() { + TelemetryStore.drain(); + collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of()))); + } + + @AfterEach + public void clearStore() { + TelemetryStore.drain(); + } + + @Test + public void findWithARawDocumentFilterCountsOneQueryRaw() { + collection.find(new Document("x", 1)); + Map deltas = TelemetryStore.drain(); + assertEquals(1L, deltas.get("queryRaw")); + assertFalse(deltas.containsKey("queryBuilders")); + } + + @Test + public void findWithARawBsonDocumentFilterCountsOneQueryRaw() { + collection.find(new BsonDocument("x", new BsonInt32(1))); + assertEquals(1L, TelemetryStore.drain().get("queryRaw")); + } + + @Test + public void findWithABuilderFilterCountsNoQueryRaw() { + collection.find(eq("x", 1)); + Map deltas = TelemetryStore.drain(); + assertEquals(1L, deltas.get("queryBuilders")); + assertFalse(deltas.containsKey("queryRaw")); + } + + @Test + public void findWithNoFilterCountsNothing() { + collection.find(); + collection.find(Document.class); + assertTrue(TelemetryStore.drain().isEmpty()); + } + + @Test + public void countDocumentsWithARawFilterCountsOneQueryRaw() { + collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(1L)))); + assertEquals(1L, collection.countDocuments(new Document("x", 1))); + assertEquals(1L, TelemetryStore.drain().get("queryRaw")); + } + + @Test + public void distinctWithARawFilterCountsOneQueryRaw() { + collection.distinct("x", new Document("x", 1), Integer.class); + assertEquals(1L, TelemetryStore.drain().get("queryRaw")); + } + + @Test + public void deleteManyWithARawFilterCountsOneQueryRaw() { + collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(BulkWriteResult.acknowledged(DELETE, 1, 0, List.of(), List.of()))))); + assertNotNull(collection.deleteMany(new Document("x", 1))); + assertEquals(1L, TelemetryStore.drain().get("queryRaw")); + } + + @Test + public void deleteOneWithARawFilterCountsOneQueryRaw() { + collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(BulkWriteResult.acknowledged(DELETE, 1, 0, List.of(), List.of()))))); + assertNotNull(collection.deleteOne(new BsonDocument())); + assertEquals(1L, TelemetryStore.drain().get("queryRaw")); + } + + @Test + public void findOneAndDeleteWithARawFilterCountsOneQueryRaw() { + collection = newCollection(new TestOperationExecutor(new ArrayList<>(Collections.singletonList(null)))); + assertNull(collection.findOneAndDelete(new Document("x", 1))); + assertEquals(1L, TelemetryStore.drain().get("queryRaw")); + } + + @Test + public void bulkWriteCountsOneBulkWriteCollection() { + collection = newCollection(new TestOperationExecutor(new ArrayList<>( + List.of(BulkWriteResult.acknowledged(1, 0, 0, null, List.of(), List.of()))))); + assertNotNull(collection.bulkWrite(List.of(new InsertOneModel<>(new Document("x", 1))))); + Map deltas = TelemetryStore.drain(); + assertEquals(1L, deltas.get("bulkWriteCollection")); + assertFalse(deltas.containsKey("queryRaw")); + } + + @Test + public void aDelegatingOverloadCountsOneUseOnly() { + collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(BulkWriteResult.acknowledged(DELETE, 1, 0, List.of(), List.of()), BulkWriteResult.acknowledged(DELETE, 1, 0, List.of(), List.of()))))); + collection.deleteMany(new Document("x", 1)); + collection.deleteMany(new BsonDocument("x", new BsonInt32(1)), new DeleteOptions()); + assertEquals(2L, TelemetryStore.drain().get("queryRaw")); + } + + private static MongoCollectionImpl newCollection(final TestOperationExecutor executor) { + return new MongoCollectionImpl<>(new MongoNamespace("db", "coll"), Document.class, + MongoClientSettings.getDefaultCodecRegistry(), ReadPreference.secondary(), ACKNOWLEDGED, + true, true, null, ReadConcern.MAJORITY, UuidRepresentation.JAVA_LEGACY, null, TIMEOUT_SETTINGS, executor); + } +} From 76aa97dd705cf5cdbb35fb1a1a54b0e3ad626e54 Mon Sep 17 00:00:00 2001 From: Slav Babanin Date: Fri, 4 Dec 2026 15:35:45 -0700 Subject: [PATCH 4/8] Add the instrumentation POC demo and its one-command runner Add InstrumentationPocDemo in driver-legacy. The legacy module sees driver-core, driver-sync, and the legacy API, so one demo covers every counter. The demo.md plan asks for a demo in driver-core, but driver-core cannot see the sync and legacy call sites. The findings file records this deviation. The demo sets the interval property before the store initializes. The sampler then starts at the configured interval. The demo offsets the round grid by a quarter of the sample interval. Each sample window then holds exactly four rounds, and the deltas match the workload plan exactly. The Gradle task telemetryPocDemo runs the demo with one command. The task forwards the mongodb.telemetryPoc system properties. The operator proves the kill switch with -Dmongodb.telemetryPoc.enabled=false: the demo prints no lines, and the operations still succeed. --- driver-legacy/build.gradle.kts | 16 +++ .../telemetry/InstrumentationPocDemo.java | 113 ++++++++++++++++++ 2 files changed, 129 insertions(+) create mode 100644 driver-legacy/src/test/unit/com/mongodb/telemetry/InstrumentationPocDemo.java diff --git a/driver-legacy/build.gradle.kts b/driver-legacy/build.gradle.kts index ca2288d8a2..b2b54ed589 100644 --- a/driver-legacy/build.gradle.kts +++ b/driver-legacy/build.gradle.kts @@ -49,3 +49,19 @@ configureMavenPublication { // Disable the manifest for driver-legacy as its not a valid OSGI package configureJarManifest { attributes["-nomanifest"] = true } + +// Runs the instrumentation POC demo. One command: ./gradlew :driver-legacy:telemetryPocDemo. Stop +// it with Ctrl+C. +// The task forwards mongodb.telemetryPoc system properties, so -Dmongodb.telemetryPoc.enabled=false +// proves the kill switch. +val telemetryPocDemo by + tasks.registering(JavaExec::class) { + description = "Runs the instrumentation POC demo against a local mongod." + group = "verification" + mainClass.set("com.mongodb.telemetry.InstrumentationPocDemo") + classpath = sourceSets.test.get().runtimeClasspath + standardInput = System.`in` + System.getProperties() + .filterKeys { it.toString().startsWith("mongodb.telemetryPoc") } + .forEach { key, value -> systemProperty(key.toString(), value) } + } diff --git a/driver-legacy/src/test/unit/com/mongodb/telemetry/InstrumentationPocDemo.java b/driver-legacy/src/test/unit/com/mongodb/telemetry/InstrumentationPocDemo.java new file mode 100644 index 0000000000..9ff152bf8a --- /dev/null +++ b/driver-legacy/src/test/unit/com/mongodb/telemetry/InstrumentationPocDemo.java @@ -0,0 +1,113 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.telemetry; + +import com.mongodb.DB; +import com.mongodb.DBCollection; +import com.mongodb.MongoClientURI; +import com.mongodb.MongoNamespace; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.MongoCollection; +import com.mongodb.client.model.Filters; +import com.mongodb.client.model.InsertOneModel; +import com.mongodb.client.model.bulk.ClientNamespacedWriteModel; +import com.mongodb.internal.telemetry.TelemetryStore; +import org.bson.BsonDocument; +import org.bson.BsonInt32; +import org.bson.Document; + +import java.util.List; + +import static com.mongodb.BasicDBObjectBuilder.start; + +/** + * The demo of the instrumentation POC. The demo runs a workload loop. The sampler writes one JSON line per interval. The operator stops + * the demo with Ctrl+C. + *

+ * The demo sets the sample interval before the first instrumented call. The store reads the interval property once, at class + * initialization. + *

+ * The environment variable {@code MONGODB_TELEMETRY_POC_URI} overrides the target. The default target is + * {@code mongodb://localhost:27017}. The kill switch {@code mongodb.telemetryPoc.enabled=false} turns off every counter. The demo then + * prints no lines, and the operations still succeed. + */ +public final class InstrumentationPocDemo { + + private static final long INTERVAL_MS = 2000; + private static final long ROUND_MS = 500; + + public static void main(final String[] notUsed) throws Exception { + if (System.getProperty(TelemetryStore.INTERVAL_PROPERTY) == null) { + System.setProperty(TelemetryStore.INTERVAL_PROPERTY, String.valueOf(INTERVAL_MS)); + } + String uri = System.getenv().getOrDefault("MONGODB_TELEMETRY_POC_URI", "mongodb://localhost:27017"); + System.out.println("[instrumentation-poc] connected: " + uri + ", interval: " + + System.getProperty(TelemetryStore.INTERVAL_PROPERTY) + "ms"); + System.out.println("[instrumentation-poc] workload: 3 builder, 2 raw, 1 bulk per " + ROUND_MS + "ms; " + + "legacy every 4th round; client bulk every 8th round"); + + try (MongoClient client = MongoClients.create(uri); + com.mongodb.MongoClient legacyClient = new com.mongodb.MongoClient(new MongoClientURI(uri))) { + MongoCollection collection = client.getDatabase("telemetryPoc").getCollection("demo"); + DB legacyDatabase = legacyClient.getDB("telemetryPoc"); + // The drain call starts the store and the sampler at a known time. It also clears startup residue. + TelemetryStore.drain(); + long round = 0; + // Offset the round grid by a quarter of the sample interval. The counter increments then stay far from the sample + // boundaries, and each sample window holds exactly four rounds. + long nextRoundAt = System.nanoTime() + INTERVAL_MS * 1_000_000L / 8; + while (true) { + round++; + runRound(client, collection, legacyDatabase.getCollection("demo"), round); + nextRoundAt += ROUND_MS * 1_000_000L; + long sleepNanos = nextRoundAt - System.nanoTime(); + if (sleepNanos > 0) { + Thread.sleep(sleepNanos / 1_000_000L, (int) (sleepNanos % 1_000_000L)); + } + } + } + } + + private static void runRound(final MongoClient client, final MongoCollection collection, + final DBCollection legacyCollection, final long round) throws Exception { + // 3 builder queries: queryBuilders +3 per round. + for (int i = 0; i < 3; i++) { + collection.find(Filters.eq("round", round)).first(); + } + // 2 raw queries: queryRaw +2 per round. + collection.find(new Document("round", round)).first(); + collection.find(new BsonDocument("round", new BsonInt32((int) round))).first(); + // 1 collection-level bulk write: bulkWriteCollection +1 per round. + collection.bulkWrite(List.of(new InsertOneModel<>(new Document("op", "collectionBulk").append("round", round)))); + // 1 legacy bulk write every 4th round: bulkWriteLegacy +1 per fourth round. + if (round % 4 == 0) { + com.mongodb.BulkWriteOperation legacyBulk = legacyCollection.initializeOrderedBulkOperation(); + legacyBulk.insert(start().append("op", "legacyBulk").append("round", round).get()); + legacyBulk.execute(); + } + // 1 client-level bulk write every 8th round: bulkWriteClient +1 per eighth round. + if (round % 8 == 0) { + client.bulkWrite(List.of(ClientNamespacedWriteModel.insertOne( + new MongoNamespace("telemetryPoc", "demo"), + new Document("op", "clientBulk").append("round", round)))); + } + } + + private InstrumentationPocDemo() { + } +} From 5f62b4b0cb0bcad90a3f0f5d8b3f6547c117be2b Mon Sep 17 00:00:00 2001 From: Slav Babanin Date: Fri, 4 Dec 2026 18:50:04 -0700 Subject: [PATCH 5/8] Classify filter nodes at render time The first design counted construction calls in the Filters statics. Review found two defects. First, a combinator around raw documents, for example nor(rawDocument, rawDocument), counted as builder although the content was raw. Second, empty() and where() return a plain BsonDocument, so a query with them counted as builder and raw. The corrected design counts the nodes at the render. The toBsonDocument methods of the Filters leaf classes increment queryBuilders once per builder node. The combinator loops check each child class before the child renders: a Document or a BsonDocument child increments queryRaw. A combinator does not count itself. The classification measures the content, not the wrapper. The design uses no gate. A customer render outside a query execution counts too. The design accepts this noise. A raw root never passes through a Filters class. The entry check in MongoCollectionImpl keeps the raw root. It reads the filter object at the call, so the lazy iterable of find is not a problem. empty() and where() classify as raw through the entry check. The counter measures executions. A retried query renders again and counts again. The demo output is unchanged: the demo queries are single-node. --- .../com/mongodb/client/model/Filters.java | 65 ++++++----------- .../model/FiltersUsageCountersTest.java | 69 ++++++++++++++----- .../telemetry/TelemetryStoreTest.java | 6 +- .../MongoCollectionImplUsageCountersTest.java | 57 ++++++++++++++- 4 files changed, 131 insertions(+), 66 deletions(-) diff --git a/driver-core/src/main/com/mongodb/client/model/Filters.java b/driver-core/src/main/com/mongodb/client/model/Filters.java index 3504a1cbe0..5029ea200d 100644 --- a/driver-core/src/main/com/mongodb/client/model/Filters.java +++ b/driver-core/src/main/com/mongodb/client/model/Filters.java @@ -35,6 +35,7 @@ import org.bson.BsonString; import org.bson.BsonType; import org.bson.BsonValue; +import org.bson.Document; import org.bson.codecs.configuration.CodecRegistry; import org.bson.conversions.Bson; @@ -88,7 +89,6 @@ public static Bson eq(@Nullable final TItem value) { * @mongodb.driver.manual reference/operator/query/eq $eq */ public static Bson eq(final String fieldName, @Nullable final TItem value) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new SimpleEncodingFilter<>(fieldName, value); } @@ -102,7 +102,6 @@ public static Bson eq(final String fieldName, @Nullable final TItem valu * @mongodb.driver.manual reference/operator/query/ne $ne */ public static Bson ne(final String fieldName, @Nullable final TItem value) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$ne", fieldName, value); } @@ -116,7 +115,6 @@ public static Bson ne(final String fieldName, @Nullable final TItem valu * @mongodb.driver.manual reference/operator/query/gt $gt */ public static Bson gt(final String fieldName, final TItem value) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$gt", fieldName, value); } @@ -130,7 +128,6 @@ public static Bson gt(final String fieldName, final TItem value) { * @mongodb.driver.manual reference/operator/query/lt $lt */ public static Bson lt(final String fieldName, final TItem value) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$lt", fieldName, value); } @@ -144,7 +141,6 @@ public static Bson lt(final String fieldName, final TItem value) { * @mongodb.driver.manual reference/operator/query/gte $gte */ public static Bson gte(final String fieldName, final TItem value) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$gte", fieldName, value); } @@ -158,7 +154,6 @@ public static Bson gte(final String fieldName, final TItem value) { * @mongodb.driver.manual reference/operator/query/lte $lte */ public static Bson lte(final String fieldName, final TItem value) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$lte", fieldName, value); } @@ -187,7 +182,6 @@ public static Bson in(final String fieldName, final TItem... values) { * @mongodb.driver.manual reference/operator/query/in $in */ public static Bson in(final String fieldName, final Iterable values) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new IterableOperatorFilter<>(fieldName, "$in", values); } @@ -216,7 +210,6 @@ public static Bson nin(final String fieldName, final TItem... values) { * @mongodb.driver.manual reference/operator/query/nin $nin */ public static Bson nin(final String fieldName, final Iterable values) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new IterableOperatorFilter<>(fieldName, "$nin", values); } @@ -237,7 +230,6 @@ public static Bson nin(final String fieldName, final Iterable val * @mongodb.driver.manual reference/operator/query/and $and */ public static Bson and(final Iterable filters) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new AndFilter(filters); } @@ -269,7 +261,6 @@ public static Bson and(final Bson... filters) { * @mongodb.driver.manual reference/operator/query/or $or */ public static Bson or(final Iterable filters) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OrNorFilter(OrNorFilter.Operator.OR, filters); } @@ -302,7 +293,6 @@ public static Bson or(final Bson... filters) { * @mongodb.driver.manual reference/operator/query/not $not */ public static Bson not(final Bson filter) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new NotFilter(filter); } @@ -325,7 +315,6 @@ public static Bson nor(final Bson... filters) { * @mongodb.driver.manual reference/operator/query/nor $nor */ public static Bson nor(final Iterable filters) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OrNorFilter(OrNorFilter.Operator.NOR, filters); } @@ -351,7 +340,6 @@ public static Bson exists(final String fieldName) { */ public static Bson exists(final String fieldName, final boolean exists) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$exists", fieldName, BsonBoolean.valueOf(exists)); } @@ -364,7 +352,6 @@ public static Bson exists(final String fieldName, final boolean exists) { * @mongodb.driver.manual reference/operator/query/type $type */ public static Bson type(final String fieldName, final BsonType type) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$type", fieldName, new BsonInt32(type.getValue())); } @@ -377,7 +364,6 @@ public static Bson type(final String fieldName, final BsonType type) { * @mongodb.driver.manual reference/operator/query/type $type */ public static Bson type(final String fieldName, final String type) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$type", fieldName, new BsonString(type)); } @@ -392,7 +378,6 @@ public static Bson type(final String fieldName, final String type) { * @mongodb.driver.manual reference/operator/query/mod $mod */ public static Bson mod(final String fieldName, final long divisor, final long remainder) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$mod", fieldName, new BsonArray(asList(new BsonInt64(divisor), new BsonInt64(remainder)))); } @@ -419,7 +404,6 @@ public static Bson regex(final String fieldName, final String pattern) { * @mongodb.driver.manual reference/operator/query/regex $regex */ public static Bson regex(final String fieldName, final String pattern, @Nullable final String options) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); notNull("pattern", pattern); return new SimpleFilter(fieldName, new BsonRegularExpression(pattern, options)); } @@ -433,7 +417,6 @@ public static Bson regex(final String fieldName, final String pattern, @Nullable * @mongodb.driver.manual reference/operator/query/regex $regex */ public static Bson regex(final String fieldName, final Pattern pattern) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); notNull("pattern", pattern); return new SimpleEncodingFilter<>(fieldName, pattern); } @@ -468,7 +451,6 @@ public static Bson text(final String search) { * @since 3.2 */ public static Bson text(final String search, final TextSearchOptions textSearchOptions) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); notNull("search", search); notNull("textSearchOptions", textSearchOptions); return new TextFilter(search, textSearchOptions); @@ -482,7 +464,6 @@ public static Bson text(final String search, final TextSearchOptions textSearchO * @mongodb.driver.manual reference/operator/query/where $where */ public static Bson where(final String javaScriptExpression) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); notNull("javaScriptExpression", javaScriptExpression); return new BsonDocument("$where", new BsonString(javaScriptExpression)); } @@ -498,7 +479,6 @@ public static Bson where(final String javaScriptExpression) { * @mongodb.driver.manual reference/operator/query/expr/ $expr */ public static Bson expr(final TExpression expression) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new SimpleEncodingFilter<>("$expr", expression); } @@ -527,7 +507,6 @@ public static Bson all(final String fieldName, final TItem... values) { * @mongodb.driver.manual reference/operator/query/all $all */ public static Bson all(final String fieldName, final Iterable values) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new IterableOperatorFilter<>(fieldName, "$all", values); } @@ -541,10 +520,10 @@ public static Bson all(final String fieldName, final Iterable val * @mongodb.driver.manual reference/operator/query/elemMatch $elemMatch */ public static Bson elemMatch(final String fieldName, final Bson filter) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new Bson() { @Override public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { + countRawChild(filter); return new BsonDocument(fieldName, new BsonDocument("$elemMatch", filter.toBsonDocument(documentClass, codecRegistry))); } }; @@ -559,7 +538,6 @@ public BsonDocument toBsonDocument(final Class documentCl * @mongodb.driver.manual reference/operator/query/size $size */ public static Bson size(final String fieldName, final int size) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$size", fieldName, size); } @@ -574,7 +552,6 @@ public static Bson size(final String fieldName, final int size) { * @since 3.2 */ public static Bson bitsAllClear(final String fieldName, final long bitmask) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$bitsAllClear", fieldName, bitmask); } @@ -589,7 +566,6 @@ public static Bson bitsAllClear(final String fieldName, final long bitmask) { * @since 3.2 */ public static Bson bitsAllSet(final String fieldName, final long bitmask) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$bitsAllSet", fieldName, bitmask); } @@ -604,7 +580,6 @@ public static Bson bitsAllSet(final String fieldName, final long bitmask) { * @since 3.2 */ public static Bson bitsAnyClear(final String fieldName, final long bitmask) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$bitsAnyClear", fieldName, bitmask); } @@ -619,7 +594,6 @@ public static Bson bitsAnyClear(final String fieldName, final long bitmask) { * @since 3.2 */ public static Bson bitsAnySet(final String fieldName, final long bitmask) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new OperatorFilter<>("$bitsAnySet", fieldName, bitmask); } @@ -634,7 +608,6 @@ public static Bson bitsAnySet(final String fieldName, final long bitmask) { * @mongodb.server.release 2.4 */ public static Bson geoWithin(final String fieldName, final Geometry geometry) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new GeometryOperatorFilter<>("$geoWithin", fieldName, geometry); } @@ -649,7 +622,6 @@ public static Bson geoWithin(final String fieldName, final Geometry geometry) { * @mongodb.server.release 2.4 */ public static Bson geoWithin(final String fieldName, final Bson geometry) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new GeometryOperatorFilter<>("$geoWithin", fieldName, geometry); } @@ -670,7 +642,6 @@ public static Bson geoWithin(final String fieldName, final Bson geometry) { */ public static Bson geoWithinBox(final String fieldName, final double lowerLeftX, final double lowerLeftY, final double upperRightX, final double upperRightY) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); BsonDocument box = new BsonDocument("$box", new BsonArray(asList(new BsonArray(asList(new BsonDouble(lowerLeftX), new BsonDouble(lowerLeftY))), @@ -692,7 +663,6 @@ public static Bson geoWithinBox(final String fieldName, final double lowerLeftX, * @since 3.1 */ public static Bson geoWithinPolygon(final String fieldName, final List> points) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); BsonArray pointsArray = new BsonArray(points.size()); for (List point : points) { pointsArray.add(new BsonArray(asList(new BsonDouble(point.get(0)), new BsonDouble(point.get(1))))); @@ -716,7 +686,6 @@ public static Bson geoWithinPolygon(final String fieldName, final List("$geoIntersects", fieldName, geometry); } @@ -773,7 +740,6 @@ public static Bson geoIntersects(final String fieldName, final Bson geometry) { * @mongodb.server.release 2.4 */ public static Bson geoIntersects(final String fieldName, final Geometry geometry) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new GeometryOperatorFilter<>("$geoIntersects", fieldName, geometry); } @@ -791,7 +757,6 @@ public static Bson geoIntersects(final String fieldName, final Geometry geometry */ public static Bson near(final String fieldName, final Point geometry, @Nullable final Double maxDistance, @Nullable final Double minDistance) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new GeometryOperatorFilter<>("$near", fieldName, geometry, maxDistance, minDistance); } @@ -809,7 +774,6 @@ public static Bson near(final String fieldName, final Point geometry, @Nullable */ public static Bson near(final String fieldName, final Bson geometry, @Nullable final Double maxDistance, @Nullable final Double minDistance) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new GeometryOperatorFilter<>("$near", fieldName, geometry, maxDistance, minDistance); } @@ -828,7 +792,6 @@ public static Bson near(final String fieldName, final Bson geometry, @Nullable f */ public static Bson near(final String fieldName, final double x, final double y, @Nullable final Double maxDistance, @Nullable final Double minDistance) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return createNearFilterDocument(fieldName, x, y, maxDistance, minDistance, "$near"); } @@ -847,7 +810,6 @@ public static Bson near(final String fieldName, final double x, final double y, */ public static Bson nearSphere(final String fieldName, final Point geometry, @Nullable final Double maxDistance, @Nullable final Double minDistance) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new GeometryOperatorFilter<>("$nearSphere", fieldName, geometry, maxDistance, minDistance); } @@ -866,7 +828,6 @@ public static Bson nearSphere(final String fieldName, final Point geometry, @Nul */ public static Bson nearSphere(final String fieldName, final Bson geometry, @Nullable final Double maxDistance, @Nullable final Double minDistance) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new GeometryOperatorFilter<>("$nearSphere", fieldName, geometry, maxDistance, minDistance); } @@ -886,7 +847,6 @@ public static Bson nearSphere(final String fieldName, final Bson geometry, @Null */ public static Bson nearSphere(final String fieldName, final double x, final double y, @Nullable final Double maxDistance, @Nullable final Double minDistance) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return createNearFilterDocument(fieldName, x, y, maxDistance, minDistance, "$nearSphere"); } @@ -900,7 +860,6 @@ public static Bson nearSphere(final String fieldName, final double x, final doub * @mongodb.driver.manual reference/operator/query/jsonSchema/ $jsonSchema */ public static Bson jsonSchema(final Bson schema) { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new SimpleEncodingFilter<>("$jsonSchema", schema); } @@ -911,7 +870,6 @@ public static Bson jsonSchema(final Bson schema) { * @since 4.2 */ public static Bson empty() { - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new BsonDocument(); } @@ -928,6 +886,16 @@ private static Bson createNearFilterDocument(final String fieldName, final doubl return new BsonDocument(fieldName, nearFilter); } + /** + * Counts one raw child of a combinator node before the child renders. A combinator does not count itself: the classification + * measures the content, not the wrapper. The check is one instanceof pair. The method does not walk the document. + */ + private static void countRawChild(final Bson child) { + if (child instanceof Document || child instanceof BsonDocument) { + TelemetryStore.increment(ApiCounter.QUERY_RAW); + } + } + private static String operatorFilterToString(final String fieldName, final String operator, final Object value) { return "Operator Filter{" + "fieldName='" + fieldName + '\'' @@ -947,6 +915,7 @@ private SimpleFilter(final String fieldName, final BsonValue value) { @Override public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); return new BsonDocument(fieldName, value); } @@ -993,6 +962,7 @@ private static final class OperatorFilter implements Bson { @Override public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); BsonDocumentWriter writer = new BsonDocumentWriter(new BsonDocument()); writer.writeStartDocument(); @@ -1051,6 +1021,7 @@ private static class AndFilter implements Bson { public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { BsonArray clauses = new BsonArray(); for (Bson filter : filters) { + countRawChild(filter); clauses.add(filter.toBsonDocument(documentClass, codecRegistry)); } @@ -1112,6 +1083,7 @@ public BsonDocument toBsonDocument(final Class documentCl BsonArray filtersArray = new BsonArray(); for (Bson filter : filters) { + countRawChild(filter); filtersArray.add(filter.toBsonDocument(documentClass, codecRegistry)); } @@ -1165,6 +1137,7 @@ private static class IterableOperatorFilter implements Bson { @Override public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); BsonDocumentWriter writer = new BsonDocumentWriter(new BsonDocument()); writer.writeStartDocument(); @@ -1229,6 +1202,7 @@ private static class SimpleEncodingFilter implements Bson { @Override public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); BsonDocumentWriter writer = new BsonDocumentWriter(new BsonDocument()); writer.writeStartDocument(); @@ -1283,6 +1257,7 @@ private static class NotFilter implements Bson { @Override public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { + countRawChild(filter); BsonDocument filterDocument = filter.toBsonDocument(documentClass, codecRegistry); if (filterDocument.size() == 1) { Map.Entry entry = filterDocument.entrySet().iterator().next(); @@ -1369,6 +1344,7 @@ private static class GeometryOperatorFilter implements Bson { @Override public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); BsonDocumentWriter writer = new BsonDocumentWriter(new BsonDocument()); writer.writeStartDocument(); writer.writeName(fieldName); @@ -1449,6 +1425,7 @@ private static class TextFilter implements Bson { @Override public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); BsonDocument searchDocument = new BsonDocument("$search", new BsonString(search)); String language = textSearchOptions.getLanguage(); diff --git a/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java b/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java index 12a8cdd88d..c2aa34d9d4 100644 --- a/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java +++ b/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java @@ -16,18 +16,35 @@ package com.mongodb.client.model; +import com.mongodb.MongoClientSettings; import com.mongodb.internal.telemetry.TelemetryStore; +import org.bson.BsonDocument; +import org.bson.BsonInt32; +import org.bson.Document; +import org.bson.codecs.configuration.CodecRegistry; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Map; +import static com.mongodb.client.model.Filters.and; +import static com.mongodb.client.model.Filters.elemMatch; +import static com.mongodb.client.model.Filters.eq; +import static com.mongodb.client.model.Filters.lt; +import static com.mongodb.client.model.Filters.nor; +import static com.mongodb.client.model.Filters.not; +import static com.mongodb.client.model.Filters.or; import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertFalse; +/** + * The render-time classification of the filter nodes. A render counts also outside a query execution. The design accepts this noise. + */ public class FiltersUsageCountersTest { + private static final CodecRegistry CODEC_REGISTRY = MongoClientSettings.getDefaultCodecRegistry(); + @BeforeEach @AfterEach public void clearStore() { @@ -35,31 +52,47 @@ public void clearStore() { } @Test - public void oneHelperCallCountsOneUse() { - assertNotNull(Filters.eq("x", 1)); + public void aLeafRenderCountsOneQueryBuildersUse() { + eq("x", 1).toBsonDocument(Object.class, CODEC_REGISTRY); assertEquals(1L, TelemetryStore.drain().get("queryBuilders")); } @Test - public void aDelegatingOverloadCountsOneUse() { - assertNotNull(Filters.eq(1)); - assertNotNull(Filters.and(Filters.eq("x", 1))); - assertNotNull(Filters.or()); - assertNotNull(Filters.exists("x")); - assertNotNull(Filters.text("search")); - assertNotNull(Filters.in("x", 1, 2)); - assertNotNull(Filters.nin("x", 1, 2)); - assertNotNull(Filters.all("x", 1, 2)); - assertNotNull(Filters.regex("x", "pattern")); - // 9 delegating calls count 9 uses. The nested eq("x", 1) counts 1 more. + public void aCombinatorRenderCountsOnlyItsChildren() { + or(eq("x", 1)).toBsonDocument(Object.class, CODEC_REGISTRY); + Map deltas = TelemetryStore.drain(); + assertEquals(1L, deltas.get("queryBuilders")); + assertFalse(deltas.containsKey("queryRaw")); + } + + @Test + public void aBuilderOnlyTreeCountsOncePerNode() { + and(eq("x", 1), lt("y", 3)).toBsonDocument(Object.class, CODEC_REGISTRY); + assertEquals(2L, TelemetryStore.drain().get("queryBuilders")); + } + + @Test + public void norOfRawDocumentsCountsTwoQueryRawAndNoQueryBuilders() { + nor(new Document("a", 1), new BsonDocument("b", new BsonInt32(1))).toBsonDocument(Object.class, CODEC_REGISTRY); + Map deltas = TelemetryStore.drain(); + assertEquals(2L, deltas.get("queryRaw")); + assertFalse(deltas.containsKey("queryBuilders")); + } + + @Test + public void aRawChildInsideACombinatorCountsQueryRaw() { + and(eq("x", 1), new Document("y", 2)).toBsonDocument(Object.class, CODEC_REGISTRY); Map deltas = TelemetryStore.drain(); - assertEquals(10L, deltas.get("queryBuilders")); + assertEquals(1L, deltas.get("queryBuilders")); + assertEquals(1L, deltas.get("queryRaw")); } @Test - public void nestedHelperCallsCountEveryUse() { - assertNotNull(Filters.and(Filters.eq("x", 1), Filters.lt("y", 3))); + public void notAndElemMatchClassifyTheirChildOnly() { + not(new Document("a", 1)).toBsonDocument(Object.class, CODEC_REGISTRY); + elemMatch("arr", eq("x", 1)).toBsonDocument(Object.class, CODEC_REGISTRY); Map deltas = TelemetryStore.drain(); - assertEquals(3L, deltas.get("queryBuilders")); + assertEquals(1L, deltas.get("queryBuilders")); + assertEquals(1L, deltas.get("queryRaw")); } } diff --git a/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetryStoreTest.java b/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetryStoreTest.java index d3b58bf96c..558ffe8986 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetryStoreTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetryStoreTest.java @@ -16,6 +16,8 @@ package com.mongodb.internal.telemetry; +import com.mongodb.MongoClientSettings; +import com.mongodb.client.model.Filters; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -28,6 +30,7 @@ import static java.util.concurrent.TimeUnit.SECONDS; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; public class TelemetryStoreTest { @@ -113,7 +116,8 @@ public void theKillSwitchMakesIncrementANoOp() { @Test public void aBrokenCounterDoesNotBreakTheInstrumentedCall() { TelemetryStore.counters[ApiCounter.QUERY_BUILDERS.ordinal()] = new ThrowingLongAdder(); - TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); + // The render is a real instrumented call site. It must succeed with a broken counter. + assertNotNull(Filters.eq("x", 1).toBsonDocument(Object.class, MongoClientSettings.getDefaultCodecRegistry())); TelemetryStore.increment(ApiCounter.QUERY_RAW); Map deltas = TelemetryStore.drain(); assertEquals(1L, deltas.get("queryRaw")); diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java index a8ac9162e0..18cf79e29c 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java @@ -23,6 +23,7 @@ import com.mongodb.bulk.BulkWriteResult; import com.mongodb.client.model.DeleteOptions; import com.mongodb.client.model.InsertOneModel; +import com.mongodb.internal.operation.BatchCursor; import com.mongodb.internal.telemetry.TelemetryStore; import org.bson.BsonDocument; import org.bson.BsonInt32; @@ -39,13 +40,20 @@ import static com.mongodb.ClusterFixture.TIMEOUT_SETTINGS; import static com.mongodb.WriteConcern.ACKNOWLEDGED; -import static com.mongodb.internal.bulk.WriteRequest.Type.DELETE; +import static com.mongodb.client.model.Filters.and; +import static com.mongodb.client.model.Filters.empty; import static com.mongodb.client.model.Filters.eq; +import static com.mongodb.client.model.Filters.lt; +import static com.mongodb.client.model.Filters.nor; +import static com.mongodb.client.model.Filters.where; +import static com.mongodb.internal.bulk.WriteRequest.Type.DELETE; 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.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; public class MongoCollectionImplUsageCountersTest { @@ -77,13 +85,49 @@ public void findWithARawBsonDocumentFilterCountsOneQueryRaw() { } @Test - public void findWithABuilderFilterCountsNoQueryRaw() { + public void findWithABuilderFilterCountsNothingAtTheCall() { collection.find(eq("x", 1)); + assertTrue(TelemetryStore.drain().isEmpty()); + } + + @Test + public void anExecutedBuilderQueryCountsOncePerNode() { + collection = newCollection(new TestOperationExecutor(new ArrayList<>(Collections.singletonList(emptyBatchCursor())))); + assertNull(collection.find(and(eq("x", 1), lt("y", 3))).first()); Map deltas = TelemetryStore.drain(); - assertEquals(1L, deltas.get("queryBuilders")); + assertEquals(2L, deltas.get("queryBuilders")); assertFalse(deltas.containsKey("queryRaw")); } + @Test + public void norOfRawDocumentsThroughFindCountsTwoQueryRawAndNoQueryBuilders() { + collection = newCollection(new TestOperationExecutor(new ArrayList<>(Collections.singletonList(emptyBatchCursor())))); + assertNull(collection.find(nor(new Document("a", 1), new BsonDocument("b", new BsonInt32(1)))).first()); + Map deltas = TelemetryStore.drain(); + assertEquals(2L, deltas.get("queryRaw")); + assertFalse(deltas.containsKey("queryBuilders")); + } + + @Test + public void emptyAndWhereClassifyAsRawThroughTheEntryCheck() { + collection.find(empty()); + collection.find(where("this.x == 1")); + assertEquals(2L, TelemetryStore.drain().get("queryRaw")); + } + + @Test + public void aQueryExecutedTwiceCountsTwice() { + collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(1L, 1L)))); + collection.countDocuments(new Document("x", 1)); + collection.countDocuments(new Document("x", 1)); + assertEquals(2L, TelemetryStore.drain().get("queryRaw")); + + collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(emptyBatchCursor(), emptyBatchCursor())))); + collection.find(eq("x", 1)).first(); + collection.find(eq("x", 1)).first(); + assertEquals(2L, TelemetryStore.drain().get("queryBuilders")); + } + @Test public void findWithNoFilterCountsNothing() { collection.find(); @@ -143,6 +187,13 @@ public void aDelegatingOverloadCountsOneUseOnly() { assertEquals(2L, TelemetryStore.drain().get("queryRaw")); } + @SuppressWarnings("unchecked") + private static BatchCursor emptyBatchCursor() { + BatchCursor cursor = mock(BatchCursor.class); + when(cursor.hasNext()).thenReturn(false); + return cursor; + } + private static MongoCollectionImpl newCollection(final TestOperationExecutor executor) { return new MongoCollectionImpl<>(new MongoNamespace("db", "coll"), Document.class, MongoClientSettings.getDefaultCodecRegistry(), ReadPreference.secondary(), ACKNOWLEDGED, From df607e56b4da1717e680b80c045e70d8de4fef1a Mon Sep 17 00:00:00 2001 From: Slav Babanin Date: Fri, 4 Dec 2026 18:56:47 -0700 Subject: [PATCH 6/8] Simplify the query classification to the Filters render sites only The only instrumentation for query construction now lives inside the Filters classes. Each inner class counts itself once in its toBsonDocument method: queryBuilders. The combinator loops check each child before the child renders: a Document or a BsonDocument child increments queryRaw. NotFilter and the elemMatch wrapper render one child each. They follow the same rule. The design removes the entry check from MongoCollectionImpl. No entry checks, no render context, no thread-local. The no-filter overload bypass reverts with it: the overloads delegate again as upstream. Known consequence, accepted: a raw root filter never enters a Filters class and counts nothing. For example find(new Document(...)) gives no count. empty() and where() return a plain BsonDocument, so they count nothing too. queryRaw measures raw nodes inside builder-wrapped trees. Full raw-root coverage needs the MongoCollectionImpl entry check. The spec discussion decides whether to add it. A retried query renders again and counts again. The counter measures executions. The demo output shows the consequence: the demo raw queries are raw roots, so their lines carry no queryRaw key. --- .../com/mongodb/client/model/Filters.java | 9 ++- .../model/FiltersUsageCountersTest.java | 20 ++--- .../client/internal/MongoCollectionImpl.java | 52 +++--------- .../MongoCollectionImplUsageCountersTest.java | 79 ++++++++++--------- 4 files changed, 67 insertions(+), 93 deletions(-) diff --git a/driver-core/src/main/com/mongodb/client/model/Filters.java b/driver-core/src/main/com/mongodb/client/model/Filters.java index 5029ea200d..083f4204ef 100644 --- a/driver-core/src/main/com/mongodb/client/model/Filters.java +++ b/driver-core/src/main/com/mongodb/client/model/Filters.java @@ -523,6 +523,7 @@ public static Bson elemMatch(final String fieldName, final Bson filter) { return new Bson() { @Override public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); countRawChild(filter); return new BsonDocument(fieldName, new BsonDocument("$elemMatch", filter.toBsonDocument(documentClass, codecRegistry))); } @@ -887,8 +888,9 @@ private static Bson createNearFilterDocument(final String fieldName, final doubl } /** - * Counts one raw child of a combinator node before the child renders. A combinator does not count itself: the classification - * measures the content, not the wrapper. The check is one instanceof pair. The method does not walk the document. + * Counts one raw child of a combinator node before the child renders. A raw child is a {@code Document} or a {@code BsonDocument}. + * The check is one instanceof pair. The method does not walk the document. A raw root never enters a {@code Filters} class, so the + * counter sees raw nodes inside builder-wrapped trees only. */ private static void countRawChild(final Bson child) { if (child instanceof Document || child instanceof BsonDocument) { @@ -1019,6 +1021,7 @@ private static class AndFilter implements Bson { @Override public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); BsonArray clauses = new BsonArray(); for (Bson filter : filters) { countRawChild(filter); @@ -1079,6 +1082,7 @@ private enum Operator { @Override public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); BsonDocument orRenderable = new BsonDocument(); BsonArray filtersArray = new BsonArray(); @@ -1257,6 +1261,7 @@ private static class NotFilter implements Bson { @Override public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); countRawChild(filter); BsonDocument filterDocument = filter.toBsonDocument(documentClass, codecRegistry); if (filterDocument.size() == 1) { diff --git a/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java b/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java index c2aa34d9d4..952f8854ca 100644 --- a/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java +++ b/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java @@ -39,7 +39,9 @@ import static org.junit.jupiter.api.Assertions.assertFalse; /** - * The render-time classification of the filter nodes. A render counts also outside a query execution. The design accepts this noise. + * The render-time classification of the filter nodes. Every inner class of Filters counts itself once per render. The combinator loops + * classify raw children. A raw root never enters a Filters class and counts nothing. A render outside a query execution counts too. The + * design accepts this noise. */ public class FiltersUsageCountersTest { @@ -58,41 +60,41 @@ public void aLeafRenderCountsOneQueryBuildersUse() { } @Test - public void aCombinatorRenderCountsOnlyItsChildren() { + public void aCombinatorRenderCountsItselfAndItsChildren() { or(eq("x", 1)).toBsonDocument(Object.class, CODEC_REGISTRY); Map deltas = TelemetryStore.drain(); - assertEquals(1L, deltas.get("queryBuilders")); + assertEquals(2L, deltas.get("queryBuilders")); assertFalse(deltas.containsKey("queryRaw")); } @Test public void aBuilderOnlyTreeCountsOncePerNode() { and(eq("x", 1), lt("y", 3)).toBsonDocument(Object.class, CODEC_REGISTRY); - assertEquals(2L, TelemetryStore.drain().get("queryBuilders")); + assertEquals(3L, TelemetryStore.drain().get("queryBuilders")); } @Test - public void norOfRawDocumentsCountsTwoQueryRawAndNoQueryBuilders() { + public void norOfRawDocumentsCountsTwoQueryRawAndOneQueryBuilders() { nor(new Document("a", 1), new BsonDocument("b", new BsonInt32(1))).toBsonDocument(Object.class, CODEC_REGISTRY); Map deltas = TelemetryStore.drain(); assertEquals(2L, deltas.get("queryRaw")); - assertFalse(deltas.containsKey("queryBuilders")); + assertEquals(1L, deltas.get("queryBuilders")); } @Test public void aRawChildInsideACombinatorCountsQueryRaw() { and(eq("x", 1), new Document("y", 2)).toBsonDocument(Object.class, CODEC_REGISTRY); Map deltas = TelemetryStore.drain(); - assertEquals(1L, deltas.get("queryBuilders")); + assertEquals(2L, deltas.get("queryBuilders")); assertEquals(1L, deltas.get("queryRaw")); } @Test - public void notAndElemMatchClassifyTheirChildOnly() { + public void notAndElemMatchCountThemselvesAndClassifyTheirChild() { not(new Document("a", 1)).toBsonDocument(Object.class, CODEC_REGISTRY); elemMatch("arr", eq("x", 1)).toBsonDocument(Object.class, CODEC_REGISTRY); Map deltas = TelemetryStore.drain(); - assertEquals(1L, deltas.get("queryBuilders")); + assertEquals(3L, deltas.get("queryBuilders")); assertEquals(1L, deltas.get("queryRaw")); } } diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java index cead694fb6..626b5381a1 100755 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java @@ -65,9 +65,9 @@ import com.mongodb.internal.client.model.changestream.ChangeStreamLevel; import com.mongodb.internal.operation.IndexHelper; import com.mongodb.internal.operation.Operations; +import com.mongodb.internal.operation.WriteOperation; import com.mongodb.internal.telemetry.ApiCounter; import com.mongodb.internal.telemetry.TelemetryStore; -import com.mongodb.internal.operation.WriteOperation; import com.mongodb.lang.Nullable; import org.bson.BsonDocument; import org.bson.BsonValue; @@ -214,8 +214,7 @@ public MongoCollection withTimeout(final long timeout, final TimeUnit @Override public long countDocuments() { - // Bypass the filter-taking overloads. A synthetic empty filter must not count as a raw query. - return executeCount(null, new BsonDocument(), new CountOptions()); + return countDocuments(new BsonDocument()); } @Override @@ -225,15 +224,12 @@ public long countDocuments(final Bson filter) { @Override public long countDocuments(final Bson filter, final CountOptions options) { - countRawQueryUse(filter); return executeCount(null, filter, options); } @Override public long countDocuments(final ClientSession clientSession) { - // Bypass the filter-taking overloads. A synthetic empty filter must not count as a raw query. - notNull("clientSession", clientSession); - return executeCount(clientSession, new BsonDocument(), new CountOptions()); + return countDocuments(clientSession, new BsonDocument()); } @Override @@ -244,7 +240,6 @@ public long countDocuments(final ClientSession clientSession, final Bson filter) @Override public long countDocuments(final ClientSession clientSession, final Bson filter, final CountOptions options) { notNull("clientSession", clientSession); - countRawQueryUse(filter); return executeCount(clientSession, filter, options); } @@ -264,41 +259,26 @@ private long executeCount(@Nullable final ClientSession clientSession, final Bso .execute(operations.countDocuments(filter, options), readPreference, readConcern, clientSession); } - /** - * Counts one query use when the filter is a raw document. The check is one instanceof pair. The method does not walk or analyze the - * document. A hand-built document counts as raw. The counter measures the paradigm, not the correctness. - */ - private static void countRawQueryUse(@Nullable final Bson filter) { - if (filter instanceof Document || filter instanceof BsonDocument) { - TelemetryStore.increment(ApiCounter.QUERY_RAW); - } - } - @Override public DistinctIterable distinct(final String fieldName, final Class resultClass) { - // Bypass the filter-taking overloads. A synthetic empty filter must not count as a raw query. - return createDistinctIterable(null, fieldName, new BsonDocument(), resultClass); + return distinct(fieldName, new BsonDocument(), resultClass); } @Override public DistinctIterable distinct(final String fieldName, final Bson filter, final Class resultClass) { - countRawQueryUse(filter); return createDistinctIterable(null, fieldName, filter, resultClass); } @Override public DistinctIterable distinct(final ClientSession clientSession, final String fieldName, final Class resultClass) { - // Bypass the filter-taking overloads. A synthetic empty filter must not count as a raw query. - notNull("clientSession", clientSession); - return createDistinctIterable(clientSession, fieldName, new BsonDocument(), resultClass); + return distinct(clientSession, fieldName, new BsonDocument(), resultClass); } @Override public DistinctIterable distinct(final ClientSession clientSession, final String fieldName, final Bson filter, final Class resultClass) { notNull("clientSession", clientSession); - countRawQueryUse(filter); return createDistinctIterable(clientSession, fieldName, filter, resultClass); } @@ -310,14 +290,12 @@ private DistinctIterable createDistinctIterable(@Nullable fin @Override public FindIterable find() { - // Bypass the filter-taking overloads. A synthetic empty filter must not count as a raw query. - return createFindIterable(null, new BsonDocument(), documentClass); + return find(new BsonDocument(), documentClass); } @Override public FindIterable find(final Class resultClass) { - // Bypass the filter-taking overloads. A synthetic empty filter must not count as a raw query. - return createFindIterable(null, new BsonDocument(), resultClass); + return find(new BsonDocument(), resultClass); } @Override @@ -327,22 +305,19 @@ public FindIterable find(final Bson filter) { @Override public FindIterable find(final Bson filter, final Class resultClass) { - countRawQueryUse(filter); return createFindIterable(null, filter, resultClass); } @Override public FindIterable find(final ClientSession clientSession) { - // Bypass the filter-taking overloads. A synthetic empty filter must not count as a raw query. notNull("clientSession", clientSession); - return createFindIterable(clientSession, new BsonDocument(), documentClass); + return find(clientSession, new BsonDocument(), documentClass); } @Override public FindIterable find(final ClientSession clientSession, final Class resultClass) { - // Bypass the filter-taking overloads. A synthetic empty filter must not count as a raw query. notNull("clientSession", clientSession); - return createFindIterable(clientSession, new BsonDocument(), resultClass); + return find(clientSession, new BsonDocument(), resultClass); } @Override @@ -355,7 +330,6 @@ public FindIterable find(final ClientSession clientSession, final Bso public FindIterable find(final ClientSession clientSession, final Bson filter, final Class resultClass) { notNull("clientSession", clientSession); - countRawQueryUse(filter); return createFindIterable(clientSession, filter, resultClass); } @@ -577,7 +551,6 @@ public DeleteResult deleteOne(final Bson filter) { @Override public DeleteResult deleteOne(final Bson filter, final DeleteOptions options) { - countRawQueryUse(filter); return executeDelete(null, filter, options, false); } @@ -589,7 +562,6 @@ public DeleteResult deleteOne(final ClientSession clientSession, final Bson filt @Override public DeleteResult deleteOne(final ClientSession clientSession, final Bson filter, final DeleteOptions options) { notNull("clientSession", clientSession); - countRawQueryUse(filter); return executeDelete(clientSession, filter, options, false); } @@ -600,7 +572,6 @@ public DeleteResult deleteMany(final Bson filter) { @Override public DeleteResult deleteMany(final Bson filter, final DeleteOptions options) { - countRawQueryUse(filter); return executeDelete(null, filter, options, true); } @@ -612,7 +583,6 @@ public DeleteResult deleteMany(final ClientSession clientSession, final Bson fil @Override public DeleteResult deleteMany(final ClientSession clientSession, final Bson filter, final DeleteOptions options) { notNull("clientSession", clientSession); - countRawQueryUse(filter); return executeDelete(clientSession, filter, options, true); } @@ -762,7 +732,6 @@ public TDocument findOneAndDelete(final ClientSession clientSession, final Bson @Nullable private TDocument executeFindOneAndDelete(@Nullable final ClientSession clientSession, final Bson filter, final FindOneAndDeleteOptions options) { - countRawQueryUse(filter); return getExecutor(operations.createTimeoutSettings(options)) .execute(operations.findOneAndDelete(filter, options), readConcern, clientSession); } @@ -796,7 +765,6 @@ public TDocument findOneAndReplace(final ClientSession clientSession, final Bson @Nullable private TDocument executeFindOneAndReplace(@Nullable final ClientSession clientSession, final Bson filter, final TDocument replacement, final FindOneAndReplaceOptions options) { - countRawQueryUse(filter); return getExecutor(operations.createTimeoutSettings(options)) .execute(operations.findOneAndReplace(filter, replacement, options), readConcern, clientSession); } @@ -830,7 +798,6 @@ public TDocument findOneAndUpdate(final ClientSession clientSession, final Bson @Nullable private TDocument executeFindOneAndUpdate(@Nullable final ClientSession clientSession, final Bson filter, final Bson update, final FindOneAndUpdateOptions options) { - countRawQueryUse(filter); return getExecutor(operations.createTimeoutSettings(options)) .execute(operations.findOneAndUpdate(filter, update, options), readConcern, clientSession); } @@ -864,7 +831,6 @@ public TDocument findOneAndUpdate(final ClientSession clientSession, final Bson @Nullable private TDocument executeFindOneAndUpdate(@Nullable final ClientSession clientSession, final Bson filter, final List update, final FindOneAndUpdateOptions options) { - countRawQueryUse(filter); return getExecutor(operations.createTimeoutSettings(options)) .execute(operations.findOneAndUpdate(filter, update, options), readConcern, clientSession); } diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java index 18cf79e29c..7cd19f88eb 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java @@ -55,6 +55,10 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +/** + * The counters of the query execution paths. A raw root never enters a Filters class, so it counts nothing. The known consequence: a + * plain raw filter gives no count. A builder-wrapped raw tree counts at the render, once per node. + */ public class MongoCollectionImplUsageCountersTest { private MongoCollectionImpl collection; @@ -71,17 +75,12 @@ public void clearStore() { } @Test - public void findWithARawDocumentFilterCountsOneQueryRaw() { + public void findWithARawRootCountsNothing() { collection.find(new Document("x", 1)); - Map deltas = TelemetryStore.drain(); - assertEquals(1L, deltas.get("queryRaw")); - assertFalse(deltas.containsKey("queryBuilders")); - } - - @Test - public void findWithARawBsonDocumentFilterCountsOneQueryRaw() { collection.find(new BsonDocument("x", new BsonInt32(1))); - assertEquals(1L, TelemetryStore.drain().get("queryRaw")); + collection.find(empty()); + collection.find(where("this.x == 1")); + assertTrue(TelemetryStore.drain().isEmpty()); } @Test @@ -95,37 +94,41 @@ public void anExecutedBuilderQueryCountsOncePerNode() { collection = newCollection(new TestOperationExecutor(new ArrayList<>(Collections.singletonList(emptyBatchCursor())))); assertNull(collection.find(and(eq("x", 1), lt("y", 3))).first()); Map deltas = TelemetryStore.drain(); - assertEquals(2L, deltas.get("queryBuilders")); + assertEquals(3L, deltas.get("queryBuilders")); assertFalse(deltas.containsKey("queryRaw")); } @Test - public void norOfRawDocumentsThroughFindCountsTwoQueryRawAndNoQueryBuilders() { + public void norOfRawDocumentsThroughFindCountsTwoQueryRawAndOneQueryBuilders() { collection = newCollection(new TestOperationExecutor(new ArrayList<>(Collections.singletonList(emptyBatchCursor())))); assertNull(collection.find(nor(new Document("a", 1), new BsonDocument("b", new BsonInt32(1)))).first()); Map deltas = TelemetryStore.drain(); assertEquals(2L, deltas.get("queryRaw")); - assertFalse(deltas.containsKey("queryBuilders")); + assertEquals(1L, deltas.get("queryBuilders")); } @Test - public void emptyAndWhereClassifyAsRawThroughTheEntryCheck() { - collection.find(empty()); - collection.find(where("this.x == 1")); - assertEquals(2L, TelemetryStore.drain().get("queryRaw")); + public void distinctWithABuilderWrappedRawTreeCountsOnExecution() { + collection = newCollection(new TestOperationExecutor(new ArrayList<>(Collections.singletonList(emptyBatchCursor())))); + assertNull(collection.distinct("x", nor(new Document("a", 1), new Document("b", 2)), Integer.class).first()); + Map deltas = TelemetryStore.drain(); + assertEquals(2L, deltas.get("queryRaw")); + assertEquals(1L, deltas.get("queryBuilders")); } @Test public void aQueryExecutedTwiceCountsTwice() { - collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(1L, 1L)))); - collection.countDocuments(new Document("x", 1)); - collection.countDocuments(new Document("x", 1)); - assertEquals(2L, TelemetryStore.drain().get("queryRaw")); - collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(emptyBatchCursor(), emptyBatchCursor())))); collection.find(eq("x", 1)).first(); collection.find(eq("x", 1)).first(); assertEquals(2L, TelemetryStore.drain().get("queryBuilders")); + + collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(1L, 1L)))); + collection.countDocuments(nor(new Document("a", 1), new Document("b", 2))); + collection.countDocuments(nor(new Document("a", 1), new Document("b", 2))); + Map deltas = TelemetryStore.drain(); + assertEquals(4L, deltas.get("queryRaw")); + assertEquals(2L, deltas.get("queryBuilders")); } @Test @@ -136,37 +139,33 @@ public void findWithNoFilterCountsNothing() { } @Test - public void countDocumentsWithARawFilterCountsOneQueryRaw() { + public void countDocumentsWithARawRootCountsNothing() { collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(1L)))); assertEquals(1L, collection.countDocuments(new Document("x", 1))); - assertEquals(1L, TelemetryStore.drain().get("queryRaw")); - } - - @Test - public void distinctWithARawFilterCountsOneQueryRaw() { - collection.distinct("x", new Document("x", 1), Integer.class); - assertEquals(1L, TelemetryStore.drain().get("queryRaw")); + assertTrue(TelemetryStore.drain().isEmpty()); } @Test - public void deleteManyWithARawFilterCountsOneQueryRaw() { + public void deleteManyWithABuilderWrappedRawTreeCountsOnExecution() { collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(BulkWriteResult.acknowledged(DELETE, 1, 0, List.of(), List.of()))))); - assertNotNull(collection.deleteMany(new Document("x", 1))); - assertEquals(1L, TelemetryStore.drain().get("queryRaw")); + assertNotNull(collection.deleteMany(nor(new Document("a", 1), new Document("b", 2)))); + Map deltas = TelemetryStore.drain(); + assertEquals(2L, deltas.get("queryRaw")); + assertEquals(1L, deltas.get("queryBuilders")); } @Test - public void deleteOneWithARawFilterCountsOneQueryRaw() { + public void deleteOneWithARawRootCountsNothing() { collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(BulkWriteResult.acknowledged(DELETE, 1, 0, List.of(), List.of()))))); assertNotNull(collection.deleteOne(new BsonDocument())); - assertEquals(1L, TelemetryStore.drain().get("queryRaw")); + assertTrue(TelemetryStore.drain().isEmpty()); } @Test - public void findOneAndDeleteWithARawFilterCountsOneQueryRaw() { + public void findOneAndDeleteWithARawRootCountsNothing() { collection = newCollection(new TestOperationExecutor(new ArrayList<>(Collections.singletonList(null)))); assertNull(collection.findOneAndDelete(new Document("x", 1))); - assertEquals(1L, TelemetryStore.drain().get("queryRaw")); + assertTrue(TelemetryStore.drain().isEmpty()); } @Test @@ -182,9 +181,11 @@ public void bulkWriteCountsOneBulkWriteCollection() { @Test public void aDelegatingOverloadCountsOneUseOnly() { collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(BulkWriteResult.acknowledged(DELETE, 1, 0, List.of(), List.of()), BulkWriteResult.acknowledged(DELETE, 1, 0, List.of(), List.of()))))); - collection.deleteMany(new Document("x", 1)); - collection.deleteMany(new BsonDocument("x", new BsonInt32(1)), new DeleteOptions()); - assertEquals(2L, TelemetryStore.drain().get("queryRaw")); + collection.deleteMany(nor(new Document("a", 1), new Document("b", 2))); + collection.deleteMany(nor(new BsonDocument("a", new BsonInt32(1)), new BsonDocument("b", new BsonInt32(2))), new DeleteOptions()); + Map deltas = TelemetryStore.drain(); + assertEquals(4L, deltas.get("queryRaw")); + assertEquals(2L, deltas.get("queryBuilders")); } @SuppressWarnings("unchecked") From 3a63c080667c688b35ba7ac001c61cf1d4edc26b Mon Sep 17 00:00:00 2001 From: Slav Babanin Date: Fri, 4 Dec 2026 20:14:27 -0700 Subject: [PATCH 7/8] Give where and empty the elemMatch wrapper treatment Filters.where and Filters.empty returned a plain BsonDocument. They never entered a Filters class, so they counted nothing at render. Both now return an anonymous Bson wrapper, the same pattern as elemMatch. The wrapper implements Bson directly, never BsonDocument. Its toBsonDocument increments queryBuilders and builds the same document as before. The public return type stays Bson, so the change keeps source and binary compatibility. The wrapper never fires the combinator child check, so no method double-counts. Every Filters static method now bumps the counter at render. where and empty count as builder usage: they are typed-API invocations. A plain raw root still counts nothing. The known consequence stands. Tests: where and empty through find count queryBuilders 1 and queryRaw 0 on execution. and(where(...), eq(...)) counts queryBuilders 3: the where wrapper, the eq leaf, and the and shell. --- .../com/mongodb/client/model/Filters.java | 18 ++++++++++++++++-- .../model/FiltersUsageCountersTest.java | 19 +++++++++++++++++++ .../MongoCollectionImplUsageCountersTest.java | 12 ++++++++++-- 3 files changed, 45 insertions(+), 4 deletions(-) diff --git a/driver-core/src/main/com/mongodb/client/model/Filters.java b/driver-core/src/main/com/mongodb/client/model/Filters.java index 083f4204ef..06df9b8dbf 100644 --- a/driver-core/src/main/com/mongodb/client/model/Filters.java +++ b/driver-core/src/main/com/mongodb/client/model/Filters.java @@ -465,7 +465,14 @@ public static Bson text(final String search, final TextSearchOptions textSearchO */ public static Bson where(final String javaScriptExpression) { notNull("javaScriptExpression", javaScriptExpression); - return new BsonDocument("$where", new BsonString(javaScriptExpression)); + // The wrapper implements Bson directly, never BsonDocument. The combinator child check never fires for it. + return new Bson() { + @Override + public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); + return new BsonDocument("$where", new BsonString(javaScriptExpression)); + } + }; } /** @@ -871,7 +878,14 @@ public static Bson jsonSchema(final Bson schema) { * @since 4.2 */ public static Bson empty() { - return new BsonDocument(); + // The wrapper implements Bson directly, never BsonDocument. The combinator child check never fires for it. + return new Bson() { + @Override + public BsonDocument toBsonDocument(final Class documentClass, final CodecRegistry codecRegistry) { + TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); + return new BsonDocument(); + } + }; } diff --git a/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java b/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java index 952f8854ca..7304ef6c04 100644 --- a/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java +++ b/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java @@ -30,11 +30,13 @@ import static com.mongodb.client.model.Filters.and; import static com.mongodb.client.model.Filters.elemMatch; +import static com.mongodb.client.model.Filters.empty; import static com.mongodb.client.model.Filters.eq; import static com.mongodb.client.model.Filters.lt; import static com.mongodb.client.model.Filters.nor; import static com.mongodb.client.model.Filters.not; import static com.mongodb.client.model.Filters.or; +import static com.mongodb.client.model.Filters.where; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -97,4 +99,21 @@ public void notAndElemMatchCountThemselvesAndClassifyTheirChild() { assertEquals(3L, deltas.get("queryBuilders")); assertEquals(1L, deltas.get("queryRaw")); } + + @Test + public void whereAndEmptyRenderAsQueryBuilders() { + where("this.x == 1").toBsonDocument(Object.class, CODEC_REGISTRY); + empty().toBsonDocument(Object.class, CODEC_REGISTRY); + Map deltas = TelemetryStore.drain(); + assertEquals(2L, deltas.get("queryBuilders")); + assertFalse(deltas.containsKey("queryRaw")); + } + + @Test + public void andOfWhereAndEqCountsThreeQueryBuildersAndNoQueryRaw() { + and(where("this.x == 1"), eq("x", 1)).toBsonDocument(Object.class, CODEC_REGISTRY); + Map deltas = TelemetryStore.drain(); + assertEquals(3L, deltas.get("queryBuilders")); + assertFalse(deltas.containsKey("queryRaw")); + } } diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java index 7cd19f88eb..fda858e601 100644 --- a/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java @@ -78,11 +78,19 @@ public void clearStore() { public void findWithARawRootCountsNothing() { collection.find(new Document("x", 1)); collection.find(new BsonDocument("x", new BsonInt32(1))); - collection.find(empty()); - collection.find(where("this.x == 1")); assertTrue(TelemetryStore.drain().isEmpty()); } + @Test + public void whereAndEmptyCountAsQueryBuildersOnExecution() { + collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(emptyBatchCursor(), emptyBatchCursor())))); + assertNull(collection.find(where("this.x == 1")).first()); + assertNull(collection.find(empty()).first()); + Map deltas = TelemetryStore.drain(); + assertEquals(2L, deltas.get("queryBuilders")); + assertFalse(deltas.containsKey("queryRaw")); + } + @Test public void findWithABuilderFilterCountsNothingAtTheCall() { collection.find(eq("x", 1)); From 723d734d06bbc0433506012d6b49de7b80097438 Mon Sep 17 00:00:00 2001 From: Slav Babanin Date: Fri, 4 Dec 2026 21:35:53 -0700 Subject: [PATCH 8/8] Add feature labels through one public register path - Adds MongoDriverInformation.register(label) returning the public FeatureHandle interface as the entire public label surface; the store keeps only a handle set, register is the only writer, and used() is one volatile read on the handle - Latches driver-internal labels at first real use: gridfs at the first bucket operation, changeStreams at the watch choke points, csfle at the explicit encrypt entries, convTxn/coreTxn at invocation; registration alone never counts - Extends the sampler line with the deduplicated, sorted feature list and extends the demo with transaction rounds and a GridFS upload JAVA-6904 --- .../src/main/com/mongodb/FeatureHandle.java | 35 +++++ .../com/mongodb/MongoDriverInformation.java | 18 +++ .../telemetry/DriverFeatureHandle.java | 71 +++++++++ .../internal/telemetry/TelemetryFeatures.java | 102 ++++++++++++ .../internal/telemetry/TelemetrySampler.java | 37 +++-- .../telemetry/TelemetryFeaturesTest.java | 142 +++++++++++++++++ .../telemetry/TelemetrySamplerTest.java | 53 ++++++- .../telemetry/InstrumentationPocDemo.java | 32 +++- .../client/gridfs/GridFSBucketImpl.java | 9 ++ .../client/internal/ClientEncryptionImpl.java | 9 ++ .../client/internal/ClientSessionImpl.java | 8 + .../client/internal/MongoClusterImpl.java | 6 + .../client/internal/MongoCollectionImpl.java | 6 + .../client/internal/MongoDatabaseImpl.java | 6 + .../internal/TelemetryFeatureLabelsTest.java | 148 ++++++++++++++++++ 15 files changed, 668 insertions(+), 14 deletions(-) create mode 100644 driver-core/src/main/com/mongodb/FeatureHandle.java create mode 100644 driver-core/src/main/com/mongodb/internal/telemetry/DriverFeatureHandle.java create mode 100644 driver-core/src/main/com/mongodb/internal/telemetry/TelemetryFeatures.java create mode 100644 driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetryFeaturesTest.java create mode 100644 driver-sync/src/test/unit/com/mongodb/client/internal/TelemetryFeatureLabelsTest.java diff --git a/driver-core/src/main/com/mongodb/FeatureHandle.java b/driver-core/src/main/com/mongodb/FeatureHandle.java new file mode 100644 index 0000000000..1dc6ee3466 --- /dev/null +++ b/driver-core/src/main/com/mongodb/FeatureHandle.java @@ -0,0 +1,35 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb; + +/** + * The handle of one feature label of the telemetry POC. A framework registers the handle once with + * {@link MongoDriverInformation#register} and keeps it. The framework calls {@link #used()} at the execution site of the feature, on + * first use. + *

+ * The handle is a latch: it flips once, then stays flipped. After the first call, every later call is one cheap read. The handle never + * touches any set or map on any use path. + *

+ * POC scope: this interface is the entire public label surface of the telemetry POC. + */ +public interface FeatureHandle { + + /** + * Flips the latch on first use of the feature. + */ + void used(); +} diff --git a/driver-core/src/main/com/mongodb/MongoDriverInformation.java b/driver-core/src/main/com/mongodb/MongoDriverInformation.java index d75cf9a1be..bd426a8ff7 100644 --- a/driver-core/src/main/com/mongodb/MongoDriverInformation.java +++ b/driver-core/src/main/com/mongodb/MongoDriverInformation.java @@ -20,6 +20,7 @@ import com.mongodb.annotations.Sealed; import com.mongodb.internal.client.DriverInformation; import com.mongodb.internal.connection.ConcreteMongoDriverInformation; +import com.mongodb.internal.telemetry.TelemetryFeatures; import java.util.ArrayList; import java.util.Collections; @@ -91,6 +92,23 @@ public static Builder builder(final MongoDriverInformation mongoDriverInformatio */ public abstract List getDriverPlatforms(); + /** + * Registers one feature label of the telemetry POC and returns its handle. A framework calls this method once per label, on the + * cold path, and keeps the handle. The framework calls {@link FeatureHandle#used()} at the execution site of the feature, on first + * use. The driver's own features register through this same method. + *

+ * The method does not change the value object: the label store is process-wide. The returned handle stays usable forever, because + * frameworks register lazily, after the handshake. + *

+ * POC scope: this method is the entire public label surface of the telemetry POC. + * + * @param label the label name of the feature + * @return the handle of the label + */ + public FeatureHandle register(final String label) { + return TelemetryFeatures.register(label); + } + /** * */ diff --git a/driver-core/src/main/com/mongodb/internal/telemetry/DriverFeatureHandle.java b/driver-core/src/main/com/mongodb/internal/telemetry/DriverFeatureHandle.java new file mode 100644 index 0000000000..d1f6320097 --- /dev/null +++ b/driver-core/src/main/com/mongodb/internal/telemetry/DriverFeatureHandle.java @@ -0,0 +1,71 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.telemetry; + +import com.mongodb.FeatureHandle; + +import java.util.concurrent.atomic.AtomicBoolean; + +import static com.mongodb.assertions.Assertions.notNull; + +/** + * The handle of one feature label of the telemetry POC. {@link TelemetryFeatures#register} creates the handle. The handle is a latch: + * it flips once, then stays flipped. + *

+ * {@link #used()} touches only the handle's own {@link AtomicBoolean}. The registered set is never touched on any use path, first use + * included. The kill switch turns {@code used()} into a no-op: a use under the switch does not latch. + *

+ * This class is not part of the public API and may be removed or changed at any time. + */ +public final class DriverFeatureHandle implements FeatureHandle { + + final String label; + private final AtomicBoolean used = new AtomicBoolean(false); + + DriverFeatureHandle(final String label) { + this.label = notNull("label", label); + } + + /** + * Flips the latch on first use. The method is one cheap read in the steady state. The method never throws. + */ + @Override + public void used() { + if (!TelemetryStore.isEnabled()) { + return; + } + if (!used.get()) { + used.compareAndSet(false, true); + } + } + + /** + * Reports whether the latch is flipped. The sampler calls this method once per window. + * + * @return true when the feature was used at least once + */ + boolean usedFlag() { + return used.get(); + } + + /** + * Unflips the latch. Only {@link TelemetryFeatures#resetForTest} calls this method. + */ + void resetLatch() { + used.set(false); + } +} diff --git a/driver-core/src/main/com/mongodb/internal/telemetry/TelemetryFeatures.java b/driver-core/src/main/com/mongodb/internal/telemetry/TelemetryFeatures.java new file mode 100644 index 0000000000..28c66b731f --- /dev/null +++ b/driver-core/src/main/com/mongodb/internal/telemetry/TelemetryFeatures.java @@ -0,0 +1,102 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.telemetry; + +import com.mongodb.FeatureHandle; +import com.mongodb.internal.VisibleForTesting; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; +import java.util.concurrent.ConcurrentHashMap; + +/** + * The feature-label store of the telemetry POC. There is one registration path: {@link #register}, reached through the public + * {@code MongoDriverInformation.register} method. The driver's own features register through the same path: each feature class holds + * its handle in a private static field and registers at class initialization. There is no driver-internal label enum and no separate + * latch array. One mechanism, one path, internal and external alike. + *

+ * The store keeps one set of {@link DriverFeatureHandle} handles, built on {@link ConcurrentHashMap#newKeySet()}. Registration is the + * only writer: one add per label, on the cold path. A use path touches only the handle's own latch. + *

+ * Every label is a latch. Delivery is resend-always: every sample line carries every latched label. Nothing is cleared, and no line + * depends on a previous line. A later clientUpdate carries the complete current value, not a delta. + *

+ * The set of handles does not dedup by label: two integrations can register the same label. The emitter dedups by label when it builds + * the list, and sorts the list, so the line is deterministic. + *

+ * The kill switch of {@link TelemetryStore} suppresses the labels too: a use under the switch does not latch, and the emit list is + * empty while the switch is off. The latches survive: the labels ship again after the switch returns on. + *

+ * This class is not part of the public API and may be removed or changed at any time. + */ +public final class TelemetryFeatures { + + static Set handles = ConcurrentHashMap.newKeySet(); + + private TelemetryFeatures() { + } + + /** + * Registers one feature label and returns its handle. The public {@code MongoDriverInformation.register} method delegates here. + * The method is the only writer of the store: one add per label, on the cold path. + * + * @param label the label name of the feature + * @return the handle of the label + */ + public static FeatureHandle register(final String label) { + DriverFeatureHandle handle = new DriverFeatureHandle(label); + handles.add(handle); + return handle; + } + + /** + * Gets every latched label, deduped by label, in sorted order. The list is empty when the kill switch is off. The method never + * clears anything: the same labels ship in every window until the process ends. + * + * @return the latched labels, deduped and sorted + */ + public static List latchedLabels() { + if (!TelemetryStore.isEnabled()) { + return new ArrayList<>(); + } + try { + Set deduped = new TreeSet<>(); + for (DriverFeatureHandle handle : handles) { + if (handle.usedFlag()) { + deduped.add(handle.label); + } + } + return new ArrayList<>(deduped); + } catch (final Throwable t) { + // A broken label store must not break the sampler. + return new ArrayList<>(); + } + } + + /** + * Unlatches every handle. Tests use this method to isolate label assertions: a handle registered by an earlier test stays + * registered, but its latch resets. A production process never clears a latch. + */ + @VisibleForTesting(otherwise = VisibleForTesting.AccessModifier.PRIVATE) + public static void resetForTest() { + for (DriverFeatureHandle handle : handles) { + handle.resetLatch(); + } + } +} diff --git a/driver-core/src/main/com/mongodb/internal/telemetry/TelemetrySampler.java b/driver-core/src/main/com/mongodb/internal/telemetry/TelemetrySampler.java index 733ac4bdda..344c063877 100644 --- a/driver-core/src/main/com/mongodb/internal/telemetry/TelemetrySampler.java +++ b/driver-core/src/main/com/mongodb/internal/telemetry/TelemetrySampler.java @@ -20,17 +20,20 @@ import java.time.Instant; import java.time.temporal.ChronoUnit; +import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** - * The sampler of the telemetry POC. The sampler drains {@link TelemetryStore} on a fixed interval. It writes one JSON line to - * {@code System.out} when at least one counter is non-zero. The line imitates a delivery channel. + * The sampler of the telemetry POC. The sampler drains {@link TelemetryStore} and reads {@link TelemetryFeatures} on a fixed + * interval. It writes one JSON line to {@code System.out} when at least one counter is non-zero or at least one label is latched. + * The line imitates a delivery channel. *

* The line format is: - * {@code {"driver":"java","ts":"","intervalMs":,"apiUsage":{"queryBuilders":12,...}}} + * {@code {"driver":"java","ts":"","intervalMs":,"features":["gridfs",...],"apiUsage":{"queryBuilders":12,...}}} + * The features key is omitted when no label is latched. *

* This class is not part of the public API and may be removed or changed at any time. */ @@ -58,25 +61,39 @@ public static TelemetrySampler start(final long intervalMs) { } /** - * Drains the store and writes one JSON line. The method omits the line when every counter is zero. The method never throws. + * Drains the store, reads the latched labels, and writes one JSON line. The labels ship in every window: delivery is + * resend-always. The method omits the line when every counter is zero and no label is latched. The method never throws. */ void sample() { try { + List features = TelemetryFeatures.latchedLabels(); Map deltas = TelemetryStore.drain(); - if (!deltas.isEmpty()) { - System.out.println(toJsonLine(deltas)); + if (!deltas.isEmpty() || !features.isEmpty()) { + System.out.println(toJsonLine(features, deltas)); } } catch (final Throwable t) { // The sampler must not throw. The scheduled task stops on an uncaught exception. } } - String toJsonLine(final Map deltas) { + String toJsonLine(final List features, final Map deltas) { StringBuilder json = new StringBuilder("{\"driver\":\"java\",\"ts\":\"") .append(Instant.now().truncatedTo(ChronoUnit.SECONDS)) .append("\",\"intervalMs\":") - .append(intervalMs) - .append(",\"apiUsage\":{"); + .append(intervalMs); + if (!features.isEmpty()) { + json.append(",\"features\":["); + boolean first = true; + for (String feature : features) { + if (!first) { + json.append(','); + } + first = false; + json.append('"').append(feature).append('"'); + } + json.append(']'); + } + json.append(",\"apiUsage\":{"); boolean first = true; for (Map.Entry entry : deltas.entrySet()) { if (!first) { @@ -89,7 +106,7 @@ String toJsonLine(final Map deltas) { } /** - * Stops the sampler. The store keeps the counters. The counters wait for the next drain. + * Stops the sampler. The store keeps the counters. The counters wait for the next drain. The labels keep their latches. */ @Override public void close() { diff --git a/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetryFeaturesTest.java b/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetryFeaturesTest.java new file mode 100644 index 0000000000..cfee2c9a6d --- /dev/null +++ b/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetryFeaturesTest.java @@ -0,0 +1,142 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.internal.telemetry; + +import com.mongodb.FeatureHandle; +import com.mongodb.MongoDriverInformation; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * The single-path feature-label store. The public registration path is MongoDriverInformation.register. There is no internal label + * enum and no separate latch array. + */ +public class TelemetryFeaturesTest { + + @BeforeEach + @AfterEach + public void resetLabels() { + TelemetryStore.setEnabledForTest(true); + TelemetryFeatures.resetForTest(); + } + + @Test + public void thePublicRegisterPathReturnsAWorkingHandle() { + FeatureHandle handle = MongoDriverInformation.builder().build().register("spring"); + assertEquals(List.of(), TelemetryFeatures.latchedLabels()); + handle.used(); + assertEquals(List.of("spring"), TelemetryFeatures.latchedLabels()); + } + + @Test + public void aHandleLatchesOnceAndStaysLatched() { + FeatureHandle handle = TelemetryFeatures.register("spring"); + handle.used(); + handle.used(); + handle.used(); + assertEquals(List.of("spring"), TelemetryFeatures.latchedLabels()); + assertEquals(List.of("spring"), TelemetryFeatures.latchedLabels()); + } + + @Test + public void twoHandlesWithTheSameLabelDedupInTheEmitList() { + TelemetryFeatures.register("spring").used(); + TelemetryFeatures.register("spring").used(); + assertEquals(List.of("spring"), TelemetryFeatures.latchedLabels()); + } + + @Test + public void theEmitListIsSortedAndDeduped() { + TelemetryFeatures.register("zeta").used(); + TelemetryFeatures.register("alpha").used(); + TelemetryFeatures.register("alpha").used(); + assertEquals(List.of("alpha", "zeta"), TelemetryFeatures.latchedLabels()); + } + + @Test + public void theKillSwitchSuppressesTheLabels() { + FeatureHandle latched = TelemetryFeatures.register("gridfs"); + latched.used(); + TelemetryStore.setEnabledForTest(false); + try { + TelemetryFeatures.register("changeStreams").used(); + assertEquals(List.of(), TelemetryFeatures.latchedLabels()); + } finally { + TelemetryStore.setEnabledForTest(true); + } + // The first latch survived the switch: delivery is resend-always and nothing is cleared. + // The use under the switch did not latch. + assertEquals(List.of("gridfs"), TelemetryFeatures.latchedLabels()); + } + + @Test + public void aUsedHandleNeverThrows() { + FeatureHandle handle = TelemetryFeatures.register("spring"); + for (int i = 0; i < 1000; i++) { + handle.used(); + } + assertEquals(List.of("spring"), TelemetryFeatures.latchedLabels()); + } + + @Test + public void sixteenThreadsOnOneHandleLatchItOnce() throws Exception { + int threads = 16; + FeatureHandle handle = TelemetryFeatures.register("spring"); + CountDownLatch startGate = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(threads); + try { + for (int i = 0; i < threads; i++) { + executor.submit(() -> { + startGate.await(); + handle.used(); + return null; + }); + } + startGate.countDown(); + executor.shutdown(); + org.junit.jupiter.api.Assertions.assertTrue(executor.awaitTermination(30, SECONDS)); + } finally { + executor.shutdownNow(); + } + assertEquals(List.of("spring"), TelemetryFeatures.latchedLabels()); + } + + @Test + public void aBrokenHandleSetDoesNotBreakTheEmitList() { + FeatureHandle handle = TelemetryFeatures.register("gridfs"); + handle.used(); + Set original = TelemetryFeatures.handles; + TelemetryFeatures.handles = null; + try { + assertEquals(List.of(), TelemetryFeatures.latchedLabels()); + } finally { + TelemetryFeatures.handles = original; + } + // The handle latch survived: used() never touches the set. + assertEquals(List.of("gridfs"), TelemetryFeatures.latchedLabels()); + } +} diff --git a/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetrySamplerTest.java b/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetrySamplerTest.java index 792a54d175..255be2649b 100644 --- a/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetrySamplerTest.java +++ b/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetrySamplerTest.java @@ -25,9 +25,11 @@ import java.io.PrintStream; import java.nio.charset.StandardCharsets; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class TelemetrySamplerTest { @@ -37,11 +39,13 @@ public class TelemetrySamplerTest { @BeforeEach public void clearStore() { TelemetryStore.drain(); + TelemetryFeatures.resetForTest(); } @AfterEach public void restoreStore() { TelemetryStore.drain(); + TelemetryFeatures.resetForTest(); } @Test @@ -50,15 +54,24 @@ public void toJsonLineWritesTheDeltasInRegistryOrder() { Map deltas = new LinkedHashMap<>(); deltas.put("queryBuilders", 12L); deltas.put("queryRaw", 8L); - BsonDocument parsed = BsonDocument.parse(sampler.toJsonLine(deltas)); + BsonDocument parsed = BsonDocument.parse(sampler.toJsonLine(List.of(), deltas)); assertEquals("java", parsed.getString("driver").getValue()); assertEquals(2000, parsed.getNumber("intervalMs").longValue()); assertTrue(parsed.getString("ts").getValue().endsWith("Z")); + assertFalse(parsed.containsKey("features")); BsonDocument apiUsage = parsed.getDocument("apiUsage"); assertEquals(12, apiUsage.getNumber("queryBuilders").longValue()); assertEquals(8, apiUsage.getNumber("queryRaw").longValue()); } + @Test + public void toJsonLineOmitsTheApiUsageDeltasAndKeepsTheFeatures() { + TelemetrySampler sampler = new TelemetrySampler(null, 2000); + BsonDocument parsed = BsonDocument.parse(sampler.toJsonLine(List.of("convTxn", "coreTxn"), Map.of())); + assertEquals(List.of("convTxn", "coreTxn"), parsed.getArray("features").stream().map(v -> v.asString().getValue()).toList()); + assertTrue(parsed.getDocument("apiUsage").isEmpty()); + } + @Test public void theSamplerWritesOneLinePerIntervalWithTheExactDelta() throws Exception { long intervalMs = 1000; @@ -80,6 +93,44 @@ public void theSamplerWritesOneLinePerIntervalWithTheExactDelta() throws Excepti assertEquals(30, apiUsage.getNumber("queryRaw").longValue()); } + @Test + public void theSamplerResendsTheLatchedLabelsInEveryLine() throws Exception { + long intervalMs = 1000; + TelemetryFeatures.register("convTxn").used(); + ByteArrayOutputStream captured = new ByteArrayOutputStream(); + System.setOut(new PrintStream(captured, true, StandardCharsets.UTF_8)); + try (TelemetrySampler sampler = TelemetrySampler.start(intervalMs)) { + runWorkload(); + Thread.sleep(intervalMs * 3 + 500); + } finally { + System.setOut(originalOut); + } + String[] lines = captured.toString(StandardCharsets.UTF_8).split(System.lineSeparator()); + // The first line carries the workload delta and the label. The next lines carry no delta, only the resent label. + assertEquals(3, lines.length); + BsonDocument first = BsonDocument.parse(lines[0]); + BsonDocument second = BsonDocument.parse(lines[1]); + BsonDocument third = BsonDocument.parse(lines[2]); + assertEquals(List.of("convTxn"), first.getArray("features").stream().map(v -> v.asString().getValue()).toList()); + assertEquals(List.of("convTxn"), second.getArray("features").stream().map(v -> v.asString().getValue()).toList()); + assertEquals(List.of("convTxn"), third.getArray("features").stream().map(v -> v.asString().getValue()).toList()); + assertTrue(second.getDocument("apiUsage").isEmpty()); + assertTrue(third.getDocument("apiUsage").isEmpty()); + } + + @Test + public void anEmptyIntervalWithNoLatchedLabelWritesNoLine() throws Exception { + long intervalMs = 1000; + ByteArrayOutputStream captured = new ByteArrayOutputStream(); + System.setOut(new PrintStream(captured, true, StandardCharsets.UTF_8)); + try (TelemetrySampler sampler = TelemetrySampler.start(intervalMs)) { + Thread.sleep(intervalMs * 2 + 500); + } finally { + System.setOut(originalOut); + } + assertEquals(0, captured.toString(StandardCharsets.UTF_8).trim().length()); + } + private static void runWorkload() { for (int i = 0; i < 50; i++) { TelemetryStore.increment(ApiCounter.QUERY_BUILDERS); diff --git a/driver-legacy/src/test/unit/com/mongodb/telemetry/InstrumentationPocDemo.java b/driver-legacy/src/test/unit/com/mongodb/telemetry/InstrumentationPocDemo.java index 9ff152bf8a..4d27a00bc9 100644 --- a/driver-legacy/src/test/unit/com/mongodb/telemetry/InstrumentationPocDemo.java +++ b/driver-legacy/src/test/unit/com/mongodb/telemetry/InstrumentationPocDemo.java @@ -25,12 +25,17 @@ import com.mongodb.client.MongoCollection; import com.mongodb.client.model.Filters; import com.mongodb.client.model.InsertOneModel; +import com.mongodb.client.gridfs.GridFSBucket; +import com.mongodb.client.gridfs.GridFSBuckets; import com.mongodb.client.model.bulk.ClientNamespacedWriteModel; import com.mongodb.internal.telemetry.TelemetryStore; import org.bson.BsonDocument; import org.bson.BsonInt32; import org.bson.Document; +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; import java.util.List; import static com.mongodb.BasicDBObjectBuilder.start; @@ -59,12 +64,15 @@ public static void main(final String[] notUsed) throws Exception { System.out.println("[instrumentation-poc] connected: " + uri + ", interval: " + System.getProperty(TelemetryStore.INTERVAL_PROPERTY) + "ms"); System.out.println("[instrumentation-poc] workload: 3 builder, 2 raw, 1 bulk per " + ROUND_MS + "ms; " - + "legacy every 4th round; client bulk every 8th round"); + + "legacy every 4th round; client bulk every 8th round; " + + "one convenient transaction per round; core transaction every 4th round; one GridFS upload per round"); try (MongoClient client = MongoClients.create(uri); com.mongodb.MongoClient legacyClient = new com.mongodb.MongoClient(new MongoClientURI(uri))) { MongoCollection collection = client.getDatabase("telemetryPoc").getCollection("demo"); DB legacyDatabase = legacyClient.getDB("telemetryPoc"); + // Bucket creation does not latch the gridfs label. The first upload does. + GridFSBucket gridFsBucket = GridFSBuckets.create(client.getDatabase("telemetryPoc")); // The drain call starts the store and the sampler at a known time. It also clears startup residue. TelemetryStore.drain(); long round = 0; @@ -73,7 +81,7 @@ public static void main(final String[] notUsed) throws Exception { long nextRoundAt = System.nanoTime() + INTERVAL_MS * 1_000_000L / 8; while (true) { round++; - runRound(client, collection, legacyDatabase.getCollection("demo"), round); + runRound(client, collection, legacyDatabase.getCollection("demo"), gridFsBucket, round); nextRoundAt += ROUND_MS * 1_000_000L; long sleepNanos = nextRoundAt - System.nanoTime(); if (sleepNanos > 0) { @@ -84,7 +92,7 @@ public static void main(final String[] notUsed) throws Exception { } private static void runRound(final MongoClient client, final MongoCollection collection, - final DBCollection legacyCollection, final long round) throws Exception { + final DBCollection legacyCollection, final GridFSBucket gridFsBucket, final long round) throws Exception { // 3 builder queries: queryBuilders +3 per round. for (int i = 0; i < 3; i++) { collection.find(Filters.eq("round", round)).first(); @@ -106,6 +114,24 @@ private static void runRound(final MongoClient client, final MongoCollection null); + } + // 1 core transaction every 4th round, without the wrapper: the coreTxn label latches on + // the first core startTransaction. The body carries no operation, so the commit sends + // nothing. + if (round % 4 == 0) { + try (com.mongodb.client.ClientSession session = client.startSession()) { + session.startTransaction(); + session.abortTransaction(); + } + } } private InstrumentationPocDemo() { diff --git a/driver-sync/src/main/com/mongodb/client/gridfs/GridFSBucketImpl.java b/driver-sync/src/main/com/mongodb/client/gridfs/GridFSBucketImpl.java index cd9432e6fe..bed185e99d 100644 --- a/driver-sync/src/main/com/mongodb/client/gridfs/GridFSBucketImpl.java +++ b/driver-sync/src/main/com/mongodb/client/gridfs/GridFSBucketImpl.java @@ -36,6 +36,8 @@ import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import com.mongodb.internal.TimeoutContext; +import com.mongodb.FeatureHandle; +import com.mongodb.MongoDriverInformation; import com.mongodb.internal.VisibleForTesting; import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; @@ -63,6 +65,9 @@ final class GridFSBucketImpl implements GridFSBucket { private static final int DEFAULT_CHUNKSIZE_BYTES = 255 * 1024; private static final String TIMEOUT_MESSAGE = "GridFS operation exceeded the timeout limit."; + // The bucket class holds its own label handle, registered through the public path. No internal telemetry import. + private static final FeatureHandle GRIDFS_FEATURE = MongoDriverInformation.builder().build().register("gridfs"); + private final String bucketName; private final int chunkSizeBytes; private final MongoCollection filesCollection; @@ -197,6 +202,7 @@ public GridFSUploadStream openUploadStream(final ClientSession clientSession, fi private GridFSUploadStream createGridFSUploadStream(@Nullable final ClientSession clientSession, final BsonValue id, final String filename, final GridFSUploadOptions options) { + GRIDFS_FEATURE.used(); Timeout operationTimeout = startTimeout(); notNull("options", options); Integer chunkSizeBytes = options.getChunkSizeBytes(); @@ -327,6 +333,7 @@ public GridFSDownloadStream openDownloadStream(final ClientSession clientSession private GridFSDownloadStream createGridFSDownloadStream(@Nullable final ClientSession clientSession, final GridFSFile gridFSFile, @Nullable final Timeout operationTimeout) { + GRIDFS_FEATURE.used(); return new GridFSDownloadStreamImpl(clientSession, gridFSFile, chunksCollection, operationTimeout); } @@ -398,11 +405,13 @@ public GridFSFindIterable find(final ClientSession clientSession, final Bson fil } private GridFSFindIterable createGridFSFindIterable(@Nullable final ClientSession clientSession, @Nullable final Bson filter) { + GRIDFS_FEATURE.used(); return new GridFSFindIterableImpl(createFindIterable(clientSession, filter, startTimeout())); } private GridFSFindIterable createGridFSFindIterable(@Nullable final ClientSession clientSession, @Nullable final Bson filter, @Nullable final Timeout operationTimeout) { + GRIDFS_FEATURE.used(); return new GridFSFindIterableImpl(createFindIterable(clientSession, filter, operationTimeout)); } diff --git a/driver-sync/src/main/com/mongodb/client/internal/ClientEncryptionImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ClientEncryptionImpl.java index 3edef6b937..4ebf9d54f8 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ClientEncryptionImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ClientEncryptionImpl.java @@ -43,6 +43,10 @@ import com.mongodb.internal.VisibleForTesting; import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; +import com.mongodb.FeatureHandle; +import com.mongodb.MongoDriverInformation; +import com.mongodb.FeatureHandle; +import com.mongodb.MongoDriverInformation; import org.bson.BsonArray; import org.bson.BsonBinary; import org.bson.BsonDocument; @@ -72,6 +76,9 @@ *

This class is not part of the public API and may be removed or changed at any time

*/ public class ClientEncryptionImpl implements ClientEncryption { + // The vault class holds its own label handle, registered through the public path. No internal telemetry import. + private static final FeatureHandle EXPLICIT_ENCRYPTION_FEATURE = MongoDriverInformation.builder().build().register("csfle"); + private final Crypt crypt; private final ClientEncryptionSettings options; private final MongoClient keyVaultClient; @@ -124,12 +131,14 @@ public BsonBinary createDataKey(final String kmsProvider, final DataKeyOptions d @Override public BsonBinary encrypt(final BsonValue value, final EncryptOptions options) { + EXPLICIT_ENCRYPTION_FEATURE.used(); Timeout operationTimeout = startTimeout(); return crypt.encryptExplicitly(value, options, operationTimeout); } @Override public BsonDocument encryptExpression(final Bson expression, final EncryptOptions options) { + EXPLICIT_ENCRYPTION_FEATURE.used(); Timeout operationTimeout = startTimeout(); return crypt.encryptExpression(expression.toBsonDocument(BsonDocument.class, collection.getCodecRegistry()), options, operationTimeout); diff --git a/driver-sync/src/main/com/mongodb/client/internal/ClientSessionImpl.java b/driver-sync/src/main/com/mongodb/client/internal/ClientSessionImpl.java index 482213b159..6dcfd4a680 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/ClientSessionImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/ClientSessionImpl.java @@ -42,6 +42,8 @@ import com.mongodb.internal.time.ExponentialBackoff; import com.mongodb.internal.time.Timeout; import com.mongodb.lang.Nullable; +import com.mongodb.FeatureHandle; +import com.mongodb.MongoDriverInformation; import java.util.concurrent.TimeUnit; import java.util.function.BooleanSupplier; @@ -59,6 +61,10 @@ final class ClientSessionImpl extends BaseClientSessionImpl implements ClientSession { + // The session class holds its own label handles, registered through the public path. No internal telemetry import. + private static final FeatureHandle CONV_TXN_FEATURE = MongoDriverInformation.builder().build().register("convTxn"); + private static final FeatureHandle CORE_TXN_FEATURE = MongoDriverInformation.builder().build().register("coreTxn"); + private static final long MAX_RETRY_TIME_LIMIT_MS = 120000; private final OperationExecutor operationExecutor; @@ -126,6 +132,7 @@ public void startTransaction() { @Override public void startTransaction(final TransactionOptions transactionOptions) { + CORE_TXN_FEATURE.used(); startTransaction(transactionOptions, createTimeoutContext(transactionOptions)); } @@ -274,6 +281,7 @@ public T withTransaction(final TransactionBody transactionBody) { @Override public T withTransaction(final TransactionBody transactionBody, final TransactionOptions options) { + CONV_TXN_FEATURE.used(); notNull("transactionBody", transactionBody); TimeoutContext withTransactionTimeoutContext = createTimeoutContext(options); boolean timeoutMsConfigured = withTransactionTimeoutContext.hasTimeoutMS(); diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java index 446216dc55..877fc2283c 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java @@ -64,6 +64,8 @@ import com.mongodb.internal.telemetry.TelemetryStore; import com.mongodb.internal.thread.AsyncClientExecutor; import com.mongodb.lang.Nullable; +import com.mongodb.FeatureHandle; +import com.mongodb.MongoDriverInformation; import org.bson.BsonDocument; import org.bson.Document; import org.bson.UuidRepresentation; @@ -85,6 +87,9 @@ import static java.util.concurrent.TimeUnit.MILLISECONDS; final class MongoClusterImpl implements MongoCluster { + + // Each class holds its own label handle for the same label, registered through the public path. The emitter dedups by label. + private static final FeatureHandle CHANGE_STREAMS_FEATURE = MongoDriverInformation.builder().build().register("changeStreams"); @Nullable private final AutoEncryptionSettings autoEncryptionSettings; private final Cluster cluster; @@ -400,6 +405,7 @@ private MongoIterable createListDatabaseNamesIterable(@Nullable final Cl private ChangeStreamIterable createChangeStreamIterable(@Nullable final ClientSession clientSession, final List pipeline, final Class resultClass) { + CHANGE_STREAMS_FEATURE.used(); return new ChangeStreamIterableImpl<>(clientSession, "admin", codecRegistry, readPreference, readConcern, operationExecutor, pipeline, resultClass, ChangeStreamLevel.CLIENT, retryReads, maxAdaptiveRetriesSetting, timeoutSettings); diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java index 626b5381a1..3ccabe7073 100755 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java @@ -69,6 +69,8 @@ import com.mongodb.internal.telemetry.ApiCounter; import com.mongodb.internal.telemetry.TelemetryStore; import com.mongodb.lang.Nullable; +import com.mongodb.FeatureHandle; +import com.mongodb.MongoDriverInformation; import org.bson.BsonDocument; import org.bson.BsonValue; import org.bson.Document; @@ -92,6 +94,9 @@ import static org.bson.codecs.configuration.CodecRegistries.withUuidRepresentation; class MongoCollectionImpl implements MongoCollection { + + // Each class holds its own label handle for the same label, registered through the public path. The emitter dedups by label. + private static final FeatureHandle CHANGE_STREAMS_FEATURE = MongoDriverInformation.builder().build().register("changeStreams"); private final MongoNamespace namespace; private final Class documentClass; private final ReadPreference readPreference; @@ -414,6 +419,7 @@ public ChangeStreamIterable watch(final ClientSession clientS private ChangeStreamIterable createChangeStreamIterable(@Nullable final ClientSession clientSession, final List pipeline, final Class resultClass) { + CHANGE_STREAMS_FEATURE.used(); return new ChangeStreamIterableImpl<>(clientSession, namespace, codecRegistry, readPreference, readConcern, executor, pipeline, resultClass, ChangeStreamLevel.COLLECTION, retryReads, maxAdaptiveRetriesSetting, timeoutSettings); } diff --git a/driver-sync/src/main/com/mongodb/client/internal/MongoDatabaseImpl.java b/driver-sync/src/main/com/mongodb/client/internal/MongoDatabaseImpl.java index 1f8a2cdedb..afc0908d01 100644 --- a/driver-sync/src/main/com/mongodb/client/internal/MongoDatabaseImpl.java +++ b/driver-sync/src/main/com/mongodb/client/internal/MongoDatabaseImpl.java @@ -36,6 +36,8 @@ import com.mongodb.internal.client.model.changestream.ChangeStreamLevel; import com.mongodb.internal.operation.Operations; import com.mongodb.lang.Nullable; +import com.mongodb.FeatureHandle; +import com.mongodb.MongoDriverInformation; import org.bson.BsonDocument; import org.bson.Document; import org.bson.UuidRepresentation; @@ -55,6 +57,9 @@ *

This class is not part of the public API and may be removed or changed at any time

*/ public class MongoDatabaseImpl implements MongoDatabase { + + // Each class holds its own label handle for the same label, registered through the public path. The emitter dedups by label. + private static final FeatureHandle CHANGE_STREAMS_FEATURE = MongoDriverInformation.builder().build().register("changeStreams"); private final String name; private final ReadPreference readPreference; private final CodecRegistry codecRegistry; @@ -405,6 +410,7 @@ private AggregateIterable createAggregateIterable(@Nullable f private ChangeStreamIterable createChangeStreamIterable(@Nullable final ClientSession clientSession, final List pipeline, final Class resultClass) { + CHANGE_STREAMS_FEATURE.used(); return new ChangeStreamIterableImpl<>(clientSession, name, codecRegistry, readPreference, readConcern, executor, pipeline, resultClass, ChangeStreamLevel.DATABASE, retryReads, maxAdaptiveRetriesSetting, timeoutSettings); } diff --git a/driver-sync/src/test/unit/com/mongodb/client/internal/TelemetryFeatureLabelsTest.java b/driver-sync/src/test/unit/com/mongodb/client/internal/TelemetryFeatureLabelsTest.java new file mode 100644 index 0000000000..953aaf27ed --- /dev/null +++ b/driver-sync/src/test/unit/com/mongodb/client/internal/TelemetryFeatureLabelsTest.java @@ -0,0 +1,148 @@ +/* + * Copyright 2008-present MongoDB, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.mongodb.client.internal; + +import com.mongodb.client.ClientSession; +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.mongodb.client.gridfs.GridFSBucket; +import com.mongodb.client.gridfs.GridFSBuckets; +import com.mongodb.internal.telemetry.TelemetryFeatures; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * The driver-internal feature labels. Every label rides the single public registration path: the call sites hold a handle from + * MongoDriverInformation.register and call used() on first real use. Registration alone never counts as use. The transaction bodies + * carry no operation, so the tests need no transaction-capable server. The latch sites are client-side. + */ +public class TelemetryFeatureLabelsTest { + + @BeforeEach + @AfterEach + public void resetLabels() { + TelemetryFeatures.resetForTest(); + } + + @Test + public void aWatchCallLatchesChangeStreams() { + try (MongoClient client = MongoClients.create()) { + client.watch(); + client.getDatabase("db").watch(); + client.getDatabase("db").getCollection("coll").watch(); + } + List labels = TelemetryFeatures.latchedLabels(); + assertEquals(1, labels.size()); + assertTrue(labels.contains("changeStreams")); + } + + @Test + public void aGridFsBucketCreationLatchesNothing() { + try (MongoClient client = MongoClients.create()) { + GridFSBucket bucket = GridFSBuckets.create(client.getDatabase("db")); + bucket.getBucketName(); + } + assertEquals(List.of(), TelemetryFeatures.latchedLabels()); + } + + @Test + public void theFirstGridFsBucketOperationLatchesGridFs() { + try (MongoClient client = MongoClients.create()) { + GridFSBucket bucket = GridFSBuckets.create(client.getDatabase("db")); + // find is lazy: the call counts as the first bucket operation, and it needs no server. + bucket.find(); + } + List labels = TelemetryFeatures.latchedLabels(); + assertEquals(1, labels.size()); + assertTrue(labels.contains("gridfs")); + } + + @Test + public void withTransactionLatchesConvTxnOnly() { + try (MongoClient client = MongoClients.create()) { + try (ClientSession session = client.startSession()) { + session.withTransaction(() -> null); + } + } + List labels = TelemetryFeatures.latchedLabels(); + assertTrue(labels.contains("convTxn")); + assertFalse(labels.contains("coreTxn")); + } + + @Test + public void startTransactionWithoutTheWrapperLatchesCoreTxnOnly() { + try (MongoClient client = MongoClients.create()) { + try (ClientSession session = client.startSession()) { + session.startTransaction(); + session.abortTransaction(); + } + } + List labels = TelemetryFeatures.latchedLabels(); + assertTrue(labels.contains("coreTxn")); + assertFalse(labels.contains("convTxn")); + } + + @Test + public void aNestedStartTransactionInsideTheWrapperLatchesBoth() { + try (MongoClient client = MongoClients.create()) { + try (ClientSession session = client.startSession()) { + session.withTransaction(() -> { + try { + // The server forbids a nested transaction on the same session. The invocation still latches coreTxn. + session.startTransaction(); + } catch (IllegalStateException expected) { + } + return null; + }); + } + } + List labels = TelemetryFeatures.latchedLabels(); + assertTrue(labels.contains("convTxn")); + assertTrue(labels.contains("coreTxn")); + } + + @Test + public void repeatedUseKeepsTheLatchAndAddsNothing() { + try (MongoClient client = MongoClients.create()) { + try (ClientSession session = client.startSession()) { + session.withTransaction(() -> null); + session.withTransaction(() -> null); + session.withTransaction(() -> null); + } + } + List labels = TelemetryFeatures.latchedLabels(); + assertEquals(1, labels.size()); + assertTrue(labels.contains("convTxn")); + } + + @Test + public void aPlainSessionLatchesNothing() { + try (MongoClient client = MongoClients.create()) { + try (ClientSession session = client.startSession()) { + assertFalse(session.hasActiveTransaction()); + } + } + assertEquals(List.of(), TelemetryFeatures.latchedLabels()); + } +}