feat: jpa, messaging, notification, mongo, graphql 어댑터터 리펙토링
This commit is contained in:
+64
-4
@@ -6,10 +6,9 @@ import dev.caskeleton.messaging.kafka.KafkaSecurityConfigurer;
|
||||
import dev.caskeleton.messaging.kafka.KafkaTransactionProfileValidator;
|
||||
import dev.caskeleton.messaging.security.BrokerTlsPolicy;
|
||||
import dev.caskeleton.messaging.security.CredentialRuntimeRegistry;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Wires the Kafka adapter's validators and security configurer.
|
||||
@@ -22,9 +21,13 @@ import org.springframework.context.annotation.Bean;
|
||||
* <p>No producer or consumer bean is created here. Those need a broker profile the application has
|
||||
* not declared yet at this point, and a default-constructed producer would connect to {@code
|
||||
* localhost:9092} — which in a test environment usually succeeds against something.
|
||||
*
|
||||
* <p>Reached only when app.messaging.broker=kafka selected it. The @ConditionalOnClass this used to
|
||||
* carry could not select: the starter depends on messaging-kafka and messaging-rabbit, each of
|
||||
* which exposes its client library as `api`, so both conditions were true for every adopter and
|
||||
* both providers assembled.
|
||||
*/
|
||||
@AutoConfiguration(after = MessagingCoreAutoConfiguration.class)
|
||||
@ConditionalOnClass(name = "org.apache.kafka.clients.producer.Producer")
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class KafkaMessagingAutoConfiguration {
|
||||
|
||||
/**
|
||||
@@ -84,4 +87,61 @@ public class KafkaMessagingAutoConfiguration {
|
||||
CredentialRuntimeRegistry credentials, BrokerTlsPolicy tlsPolicy) {
|
||||
return new KafkaSecurityConfigurer(credentials, tlsPolicy);
|
||||
}
|
||||
|
||||
/**
|
||||
* The producer this transport publishes through (MSG-INT-003).
|
||||
*
|
||||
* <p>Built from Spring Boot's own {@code spring.kafka.bootstrap-servers} rather than from a
|
||||
* second description on {@code app.messaging.*}. One broker described twice is the defect this
|
||||
* repository has already paid for in {@code app.jpa-platform.datasource.*}, and the
|
||||
* operator-facing property for "where is Kafka" is the one they already know.
|
||||
*
|
||||
* <p>Byte-array serializers on purpose: the platform's codec registry decides the wire format,
|
||||
* and a serializer configured here would be a second encoder disagreeing with it.
|
||||
*
|
||||
* @param environment the resolved environment
|
||||
* @return the producer, closed with the context
|
||||
*/
|
||||
@Bean(destroyMethod = "close")
|
||||
@ConditionalOnMissingBean
|
||||
public org.apache.kafka.clients.producer.Producer<byte[], byte[]> messagingKafkaProducer(
|
||||
org.springframework.core.env.Environment environment) {
|
||||
String bootstrapServers = environment.getProperty("spring.kafka.bootstrap-servers", "").trim();
|
||||
if (bootstrapServers.isEmpty()) {
|
||||
throw new IllegalStateException(
|
||||
"app.messaging.broker=kafka needs spring.kafka.bootstrap-servers; a producer with no "
|
||||
+ "broker address defaults to localhost:9092 and fails at the first publish rather "
|
||||
+ "than at startup");
|
||||
}
|
||||
java.util.Map<String, Object> config = new java.util.HashMap<>();
|
||||
config.put(
|
||||
org.apache.kafka.clients.producer.ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,
|
||||
bootstrapServers);
|
||||
config.put(
|
||||
org.apache.kafka.clients.producer.ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
|
||||
org.apache.kafka.common.serialization.ByteArraySerializer.class);
|
||||
config.put(
|
||||
org.apache.kafka.clients.producer.ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
|
||||
org.apache.kafka.common.serialization.ByteArraySerializer.class);
|
||||
// Durability is not a default worth inheriting: acks=1 loses an accepted publish to a leader
|
||||
// failover, which is exactly the outcome an outbox exists to prevent.
|
||||
config.put(org.apache.kafka.clients.producer.ProducerConfig.ACKS_CONFIG, "all");
|
||||
config.put(org.apache.kafka.clients.producer.ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
|
||||
return new org.apache.kafka.clients.producer.KafkaProducer<>(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* The Kafka transport the publisher writes through.
|
||||
*
|
||||
* @param producer the configured producer
|
||||
* @return the transport
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(dev.caskeleton.messaging.transport.MessagingTransport.class)
|
||||
public dev.caskeleton.messaging.kafka.KafkaMessagingTransport messagingKafkaTransport(
|
||||
org.apache.kafka.clients.producer.Producer<byte[], byte[]> producer) {
|
||||
// Generation 1: the credential generation a rotation increments. Starting elsewhere would make
|
||||
// the first rotation look like it had already happened.
|
||||
return new dev.caskeleton.messaging.kafka.KafkaMessagingTransport("kafka", 1L, producer);
|
||||
}
|
||||
}
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package dev.caskeleton.messaging.autoconfigure;
|
||||
|
||||
import dev.caskeleton.messaging.schema.MessageContractKey;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* What this deployment publishes: message type and schema version to payload class.
|
||||
*
|
||||
* <p>A named holder rather than a bare {@code Map} bean, because {@code Map} is not a neutral
|
||||
* injection type in Spring — a {@code Map<K, V>} injection point is interpreted as "every bean of
|
||||
* type V, keyed by bean name", so a contract map registered as a bean is either ignored or turned
|
||||
* into something nobody wrote. A holder makes the intent unambiguous to the container and to a
|
||||
* reader.
|
||||
*
|
||||
* <p>Empty is the default and it is fail-closed: no message type can be encoded, and every publish
|
||||
* is refused at preparation. A codec that accepted an unregistered type would serialise whatever
|
||||
* object it was handed onto a topic that consumers compiled against a different shape will read —
|
||||
* which is a wire-compatibility break that looks like a working publish.
|
||||
*
|
||||
* @param byKey the declared contracts
|
||||
*/
|
||||
public record MessageContracts(Map<MessageContractKey, Class<?>> byKey) {
|
||||
|
||||
/** Copies the map so a later mutation cannot change what a running publisher will encode. */
|
||||
public MessageContracts {
|
||||
Objects.requireNonNull(byKey, "byKey");
|
||||
byKey = Map.copyOf(byKey);
|
||||
}
|
||||
|
||||
/** A deployment that has declared nothing, and therefore publishes nothing. */
|
||||
public static MessageContracts none() {
|
||||
return new MessageContracts(Map.of());
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -5,11 +5,11 @@ import dev.caskeleton.messaging.admin.DestructiveOperationGuard;
|
||||
import dev.caskeleton.messaging.admin.runtime.BrokerTopologyInspector;
|
||||
import dev.caskeleton.messaging.admin.runtime.CompositeTopologyValidator;
|
||||
import dev.caskeleton.messaging.admin.runtime.InMemoryAdminOperationJournal;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Wires the admin plane, and only when a deployment has explicitly asked for it.
|
||||
@@ -23,7 +23,7 @@ import org.springframework.context.annotation.Bean;
|
||||
* absent from this class. No bean for it is ever auto-configured: an operator tool that needs purge
|
||||
* or delete registers one itself, with an admin credential this runtime does not hold.
|
||||
*/
|
||||
@AutoConfiguration(after = MessagingCoreAutoConfiguration.class)
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@ConditionalOnProperty(prefix = "app.messaging.admin", name = "enabled", havingValue = "true")
|
||||
public class MessagingAdminAutoConfiguration {
|
||||
|
||||
|
||||
+140
-6
@@ -22,11 +22,11 @@ import dev.caskeleton.messaging.transport.MessagingRuntimeRegistry;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import org.springframework.beans.factory.ObjectProvider;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Wires the platform's policy, transport, and observability primitives.
|
||||
@@ -40,8 +40,8 @@ import org.springframework.context.annotation.Bean;
|
||||
* capabilities, and the Admin Plane are opt-in beans with their own credentials, so a service
|
||||
* cannot acquire them by adding the starter to its classpath.
|
||||
*/
|
||||
@AutoConfiguration
|
||||
@EnableConfigurationProperties(MessagingProperties.class)
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@EnableConfigurationProperties(MessagingSettings.class)
|
||||
public class MessagingCoreAutoConfiguration {
|
||||
|
||||
/**
|
||||
@@ -144,7 +144,7 @@ public class MessagingCoreAutoConfiguration {
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public MessagingRuntimeRegistry messagingRuntimeRegistry(MessagingProperties properties) {
|
||||
public MessagingRuntimeRegistry messagingRuntimeRegistry(MessagingSettings properties) {
|
||||
return new DefaultMessagingRuntimeRegistry(properties.getShutdown().getDrainDeadline());
|
||||
}
|
||||
|
||||
@@ -156,7 +156,7 @@ public class MessagingCoreAutoConfiguration {
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public BackpressureController backpressureController(MessagingProperties properties) {
|
||||
public BackpressureController backpressureController(MessagingSettings properties) {
|
||||
return new BackpressureController(
|
||||
properties.getBackpressure().getGlobalLimit(),
|
||||
properties.getBackpressure().getPerDestinationLimit());
|
||||
@@ -170,7 +170,7 @@ public class MessagingCoreAutoConfiguration {
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public GracefulShutdownCoordinator gracefulShutdownCoordinator(MessagingProperties properties) {
|
||||
public GracefulShutdownCoordinator gracefulShutdownCoordinator(MessagingSettings properties) {
|
||||
return new GracefulShutdownCoordinator(properties.getShutdown().getDrainDeadline());
|
||||
}
|
||||
|
||||
@@ -273,4 +273,138 @@ public class MessagingCoreAutoConfiguration {
|
||||
ValidatedDestinationRegistry registry, BackpressureController backpressure) {
|
||||
return new MessagingEndpoint(registry, backpressure);
|
||||
}
|
||||
|
||||
/**
|
||||
* The codec registry, which had no implementation anywhere (MSG-INT-003).
|
||||
*
|
||||
* <p>The message contracts come from the deployment — a {@code Map} of message type and schema
|
||||
* version to payload class — and default to <b>empty</b>, which means no message type can be
|
||||
* encoded and every publish is refused at preparation. That is fail-closed on purpose: a codec
|
||||
* that accepted an unregistered type would serialise whatever object it was handed and put bytes
|
||||
* on a topic that consumers compiled against a different shape will read.
|
||||
*
|
||||
* @param contracts the declared message contracts, if the deployment registered any
|
||||
* @return the registry, defaulting to JSON
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(dev.caskeleton.messaging.schema.MessageCodecRegistry.class)
|
||||
public dev.caskeleton.messaging.runtime.RegisteredMessageCodecs messagingCodecs(
|
||||
ObjectProvider<MessageContracts> contracts) {
|
||||
return dev.caskeleton.messaging.runtime.RegisteredMessageCodecs.of(
|
||||
dev.caskeleton.messaging.schema.json.JacksonMessageCodec.of(
|
||||
contracts.getIfAvailable(MessageContracts::none).byKey()));
|
||||
}
|
||||
|
||||
/**
|
||||
* The destination profiles the publisher resolves against, from the validated registry.
|
||||
*
|
||||
* @param destinations the validated registry
|
||||
* @return the profile registry
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public dev.caskeleton.messaging.runtime.DestinationProfileRegistry messagingDestinationProfiles(
|
||||
ValidatedDestinationRegistry destinations) {
|
||||
return dev.caskeleton.messaging.runtime.DestinationProfileRegistry.of(destinations.all());
|
||||
}
|
||||
|
||||
/**
|
||||
* What this deployment may publish to.
|
||||
*
|
||||
* <p>The declared destinations, and nothing else. Deny-all assembles a platform that refuses
|
||||
* every publish a correctly configured deployment makes; allow-all makes the check decoration.
|
||||
* Declaring a destination profile is already an act of configuration, so a message to one nobody
|
||||
* declared is a typo or a module reaching past its contract — which is what this check is for.
|
||||
*
|
||||
* @param destinations the validated registry
|
||||
* @return the access policy
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public dev.caskeleton.messaging.security.DestinationAccessPolicy messagingDestinationAccess(
|
||||
ValidatedDestinationRegistry destinations) {
|
||||
return dev.caskeleton.messaging.runtime.DeclaredDestinationAccess.of(destinations.all());
|
||||
}
|
||||
|
||||
/**
|
||||
* Payload and in-flight admission.
|
||||
*
|
||||
* @param properties the bound settings
|
||||
* @return the admission controller
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public dev.caskeleton.messaging.policy.MessagingAdmissionController messagingAdmission(
|
||||
MessagingSettings properties) {
|
||||
return new dev.caskeleton.messaging.policy.MessagingAdmissionController(
|
||||
new dev.caskeleton.messaging.policy.PayloadLimitGuard(
|
||||
new dev.caskeleton.messaging.policy.PayloadPolicy(
|
||||
dev.caskeleton.messaging.schema.json.JacksonMessageCodec.DEFAULT_MAX_BYTES,
|
||||
dev.caskeleton.messaging.schema.json.JacksonMessageCodec.DEFAULT_MAX_BYTES / 2)),
|
||||
new dev.caskeleton.messaging.policy.InFlightLimiter(
|
||||
properties.getBackpressure().getPerDestinationLimit(),
|
||||
java.time.Duration.ofSeconds(5)));
|
||||
}
|
||||
|
||||
/**
|
||||
* The publisher this configuration has been consuming since it was written (MSG-INT-003).
|
||||
*
|
||||
* <p>{@code deadLetterOrchestrator}, {@code blockingMessagePublisher}, {@code
|
||||
* reactiveMessagePublisher} and {@code batchMessagePublisher} all take a {@link
|
||||
* MessagePublisher}, and no configuration produced one. A selected transport therefore could not
|
||||
* assemble: the platform failed on a missing bean rather than publishing anywhere. {@code
|
||||
* DefaultMessagePublisher} existed in {@code messaging-runtime-core} the whole time; the starter
|
||||
* did not depend on that leaf.
|
||||
*
|
||||
* @param destinations the destination profiles
|
||||
* @param access what may be published to
|
||||
* @param codecs the codec registry
|
||||
* @param admission payload and in-flight admission
|
||||
* @param runtimes the runtime registry
|
||||
* @param transport the selected transport
|
||||
* @return the publisher
|
||||
*/
|
||||
@Bean
|
||||
@ConditionalOnMissingBean(MessagePublisher.class)
|
||||
public MessagePublisher messagingPublisher(
|
||||
dev.caskeleton.messaging.runtime.DestinationProfileRegistry destinations,
|
||||
dev.caskeleton.messaging.security.DestinationAccessPolicy access,
|
||||
dev.caskeleton.messaging.schema.MessageCodecRegistry codecs,
|
||||
dev.caskeleton.messaging.policy.MessagingAdmissionController admission,
|
||||
MessagingRuntimeRegistry runtimes,
|
||||
dev.caskeleton.messaging.transport.MessagingTransport transport) {
|
||||
return new dev.caskeleton.messaging.runtime.DefaultMessagePublisher(
|
||||
destinations, access, codecs, admission, runtimes, transport);
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs the selected transport into the runtime registry (MSG-INT-003).
|
||||
*
|
||||
* <p>The registry was constructed empty and nothing ever installed anything, so every publish
|
||||
* failed at {@code PUBLISH_RUNTIME_UNAVAILABLE} — after resolving the destination, checking
|
||||
* access and encoding the payload, which is as far as a message could get. The same "registry
|
||||
* built empty" shape the notification provider registry had.
|
||||
*
|
||||
* @param runtimes the registry
|
||||
* @param transport the selected transport
|
||||
* @return the startup installation
|
||||
*/
|
||||
@Bean
|
||||
public org.springframework.beans.factory.InitializingBean messagingRuntimeInstallation(
|
||||
MessagingRuntimeRegistry runtimes,
|
||||
ObjectProvider<dev.caskeleton.messaging.transport.MessagingTransport> transport) {
|
||||
return () -> {
|
||||
dev.caskeleton.messaging.transport.MessagingTransport selected = transport.getIfAvailable();
|
||||
if (selected == null) {
|
||||
// Not a silent skip of a check: MessagingProviderSelection is what guarantees a transport
|
||||
// when a broker is selected, and it refuses startup by name when one is not. This
|
||||
// configuration is also loadable on its own — an adopter composing the policy primitives
|
||||
// without a transport — and demanding one here would refuse that.
|
||||
return;
|
||||
}
|
||||
runtimes.install(
|
||||
new dev.caskeleton.messaging.runtime.TransportMessagingRuntime(
|
||||
selected.brokerName(), 1L, selected));
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package dev.caskeleton.messaging.autoconfigure;
|
||||
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
/**
|
||||
* The one place that decides whether this application has messaging (MSG-INT-004).
|
||||
*
|
||||
* <p>The starter registered five auto-configurations directly, and not one carried a messaging
|
||||
* master condition — putting the starter on the classpath assembled the platform. That is the same
|
||||
* shape the other four adapters had, and the same fix: one root owning the condition, importing
|
||||
* children that carry none, so a bean added to any child next month is gated without anyone
|
||||
* remembering to repeat a condition.
|
||||
*
|
||||
* <p><b>Provider selection is a property, not a classpath accident.</b> Kafka and Rabbit were each
|
||||
* conditioned on their client class being present, so an application that happened to have both
|
||||
* libraries — a transitive dependency is enough — assembled both providers and published through
|
||||
* whichever bean won. Selection now reads {@code app.messaging.broker} against a closed registry,
|
||||
* and a value outside it is a startup error rather than a context with no provider at all.
|
||||
*
|
||||
* <p>{@code app.messaging.enabled=false} means no beans, no clients, no threads, and no bound
|
||||
* detail namespace. {@code MessagingStarterOffContractTest} holds that against a full context
|
||||
* including this starter's imports and the vendor auto-configurations Spring Boot would contribute.
|
||||
*/
|
||||
@AutoConfiguration
|
||||
@ConditionalOnProperty(prefix = MessagingSettings.PREFIX, name = "enabled", havingValue = "true")
|
||||
@EnableConfigurationProperties(MessagingSettings.class)
|
||||
@Import({
|
||||
MessagingCoreAutoConfiguration.class,
|
||||
MessagingProviderSelection.class,
|
||||
MessagingReliabilityAutoConfiguration.class,
|
||||
MessagingAdminAutoConfiguration.class
|
||||
})
|
||||
public class MessagingPlatformRootAutoConfiguration {}
|
||||
+4
-4
@@ -42,11 +42,11 @@ public final class MessagingPrefixMigrationValidator implements InitializingBean
|
||||
* @throws MessagingConfigurationException naming the offending keys and the prefix to use
|
||||
*/
|
||||
public void validate() {
|
||||
List<String> superseded = keysUnder(MessagingProperties.SUPERSEDED_PREFIX + '.');
|
||||
List<String> documented = keysUnder(MessagingProperties.DOCUMENTED_PREFIX + '.');
|
||||
List<String> superseded = keysUnder(MessagingSettings.SUPERSEDED_PREFIX + '.');
|
||||
List<String> documented = keysUnder(MessagingSettings.DOCUMENTED_PREFIX + '.');
|
||||
// The documented bare prefix overlaps nothing else only because app.messaging is longer; a key
|
||||
// such as `messaging.destinations` is caught here while `app.messaging.destinations` is not.
|
||||
documented.removeIf(key -> key.startsWith(MessagingProperties.PREFIX + '.'));
|
||||
documented.removeIf(key -> key.startsWith(MessagingSettings.PREFIX + '.'));
|
||||
|
||||
List<String> offending = new ArrayList<>(superseded);
|
||||
offending.addAll(documented);
|
||||
@@ -59,7 +59,7 @@ public final class MessagingPrefixMigrationValidator implements InitializingBean
|
||||
+ String.join(", ", offending.stream().sorted().limit(10).toList())
|
||||
+ (offending.size() > 10 ? " (and " + (offending.size() - 10) + " more)" : "")
|
||||
+ "; move them under '"
|
||||
+ MessagingProperties.PREFIX
|
||||
+ MessagingSettings.PREFIX
|
||||
+ "', which is the prefix the runtime and the APP_MESSAGING_* variables already use."
|
||||
+ " Accepting both would let one deployment configure half the platform under each");
|
||||
}
|
||||
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
package dev.caskeleton.messaging.autoconfigure;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.springframework.context.EnvironmentAware;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.context.annotation.ImportSelector;
|
||||
import org.springframework.core.env.Environment;
|
||||
import org.springframework.core.type.AnnotationMetadata;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
/**
|
||||
* Selects exactly one transport, from a closed registry, by name (MSG-INT-004).
|
||||
*
|
||||
* <p>Selection used to be {@code @ConditionalOnClass}: Kafka assembled because a Kafka class was on
|
||||
* the classpath and Rabbit because a Rabbit class was, so an application with both libraries — one
|
||||
* transitive dependency is enough — assembled both and published through whichever bean won a
|
||||
* {@code @ConditionalOnMissingBean} race. Nothing failed; the message simply went somewhere nobody
|
||||
* chose.
|
||||
*
|
||||
* <p>Three outcomes are startup errors now rather than silences:
|
||||
*
|
||||
* <ul>
|
||||
* <li>a broker id outside the registry — the operator set something the platform cannot honour;
|
||||
* <li>a registered broker whose client library is absent — a deployment that asked for Kafka and
|
||||
* shipped without it is told so, instead of starting with no publisher at all;
|
||||
* <li>a blank broker while messaging is on — the master switch says yes and nothing says what to.
|
||||
* </ul>
|
||||
*
|
||||
* <p>The provider configurations carry no condition of their own any more. Each is reached only
|
||||
* along the path this class chose, which is what makes "which transport is active" answerable by
|
||||
* reading one property rather than by resolving a dependency graph.
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
@Import(MessagingProviderSelection.Selector.class)
|
||||
public class MessagingProviderSelection {
|
||||
|
||||
/** Broker id to the client class that must be present for it to be honoured. */
|
||||
static final Map<String, String> REGISTERED_BROKERS =
|
||||
Map.of(
|
||||
"kafka", "org.apache.kafka.clients.producer.Producer",
|
||||
"rabbit", "com.rabbitmq.client.Channel");
|
||||
|
||||
/** Broker id to the configuration that assembles it. */
|
||||
static final Map<String, Class<?>> PROVIDER_CONFIGURATIONS =
|
||||
Map.of(
|
||||
"kafka", KafkaMessagingAutoConfiguration.class,
|
||||
"rabbit", RabbitMessagingAutoConfiguration.class);
|
||||
|
||||
/** The registered broker ids, so a message can tell an operator what is available. */
|
||||
public static List<String> registeredBrokerIds() {
|
||||
return REGISTERED_BROKERS.keySet().stream().sorted().toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the selection, or throws naming the property and the values it accepts.
|
||||
*
|
||||
* @param environment the resolved environment
|
||||
* @return the selected broker id
|
||||
*/
|
||||
public static String selectedBroker(Environment environment) {
|
||||
String broker = environment.getProperty(MessagingSettings.PREFIX + ".broker", "").trim();
|
||||
if (broker.isEmpty()) {
|
||||
throw new IllegalStateException(
|
||||
MessagingSettings.PREFIX
|
||||
+ ".enabled=true needs a transport; set "
|
||||
+ MessagingSettings.PREFIX
|
||||
+ ".broker to one of "
|
||||
+ registeredBrokerIds());
|
||||
}
|
||||
String clientClass = REGISTERED_BROKERS.get(broker);
|
||||
if (clientClass == null) {
|
||||
throw new IllegalStateException(
|
||||
MessagingSettings.PREFIX
|
||||
+ ".broker="
|
||||
+ broker
|
||||
+ " is not a registered transport; registered: "
|
||||
+ registeredBrokerIds());
|
||||
}
|
||||
if (!ClassUtils.isPresent(clientClass, MessagingProviderSelection.class.getClassLoader())) {
|
||||
throw new IllegalStateException(
|
||||
MessagingSettings.PREFIX
|
||||
+ ".broker="
|
||||
+ broker
|
||||
+ " needs "
|
||||
+ clientClass
|
||||
+ " on the classpath; the deployment selected a transport it did not ship");
|
||||
}
|
||||
return broker;
|
||||
}
|
||||
|
||||
/** Imports the one configuration the selected broker names. */
|
||||
static final class Selector implements ImportSelector, EnvironmentAware {
|
||||
|
||||
private Environment environment;
|
||||
|
||||
@Override
|
||||
public void setEnvironment(Environment environment) {
|
||||
this.environment = environment;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
|
||||
return new String[] {PROVIDER_CONFIGURATIONS.get(selectedBroker(environment)).getName()};
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -11,10 +11,10 @@ import dev.caskeleton.messaging.reliability.InboxRepository;
|
||||
import dev.caskeleton.messaging.reliability.OutboxRepository;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Wires the outbox and inbox operational beans.
|
||||
@@ -29,7 +29,7 @@ import org.springframework.context.annotation.Bean;
|
||||
* application's decision: a service running several replicas usually wants one of them to run
|
||||
* cleanup, and auto-registering a fixed-rate task would have every replica delete the same rows.
|
||||
*/
|
||||
@AutoConfiguration(after = MessagingCoreAutoConfiguration.class)
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class MessagingReliabilityAutoConfiguration {
|
||||
|
||||
/**
|
||||
|
||||
+2
-2
@@ -23,8 +23,8 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
* applies to the Spring Cloud Stream bridge, which bypasses the platform's retry and dead letter
|
||||
* policy by design.
|
||||
*/
|
||||
@ConfigurationProperties(prefix = MessagingProperties.PREFIX)
|
||||
public class MessagingProperties {
|
||||
@ConfigurationProperties(prefix = MessagingSettings.PREFIX)
|
||||
public class MessagingSettings {
|
||||
|
||||
/** The one configuration prefix this platform binds. */
|
||||
public static final String PREFIX = "app.messaging";
|
||||
+5
-4
@@ -5,10 +5,9 @@ import dev.caskeleton.messaging.rabbit.RabbitPublishFailureClassifier;
|
||||
import dev.caskeleton.messaging.rabbit.RabbitSecurityConfigurer;
|
||||
import dev.caskeleton.messaging.security.BrokerTlsPolicy;
|
||||
import dev.caskeleton.messaging.security.CredentialRuntimeRegistry;
|
||||
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* Wires the RabbitMQ adapter's validators and security configurer.
|
||||
@@ -19,9 +18,11 @@ import org.springframework.context.annotation.Bean;
|
||||
* <p>No connection or channel bean is created here. A channel opened before the application has
|
||||
* declared its security profile would connect with whatever defaults the client carries, which for
|
||||
* RabbitMQ means {@code guest/guest} against localhost.
|
||||
*
|
||||
* <p>Reached only when app.messaging.broker=rabbit selected it; see MessagingProviderSelection for
|
||||
* why a classpath condition could not make this choice.
|
||||
*/
|
||||
@AutoConfiguration(after = MessagingCoreAutoConfiguration.class)
|
||||
@ConditionalOnClass(name = "com.rabbitmq.client.Channel")
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class RabbitMessagingAutoConfiguration {
|
||||
|
||||
/**
|
||||
|
||||
+1
-5
@@ -1,5 +1 @@
|
||||
dev.caskeleton.messaging.autoconfigure.MessagingCoreAutoConfiguration
|
||||
dev.caskeleton.messaging.autoconfigure.KafkaMessagingAutoConfiguration
|
||||
dev.caskeleton.messaging.autoconfigure.RabbitMessagingAutoConfiguration
|
||||
dev.caskeleton.messaging.autoconfigure.MessagingReliabilityAutoConfiguration
|
||||
dev.caskeleton.messaging.autoconfigure.MessagingAdminAutoConfiguration
|
||||
dev.caskeleton.messaging.autoconfigure.MessagingPlatformRootAutoConfiguration
|
||||
|
||||
+2
-2
@@ -59,7 +59,7 @@ class MessagingAutoConfigurationTest {
|
||||
void experimentalAdaptersAndTheBridgeAreOffByDefault() {
|
||||
runner.run(
|
||||
context -> {
|
||||
MessagingProperties properties = context.getBean(MessagingProperties.class);
|
||||
MessagingSettings properties = context.getBean(MessagingSettings.class);
|
||||
assertThat(properties.getExperimental().isKafkaShare()).isFalse();
|
||||
assertThat(properties.getExperimental().isPulsar()).isFalse();
|
||||
assertThat(properties.getExperimental().isNats()).isFalse();
|
||||
@@ -77,7 +77,7 @@ class MessagingAutoConfigurationTest {
|
||||
"app.messaging.shutdown.drain-deadline=15s")
|
||||
.run(
|
||||
context -> {
|
||||
MessagingProperties properties = context.getBean(MessagingProperties.class);
|
||||
MessagingSettings properties = context.getBean(MessagingSettings.class);
|
||||
assertThat(properties.getExperimental().isPulsar()).isTrue();
|
||||
assertThat(properties.getBackpressure().getGlobalLimit()).isEqualTo(64);
|
||||
assertThat(properties.getShutdown().getDrainDeadline())
|
||||
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
package dev.caskeleton.messaging.autoconfigure;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.messaging.api.ContentType;
|
||||
import dev.caskeleton.messaging.api.MessageEnvelope;
|
||||
import dev.caskeleton.messaging.api.MessageId;
|
||||
import dev.caskeleton.messaging.api.MessageType;
|
||||
import dev.caskeleton.messaging.api.ProducerId;
|
||||
import dev.caskeleton.messaging.api.SchemaVersion;
|
||||
import dev.caskeleton.messaging.api.destination.DestinationName;
|
||||
import dev.caskeleton.messaging.api.destination.MessageDestination;
|
||||
import dev.caskeleton.messaging.api.publish.MessagePublisher;
|
||||
import dev.caskeleton.messaging.api.publish.PublishCompletion;
|
||||
import dev.caskeleton.messaging.api.publish.PublishOptions;
|
||||
import dev.caskeleton.messaging.api.publish.PublishResult;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Properties;
|
||||
import org.apache.kafka.clients.consumer.ConsumerConfig;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecord;
|
||||
import org.apache.kafka.clients.consumer.ConsumerRecords;
|
||||
import org.apache.kafka.clients.consumer.KafkaConsumer;
|
||||
import org.apache.kafka.common.serialization.ByteArrayDeserializer;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.condition.EnabledIf;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigurations;
|
||||
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
|
||||
import org.testcontainers.DockerClientFactory;
|
||||
import org.testcontainers.junit.jupiter.Container;
|
||||
import org.testcontainers.junit.jupiter.Testcontainers;
|
||||
import org.testcontainers.kafka.KafkaContainer;
|
||||
|
||||
/**
|
||||
* A message published through the assembled platform arrives on a real broker (MSG-INT-003).
|
||||
*
|
||||
* <p>Every messaging signal in this repository came from a fixture. The legacy adapter's {@code
|
||||
* KafkaSender} existed only as a test double; the platform's publisher could not be assembled at
|
||||
* all, because the starter did not depend on the leaf holding it and the codec registry it needs
|
||||
* had no implementation. "Messaging works" was a statement about hand-rolled fakes.
|
||||
*
|
||||
* <p>So this test asserts the one thing a fake cannot: that bytes leave the process, reach a broker
|
||||
* the platform configured itself, and can be read back by a consumer that shares nothing with the
|
||||
* producing code but the topic name.
|
||||
*
|
||||
* <p><b>Membership rule.</b> The wave's contract is that the starter earns {@code app-bootstrap}
|
||||
* runtime membership in the same change unit that turns this green. That is why this lives here
|
||||
* rather than in the composition root: the qualification has to exist and pass before anything is
|
||||
* put on a deployment's classpath, not after.
|
||||
*/
|
||||
@Testcontainers
|
||||
@EnabledIf(value = "dockerAvailable", disabledReason = "Docker not available for the live broker")
|
||||
class MessagingLiveRoundTripQualificationTest {
|
||||
|
||||
private static final DestinationName ORDERS = new DestinationName("order-events");
|
||||
private static final String TOPIC = "order-events";
|
||||
private static final DestinationName DLQ = new DestinationName("order-events-dlq");
|
||||
|
||||
@Container static final KafkaContainer KAFKA = new KafkaContainer("apache/kafka:3.8.0");
|
||||
|
||||
static boolean dockerAvailable() {
|
||||
return DockerClientFactory.instance().isDockerAvailable();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a publish through the assembled platform is readable from the broker")
|
||||
void aPublishReachesTheBroker() {
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(MessagingPlatformRootAutoConfiguration.class))
|
||||
.withPropertyValues(
|
||||
"app.messaging.enabled=true",
|
||||
"app.messaging.broker=kafka",
|
||||
"spring.kafka.bootstrap-servers=" + KAFKA.getBootstrapServers())
|
||||
// Both, because ValidatedDestinationRegistry refuses a profile whose dead-letter target is
|
||||
// not itself registered — a good invariant, and one a fixture declaring only the happy path
|
||||
// walks straight into.
|
||||
// The contract the codec encodes against. Empty is fail-closed by design — a codec that
|
||||
// accepted an unregistered type would put bytes on a topic consumers read with a different
|
||||
// shape — so a deployment that publishes must declare what it publishes.
|
||||
.withBean(
|
||||
MessageContracts.class,
|
||||
() ->
|
||||
new MessageContracts(
|
||||
java.util.Map.of(
|
||||
new dev.caskeleton.messaging.schema.MessageContractKey(
|
||||
new MessageType("order.created"), new SchemaVersion(1)),
|
||||
String.class)))
|
||||
.withBean(
|
||||
"ordersProfile",
|
||||
dev.caskeleton.messaging.policy.DestinationProfile.class,
|
||||
() -> profile(ORDERS, DLQ))
|
||||
// The dead-letter destination has none of its own: the registry refuses a self-reference,
|
||||
// and a chain of dead letters is a queue nobody drains.
|
||||
.withBean(
|
||||
"ordersDlqProfile",
|
||||
dev.caskeleton.messaging.policy.DestinationProfile.class,
|
||||
() -> profile(DLQ, null))
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context)
|
||||
.as(
|
||||
"the platform must assemble before it can publish; MSG-INT-003 was that it could not")
|
||||
.hasNotFailed();
|
||||
|
||||
PublishResult result =
|
||||
context
|
||||
.getBean(MessagePublisher.class)
|
||||
.publish(
|
||||
new MessageDestination<>(
|
||||
ORDERS, new MessageType("order.created"), String.class),
|
||||
envelope(),
|
||||
PublishOptions.defaults())
|
||||
.toCompletableFuture()
|
||||
.join();
|
||||
|
||||
assertThat(result.completion())
|
||||
.as(
|
||||
"CONFIRMED means the broker acknowledged it, not that the call returned. "
|
||||
+ "Getting here took four separate absences: the starter's dependency on "
|
||||
+ "messaging-runtime-core, the codec registry, the declared message "
|
||||
+ "contract, and a MessagingRuntime to install — each of which stopped a "
|
||||
+ "publish at a different stage, and none of which any fake would have hit.")
|
||||
.isEqualTo(PublishCompletion.CONFIRMED);
|
||||
assertThat(result.evidence().brokerAccepted())
|
||||
.as("the evidence a fixture cannot produce")
|
||||
.isTrue();
|
||||
|
||||
assertThat(readBack())
|
||||
.as(
|
||||
"the assertion a fake cannot make: bytes left the process and a consumer that "
|
||||
+ "shares nothing with the producing code but the topic name read them")
|
||||
.isNotEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
/** Reads whatever reached the topic, with a bound rather than a poll loop that can hang. */
|
||||
private static List<ConsumerRecord<byte[], byte[]>> readBack() {
|
||||
Properties config = new Properties();
|
||||
config.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, KAFKA.getBootstrapServers());
|
||||
config.put(ConsumerConfig.GROUP_ID_CONFIG, "round-trip-qualification");
|
||||
config.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
|
||||
config.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class);
|
||||
config.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class);
|
||||
|
||||
try (KafkaConsumer<byte[], byte[]> consumer = new KafkaConsumer<>(config)) {
|
||||
consumer.subscribe(List.of(TOPIC));
|
||||
Instant deadline = Instant.now().plusSeconds(30);
|
||||
while (Instant.now().isBefore(deadline)) {
|
||||
ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofSeconds(1));
|
||||
if (!records.isEmpty()) {
|
||||
return List.of(records.records(TOPIC).iterator().next());
|
||||
}
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The destination the platform resolves and the topic it physically writes to.
|
||||
*
|
||||
* <p>The physical topic is what the consumer below subscribes to, and they are deliberately the
|
||||
* same constant: a round trip that read a different topic from the one the transport wrote would
|
||||
* pass or fail for reasons unrelated to the platform.
|
||||
*/
|
||||
private static dev.caskeleton.messaging.policy.DestinationProfile profile(
|
||||
DestinationName name, DestinationName deadLetter) {
|
||||
return new dev.caskeleton.messaging.policy.DestinationProfile(
|
||||
name,
|
||||
"kafka",
|
||||
dev.caskeleton.messaging.api.destination.DestinationKind.EVENT_STREAM,
|
||||
dev.caskeleton.messaging.policy.PhysicalDestination.kafkaTopic(name.value()),
|
||||
new dev.caskeleton.messaging.policy.SchemaPolicy(
|
||||
ContentType.JSON,
|
||||
dev.caskeleton.messaging.schema.SchemaCompatibility.BACKWARD_TRANSITIVE,
|
||||
java.util.Set.of(new MessageType("order.created"))),
|
||||
dev.caskeleton.messaging.api.delivery.DeliveryGuarantee.AT_LEAST_ONCE,
|
||||
dev.caskeleton.messaging.api.delivery.OrderingScope.NONE,
|
||||
dev.caskeleton.messaging.api.delivery.ExternalSideEffectGuarantee.IDEMPOTENCY_REQUIRED,
|
||||
dev.caskeleton.messaging.policy.ProducerPolicy.defaults(),
|
||||
dev.caskeleton.messaging.policy.ConsumerPolicy.defaults("round-trip"),
|
||||
dev.caskeleton.messaging.policy.RetryPolicy.none(),
|
||||
deadLetter == null
|
||||
? dev.caskeleton.messaging.policy.DeadLetterPolicy.disabled()
|
||||
: dev.caskeleton.messaging.policy.DeadLetterPolicy.to(deadLetter),
|
||||
dev.caskeleton.messaging.policy.PayloadPolicy.defaults(),
|
||||
dev.caskeleton.messaging.policy.CapabilityTier.M1,
|
||||
false,
|
||||
false,
|
||||
false);
|
||||
}
|
||||
|
||||
private static MessageEnvelope<String> envelope() {
|
||||
return new MessageEnvelope<>(
|
||||
MessageId.newId(),
|
||||
new MessageType("order.created"),
|
||||
new SchemaVersion(1),
|
||||
Instant.parse("2026-08-14T00:00:00Z"),
|
||||
Optional.empty(),
|
||||
new ProducerId("orders"),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
ContentType.JSON,
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
Optional.empty(),
|
||||
dev.caskeleton.messaging.api.TraceContext.none(),
|
||||
dev.caskeleton.messaging.api.header.MessageHeaders.empty(),
|
||||
"{\"orderId\":\"o-1\"}");
|
||||
}
|
||||
}
|
||||
+231
@@ -0,0 +1,231 @@
|
||||
package dev.caskeleton.messaging.autoconfigure;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.messaging.api.MessageEnvelope;
|
||||
import dev.caskeleton.messaging.api.destination.MessageDestination;
|
||||
import dev.caskeleton.messaging.api.publish.MessagePublisher;
|
||||
import dev.caskeleton.messaging.api.publish.PublishOptions;
|
||||
import dev.caskeleton.messaging.api.publish.PublishResult;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.CompletionStage;
|
||||
import java.util.stream.Collectors;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigurations;
|
||||
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
|
||||
import org.springframework.util.ClassUtils;
|
||||
|
||||
/**
|
||||
* Off means nothing, and on means exactly one transport (MSG-INT-004).
|
||||
*
|
||||
* <p>The starter registered five auto-configurations and none carried a messaging master condition,
|
||||
* so an application acquired the platform by having the starter on its classpath. Worse, provider
|
||||
* selection was {@code @ConditionalOnClass} while this starter depends on {@code messaging-kafka}
|
||||
* and {@code messaging-rabbit}, each of which exposes its client library as {@code api} — so both
|
||||
* conditions are true for **every** adopter, always. Selection by classpath could not select; it
|
||||
* assembled both and let a {@code @ConditionalOnMissingBean} race decide where messages went.
|
||||
*
|
||||
* <p>The cases below are the replacement contract. The off case is deliberately checked on bean
|
||||
* names and live threads rather than on a handful of types: a platform that leaves a scheduler
|
||||
* running is not off, whatever its bean inventory says.
|
||||
*/
|
||||
class MessagingStarterOffContractTest {
|
||||
|
||||
private final ApplicationContextRunner runner =
|
||||
new ApplicationContextRunner()
|
||||
.withConfiguration(AutoConfigurations.of(MessagingPlatformRootAutoConfiguration.class));
|
||||
|
||||
@Test
|
||||
@DisplayName(
|
||||
"both client libraries really are on this classpath, so the old condition could not select")
|
||||
void bothClientLibrariesArePresent() {
|
||||
ClassLoader loader = getClass().getClassLoader();
|
||||
|
||||
assertThat(ClassUtils.isPresent("org.apache.kafka.clients.producer.Producer", loader))
|
||||
.as("messaging-kafka exposes kafka-clients as api")
|
||||
.isTrue();
|
||||
assertThat(ClassUtils.isPresent("com.rabbitmq.client.Channel", loader))
|
||||
.as("messaging-rabbit exposes spring-rabbit as api")
|
||||
.isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("with the switch off there are no platform beans")
|
||||
void offMeansNoBeans() {
|
||||
runner.run(
|
||||
context -> {
|
||||
assertThat(context).hasNotFailed();
|
||||
|
||||
Set<String> platformBeans =
|
||||
java.util.Arrays.stream(context.getBeanDefinitionNames())
|
||||
.filter(
|
||||
name -> {
|
||||
Class<?> type = context.getBeanFactory().getType(name, false);
|
||||
return type != null
|
||||
&& type.getName().startsWith("dev.caskeleton.messaging.");
|
||||
})
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
assertThat(platformBeans)
|
||||
.as("off is a structural fact, not a set of individually-conditioned beans")
|
||||
.isEmpty();
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("with the switch off no thread is started")
|
||||
void offMeansNoThreads() {
|
||||
Set<String> before = liveThreadNames();
|
||||
|
||||
runner.run(context -> assertThat(context).hasNotFailed());
|
||||
|
||||
assertThat(newMessagingThreadsSince(before))
|
||||
.as("a bean that exists but was never started is acceptable; a running thread is not")
|
||||
.isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("on with no broker names the property")
|
||||
void onWithoutABrokerNamesTheProperty() {
|
||||
runner
|
||||
.withPropertyValues("app.messaging.enabled=true")
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context)
|
||||
.hasFailed()
|
||||
.getFailure()
|
||||
.rootCause()
|
||||
.hasMessageContaining("app.messaging.broker"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("an unregistered broker is refused, and the message lists what is registered")
|
||||
void anUnregisteredBrokerIsRefused() {
|
||||
runner
|
||||
.withPropertyValues("app.messaging.enabled=true", "app.messaging.broker=carrier-pigeon")
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context)
|
||||
.hasFailed()
|
||||
.getFailure()
|
||||
.rootCause()
|
||||
.hasMessageContaining("registered: [kafka, rabbit]"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("selecting Kafka assembles Kafka and not Rabbit")
|
||||
void selectingKafkaAssemblesOnlyKafka() {
|
||||
withAPublisher()
|
||||
.withPropertyValues(
|
||||
"app.messaging.enabled=true",
|
||||
"app.messaging.broker=kafka",
|
||||
"spring.kafka.bootstrap-servers=localhost:9092")
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasNotFailed();
|
||||
assertThat(context).hasSingleBean(KafkaMessagingAutoConfiguration.class);
|
||||
assertThat(context)
|
||||
.as("both client libraries are present, so only the property can be selecting")
|
||||
.doesNotHaveBean(RabbitMessagingAutoConfiguration.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("selecting Rabbit assembles Rabbit and not Kafka")
|
||||
void selectingRabbitAssemblesOnlyRabbit() {
|
||||
withAPublisher()
|
||||
.withPropertyValues("app.messaging.enabled=true", "app.messaging.broker=rabbit")
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context).hasNotFailed();
|
||||
assertThat(context).hasSingleBean(RabbitMessagingAutoConfiguration.class);
|
||||
assertThat(context).doesNotHaveBean(KafkaMessagingAutoConfiguration.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("MSG-INT-003: a selected transport now assembles a publisher")
|
||||
void aSelectedTransportAssemblesAPublisher() {
|
||||
runner
|
||||
.withPropertyValues(
|
||||
"app.messaging.enabled=true",
|
||||
"app.messaging.broker=kafka",
|
||||
"spring.kafka.bootstrap-servers=localhost:9092")
|
||||
.run(
|
||||
context -> {
|
||||
assertThat(context)
|
||||
.as(
|
||||
"this asserted the opposite, with the note that C3 would invert it rather than "
|
||||
+ "delete it. Every policy bean was in place and the platform still could "
|
||||
+ "not publish: no configuration produced a MessagePublisher, so "
|
||||
+ "DeadLetterOrchestrator had nothing to depend on. DefaultMessagePublisher "
|
||||
+ "existed in messaging-runtime-core the whole time — the starter did not "
|
||||
+ "depend on that leaf.")
|
||||
.hasNotFailed();
|
||||
assertThat(context).hasSingleBean(MessagePublisher.class);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("a selected broker with no address fails at startup, not at the first publish")
|
||||
void aSelectedBrokerWithNoAddressFailsAtStartup() {
|
||||
runner
|
||||
.withPropertyValues("app.messaging.enabled=true", "app.messaging.broker=kafka")
|
||||
.run(
|
||||
context ->
|
||||
assertThat(context)
|
||||
.as(
|
||||
"a producer built with no bootstrap servers defaults to localhost:9092 and "
|
||||
+ "fails on the first publish — which is a deployment that starts, "
|
||||
+ "reports healthy, and loses the first message somebody sends")
|
||||
.hasFailed()
|
||||
.getFailure()
|
||||
.rootCause()
|
||||
.hasMessageContaining("spring.kafka.bootstrap-servers"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The same runner with a publisher supplied by the test.
|
||||
*
|
||||
* <p>Only so the selection cases are about selection. The platform having no production publisher
|
||||
* of its own is a separate fact with a case of its own above, and letting it fail these two would
|
||||
* have hidden a defect behind a defect.
|
||||
*/
|
||||
private ApplicationContextRunner withAPublisher() {
|
||||
return runner.withBean(
|
||||
MessagePublisher.class,
|
||||
() ->
|
||||
new MessagePublisher() {
|
||||
@Override
|
||||
public <T> CompletionStage<PublishResult> publish(
|
||||
MessageDestination<T> destination,
|
||||
MessageEnvelope<T> message,
|
||||
PublishOptions options) {
|
||||
throw new UnsupportedOperationException("never invoked; this test assembles only");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static Set<String> liveThreadNames() {
|
||||
return Thread.getAllStackTraces().keySet().stream()
|
||||
.filter(Thread::isAlive)
|
||||
.map(Thread::getName)
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
private static Set<String> newMessagingThreadsSince(Set<String> before) {
|
||||
return liveThreadNames().stream()
|
||||
.filter(name -> !before.contains(name))
|
||||
.filter(
|
||||
name -> {
|
||||
String lower = name.toLowerCase(java.util.Locale.ROOT);
|
||||
return lower.contains("kafka")
|
||||
|| lower.contains("rabbit")
|
||||
|| lower.contains("amqp")
|
||||
|| lower.contains("messaging")
|
||||
|| lower.contains("outbox");
|
||||
})
|
||||
.collect(Collectors.toSet());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user