Skip to content

Commit

Permalink
Drop the transact call in IdService (#2561)
Browse files Browse the repository at this point in the history
* Drop the `transact` call in Id services

All usages already routed through `tm().allocateId()`, which is
guaranteed to be in a transaction.

* Addressing reviews
  • Loading branch information
weiminyu authored Sep 18, 2024
1 parent a988732 commit febdbc0
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 81 deletions.

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.

0 comments on commit febdbc0

Please sign in to comment.