-
Notifications
You must be signed in to change notification settings - Fork 0
Feature / EventLog #138
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
Open
20210815
wants to merge
5
commits into
develop
Choose a base branch
from
feature/page-view-eventlog
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Feature / EventLog #138
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
b935ec8
feat(eventlog): implement Redis-buffered event logging with tests
20210815 c4d7228
fix(config): restore .gitignore and application.yml template
20210815 a1c6e6f
fix(eventlog): add DLQ for parse and DB failures and cover flush sche…
20210815 b774559
fix(eventlog): flush refactor with DLQ handling, auto-unregister inac…
20210815 a7aa513
fix(eventlog): add DLQ and flush refactor with tests; clean up duplic…
20210815 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
63 changes: 63 additions & 0 deletions
63
src/main/java/redot/redot_server/domain/eventlog/controller/EventLogController.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,63 @@ | ||
| package redot.redot_server.domain.eventlog.controller; | ||
|
|
||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.validation.Valid; | ||
| import lombok.AllArgsConstructor; | ||
| import org.springframework.http.ResponseEntity; | ||
| import org.springframework.security.core.annotation.AuthenticationPrincipal; | ||
| import org.springframework.web.bind.annotation.PostMapping; | ||
| import org.springframework.web.bind.annotation.RequestBody; | ||
| import org.springframework.web.bind.annotation.RequestMapping; | ||
| import org.springframework.web.bind.annotation.RestController; | ||
| import redot.redot_server.domain.eventlog.controller.docs.EventLogControllerDocs; | ||
| import redot.redot_server.domain.eventlog.dto.PageViewCommand; | ||
| import redot.redot_server.domain.eventlog.dto.PageViewRequest; | ||
| import redot.redot_server.domain.eventlog.service.EventLogIngestService; | ||
| import redot.redot_server.global.redotapp.resolver.annotation.CurrentRedotApp; | ||
| import redot.redot_server.global.security.principal.JwtPrincipal; | ||
|
|
||
| import java.time.Instant; | ||
| import java.util.UUID; | ||
|
|
||
| @RestController | ||
| @AllArgsConstructor | ||
| @RequestMapping("/api/v1/event-logs") | ||
| public class EventLogController implements EventLogControllerDocs { | ||
|
|
||
| private final EventLogIngestService ingestService; | ||
|
|
||
| /* | ||
| 페이지 뷰 이벤트 수집 엔드포인트 | ||
| */ | ||
| @PostMapping("/page-view") | ||
| public ResponseEntity<Void> pageView( | ||
| @CurrentRedotApp Long redotAppId, | ||
| @Valid @RequestBody PageViewRequest req, | ||
| HttpServletRequest servletRequest, | ||
| @AuthenticationPrincipal JwtPrincipal jwtPrincipal // 없을 수도 있음(비회원) | ||
| ) { | ||
| String ip = extractClientIp(servletRequest); | ||
|
|
||
| PageViewCommand cmd = new PageViewCommand( | ||
| UUID.randomUUID(), | ||
| redotAppId, | ||
| req.deviceType(), | ||
| ip, | ||
| Instant.now() | ||
| ); | ||
|
|
||
| ingestService.ingestPageView(cmd); | ||
| return ResponseEntity.accepted().build(); | ||
| } | ||
|
|
||
| /* | ||
| 클라이언트 IP 추출 | ||
| */ | ||
| private String extractClientIp(HttpServletRequest request) { | ||
| String xff = request.getHeader("X-Forwarded-For"); | ||
| if (xff != null && !xff.isBlank()) return xff.split(",")[0].trim(); | ||
| String xri = request.getHeader("X-Real-IP"); | ||
| if (xri != null && !xri.isBlank()) return xri.trim(); | ||
| return request.getRemoteAddr(); | ||
| } | ||
| } | ||
26 changes: 26 additions & 0 deletions
26
src/main/java/redot/redot_server/domain/eventlog/controller/docs/EventLogControllerDocs.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,26 @@ | ||
| package redot.redot_server.domain.eventlog.controller.docs; | ||
|
|
||
| import io.swagger.v3.oas.annotations.Operation; | ||
| import io.swagger.v3.oas.annotations.Parameter; | ||
| import io.swagger.v3.oas.annotations.enums.ParameterIn; | ||
| import io.swagger.v3.oas.annotations.responses.ApiResponse; | ||
| import io.swagger.v3.oas.annotations.tags.Tag; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import org.springframework.http.ResponseEntity; | ||
| import redot.redot_server.domain.eventlog.dto.PageViewRequest; | ||
| import redot.redot_server.global.security.principal.JwtPrincipal; | ||
|
|
||
| @Tag(name = "EventLogs", description = "이벤트 로그 관리 API") | ||
| public interface EventLogControllerDocs { | ||
| @Parameter(name = "X-App-Subdomain", in = ParameterIn.HEADER, required = true, | ||
| description = "요청 대상 Redot 앱의 서브도메인") | ||
| @Operation(summary = "페이지 뷰 이벤트 수집", | ||
| description = "클라이언트로부터 페이지 뷰 이벤트를 수집합니다.") | ||
| @ApiResponse(responseCode = "202", description = "이벤트 수집 요청 접수 성공") | ||
| ResponseEntity<Void> pageView( | ||
| @Parameter(hidden = true) Long redotAppId, | ||
| @Parameter(hidden = true) PageViewRequest req, | ||
| @Parameter(hidden = true) HttpServletRequest servletRequest, | ||
| @Parameter(hidden = true) JwtPrincipal jwtPrincipal | ||
| ); | ||
| } |
17 changes: 17 additions & 0 deletions
17
src/main/java/redot/redot_server/domain/eventlog/dto/PageViewCommand.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,17 @@ | ||
| package redot.redot_server.domain.eventlog.dto; | ||
|
|
||
| import redot.redot_server.domain.eventlog.entity.DeviceType; | ||
|
|
||
| import java.time.Instant; | ||
| import java.util.UUID; | ||
|
|
||
| public record PageViewCommand( | ||
| UUID eventId, | ||
| Long redotAppId, | ||
| // IdentityType actorType, | ||
| // Long actorId, // nullable | ||
| // String anonymousId, // nullable | ||
| DeviceType deviceType, | ||
| String ip, | ||
| Instant occurredAt | ||
| ) {} |
9 changes: 9 additions & 0 deletions
9
src/main/java/redot/redot_server/domain/eventlog/dto/PageViewRequest.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,9 @@ | ||
| package redot.redot_server.domain.eventlog.dto; | ||
|
|
||
| import jakarta.validation.constraints.NotNull; | ||
| import redot.redot_server.domain.eventlog.entity.DeviceType; | ||
|
|
||
| public record PageViewRequest( | ||
| @NotNull DeviceType deviceType | ||
| //String anonymousId // 비회원이면 프론트에서 UUID 만들어서 넣어주면 좋음 | ||
| ) {} |
7 changes: 7 additions & 0 deletions
7
src/main/java/redot/redot_server/domain/eventlog/entity/DeviceType.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,7 @@ | ||
| package redot.redot_server.domain.eventlog.entity; | ||
|
|
||
| public enum DeviceType { | ||
| MOBILE, | ||
| DESKTOP, | ||
| TABLET | ||
| } |
71 changes: 71 additions & 0 deletions
71
src/main/java/redot/redot_server/domain/eventlog/entity/EventLogEntity.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,71 @@ | ||
| package redot.redot_server.domain.eventlog.entity; | ||
|
|
||
| import jakarta.persistence.*; | ||
| import redot.redot_server.global.common.entity.BaseTimeEntity; | ||
|
|
||
| import java.time.Instant; | ||
| import java.util.UUID; | ||
|
|
||
| @Entity | ||
| @Table(name = "event_logs", | ||
| indexes = { | ||
| @Index(name = "idx_event_logs_app_time", columnList = "redot_app_id, occurred_at"), | ||
| @Index(name = "idx_event_logs_type_time", columnList = "type, occurred_at") | ||
| }, | ||
| uniqueConstraints = { | ||
| @UniqueConstraint(name = "uk_event_logs_event_id", columnNames = "event_id") | ||
| } | ||
| ) | ||
| public class EventLogEntity extends BaseTimeEntity { | ||
|
|
||
| @Id | ||
| @GeneratedValue(strategy = GenerationType.IDENTITY) | ||
| private Long id; // PK | ||
|
|
||
| // UUID를 varchar로 저장 (중복 방지 위함) | ||
| @Column(name = "event_id", nullable = false, updatable = false, length = 36) | ||
| private String eventId; // 이벤트 고유 ID | ||
|
|
||
| @Enumerated(EnumType.STRING) | ||
| @Column(nullable = false, length = 32) | ||
| private EventType type; // 이벤트 유형 | ||
|
|
||
| @Column(name = "redot_app_id", nullable = false) | ||
| private Long redotAppId; // 리닷 앱 ID | ||
|
|
||
| // @Enumerated(EnumType.STRING) | ||
| // @Column(name = "actor_type", nullable = false, length = 32) | ||
| // private IdentityType actorType; | ||
| // | ||
| // @Column(name = "actor_id") | ||
| // private Long actorId; | ||
| // | ||
| // @Column(name = "anonymous_id", length = 64) | ||
| // private String anonymousId; | ||
|
|
||
| @Enumerated(EnumType.STRING) | ||
| @Column(name = "device_type", nullable = false, length = 16) | ||
| private DeviceType deviceType; // 디바이스 유형 | ||
|
|
||
| @Column(nullable = false, length = 64) | ||
| private String ip; // IP 주소 | ||
|
|
||
| @Column(name = "occurred_at", nullable = false) | ||
| private Instant occurredAt; // 이벤트 발생 시각 | ||
|
|
||
| protected EventLogEntity() {} | ||
|
|
||
| public static EventLogEntity pageView(UUID eventId, Long redotAppId, DeviceType deviceType, String ip, Instant occurredAt) { | ||
| EventLogEntity e = new EventLogEntity(); | ||
| e.eventId = eventId.toString(); | ||
| e.type = EventType.PAGE_VIEW; | ||
| e.redotAppId = redotAppId; | ||
| // e.actorType = actorType; | ||
| // e.actorId = actorId; | ||
| // e.anonymousId = anonymousId; | ||
| e.deviceType = deviceType; | ||
| e.ip = ip; | ||
| e.occurredAt = occurredAt; | ||
| return e; | ||
| } | ||
| } |
6 changes: 6 additions & 0 deletions
6
src/main/java/redot/redot_server/domain/eventlog/entity/EventType.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,6 @@ | ||
| package redot.redot_server.domain.eventlog.entity; | ||
|
|
||
| public enum EventType { | ||
| PAGE_VIEW, CTA_CLICK, PURCHASE | ||
| // 조회, 클릭, 구매 | ||
| } |
5 changes: 5 additions & 0 deletions
5
src/main/java/redot/redot_server/domain/eventlog/entity/IdentityType.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,5 @@ | ||
| package redot.redot_server.domain.eventlog.entity; | ||
|
|
||
| public enum IdentityType { | ||
| MEMBER, GUEST | ||
| } |
9 changes: 9 additions & 0 deletions
9
src/main/java/redot/redot_server/domain/eventlog/repository/EventLogRepository.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,9 @@ | ||
| package redot.redot_server.domain.eventlog.repository; | ||
|
|
||
| import org.springframework.data.jpa.repository.JpaRepository; | ||
| import org.springframework.stereotype.Repository; | ||
| import redot.redot_server.domain.eventlog.entity.EventLogEntity; | ||
|
|
||
| @Repository | ||
| public interface EventLogRepository extends JpaRepository<EventLogEntity, Long> { | ||
| } |
135 changes: 135 additions & 0 deletions
135
src/main/java/redot/redot_server/domain/eventlog/service/EventLogFlushScheduler.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,135 @@ | ||
| package redot.redot_server.domain.eventlog.service; | ||
|
|
||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.data.redis.core.StringRedisTemplate; | ||
| import org.springframework.scheduling.annotation.Scheduled; | ||
| import org.springframework.stereotype.Component; | ||
| import redot.redot_server.domain.eventlog.dto.PageViewCommand; | ||
| import redot.redot_server.domain.eventlog.entity.EventLogEntity; | ||
| import redot.redot_server.domain.eventlog.repository.EventLogRepository; | ||
|
|
||
| import java.util.ArrayList; | ||
| import java.util.List; | ||
|
|
||
| @Component | ||
| @RequiredArgsConstructor | ||
| public class EventLogFlushScheduler { | ||
|
|
||
| private final StringRedisTemplate stringRedisTemplate; | ||
| private final EventLogStore eventLogStore; | ||
| private final ObjectMapper objectMapper; | ||
| private final EventLogRepository repo; | ||
|
|
||
| // 한번에 최대 몇 개 flush할지 | ||
| private static final int BATCH_SIZE = 2000; | ||
|
|
||
| /* | ||
| 등록된 모든 redotAppId에 대해 Redis 버퍼에서 이벤트를 읽어와 DB에 저장 | ||
| */ | ||
| @Scheduled(cron = "0 */10 * * * *") | ||
| public void flushAllApps() { | ||
| List<Long> apps = eventLogStore.getRegisteredApps(); | ||
| for (Long appId : apps) { | ||
| flushApp(appId); | ||
| } | ||
| } | ||
20210815 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| /* | ||
| 한 앱에 대해 Redis 버퍼에서 이벤트를 읽어와 DB에 저장 | ||
| */ | ||
|
|
||
| public void flushApp(Long redotAppId) { | ||
| String key = eventLogStore.bufferKey(redotAppId); | ||
|
|
||
| List<String> items = readBatch(key); | ||
| if (items.isEmpty()) { | ||
| eventLogStore.unregisterApp(redotAppId); | ||
| return; | ||
| } | ||
|
|
||
| List<EventLogEntity> entities = parseToEntities(redotAppId, items); | ||
| saveWithDlqFallback(redotAppId, entities); | ||
|
|
||
| trimProcessed(key, items.size()); | ||
| } | ||
|
|
||
| /* | ||
| Redis에서 한 번에 BATCH_SIZE만큼 항목 읽기 | ||
| */ | ||
| private List<String> readBatch(String key) { | ||
| List<String> items = stringRedisTemplate.opsForList().range(key, 0, BATCH_SIZE - 1); | ||
| return (items == null) ? List.of() : items; | ||
| } | ||
|
|
||
| /* | ||
| JSON 문자열 목록을 EventLogEntity 목록으로 변환 | ||
| */ | ||
| private List<EventLogEntity> parseToEntities(Long redotAppId, List<String> items) { | ||
| List<EventLogEntity> entities = new ArrayList<>(items.size()); | ||
| for (String json : items) { | ||
| try { | ||
| PageViewCommand cmd = objectMapper.readValue(json, PageViewCommand.class); | ||
| entities.add(EventLogEntity.pageView( | ||
| cmd.eventId(), | ||
| cmd.redotAppId(), | ||
| cmd.deviceType(), | ||
| cmd.ip(), | ||
| cmd.occurredAt() | ||
| )); | ||
| } catch (Exception e) { | ||
| eventLogStore.pushDeadLetter(redotAppId, json, "PARSE_FAIL: " + e.getMessage()); | ||
| } | ||
| } | ||
| return entities; | ||
| } | ||
|
|
||
| /* | ||
| 여러 엔티티를 개별 저장하며 실패 시 DLQ로 이동 | ||
| */ | ||
| private void saveWithDlqFallback(Long redotAppId, List<EventLogEntity> entities) { | ||
| if (entities.isEmpty()) return; | ||
|
|
||
| try { | ||
| repo.saveAll(entities); | ||
| } catch (Exception e) { | ||
| saveIndividuallyWithDlq(redotAppId, entities); | ||
| } | ||
| } | ||
|
|
||
| /* | ||
| 여러 엔티티를 개별 저장하며 실패 시 DLQ로 이동 | ||
| */ | ||
| private void saveIndividuallyWithDlq(Long redotAppId, List<EventLogEntity> entities) { | ||
| for (EventLogEntity entity : entities) { | ||
| try { | ||
| repo.save(entity); | ||
| } catch (Exception ex) { | ||
| eventLogStore.pushDeadLetter( | ||
| redotAppId, | ||
| safeToJson(entity), | ||
| "DB_SAVE_FAIL: " + ex.getMessage() | ||
| ); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /* | ||
| Redis 리스트에서 앞의 processedCount개 항목 제거 | ||
| */ | ||
| private void trimProcessed(String key, int processedCount) { | ||
| stringRedisTemplate.opsForList().trim(key, processedCount, -1); | ||
| } | ||
|
|
||
| /* | ||
| EventLogEntity를 안전하게 JSON 문자열로 변환 | ||
| */ | ||
| private String safeToJson(EventLogEntity entity) { | ||
| try { | ||
| return objectMapper.writeValueAsString(entity); | ||
| } catch (Exception ignored) { | ||
| return String.valueOf(entity); | ||
| } | ||
| } | ||
|
|
||
| } | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
제가 생각했던 구조는 엔드포인트를
/event와 같이 구성하여body에event_type을 주입하도록 일반화하는 구조였어요.지금과 같은 방식이라면 이벤트 타입이 추가될 때마다 엔드포인트가 추가돼야 하기 때문에 일반화해주시면 감사하겠습니다!