feat: services-log stores, purges and serves admin audit events

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-11-30 15:53:17 +08:00
1 parent 10f59c5ca8
commit d715073ab2
10 files changed
+505 -1

No files matched your search

@@ -38,6 +38,11 @@ public class PubSubConfig {
@Value("${pubsub.response-time-log.subscription}")
public String responseTimeLogSubscription;
@Value("${pubsub.audit-event.topic}")
public String auditEventTopic;
@Value("${pubsub.audit-event.subscription}")
public String auditEventSubscription;
@Value("${pubsub.error-log.topic}")
public String errorLogTopic;
@@ -56,6 +61,9 @@ public class PubSubConfig {
if (pubSubAdmin.getTopic(responseTimeLogTopic) == null) {
pubSubAdmin.createTopic(responseTimeLogTopic);
}
if (pubSubAdmin.getTopic(auditEventTopic) == null) {
pubSubAdmin.createTopic(auditEventTopic);
}
if (pubSubAdmin.getTopic(errorLogTopic) == null) {
pubSubAdmin.createTopic(errorLogTopic);
}
@@ -82,6 +90,15 @@ public class PubSubConfig {
.build();
subscriptionAdminClient.createSubscription(request);
}
if (pubSubAdmin.getSubscription(auditEventSubscription) == null) {
Subscription request = Subscription.newBuilder()
.setTopic(PROJECTS_PREFIX + projectId + TOPICS_PREFIX + auditEventTopic)
.setName(PROJECTS_PREFIX + projectId + SUBSCRIPTIONS_PREFIX + auditEventSubscription)
.setRetainAckedMessages(true)
.setExpirationPolicy(ExpirationPolicy.newBuilder().setTtl(com.google.protobuf.Duration.newBuilder().setSeconds(31536000)).build())
.build();
subscriptionAdminClient.createSubscription(request);
}
if (pubSubAdmin.getSubscription(errorLogSubscription) == null) {
Subscription request = Subscription.newBuilder()
.setTopic(PROJECTS_PREFIX + projectId + TOPICS_PREFIX + errorLogTopic)
@@ -111,6 +128,15 @@ public class PubSubConfig {
adapter.setAckMode(AckMode.MANUAL);
return adapter;
}
@Bean
public PubSubInboundChannelAdapter auditEventSubscriptionChannelAdapter(
@Qualifier("auditEventSubscriptionChannel") MessageChannel inputChannel, PubSubTemplate pubSubTemplate) {
PubSubInboundChannelAdapter adapter = new PubSubInboundChannelAdapter(pubSubTemplate, auditEventSubscription);
adapter.setOutputChannel(inputChannel);
adapter.setAckMode(AckMode.MANUAL);
return adapter;
}
// @Bean
// public PubSubInboundChannelAdapter errorLogSubscriptionChannelAdapter(
// @Qualifier("errorLogSubscriptionChannel") MessageChannel inputChannel, PubSubTemplate pubSubTemplate) {
@@ -129,6 +155,10 @@ public class PubSubConfig {
public MessageChannel reponseTimeLogSubscriptionChannel() {
return new DirectChannel();
}
@Bean
public MessageChannel auditEventSubscriptionChannel() {
return new DirectChannel();
}
// @Bean
// public MessageChannel errorLogSubscriptionChannel() {
// return new DirectChannel();
@@ -0,0 +1,69 @@
package com.solvway.services.log.controller;
import com.solvway.services.log.model.AuditEventLog;
import com.solvway.services.log.repo.AuditEventLogRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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 org.springframework.web.server.ResponseStatusException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
import java.util.Map;
@RestController
@RequestMapping("/log/audit")
public class AuditEventController {
public record SearchRequest(String actor, String module, String action, String outcome,
String from, String to, Integer page, Integer size) {
}
private final AuditEventLogRepository repository;
public AuditEventController(AuditEventLogRepository repository) {
this.repository = repository;
}
@PostMapping("/search")
public Map<String, Object> search(@RequestBody SearchRequest r) {
int p = r.page() == null || r.page() < 0 ? 0 : r.page();
int s = r.size() == null || r.size() < 1 ? 20 : Math.min(r.size(), 100);
LocalDateTime from = day(r.from(), 0);
LocalDateTime to = day(r.to(), 1);
Page<AuditEventLog> page = repository.search(blankToNull(r.actor()), blankToNull(r.module()),
blankToNull(r.action()), blankToNull(r.outcome()), from, to,
PageRequest.of(p, s, Sort.by(Sort.Direction.DESC, "occurredAt", "id")));
return Map.of("content", page.getContent(), "totalElements", page.getTotalElements(), "number", p, "size", s);
}
@GetMapping("/{id}")
public AuditEventLog get(@PathVariable Long id) {
return repository.findById(id)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "No audit event " + id));
}
private static String blankToNull(String v) {
return v == null || v.isBlank() ? null : v;
}
/** yyyy-MM-dd to that day's start plus plusDays; blank is null; malformed is 400. */
private static LocalDateTime day(String v, int plusDays) {
if (v == null || v.isBlank()) {
return null;
}
try {
return LocalDate.parse(v.trim()).plusDays(plusDays).atStartOfDay();
} catch (DateTimeParseException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Dates must be yyyy-MM-dd");
}
}
}
@@ -0,0 +1,34 @@
package com.solvway.services.log.model;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
/** Maps `service-log`.`audit_event` as created by the OpenSpec change SQL; the app never runs DDL. */
@Entity
@Table(name = "audit_event")
@Getter
@Setter
public class AuditEventLog {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long companyId;
private LocalDateTime occurredAt;
private String actor;
private String module;
private String action;
private String httpMethod;
private String pathTemplate;
private String targetId;
private String outcome;
private Integer httpStatus;
private String clientIp;
private String changes;
}
@@ -4,7 +4,10 @@ import com.google.cloud.spring.pubsub.support.BasicAcknowledgeablePubsubMessage;
import com.google.cloud.spring.pubsub.support.GcpPubSubHeaders;
import com.solvway.core.enums.GeneralEnum;
import com.solvway.core.utils.PubSubUtil;
import com.solvway.core.model.AuditEvent;
import com.solvway.services.log.model.AuditEventLog;
import com.solvway.services.log.model.BackOfficeAccessLog;
import com.solvway.services.log.repo.AuditEventLogRepository;
import com.solvway.services.log.model.ResponseTime;
import com.solvway.services.log.repo.BackOfficeAccessLogRepository;
import com.solvway.services.log.service.ResponseTimeService;
@@ -70,6 +73,45 @@ public class PubSubListener {
};
}
@Bean
@ServiceActivator(inputChannel = "auditEventSubscriptionChannel")
public MessageHandler auditEventMessageReceiver(AuditEventLogRepository repository) {
return message -> {
try {
pubSubUtil.checkMessageId(redisUtil.getRedisTemplate(), message.getHeaders());
AuditEvent e = pubSubUtil.convertToOriginalObject(message.getPayload(), AuditEvent.class);
AuditEventLog row = new AuditEventLog();
row.setCompanyId(e.getCompanyId());
row.setOccurredAt(e.getOccurredAt());
row.setActor(clip(e.getActor(), 191));
row.setModule(clip(e.getModule(), 64));
row.setAction(clip(e.getAction(), 128));
row.setHttpMethod(clip(e.getHttpMethod(), 16));
row.setPathTemplate(clip(e.getPathTemplate(), 255));
row.setTargetId(clip(e.getTargetId(), 128));
row.setOutcome(clip(e.getOutcome(), 16));
row.setHttpStatus(e.getHttpStatus());
row.setClientIp(clip(e.getClientIp(), 64));
row.setChanges(e.getChanges());
repository.save(row);
} catch (Exception ex) {
// Class only: the payload carries actors and IPs.
log.error("Audit event not stored: {}", ex.getClass().getName());
} finally {
BasicAcknowledgeablePubsubMessage originalMessage = message.getHeaders()
.get(GcpPubSubHeaders.ORIGINAL_MESSAGE, BasicAcknowledgeablePubsubMessage.class);
if (originalMessage != null) {
originalMessage.ack();
}
}
};
}
/** Column widths of audit_event: over-long text is cut so the insert cannot fail. */
private static String clip(String v, int max) {
return v == null || v.length() <= max ? v : v.substring(0, max);
}
private void updateAppSession(ResponseTime bean) {
try {
if (bean.getSourcePlatform().equals(GeneralEnum.CmsPlatform.APP)
@@ -0,0 +1,31 @@
package com.solvway.services.log.repo;
import com.solvway.services.log.model.AuditEventLog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
public interface AuditEventLogRepository extends JpaRepository<AuditEventLog, Long> {
/** A null filter is ignored; {@code to} is exclusive. */
@Query("select e from AuditEventLog e where (:actor is null or e.actor = :actor)"
+ " and (:module is null or e.module = :module) and (:action is null or e.action = :action)"
+ " and (:outcome is null or e.outcome = :outcome)"
+ " and (:from is null or e.occurredAt >= :from)"
+ " and (:to is null or e.occurredAt < :to)")
Page<AuditEventLog> search(@Param("actor") String actor, @Param("module") String module,
@Param("action") String action, @Param("outcome") String outcome,
@Param("from") LocalDateTime from, @Param("to") LocalDateTime to, Pageable pageable);
/** Deletes up to {@code limit} old rows; each call is its own transaction. */
@Transactional
@Modifying
@Query(value = "DELETE FROM audit_event WHERE occurred_at < :cutoff LIMIT :limit", nativeQuery = true)
int deleteBatchOlderThan(@Param("cutoff") LocalDateTime cutoff, @Param("limit") int limit);
}
@@ -0,0 +1,37 @@
package com.solvway.services.log.service;
import com.solvway.services.log.repo.AuditEventLogRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
@Component
public class AuditEventLogPurge {
private static final Logger log = LoggerFactory.getLogger(AuditEventLogPurge.class);
private static final int BATCH = 5000;
private final AuditEventLogRepository repository;
private final int retentionDays;
public AuditEventLogPurge(AuditEventLogRepository repository,
@Value("${audit.retention-days:${AUDIT_RETENTION_DAYS:730}}") int retentionDays) {
this.repository = repository;
this.retentionDays = retentionDays;
}
@Scheduled(cron = "0 30 3 * * *")
public void purge() {
LocalDateTime cutoff = LocalDateTime.now().minusDays(retentionDays);
long total = 0;
int n;
do {
n = repository.deleteBatchOlderThan(cutoff, BATCH);
total += n;
} while (n > 0);
log.info("Audit purge deleted {} rows older than {}", total, cutoff);
}
}