Complete lab7 grade 4 implementation
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
@@ -0,0 +1,217 @@
|
||||
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.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 участникам чата.
|
||||
// Приём (lab5): оригинал → staging в S3, затем вложение + job + outbox одной транзакцией → 202 queued;
|
||||
// варианты создаёт worker асинхронно.
|
||||
@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<Variant> variants, String error_code, Instant created_at, Instant updated_at) {}
|
||||
record Variant(String name, String content_type, long size_bytes, int width, int height, String sha256) {}
|
||||
|
||||
final MessengerApplication.Api api;
|
||||
final JdbcTemplate db;
|
||||
final Storage storage;
|
||||
final Jobs jobs;
|
||||
// Не больше N загрузок на реплику одновременно: диск под временные файлы и CPU проверки ограничены.
|
||||
final Semaphore uploads = new Semaphore(Integer.parseInt(System.getenv().getOrDefault("MAX_CONCURRENT_UPLOADS", "8")));
|
||||
|
||||
Attachments(MessengerApplication.Api api, JdbcTemplate db, Storage storage, Jobs jobs) {
|
||||
this.api = api;
|
||||
this.db = db;
|
||||
this.storage = storage;
|
||||
this.jobs = jobs;
|
||||
}
|
||||
|
||||
@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. Полный проверенный оригинал — в устойчивый staging (приватный S3-префикс), до записи в БД.
|
||||
UUID attachmentId = UUID.randomUUID();
|
||||
String staging = Storage.STAGING + attachmentId;
|
||||
String hash = HexFormat.of().formatHex(sha.digest());
|
||||
try {
|
||||
storage.put(staging, tmp, declared);
|
||||
} catch (SdkException e) {
|
||||
log.warn("S3 staging put failed for attachment {}: {}", attachmentId, e.toString());
|
||||
throw unavailable("object storage is unavailable");
|
||||
}
|
||||
// 4. Метаданные, задание и outbox — одна транзакция; 202 только после её COMMIT.
|
||||
// Не записалось — убираем staging (иначе его удалит очистка staging по retention).
|
||||
Instant created = now();
|
||||
try {
|
||||
jobs.accept(attachmentId, id, user, filename, declared, size, hash, image.width(), image.height(), created);
|
||||
} catch (RuntimeException e) {
|
||||
try { storage.delete(staging); } catch (SdkException ignored) {}
|
||||
throw e;
|
||||
}
|
||||
return ResponseEntity.status(202).body(new Attachment(attachmentId, id, user, filename, declared, size, hash, "queued", List.of(), null, created, created));
|
||||
} 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));
|
||||
String name = variant == null ? "original" : variant;
|
||||
if (!name.equals("original") && !VARIANTS.contains(name)) api.bad();
|
||||
// queued/processing/failed — 409: оригинал ещё не опубликован, варианты не готовы.
|
||||
if (!v.attachment().status().equals("ready")) throw new ApiException(HttpStatus.CONFLICT, "conflict", "attachment is not ready");
|
||||
Attachment a = v.attachment();
|
||||
String key = v.key(), type = a.content_type();
|
||||
long size = a.size_bytes();
|
||||
if (!name.equals("original")) {
|
||||
Object[] x = db.query("select object_key,content_type,size_bytes from attachment_variants where attachment_id=? and pipeline_version=? and name=?",
|
||||
rs -> rs.next() ? new Object[]{rs.getString(1), rs.getString(2), rs.getLong(3)} : null, id, v.version(), name);
|
||||
if (x == null) throw api.notFound();
|
||||
key = (String) x[0];
|
||||
type = (String) x[1];
|
||||
size = (long) x[2];
|
||||
}
|
||||
ResponseInputStream<GetObjectResponse> in;
|
||||
try {
|
||||
in = storage.get(key);
|
||||
} catch (NoSuchKeyException e) {
|
||||
// Метаданные есть, объекта нет: рассинхронизация, её покажет и исправит сверка.
|
||||
log.error("object {} is missing for ready attachment {}", 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) {
|
||||
s.setContentType(type);
|
||||
s.setContentLengthLong(size);
|
||||
s.setHeader("Cache-Control", "private, no-store");
|
||||
s.setHeader("X-Content-Type-Options", "nosniff");
|
||||
in.transferTo(s.getOutputStream());
|
||||
}
|
||||
}
|
||||
|
||||
record Visible(Attachment attachment, String key, Integer version) {}
|
||||
|
||||
// Вложения чатов, где пользователь участник; uploading/lost и чужие — 404 без раскрытия существования.
|
||||
// Варианты — только текущей (последней зафиксированной) версии pipeline.
|
||||
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,state,error_code,pipeline_version from attachments a"
|
||||
+ " where id=? and state in ('queued','processing','ready','failed') and exists(select 1 from chat_members m where m.chat_id=a.chat_id and m.user_id=?)", rs -> {
|
||||
if (!rs.next()) return null;
|
||||
String state = rs.getString(11);
|
||||
Integer version = rs.getObject(13, Integer.class);
|
||||
List<Variant> variants = state.equals("ready") && version != null ? db.query("select name,content_type,size_bytes,width,height,sha256 from attachment_variants"
|
||||
+ " where attachment_id=? and pipeline_version=? order by array_position(array['thumbnail','crop','optimized']::text[],name::text)",
|
||||
(x, n) -> new Variant(x.getString(1), x.getString(2), x.getLong(3), x.getInt(4), x.getInt(5), x.getString(6)), id, version) : List.of();
|
||||
return 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), state, variants, state.equals("failed") ? rs.getString(12) : null, rs.getTimestamp(8).toInstant(), rs.getTimestamp(9).toInstant()),
|
||||
rs.getString(10), version);
|
||||
}, 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,82 @@
|
||||
package ru.mtusi.messenger;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.http.HttpClient;
|
||||
import java.net.http.HttpRequest;
|
||||
import java.net.http.HttpResponse;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.env.EnvironmentPostProcessor;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.env.ConfigurableEnvironment;
|
||||
import org.springframework.core.env.MapPropertySource;
|
||||
|
||||
/**
|
||||
* Loads only the service's KV path after AppRole login. Docker secrets remain the
|
||||
* documented bootstrap fallback until the operator enables OpenBao.
|
||||
*/
|
||||
public final class BaoEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered {
|
||||
private final ObjectMapper json = new ObjectMapper();
|
||||
|
||||
@Override
|
||||
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
|
||||
if (!"true".equalsIgnoreCase(System.getenv().getOrDefault("BAO_ENABLED", "false"))) return;
|
||||
try {
|
||||
String role = System.getenv().getOrDefault("BAO_ROLE", "api");
|
||||
String roleId = readRequired(System.getenv("BAO_ROLE_ID_FILE"));
|
||||
String secretId = readRequired(System.getenv("BAO_SECRET_ID_FILE"));
|
||||
String address = System.getenv().getOrDefault("BAO_ADDR", "https://openbao:8200");
|
||||
HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).build();
|
||||
String token = post(client, address + "/v1/auth/approle/login",
|
||||
"{\"role_id\":\"" + escape(roleId) + "\",\"secret_id\":\"" + escape(secretId) + "\"}", null)
|
||||
.path("auth").path("client_token").textValue();
|
||||
if (token == null || token.isBlank()) throw new IllegalStateException("OpenBao AppRole login returned no token");
|
||||
JsonNode data = get(client, address + "/v1/kv/data/messenger/" + role, token).path("data").path("data");
|
||||
if (!data.isObject()) throw new IllegalStateException("OpenBao KV response is missing data");
|
||||
Map<String, Object> values = new HashMap<>();
|
||||
data.fields().forEachRemaining(e -> values.put(e.getKey(), e.getValue().asText()));
|
||||
environment.getPropertySources().addFirst(new MapPropertySource("openbao", values));
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("OpenBao AppRole secret loading failed closed", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String readRequired(String file) throws IOException {
|
||||
if (file == null || file.isBlank()) throw new IllegalStateException("OpenBao credential file is not configured");
|
||||
return Files.readString(Path.of(file)).trim();
|
||||
}
|
||||
|
||||
private JsonNode post(HttpClient client, String url, String body, String token) throws Exception {
|
||||
return send(client, "POST", url, body, token);
|
||||
}
|
||||
|
||||
private JsonNode get(HttpClient client, String url, String token) throws Exception {
|
||||
return send(client, "GET", url, null, token);
|
||||
}
|
||||
|
||||
private JsonNode send(HttpClient client, String method, String url, String body, String token) throws Exception {
|
||||
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(url)).timeout(Duration.ofSeconds(5));
|
||||
if (token != null) request.header("X-Vault-Token", token);
|
||||
if (body != null) request.header("Content-Type", "application/json");
|
||||
request.method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(body));
|
||||
HttpResponse<String> response = client.send(request.build(), HttpResponse.BodyHandlers.ofString());
|
||||
if (response.statusCode() / 100 != 2) throw new IllegalStateException("OpenBao request failed: HTTP " + response.statusCode());
|
||||
return json.readTree(response.body());
|
||||
}
|
||||
|
||||
private static String escape(String value) {
|
||||
return value.replace("\\", "\\\\").replace("\"", "\\\"");
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOrder() {
|
||||
return Ordered.HIGHEST_PRECEDENCE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package ru.mtusi.messenger;
|
||||
|
||||
import com.rabbitmq.client.AMQP;
|
||||
import com.rabbitmq.client.Channel;
|
||||
import com.rabbitmq.client.Connection;
|
||||
import com.rabbitmq.client.ConnectionFactory;
|
||||
import com.rabbitmq.client.impl.ExternalMechanism;
|
||||
import io.opentelemetry.context.Context;
|
||||
import io.opentelemetry.context.Scope;
|
||||
import java.io.IOException;
|
||||
import java.io.FileInputStream;
|
||||
import java.security.KeyStore;
|
||||
import javax.net.ssl.KeyManagerFactory;
|
||||
import javax.net.ssl.TrustManagerFactory;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import javax.net.ssl.SSLParameters;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
// RabbitMQ: exchange attachments → quorum-очередь attachments.process (DLX → attachments.dlq).
|
||||
// Топологию и пользователей создаёт definitions-файл брокера; клиент ничего не объявляет.
|
||||
@Component
|
||||
class Broker {
|
||||
static final String EXCHANGE = "attachments", ROUTING_KEY = "process", QUEUE = "attachments.process";
|
||||
final ConnectionFactory factory = new ConnectionFactory();
|
||||
Connection connection;
|
||||
Channel channel;
|
||||
volatile boolean returned;
|
||||
|
||||
Broker(@Value("${broker.url:amqp://localhost}") String url) throws Exception {
|
||||
String normalized = url.trim().replace("%%2F", "%2F")
|
||||
.replaceFirst("^amqp://", "amqps://").replace(":5672/", ":5671/");
|
||||
factory.setUri(normalized);
|
||||
if (normalized.startsWith("amqps://")) {
|
||||
// EXTERNAL derives the username from the certificate CN; discard any
|
||||
// legacy userinfo still present in an already-bootstrapped KV value.
|
||||
factory.setUri(normalized.replaceFirst("^(amqps://)[^/@]*@", "$1"));
|
||||
factory.setSaslConfig(mechanisms -> new ExternalMechanism());
|
||||
configureMtls();
|
||||
}
|
||||
// Переподключение делаем сами (следующий тик relay/supervisor), без скрытых повторов публикаций.
|
||||
factory.setAutomaticRecoveryEnabled(false);
|
||||
factory.setConnectionTimeout(3000);
|
||||
factory.setRequestedHeartbeat(10);
|
||||
}
|
||||
|
||||
// AMQPS is not "TLS without verification": use per-service PKCS#12 identity and CA bundle.
|
||||
void configureMtls() throws Exception {
|
||||
String p12 = System.getenv().getOrDefault("BROKER_TLS_P12", "/run/secrets/broker-client.p12");
|
||||
String password = System.getenv().getOrDefault("BROKER_TLS_P12_PASSWORD", "changeit");
|
||||
String trust = System.getenv().getOrDefault("BROKER_TLS_TRUSTSTORE", "/run/secrets/broker-ca.p12");
|
||||
KeyStore keys=KeyStore.getInstance("PKCS12");
|
||||
try (FileInputStream in=new FileInputStream(p12)) { keys.load(in,password.toCharArray()); }
|
||||
KeyStore cas=KeyStore.getInstance("PKCS12");
|
||||
try (FileInputStream in=new FileInputStream(trust)) { cas.load(in,password.toCharArray()); }
|
||||
KeyManagerFactory km=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); km.init(keys,password.toCharArray());
|
||||
TrustManagerFactory tm=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tm.init(cas);
|
||||
SSLContext ctx=SSLContext.getInstance("TLS"); ctx.init(km.getKeyManagers(),tm.getTrustManagers(),null);
|
||||
factory.useSslProtocol(ctx);
|
||||
factory.enableHostnameVerification();
|
||||
}
|
||||
|
||||
Connection connect(String name, ExecutorService executor) throws Exception {
|
||||
return factory.newConnection(executor, name);
|
||||
}
|
||||
|
||||
// trace — контекст причины попытки (Jobs.context): в нём агент OTel создаёт span publish и пишет traceparent в headers.
|
||||
record Message(String id, byte[] body, Context trace) {}
|
||||
|
||||
// Пачка с publisher confirms: возврат без исключения = брокер сохранил все сообщения в очереди.
|
||||
synchronized void publish(List<Message> messages) throws Exception {
|
||||
try {
|
||||
if (channel == null || !channel.isOpen()) {
|
||||
connection = factory.newConnection("publisher");
|
||||
channel = connection.createChannel();
|
||||
channel.confirmSelect();
|
||||
// mandatory: сообщение без маршрута брокер подтвердил бы, но не сохранил — считаем ошибкой.
|
||||
channel.addReturnListener(r -> returned = true);
|
||||
}
|
||||
returned = false;
|
||||
for (Message m : messages) {
|
||||
AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().contentType("application/json").deliveryMode(2)
|
||||
.messageId(m.id()).type(Jobs.TYPE).timestamp(new Date()).build();
|
||||
try (Scope ignored = m.trace().makeCurrent()) {
|
||||
channel.basicPublish(EXCHANGE, ROUTING_KEY, true, props, m.body());
|
||||
}
|
||||
}
|
||||
channel.waitForConfirmsOrDie(5000);
|
||||
if (returned) throw new IOException("message was not routed to a queue");
|
||||
} catch (Exception e) {
|
||||
close();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
synchronized void close() {
|
||||
if (connection != null) connection.abort(1000);
|
||||
connection = null;
|
||||
channel = null;
|
||||
}
|
||||
}
|
||||
@@ -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,215 @@
|
||||
package ru.mtusi.messenger;
|
||||
|
||||
import java.awt.Color;
|
||||
import java.awt.Graphics2D;
|
||||
import java.awt.RenderingHints;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.DataInputStream;
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import javax.imageio.IIOImage;
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.imageio.ImageReadParam;
|
||||
import javax.imageio.ImageReader;
|
||||
import javax.imageio.ImageWriteParam;
|
||||
import javax.imageio.ImageWriter;
|
||||
import javax.imageio.stream.ImageInputStream;
|
||||
import javax.imageio.stream.ImageOutputStream;
|
||||
|
||||
// Варианты изображения: thumbnail (JPEG, вписан в 256×256), crop (JPEG 128×128 из центрального квадрата),
|
||||
// optimized (WebP, вписан в 1280×1280). EXIF orientation применяется, alpha компонуется на белый,
|
||||
// метаданные исходника не переносятся. Версия pipeline задаёт параметры кодирования.
|
||||
final class ImagePipeline {
|
||||
record Params(float jpegQuality, int webpQuality) {}
|
||||
static final Map<Integer, Params> VERSIONS = Map.of(1, new Params(0.85f, 80), 2, new Params(0.92f, 90));
|
||||
// Декодирование с прореживанием до ≤ 12 Мпикс: растр одной задачи ≤ ~48 MiB при любом исходнике ≤ 40 Мпикс.
|
||||
static final long DECODE_PIXELS = 12_000_000L, MAX_PIXELS = 40_000_000L;
|
||||
|
||||
record Output(String name, String contentType, String file, int width, int height, Path path) {}
|
||||
|
||||
static final class Invalid extends Exception {
|
||||
Invalid(String message) { super(message); }
|
||||
}
|
||||
|
||||
static List<Output> render(Path source, String contentType, int version, Path dir, Jobs.Claim c) throws IOException, Invalid {
|
||||
Params p = VERSIONS.get(version);
|
||||
if (p == null) throw new Jobs.Permanent("unsupported_pipeline", "unknown pipeline_version " + version);
|
||||
int orientation = contentType.equals("image/jpeg") ? orientation(source) : 1;
|
||||
ImageReader reader = ImageIO.getImageReadersByMIMEType(contentType).next();
|
||||
BufferedImage img;
|
||||
int w, h;
|
||||
try (ImageInputStream in = ImageIO.createImageInputStream(source.toFile())) {
|
||||
reader.setInput(in, true, true);
|
||||
w = reader.getWidth(0);
|
||||
h = reader.getHeight(0);
|
||||
// Повторная проверка лимита пикселей по заголовку до декодирования.
|
||||
if ((long) w * h > MAX_PIXELS) throw new Invalid("too many pixels");
|
||||
int s = 1;
|
||||
while ((long) ((w + s - 1) / s) * ((h + s - 1) / s) > DECODE_PIXELS) s++;
|
||||
ImageReadParam param = reader.getDefaultReadParam();
|
||||
param.setSourceSubsampling(s, s, 0, 0);
|
||||
c.reader = reader;
|
||||
img = reader.read(0, param);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
c.check();
|
||||
throw new Invalid(e.toString());
|
||||
} finally {
|
||||
c.reader = null;
|
||||
reader.dispose();
|
||||
}
|
||||
// abort() по таймауту или потере аренды прерывает read: частичный растр не используем.
|
||||
c.check();
|
||||
int dw = img.getWidth(), dh = img.getHeight();
|
||||
boolean swap = orientation >= 5;
|
||||
int ow = swap ? h : w, oh = swap ? w : h;
|
||||
List<Output> out = new ArrayList<>();
|
||||
int[] t = fit(ow, oh, 256);
|
||||
out.add(jpeg("thumbnail", orient(scale(img, 0, 0, dw, dh, swap ? t[1] : t[0], swap ? t[0] : t[1]), orientation), p.jpegQuality(), dir));
|
||||
c.check();
|
||||
int side = Math.min(dw, dh);
|
||||
out.add(jpeg("crop", orient(scale(img, (dw - side) / 2, (dh - side) / 2, side, side, 128, 128), orientation), p.jpegQuality(), dir));
|
||||
c.check();
|
||||
int[] o = fit(ow, oh, 1280);
|
||||
out.add(webp(orient(scale(img, 0, 0, dw, dh, swap ? o[1] : o[0], swap ? o[0] : o[1]), orientation), p.webpQuality(), dir, c));
|
||||
return out;
|
||||
}
|
||||
|
||||
// Вписать в box×box с сохранением пропорций, без увеличения; округление вниз, минимум 1 px.
|
||||
static int[] fit(int w, int h, int box) {
|
||||
if (w <= box && h <= box) return new int[]{w, h};
|
||||
return w >= h ? new int[]{box, (int) Math.max(1, (long) h * box / w)} : new int[]{(int) Math.max(1, (long) w * box / h), box};
|
||||
}
|
||||
|
||||
// Область исходника → tw×th на белом фоне; сильное уменьшение — последовательными halving-шагами.
|
||||
static BufferedImage scale(BufferedImage src, int sx, int sy, int sw, int sh, int tw, int th) {
|
||||
BufferedImage cur = src;
|
||||
while (sw / 2 >= tw && sh / 2 >= th) {
|
||||
BufferedImage next = canvas(sw / 2, sh / 2);
|
||||
draw(next, cur, sx, sy, sw, sh, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
|
||||
cur = next;
|
||||
sx = 0;
|
||||
sy = 0;
|
||||
sw = next.getWidth();
|
||||
sh = next.getHeight();
|
||||
}
|
||||
BufferedImage out = canvas(tw, th);
|
||||
draw(out, cur, sx, sy, sw, sh, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
|
||||
return out;
|
||||
}
|
||||
|
||||
static BufferedImage canvas(int w, int h) {
|
||||
BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
|
||||
Graphics2D g = img.createGraphics();
|
||||
g.setColor(Color.WHITE);
|
||||
g.fillRect(0, 0, w, h);
|
||||
g.dispose();
|
||||
return img;
|
||||
}
|
||||
|
||||
static void draw(BufferedImage dst, BufferedImage src, int sx, int sy, int sw, int sh, Object interpolation) {
|
||||
Graphics2D g = dst.createGraphics();
|
||||
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolation);
|
||||
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
|
||||
g.drawImage(src, 0, 0, dst.getWidth(), dst.getHeight(), sx, sy, sx + sw, sy + sh, null);
|
||||
g.dispose();
|
||||
}
|
||||
|
||||
// EXIF Orientation 1–8 → поворот/отражение готового (маленького) растра.
|
||||
static BufferedImage orient(BufferedImage s, int o) {
|
||||
if (o <= 1 || o > 8) return s;
|
||||
int w = s.getWidth(), h = s.getHeight();
|
||||
BufferedImage d = new BufferedImage(o >= 5 ? h : w, o >= 5 ? w : h, BufferedImage.TYPE_INT_RGB);
|
||||
for (int y = 0; y < h; y++)
|
||||
for (int x = 0; x < w; x++) {
|
||||
int dx, dy;
|
||||
switch (o) {
|
||||
case 2 -> { dx = w - 1 - x; dy = y; }
|
||||
case 3 -> { dx = w - 1 - x; dy = h - 1 - y; }
|
||||
case 4 -> { dx = x; dy = h - 1 - y; }
|
||||
case 5 -> { dx = y; dy = x; }
|
||||
case 6 -> { dx = h - 1 - y; dy = x; }
|
||||
case 7 -> { dx = h - 1 - y; dy = w - 1 - x; }
|
||||
default -> { dx = y; dy = w - 1 - x; }
|
||||
}
|
||||
d.setRGB(dx, dy, s.getRGB(x, y));
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
// Тег 0x0112 из APP1 Exif; любая нестандартная структура — ориентация по умолчанию.
|
||||
static int orientation(Path file) {
|
||||
try (DataInputStream in = new DataInputStream(new BufferedInputStream(Files.newInputStream(file)))) {
|
||||
if (in.readUnsignedShort() != 0xFFD8) return 1;
|
||||
while (true) {
|
||||
int marker = in.readUnsignedShort();
|
||||
if ((marker & 0xFF00) != 0xFF00 || marker == 0xFFDA || marker == 0xFFD9) return 1;
|
||||
int len = in.readUnsignedShort();
|
||||
if (len < 2) return 1;
|
||||
byte[] seg = new byte[len - 2];
|
||||
in.readFully(seg);
|
||||
if (marker == 0xFFE1 && seg.length > 14 && new String(seg, 0, 6, StandardCharsets.ISO_8859_1).equals("Exif\0\0")) {
|
||||
ByteBuffer b = ByteBuffer.wrap(seg).order(seg[6] == 'I' ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
|
||||
int ifd = 6 + b.getInt(10), n = b.getShort(ifd) & 0xFFFF;
|
||||
for (int i = 0; i < n; i++) {
|
||||
int e = ifd + 2 + i * 12;
|
||||
if ((b.getShort(e) & 0xFFFF) == 0x0112) {
|
||||
int v = b.getShort(e + 8) & 0xFFFF;
|
||||
return v >= 1 && v <= 8 ? v : 1;
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
} catch (IOException | RuntimeException e) {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
static Output jpeg(String name, BufferedImage img, float quality, Path dir) throws IOException {
|
||||
Path file = dir.resolve(name + ".jpg");
|
||||
ImageWriter writer = ImageIO.getImageWritersByFormatName("jpeg").next();
|
||||
ImageWriteParam param = writer.getDefaultWriteParam();
|
||||
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
|
||||
param.setCompressionQuality(quality);
|
||||
try (ImageOutputStream out = ImageIO.createImageOutputStream(file.toFile())) {
|
||||
writer.setOutput(out);
|
||||
writer.write(null, new IIOImage(img, null, null), param);
|
||||
} finally {
|
||||
writer.dispose();
|
||||
}
|
||||
return new Output(name, "image/jpeg", name + ".jpg", img.getWidth(), img.getHeight(), file);
|
||||
}
|
||||
|
||||
// cwebp (libwebp): -q качество, -metadata none — без EXIF/XMP/ICC. Отдельный процесс с таймаутом.
|
||||
static Output webp(BufferedImage img, int quality, Path dir, Jobs.Claim c) throws IOException {
|
||||
Path png = dir.resolve("optimized.png"), file = dir.resolve("optimized.webp");
|
||||
ImageIO.write(img, "png", png.toFile());
|
||||
Process proc = new ProcessBuilder("cwebp", "-quiet", "-q", String.valueOf(quality), "-metadata", "none", png.toString(), "-o", file.toString())
|
||||
.redirectErrorStream(true).redirectOutput(ProcessBuilder.Redirect.DISCARD).start();
|
||||
c.process = proc;
|
||||
try {
|
||||
if (!proc.waitFor(30, TimeUnit.SECONDS)) {
|
||||
proc.destroyForcibly();
|
||||
throw new IOException("cwebp timeout");
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
proc.destroyForcibly();
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IOException("interrupted");
|
||||
} finally {
|
||||
c.process = null;
|
||||
}
|
||||
c.check();
|
||||
if (proc.exitValue() != 0) throw new IOException("cwebp exit code " + proc.exitValue());
|
||||
return new Output("optimized", "image/webp", "optimized.webp", img.getWidth(), img.getHeight(), file);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,498 @@
|
||||
package ru.mtusi.messenger;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import io.opentelemetry.api.GlobalOpenTelemetry;
|
||||
import io.opentelemetry.api.metrics.DoubleHistogram;
|
||||
import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator;
|
||||
import io.opentelemetry.context.Context;
|
||||
import io.opentelemetry.context.propagation.TextMapGetter;
|
||||
import java.io.IOException;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import javax.imageio.ImageReader;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import software.amazon.awssdk.services.s3.model.ListObjectsV2Response;
|
||||
import software.amazon.awssdk.services.s3.model.S3Object;
|
||||
|
||||
// Задания обработки вложений. Источник истины — таблица jobs в PostgreSQL; сообщение брокера —
|
||||
// только сигнал «попытка attempt задания job_id готова к запуску» (contracts/jobs.schema.json).
|
||||
//
|
||||
// - вложение, job и запись outbox пишутся одной транзакцией с приёмом файла, публикует relay;
|
||||
// - attempt — fencing token: захват, продление аренды и фиксация результата сверяют его в БД;
|
||||
// - эффект идемпотентен по (attachment_id, pipeline_version, variant): детерминированные ключи S3 и PK.
|
||||
@Component
|
||||
class Jobs {
|
||||
static final String TYPE = "attachment.process.v1";
|
||||
static final int MAX_ATTEMPTS = env("JOB_MAX_ATTEMPTS", 5);
|
||||
static final int TIMEOUT_SECONDS = env("JOB_TIMEOUT_SECONDS", 60);
|
||||
static final int LEASE_SECONDS = env("JOB_LEASE_SECONDS", 15);
|
||||
static final int PIPELINE_VERSION = env("PIPELINE_VERSION", 1);
|
||||
static final long BACKOFF_BASE_MS = env("JOB_BACKOFF_BASE_MS", 1000), BACKOFF_MAX_MS = env("JOB_BACKOFF_MAX_MS", 30000);
|
||||
static final long STAGING_RETENTION_SECONDS = env("STAGING_RETENTION_SECONDS", 86400);
|
||||
// Внедрение сбоев только при FAULT_INJECTION=1; точку выбирает префикс имени файла fault-<point>.
|
||||
static final boolean FAULTS = "1".equals(System.getenv("FAULT_INJECTION"));
|
||||
static final String ACTOR = System.getenv().getOrDefault("HOSTNAME", "local");
|
||||
static final ObjectMapper JSON = new ObjectMapper();
|
||||
static final Logger log = LoggerFactory.getLogger(Jobs.class);
|
||||
// От устойчивого приёма (COMMIT при 202) до публикации ready.
|
||||
// Границы покрывают норму (1–3 с), порог SLO 10 с и долгий backlog после остановки worker.
|
||||
static final DoubleHistogram TIME_TO_READY = GlobalOpenTelemetry.getMeter("ru.mtusi.messenger.worker").histogramBuilder("messenger.attachment.time_to_ready")
|
||||
.setUnit("s").setDescription("От durable acceptance до публикации ready")
|
||||
.setExplicitBucketBoundariesAdvice(java.util.List.of(0.5, 1.0, 2.0, 3.0, 5.0, 7.5, 10.0, 15.0, 20.0, 30.0, 60.0, 120.0, 300.0)).build();
|
||||
|
||||
final JdbcTemplate db;
|
||||
final TransactionTemplate tx, separate;
|
||||
final Broker broker;
|
||||
final boolean relayEnabled;
|
||||
long relayPausedUntil, lastWarning;
|
||||
|
||||
Jobs(JdbcTemplate db, PlatformTransactionManager tm, Broker broker, @Value("${outbox.enabled:true}") boolean relayEnabled) {
|
||||
this.db = db;
|
||||
this.broker = broker;
|
||||
this.relayEnabled = relayEnabled;
|
||||
tx = new TransactionTemplate(tm);
|
||||
separate = new TransactionTemplate(tm);
|
||||
separate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
// Очередь из БД (источник истины, а не счётчик брокера). Отдают все процессы с агентом — API и worker,
|
||||
// поэтому возраст задач виден и при остановленном worker; в запросах берём max().
|
||||
var meter = GlobalOpenTelemetry.getMeter("ru.mtusi.messenger.worker");
|
||||
var queue = io.opentelemetry.api.common.Attributes.of(io.opentelemetry.api.common.AttributeKey.stringKey("queue"), Broker.QUEUE);
|
||||
meter.gaugeBuilder("messenger.queue.depth").ofLongs().setUnit("{job}").setDescription("Задания в состоянии queued")
|
||||
.buildWithCallback(m -> m.record((long) queued()[0], queue));
|
||||
meter.gaugeBuilder("messenger.queue.oldest_age").setUnit("s").setDescription("Возраст самого старого queued-задания")
|
||||
.buildWithCallback(m -> m.record(queued()[1], queue));
|
||||
}
|
||||
|
||||
static int env(String name, int fallback) {
|
||||
return Integer.parseInt(System.getenv().getOrDefault(name, String.valueOf(fallback)));
|
||||
}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
record Msg(Integer schema_version, UUID job_id, String type, UUID attachment_id, Integer pipeline_version, Integer attempt,
|
||||
String created_at, String traceparent, String tracestate) {}
|
||||
|
||||
record Variant(String name, String contentType, long size, int width, int height, String sha256, String key) {}
|
||||
|
||||
record Source(String contentType, long size, String sha256, String key) {}
|
||||
|
||||
// Приём: метаданные, задание и outbox — одна транзакция. После COMMIT работа не теряется
|
||||
// ни при падении API, ни при недоступном брокере: relay опубликует позже.
|
||||
void accept(UUID id, UUID chat, UUID owner, String filename, String type, long size, String sha256, int width, int height, Instant at) {
|
||||
Timestamp ts = Timestamp.from(at);
|
||||
tx.executeWithoutResult(s -> {
|
||||
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(?,?,?,?,?,?,?,?,?,'queued',?,?,?)", id, chat, owner, filename, type, size, sha256, width, height, Storage.ORIGINALS + id, ts, ts);
|
||||
UUID job = UUID.randomUUID();
|
||||
db.update("insert into jobs(job_id,attachment_id,pipeline_version,state,attempt,attempts_limit,created_at,updated_at) values(?,?,?,'queued',1,?,?,?)",
|
||||
job, id, PIPELINE_VERSION, MAX_ATTEMPTS, ts, ts);
|
||||
enqueue(job, 1, 0);
|
||||
audit(job, 1, "accepted", null);
|
||||
});
|
||||
}
|
||||
|
||||
// Outbox relay работает в API-репликах и в worker; FOR UPDATE SKIP LOCKED делит записи между ними.
|
||||
// Падение после publish до DELETE даёт повторную публикацию — её гасит идемпотентный consumer.
|
||||
// ponytail: опрос раз в секунду (+≤1 с к времени до ready); LISTEN/NOTIFY — если задержка станет важна.
|
||||
@Scheduled(fixedDelayString = "${outbox.poll:PT1S}")
|
||||
void relay() {
|
||||
if (!relayEnabled || System.currentTimeMillis() < relayPausedUntil) return;
|
||||
try {
|
||||
while (Boolean.TRUE.equals(tx.execute(s -> relayBatch()))) {
|
||||
// полная пачка: сразу следующая
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
relayPausedUntil = System.currentTimeMillis() + 2000;
|
||||
if (System.currentTimeMillis() - lastWarning > 30000) {
|
||||
lastWarning = System.currentTimeMillis();
|
||||
log.warn("outbox relay paused: {}", e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
record Pending(long id, UUID job, int attempt, UUID attachment, int version, Instant created, String filename, String traceparent, String tracestate) {}
|
||||
|
||||
boolean relayBatch() {
|
||||
List<Pending> rows = db.query("select o.id,o.job_id,o.attempt,j.attachment_id,j.pipeline_version,j.created_at,a.filename,o.traceparent,o.tracestate from outbox o"
|
||||
+ " join jobs j on j.job_id=o.job_id join attachments a on a.id=j.attachment_id where o.available_at<=now() order by o.id limit 100 for update of o skip locked",
|
||||
(rs, n) -> new Pending(rs.getLong(1), rs.getObject(2, UUID.class), rs.getInt(3), rs.getObject(4, UUID.class), rs.getInt(5), rs.getTimestamp(6).toInstant(), rs.getString(7),
|
||||
rs.getString(8), rs.getString(9)));
|
||||
if (rows.isEmpty()) return false;
|
||||
List<Broker.Message> messages = new ArrayList<>();
|
||||
for (Pending r : rows) {
|
||||
crash("crash-before-publish", r.attachment(), r.filename());
|
||||
messages.add(new Broker.Message(r.job() + "/" + r.attempt(), message(r), context(r.traceparent(), r.tracestate())));
|
||||
}
|
||||
try {
|
||||
broker.publish(messages);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("publish failed: " + e, e);
|
||||
}
|
||||
for (Pending r : rows) crash("crash-after-publish", r.attachment(), r.filename());
|
||||
db.update("delete from outbox where id=any(?)", (Object) rows.stream().map(Pending::id).toArray(Long[]::new));
|
||||
return rows.size() == 100;
|
||||
}
|
||||
|
||||
static byte[] message(Pending r) {
|
||||
try {
|
||||
return JSON.writeValueAsBytes(new Msg(1, r.job(), TYPE, r.attachment(), r.version(), r.attempt(), r.created().toString(), r.traceparent(), r.tracestate()));
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException(e);
|
||||
}
|
||||
}
|
||||
|
||||
// Запись outbox с W3C trace context текущего span: upload (HTTP server span API) или неудачная попытка
|
||||
// (consumer span worker). Нет активного span (lease sweep, jobctl без агента) — NULL, публикация начнёт новый trace.
|
||||
void enqueue(UUID job, int attempt, double delaySeconds) {
|
||||
Map<String, String> t = new HashMap<>();
|
||||
W3CTraceContextPropagator.getInstance().inject(Context.current(), t, Map::put);
|
||||
String state = t.get("tracestate");
|
||||
db.update("insert into outbox(job_id,attempt,available_at,traceparent,tracestate) values(?,?,now()+make_interval(secs=>?),?,?)",
|
||||
job, attempt, delaySeconds, t.get("traceparent"), state != null && state.length() <= 512 ? state : null);
|
||||
}
|
||||
|
||||
static final TextMapGetter<Map<String, String>> CARRIER = new TextMapGetter<>() {
|
||||
@Override
|
||||
public Iterable<String> keys(Map<String, String> carrier) {
|
||||
return carrier.keySet();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String get(Map<String, String> carrier, String key) {
|
||||
return carrier == null ? null : carrier.get(key);
|
||||
}
|
||||
};
|
||||
|
||||
// Контекст публикации из outbox: span publish агента станет дочерним к причине попытки (без неё — корнем
|
||||
// нового trace, а не тиком relay), агент же переносит его в headers AMQP до consumer span worker.
|
||||
static Context context(String traceparent, String tracestate) {
|
||||
Map<String, String> t = new HashMap<>();
|
||||
if (traceparent != null) t.put("traceparent", traceparent);
|
||||
if (tracestate != null) t.put("tracestate", tracestate);
|
||||
return W3CTraceContextPropagator.getInstance().extract(Context.root(), t, CARRIER);
|
||||
}
|
||||
|
||||
// Строгая проверка по jobs.schema.json; лишние поля — ошибка разбора (сообщение уйдёт в DLQ).
|
||||
static Msg parse(byte[] body) throws IOException {
|
||||
Msg m = JSON.readValue(body, Msg.class);
|
||||
if (!Integer.valueOf(1).equals(m.schema_version()) || !TYPE.equals(m.type()) || m.job_id() == null || m.attachment_id() == null
|
||||
|| m.pipeline_version() == null || m.pipeline_version() < 1 || m.attempt() == null || m.attempt() < 1 || m.created_at() == null)
|
||||
throw new IOException("message does not match jobs.schema.json");
|
||||
Instant.parse(m.created_at());
|
||||
return m;
|
||||
}
|
||||
|
||||
// Захват попытки: только queued с тем же attempt. Иначе дубль или устаревшее сообщение — no-op и ack.
|
||||
Claim claim(Msg m) {
|
||||
return tx.execute(s -> {
|
||||
List<Claim> claimed = db.query("update jobs j set state='processing',lease_owner=?,lease_until=now()+make_interval(secs=>?),started_at=now(),updated_at=now()"
|
||||
+ " from attachments a where j.job_id=? and j.state='queued' and j.attempt=? and j.attachment_id=? and j.pipeline_version=? and a.id=j.attachment_id"
|
||||
+ " returning a.filename", (rs, n) -> new Claim(m.job_id(), m.attachment_id(), m.attempt(), m.pipeline_version(), rs.getString(1)),
|
||||
ACTOR, LEASE_SECONDS, m.job_id(), m.attempt(), m.attachment_id(), m.pipeline_version());
|
||||
if (claimed.isEmpty()) {
|
||||
// Причина — в audit: по нему эксперимент считает погашенные дубли.
|
||||
String why = db.query("select state,attempt from jobs where job_id=?", rs -> !rs.next() ? "unknown_job"
|
||||
: rs.getString(1).equals("done") ? "duplicate_done" : rs.getInt(2) > m.attempt() ? "stale_attempt"
|
||||
: rs.getString(1).equals("processing") ? "duplicate_in_progress" : rs.getString(1).equals("failed") ? "dropped_failed" : "mismatch", m.job_id());
|
||||
if (!why.equals("unknown_job")) audit(m.job_id(), m.attempt(), why, null);
|
||||
log.info("job {} attempt {}: {}, ack without processing", m.job_id(), m.attempt(), why);
|
||||
return null;
|
||||
}
|
||||
// ready-вложение (новая версия pipeline) остаётся ready: старый результат отдаётся до новой фиксации.
|
||||
db.update("update attachments set state='processing',updated_at=now() where id=? and state='queued'", m.attachment_id());
|
||||
audit(m.job_id(), m.attempt(), "claimed", null);
|
||||
return claimed.get(0);
|
||||
});
|
||||
}
|
||||
|
||||
// [число queued-заданий, возраст самого старого в секундах] — для метрик очереди.
|
||||
double[] queued() {
|
||||
return db.queryForObject("select count(*),coalesce(extract(epoch from now()-min(updated_at)),0) from jobs where state='queued'",
|
||||
(rs, n) -> new double[]{rs.getLong(1), rs.getDouble(2)});
|
||||
}
|
||||
|
||||
Source source(UUID attachment) {
|
||||
return db.queryForObject("select content_type,size_bytes,sha256,object_key from attachments where id=?",
|
||||
(rs, n) -> new Source(rs.getString(1), rs.getLong(2), rs.getString(3), rs.getString(4)), attachment);
|
||||
}
|
||||
|
||||
// Heartbeat: продлевает аренду, но не дальше JOB_TIMEOUT_SECONDS от начала попытки.
|
||||
boolean extend(Claim c) {
|
||||
return db.update("update jobs set lease_until=now()+make_interval(secs=>?) where job_id=? and state='processing' and attempt=? and started_at>now()-make_interval(secs=>?)",
|
||||
LEASE_SECONDS, c.job, c.attempt, TIMEOUT_SECONDS) == 1;
|
||||
}
|
||||
|
||||
// Фиксация результата: варианты, указатель версии и done — атомарно и только владельцем попытки.
|
||||
boolean complete(Claim c, List<Variant> variants) {
|
||||
return Boolean.TRUE.equals(tx.execute(s -> {
|
||||
if (lock(c) == null) return false;
|
||||
for (Variant v : variants)
|
||||
db.update("insert into attachment_variants(attachment_id,pipeline_version,name,content_type,size_bytes,width,height,sha256,object_key,job_id)"
|
||||
+ " values(?,?,?,?,?,?,?,?,?,?) on conflict do nothing", c.attachment, c.version, v.name(), v.contentType(), v.size(), v.width(), v.height(), v.sha256(), v.key(), c.job);
|
||||
// Указатель текущей версии только растёт: старая job после новой не перезапишет результат.
|
||||
boolean current = db.update("update attachments set state='ready',error_code=null,pipeline_version=?,updated_at=now() where id=? and state<>'lost'"
|
||||
+ " and coalesce(pipeline_version,0)<=?", c.version, c.attachment, c.version) == 1;
|
||||
db.update("update jobs set state='done',lease_owner=null,lease_until=null,error_code=null,updated_at=now() where job_id=?", c.job);
|
||||
audit(c.job, c.attempt, "done", current ? "current" : "superseded");
|
||||
if (current && c.version == 1)
|
||||
TIME_TO_READY.record(db.queryForObject("select extract(epoch from now()-created_at) from attachments where id=?", Double.class, c.attachment));
|
||||
return true;
|
||||
}));
|
||||
}
|
||||
|
||||
// Временная ошибка: следующая попытка через backoff с jitter, после исчерпания — failed/retry_exhausted.
|
||||
void retry(Claim c, Exception error) {
|
||||
tx.executeWithoutResult(s -> {
|
||||
Integer limit = lock(c);
|
||||
if (limit == null) return;
|
||||
if (c.attempt >= limit) {
|
||||
failLocked(c.job, c.attempt, c.attachment, "retry_exhausted", error.toString());
|
||||
return;
|
||||
}
|
||||
long cap = Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS << Math.min(20, c.attempt - 1));
|
||||
long delay = cap / 2 + ThreadLocalRandom.current().nextLong(cap / 2 + 1);
|
||||
requeueLocked(c.job, c.attempt, c.attachment, delay, "retry_scheduled", error.toString());
|
||||
});
|
||||
}
|
||||
|
||||
void fail(Claim c, String code, String error) {
|
||||
tx.executeWithoutResult(s -> {
|
||||
if (lock(c) != null) failLocked(c.job, c.attempt, c.attachment, code, error);
|
||||
});
|
||||
}
|
||||
|
||||
// Fencing: попытка ещё владеет заданием; строка заблокирована до конца транзакции. null — не владеет.
|
||||
Integer lock(Claim c) {
|
||||
Integer limit = db.query("select attempts_limit from jobs where job_id=? and state='processing' and attempt=? for update",
|
||||
rs -> rs.next() ? rs.getInt(1) : null, c.job, c.attempt);
|
||||
if (limit == null) log.warn("job {} attempt {} no longer owns the lease, result discarded", c.job, c.attempt);
|
||||
return limit;
|
||||
}
|
||||
|
||||
void requeueLocked(UUID job, int attempt, UUID attachment, long delayMs, String event, String error) {
|
||||
db.update("update jobs set state='queued',attempt=attempt+1,lease_owner=null,lease_until=null,next_attempt_at=now()+make_interval(secs=>?),last_error=?,updated_at=now() where job_id=?",
|
||||
delayMs / 1000.0, truncate(error), job);
|
||||
db.update("update attachments set state='queued',updated_at=now() where id=? and state='processing'", attachment);
|
||||
enqueue(job, attempt + 1, delayMs / 1000.0);
|
||||
audit(job, attempt, event, "next_attempt=" + (attempt + 1) + " delay_ms=" + delayMs + " error=" + truncate(error));
|
||||
}
|
||||
|
||||
void failLocked(UUID job, int attempt, UUID attachment, String code, String error) {
|
||||
db.update("update jobs set state='failed',error_code=?,last_error=?,lease_owner=null,lease_until=null,updated_at=now() where job_id=?", code, truncate(error), job);
|
||||
// failed только у вложения без готовой версии: ready (другая версия pipeline) не откатывается.
|
||||
db.update("update attachments set state='failed',error_code=?,updated_at=now() where id=? and state in ('queued','processing') and pipeline_version is null", code, attachment);
|
||||
audit(job, attempt, "failed", code);
|
||||
}
|
||||
|
||||
// Истёкшая аренда: worker умер или завис (heartbeat не продлевал) — следующая попытка, без второго эффекта.
|
||||
void sweep() {
|
||||
tx.executeWithoutResult(s -> {
|
||||
List<Object[]> expired = db.query("select job_id,attempt,attempts_limit,attachment_id from jobs where state='processing' and lease_until<now()"
|
||||
+ " order by lease_until limit 100 for update skip locked", (rs, n) -> new Object[]{rs.getObject(1, UUID.class), rs.getInt(2), rs.getInt(3), rs.getObject(4, UUID.class)});
|
||||
for (Object[] j : expired) {
|
||||
UUID job = (UUID) j[0], attachment = (UUID) j[3];
|
||||
int attempt = (int) j[1];
|
||||
if (attempt >= (int) j[2]) failLocked(job, attempt, attachment, "retry_exhausted", "lease expired");
|
||||
else requeueLocked(job, attempt, attachment, 0, "lease_expired", "lease expired");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Staging удаляется после безопасной фиксации (ready); непривязанные и failed — после retention.
|
||||
int sweepStaging(Storage storage) {
|
||||
int deleted = 0;
|
||||
Instant cutoff = Instant.now().minusSeconds(STAGING_RETENTION_SECONDS);
|
||||
for (ListObjectsV2Response page : storage.list(Storage.STAGING)) {
|
||||
Map<UUID, S3Object> objects = new HashMap<>();
|
||||
for (S3Object o : page.contents()) {
|
||||
try { objects.put(UUID.fromString(o.key().substring(Storage.STAGING.length())), o); } catch (IllegalArgumentException ignored) {}
|
||||
}
|
||||
if (objects.isEmpty()) continue;
|
||||
Map<UUID, Object[]> rows = new HashMap<>();
|
||||
db.query("select id,state,updated_at from attachments where id=any(?)", rs -> {
|
||||
rows.put(rs.getObject(1, UUID.class), new Object[]{rs.getString(2), rs.getTimestamp(3).toInstant()});
|
||||
}, (Object) objects.keySet().toArray(new UUID[0]));
|
||||
for (Map.Entry<UUID, S3Object> e : objects.entrySet()) {
|
||||
Object[] r = rows.get(e.getKey());
|
||||
boolean delete = r == null ? e.getValue().lastModified().isBefore(cutoff)
|
||||
: r[0].equals("ready") || (r[0].equals("failed") && ((Instant) r[1]).isBefore(cutoff));
|
||||
if (delete) {
|
||||
storage.delete(e.getValue().key());
|
||||
deleted++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (deleted > 0) log.info("staging sweep deleted {} objects", deleted);
|
||||
return deleted;
|
||||
}
|
||||
|
||||
// Операторские команды: docker compose run --rm jobctl <command>.
|
||||
int cli(String[] args) throws IOException {
|
||||
String command = args.length > 0 ? args[0] : "";
|
||||
Object result;
|
||||
switch (command) {
|
||||
case "status" -> {
|
||||
Map<String, Object> r = new LinkedHashMap<>();
|
||||
r.put("jobs", db.queryForList("select pipeline_version,state,count(*) from jobs group by 1,2 order by 1,2"));
|
||||
r.put("attachments", db.queryForList("select state,count(*) from attachments group by 1 order by 1"));
|
||||
r.put("outbox_pending", db.queryForObject("select count(*) from outbox", Long.class));
|
||||
r.put("failed", db.queryForList("select job_id::text,attachment_id::text,pipeline_version,attempt,error_code,updated_at::text from jobs where state='failed' order by updated_at desc limit 50"));
|
||||
result = r;
|
||||
}
|
||||
case "replay" -> {
|
||||
List<UUID> ids = args.length > 1 && args[1].equals("--all-failed")
|
||||
? db.queryForList("select job_id from jobs where state='failed'", UUID.class) : ids(args, 1);
|
||||
Map<String, String> r = new LinkedHashMap<>();
|
||||
for (UUID id : ids) r.put(id.toString(), replay(id));
|
||||
result = r;
|
||||
}
|
||||
case "reprocess" -> {
|
||||
if (args.length < 3 || !args[1].startsWith("--pipeline-version=")) return usage();
|
||||
int version = Integer.parseInt(args[1].substring(19));
|
||||
boolean all = args[2].equals("--all");
|
||||
result = Map.of("jobs_created", reprocess(version, all ? List.of() : ids(args, 2), all));
|
||||
}
|
||||
case "redispatch" -> {
|
||||
long older = args.length > 1 && args[1].startsWith("--older-than=") ? Long.parseLong(args[1].substring(13)) : 300;
|
||||
result = Map.of("republished", redispatch(older));
|
||||
}
|
||||
default -> { return usage(); }
|
||||
}
|
||||
System.out.println(JSON.copy().enable(SerializationFeature.INDENT_OUTPUT).writeValueAsString(result));
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int usage() {
|
||||
System.err.println("usage: jobctl status | replay <job_id>...|--all-failed | reprocess --pipeline-version=N <attachment_id>...|--all | redispatch [--older-than=SECONDS]");
|
||||
return 2;
|
||||
}
|
||||
|
||||
static List<UUID> ids(String[] args, int from) {
|
||||
List<UUID> ids = new ArrayList<>();
|
||||
for (int i = from; i < args.length; i++) ids.add(UUID.fromString(args[i]));
|
||||
return ids;
|
||||
}
|
||||
|
||||
// Явный replay только failed: done-задание не исполняется повторно, прежний эффект защищён PK и fencing.
|
||||
String replay(UUID job) {
|
||||
return tx.execute(s -> {
|
||||
Object[] j = db.query("select state,attempt,attachment_id from jobs where job_id=? for update",
|
||||
rs -> rs.next() ? new Object[]{rs.getString(1), rs.getInt(2), rs.getObject(3, UUID.class)} : null, job);
|
||||
if (j == null) return "unknown job";
|
||||
if (!j[0].equals("failed")) return "skipped: job is " + j[0];
|
||||
int attempt = (int) j[1] + 1;
|
||||
db.update("update jobs set state='queued',attempt=?,attempts_limit=?,error_code=null,next_attempt_at=now(),updated_at=now() where job_id=?",
|
||||
attempt, attempt + MAX_ATTEMPTS - 1, job);
|
||||
db.update("update attachments set state='queued',error_code=null,updated_at=now() where id=? and state='failed'", j[2]);
|
||||
enqueue(job, attempt, 0);
|
||||
audit(job, attempt, "replayed", "operator");
|
||||
return "queued as attempt " + attempt;
|
||||
});
|
||||
}
|
||||
|
||||
// Новая версия pipeline — новая логическая работа (новый job_id); на одну версию не больше одной job.
|
||||
int reprocess(int version, List<UUID> ids, boolean all) {
|
||||
return db.update("with j as (insert into jobs(job_id,attachment_id,pipeline_version,state,attempt,attempts_limit,created_at,updated_at)"
|
||||
+ " select gen_random_uuid(),id,?,'queued',1,?,now(),now() from attachments where state in ('queued','processing','ready') and (? or id=any(?))"
|
||||
+ " on conflict (attachment_id,pipeline_version) do nothing returning job_id) insert into outbox(job_id,attempt) select job_id,1 from j",
|
||||
version, MAX_ATTEMPTS, all, ids.toArray(new UUID[0]));
|
||||
}
|
||||
|
||||
// Ручное восстановление queued-заданий, чьё сообщение потеряно (например, ушло в DLQ по delivery-limit).
|
||||
int redispatch(long olderThanSeconds) {
|
||||
return db.update("with r as (update jobs j set next_attempt_at=now(),updated_at=now() where state='queued' and next_attempt_at<now()-make_interval(secs=>?)"
|
||||
+ " and not exists(select 1 from outbox o where o.job_id=j.job_id) returning job_id,attempt) insert into outbox(job_id,attempt) select job_id,attempt from r", olderThanSeconds);
|
||||
}
|
||||
|
||||
void audit(UUID job, int attempt, String event, String detail) {
|
||||
db.update("insert into job_audit(job_id,attempt,event,actor,detail) values(?,?,?,?,?)", job, attempt, event, ACTOR, detail);
|
||||
}
|
||||
|
||||
static String truncate(String s) {
|
||||
return s == null || s.length() <= 500 ? s : s.substring(0, 500);
|
||||
}
|
||||
|
||||
// Аварийная остановка процесса в заданной точке, один раз на вложение (отметка коммитится до halt).
|
||||
void crash(String point, UUID attachment, String filename) {
|
||||
if (!FAULTS || filename == null || !filename.startsWith("fault-" + point)) return;
|
||||
Integer fired = separate.execute(s -> db.update("insert into fault_marks(point,attachment_id) values(?,?) on conflict do nothing", point, attachment));
|
||||
if (fired == null || fired == 0) return;
|
||||
log.warn("FAULT INJECTION {}: halting process (attachment {})", point, attachment);
|
||||
// Пауза, чтобы уже отправляемый HTTP-ответ этого процесса дошёл: падение — именно в фоновой точке.
|
||||
try { Thread.sleep(1000); } catch (InterruptedException ignored) {}
|
||||
Runtime.getRuntime().halt(137);
|
||||
}
|
||||
|
||||
// Захваченная попытка в worker: флаги для heartbeat/таймаута и ссылки, которые прерывает abort().
|
||||
static final class Claim {
|
||||
final UUID job, attachment;
|
||||
final int attempt, version;
|
||||
final String filename;
|
||||
final long started = System.nanoTime();
|
||||
volatile boolean fenced;
|
||||
volatile ImageReader reader;
|
||||
volatile Process process;
|
||||
|
||||
Claim(UUID job, UUID attachment, int attempt, int version, String filename) {
|
||||
this.job = job;
|
||||
this.attachment = attachment;
|
||||
this.attempt = attempt;
|
||||
this.version = version;
|
||||
this.filename = filename;
|
||||
}
|
||||
|
||||
long elapsedSeconds() {
|
||||
return (System.nanoTime() - started) / 1_000_000_000L;
|
||||
}
|
||||
|
||||
long elapsedNanos() {
|
||||
return System.nanoTime() - started;
|
||||
}
|
||||
|
||||
// Перед каждым побочным эффектом: аренда потеряна — стоп без записи; превышен таймаут — временная ошибка.
|
||||
void check() {
|
||||
if (fenced) throw new Fenced();
|
||||
if (elapsedSeconds() >= TIMEOUT_SECONDS) throw new TimedOut();
|
||||
}
|
||||
|
||||
void abort() {
|
||||
ImageReader r = reader;
|
||||
if (r != null) r.abort();
|
||||
Process p = process;
|
||||
if (p != null) p.destroyForcibly();
|
||||
}
|
||||
}
|
||||
|
||||
static final class Fenced extends RuntimeException {
|
||||
Fenced() { super("lease lost"); }
|
||||
}
|
||||
|
||||
static final class TimedOut extends RuntimeException {
|
||||
TimedOut() { super("job timeout exceeded"); }
|
||||
}
|
||||
|
||||
static final class Permanent extends RuntimeException {
|
||||
final String code;
|
||||
|
||||
Permanent(String code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,535 @@
|
||||
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.argon2.Argon2PasswordEncoder;
|
||||
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 и выход),
|
||||
// worker (обработка заданий из брокера), reconcile (сверка БД и S3) и jobctl (операторские команды заданий).
|
||||
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("worker")) {
|
||||
// Без HTTP: процесс живёт за счёт потоков consumer/планировщика; SIGTERM — graceful stop.
|
||||
new SpringApplicationBuilder(MessengerApplication.class).web(WebApplicationType.NONE)
|
||||
.properties("reconcile.enabled=false", "worker.enabled=true").run();
|
||||
return;
|
||||
}
|
||||
if (!mode.equals("reconcile") && !mode.equals("jobctl")) {
|
||||
System.err.println("usage: [api | migrate | worker | reconcile [--apply] [--grace-seconds=N] [--verify-checksums] | jobctl <command>]");
|
||||
System.exit(2);
|
||||
}
|
||||
ConfigurableApplicationContext ctx = new SpringApplicationBuilder(MessengerApplication.class)
|
||||
.web(WebApplicationType.NONE)
|
||||
.properties("reconcile.enabled=false", "outbox.enabled=false", "spring.main.banner-mode=off", "logging.level.root=WARN")
|
||||
.run();
|
||||
int code;
|
||||
try {
|
||||
String[] rest = Arrays.copyOfRange(args, 1, args.length);
|
||||
code = mode.equals("jobctl") ? ctx.getBean(Jobs.class).cli(rest) : ctx.getBean(Reconciler.class).cli(rest);
|
||||
} catch (Exception e) {
|
||||
LoggerFactory.getLogger(MessengerApplication.class).error(mode + " failed", e);
|
||||
code = 1;
|
||||
}
|
||||
int exit = code;
|
||||
System.exit(SpringApplication.exit(ctx, () -> exit));
|
||||
}
|
||||
|
||||
// @Bean регистрирует возвращаемый объект в контейнере Spring.
|
||||
// Argon2id хранит salt и параметры в PHC-строке; исходный пароль не попадает в базу.
|
||||
@Bean
|
||||
Argon2PasswordEncoder passwordEncoder() {
|
||||
int memory = Integer.parseInt(System.getenv().getOrDefault("ARGON2_MEMORY_KIB", "19456"));
|
||||
int iterations = Integer.parseInt(System.getenv().getOrDefault("ARGON2_ITERATIONS", "2"));
|
||||
int parallelism = Integer.parseInt(System.getenv().getOrDefault("ARGON2_PARALLELISM", "1"));
|
||||
return new Argon2PasswordEncoder(16, 32, parallelism, memory, iterations);
|
||||
}
|
||||
|
||||
// Отключаем автоматическое превращение чисел в строки при чтении 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);
|
||||
long started = System.nanoTime();
|
||||
try {
|
||||
// Учебный отказ для эксперимента SLO (только FAULT_INJECTION=1): заголовок X-Fault-Inject: http-500
|
||||
// даёт 500 до обработчика, без побочных эффектов, так нагрузка задаёт точную долю ошибок.
|
||||
if (Jobs.FAULTS && "http-500".equals(r.getHeader("X-Fault-Inject"))) {
|
||||
s.setStatus(500);
|
||||
s.setContentType("application/json");
|
||||
s.getWriter().write("{\"error\":{\"code\":\"internal_error\",\"message\":\"injected fault\",\"request_id\":\"" + id + "\"}}");
|
||||
return;
|
||||
}
|
||||
// Передаём запрос дальше по цепочке Spring.
|
||||
c.doFilter(r, s);
|
||||
} finally {
|
||||
// Структурный лог запроса внутри server span: агент OTel добавит trace_id/span_id.
|
||||
// Только шаблон маршрута, без raw URL, тела и заголовков; health-пробы не логируем.
|
||||
if (!r.getRequestURI().startsWith("/health")) {
|
||||
Object route = r.getAttribute(org.springframework.web.servlet.HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
|
||||
long ms = (System.nanoTime() - started) / 1_000_000;
|
||||
LoggerFactory.getLogger("http").atInfo().addKeyValue("event", "http.request")
|
||||
.addKeyValue("http.request.method", r.getMethod())
|
||||
.addKeyValue("http.route", route == null ? "unmatched" : route.toString())
|
||||
.addKeyValue("http.response.status_code", s.getStatus())
|
||||
.addKeyValue("request_id", id)
|
||||
.log("{} {} -> {} in {} ms", r.getMethod(), route, s.getStatus(), ms);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// TLS chain validation alone is insufficient: only the LB service identity may invoke API.
|
||||
@Bean OncePerRequestFilter lbIdentity() {
|
||||
return new OncePerRequestFilter() {
|
||||
@Override protected void doFilterInternal(HttpServletRequest r, HttpServletResponse s, FilterChain c)
|
||||
throws ServletException, IOException {
|
||||
if (!Boolean.parseBoolean(System.getenv().getOrDefault("API_MTLS_ENABLED", "false"))) { c.doFilter(r,s); return; }
|
||||
Object peer = r.getAttribute("jakarta.servlet.request.X509Certificate");
|
||||
boolean allowed=false;
|
||||
if (peer instanceof java.security.cert.X509Certificate[] chain && chain.length > 0) {
|
||||
try { for (List<?> san : chain[0].getSubjectAlternativeNames())
|
||||
if (san.size() >= 2 && Integer.valueOf(2).equals(san.get(0)) && "lb".equals(san.get(1))) allowed=true;
|
||||
} catch (java.security.cert.CertificateParsingException ignored) { }
|
||||
}
|
||||
if (!allowed) { s.sendError(403, "mTLS client identity is not allowed"); return; }
|
||||
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;
|
||||
// Argon2id проверяет и хеширует пароли.
|
||||
final Argon2PasswordEncoder 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, Argon2PasswordEncoder 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(sessionKey(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; }
|
||||
// Ключ сессии в Redis — SHA-256 токена: агент OTel пишет команду Redis (GET session:<ключ>) в span,
|
||||
// поэтому сырой токен не должен быть частью ключа (и не лежит открыто в дампе Redis).
|
||||
String sessionKey(String token) {
|
||||
try { return "session:"+HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(token.getBytes(StandardCharsets.UTF_8))); }
|
||||
catch (Exception e) { throw new IllegalStateException("session hashing is unavailable",e); }
|
||||
}
|
||||
// Предварительный 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); }
|
||||
}
|
||||
// Общий на все API-реплики лимит логинов в Redis. Инкремент с TTL не раскрывает,
|
||||
// существует ли username, и ограничивает дорогостоящую проверку Argon2.
|
||||
void loginBudget(String username) {
|
||||
String key="login:"+sessionKey(username).substring("session:".length());
|
||||
try {
|
||||
Long n=redis.opsForValue().increment(key);
|
||||
if (n != null && n == 1) redis.expire(key, Duration.ofMinutes(1));
|
||||
if (n != null && n > 10) throw new ApiException(HttpStatus.TOO_MANY_REQUESTS,"rate_limited","try again later");
|
||||
} catch (ApiException e) { throw e; }
|
||||
catch (Exception e) { throw new ApiException(HttpStatus.SERVICE_UNAVAILABLE,"unavailable","session store is unavailable"); }
|
||||
}
|
||||
|
||||
// Готовность проверяет не только 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]; }
|
||||
loginBudget(p.length > 0 ? p[0] : "malformed");
|
||||
// Получаем 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"); }
|
||||
// Upgrade a legacy/weaker Argon2id PHC string on successful authentication.
|
||||
if (encoder.upgradeEncoding(hash)) db.update("update users set password_hash=? where username=?", encoder.encode(passwordValue(p[1])), p[0]);
|
||||
// После успешной проверки загружаем полную модель пользователя.
|
||||
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(sessionKey(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(sessionKey(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");
|
||||
// Хеш тела для повторов с тем же ключом: отсутствующий 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);
|
||||
}
|
||||
// Вложения этого чата: queued/processing/ready можно, failed — 409; чужое или неизвестное — 404.
|
||||
// Проверка после ключа: повтор успешного запроса возвращает сохранённое сообщение; ошибка откатывает ключ.
|
||||
if(!attachments.isEmpty()) {
|
||||
List<String> states=db.queryForList("select state from attachments where chat_id=? and id=any(?) and state in ('queued','processing','ready','failed')",String.class,id,attachments.toArray(new UUID[0]));
|
||||
if(states.size()!=attachments.size()) throw notFound();
|
||||
if(states.contains("failed")) throw new ApiException(HttpStatus.CONFLICT,"conflict","failed attachment cannot be attached");
|
||||
}
|
||||
// Сообщение и его вложения пишутся в той же транзакции, что и ключ: появится всё или ничего.
|
||||
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\"");
|
||||
if(e.status==HttpStatus.TOO_MANY_REQUESTS) h.set("Retry-After", "60");
|
||||
// Возвращаем статус, заголовки и единое тело ошибки.
|
||||
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,297 @@
|
||||
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), повторный запуск ничего не меняет;
|
||||
// - queued/processing/failed — зона pipeline (lab5): оригинал публикует worker, сверка их не трогает.
|
||||
@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");
|
||||
}
|
||||
case "queued", "processing", "failed" -> count(findings, "pipeline_not_published");
|
||||
default -> count(findings, "lost_known");
|
||||
}
|
||||
}
|
||||
|
||||
void both(S3Object o, Row r) {
|
||||
switch (r.state()) {
|
||||
case "queued", "processing", "failed" -> count(findings, "pipeline_in_progress");
|
||||
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,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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
package ru.mtusi.messenger;
|
||||
|
||||
import com.rabbitmq.client.AMQP;
|
||||
import com.rabbitmq.client.Channel;
|
||||
import com.rabbitmq.client.Connection;
|
||||
import com.rabbitmq.client.DefaultConsumer;
|
||||
import com.rabbitmq.client.Envelope;
|
||||
import com.rabbitmq.client.ShutdownSignalException;
|
||||
import io.opentelemetry.api.GlobalOpenTelemetry;
|
||||
import io.opentelemetry.api.common.AttributeKey;
|
||||
import io.opentelemetry.api.common.Attributes;
|
||||
import io.opentelemetry.api.metrics.DoubleHistogram;
|
||||
import io.opentelemetry.api.metrics.LongCounter;
|
||||
import io.opentelemetry.api.metrics.Meter;
|
||||
import io.opentelemetry.api.trace.Span;
|
||||
import io.opentelemetry.api.trace.StatusCode;
|
||||
import jakarta.annotation.PreDestroy;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.security.DigestInputStream;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Stream;
|
||||
import javax.imageio.ImageIO;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.stereotype.Component;
|
||||
import software.amazon.awssdk.core.exception.SdkException;
|
||||
|
||||
// Worker — отдельный процесс (режим worker). Потребляет attachments.process с ручным ack:
|
||||
// ack только после зафиксированного результата или осознанного no-op для дубля.
|
||||
// Конкуренция ограничена: WORKER_CONCURRENCY каналов, у каждого prefetch 1.
|
||||
@Component
|
||||
@ConditionalOnProperty(name = "worker.enabled", havingValue = "true")
|
||||
class Worker {
|
||||
static final Logger log = LoggerFactory.getLogger(Worker.class);
|
||||
static final int CONCURRENCY = Jobs.env("WORKER_CONCURRENCY", 2);
|
||||
static final Path ALIVE = Path.of("/tmp/worker-alive");
|
||||
// Свои метрики заданий (реализацию даёт OTel Java agent). Labels только низкой кардинальности:
|
||||
// тип задания и исход; ID вложений/заданий в метрики не попадают.
|
||||
static final Meter METER = GlobalOpenTelemetry.getMeter("ru.mtusi.messenger.worker");
|
||||
static final AttributeKey<String> JOB_TYPE = AttributeKey.stringKey("job.type"), OUTCOME = AttributeKey.stringKey("outcome"),
|
||||
QUEUE = AttributeKey.stringKey("queue");
|
||||
// Границы под ожидаемые попытки (доли секунды … JOB_TIMEOUT_SECONDS=60), а не дефолтные 0/5/10/25… с.
|
||||
static final List<Double> DURATION_BUCKETS = List.of(0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 5.0, 10.0, 30.0, 60.0);
|
||||
static final LongCounter PROCESSED = METER.counterBuilder("messenger.jobs.processed").setUnit("{job}")
|
||||
.setDescription("Сообщения заданий по исходу: done, retry, failed, duplicate, fenced").build();
|
||||
static final DoubleHistogram DURATION = METER.histogramBuilder("messenger.job.duration").setUnit("s")
|
||||
.setDescription("Время попытки от захвата до фиксации исхода").setExplicitBucketBoundariesAdvice(DURATION_BUCKETS).build();
|
||||
|
||||
final Broker broker;
|
||||
final Jobs jobs;
|
||||
final Storage storage;
|
||||
final Set<Jobs.Claim> inflight = ConcurrentHashMap.newKeySet();
|
||||
final ExecutorService consumers = Executors.newFixedThreadPool(CONCURRENCY);
|
||||
final ScheduledExecutorService timer = Executors.newScheduledThreadPool(3);
|
||||
final Map<Channel, String> subscriptions = new LinkedHashMap<>();
|
||||
Connection connection;
|
||||
volatile boolean stopping;
|
||||
|
||||
Worker(Broker broker, Jobs jobs, Storage storage) {
|
||||
this.broker = broker;
|
||||
this.jobs = jobs;
|
||||
this.storage = storage;
|
||||
ImageIO.setUseCache(false);
|
||||
int beat = Math.max(1, Jobs.LEASE_SECONDS / 3);
|
||||
timer.scheduleWithFixedDelay(() -> quietly("broker supervisor", this::supervise), 0, 2, TimeUnit.SECONDS);
|
||||
timer.scheduleWithFixedDelay(() -> quietly("heartbeat", this::heartbeat), beat, beat, TimeUnit.SECONDS);
|
||||
timer.scheduleWithFixedDelay(() -> quietly("lease sweep", jobs::sweep), 2, 2, TimeUnit.SECONDS);
|
||||
timer.scheduleWithFixedDelay(() -> quietly("staging sweep", () -> jobs.sweepStaging(storage)), 10, 60, TimeUnit.SECONDS);
|
||||
// Насыщение worker; метрики очереди — в Jobs, чтобы их отдавал и API, когда worker остановлен.
|
||||
METER.gaugeBuilder("messenger.worker.busy").ofLongs().setUnit("{job}").setDescription("Попытки в работе").buildWithCallback(m -> m.record(inflight.size()));
|
||||
METER.gaugeBuilder("messenger.worker.capacity").ofLongs().setUnit("{job}").setDescription("WORKER_CONCURRENCY").buildWithCallback(m -> m.record(CONCURRENCY));
|
||||
}
|
||||
|
||||
static void record(String outcome, double seconds) {
|
||||
Attributes a = Attributes.of(JOB_TYPE, Jobs.TYPE, OUTCOME, outcome);
|
||||
PROCESSED.add(1, a);
|
||||
if (seconds >= 0) DURATION.record(seconds, a);
|
||||
}
|
||||
|
||||
// Исход попытки — на consumer span агента RabbitMQ (его родитель — span publish из headers AMQP):
|
||||
// в trace upload видно, какая попытка ушла в retry/failed и какая дошла до done.
|
||||
static void tag(int attempt, String outcome) {
|
||||
Span span = Span.current().setAttribute("job.attempt", attempt).setAttribute("job.outcome", outcome);
|
||||
if (outcome.equals("retry") || outcome.equals("failed")) span.setStatus(StatusCode.ERROR, outcome);
|
||||
}
|
||||
|
||||
static void quietly(String what, Runnable task) {
|
||||
try {
|
||||
task.run();
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("{} failed: {}", what, e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
// (Пере)подключение к брокеру; файл ALIVE — healthcheck контейнера.
|
||||
synchronized void supervise() {
|
||||
if (stopping) return;
|
||||
try {
|
||||
if (connection == null || !connection.isOpen()) {
|
||||
subscriptions.clear();
|
||||
connection = broker.connect("worker-" + Jobs.ACTOR, consumers);
|
||||
for (int i = 0; i < CONCURRENCY; i++) {
|
||||
Channel ch = connection.createChannel();
|
||||
ch.basicQos(1);
|
||||
subscriptions.put(ch, ch.basicConsume(Broker.QUEUE, false, consumer(ch)));
|
||||
}
|
||||
log.info("consuming {} with concurrency {}", Broker.QUEUE, CONCURRENCY);
|
||||
}
|
||||
Files.writeString(ALIVE, Instant.now().toString());
|
||||
} catch (Exception e) {
|
||||
log.warn("broker unavailable: {}", e.toString());
|
||||
if (connection != null) connection.abort();
|
||||
connection = null;
|
||||
}
|
||||
}
|
||||
|
||||
DefaultConsumer consumer(Channel ch) {
|
||||
return new DefaultConsumer(ch) {
|
||||
@Override
|
||||
public void handleDelivery(String tag, Envelope envelope, AMQP.BasicProperties props, byte[] body) {
|
||||
deliver(ch, envelope.getDeliveryTag(), body);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
void deliver(Channel ch, long tag, byte[] body) {
|
||||
Jobs.Msg m;
|
||||
try {
|
||||
m = Jobs.parse(body);
|
||||
} catch (IOException | RuntimeException e) {
|
||||
log.warn("malformed job message rejected to DLQ: {}", e.toString());
|
||||
settle(() -> ch.basicReject(tag, false));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
process(m);
|
||||
} catch (DataAccessException e) {
|
||||
// Без БД нельзя ни захватить, ни зафиксировать: вернуть сообщение после паузы (delivery-limit → DLQ).
|
||||
log.warn("database unavailable, requeue job {}: {}", m.job_id(), e.toString());
|
||||
sleep(5000);
|
||||
settle(() -> ch.basicNack(tag, false, true));
|
||||
return;
|
||||
}
|
||||
settle(() -> ch.basicAck(tag, false));
|
||||
}
|
||||
|
||||
interface Io {
|
||||
void run() throws IOException;
|
||||
}
|
||||
|
||||
// Канал закрыт (рестарт брокера) — неподтверждённое сообщение брокер доставит повторно.
|
||||
static void settle(Io action) {
|
||||
try {
|
||||
action.run();
|
||||
} catch (IOException | ShutdownSignalException e) {
|
||||
log.warn("ack/nack failed, broker will redeliver: {}", e.toString());
|
||||
}
|
||||
}
|
||||
|
||||
record Result(List<Jobs.Variant> variants, boolean fromStaging) {}
|
||||
|
||||
void process(Jobs.Msg m) {
|
||||
Jobs.Claim c = jobs.claim(m);
|
||||
if (c == null) {
|
||||
record("duplicate", -1);
|
||||
tag(m.attempt(), "duplicate");
|
||||
return;
|
||||
}
|
||||
inflight.add(c);
|
||||
String outcome = "retry";
|
||||
try {
|
||||
jobs.crash("crash-after-claim", c.attachment, c.filename);
|
||||
Result r = run(c);
|
||||
jobs.crash("crash-after-s3", c.attachment, c.filename);
|
||||
if (Jobs.FAULTS && c.filename.startsWith("fault-slow") && c.version == 1) sleep(40000);
|
||||
c.check();
|
||||
if (!jobs.complete(c, r.variants())) {
|
||||
outcome = "fenced";
|
||||
return;
|
||||
}
|
||||
outcome = "done";
|
||||
jobs.crash("crash-after-commit", c.attachment, c.filename);
|
||||
// Staging удаляем только после COMMIT результата; не вышло — уберёт sweepStaging.
|
||||
if (r.fromStaging()) {
|
||||
try { storage.delete(Storage.STAGING + c.attachment); } catch (SdkException e) { log.warn("staging cleanup deferred: {}", e.toString()); }
|
||||
}
|
||||
log.atInfo().addKeyValue("event", "job.done").log("job {} attempt {} done: attachment {} v{}", c.job, c.attempt, c.attachment, c.version);
|
||||
} catch (Jobs.Fenced e) {
|
||||
outcome = "fenced";
|
||||
log.atWarn().addKeyValue("event", "job.fenced").log("job {} attempt {}: lease lost, stopping without commit", c.job, c.attempt);
|
||||
} catch (ImagePipeline.Invalid e) {
|
||||
outcome = "failed";
|
||||
log.atWarn().addKeyValue("event", "job.failed").log("job {} attempt {}: invalid_image", c.job, c.attempt);
|
||||
jobs.fail(c, "invalid_image", e.getMessage());
|
||||
} catch (Jobs.Permanent e) {
|
||||
outcome = "failed";
|
||||
log.atWarn().addKeyValue("event", "job.failed").log("job {} attempt {}: {}", c.job, c.attempt, e.code);
|
||||
jobs.fail(c, e.code, e.getMessage());
|
||||
} catch (DataAccessException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
log.atWarn().addKeyValue("event", "job.retry").log("job {} attempt {} failed: {}", c.job, c.attempt, e.toString());
|
||||
jobs.retry(c, e);
|
||||
} finally {
|
||||
inflight.remove(c);
|
||||
record(outcome, c.elapsedNanos() / 1e9);
|
||||
tag(c.attempt, outcome);
|
||||
}
|
||||
}
|
||||
|
||||
Result run(Jobs.Claim c) throws Exception {
|
||||
Path dir = Files.createTempDirectory("job-");
|
||||
try {
|
||||
// Доверенные метаданные — из БД; из сообщения берётся только ID.
|
||||
Jobs.Source s = jobs.source(c.attachment);
|
||||
String staging = Storage.STAGING + c.attachment;
|
||||
boolean fromStaging = storage.size(staging) != null;
|
||||
if (!fromStaging && storage.size(s.key()) == null) throw new Jobs.Permanent("source_missing", "neither staging nor original object exists");
|
||||
Path src = dir.resolve("source");
|
||||
storage.download(fromStaging ? staging : s.key(), src);
|
||||
if (Files.size(src) != s.size() || !sha256(src).equals(s.sha256())) throw new Jobs.Permanent("processing_failed", "source checksum mismatch");
|
||||
c.check();
|
||||
// Публикация оригинала в конечный префикс: серверная копия тех же байтов, повтор безопасен.
|
||||
if (fromStaging) storage.copy(staging, s.key());
|
||||
if (Jobs.FAULTS && c.filename.startsWith("fault-transient") && c.attempt <= Jobs.MAX_ATTEMPTS) throw new IOException("injected transient fault");
|
||||
// Один retry и успех: цепочка upload → попытка 1 (ERROR retry) → попытка 2 → S3/DB в одной трассе.
|
||||
if (Jobs.FAULTS && c.filename.startsWith("fault-flaky") && c.attempt == 1) throw new IOException("injected transient fault, attempt 1 only");
|
||||
List<Jobs.Variant> variants = new ArrayList<>();
|
||||
for (ImagePipeline.Output o : ImagePipeline.render(src, s.contentType(), c.version, dir, c)) {
|
||||
c.check();
|
||||
// Детерминированный ключ эффекта (attachment, version, variant): повтор перезаписывает тот же объект.
|
||||
String key = Storage.VARIANTS + c.attachment + "/v" + c.version + "/" + o.file();
|
||||
storage.put(key, o.path(), o.contentType());
|
||||
variants.add(new Jobs.Variant(o.name(), o.contentType(), Files.size(o.path()), o.width(), o.height(), sha256(o.path()), key));
|
||||
}
|
||||
return new Result(variants, fromStaging);
|
||||
} finally {
|
||||
try (Stream<Path> files = Files.walk(dir)) {
|
||||
files.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Продление аренды работающих попыток; не продлилась (истекла/перехвачена) — прервать без фиксации.
|
||||
void heartbeat() {
|
||||
for (Jobs.Claim c : inflight) {
|
||||
if (c.elapsedSeconds() >= Jobs.TIMEOUT_SECONDS) {
|
||||
c.abort();
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
if (!jobs.extend(c)) {
|
||||
c.fenced = true;
|
||||
c.abort();
|
||||
}
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("heartbeat for job {} failed: {}", c.job, e.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static String sha256(Path file) throws IOException {
|
||||
MessageDigest sha = Attachments.sha256();
|
||||
try (InputStream in = new DigestInputStream(Files.newInputStream(file), sha)) {
|
||||
in.transferTo(java.io.OutputStream.nullOutputStream());
|
||||
}
|
||||
return HexFormat.of().formatHex(sha.digest());
|
||||
}
|
||||
|
||||
static void sleep(long ms) {
|
||||
try {
|
||||
Thread.sleep(ms);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
// SIGTERM: перестать брать новые сообщения, дождаться текущих попыток (≤ 25 с), закрыть соединение.
|
||||
@PreDestroy
|
||||
void stop() {
|
||||
stopping = true;
|
||||
synchronized (this) {
|
||||
subscriptions.forEach((ch, tag) -> {
|
||||
try { ch.basicCancel(tag); } catch (Exception ignored) {}
|
||||
});
|
||||
}
|
||||
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(25);
|
||||
while (!inflight.isEmpty() && System.nanoTime() < deadline) sleep(200);
|
||||
timer.shutdownNow();
|
||||
synchronized (this) {
|
||||
if (connection != null) connection.abort();
|
||||
}
|
||||
consumers.shutdown();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user