Skip to content

AbstractConfigurableMongoDbMessageStore's getNextId might overflow to long leading to "java.lang.Long cannot be cast to java.lang.Integer" #3336

@juanavelez

Description

@juanavelez

In what version(s) of Spring Integration are you seeing this issue?

It happens from version 4.3.12.RELEASE up to current. But it is possible that it happens with prior/future versions as well.

Describe the bug

Because getNextId performs an "increment" (by 1) on the "sequence" field of the special "messagesSequence" document, after Integer.MAX_VALUE calls to getNextId, next value will overflow from Integer.MAX_VALUE to a Long and when trying to retrieve it, will get fail with:

Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer

	/**
	 * Perform MongoDB {@code INC} operation for the document, which contains the {@link MessageDocument}
	 * {@code sequence}, and return the new incremented value for the new {@link MessageDocument}.
	 * The {@link #SEQUENCE_NAME} document is created on demand.
	 * @return the next sequence value.
	 */
	protected int getNextId() {
		Query query = Query.query(Criteria.where("_id").is(SEQUENCE_NAME));
		query.fields().include(MessageDocumentFields.SEQUENCE);
		return (Integer) this.mongoTemplate.findAndModify(query,
				new Update().inc(MessageDocumentFields.SEQUENCE, 1),
				FindAndModifyOptions.options().returnNew(true).upsert(true),
				Map.class, this.collectionName)
				.get(MessageDocumentFields.SEQUENCE);
	}

To Reproduce

Add Integer.MAX_VALUE + 1 of messages in aggregation store.

Caused by: java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer
	at org.springframework.integration.mongodb.store.AbstractConfigurableMongoDbMessageStore.getNextId(AbstractConfigurableMongoDbMessageStore.java:180)
	at org.springframework.integration.mongodb.store.ConfigurableMongoDbMessageStore.addMessagesToGroup(ConfigurableMongoDbMessageStore.java:196)
	at org.springframework.integration.mongodb.store.ConfigurableMongoDbMessageStore.addMessageToGroup(ConfigurableMongoDbMessageStore.java:167)
	at org.springframework.integration.aggregator.AbstractCorrelatingMessageHandler.store(AbstractCorrelatingMessageHandler.java:621)
	at org.springframework.integration.aggregator.AbstractCorrelatingMessageHandler.handleMessageInternal(AbstractCorrelatingMessageHandler.java:413)
	at org.springframework.integration.handler.AbstractMessageHandler.handleMessage(AbstractMessageHandler.java:127)

Expected behavior

Well, getNextId returns an int which populates the MessageDocument's sequence which is an int, so most likely, the MessageDocument's sequence's type needs to be changed from int to long and then getNextId, needs to return a long.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions