use of org.bson.codecs.Decoder in project incubator-skywalking by apache.
the class MongoDBMethodInterceptorTest method setUp.
@SuppressWarnings({ "rawtypes", "unchecked" })
@Before
public void setUp() throws Exception {
interceptor = new MongoDBMethodInterceptor();
Config.Plugin.MongoDB.TRACE_PARAM = true;
when(enhancedInstance.getSkyWalkingDynamicField()).thenReturn("127.0.0.1:27017");
BsonDocument document = new BsonDocument();
document.append("name", new BsonString("by"));
MongoNamespace mongoNamespace = new MongoNamespace("test.user");
Decoder decoder = PowerMockito.mock(Decoder.class);
FindOperation findOperation = new FindOperation(mongoNamespace, decoder);
findOperation.filter(document);
arguments = new Object[] { findOperation };
argumentTypes = new Class[] { findOperation.getClass() };
}
use of org.bson.codecs.Decoder in project mongo-java-driver by mongodb.
the class CommandOperationHelper method executeRetryableWriteAsync.
static <T, R> void executeRetryableWriteAsync(final AsyncWriteBinding binding, final String database, final ReadPreference readPreference, final FieldNameValidator fieldNameValidator, final Decoder<T> commandResultDecoder, final CommandCreator commandCreator, final CommandWriteTransformerAsync<T, R> transformer, final Function<BsonDocument, BsonDocument> retryCommandModifier, final SingleResultCallback<R> callback) {
RetryState retryState = initialRetryState(true);
binding.retain();
AsyncCallbackSupplier<R> asyncWrite = CommandOperationHelper.<R>decorateWriteWithRetries(retryState, funcCallback -> {
logRetryExecute(retryState);
boolean firstAttempt = retryState.isFirstAttempt();
if (!firstAttempt && binding.getSessionContext().hasActiveTransaction()) {
binding.getSessionContext().clearTransactionContext();
}
withAsyncSourceAndConnection(binding::getWriteConnectionSource, true, funcCallback, (source, connection, releasingCallback) -> {
int maxWireVersion = connection.getDescription().getMaxWireVersion();
SingleResultCallback<R> addingRetryableLabelCallback = firstAttempt ? releasingCallback : addingRetryableLabelCallback(releasingCallback, maxWireVersion);
if (retryState.breakAndCompleteIfRetryAnd(() -> !canRetryWrite(source.getServerDescription(), connection.getDescription(), binding.getSessionContext()), addingRetryableLabelCallback)) {
return;
}
BsonDocument command;
try {
command = retryState.attachment(AttachmentKeys.command()).map(previousAttemptCommand -> {
assertFalse(firstAttempt);
return retryCommandModifier.apply(previousAttemptCommand);
}).orElseGet(() -> commandCreator.create(source.getServerDescription(), connection.getDescription()));
// attach `maxWireVersion`, `retryableCommandFlag` ASAP because they are used to check whether we should retry
retryState.attach(AttachmentKeys.maxWireVersion(), maxWireVersion, true).attach(AttachmentKeys.retryableCommandFlag(), isRetryWritesEnabled(command), true).attach(AttachmentKeys.commandDescriptionSupplier(), command::getFirstKey, true).attach(AttachmentKeys.command(), command, false);
logRetryExecute(retryState);
} catch (Throwable t) {
addingRetryableLabelCallback.onResult(null, t);
return;
}
connection.commandAsync(database, command, fieldNameValidator, readPreference, commandResultDecoder, binding.getSessionContext(), binding.getServerApi(), binding.getRequestContext(), transformingWriteCallback(transformer, connection, addingRetryableLabelCallback));
});
}).whenComplete(binding::release);
asyncWrite.get(exceptionTransformingCallback(errorHandlingCallback(callback, LOGGER)));
}
use of org.bson.codecs.Decoder in project mongo-java-driver by mongodb.
the class ListIndexesOperation method executeAsync.
@Override
public void executeAsync(final AsyncReadBinding binding, final SingleResultCallback<AsyncBatchCursor<T>> callback) {
RetryState retryState = initialRetryState(retryReads);
binding.retain();
AsyncCallbackSupplier<AsyncBatchCursor<T>> asyncRead = CommandOperationHelper.<AsyncBatchCursor<T>>decorateReadWithRetries(retryState, funcCallback -> {
logRetryExecute(retryState);
withAsyncSourceAndConnection(binding::getReadConnectionSource, false, funcCallback, (source, connection, releasingCallback) -> {
if (retryState.breakAndCompleteIfRetryAnd(() -> !canRetryRead(source.getServerDescription(), connection.getDescription(), binding.getSessionContext()), releasingCallback)) {
return;
}
if (serverIsAtLeastVersionThreeDotZero(connection.getDescription())) {
createReadCommandAndExecuteAsync(retryState, binding, source, namespace.getDatabaseName(), getCommandCreator(), createCommandDecoder(), asyncTransformer(), connection, (result, t) -> {
if (t != null && !isNamespaceError(t)) {
releasingCallback.onResult(null, t);
} else {
releasingCallback.onResult(result != null ? result : emptyAsyncCursor(source), null);
}
});
} else {
retryState.markAsLastAttempt();
connection.queryAsync(getIndexNamespace(), asQueryDocument(connection.getDescription(), binding.getReadPreference()), null, 0, 0, batchSize, binding.getReadPreference().isSecondaryOk(), false, false, false, false, false, decoder, binding.getRequestContext(), new SingleResultCallback<QueryResult<T>>() {
@Override
public void onResult(final QueryResult<T> result, final Throwable t) {
if (t != null) {
releasingCallback.onResult(null, t);
} else {
releasingCallback.onResult(new AsyncQueryBatchCursor<T>(result, 0, batchSize, 0, decoder, source, connection), null);
}
}
});
}
});
}).whenComplete(binding::release);
asyncRead.get(errorHandlingCallback(callback, LOGGER));
}
use of org.bson.codecs.Decoder in project mongo-java-driver by mongodb.
the class CryptConnection method commandAsync.
@Override
public <T> void commandAsync(final String database, final BsonDocument command, final FieldNameValidator commandFieldNameValidator, final ReadPreference readPreference, final Decoder<T> commandResultDecoder, final SessionContext sessionContext, final ServerApi serverApi, final RequestContext requestContext, final boolean responseExpected, @Nullable final SplittablePayload payload, @Nullable final FieldNameValidator payloadFieldNameValidator, final SingleResultCallback<T> callback) {
if (serverIsLessThanVersionFourDotTwo(wrapped.getDescription())) {
callback.onResult(null, new MongoClientException("Auto-encryption requires a minimum MongoDB version of 4.2"));
return;
}
try {
BasicOutputBuffer bsonOutput = new BasicOutputBuffer();
BsonBinaryWriter bsonBinaryWriter = new BsonBinaryWriter(new BsonWriterSettings(), new BsonBinaryWriterSettings(getDescription().getMaxDocumentSize()), bsonOutput, getFieldNameValidator(payload, commandFieldNameValidator, payloadFieldNameValidator));
BsonWriter writer = payload == null ? bsonBinaryWriter : new SplittablePayloadBsonWriter(bsonBinaryWriter, bsonOutput, createSplittablePayloadMessageSettings(), payload, MAX_SPLITTABLE_DOCUMENT_SIZE);
getEncoder(command).encode(writer, command, EncoderContext.builder().build());
crypt.encrypt(database, new RawBsonDocument(bsonOutput.getInternalBuffer(), 0, bsonOutput.getSize())).flatMap((Function<RawBsonDocument, Mono<RawBsonDocument>>) encryptedCommand -> Mono.create(sink -> wrapped.commandAsync(database, encryptedCommand, commandFieldNameValidator, readPreference, new RawBsonDocumentCodec(), sessionContext, serverApi, requestContext, responseExpected, null, null, sinkToCallback(sink)))).flatMap(crypt::decrypt).map(decryptedResponse -> commandResultDecoder.decode(new BsonBinaryReader(decryptedResponse.getByteBuffer().asNIO()), DecoderContext.builder().build())).subscribe(decryptedResult -> callback.onResult(decryptedResult, null), e -> callback.onResult(null, e));
} catch (Throwable t) {
callback.onResult(null, t);
}
}
use of org.bson.codecs.Decoder in project mongo-java-driver by mongodb.
the class CommandOperationHelper method executeRetryableWrite.
static <T, R> R executeRetryableWrite(final WriteBinding binding, final String database, final ReadPreference readPreference, final FieldNameValidator fieldNameValidator, final Decoder<T> commandResultDecoder, final CommandCreator commandCreator, final CommandWriteTransformer<T, R> transformer, final Function<BsonDocument, BsonDocument> retryCommandModifier) {
RetryState retryState = initialRetryState(true);
Supplier<R> retryingWrite = decorateWriteWithRetries(retryState, () -> {
logRetryExecute(retryState);
boolean firstAttempt = retryState.isFirstAttempt();
if (!firstAttempt && binding.getSessionContext().hasActiveTransaction()) {
binding.getSessionContext().clearTransactionContext();
}
return withSourceAndConnection(binding::getWriteConnectionSource, true, (source, connection) -> {
int maxWireVersion = connection.getDescription().getMaxWireVersion();
try {
retryState.breakAndThrowIfRetryAnd(() -> !canRetryWrite(source.getServerDescription(), connection.getDescription(), binding.getSessionContext()));
BsonDocument command = retryState.attachment(AttachmentKeys.command()).map(previousAttemptCommand -> {
assertFalse(firstAttempt);
return retryCommandModifier.apply(previousAttemptCommand);
}).orElseGet(() -> commandCreator.create(source.getServerDescription(), connection.getDescription()));
// attach `maxWireVersion`, `retryableCommandFlag` ASAP because they are used to check whether we should retry
retryState.attach(AttachmentKeys.maxWireVersion(), maxWireVersion, true).attach(AttachmentKeys.retryableCommandFlag(), isRetryWritesEnabled(command), true).attach(AttachmentKeys.commandDescriptionSupplier(), command::getFirstKey, true).attach(AttachmentKeys.command(), command, false);
logRetryExecute(retryState);
return transformer.apply(connection.command(database, command, fieldNameValidator, readPreference, commandResultDecoder, binding.getSessionContext(), binding.getServerApi(), binding.getRequestContext()), connection);
} catch (MongoException e) {
if (!firstAttempt) {
addRetryableWriteErrorLabel(e, maxWireVersion);
}
throw e;
}
});
});
try {
return retryingWrite.get();
} catch (MongoException e) {
throw transformWriteException(e);
}
}
Aggregations