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/client/model/Filters.java b/driver-core/src/main/com/mongodb/client/model/Filters.java
index c516fe2893..06df9b8dbf 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;
@@ -33,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;
@@ -462,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));
+ }
+ };
}
/**
@@ -520,6 +530,8 @@ 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)));
}
};
@@ -866,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();
+ }
+ };
}
@@ -882,6 +901,17 @@ 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 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) {
+ TelemetryStore.increment(ApiCounter.QUERY_RAW);
+ }
+ }
+
private static String operatorFilterToString(final String fieldName, final String operator, final Object value) {
return "Operator Filter{"
+ "fieldName='" + fieldName + '\''
@@ -901,6 +931,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);
}
@@ -947,6 +978,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();
@@ -1003,8 +1035,10 @@ 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);
clauses.add(filter.toBsonDocument(documentClass, codecRegistry));
}
@@ -1062,10 +1096,12 @@ 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();
for (Bson filter : filters) {
+ countRawChild(filter);
filtersArray.add(filter.toBsonDocument(documentClass, codecRegistry));
}
@@ -1119,6 +1155,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();
@@ -1183,6 +1220,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();
@@ -1237,6 +1275,8 @@ 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) {
Map.Entry entry = filterDocument.entrySet().iterator().next();
@@ -1323,6 +1363,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);
@@ -1403,6 +1444,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/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/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
new file mode 100644
index 0000000000..344c063877
--- /dev/null
+++ b/driver-core/src/main/com/mongodb/internal/telemetry/TelemetrySampler.java
@@ -0,0 +1,115 @@
+/*
+ * 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.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} 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":,"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.
+ */
+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, 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() || !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 List features, final Map deltas) {
+ StringBuilder json = new StringBuilder("{\"driver\":\"java\",\"ts\":\"")
+ .append(Instant.now().truncatedTo(ChronoUnit.SECONDS))
+ .append("\",\"intervalMs\":")
+ .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) {
+ 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. The labels keep their latches.
+ */
+ @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/client/model/FiltersUsageCountersTest.java b/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java
new file mode 100644
index 0000000000..7304ef6c04
--- /dev/null
+++ b/driver-core/src/test/unit/com/mongodb/client/model/FiltersUsageCountersTest.java
@@ -0,0 +1,119 @@
+/*
+ * 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.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.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;
+
+/**
+ * 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 {
+
+ private static final CodecRegistry CODEC_REGISTRY = MongoClientSettings.getDefaultCodecRegistry();
+
+ @BeforeEach
+ @AfterEach
+ public void clearStore() {
+ TelemetryStore.drain();
+ }
+
+ @Test
+ public void aLeafRenderCountsOneQueryBuildersUse() {
+ eq("x", 1).toBsonDocument(Object.class, CODEC_REGISTRY);
+ assertEquals(1L, TelemetryStore.drain().get("queryBuilders"));
+ }
+
+ @Test
+ public void aCombinatorRenderCountsItselfAndItsChildren() {
+ or(eq("x", 1)).toBsonDocument(Object.class, CODEC_REGISTRY);
+ Map deltas = TelemetryStore.drain();
+ 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(3L, TelemetryStore.drain().get("queryBuilders"));
+ }
+
+ @Test
+ 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"));
+ 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(2L, deltas.get("queryBuilders"));
+ assertEquals(1L, deltas.get("queryRaw"));
+ }
+
+ @Test
+ 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(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-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
new file mode 100644
index 0000000000..255be2649b
--- /dev/null
+++ b/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetrySamplerTest.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 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.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 {
+
+ private final PrintStream originalOut = System.out;
+
+ @BeforeEach
+ public void clearStore() {
+ TelemetryStore.drain();
+ TelemetryFeatures.resetForTest();
+ }
+
+ @AfterEach
+ public void restoreStore() {
+ TelemetryStore.drain();
+ TelemetryFeatures.resetForTest();
+ }
+
+ @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(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;
+ 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());
+ }
+
+ @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);
+ }
+ 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..558ffe8986
--- /dev/null
+++ b/driver-core/src/test/unit/com/mongodb/internal/telemetry/TelemetryStoreTest.java
@@ -0,0 +1,180 @@
+/*
+ * 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.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;
+
+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.assertNotNull;
+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();
+ // 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"));
+ }
+
+ @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");
+ }
+ }
+}
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/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-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..4d27a00bc9
--- /dev/null
+++ b/driver-legacy/src/test/unit/com/mongodb/telemetry/InstrumentationPocDemo.java
@@ -0,0 +1,139 @@
+/*
+ * 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.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;
+
+/**
+ * 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; "
+ + "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;
+ // 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"), gridFsBucket, 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 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();
+ }
+ // 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))));
+ }
+ // 1 GridFS upload per round: the gridfs label latches on the first bucket operation, not on bucket creation.
+ try (InputStream source = new ByteArrayInputStream("telemetry-poc-demo".getBytes(StandardCharsets.UTF_8))) {
+ gridFsBucket.uploadFromStream("demo-" + round, source);
+ }
+ // 1 convenient transaction per round: the convTxn label latches on the first wrapper call.
+ // The body carries no operation, so the demo needs no transaction-capable server.
+ try (com.mongodb.client.ClientSession session = client.startSession()) {
+ session.withTransaction(() -> 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 9052670411..877fc2283c 100644
--- a/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java
+++ b/driver-sync/src/main/com/mongodb/client/internal/MongoClusterImpl.java
@@ -60,8 +60,12 @@
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 com.mongodb.FeatureHandle;
+import com.mongodb.MongoDriverInformation;
import org.bson.BsonDocument;
import org.bson.Document;
import org.bson.UuidRepresentation;
@@ -83,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;
@@ -398,6 +405,7 @@ private MongoIterable createListDatabaseNamesIterable(@Nullable final Cl
private ChangeStreamIterable createChangeStreamIterable(@Nullable final ClientSession clientSession,
final List extends Bson> pipeline, final Class resultClass) {
+ CHANGE_STREAMS_FEATURE.used();
return new ChangeStreamIterableImpl<>(clientSession, "admin", codecRegistry, readPreference,
readConcern, operationExecutor, pipeline, resultClass, ChangeStreamLevel.CLIENT,
retryReads, maxAdaptiveRetriesSetting, timeoutSettings);
@@ -407,6 +415,7 @@ private ClientBulkWriteResult executeBulkWrite(
@Nullable final ClientSession clientSession,
final List extends ClientNamespacedWriteModel> 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..3ccabe7073 100755
--- a/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java
+++ b/driver-sync/src/main/com/mongodb/client/internal/MongoCollectionImpl.java
@@ -66,7 +66,11 @@
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.lang.Nullable;
+import com.mongodb.FeatureHandle;
+import com.mongodb.MongoDriverInformation;
import org.bson.BsonDocument;
import org.bson.BsonValue;
import org.bson.Document;
@@ -90,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;
@@ -412,6 +419,7 @@ public ChangeStreamIterable watch(final ClientSession clientS
private ChangeStreamIterable createChangeStreamIterable(@Nullable final ClientSession clientSession,
final List extends Bson> pipeline,
final Class resultClass) {
+ CHANGE_STREAMS_FEATURE.used();
return new ChangeStreamIterableImpl<>(clientSession, namespace, codecRegistry, readPreference, readConcern, executor,
pipeline, resultClass, ChangeStreamLevel.COLLECTION, retryReads, maxAdaptiveRetriesSetting, timeoutSettings);
}
@@ -479,6 +487,7 @@ private BulkWriteResult executeBulkWrite(@Nullable final ClientSession clientSes
final List extends WriteModel extends TDocument>> requests,
final BulkWriteOptions options) {
notNull("requests", requests);
+ TelemetryStore.increment(ApiCounter.BULK_WRITE_COLLECTION);
return getExecutor(timeoutSettings)
.execute(operations.bulkWrite(requests, options), readConcern, clientSession);
}
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 extends Bson> 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/MongoCollectionImplUsageCountersTest.java b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java
new file mode 100644
index 0000000000..fda858e601
--- /dev/null
+++ b/driver-sync/src/test/unit/com/mongodb/client/internal/MongoCollectionImplUsageCountersTest.java
@@ -0,0 +1,211 @@
+/*
+ * 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.operation.BatchCursor;
+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.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;
+
+/**
+ * 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;
+
+ @BeforeEach
+ public void setUp() {
+ TelemetryStore.drain();
+ collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of())));
+ }
+
+ @AfterEach
+ public void clearStore() {
+ TelemetryStore.drain();
+ }
+
+ @Test
+ public void findWithARawRootCountsNothing() {
+ collection.find(new Document("x", 1));
+ collection.find(new BsonDocument("x", new BsonInt32(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));
+ 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(3L, deltas.get("queryBuilders"));
+ assertFalse(deltas.containsKey("queryRaw"));
+ }
+
+ @Test
+ 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"));
+ assertEquals(1L, deltas.get("queryBuilders"));
+ }
+
+ @Test
+ 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(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
+ public void findWithNoFilterCountsNothing() {
+ collection.find();
+ collection.find(Document.class);
+ assertTrue(TelemetryStore.drain().isEmpty());
+ }
+
+ @Test
+ public void countDocumentsWithARawRootCountsNothing() {
+ collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(1L))));
+ assertEquals(1L, collection.countDocuments(new Document("x", 1)));
+ assertTrue(TelemetryStore.drain().isEmpty());
+ }
+
+ @Test
+ public void deleteManyWithABuilderWrappedRawTreeCountsOnExecution() {
+ collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(BulkWriteResult.acknowledged(DELETE, 1, 0, List.of(), List.of())))));
+ 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 deleteOneWithARawRootCountsNothing() {
+ collection = newCollection(new TestOperationExecutor(new ArrayList<>(List.of(BulkWriteResult.acknowledged(DELETE, 1, 0, List.of(), List.of())))));
+ assertNotNull(collection.deleteOne(new BsonDocument()));
+ assertTrue(TelemetryStore.drain().isEmpty());
+ }
+
+ @Test
+ public void findOneAndDeleteWithARawRootCountsNothing() {
+ collection = newCollection(new TestOperationExecutor(new ArrayList<>(Collections.singletonList(null))));
+ assertNull(collection.findOneAndDelete(new Document("x", 1)));
+ assertTrue(TelemetryStore.drain().isEmpty());
+ }
+
+ @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(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")
+ 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,
+ true, true, null, ReadConcern.MAJORITY, UuidRepresentation.JAVA_LEGACY, null, TIMEOUT_SETTINGS, executor);
+ }
+}
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());
+ }
+}