73 lines
2.7 KiB
Java
73 lines
2.7 KiB
Java
package ru.mtusi.messenger;
|
|
|
|
import io.minio.GetObjectArgs;
|
|
import io.minio.MakeBucketArgs;
|
|
import io.minio.MinioClient;
|
|
import io.minio.PutObjectArgs;
|
|
import io.minio.RemoveObjectArgs;
|
|
import io.minio.BucketExistsArgs;
|
|
import org.springframework.stereotype.Component;
|
|
|
|
import java.io.InputStream;
|
|
|
|
@Component
|
|
public class S3Storage {
|
|
private final MinioClient client;
|
|
private final String bucket;
|
|
|
|
public S3Storage() {
|
|
String endpoint = env("S3_ENDPOINT", "http://minio:9000");
|
|
String access = env("S3_ACCESS_KEY_ID", "messenger-api");
|
|
String secret = env("S3_SECRET_ACCESS_KEY", "messenger-api-secret");
|
|
this.bucket = env("S3_BUCKET", "messenger-attachments");
|
|
this.client = MinioClient.builder().endpoint(endpoint).credentials(access, secret).build();
|
|
try {
|
|
if (!client.bucketExists(BucketExistsArgs.builder().bucket(bucket).build())) {
|
|
client.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
|
|
}
|
|
} catch (Exception exception) {
|
|
throw new IllegalStateException("S3 bucket is unavailable", exception);
|
|
}
|
|
}
|
|
|
|
public void put(String key, InputStream input, long size, String contentType) {
|
|
try {
|
|
client.putObject(PutObjectArgs.builder().bucket(bucket).object(key).stream(input, size, -1)
|
|
.contentType(contentType).build());
|
|
} catch (Exception exception) {
|
|
throw new ApiException(503, "unavailable", "S3-хранилище недоступно");
|
|
}
|
|
}
|
|
|
|
public void check() {
|
|
try {
|
|
if (!client.bucketExists(BucketExistsArgs.builder().bucket(bucket).build())) {
|
|
throw new IllegalStateException("bucket is missing");
|
|
}
|
|
} catch (Exception exception) {
|
|
throw new ApiException(503, "unavailable", "S3-хранилище недоступно");
|
|
}
|
|
}
|
|
|
|
public InputStream get(String key) {
|
|
try {
|
|
return client.getObject(GetObjectArgs.builder().bucket(bucket).object(key).build());
|
|
} catch (Exception exception) {
|
|
throw new ApiException(503, "unavailable", "S3-хранилище недоступно");
|
|
}
|
|
}
|
|
|
|
public void delete(String key) {
|
|
try {
|
|
client.removeObject(RemoveObjectArgs.builder().bucket(bucket).object(key).build());
|
|
} catch (Exception ignored) {
|
|
// Best-effort compensation; orphan cleanup is documented in REPORT.md.
|
|
}
|
|
}
|
|
|
|
private static String env(String name, String fallback) {
|
|
String value = System.getenv(name);
|
|
return value == null || value.isBlank() ? fallback : value;
|
|
}
|
|
}
|