Публичный вход — HTTPS с проверкой SAN, LB ходит в каждую реплику по mTLS и пускает только CN=lb. Worker не читает хеши паролей и чужие префиксы S3; после смены его ключа и возврата ACL то же вложение становится ready.
Skeleton contracts / contracts (pull_request) Failing after 32s

Автор / группа: ivanstorozhev, БВТ2304
Целевая оценка (3/4/5): 5
Трек 5, если заявлен: трек 1, компрометация worker

Что реализовано и что перенесено: из lab6 перенесены Spring Boot API, PostgreSQL, Redis-кэш сессий, Liquibase через одноразовый сервис migrate, HAProxy без sticky session, две реплики, X-Instance-Id, обязательный Idempotency-Key, scripts/stop-one.sh и scripts/restart.sh, приватный SeaweedFS, ответ 202, staging, transactional outbox, отдельный worker, Kafka 3.9.1 (KRaft, volume kafka-data), состояния queued/processing/ready/failed, JPEG thumbnail и crop, lossy WebP, retry с backoff и jitter, топик attachments.failed, явный replay и lease, OTLP в Collector 0.139.0, Prometheus v3.2.1, Loki 3.4.2, Tempo 2.7.2 и Grafana 11.6.1. Оригинал принимается в S3 в одной транзакции со строкой outbox. Worker коммитит смещение только после записи вариантов в фиксированные ключи. Сообщение брокера содержит идентификаторы и W3C traceparent, без тела сообщения и ключа объекта. Добавлены локальный CA (scripts/bootstrap.sh), публичный TLS на 127.0.0.1:8443 с SAN localhost и 127.0.0.1, mTLS-шлюз каждой реплики с allowlist CN=lb и CRL, JDBC sslmode=verify-full к Postgres, роли messenger / messenger_api / messenger_worker, TLS и ACL Redis, TLS-шлюз S3 с префиксами worker, mTLS Kafka с ACL User:api и User:worker, mTLS к Collector и далее к Prometheus, Loki и Tempo. OpenBao 2.6.6 не в dev mode, file storage, cert auth, токен 45 с, политики только на свой KV. Argon2id m=19456,t=2,p=1, перехеш при успешном входе, общий лимит 8/30 в Redis до подсчёта хеша. Приложение и worker не root, cap_drop ALL, read_only, no-new-privileges. Секреты читаются сертификатом сервиса при старте и не лежат в образе.

Команды запуска из чистого clone:
bash scripts/up.sh
make test CA_FILE="$PWD/secrets/ca/ca.crt"
make test-security CA_FILE="$PWD/secrets/ca/ca.crt"

Результаты проверок и ссылка на REPORT.md: подробности и числа в REPORT.md и evidence/grade7.txt
make check — PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
make test — PASS: lab7 public API scenario; infrastructure and grading evidence remain separate.
make test-security — PASS: trusted HTTPS works; untrusted CA rejected.
mTLS https://api-a:8443/health/ready: без сертификата, чужой CA, CN=stranger и CN=api — отказ; CN=lb — 200. Collector: CN=stranger — отказ, CN=api — HTTP 415. Отозванный лист CN=lb после CRL — отказ, публичный health остаётся 200, id образа не менялся. SET ROLE messenger_worker не читает password_hash и читает attachments. S3 worker: staging/* 200, forbidden/ 403, CreateBucket 403; admin CreateBucket 200. Kafka worker produce в attachments.process — TopicAuthorizationException. Вход: восемь 401, девятый 429 и Retry-After 60; один успешный вход 105 мс. OpenBao: чужой путь 403, renew-self с тем же сертификатом даёт lease 45 с, через 50 с токен 403. Sealed OpenBao: health работающего API 200, новый cert login 503. Трек 1: вложение 74b90666-d1df-47d1-9b1b-40f7c3af4860 принято как 202 queued при остановленном worker, осталось queued после смены ключа S3 и снятия Read ACL, после возврата ACL стало ready.
Argon2ParamsTest и TextRulesTest — PASS. Полный mvn test и make test-persistence / make test-failover на этом стенде не перезапускались.

Ограничения / известные ошибки: один Docker-хост, единственные PostgreSQL, Redis, SeaweedFS, Kafka, Loki, Tempo и Prometheus остаются точками отказа. Replication factor топиков равен 1. Доставка at least once. Unseal OpenBao — один ключ оператора, не Shamir. Контроллер Kafka на 127.0.0.1:9093 без TLS пускает User:ANONYMOUS только для KRaft; порт снаружи не опубликован. У API ключ S3 на весь bucket и bootstrap Admin, у worker только три префикса. File storage OpenBao 2.6.6 помечен как устаревающий к 2.7. Postgres, Redis, Kafka, SeaweedFS, OpenBao и телеметрия не read_only, потому что пишут свои данные. /tmp приложения смонтирован с exec: туда распаковывается библиотека WebP. Trivy 0.67.2: Ubuntu 22.04 — 18 HIGH и 0 CRITICAL, jar — 12 записей (4 CRITICAL); разбор применимости в security/SCAN.md, сокета Docker и root у приложения нет.

Источники и использование ИИ: контракт contracts/openapi.json, contracts/trust-matrix.md, COURSE.md и README задания; код lab6; Spring Boot 4.1.1, Spring Data JPA, spring-security-crypto, Spring Data Redis, Spring Kafka, Liquibase, Actuator, OpenTelemetry, AWS SDK for Java 2.31.50, Thumbnailator 0.4.20, webp-imageio 0.11.0, PostgreSQL 16.10, Redis 7.4.6, HAProxy 3.2.6, SeaweedFS 4.52, Apache Kafka 3.9.1, OpenBao 2.6.6, Collector 0.139.0, Prometheus v3.2.1, Loki 3.4.2, Tempo 2.7.2, Grafana 11.6.1, Trivy 0.67.2. Помощь ИИ использована при переносе lab6, mTLS, OpenBao, треке 1 и отчёте.

Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
Контракт и публичные тесты не ослаблены.
make check и make test выполнены; приложен реальный вывод.
Сценарии отказов/безопасности своего уровня воспроизведены.
Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
README задания сохранён, REPORT.md содержит инструкцию именно моего решения.

Лабораторная 7

Автор / группа: TODO
Целевая оценка (3/4/5): TODO
Трек 5, если заявлен: TODO

Что реализовано и что перенесено: TODO
Команды запуска из чистого clone: TODO
Результаты проверок и ссылка на REPORT.md: TODO
Ограничения / известные ошибки: TODO
Источники и использование ИИ: TODO

Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
Контракт и публичные тесты не ослаблены.
make check и make test выполнены; приложен реальный вывод.
Сценарии отказов/безопасности своего уровня воспроизведены.
Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
README задания сохранён, REPORT.md содержит инструкцию именно моего решения.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
ivanstorozhev
2026-11-26 21:46:22 +03:00
co-authored by Cursor
parent 20afc2c790
commit f424658b1d
172 changed files with 10663 additions and 100 deletions
@@ -0,0 +1,430 @@
package ru.mtuci.messenger.job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import ru.mtuci.messenger.domain.AttachmentEntity;
import ru.mtuci.messenger.domain.AttachmentVariantEntity;
import ru.mtuci.messenger.domain.FailedJobEntity;
import ru.mtuci.messenger.domain.OutboxMessage;
import ru.mtuci.messenger.exception.ConflictException;
import ru.mtuci.messenger.exception.NotFoundException;
import ru.mtuci.messenger.exception.PayloadTooLargeException;
import ru.mtuci.messenger.exception.UnavailableException;
import ru.mtuci.messenger.exception.UnsupportedMediaException;
import ru.mtuci.messenger.repository.AttachmentRepository;
import ru.mtuci.messenger.repository.AttachmentVariantRepository;
import ru.mtuci.messenger.repository.FailedJobRepository;
import ru.mtuci.messenger.repository.OutboxRepository;
import ru.mtuci.messenger.service.ImageFiles;
import ru.mtuci.messenger.service.ImageVariants;
import ru.mtuci.messenger.service.RetryDelay;
import ru.mtuci.messenger.storage.ObjectStorage;
import ru.mtuci.messenger.telemetry.JobMetrics;
import ru.mtuci.messenger.telemetry.LogEvents;
import ru.mtuci.messenger.telemetry.TraceCarrier;
import tools.jackson.databind.json.JsonMapper;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HexFormat;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@Service
public class AttachmentJobs {
private static final Logger log = LoggerFactory.getLogger(AttachmentJobs.class);
private static final Path CRASH_AFTER_WRITE = Path.of("/tmp/messenger-crash-after-write");
private static final Path FAIL_PERMANENT = Path.of("/tmp/messenger-fail-permanent");
private static final Path FAIL_TRANSIENT = Path.of("/tmp/messenger-fail-transient");
private final AttachmentRepository attachments;
private final AttachmentVariantRepository variants;
private final OutboxRepository outbox;
private final FailedJobRepository failedJobs;
private final ObjectStorage storage;
private final JsonMapper json;
private final TransactionTemplate transactions;
private final ObjectProvider<BrokerPublisher> brokers;
private final int maxAttempts;
private final Duration timeout;
private final long backoffBaseMs;
private final long backoffCapMs;
private final int maxBytes;
private final long maxPixels;
private final float jpegQuality;
private final float webpQuality;
private final Set<UUID> localLeases = ConcurrentHashMap.newKeySet();
private final JobMetrics metrics;
private final TraceCarrier traces;
public AttachmentJobs(AttachmentRepository attachments, AttachmentVariantRepository variants, OutboxRepository outbox,
FailedJobRepository failedJobs, ObjectStorage storage, JsonMapper json,
PlatformTransactionManager transactionManager, ObjectProvider<BrokerPublisher> brokers,
JobMetrics metrics, TraceCarrier traces,
@Value("${app.job.max-attempts:5}") int maxAttempts,
@Value("${app.job.timeout:60s}") Duration timeout,
@Value("${app.job.backoff-base-ms:1000}") long backoffBaseMs,
@Value("${app.job.backoff-cap-ms:30000}") long backoffCapMs,
@Value("${app.upload.max-bytes:10485760}") int maxBytes,
@Value("${app.upload.max-pixels:40000000}") long maxPixels,
@Value("${app.image.jpeg-quality:0.85}") float jpegQuality,
@Value("${app.image.webp-quality:0.8}") float webpQuality) {
this.attachments = attachments;
this.variants = variants;
this.outbox = outbox;
this.failedJobs = failedJobs;
this.storage = storage;
this.json = json;
this.transactions = new TransactionTemplate(transactionManager);
this.brokers = brokers;
this.metrics = metrics;
this.traces = traces;
this.maxAttempts = maxAttempts;
this.timeout = timeout;
this.backoffBaseMs = backoffBaseMs;
this.backoffCapMs = backoffCapMs;
this.maxBytes = maxBytes;
this.maxPixels = maxPixels;
this.jpegQuality = jpegQuality;
this.webpQuality = webpQuality;
}
public void enqueue(AttachmentEntity attachment, int attempt, Instant availableAt) {
JobPayload payload = new JobPayload(1, attachment.getJobId(), "attachment.process.v1", attachment.getId(),
attachment.getPipelineVersion(), attempt, attachment.getCreatedAt(), traces.currentTraceparent(), null);
outbox.save(new OutboxMessage(UUID.randomUUID(), attachment.getJobId(), attachment.getId(), attempt,
json.writeValueAsString(payload), availableAt, now()));
}
public void handle(String body, boolean redelivered) {
long started = System.nanoTime();
JobPayload job = parse(body);
Claim claim = transactions.execute(status -> claim(job, redelivered));
if (claim == null || !claim.process()) {
if (claim != null && claim.dlq()) {
publishFailed(body);
metrics.record("failed", elapsed(started));
}
return;
}
String outcome = null;
try {
try {
Processed processed = process(claim);
Boolean saved = transactions.execute(status -> finishReady(claim, processed));
if (Boolean.TRUE.equals(saved)) {
storage.deleteQuietly(claim.stagingKey());
outcome = "success";
}
} catch (PermanentJobException exception) {
Boolean saved = transactions.execute(status -> finishFailed(claim, exception.errorCode()));
if (Boolean.TRUE.equals(saved)) {
publishFailed(body);
outcome = "failed";
}
} catch (TransientJobException exception) {
LogEvents.info(log, "job.retry", "transient job failure attachment={} type={}",
claim.attachmentId(), exception.getClass().getSimpleName());
transactions.executeWithoutResult(status -> finishRetry(claim));
outcome = "retry";
}
} finally {
localLeases.remove(claim.leaseToken());
if (outcome != null) {
metrics.record(outcome, elapsed(started));
}
}
}
public void rejectPoison(String body) {
log.warn("poison job");
publishFailed(body);
}
public AttachmentEntity replay(UUID attachmentId) {
return transactions.execute(status -> {
AttachmentEntity attachment = attachments.lockById(attachmentId).orElseThrow(NotFoundException::new);
if ("ready".equals(attachment.getStatus())) {
return attachment;
}
if (!"failed".equals(attachment.getStatus())) {
throw new ConflictException("Задание ещё выполняется");
}
Instant now = now();
attachment.prepareReplay(now);
for (FailedJobEntity failed : failedJobs.findByAttachmentIdAndReplayedAtIsNull(attachmentId)) {
failed.markReplayed(now);
}
enqueue(attachment, 1, now);
log.info("replay attachment={}", attachmentId);
return attachment;
});
}
public int reapExpired() {
int recovered = 0;
for (UUID id : attachments.findExpiredLeaseIds(Instant.now())) {
Boolean changed = transactions.execute(status -> recoverOne(id));
if (Boolean.TRUE.equals(changed)) {
recovered++;
}
}
return recovered;
}
private boolean recoverOne(UUID id) {
AttachmentEntity attachment = attachments.lockById(id).orElse(null);
Instant now = now();
if (attachment == null || !"processing".equals(attachment.getStatus()) || attachment.leaseHeld(now)) {
return false;
}
if (attachment.getAttempt() >= maxAttempts) {
markFailed(attachment, "retry_exhausted", now);
return true;
}
attachment.markQueued(now);
enqueue(attachment, attachment.getAttempt() + 1, now);
log.info("lease expired attachment={} attempt={}", id, attachment.getAttempt());
return true;
}
private Claim claim(JobPayload job, boolean redelivered) {
AttachmentEntity attachment = attachments.lockById(job.attachmentId()).orElse(null);
if (attachment == null || attachment.getPipelineVersion() > job.pipelineVersion()) {
return Claim.done(false);
}
if ("ready".equals(attachment.getStatus()) || "failed".equals(attachment.getStatus())) {
return Claim.done(false);
}
Instant now = now();
boolean ownedHere = attachment.getLeaseToken() != null && localLeases.contains(attachment.getLeaseToken());
if ("processing".equals(attachment.getStatus()) && attachment.leaseHeld(now) && ownedHere && !redelivered) {
return Claim.done(false);
}
int next = attachment.getAttempt() + 1;
if (next > maxAttempts) {
markFailed(attachment, "retry_exhausted", now);
return Claim.done(true);
}
if (attachment.getStagingKey() == null || attachment.getJobId() == null) {
markFailed(attachment, "processing_failed", now);
return Claim.done(true);
}
UUID token = UUID.randomUUID();
attachment.markProcessing(next, token, now.plus(timeout), now);
localLeases.add(token);
return new Claim(true, false, attachment.getId(), attachment.getJobId(), token, next, attachment.getStagingKey(),
attachment.getObjectKey(), attachment.getContentType(), attachment.getSizeBytes(), attachment.getSha256(),
attachment.getPipelineVersion());
}
private Processed process(Claim claim) {
if (failTransientRequested()) {
throw new TransientJobException("demo");
}
long started = System.nanoTime();
byte[] original = readStaging(claim);
checkTime(started);
if (original.length != claim.sizeBytes() || !sha256(original).equals(claim.sha256())) {
throw new PermanentJobException("invalid_image");
}
try {
ImageFiles.inspect(original, claim.contentType(), maxPixels);
} catch (UnsupportedMediaException | PayloadTooLargeException exception) {
throw new PermanentJobException("invalid_image");
}
if (failPermanentRequested()) {
throw new PermanentJobException("processing_failed");
}
try {
checkTime(started);
storage.put(claim.objectKey(), original, claim.contentType());
var rendered = ImageVariants.render(original, jpegQuality, webpQuality);
checkTime(started);
for (ImageVariants.VariantBytes variant : rendered) {
storage.put(variantKey(claim.attachmentId(), variant.name()), variant.bytes(), variant.contentType());
}
if (crashAfterWriteRequested()) {
log.warn("fault injection: exit after object write before result commit");
System.exit(1);
}
return new Processed(rendered);
} catch (PermanentJobException | TransientJobException exception) {
throw exception;
} catch (UnavailableException exception) {
throw new TransientJobException(exception);
} catch (IOException exception) {
throw new PermanentJobException("invalid_image");
} catch (RuntimeException exception) {
log.warn("transient processing failure type={}", exception.getClass().getSimpleName());
throw new TransientJobException(exception);
}
}
private byte[] readStaging(Claim claim) {
try (InputStream input = storage.get(claim.stagingKey())) {
return ImageFiles.readLimited(input, maxBytes);
} catch (PayloadTooLargeException exception) {
throw new PermanentJobException("invalid_image");
} catch (NotFoundException exception) {
throw new PermanentJobException("processing_failed");
} catch (UnavailableException exception) {
throw new TransientJobException(exception);
} catch (IOException exception) {
throw new TransientJobException(exception);
}
}
private boolean finishReady(Claim claim, Processed processed) {
AttachmentEntity attachment = attachments.lockById(claim.attachmentId()).orElse(null);
if (attachment == null || lost(claim, attachment) || "ready".equals(attachment.getStatus())) {
return false;
}
variants.deleteForPipeline(attachment.getId(), attachment.getPipelineVersion());
for (ImageVariants.VariantBytes variant : processed.variants()) {
variants.save(new AttachmentVariantEntity(UUID.randomUUID(), attachment.getId(), attachment.getPipelineVersion(),
variant.name(), variant.contentType(), variant.bytes().length, variant.width(), variant.height(),
sha256(variant.bytes()), variantKey(attachment.getId(), variant.name())));
}
Instant readyAt = now();
attachment.markReady(readyAt);
metrics.ready(Duration.between(attachment.getCreatedAt(), readyAt));
LogEvents.info(log, "job.ready", "attachment ready id={}", attachment.getId());
return true;
}
private boolean finishFailed(Claim claim, String code) {
AttachmentEntity attachment = attachments.lockById(claim.attachmentId()).orElse(null);
if (attachment == null || lost(claim, attachment) || "ready".equals(attachment.getStatus())
|| "failed".equals(attachment.getStatus())) {
return false;
}
markFailed(attachment, code, now());
return true;
}
private void publishFailed(String body) {
BrokerPublisher publisher = brokers.getIfAvailable();
if (publisher != null) {
publisher.failed(body);
}
}
private void finishRetry(Claim claim) {
AttachmentEntity attachment = attachments.lockById(claim.attachmentId()).orElse(null);
if (attachment == null || lost(claim, attachment) || "ready".equals(attachment.getStatus())
|| "failed".equals(attachment.getStatus())) {
return;
}
Instant now = now();
if (attachment.getAttempt() >= maxAttempts) {
markFailed(attachment, "retry_exhausted", now);
return;
}
attachment.markQueued(now);
long delay = RetryDelay.millis(attachment.getAttempt(), backoffBaseMs, backoffCapMs);
enqueue(attachment, attachment.getAttempt() + 1, now.plusMillis(delay));
}
private void markFailed(AttachmentEntity attachment, String code, Instant now) {
attachment.markFailed(code, now);
failedJobs.save(new FailedJobEntity(UUID.randomUUID(), attachment.getJobId(), attachment.getId(), code,
attachment.getAttempt(), now));
LogEvents.info(log, "job.failed", "attachment failed id={} code={}", attachment.getId(), code);
}
private static boolean lost(Claim claim, AttachmentEntity attachment) {
return attachment.getLeaseToken() == null || !claim.leaseToken().equals(attachment.getLeaseToken());
}
private void checkTime(long started) {
if (System.nanoTime() - started > timeout.toNanos()) {
throw new TransientJobException("timeout");
}
}
private JobPayload parse(String body) {
try {
JobPayload job = json.readValue(body, JobPayload.class);
if (job == null || job.schemaVersion() != 1 || job.attachmentId() == null || job.jobId() == null
|| !"attachment.process.v1".equals(job.type()) || job.pipelineVersion() < 1 || job.attempt() < 1) {
throw new PoisonJobException();
}
return job;
} catch (PoisonJobException exception) {
throw exception;
} catch (RuntimeException exception) {
throw new PoisonJobException();
}
}
private static boolean crashAfterWriteRequested() {
try {
return Files.deleteIfExists(CRASH_AFTER_WRITE);
} catch (IOException exception) {
return false;
}
}
private static boolean failTransientRequested() {
try {
return Files.deleteIfExists(FAIL_TRANSIENT);
} catch (IOException exception) {
return false;
}
}
private static boolean failPermanentRequested() {
try {
return Files.deleteIfExists(FAIL_PERMANENT);
} catch (IOException exception) {
return false;
}
}
static String variantKey(UUID attachmentId, String name) {
return "variants/" + attachmentId + "/" + name;
}
private static String sha256(byte[] bytes) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException(exception);
}
}
private static Instant now() {
return Instant.now().truncatedTo(ChronoUnit.MICROS);
}
private static Duration elapsed(long startedNanos) {
Duration duration = Duration.ofNanos(System.nanoTime() - startedNanos);
return duration.isNegative() ? Duration.ZERO : duration;
}
private record Claim(boolean process, boolean dlq, UUID attachmentId, UUID jobId, UUID leaseToken, int attempt,
String stagingKey, String objectKey, String contentType, long sizeBytes, String sha256,
int pipelineVersion) {
static Claim done(boolean dlq) {
return new Claim(false, dlq, null, null, null, 0, null, null, null, 0, null, 0);
}
}
private record Processed(java.util.List<ImageVariants.VariantBytes> variants) {
}
}
@@ -0,0 +1,69 @@
package ru.mtuci.messenger.job;
import io.micrometer.tracing.Span;
import io.micrometer.tracing.Tracer;
import io.micrometer.tracing.propagation.Propagator;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;
import ru.mtuci.messenger.telemetry.KafkaTrace;
import ru.mtuci.messenger.telemetry.LogEvents;
import ru.mtuci.messenger.telemetry.WorkerSaturation;
@Component
@ConditionalOnProperty(name = "app.worker.consume", havingValue = "true")
public class AttachmentWorker {
private static final Logger log = LoggerFactory.getLogger(AttachmentWorker.class);
private final AttachmentJobs jobs;
private final WorkerSaturation saturation;
private final ObjectProvider<Tracer> tracers;
private final ObjectProvider<Propagator> propagators;
public AttachmentWorker(AttachmentJobs jobs, WorkerSaturation saturation, ObjectProvider<Tracer> tracers,
ObjectProvider<Propagator> propagators) {
this.jobs = jobs;
this.saturation = saturation;
this.tracers = tracers;
this.propagators = propagators;
}
@KafkaListener(topics = BrokerConfig.PROCESS, groupId = "attachment-worker")
public void onMessage(ConsumerRecord<String, String> record, Acknowledgment acknowledgment) {
Tracer tracer = tracers.getIfAvailable();
Span span = KafkaTrace.consumer(tracer, propagators.getIfAvailable(), record.headers(),
KafkaTrace.traceparentOf(record.value()));
Tracer.SpanInScope scope = span == null || tracer == null ? null : tracer.withSpan(span);
saturation.enter();
try {
jobs.handle(record.value(), false);
acknowledgment.acknowledge();
} catch (PoisonJobException exception) {
if (span != null) {
span.error(exception);
}
jobs.rejectPoison(record.value());
acknowledgment.acknowledge();
} catch (RuntimeException exception) {
if (span != null) {
span.error(exception);
}
LogEvents.warn(log, "job.not_acked", "job not acked type={}", exception.getClass().getSimpleName());
throw exception;
} finally {
saturation.exit();
if (scope != null) {
scope.close();
}
if (span != null) {
span.end();
}
}
}
}
@@ -0,0 +1,45 @@
package ru.mtuci.messenger.job;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.TopicBuilder;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.listener.ContainerProperties;
import org.springframework.kafka.listener.DefaultErrorHandler;
import org.springframework.util.backoff.FixedBackOff;
@Configuration
@EnableKafka
@ConditionalOnProperty(name = "app.broker.enabled", havingValue = "true")
public class BrokerConfig {
public static final String PROCESS = "attachments.process";
public static final String FAILED = "attachments.failed";
@Bean
NewTopic processTopic(@Value("${app.worker.concurrency:2}") int concurrency) {
return TopicBuilder.name(PROCESS).partitions(concurrency).replicas(1).build();
}
@Bean
NewTopic failedTopic() {
return TopicBuilder.name(FAILED).partitions(1).replicas(1).build();
}
@Bean
ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory(
ConsumerFactory<String, String> consumerFactory,
@Value("${app.worker.concurrency:2}") int concurrency) {
ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory);
factory.setConcurrency(concurrency);
factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL);
factory.setCommonErrorHandler(new DefaultErrorHandler(new FixedBackOff(1000L, FixedBackOff.UNLIMITED_ATTEMPTS)));
return factory;
}
}
@@ -0,0 +1,84 @@
package ru.mtuci.messenger.job;
import io.micrometer.tracing.Span;
import io.micrometer.tracing.Tracer;
import io.micrometer.tracing.propagation.Propagator;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import ru.mtuci.messenger.telemetry.KafkaTrace;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@Component
@ConditionalOnProperty(name = "app.broker.enabled", havingValue = "true")
public class BrokerPublisher {
private static final Logger log = LoggerFactory.getLogger(BrokerPublisher.class);
private final KafkaTemplate<String, String> kafka;
private final ObjectProvider<Tracer> tracers;
private final ObjectProvider<Propagator> propagators;
public BrokerPublisher(KafkaTemplate<String, String> kafka, ObjectProvider<Tracer> tracers,
ObjectProvider<Propagator> propagators) {
this.kafka = kafka;
this.tracers = tracers;
this.propagators = propagators;
}
public void confirm(String key, String payload) {
send(BrokerConfig.PROCESS, key, payload);
}
public void failed(String payload) {
try {
send(BrokerConfig.FAILED, null, payload);
} catch (RuntimeException exception) {
log.warn("dlq publish failed type={}", exception.getClass().getSimpleName());
}
}
private void send(String topic, String key, String payload) {
Tracer tracer = tracers.getIfAvailable();
Propagator propagator = propagators.getIfAvailable();
Span span = KafkaTrace.producer(tracer, propagator, topic, KafkaTrace.traceparentOf(payload));
Tracer.SpanInScope scope = span == null || tracer == null ? null : tracer.withSpan(span);
try {
ProducerRecord<String, String> record = new ProducerRecord<>(topic, key, payload);
KafkaTrace.inject(propagator, span, record.headers());
SendResult<String, String> result = kafka.send(record).get(5, TimeUnit.SECONDS);
if (result == null || result.getRecordMetadata() == null) {
throw new IllegalStateException("broker nack");
}
} catch (InterruptedException exception) {
Thread.currentThread().interrupt();
if (span != null) {
span.error(exception);
}
throw new IllegalStateException("broker confirm interrupted");
} catch (TimeoutException | ExecutionException | RuntimeException exception) {
if (span != null) {
span.error(exception);
}
if (exception instanceof RuntimeException runtime) {
throw runtime;
}
throw new IllegalStateException("broker confirm failed");
} finally {
if (scope != null) {
scope.close();
}
if (span != null) {
span.end();
}
}
}
}
@@ -0,0 +1,23 @@
package ru.mtuci.messenger.job;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.Instant;
import java.util.UUID;
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public record JobPayload(
@JsonProperty("schema_version") int schemaVersion,
@JsonProperty("job_id") UUID jobId,
@JsonProperty("type") String type,
@JsonProperty("attachment_id") UUID attachmentId,
@JsonProperty("pipeline_version") int pipelineVersion,
@JsonProperty("attempt") int attempt,
@JsonProperty("created_at") Instant createdAt,
@JsonProperty("traceparent") String traceparent,
@JsonProperty("tracestate") String tracestate
) {
}
@@ -0,0 +1,21 @@
package ru.mtuci.messenger.job;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@ConditionalOnProperty(name = "app.worker.consume", havingValue = "true")
public class LeaseReaper {
private final AttachmentJobs jobs;
public LeaseReaper(AttachmentJobs jobs) {
this.jobs = jobs;
}
@Scheduled(fixedDelayString = "${app.job.reaper-ms:5000}")
public void reap() {
jobs.reapExpired();
}
}
@@ -0,0 +1,71 @@
package ru.mtuci.messenger.job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import ru.mtuci.messenger.domain.OutboxMessage;
import ru.mtuci.messenger.repository.OutboxRepository;
import ru.mtuci.messenger.service.DemoFlags;
import ru.mtuci.messenger.telemetry.LogEvents;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
@Component
@ConditionalOnProperty(name = "app.outbox.enabled", havingValue = "true", matchIfMissing = true)
public class OutboxPublisher {
private static final Logger log = LoggerFactory.getLogger(OutboxPublisher.class);
private final OutboxRepository outbox;
private final DemoFlags flags;
private final BrokerPublisher broker;
private final TransactionTemplate transactions;
public OutboxPublisher(OutboxRepository outbox, DemoFlags flags, BrokerPublisher broker,
PlatformTransactionManager transactionManager) {
this.outbox = outbox;
this.flags = flags;
this.broker = broker;
this.transactions = new TransactionTemplate(transactionManager);
}
@Scheduled(fixedDelayString = "${app.outbox.poll-ms:500}")
public void publishDue() {
if (flags.outboxPaused()) {
return;
}
for (int i = 0; i < 10; i++) {
if (flags.outboxPaused()) {
return;
}
Boolean sent = transactions.execute(status -> publishOne());
if (!Boolean.TRUE.equals(sent)) {
return;
}
}
}
private boolean publishOne() {
if (flags.outboxPaused()) {
return false;
}
List<UUID> ids = outbox.lockDueIds(Instant.now(), 1);
if (ids.isEmpty()) {
return false;
}
OutboxMessage row = outbox.findById(ids.getFirst()).orElseThrow();
if (row.getPublishedAt() != null) {
return false;
}
broker.confirm(row.getAttachmentId().toString(), row.getPayload());
row.setPublishedAt(Instant.now());
LogEvents.info(log, "outbox.published", "outbox published id={}", row.getId());
return true;
}
}
@@ -0,0 +1,15 @@
package ru.mtuci.messenger.job;
public class PermanentJobException extends RuntimeException {
private final String errorCode;
public PermanentJobException(String errorCode) {
super(errorCode);
this.errorCode = errorCode;
}
public String errorCode() {
return errorCode;
}
}
@@ -0,0 +1,8 @@
package ru.mtuci.messenger.job;
public class PoisonJobException extends RuntimeException {
public PoisonJobException() {
super("bad job");
}
}
@@ -0,0 +1,12 @@
package ru.mtuci.messenger.job;
public class TransientJobException extends RuntimeException {
public TransientJobException(String message) {
super(message);
}
public TransientJobException(Throwable cause) {
super(cause);
}
}