diff --git a/spring-modulith-bom/pom.xml b/spring-modulith-bom/pom.xml index afd642dd2..ca5853c3d 100644 --- a/spring-modulith-bom/pom.xml +++ b/spring-modulith-bom/pom.xml @@ -59,6 +59,11 @@ spring-modulith-events-core 2.2.0-SNAPSHOT + + org.springframework.modulith + spring-modulith-events-couchbase + 2.2.0-SNAPSHOT + org.springframework.modulith spring-modulith-events-jackson @@ -144,6 +149,11 @@ spring-modulith-starter-core 2.2.0-SNAPSHOT + + org.springframework.modulith + spring-modulith-starter-couchbase + 2.2.0-SNAPSHOT + org.springframework.modulith spring-modulith-starter-insight diff --git a/spring-modulith-events/pom.xml b/spring-modulith-events/pom.xml index 2f3ace313..cbfb63ac0 100644 --- a/spring-modulith-events/pom.xml +++ b/spring-modulith-events/pom.xml @@ -17,6 +17,7 @@ spring-modulith-events-amqp spring-modulith-events-api spring-modulith-events-core + spring-modulith-events-couchbase spring-modulith-events-jackson spring-modulith-events-jdbc spring-modulith-events-jms diff --git a/spring-modulith-events/spring-modulith-events-couchbase/pom.xml b/spring-modulith-events/spring-modulith-events-couchbase/pom.xml new file mode 100644 index 000000000..2afbcd739 --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/pom.xml @@ -0,0 +1,93 @@ + + + 4.0.0 + + org.springframework.modulith + spring-modulith-events + 2.2.0-SNAPSHOT + + + Spring Modulith - Events - CouchBase-based repository + spring-modulith-events-couchbase + + + spring.modulith.events.couchbase + + + + + + org.testcontainers + testcontainers-bom + ${testcontainers.version} + pom + import + + + + + + + + org.jspecify + jspecify + + + + ${project.groupId} + spring-modulith-events-core + ${project.version} + + + + org.springframework.data + spring-data-couchbase + + + + org.springframework.boot + spring-boot-data-couchbase + + + + org.springframework.boot + spring-boot-transaction + true + + + + org.springframework.boot + spring-boot-starter-data-couchbase-test + test + + + + + + org.springframework.boot + spring-boot-testcontainers + test + + + + org.testcontainers + testcontainers + test + + + + org.testcontainers + testcontainers-junit-jupiter + test + + + + org.testcontainers + testcontainers-couchbase + test + + + + \ No newline at end of file diff --git a/spring-modulith-events/spring-modulith-events-couchbase/src/main/java/org/springframework/modulith/events/couchbase/CouchbaseEventPublication.java b/spring-modulith-events/spring-modulith-events-couchbase/src/main/java/org/springframework/modulith/events/couchbase/CouchbaseEventPublication.java new file mode 100644 index 000000000..79f9a92c7 --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/src/main/java/org/springframework/modulith/events/couchbase/CouchbaseEventPublication.java @@ -0,0 +1,134 @@ +/* + * Copyright 2026 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.modulith.events.couchbase; + +import org.jspecify.annotations.Nullable; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.PersistenceCreator; +import org.springframework.data.couchbase.core.mapping.Document; +import org.springframework.data.couchbase.core.mapping.Field; +import org.springframework.data.couchbase.repository.Collection; +import org.springframework.util.Assert; + +import java.time.Instant; +import java.util.UUID; + +import static org.springframework.modulith.events.EventPublication.*; +import static org.springframework.modulith.events.couchbase.CouchbaseEventPublicationRepository.*; + +/** + * A CouchBase Document to represent event publications. + * + * @author Oliver Drotbohm + * @author Alexandre Vigneron + */ +@Document +@Collection(value = BASE_COLLECTION) +class CouchbaseEventPublication { + + @Id + final UUID id; + @Field + final Instant publicationDate; + @Field + final String listenerId; + @Field + final Object event; + @Field + @Nullable + final Instant lastResubmissionDate; + @Field + final int completionAttempts; + + @Field + @Nullable + Instant completionDate; + @Field + Status status; + + /** + * Creates a new {@link CouchbaseEventPublication} for the given id, publication date, listener id, event and completion + * date. + * + * @param id must not be {@literal null}. + * @param publicationDate must not be {@literal null}. + * @param listenerId must not be {@literal null} or empty. + * @param event must not be {@literal null}. + * @param completionDate can be {@literal null}. + * @param status can be {@literal null}. + * @param lastResubmissionDate can be {@literal null}. + */ + @PersistenceCreator + public CouchbaseEventPublication(UUID id, Instant publicationDate, String listenerId, Object event, + @Nullable Instant completionDate, @Nullable Status status, + @Nullable Instant lastResubmissionDate, int completionAttempts) { + Assert.notNull(id, "Id must not be null!"); + Assert.notNull(publicationDate, "Publication date must not be null!"); + Assert.notNull(listenerId, "Listener id must not be null!"); + Assert.notNull(event, "Event must not be null!"); + + this.id = id; + this.publicationDate = publicationDate; + this.listenerId = listenerId; + this.event = event; + this.completionDate = completionDate; + this.status = status != null ? status : completionDate != null ? Status.COMPLETED : Status.PROCESSING; + this.lastResubmissionDate = lastResubmissionDate; + this.completionAttempts = completionAttempts; + } + + /** + * Marks the publication as completed at the given {@link Instant}. + * + * @param instant must not be {@literal null}. + * @return will never be {@literal null}. + */ + CouchbaseEventPublication markCompleted(Instant instant) { + + Assert.notNull(instant, "Instant must not be null!"); + + this.completionDate = instant; + this.status = Status.COMPLETED; + + return this; + } + + /** + * Marks the publication as failed. + * + * @return will never be {@literal null}. + */ + CouchbaseEventPublication markFailed() { + this.status = Status.FAILED; + + return this; + } + + /** + * Marks the publication as resubmitted at the given {@link Instant}. + * + * @param instant must not be {@literal null}. + * @return will never be {@literal null}. + */ + CouchbaseEventPublication markResubmitted(Instant instant) { + Assert.notNull(instant, "Instant must not be null!"); + + return new CouchbaseEventPublication( + id, publicationDate, listenerId, event, completionDate, + Status.RESUBMITTED, instant, this.completionAttempts + 1 + ); + } +} diff --git a/spring-modulith-events/spring-modulith-events-couchbase/src/main/java/org/springframework/modulith/events/couchbase/CouchbaseEventPublicationAutoConfiguration.java b/spring-modulith-events/spring-modulith-events-couchbase/src/main/java/org/springframework/modulith/events/couchbase/CouchbaseEventPublicationAutoConfiguration.java new file mode 100644 index 000000000..e4cda91aa --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/src/main/java/org/springframework/modulith/events/couchbase/CouchbaseEventPublicationAutoConfiguration.java @@ -0,0 +1,42 @@ +/* + * Copyright 2026 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.modulith.events.couchbase; + +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.context.annotation.Bean; +import org.springframework.core.env.Environment; +import org.springframework.data.couchbase.core.CouchbaseTemplate; +import org.springframework.modulith.events.config.EventPublicationAutoConfiguration; +import org.springframework.modulith.events.config.EventPublicationConfigurationExtension; +import org.springframework.modulith.events.support.CompletionMode; + +/** + * Autoconfiguration for Couchbase event publication repository. + * + * @author Oliver Drotbohm + * @author Alexandre Vigneron + */ +@AutoConfiguration +@AutoConfigureBefore(EventPublicationAutoConfiguration.class) +class CouchbaseEventPublicationAutoConfiguration implements EventPublicationConfigurationExtension { + + @Bean + CouchbaseEventPublicationRepository couchBaseEventPublicationRepository(CouchbaseTemplate template, + Environment environment) { + return new CouchbaseEventPublicationRepository(template, CompletionMode.from(environment)); + } +} diff --git a/spring-modulith-events/spring-modulith-events-couchbase/src/main/java/org/springframework/modulith/events/couchbase/CouchbaseEventPublicationRepository.java b/spring-modulith-events/spring-modulith-events-couchbase/src/main/java/org/springframework/modulith/events/couchbase/CouchbaseEventPublicationRepository.java new file mode 100644 index 000000000..e54067f8d --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/src/main/java/org/springframework/modulith/events/couchbase/CouchbaseEventPublicationRepository.java @@ -0,0 +1,394 @@ +/* + * Copyright 2022-2026 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.modulith.events.couchbase; + +import static org.springframework.data.couchbase.core.query.Query.query; +import static org.springframework.data.couchbase.core.query.QueryCriteria.where; + +import java.time.Instant; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import java.util.function.UnaryOperator; + +import org.jspecify.annotations.Nullable; +import org.springframework.data.couchbase.core.CouchbaseTemplate; +import org.springframework.data.couchbase.core.mapping.CouchbaseDocument; +import org.springframework.data.couchbase.core.query.Query; +import org.springframework.data.couchbase.core.query.QueryCriteria; +import org.springframework.data.domain.Sort; +import org.springframework.modulith.events.EventPublication.Status; +import org.springframework.modulith.events.core.EventPublicationRepository; +import org.springframework.modulith.events.core.PublicationTargetIdentifier; +import org.springframework.modulith.events.core.TargetEventPublication; +import org.springframework.modulith.events.support.CompletionMode; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.Assert; + +/** + * Repository to store {@link TargetEventPublication}s in a Couchbase DB. + * + * @author Oliver Drotbohm + * @author Alexandre Vigneron + */ +@Transactional +class CouchbaseEventPublicationRepository implements EventPublicationRepository { + + private static final String COMPLETION_DATE = "completionDate"; + private static final String ID = "META().id"; + private static final String LISTENER_ID = "listenerId"; + private static final String PUBLICATION_DATE = "publicationDate"; + private static final String STATUS = "status"; + + private static final Sort DEFAULT_SORT = Sort.by(PUBLICATION_DATE).ascending(); + + static final String BASE_COLLECTION = "EVENT_PUBLICATION"; + static final String ARCHIVE_COLLECTION = "EVENT_PUBLICATION_ARCHIVE"; + + private final CouchbaseTemplate couchbaseTemplate; + private final CompletionMode completionMode; + private final String collection, archiveCollection; + + /** + * Creates a new {@link CouchbaseEventPublicationRepository} for the given {@link CouchbaseTemplate}. + * + * @param couchbaseTemplate must not be {@literal null}. + * @param completionMode must not be {@literal null}. + */ + public CouchbaseEventPublicationRepository(CouchbaseTemplate couchbaseTemplate, CompletionMode completionMode) { + + Assert.notNull(couchbaseTemplate, "CouchbaseTemplate must not be null!"); + Assert.notNull(completionMode, "Completion mode must not be null!"); + + this.couchbaseTemplate = couchbaseTemplate; + this.completionMode = completionMode; + this.collection = BASE_COLLECTION; + this.archiveCollection = completionMode == CompletionMode.ARCHIVE ? ARCHIVE_COLLECTION : collection; + } + + @Override + public TargetEventPublication create(TargetEventPublication publication) { + + couchbaseTemplate.upsertById(CouchbaseEventPublication.class) + .inCollection(collection) + .one(domainToDocument(publication)); + + return publication; + } + + @Override + public void markCompleted(Object event, PublicationTargetIdentifier identifier, Instant completionDate) { + + findIncompletePublicationsByEventAndTargetIdentifier(event, identifier) + .map(TargetEventPublication::getIdentifier) + .ifPresent(id -> markCompleted(id, completionDate)); + } + + @Override + public void markCompleted(UUID identifier, Instant completionDate) { + var criteria = where(ID).is(identifier.toString()).and(COMPLETION_DATE).isMissing(); + + if (completionMode == CompletionMode.DELETE) { + + couchbaseTemplate.removeByQuery(CouchbaseEventPublication.class) + .inCollection(collection) + .matching(criteria) + .all(); + + } else if (completionMode == CompletionMode.ARCHIVE) { + + markCompleted(criteria, completionDate); + + } else { + updateFirst(criteria, collection, publication -> publication.markCompleted(completionDate)); + } + } + + @Override + public void markFailed(UUID identifier) { + + var criteria = where(ID).is(identifier.toString()).and(STATUS).ne(Status.FAILED); + + updateFirst(criteria, collection, CouchbaseEventPublication::markFailed); + } + + @Override + public boolean markResubmitted(UUID identifier, Instant resubmissionDate) { + + var criteria = where(ID).is(identifier.toString()).and(STATUS).ne(Status.RESUBMITTED); + + return updateFirst(criteria, collection, publication -> publication.markResubmitted(resubmissionDate)); + } + + @Override + @Transactional(readOnly = true) + public List findIncompletePublications() { + return readMapped(defaultQuery(where(COMPLETION_DATE).isMissing())); + } + + @Override + @Transactional(readOnly = true) + public List findIncompletePublicationsPublishedBefore(Instant instant) { + return readMapped(defaultQuery(where(COMPLETION_DATE).isMissing().and(PUBLICATION_DATE).lt(instant.toEpochMilli()))); + } + + @Override + @Transactional(readOnly = true) + public Optional findIncompletePublicationsByEventAndTargetIdentifier( + Object event, PublicationTargetIdentifier targetIdentifier) { + + // N1QL cannot parameterize complex sub-objects (CouchbaseDocument fails JsonValue.coerce). + return readMapped(defaultQuery(where(LISTENER_ID).is(targetIdentifier.getValue()).and(COMPLETION_DATE).isMissing())) + .stream() + .filter(it -> eventsMatch(it.getEvent(), event)) + .findFirst(); + } + + @Override + public List findCompletedPublications() { + return readMapped(defaultQuery(where(COMPLETION_DATE).isValued()), archiveCollection); + } + + @Override + public List findFailedPublications(FailedCriteria criteria) { + + var statusFailed = where(STATUS).is(Status.FAILED); + + var reference = criteria.getPublicationDateReference(); + + if (reference != null) { + statusFailed = statusFailed.and(PUBLICATION_DATE).lt(reference.toEpochMilli()); + } + + var limit = criteria.getMaxItemsToRead(); + + if (limit > Integer.MAX_VALUE) { + throw new IllegalArgumentException("Number of items to read needs to fit into an integer!"); + } + + var query = defaultQuery(statusFailed); + + return readMapped(limit != -1 ? query.limit((int) limit) : query); + } + + @Override + public int countByStatus(Status status) { + + var collection = status == Status.COMPLETED && completionMode == CompletionMode.ARCHIVE + ? archiveCollection + : this.collection; + + return (int) couchbaseTemplate.findByQuery(CouchbaseEventPublication.class) + .inCollection(collection) + .matching(where(STATUS).is(status)) + .count(); + } + + @Override + public void deletePublications(List identifiers) { + var idStrings = identifiers.stream().map(UUID::toString).toArray(); + + couchbaseTemplate.removeByQuery(CouchbaseEventPublication.class) + .inCollection(collection) + .matching(where(ID).in(idStrings)) + .all(); + + couchbaseTemplate.removeByQuery(CouchbaseEventPublication.class) + .inCollection(archiveCollection) + .matching(where(ID).in(idStrings)) + .all(); + } + + @Override + public void deleteCompletedPublications() { + couchbaseTemplate.removeByQuery(CouchbaseEventPublication.class) + .inCollection(archiveCollection) + .matching(where(COMPLETION_DATE).isNotNull()) + .all(); + } + + @Override + public void deleteCompletedPublicationsBefore(Instant instant) { + + Assert.notNull(instant, "Instant must not be null!"); + + couchbaseTemplate.removeByQuery(CouchbaseEventPublication.class) + .inCollection(archiveCollection) + // Convert to millis before because QueryCriteria convert instant to string by default but Couchbase use Long (see InstantToLongConverter) + .matching(where(COMPLETION_DATE).lt(instant.toEpochMilli())) + .all(); + } + + private List readMapped(Query query) { + return readMapped(query, collection); + } + + private List readMapped(Query query, String collection) { + + return couchbaseTemplate.findByQuery(CouchbaseEventPublication.class) + .inCollection(collection) + .matching(query) + .stream() + .map(CouchbaseEventPublicationRepository::documentToDomain) + .toList(); + } + + private static CouchbaseEventPublication domainToDocument(TargetEventPublication publication) { + + return new CouchbaseEventPublication( + publication.getIdentifier(), + publication.getPublicationDate(), + publication.getTargetIdentifier().getValue(), + publication.getEvent(), + publication.getCompletionDate().orElse(null), + publication.getStatus(), + publication.getLastResubmissionDate(), + publication.getCompletionAttempts()); + } + + private static TargetEventPublication documentToDomain(CouchbaseEventPublication document) { + return new CouchBaseEventPublicationAdapter(document); + } + + private static Query defaultQuery(QueryCriteria criteria) { + return query(criteria).with(DEFAULT_SORT); + } + + private void markCompleted(QueryCriteria criteria, Instant completionDate) { + + var query = defaultQuery(criteria); + var matching = couchbaseTemplate.findByQuery(CouchbaseEventPublication.class) + .inCollection(collection) + .matching(query) + .all(); + + matching.forEach(publication -> { + + couchbaseTemplate.upsertById(CouchbaseEventPublication.class) + .inCollection(archiveCollection) + .one(publication.markCompleted(completionDate)); + + couchbaseTemplate.removeById(CouchbaseEventPublication.class) + .inCollection(collection) + .one(publication.id.toString()); + }); + } + + private boolean updateFirst(QueryCriteria query, String collection, UnaryOperator mutator) { + + var result = couchbaseTemplate.findByQuery(CouchbaseEventPublication.class) + .inCollection(collection) + .matching(query) + .first(); + + result.ifPresent(it -> couchbaseTemplate.upsertById(CouchbaseEventPublication.class) + .inCollection(collection) + .one(mutator.apply(it))); + + return result.isPresent(); + } + + /** + * Compares two event objects by their serialized Couchbase representation + */ + private boolean eventsMatch(Object stored, Object query) { + + var converter = couchbaseTemplate.getConverter(); + var storedSerialized = converter.convertForWriteIfNeeded(stored); + var querySerialized = converter.convertForWriteIfNeeded(query); + + if (storedSerialized instanceof CouchbaseDocument storedDoc + && querySerialized instanceof CouchbaseDocument queryDoc) { + return storedDoc.export().equals(queryDoc.export()); + } + + return Objects.equals(storedSerialized, querySerialized); + } + + private static class CouchBaseEventPublicationAdapter implements TargetEventPublication { + + private final CouchbaseEventPublication publication; + + CouchBaseEventPublicationAdapter(CouchbaseEventPublication publication) { + this.publication = publication; + } + + @Override + public UUID getIdentifier() { + return publication.id; + } + + @Override + public Object getEvent() { + return publication.event; + } + + @Override + public PublicationTargetIdentifier getTargetIdentifier() { + return PublicationTargetIdentifier.of(publication.listenerId); + } + + @Override + public Instant getPublicationDate() { + return publication.publicationDate; + } + + @Override + public Optional getCompletionDate() { + return Optional.ofNullable(publication.completionDate); + } + + @Override + public void markCompleted(Instant instant) { + this.publication.markCompleted(instant); + } + + @Override + public Status getStatus() { + return publication.status; + } + + @Override + public int getCompletionAttempts() { + return publication.completionAttempts; + } + + @Override + public @Nullable Instant getLastResubmissionDate() { + return publication.lastResubmissionDate; + } + + @Override + public boolean equals(Object obj) { + + if (this == obj) { + return true; + } + + if (!(obj instanceof CouchBaseEventPublicationAdapter that)) { + return false; + } + + return Objects.equals(publication, that.publication); + } + + @Override + public int hashCode() { + return Objects.hash(publication); + } + } +} diff --git a/spring-modulith-events/spring-modulith-events-couchbase/src/main/java/org/springframework/modulith/events/couchbase/CouchbaseTransactionAutoConfiguration.java b/spring-modulith-events/spring-modulith-events-couchbase/src/main/java/org/springframework/modulith/events/couchbase/CouchbaseTransactionAutoConfiguration.java new file mode 100644 index 000000000..1a22827e3 --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/src/main/java/org/springframework/modulith/events/couchbase/CouchbaseTransactionAutoConfiguration.java @@ -0,0 +1,55 @@ +/* + * Copyright 2023-2026 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.modulith.events.couchbase; + +import org.springframework.boot.autoconfigure.AutoConfiguration; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.transaction.autoconfigure.TransactionAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.data.couchbase.CouchbaseClientFactory; +import org.springframework.data.couchbase.transaction.CouchbaseCallbackTransactionManager; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Auto-configuration to enable Couchbase transaction management as that is required for the + * {@link org.springframework.modulith.events.core.EventPublicationRegistry} to work properly. + * + * @author Oliver Drotbohm + * @author Alexandre Vigneron + */ +@AutoConfiguration +@AutoConfigureBefore(TransactionAutoConfiguration.class) +@ConditionalOnProperty( + name = "spring.modulith.events.couchbase.transaction-management.enabled", + havingValue = "true", + matchIfMissing = true) +class CouchbaseTransactionAutoConfiguration { + + @Bean + @ConditionalOnMissingBean + CouchbaseCallbackTransactionManager transactionManager(CouchbaseClientFactory factory) { + return new CouchbaseCallbackTransactionManager(factory); + } + + @Bean + @ConditionalOnMissingBean + TransactionTemplate transactionTemplate(PlatformTransactionManager txManager) { + return new TransactionTemplate(txManager); + } +} diff --git a/spring-modulith-events/spring-modulith-events-couchbase/src/main/java/org/springframework/modulith/events/couchbase/package-info.java b/spring-modulith-events/spring-modulith-events-couchbase/src/main/java/org/springframework/modulith/events/couchbase/package-info.java new file mode 100644 index 000000000..7ba18fc0b --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/src/main/java/org/springframework/modulith/events/couchbase/package-info.java @@ -0,0 +1,5 @@ +/** + * CouchBase integration for {@link org.springframework.modulith.events.core.EventPublicationRepository}. + */ +@org.jspecify.annotations.NullMarked +package org.springframework.modulith.events.couchbase; diff --git a/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/META-INF/LICENSE b/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/META-INF/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/META-INF/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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 + + http://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. diff --git a/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/META-INF/NOTICE b/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/META-INF/NOTICE new file mode 100644 index 000000000..ba40f0538 --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/META-INF/NOTICE @@ -0,0 +1,6 @@ +Spring Modulith ${project.version} +Copyright (c) 2021-2024 Broadcom, Inc. + +This product is licensed to you under the Apache License, Version 2.0 +(the "License"). You may not use this product except in compliance with +the License. diff --git a/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/META-INF/spring-configuration-metadata.json b/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/META-INF/spring-configuration-metadata.json new file mode 100644 index 000000000..81d2a6a7a --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/META-INF/spring-configuration-metadata.json @@ -0,0 +1,10 @@ +{ + "properties": [ + { + "name": "spring.modulith.events.couchbase.transaction-management.enabled", + "type": "java.lang.Boolean", + "description": "Whether to automatically enable transactions for Couchbase.", + "defaultValue": "true" + } + ] +} diff --git a/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports b/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports new file mode 100644 index 000000000..d6b4a44ef --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports @@ -0,0 +1,2 @@ +org.springframework.modulith.events.couchbase.CouchbaseEventPublicationAutoConfiguration +org.springframework.modulith.events.couchbase.CouchbaseTransactionAutoConfiguration diff --git a/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/org/springframework/modulith/events/couchbase/schemas/schema-couchbase-archive.sql b/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/org/springframework/modulith/events/couchbase/schemas/schema-couchbase-archive.sql new file mode 100644 index 000000000..32555fe54 --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/org/springframework/modulith/events/couchbase/schemas/schema-couchbase-archive.sql @@ -0,0 +1,6 @@ +CREATE COLLECTION EVENT_PUBLICATION_ARCHIVE IF NOT EXISTS; + +CREATE INDEX IF NOT EXISTS EVENT_PUBLICATION_ARCHIVE_BY_COMPLETION_DATE_IDX ON EVENT_PUBLICATION_ARCHIVE (completionDate); +CREATE INDEX IF NOT EXISTS EVENT_PUBLICATION_ARCHIVE_BY_STATUS_IDX ON EVENT_PUBLICATION_ARCHIVE (status); +CREATE INDEX IF NOT EXISTS EVENT_PUBLICATION_ARCHIVE_BY_ID_AND_STATUS_IDX ON EVENT_PUBLICATION_ARCHIVE (META().id, status); + diff --git a/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/org/springframework/modulith/events/couchbase/schemas/schema-couchbase.sql b/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/org/springframework/modulith/events/couchbase/schemas/schema-couchbase.sql new file mode 100644 index 000000000..3f4d0c45c --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/src/main/resources/org/springframework/modulith/events/couchbase/schemas/schema-couchbase.sql @@ -0,0 +1,9 @@ +CREATE COLLECTION EVENT_PUBLICATION IF NOT EXISTS; + +CREATE INDEX IF NOT EXISTS EVENT_PUBLICATION_BY_ID_AND_COMPLETION_DATE_ORDER_BY_PUBLICATION_DATE_ASC_IDX ON EVENT_PUBLICATION (META().id, completionDate, publicationDate ASC); +CREATE INDEX IF NOT EXISTS EVENT_PUBLICATION_BY_ID_AND_STATUS_IDX ON EVENT_PUBLICATION (META().id, status); +CREATE INDEX IF NOT EXISTS EVENT_PUBLICATION_BY_STATUS_IDX ON EVENT_PUBLICATION (status); +CREATE INDEX IF NOT EXISTS EVENT_PUBLICATION_BY_PUBLICATION_DATE_IDX ON EVENT_PUBLICATION (publicationDate INCLUDE MISSING); +CREATE INDEX IF NOT EXISTS EVENT_PUBLICATION_BY_COMPLETION_DATE_IDX ON EVENT_PUBLICATION (completionDate); +CREATE INDEX IF NOT EXISTS EVENT_PUBLICATION_BY_COMPLETION_DATE_AND_LISTENER_ID_IDX ON EVENT_PUBLICATION (listenerId, completionDate IS MISSING) WHERE completionDate IS MISSING; +CREATE INDEX IF NOT EXISTS EVENT_PUBLICATION_BY_PUBLICATION_DATE_AND_STATUS_IDX ON EVENT_PUBLICATION (status, publicationDate); \ No newline at end of file diff --git a/spring-modulith-events/spring-modulith-events-couchbase/src/test/java/org/springframework/modulith/events/couchbase/CouchbaseEventPublicationAutoConfigurationIntegrationTests.java b/spring-modulith-events/spring-modulith-events-couchbase/src/test/java/org/springframework/modulith/events/couchbase/CouchbaseEventPublicationAutoConfigurationIntegrationTests.java new file mode 100644 index 000000000..63bbe6718 --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/src/test/java/org/springframework/modulith/events/couchbase/CouchbaseEventPublicationAutoConfigurationIntegrationTests.java @@ -0,0 +1,44 @@ +/* + * Copyright 2022-2026 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.modulith.events.couchbase; + +import static org.assertj.core.api.Assertions.*; + +import org.springframework.data.couchbase.transaction.CouchbaseCallbackTransactionManager; +import org.springframework.modulith.testapp.TestApplication; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.ApplicationContext; +import org.springframework.modulith.events.core.EventPublicationRegistry; + +/** + * @author Oliver Drotbohm + * @author Alexandre Vigneron + */ +@SpringBootTest(classes = TestApplication.class) +class CouchbaseEventPublicationAutoConfigurationIntegrationTests { + + @Autowired ApplicationContext context; + + @Test // GH-4, GH-175 + void bootstrapsApplicationComponents() { + + assertThat(context.getBean(EventPublicationRegistry.class)).isNotNull(); + assertThat(context.getBean(CouchbaseEventPublicationRepository.class)).isNotNull(); + assertThat(context.getBean(CouchbaseCallbackTransactionManager.class)).isNotNull(); + } +} diff --git a/spring-modulith-events/spring-modulith-events-couchbase/src/test/java/org/springframework/modulith/events/couchbase/CouchbaseEventPublicationRepositoryTest.java b/spring-modulith-events/spring-modulith-events-couchbase/src/test/java/org/springframework/modulith/events/couchbase/CouchbaseEventPublicationRepositoryTest.java new file mode 100644 index 000000000..019a82b96 --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/src/test/java/org/springframework/modulith/events/couchbase/CouchbaseEventPublicationRepositoryTest.java @@ -0,0 +1,421 @@ +/* + * Copyright 2022-2026 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.modulith.events.couchbase; + +import static org.assertj.core.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.*; + +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.time.temporal.ChronoUnit; +import java.util.Comparator; +import java.util.List; +import java.util.UUID; + +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.data.couchbase.test.autoconfigure.DataCouchbaseTest; +import org.springframework.context.annotation.Import; +import org.springframework.core.env.Environment; +import org.springframework.data.couchbase.core.CouchbaseTemplate; +import org.springframework.modulith.events.EventPublication.Status; +import org.springframework.modulith.events.core.EventPublicationRepository.FailedCriteria; +import org.springframework.modulith.events.core.PublicationTargetIdentifier; +import org.springframework.modulith.events.core.TargetEventPublication; +import org.springframework.modulith.events.support.CompletionMode; +import org.springframework.modulith.testapp.Infrastructure; +import org.springframework.modulith.testapp.TestApplication; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.TestPropertySource; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * @author Oliver Drotbohm + * @author Alexandre Vigneron + */ +@Testcontainers(disabledWithoutDocker = true) +class CouchbaseEventPublicationRepositoryTest { + + private static final PublicationTargetIdentifier TARGET_IDENTIFIER = PublicationTargetIdentifier.of("listener"); + + @DataCouchbaseTest + @Import(Infrastructure.class) + @ContextConfiguration(classes = TestApplication.class) + static abstract class TestBase { + + @Autowired CouchbaseTemplate couchbaseTemplate; + @Autowired Environment environment; + + CouchbaseEventPublicationRepository repository; + CompletionMode completionMode; + String archiveCollection = CouchbaseEventPublicationRepository.ARCHIVE_COLLECTION; + + @BeforeEach + void setUp() { + this.completionMode = CompletionMode.from(environment); + this.repository = new CouchbaseEventPublicationRepository(couchbaseTemplate, completionMode); + } + + @AfterEach + void tearDown() { + couchbaseTemplate.removeByQuery(CouchbaseEventPublication.class).all(); + couchbaseTemplate.removeByQuery(CouchbaseEventPublication.class).inCollection(archiveCollection).all(); + } + + @Test // GH-4 + void shouldPersistAndUpdateEventPublication() { + + var publication = createPublication(new TestEvent("abc")); + + var eventPublications = repository.findIncompletePublications(); + + assertThat(eventPublications).hasSize(1); + assertThat(eventPublications.get(0).getEvent()).isEqualTo(publication.getEvent()); + assertThat(eventPublications.get(0).getTargetIdentifier()).isEqualTo(publication.getTargetIdentifier()); + + assertThat( + repository.findIncompletePublicationsByEventAndTargetIdentifier(new TestEvent("abc"), TARGET_IDENTIFIER)) + .isPresent(); + + // Complete publication + repository.markCompleted(publication, Instant.now()); + + assertThat(repository.findIncompletePublications()).isEmpty(); + } + + @Test // GH-4 + void shouldUpdateSingleEventPublication() { + + var first = createPublication(new TestEvent("id1")); + var second = createPublication(new TestEvent("id2")); + + repository.markCompleted(second, Instant.now()); + + assertThat(repository.findIncompletePublications()).hasSize(1) + .element(0) + .extracting(TargetEventPublication::getEvent).isEqualTo(first.getEvent()); + } + + @Test // GH-133 + void returnsOldestIncompletePublicationsFirst() { + + var now = LocalDateTime.now(); + + savePublicationAt(now.withHour(3)); + savePublicationAt(now.withHour(0)); + savePublicationAt(now.withHour(1)); + + assertThat(repository.findIncompletePublications()) + .isSortedAccordingTo(Comparator.comparing(TargetEventPublication::getPublicationDate)); + } + + @Test // GH-294 + void findsPublicationsOlderThanReference() throws Exception { + + var first = createPublication(new TestEvent("first")); + + Thread.sleep(100); + + var now = Instant.now(); + var second = createPublication(new TestEvent("second")); + + assertThat(repository.findIncompletePublications()) + .extracting(TargetEventPublication::getIdentifier) + .containsExactly(first.getIdentifier(), second.getIdentifier()); + + assertThat(repository.findIncompletePublicationsPublishedBefore(now)) + .hasSize(1) + .element(0).extracting(TargetEventPublication::getIdentifier).isEqualTo(first.getIdentifier()); + } + + @Test // GH-451 + void findsCompletedPublications() { + + var event = new TestEvent("first"); + var publication = createPublication(event); + + repository.markCompleted(publication, Instant.now()); + + if (completionMode == CompletionMode.DELETE) { + + assertThat(repository.findCompletedPublications()).isEmpty(); + + } else { + + assertThat(repository.findCompletedPublications()) + .hasSize(1) + .element(0) + .extracting(TargetEventPublication::getEvent) + .isEqualTo(event); + } + + } + + @Test // GH-258 + void marksPublicationAsCompletedById() { + + var event = new TestEvent("first"); + var publication = createPublication(event); + + repository.markCompleted(publication.getIdentifier(), Instant.now()); + + assertThat(repository.findIncompletePublications()).isEmpty(); + + if (completionMode == CompletionMode.DELETE) { + + assertThat(repository.findCompletedPublications()).isEmpty(); + + } else { + + assertThat(repository.findCompletedPublications()) + .extracting(TargetEventPublication::getIdentifier) + .containsExactly(publication.getIdentifier()); + } + + if (completionMode == CompletionMode.ARCHIVE) { + assertThat(couchbaseTemplate.findByQuery(CouchbaseEventPublication.class).inCollection(archiveCollection).all()).isNotEmpty(); + } + } + + @Test // GH-4 + void shouldFindEventPublicationByEventAndTargetIdentifier() { + + var first = createPublication(new TestEvent("abc")); + createPublication(new TestEvent("def")); + + var firstEvent = first.getEvent(); + + createPublication(firstEvent, PublicationTargetIdentifier.of("somethingDifferent")); + + var actual = repository.findIncompletePublicationsByEventAndTargetIdentifier(firstEvent, TARGET_IDENTIFIER); + + assertThat(actual).hasValueSatisfying(it -> { + assertThat(it.getEvent()).isEqualTo(firstEvent); + assertThat(it.getTargetIdentifier()).isEqualTo(TARGET_IDENTIFIER); + }); + } + + @Test // GH-4 + void shouldTolerateEmptyResultTest() { + + var testEvent = new TestEvent("id"); + + assertThat(repository.findIncompletePublicationsByEventAndTargetIdentifier(testEvent, TARGET_IDENTIFIER)) + .isEmpty(); + } + + @Test + void shouldNotReturnCompletedEvents() { + + var publication = createPublication(new TestEvent("abc")); + + repository.markCompleted(publication, Instant.now()); + + var actual = repository.findIncompletePublicationsByEventAndTargetIdentifier(publication.getEvent(), + TARGET_IDENTIFIER); + + assertThat(actual).isEmpty(); + } + + @Test // GH-4 + void shouldReturnTheOldestEventTest() throws InterruptedException { + + var publication = createPublication(new TestEvent("id")); + + Thread.sleep(10); + repository.create(publication); + + var actual = repository.findIncompletePublicationsByEventAndTargetIdentifier(publication.getEvent(), + TARGET_IDENTIFIER); + + assertThat(actual).hasValueSatisfying(it -> // + assertThat(it.getPublicationDate()) // + .isCloseTo(publication.getPublicationDate(), within(1, ChronoUnit.MILLIS))); + } + + @Test // GH-20 + void shouldDeleteCompletedEvents() { + + var publication = createPublication(new TestEvent("abc")); + var second = createPublication(new TestEvent("def")); + + repository.markCompleted(publication, Instant.now()); + repository.deleteCompletedPublications(); + + assertThat(couchbaseTemplate.findByQuery(CouchbaseEventPublication.class).all()) // + .hasSize(1) // + .element(0) // + .extracting(it -> it.event) // + .isEqualTo(second.getEvent()); + } + + @Test // GH-251 + void shouldDeleteCompletedEventsBefore() { + + assumeTrue(completionMode == CompletionMode.UPDATE); + + var first = createPublication(new TestEvent("abc")); + var second = createPublication(new TestEvent("def")); + + var now = Instant.now(); + + repository.markCompleted(first, now.minusSeconds(30)); + repository.markCompleted(second, now); + repository.deleteCompletedPublicationsBefore(now.minusSeconds(15)); + + assertThat(couchbaseTemplate.findByQuery(CouchbaseEventPublication.class).all()) // + .hasSize(1) // + .element(0).extracting(it -> it.event).isEqualTo(second.getEvent()); + } + + @Test // GH-294 + void deletesPublicationsByIdentifier() { + + var first = createPublication(new TestEvent("first")); + var second = createPublication(new TestEvent("second")); + + repository.deletePublications(List.of(first.getIdentifier())); + + assertThat(repository.findIncompletePublications()) + .hasSize(1) + .element(0) + .matches(it -> it.getIdentifier().equals(second.getIdentifier())) + .matches(it -> it.getEvent().equals(second.getEvent())); + } + + @Test // GH-1336 + void looksUpFailedPublication() { + + var event = new TestEvent("first"); + var publication = createPublication(event); + + repository.markFailed(publication.getIdentifier()); + + assertThat(repository.findFailedPublications(FailedCriteria.ALL)) + .extracting(TargetEventPublication::getIdentifier) + .containsExactly(publication.getIdentifier()); + } + + @Test // GH-1336 + void claimsResubmissionOnce() { + + var event = new TestEvent("first"); + var publication = createPublication(event); + + repository.markFailed(publication.getIdentifier()); + + var now = Instant.now(); + + assertThat(repository.markResubmitted(publication.getIdentifier(), now)).isTrue(); + assertThat(repository.markResubmitted(publication.getIdentifier(), now)).isFalse(); + } + + @Test // GH-1336 + void countsByStatus() { + + var event = new TestEvent("first"); + var publication = createPublication(event); + + assertOneByStatus(Status.PUBLISHED); + + repository.markFailed(publication.getIdentifier()); + assertOneByStatus(Status.FAILED); + + repository.markResubmitted(publication.getIdentifier(), Instant.now()); + assertOneByStatus(Status.RESUBMITTED); + } + + @Test // GH-1336 + void marksPublicationAsProcessing() { + + var event = new TestEvent("first"); + var publication = createPublication(event); + + repository.markProcessing(publication.getIdentifier()); + } + + @Test // GH-1336 + void looksUpFailedPublicationInBatch() { + + var event = new TestEvent("first"); + var publication = createPublication(event); + + repository.markFailed(publication.getIdentifier()); + + assertThat(repository.findFailedPublications(FailedCriteria.ALL.withItemsToRead(10))) + .extracting(TargetEventPublication::getIdentifier) + .containsExactly(publication.getIdentifier()); + } + + @Test // GH-1321 + void looksUpFailedPublicationWithReferenceDate() throws Exception { + + var event = new TestEvent("first"); + var publication = createPublication(event); + + repository.markFailed(publication.getIdentifier()); + + Thread.sleep(200); + + var criteria = FailedCriteria.ALL + .withPublicationsPublishedBefore(publication.getPublicationDate().plusMillis(50)); + + assertThat(repository.findFailedPublications(criteria)) + .extracting(TargetEventPublication::getIdentifier) + .containsExactly(publication.getIdentifier()); + } + + private TargetEventPublication createPublication(Object event) { + return createPublication(event, TARGET_IDENTIFIER); + } + + private TargetEventPublication createPublication(Object event, PublicationTargetIdentifier id) { + return repository.create(TargetEventPublication.of(event, id)); + } + + private void savePublicationAt(LocalDateTime date) { + + var now = date.toInstant(ZoneOffset.UTC); + var publication = new CouchbaseEventPublication(UUID.randomUUID(), now, "", "", null, Status.PUBLISHED, now, 1); + + couchbaseTemplate.save(publication); + } + + private void assertOneByStatus(Status reference) { + + for (var status : Status.values()) { + assertThat(repository.countByStatus(status)).isEqualTo(status == reference ? 1 : 0); + } + } + } + + @Nested + class WithUpdateCompletionTest extends TestBase {} + + @Nested + @TestPropertySource(properties = CompletionMode.PROPERTY + "=DELETE") + class WithDeleteCompletionTest extends TestBase {} + + @Nested + @TestPropertySource(properties = CompletionMode.PROPERTY + "=ARCHIVE") + class WithArchiveCompletionTest extends TestBase {} + + private record TestEvent(String eventId) {} +} diff --git a/spring-modulith-events/spring-modulith-events-couchbase/src/test/java/org/springframework/modulith/testapp/Infrastructure.java b/spring-modulith-events/spring-modulith-events-couchbase/src/test/java/org/springframework/modulith/testapp/Infrastructure.java new file mode 100644 index 000000000..3a97e7b67 --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/src/test/java/org/springframework/modulith/testapp/Infrastructure.java @@ -0,0 +1,77 @@ +/* + * Copyright 2025-2026 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.modulith.testapp; + +import static com.couchbase.client.core.io.CollectionIdentifier.*; + +import java.time.Duration; +import java.util.Optional; +import java.util.Set; + +import com.fasterxml.jackson.databind.json.JsonMapper; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.springframework.context.annotation.Bean; +import org.testcontainers.couchbase.BucketDefinition; +import org.testcontainers.couchbase.CouchbaseContainer; +import org.testcontainers.utility.DockerImageName; + +import com.couchbase.client.core.env.SeedNode; +import com.couchbase.client.java.Cluster; +import com.couchbase.client.java.ClusterOptions; + +/** + * @author Oliver Drotbohm + * @author Alexandre Vigneron + */ +@TestConfiguration(proxyBeanMethods = false) +public class Infrastructure { + private static final String COUCHBASE_USER = "user"; + private static final String COUCHBASE_PASSWORD = "password"; + private static final String BASE_COLLECTION = "EVENT_PUBLICATION"; + private static final String ARCHIVE_COLLECTION = "EVENT_PUBLICATION_ARCHIVE"; + + @Value("${spring.data.couchbase.bucket-name}") + private String bucketName; + + @Bean + @ServiceConnection + CouchbaseContainer couchbaseContainer() { + var container = new CouchbaseContainer(DockerImageName.parse("couchbase/server:latest")) + .withBucket(new BucketDefinition(bucketName).withPrimaryIndex(false)) + .withCredentials(COUCHBASE_USER, COUCHBASE_PASSWORD); + + container.start(); + + var seedNodes = Set.of( + SeedNode.create(container.getHost(), Optional.of(container.getBootstrapCarrierDirectPort()), Optional.of(container.getBootstrapHttpDirectPort()) + )); + try (var cluster = Cluster.connect(seedNodes, ClusterOptions.clusterOptions(container.getUsername(), container.getPassword()))) { + cluster.bucket(bucketName).collections().createCollection(DEFAULT_SCOPE, BASE_COLLECTION); + cluster.bucket(bucketName).collections().createCollection(DEFAULT_SCOPE, ARCHIVE_COLLECTION); + cluster.waitUntilReady(Duration.ofMinutes(2)); + } + + return container; + } + + @Bean + JsonMapper jsonMapper() { + return JsonMapper.builder() + .build(); + } +} diff --git a/spring-modulith-events/spring-modulith-events-couchbase/src/test/java/org/springframework/modulith/testapp/TestApplication.java b/spring-modulith-events/spring-modulith-events-couchbase/src/test/java/org/springframework/modulith/testapp/TestApplication.java new file mode 100644 index 000000000..082d6e4ef --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/src/test/java/org/springframework/modulith/testapp/TestApplication.java @@ -0,0 +1,27 @@ +/* + * Copyright 2022-2026 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.modulith.testapp; + +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.context.annotation.Import; + +/** + * @author Oliver Drotbohm + * @author Alexandre Vigneron + */ +@SpringBootApplication +@Import(Infrastructure.class) +public class TestApplication {} diff --git a/spring-modulith-events/spring-modulith-events-couchbase/src/test/resources/application.properties b/spring-modulith-events/spring-modulith-events-couchbase/src/test/resources/application.properties new file mode 100644 index 000000000..0052ecf94 --- /dev/null +++ b/spring-modulith-events/spring-modulith-events-couchbase/src/test/resources/application.properties @@ -0,0 +1 @@ +spring.data.couchbase.bucket-name=modulith \ No newline at end of file diff --git a/spring-modulith-examples/pom.xml b/spring-modulith-examples/pom.xml index 09ca437ac..0cbe575c4 100644 --- a/spring-modulith-examples/pom.xml +++ b/spring-modulith-examples/pom.xml @@ -17,6 +17,7 @@ spring-modulith-example-epr-jdbc + spring-modulith-example-epr-couchbase spring-modulith-example-epr-neo4j diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/.mvn/wrapper/maven-wrapper.jar b/spring-modulith-examples/spring-modulith-example-epr-couchbase/.mvn/wrapper/maven-wrapper.jar new file mode 100644 index 000000000..bf82ff01c Binary files /dev/null and b/spring-modulith-examples/spring-modulith-example-epr-couchbase/.mvn/wrapper/maven-wrapper.jar differ diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/.mvn/wrapper/maven-wrapper.properties b/spring-modulith-examples/spring-modulith-example-epr-couchbase/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 000000000..6caf4740a --- /dev/null +++ b/spring-modulith-examples/spring-modulith-example-epr-couchbase/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,18 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.3/apache-maven-3.9.3-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/mvnw b/spring-modulith-examples/spring-modulith-example-epr-couchbase/mvnw new file mode 100755 index 000000000..b7f064624 --- /dev/null +++ b/spring-modulith-examples/spring-modulith-example-epr-couchbase/mvnw @@ -0,0 +1,287 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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 +# +# http://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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.1.1 +# +# Required ENV vars: +# ------------------ +# JAVA_HOME - location of a JDK home dir +# +# Optional ENV vars +# ----------------- +# MAVEN_OPTS - parameters passed to the Java VM when running Maven +# e.g. to debug Maven itself, use +# set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +# MAVEN_SKIP_RC - flag to disable loading of mavenrc files +# ---------------------------------------------------------------------------- + +if [ -z "$MAVEN_SKIP_RC" ] ; then + + if [ -f /usr/local/etc/mavenrc ] ; then + . /usr/local/etc/mavenrc + fi + + if [ -f /etc/mavenrc ] ; then + . /etc/mavenrc + fi + + if [ -f "$HOME/.mavenrc" ] ; then + . "$HOME/.mavenrc" + fi + +fi + +# OS specific support. $var _must_ be set to either true or false. +cygwin=false; +darwin=false; +mingw=false +case "`uname`" in + CYGWIN*) cygwin=true ;; + MINGW*) mingw=true;; + Darwin*) darwin=true + # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home + # See https://developer.apple.com/library/mac/qa/qa1170/_index.html + if [ -z "$JAVA_HOME" ]; then + if [ -x "/usr/libexec/java_home" ]; then + JAVA_HOME="`/usr/libexec/java_home`"; export JAVA_HOME + else + JAVA_HOME="/Library/Java/Home"; export JAVA_HOME + fi + fi + ;; +esac + +if [ -z "$JAVA_HOME" ] ; then + if [ -r /etc/gentoo-release ] ; then + JAVA_HOME=`java-config --jre-home` + fi +fi + +# For Cygwin, ensure paths are in UNIX format before anything is touched +if $cygwin ; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --unix "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --unix "$CLASSPATH"` +fi + +# For Mingw, ensure paths are in UNIX format before anything is touched +if $mingw ; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" +fi + +if [ -z "$JAVA_HOME" ]; then + javaExecutable="`which javac`" + if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then + # readlink(1) is not available as standard on Solaris 10. + readLink=`which readlink` + if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then + if $darwin ; then + javaHome="`dirname \"$javaExecutable\"`" + javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" + else + javaExecutable="`readlink -f \"$javaExecutable\"`" + fi + javaHome="`dirname \"$javaExecutable\"`" + javaHome=`expr "$javaHome" : '\(.*\)/bin'` + JAVA_HOME="$javaHome" + export JAVA_HOME + fi + fi +fi + +if [ -z "$JAVACMD" ] ; then + if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + else + JAVACMD="`\\unset -f command; \\command -v java`" + fi +fi + +if [ ! -x "$JAVACMD" ] ; then + echo "Error: JAVA_HOME is not defined correctly." >&2 + echo " We cannot execute $JAVACMD" >&2 + exit 1 +fi + +if [ -z "$JAVA_HOME" ] ; then + echo "Warning: JAVA_HOME environment variable is not set." +fi + +# traverses directory structure from process work directory to filesystem root +# first directory with .mvn subdirectory is considered project base directory +find_maven_basedir() { + if [ -z "$1" ] + then + echo "Path not specified to find_maven_basedir" + return 1 + fi + + basedir="$1" + wdir="$1" + while [ "$wdir" != '/' ] ; do + if [ -d "$wdir"/.mvn ] ; then + basedir=$wdir + break + fi + # workaround for JBEAP-8937 (on Solaris 10/Sparc) + if [ -d "${wdir}" ]; then + wdir=`cd "$wdir/.."; pwd` + fi + # end of workaround + done + printf '%s' "$(cd "$basedir"; pwd)" +} + +# concatenates all lines of a file +concat_lines() { + if [ -f "$1" ]; then + echo "$(tr -s '\n' ' ' < "$1")" + fi +} + +BASE_DIR=$(find_maven_basedir "$(dirname $0)") +if [ -z "$BASE_DIR" ]; then + exit 1; +fi + +MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"}; export MAVEN_PROJECTBASEDIR +if [ "$MVNW_VERBOSE" = true ]; then + echo $MAVEN_PROJECTBASEDIR +fi + +########################################################################################## +# Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +# This allows using the maven wrapper in projects that prohibit checking in binary data. +########################################################################################## +if [ -r "$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found .mvn/wrapper/maven-wrapper.jar" + fi +else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Couldn't find .mvn/wrapper/maven-wrapper.jar, downloading it ..." + fi + if [ -n "$MVNW_REPOURL" ]; then + wrapperUrl="$MVNW_REPOURL/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + else + wrapperUrl="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + fi + while IFS="=" read key value; do + case "$key" in (wrapperUrl) wrapperUrl="$value"; break ;; + esac + done < "$BASE_DIR/.mvn/wrapper/maven-wrapper.properties" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Downloading from: $wrapperUrl" + fi + wrapperJarPath="$BASE_DIR/.mvn/wrapper/maven-wrapper.jar" + if $cygwin; then + wrapperJarPath=`cygpath --path --windows "$wrapperJarPath"` + fi + + if command -v wget > /dev/null; then + QUIET="--quiet" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found wget ... using wget" + QUIET="" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + wget $QUIET "$wrapperUrl" -O "$wrapperJarPath" + else + wget $QUIET --http-user="$MVNW_USERNAME" --http-password="$MVNW_PASSWORD" "$wrapperUrl" -O "$wrapperJarPath" + fi + [ $? -eq 0 ] || rm -f "$wrapperJarPath" + elif command -v curl > /dev/null; then + QUIET="--silent" + if [ "$MVNW_VERBOSE" = true ]; then + echo "Found curl ... using curl" + QUIET="" + fi + if [ -z "$MVNW_USERNAME" ] || [ -z "$MVNW_PASSWORD" ]; then + curl $QUIET -o "$wrapperJarPath" "$wrapperUrl" -f -L + else + curl $QUIET --user "$MVNW_USERNAME:$MVNW_PASSWORD" -o "$wrapperJarPath" "$wrapperUrl" -f -L + fi + [ $? -eq 0 ] || rm -f "$wrapperJarPath" + else + if [ "$MVNW_VERBOSE" = true ]; then + echo "Falling back to using Java to download" + fi + javaSource="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.java" + javaClass="$BASE_DIR/.mvn/wrapper/MavenWrapperDownloader.class" + # For Cygwin, switch paths to Windows format before running javac + if $cygwin; then + javaSource=`cygpath --path --windows "$javaSource"` + javaClass=`cygpath --path --windows "$javaClass"` + fi + if [ -e "$javaSource" ]; then + if [ ! -e "$javaClass" ]; then + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Compiling MavenWrapperDownloader.java ..." + fi + # Compiling the Java class + ("$JAVA_HOME/bin/javac" "$javaSource") + fi + if [ -e "$javaClass" ]; then + # Running the downloader + if [ "$MVNW_VERBOSE" = true ]; then + echo " - Running MavenWrapperDownloader.java ..." + fi + ("$JAVA_HOME/bin/java" -cp .mvn/wrapper MavenWrapperDownloader "$MAVEN_PROJECTBASEDIR") + fi + fi + fi +fi +########################################################################################## +# End of extension +########################################################################################## + +MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" + +# For Cygwin, switch paths to Windows format before running java +if $cygwin; then + [ -n "$JAVA_HOME" ] && + JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` + [ -n "$CLASSPATH" ] && + CLASSPATH=`cygpath --path --windows "$CLASSPATH"` + [ -n "$MAVEN_PROJECTBASEDIR" ] && + MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` +fi + +# Provide a "standardized" way to retrieve the CLI args that will +# work with both Windows and non-Windows executions. +MAVEN_CMD_LINE_ARGS="$MAVEN_CONFIG $@" +export MAVEN_CMD_LINE_ARGS + +WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +exec "$JAVACMD" \ + $MAVEN_OPTS \ + $MAVEN_DEBUG_OPTS \ + -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ + "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ + ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/mvnw.cmd b/spring-modulith-examples/spring-modulith-example-epr-couchbase/mvnw.cmd new file mode 100644 index 000000000..474c9d6b7 --- /dev/null +++ b/spring-modulith-examples/spring-modulith-example-epr-couchbase/mvnw.cmd @@ -0,0 +1,187 @@ +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.1.1 +@REM +@REM Required ENV vars: +@REM JAVA_HOME - location of a JDK home dir +@REM +@REM Optional ENV vars +@REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands +@REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a keystroke before ending +@REM MAVEN_OPTS - parameters passed to the Java VM when running Maven +@REM e.g. to debug Maven itself, use +@REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 +@REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files +@REM ---------------------------------------------------------------------------- + +@REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' +@echo off +@REM set title of command window +title %0 +@REM enable echoing by setting MAVEN_BATCH_ECHO to 'on' +@if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% + +@REM set %HOME% to equivalent of $HOME +if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") + +@REM Execute a user defined script before this one +if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre +@REM check for pre script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_pre.bat" call "%USERPROFILE%\mavenrc_pre.bat" %* +if exist "%USERPROFILE%\mavenrc_pre.cmd" call "%USERPROFILE%\mavenrc_pre.cmd" %* +:skipRcPre + +@setlocal + +set ERROR_CODE=0 + +@REM To isolate internal variables from possible post scripts, we use another setlocal +@setlocal + +@REM ==== START VALIDATION ==== +if not "%JAVA_HOME%" == "" goto OkJHome + +echo. +echo Error: JAVA_HOME not found in your environment. >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +:OkJHome +if exist "%JAVA_HOME%\bin\java.exe" goto init + +echo. +echo Error: JAVA_HOME is set to an invalid directory. >&2 +echo JAVA_HOME = "%JAVA_HOME%" >&2 +echo Please set the JAVA_HOME variable in your environment to match the >&2 +echo location of your Java installation. >&2 +echo. +goto error + +@REM ==== END VALIDATION ==== + +:init + +@REM Find the project base dir, i.e. the directory that contains the folder ".mvn". +@REM Fallback to current working directory if not found. + +set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% +IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir + +set EXEC_DIR=%CD% +set WDIR=%EXEC_DIR% +:findBaseDir +IF EXIST "%WDIR%"\.mvn goto baseDirFound +cd .. +IF "%WDIR%"=="%CD%" goto baseDirNotFound +set WDIR=%CD% +goto findBaseDir + +:baseDirFound +set MAVEN_PROJECTBASEDIR=%WDIR% +cd "%EXEC_DIR%" +goto endDetectBaseDir + +:baseDirNotFound +set MAVEN_PROJECTBASEDIR=%EXEC_DIR% +cd "%EXEC_DIR%" + +:endDetectBaseDir + +IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig + +@setlocal EnableExtensions EnableDelayedExpansion +for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a +@endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% + +:endReadAdditionalConfig + +SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" +set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" +set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain + +set WRAPPER_URL="https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + +FOR /F "usebackq tokens=1,2 delims==" %%A IN ("%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.properties") DO ( + IF "%%A"=="wrapperUrl" SET WRAPPER_URL=%%B +) + +@REM Extension to allow automatically downloading the maven-wrapper.jar from Maven-central +@REM This allows using the maven wrapper in projects that prohibit checking in binary data. +if exist %WRAPPER_JAR% ( + if "%MVNW_VERBOSE%" == "true" ( + echo Found %WRAPPER_JAR% + ) +) else ( + if not "%MVNW_REPOURL%" == "" ( + SET WRAPPER_URL="%MVNW_REPOURL%/org/apache/maven/wrapper/maven-wrapper/3.1.1/maven-wrapper-3.1.1.jar" + ) + if "%MVNW_VERBOSE%" == "true" ( + echo Couldn't find %WRAPPER_JAR%, downloading it ... + echo Downloading from: %WRAPPER_URL% + ) + + powershell -Command "&{"^ + "$webclient = new-object System.Net.WebClient;"^ + "if (-not ([string]::IsNullOrEmpty('%MVNW_USERNAME%') -and [string]::IsNullOrEmpty('%MVNW_PASSWORD%'))) {"^ + "$webclient.Credentials = new-object System.Net.NetworkCredential('%MVNW_USERNAME%', '%MVNW_PASSWORD%');"^ + "}"^ + "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; $webclient.DownloadFile('%WRAPPER_URL%', '%WRAPPER_JAR%')"^ + "}" + if "%MVNW_VERBOSE%" == "true" ( + echo Finished downloading %WRAPPER_JAR% + ) +) +@REM End of extension + +@REM Provide a "standardized" way to retrieve the CLI args that will +@REM work with both Windows and non-Windows executions. +set MAVEN_CMD_LINE_ARGS=%* + +%MAVEN_JAVA_EXE% ^ + %JVM_CONFIG_MAVEN_PROPS% ^ + %MAVEN_OPTS% ^ + %MAVEN_DEBUG_OPTS% ^ + -classpath %WRAPPER_JAR% ^ + "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" ^ + %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* +if ERRORLEVEL 1 goto error +goto end + +:error +set ERROR_CODE=1 + +:end +@endlocal & set ERROR_CODE=%ERROR_CODE% + +if not "%MAVEN_SKIP_RC%"=="" goto skipRcPost +@REM check for post script, once with legacy .bat ending and once with .cmd ending +if exist "%USERPROFILE%\mavenrc_post.bat" call "%USERPROFILE%\mavenrc_post.bat" +if exist "%USERPROFILE%\mavenrc_post.cmd" call "%USERPROFILE%\mavenrc_post.cmd" +:skipRcPost + +@REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' +if "%MAVEN_BATCH_PAUSE%"=="on" pause + +if "%MAVEN_TERMINATE_CMD%"=="on" exit %ERROR_CODE% + +cmd /C exit /B %ERROR_CODE% diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/pom.xml b/spring-modulith-examples/spring-modulith-example-epr-couchbase/pom.xml new file mode 100644 index 000000000..19743c8cb --- /dev/null +++ b/spring-modulith-examples/spring-modulith-example-epr-couchbase/pom.xml @@ -0,0 +1,56 @@ + + + 4.0.0 + + + org.springframework.modulith + spring-modulith-examples + 2.2.0-SNAPSHOT + ../pom.xml + + + spring-modulith-example-epr-couchbase + Spring Modulith - Examples - EPR Couchbase Example + + + + + org.springframework.modulith + spring-modulith-starter-couchbase + + + + + + org.jmolecules + jmolecules-events + + + + + + org.springframework.boot + spring-boot-starter-data-couchbase + + + + org.testcontainers + testcontainers-junit-jupiter + test + + + + org.testcontainers + testcontainers-couchbase + test + + + + org.springframework.boot + spring-boot-testcontainers + test + + + + + diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/asciidoc/index.adoc b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/asciidoc/index.adoc new file mode 100644 index 000000000..bab583d64 --- /dev/null +++ b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/asciidoc/index.adoc @@ -0,0 +1,16 @@ += Spring Modulith Example Documentation +:modulith-docs: ../../../target/spring-modulith-docs + +== Overview + +plantuml::{modulith-docs}/components.puml[format="svg"] + +== Inventory + +plantuml::{modulith-docs}/module-inventory.puml[format="svg"] +include::{modulith-docs}/module-inventory.adoc[] + +== Orders + +plantuml::{modulith-docs}/module-order.puml[format="svg"] +include::{modulith-docs}/module-order.adoc[] diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/Application.java b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/Application.java new file mode 100644 index 000000000..aaa1900e9 --- /dev/null +++ b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/Application.java @@ -0,0 +1,38 @@ +/* + * Copyright 2022-2026 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 example; + +import example.order.OrderManagement; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * Spring Modulith example application + * + * @author Oliver Drotbohm + * @author Alexandre Vigneron + */ +@SpringBootApplication +public class Application { + + public static void main(String... args) { + + var context = SpringApplication.run(Application.class, args); + + context.getBean(OrderManagement.class).complete(); + } +} diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/inventory/InventoryManagement.java b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/inventory/InventoryManagement.java new file mode 100644 index 000000000..646c8a3cf --- /dev/null +++ b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/inventory/InventoryManagement.java @@ -0,0 +1,54 @@ +/* + * Copyright 2022-2026 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 example.inventory; + +import example.order.OrderCompleted; +import lombok.RequiredArgsConstructor; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.modulith.events.ApplicationModuleListener; +import org.springframework.stereotype.Service; + +/** + * A Spring {@link Service} exposed by the inventory module. + * + * @author Oliver Drotbohm + * @author Alexandre Vigneron + */ +@Service +@RequiredArgsConstructor +class InventoryManagement { + + private static final Logger LOG = LoggerFactory.getLogger(InventoryManagement.class); + + private final ApplicationEventPublisher events; + + @ApplicationModuleListener + void on(OrderCompleted event) throws InterruptedException { + + var orderId = event.orderId(); + + LOG.info("Received order completion for {}.", orderId); + + // Simulate busy work + Thread.sleep(1000); + events.publishEvent(new InventoryUpdated(orderId)); + + LOG.info("Finished order completion for {}.", orderId); + } +} diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/inventory/InventoryUpdated.java b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/inventory/InventoryUpdated.java new file mode 100644 index 000000000..a19223862 --- /dev/null +++ b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/inventory/InventoryUpdated.java @@ -0,0 +1,24 @@ +/* + * Copyright 2023-2026 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 example.inventory; + +import java.util.UUID; + +/** + * @author Oliver Drotbohm + * @author Alexandre Vigneron + */ +public record InventoryUpdated(UUID orderId) {} diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/inventory/package-info.java b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/inventory/package-info.java new file mode 100644 index 000000000..e4ed115fe --- /dev/null +++ b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/inventory/package-info.java @@ -0,0 +1,8 @@ +/** + * The logical application module inventory implemented as a single-package module. Allows to hide application + * components inside the module by using package scoped types. + * + * @see example.inventory.InventoryInternal + */ +@org.jspecify.annotations.NullMarked +package example.inventory; diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/order/OrderCompleted.java b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/order/OrderCompleted.java new file mode 100644 index 000000000..f18ad3d47 --- /dev/null +++ b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/order/OrderCompleted.java @@ -0,0 +1,26 @@ +/* + * Copyright 2022-2026 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 example.order; + +import java.util.UUID; + +import org.jmolecules.event.types.DomainEvent; + +/** + * @author Oliver Drotbohm + * @author Alexandre Vigneron + */ +public record OrderCompleted(UUID orderId) implements DomainEvent {} diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/order/OrderManagement.java b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/order/OrderManagement.java new file mode 100644 index 000000000..575e086c9 --- /dev/null +++ b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/order/OrderManagement.java @@ -0,0 +1,41 @@ +/* + * Copyright 2022-2026 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 example.order; + +import lombok.NonNull; +import lombok.RequiredArgsConstructor; + +import java.util.UUID; + +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * @author Oliver Drotbohm + * @author Alexandre Vigneron + */ +@Service +@RequiredArgsConstructor +public class OrderManagement { + + private final @NonNull ApplicationEventPublisher events; + + @Transactional + public void complete() { + events.publishEvent(new OrderCompleted(UUID.randomUUID())); + } +} diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/order/package-info.java b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/order/package-info.java new file mode 100644 index 000000000..62bc46dcc --- /dev/null +++ b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/main/java/example/order/package-info.java @@ -0,0 +1,8 @@ +/** + * The logical application module order implemented as a multi-package module. Internal components located in nested + * packages are prevented from being accessed by the {@link org.springframework.modulith.core.ApplicationModules} type. + * + * @see example.ModularityTests + */ +@org.jspecify.annotations.NullMarked +package example.order; diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/test/java/example/ApplicationIntegrationTests.java b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/test/java/example/ApplicationIntegrationTests.java new file mode 100644 index 000000000..1ced5d9dc --- /dev/null +++ b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/test/java/example/ApplicationIntegrationTests.java @@ -0,0 +1,112 @@ +/* + * Copyright 2022-2026 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 example; + +import com.couchbase.client.core.env.SeedNode; +import com.couchbase.client.java.Cluster; +import com.couchbase.client.java.ClusterOptions; +import example.inventory.InventoryUpdated; +import example.order.OrderManagement; + +import java.time.Duration; +import java.util.Collection; +import java.util.Optional; +import java.util.Set; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.context.TestConfiguration; +import org.springframework.boot.testcontainers.service.connection.ServiceConnection; +import org.springframework.context.annotation.Bean; +import org.springframework.modulith.events.core.EventPublicationRegistry; +import org.springframework.modulith.test.EnableScenarios; +import org.springframework.modulith.test.Scenario; +import org.testcontainers.couchbase.BucketDefinition; +import org.testcontainers.couchbase.CouchbaseContainer; +import org.testcontainers.junit.jupiter.Testcontainers; + +import org.testcontainers.utility.DockerImageName; + +import static com.couchbase.client.core.io.CollectionIdentifier.DEFAULT_SCOPE; + +/** + * Integration test for the overall application. + * + * @author Oliver Drotbohm + * @author Alexandre Vigneron + */ +@SpringBootTest +@EnableScenarios +@Testcontainers(disabledWithoutDocker = true) +class ApplicationIntegrationTests { + + public static void main(String[] args) { + + SpringApplication.from(Application::main) + .with(CouchbaseInfrastructureConfiguration.class) + .run(args) + .getApplicationContext(); + } + + @TestConfiguration + static class CouchbaseInfrastructureConfiguration { + private static final String COUCHBASE_USER = "user"; + private static final String COUCHBASE_PASSWORD = "password"; + private static final String BASE_COLLECTION = "EVENT_PUBLICATION"; + private static final String ARCHIVE_COLLECTION = "EVENT_PUBLICATION_ARCHIVE"; + + @Value("${spring.data.couchbase.bucket-name}") + private String bucketName; + + @Bean + @ServiceConnection + CouchbaseContainer couchbaseContainer() { + var container = new CouchbaseContainer(DockerImageName.parse("couchbase/server:latest")) + .withBucket(new BucketDefinition(bucketName).withPrimaryIndex(false)) + .withCredentials(COUCHBASE_USER, COUCHBASE_PASSWORD); + + container.start(); + + var seedNodes = Set.of( + SeedNode.create(container.getHost(), Optional.of(container.getBootstrapCarrierDirectPort()), Optional.of(container.getBootstrapHttpDirectPort()) + )); + try (var cluster = Cluster.connect(seedNodes, ClusterOptions.clusterOptions(container.getUsername(), container.getPassword()))) { + cluster.bucket(bucketName).collections().createCollection(DEFAULT_SCOPE, BASE_COLLECTION); + cluster.bucket(bucketName).collections().createCollection(DEFAULT_SCOPE, ARCHIVE_COLLECTION); + cluster.waitUntilReady(Duration.ofMinutes(2)); + } + + return container; + } + } + + @Autowired OrderManagement orders; + @Autowired EventPublicationRegistry registry; + + @Test + @Disabled("Skipped because it doesn't work for now with propagation level REQUIRE_NEW") + void bootstrapsApplication(Scenario scenario) throws Exception { + + scenario.stimulate(() -> orders.complete()) + .andWaitForStateChange(() -> registry.findIncompletePublications(), Collection::isEmpty) + .andExpect(InventoryUpdated.class) + .toArrive(); + } +} diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/test/java/example/ModularityTests.java b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/test/java/example/ModularityTests.java new file mode 100644 index 000000000..addf2a819 --- /dev/null +++ b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/test/java/example/ModularityTests.java @@ -0,0 +1,41 @@ +/* + * Copyright 2022-2026 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 example; + +import org.junit.jupiter.api.Test; +import org.springframework.modulith.core.ApplicationModules; +import org.springframework.modulith.docs.Documenter; + +/** + * Tests to verify the modular structure and generate documentation for the modules. + * + * @author Oliver Drotbohm + * @author Alexandre Vigneron + */ +class ModularityTests { + + ApplicationModules modules = ApplicationModules.of(Application.class); + + @Test + void verifiesModularStructure() { + modules.verify(); + } + + @Test + void createModuleDocumentation() { + new Documenter(modules).writeDocumentation(); + } +} diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/test/resources/application.properties b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/test/resources/application.properties new file mode 100644 index 000000000..0052ecf94 --- /dev/null +++ b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/test/resources/application.properties @@ -0,0 +1 @@ +spring.data.couchbase.bucket-name=modulith \ No newline at end of file diff --git a/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/test/resources/logback.xml b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/test/resources/logback.xml new file mode 100644 index 000000000..6dfe47de9 --- /dev/null +++ b/spring-modulith-examples/spring-modulith-example-epr-couchbase/src/test/resources/logback.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/spring-modulith-starters/pom.xml b/spring-modulith-starters/pom.xml index 91f3fd2dd..5af3d8dda 100644 --- a/spring-modulith-starters/pom.xml +++ b/spring-modulith-starters/pom.xml @@ -15,6 +15,7 @@ spring-modulith-starter-core + spring-modulith-starter-couchbase spring-modulith-starter-insight spring-modulith-starter-jdbc spring-modulith-starter-jpa diff --git a/spring-modulith-starters/spring-modulith-starter-couchbase/pom.xml b/spring-modulith-starters/spring-modulith-starter-couchbase/pom.xml new file mode 100644 index 000000000..d6dead560 --- /dev/null +++ b/spring-modulith-starters/spring-modulith-starter-couchbase/pom.xml @@ -0,0 +1,53 @@ + + + 4.0.0 + + + org.springframework.modulith + spring-modulith-starters + 2.2.0-SNAPSHOT + ../pom.xml + + + spring-modulith-starter-couchbase + Spring Modulith - Starters - Starter Couchbase + + + spring.modulith.starter.couchbase + + + + + + org.springframework.modulith + spring-modulith-starter-core + 2.2.0-SNAPSHOT + + + + + org.springframework.modulith + spring-modulith-events-api + 2.2.0-SNAPSHOT + + + org.springframework.modulith + spring-modulith-events-core + 2.2.0-SNAPSHOT + runtime + + + org.springframework.modulith + spring-modulith-events-jackson + 2.2.0-SNAPSHOT + runtime + + + org.springframework.modulith + spring-modulith-events-couchbase + 2.2.0-SNAPSHOT + runtime + + + + diff --git a/spring-modulith-starters/spring-modulith-starter-couchbase/src/main/resources/META-INF/LICENSE b/spring-modulith-starters/spring-modulith-starter-couchbase/src/main/resources/META-INF/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/spring-modulith-starters/spring-modulith-starter-couchbase/src/main/resources/META-INF/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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 + + http://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. diff --git a/spring-modulith-starters/spring-modulith-starter-couchbase/src/main/resources/META-INF/NOTICE b/spring-modulith-starters/spring-modulith-starter-couchbase/src/main/resources/META-INF/NOTICE new file mode 100644 index 000000000..ba40f0538 --- /dev/null +++ b/spring-modulith-starters/spring-modulith-starter-couchbase/src/main/resources/META-INF/NOTICE @@ -0,0 +1,6 @@ +Spring Modulith ${project.version} +Copyright (c) 2021-2024 Broadcom, Inc. + +This product is licensed to you under the Apache License, Version 2.0 +(the "License"). You may not use this product except in compliance with +the License. diff --git a/src/docs/antora/modules/ROOT/pages/appendix.adoc b/src/docs/antora/modules/ROOT/pages/appendix.adoc index fc406c043..837c971d5 100644 --- a/src/docs/antora/modules/ROOT/pages/appendix.adoc +++ b/src/docs/antora/modules/ROOT/pages/appendix.adoc @@ -1,6 +1,7 @@ [[appendix]] = Appendix :jdbc-schema-base: partial$spring-modulith-events-jdbc-src/main/resources/org/springframework/modulith/events/jdbc/schemas +:couchbase-schema-base: partial$spring-modulith-events-couchbase-src/main/resources/org/springframework/modulith/events/couchbase/schemas [appendix] [[compatibility-matrix]] @@ -272,6 +273,7 @@ a|* `spring-modulith-docs` |`spring-modulith-events-amqp`|`runtime`|Event externalization support for AMQP. |`spring-modulith-events-api`|`runtime`|API to customize the event features of Spring Modulith. |`spring-modulith-events-core`|`runtime`|The core implementation of the event publication registry as well as the integration abstractions `EventPublicationRegistry` and `EventPublicationSerializer`. +|`spring-modulith-events-couchbase`|`runtime`|A Couchbase-based implementation of the `EventPublicationRegistry`. |`spring-modulith-events-jackson`|`runtime`|A Jackson-based implementation of the `EventPublicationSerializer`. |`spring-modulith-events-jdbc`|`runtime`|A JDBC-based implementation of the `EventPublicationRegistry`. |`spring-modulith-events-jms`|`runtime`|Event externalization support for JMS. @@ -292,8 +294,8 @@ a|* `spring-modulith-docs` [[schemas]] == Event publication registry schemas -The JDBC-based event publication registry support expects the following database schemas to be present in the database. -If you would like Spring Modulith to create the schema for you, set the application property `spring.modulith.events.jdbc-schema-initialization.enabled` to `true`. +The JDBC-based and Couchbase-based event publication registry support expects the following database operations to be executed on the database. +If you would like Spring Modulith to create the schema for you (JDBC-only), set the application property `spring.modulith.events.jdbc-schema-initialization.enabled` to `true`. [[schemas.h2]] === H2 @@ -481,6 +483,23 @@ include::{jdbc-schema-base}/v1/schema-postgresql.sql[] include::{jdbc-schema-base}/v1/schema-postgresql-archive.sql[] ---- +[[schemas.couchbase]] +=== Couchbase + +These operations need to be executed inside an existing bucket + +.Standard schema +[source, sql] +---- +include::{couchbase-schema-base}/schema-couchbase.sql[] +---- + +.Archive-enabled schema +[source, sql] +---- +include::{couchbase-schema-base}/schema-couchbase-archive.sql[] +---- + [appendix] [[migrating-from-moduliths]] == Migrating from Moduliths diff --git a/src/docs/antora/modules/ROOT/pages/events.adoc b/src/docs/antora/modules/ROOT/pages/events.adoc index 71bdb6e0f..9efa2b298 100644 --- a/src/docs/antora/modules/ROOT/pages/events.adoc +++ b/src/docs/antora/modules/ROOT/pages/events.adoc @@ -300,6 +300,10 @@ The following starters are available: |`spring-modulith-starter-jdbc` |Using JDBC as persistence technology. Also works in JPA-based applications but bypasses your JPA provider for actual event persistence. +|Couchbase +|`spring-modulith-starter-couchbase` +|Using Couchbase as persistence technology. Also enables Couchbase transactions. The transaction auto-configuration can be disabled by setting the `spring.modulith.events.couchbase.transaction-management.enabled` property to `false`. + |MongoDB |`spring-modulith-starter-mongodb` |Using MongoDB as persistence technology. Also enables MongoDB transactions and requires a replica set setup of the server to interact with. The transaction auto-configuration can be disabled by setting the `spring.modulith.events.mongodb.transaction-management.enabled` property to `false`. @@ -369,7 +373,7 @@ Contrary to the `DELETE` mode, completed event publications are then still acces [[publication-registry.publication-repositories]] === Event Publication Repositories -To actually write the event publication log, Spring Modulith exposes an `EventPublicationRepository` SPI and implementations for popular persistence technologies that support transactions, like JPA, JDBC and MongoDB. +To actually write the event publication log, Spring Modulith exposes an `EventPublicationRepository` SPI and implementations for popular persistence technologies that support transactions, like JPA, JDBC, Couchbase and MongoDB. You select the persistence technology to be used by adding the corresponding JAR to your Spring Modulith application. We have prepared dedicated xref:events.adoc#starters[starters] to ease that task. @@ -377,6 +381,9 @@ The JDBC-based implementation will create a dedicated table for the event public The schema creation will of course also back off if the required tables already exist, for example if created via database migration tools such as Flyway or Liquibase. For details, please consult the xref:appendix.adoc#schemas[schema overview] in the appendix. +The Couchbase-based implementation will need collections and indexes for the event publication log. +For details, please consult the xref:appendix.adoc#schemas.couchbase[couchbase schemas] in the appendix. + [[publication-registry.serialization]] === Event Serializer diff --git a/src/docs/antora/modules/ROOT/partials/spring-modulith-events-couchbase-src b/src/docs/antora/modules/ROOT/partials/spring-modulith-events-couchbase-src new file mode 120000 index 000000000..e740dba9a --- /dev/null +++ b/src/docs/antora/modules/ROOT/partials/spring-modulith-events-couchbase-src @@ -0,0 +1 @@ +../../../../../../spring-modulith-events/spring-modulith-events-couchbase/src \ No newline at end of file