Apply completed lab 4 implementation
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,200 @@
|
||||
package ru.mtusi.messenger;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import software.amazon.awssdk.core.ResponseInputStream;
|
||||
import software.amazon.awssdk.core.exception.SdkException;
|
||||
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
|
||||
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
|
||||
import ru.mtusi.messenger.MessengerApplication.ApiException;
|
||||
|
||||
// Вложения: метаданные в PostgreSQL, байты в приватном S3. Доступ только через API участникам чата.
|
||||
@RestController
|
||||
class Attachments {
|
||||
static final long MAX_BYTES = 10L * 1024 * 1024;
|
||||
static final Set<String> VARIANTS = Set.of("thumbnail", "crop", "optimized");
|
||||
static final Logger log = LoggerFactory.getLogger(Attachments.class);
|
||||
|
||||
record Attachment(UUID id, UUID chat_id, UUID owner_id, String filename, String content_type, long size_bytes, String sha256,
|
||||
String status, List<Object> variants, String error_code, Instant created_at, Instant updated_at) {}
|
||||
|
||||
final MessengerApplication.Api api;
|
||||
final JdbcTemplate db;
|
||||
final Storage storage;
|
||||
// Не больше N загрузок на реплику одновременно: диск под временные файлы и CPU проверки ограничены.
|
||||
final Semaphore uploads = new Semaphore(Integer.parseInt(System.getenv().getOrDefault("MAX_CONCURRENT_UPLOADS", "8")));
|
||||
|
||||
Attachments(MessengerApplication.Api api, JdbcTemplate db, Storage storage) {
|
||||
this.api = api;
|
||||
this.db = db;
|
||||
this.storage = storage;
|
||||
}
|
||||
|
||||
@PostMapping("/api/v1/chats/{id}/attachments")
|
||||
ResponseEntity<Attachment> upload(@PathVariable UUID id, @RequestParam(required = false) String filename, HttpServletRequest r)
|
||||
throws IOException, InterruptedException {
|
||||
// Порядок как у остальных endpoint: сессия → доступ к чату → входные данные.
|
||||
UUID user = api.auth(r);
|
||||
if (!api.member(id, user)) throw api.notFound();
|
||||
if (!validFilename(filename)) api.bad();
|
||||
String declared = declaredType(r.getContentType());
|
||||
if (declared == null) throw unsupported();
|
||||
// Заявленный размер проверяем до чтения тела.
|
||||
if (r.getContentLengthLong() > MAX_BYTES) throw tooLarge();
|
||||
if (!uploads.tryAcquire(10, TimeUnit.SECONDS)) throw unavailable("too many concurrent uploads, retry later");
|
||||
Path tmp = Files.createTempFile("upload-", ".bin");
|
||||
try {
|
||||
// 1. Тело — во временный файл с жёстким лимитом, SHA-256 считается по ходу. Файл живёт
|
||||
// только до конца запроса: это буфер проверки, а не хранилище оригинала.
|
||||
MessageDigest sha = sha256();
|
||||
long size = 0;
|
||||
try (InputStream in = r.getInputStream(); OutputStream out = Files.newOutputStream(tmp)) {
|
||||
byte[] buf = new byte[65536];
|
||||
while (true) {
|
||||
int n;
|
||||
try { n = in.read(buf); } catch (IOException e) { throw new ApiException(HttpStatus.BAD_REQUEST, "invalid_request", "upload interrupted"); }
|
||||
if (n < 0) break;
|
||||
size += n;
|
||||
if (size > MAX_BYTES) throw tooLarge();
|
||||
sha.update(buf, 0, n);
|
||||
out.write(buf, 0, n);
|
||||
}
|
||||
}
|
||||
if (size == 0) api.bad();
|
||||
// 2. Формат по содержимому, лимит пикселей по заголовку — до распаковки.
|
||||
ImageCheck.Info image;
|
||||
try { image = ImageCheck.inspect(tmp); } catch (ImageCheck.Invalid e) { throw e.tooLarge ? tooLarge() : unsupported(); }
|
||||
if (!image.contentType().equals(declared)) throw unsupported();
|
||||
// 3. Намерение в БД до S3 PUT: любой сбой дальше оставляет след, который найдёт сверка.
|
||||
UUID attachmentId = UUID.randomUUID();
|
||||
String key = Storage.ORIGINALS + attachmentId;
|
||||
String hash = HexFormat.of().formatHex(sha.digest());
|
||||
Instant created = now();
|
||||
db.update("insert into attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,width,height,state,object_key,created_at,updated_at) values(?,?,?,?,?,?,?,?,?,'uploading',?,?,?)",
|
||||
attachmentId, id, user, filename, declared, size, hash, image.width(), image.height(), key, Timestamp.from(created), Timestamp.from(created));
|
||||
// 4. S3 PUT. Не удался — сразу компенсируем строку; если и это не вышло, её уберёт сверка.
|
||||
try {
|
||||
storage.put(key, tmp, declared);
|
||||
} catch (SdkException e) {
|
||||
log.warn("S3 put failed for attachment {}: {}", attachmentId, e.toString());
|
||||
try { db.update("delete from attachments where id=? and state='uploading'", attachmentId); } catch (DataAccessException ignored) {}
|
||||
throw unavailable("object storage is unavailable");
|
||||
}
|
||||
// 5. ready — только после сохранения объекта. Не записалось — удаляем объект, строку уберёт сверка.
|
||||
Instant ready = now();
|
||||
try {
|
||||
db.update("update attachments set state='ready', updated_at=? where id=?", Timestamp.from(ready), attachmentId);
|
||||
} catch (DataAccessException e) {
|
||||
try { storage.delete(key); } catch (SdkException ignored) {}
|
||||
throw e;
|
||||
}
|
||||
return ResponseEntity.status(201).body(new Attachment(attachmentId, id, user, filename, declared, size, hash, "ready", List.of(), null, created, ready));
|
||||
} finally {
|
||||
Files.deleteIfExists(tmp);
|
||||
uploads.release();
|
||||
}
|
||||
}
|
||||
|
||||
@GetMapping("/api/v1/attachments/{id}")
|
||||
Attachment metadata(@PathVariable UUID id, HttpServletRequest r) {
|
||||
return visible(id, api.auth(r)).attachment();
|
||||
}
|
||||
|
||||
// Байты отдаются потоком из S3 через авторизованный API, без redirect на bucket.
|
||||
@GetMapping("/api/v1/attachments/{id}/content")
|
||||
void content(@PathVariable UUID id, @RequestParam(required = false) String variant, HttpServletRequest r, HttpServletResponse s) throws IOException {
|
||||
Visible v = visible(id, api.auth(r));
|
||||
if (variant != null && !variant.equals("original")) {
|
||||
// Вариантов в lab4 нет: известное имя — 404 (варианта нет), прочее — неверный параметр.
|
||||
if (VARIANTS.contains(variant)) throw api.notFound();
|
||||
api.bad();
|
||||
}
|
||||
ResponseInputStream<GetObjectResponse> in;
|
||||
try {
|
||||
in = storage.get(v.key());
|
||||
} catch (NoSuchKeyException e) {
|
||||
// Метаданные есть, объекта нет: рассинхронизация, её покажет и исправит сверка.
|
||||
log.error("object {} is missing for ready attachment {}", v.key(), id);
|
||||
throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "internal_error", "internal server error");
|
||||
} catch (SdkException e) {
|
||||
throw unavailable("object storage is unavailable");
|
||||
}
|
||||
try (in) {
|
||||
Attachment a = v.attachment();
|
||||
s.setContentType(a.content_type());
|
||||
s.setContentLengthLong(a.size_bytes());
|
||||
s.setHeader("Cache-Control", "private, no-store");
|
||||
s.setHeader("X-Content-Type-Options", "nosniff");
|
||||
in.transferTo(s.getOutputStream());
|
||||
}
|
||||
}
|
||||
|
||||
record Visible(Attachment attachment, String key) {}
|
||||
|
||||
// Только ready-вложения чатов, где пользователь участник; иначе 404 без раскрытия существования.
|
||||
Visible visible(UUID id, UUID user) {
|
||||
Visible v = db.query("select id,chat_id,owner_id,filename,content_type,size_bytes,sha256,created_at,updated_at,object_key from attachments a where id=? and state='ready'"
|
||||
+ " and exists(select 1 from chat_members m where m.chat_id=a.chat_id and m.user_id=?)", rs -> rs.next()
|
||||
? new Visible(new Attachment(rs.getObject(1, UUID.class), rs.getObject(2, UUID.class), rs.getObject(3, UUID.class), rs.getString(4), rs.getString(5),
|
||||
rs.getLong(6), rs.getString(7), "ready", List.of(), null, rs.getTimestamp(8).toInstant(), rs.getTimestamp(9).toInstant()), rs.getString(10))
|
||||
: null, id, user);
|
||||
if (v == null) throw api.notFound();
|
||||
return v;
|
||||
}
|
||||
|
||||
// filename только для отображения: 1–255 code points, без путей, NUL и управляющих символов.
|
||||
static boolean validFilename(String name) {
|
||||
if (name == null || name.isBlank() || name.equals(".") || name.equals("..")) return false;
|
||||
if (name.codePointCount(0, name.length()) > 255) return false;
|
||||
return name.codePoints().noneMatch(c -> c == '/' || c == '\\' || Character.getType(c) == Character.CONTROL
|
||||
|| c == 0x2028 || c == 0x2029 || Character.getType(c) == Character.SURROGATE);
|
||||
}
|
||||
|
||||
static String declaredType(String header) {
|
||||
try {
|
||||
MediaType t = MediaType.parseMediaType(header);
|
||||
String base = t.getType() + "/" + t.getSubtype();
|
||||
return base.equals("image/png") || base.equals("image/jpeg") ? base : null;
|
||||
} catch (RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
static Instant now() { return Instant.now().truncatedTo(ChronoUnit.MICROS); }
|
||||
|
||||
static MessageDigest sha256() {
|
||||
try { return MessageDigest.getInstance("SHA-256"); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
|
||||
}
|
||||
|
||||
static ApiException tooLarge() { return new ApiException(HttpStatus.PAYLOAD_TOO_LARGE, "payload_too_large", "attachment exceeds 10 MiB or 40 megapixels"); }
|
||||
static ApiException unsupported() { return new ApiException(HttpStatus.UNSUPPORTED_MEDIA_TYPE, "unsupported_media_type", "only valid PNG or JPEG content is accepted"); }
|
||||
static ApiException unavailable(String message) { return new ApiException(HttpStatus.SERVICE_UNAVAILABLE, "unavailable", message); }
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
package ru.mtusi.messenger;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.EOFException;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.zip.CRC32;
|
||||
import java.util.zip.DataFormatException;
|
||||
import java.util.zip.Inflater;
|
||||
|
||||
// Потоковая проверка PNG/JPEG по содержимому без декодирования в пиксели: память — буферы по 64 KiB,
|
||||
// а не ширина × высота. Размеры читаются из заголовка, лимит пикселей применяется до распаковки.
|
||||
final class ImageCheck {
|
||||
static final long MAX_PIXELS = 40_000_000L;
|
||||
static final byte[] PNG_SIGNATURE = {(byte) 0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'};
|
||||
|
||||
record Info(String contentType, int width, int height) {}
|
||||
|
||||
// tooLarge: валидный формат, но больше 40 Мпикс (413); иначе файл повреждён или чужого формата (415).
|
||||
static final class Invalid extends Exception {
|
||||
final boolean tooLarge;
|
||||
Invalid(String message, boolean tooLarge) { super(message); this.tooLarge = tooLarge; }
|
||||
}
|
||||
|
||||
private ImageCheck() {}
|
||||
|
||||
static Info inspect(Path file) throws IOException, Invalid {
|
||||
try (InputStream in = new BufferedInputStream(Files.newInputStream(file), 65536)) {
|
||||
in.mark(8);
|
||||
byte[] head = in.readNBytes(8);
|
||||
in.reset();
|
||||
if (Arrays.equals(head, PNG_SIGNATURE)) return png(new DataInputStream(in));
|
||||
if (head.length >= 3 && (head[0] & 0xff) == 0xff && (head[1] & 0xff) == 0xd8 && (head[2] & 0xff) == 0xff) return jpeg(in);
|
||||
throw bad("not a PNG or JPEG");
|
||||
}
|
||||
}
|
||||
|
||||
static Invalid bad(String message) { return new Invalid(message, false); }
|
||||
|
||||
static void checkPixels(long width, long height) throws Invalid {
|
||||
if (width <= 0 || height <= 0) throw bad("zero image dimension");
|
||||
if (width * height > MAX_PIXELS) throw new Invalid("image exceeds 40 megapixels", true);
|
||||
}
|
||||
|
||||
// PNG: CRC каждого chunk, IHDR первым, IEND последним, а IDAT распаковывается в никуда со счётчиком байтов.
|
||||
// Ровно ожидаемое число байтов после inflate ловит и обрыв, и мусор, и «бомбу» с честным заголовком.
|
||||
static Info png(DataInputStream in) throws IOException, Invalid {
|
||||
in.readFully(new byte[8]);
|
||||
CRC32 crc = new CRC32();
|
||||
Inflater inflater = new Inflater();
|
||||
byte[] buf = new byte[65536], out = new byte[65536];
|
||||
int width = 0, height = 0;
|
||||
long expected = -1, produced = 0;
|
||||
boolean first = true, inIdat = false, idatDone = false;
|
||||
try {
|
||||
while (true) {
|
||||
int length = in.readInt();
|
||||
if (length < 0) throw bad("invalid PNG chunk length");
|
||||
byte[] type = new byte[4];
|
||||
in.readFully(type);
|
||||
String name = new String(type, StandardCharsets.ISO_8859_1);
|
||||
crc.reset();
|
||||
crc.update(type);
|
||||
if (first != name.equals("IHDR")) throw bad("IHDR must be the first chunk");
|
||||
boolean idat = name.equals("IDAT");
|
||||
if (idat && (idatDone || expected < 0)) throw bad("IDAT chunks must be consecutive after IHDR");
|
||||
if (inIdat && !idat) idatDone = true;
|
||||
inIdat = idat;
|
||||
if (first) {
|
||||
if (length != 13) throw bad("invalid IHDR");
|
||||
byte[] h = new byte[13];
|
||||
in.readFully(h);
|
||||
crc.update(h);
|
||||
width = int32(h, 0);
|
||||
height = int32(h, 4);
|
||||
checkPixels(width, height);
|
||||
expected = rawSize(width, height, h[8] & 0xff, h[9] & 0xff, h[12] & 0xff);
|
||||
if (h[10] != 0 || h[11] != 0) throw bad("unsupported PNG compression/filter");
|
||||
} else {
|
||||
for (long left = length; left > 0; ) {
|
||||
int n = in.read(buf, 0, (int) Math.min(buf.length, left));
|
||||
if (n < 0) throw new EOFException();
|
||||
crc.update(buf, 0, n);
|
||||
left -= n;
|
||||
if (!idat || inflater.finished()) continue;
|
||||
inflater.setInput(buf, 0, n);
|
||||
while (!inflater.finished() && !inflater.needsInput()) {
|
||||
int k = inflater.inflate(out);
|
||||
produced += k;
|
||||
if (produced > expected) throw bad("PNG pixel data is larger than IHDR declares");
|
||||
if (k == 0 && inflater.needsDictionary()) throw bad("invalid PNG zlib stream");
|
||||
if (k == 0) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (in.readInt() != (int) crc.getValue()) throw bad("PNG chunk CRC mismatch");
|
||||
first = false;
|
||||
if (name.equals("IEND")) {
|
||||
if (!inflater.finished() || produced != expected) throw bad("PNG pixel data is truncated");
|
||||
if (in.read() != -1) throw bad("data after PNG IEND");
|
||||
return new Info("image/png", width, height);
|
||||
}
|
||||
}
|
||||
} catch (EOFException e) {
|
||||
throw bad("truncated PNG");
|
||||
} catch (DataFormatException e) {
|
||||
throw bad("invalid PNG zlib stream");
|
||||
} finally {
|
||||
inflater.end();
|
||||
}
|
||||
}
|
||||
|
||||
// Размер распакованных строк PNG (с байтом фильтра); для Adam7 — сумма по семи проходам.
|
||||
static long rawSize(long width, long height, int depth, int colorType, int interlace) throws Invalid {
|
||||
int channels = switch (colorType) {
|
||||
case 0 -> depth == 1 || depth == 2 || depth == 4 || depth == 8 || depth == 16 ? 1 : 0;
|
||||
case 3 -> depth == 1 || depth == 2 || depth == 4 || depth == 8 ? 1 : 0;
|
||||
case 2 -> depth == 8 || depth == 16 ? 3 : 0;
|
||||
case 4 -> depth == 8 || depth == 16 ? 2 : 0;
|
||||
case 6 -> depth == 8 || depth == 16 ? 4 : 0;
|
||||
default -> 0;
|
||||
};
|
||||
if (channels == 0) throw bad("invalid PNG color type/bit depth");
|
||||
long bits = (long) channels * depth;
|
||||
if (interlace == 0) return height * (1 + (width * bits + 7) / 8);
|
||||
if (interlace != 1) throw bad("invalid PNG interlace method");
|
||||
int[][] passes = {{0, 0, 8, 8}, {4, 0, 8, 8}, {0, 4, 4, 8}, {2, 0, 4, 4}, {0, 2, 2, 4}, {1, 0, 2, 2}, {0, 1, 1, 2}};
|
||||
long total = 0;
|
||||
for (int[] p : passes) {
|
||||
long w = width > p[0] ? (width - p[0] + p[2] - 1) / p[2] : 0;
|
||||
long h = height > p[1] ? (height - p[1] + p[3] - 1) / p[3] : 0;
|
||||
if (w > 0 && h > 0) total += h * (1 + (w * bits + 7) / 8);
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
// JPEG: SOI, корректные длины сегментов, SOF до первого SOS, энтропийные данные до EOI.
|
||||
// Байты после EOI допускаются: их дописывают многие камеры и телефоны.
|
||||
static Info jpeg(InputStream in) throws IOException, Invalid {
|
||||
in.skipNBytes(2);
|
||||
int width = 0, height = 0, marker = -1;
|
||||
boolean scan = false;
|
||||
try {
|
||||
while (true) {
|
||||
if (marker < 0) {
|
||||
if (in.read() != 0xff) throw bad("invalid JPEG marker");
|
||||
do marker = read(in); while (marker == 0xff);
|
||||
}
|
||||
int m = marker;
|
||||
marker = -1;
|
||||
if (m == 0xd9) {
|
||||
if (width == 0 || !scan) throw bad("JPEG has no frame or scan");
|
||||
return new Info("image/jpeg", width, height);
|
||||
}
|
||||
if (m == 0x01 || (m >= 0xd0 && m <= 0xd7)) continue;
|
||||
if (m == 0xd8 || m == 0x00) throw bad("unexpected JPEG marker");
|
||||
int length = (read(in) << 8) | read(in);
|
||||
if (length < 2) throw bad("invalid JPEG segment length");
|
||||
boolean sof = m >= 0xc0 && m <= 0xcf && m != 0xc4 && m != 0xc8 && m != 0xcc;
|
||||
if (sof) {
|
||||
if (length < 8 || width != 0) throw bad("invalid JPEG frame header");
|
||||
in.skipNBytes(1);
|
||||
height = (read(in) << 8) | read(in);
|
||||
width = (read(in) << 8) | read(in);
|
||||
checkPixels(width, height);
|
||||
in.skipNBytes(length - 7);
|
||||
} else if (m == 0xda) {
|
||||
if (width == 0) throw bad("JPEG scan before frame header");
|
||||
in.skipNBytes(length - 2);
|
||||
marker = entropy(in);
|
||||
scan = true;
|
||||
} else {
|
||||
in.skipNBytes(length - 2);
|
||||
}
|
||||
}
|
||||
} catch (EOFException e) {
|
||||
throw bad("truncated JPEG");
|
||||
}
|
||||
}
|
||||
|
||||
// Пропускает сжатые данные скана; FF00 — экранированный байт, FFD0..FFD7 — restart-маркеры.
|
||||
static int entropy(InputStream in) throws IOException {
|
||||
boolean ff = false;
|
||||
while (true) {
|
||||
int c = read(in);
|
||||
if (!ff) { ff = c == 0xff; continue; }
|
||||
if (c == 0xff) continue;
|
||||
if (c == 0x00 || (c >= 0xd0 && c <= 0xd7)) { ff = false; continue; }
|
||||
return c;
|
||||
}
|
||||
}
|
||||
|
||||
static int read(InputStream in) throws IOException {
|
||||
int c = in.read();
|
||||
if (c < 0) throw new EOFException();
|
||||
return c;
|
||||
}
|
||||
|
||||
static int int32(byte[] b, int at) {
|
||||
return ((b[at] & 0xff) << 24) | ((b[at + 1] & 0xff) << 16) | ((b[at + 2] & 0xff) << 8) | (b[at + 3] & 0xff);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
package ru.mtusi.messenger;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.*;
|
||||
import org.springframework.boot.*;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
|
||||
import org.springframework.boot.builder.SpringApplicationBuilder;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.http.*;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import com.fasterxml.jackson.databind.MapperFeature;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.time.*;
|
||||
import java.util.*;
|
||||
import java.util.Base64;
|
||||
|
||||
// Главная аннотация Spring Boot: включает запуск приложения и автоматическую настройку.
|
||||
// @EnableScheduling запускает периодическую сверку БД и S3 (Reconciler) в API-репликах.
|
||||
@SpringBootApplication
|
||||
@EnableScheduling
|
||||
public class MessengerApplication {
|
||||
// Идентификатор экземпляра API = hostname контейнера (первые 12 символов ID контейнера в Docker).
|
||||
// По нему scripts/stop-one.sh находит и останавливает нужную реплику.
|
||||
private static final String INSTANCE_ID = System.getenv().getOrDefault("HOSTNAME", UUID.randomUUID().toString());
|
||||
|
||||
// Один образ — три режима: api (HTTP-сервер, по умолчанию), migrate (Flyway и выход)
|
||||
// и reconcile (сверка БД и S3 и выход; аргументы см. Reconciler.cli).
|
||||
public static void main(String[] args) throws IOException {
|
||||
String mode = args.length > 0 ? args[0] : "api";
|
||||
if (mode.equals("api")) {
|
||||
SpringApplication.run(MessengerApplication.class, args);
|
||||
return;
|
||||
}
|
||||
if (mode.equals("migrate")) {
|
||||
// Только Flyway, без контекста Spring: контейнеру migration не нужны ни Redis, ни S3, ни их секреты.
|
||||
String password = java.nio.file.Files.readString(java.nio.file.Path.of("/run/secrets/spring.datasource.password")).trim();
|
||||
org.flywaydb.core.Flyway.configure().dataSource(System.getenv("SPRING_DATASOURCE_URL"), System.getenv("SPRING_DATASOURCE_USERNAME"), password).load().migrate();
|
||||
return;
|
||||
}
|
||||
if (!mode.equals("reconcile")) {
|
||||
System.err.println("usage: [api | migrate | reconcile [--apply] [--grace-seconds=N] [--verify-checksums]]");
|
||||
System.exit(2);
|
||||
}
|
||||
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(MessengerApplication.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("reconcile.enabled=false", "spring.main.banner-mode=off", "logging.level.root=WARN")
|
||||
.run();
|
||||
int code;
|
||||
try {
|
||||
code = ctx.getBean(Reconciler.class).cli(Arrays.copyOfRange(args, 1, args.length));
|
||||
} catch (Exception e) {
|
||||
LoggerFactory.getLogger(MessengerApplication.class).error("reconcile failed", e);
|
||||
code = 1;
|
||||
}
|
||||
int exit = code;
|
||||
System.exit(SpringApplication.exit(ctx, () -> exit));
|
||||
}
|
||||
|
||||
// @Bean регистрирует возвращаемый объект в контейнере Spring.
|
||||
// BCrypt хранит пароль в виде хеша, поэтому исходный пароль не попадает в базу.
|
||||
@Bean
|
||||
BCryptPasswordEncoder passwordEncoder() {
|
||||
// Возвращаем BCrypt-кодировщик, который Spring передаст контроллеру.
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
// Отключаем автоматическое превращение чисел в строки при чтении JSON.
|
||||
@Bean
|
||||
Jackson2ObjectMapperBuilderCustomizer strictJson() {
|
||||
return builder -> builder.featuresToDisable(MapperFeature.ALLOW_COERCION_OF_SCALARS);
|
||||
}
|
||||
|
||||
// @Bean регистрирует фильтр в контейнере Spring.
|
||||
// Фильтр добавляет общий идентификатор каждому HTTP-ответу.
|
||||
@Bean OncePerRequestFilter requestId() {
|
||||
return new OncePerRequestFilter() {
|
||||
// Метод фильтра вызывается для каждого HTTP-запроса.
|
||||
protected void doFilterInternal(HttpServletRequest r, HttpServletResponse s, FilterChain c)
|
||||
throws ServletException, IOException {
|
||||
// Создаём уникальный идентификатор текущего запроса.
|
||||
String id=UUID.randomUUID().toString();
|
||||
// Добавляем идентификатор в HTTP-ответ.
|
||||
s.setHeader("X-Request-Id", id);
|
||||
// Добавляем стабильный идентификатор экземпляра API.
|
||||
s.setHeader("X-Instance-Id", INSTANCE_ID);
|
||||
// Сохраняем тот же идентификатор для обработчика ошибок.
|
||||
r.setAttribute("requestId", id);
|
||||
// Передаём запрос дальше по цепочке Spring.
|
||||
c.doFilter(r, s);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Эти record-классы описывают JSON-модели ответов и запросов.
|
||||
// Публичная модель пользователя без пароля.
|
||||
record User(UUID id, String username, String display_name, Instant created_at) {}
|
||||
// Модель чата со списком участников.
|
||||
record Chat(UUID id, String title, List<UUID> member_ids, Instant created_at) {}
|
||||
// Модель сообщения с автором, временем создания и вложениями (в порядке из запроса).
|
||||
record Message(UUID id, UUID chat_id, UUID sender_id, String text, Instant created_at, List<UUID> attachment_ids) {}
|
||||
// Универсальная модель страницы списка.
|
||||
record Page<T>(List<T> items, String next_cursor) {}
|
||||
// Ответ успешного входа с Bearer-токеном.
|
||||
record Session(String token, String token_type, Instant expires_at, User user) {}
|
||||
// Тело запроса регистрации.
|
||||
record UserIn(JsonNode username, JsonNode display_name, JsonNode password) {}
|
||||
// Тело запроса создания чата.
|
||||
record ChatIn(JsonNode title, List<UUID> member_ids) {}
|
||||
// Тело запроса отправки сообщения; attachment_ids необязателен (по умолчанию []).
|
||||
record MessageIn(JsonNode text, JsonNode attachment_ids) {}
|
||||
// Поля внутренней ошибки API.
|
||||
record Error(String code, String message, String request_id) {}
|
||||
// Обёртка, требуемая форматом JSON ошибки.
|
||||
record ErrorBody(Error error) {}
|
||||
|
||||
// Исключение хранит HTTP-статус и безопасный код ошибки.
|
||||
static class ApiException extends RuntimeException {
|
||||
// HTTP-статус, который будет отправлен клиенту.
|
||||
final HttpStatus status;
|
||||
// Короткий код ошибки для программы-клиента.
|
||||
final String code;
|
||||
ApiException(HttpStatus s, String c, String m) {
|
||||
// Сохраняем текст сообщения в стандартном RuntimeException.
|
||||
super(m);
|
||||
status=s;
|
||||
code=c;
|
||||
}
|
||||
}
|
||||
|
||||
// @RestController объединяет @Controller и @ResponseBody.
|
||||
// Методы этого класса принимают HTTP-запросы и возвращают JSON.
|
||||
@RestController
|
||||
static class Api {
|
||||
// JdbcTemplate работает с PostgreSQL, RedisTemplate — с Redis-сессиями.
|
||||
// JdbcTemplate отправляет SQL-запросы в PostgreSQL.
|
||||
final JdbcTemplate db;
|
||||
// StringRedisTemplate работает со строковыми ключами Redis.
|
||||
final StringRedisTemplate redis;
|
||||
// BCryptPasswordEncoder проверяет и хеширует пароли.
|
||||
final BCryptPasswordEncoder encoder;
|
||||
// Генератор создаёт 32 случайных байта для каждой сессии.
|
||||
final SecureRandom random = new SecureRandom();
|
||||
// TTL можно уменьшить через переменную окружения для проверки expiry.
|
||||
final long ttl = Long.parseLong(System.getenv().getOrDefault("SESSION_TTL_SECONDS", "3600"));
|
||||
Api(JdbcTemplate d, StringRedisTemplate r, BCryptPasswordEncoder e) {
|
||||
// Сохраняем зависимости, созданные Spring Boot.
|
||||
db=d;
|
||||
redis=r;
|
||||
encoder=e;
|
||||
}
|
||||
// Метод проверяет доступность PostgreSQL тестовым запросом.
|
||||
void dbOk() {
|
||||
try {
|
||||
// Простой запрос проверяет соединение с PostgreSQL.
|
||||
db.queryForObject("select 1", Integer.class);
|
||||
} catch (Exception e) {
|
||||
// Внутреннюю ошибку базы не показываем клиенту.
|
||||
throw new ApiException(HttpStatus.SERVICE_UNAVAILABLE,"unavailable","database is unavailable");
|
||||
}
|
||||
}
|
||||
// Метод проверяет Bearer-токен и возвращает UUID пользователя.
|
||||
UUID auth(HttpServletRequest req) {
|
||||
// Читаем заголовок авторизации из HTTP-запроса.
|
||||
String h=req.getHeader("Authorization");
|
||||
// Защищённые методы принимают только Bearer-схему.
|
||||
if (h==null || !h.startsWith("Bearer ")) throw unauth();
|
||||
// В Redis хранится связь токена с UUID пользователя.
|
||||
try { String v=redis.opsForValue().get("session:"+h.substring(7)); if(v==null) throw unauth(); return UUID.fromString(v); }
|
||||
catch (ApiException e) { throw e; } catch (Exception e) { throw new ApiException(HttpStatus.SERVICE_UNAVAILABLE,"unavailable","session store is unavailable"); }
|
||||
}
|
||||
ApiException unauth() { return new ApiException(HttpStatus.UNAUTHORIZED,"unauthorized","valid Bearer session required"); }
|
||||
// Загружаем пользователя по UUID из PostgreSQL.
|
||||
// Метод ищет пользователя в PostgreSQL по его UUID.
|
||||
User user(UUID id) {
|
||||
return db.query("select id,username,display_name,created_at from users where id=?", rs -> rs.next()
|
||||
? new User(rs.getObject(1,UUID.class),rs.getString(2),rs.getString(3),rs.getTimestamp(4).toInstant()) : null, id);
|
||||
}
|
||||
// Метод проверяет, состоит ли пользователь в выбранном чате.
|
||||
boolean member(UUID chat, UUID user) {
|
||||
// Пользователь должен состоять в чате, иначе ресурс для него скрыт.
|
||||
return Boolean.TRUE.equals(db.queryForObject("select exists(select 1 from chat_members where chat_id=? and user_id=?)",Boolean.class,chat,user));
|
||||
}
|
||||
// Загружает один чат и его участников напрямую по идентификатору.
|
||||
Chat chatById(UUID id) {
|
||||
return db.query("select id,title,created_at from chats where id=?",rs -> rs.next()
|
||||
? new Chat(rs.getObject(1,UUID.class),rs.getString(2),
|
||||
db.query("select user_id from chat_members where chat_id=?",(z,k)->z.getObject(1,UUID.class),id),
|
||||
rs.getTimestamp(3).toInstant()) : null,id);
|
||||
}
|
||||
// Считает символы как Unicode code points, а не как UTF-16 char.
|
||||
int codePointLength(String value) {
|
||||
return value.codePointCount(0,value.length());
|
||||
}
|
||||
// Возвращает значение только если JSON-поле действительно является строкой.
|
||||
String string(JsonNode value) { return value!=null && value.isTextual()?value.textValue():null; }
|
||||
// PostgreSQL не хранит нулевой байт, поэтому заменяем его безопасным символом.
|
||||
String databaseText(String value) { return value==null?null:value.replace('\0','\uFFFD'); }
|
||||
// Проверяет обязательную непустую строку и её максимальную длину.
|
||||
boolean text(String value, int max) { return value!=null && !value.isBlank() && codePointLength(value)<=max; }
|
||||
// Предварительный SHA-256 сохраняет весь пароль перед ограниченным BCrypt.
|
||||
String passwordValue(String value) {
|
||||
try { return Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); }
|
||||
catch (Exception e) { throw new IllegalStateException("password hashing is unavailable",e); }
|
||||
}
|
||||
|
||||
// Готовность проверяет не только Java-процесс, но и его зависимости.
|
||||
// @GetMapping связывает GET-запрос с Java-методом.
|
||||
@GetMapping({"/health/live","/health/ready"})
|
||||
// Для ready дополнительно проверяем PostgreSQL и Redis.
|
||||
// Метод возвращает JSON со статусом приложения.
|
||||
Map<String,String> health(HttpServletRequest r) { if (r.getRequestURI().endsWith("ready")) { dbOk(); try { redis.hasKey("health"); } catch(Exception e) { throw new ApiException(HttpStatus.SERVICE_UNAVAILABLE,"unavailable","session store is unavailable"); } } return Map.of("status","ok"); }
|
||||
// @PostMapping связывает POST-запрос с методом регистрации.
|
||||
@PostMapping("/api/v1/users")
|
||||
// @RequestBody преобразует JSON-тело запроса в объект UserIn.
|
||||
ResponseEntity<User> register(@RequestBody UserIn in) {
|
||||
String username=in==null?null:string(in.username());
|
||||
String displayName=in==null?null:string(in.display_name());
|
||||
String password=in==null?null:string(in.password());
|
||||
// До запроса в базу проверяем формат обязательных полей.
|
||||
if(username==null || !username.matches("[a-z0-9_]{3,32}") || !text(displayName,100) || password==null || password.isBlank() || codePointLength(password)<12 || codePointLength(password)>128) bad();
|
||||
displayName=databaseText(displayName);
|
||||
// Создаём UUID пользователя и фиксируем время регистрации.
|
||||
UUID id=UUID.randomUUID(); Instant now=Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MICROS);
|
||||
// Значения передаются параметрами, а не склеиваются со строкой SQL.
|
||||
try { db.update("insert into users values(?,?,?,?,?)",id,username,displayName,encoder.encode(passwordValue(password)),java.sql.Timestamp.from(now)); }
|
||||
// Уникальное ограничение username превращаем в понятный ответ 409.
|
||||
catch(DuplicateKeyException e) { throw new ApiException(HttpStatus.CONFLICT,"conflict","username is already used"); }
|
||||
// Возвращаем созданного пользователя без пароля.
|
||||
return ResponseEntity.status(201).body(new User(id,username,displayName,now));
|
||||
}
|
||||
// POST-метод входа проверяет Basic-логин и создаёт Bearer-сессию.
|
||||
@PostMapping("/api/v1/auth/sessions")
|
||||
// HttpServletRequest позволяет прочитать заголовок Authorization.
|
||||
ResponseEntity<Session> login(HttpServletRequest req) {
|
||||
// Читаем Basic-заголовок, который используется только при входе.
|
||||
String h=req.getHeader("Authorization");
|
||||
if(h==null || !h.startsWith("Basic ")) { HttpHeaders x=new HttpHeaders(); x.set("WWW-Authenticate","Basic realm=\"messenger\", charset=\"UTF-8\""); throw new ApiException(HttpStatus.UNAUTHORIZED,"unauthorized","Basic authentication required"); }
|
||||
// Basic используется только для входа, после него клиент получает Bearer-токен.
|
||||
String[] p; try { p=new String(Base64.getDecoder().decode(h.substring(6)),StandardCharsets.UTF_8).split(":",2); } catch(Exception e) { p=new String[0]; }
|
||||
// Получаем BCrypt-хеш пользователя из PostgreSQL.
|
||||
String hash=p.length==2 ? db.query("select password_hash from users where username=?",rs -> rs.next()?rs.getString(1):null,p[0]) : null;
|
||||
// Сравниваем введённый пароль с сохранённым хешем.
|
||||
if(p.length!=2 || hash==null || codePointLength(p[1])<12 || codePointLength(p[1])>128 || !encoder.matches(passwordValue(p[1]),hash)) { HttpHeaders x=new HttpHeaders(); x.set("WWW-Authenticate","Basic realm=\"messenger\", charset=\"UTF-8\""); throw new ApiException(HttpStatus.UNAUTHORIZED,"unauthorized","invalid credentials"); }
|
||||
// После успешной проверки загружаем полную модель пользователя.
|
||||
User u=user(db.queryForObject("select id from users where username=?",UUID.class,p[0]));
|
||||
// Генерируем непрозрачный случайный токен сессии.
|
||||
byte[] secret=new byte[32]; random.nextBytes(secret);
|
||||
String token=Base64.getUrlEncoder().withoutPadding().encodeToString(secret);
|
||||
// Вычисляем момент, когда сессия перестанет действовать.
|
||||
Instant exp=Instant.now().plusSeconds(ttl);
|
||||
// Сессия автоматически удалится из Redis после окончания TTL.
|
||||
try { redis.opsForValue().set("session:"+token,u.id().toString(),Duration.ofSeconds(ttl)); } catch(Exception e) { throw new ApiException(HttpStatus.SERVICE_UNAVAILABLE,"unavailable","session store is unavailable"); }
|
||||
return ResponseEntity.status(201).body(new Session(token,"Bearer",exp,u));
|
||||
}
|
||||
// @DeleteMapping связывает DELETE-запрос с удалением сессии.
|
||||
// Logout сразу удаляет текущий токен из Redis.
|
||||
@DeleteMapping("/api/v1/auth/sessions/current") ResponseEntity<Void> logout(HttpServletRequest r) { auth(r); redis.delete("session:"+r.getHeader("Authorization").substring(7)); return ResponseEntity.noContent().build(); }
|
||||
// GET-запрос возвращает данные текущего авторизованного пользователя.
|
||||
@GetMapping("/api/v1/users/me") User me(HttpServletRequest r) { return user(auth(r)); }
|
||||
// @Transactional объединяет несколько SQL-команд в одну транзакцию.
|
||||
// Если одна команда завершится ошибкой, изменения откатываются.
|
||||
// Вставка чата и всех его участников выполняется как одна транзакция.
|
||||
@Transactional
|
||||
// POST-запрос создаёт новый чат.
|
||||
@PostMapping("/api/v1/chats") ResponseEntity<Chat> createChat(@RequestBody ChatIn in,HttpServletRequest r) {
|
||||
// Владелец чата определяется по Bearer-сессии.
|
||||
String title=in==null?null:string(in.title());
|
||||
UUID owner=auth(r); if(!text(title,100)||in.member_ids()==null||in.member_ids().isEmpty()||in.member_ids().size()>100||new HashSet<>(in.member_ids()).size()!=in.member_ids().size()||!in.member_ids().contains(owner)) bad();
|
||||
// Проверяем существование каждого участника.
|
||||
for(UUID id:in.member_ids()) if(user(id)==null) bad();
|
||||
// ID и время создаются сервером. PostgreSQL хранит микросекунды, поэтому ответ POST совпадает с GET.
|
||||
UUID id=UUID.randomUUID(); Instant now=Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MICROS);
|
||||
// Записываем чат и участников в одной транзакции.
|
||||
title=databaseText(title);
|
||||
db.update("insert into chats values(?,?,?)",id,title,java.sql.Timestamp.from(now)); for(UUID m:in.member_ids()) db.update("insert into chat_members values(?,?)",id,m);
|
||||
// Возвращаем созданную модель чата.
|
||||
return ResponseEntity.status(201).body(new Chat(id,title,in.member_ids(),now));
|
||||
}
|
||||
// GET-запрос получает список чатов текущего пользователя.
|
||||
@GetMapping("/api/v1/chats")
|
||||
Page<Chat> chats(HttpServletRequest r) {
|
||||
// Определяем пользователя, для которого строится список.
|
||||
UUID u=auth(r);
|
||||
String cursor=r.getParameter("cursor");
|
||||
int limit=parseLimit(r.getParameter("limit"));
|
||||
// Запрашиваем только чаты, где пользователь является участником.
|
||||
String sql="select c.id,c.title,c.created_at from chats c join chat_members m on m.chat_id=c.id where m.user_id=? ";
|
||||
List<Object> args=new ArrayList<>(List.of(u));
|
||||
if(cursor!=null) {
|
||||
try {
|
||||
String[] p=new String(Base64.getUrlDecoder().decode(cursor),StandardCharsets.UTF_8).split("\\|",-1);
|
||||
if(p.length!=2) bad();
|
||||
sql+="and (c.created_at,c.id)>(?,?) ";
|
||||
args.add(java.sql.Timestamp.from(OffsetDateTime.parse(p[0]).toInstant()));
|
||||
args.add(UUID.fromString(p[1]));
|
||||
} catch(Exception e) { if(e instanceof ApiException a) throw a; bad(); }
|
||||
}
|
||||
sql+="order by c.created_at,c.id limit ?";
|
||||
args.add(limit+1);
|
||||
List<Chat> x=db.query(sql,(rs,n)->new Chat(rs.getObject(1,UUID.class),rs.getString(2),db.query("select user_id from chat_members where chat_id=?", (z,k)->z.getObject(1,UUID.class),rs.getObject(1)),rs.getTimestamp(3).toInstant()),args.toArray());
|
||||
String next=x.size()>limit?Base64.getUrlEncoder().withoutPadding().encodeToString((x.get(limit-1).created_at()+"|"+x.get(limit-1).id()).getBytes(StandardCharsets.UTF_8)):null;
|
||||
return new Page<>(x.subList(0,Math.min(limit,x.size())),next);
|
||||
}
|
||||
// {id} является переменной частью URL.
|
||||
@GetMapping("/api/v1/chats/{id}")
|
||||
// @PathVariable получает id из адреса запроса.
|
||||
Chat chat(@PathVariable UUID id,HttpServletRequest r) {
|
||||
// Сначала проверяем токен и членство в чате.
|
||||
UUID u=auth(r); if(!member(id,u)) throw notFound();
|
||||
// Загружаем чат напрямую, поэтому поздние записи не зависят от первой страницы списка.
|
||||
Chat result=chatById(id);
|
||||
if(result==null) throw notFound();
|
||||
return result;
|
||||
}
|
||||
// POST-запрос добавляет сообщение в выбранный чат.
|
||||
// @PathVariable получает id чата, а @RequestBody — текст из JSON.
|
||||
@Transactional
|
||||
@PostMapping("/api/v1/chats/{id}/messages") ResponseEntity<Message> message(@PathVariable UUID id,@RequestBody MessageIn in,HttpServletRequest r) {
|
||||
// Автор сообщения берётся из сессии, а не из тела запроса.
|
||||
String messageText=databaseText(in==null?null:string(in.text()));
|
||||
UUID u=auth(r); if(!member(id,u)) throw notFound();
|
||||
List<UUID> attachments=attachmentIds(in==null?null:in.attachment_ids());
|
||||
// Пустой текст допустим только с вложением; непустой не может состоять из одних пробелов.
|
||||
if(messageText==null || codePointLength(messageText)>4000 || (messageText.isEmpty()?attachments.isEmpty():messageText.isBlank())) bad();
|
||||
// Проверяем обязательный Idempotency-Key.
|
||||
String key=r.getHeader("Idempotency-Key");
|
||||
if(key==null || !key.matches("[A-Za-z0-9._:-]{1,128}")) throw new ApiException(HttpStatus.BAD_REQUEST,"invalid_request","valid Idempotency-Key required");
|
||||
// Все вложения должны быть готовыми вложениями этого чата; чужое или неизвестное — 404.
|
||||
if(!attachments.isEmpty() && db.queryForObject("select count(*) from attachments where chat_id=? and state='ready' and id=any(?)",Integer.class,id,attachments.toArray(new UUID[0]))!=attachments.size()) throw notFound();
|
||||
// Хеш тела для повторов с тем же ключом: отсутствующий attachment_ids и [] дают одно значение.
|
||||
String bodyHash;
|
||||
try { bodyHash=Base64.getEncoder().encodeToString(MessageDigest.getInstance("SHA-256").digest((messageText+"\0"+attachments).getBytes(StandardCharsets.UTF_8))); }
|
||||
catch(Exception e) { throw new IllegalStateException("hash unavailable",e); }
|
||||
// Сервер создаёт ID и время сообщения.
|
||||
UUID mid=UUID.randomUUID(); Instant now=Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MICROS);
|
||||
// Сначала занимаем ключ. При одновременном повторе через другую реплику PostgreSQL ждёт
|
||||
// её транзакцию, а ON CONFLICT DO NOTHING не обрывает нашу транзакцию ошибкой (иначе был бы 503).
|
||||
if(db.update("insert into idempotency_keys values(?,?,?,?,?,?) on conflict do nothing",key,u,id,bodyHash,mid,java.sql.Timestamp.from(now))==0) {
|
||||
// Ключ уже занят: тот же body — возвращаем созданное сообщение, другой body — 409.
|
||||
UUID existingId=db.query("select message_id,request_hash from idempotency_keys where user_id=? and chat_id=? and idempotency_key=?",rs -> {
|
||||
if(rs.next()) {
|
||||
if(!bodyHash.equals(rs.getString(2))) throw new ApiException(HttpStatus.CONFLICT,"conflict","different body with same idempotency key");
|
||||
return rs.getObject(1,UUID.class);
|
||||
}
|
||||
return null;
|
||||
},u,id,key);
|
||||
Message existing=db.queryForObject(MESSAGE_SELECT+"where m.id=?",this::messageRow,existingId);
|
||||
return ResponseEntity.status(201).body(existing);
|
||||
}
|
||||
// Сообщение и его вложения пишутся в той же транзакции, что и ключ: появится всё или ничего.
|
||||
db.update("insert into messages values(?,?,?,?,?)",mid,id,u,messageText,java.sql.Timestamp.from(now));
|
||||
for(int i=0;i<attachments.size();i++) db.update("insert into message_attachments values(?,?,?)",mid,attachments.get(i),i);
|
||||
return ResponseEntity.status(201).body(new Message(mid,id,u,messageText,now,attachments));
|
||||
}
|
||||
// Колонки сообщения; attachment_ids собираются из message_attachments в порядке отправки.
|
||||
static final String MESSAGE_SELECT="select m.id,m.chat_id,m.sender_id,m.text,m.created_at,"
|
||||
+"coalesce((select array_agg(x.attachment_id order by x.position) from message_attachments x where x.message_id=m.id),'{}') from messages m ";
|
||||
Message messageRow(java.sql.ResultSet rs,int n) throws java.sql.SQLException {
|
||||
return new Message(rs.getObject(1,UUID.class),rs.getObject(2,UUID.class),rs.getObject(3,UUID.class),rs.getString(4),rs.getTimestamp(5).toInstant(),List.of((UUID[])rs.getArray(6).getArray()));
|
||||
}
|
||||
// attachment_ids: отсутствует — []; иначе массив 0–10 уникальных UUID в каноническом виде.
|
||||
List<UUID> attachmentIds(JsonNode value) {
|
||||
if(value==null) return List.of();
|
||||
if(!value.isArray() || value.size()>10) bad();
|
||||
List<UUID> ids=new ArrayList<>();
|
||||
for(JsonNode x:value) {
|
||||
String s=x.isTextual()?x.textValue():"";
|
||||
try { UUID id=UUID.fromString(s); if(!id.toString().equalsIgnoreCase(s)) bad(); ids.add(id); } catch(IllegalArgumentException e) { bad(); }
|
||||
}
|
||||
if(new HashSet<>(ids).size()!=ids.size()) bad();
|
||||
return ids;
|
||||
}
|
||||
// GET-запрос возвращает историю сообщений с cursor-пагинацией.
|
||||
// @RequestParam получает limit и cursor из параметров URL.
|
||||
@GetMapping("/api/v1/chats/{id}/messages") Page<Message> messages(@PathVariable UUID id,@RequestParam(required=false) String limit,@RequestParam(required=false) String cursor,HttpServletRequest r) {
|
||||
// Историю может читать только участник чата.
|
||||
UUID u=auth(r); if(!member(id,u)) throw notFound(); int pageLimit=parseLimit(limit);
|
||||
// Начинаем параметризованный запрос истории.
|
||||
String sql=MESSAGE_SELECT+"where m.chat_id=? ";
|
||||
// Список параметров передаётся в JdbcTemplate отдельно от SQL.
|
||||
List<Object> args=new ArrayList<>(List.of(id));
|
||||
if(cursor!=null) {
|
||||
try {
|
||||
// Cursor хранит время и ID последнего сообщения предыдущей страницы.
|
||||
// Декодируем cursor из Base64 в обычную строку.
|
||||
String[] p=new String(Base64.getUrlDecoder().decode(cursor),StandardCharsets.UTF_8).split("\\|",-1);
|
||||
if(p.length!=3 || !id.equals(UUID.fromString(p[0]))) bad();
|
||||
// Добавляем условие keyset-пагинации после последнего сообщения.
|
||||
sql+="and (m.created_at,m.id)>(?,?) "; args.add(java.sql.Timestamp.from(OffsetDateTime.parse(p[1]).toInstant())); args.add(UUID.fromString(p[2]));
|
||||
} catch(Exception e) { bad(); }
|
||||
}
|
||||
// Сортируем историю и берём одну запись сверх лимита для следующего cursor.
|
||||
sql+="order by m.created_at,m.id limit ?"; args.add(pageLimit+1);
|
||||
// Выполняем запрос и превращаем строки базы в объекты Message.
|
||||
List<Message> x=db.query(sql,this::messageRow,args.toArray());
|
||||
// Если запись сверх лимита есть, кодируем её позицию как следующий cursor.
|
||||
String next=x.size()>pageLimit?Base64.getUrlEncoder().withoutPadding().encodeToString((id+"|"+x.get(pageLimit-1).created_at()+"|"+x.get(pageLimit-1).id()).getBytes(StandardCharsets.UTF_8)):null; return new Page<>(x.subList(0,Math.min(pageLimit,x.size())),next);
|
||||
}
|
||||
// Преобразует limit списка чатов в число и проверяет диапазон.
|
||||
int parseLimit(String value) { try { int limit=value==null?50:Integer.parseInt(value); if(limit<1||limit>100) bad(); return limit; } catch(NumberFormatException e) { bad(); return 0; } }
|
||||
// Формируем ошибку, не раскрывая наличие чужого объекта.
|
||||
ApiException notFound(){return new ApiException(HttpStatus.NOT_FOUND,"not_found","object not found");}
|
||||
// Формируем общую ошибку некорректного запроса.
|
||||
void bad(){throw new ApiException(HttpStatus.BAD_REQUEST,"invalid_request","invalid request");}
|
||||
}
|
||||
// @RestControllerAdvice применяет обработчики ко всем REST-контроллерам.
|
||||
// Благодаря этому ошибки возвращаются в одном формате JSON.
|
||||
@RestControllerAdvice static class Errors {
|
||||
// Все ошибки API приводятся к одному JSON-формату.
|
||||
// @ExceptionHandler связывает тип исключения с методом обработки.
|
||||
// Здесь обрабатываются специально созданные ошибки API.
|
||||
@ExceptionHandler(ApiException.class) ResponseEntity<ErrorBody> api(ApiException e,HttpServletRequest r){
|
||||
// Создаём заголовки ответа с ошибкой.
|
||||
HttpHeaders h=new HttpHeaders();
|
||||
if(e.status==HttpStatus.UNAUTHORIZED) h.set("WWW-Authenticate",r.getRequestURI().equals("/api/v1/auth/sessions")?"Basic realm=\"messenger\", charset=\"UTF-8\"":"Bearer realm=\"messenger\"");
|
||||
// Возвращаем статус, заголовки и единое тело ошибки.
|
||||
return ResponseEntity.status(e.status).headers(h).body(new ErrorBody(new Error(e.code,e.getMessage(),id(r))));
|
||||
}
|
||||
// Неожиданные исключения превращаем в безопасный ответ 500.
|
||||
// Этот обработчик является запасным для неожиданных исключений.
|
||||
@ExceptionHandler(Exception.class) ResponseEntity<ErrorBody> other(Exception e,HttpServletRequest r){
|
||||
// Ошибки самого Spring MVC (неизвестный путь, метод, Content-Type) сохраняют свой 4xx, а не становятся 500.
|
||||
if(e instanceof org.springframework.web.ErrorResponse x && x.getStatusCode().is4xxClientError()) {
|
||||
int s=x.getStatusCode().value();
|
||||
Error err=s==404?new Error("not_found","object not found",id(r)):s==415?new Error("unsupported_media_type","unsupported media type",id(r)):new Error("invalid_request","invalid request",id(r));
|
||||
return ResponseEntity.status(s).headers(x.getHeaders()).body(new ErrorBody(err));
|
||||
}
|
||||
LoggerFactory.getLogger(Errors.class).error("request failed",e); return ResponseEntity.status(500).body(new ErrorBody(new Error("internal_error","internal server error",id(r)))); }
|
||||
// Неправильный JSON считается ошибкой входных данных клиента.
|
||||
// Этот обработчик ловит неправильный или повреждённый JSON.
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class) ResponseEntity<ErrorBody> malformed(HttpServletRequest r){ return ResponseEntity.badRequest().body(new ErrorBody(new Error("invalid_request","invalid request",id(r)))); }
|
||||
// Ошибка преобразования UUID или числового параметра означает неверный запрос.
|
||||
@ExceptionHandler(MethodArgumentTypeMismatchException.class) ResponseEntity<ErrorBody> mismatch(HttpServletRequest r){ return ResponseEntity.badRequest().body(new ErrorBody(new Error("invalid_request","invalid request",id(r)))); }
|
||||
// Ошибка PostgreSQL возвращается как временная недоступность зависимости.
|
||||
@ExceptionHandler(DataAccessException.class) ResponseEntity<ErrorBody> database(DataAccessException e,HttpServletRequest r){ return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE).body(new ErrorBody(new Error("unavailable","database is unavailable",id(r)))); }
|
||||
// Получаем ID запроса, который добавил фильтр.
|
||||
String id(HttpServletRequest r){ return String.valueOf(r.getAttribute("requestId")); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
package ru.mtusi.messenger;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.io.InputStream;
|
||||
import java.security.DigestInputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.jdbc.core.ConnectionCallback;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
|
||||
import software.amazon.awssdk.services.s3.model.S3Object;
|
||||
|
||||
// Сверка PostgreSQL и S3 (трек 2). Оба списка обходятся отсортированными по ключу и сливаются за O(n)
|
||||
// с постоянной памятью: страница S3 по 1000 ключей и страница строк БД по 1000.
|
||||
//
|
||||
// Правила безопасности:
|
||||
// - ничего моложе grace period (по LastModified объекта / updated_at строки) не трогаем:
|
||||
// загрузка в процессе пишет строку до объекта и объект до ready;
|
||||
// - ready-строки не удаляются никогда, а при отсутствии объекта (подтверждённом HEAD) помечаются lost;
|
||||
// - строка, на которую ссылается сообщение, защищена FK message_attachments;
|
||||
// - объект без строки удаляется только после повторной проверки по ключу в БД;
|
||||
// - одновременно работает одна сверка (pg advisory lock), повторный запуск ничего не меняет.
|
||||
@Component
|
||||
class Reconciler {
|
||||
static final long LOCK_ID = 4_040_404L;
|
||||
static final int PAGE = 1000;
|
||||
static final Logger log = LoggerFactory.getLogger(Reconciler.class);
|
||||
|
||||
final JdbcTemplate db;
|
||||
final Storage storage;
|
||||
final boolean enabled;
|
||||
final long graceSeconds;
|
||||
|
||||
Reconciler(JdbcTemplate db, Storage storage, @Value("${reconcile.enabled:true}") boolean enabled, @Value("${reconcile.grace-seconds:3600}") long graceSeconds) {
|
||||
this.db = db;
|
||||
this.storage = storage;
|
||||
this.enabled = enabled;
|
||||
this.graceSeconds = graceSeconds;
|
||||
}
|
||||
|
||||
// Автоматическая компенсация в API-репликах: раз в interval, в apply-режиме, с grace по умолчанию 1 час.
|
||||
@Scheduled(initialDelayString = "${reconcile.initial-delay:PT1M}", fixedDelayString = "${reconcile.interval:PT15M}")
|
||||
void scheduled() {
|
||||
if (!enabled) return;
|
||||
try {
|
||||
Map<String, Object> report = run(true, Duration.ofSeconds(graceSeconds), false);
|
||||
if (!Map.of().equals(report.get("actions"))) log.info("reconcile: {}", report);
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("reconcile failed: {}", e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
// CLI: reconcile [--apply] [--grace-seconds=N] [--verify-checksums]; по умолчанию dry-run.
|
||||
int cli(String[] args) throws Exception {
|
||||
boolean apply = false, verify = false;
|
||||
long grace = graceSeconds;
|
||||
for (String a : args) {
|
||||
if (a.equals("--apply")) apply = true;
|
||||
else if (a.equals("--dry-run")) apply = false;
|
||||
else if (a.equals("--verify-checksums")) verify = true;
|
||||
else if (a.startsWith("--grace-seconds=")) grace = Long.parseLong(a.substring(16));
|
||||
else { System.err.println("unknown argument: " + a); return 2; }
|
||||
}
|
||||
Map<String, Object> report = run(apply, Duration.ofSeconds(grace), verify);
|
||||
System.out.println(new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(report));
|
||||
return report.containsKey("skipped") ? 3 : 0;
|
||||
}
|
||||
|
||||
Map<String, Object> run(boolean apply, Duration grace, boolean verify) {
|
||||
return db.execute((ConnectionCallback<Map<String, Object>>) c -> {
|
||||
try (PreparedStatement st = c.prepareStatement("select pg_try_advisory_lock(?)")) {
|
||||
st.setLong(1, LOCK_ID);
|
||||
try (ResultSet rs = st.executeQuery()) {
|
||||
rs.next();
|
||||
if (!rs.getBoolean(1)) return Map.of("skipped", "another reconcile is running");
|
||||
}
|
||||
}
|
||||
try {
|
||||
return new Pass(apply, grace, verify).scan();
|
||||
} finally {
|
||||
try (PreparedStatement st = c.prepareStatement("select pg_advisory_unlock(?)")) {
|
||||
st.setLong(1, LOCK_ID);
|
||||
st.execute();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
record Row(UUID id, String key, String state, long size, String sha256, Instant updated, boolean used) {}
|
||||
|
||||
// Один проход сверки со счётчиками для отчёта и оценки стоимости.
|
||||
final class Pass {
|
||||
final boolean apply, verify;
|
||||
final Duration grace;
|
||||
final Instant cutoff;
|
||||
final Map<String, Long> findings = new LinkedHashMap<>(), actions = new LinkedHashMap<>(), cost = new LinkedHashMap<>();
|
||||
final List<Map<String, Object>> details = new ArrayList<>();
|
||||
|
||||
Pass(boolean apply, Duration grace, boolean verify) {
|
||||
this.apply = apply;
|
||||
this.grace = grace;
|
||||
this.verify = verify;
|
||||
cutoff = Instant.now().minus(grace);
|
||||
}
|
||||
|
||||
Map<String, Object> scan() {
|
||||
long started = System.nanoTime();
|
||||
Iterator<S3Object> objects = objects();
|
||||
Iterator<Row> rows = rows();
|
||||
S3Object o = next(objects);
|
||||
Row r = next(rows);
|
||||
while (o != null || r != null) {
|
||||
int cmp = o == null ? 1 : r == null ? -1 : o.key().compareTo(r.key());
|
||||
if (cmp < 0) { objectWithoutRow(o); o = next(objects); }
|
||||
else if (cmp > 0) { rowWithoutObject(r); r = next(rows); }
|
||||
else { both(o, r); o = next(objects); r = next(rows); }
|
||||
}
|
||||
Map<String, Object> report = new LinkedHashMap<>();
|
||||
report.put("mode", apply ? "apply" : "dry-run");
|
||||
report.put("grace_seconds", grace.toSeconds());
|
||||
report.put("verify_checksums", verify);
|
||||
report.put("duration_ms", (System.nanoTime() - started) / 1_000_000);
|
||||
report.put("cost", cost);
|
||||
report.put("findings", findings);
|
||||
report.put("actions", actions);
|
||||
report.put("details", details.size() > 50 ? details.subList(0, 50) : details);
|
||||
return report;
|
||||
}
|
||||
|
||||
void objectWithoutRow(S3Object o) {
|
||||
if (o.lastModified().isAfter(cutoff)) { count(findings, "orphan_object_fresh_kept"); return; }
|
||||
count(findings, "orphan_object");
|
||||
detail("orphan_object", o.key(), null);
|
||||
if (!apply) return;
|
||||
// Повторная проверка: строка могла появиться после чтения страницы БД.
|
||||
count(cost, "db_queries");
|
||||
if (Boolean.TRUE.equals(db.queryForObject("select exists(select 1 from attachments where object_key=?)", Boolean.class, o.key()))) return;
|
||||
count(cost, "s3_delete_requests");
|
||||
storage.delete(o.key());
|
||||
count(actions, "objects_deleted");
|
||||
}
|
||||
|
||||
void rowWithoutObject(Row r) {
|
||||
switch (r.state()) {
|
||||
case "uploading" -> {
|
||||
if (r.updated().isAfter(cutoff)) { count(findings, "upload_in_progress_kept"); return; }
|
||||
count(findings, "stale_upload");
|
||||
detail("stale_upload", r.key(), r.id());
|
||||
if (apply && deleteStaleRow(r)) count(actions, "rows_deleted");
|
||||
}
|
||||
case "ready" -> {
|
||||
if (r.updated().isAfter(cutoff)) { count(findings, "fresh_row_kept"); return; }
|
||||
// Листинг не считаем доказательством: отсутствие подтверждает HEAD (404).
|
||||
count(cost, "s3_head_requests");
|
||||
if (storage.size(r.key()) != null) return;
|
||||
count(findings, r.used() ? "missing_object_used" : "missing_object");
|
||||
detail("missing_object", r.key(), r.id());
|
||||
if (apply && markLost(r)) count(actions, "marked_lost");
|
||||
}
|
||||
default -> count(findings, "lost_known");
|
||||
}
|
||||
}
|
||||
|
||||
void both(S3Object o, Row r) {
|
||||
switch (r.state()) {
|
||||
case "uploading" -> {
|
||||
if (r.updated().isAfter(cutoff)) { count(findings, "upload_in_progress_kept"); return; }
|
||||
// PUT прошёл, ready не записан: клиент получил ошибку и id не знает — объект и строку удаляем.
|
||||
count(findings, "stale_upload_with_object");
|
||||
detail("stale_upload_with_object", r.key(), r.id());
|
||||
if (!apply || !deleteStaleRow(r)) return;
|
||||
count(cost, "s3_delete_requests");
|
||||
storage.delete(r.key());
|
||||
count(actions, "rows_deleted");
|
||||
count(actions, "objects_deleted");
|
||||
}
|
||||
case "ready" -> {
|
||||
if (r.updated().isAfter(cutoff)) return;
|
||||
String problem = o.size() != r.size() ? "size_mismatch" : verify && !checksumMatches(r) ? "checksum_mismatch" : null;
|
||||
if (problem == null) return;
|
||||
count(findings, problem);
|
||||
detail(problem, r.key(), r.id());
|
||||
if (apply && markLost(r)) count(actions, "marked_lost");
|
||||
}
|
||||
default -> {
|
||||
// lost, но объект снова на месте: вернуть в ready можно только после сверки SHA-256,
|
||||
// иначе файл, помеченный за неверную контрольную сумму, «воскрес» бы по одному размеру.
|
||||
if (o.size() != r.size()) { count(findings, "lost_known"); return; }
|
||||
if (!verify) { count(findings, "lost_object_back_unverified"); return; }
|
||||
if (!checksumMatches(r)) { count(findings, "lost_known"); return; }
|
||||
count(findings, "lost_object_back");
|
||||
detail("lost_object_back", r.key(), r.id());
|
||||
if (!apply) return;
|
||||
count(cost, "db_queries");
|
||||
if (db.update("update attachments set state='ready', updated_at=now() where id=? and state='lost'", r.id()) == 1) count(actions, "restored");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
boolean deleteStaleRow(Row r) {
|
||||
count(cost, "db_queries");
|
||||
return db.update("delete from attachments a where id=? and state='uploading' and updated_at<? and not exists(select 1 from message_attachments x where x.attachment_id=a.id)",
|
||||
r.id(), Timestamp.from(cutoff)) == 1;
|
||||
}
|
||||
|
||||
boolean markLost(Row r) {
|
||||
count(cost, "db_queries");
|
||||
return db.update("update attachments set state='lost', updated_at=now() where id=? and state='ready'", r.id()) == 1;
|
||||
}
|
||||
|
||||
boolean checksumMatches(Row r) {
|
||||
count(cost, "s3_get_requests");
|
||||
MessageDigest sha = Attachments.sha256();
|
||||
try (InputStream in = new DigestInputStream(storage.get(r.key()), sha)) {
|
||||
cost.merge("bytes_read", in.transferTo(java.io.OutputStream.nullOutputStream()), Long::sum);
|
||||
} catch (java.io.IOException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
return java.util.HexFormat.of().formatHex(sha.digest()).equals(r.sha256());
|
||||
}
|
||||
|
||||
// Ленивый обход листинга S3 постранично.
|
||||
Iterator<S3Object> objects() {
|
||||
Iterator<ListObjectsV2Response> pages = storage.list().iterator();
|
||||
return new Iterator<>() {
|
||||
Iterator<S3Object> page = List.<S3Object>of().iterator();
|
||||
public boolean hasNext() {
|
||||
while (!page.hasNext() && pages.hasNext()) {
|
||||
count(cost, "s3_list_requests");
|
||||
page = pages.next().contents().iterator();
|
||||
}
|
||||
return page.hasNext();
|
||||
}
|
||||
public S3Object next() {
|
||||
S3Object o = page.next();
|
||||
count(cost, "s3_objects");
|
||||
return o;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Keyset-пагинация строк по object_key (COLLATE "C" — тот же порядок, что у S3).
|
||||
Iterator<Row> rows() {
|
||||
return new Iterator<>() {
|
||||
Iterator<Row> page = List.<Row>of().iterator();
|
||||
String after = "";
|
||||
boolean done;
|
||||
public boolean hasNext() {
|
||||
if (!page.hasNext() && !done) {
|
||||
count(cost, "db_queries");
|
||||
List<Row> rows = db.query("select id,object_key,state,size_bytes,sha256,updated_at,exists(select 1 from message_attachments x where x.attachment_id=a.id)"
|
||||
+ " from attachments a where object_key>? order by object_key limit ?", (rs, n) -> new Row(rs.getObject(1, UUID.class), rs.getString(2),
|
||||
rs.getString(3), rs.getLong(4), rs.getString(5), rs.getTimestamp(6).toInstant(), rs.getBoolean(7)), after, PAGE);
|
||||
done = rows.size() < PAGE;
|
||||
if (!rows.isEmpty()) after = rows.get(rows.size() - 1).key();
|
||||
page = rows.iterator();
|
||||
}
|
||||
return page.hasNext();
|
||||
}
|
||||
public Row next() {
|
||||
count(cost, "db_rows");
|
||||
return page.next();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
<T> T next(Iterator<T> it) { return it.hasNext() ? it.next() : null; }
|
||||
|
||||
void count(Map<String, Long> map, String name) { map.merge(name, 1L, Long::sum); }
|
||||
|
||||
void detail(String kind, String key, UUID id) {
|
||||
Map<String, Object> d = new LinkedHashMap<>();
|
||||
d.put("kind", kind);
|
||||
d.put("key", key);
|
||||
if (id != null) d.put("attachment_id", id);
|
||||
details.add(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
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 {
|
||||
// Оригиналы лежат под общим префиксом: его обходит сверка.
|
||||
static final String ORIGINALS = "originals/";
|
||||
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));
|
||||
}
|
||||
|
||||
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 s3.listObjectsV2Paginator(b -> b.bucket(bucket).prefix(ORIGINALS));
|
||||
}
|
||||
|
||||
static boolean isOriginal(S3Object o) {
|
||||
return o.key().startsWith(ORIGINALS);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user