-
Notifications
You must be signed in to change notification settings - Fork 0
[#6] Event Store service: Kafka -> PostgreSQL persistence #118
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| # Event Store Service | ||
|
|
||
| `event-store-service` реализует Issue #6: читает события из Kafka (`user.login.events`) и сохраняет их в PostgreSQL (`audit.events`). | ||
|
|
||
| ## Что внутри | ||
|
|
||
| - Kafka consumer (`UserLoginEventConsumer`) | ||
| - Преобразование `AuditEvent` -> `StoredAuditEvent` | ||
| - Расчет `SHA-256` хэша payload (`event_hash`) | ||
| - Сохранение через Spring Data R2DBC | ||
| - Flyway миграции в `src/main/resources/db/migration` | ||
|
|
||
| ## Быстрый запуск | ||
|
|
||
| Из каталога `backend/`: | ||
|
|
||
| ```bash | ||
| mvn spring-boot:run -pl event-store-service -am | ||
| ``` | ||
|
|
||
| ## Тесты | ||
|
|
||
| Из каталога `backend/`: | ||
|
|
||
| ```bash | ||
| mvn -pl event-store-service test | ||
| ``` | ||
|
|
||
| Интеграционный сценарий Kafka -> PostgreSQL покрыт тестом | ||
| `EventStoreKafkaToPostgresIntegrationTest` на Testcontainers. | ||
| Если Docker недоступен, этот тест будет автоматически пропущен. | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
16 changes: 16 additions & 0 deletions
16
...e-service/src/main/java/lt/satsyuk/distributed/audit/eventstore/config/JacksonConfig.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| package lt.satsyuk.distributed.audit.eventstore.config; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import com.fasterxml.jackson.databind.json.JsonMapper; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
|
|
||
| @Configuration | ||
| public class JacksonConfig { | ||
|
|
||
| @Bean | ||
| public ObjectMapper objectMapper() { | ||
| return JsonMapper.builder().findAndAddModules().build(); | ||
| } | ||
| } | ||
|
|
49 changes: 49 additions & 0 deletions
49
...ice/src/main/java/lt/satsyuk/distributed/audit/eventstore/config/KafkaListenerConfig.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| package lt.satsyuk.distributed.audit.eventstore.config; | ||
|
|
||
| import lt.satsyuk.distributed.audit.event.AuditEvent; | ||
| import lt.satsyuk.distributed.audit.event.UserLoggedInEvent; | ||
| import org.apache.kafka.clients.consumer.ConsumerConfig; | ||
| import org.apache.kafka.common.serialization.StringDeserializer; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
| import org.springframework.context.annotation.Bean; | ||
| import org.springframework.context.annotation.Configuration; | ||
| import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; | ||
| import org.springframework.kafka.core.ConsumerFactory; | ||
| import org.springframework.kafka.core.DefaultKafkaConsumerFactory; | ||
| import org.springframework.kafka.support.serializer.JsonDeserializer; | ||
|
|
||
| import java.util.HashMap; | ||
| import java.util.Map; | ||
|
|
||
| @Configuration | ||
| public class KafkaListenerConfig { | ||
|
|
||
| @Bean | ||
| public ConsumerFactory<String, AuditEvent> consumerFactory( | ||
| @Value("${spring.kafka.bootstrap-servers}") String bootstrapServers, | ||
| @Value("${spring.kafka.consumer.group-id:event-store-consumer}") String groupId | ||
| ) { | ||
| Map<String, Object> props = new HashMap<>(); | ||
| props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); | ||
| props.put(ConsumerConfig.GROUP_ID_CONFIG, groupId); | ||
| props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); | ||
| props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); | ||
| props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, JsonDeserializer.class); | ||
| props.put(JsonDeserializer.TRUSTED_PACKAGES, "lt.satsyuk.distributed.audit.event"); | ||
| props.put(JsonDeserializer.USE_TYPE_INFO_HEADERS, false); | ||
| props.put(JsonDeserializer.VALUE_DEFAULT_TYPE, UserLoggedInEvent.class.getName()); | ||
|
|
||
| return new DefaultKafkaConsumerFactory<>(props); | ||
| } | ||
|
|
||
| @Bean(name = "kafkaListenerContainerFactory") | ||
| public ConcurrentKafkaListenerContainerFactory<String, AuditEvent> kafkaListenerContainerFactory( | ||
| ConsumerFactory<String, AuditEvent> consumerFactory | ||
| ) { | ||
| ConcurrentKafkaListenerContainerFactory<String, AuditEvent> factory = | ||
| new ConcurrentKafkaListenerContainerFactory<>(); | ||
| factory.setConsumerFactory(consumerFactory); | ||
| return factory; | ||
| } | ||
| } | ||
|
|
||
14 changes: 14 additions & 0 deletions
14
...e/src/main/java/lt/satsyuk/distributed/audit/eventstore/config/KafkaTopicsProperties.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| package lt.satsyuk.distributed.audit.eventstore.config; | ||
|
|
||
| import lombok.Getter; | ||
| import lombok.Setter; | ||
| import org.springframework.boot.context.properties.ConfigurationProperties; | ||
|
|
||
| @ConfigurationProperties(prefix = "kafka.topics") | ||
| @Getter | ||
| @Setter | ||
| public class KafkaTopicsProperties { | ||
|
|
||
| private String userLoginEvents = "user.login.events"; | ||
| } | ||
|
igorsatsyuk marked this conversation as resolved.
|
||
|
|
||
47 changes: 47 additions & 0 deletions
47
...rc/main/java/lt/satsyuk/distributed/audit/eventstore/consumer/UserLoginEventConsumer.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| package lt.satsyuk.distributed.audit.eventstore.consumer; | ||
|
|
||
| import lt.satsyuk.distributed.audit.event.AuditEvent; | ||
| import lt.satsyuk.distributed.audit.event.UserLoggedInEvent; | ||
| import lt.satsyuk.distributed.audit.eventstore.config.KafkaTopicsProperties; | ||
| import lt.satsyuk.distributed.audit.eventstore.service.EventPersistenceService; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
| import org.springframework.kafka.annotation.KafkaListener; | ||
| import org.springframework.messaging.handler.annotation.Header; | ||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import static org.springframework.kafka.support.KafkaHeaders.RECEIVED_KEY; | ||
|
|
||
| @Component | ||
| public class UserLoginEventConsumer { | ||
|
|
||
| private static final Logger log = LoggerFactory.getLogger(UserLoginEventConsumer.class); | ||
|
|
||
| private final EventPersistenceService eventPersistenceService; | ||
| private final KafkaTopicsProperties kafkaTopicsProperties; | ||
|
|
||
| public UserLoginEventConsumer( | ||
| EventPersistenceService eventPersistenceService, | ||
| KafkaTopicsProperties kafkaTopicsProperties | ||
| ) { | ||
| this.eventPersistenceService = eventPersistenceService; | ||
| this.kafkaTopicsProperties = kafkaTopicsProperties; | ||
| } | ||
|
|
||
| @KafkaListener(topics = "${kafka.topics.user-login-events}") | ||
| public void consume(AuditEvent event, @Header(value = RECEIVED_KEY, required = false) String key) { | ||
| if (!(event instanceof UserLoggedInEvent userLoggedInEvent)) { | ||
| log.warn("Skipping unsupported event type from topic [{}], key=[{}]", kafkaTopicsProperties.getUserLoginEvents(), key); | ||
| return; | ||
| } | ||
|
|
||
| try { | ||
| // Keep Kafka offset handling aligned with DB write result. | ||
| eventPersistenceService.persist(userLoggedInEvent).block(); | ||
| } catch (RuntimeException ex) { | ||
| log.error("Failed to persist event key=[{}]", key, ex); | ||
| throw new IllegalStateException("Failed to persist event key=[" + key + "]", ex); | ||
| } | ||
| } | ||
| } | ||
|
|
42 changes: 42 additions & 0 deletions
42
...service/src/main/java/lt/satsyuk/distributed/audit/eventstore/model/StoredAuditEvent.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| package lt.satsyuk.distributed.audit.eventstore.model; | ||
|
|
||
| import io.r2dbc.postgresql.codec.Json; | ||
| import lombok.Getter; | ||
| import lombok.Setter; | ||
| import org.springframework.data.annotation.Id; | ||
| import org.springframework.data.relational.core.mapping.Column; | ||
| import org.springframework.data.relational.core.mapping.Table; | ||
|
|
||
| import java.time.LocalDateTime; | ||
|
|
||
| @Table(schema = "audit", name = "events") | ||
| @Getter | ||
| @Setter | ||
| public class StoredAuditEvent { | ||
|
|
||
| @Id | ||
| private Long id; | ||
|
|
||
| @Column("event_id") | ||
| private String eventId; | ||
|
|
||
| @Column("aggregate_id") | ||
| private String aggregateId; | ||
|
|
||
| @Column("event_type") | ||
| private String eventType; | ||
|
|
||
| @Column("user_id") | ||
| private String userId; | ||
|
|
||
| @Column("payload") | ||
| private Json payload; | ||
|
|
||
| @Column("event_hash") | ||
| private String eventHash; | ||
|
|
||
| @Column("created_at") | ||
| private LocalDateTime createdAt; | ||
|
|
||
| } | ||
|
|
8 changes: 8 additions & 0 deletions
8
...n/java/lt/satsyuk/distributed/audit/eventstore/repository/StoredAuditEventRepository.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| package lt.satsyuk.distributed.audit.eventstore.repository; | ||
|
|
||
| import lt.satsyuk.distributed.audit.eventstore.model.StoredAuditEvent; | ||
| import org.springframework.data.repository.reactive.ReactiveCrudRepository; | ||
|
|
||
| public interface StoredAuditEventRepository extends ReactiveCrudRepository<StoredAuditEvent, Long> { | ||
| } | ||
|
|
30 changes: 30 additions & 0 deletions
30
...rvice/src/main/java/lt/satsyuk/distributed/audit/eventstore/service/EventHashService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| package lt.satsyuk.distributed.audit.eventstore.service; | ||
|
|
||
| import org.springframework.stereotype.Component; | ||
|
|
||
| import java.nio.charset.StandardCharsets; | ||
| import java.security.MessageDigest; | ||
| import java.security.NoSuchAlgorithmException; | ||
|
|
||
| @Component | ||
| public class EventHashService { | ||
|
|
||
| public String sha256Hex(String payload) { | ||
| try { | ||
| MessageDigest digest = MessageDigest.getInstance("SHA-256"); | ||
| byte[] hash = digest.digest(payload.getBytes(StandardCharsets.UTF_8)); | ||
| return bytesToHex(hash); | ||
| } catch (NoSuchAlgorithmException ex) { | ||
| throw new IllegalStateException("SHA-256 is not available", ex); | ||
| } | ||
| } | ||
|
|
||
| private String bytesToHex(byte[] bytes) { | ||
| StringBuilder result = new StringBuilder(bytes.length * 2); | ||
| for (byte value : bytes) { | ||
| result.append(String.format("%02x", value)); | ||
| } | ||
| return result.toString(); | ||
| } | ||
| } | ||
|
|
91 changes: 91 additions & 0 deletions
91
...rc/main/java/lt/satsyuk/distributed/audit/eventstore/service/EventPersistenceService.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,91 @@ | ||
| package lt.satsyuk.distributed.audit.eventstore.service; | ||
|
|
||
| import com.fasterxml.jackson.core.JsonProcessingException; | ||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import io.r2dbc.postgresql.codec.Json; | ||
| import lt.satsyuk.distributed.audit.event.AuditEvent; | ||
| import lt.satsyuk.distributed.audit.event.UserLoggedInEvent; | ||
| import lt.satsyuk.distributed.audit.eventstore.model.StoredAuditEvent; | ||
| import lt.satsyuk.distributed.audit.eventstore.repository.StoredAuditEventRepository; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
| import org.springframework.dao.DataAccessResourceFailureException; | ||
| import org.springframework.dao.DuplicateKeyException; | ||
| import org.springframework.stereotype.Service; | ||
| import reactor.core.publisher.Mono; | ||
| import reactor.util.retry.Retry; | ||
|
|
||
| import java.time.Duration; | ||
| import java.time.Instant; | ||
| import java.time.LocalDateTime; | ||
| import java.time.ZoneOffset; | ||
|
|
||
| @Service | ||
| public class EventPersistenceService { | ||
|
|
||
| private static final Logger log = LoggerFactory.getLogger(EventPersistenceService.class); | ||
|
|
||
| private final ObjectMapper objectMapper; | ||
| private final EventHashService eventHashService; | ||
| private final StoredAuditEventRepository repository; | ||
|
|
||
| public EventPersistenceService( | ||
| ObjectMapper objectMapper, | ||
| EventHashService eventHashService, | ||
| StoredAuditEventRepository repository | ||
| ) { | ||
| this.objectMapper = objectMapper; | ||
| this.eventHashService = eventHashService; | ||
| this.repository = repository; | ||
| } | ||
|
|
||
| public Mono<StoredAuditEvent> persist(AuditEvent event) { | ||
| return Mono.fromCallable(() -> toEntity(event)) | ||
| .flatMap(repository::save) | ||
| .doOnSuccess(saved -> { | ||
| if (saved != null) { | ||
| log.debug("Saved event [{}] to audit.events", saved.getEventId()); | ||
| } | ||
| }) | ||
| .retryWhen(Retry.backoff(3, Duration.ofMillis(200)) | ||
| .filter(DataAccessResourceFailureException.class::isInstance)) | ||
| .onErrorResume(DuplicateKeyException.class, ignored -> { | ||
| log.info("Event [{}] already persisted, skipping duplicate", event.getEventId()); | ||
| return Mono.empty(); | ||
| }); | ||
| } | ||
|
|
||
| private StoredAuditEvent toEntity(AuditEvent event) throws JsonProcessingException { | ||
| String payloadJson = objectMapper.writeValueAsString(event); | ||
| String aggregateId = resolveAggregateId(event); | ||
|
|
||
| StoredAuditEvent entity = new StoredAuditEvent(); | ||
| entity.setEventId(event.getEventId()); | ||
| entity.setAggregateId(aggregateId); | ||
| entity.setEventType(event.getEventType().name()); | ||
| entity.setUserId(resolveUserId(event)); | ||
| entity.setPayload(Json.of(payloadJson)); | ||
| entity.setEventHash(eventHashService.sha256Hex(payloadJson)); | ||
| entity.setCreatedAt(LocalDateTime.ofInstant(resolveTimestamp(event), ZoneOffset.UTC)); | ||
| return entity; | ||
| } | ||
|
|
||
| private String resolveAggregateId(AuditEvent event) { | ||
| if (event instanceof UserLoggedInEvent userLoggedInEvent && userLoggedInEvent.getUserId() != null) { | ||
| return "user:" + userLoggedInEvent.getUserId(); | ||
| } | ||
| return event.getEventId(); | ||
| } | ||
|
|
||
| private String resolveUserId(AuditEvent event) { | ||
| if (event instanceof UserLoggedInEvent userLoggedInEvent) { | ||
| return userLoggedInEvent.getUserId(); | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| private Instant resolveTimestamp(AuditEvent event) { | ||
| return event.getOccurredAt() != null ? event.getOccurredAt() : Instant.now(); | ||
| } | ||
| } | ||
|
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.