完善任务存储、权限及货源查询流程

This commit is contained in:
supernijia
2026-08-14 22:49:15 +08:00
parent 91cd02eeb4
commit cf59e23f15
21 changed files with 2584 additions and 566 deletions
@@ -3,38 +3,148 @@ package com.nanri.aiimage.modules.file.service.object;
import com.nanri.aiimage.config.TransientStorageProperties;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
class RustfsDeleteRetryServiceTest {
@Test
void retryPendingDeletesRefillsDeferredItemsBeforeQueueDrainsCompletely() {
void pendingUniqueKeysNeverExceedCapacityUnderConcurrentAdmission() throws Exception {
TransientStorageProperties properties = new TransientStorageProperties();
properties.setDeleteRetryEnabled(true);
properties.setDeleteRetryQueueCapacity(2);
properties.setDeleteRetryBatchSize(1);
properties.setDeleteRetryQueueCapacity(3);
RustfsObjectStorageService rustfs = mock(RustfsObjectStorageService.class);
RustfsDeleteRetryService service = new RustfsDeleteRetryService(properties, rustfs);
ExecutorService executor = Executors.newFixedThreadPool(8);
CountDownLatch start = new CountDownLatch(1);
List<Future<?>> futures = new ArrayList<>();
try {
for (int i = 0; i < 20; i++) {
String objectKey = "object-" + i;
futures.add(executor.submit(() -> {
start.await();
service.enqueue(objectKey, new IllegalStateException("failed"));
return null;
}));
}
start.countDown();
for (Future<?> future : futures) {
future.get(5, TimeUnit.SECONDS);
}
} finally {
executor.shutdownNow();
}
assertEquals(3, service.pendingCount());
}
@Test
void failedKeyIsAttemptedOnlyOncePerScheduledInvocation() {
TransientStorageProperties properties = new TransientStorageProperties();
properties.setDeleteRetryEnabled(true);
properties.setDeleteRetryQueueCapacity(10);
properties.setDeleteRetryBatchSize(10);
RustfsObjectStorageService rustfs = mock(RustfsObjectStorageService.class);
doAnswer(invocation -> {
String objectKey = invocation.getArgument(0);
if ("b".equals(objectKey)) {
throw new IllegalStateException("still failing");
}
return null;
}).when(rustfs).deleteObjectFromRetry(org.mockito.ArgumentMatchers.anyString());
throw new IllegalStateException("still failing");
}).when(rustfs).deleteObjectFromRetry(eq("a"), anyLong());
RustfsDeleteRetryService service = new RustfsDeleteRetryService(properties, rustfs);
service.enqueue("a", new IllegalStateException("failed-a"));
service.enqueue("b", new IllegalStateException("failed-b"));
service.enqueue("c", new IllegalStateException("failed-c"));
service.retryPendingDeletes();
service.retryPendingDeletes();
verify(rustfs).deleteObjectFromRetry(eq("a"), anyLong());
assertEquals(1, service.pendingCount());
service.retryPendingDeletes();
verify(rustfs).deleteObjectFromRetry("c");
verify(rustfs, times(2)).deleteObjectFromRetry(eq("a"), anyLong());
assertEquals(1, service.pendingCount());
}
@Test
void successfulRetryDoesNotRemoveConcurrentReenqueue() throws Exception {
TransientStorageProperties properties = new TransientStorageProperties();
properties.setDeleteRetryEnabled(true);
properties.setDeleteRetryQueueCapacity(10);
properties.setDeleteRetryBatchSize(10);
RustfsObjectStorageService rustfs = mock(RustfsObjectStorageService.class);
CountDownLatch deleteStarted = new CountDownLatch(1);
CountDownLatch allowDeleteSuccess = new CountDownLatch(1);
doAnswer(invocation -> {
deleteStarted.countDown();
assertTrue(allowDeleteSuccess.await(5, TimeUnit.SECONDS));
return null;
}).when(rustfs).deleteObjectFromRetry(eq("a"), anyLong());
RustfsDeleteRetryService service = new RustfsDeleteRetryService(properties, rustfs);
service.enqueue("a", new IllegalStateException("first failure"));
ExecutorService executor = Executors.newSingleThreadExecutor();
try {
Future<?> retry = executor.submit(service::retryPendingDeletes);
assertTrue(deleteStarted.await(5, TimeUnit.SECONDS));
service.enqueue("a", new IllegalStateException("new failure while delete completes"));
allowDeleteSuccess.countDown();
retry.get(5, TimeUnit.SECONDS);
} finally {
allowDeleteSuccess.countDown();
executor.shutdownNow();
}
assertEquals(1, service.pendingCount());
service.retryPendingDeletes();
verify(rustfs, times(2)).deleteObjectFromRetry(eq("a"), anyLong());
assertEquals(0, service.pendingCount());
}
@Test
void batchDeadlineStopsBeforeNextItemAndPassesRemainingBudget() {
TransientStorageProperties properties = new TransientStorageProperties();
properties.setDeleteRetryEnabled(true);
properties.setDeleteRetryQueueCapacity(10);
properties.setDeleteRetryBatchSize(10);
properties.setDeleteRetryBatchTimeoutSeconds(1);
RustfsObjectStorageService rustfs = mock(RustfsObjectStorageService.class);
AtomicLong receivedBudgetNanos = new AtomicLong();
doAnswer(invocation -> {
long budgetNanos = invocation.getArgument(1);
receivedBudgetNanos.set(budgetNanos);
long deadlineNanos = System.nanoTime() + budgetNanos;
while (System.nanoTime() < deadlineNanos) {
Thread.onSpinWait();
}
throw new IllegalStateException("timed out");
}).when(rustfs).deleteObjectFromRetry(eq("a"), anyLong());
RustfsDeleteRetryService service = new RustfsDeleteRetryService(properties, rustfs);
service.enqueue("a", new IllegalStateException("failed-a"));
service.enqueue("b", new IllegalStateException("failed-b"));
long startedAt = System.nanoTime();
service.retryPendingDeletes();
long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt);
assertTrue(receivedBudgetNanos.get() > 0L);
assertTrue(receivedBudgetNanos.get() <= TimeUnit.SECONDS.toNanos(1));
assertTrue(elapsedMillis < 2000L, "batch should stop close to its configured deadline");
verify(rustfs, never()).deleteObjectFromRetry(eq("b"), anyLong());
assertEquals(2, service.pendingCount());
}
}
@@ -3,19 +3,34 @@ package com.nanri.aiimage.modules.file.service.object;
import com.nanri.aiimage.config.TransientStorageProperties;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.StatObjectArgs;
import okhttp3.OkHttpClient;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.ObjectProvider;
import java.lang.reflect.Field;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.same;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -24,6 +39,9 @@ class RustfsObjectStorageServiceTest {
@Test
void httpClientUsesConfiguredConnectionPoolAndKeepsRetryEnabled() {
TransientStorageProperties properties = configuredProperties();
properties.setCallTimeoutSeconds(45);
properties.setDispatcherMaxRequests(12);
properties.setDispatcherMaxRequestsPerHost(9);
properties.setConnectionPoolMaxIdle(3);
properties.setConnectionPoolKeepAliveMillis(1500);
RustfsObjectStorageService service = new RustfsObjectStorageService(
@@ -33,6 +51,26 @@ class RustfsObjectStorageServiceTest {
assertTrue(client.retryOnConnectionFailure(), "RustFS OkHttp 应开启连接失败重试");
assertNotNull(client.connectionPool(), "RustFS OkHttp 应使用显式 connectionPool 配置");
assertEquals(TimeUnit.SECONDS.toMillis(45), client.callTimeoutMillis());
assertEquals(12, client.dispatcher().getMaxRequests());
assertEquals(9, client.dispatcher().getMaxRequestsPerHost());
}
@Test
void deadlineClientViewShortensCallTimeoutAndSharesResources() {
TransientStorageProperties properties = configuredProperties();
properties.setCallTimeoutSeconds(45);
RustfsObjectStorageService service = new RustfsObjectStorageService(
properties, emptyProvider(), emptyProvider(), null);
OkHttpClient shared = service.getHttpClient();
OkHttpClient bounded = service.getHttpClient(
System.nanoTime() + TimeUnit.SECONDS.toNanos(2));
assertTrue(bounded.callTimeoutMillis() > 0);
assertTrue(bounded.callTimeoutMillis() <= 2000);
assertTrue(shared.connectionPool() == bounded.connectionPool());
assertTrue(shared.dispatcher() == bounded.dispatcher());
}
@Test
@@ -106,6 +144,241 @@ class RustfsObjectStorageServiceTest {
assertTrue(rejected.getMessage().contains("cooldown active"));
}
@Test
void retryBackoffDoesNotHoldUploadPermit() throws Exception {
TransientStorageProperties properties = configuredProperties();
properties.setMaxConcurrentUploads(1);
properties.setAcquirePermitTimeoutMillis(300);
properties.setUploadMaxRetries(2);
properties.setBaseRetryDelayMillis(1000);
properties.setMaxRetryDelayMillis(1000);
MinioClient client = mock(MinioClient.class);
CountDownLatch firstAttemptFailed = new CountDownLatch(1);
AtomicInteger calls = new AtomicInteger();
doAnswer(invocation -> {
if (calls.incrementAndGet() == 1) {
firstAttemptFailed.countDown();
throw new IllegalStateException("first attempt failed");
}
return null;
}).when(client).putObject(any(PutObjectArgs.class));
RustfsObjectStorageService service = new RustfsObjectStorageService(
properties, emptyProvider(), emptyProvider(), () -> client);
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
Future<String> first = executor.submit(() -> service.uploadText("task/first.json", "{}", false));
assertTrue(firstAttemptFailed.await(2, TimeUnit.SECONDS));
Future<String> second = executor.submit(() -> service.uploadText("task/second.json", "{}", false));
assertEquals("task/second.json", second.get(800, TimeUnit.MILLISECONDS));
assertEquals("task/first.json", first.get(2, TimeUnit.SECONDS));
verify(client, times(3)).putObject(any(PutObjectArgs.class));
assertEquals(1, privateSemaphore(service, "uploadSemaphore").availablePermits());
} finally {
executor.shutdownNow();
}
}
@Test
void visibilityCheckDoesNotHoldUploadPermit() throws Exception {
TransientStorageProperties properties = configuredProperties();
properties.setMaxConcurrentUploads(1);
properties.setAcquirePermitTimeoutMillis(300);
MinioClient client = mock(MinioClient.class);
CountDownLatch statStarted = new CountDownLatch(1);
CountDownLatch releaseStat = new CountDownLatch(1);
doAnswer(invocation -> {
statStarted.countDown();
assertTrue(releaseStat.await(2, TimeUnit.SECONDS));
return null;
}).when(client).statObject(any(StatObjectArgs.class));
RustfsObjectStorageService service = new RustfsObjectStorageService(
properties, emptyProvider(), emptyProvider(), () -> client);
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
Future<String> first = executor.submit(() -> service.uploadText("task/first.json", "{}", true));
assertTrue(statStarted.await(2, TimeUnit.SECONDS));
Future<String> second = executor.submit(() -> service.uploadText("task/second.json", "{}", false));
assertEquals("task/second.json", second.get(800, TimeUnit.MILLISECONDS));
releaseStat.countDown();
assertEquals("task/first.json", first.get(2, TimeUnit.SECONDS));
assertEquals(1, privateSemaphore(service, "uploadSemaphore").availablePermits());
} finally {
releaseStat.countDown();
executor.shutdownNow();
}
}
@Test
void openedCircuitStopsRemainingOuterAttempts() {
TransientStorageProperties properties = configuredProperties();
properties.setUploadMaxRetries(3);
properties.setFailureWindowThreshold(1);
properties.setFailureCooldownMillis(10000);
AtomicInteger clientBuilds = new AtomicInteger();
RustfsObjectStorageService service = new RustfsObjectStorageService(
properties, emptyProvider(), emptyProvider(), () -> {
clientBuilds.incrementAndGet();
throw new IllegalStateException("rustfs down");
});
IllegalStateException ex = assertThrows(IllegalStateException.class,
() -> service.uploadText("task/a.json", "{}", false));
assertTrue(ex.getMessage().contains("cooldown active"));
assertEquals(1, clientBuilds.get());
}
@Test
void successfulDeleteDoesNotResetReadWriteFailureWindow() throws Exception {
TransientStorageProperties properties = configuredProperties();
properties.setUploadMaxRetries(1);
properties.setFailureWindowThreshold(2);
properties.setFailureCooldownMillis(10000);
MinioClient client = mock(MinioClient.class);
doThrow(new IllegalStateException("upload failed"))
.when(client).putObject(any(PutObjectArgs.class));
RustfsObjectStorageService service = new RustfsObjectStorageService(
properties, emptyProvider(), emptyProvider(), () -> client);
assertThrows(IllegalStateException.class,
() -> service.uploadText("task/first.json", "{}", false));
service.deleteObject("task/old.json");
assertThrows(IllegalStateException.class,
() -> service.uploadText("task/second.json", "{}", false));
IllegalStateException rejected = assertThrows(IllegalStateException.class,
() -> service.uploadText("task/third.json", "{}", false));
assertTrue(rejected.getMessage().contains("cooldown active"));
verify(client, times(2)).putObject(any(PutObjectArgs.class));
verify(client).removeObject(any(RemoveObjectArgs.class));
}
@Test
void failedDeleteDoesNotIncreaseReadWriteFailureWindow() throws Exception {
TransientStorageProperties properties = configuredProperties();
properties.setUploadMaxRetries(1);
properties.setDeleteMaxRetries(1);
properties.setFailureWindowThreshold(2);
properties.setFailureCooldownMillis(10000);
MinioClient client = mock(MinioClient.class);
doThrow(new IllegalStateException("upload failed"))
.when(client).putObject(any(PutObjectArgs.class));
doThrow(new IllegalStateException("delete failed"))
.when(client).removeObject(any(RemoveObjectArgs.class));
RustfsObjectStorageService service = new RustfsObjectStorageService(
properties, emptyProvider(), emptyProvider(), () -> client);
assertThrows(IllegalStateException.class,
() -> service.uploadText("task/first.json", "{}", false));
assertThrows(IllegalStateException.class, () -> service.deleteObject("task/old.json"));
IllegalStateException opensCircuit = assertThrows(IllegalStateException.class,
() -> service.uploadText("task/second.json", "{}", false));
assertTrue(opensCircuit.getMessage().contains("failed to upload"));
IllegalStateException rejected = assertThrows(IllegalStateException.class,
() -> service.uploadText("task/third.json", "{}", false));
assertTrue(rejected.getMessage().contains("cooldown active"));
verify(client, times(2)).putObject(any(PutObjectArgs.class));
}
@Test
void repeatedStatFailuresOpenCircuitAndEnqueueOneCompensationPerObject() throws Exception {
TransientStorageProperties properties = configuredProperties();
properties.setFailureWindowThreshold(5);
properties.setFailureCooldownMillis(10000);
RustfsDeleteRetryService retryService = mock(RustfsDeleteRetryService.class);
MinioClient client = mock(MinioClient.class);
doThrow(new IllegalStateException("stat failed"))
.when(client).statObject(any(StatObjectArgs.class));
RustfsObjectStorageService service = new RustfsObjectStorageService(
properties, emptyProvider(), provider(retryService), () -> client);
IllegalStateException firstFailure = assertThrows(IllegalStateException.class,
() -> service.uploadText("task/a.json", "{}", true));
IllegalStateException secondFailure = assertThrows(IllegalStateException.class,
() -> service.uploadText("task/b.json", "{}", true));
assertTrue(firstFailure.getMessage().contains("not visible"));
assertTrue(secondFailure.getMessage().contains("not visible"));
verify(client, times(5)).statObject(any(StatObjectArgs.class));
verify(retryService).enqueue(eq("task/a.json"), same(firstFailure));
verify(retryService).enqueue(eq("task/b.json"), same(secondFailure));
IllegalStateException rejected = assertThrows(IllegalStateException.class,
() -> service.uploadText("task/c.json", "{}", false));
assertTrue(rejected.getMessage().contains("cooldown active"));
verify(client, times(2)).putObject(any(PutObjectArgs.class));
}
@Test
void retryDeleteBudgetCutsOffLongBackoff() throws Exception {
TransientStorageProperties properties = configuredProperties();
properties.setDeleteMaxRetries(3);
properties.setBaseRetryDelayMillis(5000);
properties.setMaxRetryDelayMillis(5000);
MinioClient client = mock(MinioClient.class);
doThrow(new IllegalStateException("delete failed"))
.when(client).removeObject(any(RemoveObjectArgs.class));
RustfsObjectStorageService service = new RustfsObjectStorageService(
properties, emptyProvider(), emptyProvider(), () -> client);
long startedAt = System.nanoTime();
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> service.deleteObjectFromRetry("task/a.json", TimeUnit.MILLISECONDS.toNanos(200)));
long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt);
assertTrue(failure.getMessage().contains("operation timeout"));
assertTrue(elapsedMillis < 1000, "operation budget should cut off the five-second backoff");
verify(client).removeObject(any(RemoveObjectArgs.class));
}
@Test
void configuredOperationBudgetCutsOffLongBackoff() throws Exception {
TransientStorageProperties properties = configuredProperties();
properties.setOperationTimeoutSeconds(1);
properties.setUploadMaxRetries(3);
properties.setBaseRetryDelayMillis(5000);
properties.setMaxRetryDelayMillis(5000);
MinioClient client = mock(MinioClient.class);
doThrow(new IllegalStateException("upload failed"))
.when(client).putObject(any(PutObjectArgs.class));
RustfsObjectStorageService service = new RustfsObjectStorageService(
properties, emptyProvider(), emptyProvider(), () -> client);
long startedAt = System.nanoTime();
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> service.uploadText("task/a.json", "{}", false));
long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startedAt);
assertTrue(failure.getMessage().contains("operation timeout"));
assertTrue(elapsedMillis < 2000, "configured budget should cut off the five-second backoff");
verify(client).putObject(any(PutObjectArgs.class));
}
@Test
void completedUploadIsEnqueuedWhenDeadlineExpiresAfterPut() throws Exception {
TransientStorageProperties properties = configuredProperties();
properties.setOperationTimeoutSeconds(1);
RustfsDeleteRetryService retryService = mock(RustfsDeleteRetryService.class);
MinioClient client = mock(MinioClient.class);
doAnswer(invocation -> {
Thread.sleep(1100);
return null;
}).when(client).putObject(any(PutObjectArgs.class));
RustfsObjectStorageService service = new RustfsObjectStorageService(
properties, emptyProvider(), provider(retryService), () -> client);
IllegalStateException failure = assertThrows(IllegalStateException.class,
() -> service.uploadText("task/a.json", "{}", false));
assertTrue(failure.getMessage().contains("operation timeout"));
verify(client).putObject(any(PutObjectArgs.class));
verify(retryService).enqueue(eq("task/a.json"), same(failure));
}
private static TransientStorageProperties configuredProperties() {
TransientStorageProperties properties = new TransientStorageProperties();
properties.setEndpoint("http://127.0.0.1:9000");