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
15 changes: 15 additions & 0 deletions teaql-core/src/main/java/io/teaql/core/BaseEntity.java
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ public void __internalSetQueryFacets(Map<String, ? extends SmartList<?>> facets)
* Shared change tracking root for the entire entity graph.
*/
private EntityMutationLedger entityMutationLedger;
private boolean transactionOutcomeUnknown;
// Database baseline is a row-owned scalar, not a reason to allocate a ledger.
private Long hydratedOriginalVersion;

Expand Down Expand Up @@ -499,6 +500,20 @@ public EntityMutationLedger getEntityMutationLedger() {
@com.fasterxml.jackson.annotation.JsonIgnore
public boolean __internalHasMutationLedger() { return entityMutationLedger != null; }

@FrameworkInternal("Retain transaction replay denial across ledger replacement")
public void __internalFenceTransactionReplay() {
transactionOutcomeUnknown = true;
if (entityMutationLedger != null) entityMutationLedger.__internalFenceTransactionReplay();
}

@FrameworkInternal("Called before a graph reuses its previously materialized write baseline")
public void __internalRequireTransactionReplayAllowed() {
if (transactionOutcomeUnknown
|| entityMutationLedger != null && entityMutationLedger.__internalTransactionReplayFenced()) {
throw new TransactionOutcomeUnknownException();
}
}

public void setEntityMutationLedger(EntityMutationLedger entityMutationLedger) {
if (this.entityMutationLedger != null) this.entityMutationLedger.requireSaveable();
this.entityMutationLedger = entityMutationLedger;
Expand Down
10 changes: 10 additions & 0 deletions teaql-core/src/main/java/io/teaql/core/EntityMutationLedger.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,16 @@ public class EntityMutationLedger {
private boolean committedStateRequiresReload;
private boolean transactionOutcomeUnknownRequiresReload;

@FrameworkInternal("Fence a graph whose database transaction did not confirm completion")
public void __internalFenceTransactionReplay() {
markTransactionOutcomeUnknownRequiresReload();
}

@FrameworkInternal("Test whether an existing graph must be reloaded before replay")
public boolean __internalTransactionReplayFenced() {
return transactionOutcomeUnknownRequiresReload;
}

// --- Change Set Stack ---

public void pushChangeSet() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package io.teaql.core;

/** Database commit was confirmed before a completion action failed. */
public final class TransactionCommittedException extends TeaQLRuntimeException {
public TransactionCommittedException(Throwable cause) {
super("TRANSACTION_ALREADY_COMMITTED: a completion action failed", cause);
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package io.teaql.core;

import java.util.function.Supplier;

public interface TransactionExecutor extends DataServiceExecutor {
@FrameworkInternal("Physical transaction ownership; not a workspace API")
default boolean hasActiveTransaction() { return false; }
@FrameworkInternal("Atomic graph participant identity; not a workspace API")
default Object transactionResource() { return null; }
/** Returns true only when callbacks belong to the currently active physical transaction. */
Expand All @@ -15,5 +19,9 @@ default boolean registerTransactionSynchronization(
/** True only when the next transaction invocation owns physical completion. */
@FrameworkInternal("Select reconciliation timing without changing the workspace transaction API")
default boolean ownsNextPhysicalTransaction(UserContext context) { return false; }
@FrameworkInternal("Keep operations without the bound UserContext out of its physical transaction")
default <T> T withoutActiveTransaction(Supplier<T> work) {
throw new UnsupportedOperationException("The data service cannot suspend its active transaction");
}
<T> T executeInTransaction(UserContext context, TransactionCallback<T> action);
}
6 changes: 6 additions & 0 deletions teaql-core/src/main/java/io/teaql/core/UserContext.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package io.teaql.core;

import java.util.stream.Stream;
import java.util.function.Function;
import io.teaql.core.utils.OptNullBasicTypeFromObjectGetter;
import java.util.List;
import io.teaql.data.dynamic.DynamicFieldsFacade;
Expand All @@ -22,6 +23,11 @@

public interface UserContext extends OptNullBasicTypeFromObjectGetter<String> {

/** Execute the callback with a UserContext bound to one database transaction. */
default <T> T transaction(Function<UserContext, T> work) {
throw new UnsupportedOperationException("This UserContext does not support transactions");
}

String TEAQL_LOCALE = "teaql.locale";
String TEAQL_I18N_CATALOG = "teaql.i18n.catalog";
String TEAQL_CHECKER_MESSAGES = "teaql.checker.messages";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ public <T> T executeInTransaction(UserContext context, TransactionCallback<T> ac

@Override public Object transactionResource() { return executionAdapter; }

@Override public boolean hasActiveTransaction() { return executionAdapter.hasActiveTransaction(); }

@Override public boolean registerTransactionSynchronization(
UserContext context, Runnable committed, Runnable rolledBack) {
return executionAdapter.registerTransactionSynchronization(committed, rolledBack);
Expand All @@ -94,6 +96,10 @@ public <T> T executeInTransaction(UserContext context, TransactionCallback<T> ac
return !executionAdapter.hasActiveTransaction();
}

@Override public <T> T withoutActiveTransaction(java.util.function.Supplier<T> work) {
return executionAdapter.withoutActiveTransaction(work);
}

@Override
public void ensureSchema(UserContext context, io.teaql.core.SchemaExecutor.Invocation invocation) {
io.teaql.core.SchemaExecutor.Invocation.requireContextOwned(invocation);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ default void restrictOrdinaryMutations() {

/** Provider-owned completion callbacks. Unsupported adapters must not claim registration. */
default boolean registerTransactionSynchronization(Runnable committed, Runnable rolledBack) { return false; }
default <T> T withoutActiveTransaction(java.util.function.Supplier<T> work) {
throw new UnsupportedOperationException("The SQL adapter cannot suspend its active transaction");
}

default boolean registerTransactionSynchronization(Runnable committed, Runnable rolledBack, Runnable unknown) {
return registerTransactionSynchronization(committed, rolledBack);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,19 @@ private void markTransactionRollbackOnly() {

@Override public boolean hasActiveTransaction() { return transactionConnection.get() != null; }

@Override public <T> T withoutActiveTransaction(java.util.function.Supplier<T> work) {
Connection connection = transactionConnection.get();
if (connection == null) return work.get();
var completion = transactionCompletion.get();
transactionConnection.remove();
transactionCompletion.remove();
try { return work.get(); }
finally {
transactionConnection.set(connection);
transactionCompletion.set(completion);
}
}

@Override public boolean registerTransactionSynchronization(Runnable committed, Runnable rolledBack) {
return registerTransactionSynchronization(committed, rolledBack, () -> {});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
package io.teaql.provider.jdbc;

import io.teaql.core.TransactionOutcomeUnknownException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
Expand All @@ -8,13 +15,22 @@

/** Completion belongs to the physical owner, never to an inner save call. */
public class JdbcTransactionCompletionTest {
private record Source(String url, boolean loseCommitAcknowledgement) implements javax.sql.DataSource {
Source(String url) { this(url, false); }
public java.sql.Connection getConnection() throws java.sql.SQLException {
private interface ConnectionFactory {
Connection open() throws SQLException;
}

private record Source(ConnectionFactory factory) implements javax.sql.DataSource {
private Source(String url) { this(() -> DriverManager.getConnection(url)); }
private Source(String url, boolean loseCommitAcknowledgement) {
this(() -> open(url, loseCommitAcknowledgement));
}
public java.sql.Connection getConnection() throws java.sql.SQLException { return factory.open(); }

private static java.sql.Connection open(String url, boolean loseCommitAcknowledgement) throws java.sql.SQLException {
var connection = java.sql.DriverManager.getConnection(url);
if (!loseCommitAcknowledgement) return connection;
return (java.sql.Connection) java.lang.reflect.Proxy.newProxyInstance(
getClass().getClassLoader(), new Class<?>[]{java.sql.Connection.class},
Source.class.getClassLoader(), new Class<?>[]{java.sql.Connection.class},
(proxy, method, args) -> {
try {
Object result = method.invoke(connection, args);
Expand All @@ -37,11 +53,87 @@ public void setLoginTimeout(int value) {}
public boolean isWrapperFor(Class<?> type) { return false; }
}

private JdbcSqlExecutor fixture() {
var source = new Source("jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1");
var sql = new JdbcSqlExecutor(source);
private static String fixtureUrl() {
String url = "jdbc:h2:mem:" + UUID.randomUUID() + ";DB_CLOSE_DELAY=-1";
var sql = new JdbcSqlExecutor(new Source(url));
sql.execute("CREATE TABLE completion_test(id INT PRIMARY KEY)");
return sql;
return url;
}

private JdbcSqlExecutor fixture() {
return new JdbcSqlExecutor(new Source(fixtureUrl()));
}

private static Source faultSource(InvocationHandler fault) {
return new Source(() -> (Connection) Proxy.newProxyInstance(
Connection.class.getClassLoader(), new Class<?>[]{Connection.class}, fault));
}

@Test public void unconfirmedRollbackCannotReturnAnActiveConnectionToItsPool() throws Exception {
String url = fixtureUrl();
var observations = new ArrayList<String>();
try (var physical = DriverManager.getConnection(url)) {
var sql = new JdbcSqlExecutor(faultSource((proxy, method, args) -> {
switch (method.getName()) {
case "rollback" -> {
observations.add("rollback");
throw new SQLException("PRIVATE_ROLLBACK_DIAGNOSTIC");
}
case "abort" -> {
observations.add("abort");
return null;
}
case "close" -> observations.add("unsafe close");
case "setAutoCommit" -> {
if (Boolean.TRUE.equals(args[0])) observations.add("unsafe autoCommit");
}
default -> { }
}
try { return method.invoke(physical, args); }
catch (InvocationTargetException error) { throw error.getCause(); }
}));
var failure = assertThrows(TransactionOutcomeUnknownException.class, () -> sql.executeInTransaction(() -> {
sql.update("INSERT INTO completion_test VALUES(?)", new Object[]{1});
assertTrue(sql.registerTransactionSynchronization(() -> fail("commit unconfirmed"),
() -> fail("rollback unconfirmed"), () -> observations.add("unknown")));
throw new IllegalStateException("business cancelled");
}));
assertNull(failure.getCause());
assertFalse(failure.getMessage().contains("PRIVATE_ROLLBACK_DIAGNOSTIC"));
assertEquals(List.of("rollback", "rollback", "abort", "unknown"), observations);
assertFalse(sql.hasActiveTransaction());
var independent = new JdbcSqlExecutor(new Source(url));
assertTrue(independent.queryForList("SELECT id FROM completion_test", new Object[0]).isEmpty());
physical.rollback();
}
}

@Test public void driverCleanupFailureKeepsConfirmedCommit() throws Exception {
String url = fixtureUrl();
var observations = new ArrayList<String>();
try (var physical = DriverManager.getConnection(url)) {
var sql = new JdbcSqlExecutor(faultSource((proxy, method, args) -> {
if (method.getName().equals("setAutoCommit") && Boolean.TRUE.equals(args[0])) {
observations.add("autoCommit restoration");
throw new SQLException("PRIVATE_RESTORATION_DIAGNOSTIC");
}
if (method.getName().equals("close")) {
observations.add("close");
throw new SQLException("PRIVATE_CLOSE_DIAGNOSTIC");
}
try { return method.invoke(physical, args); }
catch (InvocationTargetException error) { throw error.getCause(); }
}));
sql.executeInTransaction(() -> {
sql.update("INSERT INTO completion_test VALUES(?)", new Object[]{1});
assertTrue(sql.registerTransactionSynchronization(() -> observations.add("committed"),
() -> fail("commit confirmed"), () -> fail("commit confirmed")));
});
assertEquals(List.of("autoCommit restoration", "close", "committed"), observations);
assertFalse(sql.hasActiveTransaction());
var independent = new JdbcSqlExecutor(new Source(url));
assertEquals(1, independent.queryForList("SELECT id FROM completion_test", new Object[0]).size());
}
}

@Test public void noActiveTransactionCannotAcceptCallbacks() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,10 @@ public void executeInTransaction(Runnable action) {

@Override public boolean hasActiveTransaction() { return transactionCompletion.active(); }

@Override public <T> T withoutActiveTransaction(java.util.function.Supplier<T> work) {
return transactionCompletion.withoutActiveTransaction(work);
}

@Override public boolean registerTransactionSynchronization(Runnable committed, Runnable rolledBack) {
return registerTransactionSynchronization(committed, rolledBack, () -> {});
}
Expand Down
Loading
Loading