Skip to content

Commit

Permalink
Merge branch 'allocation-logic' of github.com:jicelhay/nomulus into a…
Browse files Browse the repository at this point in the history
…llocation-logic
  • Loading branch information
jicelhay committed Sep 19, 2024
2 parents 3077dc0 + 11b6eeb commit 7cf1920
Show file tree
Hide file tree
Showing 9 changed files with 215 additions and 130 deletions.
106 changes: 65 additions & 41 deletions console-webapp/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
Expand Down Expand Up @@ -224,7 +225,7 @@ public <T> T transactNoRetry(
EntityTransaction txn = txnInfo.entityManager.getTransaction();
try {
txn.begin();
txnInfo.start(clock, readOnly ? ReplicaDbIdService::allocatedId : IdService::allocateId);
txnInfo.start(clock, readOnly ? ReplicaDbIdService::allocateId : this::fetchIdFromSequence);
if (readOnly) {
getEntityManager().createNativeQuery("SET TRANSACTION READ ONLY").executeUpdate();
logger.atInfo().log("Using read-only SQL replica");
Expand Down Expand Up @@ -558,6 +559,19 @@ private <T> EntityType<T> getEntityType(Class<T> clazz) {
return emf.getMetamodel().entity(clazz);
}

/**
* A SQL Sequence based ID allocator that generates an ID from a monotonically increasing {@link
* AtomicLong}
*
* <p>The generated IDs are project-wide unique.
*/
private long fetchIdFromSequence() {
return (Long)
getEntityManager()
.createNativeQuery("SELECT nextval('project_wide_unique_id_seq')")
.getSingleResult();
}

private record EntityId(String name, Object value) {}

private static ImmutableSet<EntityId> getEntityIdsFromEntity(
Expand Down Expand Up @@ -1038,4 +1052,23 @@ public ImmutableList<T> list() {
.collect(toImmutableList());
}
}

/**
* Provides {@code long} values for use as {@code id} by JPA model entities in (read-only)
* transactions in the replica database. Each id is only unique in the JVM instance.
*
* <p>The {@link #fetchIdFromSequence database sequence-based id allocator} cannot be used with
* the replica because id generation is a write operation.
*/
private static final class ReplicaDbIdService {

private static final AtomicLong nextId = new AtomicLong(1);

/**
* Returns the next long value from a {@link AtomicLong}. Each id is unique in the JVM instance.
*/
static long allocateId() {
return nextId.getAndIncrement();
}
}
}

This file was deleted.

Loading

0 comments on commit 7cf1920

Please sign in to comment.