spring-data-mongodb icon indicating copy to clipboard operation
spring-data-mongodb copied to clipboard

"update one" aggregation update with optimistic locking throws exception

Open tiboun opened this issue 3 years ago • 4 comments

Hi,

I was wondering if I used the aggregation update badly.

I'm currently using spring-data-mongodb 3.3.4.

In fact, update first throws an exception while update all doesn't because of the optimistic lock checking in the method doUpdate of ReactiveMongoTemplate.

In order to reproduce the exception, we need to do an aggregation update and specify a matching query that doesn't match any document. I currently have two stages in my aggregation pipeline.

The exception occurs while trying to get MappedUpdate from the entity before checking if it contains the version property in order to throw an OptimisticLockingFailureException. A "'name' must not be null" is thrown.

Above this method we can see that we make a difference between aggregation update and basic update. My suggestion would be to change the code as follows but didn't check it yet :

Change from :

if (entity != null && entity.hasVersionProperty() && !multi) {
				if (updateResult.wasAcknowledged() && updateResult.getMatchedCount() == 0) {

					Document updateObj = updateContext.getMappedUpdate(entity);
					if (containsVersionProperty(queryObj, entity))
						throw new OptimisticLockingFailureException("Optimistic lock exception on saving entity: "
								+ updateObj.toString() + " to collection " + collectionName);
				}
			}

to:

if (entity != null && entity.hasVersionProperty() && !multi) {
				if (updateResult.wasAcknowledged() && updateResult.getMatchedCount() == 0) {
					if (containsVersionProperty(queryObj, entity)){
					    List<Document> updateObjs = updateContext.isAggregationUpdate() ? updateContext.getUpdatePipeline(entityClass): List.of(updateContext.getMappedUpdate(entity));
                                            String updateObjStr = updateObjs.stream().map(String::valueOf).collect(Collectors.joining("[", ",\n", "]"));
						throw new OptimisticLockingFailureException("Optimistic lock exception on saving entity: "
								+ updateObjStr + " to collection " + collectionName);
                                        }
				}
			}

Moving the build of updateObj to the if block avoid building it when we know that query object doesn't contain the version property save some computation.

We may, as well, move it to the previous if condition if getting version property don't do any computation as follow :

if (!multi && containsVersionProperty(queryObj, entity)) {
				if (updateResult.wasAcknowledged() && updateResult.getMatchedCount() == 0) {
					    List<Document> updateObjs = updateContext.isAggregationUpdate() ? updateContext.getUpdatePipeline(entityClass): List.of(updateContext.getMappedUpdate(entity));
                                            String updateObjStr = updateObjs.stream().map(String::valueOf).collect(Collectors.joining("[", ",\n", "]"));
						throw new OptimisticLockingFailureException("Optimistic lock exception on saving entity: "
								+ updateObjStr + " to collection " + collectionName);
				}
			}

As a workaround, since the match query target a document id, I used all instead of first and all works as expected since I don't use the optimistic locking in my case.

tiboun avatar Jun 27 '22 12:06 tiboun

It would be great to have a minimal sample (something that we can unzip or git clone, build, and deploy) that reproduces the problem.

christophstrobl avatar Jun 27 '22 12:06 christophstrobl

I've modified one of the ReactiveMongoTemplateUpdateTest in order to reproduce the problem.

You can reproduce so with the following unit test:

@Test
	public void versionedAggregateUpdateWithSet() {

		Versioned source = new Versioned("id-1", "value-0");
		template.insert(Versioned.class).one(source).then().as(StepVerifier::create).verifyComplete();

		AggregationUpdate update = AggregationUpdate.update().set("value").toValue("changed");
		template.update(Versioned.class).matching(Query.query(Criteria.where("id").is(source.id + " no match"))).apply(update).first()
				.then().as(StepVerifier::create).verifyComplete();

		Flux.from(collection(Versioned.class).find(new org.bson.Document("_id", source.id)).limit(1)).collectList()
				.as(StepVerifier::create).consumeNextWith(it -> {
					assertThat(it).containsExactly(
							new org.bson.Document("_id", source.id).append("version", 1L).append("value", "changed").append("_class",
									"org.springframework.data.mongodb.core.ReactiveMongoTemplateUpdateTests$Versioned"));
				}).verifyComplete();
	}

It will throw the exception. The unit test above is not a valid one. Purpose of this test was just to reproduce the behavior that I wasn't expected.

The failure result is the following :

ReactiveMongoTemplateUpdateTests.versionedAggregateUpdateWithSet expectation "expectComplete" failed (expected: onComplete(); actual: onError(java.lang.IllegalArgumentException: Name must not be null))

Best regards,

tiboun avatar Jun 27 '22 21:06 tiboun