Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
105 lines
5.3 KiB
Java
105 lines
5.3 KiB
Java
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;
|
||
}
|
||
}
|