Закрыть оценку 4: ключ API без Admin, очистка сирот и замер памяти.

Данные ходят ключом Read/Write/List, Admin только создаёт bucket. Объект без строки старше двух минут удаляется. Десять загрузок по 8 МиБ дали пик 581 МиБ при лимите 1024.
This commit is contained in:
ivanstorozhev
2026-11-06 10:26:48 +03:00
parent 0450ba42ad
commit 524d7d8c75
16 changed files with 581 additions and 25 deletions
@@ -6,4 +6,6 @@ import ru.mtuci.messenger.domain.AttachmentEntity;
import java.util.UUID;
public interface AttachmentRepository extends JpaRepository<AttachmentEntity, UUID> {
boolean existsByObjectKey(String objectKey);
}
@@ -2,6 +2,7 @@ package ru.mtuci.messenger.storage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import ru.mtuci.messenger.exception.NotFoundException;
@@ -14,29 +15,42 @@ import software.amazon.awssdk.services.s3.model.CreateBucketRequest;
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.HeadBucketRequest;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.services.s3.model.S3Object;
import java.io.InputStream;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
@Component
public class ObjectStorage {
private static final Logger log = LoggerFactory.getLogger(ObjectStorage.class);
private final S3Client s3;
private final S3Client data;
private final S3Client bootstrap;
private final String bucket;
public ObjectStorage(S3Client s3, @Value("${app.s3.bucket}") String bucket) {
this.s3 = s3;
public ObjectStorage(@Qualifier("s3Data") S3Client data,
@Qualifier("s3Bootstrap") S3Client bootstrap,
@Value("${app.s3.bucket}") String bucket) {
this.data = data;
this.bootstrap = bootstrap;
this.bucket = bucket;
}
public record StoredObject(String key, Instant modified) {
}
public void ensureBucket() {
try {
s3.headBucket(HeadBucketRequest.builder().bucket(bucket).build());
bootstrap.headBucket(HeadBucketRequest.builder().bucket(bucket).build());
} catch (NoSuchBucketException missing) {
createBucket();
} catch (S3Exception exception) {
@@ -52,7 +66,7 @@ public class ObjectStorage {
public void put(String key, byte[] body, String contentType) {
try {
s3.putObject(PutObjectRequest.builder()
data.putObject(PutObjectRequest.builder()
.bucket(bucket)
.key(key)
.contentType(contentType)
@@ -65,7 +79,7 @@ public class ObjectStorage {
public InputStream get(String key) {
try {
return s3.getObject(GetObjectRequest.builder().bucket(bucket).key(key).build());
return data.getObject(GetObjectRequest.builder().bucket(bucket).key(key).build());
} catch (NoSuchKeyException missing) {
throw new NotFoundException();
} catch (S3Exception exception) {
@@ -78,9 +92,36 @@ public class ObjectStorage {
}
}
public List<StoredObject> list(String prefix) {
List<StoredObject> objects = new ArrayList<>();
String token = null;
do {
ListObjectsV2Request.Builder request = ListObjectsV2Request.builder()
.bucket(bucket)
.prefix(prefix);
if (token != null) {
request.continuationToken(token);
}
ListObjectsV2Response page;
try {
page = data.listObjectsV2(request.build());
} catch (RuntimeException exception) {
throw storageFailure(exception);
}
if (page.contents() != null) {
for (S3Object object : page.contents()) {
Instant modified = object.lastModified() == null ? Instant.EPOCH : object.lastModified();
objects.add(new StoredObject(object.key(), modified));
}
}
token = page.nextContinuationToken();
} while (token != null);
return objects;
}
public void deleteQuietly(String key) {
try {
s3.deleteObject(DeleteObjectRequest.builder().bucket(bucket).key(key).build());
data.deleteObject(DeleteObjectRequest.builder().bucket(bucket).key(key).build());
} catch (RuntimeException exception) {
log.warn("s3 delete failed status={}", exception.getClass().getSimpleName());
}
@@ -88,7 +129,7 @@ public class ObjectStorage {
private void createBucket() {
try {
s3.createBucket(CreateBucketRequest.builder().bucket(bucket).build());
bootstrap.createBucket(CreateBucketRequest.builder().bucket(bucket).build());
} catch (BucketAlreadyExistsException | BucketAlreadyOwnedByYouException ignored) {
// another replica created the bucket
} catch (S3Exception exception) {
@@ -0,0 +1,57 @@
package ru.mtuci.messenger.storage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import ru.mtuci.messenger.repository.AttachmentRepository;
import java.time.Duration;
import java.time.Instant;
@Component
@Profile("!migrate")
@ConditionalOnProperty(name = "app.s3.sweep-enabled", havingValue = "true", matchIfMissing = true)
public class OrphanSweeper {
private static final Logger log = LoggerFactory.getLogger(OrphanSweeper.class);
private final ObjectStorage storage;
private final AttachmentRepository attachments;
private final Duration grace;
public OrphanSweeper(ObjectStorage storage, AttachmentRepository attachments,
@Value("${app.s3.orphan-grace:2m}") Duration grace) {
this.storage = storage;
this.attachments = attachments;
this.grace = grace;
}
@Scheduled(fixedDelayString = "${app.s3.sweep-interval-ms:60000}",
initialDelayString = "${app.s3.sweep-initial-delay-ms:60000}")
public int sweep() {
return sweepOlderThan(Instant.now().minus(grace));
}
public int sweepOlderThan(Instant cutoff) {
int removed = 0;
for (ObjectStorage.StoredObject object : storage.list("originals/")) {
if (!expiredUnreferenced(object.modified(), cutoff, attachments.existsByObjectKey(object.key()))) {
continue;
}
storage.deleteQuietly(object.key());
removed++;
}
if (removed > 0) {
log.info("removed {} orphan objects older than {}", removed, cutoff);
}
return removed;
}
static boolean expiredUnreferenced(Instant modified, Instant cutoff, boolean referenced) {
return !referenced && !modified.isAfter(cutoff);
}
}
@@ -16,11 +16,23 @@ import java.time.Duration;
@Configuration
public class S3Config {
@Bean(destroyMethod = "close")
S3Client s3Client(@Value("${app.s3.endpoint}") String endpoint,
@Value("${app.s3.region}") String region,
@Value("${app.s3.access-key}") String accessKey,
@Value("${app.s3.secret-key}") String secretKey) {
@Bean(name = "s3Data", destroyMethod = "close")
S3Client s3Data(@Value("${app.s3.endpoint}") String endpoint,
@Value("${app.s3.region}") String region,
@Value("${app.s3.access-key}") String accessKey,
@Value("${app.s3.secret-key}") String secretKey) {
return client(endpoint, region, accessKey, secretKey);
}
@Bean(name = "s3Bootstrap", destroyMethod = "close")
S3Client s3Bootstrap(@Value("${app.s3.endpoint}") String endpoint,
@Value("${app.s3.region}") String region,
@Value("${app.s3.bootstrap-access-key}") String accessKey,
@Value("${app.s3.bootstrap-secret-key}") String secretKey) {
return client(endpoint, region, accessKey, secretKey);
}
private static S3Client client(String endpoint, String region, String accessKey, String secretKey) {
return S3Client.builder()
.endpointOverride(URI.create(endpoint))
.region(Region.of(region))
@@ -34,4 +46,5 @@ public class S3Config {
.apiCallAttemptTimeout(Duration.ofSeconds(8)))
.build();
}
}
@@ -0,0 +1,11 @@
package ru.mtuci.messenger.storage;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@EnableScheduling
@Profile("!migrate")
public class SweepConfig {
}
@@ -115,6 +115,11 @@ app:
bucket: ${S3_BUCKET:messenger-attachments}
access-key: ${S3_ACCESS_KEY:messenger}
secret-key: ${S3_SECRET_KEY:messenger}
bootstrap-access-key: ${S3_BOOTSTRAP_ACCESS_KEY:messenger-bootstrap}
bootstrap-secret-key: ${S3_BOOTSTRAP_SECRET_KEY:messenger-bootstrap}
orphan-grace: ${S3_ORPHAN_GRACE:2m}
sweep-interval-ms: ${S3_SWEEP_INTERVAL_MS:60000}
sweep-initial-delay-ms: ${S3_SWEEP_INITIAL_DELAY_MS:60000}
logging:
pattern:
@@ -3,6 +3,8 @@ package ru.mtuci.messenger;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import ru.mtuci.messenger.storage.ObjectStorage;
import ru.mtuci.messenger.storage.OrphanSweeper;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.server.LocalServerPort;
import org.springframework.test.context.DynamicPropertyRegistry;
@@ -25,10 +27,12 @@ import java.util.Base64;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.time.Instant;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class AttachmentIntegrationTest {
@@ -39,6 +43,12 @@ class AttachmentIntegrationTest {
@Autowired
JsonMapper jsonMapper;
@Autowired
ObjectStorage storage;
@Autowired
OrphanSweeper sweeper;
private ApiClient api;
private final HttpClient http = HttpClient.newHttpClient();
@@ -94,6 +104,48 @@ class AttachmentIntegrationTest {
Map.of("text", "", "attachment_ids", List.of(attachment.get("id").asString())),
Map.of("Idempotency-Key", UUID.randomUUID().toString()));
assertEquals(404, foreign.status());
assertEquals("not_found", foreign.body().get("error").get("code").asString());
ApiClient.Result missing = api.post("/api/v1/chats/" + chatId + "/messages", aliceToken,
Map.of("text", "", "attachment_ids", List.of(UUID.randomUUID().toString())),
Map.of("Idempotency-Key", UUID.randomUUID().toString()));
assertEquals(404, missing.status());
HttpResponse<String> corrupt = upload(aliceToken, chatId, "broken.png", "image/png",
new byte[] {(byte) 137, 80, 78, 71, 13, 10, 26, 10, 0, 1, 2});
assertEquals(415, corrupt.statusCode());
assertEquals("unsupported_media_type", jsonMapper.readTree(corrupt.body()).get("error").get("code").asString());
byte[] jpeg = new byte[] {
(byte) 0xff, (byte) 0xd8,
(byte) 0xff, (byte) 0xc0, 0x00, 0x0b, 0x08, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x11, 0x00,
(byte) 0xff, (byte) 0xd9
};
HttpResponse<String> mime = upload(aliceToken, chatId, "photo.png", "image/png", jpeg);
assertEquals(415, mime.statusCode());
HttpResponse<String> tooBig = upload(aliceToken, chatId, "big.png", "image/png", new byte[10_485_761]);
assertEquals(413, tooBig.statusCode());
assertEquals("payload_too_large", jsonMapper.readTree(tooBig.body()).get("error").get("code").asString());
assertTrue(tooBig.statusCode() < 500);
}
@Test
void sweepDropsOrphanAndKeepsReferencedObject() throws Exception {
String password = "Example-only-not-a-real-secret-123";
JsonNode alice = register("sw", password);
String token = login(alice.get("username").asString(), password);
String chatId = chat(token, List.of(alice.get("id").asString()));
byte[] png = Files.readAllBytes(Path.of("../tests/fixtures/sample.png"));
HttpResponse<String> created = upload(token, chatId, "sample.png", "image/png", png);
assertEquals(201, created.statusCode());
String id = jsonMapper.readTree(created.body()).get("id").asString();
storage.put("originals/orphan-" + UUID.randomUUID(), new byte[] {9, 9, 9}, "application/octet-stream");
int removed = sweeper.sweepOlderThan(Instant.now().plusSeconds(120));
assertTrue(removed >= 1);
assertEquals(200, download(token, id).statusCode());
assertTrue(storage.list("originals/").stream().noneMatch(object -> object.key().contains("orphan-")));
}
private HttpResponse<String> upload(String token, String chatId, String filename, String type, byte[] body) throws Exception {
@@ -0,0 +1,19 @@
package ru.mtuci.messenger.storage;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
class OrphanSweeperTest {
@Test
void graceKeepsFreshObjectAndReferencedRow() {
Instant cutoff = Instant.parse("2026-11-06T07:00:00Z");
assertFalse(OrphanSweeper.expiredUnreferenced(cutoff.plusSeconds(1), cutoff, false));
assertFalse(OrphanSweeper.expiredUnreferenced(cutoff.minusSeconds(30), cutoff, true));
assertTrue(OrphanSweeper.expiredUnreferenced(cutoff.minusSeconds(30), cutoff, false));
}
}
@@ -12,6 +12,8 @@ public final class LabContainers {
public static final String S3_ACCESS_KEY = "messenger-test";
public static final String S3_SECRET_KEY = "messenger-test-secret";
public static final String S3_BOOTSTRAP_ACCESS_KEY = "messenger-bootstrap";
public static final String S3_BOOTSTRAP_SECRET_KEY = "messenger-bootstrap-secret";
public static final String S3_BUCKET = "messenger-attachments";
public static final PostgreSQLContainer POSTGRES = new PostgreSQLContainer("postgres:16.10");
@@ -47,5 +49,8 @@ public final class LabContainers {
registry.add("app.s3.bucket", () -> S3_BUCKET);
registry.add("app.s3.access-key", () -> S3_ACCESS_KEY);
registry.add("app.s3.secret-key", () -> S3_SECRET_KEY);
registry.add("app.s3.bootstrap-access-key", () -> S3_BOOTSTRAP_ACCESS_KEY);
registry.add("app.s3.bootstrap-secret-key", () -> S3_BOOTSTRAP_SECRET_KEY);
registry.add("app.s3.sweep-initial-delay-ms", () -> "3600000");
}
}
+11 -1
View File
@@ -8,7 +8,17 @@
"secretKey": "messenger-test-secret"
}
],
"actions": ["Admin", "Read", "Write", "List", "Tagging"]
"actions": ["Read", "Write", "List"]
},
{
"name": "messenger-bootstrap",
"credentials": [
{
"accessKey": "messenger-bootstrap",
"secretKey": "messenger-bootstrap-secret"
}
],
"actions": ["Admin"]
}
]
}