From 8a8bd222b90a01c3874d9d7402ffed5d6a3f2d09 Mon Sep 17 00:00:00 2001 From: M Fari Madyan Date: Fri, 27 Nov 2026 12:43:31 +0700 Subject: [PATCH] feat(exam): record exam-result events in a transactional outbox When an attempt's result becomes final (fully auto-graded on submit, or when the last essay is graded), an "exam.result_ready" event is written to outbox_events in the same transaction as the grade. OutboxRelay publishes pending rows in the background so the student can be e-mailed. - Off by default (APP_NOTIFY_EXAM_RESULTS=false): no outbox beans, no relay, resultReady() is a no-op. Existing deployments behave as before. - Publishers: "log" (local development, default) or "pubsub" (Google Cloud Pub/Sub over REST, authenticated with the VM's service account through the metadata server; no key file). - One event per attempt (unique event_type + aggregate_id); later re-grades do not send it again. Rows are locked with SKIP LOCKED so several instances can run the relay. Failed publishes are retried up to app.outbox.max-attempts. - The score is only included when the exam shows results to students. - V5 migration adds the outbox_events table. Frontend: the backend address Nginx proxies /api and /ws to is now BACKEND_UPSTREAM (default backend:8080, unchanged for Docker Compose), so the same image also works on Cloud Run where both containers share localhost. --- .../common/outbox/EventPublisher.java | 7 ++ .../common/outbox/LoggingEventPublisher.java | 16 +++ .../outbox/MetadataServerTokenProvider.java | 69 +++++++++++ .../elearning/common/outbox/OutboxEvent.java | 58 +++++++++ .../common/outbox/OutboxEventRepository.java | 42 +++++++ .../elearning/common/outbox/OutboxRelay.java | 85 +++++++++++++ .../common/outbox/PubSubRestPublisher.java | 69 +++++++++++ .../com/elearning/config/OutboxConfig.java | 58 +++++++++ .../exam/service/ExamResultEvents.java | 67 ++++++++++ .../exam/service/ExamRunnerService.java | 11 ++ backend/src/main/resources/application.yml | 13 ++ .../db/migration/V5__outbox_events.sql | 20 +++ .../common/outbox/OutboxRelayTest.java | 95 +++++++++++++++ .../outbox/PubSubRestPublisherTest.java | 115 ++++++++++++++++++ .../exam/service/ExamResultEventsTest.java | 88 ++++++++++++++ .../exam/service/ExamRunnerServiceTest.java | 27 +++- frontend/Dockerfile | 4 +- frontend/nginx.conf | 6 +- 18 files changed, 846 insertions(+), 4 deletions(-) create mode 100644 backend/src/main/java/com/elearning/common/outbox/EventPublisher.java create mode 100644 backend/src/main/java/com/elearning/common/outbox/LoggingEventPublisher.java create mode 100644 backend/src/main/java/com/elearning/common/outbox/MetadataServerTokenProvider.java create mode 100644 backend/src/main/java/com/elearning/common/outbox/OutboxEvent.java create mode 100644 backend/src/main/java/com/elearning/common/outbox/OutboxEventRepository.java create mode 100644 backend/src/main/java/com/elearning/common/outbox/OutboxRelay.java create mode 100644 backend/src/main/java/com/elearning/common/outbox/PubSubRestPublisher.java create mode 100644 backend/src/main/java/com/elearning/config/OutboxConfig.java create mode 100644 backend/src/main/java/com/elearning/modules/exam/service/ExamResultEvents.java create mode 100644 backend/src/main/resources/db/migration/V5__outbox_events.sql create mode 100644 backend/src/test/java/com/elearning/common/outbox/OutboxRelayTest.java create mode 100644 backend/src/test/java/com/elearning/common/outbox/PubSubRestPublisherTest.java create mode 100644 backend/src/test/java/com/elearning/modules/exam/service/ExamResultEventsTest.java diff --git a/backend/src/main/java/com/elearning/common/outbox/EventPublisher.java b/backend/src/main/java/com/elearning/common/outbox/EventPublisher.java new file mode 100644 index 0000000..89be947 --- /dev/null +++ b/backend/src/main/java/com/elearning/common/outbox/EventPublisher.java @@ -0,0 +1,7 @@ +package com.elearning.common.outbox; + +/** Sends an outbox event to a message broker. Throwing means "try again later". */ +public interface EventPublisher { + + void publish(OutboxEvent event) throws Exception; +} diff --git a/backend/src/main/java/com/elearning/common/outbox/LoggingEventPublisher.java b/backend/src/main/java/com/elearning/common/outbox/LoggingEventPublisher.java new file mode 100644 index 0000000..2756836 --- /dev/null +++ b/backend/src/main/java/com/elearning/common/outbox/LoggingEventPublisher.java @@ -0,0 +1,16 @@ +package com.elearning.common.outbox; + +import lombok.extern.slf4j.Slf4j; + +/** + * Local development: logs the event instead of sending it. The payload is not logged because it + * contains the student's e-mail address. + */ +@Slf4j +public class LoggingEventPublisher implements EventPublisher { + + @Override + public void publish(OutboxEvent event) { + log.info("Outbox event {} ({} bytes) would be published", event.eventId(), event.getPayload().length()); + } +} diff --git a/backend/src/main/java/com/elearning/common/outbox/MetadataServerTokenProvider.java b/backend/src/main/java/com/elearning/common/outbox/MetadataServerTokenProvider.java new file mode 100644 index 0000000..12862d2 --- /dev/null +++ b/backend/src/main/java/com/elearning/common/outbox/MetadataServerTokenProvider.java @@ -0,0 +1,69 @@ +package com.elearning.common.outbox; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.time.Clock; +import java.time.Duration; +import java.time.Instant; +import java.util.function.Supplier; + +/** + * OAuth access token of the VM's service account, read from the Compute Engine metadata server. + * No key file is involved: the token belongs to the service account attached to the VM, and it is + * cached until a minute before it expires. + */ +public class MetadataServerTokenProvider implements Supplier { + + /** IP instead of metadata.google.internal: works inside containers whatever their DNS setup. */ + public static final String DEFAULT_URL = + "http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token"; + + private final HttpClient httpClient; + private final ObjectMapper objectMapper; + private final URI tokenUri; + private final Clock clock; + + private String token; + private Instant refreshAt = Instant.EPOCH; + + public MetadataServerTokenProvider(HttpClient httpClient, ObjectMapper objectMapper, String tokenUrl, Clock clock) { + this.httpClient = httpClient; + this.objectMapper = objectMapper; + this.tokenUri = URI.create(tokenUrl); + this.clock = clock; + } + + @Override + public synchronized String get() { + if (token != null && clock.instant().isBefore(refreshAt)) { + return token; + } + try { + HttpRequest request = HttpRequest.newBuilder(tokenUri) + .header("Metadata-Flavor", "Google") + .timeout(Duration.ofSeconds(5)) + .GET() + .build(); + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() != 200) { + throw new IllegalStateException("Metadata server returned HTTP " + response.statusCode()); + } + JsonNode body = objectMapper.readTree(response.body()); + token = body.path("access_token").asText(); + long expiresIn = body.path("expires_in").asLong(0); + refreshAt = clock.instant().plusSeconds(Math.max(0, expiresIn - 60)); + return token; + } catch (IOException e) { + throw new IllegalStateException("Could not read an access token from the metadata server: " + e.getMessage(), e); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted while reading an access token", e); + } + } +} diff --git a/backend/src/main/java/com/elearning/common/outbox/OutboxEvent.java b/backend/src/main/java/com/elearning/common/outbox/OutboxEvent.java new file mode 100644 index 0000000..74681ff --- /dev/null +++ b/backend/src/main/java/com/elearning/common/outbox/OutboxEvent.java @@ -0,0 +1,58 @@ +package com.elearning.common.outbox; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.Table; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.time.LocalDateTime; + +/** An event waiting to be published outside the application. See V5__outbox_events.sql. */ +@Entity +@Table(name = "outbox_events") +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class OutboxEvent { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + @Column(name = "event_type", nullable = false, length = 100) + private String eventType; + + @Column(name = "aggregate_id", nullable = false) + private Long aggregateId; + + /** JSON body of the message. */ + @Column(nullable = false, columnDefinition = "TEXT") + private String payload; + + @Column(name = "created_at", nullable = false, insertable = false, updatable = false) + private LocalDateTime createdAt; + + @Column(name = "published_at") + private LocalDateTime publishedAt; + + @Column(nullable = false) + @Builder.Default + private Integer attempts = 0; + + @Column(name = "last_error", length = 500) + private String lastError; + + /** Stable id for consumers that must not act twice on the same event (Pub/Sub delivers at least once). */ + public String eventId() { + return eventType + ":" + aggregateId; + } +} diff --git a/backend/src/main/java/com/elearning/common/outbox/OutboxEventRepository.java b/backend/src/main/java/com/elearning/common/outbox/OutboxEventRepository.java new file mode 100644 index 0000000..fa1c8b9 --- /dev/null +++ b/backend/src/main/java/com/elearning/common/outbox/OutboxEventRepository.java @@ -0,0 +1,42 @@ +package com.elearning.common.outbox; + +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.stereotype.Repository; + +import java.util.List; + +@Repository +public interface OutboxEventRepository extends JpaRepository { + + /** + * Records an event unless one with the same type and aggregate already exists. Never throws on a + * duplicate, so it cannot roll back the transaction that is grading the exam. + * + * @return 1 if the event was recorded, 0 if it already existed + */ + @Modifying + @Query(value = """ + INSERT INTO outbox_events (event_type, aggregate_id, payload) + VALUES (:eventType, :aggregateId, :payload) + ON CONFLICT (event_type, aggregate_id) DO NOTHING + """, nativeQuery = true) + int insertIfAbsent(@Param("eventType") String eventType, + @Param("aggregateId") Long aggregateId, + @Param("payload") String payload); + + /** + * Locks the oldest unpublished events. SKIP LOCKED lets several backend instances run the relay + * at the same time without publishing the same row twice. + */ + @Query(value = """ + SELECT * FROM outbox_events + WHERE published_at IS NULL AND attempts < :maxAttempts + ORDER BY id + LIMIT :limit + FOR UPDATE SKIP LOCKED + """, nativeQuery = true) + List lockPendingBatch(@Param("maxAttempts") int maxAttempts, @Param("limit") int limit); +} diff --git a/backend/src/main/java/com/elearning/common/outbox/OutboxRelay.java b/backend/src/main/java/com/elearning/common/outbox/OutboxRelay.java new file mode 100644 index 0000000..38be20e --- /dev/null +++ b/backend/src/main/java/com/elearning/common/outbox/OutboxRelay.java @@ -0,0 +1,85 @@ +package com.elearning.common.outbox; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.transaction.support.TransactionTemplate; + +import java.time.Clock; +import java.time.LocalDateTime; +import java.util.List; + +/** + * Publishes pending outbox events every few seconds. + * + *
    + *
  • A failed publish leaves the event pending with {@code attempts + 1}; after {@code maxAttempts} + * it is left for an operator (the row keeps the last error).
  • + *
  • Rows are locked with SKIP LOCKED, so several backend instances can run the relay safely.
  • + *
  • Delivery is at least once: a crash between publishing and committing republishes the event. + * Consumers deduplicate on the {@code eventId} attribute.
  • + *
+ * + * Registered by {@code OutboxConfig} only when an outbound event type is enabled. + */ +@Slf4j +public class OutboxRelay { + + private final OutboxEventRepository repository; + private final EventPublisher publisher; + private final TransactionTemplate transactionTemplate; + private final Clock clock; + private final int batchSize; + private final int maxAttempts; + + public OutboxRelay(OutboxEventRepository repository, EventPublisher publisher, TransactionTemplate transactionTemplate, + Clock clock, int batchSize, int maxAttempts) { + this.repository = repository; + this.publisher = publisher; + this.transactionTemplate = transactionTemplate; + this.clock = clock; + this.batchSize = batchSize; + this.maxAttempts = maxAttempts; + } + + @Scheduled(initialDelayString = "${app.outbox.relay-initial-delay-ms:10000}", + fixedDelayString = "${app.outbox.relay-interval-ms:5000}") + public void relay() { + // Keep going while full batches publish cleanly; stop at the first partial or failing batch. + int published; + do { + Integer result = transactionTemplate.execute(status -> publishBatch()); + published = result == null ? 0 : result; + } while (published == batchSize); + } + + /** Publishes one batch inside the caller's transaction. Returns how many events were published. */ + int publishBatch() { + List events = repository.lockPendingBatch(maxAttempts, batchSize); + int published = 0; + for (OutboxEvent event : events) { + try { + publisher.publish(event); + event.setPublishedAt(LocalDateTime.now(clock)); + event.setLastError(null); + published++; + } catch (Exception e) { + event.setAttempts(event.getAttempts() + 1); + event.setLastError(truncate(e.getMessage())); + if (event.getAttempts() >= maxAttempts) { + log.error("Outbox event {} failed {} times and will not be retried: {}", + event.eventId(), event.getAttempts(), event.getLastError()); + } else { + log.warn("Outbox event {} not published (attempt {}): {}", + event.eventId(), event.getAttempts(), event.getLastError()); + } + } + } + repository.saveAll(events); + return published; + } + + private static String truncate(String message) { + if (message == null) return "unknown error"; + return message.length() <= 500 ? message : message.substring(0, 500); + } +} diff --git a/backend/src/main/java/com/elearning/common/outbox/PubSubRestPublisher.java b/backend/src/main/java/com/elearning/common/outbox/PubSubRestPublisher.java new file mode 100644 index 0000000..7c94785 --- /dev/null +++ b/backend/src/main/java/com/elearning/common/outbox/PubSubRestPublisher.java @@ -0,0 +1,69 @@ +package com.elearning.common.outbox; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Base64; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +/** + * Publishes to Google Cloud Pub/Sub through its REST API ({@code topics.publish}). + * + *

The official client library would add gRPC and several megabytes of dependencies for one call + * every few seconds. Retries are already handled by the outbox (a failed publish stays pending), so a + * plain HTTPS request with the VM's service-account token is enough. + */ +public class PubSubRestPublisher implements EventPublisher { + + public static final String DEFAULT_ENDPOINT = "https://pubsub.googleapis.com"; + + private final HttpClient httpClient; + private final ObjectMapper objectMapper; + private final Supplier accessToken; + private final URI publishUri; + + /** + * @param topic full topic name, e.g. {@code projects/my-project/topics/exam-results} + */ + public PubSubRestPublisher(HttpClient httpClient, ObjectMapper objectMapper, Supplier accessToken, + String endpoint, String topic) { + if (topic == null || !topic.matches("projects/[^/]+/topics/[^/]+")) { + throw new IllegalArgumentException( + "app.outbox.pubsub.topic must look like projects//topics/, got: " + topic); + } + this.httpClient = httpClient; + this.objectMapper = objectMapper; + this.accessToken = accessToken; + this.publishUri = URI.create(endpoint.replaceAll("/+$", "") + "/v1/" + topic + ":publish"); + } + + @Override + public void publish(OutboxEvent event) throws Exception { + Map body = Map.of("messages", List.of(Map.of( + "data", Base64.getEncoder().encodeToString(event.getPayload().getBytes(StandardCharsets.UTF_8)), + "attributes", Map.of( + "eventType", event.getEventType(), + "eventId", event.eventId())))); + + HttpRequest request = HttpRequest.newBuilder(publishUri) + .header("Authorization", "Bearer " + accessToken.get()) + .header("Content-Type", "application/json") + .timeout(Duration.ofSeconds(10)) + .POST(HttpRequest.BodyPublishers.ofString(objectMapper.writeValueAsString(body))) + .build(); + + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() / 100 != 2) { + String detail = response.body() == null ? "" : response.body(); + throw new IllegalStateException("Pub/Sub publish failed: HTTP " + response.statusCode() + " " + + detail.substring(0, Math.min(detail.length(), 200))); + } + } +} diff --git a/backend/src/main/java/com/elearning/config/OutboxConfig.java b/backend/src/main/java/com/elearning/config/OutboxConfig.java new file mode 100644 index 0000000..af9bed6 --- /dev/null +++ b/backend/src/main/java/com/elearning/config/OutboxConfig.java @@ -0,0 +1,58 @@ +package com.elearning.config; + +import com.elearning.common.outbox.EventPublisher; +import com.elearning.common.outbox.LoggingEventPublisher; +import com.elearning.common.outbox.MetadataServerTokenProvider; +import com.elearning.common.outbox.OutboxEventRepository; +import com.elearning.common.outbox.OutboxRelay; +import com.elearning.common.outbox.PubSubRestPublisher; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionTemplate; + +import java.net.http.HttpClient; +import java.time.Clock; +import java.time.Duration; + +/** + * Outbound events (transactional outbox). Nothing runs unless + * {@code app.notifications.exam-results.enabled=true}; then {@code app.outbox.publisher} chooses + * {@code log} (local development, default) or {@code pubsub} (Google Cloud Pub/Sub). + */ +@Configuration +@ConditionalOnProperty(name = "app.notifications.exam-results.enabled", havingValue = "true") +public class OutboxConfig { + + @Bean + @ConditionalOnProperty(name = "app.outbox.publisher", havingValue = "log", matchIfMissing = true) + public EventPublisher loggingEventPublisher() { + return new LoggingEventPublisher(); + } + + @Bean + @ConditionalOnProperty(name = "app.outbox.publisher", havingValue = "pubsub") + public EventPublisher pubSubEventPublisher( + ObjectMapper objectMapper, + @Value("${app.outbox.pubsub.topic:}") String topic, + @Value("${app.outbox.pubsub.endpoint:" + PubSubRestPublisher.DEFAULT_ENDPOINT + "}") String endpoint, + @Value("${app.outbox.pubsub.token-url:" + MetadataServerTokenProvider.DEFAULT_URL + "}") String tokenUrl) { + HttpClient httpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(); + MetadataServerTokenProvider tokens = new MetadataServerTokenProvider(httpClient, objectMapper, tokenUrl, Clock.systemUTC()); + return new PubSubRestPublisher(httpClient, objectMapper, tokens, endpoint, topic); + } + + @Bean + public OutboxRelay outboxRelay( + OutboxEventRepository repository, + EventPublisher publisher, + PlatformTransactionManager transactionManager, + @Value("${app.outbox.batch-size:50}") int batchSize, + @Value("${app.outbox.max-attempts:10}") int maxAttempts) { + return new OutboxRelay(repository, publisher, new TransactionTemplate(transactionManager), + Clock.systemDefaultZone(), batchSize, maxAttempts); + } +} diff --git a/backend/src/main/java/com/elearning/modules/exam/service/ExamResultEvents.java b/backend/src/main/java/com/elearning/modules/exam/service/ExamResultEvents.java new file mode 100644 index 0000000..96b9596 --- /dev/null +++ b/backend/src/main/java/com/elearning/modules/exam/service/ExamResultEvents.java @@ -0,0 +1,67 @@ +package com.elearning.modules.exam.service; + +import com.elearning.common.outbox.OutboxEventRepository; +import com.elearning.modules.exam.entity.ExamAttempt; +import com.elearning.modules.exam.entity.Examination; +import com.elearning.modules.user.entity.User; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Records an "exam result ready" event in the outbox when an attempt's result becomes final, so the + * student can be e-mailed. Call it inside the transaction that sets the attempt to {@code completed}: + * the event is then committed or rolled back together with the grade. + * + *

The score is only included when the exam shows results to students ({@code show_result}); otherwise + * the e-mail just says the exam was graded. + */ +@Service +public class ExamResultEvents { + + public static final String RESULT_READY = "exam.result_ready"; + + private final OutboxEventRepository outbox; + private final ObjectMapper objectMapper; + private final boolean enabled; + + public ExamResultEvents(OutboxEventRepository outbox, ObjectMapper objectMapper, + @Value("${app.notifications.exam-results.enabled:false}") boolean enabled) { + this.outbox = outbox; + this.objectMapper = objectMapper; + this.enabled = enabled; + } + + public void resultReady(ExamAttempt attempt) { + if (!enabled) { + return; + } + Examination exam = attempt.getExamination(); + User user = attempt.getStudent().getUser(); + + Map payload = new LinkedHashMap<>(); + payload.put("attemptId", attempt.getId()); + payload.put("examId", exam.getId()); + payload.put("examTitle", exam.getTitle()); + payload.put("studentName", user.getName()); + payload.put("studentEmail", user.getEmail()); + payload.put("showScore", exam.isShowResult()); + if (exam.isShowResult()) { + payload.put("score", attempt.getScore()); + payload.put("passed", attempt.getPassed()); + payload.put("passingScore", exam.getPassingScore()); + } + payload.put("finishedAt", attempt.getFinishedAt() == null ? null : attempt.getFinishedAt().toString()); + + try { + outbox.insertIfAbsent(RESULT_READY, attempt.getId(), objectMapper.writeValueAsString(payload)); + } catch (JsonProcessingException e) { + // Plain maps of strings and numbers always serialize; fail loudly if that ever changes. + throw new IllegalStateException("Could not serialize exam result event", e); + } + } +} diff --git a/backend/src/main/java/com/elearning/modules/exam/service/ExamRunnerService.java b/backend/src/main/java/com/elearning/modules/exam/service/ExamRunnerService.java index 403c394..b052d1b 100644 --- a/backend/src/main/java/com/elearning/modules/exam/service/ExamRunnerService.java +++ b/backend/src/main/java/com/elearning/modules/exam/service/ExamRunnerService.java @@ -37,6 +37,7 @@ public class ExamRunnerService { private final ExamAnswerRepository answerRepository; private final StudentRepository studentRepository; private final ExamRealtimeService realtimeService; + private final ExamResultEvents resultEvents; /** Attempt states after which no more answers are accepted. */ private static final Set FINISHED_STATUSES = EnumSet.of( @@ -276,6 +277,10 @@ public ExamAttempt autoFinalizeAttempt(ExamAttempt attempt, Examination exam) { attempt.setFinishedAt(LocalDateTime.now()); ExamAttempt savedAttempt = attemptRepository.save(attempt); + if (savedAttempt.getStatus() == AttemptStatus.completed) { + // Fully auto-graded: the result is final now. Essays wait for gradeEssay. + resultEvents.resultReady(savedAttempt); + } realtimeService.broadcastExamEvent(exam.getId(), "EXAM_SUBMITTED", Map.of( "attemptId", savedAttempt.getId(), @@ -326,11 +331,17 @@ public void gradeEssay(Long attemptId, Long answerId, EssayGradingDto dto, UserP // The attempt is only complete once every manually graded answer has a grade. boolean stillPending = answers.stream().anyMatch(a -> a.getCorrect() == null); + AttemptStatus previousStatus = attempt.getStatus(); int score = AnswerGrader.scorePercent(totalEarned, totalPossible); attempt.setScore(score); attempt.setPassed(score >= attempt.getExamination().getPassingScore()); attempt.setStatus(stillPending ? AttemptStatus.needs_grading : AttemptStatus.completed); attemptRepository.save(attempt); + + // Announce the result once, when the last pending answer is graded (not on later re-grades). + if (previousStatus != AttemptStatus.completed && attempt.getStatus() == AttemptStatus.completed) { + resultEvents.resultReady(attempt); + } } /** diff --git a/backend/src/main/resources/application.yml b/backend/src/main/resources/application.yml index f0906fc..2dd3f41 100644 --- a/backend/src/main/resources/application.yml +++ b/backend/src/main/resources/application.yml @@ -86,6 +86,19 @@ app: realtime: # local = in-memory STOMP broker of this instance; redis = relay exam events to every instance mode: ${APP_REALTIME_MODE:local} + notifications: + exam-results: + # true = record an "exam result ready" event (transactional outbox) so the student can be e-mailed + enabled: ${APP_NOTIFY_EXAM_RESULTS:false} + outbox: + # log = only log events (local development); pubsub = publish to Google Cloud Pub/Sub + publisher: ${APP_OUTBOX_PUBLISHER:log} + relay-interval-ms: ${APP_OUTBOX_RELAY_INTERVAL_MS:5000} + batch-size: 50 + max-attempts: 10 + pubsub: + # full topic name, e.g. projects/my-project/topics/exam-results + topic: ${APP_OUTBOX_PUBSUB_TOPIC:} exam: finalizer: # Background job that submits attempts whose time ran out while the student was away. diff --git a/backend/src/main/resources/db/migration/V5__outbox_events.sql b/backend/src/main/resources/db/migration/V5__outbox_events.sql new file mode 100644 index 0000000..e4f6e8c --- /dev/null +++ b/backend/src/main/resources/db/migration/V5__outbox_events.sql @@ -0,0 +1,20 @@ +-- V5: transactional outbox for events that leave the application (exam result e-mails via Pub/Sub). +-- +-- The event row is written in the same transaction as the change it describes, so a committed grade +-- always has its event and a rolled-back grade never does. OutboxRelay publishes pending rows later. + +CREATE TABLE outbox_events ( + id BIGSERIAL PRIMARY KEY, + event_type VARCHAR(100) NOT NULL, + aggregate_id BIGINT NOT NULL, + payload TEXT NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT NOW(), + published_at TIMESTAMP, + attempts INT NOT NULL DEFAULT 0, + last_error VARCHAR(500), + -- One event per type and aggregate: an attempt's result is announced once. + CONSTRAINT uq_outbox_event UNIQUE (event_type, aggregate_id) +); + +-- The relay only ever looks for unpublished rows. +CREATE INDEX idx_outbox_events_pending ON outbox_events (id) WHERE published_at IS NULL; diff --git a/backend/src/test/java/com/elearning/common/outbox/OutboxRelayTest.java b/backend/src/test/java/com/elearning/common/outbox/OutboxRelayTest.java new file mode 100644 index 0000000..1eb370b --- /dev/null +++ b/backend/src/test/java/com/elearning/common/outbox/OutboxRelayTest.java @@ -0,0 +1,95 @@ +package com.elearning.common.outbox; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionCallback; +import org.springframework.transaction.support.TransactionTemplate; + +import java.time.Clock; +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZoneOffset; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class OutboxRelayTest { + + private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-11-15T03:00:00Z"), ZoneOffset.UTC); + + private OutboxEventRepository repository; + private EventPublisher publisher; + private TransactionTemplate transactionTemplate; + + @BeforeEach + @SuppressWarnings("unchecked") + void setUp() { + repository = mock(OutboxEventRepository.class); + publisher = mock(EventPublisher.class); + transactionTemplate = mock(TransactionTemplate.class); + // Run the callback directly: the transaction itself is Spring's job, not the relay's. + when(transactionTemplate.execute(any())).thenAnswer(inv -> ((TransactionCallback) inv.getArgument(0)).doInTransaction(null)); + } + + @Test + void marksPublishedEventsAndRetriesFailedOnesLater() throws Exception { + OutboxEvent ok = event(1L, 0); + OutboxEvent failing = event(2L, 3); + when(repository.lockPendingBatch(10, 50)).thenReturn(List.of(ok, failing)); + doThrow(new IllegalStateException("Pub/Sub publish failed: HTTP 503")).when(publisher).publish(failing); + + int published = relay(50).publishBatch(); + + assertEquals(1, published); + assertEquals(LocalDateTime.now(CLOCK), ok.getPublishedAt()); + assertNull(failing.getPublishedAt()); + assertEquals(4, failing.getAttempts()); + assertEquals("Pub/Sub publish failed: HTTP 503", failing.getLastError()); + verify(repository).saveAll(List.of(ok, failing)); + } + + @Test + void keepsRelayingWhileFullBatchesPublishCleanly() { + when(repository.lockPendingBatch(anyInt(), anyInt())) + .thenReturn(List.of(event(1L, 0), event(2L, 0))) + .thenReturn(List.of(event(3L, 0))); + + relay(2).relay(); + + // First batch was full (2 of 2), second was partial (1 of 2): two rounds, then stop. + verify(repository, times(2)).lockPendingBatch(10, 2); + } + + @Test + void stopsAfterABatchWithFailuresInsteadOfHammeringTheBroker() throws Exception { + OutboxEvent failing = event(1L, 0); + when(repository.lockPendingBatch(anyInt(), anyInt())).thenReturn(List.of(failing)); + doThrow(new IllegalStateException("down")).when(publisher).publish(any()); + + relay(1).relay(); + + verify(repository, times(1)).lockPendingBatch(10, 1); + } + + private OutboxRelay relay(int batchSize) { + return new OutboxRelay(repository, publisher, transactionTemplate, CLOCK, batchSize, 10); + } + + private static OutboxEvent event(long id, int attempts) { + return OutboxEvent.builder() + .id(id) + .eventType("exam.result_ready") + .aggregateId(500L + id) + .payload("{}") + .attempts(attempts) + .build(); + } +} diff --git a/backend/src/test/java/com/elearning/common/outbox/PubSubRestPublisherTest.java b/backend/src/test/java/com/elearning/common/outbox/PubSubRestPublisherTest.java new file mode 100644 index 0000000..f77b774 --- /dev/null +++ b/backend/src/test/java/com/elearning/common/outbox/PubSubRestPublisherTest.java @@ -0,0 +1,115 @@ +package com.elearning.common.outbox; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sun.net.httpserver.HttpServer; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; +import java.time.Clock; +import java.time.Instant; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** Runs the publisher and the token provider against a local HTTP server that plays Pub/Sub and the metadata server. */ +class PubSubRestPublisherTest { + + private static final String TOPIC = "projects/demo/topics/exam-results"; + + private final ObjectMapper objectMapper = new ObjectMapper(); + private final HttpClient httpClient = HttpClient.newHttpClient(); + private final List publishedBodies = new ArrayList<>(); + private final List authHeaders = new ArrayList<>(); + private final AtomicInteger tokenRequests = new AtomicInteger(); + private volatile int publishStatus = 200; + private HttpServer server; + private String baseUrl; + + @BeforeEach + void startServer() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.createContext("/token", exchange -> { + tokenRequests.incrementAndGet(); + boolean fromGoogle = "Google".equals(exchange.getRequestHeaders().getFirst("Metadata-Flavor")); + respond(exchange, fromGoogle ? 200 : 403, "{\"access_token\":\"tok-" + tokenRequests.get() + "\",\"expires_in\":3600}"); + }); + server.createContext("/v1/" + TOPIC + ":publish", exchange -> { + authHeaders.add(exchange.getRequestHeaders().getFirst("Authorization")); + publishedBodies.add(new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8)); + respond(exchange, publishStatus, publishStatus == 200 ? "{\"messageIds\":[\"1\"]}" : "{\"error\":\"unavailable\"}"); + }); + server.start(); + baseUrl = "http://127.0.0.1:" + server.getAddress().getPort(); + } + + @AfterEach + void stopServer() { + server.stop(0); + } + + @Test + void publishesTheEventAsABase64MessageWithItsIdAsAttribute() throws Exception { + publisher().publish(event()); + + assertEquals(1, publishedBodies.size()); + assertEquals("Bearer tok-1", authHeaders.get(0)); + JsonNode message = objectMapper.readTree(publishedBodies.get(0)).get("messages").get(0); + String data = new String(Base64.getDecoder().decode(message.get("data").asText()), StandardCharsets.UTF_8); + assertEquals("{\"attemptId\":500}", data); + assertEquals("exam.result_ready", message.get("attributes").get("eventType").asText()); + assertEquals("exam.result_ready:500", message.get("attributes").get("eventId").asText()); + } + + @Test + void reusesTheAccessTokenUntilItIsAboutToExpire() throws Exception { + PubSubRestPublisher publisher = publisher(); + publisher.publish(event()); + publisher.publish(event()); + + assertEquals(1, tokenRequests.get()); + } + + @Test + void anErrorResponseThrowsSoTheEventStaysPending() { + publishStatus = 503; + + IllegalStateException error = assertThrows(IllegalStateException.class, () -> publisher().publish(event())); + assertTrue(error.getMessage().contains("HTTP 503")); + } + + @Test + void rejectsATopicThatIsNotAFullResourceName() { + assertThrows(IllegalArgumentException.class, + () -> new PubSubRestPublisher(httpClient, objectMapper, () -> "t", baseUrl, "exam-results")); + } + + private PubSubRestPublisher publisher() { + Clock clock = Clock.fixed(Instant.parse("2026-11-15T03:00:00Z"), ZoneOffset.UTC); + MetadataServerTokenProvider tokens = new MetadataServerTokenProvider(httpClient, objectMapper, baseUrl + "/token", clock); + return new PubSubRestPublisher(httpClient, objectMapper, tokens, baseUrl, TOPIC); + } + + private static OutboxEvent event() { + return OutboxEvent.builder().id(1L).eventType("exam.result_ready").aggregateId(500L).payload("{\"attemptId\":500}").build(); + } + + private static void respond(com.sun.net.httpserver.HttpExchange exchange, int status, String body) throws IOException { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(status, bytes.length); + exchange.getResponseBody().write(bytes); + exchange.close(); + } +} diff --git a/backend/src/test/java/com/elearning/modules/exam/service/ExamResultEventsTest.java b/backend/src/test/java/com/elearning/modules/exam/service/ExamResultEventsTest.java new file mode 100644 index 0000000..99e3aa4 --- /dev/null +++ b/backend/src/test/java/com/elearning/modules/exam/service/ExamResultEventsTest.java @@ -0,0 +1,88 @@ +package com.elearning.modules.exam.service; + +import com.elearning.common.outbox.OutboxEventRepository; +import com.elearning.modules.exam.entity.ExamAttempt; +import com.elearning.modules.exam.entity.Examination; +import com.elearning.modules.user.entity.Student; +import com.elearning.modules.user.entity.User; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.time.LocalDateTime; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +class ExamResultEventsTest { + + private final ObjectMapper objectMapper = new ObjectMapper(); + private OutboxEventRepository outbox; + private ExamAttempt attempt; + private Examination exam; + + @BeforeEach + void setUp() { + outbox = mock(OutboxEventRepository.class); + + User user = User.builder().name("Andi").email("andi@siswa.id").password("x").build(); + Student student = Student.builder().user(user).nis("2025001").build(); + exam = Examination.builder().title("Quiz 1").passingScore(70).build(); + exam.setId(100L); + attempt = ExamAttempt.builder() + .examination(exam) + .student(student) + .score(85) + .passed(true) + .finishedAt(LocalDateTime.of(2026, 11, 15, 10, 30)) + .build(); + attempt.setId(500L); + } + + @Test + void doesNothingWhenNotificationsAreDisabled() { + new ExamResultEvents(outbox, objectMapper, false).resultReady(attempt); + + verifyNoInteractions(outbox); + } + + @Test + void includesTheScoreWhenTheExamShowsResults() throws Exception { + exam.setShowResult(true); + + JsonNode payload = record(); + + assertEquals("andi@siswa.id", payload.get("studentEmail").asText()); + assertEquals("Quiz 1", payload.get("examTitle").asText()); + assertTrue(payload.get("showScore").asBoolean()); + assertEquals(85, payload.get("score").asInt()); + assertTrue(payload.get("passed").asBoolean()); + assertEquals(70, payload.get("passingScore").asInt()); + } + + @Test + void leavesTheScoreOutWhenTheTeacherHidesResults() throws Exception { + exam.setShowResult(false); + + JsonNode payload = record(); + + assertFalse(payload.get("showScore").asBoolean()); + assertFalse(payload.has("score")); + assertFalse(payload.has("passed")); + } + + private JsonNode record() throws Exception { + new ExamResultEvents(outbox, objectMapper, true).resultReady(attempt); + + ArgumentCaptor payload = ArgumentCaptor.forClass(String.class); + verify(outbox).insertIfAbsent(eq(ExamResultEvents.RESULT_READY), eq(500L), payload.capture()); + return objectMapper.readTree(payload.getValue()); + } +} diff --git a/backend/src/test/java/com/elearning/modules/exam/service/ExamRunnerServiceTest.java b/backend/src/test/java/com/elearning/modules/exam/service/ExamRunnerServiceTest.java index 5f46e11..213c107 100644 --- a/backend/src/test/java/com/elearning/modules/exam/service/ExamRunnerServiceTest.java +++ b/backend/src/test/java/com/elearning/modules/exam/service/ExamRunnerServiceTest.java @@ -63,6 +63,7 @@ class ExamRunnerServiceTest { @Mock private ExamAnswerRepository answerRepository; @Mock private StudentRepository studentRepository; @Mock private ExamRealtimeService realtimeService; + @Mock private ExamResultEvents resultEvents; @InjectMocks private ExamRunnerService service; @@ -151,6 +152,8 @@ void finalizeGradesObjectiveQuestionsAndCompletesAttempt() { assertFalse(placeholder.getCorrect()); assertEquals(0, placeholder.getPointsEarned()); verify(realtimeService).broadcastExamEvent(any(), any(), any()); + // Fully auto-graded: the result is final, so the e-mail event is recorded now. + verify(resultEvents).resultReady(result); } @Test @@ -168,6 +171,8 @@ void finalizeLeavesEssaysAndShortAnswersWithoutKeyForTheTeacher() { assertNull(essayAnswer.getCorrect()); assertNull(keylessAnswer.getCorrect()); assertEquals(0, result.getScore()); + // The score is provisional until the teacher grades the essays: no e-mail yet. + verify(resultEvents, never()).resultReady(any()); } @Test @@ -177,7 +182,7 @@ void finalizeDoesNothingForAttemptsThatAreAlreadyFinished() { ExamAttempt result = service.autoFinalizeAttempt(attempt, exam); assertSame(attempt, result); - verifyNoInteractions(questionRepository, realtimeService); + verifyNoInteractions(questionRepository, realtimeService, resultEvents); verify(attemptRepository, never()).save(any()); } @@ -199,12 +204,32 @@ void manualGradingKeepsAttemptPendingUntilEveryEssayIsGraded() { service.gradeEssay(ATTEMPT_ID, 11L, EssayGradingDto.builder().pointsEarned(4).build(), teacherPrincipal); assertEquals(AttemptStatus.needs_grading, attempt.getStatus()); + verify(resultEvents, never()).resultReady(any()); service.gradeEssay(ATTEMPT_ID, 12L, EssayGradingDto.builder().pointsEarned(3).feedback("Add an example").build(), teacherPrincipal); assertEquals(AttemptStatus.completed, attempt.getStatus()); assertEquals(70, attempt.getScore()); // 7 of 10 points assertTrue(attempt.getPassed()); assertEquals("Add an example", answer2.getFeedback()); + verify(resultEvents).resultReady(attempt); + } + + @Test + void regradingACompletedAttemptDoesNotAnnounceTheResultAgain() { + Question essay = question(1L, QuestionType.essay, null, 10); + ExamAttempt attempt = attempt(AttemptStatus.completed, LocalDateTime.now().minusMinutes(30)); + ExamAnswer essayAnswer = answer(attempt, essay, "text"); + essayAnswer.setId(11L); + essayAnswer.setCorrect(true); + essayAnswer.setPointsEarned(6); + stubQuestionsAndAnswers(List.of(essay), List.of(essayAnswer)); + when(attemptRepository.findById(ATTEMPT_ID)).thenReturn(Optional.of(attempt)); + when(answerRepository.findById(11L)).thenReturn(Optional.of(essayAnswer)); + + service.gradeEssay(ATTEMPT_ID, 11L, EssayGradingDto.builder().pointsEarned(8).build(), teacherPrincipal); + + assertEquals(80, attempt.getScore()); + verify(resultEvents, never()).resultReady(any()); } @Test diff --git a/frontend/Dockerfile b/frontend/Dockerfile index 9193f07..2990bcf 100644 --- a/frontend/Dockerfile +++ b/frontend/Dockerfile @@ -16,7 +16,9 @@ COPY --from=build /app/dist /usr/share/nginx/html # Rendered to /etc/nginx/conf.d/default.conf at start-up; only the variables below are substituted, # so nginx's own $uri, $host, ... stay untouched. COPY nginx.conf /etc/nginx/templates/default.conf.template -ENV NGINX_ENVSUBST_FILTER="^CSP_" +ENV NGINX_ENVSUBST_FILTER="^(CSP_|BACKEND_)" +# Where Nginx proxies /api and /ws. Docker Compose resolves "backend"; Cloud Run sets 127.0.0.1:8080. +ENV BACKEND_UPSTREAM="backend:8080" # Extra CSP sources for optional analytics, e.g. # CSP_SCRIPT_SRC_EXTRA="https://www.googletagmanager.com https://analytics.example.com" # CSP_CONNECT_SRC_EXTRA="https://*.google-analytics.com https://analytics.example.com" diff --git a/frontend/nginx.conf b/frontend/nginx.conf index 47924e5..3720b9c 100644 --- a/frontend/nginx.conf +++ b/frontend/nginx.conf @@ -43,8 +43,10 @@ server { try_files $uri $uri/ /index.html; } + # BACKEND_UPSTREAM is host:port of the Spring Boot container: backend:8080 on Docker Compose (the + # image's default), 127.0.0.1:8080 on Cloud Run where both containers share localhost. location /api/ { - proxy_pass http://backend:8080/api/; + proxy_pass http://${BACKEND_UPSTREAM}/api/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; @@ -58,7 +60,7 @@ server { } location /ws { - proxy_pass http://backend:8080; + proxy_pass http://${BACKEND_UPSTREAM}; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade";