feat: jpa, messaging, notification, mongo, graphql 어댑터터 구현체 추가

This commit is contained in:
DongHyeonka
2026-08-15 13:01:58 +09:00
parent e23ed9486e
commit f56dd3e4eb
174 changed files with 10338 additions and 1274 deletions
@@ -65,28 +65,164 @@ public final class DefaultBatchMessagePublisher implements BatchMessagePublisher
Instant startedAt = clock.get();
List<CompletableFuture<BatchPublishItemResult>> pending = new ArrayList<>(requests.size());
boolean rejectionSeen = false;
// Index and message id per slot, so an entry still outstanding at the deadline can still be
// reported against the input position it came from.
List<BatchPublishItemResult> placeholders = new ArrayList<>(requests.size());
for (int index = 0; index < requests.size(); index++) {
if (rejectionSeen && options.stopOnFirstRejection()) {
break;
placeholders.add(outstanding(index, requests.get(index).message().messageId()));
if (options.stopOnFirstRejection() && anyRejected(pending)) {
// Every remaining index still gets a result. Breaking out shortened the result list, so a
// caller could not tell "not submitted" from "result lost" — and those need opposite
// actions.
pending.add(
CompletableFuture.completedFuture(
notSubmitted(index, requests.get(index).message().messageId(), startedAt)));
continue;
}
pending.add(submit(requests.get(index), index));
CompletableFuture<BatchPublishItemResult> submitted = submit(requests.get(index), index);
pending.add(submitted);
if (options.stopOnFirstRejection()) {
// Only observable for an entry that failed synchronously, which is the local-validation
// case; a broker rejection resolves later and is picked up on the next iteration.
CompletableFuture<BatchPublishItemResult> latest = pending.get(pending.size() - 1);
rejectionSeen =
latest.isDone() && latest.join().result().completion() == PublishCompletion.REJECTED;
// Sequential under stop-on-first-rejection: waiting for this entry's outcome is the only
// way the flag can mean anything. The previous loop only saw a rejection that had already
// resolved, which for an asynchronous broker is never — so every remaining entry was
// submitted anyway and the option did nothing.
awaitQuietly(submitted, remaining(startedAt, options.timeout()));
}
}
return CompletableFuture.allOf(pending.toArray(CompletableFuture[]::new))
.thenApply(
ignored ->
new BatchPublishResult(
pending.stream().map(CompletableFuture::join).toList(),
Duration.between(startedAt, clock.get())));
CompletableFuture<BatchPublishResult> completed = new CompletableFuture<>();
CompletableFuture<Void> all =
CompletableFuture.allOf(pending.toArray(CompletableFuture[]::new));
// The returned stage is deliberately dropped: `completed` is what the caller holds, and this
// callback's only job is to fill it in. Nothing downstream observes the intermediate stage.
CompletableFuture<Void> ignoredCompletion =
all.whenComplete(
(ignored, failure) ->
completed.complete(
new BatchPublishResult(
resolveAll(pending, placeholders),
Duration.between(startedAt, clock.get()))));
assert ignoredCompletion != null;
// The whole-batch deadline the options document. It was never read, so a publisher that never
// completed left the caller's stage pending forever — a timeout that exists only in the
// javadoc.
// Same for the scheduled future: cancelling it early would only save a no-op, and the task
// checks `isDone` before completing anything.
java.util.concurrent.ScheduledFuture<?> ignoredDeadline =
DEADLINES.schedule(
() -> {
if (!completed.isDone()) {
completed.complete(
new BatchPublishResult(
resolveAll(pending, placeholders),
Duration.between(startedAt, clock.get())));
}
},
options.timeout().toMillis(),
java.util.concurrent.TimeUnit.MILLISECONDS);
assert ignoredDeadline != null;
return completed;
}
/**
* One scheduler for batch deadlines.
*
* <p>A daemon thread so a pending deadline never keeps the JVM alive, and one shared instance
* because a scheduler per batch is a thread per batch.
*/
private static final java.util.concurrent.ScheduledExecutorService DEADLINES =
java.util.concurrent.Executors.newSingleThreadScheduledExecutor(
runnable -> {
Thread thread = new Thread(runnable, "messaging-batch-deadline");
thread.setDaemon(true);
return thread;
});
private boolean anyRejected(List<CompletableFuture<BatchPublishItemResult>> pending) {
return pending.stream()
.anyMatch(
future ->
future.isDone()
&& !future.isCompletedExceptionally()
&& future.join().result().completion() == PublishCompletion.REJECTED);
}
private void awaitQuietly(CompletableFuture<?> future, Duration budget) {
if (budget.isNegative() || budget.isZero()) {
return;
}
try {
future.get(budget.toMillis(), java.util.concurrent.TimeUnit.MILLISECONDS);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
} catch (java.util.concurrent.ExecutionException
| java.util.concurrent.TimeoutException other) {
// Both are outcomes the result already carries; nothing to add here.
}
}
private Duration remaining(Instant startedAt, Duration timeout) {
return timeout.minus(Duration.between(startedAt, clock.get()));
}
/**
* An entry the batch never submitted because an earlier one was rejected.
*
* <p>Distinct from a failure: nothing was sent, so the caller may submit it unchanged.
*/
private BatchPublishItemResult notSubmitted(
int index, dev.caskeleton.messaging.api.MessageId messageId, Instant startedAt) {
return new BatchPublishItemResult(
index,
messageId,
new dev.caskeleton.messaging.api.publish.PublishResult(
PublishCompletion.REJECTED,
dev.caskeleton.messaging.api.publish.PublishEvidence.notTransmitted(),
dev.caskeleton.messaging.api.publish.RoutingOutcome.UNKNOWN,
java.util.Optional.empty(),
1,
Duration.between(startedAt, clock.get()),
java.util.Optional.of(
dev.caskeleton.messaging.api.error.FailureDescriptor.of(
dev.caskeleton.messaging.api.error.FailureCategory.CONFIGURATION,
"NOT_SUBMITTED_AFTER_REJECTION",
"an earlier entry was rejected and this batch stops on the first rejection"))));
}
private List<BatchPublishItemResult> resolveAll(
List<CompletableFuture<BatchPublishItemResult>> pending,
List<BatchPublishItemResult> placeholders) {
List<BatchPublishItemResult> resolved = new ArrayList<>(pending.size());
for (int index = 0; index < pending.size(); index++) {
CompletableFuture<BatchPublishItemResult> future = pending.get(index);
resolved.add(
future.isDone() && !future.isCompletedExceptionally()
? future.join()
: placeholders.get(index));
}
return List.copyOf(resolved);
}
/** An entry still outstanding when the deadline arrived is ambiguous, never a success. */
private BatchPublishItemResult outstanding(
int index, dev.caskeleton.messaging.api.MessageId messageId) {
return new BatchPublishItemResult(
index,
messageId,
new dev.caskeleton.messaging.api.publish.PublishResult(
PublishCompletion.AMBIGUOUS,
dev.caskeleton.messaging.api.publish.PublishEvidence.ambiguous(),
dev.caskeleton.messaging.api.publish.RoutingOutcome.UNKNOWN,
java.util.Optional.empty(),
1,
Duration.ZERO,
java.util.Optional.of(
dev.caskeleton.messaging.api.error.FailureDescriptor.of(
dev.caskeleton.messaging.api.error.FailureCategory.AMBIGUOUS,
"BATCH_DEADLINE_EXCEEDED",
"the batch deadline elapsed before this entry produced evidence"))));
}
private <T> CompletableFuture<BatchPublishItemResult> submit(
@@ -67,8 +67,19 @@ public class KafkaMessagingAutoConfiguration {
* @param tlsPolicy the transport security policy
* @return the configurer
*/
/**
* The security configurer, which exists only when a credential source does.
*
* <p>It took {@code CredentialRuntimeRegistry} as a required parameter, and that registry is
* created only when the application supplies a {@code CredentialProvider}. Without one the
* context failed on a missing bean naming the registry — an error that describes the platform's
* internals rather than the one thing the operator has to do. The condition moves the failure to
* a place that can say so.
*/
@Bean
@ConditionalOnMissingBean
@org.springframework.boot.autoconfigure.condition.ConditionalOnBean(
CredentialRuntimeRegistry.class)
public KafkaSecurityConfigurer kafkaSecurityConfigurer(
CredentialRuntimeRegistry credentials, BrokerTlsPolicy tlsPolicy) {
return new KafkaSecurityConfigurer(credentials, tlsPolicy);
@@ -1,9 +1,10 @@
package dev.caskeleton.messaging.autoconfigure;
import dev.caskeleton.messaging.admin.AdminOperationJournal;
import dev.caskeleton.messaging.admin.DestructiveOperationGuard;
import dev.caskeleton.messaging.admin.runtime.AdminOperationIdempotencyStore;
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;
@@ -13,17 +14,17 @@ import org.springframework.context.annotation.Bean;
/**
* Wires the admin plane, and only when a deployment has explicitly asked for it.
*
* <p>Off unless {@code backend.messaging.admin.enabled=true}. An application that acquires the
* admin plane by adding a starter to its classpath is exactly the situation the plane's guards
* exist to prevent — the guards would still refuse an unapproved operation, but the beans would be
* reachable from any code in the process.
* <p>Off unless {@code app.messaging.admin.enabled=true}. An application that acquires the admin
* plane by adding a starter to its classpath is exactly the situation the plane's guards exist to
* prevent — the guards would still refuse an unapproved operation, but the beans would be reachable
* from any code in the process.
*
* <p>{@link dev.caskeleton.messaging.admin.runtime.DestructiveMessagingAdmin} is deliberately
* 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)
@ConditionalOnProperty(prefix = "backend.messaging.admin", name = "enabled", havingValue = "true")
@ConditionalOnProperty(prefix = "app.messaging.admin", name = "enabled", havingValue = "true")
public class MessagingAdminAutoConfiguration {
/**
@@ -40,14 +41,34 @@ public class MessagingAdminAutoConfiguration {
}
/**
* Returns the store that stops one approval being executed twice.
* Returns a single-process journal so a development runtime starts without extra wiring.
*
* @return the idempotency store
* <p>It declares itself non-durable, and {@link MessagingAdminDurabilityValidator} refuses to let
* a production profile start on it. That pairing is deliberate: the convenient default stays
* convenient for local work and becomes a startup failure — naming what to supply — the moment
* the deployment claims to be production. The previous default was an indistinguishable {@code
* ConcurrentHashMap} that silently let two replicas execute the same approval.
*
* @return the in-memory journal
*/
@Bean
@ConditionalOnMissingBean
public AdminOperationIdempotencyStore adminOperationIdempotencyStore() {
return new AdminOperationIdempotencyStore();
public AdminOperationJournal adminOperationJournal() {
return new InMemoryAdminOperationJournal();
}
/**
* Returns the validator that refuses a production profile on a non-durable journal.
*
* @param journal the journal in use
* @param environment the Spring environment
* @return the validator
*/
@Bean
@ConditionalOnMissingBean
public MessagingAdminDurabilityValidator messagingAdminDurabilityValidator(
AdminOperationJournal journal, org.springframework.core.env.Environment environment) {
return new MessagingAdminDurabilityValidator(journal, environment);
}
/**
@@ -0,0 +1,68 @@
package dev.caskeleton.messaging.autoconfigure;
import dev.caskeleton.messaging.admin.AdminOperationJournal;
import dev.caskeleton.messaging.api.error.MessagingConfigurationException;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.env.Environment;
/**
* Refuses to start a production profile on a journal that cannot survive a restart.
*
* <p>The previous default was an in-memory map registered by this starter, and nothing in the
* application said so. Two replicas each had their own copy, so both could claim the same approval
* at the same moment; a restart forgot every claim, so the same approval could be executed again by
* the same process. Both failures look like a successful redrive until somebody counts the
* duplicates.
*
* <p>The check is a startup failure rather than a warning because the gap only shows up during the
* incident the operation was run to resolve, which is the worst possible moment to discover it.
*/
public final class MessagingAdminDurabilityValidator implements InitializingBean {
private static final Set<String> PRODUCTION_PROFILES = Set.of("prod", "production");
private final AdminOperationJournal journal;
private final Environment environment;
/**
* Creates the validator.
*
* @param journal the journal the admin service will use
* @param environment the Spring environment, read for active profiles
*/
public MessagingAdminDurabilityValidator(AdminOperationJournal journal, Environment environment) {
this.journal = Objects.requireNonNull(journal, "journal must not be null");
this.environment = Objects.requireNonNull(environment, "environment must not be null");
}
@Override
public void afterPropertiesSet() {
validate();
}
/**
* Refuses a production profile on a non-durable journal.
*
* @throws MessagingConfigurationException naming what to supply
*/
public void validate() {
List<String> active = List.of(environment.getActiveProfiles());
boolean production = active.stream().anyMatch(PRODUCTION_PROFILES::contains);
if (!production || journal.isDurable()) {
return;
}
throw new MessagingConfigurationException(
"ADMIN_JOURNAL_NOT_DURABLE",
"the destructive-operation journal in use ("
+ journal.getClass().getSimpleName()
+ ") is not durable, and profiles "
+ active
+ " include a production profile; supply an AdminOperationJournal bean backed by the"
+ " shared database (JdbcAdminOperationJournal) so one approval cannot be executed"
+ " twice across replicas or across a restart");
}
}
@@ -44,6 +44,35 @@ import org.springframework.context.annotation.Bean;
@EnableConfigurationProperties(MessagingProperties.class)
public class MessagingCoreAutoConfiguration {
/**
* Fails the context when a production broker profile has no credential source.
*
* <p>One actionable error instead of a missing-bean message naming an internal registry type.
*/
@Bean
public MessagingCredentialRequirementValidator messagingCredentialRequirementValidator(
org.springframework.beans.factory.ObjectProvider<
dev.caskeleton.messaging.security.BrokerSecurityProfile>
profiles,
org.springframework.beans.factory.ObjectProvider<
dev.caskeleton.messaging.security.CredentialProvider>
credentials,
org.springframework.core.env.Environment environment) {
return new MessagingCredentialRequirementValidator(profiles, credentials, environment);
}
/**
* Fails the context when configuration uses a prefix nothing binds.
*
* <p>Registered here rather than left to review because the failure it catches is silent: a key
* under {@code backend.messaging} or a bare {@code messaging} looks configured and does nothing.
*/
@Bean
public MessagingPrefixMigrationValidator messagingPrefixMigrationValidator(
org.springframework.core.env.ConfigurableEnvironment environment) {
return new MessagingPrefixMigrationValidator(environment);
}
/**
* Validates every registered destination profile at startup.
*
@@ -0,0 +1,73 @@
package dev.caskeleton.messaging.autoconfigure;
import dev.caskeleton.messaging.api.error.MessagingConfigurationException;
import dev.caskeleton.messaging.security.BrokerSecurityProfile;
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.core.env.Environment;
/**
* Fails startup with one actionable error when a production profile has no credential source.
*
* <p>The broker configurations declared {@code CredentialRuntimeRegistry} as a required constructor
* parameter, and that registry exists only when the application supplies a {@code
* CredentialProvider}. An application that enabled the starter without one therefore failed on "no
* qualifying bean of type CredentialRuntimeRegistry" — a message about this platform's internals,
* naming a type the operator has never heard of, when the thing they have to do is supply a
* credential source.
*
* <p>The check is scoped to production profiles. A local profile that connects to a broker with no
* authentication is a legitimate development setup; the same profile marked production is not, and
* the two must not be satisfiable by the same configuration.
*/
public final class MessagingCredentialRequirementValidator implements InitializingBean {
private final ObjectProvider<BrokerSecurityProfile> profiles;
private final ObjectProvider<dev.caskeleton.messaging.security.CredentialProvider> credentials;
private final Environment environment;
public MessagingCredentialRequirementValidator(
ObjectProvider<BrokerSecurityProfile> profiles,
ObjectProvider<dev.caskeleton.messaging.security.CredentialProvider> credentials,
Environment environment) {
this.profiles = Objects.requireNonNull(profiles, "profiles must not be null");
this.credentials = Objects.requireNonNull(credentials, "credentials must not be null");
this.environment = Objects.requireNonNull(environment, "environment must not be null");
}
@Override
public void afterPropertiesSet() {
validate();
}
/**
* Refuses a production broker profile with no credential provider.
*
* @throws MessagingConfigurationException naming the profiles and what to supply
*/
public void validate() {
if (credentials.getIfAvailable() != null) {
return;
}
List<String> production =
profiles.stream()
.filter(BrokerSecurityProfile::production)
.map(BrokerSecurityProfile::broker)
.toList();
if (production.isEmpty()) {
return;
}
throw new MessagingConfigurationException(
"MESSAGING_CREDENTIAL_PROVIDER_REQUIRED",
"broker profile(s) "
+ production
+ " are marked production and no CredentialProvider bean is defined; supply one, or"
+ " mark the profile non-production if this deployment genuinely connects without"
+ " authentication. Active Spring profiles: "
+ List.of(environment.getActiveProfiles()));
}
}
@@ -0,0 +1,83 @@
package dev.caskeleton.messaging.autoconfigure;
import dev.caskeleton.messaging.api.error.MessagingConfigurationException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.PropertySource;
/**
* Refuses a configuration written against a prefix this platform no longer binds.
*
* <p>There were three namespaces. The starter's binder read {@code backend.messaging}; the deployed
* runtime and its {@code APP_MESSAGING_*} environment variables read {@code app.messaging}; and the
* configuration reference documented a bare {@code messaging} with destination, broker and security
* sections that no binder had ever contained. Two of the three bound nothing, so a deployment
* configured exactly as documented changed no behaviour and produced no error — the settings were
* simply inert.
*
* <p>Silence is the specific failure being fixed here. A key under a dead prefix is not a typo the
* operator will notice: it looks configured, it starts cleanly, and the first evidence that the
* limit or the flag never applied arrives during the incident it was meant to prevent.
*/
public final class MessagingPrefixMigrationValidator implements InitializingBean {
private final ConfigurableEnvironment environment;
public MessagingPrefixMigrationValidator(ConfigurableEnvironment environment) {
this.environment = Objects.requireNonNull(environment, "environment must not be null");
}
@Override
public void afterPropertiesSet() {
validate();
}
/**
* Fails when any key uses a superseded prefix.
*
* @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 + '.');
// 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 + '.'));
List<String> offending = new ArrayList<>(superseded);
offending.addAll(documented);
if (offending.isEmpty()) {
return;
}
throw new MessagingConfigurationException(
"MESSAGING_PREFIX_SUPERSEDED",
"these properties use a prefix this platform does not bind: "
+ String.join(", ", offending.stream().sorted().limit(10).toList())
+ (offending.size() > 10 ? " (and " + (offending.size() - 10) + " more)" : "")
+ "; move them under '"
+ MessagingProperties.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");
}
private List<String> keysUnder(String prefix) {
List<String> keys = new ArrayList<>();
for (PropertySource<?> source : environment.getPropertySources()) {
if (!(source instanceof EnumerablePropertySource<?> enumerable)) {
// A non-enumerable source cannot be scanned, and guessing at its contents would produce a
// startup failure nobody can act on.
continue;
}
for (String key : enumerable.getPropertyNames()) {
if (key.startsWith(prefix)) {
keys.add(key);
}
}
}
return keys;
}
}
@@ -6,14 +6,35 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* The platform's bound configuration.
*
* <p>Bound under {@code app.messaging}, which is the prefix the deployed runtime and the {@code
* APP_MESSAGING_*} environment variables already use. There were three namespaces: this binder read
* {@code backend.messaging}, the existing runtime settings read {@code app.messaging}, and the
* configuration reference documented a bare {@code messaging}. Two of the three bound nothing, so a
* deployment configured from the documentation changed no behaviour at all and nothing reported a
* problem.
*
* <p>{@code backend.messaging} is refused rather than quietly accepted as an alias — see {@link
* MessagingPrefixMigrationValidator}. An alias that works is a fourth thing to keep in sync, and
* the failure it prevents (a deployment split across two prefixes, each half-configuring the
* platform) is worse than an actionable startup error.
*
* <p>Every Experimental and bridge flag defaults to {@code false}. An adapter whose contract suite
* is still being proven must not become load-bearing because a default turned it on, and the same
* applies to the Spring Cloud Stream bridge, which bypasses the platform's retry and dead letter
* policy by design.
*/
@ConfigurationProperties(prefix = "backend.messaging")
@ConfigurationProperties(prefix = MessagingProperties.PREFIX)
public class MessagingProperties {
/** The one configuration prefix this platform binds. */
public static final String PREFIX = "app.messaging";
/** The prefix this binder used to read, kept only so the migration error can name it. */
public static final String SUPERSEDED_PREFIX = "backend.messaging";
/** The prefix the configuration reference documented, which nothing ever bound. */
public static final String DOCUMENTED_PREFIX = "messaging";
private final Experimental experimental = new Experimental();
private final Bridge bridge = new Bridge();
private final Backpressure backpressure = new Backpressure();
@@ -53,8 +53,19 @@ public class RabbitMessagingAutoConfiguration {
* @param tlsPolicy the transport security policy
* @return the configurer
*/
/**
* The security configurer, which exists only when a credential source does.
*
* <p>It took {@code CredentialRuntimeRegistry} as a required parameter, and that registry is
* created only when the application supplies a {@code CredentialProvider}. Without one the
* context failed on a missing bean naming the registry — an error that describes the platform's
* internals rather than the one thing the operator has to do. The condition moves the failure to
* a place that can say so.
*/
@Bean
@ConditionalOnMissingBean
@org.springframework.boot.autoconfigure.condition.ConditionalOnBean(
CredentialRuntimeRegistry.class)
public RabbitSecurityConfigurer rabbitSecurityConfigurer(
CredentialRuntimeRegistry credentials, BrokerTlsPolicy tlsPolicy) {
return new RabbitSecurityConfigurer(credentials, tlsPolicy);
@@ -38,6 +38,21 @@ class BatchPublisherTest {
private static final Instant NOW = Instant.parse("2026-08-10T09:15:00Z");
private static PublishResult rejected() {
return new PublishResult(
PublishCompletion.REJECTED,
PublishEvidence.notTransmitted(),
RoutingOutcome.UNKNOWN,
Optional.empty(),
1,
Duration.ZERO,
Optional.of(
dev.caskeleton.messaging.api.error.FailureDescriptor.of(
dev.caskeleton.messaging.api.error.FailureCategory.PERMANENT_BUSINESS,
"BROKER_REJECTED",
"the broker refused the message")));
}
private static PublishResult confirmed() {
return new PublishResult(
PublishCompletion.CONFIRMED,
@@ -193,7 +208,81 @@ class BatchPublisherTest {
.join();
assertThat(calls).containsExactly(0, 1);
assertThat(result.items()).hasSize(2);
assertThat(result.items())
.as("truncating the list left the caller unable to tell 'not submitted' from 'lost'")
.hasSize(4);
assertThat(result.items().get(3).result().failure().orElseThrow().code())
.isEqualTo("NOT_SUBMITTED_AFTER_REJECTION");
}
@Test
@org.junit.jupiter.api.DisplayName(
"the batch deadline completes outstanding entries as ambiguous")
void theBatchDeadlineCompletesOutstandingEntries() {
BatchPublishResult result =
new DefaultBatchMessagePublisher(
new MessagePublisher() {
@Override
public <T> CompletionStage<PublishResult> publish(
MessageDestination<T> destination,
MessageEnvelope<T> message,
PublishOptions options) {
return new CompletableFuture<>();
}
},
() -> NOW)
.publish(requests(2), new BatchPublishOptions(Duration.ofMillis(50), 100, false))
.toCompletableFuture()
.join();
assertThat(result.items())
.as("options.timeout() was never read, so a publisher that never completes hung forever")
.hasSize(2);
assertThat(result.items())
.allSatisfy(
item ->
assertThat(item.result().completion())
.isEqualTo(dev.caskeleton.messaging.api.publish.PublishCompletion.AMBIGUOUS));
}
@Test
@org.junit.jupiter.api.DisplayName("a delayed rejection still stops the entries after it")
void aDelayedRejectionStopsLaterEntries() {
List<Integer> calls = new ArrayList<>();
java.util.concurrent.CompletableFuture<dev.caskeleton.messaging.api.publish.PublishResult>
delayed = new java.util.concurrent.CompletableFuture<>();
BatchPublishResult result =
new DefaultBatchMessagePublisher(
new MessagePublisher() {
@Override
public <T> CompletionStage<PublishResult> publish(
MessageDestination<T> destination,
MessageEnvelope<T> message,
PublishOptions options) {
int index = calls.size();
calls.add(index);
if (index == 0) {
// Resolves only after the publisher returns, which is what an asynchronous
// broker rejection looks like. The old loop only saw an already-completed
// failure, so every later entry was submitted anyway.
// Completed on another thread so the rejection lands after this method
// returns — the shape an asynchronous broker rejection actually has.
new Thread(() -> delayed.complete(rejected())).start();
return delayed;
}
return CompletableFuture.completedFuture(confirmed());
}
},
() -> NOW)
.publish(requests(3), new BatchPublishOptions(Duration.ofSeconds(2), 100, true))
.toCompletableFuture()
.join();
assertThat(calls).containsExactly(0);
assertThat(result.items()).hasSize(3);
assertThat(result.items().get(2).result().failure().orElseThrow().code())
.isEqualTo("NOT_SUBMITTED_AFTER_REJECTION");
}
@Test
@@ -71,10 +71,10 @@ class MessagingAutoConfigurationTest {
void propertiesBindFromConfiguration() {
runner
.withPropertyValues(
"backend.messaging.experimental.pulsar=true",
"backend.messaging.backpressure.global-limit=64",
"backend.messaging.backpressure.per-destination-limit=8",
"backend.messaging.shutdown.drain-deadline=15s")
"app.messaging.experimental.pulsar=true",
"app.messaging.backpressure.global-limit=64",
"app.messaging.backpressure.per-destination-limit=8",
"app.messaging.shutdown.drain-deadline=15s")
.run(
context -> {
MessagingProperties properties = context.getBean(MessagingProperties.class);
@@ -111,8 +111,8 @@ class MessagingAutoConfigurationTest {
void backpressureLimitsAreValidatedAtStartup() {
runner
.withPropertyValues(
"backend.messaging.backpressure.global-limit=4",
"backend.messaging.backpressure.per-destination-limit=8")
"app.messaging.backpressure.global-limit=4",
"app.messaging.backpressure.per-destination-limit=8")
.run(context -> assertThat(context).hasFailed());
}
@@ -235,4 +235,259 @@ class MessagingAutoConfigurationTest {
false,
false);
}
@org.junit.jupiter.api.Test
@org.junit.jupiter.api.DisplayName("a superseded prefix fails startup instead of binding nothing")
void aSupersededPrefixFailsStartup() {
new org.springframework.boot.test.context.runner.ApplicationContextRunner()
.withConfiguration(
org.springframework.boot.autoconfigure.AutoConfigurations.of(
MessagingCoreAutoConfiguration.class))
.withPropertyValues("backend.messaging.backpressure.global-limit=64")
.run(
context ->
org.assertj.core.api.Assertions.assertThat(context)
.as(
"a key under a dead prefix looks configured, starts cleanly and does"
+ " nothing")
.hasFailed());
}
@org.junit.jupiter.api.Test
@org.junit.jupiter.api.DisplayName("the documented bare prefix also fails")
void theDocumentedBarePrefixAlsoFails() {
new org.springframework.boot.test.context.runner.ApplicationContextRunner()
.withConfiguration(
org.springframework.boot.autoconfigure.AutoConfigurations.of(
MessagingCoreAutoConfiguration.class))
.withPropertyValues("messaging.destinations.orders.broker=kafka-primary")
.run(context -> org.assertj.core.api.Assertions.assertThat(context).hasFailed());
}
@org.junit.jupiter.api.Test
@org.junit.jupiter.api.DisplayName("the canonical prefix passes the validator")
void theCanonicalPrefixPassesTheValidator() {
org.springframework.core.env.StandardEnvironment environment =
new org.springframework.core.env.StandardEnvironment();
environment
.getPropertySources()
.addFirst(
new org.springframework.core.env.MapPropertySource(
"test", java.util.Map.of("app.messaging.backpressure.global-limit", "64")));
org.assertj.core.api.Assertions.assertThatCode(
() -> new MessagingPrefixMigrationValidator(environment).validate())
.doesNotThrowAnyException();
}
@org.junit.jupiter.api.Test
@org.junit.jupiter.api.DisplayName("the migration error names the keys and the new prefix")
void theMigrationErrorNamesTheKeys() {
org.springframework.core.env.StandardEnvironment environment =
new org.springframework.core.env.StandardEnvironment();
environment
.getPropertySources()
.addFirst(
new org.springframework.core.env.MapPropertySource(
"test", java.util.Map.of("backend.messaging.backpressure.global-limit", "64")));
org.assertj.core.api.Assertions.assertThatThrownBy(
() -> new MessagingPrefixMigrationValidator(environment).validate())
.hasMessageContaining("backend.messaging.backpressure.global-limit")
.hasMessageContaining("app.messaging");
}
@org.junit.jupiter.api.Test
@org.junit.jupiter.api.DisplayName(
"a production profile on an in-memory journal refuses to start")
void aProductionProfileOnAnInMemoryJournalRefusesToStart() {
org.springframework.mock.env.MockEnvironment production =
new org.springframework.mock.env.MockEnvironment();
production.setActiveProfiles("prod");
org.assertj.core.api.Assertions.assertThatThrownBy(
() ->
new MessagingAdminDurabilityValidator(
new dev.caskeleton.messaging.admin.runtime.InMemoryAdminOperationJournal(),
production)
.validate())
.as(
"two replicas with their own maps each believed they were the only one executing an"
+ " approval, and a restart forgot every claim")
.isInstanceOf(dev.caskeleton.messaging.api.error.MessagingConfigurationException.class)
.hasMessageContaining("not durable")
.hasMessageContaining("JdbcAdminOperationJournal");
}
@org.junit.jupiter.api.Test
@org.junit.jupiter.api.DisplayName("local development still starts on the in-memory journal")
void localDevelopmentStillStartsOnTheInMemoryJournal() {
org.assertj.core.api.Assertions.assertThatCode(
() ->
new MessagingAdminDurabilityValidator(
new dev.caskeleton.messaging.admin.runtime.InMemoryAdminOperationJournal(),
new org.springframework.mock.env.MockEnvironment())
.validate())
.doesNotThrowAnyException();
}
@org.junit.jupiter.api.Test
@org.junit.jupiter.api.DisplayName("a durable journal satisfies a production profile")
void aDurableJournalSatisfiesAProductionProfile() {
org.springframework.mock.env.MockEnvironment production =
new org.springframework.mock.env.MockEnvironment();
production.setActiveProfiles("production");
org.assertj.core.api.Assertions.assertThatCode(
() ->
new MessagingAdminDurabilityValidator(new DurableJournal(), production).validate())
.doesNotThrowAnyException();
}
@org.junit.jupiter.api.Test
@org.junit.jupiter.api.DisplayName(
"a production profile without a credential provider fails with one actionable error")
void aProductionProfileWithoutCredentialsFailsActionably() {
org.assertj.core.api.Assertions.assertThatThrownBy(
() ->
new MessagingCredentialRequirementValidator(
new StaticProvider<>(
new dev.caskeleton.messaging.security.BrokerSecurityProfile(
"kafka-primary",
true,
true,
true,
new dev.caskeleton.messaging.security.BrokerCredentialProfile
.SaslScram("kafka-app"),
new dev.caskeleton.messaging.security.BrokerCredentialProfile
.SaslScram("kafka-app"),
java.util.Optional.empty(),
dev.caskeleton.messaging.security.DestinationAccessPolicy
.denyAll())),
new StaticProvider<dev.caskeleton.messaging.security.CredentialProvider>(),
new org.springframework.core.env.StandardEnvironment())
.validate())
.as(
"the context used to fail on a missing CredentialRuntimeRegistry, naming an internal"
+ " type instead of the one thing the operator has to supply")
.isInstanceOf(dev.caskeleton.messaging.api.error.MessagingConfigurationException.class)
.hasMessageContaining("CredentialProvider")
.hasMessageContaining("kafka-primary");
}
@org.junit.jupiter.api.Test
@org.junit.jupiter.api.DisplayName("a non-production profile without credentials still starts")
void aNonProductionProfileWithoutCredentialsStarts() {
org.assertj.core.api.Assertions.assertThatCode(
() ->
new MessagingCredentialRequirementValidator(
new StaticProvider<>(
new dev.caskeleton.messaging.security.BrokerSecurityProfile(
"kafka-local",
false,
false,
false,
new dev.caskeleton.messaging.security.BrokerCredentialProfile
.SaslScram("kafka-app"),
new dev.caskeleton.messaging.security.BrokerCredentialProfile
.SaslScram("kafka-app"),
java.util.Optional.empty(),
dev.caskeleton.messaging.security.DestinationAccessPolicy
.denyAll())),
new StaticProvider<dev.caskeleton.messaging.security.CredentialProvider>(),
new org.springframework.core.env.StandardEnvironment())
.validate())
.as("a local broker with no authentication is a legitimate development setup")
.doesNotThrowAnyException();
}
/** A journal that claims durability, standing in for the JDBC one. */
private static final class DurableJournal
implements dev.caskeleton.messaging.admin.AdminOperationJournal {
@Override
public dev.caskeleton.messaging.admin.AdminOperationLease begin(
String approvalTicket,
dev.caskeleton.messaging.admin.PlanDigest planDigest,
String operationId,
String leaseOwner,
java.time.Duration leaseDuration,
java.time.Instant now) {
throw new UnsupportedOperationException("the durability check never executes an operation");
}
@Override
public void checkpoint(
dev.caskeleton.messaging.admin.AdminOperationLease lease,
int itemsCompleted,
java.time.Duration leaseDuration,
java.time.Instant now) {
throw new UnsupportedOperationException("the durability check never executes an operation");
}
@Override
public void complete(
dev.caskeleton.messaging.admin.AdminOperationLease lease,
int itemsCompleted,
java.time.Instant now) {
throw new UnsupportedOperationException("the durability check never executes an operation");
}
@Override
public void fail(
dev.caskeleton.messaging.admin.AdminOperationLease lease,
int itemsCompleted,
String failureCode,
java.time.Instant now) {
throw new UnsupportedOperationException("the durability check never executes an operation");
}
@Override
public java.util.Optional<dev.caskeleton.messaging.admin.AdminOperationRecord> find(
String approvalTicket, dev.caskeleton.messaging.admin.PlanDigest planDigest) {
return java.util.Optional.empty();
}
@Override
public boolean isDurable() {
return true;
}
}
/** A fixed ObjectProvider, so the validator can be exercised without a container. */
private static final class StaticProvider<T>
implements org.springframework.beans.factory.ObjectProvider<T> {
private final java.util.List<T> values;
@SafeVarargs
private StaticProvider(T... values) {
this.values = java.util.List.of(values);
}
@Override
public T getObject() {
return values.get(0);
}
@Override
public T getObject(Object... args) {
return getObject();
}
@Override
public T getIfAvailable() {
return values.isEmpty() ? null : values.get(0);
}
@Override
public T getIfUnique() {
return values.size() == 1 ? values.get(0) : null;
}
@Override
public java.util.stream.Stream<T> stream() {
return values.stream();
}
}
}