|
| 1 | +package com.ject.vs.analytics; |
| 2 | + |
| 3 | +import org.slf4j.Logger; |
| 4 | +import org.slf4j.LoggerFactory; |
| 5 | +import org.springframework.http.MediaType; |
| 6 | +import org.springframework.http.client.SimpleClientHttpRequestFactory; |
| 7 | +import org.springframework.scheduling.annotation.Async; |
| 8 | +import org.springframework.stereotype.Component; |
| 9 | +import org.springframework.web.client.RestClient; |
| 10 | +import org.springframework.web.util.UriComponentsBuilder; |
| 11 | + |
| 12 | +import java.time.Duration; |
| 13 | +import java.util.LinkedHashMap; |
| 14 | +import java.util.List; |
| 15 | +import java.util.Map; |
| 16 | +import java.util.UUID; |
| 17 | + |
| 18 | +/** |
| 19 | + * 행동 로그를 GA4(Google Analytics 4)로도 전송하는 어댑터. |
| 20 | + * |
| 21 | + * <p>RDB(analytics_events) 적재와 별개로, PM·디자이너가 GA4 대시보드에서 같은 이벤트를 |
| 22 | + * 실시간으로 볼 수 있게 한다. 서버 사이드라 SDK가 아니라 |
| 23 | + * <a href="https://developers.google.com/analytics/devguides/collection/protocol/ga4">GA4 Measurement Protocol</a> |
| 24 | + * (HTTP POST)로 전송한다. |
| 25 | + * |
| 26 | + * <p>설계 원칙(기존 {@link AnalyticsEventLogger}와 동일): |
| 27 | + * <ul> |
| 28 | + * <li><b>비즈니스에 영향 없음</b> — 모든 예외를 삼키고, 미설정 시 no-op.</li> |
| 29 | + * <li><b>요청 지연 없음</b> — 외부 HTTP라 {@code @Async}로 분리(fire-and-forget). |
| 30 | + * 호출 스레드에서 필요한 값(clientId/userId/params)을 모두 인자로 받으므로 |
| 31 | + * 비동기 스레드에 요청 컨텍스트가 없어도 안전하다.</li> |
| 32 | + * </ul> |
| 33 | + */ |
| 34 | +@Component |
| 35 | +public class GoogleAnalyticsClient { |
| 36 | + |
| 37 | + /** 전송 실패 경고 등 내부 진단용 로거(파일 어펜더는 "analytics" 로거명 공유). */ |
| 38 | + private static final Logger log = LoggerFactory.getLogger("analytics"); |
| 39 | + |
| 40 | + /** GA4가 사용자를 '참여(engaged)'로 집계하도록 넣는 최소 참여 시간(ms). */ |
| 41 | + private static final int ENGAGEMENT_TIME_MSEC = 1; |
| 42 | + |
| 43 | + /** GA4 이벤트 파라미터 값 문자열 최대 길이(MP 제약: 100자). */ |
| 44 | + private static final int MAX_VALUE_LENGTH = 100; |
| 45 | + |
| 46 | + private final GoogleAnalyticsProperties properties; |
| 47 | + private final RestClient restClient; |
| 48 | + |
| 49 | + public GoogleAnalyticsClient(GoogleAnalyticsProperties properties, RestClient.Builder builder) { |
| 50 | + this.properties = properties; |
| 51 | + // 외부망 지연이 비동기 스레드를 오래 점유하지 않도록 짧은 타임아웃을 둔다. |
| 52 | + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); |
| 53 | + factory.setConnectTimeout((int) Duration.ofSeconds(2).toMillis()); |
| 54 | + factory.setReadTimeout((int) Duration.ofSeconds(2).toMillis()); |
| 55 | + this.restClient = builder.requestFactory(factory).build(); |
| 56 | + } |
| 57 | + |
| 58 | + @Async("analyticsExecutor") |
| 59 | + public void send(String eventName, Long userId, String anonymousId, boolean member, |
| 60 | + String platform, Map<String, Object> properties) { |
| 61 | + if (!this.properties.isConfigured()) { |
| 62 | + return; |
| 63 | + } |
| 64 | + try { |
| 65 | + Map<String, Object> payload = buildPayload(eventName, userId, anonymousId, member, platform, properties); |
| 66 | + |
| 67 | + String url = UriComponentsBuilder.fromUriString(this.properties.endpoint()) |
| 68 | + .queryParam("measurement_id", this.properties.measurementId()) |
| 69 | + .queryParam("api_secret", this.properties.apiSecret()) |
| 70 | + .build() |
| 71 | + .toUriString(); |
| 72 | + |
| 73 | + restClient.post() |
| 74 | + .uri(url) |
| 75 | + .contentType(MediaType.APPLICATION_JSON) |
| 76 | + .body(payload) |
| 77 | + .retrieve() |
| 78 | + .toBodilessEntity(); |
| 79 | + } catch (Exception e) { |
| 80 | + log.warn("GA4 forwarding failed for '{}': {}", eventName, e.getMessage()); |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + /** |
| 85 | + * GA4 Measurement Protocol 요청 본문을 만든다. (전송 없이 순수 변환 — 테스트 가능) |
| 86 | + * |
| 87 | + * <pre>{@code |
| 88 | + * { "client_id": "...", "user_id": "42", "events": [ { "name": "...", "params": { ... } } ] } |
| 89 | + * }</pre> |
| 90 | + */ |
| 91 | + Map<String, Object> buildPayload(String eventName, Long userId, String anonymousId, boolean member, |
| 92 | + String platform, Map<String, Object> properties) { |
| 93 | + Map<String, Object> event = new LinkedHashMap<>(); |
| 94 | + event.put("name", eventName); |
| 95 | + event.put("params", buildParams(member, platform, properties)); |
| 96 | + |
| 97 | + Map<String, Object> payload = new LinkedHashMap<>(); |
| 98 | + // client_id는 필수. 비회원 쿠키(anonymous_id)를 우선 사용해 가입 전후 흐름을 한 사용자로 잇는다. |
| 99 | + payload.put("client_id", resolveClientId(anonymousId, userId)); |
| 100 | + if (userId != null) { |
| 101 | + payload.put("user_id", String.valueOf(userId)); |
| 102 | + } |
| 103 | + payload.put("events", List.of(event)); |
| 104 | + return payload; |
| 105 | + } |
| 106 | + |
| 107 | + private Map<String, Object> buildParams(boolean member, String platform, Map<String, Object> properties) { |
| 108 | + Map<String, Object> params = new LinkedHashMap<>(); |
| 109 | + params.put("engagement_time_msec", ENGAGEMENT_TIME_MSEC); |
| 110 | + params.put("is_member", member); |
| 111 | + if (platform != null) { |
| 112 | + params.put("platform", platform); |
| 113 | + } |
| 114 | + if (properties != null) { |
| 115 | + properties.forEach((key, value) -> { |
| 116 | + Object sanitized = sanitize(value); |
| 117 | + if (sanitized != null) { |
| 118 | + params.put(key, sanitized); |
| 119 | + } |
| 120 | + }); |
| 121 | + } |
| 122 | + return params; |
| 123 | + } |
| 124 | + |
| 125 | + /** GA4 파라미터 값 규칙에 맞춘다: null은 제외, 숫자는 그대로, 그 외는 문자열(최대 100자)로. */ |
| 126 | + private Object sanitize(Object value) { |
| 127 | + if (value == null) { |
| 128 | + return null; |
| 129 | + } |
| 130 | + if (value instanceof Number) { |
| 131 | + return value; |
| 132 | + } |
| 133 | + String text = value.toString(); |
| 134 | + return text.length() > MAX_VALUE_LENGTH ? text.substring(0, MAX_VALUE_LENGTH) : text; |
| 135 | + } |
| 136 | + |
| 137 | + /** 익명 쿠키 → 회원 id → 랜덤 UUID 순으로 안정적인 client_id를 고른다. */ |
| 138 | + private String resolveClientId(String anonymousId, Long userId) { |
| 139 | + if (anonymousId != null && !anonymousId.isBlank()) { |
| 140 | + return anonymousId; |
| 141 | + } |
| 142 | + if (userId != null) { |
| 143 | + return "uid." + userId; |
| 144 | + } |
| 145 | + return UUID.randomUUID().toString(); |
| 146 | + } |
| 147 | +} |
0 commit comments