Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

import org.apache.commons.logging.Log;
Expand Down Expand Up @@ -50,6 +51,8 @@ class HeaderEnricher implements Function<Object, Object> {

private final SpelExpressionParser spelParser = new SpelExpressionParser();

private final Map<String, Expression> expressionCache = new ConcurrentHashMap<>();

private final StandardEvaluationContext evalContext = new StandardEvaluationContext();

@SuppressWarnings("unchecked")
Expand All @@ -65,25 +68,29 @@ class HeaderEnricher implements Function<Object, Object> {
@Override
public Object apply(Object input) {
if (input instanceof Message<?>) {
MessageBuilder<?> messageBuilder = MessageBuilder.fromMessage((Message<?>) input);
Map<String, String> mappings = this.headerExpressions.get("0");
for (Entry<String, String> keyValueExpressionEntry : mappings.entrySet()) {
Expression expression = this.spelParser.parseExpression(keyValueExpressionEntry.getValue());
try {
Object value = expression.getValue(this.evalContext, input, Object.class);
messageBuilder.setHeader(keyValueExpressionEntry.getKey(), value);
}
catch (Exception e) {
String message = "Failed while evaluating expression \"" + keyValueExpressionEntry.getValue() + "\" on incoming message";
if (logger.isDebugEnabled()) {
logger.warn(message + ": " + input, e);
if (mappings != null && !mappings.isEmpty()) {
MessageBuilder<?> messageBuilder = MessageBuilder.fromMessage((Message<?>) input);
for (Entry<String, String> keyValueExpressionEntry : mappings.entrySet()) {
Expression expression = this.expressionCache.computeIfAbsent(keyValueExpressionEntry.getValue(),
this.spelParser::parseExpression);
try {
Object value = expression.getValue(this.evalContext, input, Object.class);
messageBuilder.setHeader(keyValueExpressionEntry.getKey(), value);
}
else {
logger.warn(message);
catch (Exception e) {
String message = "Failed while evaluating expression \"" + keyValueExpressionEntry.getValue()
+ "\" on incoming message";
if (logger.isDebugEnabled()) {
logger.warn(message, e);
}
else {
logger.warn(message);
}
}
}
input = messageBuilder.build();
}
input = messageBuilder.build();
}

return input;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

package org.springframework.cloud.function.context.config;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
Expand All @@ -42,6 +44,7 @@
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.messaging.Message;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
Expand All @@ -66,6 +69,8 @@ public class RoutingFunction implements Function<Object, Object> {
*/
public static final String DEFAULT_ROUTE_HANDLER = "defaultMessageRoutingHandler";

private static final int EXPRESSION_CACHE_MAX_SIZE = 256;

private static final Log logger = LogFactory.getLog(RoutingFunction.class);

private final StandardEvaluationContext evalContext = new StandardEvaluationContext();
Expand All @@ -75,6 +80,14 @@ public class RoutingFunction implements Function<Object, Object> {

private final SpelExpressionParser spelParser = new SpelExpressionParser();

private final Map<String, Expression> expressionCache = Collections.synchronizedMap(
new LinkedHashMap<>(16, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<String, Expression> eldest) {
return size() > EXPRESSION_CACHE_MAX_SIZE;
}
});

private final FunctionCatalog functionCatalog;

private final FunctionProperties functionProperties;
Expand Down Expand Up @@ -151,7 +164,9 @@ else if (StringUtils.hasText(functionProperties.getDefinition())) {
else {
throw new IllegalStateException("Failed to establish route, since neither were provided: "
+ "'spring.cloud.function.definition' as Message header or as application property or "
+ "'spring.cloud.function.routing-expression' as application property. Incoming message: " + input);
+ "'spring.cloud.function.routing-expression' as application property. Incoming message payload type: "
+ ObjectUtils.nullSafeClassName(message.getPayload()) + ", headers: "
+ message.getHeaders().keySet());
}
}
}
Expand Down Expand Up @@ -242,22 +257,31 @@ private FunctionInvocationWrapper functionFromExpression(String routingExpressio
}

private FunctionInvocationWrapper functionFromExpression(String routingExpression, Object input, boolean isViaHeader) {
Expression expression = spelParser.parseExpression(routingExpression);
Expression expression = this.parseExpression(routingExpression);
if (input instanceof Message) {
input = MessageUtils.toCaseInsensitiveHeadersStructure((Message<?>) input);
}

String definition = isViaHeader ? expression.getValue(this.headerEvalContext, input, String.class) : expression.getValue(this.evalContext, input, String.class);
Assert.hasText(definition, "Failed to resolve function name based on routing expression '" + functionProperties.getRoutingExpression() + "'");
Assert.hasText(definition, "Failed to resolve function name based on routing expression '" + routingExpression + "'");
FunctionInvocationWrapper function = this.resolveFunction(definition);
Assert.notNull(function, "Failed to lookup function to route to based on the expression '"
+ functionProperties.getRoutingExpression() + "' which resolved to '" + definition + "' function definition.");
+ routingExpression + "' which resolved to '" + definition + "' function definition.");
if (logger.isDebugEnabled()) {
logger.debug("Resolved function from provided [routing-expression] " + routingExpression);
}
return function;
}

private Expression parseExpression(String routingExpression) {
Expression expression = this.expressionCache.get(routingExpression);
if (expression == null) {
expression = this.spelParser.parseExpression(routingExpression);
this.expressionCache.put(routingExpression, expression);
}
return expression;
}

private FunctionInvocationWrapper resolveFunction(String definition) {
FunctionInvocationWrapper function = functionCatalog.lookup(definition);
if (function == null) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/*
* Copyright 2026-present the original author or authors.
*
* 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
*
* https://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 org.springframework.cloud.function.context.catalog;

import java.util.Map;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.slf4j.LoggerFactory;

import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.expression.Expression;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.test.util.ReflectionTestUtils;

import static org.assertj.core.api.Assertions.assertThat;

/**
* Unit tests for {@link HeaderEnricher}.
*
* @author Divyansh Kumar
*/
@ExtendWith(OutputCaptureExtension.class)
class HeaderEnricherTests {

@Test
void testMissingZeroIndexIsSkipped() {
HeaderEnricher enricher = new HeaderEnricher(Map.of("1", Map.of("k", "'v'")), null);
Message<String> input = MessageBuilder.withPayload("hello").build();

Object result = enricher.apply(input);

assertThat(result).isSameAs(input);
}

@SuppressWarnings("unchecked")
@Test
void testExpressionIsCachedAcrossMessages() {
HeaderEnricher enricher = new HeaderEnricher(Map.of("0", Map.of("enriched", "'ok'")), null);

Message<?> first = (Message<?>) enricher.apply(MessageBuilder.withPayload("a").build());
Map<String, Expression> cache = (Map<String, Expression>) ReflectionTestUtils.getField(enricher,
"expressionCache");
assertThat(cache).containsOnlyKeys("'ok'");
Expression firstParsed = cache.get("'ok'");

Message<?> second = (Message<?>) enricher.apply(MessageBuilder.withPayload("b").build());
assertThat(first.getHeaders().get("enriched")).isEqualTo("ok");
assertThat(second.getHeaders().get("enriched")).isEqualTo("ok");
assertThat(cache.get("'ok'")).isSameAs(firstParsed);
}

@Test
void testEvaluationFailureDoesNotLogMessageContent(CapturedOutput output) {
Logger logger = (Logger) LoggerFactory.getLogger(HeaderEnricher.class);
Level previousLevel = logger.getLevel();
logger.setLevel(Level.DEBUG);
try {
HeaderEnricher enricher = new HeaderEnricher(Map.of("0", Map.of("broken", "headers['missing'].value")),
null);
Message<String> input = MessageBuilder.withPayload("secret-body")
.setHeader("Authorization", "Bearer top-secret")
.build();

enricher.apply(input);

assertThat(output.getOut()).contains("Failed while evaluating expression");
assertThat(output.getOut()).doesNotContain("secret-body");
assertThat(output.getOut()).doesNotContain("Bearer top-secret");
}
finally {
logger.setLevel(previousLevel);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,11 @@
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.test.util.ReflectionTestUtils;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;

/**
*
Expand Down Expand Up @@ -378,6 +381,64 @@ public void testMultipleRoutersCaseInsensitiveKeys() {
assertThat(function.apply(message)).isEqualTo("HELLO");
}

@SuppressWarnings("rawtypes")
@Test
public void testUnroutableMessageDoesNotExposePayloadOrHeaderValues() {
FunctionCatalog functionCatalog = this.configureCatalog();
Function function = functionCatalog.lookup(RoutingFunction.FUNCTION_NAME);
Message<String> message = MessageBuilder.withPayload("secret-payload")
.setHeader("Authorization", "Bearer secret-token")
.build();

assertThatIllegalStateException().isThrownBy(() -> function.apply(message))
.withMessageContaining("java.lang.String")
.withMessageContaining("Authorization")
.withMessageNotContaining("secret-payload")
.withMessageNotContaining("Bearer secret-token");
}

@SuppressWarnings("rawtypes")
@Test
public void testHeaderRoutingExpressionFailureReportsEvaluatedExpression() {
FunctionCatalog functionCatalog = this.configureCatalog();
Function function = functionCatalog.lookup(RoutingFunction.FUNCTION_NAME);

Message<String> emptyResultMessage = MessageBuilder.withPayload("hello")
.setHeader(FunctionProperties.ROUTING_EXPRESSION, "''")
.build();
assertThatIllegalArgumentException().isThrownBy(() -> function.apply(emptyResultMessage))
.withMessageContaining("''")
.withMessageNotContaining("'null'");

Message<String> unknownFunctionMessage = MessageBuilder.withPayload("hello")
.setHeader(FunctionProperties.ROUTING_EXPRESSION, "'nonExistentFn'")
.build();
assertThatIllegalArgumentException().isThrownBy(() -> function.apply(unknownFunctionMessage))
.withMessageContaining("'nonExistentFn'")
.withMessageNotContaining("'null'");
}

@SuppressWarnings("unchecked")
@Test
public void testRoutingExpressionCacheBounded() {
FunctionCatalog functionCatalog = this.configureCatalog();
RoutingFunction router = this.context.getBean(RoutingFunction.class);
assertThat(functionCatalog).isNotNull();

for (int i = 0; i < 260; i++) {
String expr = "headers['k'] == '" + i + "' ? 'uppercase' : 'uppercase'";
Message<String> message = MessageBuilder.withPayload("hello")
.setHeader("k", String.valueOf(i))
.setHeader(FunctionProperties.ROUTING_EXPRESSION, expr)
.build();
assertThat(router.apply(message)).isEqualTo("HELLO");
}

Map<String, ?> cache = (Map<String, ?>) ReflectionTestUtils.getField(router, "expressionCache");
assertThat(cache).isNotNull();
assertThat(cache).hasSize(256);
}

@EnableAutoConfiguration
@Configuration
protected static class RoutingFunctionConfiguration {
Expand Down