Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .gcloudignore
Original file line number Diff line number Diff line change
@@ -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
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
docs_backup/

# Operating System
.DS_Store
Thumbs.db
Expand Down Expand Up @@ -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
Original file line number Diff line number Diff line change
@@ -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;
}
Original file line number Diff line number Diff line change
@@ -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());
}
}
Original file line number Diff line number Diff line change
@@ -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<String> {

/** 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<String> 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);
}
}
}
58 changes: 58 additions & 0 deletions backend/src/main/java/com/elearning/common/outbox/OutboxEvent.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
Original file line number Diff line number Diff line change
@@ -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<OutboxEvent, Long> {

/**
* 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<OutboxEvent> lockPendingBatch(@Param("maxAttempts") int maxAttempts, @Param("limit") int limit);
}
85 changes: 85 additions & 0 deletions backend/src/main/java/com/elearning/common/outbox/OutboxRelay.java
Original file line number Diff line number Diff line change
@@ -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.
*
* <ul>
* <li>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).</li>
* <li>Rows are locked with SKIP LOCKED, so several backend instances can run the relay safely.</li>
* <li>Delivery is at least once: a crash between publishing and committing republishes the event.
* Consumers deduplicate on the {@code eventId} attribute.</li>
* </ul>
*
* 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<OutboxEvent> 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);
}
}
Original file line number Diff line number Diff line change
@@ -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}).
*
* <p>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<String> 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<String> accessToken,
String endpoint, String topic) {
if (topic == null || !topic.matches("projects/[^/]+/topics/[^/]+")) {
throw new IllegalArgumentException(
"app.outbox.pubsub.topic must look like projects/<project>/topics/<topic>, 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<String, Object> 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<String> 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)));
}
}
}
Loading
Loading