You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@james.apache.org by bt...@apache.org on 2026/10/01 09:28:19 UTC
(james-project) branch master updated (3e54de48f4 -> ac241179b8)
This is an automated email from the ASF dual-hosted git repository.
chibenwa pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git
from 3e54de48f4 [ENHANCEMENT] Apache James Blob File Sharding (#3197)
new 0baecc4b26 JAMES-2586 Regression test for throttled full re-indexing on Postgres
new eb9f0c0f85 JAMES-2586 Upgrade jOOQ to 3.20.20 and r2dbc-postgresql to 1.1.3
new b19553cd8b JAMES-2586 Reproduce a pooled Postgres connection staying busy after a timed out query
new 9f898f0796 JAMES-2586 Cancel the Postgres query upon jOOQ reactive timeout
new ac241179b8 JAMES-2586 Cancel the Postgres query upon jOOQ reactive timeout in executeTransaction
The 5 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
backends-common/postgres/pom.xml | 4 +-
.../backends/postgres/utils/PostgresExecutor.java | 47 ++++++-
.../postgres/PostgresConfigurationTest.java | 2 +-
.../postgres/PostgresExecutorTimeoutTest.java | 147 +++++++++++++++++++++
.../james/backends/postgres/PostgresExtension.java | 9 +-
...java => PostgresReIndexingIntegrationTest.java} | 138 ++++++++++---------
6 files changed, 265 insertions(+), 82 deletions(-)
create mode 100644 backends-common/postgres/src/test/java/org/apache/james/backends/postgres/PostgresExecutorTimeoutTest.java
copy server/protocols/webadmin-integration-test/postgres-webadmin-integration-test/src/test/java/org/apache/james/webadmin/integration/postgres/{PostgresPopulateEmailQueryViewTaskIntegrationTest.java => PostgresReIndexingIntegrationTest.java} (54%)
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
(james-project) 01/05: JAMES-2586 Regression test for throttled full re-indexing on Postgres
Posted by bt...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
chibenwa pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git
commit 0baecc4b26bc89cdc74e475b13df38dd58770ce5
Author: Quan Tran <hq...@linagora.com>
AuthorDate: Sat Sep 26 21:41:22 2026 +0700
JAMES-2586 Regression test for throttled full re-indexing on Postgres
A throttled full re-indexing on the Postgres app
(`/mailboxes?task=reIndex&messagesPerSecond=N`) used to fail after exactly
`jooq.reactive.timeout` (10 seconds by default) with:
PostgresExecutor - Time out executing Postgres query. May need to check
either jOOQ reactive issue or Postgres DB performance.
java.util.concurrent.TimeoutException: Did not observe any item or
terminal signal within 10000ms in 'flatMapMany'
The re-indexing lists every mailbox with a mailbox concurrency of 1 and
throttles the messages of each mailbox, so a streamed listing query was
kept open while the first mailbox was slowly re-indexed, and the reactive
timeout fired while Postgres only waited for downstream demand.
Paginated listings (see "[FIX] PG: Generalise streaming with paging") no
longer hold a query open during the consumption. This test locks in the
reported scenario on a Guice Postgres server, with a 2 seconds timeout
and 1 message per second over two mailboxes.
`PostgresExtension.withJooqReactiveTimeout` allows tests to shorten the
timeout.
Co-Authored-By: Claude Opus 5.5 <no...@anthropic.com>
---
.../james/backends/postgres/PostgresExtension.java | 9 +-
.../PostgresReIndexingIntegrationTest.java | 151 +++++++++++++++++++++
2 files changed, 159 insertions(+), 1 deletion(-)
diff --git a/backends-common/postgres/src/test/java/org/apache/james/backends/postgres/PostgresExtension.java b/backends-common/postgres/src/test/java/org/apache/james/backends/postgres/PostgresExtension.java
index 84143e5b80..1db077b0db 100644
--- a/backends-common/postgres/src/test/java/org/apache/james/backends/postgres/PostgresExtension.java
+++ b/backends-common/postgres/src/test/java/org/apache/james/backends/postgres/PostgresExtension.java
@@ -87,11 +87,13 @@ public class PostgresExtension implements GuiceModuleTestExtension {
}
public static final PoolSize DEFAULT_POOL_SIZE = PoolSize.SMALL;
+ public static final Duration DEFAULT_JOOQ_REACTIVE_TIMEOUT = Duration.ofSeconds(20L);
public static PostgreSQLContainer<?> PG_CONTAINER = DockerPostgresSingleton.SINGLETON;
private final PostgresDataDefinition postgresDataDefinition;
private final RowLevelSecurity rowLevelSecurity;
private final PostgresFixture.Database selectedDatabase;
private PoolSize poolSize;
+ private Duration jooqReactiveTimeout = DEFAULT_JOOQ_REACTIVE_TIMEOUT;
private PostgresConfiguration postgresConfiguration;
private PostgresExecutor defaultPostgresExecutor;
private PostgresExecutor byPassRLSPostgresExecutor;
@@ -100,6 +102,11 @@ public class PostgresExtension implements GuiceModuleTestExtension {
private PostgresExecutor.Factory executorFactory;
private PostgresTableManager postgresTableManager;
+ public PostgresExtension withJooqReactiveTimeout(Duration jooqReactiveTimeout) {
+ this.jooqReactiveTimeout = jooqReactiveTimeout;
+ return this;
+ }
+
public void pause() {
PG_CONTAINER.getDockerClient().pauseContainerCmd(PG_CONTAINER.getContainerId())
.exec();
@@ -161,7 +168,7 @@ public class PostgresExtension implements GuiceModuleTestExtension {
.byPassRLSUser(DEFAULT_DATABASE.dbUser())
.byPassRLSPassword(DEFAULT_DATABASE.dbPassword())
.rowLevelSecurityEnabled(rowLevelSecurity.isRowLevelSecurityEnabled())
- .jooqReactiveTimeout(Optional.of(Duration.ofSeconds(20L)))
+ .jooqReactiveTimeout(Optional.of(jooqReactiveTimeout))
.build();
Function<PostgresConfiguration.Credential, PostgresqlConnectionConfiguration> postgresqlConnectionConfigurationFunction = credential ->
diff --git a/server/protocols/webadmin-integration-test/postgres-webadmin-integration-test/src/test/java/org/apache/james/webadmin/integration/postgres/PostgresReIndexingIntegrationTest.java b/server/protocols/webadmin-integration-test/postgres-webadmin-integration-test/src/test/java/org/apache/james/webadmin/integration/postgres/PostgresReIndexingIntegrationTest.java
new file mode 100644
index 0000000000..a111cf8030
--- /dev/null
+++ b/server/protocols/webadmin-integration-test/postgres-webadmin-integration-test/src/test/java/org/apache/james/webadmin/integration/postgres/PostgresReIndexingIntegrationTest.java
@@ -0,0 +1,151 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.webadmin.integration.postgres;
+
+import static io.restassured.RestAssured.given;
+import static io.restassured.RestAssured.with;
+import static org.apache.james.data.UsersRepositoryModuleChooser.Implementation.DEFAULT;
+import static org.hamcrest.Matchers.is;
+
+import java.time.Duration;
+
+import org.apache.james.FakeMessageSearchIndex;
+import org.apache.james.GuiceJamesServer;
+import org.apache.james.JamesServerBuilder;
+import org.apache.james.JamesServerExtension;
+import org.apache.james.PostgresJamesConfiguration;
+import org.apache.james.PostgresJamesServerMain;
+import org.apache.james.SearchConfiguration;
+import org.apache.james.backends.postgres.PostgresExtension;
+import org.apache.james.core.Username;
+import org.apache.james.mailbox.MailboxSession;
+import org.apache.james.mailbox.MessageManager.AppendCommand;
+import org.apache.james.mailbox.model.Mailbox;
+import org.apache.james.mailbox.model.MailboxId;
+import org.apache.james.mailbox.model.MailboxPath;
+import org.apache.james.mailbox.store.mail.model.MailboxMessage;
+import org.apache.james.mailbox.store.search.ListeningMessageSearchIndex;
+import org.apache.james.modules.MailboxProbeImpl;
+import org.apache.james.probe.DataProbe;
+import org.apache.james.utils.DataProbeImpl;
+import org.apache.james.utils.WebAdminGuiceProbe;
+import org.apache.james.webadmin.WebAdminUtils;
+import org.apache.james.webadmin.routes.TasksRoutes;
+import org.apache.mailbox.tools.indexer.FullReindexingTask;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import io.restassured.RestAssured;
+import reactor.core.publisher.Mono;
+
+/**
+ * Regression test for the "Time out executing Postgres query" error reported when running a throttled full re-indexing
+ * against the Postgres app: listing mailboxes and messages must not hold a Postgres query open while the messages are
+ * slowly re-indexed, otherwise the jOOQ reactive timeout fails the task.
+ */
+class PostgresReIndexingIntegrationTest {
+ private static class AcceptingMessageSearchIndex extends FakeMessageSearchIndex {
+ @Override
+ public Mono<Void> add(MailboxSession session, Mailbox mailbox, MailboxMessage message) {
+ return Mono.empty();
+ }
+
+ @Override
+ public Mono<Void> deleteAll(MailboxSession session, MailboxId mailboxId) {
+ return Mono.empty();
+ }
+
+ @Override
+ public void postReindexing() {
+
+ }
+ }
+
+ private static final Duration JOOQ_REACTIVE_TIMEOUT = Duration.ofSeconds(2);
+ private static final int ONE_MESSAGE_PER_SECOND = 1;
+ private static final int INBOX_MESSAGE_COUNT = 4;
+ private static final int SENT_MESSAGE_COUNT = 1;
+ private static final String DOMAIN = "domain.tld";
+ private static final Username BOB = Username.of("bob@" + DOMAIN);
+ private static final String PASSWORD = "password";
+ private static final MailboxPath BOB_INBOX = MailboxPath.inbox(BOB);
+ private static final MailboxPath BOB_SENT = MailboxPath.forUser(BOB, "Sent");
+
+ @RegisterExtension
+ static JamesServerExtension jamesServerExtension = new JamesServerBuilder<PostgresJamesConfiguration>(tmpDir ->
+ PostgresJamesConfiguration.builder()
+ .workingDirectory(tmpDir)
+ .configurationFromClasspath()
+ .searchConfiguration(SearchConfiguration.scanning())
+ .usersRepository(DEFAULT)
+ .eventBusImpl(PostgresJamesConfiguration.EventBusImpl.IN_MEMORY)
+ .build())
+ .extension(PostgresExtension.empty().withJooqReactiveTimeout(JOOQ_REACTIVE_TIMEOUT))
+ .server(configuration -> PostgresJamesServerMain.createServer(configuration)
+ .overrideWith(binder -> binder.bind(ListeningMessageSearchIndex.class).toInstance(new AcceptingMessageSearchIndex())))
+ .build();
+
+ private MailboxProbeImpl mailboxProbe;
+
+ @BeforeEach
+ void setUp(GuiceJamesServer guiceJamesServer) throws Exception {
+ DataProbe dataProbe = guiceJamesServer.getProbe(DataProbeImpl.class);
+ mailboxProbe = guiceJamesServer.getProbe(MailboxProbeImpl.class);
+ WebAdminGuiceProbe webAdminGuiceProbe = guiceJamesServer.getProbe(WebAdminGuiceProbe.class);
+ RestAssured.requestSpecification = WebAdminUtils.buildRequestSpecification(webAdminGuiceProbe.getWebAdminPort())
+ .build();
+
+ dataProbe.addDomain(DOMAIN);
+ dataProbe.addUser(BOB.asString(), PASSWORD);
+ mailboxProbe.createMailbox(BOB_INBOX);
+ mailboxProbe.createMailbox(BOB_SENT);
+ appendMessages(BOB_INBOX, INBOX_MESSAGE_COUNT);
+ appendMessages(BOB_SENT, SENT_MESSAGE_COUNT);
+ }
+
+ @Test
+ void throttledFullReIndexingShouldNotTimeoutWhenIndexingAMailboxTakesLongerThanTheJooqReactiveTimeout() {
+ String taskId = with()
+ .queryParam("task", "reIndex")
+ .queryParam("messagesPerSecond", ONE_MESSAGE_PER_SECOND)
+ .post("/mailboxes")
+ .jsonPath()
+ .get("taskId");
+
+ given()
+ .basePath(TasksRoutes.BASE)
+ .when()
+ .get(taskId + "/await")
+ .then()
+ .body("status", is("completed"))
+ .body("type", is(FullReindexingTask.FULL_RE_INDEXING.asString()))
+ .body("additionalInformation.successfullyReprocessedMailCount", is(INBOX_MESSAGE_COUNT + SENT_MESSAGE_COUNT))
+ .body("additionalInformation.failedReprocessedMailCount", is(0))
+ .body("additionalInformation.runningOptions.messagesPerSecond", is(ONE_MESSAGE_PER_SECOND));
+ }
+
+ private void appendMessages(MailboxPath mailboxPath, int count) throws Exception {
+ for (int i = 0; i < count; i++) {
+ mailboxProbe.appendMessage(BOB.asString(), mailboxPath,
+ AppendCommand.builder().build("header: value\r\n\r\nbody " + i));
+ }
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
(james-project) 03/05: JAMES-2586 Reproduce a pooled Postgres connection staying busy after a timed out query
Posted by bt...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
chibenwa pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git
commit b19553cd8be6a247a315b687d45f6b926aff6b02
Author: Quan Tran <hq...@linagora.com>
AuthorDate: Sat Sep 26 21:45:07 2026 +0700
JAMES-2586 Reproduce a pooled Postgres connection staying busy after a timed out query
Cancelling the reactive pipeline upon `jooq.reactive.timeout` does not
stop the query on the Postgres server: the connection keeps processing
it and is handed back to the pool in that state. The next query
acquiring that connection queues behind the still running statement
and times out in turn, which cascades into the "everything needing
Postgres fails, then sometimes recovers" behaviour of
linagora/tmail-backend#1599.
PostgresExecutorTimeoutTest reproduces it with a pool of a single
connection and a 60 seconds `pg_sleep`:
- a query stalling on the database side must time out,
- right after the timeout, a query on that connection must succeed.
The latter fails before the fix.
Co-Authored-By: Claude Opus 5.5 <no...@anthropic.com>
---
.../postgres/PostgresExecutorTimeoutTest.java | 129 +++++++++++++++++++++
1 file changed, 129 insertions(+)
diff --git a/backends-common/postgres/src/test/java/org/apache/james/backends/postgres/PostgresExecutorTimeoutTest.java b/backends-common/postgres/src/test/java/org/apache/james/backends/postgres/PostgresExecutorTimeoutTest.java
new file mode 100644
index 0000000000..a8fbf852f8
--- /dev/null
+++ b/backends-common/postgres/src/test/java/org/apache/james/backends/postgres/PostgresExecutorTimeoutTest.java
@@ -0,0 +1,129 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one *
+ * or more contributor license agreements. See the NOTICE file *
+ * distributed with this work for additional information *
+ * regarding copyright ownership. The ASF licenses this file *
+ * to you under the Apache License, Version 2.0 (the *
+ * "License"); you may not use this file except in compliance *
+ * with the License. You may obtain a copy of the License at *
+ * *
+ * http://www.apache.org/licenses/LICENSE-2.0 *
+ * *
+ * Unless required by applicable law or agreed to in writing, *
+ * software distributed under the License is distributed on an *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
+ * KIND, either express or implied. See the License for the *
+ * specific language governing permissions and limitations *
+ * under the License. *
+ ****************************************************************/
+
+package org.apache.james.backends.postgres;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import java.time.Duration;
+import java.util.List;
+import java.util.Optional;
+import java.util.concurrent.TimeoutException;
+
+import org.apache.james.backends.postgres.utils.JamesPostgresConnectionFactory;
+import org.apache.james.backends.postgres.utils.PoolBackedPostgresConnectionFactory;
+import org.apache.james.backends.postgres.utils.PostgresExecutor;
+import org.apache.james.metrics.tests.RecordingMetricFactory;
+import org.jooq.Field;
+import org.jooq.Record;
+import org.jooq.Table;
+import org.jooq.impl.DSL;
+import org.jooq.impl.SQLDataType;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import reactor.core.publisher.Flux;
+import reactor.core.publisher.Mono;
+
+class PostgresExecutorTimeoutTest {
+ private static final Duration JOOQ_REACTIVE_TIMEOUT = Duration.ofMillis(500);
+ private static final Duration LONGER_THAN_TIMEOUT_IN_SECONDS = Duration.ofSeconds(60);
+ private static final int SINGLE_CONNECTION_POOL = 1;
+ private static final int ROW_COUNT = 3;
+ private static final Table<Record> TABLE = DSL.table("timeout_test");
+ private static final Field<Integer> ID = DSL.field("id", SQLDataType.INTEGER);
+
+ @RegisterExtension
+ static PostgresExtension postgresExtension = PostgresExtension.empty();
+
+ private static JamesPostgresConnectionFactory singleConnectionFactory;
+ private static PostgresExecutor postgresExecutor;
+
+ @BeforeAll
+ static void beforeAll() {
+ PostgresConfiguration extensionConfiguration = postgresExtension.getPostgresConfiguration();
+ PostgresConfiguration shortTimeoutConfiguration = PostgresConfiguration.builder()
+ .databaseName(extensionConfiguration.getDatabaseName())
+ .databaseSchema(extensionConfiguration.getDatabaseSchema())
+ .host(extensionConfiguration.getHost())
+ .port(extensionConfiguration.getPort())
+ .username(extensionConfiguration.getDefaultCredential().getUsername())
+ .password(extensionConfiguration.getDefaultCredential().getPassword())
+ .byPassRLSUser(extensionConfiguration.getByPassRLSCredential().getUsername())
+ .byPassRLSPassword(extensionConfiguration.getByPassRLSCredential().getPassword())
+ .rowLevelSecurityEnabled(false)
+ .jooqReactiveTimeout(Optional.of(JOOQ_REACTIVE_TIMEOUT))
+ .build();
+ singleConnectionFactory = new PoolBackedPostgresConnectionFactory(RowLevelSecurity.DISABLED,
+ SINGLE_CONNECTION_POOL, SINGLE_CONNECTION_POOL, postgresExtension.getConnectionFactory());
+ postgresExecutor = new PostgresExecutor.Factory(singleConnectionFactory, shortTimeoutConfiguration, new RecordingMetricFactory())
+ .create();
+ }
+
+ @AfterAll
+ static void afterAll() {
+ singleConnectionFactory.close().block();
+ }
+
+ @BeforeEach
+ void beforeEach() {
+ PostgresExecutor setUpExecutor = postgresExtension.getDefaultPostgresExecutor();
+ setUpExecutor.executeVoid(dslContext -> Mono.from(dslContext.createTableIfNotExists(TABLE)
+ .column(ID)))
+ .block();
+ Flux.range(1, ROW_COUNT)
+ .concatMap(id -> setUpExecutor.executeVoid(dslContext -> Mono.from(dslContext.insertInto(TABLE, ID).values(id))))
+ .blockLast();
+ }
+
+ @AfterEach
+ void afterEach() {
+ postgresExtension.getDefaultPostgresExecutor()
+ .executeVoid(dslContext -> Mono.from(dslContext.dropTableIfExists(TABLE)))
+ .block();
+ }
+
+ @Test
+ void executeRowsShouldTimeoutWhenTheDatabaseDoesNotAnswerWhileRowsAreAwaited() {
+ assertThatThrownBy(() -> sleepOnTheDatabaseSide().collectList().block())
+ .hasCauseInstanceOf(TimeoutException.class);
+ }
+
+ @Test
+ void connectionShouldBeUsableRightAfterATimeout() {
+ assertThatThrownBy(() -> sleepOnTheDatabaseSide().collectList().block())
+ .hasCauseInstanceOf(TimeoutException.class);
+
+ List<Integer> ids = postgresExecutor.executeRows(dslContext -> Flux.from(dslContext.select(ID).from(TABLE).orderBy(ID)))
+ .map(record -> record.get(ID))
+ .collectList()
+ .block();
+
+ assertThat(ids).containsExactly(1, 2, 3);
+ }
+
+ private Flux<Record> sleepOnTheDatabaseSide() {
+ return postgresExecutor.executeRows(dslContext -> Flux.from(dslContext.select(DSL.field("pg_sleep(" + LONGER_THAN_TIMEOUT_IN_SECONDS.toSeconds() + ")"))));
+ }
+}
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
(james-project) 04/05: JAMES-2586 Cancel the Postgres query upon jOOQ reactive timeout
Posted by bt...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
chibenwa pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git
commit 9f898f0796a5fc29f7fdaa0a3572a3d137df2980
Author: Quan Tran <hq...@linagora.com>
AuthorDate: Sat Sep 26 21:45:56 2026 +0700
JAMES-2586 Cancel the Postgres query upon jOOQ reactive timeout
Upon TimeoutException, `PostgresExecutor` now asks Postgres to cancel
the running query through r2dbc-postgresql `cancelRequest()` (the pooled
connection being unwrapped to the driver connection) before propagating
the error and releasing the connection. The cancel request goes through
a dedicated connection, so it does not depend on the busy one.
The connection thus becomes usable again within milliseconds instead of
staying busy until the query completes on its own, which prevents a
single slow query from cascading timeouts onto unrelated queries.
This applies to every execution method, including each page of
`executeRowsPaginated`.
Co-Authored-By: Claude Opus 5.5 <no...@anthropic.com>
---
.../backends/postgres/utils/PostgresExecutor.java | 45 +++++++++++++++++++---
1 file changed, 39 insertions(+), 6 deletions(-)
diff --git a/backends-common/postgres/src/main/java/org/apache/james/backends/postgres/utils/PostgresExecutor.java b/backends-common/postgres/src/main/java/org/apache/james/backends/postgres/utils/PostgresExecutor.java
index baee1f95e6..dc7db5c768 100644
--- a/backends-common/postgres/src/main/java/org/apache/james/backends/postgres/utils/PostgresExecutor.java
+++ b/backends-common/postgres/src/main/java/org/apache/james/backends/postgres/utils/PostgresExecutor.java
@@ -51,8 +51,10 @@ import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
+import io.r2dbc.postgresql.api.PostgresqlConnection;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.R2dbcBadGrammarException;
+import io.r2dbc.spi.Wrapped;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;
@@ -121,7 +123,7 @@ public class PostgresExecutor {
connection -> dslContext(connection)
.flatMap(queryFunction)
.timeout(postgresConfiguration.getJooqReactiveTimeout())
- .doOnError(TimeoutException.class, e -> LOGGER.error(JOOQ_TIMEOUT_ERROR_LOG, e))
+ .onErrorResume(TimeoutException.class, e -> handleTimeout(connection, e))
.retryWhen(Retry.backoff(MAX_RETRY_ATTEMPTS, MIN_BACKOFF)
.filter(preparedStatementConflictException()))
.then(),
@@ -153,7 +155,7 @@ public class PostgresExecutor {
Flux<Record> recordFlux = dslContext(connection)
.flatMapMany(queryFunction)
.timeout(postgresConfiguration.getJooqReactiveTimeout())
- .doOnError(TimeoutException.class, e -> LOGGER.error(JOOQ_TIMEOUT_ERROR_LOG, e))
+ .onErrorResume(TimeoutException.class, e -> handleTimeout(connection, e))
.retryWhen(Retry.backoff(MAX_RETRY_ATTEMPTS, MIN_BACKOFF)
.filter(preparedStatementConflictException()));
@@ -210,7 +212,7 @@ public class PostgresExecutor {
connection -> dslContext(connection)
.flatMapMany(queryFunction)
.timeout(postgresConfiguration.getJooqReactiveTimeout())
- .doOnError(TimeoutException.class, e -> LOGGER.error(JOOQ_TIMEOUT_ERROR_LOG, e))
+ .onErrorResume(TimeoutException.class, e -> handleTimeout(connection, e))
.retryWhen(Retry.backoff(MAX_RETRY_ATTEMPTS, MIN_BACKOFF)
.filter(preparedStatementConflictException())),
jamesPostgresConnectionFactory::closeConnection)));
@@ -222,7 +224,7 @@ public class PostgresExecutor {
connection -> dslContext(connection)
.flatMap(queryFunction.andThen(Mono::from))
.timeout(postgresConfiguration.getJooqReactiveTimeout())
- .doOnError(TimeoutException.class, e -> LOGGER.error(JOOQ_TIMEOUT_ERROR_LOG, e))
+ .onErrorResume(TimeoutException.class, e -> handleTimeout(connection, e))
.retryWhen(Retry.backoff(MAX_RETRY_ATTEMPTS, MIN_BACKOFF)
.filter(preparedStatementConflictException())),
jamesPostgresConnectionFactory::closeConnection)));
@@ -240,7 +242,7 @@ public class PostgresExecutor {
connection -> dslContext(connection)
.flatMap(queryFunction)
.timeout(postgresConfiguration.getJooqReactiveTimeout())
- .doOnError(TimeoutException.class, e -> LOGGER.error(JOOQ_TIMEOUT_ERROR_LOG, e))
+ .onErrorResume(TimeoutException.class, e -> handleTimeout(connection, e))
.retryWhen(Retry.backoff(MAX_RETRY_ATTEMPTS, MIN_BACKOFF)
.filter(preparedStatementConflictException()))
.map(Record1::value1),
@@ -258,7 +260,7 @@ public class PostgresExecutor {
connection -> dslContext(connection)
.flatMap(queryFunction)
.timeout(postgresConfiguration.getJooqReactiveTimeout())
- .doOnError(TimeoutException.class, e -> LOGGER.error(JOOQ_TIMEOUT_ERROR_LOG, e))
+ .onErrorResume(TimeoutException.class, e -> handleTimeout(connection, e))
.retryWhen(Retry.backoff(MAX_RETRY_ATTEMPTS, MIN_BACKOFF)
.filter(preparedStatementConflictException())),
jamesPostgresConnectionFactory::closeConnection)));
@@ -288,6 +290,37 @@ public class PostgresExecutor {
jamesPostgresConnectionFactory.close().block();
}
+ private <T> Mono<T> handleTimeout(Connection connection, TimeoutException timeoutException) {
+ LOGGER.error(JOOQ_TIMEOUT_ERROR_LOG, timeoutException);
+ return cancelRunningQuery(connection)
+ .then(Mono.error(timeoutException));
+ }
+
+ /**
+ * Cancelling the reactive pipeline does not stop the query on the Postgres server side: the connection stays busy
+ * until the query completes, and is handed back to the pool in that state. Asking Postgres to cancel the running query
+ * ensures the connection is quickly usable again.
+ */
+ private Mono<Void> cancelRunningQuery(Connection connection) {
+ return unwrapPostgresqlConnection(connection)
+ .map(postgresqlConnection -> postgresqlConnection.cancelRequest()
+ .onErrorResume(e -> {
+ LOGGER.warn("Failed to cancel the timed out Postgres query", e);
+ return Mono.empty();
+ }))
+ .orElse(Mono.empty());
+ }
+
+ private Optional<PostgresqlConnection> unwrapPostgresqlConnection(Connection connection) {
+ if (connection instanceof PostgresqlConnection postgresqlConnection) {
+ return Optional.of(postgresqlConnection);
+ }
+ if (connection instanceof Wrapped<?> wrapped && wrapped.unwrap() instanceof PostgresqlConnection postgresqlConnection) {
+ return Optional.of(postgresqlConnection);
+ }
+ return Optional.empty();
+ }
+
private Predicate<Throwable> preparedStatementConflictException() {
return throwable -> throwable.getCause() instanceof R2dbcBadGrammarException
&& throwable.getMessage().contains("prepared statement")
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
(james-project) 05/05: JAMES-2586 Cancel the Postgres query upon jOOQ reactive timeout in executeTransaction
Posted by bt...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
chibenwa pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git
commit ac241179b804fa36bd43f7e099530dec09f564a2
Author: Quan Tran <hq...@linagora.com>
AuthorDate: Tue Sep 29 14:22:32 2026 +0700
JAMES-2586 Cancel the Postgres query upon jOOQ reactive timeout in executeTransaction
`executeTransaction`, introduced by #3203, only logged the jOOQ reactive
timeout. The timed out query kept running on the Postgres server, and the
error only reached the caller once the connection was released, that is
once the query completed on its own: the caller and the pooled
connection stayed blocked for as long as the query ran.
Handle its timeout like the other `PostgresExecutor` methods: cancel the
running query through r2dbc-postgresql `cancelRequest()` before
propagating the error and releasing the connection. The transaction is
rolled back upon connection release.
`PostgresExecutorTimeoutTest` covers it with a transaction inserting a
row then sleeping on the database side, on a single connection pool:
the timeout is surfaced right away, the connection is usable right after,
and the row is not committed.
Co-Authored-By: Claude Opus 5.5 <no...@anthropic.com>
---
.../backends/postgres/utils/PostgresExecutor.java | 2 +-
.../backends/postgres/PostgresExecutorTimeoutTest.java | 18 ++++++++++++++++++
2 files changed, 19 insertions(+), 1 deletion(-)
diff --git a/backends-common/postgres/src/main/java/org/apache/james/backends/postgres/utils/PostgresExecutor.java b/backends-common/postgres/src/main/java/org/apache/james/backends/postgres/utils/PostgresExecutor.java
index dc7db5c768..b5fbd1c128 100644
--- a/backends-common/postgres/src/main/java/org/apache/james/backends/postgres/utils/PostgresExecutor.java
+++ b/backends-common/postgres/src/main/java/org/apache/james/backends/postgres/utils/PostgresExecutor.java
@@ -275,7 +275,7 @@ public class PostgresExecutor {
.flatMap(result -> Mono.from(connection.commitTransaction()).thenReturn(result))
.onErrorResume(throwable -> Mono.from(connection.rollbackTransaction()).then(Mono.error(throwable))))
.timeout(postgresConfiguration.getJooqReactiveTimeout())
- .doOnError(TimeoutException.class, e -> LOGGER.error(JOOQ_TIMEOUT_ERROR_LOG, e))
+ .onErrorResume(TimeoutException.class, e -> handleTimeout(connection, e))
.retryWhen(Retry.backoff(MAX_RETRY_ATTEMPTS, MIN_BACKOFF)
.filter(preparedStatementConflictException())),
jamesPostgresConnectionFactory::closeConnection)));
diff --git a/backends-common/postgres/src/test/java/org/apache/james/backends/postgres/PostgresExecutorTimeoutTest.java b/backends-common/postgres/src/test/java/org/apache/james/backends/postgres/PostgresExecutorTimeoutTest.java
index a8fbf852f8..be40e6f4b9 100644
--- a/backends-common/postgres/src/test/java/org/apache/james/backends/postgres/PostgresExecutorTimeoutTest.java
+++ b/backends-common/postgres/src/test/java/org/apache/james/backends/postgres/PostgresExecutorTimeoutTest.java
@@ -51,6 +51,8 @@ class PostgresExecutorTimeoutTest {
private static final Duration LONGER_THAN_TIMEOUT_IN_SECONDS = Duration.ofSeconds(60);
private static final int SINGLE_CONNECTION_POOL = 1;
private static final int ROW_COUNT = 3;
+ private static final int ROW_INSERTED_BY_TIMED_OUT_TRANSACTION = 42;
+ private static final Duration WELL_BEFORE_THE_DATABASE_SLEEP_ENDS = Duration.ofSeconds(10);
private static final Table<Record> TABLE = DSL.table("timeout_test");
private static final Field<Integer> ID = DSL.field("id", SQLDataType.INTEGER);
@@ -123,6 +125,22 @@ class PostgresExecutorTimeoutTest {
assertThat(ids).containsExactly(1, 2, 3);
}
+ @Test
+ void executeTransactionShouldRollbackAndLeaveTheConnectionUsableRightAfterATimeout() {
+ assertThatThrownBy(() -> postgresExecutor.executeTransaction(dslContext -> Mono.from(dslContext.insertInto(TABLE, ID).values(ROW_INSERTED_BY_TIMED_OUT_TRANSACTION))
+ .then(Mono.from(dslContext.select(DSL.field("pg_sleep(" + LONGER_THAN_TIMEOUT_IN_SECONDS.toSeconds() + ")")))))
+ .block(WELL_BEFORE_THE_DATABASE_SLEEP_ENDS))
+ .hasCauseInstanceOf(TimeoutException.class)
+ .hasMessageContaining("Did not observe any item or terminal signal");
+
+ List<Integer> ids = postgresExecutor.executeRows(dslContext -> Flux.from(dslContext.select(ID).from(TABLE).orderBy(ID)))
+ .map(record -> record.get(ID))
+ .collectList()
+ .block(WELL_BEFORE_THE_DATABASE_SLEEP_ENDS);
+
+ assertThat(ids).containsExactly(1, 2, 3);
+ }
+
private Flux<Record> sleepOnTheDatabaseSide() {
return postgresExecutor.executeRows(dslContext -> Flux.from(dslContext.select(DSL.field("pg_sleep(" + LONGER_THAN_TIMEOUT_IN_SECONDS.toSeconds() + ")"))));
}
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org
(james-project) 02/05: JAMES-2586 Upgrade jOOQ to 3.20.20 and r2dbc-postgresql to 1.1.3
Posted by bt...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
chibenwa pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/james-project.git
commit eb9f0c0f85e27e2129a4ce2eabc5eb2a7e58f39a
Author: Quan Tran <hq...@linagora.com>
AuthorDate: Fri Sep 25 19:32:26 2026 +0700
JAMES-2586 Upgrade jOOQ to 3.20.20 and r2dbc-postgresql to 1.1.3
Both releases carry fixes for the query cancellation scenarios the
`jooq.reactive.timeout` safety net was introduced for:
- jOOQ#20112 (fixed in 3.20.20): cancelling an in-flight R2DBC query
could orphan the row subscription and permanently poison the pooled
connection, every later query on it hanging silently.
- r2dbc-postgresql#661 (fixed in 1.1.3): the client could get stuck on
a cancelled conversation, the connection never being drained.
`PostgresConfigurationTest` is adapted to the more detailed invalid SSL
mode message of the new driver.
Co-Authored-By: Claude Fable 5.1 <no...@anthropic.com>
---
backends-common/postgres/pom.xml | 4 ++--
.../org/apache/james/backends/postgres/PostgresConfigurationTest.java | 2 +-
2 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/backends-common/postgres/pom.xml b/backends-common/postgres/pom.xml
index aa3e0f3416..3e30764e40 100644
--- a/backends-common/postgres/pom.xml
+++ b/backends-common/postgres/pom.xml
@@ -29,8 +29,8 @@
<name>Apache James :: Backends Common :: Postgres</name>
<properties>
- <jooq.version>3.20.5</jooq.version>
- <r2dbc.postgresql.version>1.0.7.RELEASE</r2dbc.postgresql.version>
+ <jooq.version>3.20.20</jooq.version>
+ <r2dbc.postgresql.version>1.1.3.RELEASE</r2dbc.postgresql.version>
</properties>
<dependencies>
diff --git a/backends-common/postgres/src/test/java/org/apache/james/backends/postgres/PostgresConfigurationTest.java b/backends-common/postgres/src/test/java/org/apache/james/backends/postgres/PostgresConfigurationTest.java
index 08d76a2356..4b16c06056 100644
--- a/backends-common/postgres/src/test/java/org/apache/james/backends/postgres/PostgresConfigurationTest.java
+++ b/backends-common/postgres/src/test/java/org/apache/james/backends/postgres/PostgresConfigurationTest.java
@@ -120,6 +120,6 @@ class PostgresConfigurationTest {
.sslMode("invalid")
.build())
.isInstanceOf(IllegalArgumentException.class)
- .hasMessage("Invalid ssl mode value: invalid");
+ .hasMessageStartingWith("Invalid ssl mode value: invalid");
}
}
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@james.apache.org
For additional commands, e-mail: notifications-help@james.apache.org