Complete lab7 grade 4 implementation
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
package ru.mtusi.messenger;
|
||||
|
||||
import java.net.URI;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||
import software.amazon.awssdk.core.ResponseInputStream;
|
||||
import software.amazon.awssdk.core.sync.RequestBody;
|
||||
import software.amazon.awssdk.http.apache.ApacheHttpClient;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
|
||||
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
|
||||
import software.amazon.awssdk.services.s3.model.S3Object;
|
||||
import software.amazon.awssdk.services.s3.model.S3Exception;
|
||||
import software.amazon.awssdk.services.s3.paginators.ListObjectsV2Iterable;
|
||||
|
||||
// Байты вложений в приватном S3-bucket. Ключи API имеют права только на этот bucket.
|
||||
@Component
|
||||
class Storage {
|
||||
// Опубликованные оригиналы (их обходит сверка), устойчивый staging приёма и варианты worker.
|
||||
static final String ORIGINALS = "originals/", STAGING = "staging/", VARIANTS = "variants/";
|
||||
final S3Client s3;
|
||||
final String bucket;
|
||||
|
||||
Storage(@Value("${s3.endpoint}") String endpoint, @Value("${s3.region:us-east-1}") String region, @Value("${s3.bucket}") String bucket,
|
||||
@Value("${s3.access-key}") String accessKey, @Value("${s3.secret-key}") String secretKey) {
|
||||
this.bucket = bucket;
|
||||
// Короткий connect timeout: недоступный S3 быстро даёт 503, а не держит поток API.
|
||||
s3 = S3Client.builder()
|
||||
.endpointOverride(URI.create(endpoint))
|
||||
.region(Region.of(region))
|
||||
.forcePathStyle(true)
|
||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(accessKey.trim(), secretKey.trim())))
|
||||
.httpClientBuilder(ApacheHttpClient.builder().maxConnections(64).connectionTimeout(Duration.ofSeconds(2)).socketTimeout(Duration.ofSeconds(30)))
|
||||
.overrideConfiguration(c -> c.apiCallTimeout(Duration.ofSeconds(60)).apiCallAttemptTimeout(Duration.ofSeconds(30)))
|
||||
.build();
|
||||
}
|
||||
|
||||
// Файл читается потоком с диска: размер известен заранее, в RAM целиком не попадает.
|
||||
void put(String key, Path file, String contentType) {
|
||||
s3.putObject(b -> b.bucket(bucket).key(key).contentType(contentType), RequestBody.fromFile(file));
|
||||
}
|
||||
|
||||
ResponseInputStream<GetObjectResponse> get(String key) {
|
||||
return s3.getObject(b -> b.bucket(bucket).key(key));
|
||||
}
|
||||
|
||||
// Скачивание во временный файл worker (файла ещё не должно быть).
|
||||
void download(String key, Path file) {
|
||||
s3.getObject(b -> b.bucket(bucket).key(key), file);
|
||||
}
|
||||
|
||||
// Серверное копирование staging → конечный префикс: байты не проходят через worker.
|
||||
void copy(String from, String to) {
|
||||
s3.copyObject(b -> b.sourceBucket(bucket).sourceKey(from).destinationBucket(bucket).destinationKey(to));
|
||||
}
|
||||
|
||||
void delete(String key) {
|
||||
s3.deleteObject(b -> b.bucket(bucket).key(key));
|
||||
}
|
||||
|
||||
// null — объекта точно нет (404); иначе его размер. Прочие ошибки S3 пробрасываются.
|
||||
Long size(String key) {
|
||||
try {
|
||||
return s3.headObject(b -> b.bucket(bucket).key(key)).contentLength();
|
||||
} catch (NoSuchKeyException e) {
|
||||
return null;
|
||||
} catch (S3Exception e) {
|
||||
if (e.statusCode() == 404) return null;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
// Ленивый постраничный листинг (по 1000 ключей) в побайтовом порядке ключей.
|
||||
ListObjectsV2Iterable list() {
|
||||
return list(ORIGINALS);
|
||||
}
|
||||
|
||||
ListObjectsV2Iterable list(String prefix) {
|
||||
return s3.listObjectsV2Paginator(b -> b.bucket(bucket).prefix(prefix));
|
||||
}
|
||||
|
||||
static boolean isOriginal(S3Object o) {
|
||||
return o.key().startsWith(ORIGINALS);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user