diff --git a/README.md b/README.md index 40bff7e..5f9a0bc 100644 --- a/README.md +++ b/README.md @@ -81,8 +81,8 @@ Starting with 4.0.1, every published JAR declares a stable `Automatic-Module-Nam | `smtp-connection-pool-jakarta-provider` | `org.simplejavamail.smtpconnectionpool.jakarta` | | `smtp-connection-pool-camel` | `org.simplejavamail.smtpconnectionpool.camel` | -The transitive object-pool chain is stable as well: `generic-object-pool 2.5.0` declares -`org.bbottema.genericobjectpool`, and `clustered-object-pool 4.1.0` declares +The transitive object-pool chain is stable as well: `generic-object-pool` declares +`org.bbottema.genericobjectpool`, and `clustered-object-pool` declares `org.bbottema.clusteredobjectpool`. The build inspects every packaged manifest and compiles a real module-path consumer requiring all five names. @@ -325,6 +325,11 @@ Verification runs all module tests, the real-server demo smoke tests, SpotBugs, [Simple Java Mail #699](https://github.com/bbottema/simple-java-mail/issues/699) may produce a faster physical transport. If it implements Jakarta Mail's synchronous `Transport` contract with one reusable physical session per instance, it can be selected beneath these paths just like Angus. If it instead uses Simple Java Mail's `CustomMailer`, it owns its own lifecycle and must not be stacked on this pool. +## Unreleased + +- [#33](https://github.com/simple-java-mail/smtp-connection-pool/issues/33), [#34](https://github.com/simple-java-mail/smtp-connection-pool/pull/34): opt into age-based expiration with `mail.smtppool.pool.expiration-since-creation-millis` in the Jakarta provider and Camel adapter. The default `0` preserves the existing policy. Expiration is checked asynchronously while transports are available; it does not impose a hard connection-lifetime limit. +- Update to `clustered-object-pool 4.1.1`, bringing in the timeout-policy equality fix from `generic-object-pool 2.5.1`. Creation-age and last-claim rules retain separate expiry state even with identical thresholds, using the standard combined policy ([upstream fix](https://github.com/bbottema/generic-object-pool/issues/24)). Existing APIs, Java baselines and module names remain supported. + ## Current release `4.1.0` (8 September 2026) diff --git a/RELEASE.txt b/RELEASE.txt index 310ebbe..25ef956 100644 --- a/RELEASE.txt +++ b/RELEASE.txt @@ -4,6 +4,12 @@ https://github.com/simple-java-mail/smtp-connection-pool RELEASE NOTES SMTP Connection Pool +Unreleased + +- #33, #34: Add mail.smtppool.pool.expiration-since-creation-millis to the Jakarta provider and Camel configuration. The default 0 keeps age-based expiration disabled; negative values are rejected. Either the last-claim or creation-age threshold makes an available transport eligible for asynchronous retirement. Active leases are not expired, and rapid reuse can delay retirement beyond the threshold. +- #34: Update clustered-object-pool to 4.1.1 and transitively generic-object-pool to 2.5.1, fixing equality between different timeout-policy types with matching thresholds (bbottema/generic-object-pool#24, bbottema/generic-object-pool#25). Use the upstream CombinedExpirationPolicies so both rules and their expiry state remain distinct. Existing APIs, Java baselines and JPMS automatic module names remain supported. + + v4.1.0 (08-Sep-2026) - #31: Add opt-in ClaimOptions/ClaimControl on direct, keyed and load-balanced transport acquisition. One cooperative budget covers registration, selection, waiting and preparation, using clustered-object-pool 4.1.0 and generic-object-pool 2.5.0. diff --git a/pom.xml b/pom.xml index f0acf21..9bb9609 100644 --- a/pom.xml +++ b/pom.xml @@ -37,7 +37,7 @@ benny@bennybottema.com 2.1.3 2.1.4 - 4.1.0 + 4.1.1 2.0.5 6.2.19 4.22.0 diff --git a/smtp-connection-pool-camel/README.md b/smtp-connection-pool-camel/README.md index 60d0d5b..8355869 100644 --- a/smtp-connection-pool-camel/README.md +++ b/smtp-connection-pool-camel/README.md @@ -43,6 +43,19 @@ to("smtppool://smtp.example.com:2525" + "&username=user&password=secret&to=recipient@example.com"); ``` +Pool tuning properties reach the pool the same way. To make available transports eligible for retirement +15 minutes after creation, independently of their last claim: + +```java +to("smtppool://smtp.example.com:587" + + "?mail.smtppool.pool.expiration-since-creation-millis=900000" + + "&username=user&password=secret&to=recipient@example.com"); +``` + +Expiration is checked asynchronously while transports are available. Active leases are not interrupted, and rapid +reuse can delay retirement past the threshold. See the [provider configuration](../smtp-connection-pool-jakarta-provider/README.md#configuration-reference) +for the expiration settings and defaults. + Internally created Jakarta Mail Sessions are tracked and shut down gracefully when the Camel component stops. Camel waits up to 30 seconds; on timeout or interruption it escalates to forced shutdown and also waits for physical cleanup before stop returns. If an externally supplied Session is used, its owner must call `SmtpPoolRegistry.shutdown(session)`. Ordinary Camel `smtp:`/`smtps:` components and ordinary Jakarta Mail `session.getTransport("smtp")` lookups are untouched. The adapter does not register `PooledTransport` as `smtp`; it asks Camel to use `smtppool` explicitly. diff --git a/smtp-connection-pool-jakarta-provider/README.md b/smtp-connection-pool-jakarta-provider/README.md index 5483bfb..c44a42b 100644 --- a/smtp-connection-pool-jakarta-provider/README.md +++ b/smtp-connection-pool-jakarta-provider/README.md @@ -93,9 +93,15 @@ The resolver branch takes precedence over a configured `Provider`, which takes p | `mail.smtppool.pool.max-size` | integer | `4` | Maximum physical connections per identity | | `mail.smtppool.pool.claim-timeout-millis` | long | `30000` | Maximum wait for an exclusive lease | | `mail.smtppool.pool.expiration-millis` | long | `10000` | Eligibility threshold measured since an available transport's last claim | +| `mail.smtppool.pool.expiration-since-creation-millis` | long | `0` | Eligibility threshold measured since an available pooled transport was created; `0` disables age-based expiration | Provider and resolver values are objects placed with `Properties.put`, not strings loaded from a properties file. +When age-based expiration is enabled, either expiration threshold makes an available transport eligible for retirement. +The pool checks asynchronously and never expires an active lease. A transport can be reclaimed before it is checked, +so this setting does not impose a strict maximum connection lifetime or guarantee retirement before a server's age +limit. At the default `0`, the existing last-claim-only policy is used. Negative age thresholds are rejected. + Endpoint identity includes the Session-scoped manager, normalized delegate protocol and resolved provider metadata, host, effective port, username, and an HMAC credential fingerprint. Raw passwords/tokens are excluded from equality and `toString` and retained only while needed for reconnect/allocation. When credentials rotate, the new generation becomes current immediately; the superseded pool accepts no new claims, drains existing leases, and then clears its credential material and retained pool record. Remaining material is cleared on Session-pool shutdown. Passwords supplied by Jakarta Mail and saved Session authentication are fingerprinted automatically. The configured OAuth token supplier is resolved for every pooled `connect`, so rotating a token creates a separate identity. If a custom authenticator rotates credentials without exposing the effective password, update `mail.smtppool.credential.identity` with its generation/version. diff --git a/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManager.java b/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManager.java index 66d9f9c..c978b36 100644 --- a/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManager.java +++ b/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManager.java @@ -10,7 +10,10 @@ import org.bbottema.clusteredobjectpool.core.ClusterConfig; import org.bbottema.clusteredobjectpool.core.ResourceClusters; import org.bbottema.clusteredobjectpool.core.api.ResourceKey.ResourceClusterAndPoolKey; +import org.bbottema.genericobjectpool.ExpirationPolicy; import org.bbottema.genericobjectpool.PoolableObject; +import org.bbottema.genericobjectpool.expirypolicies.CombinedExpirationPolicies; +import org.bbottema.genericobjectpool.expirypolicies.TimeoutSinceCreationExpirationPolicy; import org.bbottema.genericobjectpool.expirypolicies.TimeoutSinceLastAllocationExpirationPolicy; import org.bbottema.genericobjectpool.util.Timeout; import org.simplejavamail.smtpconnectionpool.SessionTransport; @@ -22,6 +25,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.IdentityHashMap; import java.util.Locale; import java.util.Map; @@ -74,7 +78,10 @@ public SmtpPoolManager(final Session session) { SmtpPoolProperties.DEFAULT_CLAIM_TIMEOUT_MILLIS); final long expiration = longProperty(SmtpPoolProperties.EXPIRATION_MILLIS, SmtpPoolProperties.DEFAULT_EXPIRATION_MILLIS); - if (coreSize < 0 || maxSize < 1 || coreSize > maxSize || claimTimeout < 0 || expiration < 0) { + final long expirationSinceCreation = longProperty(SmtpPoolProperties.EXPIRATION_SINCE_CREATION_MILLIS, + SmtpPoolProperties.DEFAULT_EXPIRATION_SINCE_CREATION_MILLIS); + if (coreSize < 0 || maxSize < 1 || coreSize > maxSize || claimTimeout < 0 || expiration < 0 + || expirationSinceCreation < 0) { throw new IllegalArgumentException("Invalid smtppool sizing or timeout configuration"); } @@ -82,8 +89,7 @@ public SmtpPoolManager(final Session session) { final ClusterConfig config = ClusterConfig.builder() .allocatorFactory(allocatorFactory) - .defaultExpirationPolicy(new TimeoutSinceLastAllocationExpirationPolicy( - expiration, TimeUnit.MILLISECONDS)) + .defaultExpirationPolicy(expirationPolicy(expiration, expirationSinceCreation)) .defaultCorePoolSize(coreSize) .defaultMaxPoolSize(maxSize) .claimTimeout(new Timeout(claimTimeout, TimeUnit.MILLISECONDS)) @@ -437,6 +443,25 @@ private void markSessionShuttingDown() { } } + /** + * Combines the idle threshold with an optional age-since-creation threshold. A transport expires when either + * rule matches; an age threshold of {@code 0} preserves the historical idle-only behaviour exactly. + */ + static ExpirationPolicy expirationPolicy(final long expirationMillis, + final long expirationSinceCreationMillis) { + final ExpirationPolicy idlePolicy = + new TimeoutSinceLastAllocationExpirationPolicy(expirationMillis, + TimeUnit.MILLISECONDS); + if (expirationSinceCreationMillis == 0L) { + return idlePolicy; + } + final Set> policies = new HashSet>(); + policies.add(idlePolicy); + policies.add(new TimeoutSinceCreationExpirationPolicy(expirationSinceCreationMillis, + TimeUnit.MILLISECONDS)); + return new CombinedExpirationPolicies(policies); + } + private static String firstNonBlank(final String... candidates) { for (String candidate : candidates) { if (candidate != null && !candidate.trim().isEmpty()) { diff --git a/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolProperties.java b/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolProperties.java index 0446e2e..d9651bc 100644 --- a/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolProperties.java +++ b/smtp-connection-pool-jakarta-provider/src/main/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolProperties.java @@ -31,6 +31,11 @@ public final class SmtpPoolProperties { public static final String CLAIM_TIMEOUT_MILLIS = "mail.smtppool.pool.claim-timeout-millis"; /** Expiration threshold in milliseconds measured since an available transport's last claim. */ public static final String EXPIRATION_MILLIS = "mail.smtppool.pool.expiration-millis"; + /** + * Expiration eligibility threshold in milliseconds since a pooled transport was created; {@code 0} disables it. + * Checked asynchronously while the transport is available, so this is not a strict connection-lifetime limit. + */ + public static final String EXPIRATION_SINCE_CREATION_MILLIS = "mail.smtppool.pool.expiration-since-creation-millis"; /** Default core pool size. */ public static final int DEFAULT_CORE_POOL_SIZE = 0; @@ -40,6 +45,8 @@ public final class SmtpPoolProperties { public static final long DEFAULT_CLAIM_TIMEOUT_MILLIS = 30_000L; /** Default available-transport expiration threshold in milliseconds. */ public static final long DEFAULT_EXPIRATION_MILLIS = 10_000L; + /** Default age-based expiration threshold in milliseconds; {@code 0} keeps age-based expiration disabled. */ + public static final long DEFAULT_EXPIRATION_SINCE_CREATION_MILLIS = 0L; private SmtpPoolProperties() { } diff --git a/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/PooledTransportIntegrationTest.java b/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/PooledTransportIntegrationTest.java index 272f9be..6719fc1 100644 --- a/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/PooledTransportIntegrationTest.java +++ b/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/PooledTransportIntegrationTest.java @@ -484,6 +484,43 @@ void poolCapacityTimesOutASecondExclusiveClaimAndRecoversAfterRelease() throws E assertEquals(1, FakeTransport.instances.get()); } + @Test + void ageBasedExpirationRetiresAnAvailableTransportBeforeTheIdleThreshold() throws Exception { + session.getProperties().setProperty(SmtpPoolProperties.EXPIRATION_MILLIS, "60000"); + session.getProperties().setProperty(SmtpPoolProperties.EXPIRATION_SINCE_CREATION_MILLIS, "50"); + sendOnce("secret"); + assertEquals(1, FakeTransport.instances.get()); + + // The idle threshold cannot fire within this window, so a retirement here can only come from the age rule. + final SmtpPoolManager manager = SmtpPoolRegistry.getOrCreate(session); + for (int attempt = 0; attempt < 200 && manager.getLiveTransportCount() > 0; attempt++) { + Thread.sleep(25L); + } + assertEquals(0, manager.getLiveTransportCount()); + + sendOnce("secret"); + assertEquals(2, FakeTransport.instances.get()); + } + + @Test + void anUnsetAgeThresholdLeavesIdleOnlyExpirationBehaviourUnchanged() throws Exception { + session.getProperties().setProperty(SmtpPoolProperties.EXPIRATION_MILLIS, "60000"); + sendOnce("secret"); + + final SmtpPoolManager manager = SmtpPoolRegistry.getOrCreate(session); + Thread.sleep(300L); + + assertEquals(1, manager.getLiveTransportCount()); + sendOnce("secret"); + assertEquals(1, FakeTransport.instances.get()); + } + + @Test + void aNegativeAgeThresholdIsRejectedWhenTheManagerIsCreated() { + session.getProperties().setProperty(SmtpPoolProperties.EXPIRATION_SINCE_CREATION_MILLIS, "-1"); + assertThrows(IllegalArgumentException.class, () -> SmtpPoolRegistry.getOrCreate(session)); + } + @Test void interruptedPoolClaimPreservesTheWaiterInterruptFlag() throws Exception { session.getProperties().setProperty(SmtpPoolProperties.MAX_POOL_SIZE, "1"); diff --git a/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManagerExpirationTest.java b/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManagerExpirationTest.java new file mode 100644 index 0000000..48ece33 --- /dev/null +++ b/smtp-connection-pool-jakarta-provider/src/test/java/org/simplejavamail/smtpconnectionpool/jakarta/SmtpPoolManagerExpirationTest.java @@ -0,0 +1,59 @@ +package org.simplejavamail.smtpconnectionpool.jakarta; + +import org.bbottema.genericobjectpool.ExpirationPolicy; +import org.bbottema.genericobjectpool.PoolableObject; +import org.bbottema.genericobjectpool.expirypolicies.TimeoutSinceLastAllocationExpirationPolicy; +import org.junit.jupiter.api.Test; +import org.simplejavamail.smtpconnectionpool.SessionTransport; + +import java.util.HashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +class SmtpPoolManagerExpirationTest { + + @Test + void equalThresholdsRetainTheCreationRuleAndSeparateExpiryState() { + final ExpirationPolicy policy = SmtpPoolManager.expirationPolicy(50L, 50L); + final PoolableObject transport = transportAged(50L, 0L); + + assertTrue(policy.hasExpired(transport), "Only creation age has reached the shared threshold"); + assertEquals(2, transport.getExpiriesMs().size(), "Both rules must keep their own expiry state"); + } + + @Test + void theIdleRuleStillExpiresBeforeTheCreationThreshold() { + final ExpirationPolicy policy = SmtpPoolManager.expirationPolicy(50L, 60_000L); + assertTrue(policy.hasExpired(transportAged(100L, 50L))); + } + + @Test + void neitherRuleExpiresBeforeItsThreshold() { + final ExpirationPolicy policy = SmtpPoolManager.expirationPolicy(50L, 100L); + assertFalse(policy.hasExpired(transportAged(99L, 49L))); + } + + @Test + void zeroCreationThresholdPreservesTheSingleIdlePolicy() { + final ExpirationPolicy policy = SmtpPoolManager.expirationPolicy(50L, 0L); + assertInstanceOf(TimeoutSinceLastAllocationExpirationPolicy.class, policy); + assertFalse(policy.hasExpired(transportAged(60_000L, 49L))); + assertTrue(policy.hasExpired(transportAged(60_000L, 50L))); + } + + @SuppressWarnings({"unchecked", "rawtypes"}) + private static PoolableObject transportAged(final long creationAge, final long lastClaimAge) { + final PoolableObject transport = mock(PoolableObject.class); + final Map expiryState = new HashMap(); + when(transport.ageMs()).thenReturn(creationAge); + when(transport.allocationAgeMs()).thenReturn(lastClaimAge); + when(transport.getExpiriesMs()).thenReturn(expiryState); + return transport; + } +}