From 8a8bd222b90a01c3874d9d7402ffed5d6a3f2d09 Mon Sep 17 00:00:00 2001 From: M Fari Madyan Date: Fri, 27 Nov 2026 12:43:31 +0700 Subject: [PATCH 1/2] 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"; From 873adcf65cde9af406946cb1e2ae020885a4b775 Mon Sep 17 00:00:00 2001 From: M Fari Madyan Date: Fri, 27 Nov 2026 12:43:50 +0700 Subject: [PATCH 2/2] feat(deploy): add Google Cloud deployment (Compute Engine VM and Cloud Run) Two optional ways to run the app on Google Cloud. The existing VPS setup (docker-compose.prod.yml, deploy.sh) is unchanged and does not read any of it. - deploy/gcp: one Compute Engine VM running docker-compose.gcp.yml, with PostgreSQL on Cloud SQL (Auth Proxy), uploads in Cloud Storage (S3 API + HMAC key), images from Artifact Registry, logs in Cloud Logging, TLS via certbot. Numbered gcloud scripts (foundation, Cloud SQL, VM, functions, teardown); secrets are generated into Secret Manager and rendered into the VM's .env. - deploy/cloudrun: Terraform for a Cloud Run service (frontend + backend containers), Cloud SQL, Memorystore and Secret Manager. - functions/: Cloud Run functions - exam-result-mailer: e-mails students from the exam.result_ready Pub/Sub events (deduplicated by event id) - sql-export: scheduled Cloud SQL export to Cloud Storage - upload-inspector: checks uploaded files against their declared type - .gitignore: Terraform state and tfvars (they hold secrets and project ids). --- .gcloudignore | 19 + .gitignore | 11 + deploy/cloudrun/README.md | 140 + deploy/cloudrun/cloudbuild.yaml | 22 + deploy/cloudrun/data.tf | 103 + deploy/cloudrun/deploy.sh | 131 + deploy/cloudrun/main.tf | 59 + deploy/cloudrun/network.tf | 41 + deploy/cloudrun/outputs.tf | 41 + deploy/cloudrun/secrets.tf | 62 + deploy/cloudrun/service.tf | 206 ++ deploy/cloudrun/terraform.tfvars.example | 14 + deploy/cloudrun/variables.tf | 123 + deploy/cloudrun/versions.tf | 26 + deploy/gcp/10-foundation.sh | 66 + deploy/gcp/20-cloudsql.sh | 48 + deploy/gcp/30-vm.sh | 49 + deploy/gcp/40-functions.sh | 109 + deploy/gcp/99-teardown.sh | 54 + deploy/gcp/README.md | 60 + deploy/gcp/certbot.sh | 21 + deploy/gcp/cloudbuild.yaml | 24 + deploy/gcp/deploy.sh | 51 + deploy/gcp/gcp.env.example | 30 + deploy/gcp/lib.sh | 67 + deploy/gcp/lifecycle-ops.json | 16 + deploy/gcp/vm/bootstrap.sh | 44 + deploy/gcp/vm/nginx-elearning.conf | 39 + deploy/gcp/vm/render-env.sh | 31 + docker-compose.gcp.yml | 121 + functions/exam-result-mailer/.gcloudignore | 3 + functions/exam-result-mailer/handler.js | 97 + functions/exam-result-mailer/handler.test.js | 83 + functions/exam-result-mailer/index.js | 46 + .../exam-result-mailer/package-lock.json | 2563 +++++++++++++++++ functions/exam-result-mailer/package.json | 20 + functions/sql-export/.gcloudignore | 3 + functions/sql-export/handler.js | 65 + functions/sql-export/handler.test.js | 66 + functions/sql-export/index.js | 27 + functions/sql-export/package-lock.json | 1955 +++++++++++++ functions/sql-export/package.json | 19 + functions/upload-inspector/.gcloudignore | 3 + functions/upload-inspector/handler.js | 42 + functions/upload-inspector/handler.test.js | 54 + functions/upload-inspector/index.js | 21 + functions/upload-inspector/package-lock.json | 2553 ++++++++++++++++ functions/upload-inspector/package.json | 19 + functions/upload-inspector/signatures.js | 53 + 49 files changed, 9520 insertions(+) create mode 100644 .gcloudignore create mode 100644 deploy/cloudrun/README.md create mode 100644 deploy/cloudrun/cloudbuild.yaml create mode 100644 deploy/cloudrun/data.tf create mode 100755 deploy/cloudrun/deploy.sh create mode 100644 deploy/cloudrun/main.tf create mode 100644 deploy/cloudrun/network.tf create mode 100644 deploy/cloudrun/outputs.tf create mode 100644 deploy/cloudrun/secrets.tf create mode 100644 deploy/cloudrun/service.tf create mode 100644 deploy/cloudrun/terraform.tfvars.example create mode 100644 deploy/cloudrun/variables.tf create mode 100644 deploy/cloudrun/versions.tf create mode 100755 deploy/gcp/10-foundation.sh create mode 100755 deploy/gcp/20-cloudsql.sh create mode 100755 deploy/gcp/30-vm.sh create mode 100755 deploy/gcp/40-functions.sh create mode 100755 deploy/gcp/99-teardown.sh create mode 100644 deploy/gcp/README.md create mode 100755 deploy/gcp/certbot.sh create mode 100644 deploy/gcp/cloudbuild.yaml create mode 100755 deploy/gcp/deploy.sh create mode 100644 deploy/gcp/gcp.env.example create mode 100755 deploy/gcp/lib.sh create mode 100644 deploy/gcp/lifecycle-ops.json create mode 100755 deploy/gcp/vm/bootstrap.sh create mode 100644 deploy/gcp/vm/nginx-elearning.conf create mode 100755 deploy/gcp/vm/render-env.sh create mode 100644 docker-compose.gcp.yml create mode 100644 functions/exam-result-mailer/.gcloudignore create mode 100644 functions/exam-result-mailer/handler.js create mode 100644 functions/exam-result-mailer/handler.test.js create mode 100644 functions/exam-result-mailer/index.js create mode 100644 functions/exam-result-mailer/package-lock.json create mode 100644 functions/exam-result-mailer/package.json create mode 100644 functions/sql-export/.gcloudignore create mode 100644 functions/sql-export/handler.js create mode 100644 functions/sql-export/handler.test.js create mode 100644 functions/sql-export/index.js create mode 100644 functions/sql-export/package-lock.json create mode 100644 functions/sql-export/package.json create mode 100644 functions/upload-inspector/.gcloudignore create mode 100644 functions/upload-inspector/handler.js create mode 100644 functions/upload-inspector/handler.test.js create mode 100644 functions/upload-inspector/index.js create mode 100644 functions/upload-inspector/package-lock.json create mode 100644 functions/upload-inspector/package.json create mode 100644 functions/upload-inspector/signatures.js diff --git a/.gcloudignore b/.gcloudignore new file mode 100644 index 0000000..f7e0f88 --- /dev/null +++ b/.gcloudignore @@ -0,0 +1,19 @@ +# Files not uploaded to Cloud Build (gcloud builds submit) or to Cloud Run functions. +.git/ +.github/ +.gcloudignore +**/node_modules/ +**/target/ +**/dist/ +screenshots/ +docs/ +docs_backup/ +.env +.env.* +deploy/gcp/.env.gcp +# Terraform working files of deploy/cloudrun (the state holds secrets: never upload it to a build) +**/.terraform/ +**/*.tfstate +**/*.tfstate.* +**/*.tfvars +**/*.tfvars.json diff --git a/.gitignore b/.gitignore index c204910..42b6a0f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,5 @@ +docs_backup/ + # Operating System .DS_Store Thumbs.db @@ -28,3 +30,12 @@ target/ # Logs & Storage *.log storage/uploads/ + +# Terraform (deploy/cloudrun): the state and tfvars hold secrets and project ids +.terraform/ +*.tfstate +*.tfstate.* +*.tfvars +*.tfvars.json +!*.tfvars.example +crash.log diff --git a/deploy/cloudrun/README.md b/deploy/cloudrun/README.md new file mode 100644 index 0000000..794a034 --- /dev/null +++ b/deploy/cloudrun/README.md @@ -0,0 +1,140 @@ +# Deploying to Cloud Run + +The same two application containers as the single-VPS deployment, running on Cloud Run, with +everything that holds state moved to managed services. Defined in Terraform. + +| On the VPS (`docker-compose.prod.yml`) | On Cloud Run (this folder) | +|---|---| +| `frontend` + `backend` containers on one server | One Cloud Run service; every instance runs both containers (Nginx is the ingress container, Spring Boot the sidecar), 0 to `max_instances` instances | +| Host Nginx + Certbot | Cloud Run's HTTPS endpoint (managed certificate) | +| `postgres` container + cron `pg_dump` | Cloud SQL for PostgreSQL 16, private IP only, automated backups and point-in-time recovery | +| `redis` container | Memorystore for Redis 7.2 with AUTH | +| `backend_storage` volume | Cloud Storage bucket through its S3-compatible API (`APP_STORAGE_TYPE=s3`, HMAC key) | +| `.env` on the server | Secret Manager, injected as environment variables | +| `git pull && docker build` on the server | Cloud Build builds the images, Cloud Run pulls them from Artifact Registry | +| UFW | No public IP on the database or Redis: the service reaches them through a VPC (Direct VPC egress) | + +`deploy/gcp` is a different setup (one Compute Engine VM running Docker Compose). The two do not +share resources and can live in the same project. + +## What changes in the application + +Nothing in the Java code. The switches from the scaling work do the job +(`APP_STORAGE_TYPE=s3`, `APP_REALTIME_MODE=redis`, `APP_RATE_LIMIT_STORE=redis`), and the frontend +image reads where the backend is from `BACKEND_UPSTREAM` (default `backend:8080`, so Docker Compose +behaves as before; Cloud Run sets `127.0.0.1:8080`). + +## Prerequisites + +- [Google Cloud CLI](https://cloud.google.com/sdk/docs/install) and [Terraform](https://developer.hashicorp.com/terraform/install) 1.6 or newer +- A project with billing enabled, and a budget alert on it +- Credentials for both tools: + + ```bash + gcloud auth login + gcloud auth application-default login # Terraform uses these + gcloud auth application-default set-quota-project YOUR_PROJECT_ID + ``` + +## Deploy + +```bash +cp deploy/cloudrun/terraform.tfvars.example deploy/cloudrun/terraform.tfvars # fill in project_id +deploy/cloudrun/deploy.sh --plan # optional: read what will be created +deploy/cloudrun/deploy.sh # build, then terraform apply (asks before applying) +``` + +The first run creates the network, Cloud SQL and Redis and takes 20 to 30 minutes. Every later +release is `deploy/cloudrun/deploy.sh` again; it prints how long the build and the rollout took. +Rollback: `IMAGE_TAG= deploy/cloudrun/deploy.sh --no-build`. + +The script prints the URL at the end (`https://SERVICE-PROJECT_NUMBER.REGION.run.app`). +Flyway creates the schema on the first start, including the default admin account, which must +change its password on first login (see the main README). + +## Custom domain + +1. Verify the domain for your Google account (once per domain; a subdomain is covered by its parent): + `gcloud domains verify example.com`, then add the TXT record it shows. +2. Set `domain = "elearning-gcp.example.com"` in `terraform.tfvars` and run + `terraform -chdir=deploy/cloudrun apply`. It adds the mapping and a new revision that accepts + the new origin; the image stays the one from the last `deploy.sh`. +3. Create the record from `terraform -chdir=deploy/cloudrun output domain_dns_records` at your DNS + provider (a CNAME to `ghs.googlehosted.com.` for a subdomain). On Cloudflare set it to + **DNS only**: the certificate cannot be issued through the proxy. +4. Wait for the certificate: usually about 15 minutes, up to 24 hours. + +Domain mappings are a Preview feature, available in some regions only (`asia-southeast1` is one), +and Google does not recommend them for production because they add latency. For production, put a +global external Application Load Balancer in front of the service instead. + +## Demo data + +The database has no public address, so `psql` from a laptop cannot reach it. Import through the +Cloud SQL API instead: + +```bash +cd deploy/cloudrun +BUCKET="$(terraform output -raw uploads_bucket)" +gcloud storage cp ../../backend/src/main/resources/db/migration/seed_demo_data.sql "gs://$BUCKET/_import/" +gcloud storage buckets add-iam-policy-binding "gs://$BUCKET" \ + --member="serviceAccount:$(terraform output -raw sql_instance_service_account)" --role=roles/storage.objectViewer +gcloud sql import sql "$(terraform output -raw sql_instance)" "gs://$BUCKET/_import/seed_demo_data.sql" \ + --database=elearning --user=elearning +gcloud storage rm "gs://$BUCKET/_import/seed_demo_data.sql" +``` + +Moving the real data from the VPS works the same way; `deploy/gcp/README.md` has the `pg_dump` and +uploads commands. + +## Measuring + +```bash +URL="$(terraform -chdir=deploy/cloudrun output -raw service_url)" + +# Cold start: wait until no instance is left (about 15 minutes without traffic), then +curl -s -o /dev/null -w 'cold: %{time_total}s\n' "$URL/api/v1/auth/me" +curl -s -o /dev/null -w 'warm: %{time_total}s\n' "$URL/api/v1/auth/me" +``` + +A `401` is the expected answer: the request went through Nginx to Spring Boot. Instance counts and +request latency are on the service's Metrics tab; cost per service is in Billing > Reports after a +day or two. + +## Known gaps + +- **Background jobs and CPU throttling.** With `cpu_always_allocated = false`, an instance only gets + CPU while it handles a request, and with `min_instances = 0` there may be no instance at all. The + exam finalizer (`app.exam.finalizer`, every 60 s) then runs late: an attempt whose time ran out is + submitted when the next request arrives. Set `cpu_always_allocated = true` and + `min_instances = 1` during exams, at a higher price. +- **WebSockets.** A connection ends after 60 minutes at most (Cloud Run's request timeout); the + STOMP client reconnects. With several instances a browser may reconnect to another one, which is + why `APP_REALTIME_MODE=redis` is set. +- **Database connections.** `db-f1-micro` allows 25 connections. `max_instances * db_pool_size` + (default 3 x 5) must stay below that. +- **Client IP for rate limits.** The backend takes the visitor's address from `X-Forwarded-For`, + as on the VPS. After the first deploy, check a few failed logins in the logs: the IP must be + yours, not a Google address. +- **Exam result e-mails.** The Pub/Sub outbox and the Cloud Run functions of `deploy/gcp` are not + part of this stack; `APP_OUTBOX_PUBLISHER` stays at `log`. + +## What it costs + +Cloud SQL and Memorystore are billed around the clock, whether or not anyone uses the app; Cloud +Run is billed per request-second and falls to zero. At list prices for `us-central1` (other regions +cost more): Memorystore Basic 1 GB about $36 a month, Cloud SQL `db-f1-micro` about $8 plus storage. +Check the [pricing calculator](https://cloud.google.com/products/calculator) for your region. + +## Tearing down + +```bash +cd deploy/cloudrun +# in terraform.tfvars: db_deletion_protection = false, uploads_force_destroy = true +terraform apply +terraform destroy +``` + +If `destroy` stops at the private services connection or the network, run it again after a few +minutes. For a demo project, deleting the whole project (`gcloud projects delete`) is the most +thorough option. diff --git a/deploy/cloudrun/cloudbuild.yaml b/deploy/cloudrun/cloudbuild.yaml new file mode 100644 index 0000000..87ce877 --- /dev/null +++ b/deploy/cloudrun/cloudbuild.yaml @@ -0,0 +1,22 @@ +# Builds both images on Cloud Build (x86_64, what Cloud Run runs) and pushes them to Artifact Registry. +# Building on an Apple Silicon laptop would produce arm64 images that Cloud Run cannot start. +# gcloud builds submit --config deploy/cloudrun/cloudbuild.yaml --substitutions=_REGISTRY=...,_TAG=... +steps: + - id: backend + name: gcr.io/cloud-builders/docker + args: ["build", "-t", "${_REGISTRY}/backend:${_TAG}", "backend"] + waitFor: ["-"] + - id: frontend + name: gcr.io/cloud-builders/docker + args: ["build", "-t", "${_REGISTRY}/frontend:${_TAG}", "frontend"] + waitFor: ["-"] + +images: + - "${_REGISTRY}/backend:${_TAG}" + - "${_REGISTRY}/frontend:${_TAG}" + +options: + logging: CLOUD_LOGGING_ONLY + machineType: E2_HIGHCPU_8 + +timeout: 1200s diff --git a/deploy/cloudrun/data.tf b/deploy/cloudrun/data.tf new file mode 100644 index 0000000..c9ddcf1 --- /dev/null +++ b/deploy/cloudrun/data.tf @@ -0,0 +1,103 @@ +# The three places that hold state: PostgreSQL, Redis and the uploads bucket. + +# --- Cloud SQL for PostgreSQL (replaces the postgres container and its pg_dump cron job) ------------- + +resource "google_sql_database_instance" "db" { + project = var.project_id + name = "${var.name_prefix}-db" + region = var.region + database_version = "POSTGRES_16" + deletion_protection = var.db_deletion_protection + + settings { + tier = var.db_tier + edition = "ENTERPRISE" + availability_type = "ZONAL" + disk_type = "PD_SSD" + disk_size = 10 + disk_autoresize = true + + ip_configuration { + # No public address: only the VPC (and so only the Cloud Run service) can connect. + ipv4_enabled = false + private_network = google_compute_network.vpc.id + } + + backup_configuration { + enabled = true + point_in_time_recovery_enabled = true + start_time = "18:00" # UTC, 01:00 in Jakarta + } + } + + depends_on = [google_service_networking_connection.psa] +} + +resource "google_sql_database" "app" { + project = var.project_id + name = "elearning" + instance = google_sql_database_instance.db.name +} + +resource "random_password" "db" { + length = 32 + special = false +} + +resource "google_sql_user" "app" { + project = var.project_id + name = "elearning" + instance = google_sql_database_instance.db.name + password = random_password.db.result +} + +# --- Memorystore for Redis (replaces the redis container) -------------------------------------------- +# Refresh tokens, login rate limits and, with several instances, the exam event fan-out. + +resource "google_redis_instance" "cache" { + project = var.project_id + name = "${var.name_prefix}-redis" + region = var.region + tier = "BASIC" + memory_size_gb = var.redis_memory_gb + redis_version = "REDIS_7_2" + authorized_network = google_compute_network.vpc.id + connect_mode = "PRIVATE_SERVICE_ACCESS" + auth_enabled = true + + depends_on = [google_service_networking_connection.psa] +} + +# --- Cloud Storage (replaces the backend_storage volume) --------------------------------------------- +# The backend talks to it through the S3-compatible XML API (APP_STORAGE_TYPE=s3) with an HMAC key +# that belongs to a service account which can do nothing but read and write this bucket. + +resource "google_storage_bucket" "uploads" { + project = var.project_id + name = "${var.project_id}-${var.name_prefix}-uploads" + location = var.region + uniform_bucket_level_access = true + public_access_prevention = "enforced" + force_destroy = var.uploads_force_destroy + + depends_on = [google_project_service.apis] +} + +resource "google_service_account" "storage" { + project = var.project_id + account_id = "${var.name_prefix}-storage" + display_name = "E-Learning uploads (HMAC key for the S3-compatible API)" + + depends_on = [google_project_service.apis] +} + +resource "google_storage_bucket_iam_member" "storage_uploads" { + bucket = google_storage_bucket.uploads.name + role = "roles/storage.objectUser" + member = "serviceAccount:${google_service_account.storage.email}" +} + +resource "google_storage_hmac_key" "uploads" { + project = var.project_id + service_account_email = google_service_account.storage.email +} diff --git a/deploy/cloudrun/deploy.sh b/deploy/cloudrun/deploy.sh new file mode 100755 index 0000000..4713064 --- /dev/null +++ b/deploy/cloudrun/deploy.sh @@ -0,0 +1,131 @@ +#!/usr/bin/env bash +# Builds the images on Cloud Build and rolls them out to Cloud Run with Terraform. Run from your laptop: +# deploy/cloudrun/deploy.sh # build the current commit and deploy it +# deploy/cloudrun/deploy.sh --yes # same, without Terraform's confirmation prompt +# deploy/cloudrun/deploy.sh --plan # show what Terraform would change; builds and applies nothing +# IMAGE_TAG=abc1234 deploy/cloudrun/deploy.sh --no-build # roll back to a tag that already exists +# +# The first run also creates the network, Cloud SQL and Redis: allow 20-30 minutes. Later runs only +# build and replace the Cloud Run revision. +set -euo pipefail + +TF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$TF_DIR/../.." && pwd)" + +BUILD=true +PLAN_ONLY=false +APPROVE="" +for arg in "$@"; do + case "$arg" in + --no-build) BUILD=false ;; + --plan) PLAN_ONLY=true ;; + --yes | -y) APPROVE="-auto-approve" ;; + --help | -h) + sed -n '2,9p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//' + exit 0 + ;; + *) + echo "Unknown argument: $arg (see --help)" >&2 + exit 1 + ;; + esac +done + +step() { printf '\n\033[1;36m==> %s\033[0m\n' "$*"; } +note() { printf ' %s\n' "$*"; } +tf() { terraform -chdir="$TF_DIR" "$@"; } +elapsed() { printf '%dm%02ds' $(($1 / 60)) $(($1 % 60)); } + +for cmd in gcloud terraform git python3; do + command -v "$cmd" >/dev/null || { echo "Missing command: $cmd" >&2; exit 1; } +done +if [[ ! -f "$TF_DIR/terraform.tfvars" ]]; then + echo "Missing $TF_DIR/terraform.tfvars. Copy terraform.tfvars.example and fill it in." >&2 + exit 1 +fi + +step "Terraform init and validate" +tf init -input=false >/dev/null +tf validate + +# Read the settings from Terraform itself, so the script and the stack cannot disagree. +tf_var() { printf 'var.%s\n' "$1" | tf console | tr -d '"'; } +PROJECT_ID="$(tf_var project_id)" +REGION="$(tf_var region)" +NAME_PREFIX="$(tf_var name_prefix)" +SERVICE="$(tf_var service_name)" +REGISTRY="${REGION}-docker.pkg.dev/${PROJECT_ID}/${NAME_PREFIX}" +note "project $PROJECT_ID, region $REGION, service $SERVICE" + +# Every gcloud call below targets this project, whatever `gcloud config` says. +export CLOUDSDK_CORE_PROJECT="$PROJECT_ID" + +if $PLAN_ONLY; then + tf plan -input=false + exit 0 +fi + +START=$SECONDS + +if $BUILD; then + step "APIs and the image registry (needed before the first build)" + gcloud services enable serviceusage.googleapis.com cloudresourcemanager.googleapis.com --quiet + tf apply -input=false -auto-approve \ + -target=google_project_service.apis -target=google_artifact_registry_repository.app >/dev/null + note "registry: $REGISTRY" + + cd "$REPO_ROOT" + IMAGE_TAG="${IMAGE_TAG:-$(git rev-parse --short HEAD)}" + if [[ -n "$(git status --porcelain -- backend frontend)" ]]; then + # Without this, a rebuilt image would reuse the commit's tag and Cloud Run would see no change. + IMAGE_TAG="${IMAGE_TAG}-$(date +%Y%m%d%H%M%S)" + note "uncommitted changes in backend/ or frontend/ are built in: tag $IMAGE_TAG" + fi + + step "Cloud Build: backend + frontend -> $REGISTRY (tag $IMAGE_TAG)" + BUILD_START=$SECONDS + gcloud builds submit --region="$REGION" --config=deploy/cloudrun/cloudbuild.yaml \ + --substitutions="_REGISTRY=$REGISTRY,_TAG=$IMAGE_TAG" . + note "build took $(elapsed $((SECONDS - BUILD_START)))" +else + : "${IMAGE_TAG:?--no-build needs IMAGE_TAG=}" +fi + +# Remembered for later plain `terraform apply` runs, which would otherwise remove the service. +printf '{"image_tag": "%s"}\n' "$IMAGE_TAG" >"$TF_DIR/image.auto.tfvars.json" + +step "Terraform apply (tag $IMAGE_TAG)" +APPLY_START=$SECONDS +# shellcheck disable=SC2086 # empty or a single flag (kept a plain string: macOS ships bash 3.2) +tf apply -input=false $APPROVE +note "apply took $(elapsed $((SECONDS - APPLY_START)))" + +# Cloud Run gives a service a second run.app URL that cannot be computed beforehand. The backend only +# accepts origins it knows, so add any new URL and roll out once more (first deploy only). +step "Checking the service's URLs against the allowed origins" +missing="$( + gcloud run services describe "$SERVICE" --region="$REGION" --format=json | + ORIGINS="$(tf output -json cors_origins)" python3 -c ' +import json, os, sys +svc = json.load(sys.stdin) +urls = json.loads(svc.get("metadata", {}).get("annotations", {}).get("run.googleapis.com/urls", "[]")) +status_url = svc.get("status", {}).get("url") +if status_url: + urls.append(status_url) +known = set(json.loads(os.environ["ORIGINS"])) +run_urls = sorted({u.rstrip("/") for u in urls if u.endswith(".run.app")}) +if any(u not in known for u in run_urls): + print(json.dumps({"discovered_run_urls": run_urls})) +' +)" +if [[ -n "$missing" ]]; then + printf '%s\n' "$missing" >"$TF_DIR/urls.auto.tfvars.json" + note "new run.app URL found: applying once more so the backend accepts it" + tf apply -input=false -auto-approve >/dev/null +else + note "all URLs are allowed" +fi + +step "Deployed $IMAGE_TAG in $(elapsed $((SECONDS - START)))" +note "URL: $(tf output -raw service_url)" +note "Logs: gcloud run services logs read $SERVICE --region=$REGION --project=$PROJECT_ID --limit=50" diff --git a/deploy/cloudrun/main.tf b/deploy/cloudrun/main.tf new file mode 100644 index 0000000..947cb56 --- /dev/null +++ b/deploy/cloudrun/main.tf @@ -0,0 +1,59 @@ +# Spring Boot + React e-learning on Cloud Run. +# +# Browser -> Cloud Run service (one instance = two containers) +# frontend: Nginx, serves the SPA and proxies /api and /ws to 127.0.0.1:8080 +# backend: Spring Boot +# -> Direct VPC egress -> Cloud SQL (private IP) and Memorystore for Redis +# -> Cloud Storage (S3-compatible API) for uploads +# +# Walkthrough: README.md in this folder. + +data "google_project" "this" { + project_id = var.project_id +} + +locals { + registry = "${var.region}-docker.pkg.dev/${var.project_id}/${google_artifact_registry_repository.app.repository_id}" + + # Cloud Run's deterministic URL: known before the service exists, so the backend can allow it. + run_url = "https://${var.service_name}-${data.google_project.this.number}.${var.region}.run.app" + + # The backend treats browser requests as cross-origin (Nginx forwards them as plain HTTP), so every + # public origin must be listed. Exact origins only: a pattern such as https://*.run.app would also + # match services in other people's projects. + cors_origins = distinct(compact(concat( + [local.run_url, var.domain == "" ? "" : "https://${var.domain}"], + var.discovered_run_urls, + var.extra_cors_origins, + ))) +} + +resource "google_project_service" "apis" { + for_each = toset([ + "artifactregistry.googleapis.com", + "cloudbuild.googleapis.com", + "compute.googleapis.com", + "iam.googleapis.com", + "redis.googleapis.com", + "run.googleapis.com", + "secretmanager.googleapis.com", + "servicenetworking.googleapis.com", + "sqladmin.googleapis.com", + "storage.googleapis.com", + ]) + + project = var.project_id + service = each.key + disable_on_destroy = false +} + +# Images are built by Cloud Build (deploy.sh) and pulled by Cloud Run. +resource "google_artifact_registry_repository" "app" { + project = var.project_id + location = var.region + repository_id = var.name_prefix + format = "DOCKER" + description = "E-learning backend and frontend images (Cloud Run)" + + depends_on = [google_project_service.apis] +} diff --git a/deploy/cloudrun/network.tf b/deploy/cloudrun/network.tf new file mode 100644 index 0000000..e476ba8 --- /dev/null +++ b/deploy/cloudrun/network.tf @@ -0,0 +1,41 @@ +# Private network: Cloud Run reaches the database and Redis over internal IPs only. + +resource "google_compute_network" "vpc" { + project = var.project_id + name = "${var.name_prefix}-vpc" + auto_create_subnetworks = false + + depends_on = [google_project_service.apis] +} + +# Cloud Run instances take their addresses from this subnet (Direct VPC egress, no connector VM). +resource "google_compute_subnetwork" "run" { + project = var.project_id + name = "${var.name_prefix}-subnet" + region = var.region + network = google_compute_network.vpc.id + ip_cidr_range = "10.10.0.0/24" + private_ip_google_access = true +} + +# Range handed to Google's managed services (Cloud SQL, Memorystore) through private services access. +resource "google_compute_global_address" "psa" { + project = var.project_id + name = "${var.name_prefix}-psa" + purpose = "VPC_PEERING" + address_type = "INTERNAL" + prefix_length = 20 + network = google_compute_network.vpc.id +} + +resource "google_service_networking_connection" "psa" { + network = google_compute_network.vpc.id + service = "servicenetworking.googleapis.com" + reserved_peering_ranges = [google_compute_global_address.psa.name] + + # The API often refuses to delete this connection for a while after the last instance is gone. + # ABANDON lets terraform destroy continue; deleting the VPC removes the peering. + deletion_policy = "ABANDON" + + depends_on = [google_project_service.apis] +} diff --git a/deploy/cloudrun/outputs.tf b/deploy/cloudrun/outputs.tf new file mode 100644 index 0000000..8735533 --- /dev/null +++ b/deploy/cloudrun/outputs.tf @@ -0,0 +1,41 @@ +output "service_url" { + description = "Public URL of the application (Cloud Run's deterministic URL)." + value = var.image_tag == "" ? "(not deployed yet: run deploy/cloudrun/deploy.sh)" : local.run_url +} + +output "custom_domain_url" { + description = "Custom hostname, once var.domain is set and its DNS records exist." + value = var.domain == "" ? null : "https://${var.domain}" +} + +output "domain_dns_records" { + description = "DNS records to create at your DNS provider for var.domain (DNS only, not proxied)." + value = try(google_cloud_run_domain_mapping.custom[0].status[0].resource_records, []) +} + +output "cors_origins" { + description = "Origins the backend accepts." + value = local.cors_origins +} + +output "registry" { + description = "Artifact Registry path of the images." + value = local.registry +} + +output "uploads_bucket" { + value = google_storage_bucket.uploads.name +} + +output "sql_instance" { + value = google_sql_database_instance.db.name +} + +output "sql_instance_service_account" { + description = "Needs roles/storage.objectViewer on a bucket to import SQL files from it (README: demo data)." + value = google_sql_database_instance.db.service_account_email_address +} + +output "redis_host" { + value = google_redis_instance.cache.host +} diff --git a/deploy/cloudrun/secrets.tf b/deploy/cloudrun/secrets.tf new file mode 100644 index 0000000..84c0f45 --- /dev/null +++ b/deploy/cloudrun/secrets.tf @@ -0,0 +1,62 @@ +# Secrets are generated here and stored in Secret Manager; Cloud Run injects them as environment +# variables at start-up. Nothing secret is written to terraform.tfvars or the service definition. +# They are in the Terraform state, though: see the note in versions.tf. + +resource "random_bytes" "jwt" { + length = 32 # 256-bit key, Base64-encoded, as JwtProvider expects +} + +locals { + secret_names = toset(["jwt-secret", "db-password", "redis-auth", "storage-hmac-secret"]) + + secret_values = { + "jwt-secret" = random_bytes.jwt.base64 + "db-password" = random_password.db.result + "redis-auth" = google_redis_instance.cache.auth_string + "storage-hmac-secret" = google_storage_hmac_key.uploads.secret + } +} + +resource "google_secret_manager_secret" "app" { + for_each = local.secret_names + + project = var.project_id + secret_id = "${var.name_prefix}-${each.key}" + + # Kept in the region only, next to the data they protect. + replication { + user_managed { + replicas { + location = var.region + } + } + } + + depends_on = [google_project_service.apis] +} + +resource "google_secret_manager_secret_version" "app" { + for_each = local.secret_names + + secret = google_secret_manager_secret.app[each.key].id + secret_data = local.secret_values[each.key] +} + +# Identity of the Cloud Run service. It can read exactly these four secrets and nothing else: +# the database and Redis are reached over the private network, the bucket through the HMAC key. +resource "google_service_account" "run" { + project = var.project_id + account_id = var.name_prefix + display_name = "E-Learning Cloud Run service" + + depends_on = [google_project_service.apis] +} + +resource "google_secret_manager_secret_iam_member" "run" { + for_each = local.secret_names + + project = var.project_id + secret_id = google_secret_manager_secret.app[each.key].secret_id + role = "roles/secretmanager.secretAccessor" + member = "serviceAccount:${google_service_account.run.email}" +} diff --git a/deploy/cloudrun/service.tf b/deploy/cloudrun/service.tf new file mode 100644 index 0000000..b4c80a3 --- /dev/null +++ b/deploy/cloudrun/service.tf @@ -0,0 +1,206 @@ +# The Cloud Run service: the frontend and backend containers of docker-compose.prod.yml, side by side +# in every instance. Created once an image tag exists (deploy.sh builds the images first). + +locals { + backend_env = { + SPRING_DATASOURCE_URL = "jdbc:postgresql://${google_sql_database_instance.db.private_ip_address}:5432/${google_sql_database.app.name}" + SPRING_DATASOURCE_USERNAME = google_sql_user.app.name + # application.yml allows 20 connections per instance; a shared-core Cloud SQL instance has 25 in total. + SPRING_DATASOURCE_HIKARI_MAXIMUMPOOLSIZE = tostring(var.db_pool_size) + SPRING_DATASOURCE_HIKARI_MINIMUMIDLE = "1" + + SPRING_DATA_REDIS_HOST = google_redis_instance.cache.host + SPRING_DATA_REDIS_PORT = tostring(google_redis_instance.cache.port) + + # Several instances: shared rate limits, exam events relayed through Redis, uploads in a bucket. + APP_RATE_LIMIT_STORE = "redis" + APP_REALTIME_MODE = "redis" + APP_STORAGE_TYPE = "s3" + APP_STORAGE_S3_ENDPOINT = "https://storage.googleapis.com" + APP_STORAGE_S3_REGION = "auto" + APP_STORAGE_S3_PATH_STYLE = "true" + APP_STORAGE_S3_BUCKET = google_storage_bucket.uploads.name + APP_STORAGE_S3_ACCESS_KEY = google_storage_hmac_key.uploads.access_id + + APP_CORS_ALLOWED_ORIGINS = join(",", local.cors_origins) + APP_DEMO_MODE = tostring(var.demo_mode) + APP_REGISTRATION_ENABLED = "false" + SPRINGDOC_ENABLED = "false" + LOG_LEVEL_APP = "INFO" + + # The JVM sizes its heap from the container's memory limit. + JAVA_TOOL_OPTIONS = "-XX:MaxRAMPercentage=70" + } + + # Environment variable -> key in local.secret_names + backend_secret_env = { + JWT_SECRET = "jwt-secret" + SPRING_DATASOURCE_PASSWORD = "db-password" + SPRING_DATA_REDIS_PASSWORD = "redis-auth" + APP_STORAGE_S3_SECRET_KEY = "storage-hmac-secret" + } +} + +resource "google_cloud_run_v2_service" "app" { + count = var.image_tag == "" ? 0 : 1 + + project = var.project_id + name = var.service_name + location = var.region + ingress = "INGRESS_TRAFFIC_ALL" + deletion_protection = false + + template { + service_account = google_service_account.run.email + + # WebSocket connections (exam monitoring) are requests too: 60 minutes is Cloud Run's maximum. + # The STOMP client reconnects after that. + timeout = "3600s" + # Keeps a browser on the same instance while it is up (best effort), which WebSockets like. + session_affinity = true + max_instance_request_concurrency = 80 + + scaling { + min_instance_count = var.min_instances + max_instance_count = var.max_instances + } + + # Direct VPC egress: private addresses (Cloud SQL, Redis) go through the VPC, everything else + # (Cloud Storage, Secret Manager) takes the normal path. + vpc_access { + egress = "PRIVATE_RANGES_ONLY" + network_interfaces { + network = google_compute_network.vpc.id + subnetwork = google_compute_subnetwork.run.id + } + } + + # Ingress container: the only one with a port. Same image as on the VPS; BACKEND_UPSTREAM points + # Nginx at the backend container, which shares localhost with it. + containers { + name = "frontend" + image = "${local.registry}/frontend:${var.image_tag}" + depends_on = ["backend"] + + ports { + container_port = 80 + } + + env { + name = "BACKEND_UPSTREAM" + value = "127.0.0.1:8080" + } + + resources { + limits = { + cpu = "500m" + memory = "256Mi" + } + cpu_idle = !var.cpu_always_allocated + } + + startup_probe { + period_seconds = 2 + timeout_seconds = 1 + failure_threshold = 30 + tcp_socket { + port = 80 + } + } + } + + containers { + name = "backend" + image = "${local.registry}/backend:${var.image_tag}" + + dynamic "env" { + for_each = local.backend_env + content { + name = env.key + value = env.value + } + } + + dynamic "env" { + for_each = local.backend_secret_env + content { + name = env.key + value_source { + secret_key_ref { + secret = google_secret_manager_secret.app[env.value].secret_id + version = "latest" + } + } + } + } + + resources { + limits = { + cpu = var.backend_cpu + memory = var.backend_memory + } + cpu_idle = !var.cpu_always_allocated + startup_cpu_boost = true + } + + # Ready = Spring context up, Flyway migrations applied. Up to ~4 minutes for a first start. + startup_probe { + initial_delay_seconds = 5 + period_seconds = 5 + timeout_seconds = 3 + failure_threshold = 48 + http_get { + path = "/actuator/health/readiness" + port = 8080 + } + } + + liveness_probe { + period_seconds = 30 + timeout_seconds = 5 + failure_threshold = 3 + http_get { + path = "/actuator/health/liveness" + port = 8080 + } + } + } + } + + depends_on = [ + google_project_service.apis, + google_secret_manager_secret_version.app, + google_secret_manager_secret_iam_member.run, + google_storage_bucket_iam_member.storage_uploads, + ] +} + +# Public website: anyone may call the service. The application does its own authentication. +resource "google_cloud_run_v2_service_iam_member" "public" { + count = var.image_tag == "" ? 0 : 1 + + project = var.project_id + location = var.region + name = google_cloud_run_v2_service.app[0].name + role = "roles/run.invoker" + member = "allUsers" +} + +# Optional custom hostname. Domain mappings are a Preview feature that Google does not recommend for +# production (added latency); the supported alternative is a global external Application Load Balancer. +# The domain must be verified for your account first: see README.md. +resource "google_cloud_run_domain_mapping" "custom" { + count = var.domain != "" && var.image_tag != "" ? 1 : 0 + + project = var.project_id + location = var.region + name = var.domain + + metadata { + namespace = var.project_id + } + + spec { + route_name = google_cloud_run_v2_service.app[0].name + } +} diff --git a/deploy/cloudrun/terraform.tfvars.example b/deploy/cloudrun/terraform.tfvars.example new file mode 100644 index 0000000..c2926eb --- /dev/null +++ b/deploy/cloudrun/terraform.tfvars.example @@ -0,0 +1,14 @@ +# Copy to terraform.tfvars (git-ignored) and fill in. Every variable is described in variables.tf. + +project_id = "your-project-id" +region = "asia-southeast1" + +# Custom hostname: leave empty for the first deploy, set it once the domain is verified (README.md). +# domain = "elearning-gcp.example.com" + +# true only for a public demo with shared demo accounts +demo_mode = false + +# Scale to zero by default. Raise min_instances to 1 to avoid cold starts (costs more). +# min_instances = 0 +# max_instances = 3 diff --git a/deploy/cloudrun/variables.tf b/deploy/cloudrun/variables.tf new file mode 100644 index 0000000..5a3b252 --- /dev/null +++ b/deploy/cloudrun/variables.tf @@ -0,0 +1,123 @@ +variable "project_id" { + description = "Google Cloud project that holds everything below. Billing must be enabled." + type = string +} + +variable "region" { + description = "Region for every resource. Cloud Run domain mappings (var.domain) only exist in some regions; asia-southeast1 is the closest one to Indonesia." + type = string + default = "asia-southeast1" +} + +variable "name_prefix" { + description = "Prefix for resource names, so this stack can share a project with deploy/gcp (the VM setup)." + type = string + default = "elearning-run" + + validation { + condition = can(regex("^[a-z][a-z0-9-]{4,16}[a-z0-9]$", var.name_prefix)) + error_message = "name_prefix must be 6-18 characters: lowercase letters, digits and hyphens, starting with a letter." + } +} + +variable "service_name" { + description = "Cloud Run service name. It is part of the run.app URL." + type = string + default = "elearning" +} + +variable "image_tag" { + description = "Tag of the backend and frontend images in Artifact Registry. deploy.sh writes it to image.auto.tfvars.json after each build. Empty: everything except the Cloud Run service is created." + type = string + default = "" +} + +# --- Public address --------------------------------------------------------------------------------- + +variable "domain" { + description = "Optional custom hostname, e.g. elearning-gcp.example.com. Creates a Cloud Run domain mapping and allows the origin. Leave empty to use the run.app URL only." + type = string + default = "" +} + +variable "extra_cors_origins" { + description = "More origins the API and the WebSocket endpoint accept, e.g. a local frontend during development." + type = list(string) + default = [] +} + +variable "discovered_run_urls" { + description = "Written by deploy.sh (urls.auto.tfvars.json): run.app URLs Cloud Run assigned to the service that cannot be computed in advance." + type = list(string) + default = [] +} + +# --- Cloud Run --------------------------------------------------------------------------------------- + +variable "min_instances" { + description = "0 = scale to zero (cold starts, lowest cost). 1 keeps one instance warm." + type = number + default = 0 +} + +variable "max_instances" { + description = "Upper bound for instances. Keep max_instances * db_pool_size below the database's connection limit (db-f1-micro: 25)." + type = number + default = 3 +} + +variable "backend_cpu" { + description = "CPU limit of the Spring Boot container." + type = string + default = "1000m" +} + +variable "backend_memory" { + description = "Memory limit of the Spring Boot container." + type = string + default = "1Gi" +} + +variable "cpu_always_allocated" { + description = "false = CPU only while a request is being handled (cheapest). true = instance-based billing; needed if background jobs must run on time, see README (known gaps)." + type = bool + default = false +} + +variable "db_pool_size" { + description = "HikariCP maximum pool size per instance (application.yml defaults to 20, too many for a shared-core database with several instances)." + type = number + default = 5 +} + +variable "demo_mode" { + description = "APP_DEMO_MODE: true only for a public demo with shared demo accounts." + type = bool + default = false +} + +# --- Data services ----------------------------------------------------------------------------------- + +variable "db_tier" { + description = "Cloud SQL machine type. db-f1-micro and db-g1-small are shared-core (cheap, no SLA); db-custom-1-3840 is dedicated." + type = string + default = "db-f1-micro" +} + +variable "db_deletion_protection" { + description = "Blocks terraform destroy from deleting the database. Set to false (and apply) before tearing the stack down." + type = bool + default = true +} + +variable "redis_memory_gb" { + description = "Memorystore for Redis size. 1 GB is the minimum and plenty for refresh tokens, rate limits and exam events." + type = number + default = 1 +} + +variable "uploads_force_destroy" { + description = "Lets terraform destroy delete the uploads bucket even when it still holds files." + type = bool + default = false +} diff --git a/deploy/cloudrun/versions.tf b/deploy/cloudrun/versions.tf new file mode 100644 index 0000000..60d0c3e --- /dev/null +++ b/deploy/cloudrun/versions.tf @@ -0,0 +1,26 @@ +terraform { + required_version = ">= 1.6" + + required_providers { + google = { + source = "hashicorp/google" + version = ">= 6.20, < 8.0" + } + random = { + source = "hashicorp/random" + version = "~> 3.6" + } + } + + # State is local by default and holds the generated secrets: it is git-ignored, keep it off shared + # disks. For a team, create a bucket and uncomment: + # backend "gcs" { + # bucket = "YOUR_PROJECT_ID-tfstate" + # prefix = "elearning-cloudrun" + # } +} + +provider "google" { + project = var.project_id + region = var.region +} diff --git a/deploy/gcp/10-foundation.sh b/deploy/gcp/10-foundation.sh new file mode 100755 index 0000000..1dd7d97 --- /dev/null +++ b/deploy/gcp/10-foundation.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# APIs, service accounts, Artifact Registry, buckets, Pub/Sub topics and the app's own secrets. +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +step "Enabling APIs (first run takes a minute or two)" +gcloud services enable \ + compute.googleapis.com sqladmin.googleapis.com artifactregistry.googleapis.com cloudbuild.googleapis.com \ + secretmanager.googleapis.com pubsub.googleapis.com cloudfunctions.googleapis.com run.googleapis.com \ + eventarc.googleapis.com cloudscheduler.googleapis.com iap.googleapis.com logging.googleapis.com \ + monitoring.googleapis.com storage.googleapis.com iam.googleapis.com + +step "Service accounts (one per workload, each with only what it needs)" +ensure_sa elearning-vm "E-Learning VM (Docker Compose host)" +ensure_sa elearning-storage "E-Learning uploads (HMAC key for the S3-compatible API)" + +for role in roles/cloudsql.client roles/logging.logWriter roles/monitoring.metricWriter; do + project_role "serviceAccount:$VM_SA" "$role" +done + +step "Artifact Registry: $REGISTRY" +quietly gcloud artifacts repositories describe "$AR_REPO" --location="$REGION" || + gcloud artifacts repositories create "$AR_REPO" --repository-format=docker --location="$REGION" \ + --description="E-Learning backend and frontend images" +gcloud artifacts repositories add-iam-policy-binding "$AR_REPO" --location="$REGION" \ + --member="serviceAccount:$VM_SA" --role=roles/artifactregistry.reader >/dev/null + +step "Buckets: gs://$UPLOADS_BUCKET (uploads), gs://$OPS_BUCKET (exports, dedup markers)" +for bucket in "$UPLOADS_BUCKET" "$OPS_BUCKET"; do + quietly gcloud storage buckets describe "gs://$bucket" || + gcloud storage buckets create "gs://$bucket" --location="$REGION" \ + --uniform-bucket-level-access --public-access-prevention +done +gcloud storage buckets update "gs://$OPS_BUCKET" --lifecycle-file="$GCP_DIR/lifecycle-ops.json" +gcloud storage buckets add-iam-policy-binding "gs://$UPLOADS_BUCKET" \ + --member="serviceAccount:$STORAGE_SA" --role=roles/storage.objectAdmin >/dev/null + +step "HMAC key for the backend's S3 client (the secret is shown once: stored straight into Secret Manager)" +if quietly gcloud secrets describe gcs-hmac-access-id; then + note "HMAC secrets exist (kept)" +else + hmac_json="$(gcloud storage hmac create "$STORAGE_SA" --format=json)" + access_id="$(printf '%s' "$hmac_json" | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d["metadata"]["accessId"])')" + secret="$(printf '%s' "$hmac_json" | python3 -c 'import json,sys; print(json.load(sys.stdin)["secret"])')" + ensure_secret gcs-hmac-access-id "$access_id" + ensure_secret gcs-hmac-secret "$secret" + unset hmac_json secret +fi + +step "Application secrets" +ensure_secret jwt-secret "$(openssl rand -base64 32)" +for secret in gcs-hmac-access-id gcs-hmac-secret jwt-secret; do + grant_secret "$secret" "$VM_SA" +done + +step "Pub/Sub: $TOPIC (+ $DEAD_LETTER_TOPIC)" +for topic in "$TOPIC" "$DEAD_LETTER_TOPIC"; do + quietly gcloud pubsub topics describe "$topic" || gcloud pubsub topics create "$topic" +done +# Keep dead letters for a week so they can be inspected and replayed. +quietly gcloud pubsub subscriptions describe "${DEAD_LETTER_TOPIC}-sub" || + gcloud pubsub subscriptions create "${DEAD_LETTER_TOPIC}-sub" --topic="$DEAD_LETTER_TOPIC" --message-retention-duration=7d +# The VM may publish to this one topic, nothing else. +gcloud pubsub topics add-iam-policy-binding "$TOPIC" \ + --member="serviceAccount:$VM_SA" --role=roles/pubsub.publisher >/dev/null + +step "Done. Next: 20-cloudsql.sh" diff --git a/deploy/gcp/20-cloudsql.sh b/deploy/gcp/20-cloudsql.sh new file mode 100755 index 0000000..be7c17c --- /dev/null +++ b/deploy/gcp/20-cloudsql.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Cloud SQL for PostgreSQL 16: automated backups, point-in-time recovery, maintenance window, +# connections only through the Cloud SQL connectors (no authorized networks, client certificates required). +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +step "Cloud SQL instance $SQL_INSTANCE ($SQL_TIER) in $REGION: creating takes ~10 minutes" +if quietly gcloud sql instances describe "$SQL_INSTANCE"; then + note "instance exists (kept)" +else + # Times are UTC: backups at 01:00 WIB, maintenance Sunday 02:00 WIB, both outside school hours. + gcloud sql instances create "$SQL_INSTANCE" \ + --database-version=POSTGRES_16 \ + --edition=ENTERPRISE \ + --tier="$SQL_TIER" \ + --region="$REGION" \ + --storage-type=SSD \ + --storage-size=10GB \ + --storage-auto-increase \ + --backup-start-time=18:00 \ + --enable-point-in-time-recovery \ + --retained-backups-count=7 \ + --retained-transaction-log-days=7 \ + --maintenance-window-day=SUN \ + --maintenance-window-hour=19 \ + --ssl-mode=TRUSTED_CLIENT_CERTIFICATE_REQUIRED \ + --deletion-protection +fi + +step "Database and user" +quietly gcloud sql databases describe "$SQL_DATABASE" --instance="$SQL_INSTANCE" || + gcloud sql databases create "$SQL_DATABASE" --instance="$SQL_INSTANCE" + +if quietly gcloud secrets describe db-password; then + note "db-password secret exists (user kept)" +else + password="$(openssl rand -base64 24 | tr -d '/+=' | cut -c1-28)" + gcloud sql users create "$SQL_USER" --instance="$SQL_INSTANCE" --password="$password" + ensure_secret db-password "$password" + unset password +fi +grant_secret db-password "$VM_SA" + +step "Let Cloud SQL write exports to gs://$OPS_BUCKET (used by the sql-export function)" +sql_sa="$(gcloud sql instances describe "$SQL_INSTANCE" --format='value(serviceAccountEmailAddress)')" +gcloud storage buckets add-iam-policy-binding "gs://$OPS_BUCKET" \ + --member="serviceAccount:$sql_sa" --role=roles/storage.objectAdmin >/dev/null + +step "Done. Connection name: $CLOUD_SQL_CONNECTION. Next: 30-vm.sh" diff --git a/deploy/gcp/30-vm.sh b/deploy/gcp/30-vm.sh new file mode 100755 index 0000000..f9128ca --- /dev/null +++ b/deploy/gcp/30-vm.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Static IP, firewall, and the Compute Engine VM that runs docker-compose.gcp.yml behind host Nginx. +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +step "Static external IP" +quietly gcloud compute addresses describe elearning-ip --region="$REGION" || + gcloud compute addresses create elearning-ip --region="$REGION" +ip="$(gcloud compute addresses describe elearning-ip --region="$REGION" --format='value(address)')" + +step "Firewall: 80/443 from anywhere, SSH only through Identity-Aware Proxy" +quietly gcloud compute firewall-rules describe elearning-allow-web || + gcloud compute firewall-rules create elearning-allow-web --network=default --direction=INGRESS \ + --action=allow --rules=tcp:80,tcp:443 --source-ranges=0.0.0.0/0 --target-tags=elearning-web +# 35.235.240.0/20 is the range IAP TCP forwarding connects from. +quietly gcloud compute firewall-rules describe elearning-allow-iap-ssh || + gcloud compute firewall-rules create elearning-allow-iap-ssh --network=default --direction=INGRESS \ + --action=allow --rules=tcp:22 --source-ranges=35.235.240.0/20 --target-tags=elearning-web +# The default network opens SSH (and RDP) to the whole internet. This project only hosts this app, +# so remove those rules; in a shared project, narrow them instead. +for rule in default-allow-ssh default-allow-rdp; do + if quietly gcloud compute firewall-rules describe "$rule"; then + gcloud compute firewall-rules delete "$rule" --quiet + fi +done + +step "VM $VM_NAME ($VM_MACHINE_TYPE, Debian 12) with service account $VM_SA" +if quietly gcloud compute instances describe "$VM_NAME" --zone="$ZONE"; then + note "VM exists (kept)" +else + # --scopes=cloud-platform: access is decided by the service account's IAM roles, not by legacy scopes. + gcloud compute instances create "$VM_NAME" \ + --zone="$ZONE" \ + --machine-type="$VM_MACHINE_TYPE" \ + --image-family=debian-12 --image-project=debian-cloud \ + --boot-disk-size=20GB --boot-disk-type=pd-balanced \ + --service-account="$VM_SA" --scopes=cloud-platform \ + --tags=elearning-web \ + --address="$ip" \ + --shielded-secure-boot --shielded-vtpm --shielded-integrity-monitoring \ + --metadata=enable-oslogin=TRUE \ + --metadata-from-file=startup-script="$GCP_DIR/vm/bootstrap.sh" +fi + +step "Done" +note "Static IP: $ip" +note "1. Create a DNS A record: $DOMAIN -> $ip (DNS only, no proxy, until the certificate is issued)." +note "2. Wait for bootstrap (about 3 minutes):" +note " gcloud compute ssh $VM_NAME --zone=$ZONE --tunnel-through-iap --command='sudo tail -n 5 /var/log/elearning-bootstrap.log'" +note "3. Run deploy.sh, then certbot.sh." diff --git a/deploy/gcp/40-functions.sh b/deploy/gcp/40-functions.sh new file mode 100755 index 0000000..00a65f5 --- /dev/null +++ b/deploy/gcp/40-functions.sh @@ -0,0 +1,109 @@ +#!/usr/bin/env bash +# Cloud Run functions (deployed with `gcloud functions deploy`, Node.js 22): +# exam-result-mailer Pub/Sub exam-results -> e-mail (SMTP), dead-letter topic after 5 failed deliveries +# upload-inspector object finalized in the uploads bucket -> quarantine files whose content lies about their type +# sql-export HTTP, called nightly by Cloud Scheduler -> Cloud SQL export to gs://$OPS_BUCKET +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" +: "${SMTP_HOST:?}" "${SMTP_PORT:?}" "${SMTP_USER:?}" "${SMTP_FROM:?}" + +FUNCTIONS_DIR="$REPO_ROOT/functions" +PROJECT_NUMBER="$(project_number)" +PUBSUB_AGENT="service-${PROJECT_NUMBER}@gcp-sa-pubsub.iam.gserviceaccount.com" + +step "Service accounts, one per function" +ensure_sa fn-exam-result-mailer "Function: exam result mailer" +ensure_sa fn-upload-inspector "Function: upload inspector" +ensure_sa fn-sql-export "Function: Cloud SQL export" +ensure_sa elearning-scheduler "Cloud Scheduler: invokes sql-export" + +# Mailer: dedup markers in the ops bucket, SMTP password from Secret Manager, receives Eventarc events. +gcloud storage buckets add-iam-policy-binding "gs://$OPS_BUCKET" \ + --member="serviceAccount:$MAILER_SA" --role=roles/storage.objectAdmin >/dev/null +# Inspector: read and move objects in the uploads bucket only. +gcloud storage buckets add-iam-policy-binding "gs://$UPLOADS_BUCKET" \ + --member="serviceAccount:$INSPECTOR_SA" --role=roles/storage.objectAdmin >/dev/null +for sa in "$MAILER_SA" "$INSPECTOR_SA"; do + project_role "serviceAccount:$sa" roles/eventarc.eventReceiver +done +# sql-export: a custom role with exactly the permissions the export call needs (cloudsql.editor could +# also delete databases and change users). +if ! quietly gcloud iam roles describe sqlExporter --project="$PROJECT_ID"; then + gcloud iam roles create sqlExporter --project="$PROJECT_ID" --title="Cloud SQL exporter" \ + --permissions=cloudsql.instances.export,cloudsql.instances.get --stage=GA +fi +project_role "serviceAccount:$SQL_EXPORT_SA" "projects/$PROJECT_ID/roles/sqlExporter" + +step "SMTP password -> Secret Manager (smtp-pass)" +if quietly gcloud secrets describe smtp-pass; then + note "smtp-pass exists (kept). Rotate with: gcloud secrets versions add smtp-pass --data-file=-" +else + read -r -s -p "SMTP password for $SMTP_USER (input hidden): " smtp_pass + echo + ensure_secret smtp-pass "$smtp_pass" + unset smtp_pass +fi +grant_secret smtp-pass "$MAILER_SA" + +step "Cloud Storage service agent may publish events (needed by Cloud Storage triggers)" +storage_agent="$(gcloud storage service-agent --project="$PROJECT_ID")" +project_role "serviceAccount:$storage_agent" roles/pubsub.publisher + +common=(--gen2 --runtime=nodejs22 --region="$REGION" --memory=256Mi --max-instances=3 --quiet) + +step "Deploying exam-result-mailer" +gcloud functions deploy exam-result-mailer "${common[@]}" \ + --source="$FUNCTIONS_DIR/exam-result-mailer" --entry-point=examResultMailer \ + --trigger-topic="$TOPIC" --retry \ + --service-account="$MAILER_SA" --trigger-service-account="$MAILER_SA" \ + --set-env-vars="^|^SMTP_HOST=$SMTP_HOST|SMTP_PORT=$SMTP_PORT|SMTP_USER=$SMTP_USER|SMTP_FROM=$SMTP_FROM|DEDUP_BUCKET=$OPS_BUCKET|APP_URL=https://$DOMAIN" \ + --set-secrets="SMTP_PASS=smtp-pass:latest" + +step "Deploying upload-inspector" +gcloud functions deploy upload-inspector "${common[@]}" \ + --source="$FUNCTIONS_DIR/upload-inspector" --entry-point=uploadInspector \ + --trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \ + --trigger-event-filters="bucket=$UPLOADS_BUCKET" --trigger-location="$REGION" --retry \ + --service-account="$INSPECTOR_SA" --trigger-service-account="$INSPECTOR_SA" + +step "Deploying sql-export (private: only the scheduler's service account may call it)" +gcloud functions deploy sql-export "${common[@]}" \ + --source="$FUNCTIONS_DIR/sql-export" --entry-point=sqlExport \ + --trigger-http --no-allow-unauthenticated --timeout=60s \ + --service-account="$SQL_EXPORT_SA" \ + --set-env-vars="GCP_PROJECT=$PROJECT_ID,SQL_INSTANCE=$SQL_INSTANCE,SQL_DATABASE=$SQL_DATABASE,EXPORT_BUCKET=$OPS_BUCKET" + +step "Who may invoke what (each function is a Cloud Run service underneath)" +gcloud run services add-iam-policy-binding exam-result-mailer --region="$REGION" \ + --member="serviceAccount:$MAILER_SA" --role=roles/run.invoker >/dev/null +gcloud run services add-iam-policy-binding upload-inspector --region="$REGION" \ + --member="serviceAccount:$INSPECTOR_SA" --role=roles/run.invoker >/dev/null +gcloud run services add-iam-policy-binding sql-export --region="$REGION" \ + --member="serviceAccount:$SCHEDULER_SA" --role=roles/run.invoker >/dev/null + +step "Dead-letter policy on the mailer's subscription (created by Eventarc)" +trigger="$(gcloud functions describe exam-result-mailer --region="$REGION" --format='value(eventTrigger.trigger)')" +subscription="$(gcloud eventarc triggers describe "${trigger##*/}" --location="$REGION" --format='value(transport.pubsub.subscription)')" +gcloud pubsub subscriptions update "$subscription" \ + --dead-letter-topic="$DEAD_LETTER_TOPIC" --max-delivery-attempts=5 +# Pub/Sub's own service agent moves the message, so it needs both sides of the move. +gcloud pubsub topics add-iam-policy-binding "$DEAD_LETTER_TOPIC" \ + --member="serviceAccount:$PUBSUB_AGENT" --role=roles/pubsub.publisher >/dev/null +gcloud pubsub subscriptions add-iam-policy-binding "$subscription" \ + --member="serviceAccount:$PUBSUB_AGENT" --role=roles/pubsub.subscriber >/dev/null + +step "Cloud Scheduler: nightly export at 03:00 WIB (after the 01:00 automated backup)" +url="$(gcloud functions describe sql-export --region="$REGION" --format='value(serviceConfig.uri)')" +if quietly gcloud scheduler jobs describe elearning-sql-export --location="$REGION"; then + verb=update +else + verb=create +fi +gcloud scheduler jobs "$verb" http elearning-sql-export --location="$REGION" \ + --schedule="0 3 * * *" --time-zone="Asia/Jakarta" \ + --uri="$url" --http-method=POST \ + --oidc-service-account-email="$SCHEDULER_SA" --oidc-token-audience="$url" \ + --attempt-deadline=120s --max-retry-attempts=3 --min-backoff=10m + +step "Done" +note "Try the export now: gcloud scheduler jobs run elearning-sql-export --location=$REGION" +note "Mailer logs: gcloud functions logs read exam-result-mailer --region=$REGION --limit=20" diff --git a/deploy/gcp/99-teardown.sh b/deploy/gcp/99-teardown.sh new file mode 100755 index 0000000..93b90cb --- /dev/null +++ b/deploy/gcp/99-teardown.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# Deletes everything the other scripts created, so billing stops. Irreversible: the database, its +# backups and every uploaded file are deleted. Export what you want to keep first. +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +echo "This deletes the VM, the Cloud SQL instance (and its backups), both buckets with all files," +echo "the functions, topics, secrets and service accounts in project $PROJECT_ID." +read -r -p "Type the project id to confirm: " answer +[[ "$answer" == "$PROJECT_ID" ]] || { echo "Aborted."; exit 1; } + +# Each delete is allowed to fail (already gone), the script carries on. +try() { "$@" --quiet 2>/dev/null || note "skipped: $*"; } + +step "Scheduler and functions" +try gcloud scheduler jobs delete elearning-sql-export --location="$REGION" +for fn in exam-result-mailer upload-inspector sql-export; do + try gcloud functions delete "$fn" --region="$REGION" +done + +step "VM, IP, firewall rules" +try gcloud compute instances delete "$VM_NAME" --zone="$ZONE" +try gcloud compute addresses delete elearning-ip --region="$REGION" +for rule in elearning-allow-web elearning-allow-iap-ssh; do + try gcloud compute firewall-rules delete "$rule" +done + +step "Cloud SQL (deletion protection off first)" +try gcloud sql instances patch "$SQL_INSTANCE" --no-deletion-protection +try gcloud sql instances delete "$SQL_INSTANCE" + +step "Buckets, registry, Pub/Sub" +for bucket in "$UPLOADS_BUCKET" "$OPS_BUCKET"; do + try gcloud storage rm --recursive "gs://$bucket" +done +try gcloud artifacts repositories delete "$AR_REPO" --location="$REGION" +try gcloud pubsub subscriptions delete "${DEAD_LETTER_TOPIC}-sub" +for topic in "$TOPIC" "$DEAD_LETTER_TOPIC"; do + try gcloud pubsub topics delete "$topic" +done + +step "HMAC key, secrets, service accounts, custom role" +for id in $(gcloud storage hmac list --service-account="$STORAGE_SA" --format='value(accessId)' 2>/dev/null); do + try gcloud storage hmac update "$id" --deactivate + try gcloud storage hmac delete "$id" +done +for secret in db-password jwt-secret gcs-hmac-access-id gcs-hmac-secret smtp-pass; do + try gcloud secrets delete "$secret" +done +for sa in "$VM_SA" "$STORAGE_SA" "$MAILER_SA" "$INSPECTOR_SA" "$SQL_EXPORT_SA" "$SCHEDULER_SA"; do + try gcloud iam service-accounts delete "$sa" +done +try gcloud iam roles delete sqlExporter --project="$PROJECT_ID" + +step "Done. To remove the project itself (and anything left in it): gcloud projects delete $PROJECT_ID" diff --git a/deploy/gcp/README.md b/deploy/gcp/README.md new file mode 100644 index 0000000..33f8ecf --- /dev/null +++ b/deploy/gcp/README.md @@ -0,0 +1,60 @@ +# Deploying to Google Cloud + +The same Docker Compose setup as the single-VPS deployment, on a Compute Engine VM, with the parts +that hold data moved to managed services: + +| On the VPS (`docker-compose.prod.yml`) | On Google Cloud (`docker-compose.gcp.yml`) | +|---|---| +| `postgres` container + cron `pg_dump` | Cloud SQL for PostgreSQL 16 (automated backups, point-in-time recovery), reached through the Cloud SQL Auth Proxy container | +| `backend_storage` volume | Cloud Storage bucket through its S3-compatible API (`APP_STORAGE_TYPE=s3`, HMAC key) | +| `.env` on the server | Secret Manager; `vm/render-env.sh` writes `.env` on the VM with the VM's service account | +| `git pull && docker build` on the server | Cloud Build builds the images, the VM only pulls them from Artifact Registry | +| UFW | VPC firewall: 80/443 open, SSH only through Identity-Aware Proxy | +| `redis` container | unchanged (refresh tokens and rate limits; losing it only logs users out) | +| Host Nginx + Certbot | unchanged | +| — | Cloud Run functions: exam result e-mails (Pub/Sub), upload content checks (Cloud Storage trigger), nightly SQL export (Cloud Scheduler) | + +## Prerequisites + +- [Google Cloud CLI](https://cloud.google.com/sdk/docs/install), logged in: `gcloud auth login` +- A project with billing enabled, and a budget alert on it +- A domain you can add an A record to +- An SMTP account for the e-mails (port 587 or 465; Google Cloud blocks outbound port 25) + +## Steps + +```bash +cp deploy/gcp/gcp.env.example deploy/gcp/.env.gcp # fill it in (git-ignored) + +deploy/gcp/10-foundation.sh # APIs, service accounts, registry, buckets, Pub/Sub, secrets +deploy/gcp/20-cloudsql.sh # Cloud SQL instance, database, user (~10 min) +deploy/gcp/30-vm.sh # static IP, firewall, VM; prints the IP for your DNS record +deploy/gcp/deploy.sh # Cloud Build -> Artifact Registry -> docker compose up on the VM +deploy/gcp/certbot.sh # Let's Encrypt, once DNS points at the VM +deploy/gcp/40-functions.sh # the three functions, dead-letter topic, scheduler job +``` + +Every later release is `deploy/gcp/deploy.sh` again. Rollback: `IMAGE_TAG= deploy/gcp/deploy.sh --no-build`. + +## Moving data from the VPS + +```bash +# on the VPS +docker exec elearning-postgres pg_dump -U postgres --no-owner --no-acl elearning | gzip > elearning.sql.gz +# the volume name depends on the compose project (folder) name +volume="$(docker volume ls --format '{{.Name}}' | grep backend_storage)" +docker run --rm -v "$volume":/data -v "$PWD":/out alpine tar czf /out/uploads.tgz -C /data . + +# from your laptop (after copying both files over) +gcloud storage cp elearning.sql.gz gs://$PROJECT_ID-ops/migration/ +gcloud sql import sql elearning-db gs://$PROJECT_ID-ops/migration/elearning.sql.gz --database=elearning --user=elearning +mkdir uploads && tar xzf uploads.tgz -C uploads && gcloud storage rsync -r uploads gs://$PROJECT_ID-uploads +``` + +Import before the first `deploy.sh`, or stop the backend while importing: Flyway sees the imported +`flyway_schema_history` and only applies the migrations the VPS did not have yet. + +## Tearing down + +`deploy/gcp/99-teardown.sh` deletes everything above (asks you to type the project id). Deleting the +whole project (`gcloud projects delete`) is the most thorough option for a demo project. diff --git a/deploy/gcp/certbot.sh b/deploy/gcp/certbot.sh new file mode 100755 index 0000000..fa9f490 --- /dev/null +++ b/deploy/gcp/certbot.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Issues the Let's Encrypt certificate on the VM (HTTP-01 challenge through host Nginx) and turns on +# the HTTP -> HTTPS redirect. Run once, after the DNS A record points at the VM's static IP. +# Renewal: the certbot package installs a systemd timer; check it with `systemctl list-timers certbot`. +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" +: "${LETSENCRYPT_EMAIL:?}" + +ip="$(gcloud compute addresses describe elearning-ip --region="$REGION" --format='value(address)')" +resolved="$(dig +short "$DOMAIN" A | tail -n1 || true)" +if [[ "$resolved" != "$ip" ]]; then + echo "$DOMAIN resolves to '${resolved:-nothing}', expected $ip. Fix the DNS record first." >&2 + exit 1 +fi + +step "Certbot for $DOMAIN" +gcloud compute ssh "$VM_NAME" --zone="$ZONE" --tunnel-through-iap --command="set -euo pipefail +sudo certbot --nginx -d '$DOMAIN' -m '$LETSENCRYPT_EMAIL' --agree-tos --no-eff-email --redirect -n +sudo certbot renew --dry-run +systemctl list-timers certbot.timer --no-pager" + +step "Done: https://$DOMAIN" diff --git a/deploy/gcp/cloudbuild.yaml b/deploy/gcp/cloudbuild.yaml new file mode 100644 index 0000000..33ebcad --- /dev/null +++ b/deploy/gcp/cloudbuild.yaml @@ -0,0 +1,24 @@ +# Builds both images on Cloud Build (x86_64, same as the e2 VM) and pushes them to Artifact Registry. +# Building on an Apple Silicon laptop would produce arm64 images that the VM cannot run without emulation. +# gcloud builds submit --config deploy/gcp/cloudbuild.yaml --substitutions=_REGISTRY=...,_TAG=... +steps: + - id: backend + name: gcr.io/cloud-builders/docker + args: ["build", "-t", "${_REGISTRY}/backend:${_TAG}", "-t", "${_REGISTRY}/backend:latest", "backend"] + waitFor: ["-"] + - id: frontend + name: gcr.io/cloud-builders/docker + args: ["build", "-t", "${_REGISTRY}/frontend:${_TAG}", "-t", "${_REGISTRY}/frontend:latest", "frontend"] + waitFor: ["-"] + +images: + - "${_REGISTRY}/backend:${_TAG}" + - "${_REGISTRY}/backend:latest" + - "${_REGISTRY}/frontend:${_TAG}" + - "${_REGISTRY}/frontend:latest" + +options: + logging: CLOUD_LOGGING_ONLY + machineType: E2_HIGHCPU_8 + +timeout: 1200s diff --git a/deploy/gcp/deploy.sh b/deploy/gcp/deploy.sh new file mode 100755 index 0000000..c99e549 --- /dev/null +++ b/deploy/gcp/deploy.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# Builds the images on Cloud Build and rolls them out on the VM. Run from your laptop: +# deploy/gcp/deploy.sh # build the current commit and deploy it +# deploy/gcp/deploy.sh --no-build # redeploy an image tag that already exists (IMAGE_TAG=...) +# +# Replaces Part 4's deploy.sh (git pull + docker build on the server): the VM never builds anything. +source "$(dirname "${BASH_SOURCE[0]}")/lib.sh" + +cd "$REPO_ROOT" +IMAGE_TAG="${IMAGE_TAG:-$(git rev-parse --short HEAD)}" +if [[ -n "$(git status --porcelain -- backend frontend)" ]]; then + note "warning: uncommitted changes in backend/ or frontend/ are built into $IMAGE_TAG" +fi + +if [[ "${1:-}" != "--no-build" ]]; then + step "Cloud Build: backend + frontend -> $REGISTRY (tag $IMAGE_TAG)" + gcloud builds submit --region="$REGION" --config=deploy/gcp/cloudbuild.yaml \ + --substitutions="_REGISTRY=$REGISTRY,_TAG=$IMAGE_TAG" . +fi + +ssh_vm() { gcloud compute ssh "$VM_NAME" --zone="$ZONE" --tunnel-through-iap --command="$1"; } + +step "Copying compose file, env script and Nginx config to the VM (SSH through IAP)" +sed "s/__DOMAIN__/$DOMAIN/g" deploy/gcp/vm/nginx-elearning.conf >"/tmp/nginx-elearning.$$.conf" +gcloud compute scp --zone="$ZONE" --tunnel-through-iap \ + docker-compose.gcp.yml deploy/gcp/vm/render-env.sh "/tmp/nginx-elearning.$$.conf" "$VM_NAME:/tmp/" +rm -f "/tmp/nginx-elearning.$$.conf" + +step "Rolling out $IMAGE_TAG" +ssh_vm "set -euo pipefail +sudo install -m 0640 /tmp/docker-compose.gcp.yml /opt/elearning/docker-compose.gcp.yml +sudo install -m 0750 /tmp/render-env.sh /opt/elearning/render-env.sh +# Install the HTTP site only the first time: afterwards Certbot owns the file (it adds the TLS block). +if [ ! -f /etc/nginx/sites-available/elearning ]; then + sudo install -m 0644 /tmp/nginx-elearning.$$.conf /etc/nginx/sites-available/elearning + sudo ln -sf /etc/nginx/sites-available/elearning /etc/nginx/sites-enabled/elearning + sudo rm -f /etc/nginx/sites-enabled/default + sudo nginx -t && sudo systemctl reload nginx +fi +rm -f /tmp/docker-compose.gcp.yml /tmp/render-env.sh /tmp/nginx-elearning.$$.conf +sudo GCP_PROJECT='$PROJECT_ID' DOMAIN='$DOMAIN' REGISTRY='$REGISTRY' IMAGE_TAG='$IMAGE_TAG' \ + CLOUD_SQL_INSTANCE='$CLOUD_SQL_CONNECTION' UPLOADS_BUCKET='$UPLOADS_BUCKET' \ + POSTGRES_DB='$SQL_DATABASE' POSTGRES_USER='$SQL_USER' /opt/elearning/render-env.sh +cd /opt/elearning +sudo docker compose -f docker-compose.gcp.yml pull --quiet +sudo docker compose -f docker-compose.gcp.yml up -d --remove-orphans +sudo docker compose -f docker-compose.gcp.yml ps +sudo docker image prune -f >/dev/null" + +step "Deployed $IMAGE_TAG. Health: https://$DOMAIN (after certbot.sh) or the logs:" +note "gcloud compute ssh $VM_NAME --zone=$ZONE --tunnel-through-iap --command='sudo docker logs --tail 50 elearning-backend'" diff --git a/deploy/gcp/gcp.env.example b/deploy/gcp/gcp.env.example new file mode 100644 index 0000000..73abb93 --- /dev/null +++ b/deploy/gcp/gcp.env.example @@ -0,0 +1,30 @@ +# Copy to deploy/gcp/.env.gcp (git-ignored) and fill in. Every script in deploy/gcp reads it. + +PROJECT_ID=elearning-gcp-demo-12345 +# Jakarta: closest to Indonesian schools, and keeps student data in the country. +REGION=asia-southeast2 +ZONE=asia-southeast2-a + +# Public hostname. Point an A record at the static IP printed by 30-vm.sh before running certbot. +DOMAIN=elearning.example.com +LETSENCRYPT_EMAIL=admin@example.com + +# Compute Engine VM (Docker Compose host). e2-medium: 2 vCPU (shared), 4 GB. +VM_NAME=elearning-vm +VM_MACHINE_TYPE=e2-medium + +# Cloud SQL for PostgreSQL. db-g1-small is shared-core (cheap, no SLA); db-custom-1-3840 is dedicated. +SQL_INSTANCE=elearning-db +SQL_TIER=db-g1-small +SQL_DATABASE=elearning +SQL_USER=elearning + +# Artifact Registry repository for the backend and frontend images +AR_REPO=elearning + +# Exam result e-mails (Cloud Run function). The SMTP password is asked for by 40-functions.sh and +# stored in Secret Manager. Port 25 is blocked on Google Cloud: use 587 (STARTTLS) or 465 (TLS). +SMTP_HOST=smtp.gmail.com +SMTP_PORT=587 +SMTP_USER=notifications@example.com +SMTP_FROM="E-Learning " diff --git a/deploy/gcp/lib.sh b/deploy/gcp/lib.sh new file mode 100755 index 0000000..b9ed3c2 --- /dev/null +++ b/deploy/gcp/lib.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# Shared by every script in deploy/gcp: loads .env.gcp, derives resource names, small helpers. +# The scripts are safe to re-run: each step checks whether its resource already exists. +# shellcheck disable=SC2034 # variables are used by the scripts that source this file + +set -euo pipefail + +GCP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$GCP_DIR/../.." && pwd)" +CONFIG="${GCP_CONFIG:-$GCP_DIR/.env.gcp}" + +if [[ ! -f "$CONFIG" ]]; then + echo "Missing $CONFIG. Copy deploy/gcp/gcp.env.example to deploy/gcp/.env.gcp and fill it in." >&2 + exit 1 +fi +set -a +# shellcheck source=/dev/null +source "$CONFIG" +set +a + +: "${PROJECT_ID:?}" "${REGION:?}" "${ZONE:?}" "${DOMAIN:?}" "${VM_NAME:?}" "${SQL_INSTANCE:?}" "${SQL_DATABASE:?}" "${SQL_USER:?}" "${AR_REPO:?}" + +# Every gcloud call below targets this project, whatever `gcloud config` says. +export CLOUDSDK_CORE_PROJECT="$PROJECT_ID" + +UPLOADS_BUCKET="${PROJECT_ID}-uploads" +OPS_BUCKET="${PROJECT_ID}-ops" # SQL exports and the mailer's dedup markers +REGISTRY="${REGION}-docker.pkg.dev/${PROJECT_ID}/${AR_REPO}" +CLOUD_SQL_CONNECTION="${PROJECT_ID}:${REGION}:${SQL_INSTANCE}" +TOPIC="exam-results" +DEAD_LETTER_TOPIC="exam-results-dead-letter" + +sa_email() { echo "$1@${PROJECT_ID}.iam.gserviceaccount.com"; } +VM_SA="$(sa_email elearning-vm)" # the VM: Cloud SQL client, secrets, registry, Pub/Sub publisher +STORAGE_SA="$(sa_email elearning-storage)" # owns the HMAC key the backend uses for the uploads bucket +MAILER_SA="$(sa_email fn-exam-result-mailer)" +INSPECTOR_SA="$(sa_email fn-upload-inspector)" +SQL_EXPORT_SA="$(sa_email fn-sql-export)" +SCHEDULER_SA="$(sa_email elearning-scheduler)" + +step() { printf '\n\033[1;36m==> %s\033[0m\n' "$*"; } +note() { printf ' %s\n' "$*"; } +quietly() { "$@" >/dev/null 2>&1; } + +ensure_sa() { # name, display name + quietly gcloud iam service-accounts describe "$(sa_email "$1")" || + gcloud iam service-accounts create "$1" --display-name="$2" +} + +project_role() { # member, role + gcloud projects add-iam-policy-binding "$PROJECT_ID" --member="$1" --role="$2" --condition=None >/dev/null +} + +# Secrets live in the region only (user-managed replication), next to the data they protect. +ensure_secret() { # name, value (only used when the secret does not exist yet) + if ! quietly gcloud secrets describe "$1"; then + printf '%s' "$2" | gcloud secrets create "$1" --replication-policy=user-managed --locations="$REGION" --data-file=- + else + note "secret $1 exists (kept)" + fi +} + +grant_secret() { # secret, service account email + gcloud secrets add-iam-policy-binding "$1" --member="serviceAccount:$2" --role=roles/secretmanager.secretAccessor >/dev/null +} + +project_number() { gcloud projects describe "$PROJECT_ID" --format='value(projectNumber)'; } diff --git a/deploy/gcp/lifecycle-ops.json b/deploy/gcp/lifecycle-ops.json new file mode 100644 index 0000000..5b7313e --- /dev/null +++ b/deploy/gcp/lifecycle-ops.json @@ -0,0 +1,16 @@ +{ + "rule": [ + { + "action": { "type": "Delete" }, + "condition": { "age": 30, "matchesPrefix": ["mailer-dedup/"] } + }, + { + "action": { "type": "SetStorageClass", "storageClass": "COLDLINE" }, + "condition": { "age": 30, "matchesPrefix": ["sql-exports/"] } + }, + { + "action": { "type": "Delete" }, + "condition": { "age": 365, "matchesPrefix": ["sql-exports/"] } + } + ] +} diff --git a/deploy/gcp/vm/bootstrap.sh b/deploy/gcp/vm/bootstrap.sh new file mode 100755 index 0000000..8595888 --- /dev/null +++ b/deploy/gcp/vm/bootstrap.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# Startup script of the VM (runs as root on every boot; every step is idempotent). +# Installs Docker Engine + Compose plugin, Nginx and Certbot, adds swap, and lets root pull from +# Artifact Registry with the VM's service account. + +set -euo pipefail +exec >>/var/log/elearning-bootstrap.log 2>&1 +echo "=== bootstrap $(date -Is)" + +export DEBIAN_FRONTEND=noninteractive +REGION="$(curl -s -H 'Metadata-Flavor: Google' http://169.254.169.254/computeMetadata/v1/instance/zone | awk -F/ '{print $NF}' | sed 's/-[a-z]$//')" + +if ! command -v docker >/dev/null; then + apt-get update -q + apt-get install -y -q ca-certificates curl gnupg + install -m 0755 -d /etc/apt/keyrings + curl -fsSL https://download.docker.com/linux/debian/gpg -o /etc/apt/keyrings/docker.asc + chmod a+r /etc/apt/keyrings/docker.asc + echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/debian $(. /etc/os-release && echo "$VERSION_CODENAME") stable" \ + >/etc/apt/sources.list.d/docker.list + apt-get update -q + apt-get install -y -q docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin +fi + +if ! command -v nginx >/dev/null; then + apt-get install -y -q nginx certbot python3-certbot-nginx +fi + +# 2 GB swap: the JVM, Redis and Nginx share 4 GB (same reasoning as on the VPS in Part 4). +if ! swapon --show | grep -q /swapfile; then + if [[ ! -f /swapfile ]]; then + fallocate -l 2G /swapfile + chmod 600 /swapfile + mkswap /swapfile + fi + swapon /swapfile + grep -q /swapfile /etc/fstab || echo '/swapfile none swap sw 0 0' >>/etc/fstab +fi + +# docker pull from Artifact Registry as root, using the VM's service account (no key file). +gcloud auth configure-docker "${REGION}-docker.pkg.dev" --quiet + +install -d -m 0750 /opt/elearning +echo "=== bootstrap done $(date -Is)" diff --git a/deploy/gcp/vm/nginx-elearning.conf b/deploy/gcp/vm/nginx-elearning.conf new file mode 100644 index 0000000..1a43a75 --- /dev/null +++ b/deploy/gcp/vm/nginx-elearning.conf @@ -0,0 +1,39 @@ +# Host Nginx on the VM: same role as in Part 4 (TLS termination via Certbot, reverse proxy to the +# frontend container on 127.0.0.1:8088). __DOMAIN__ is replaced by deploy.sh. +# Certbot adds the 443 server block and the HTTP -> HTTPS redirect (certbot.sh). + +server { + listen 80; + listen [::]:80; + server_name __DOMAIN__; + + server_tokens off; + # Allow up to 50MB for learning materials (same limit as the frontend container and Spring) + client_max_body_size 50M; + + access_log /var/log/nginx/elearning_access.log; + error_log /var/log/nginx/elearning_error.log; + + # Frontend SPA and REST API + location / { + proxy_pass http://127.0.0.1:8088; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + # WebSocket (STOMP) for live exam monitoring + location /ws { + proxy_pass http://127.0.0.1:8088/ws; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "Upgrade"; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 86400s; + proxy_send_timeout 86400s; + } +} diff --git a/deploy/gcp/vm/render-env.sh b/deploy/gcp/vm/render-env.sh new file mode 100755 index 0000000..ee28d70 --- /dev/null +++ b/deploy/gcp/vm/render-env.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Runs ON the VM (called by deploy.sh). Writes /opt/elearning/.env for docker-compose.gcp.yml. +# Secrets are read from Secret Manager with the VM's own service account, so they never pass +# through the machine that runs the deployment. +# +# Non-secret settings arrive as environment variables from deploy.sh: +# GCP_PROJECT DOMAIN REGISTRY IMAGE_TAG CLOUD_SQL_INSTANCE UPLOADS_BUCKET POSTGRES_DB POSTGRES_USER + +set -euo pipefail +: "${GCP_PROJECT:?}" "${DOMAIN:?}" "${REGISTRY:?}" "${IMAGE_TAG:?}" "${CLOUD_SQL_INSTANCE:?}" "${UPLOADS_BUCKET:?}" "${POSTGRES_DB:?}" "${POSTGRES_USER:?}" + +secret() { gcloud secrets versions access latest --secret="$1" --project="$GCP_PROJECT"; } + +umask 077 +tmp="$(mktemp /opt/elearning/.env.XXXXXX)" +{ + echo "GCP_PROJECT=$GCP_PROJECT" + echo "DOMAIN=$DOMAIN" + echo "REGISTRY=$REGISTRY" + echo "IMAGE_TAG=$IMAGE_TAG" + echo "CLOUD_SQL_INSTANCE=$CLOUD_SQL_INSTANCE" + echo "UPLOADS_BUCKET=$UPLOADS_BUCKET" + echo "POSTGRES_DB=$POSTGRES_DB" + echo "POSTGRES_USER=$POSTGRES_USER" + echo "POSTGRES_PASSWORD=$(secret db-password)" + echo "JWT_SECRET=$(secret jwt-secret)" + echo "GCS_HMAC_ACCESS_ID=$(secret gcs-hmac-access-id)" + echo "GCS_HMAC_SECRET=$(secret gcs-hmac-secret)" +} >"$tmp" +mv "$tmp" /opt/elearning/.env +echo "Wrote /opt/elearning/.env (mode 600, image tag $IMAGE_TAG)" diff --git a/docker-compose.gcp.yml b/docker-compose.gcp.yml new file mode 100644 index 0000000..fd1c9b5 --- /dev/null +++ b/docker-compose.gcp.yml @@ -0,0 +1,121 @@ +# Production on Google Cloud: one Compute Engine VM running this file, with +# - PostgreSQL on Cloud SQL, reached through the Cloud SQL Auth Proxy container below +# - uploads in Cloud Storage (S3-compatible XML API + HMAC key) +# - exam result events to Pub/Sub (transactional outbox -> Cloud Run function -> e-mail) +# - Redis still in a container (refresh tokens and rate limits only; losing it logs users out) +# - images built by Cloud Build and pulled from Artifact Registry (nothing is built on the VM) +# +# The .env next to this file is written by deploy/gcp/vm/render-env.sh from Secret Manager. +# Walkthrough: deploy/gcp/README.md + +x-logging: &gcp-logging + # Container logs go to Cloud Logging; `docker logs` keeps working (Docker's dual logging). + driver: gcplogs + options: + gcp-log-cmd: "false" + +services: + cloud-sql-proxy: + image: gcr.io/cloud-sql-connectors/cloud-sql-proxy:2.14.0-alpine + container_name: elearning-cloud-sql-proxy + restart: always + # Authenticates with the VM's service account (roles/cloudsql.client) through the metadata server; + # the connection to Cloud SQL is TLS with an ephemeral certificate. No password file, no key file. + command: + - "--address=0.0.0.0" + - "--port=5432" + - "--health-check" + - "--http-address=0.0.0.0" + - "--http-port=9090" + - "${CLOUD_SQL_INSTANCE:?CLOUD_SQL_INSTANCE is required (project:region:instance)}" + healthcheck: + test: ["CMD", "wget", "-qO-", "http://127.0.0.1:9090/readiness"] + interval: 10s + timeout: 5s + retries: 5 + start_period: 10s + logging: *gcp-logging + networks: + - elearning-network + + redis: + image: redis:7-alpine + container_name: elearning-redis + restart: always + volumes: + - redis_data:/data + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 5s + retries: 5 + logging: *gcp-logging + networks: + - elearning-network + + backend: + image: ${REGISTRY:?REGISTRY is required}/backend:${IMAGE_TAG:-latest} + container_name: elearning-backend + restart: always + environment: + SPRING_DATASOURCE_URL: jdbc:postgresql://cloud-sql-proxy:5432/${POSTGRES_DB:-elearning} + SPRING_DATASOURCE_USERNAME: ${POSTGRES_USER:-elearning} + SPRING_DATASOURCE_PASSWORD: ${POSTGRES_PASSWORD:?POSTGRES_PASSWORD is required} + SPRING_DATA_REDIS_HOST: redis + SPRING_DATA_REDIS_PORT: 6379 + JWT_SECRET: ${JWT_SECRET:?JWT_SECRET is required} + # Uploads: Cloud Storage through its S3-compatible API + APP_STORAGE_TYPE: s3 + APP_STORAGE_S3_ENDPOINT: https://storage.googleapis.com + APP_STORAGE_S3_REGION: ${APP_STORAGE_S3_REGION:-auto} + APP_STORAGE_S3_PATH_STYLE: "true" + APP_STORAGE_S3_BUCKET: ${UPLOADS_BUCKET:?UPLOADS_BUCKET is required} + APP_STORAGE_S3_ACCESS_KEY: ${GCS_HMAC_ACCESS_ID:?GCS_HMAC_ACCESS_ID is required} + APP_STORAGE_S3_SECRET_KEY: ${GCS_HMAC_SECRET:?GCS_HMAC_SECRET is required} + # Exam result e-mails + APP_NOTIFY_EXAM_RESULTS: ${APP_NOTIFY_EXAM_RESULTS:-true} + APP_OUTBOX_PUBLISHER: pubsub + APP_OUTBOX_PUBSUB_TOPIC: projects/${GCP_PROJECT:?GCP_PROJECT is required}/topics/exam-results + APP_CORS_ALLOWED_ORIGINS: https://${DOMAIN:?DOMAIN is required} + APP_DEMO_MODE: ${APP_DEMO_MODE:-false} + APP_REGISTRATION_ENABLED: ${APP_REGISTRATION_ENABLED:-false} + SPRINGDOC_ENABLED: "false" + LOG_LEVEL_APP: ${LOG_LEVEL_APP:-INFO} + # e2-medium has 4 GB: leave room for Redis, Nginx and the OS + JAVA_TOOL_OPTIONS: ${JAVA_TOOL_OPTIONS:--XX:MaxRAMPercentage=60} + mem_limit: ${BACKEND_MEM_LIMIT:-2g} + healthcheck: + test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:8080/actuator/health"] + interval: 10s + timeout: 5s + retries: 5 + start_period: 60s + depends_on: + cloud-sql-proxy: + condition: service_healthy + redis: + condition: service_healthy + logging: *gcp-logging + networks: + - elearning-network + + frontend: + image: ${REGISTRY}/frontend:${IMAGE_TAG:-latest} + container_name: elearning-frontend + restart: always + ports: + # Host Nginx (TLS, Let's Encrypt) proxies to this port; never exposed directly. + - "127.0.0.1:${FRONTEND_PORT:-8088}:80" + depends_on: + backend: + condition: service_healthy + logging: *gcp-logging + networks: + - elearning-network + +volumes: + redis_data: + +networks: + elearning-network: + driver: bridge diff --git a/functions/exam-result-mailer/.gcloudignore b/functions/exam-result-mailer/.gcloudignore new file mode 100644 index 0000000..66fc6d6 --- /dev/null +++ b/functions/exam-result-mailer/.gcloudignore @@ -0,0 +1,3 @@ +node_modules/ +*.test.js +.gcloudignore diff --git a/functions/exam-result-mailer/handler.js b/functions/exam-result-mailer/handler.js new file mode 100644 index 0000000..30ac4e6 --- /dev/null +++ b/functions/exam-result-mailer/handler.js @@ -0,0 +1,97 @@ +// Pure logic of the exam result mailer: no SMTP, no Cloud Storage. index.js wires the real +// dependencies; tests pass fakes. + +/** A message that will never succeed (bad JSON, no address). Acknowledge it instead of retrying. */ +export class PermanentError extends Error {} + +const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + +/** Reads the outbox payload and event id from a Pub/Sub CloudEvent. */ +export function parseResultEvent(cloudEvent) { + const message = cloudEvent?.data?.message; + if (!message?.data) throw new PermanentError("Pub/Sub message has no data"); + + let payload; + try { + payload = JSON.parse(Buffer.from(message.data, "base64").toString("utf8")); + } catch { + throw new PermanentError("Message data is not JSON"); + } + if (typeof payload.studentEmail !== "string" || !EMAIL.test(payload.studentEmail)) { + throw new PermanentError("Message has no valid studentEmail"); + } + if (typeof payload.examTitle !== "string" || !payload.examTitle.trim()) { + throw new PermanentError("Message has no examTitle"); + } + + const eventId = message.attributes?.eventId || `exam.result_ready:${payload.attemptId}`; + return { eventId, payload }; +} + +const escapeHtml = (value) => + String(value).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]); + +/** Indonesian e-mail: the platform is used by Indonesian schools. */ +export function renderResultEmail(payload, appUrl) { + const name = payload.studentName || "Siswa"; + const title = payload.examTitle; + const subject = `Hasil ujian: ${title}`; + + const lines = [`Halo ${name},`, "", `Ujian "${title}" sudah selesai dinilai.`]; + if (payload.showScore) { + lines.push(`Nilai kamu: ${payload.score} (batas lulus ${payload.passingScore}).`); + lines.push(payload.passed ? "Selamat, kamu lulus." : "Kamu belum mencapai batas lulus."); + } else { + lines.push("Gurumu belum menampilkan nilai untuk ujian ini."); + } + if (appUrl) lines.push("", `Lihat detailnya di ${appUrl}`); + lines.push("", "Email ini dikirim otomatis, mohon tidak dibalas."); + + const text = lines.join("\n"); + const html = lines.map((line) => (line ? `

${escapeHtml(line)}

` : "")).join("\n"); + return { subject, text, html }; +} + +/** + * Builds the CloudEvent handler. + * + * Pub/Sub delivers at least once, and the outbox can publish an event twice after a crash. The handler + * claims the event id first (an object created only if it does not exist yet), sends the e-mail, and + * releases the claim if sending fails so the retry can try again. + * + * @param {object} deps + * @param {(eventId: string) => Promise} deps.claim true if this delivery owns the event + * @param {(eventId: string) => Promise} deps.release + * @param {(mail: {to: string, subject: string, text: string, html: string}) => Promise} deps.send + * @param {string} [deps.appUrl] + * @param {{info: Function, warn: Function, error: Function}} [deps.log] + */ +export function createMailerHandler({ claim, release, send, appUrl, log = console }) { + return async function handle(cloudEvent) { + let event; + try { + event = parseResultEvent(cloudEvent); + } catch (error) { + if (error instanceof PermanentError) { + log.error(JSON.stringify({ severity: "ERROR", message: `Dropping exam result message: ${error.message}` })); + return; // acknowledged: retrying cannot fix it + } + throw error; + } + + if (!(await claim(event.eventId))) { + log.info(JSON.stringify({ severity: "INFO", message: "Duplicate delivery skipped", eventId: event.eventId })); + return; + } + + const mail = renderResultEmail(event.payload, appUrl); + try { + await send({ to: event.payload.studentEmail, ...mail }); + } catch (error) { + await release(event.eventId); + throw error; // Pub/Sub retries the delivery + } + // No address in the log: it is personal data and Cloud Logging keeps it for weeks. + log.info(JSON.stringify({ severity: "INFO", message: "Exam result e-mail sent", eventId: event.eventId })); + }; +} diff --git a/functions/exam-result-mailer/handler.test.js b/functions/exam-result-mailer/handler.test.js new file mode 100644 index 0000000..848d043 --- /dev/null +++ b/functions/exam-result-mailer/handler.test.js @@ -0,0 +1,83 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { createMailerHandler, parseResultEvent, renderResultEmail } from "./handler.js"; + +const event = (payload, attributes = { eventId: "exam.result_ready:500" }) => ({ + data: { message: { data: Buffer.from(JSON.stringify(payload)).toString("base64"), attributes } }, +}); +const base = { attemptId: 500, examTitle: "Quiz 1", studentName: "Andi", studentEmail: "andi@siswa.id" }; +const silent = { info() {}, warn() {}, error() {} }; + +test("parses the outbox payload and the event id", () => { + const { eventId, payload } = parseResultEvent(event(base)); + assert.equal(eventId, "exam.result_ready:500"); + assert.equal(payload.studentEmail, "andi@siswa.id"); +}); + +test("shows the score only when the teacher allows it", () => { + const shown = renderResultEmail({ ...base, showScore: true, score: 85, passed: true, passingScore: 70 }); + assert.match(shown.text, /Nilai kamu: 85 \(batas lulus 70\)/); + assert.match(shown.text, /lulus/); + + const hidden = renderResultEmail({ ...base, showScore: false, score: 85 }); + assert.doesNotMatch(hidden.text, /85/); + assert.match(hidden.text, /belum menampilkan nilai/); +}); + +test("escapes HTML in teacher-provided text", () => { + const { html } = renderResultEmail({ ...base, examTitle: "" }); + assert.doesNotMatch(html, /