mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Moved the workspace to the root, Added the build scripts, ARM64 releases and the Docker image
Source/'s content is at the root now, Source/README.md merged into readme.md. Scripts at the root: build.ps1, test.ps1 (was check.ps1), release.ps1 (over release.py) and clean.ps1. Everything is LF except the .ps1 files. CI (.github/workflows/ci.yml) runs on a v* tag or by hand: the checks, then a release for Windows x64 and ARM64 and Linux x64 and ARM64, each on its own kind of runner, the archives kept as artifacts. release.py names the platform from the Rust host, make_wheel.py tags the wheel from the library's header. docker/: the server's image (built from source, the tools beside it, uid 10001), compose.yml and test.sh. CI builds amd64 and arm64 natively, checks them, and on a tag pushes them to ghcr.io with an index for <version> and latest. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,218 @@
|
||||
//! Replication's receiving end: a server that dialed in sends what this
|
||||
//! one lacks (`push_to.rs` is the other end). Taken only from addresses in
|
||||
//! `[replication] accept_from`, and only what its roles' `accept_*` allow.
|
||||
|
||||
use crate::connection::{Frames, Peer, receive_parts, refused, send};
|
||||
use crate::writer::Write;
|
||||
use crate::{Shared, now};
|
||||
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_SIZE, MAX_MISSING_ATTACHMENTS};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, Continue, MessagePushed, ReplicateAttachment, ReplicateMessages, SyncState,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Whether `address` is in `accept_from`: `*`, an address as written, or
|
||||
/// a hostname resolving to it (looked up now).
|
||||
async fn is_accepted(shared: &Shared, address: IpAddr) -> bool {
|
||||
let address = address.to_canonical();
|
||||
for host in &shared.config.replication.accept_from {
|
||||
if host == "*" {
|
||||
return true;
|
||||
}
|
||||
if let Ok(ip) = host.parse::<IpAddr>() {
|
||||
if ip.to_canonical() == address {
|
||||
return true;
|
||||
}
|
||||
} else if let Ok(found) = tokio::net::lookup_host((host.as_str(), 0)).await
|
||||
&& found
|
||||
.into_iter()
|
||||
.any(|at| at.ip().to_canonical() == address)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Refused unless the connection comes from `accept_from` (looked up at
|
||||
/// its first replication request).
|
||||
async fn check_address(shared: &Shared, peer: &mut Peer) -> Result<(), Packet> {
|
||||
let accepted = match peer.accepted {
|
||||
Some(accepted) => accepted,
|
||||
None => *peer
|
||||
.accepted
|
||||
.insert(is_accepted(shared, peer.address).await),
|
||||
};
|
||||
match accepted {
|
||||
true => Ok(()),
|
||||
false => Err(refused(
|
||||
ErrorCode::NotAllowed,
|
||||
format!(
|
||||
"this server doesn't take replication from {} ({}): not in its accept_from",
|
||||
peer.node, peer.address
|
||||
),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Refused unless the connection comes from `accept_from` and its roles
|
||||
/// accept `node`'s messages in `topic`.
|
||||
async fn check(shared: &Shared, peer: &mut Peer, topic: &str, node: &str) -> Result<(), Packet> {
|
||||
check_address(shared, peer).await?;
|
||||
match peer.permissions.accepts(topic, node) {
|
||||
true => Ok(()),
|
||||
false => Err(refused(
|
||||
ErrorCode::NotAllowed,
|
||||
format!("this server doesn't take {topic}:{node} from {}", peer.node),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// What it takes from this peer, how far it is in those, and the
|
||||
/// attachments it lacks among them.
|
||||
pub(crate) async fn sync_state(shared: &Arc<Shared>, peer: &mut Peer) -> Packet {
|
||||
if let Err(refusal) = check_address(shared, peer).await {
|
||||
return refusal;
|
||||
}
|
||||
let (topics, nodes) = peer.permissions.accepted();
|
||||
let found = shared
|
||||
.read(|reader| {
|
||||
Ok((
|
||||
reader.heads()?,
|
||||
reader.missing_attachments(MAX_MISSING_ATTACHMENTS)?,
|
||||
))
|
||||
})
|
||||
.await;
|
||||
let (mut heads, mut missing) = match found {
|
||||
Ok(found) => found,
|
||||
Err(refusal) => return refusal.into(),
|
||||
};
|
||||
heads.retain(|head| peer.permissions.accepts(&head.topic, &head.node));
|
||||
missing.retain(|missing| peer.permissions.accepts(&missing.topic, &missing.node));
|
||||
SyncState {
|
||||
topics,
|
||||
nodes,
|
||||
heads,
|
||||
missing,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
/// A batch of a topic and node's messages: stored (those past their age
|
||||
/// here only counted), answered with its last id.
|
||||
pub(crate) async fn replicate_messages(
|
||||
shared: &Arc<Shared>,
|
||||
peer: &mut Peer,
|
||||
batch: ReplicateMessages,
|
||||
) -> Packet {
|
||||
if let Err(refusal) = check(shared, peer, &batch.topic, &batch.node).await {
|
||||
return refusal;
|
||||
}
|
||||
if let Some(big) = batch
|
||||
.messages
|
||||
.iter()
|
||||
.find(|m| m.data.len() > MAX_MESSAGE_SIZE)
|
||||
{
|
||||
return refused(
|
||||
ErrorCode::TooBig,
|
||||
format!("message #{}: {MAX_MESSAGE_SIZE} bytes at most", big.id),
|
||||
);
|
||||
}
|
||||
let skip_before = shared
|
||||
.config
|
||||
.retention
|
||||
.age(&batch.topic)
|
||||
.map_or(0, |age| now().saturating_sub(age.as_millis() as u64));
|
||||
let write = Write::Replicate {
|
||||
topic: batch.topic,
|
||||
node: batch.node,
|
||||
messages: batch.messages,
|
||||
max_attachment_size: shared.config.server.max_attachment_size,
|
||||
skip_before,
|
||||
};
|
||||
match shared.pushes.send(write).await {
|
||||
Ok(message_id) => MessagePushed { message_id }.into(),
|
||||
Err(refusal) => refusal.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// An attachment this server lacks: `Continue`, its parts from where it
|
||||
/// stopped, checked with its SHA-256 (the parts it had read back for it).
|
||||
/// An error closes the connection.
|
||||
pub(crate) async fn replicate_attachment(
|
||||
shared: &Arc<Shared>,
|
||||
peer: &mut Peer,
|
||||
frames: &mut Frames,
|
||||
request: ReplicateAttachment,
|
||||
) -> Result<Packet, String> {
|
||||
if let Err(refusal) = check(shared, peer, &request.topic, &request.node).await {
|
||||
return Ok(refusal);
|
||||
}
|
||||
let message = format!("{}:{}#{}", request.topic, request.node, request.message_id);
|
||||
let ReplicateAttachment {
|
||||
topic,
|
||||
node,
|
||||
message_id,
|
||||
from_part,
|
||||
} = request;
|
||||
let stored = match shared
|
||||
.read(move |reader| reader.attachment(&topic, &node, message_id))
|
||||
.await
|
||||
{
|
||||
Ok(Some(stored)) if stored.state == AttachmentState::Replicating => stored,
|
||||
Ok(_) => {
|
||||
return Ok(refused(
|
||||
ErrorCode::NotFound,
|
||||
format!("{message}: no attachment missing here"),
|
||||
));
|
||||
}
|
||||
Err(refusal) => return Ok(refusal.into()),
|
||||
};
|
||||
let attachment = Attachment {
|
||||
size: stored.size,
|
||||
sha256: stored.sha256,
|
||||
};
|
||||
let next = stored.received / ATTACHMENT_PART_SIZE;
|
||||
if from_part != next || stored.received == stored.size {
|
||||
return Ok(refused(
|
||||
ErrorCode::InvalidRequest,
|
||||
format!("{message}: part {next} is the next one here, not {from_part}"),
|
||||
));
|
||||
}
|
||||
|
||||
// The parts it has, read back for the SHA-256.
|
||||
let sha256 = match shared.hash_parts(stored.id, 0..from_part).await {
|
||||
Ok(sha256) => sha256,
|
||||
Err(refusal) => return Ok(refusal.into()),
|
||||
};
|
||||
let attachment_id = stored.id as u64;
|
||||
send(frames, Continue {}.into())
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
let refusal = receive_parts(
|
||||
shared,
|
||||
frames,
|
||||
attachment_id,
|
||||
&attachment,
|
||||
from_part,
|
||||
sha256,
|
||||
)
|
||||
.await?;
|
||||
if let Some(refusal) = &refusal
|
||||
&& refusal.code != ErrorCode::DataMismatch.code()
|
||||
{
|
||||
// A part not written: it goes on from there next time.
|
||||
return Ok(refusal.clone().into());
|
||||
}
|
||||
let finish = Write::FinishReplicated {
|
||||
attachment: attachment_id,
|
||||
matches: refusal.is_none(),
|
||||
};
|
||||
Ok(match (shared.pushes.send(finish).await, refusal) {
|
||||
(Err(refusal), _) | (Ok(_), Some(refusal)) => refusal.into(),
|
||||
(Ok(_), None) => MessagePushed { message_id }.into(),
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
//! One connection: TLS, the versions, who it is, then its requests, one at
|
||||
//! a time (`docs/protocol.md`).
|
||||
|
||||
use crate::writer::Write;
|
||||
use crate::{Shared, accept_from, now};
|
||||
use aws_lc_rs::digest;
|
||||
use bakashrot_config::Permissions;
|
||||
use bakashrot_pki::Identity;
|
||||
use bakashrot_proto::limits::{MAX_MESSAGE_SIZE, MAX_NAMES_LIST_ENTRIES, MAX_PACKET_SIZE};
|
||||
use bakashrot_proto::names::names_equal;
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, Continue, GetAttachment, GetMessages, ListNames, MessagePushed,
|
||||
Messages, NameKind, NamesList, PushMessage, Query, QueryResult, RequestRefused, Welcome,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use std::collections::VecDeque;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::time::timeout;
|
||||
use tokio_rustls::server::TlsStream;
|
||||
use tokio_util::codec::{Framed, LengthDelimitedCodec};
|
||||
use tracing::{debug, info};
|
||||
|
||||
/// How long TLS and the versions may take.
|
||||
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// How long a connection may stay silent between requests.
|
||||
const IDLE_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
|
||||
/// How long an attachment's next part may take to come.
|
||||
const PART_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// An upload's parts given to the writer and not written yet, at most: the
|
||||
/// next ones wait (the client with them, through TCP).
|
||||
const PARTS_IN_FLIGHT: usize = 4;
|
||||
|
||||
pub(crate) type Frames = Framed<TlsStream<TcpStream>, LengthDelimitedCodec>;
|
||||
|
||||
/// Serves one connection until it ends, logging why.
|
||||
pub(crate) async fn handle(shared: Arc<Shared>, tcp: TcpStream, peer: SocketAddr) {
|
||||
match serve(&shared, tcp, peer.ip()).await {
|
||||
Ok(node) => debug!("{peer} ({node}): closed"),
|
||||
Err(why) => info!("{peer}: {why}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Who it is once checked: its node, its certificate's serial (for later
|
||||
/// revocations), what it may do, where it connects from.
|
||||
pub(crate) struct Peer {
|
||||
pub(crate) node: String,
|
||||
serial: Vec<u8>,
|
||||
pub(crate) permissions: Permissions,
|
||||
pub(crate) address: IpAddr,
|
||||
/// Whether `accept_from` has it, once a replication request asked.
|
||||
pub(crate) accepted: Option<bool>,
|
||||
}
|
||||
|
||||
async fn serve(shared: &Arc<Shared>, tcp: TcpStream, address: IpAddr) -> Result<String, String> {
|
||||
tcp.set_nodelay(true).map_err(|error| error.to_string())?;
|
||||
let (mut frames, mut peer) = timeout(HANDSHAKE_TIMEOUT, open(shared, tcp, address))
|
||||
.await
|
||||
.map_err(|_| "too slow to connect".to_owned())??;
|
||||
debug!("{} connected", peer.node);
|
||||
|
||||
loop {
|
||||
let bytes = match timeout(IDLE_TIMEOUT, frames.next()).await {
|
||||
Err(_) => return Err(format!("{}: idle too long", peer.node)),
|
||||
Ok(None) => return Ok(peer.node),
|
||||
Ok(Some(bytes)) => bytes.map_err(|error| format!("{}: {error}", peer.node))?,
|
||||
};
|
||||
let revoked = shared
|
||||
.revocations
|
||||
.read()
|
||||
.map_or(true, |revocations| revocations.revokes_serial(&peer.serial));
|
||||
if revoked {
|
||||
return Err(format!("{}: its certificate was revoked", peer.node));
|
||||
}
|
||||
let packet = Packet::decode(&bytes).map_err(|error| format!("{}: {error}", peer.node))?;
|
||||
let failed = |why: String| format!("{}: {why}", peer.node);
|
||||
let answer = match packet {
|
||||
Packet::PushMessage(push) => self::push(shared, &peer, &mut frames, push)
|
||||
.await
|
||||
.map_err(failed)?,
|
||||
Packet::GetAttachment(get) => {
|
||||
match get_attachment(shared, &peer, &mut frames, get)
|
||||
.await
|
||||
.map_err(failed)?
|
||||
{
|
||||
Some(refusal) => refusal,
|
||||
None => continue,
|
||||
}
|
||||
}
|
||||
Packet::GetMessages(get) => get_messages(shared, &peer, get).await,
|
||||
Packet::ListNames(list) => list_names(shared, &peer, list).await,
|
||||
Packet::Query(query) => self::query(shared, &peer, query).await,
|
||||
Packet::SyncStateRequest(_) => accept_from::sync_state(shared, &mut peer).await,
|
||||
Packet::ReplicateMessages(batch) => {
|
||||
accept_from::replicate_messages(shared, &mut peer, batch).await
|
||||
}
|
||||
Packet::ReplicateAttachment(request) => {
|
||||
accept_from::replicate_attachment(shared, &mut peer, &mut frames, request)
|
||||
.await
|
||||
.map_err(|why| format!("{}: {why}", peer.node))?
|
||||
}
|
||||
other => {
|
||||
return Err(format!(
|
||||
"{}: sent {}, not a request",
|
||||
peer.node,
|
||||
other.packet_type().name()
|
||||
));
|
||||
}
|
||||
};
|
||||
send(&mut frames, answer)
|
||||
.await
|
||||
.map_err(|error| format!("{}: {error}", peer.node))?;
|
||||
}
|
||||
}
|
||||
|
||||
/// After a refused handshake (its alert sent): a close the client reads,
|
||||
/// not a reset that can beat the alert to it. In TLS 1.3 the client has
|
||||
/// already sent its version when the server refuses its certificate, and
|
||||
/// a socket closed with data unread is reset (Windows drops what the
|
||||
/// client hadn't read yet then). So: shut down, and read until the client
|
||||
/// closes, 1 s at most.
|
||||
async fn close_gently(mut tcp: TcpStream) {
|
||||
let _ = tcp.shutdown().await;
|
||||
let mut unread = [0; 1024];
|
||||
let _ = timeout(Duration::from_secs(1), async {
|
||||
while tcp.read(&mut unread).await.is_ok_and(|read| read > 0) {}
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
/// TLS, the versions, the identity, the welcome (or the refusal).
|
||||
async fn open(
|
||||
shared: &Arc<Shared>,
|
||||
tcp: TcpStream,
|
||||
address: IpAddr,
|
||||
) -> Result<(Frames, Peer), String> {
|
||||
let mut stream = match shared.acceptor.accept(tcp).into_fallible().await {
|
||||
Ok(stream) => stream,
|
||||
Err((error, tcp)) => {
|
||||
close_gently(tcp).await;
|
||||
return Err(format!("TLS: {error}"));
|
||||
}
|
||||
};
|
||||
|
||||
stream
|
||||
.write_all(&frame::version_bytes())
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
stream.flush().await.map_err(|error| error.to_string())?;
|
||||
let mut theirs = [0; frame::VERSION_SIZE];
|
||||
stream
|
||||
.read_exact(&mut theirs)
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
frame::check_version(theirs).map_err(|version| format!("speaks protocol {version}"))?;
|
||||
|
||||
let (_, connection) = stream.get_ref();
|
||||
let certificate = connection
|
||||
.peer_certificates()
|
||||
.and_then(<[_]>::first)
|
||||
.map(|certificate| certificate.to_vec())
|
||||
.unwrap_or_default();
|
||||
let identity = Identity::from_certificate(&certificate).map_err(|error| error.to_string())?;
|
||||
let serial = bakashrot_pki::serial(&certificate).map_err(|error| error.to_string())?;
|
||||
let mut frames = Framed::new(stream, frame::codec(MAX_PACKET_SIZE));
|
||||
|
||||
let Some(permissions) = shared.config.permissions(&identity.roles) else {
|
||||
let refused = RequestRefused::new(
|
||||
ErrorCode::NotAllowed,
|
||||
format!(
|
||||
"none of {}'s roles ({}) is allowed on this server",
|
||||
identity.name,
|
||||
identity.roles.join(", ")
|
||||
),
|
||||
);
|
||||
let _ = send(&mut frames, refused.into()).await;
|
||||
return Err(format!(
|
||||
"{}: refused, none of its roles is allowed",
|
||||
identity.name
|
||||
));
|
||||
};
|
||||
let welcome = Welcome {
|
||||
server: shared.name.clone(),
|
||||
node: identity.name.clone(),
|
||||
};
|
||||
send(&mut frames, welcome.into())
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
Ok((
|
||||
frames,
|
||||
Peer {
|
||||
node: identity.name,
|
||||
serial,
|
||||
permissions,
|
||||
address,
|
||||
accepted: None,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// A push, with its attachment's parts if it has one. An error closes the
|
||||
/// connection.
|
||||
async fn push(
|
||||
shared: &Arc<Shared>,
|
||||
peer: &Peer,
|
||||
frames: &mut Frames,
|
||||
push: PushMessage,
|
||||
) -> Result<Packet, String> {
|
||||
if !shared.config.server.has_topic(&push.topic) {
|
||||
return Ok(refused(
|
||||
ErrorCode::UnknownName,
|
||||
format!("unknown topic '{}'", push.topic),
|
||||
));
|
||||
}
|
||||
if !peer.permissions.can_push(&push.topic) {
|
||||
return Ok(refused(
|
||||
ErrorCode::NotAllowed,
|
||||
format!("{} may not push to '{}'", peer.node, push.topic),
|
||||
));
|
||||
}
|
||||
if push.data.len() > MAX_MESSAGE_SIZE {
|
||||
return Ok(refused(
|
||||
ErrorCode::TooBig,
|
||||
format!(
|
||||
"a message of {} bytes: {MAX_MESSAGE_SIZE} at most",
|
||||
push.data.len()
|
||||
),
|
||||
));
|
||||
}
|
||||
let PushMessage {
|
||||
topic,
|
||||
data,
|
||||
attachment,
|
||||
} = push;
|
||||
let Some(attachment) = attachment else {
|
||||
let write = Write::Push {
|
||||
topic,
|
||||
node: peer.node.clone(),
|
||||
pushed_at: now(),
|
||||
data,
|
||||
};
|
||||
return Ok(pushed(shared.pushes.send(write).await));
|
||||
};
|
||||
|
||||
let max = shared.config.server.max_attachment_size;
|
||||
if attachment.size > max {
|
||||
return Ok(refused(
|
||||
ErrorCode::TooBig,
|
||||
format!(
|
||||
"an attachment of {} bytes: {max} at most on this server",
|
||||
attachment.size
|
||||
),
|
||||
));
|
||||
}
|
||||
let start = Write::StartUpload {
|
||||
size: attachment.size,
|
||||
sha256: attachment.sha256,
|
||||
};
|
||||
let upload = match shared.pushes.send(start).await {
|
||||
Ok(upload) => upload,
|
||||
Err(refusal) => return Ok(refusal.into()),
|
||||
};
|
||||
let sha256 = digest::Context::new(&digest::SHA256);
|
||||
let received = match send(frames, Continue {}.into()).await {
|
||||
Ok(()) => receive_parts(shared, frames, upload, &attachment, 0, sha256).await,
|
||||
Err(error) => Err(error.to_string()),
|
||||
};
|
||||
let refusal = match received {
|
||||
Ok(None) => {
|
||||
let write = Write::PushWithUpload {
|
||||
upload,
|
||||
topic,
|
||||
node: peer.node.clone(),
|
||||
pushed_at: now(),
|
||||
data,
|
||||
};
|
||||
match shared.pushes.send(write).await {
|
||||
Ok(message_id) => return Ok(MessagePushed { message_id }.into()),
|
||||
Err(refusal) => Ok(refusal),
|
||||
}
|
||||
}
|
||||
Ok(Some(refusal)) => Ok(refusal),
|
||||
Err(why) => Err(why),
|
||||
};
|
||||
// Not pushed: the upload goes (queued after its parts).
|
||||
drop(shared.pushes.send(Write::CancelUpload { upload }));
|
||||
refusal.map(Packet::from)
|
||||
}
|
||||
|
||||
/// Reads an attachment's parts from `from_part` on (an upload's, or a
|
||||
/// replicated one's), has the writer store them while the next ones come,
|
||||
/// checks the SHA-256 (`sha256` has the parts before): the refusal if one
|
||||
/// is due (the parts all read even then; `DataMismatch` for the SHA-256),
|
||||
/// an error if the connection must close.
|
||||
pub(crate) async fn receive_parts(
|
||||
shared: &Arc<Shared>,
|
||||
frames: &mut Frames,
|
||||
upload: u64,
|
||||
attachment: &Attachment,
|
||||
from_part: u64,
|
||||
mut sha256: digest::Context,
|
||||
) -> Result<Option<RequestRefused>, String> {
|
||||
let mut writing = VecDeque::new();
|
||||
let mut refusal = None;
|
||||
for part in from_part..attachment.part_count() {
|
||||
let bytes = match timeout(PART_TIMEOUT, frames.next()).await {
|
||||
Err(_) => return Err(format!("part {part} of an attachment: too slow")),
|
||||
Ok(None) => return Err(format!("closed at part {part} of an attachment")),
|
||||
Ok(Some(bytes)) => bytes.map_err(|error| error.to_string())?,
|
||||
};
|
||||
let Packet::AttachmentPart(AttachmentPart { data }) =
|
||||
Packet::decode(&bytes).map_err(|error| error.to_string())?
|
||||
else {
|
||||
return Err(format!(
|
||||
"sent something else than part {part} of an attachment"
|
||||
));
|
||||
};
|
||||
if refusal.is_some() {
|
||||
continue;
|
||||
}
|
||||
let expected = attachment.part_len(part);
|
||||
if data.len() as u64 != expected {
|
||||
refusal = Some(RequestRefused::new(
|
||||
ErrorCode::InvalidRequest,
|
||||
format!("part {part}: {} bytes, {expected} expected", data.len()),
|
||||
));
|
||||
continue;
|
||||
}
|
||||
sha256.update(&data);
|
||||
writing.push_back(shared.pushes.send(Write::Part { upload, part, data }));
|
||||
if writing.len() >= PARTS_IN_FLIGHT
|
||||
&& let Some(written) = writing.pop_front()
|
||||
&& let Err(refused) = written.await
|
||||
{
|
||||
refusal = Some(refused);
|
||||
}
|
||||
}
|
||||
for written in writing {
|
||||
if let Err(refused) = written.await {
|
||||
refusal.get_or_insert(refused);
|
||||
}
|
||||
}
|
||||
if refusal.is_none() && sha256.finish().as_ref() != attachment.sha256 {
|
||||
refusal = Some(RequestRefused::new(
|
||||
ErrorCode::DataMismatch,
|
||||
"the attachment doesn't match its SHA-256",
|
||||
));
|
||||
}
|
||||
Ok(refusal)
|
||||
}
|
||||
|
||||
/// A message's attachment: its size and SHA-256, then its parts from
|
||||
/// `from_part`, sent here; or the refusal to send. An error (a part that
|
||||
/// can't be read, the connection) closes the connection: the client asks
|
||||
/// again from the part it lacks.
|
||||
async fn get_attachment(
|
||||
shared: &Arc<Shared>,
|
||||
peer: &Peer,
|
||||
frames: &mut Frames,
|
||||
get: GetAttachment,
|
||||
) -> Result<Option<Packet>, String> {
|
||||
if !peer.permissions.can_read(&get.topic) {
|
||||
return Ok(Some(refused(
|
||||
ErrorCode::NotAllowed,
|
||||
format!("{} may not read '{}'", peer.node, get.topic),
|
||||
)));
|
||||
}
|
||||
if !shared.config.server.has_topic(&get.topic) {
|
||||
return Ok(Some(refused(
|
||||
ErrorCode::UnknownName,
|
||||
format!("unknown topic '{}'", get.topic),
|
||||
)));
|
||||
}
|
||||
let message = format!("{}:{}#{}", get.topic, get.node, get.message_id);
|
||||
let GetAttachment {
|
||||
topic,
|
||||
node,
|
||||
message_id,
|
||||
from_part,
|
||||
} = get;
|
||||
let found = shared
|
||||
.read(move |reader| reader.attachment(&topic, &node, message_id))
|
||||
.await;
|
||||
let stored = match found {
|
||||
Ok(Some(stored)) => stored,
|
||||
Ok(None) => {
|
||||
return Ok(Some(refused(
|
||||
ErrorCode::NotFound,
|
||||
format!("no attachment for {message}"),
|
||||
)));
|
||||
}
|
||||
Err(refusal) => return Ok(Some(refusal.into())),
|
||||
};
|
||||
let not_here = match stored.state {
|
||||
AttachmentState::Ready => None,
|
||||
AttachmentState::TooBig => Some((
|
||||
ErrorCode::TooBig,
|
||||
"bigger than this server keeps: get it from another one",
|
||||
)),
|
||||
AttachmentState::Replicating => Some((ErrorCode::NotReady, "isn't on this server yet")),
|
||||
AttachmentState::Uploading | AttachmentState::Deleting => {
|
||||
Some((ErrorCode::NotFound, "isn't there any more"))
|
||||
}
|
||||
};
|
||||
if let Some((code, why)) = not_here {
|
||||
return Ok(Some(refused(
|
||||
code,
|
||||
format!("the attachment of {message} {why}"),
|
||||
)));
|
||||
}
|
||||
let attachment = Attachment {
|
||||
size: stored.size,
|
||||
sha256: stored.sha256,
|
||||
};
|
||||
let count = attachment.part_count();
|
||||
if from_part >= count {
|
||||
return Ok(Some(refused(
|
||||
ErrorCode::InvalidRequest,
|
||||
format!("from part {from_part}: the attachment of {message} has {count}"),
|
||||
)));
|
||||
}
|
||||
send(frames, attachment.into())
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
for part in from_part..count {
|
||||
let data = shared
|
||||
.read(move |reader| reader.read_part(stored.id, part))
|
||||
.await
|
||||
.map_err(|refusal| format!("part {part} of {message}: {}", refusal.reason))?;
|
||||
send(frames, AttachmentPart { data }.into())
|
||||
.await
|
||||
.map_err(|error| error.to_string())?;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// A push's answer.
|
||||
fn pushed(outcome: crate::writer::Outcome) -> Packet {
|
||||
match outcome {
|
||||
Ok(message_id) => MessagePushed { message_id }.into(),
|
||||
Err(refusal) => refusal.into(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_messages(shared: &Arc<Shared>, peer: &Peer, get: GetMessages) -> Packet {
|
||||
if !peer.permissions.can_read(&get.topic) {
|
||||
return refused(
|
||||
ErrorCode::NotAllowed,
|
||||
format!("{} may not read '{}'", peer.node, get.topic),
|
||||
);
|
||||
}
|
||||
if !shared.config.server.has_topic(&get.topic) {
|
||||
return refused(
|
||||
ErrorCode::UnknownName,
|
||||
format!("unknown topic '{}'", get.topic),
|
||||
);
|
||||
}
|
||||
let GetMessages {
|
||||
topic,
|
||||
node,
|
||||
after,
|
||||
limit,
|
||||
} = get;
|
||||
// Its own node is known even before its first push.
|
||||
let own = names_equal(&node, &peer.node);
|
||||
match shared
|
||||
.read(move |reader| reader.messages(&topic, &node, after, limit))
|
||||
.await
|
||||
{
|
||||
Ok(messages) => messages.into(),
|
||||
Err(refused) if own && refused.code == ErrorCode::UnknownName.code() => Messages {
|
||||
more: false,
|
||||
messages: Vec::new(),
|
||||
}
|
||||
.into(),
|
||||
Err(refused) => refused.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Topics: the server's, those it may push to or read unless it may query
|
||||
/// (queries read everything). Nodes: every one with messages.
|
||||
async fn list_names(shared: &Arc<Shared>, peer: &Peer, list: ListNames) -> Packet {
|
||||
let mut names = match list.kind {
|
||||
NameKind::Topic => shared
|
||||
.config
|
||||
.server
|
||||
.topics
|
||||
.iter()
|
||||
.filter(|topic| {
|
||||
peer.permissions.can_query()
|
||||
|| peer.permissions.can_push(topic)
|
||||
|| peer.permissions.can_read(topic)
|
||||
})
|
||||
.cloned()
|
||||
.collect(),
|
||||
NameKind::Node => match shared.read(|reader| reader.nodes()).await {
|
||||
Ok(nodes) => nodes,
|
||||
Err(refused) => return refused.into(),
|
||||
},
|
||||
};
|
||||
let truncated = names.len() > MAX_NAMES_LIST_ENTRIES;
|
||||
names.truncate(MAX_NAMES_LIST_ENTRIES);
|
||||
NamesList {
|
||||
kind: list.kind,
|
||||
truncated,
|
||||
names,
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
async fn query(shared: &Arc<Shared>, peer: &Peer, query: Query) -> Packet {
|
||||
if !peer.permissions.can_query() {
|
||||
return refused(
|
||||
ErrorCode::NotAllowed,
|
||||
format!("{} may not run queries", peer.node),
|
||||
);
|
||||
}
|
||||
match shared.query(query.sql).await {
|
||||
Ok(json) => QueryResult { json }.into(),
|
||||
Err(refused) => refused.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn refused(code: ErrorCode, reason: String) -> Packet {
|
||||
RequestRefused::new(code, reason).into()
|
||||
}
|
||||
|
||||
pub(crate) async fn send(frames: &mut Frames, packet: Packet) -> std::io::Result<()> {
|
||||
frames.send(bytes::Bytes::from(packet.encode())).await
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
//! BakaShrot's server: takes TLS connections from the CA's clients and
|
||||
//! peers, knows each by its certificate (its node, its roles), and answers
|
||||
//! their requests from the database.
|
||||
//!
|
||||
//! - [`Server::start`]: reads the certificates, opens the database, starts
|
||||
//! the writer's thread.
|
||||
//! - [`Server::serve`]: takes connections, a task each
|
||||
//! (`connection.rs`); pushes go to the writer's thread (`writer.rs`),
|
||||
//! reads and queries to pools of connections.
|
||||
//! - [`Server::watch_revocations`]: reloads the CRL file when it changes;
|
||||
//! a revoked certificate's connection is dropped at its next request.
|
||||
//! - [`Server::apply_retention`]: deletes messages past their topic's age
|
||||
//! (`retention.rs`).
|
||||
//! - [`Server::replicate`]: sends what the servers of `push_to` lack
|
||||
//! (`push_to.rs`); those dialing in, if in `accept_from`, are answered
|
||||
//! by `accept_from.rs`.
|
||||
//! - [`Server::stop`]: commits what was queued for the writer, refuses
|
||||
//! the rest.
|
||||
|
||||
mod accept_from;
|
||||
mod connection;
|
||||
mod push_to;
|
||||
mod retention;
|
||||
mod writer;
|
||||
|
||||
use bakashrot_config::Config;
|
||||
use bakashrot_pki::{Revocations, SharedRevocations, summarize, tls};
|
||||
use bakashrot_proto::ErrorCode;
|
||||
use bakashrot_proto::packets::RequestRefused;
|
||||
use bakashrot_storage::{Database, QueryRunner, Reader};
|
||||
use std::net::SocketAddr;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_rustls::{TlsAcceptor, TlsConnector};
|
||||
use tracing::{info, warn};
|
||||
use writer::Pushes;
|
||||
|
||||
/// How often the CRL file is looked at.
|
||||
const CRL_POLL: Duration = Duration::from_secs(5);
|
||||
|
||||
/// How often the WAL is checkpointed.
|
||||
const CHECKPOINT_INTERVAL: Duration = Duration::from_secs(1);
|
||||
|
||||
/// A server, ready to take connections.
|
||||
#[derive(Clone)]
|
||||
pub struct Server {
|
||||
shared: Arc<Shared>,
|
||||
}
|
||||
|
||||
/// What every connection uses.
|
||||
struct Shared {
|
||||
config: Config,
|
||||
/// The server's own name: its certificate's.
|
||||
name: String,
|
||||
acceptor: TlsAcceptor,
|
||||
/// To dial the servers of `push_to`.
|
||||
connector: TlsConnector,
|
||||
revocations: SharedRevocations,
|
||||
/// The CA's certificate, to check CRLs with.
|
||||
ca: String,
|
||||
database: Database,
|
||||
pushes: Pushes,
|
||||
/// Read connections not in use.
|
||||
readers: Mutex<Vec<Reader>>,
|
||||
/// Query connections not in use.
|
||||
queries: Mutex<Vec<QueryRunner>>,
|
||||
}
|
||||
|
||||
impl Server {
|
||||
/// Reads the server's certificates and CRL, opens its database, starts
|
||||
/// its writer. Errors say which file and why.
|
||||
pub fn start(config: Config) -> Result<Server, String> {
|
||||
let server = &config.server;
|
||||
let ca = read(&server.ca)?;
|
||||
let certificate = read(&server.certificate)?;
|
||||
let key = read(&server.key)?;
|
||||
let name = summarize(&certificate)
|
||||
.ok()
|
||||
.and_then(|summary| summary.identity)
|
||||
.map(|identity| identity.name)
|
||||
.ok_or_else(|| {
|
||||
format!(
|
||||
"{}: not a BakaShrot certificate",
|
||||
server.certificate.display()
|
||||
)
|
||||
})?;
|
||||
let revocations = load_revocations(server.crl.as_deref(), &ca)?.shared();
|
||||
let tls = tls::server_config(&ca, &certificate, &key, revocations.clone())
|
||||
.map_err(|error| format!("the server's TLS: {error}"))?;
|
||||
let dialing = tls::client_config(&ca, &certificate, &key, revocations.clone())
|
||||
.map_err(|error| format!("the TLS to peers: {error}"))?;
|
||||
let database = Database::open(&server.database, server.synchronous)
|
||||
.map_err(|error| error.to_string())?;
|
||||
let pushes = Pushes::start(database.writer().map_err(|error| error.to_string())?)
|
||||
.map_err(|error| format!("the writer's thread: {error}"))?;
|
||||
start_checkpoints(&database)?;
|
||||
Ok(Server {
|
||||
shared: Arc::new(Shared {
|
||||
name,
|
||||
acceptor: TlsAcceptor::from(tls),
|
||||
connector: TlsConnector::from(dialing),
|
||||
revocations,
|
||||
ca,
|
||||
database,
|
||||
pushes,
|
||||
readers: Mutex::new(Vec::new()),
|
||||
queries: Mutex::new(Vec::new()),
|
||||
config,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
/// The server's name: its certificate's.
|
||||
pub fn name(&self) -> &str {
|
||||
&self.shared.name
|
||||
}
|
||||
|
||||
/// Where the config says to listen.
|
||||
pub fn listen(&self) -> SocketAddr {
|
||||
self.shared.config.server.listen
|
||||
}
|
||||
|
||||
/// Takes connections on `listener`, each in a task of its own, until
|
||||
/// the listener fails.
|
||||
pub async fn serve(&self, listener: TcpListener) -> std::io::Result<()> {
|
||||
loop {
|
||||
let (tcp, peer) = listener.accept().await?;
|
||||
tokio::spawn(connection::handle(self.shared.clone(), tcp, peer));
|
||||
}
|
||||
}
|
||||
|
||||
/// Reloads the CRL file whenever it changes (its time or size, looked
|
||||
/// at every few seconds). A CRL that can't be read or isn't the CA's is
|
||||
/// refused: the previous one stays. Never returns.
|
||||
pub async fn watch_revocations(&self) {
|
||||
let Some(path) = self.shared.config.server.crl.clone() else {
|
||||
return std::future::pending().await;
|
||||
};
|
||||
let mut seen = stamp(&path);
|
||||
loop {
|
||||
tokio::time::sleep(CRL_POLL).await;
|
||||
let now = stamp(&path);
|
||||
if now != seen {
|
||||
seen = now;
|
||||
match self.reload_revocations() {
|
||||
Ok(count) => info!("{}: reloaded, {count} revoked", path.display()),
|
||||
Err(error) => warn!("{error}: the previous CRL stays"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deletes each topic's messages past its age (`[retention]`), then
|
||||
/// their attachments: right away, then every `retention_interval`.
|
||||
/// Never returns.
|
||||
pub async fn apply_retention(&self) {
|
||||
retention::run(&self.shared).await
|
||||
}
|
||||
|
||||
/// Keeps a link to each server of `[replication] push_to`, sending
|
||||
/// each what it lacks (again at once after sending, after `sync_interval`
|
||||
/// when there was nothing). Never returns.
|
||||
pub async fn replicate(&self) {
|
||||
push_to::run(self.shared.clone()).await
|
||||
}
|
||||
|
||||
/// Stops writing: every write queued before is committed (and so
|
||||
/// answered), the ones after are refused (`ServerError`, the server
|
||||
/// stopping). Then the server can be dropped, its runtime stopped.
|
||||
pub async fn stop(&self) {
|
||||
self.shared.pushes.stop().await;
|
||||
}
|
||||
|
||||
/// Reloads the CRL file now: how many certificates it revokes.
|
||||
pub fn reload_revocations(&self) -> Result<usize, String> {
|
||||
let shared = &self.shared;
|
||||
let revocations = load_revocations(shared.config.server.crl.as_deref(), &shared.ca)?;
|
||||
let count = revocations.len();
|
||||
// A poisoned lock: the TLS checks refuse everyone, replace it all.
|
||||
match shared.revocations.write() {
|
||||
Ok(mut current) => *current = revocations,
|
||||
Err(poisoned) => *poisoned.into_inner() = revocations,
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
/// Runs `read` on a read connection, off the async threads.
|
||||
async fn read<T: Send + 'static>(
|
||||
self: &Arc<Self>,
|
||||
read: impl FnOnce(&Reader) -> bakashrot_storage::Result<T> + Send + 'static,
|
||||
) -> Result<T, RequestRefused> {
|
||||
self.pooled(|shared| &shared.readers, Database::reader, read)
|
||||
.await
|
||||
}
|
||||
|
||||
/// The SHA-256 of an attachment's stored `parts`, read back one at a
|
||||
/// time (to go on with more, or to compare).
|
||||
async fn hash_parts(
|
||||
self: &Arc<Self>,
|
||||
attachment_id: i64,
|
||||
parts: std::ops::Range<u64>,
|
||||
) -> Result<aws_lc_rs::digest::Context, RequestRefused> {
|
||||
let mut sha256 = aws_lc_rs::digest::Context::new(&aws_lc_rs::digest::SHA256);
|
||||
for part in parts {
|
||||
let data = self
|
||||
.read(move |reader| reader.read_part(attachment_id, part))
|
||||
.await?;
|
||||
sha256.update(&data);
|
||||
}
|
||||
Ok(sha256)
|
||||
}
|
||||
|
||||
/// Runs a client's SQL on a query connection, off the async threads.
|
||||
async fn query(self: &Arc<Self>, sql: String) -> Result<String, RequestRefused> {
|
||||
self.pooled(
|
||||
|shared| &shared.queries,
|
||||
Database::query_runner,
|
||||
move |runner: &QueryRunner| runner.run(&sql),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Runs `work` on an idle connection of `pool`, or a new one, then
|
||||
/// puts it back.
|
||||
async fn pooled<C: Send + 'static, T: Send + 'static>(
|
||||
self: &Arc<Self>,
|
||||
pool: fn(&Shared) -> &Mutex<Vec<C>>,
|
||||
open: fn(&Database) -> bakashrot_storage::Result<C>,
|
||||
work: impl FnOnce(&C) -> bakashrot_storage::Result<T> + Send + 'static,
|
||||
) -> Result<T, RequestRefused> {
|
||||
let shared = self.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let idle = pool(&shared).lock().ok().and_then(|mut idle| idle.pop());
|
||||
let connection = match idle {
|
||||
Some(connection) => connection,
|
||||
None => open(&shared.database).map_err(refusal)?,
|
||||
};
|
||||
let value = work(&connection).map_err(refusal);
|
||||
if let Ok(mut idle) = pool(&shared).lock() {
|
||||
idle.push(connection);
|
||||
}
|
||||
value
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|_| Err(server_error("a read failed")))
|
||||
}
|
||||
}
|
||||
|
||||
/// Checkpoints the WAL every second, on a thread and a connection of its
|
||||
/// own, so the writer doesn't do it in the middle of a commit (2.5 times
|
||||
/// the pushes: `docs/storage.md`, "Against the old storage").
|
||||
fn start_checkpoints(database: &Database) -> Result<(), String> {
|
||||
let checkpointer = database.checkpointer().map_err(|error| error.to_string())?;
|
||||
std::thread::Builder::new()
|
||||
.name("checkpoints".into())
|
||||
.spawn(move || {
|
||||
loop {
|
||||
std::thread::sleep(CHECKPOINT_INTERVAL);
|
||||
if let Err(error) = checkpointer.checkpoint() {
|
||||
warn!("checkpointing the database: {error}");
|
||||
}
|
||||
}
|
||||
})
|
||||
.map(|_| ())
|
||||
.map_err(|error| format!("the checkpoints' thread: {error}"))
|
||||
}
|
||||
|
||||
/// A storage error as the refusal clients get.
|
||||
fn refusal(error: bakashrot_storage::Error) -> RequestRefused {
|
||||
use bakashrot_storage::Error;
|
||||
let code = match &error {
|
||||
Error::Invalid(_) => ErrorCode::InvalidRequest,
|
||||
Error::NotFound(_) => ErrorCode::NotFound,
|
||||
Error::UnknownName(_) => ErrorCode::UnknownName,
|
||||
Error::TooBig(_) => ErrorCode::TooBig,
|
||||
Error::Query(_) => ErrorCode::QueryFailed,
|
||||
Error::Sqlite(_) | Error::Unusable(_) => {
|
||||
warn!("the database: {error}");
|
||||
return server_error("the database failed");
|
||||
}
|
||||
};
|
||||
RequestRefused::new(code, error.to_string())
|
||||
}
|
||||
|
||||
fn server_error(reason: &str) -> RequestRefused {
|
||||
RequestRefused::new(ErrorCode::ServerError, reason)
|
||||
}
|
||||
|
||||
fn read(path: &Path) -> Result<String, String> {
|
||||
std::fs::read_to_string(path).map_err(|error| format!("{}: {error}", path.display()))
|
||||
}
|
||||
|
||||
/// The CRL file's revocations; none without one (no file, or not set).
|
||||
fn load_revocations(path: Option<&Path>, ca: &str) -> Result<Revocations, String> {
|
||||
let Some(path) = path.filter(|path| path.exists()) else {
|
||||
return Ok(Revocations::none());
|
||||
};
|
||||
Revocations::load(&read(path)?, ca).map_err(|error| format!("{}: {error}", path.display()))
|
||||
}
|
||||
|
||||
/// Now, in ms since 1970 UTC: when a message is pushed.
|
||||
fn now() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_or(0, |since| since.as_millis() as u64)
|
||||
}
|
||||
|
||||
/// A file's time and size, to see it changed.
|
||||
fn stamp(path: &Path) -> Option<(SystemTime, u64)> {
|
||||
let metadata = std::fs::metadata(path).ok()?;
|
||||
Some((metadata.modified().ok()?, metadata.len()))
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
//! `bakashrot-server <config.toml>`: runs a server until it's told to stop
|
||||
//! (SIGTERM or SIGINT on Linux; Ctrl+C, Ctrl+Break or its console closed
|
||||
//! on Windows), then stops cleanly: what was queued for the database is
|
||||
//! committed first.
|
||||
//!
|
||||
//! Logs go to the console (stdout), `BAKASHROT_LOG` sets their level
|
||||
//! (`error`, `warn`, `info` by default, `debug`, `trace`).
|
||||
|
||||
use bakashrot_config::Config;
|
||||
use bakashrot_server::Server;
|
||||
use std::io::IsTerminal;
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
use tokio::net::TcpListener;
|
||||
use tracing::level_filters::LevelFilter;
|
||||
use tracing::{error, info};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> ExitCode {
|
||||
let level = std::env::var("BAKASHROT_LOG").ok();
|
||||
let filter = level.as_deref().map_or(Ok(LevelFilter::INFO), str::parse);
|
||||
tracing_subscriber::fmt()
|
||||
.with_target(false)
|
||||
.with_max_level(*filter.as_ref().unwrap_or(&LevelFilter::INFO))
|
||||
// No colour codes in a file or a journal.
|
||||
.with_ansi(std::io::stdout().is_terminal())
|
||||
.init();
|
||||
if filter.is_err() {
|
||||
error!("BAKASHROT_LOG: not a level (error, warn, info, debug, trace), logging info");
|
||||
}
|
||||
let Some(path) = std::env::args_os().nth(1).map(PathBuf::from) else {
|
||||
eprintln!("usage: bakashrot-server <config.toml>");
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
match run(&path).await {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(why) => {
|
||||
error!("{why}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run(path: &std::path::Path) -> Result<(), String> {
|
||||
let config = Config::load(path).map_err(|error| error.to_string())?;
|
||||
let server = Server::start(config)?;
|
||||
let listener = TcpListener::bind(server.listen())
|
||||
.await
|
||||
.map_err(|error| format!("listening on {}: {error}", server.listen()))?;
|
||||
info!("{} listening on {}", server.name(), server.listen());
|
||||
let outcome = tokio::select! {
|
||||
served = server.serve(listener) => served.map_err(|error| format!("accepting: {error}")),
|
||||
_ = server.watch_revocations() => Ok(()),
|
||||
_ = server.apply_retention() => Ok(()),
|
||||
_ = server.replicate() => Ok(()),
|
||||
signal = stop_signal() => {
|
||||
info!("{}, stopping", signal?);
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
server.stop().await;
|
||||
info!("stopped");
|
||||
outcome
|
||||
}
|
||||
|
||||
/// The first stop signal: its name.
|
||||
#[cfg(unix)]
|
||||
async fn stop_signal() -> Result<&'static str, String> {
|
||||
use tokio::signal::unix::{SignalKind, signal};
|
||||
let listen = |kind| signal(kind).map_err(|error| format!("listening for signals: {error}"));
|
||||
let (mut terminate, mut interrupt) = (
|
||||
listen(SignalKind::terminate())?,
|
||||
listen(SignalKind::interrupt())?,
|
||||
);
|
||||
Ok(tokio::select! {
|
||||
_ = terminate.recv() => "SIGTERM",
|
||||
_ = interrupt.recv() => "SIGINT",
|
||||
})
|
||||
}
|
||||
|
||||
/// The first stop signal: its name. Closing the console leaves a few
|
||||
/// seconds before Windows ends the process, enough to commit.
|
||||
#[cfg(windows)]
|
||||
async fn stop_signal() -> Result<&'static str, String> {
|
||||
use tokio::signal::windows;
|
||||
let failed = |error: std::io::Error| format!("listening for Ctrl+C: {error}");
|
||||
let mut c = windows::ctrl_c().map_err(failed)?;
|
||||
let mut r#break = windows::ctrl_break().map_err(failed)?;
|
||||
let mut close = windows::ctrl_close().map_err(failed)?;
|
||||
Ok(tokio::select! {
|
||||
_ = c.recv() => "Ctrl+C",
|
||||
_ = r#break.recv() => "Ctrl+Break",
|
||||
_ = close.recv() => "the console closed",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
//! Replication's sending end: a link to each server of
|
||||
//! `[replication] push_to`, kept up (dialed again after `retry_delay`).
|
||||
//! It checks in: asks what the other server takes and has (`SyncState`),
|
||||
//! sends the messages it lacks, by topic and node name, then the
|
||||
//! attachments it lacks; again at once if it sent any (it keeps up under
|
||||
//! load), after `sync_interval` otherwise. Only what the other server's roles'
|
||||
//! `send_*` allow. `accept_from.rs` is the other end.
|
||||
|
||||
use crate::Shared;
|
||||
use crate::writer::Write;
|
||||
use bakashrot_config::Permissions;
|
||||
use bakashrot_pki::tls;
|
||||
use bakashrot_proto::limits::{ALPN, MAX_PACKET_SIZE};
|
||||
use bakashrot_proto::names::{names_equal, pattern_matches};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, MissingAttachment, ReplicateAttachment, ReplicateMessages,
|
||||
SyncState, SyncStateRequest,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::task::JoinSet;
|
||||
use tokio::time::{sleep, timeout};
|
||||
use tokio_rustls::client::TlsStream;
|
||||
use tokio_util::codec::{Framed, LengthDelimitedCodec};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
/// How long connecting may take: TCP, TLS, the versions, the welcome.
|
||||
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
/// How long an answer may take.
|
||||
const ANSWER_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
|
||||
/// Keeps a link to each server of `push_to`. Never returns.
|
||||
pub(crate) async fn run(shared: Arc<Shared>) {
|
||||
let mut links = JoinSet::new();
|
||||
for address in &shared.config.replication.push_to {
|
||||
links.spawn(keep_linked(shared.clone(), address.clone()));
|
||||
}
|
||||
while links.join_next().await.is_some() {}
|
||||
std::future::pending().await
|
||||
}
|
||||
|
||||
/// Links to `address`, checks in until the link fails, then again after
|
||||
/// `retry_delay`. A failure is logged once until it changes.
|
||||
async fn keep_linked(shared: Arc<Shared>, address: String) {
|
||||
let replication = &shared.config.replication;
|
||||
let mut last_failure = String::new();
|
||||
loop {
|
||||
let failure = match Link::open(&shared, &address).await {
|
||||
Ok(mut link) => {
|
||||
info!("{address}: linked to {}", link.name);
|
||||
last_failure.clear();
|
||||
loop {
|
||||
match link.check_in(&shared).await {
|
||||
Ok(true) => {}
|
||||
Ok(false) => sleep(replication.sync_interval).await,
|
||||
Err(why) => break format!("{} ({address}): {why}", link.name),
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(why) => format!("{address}: {why}"),
|
||||
};
|
||||
if failure != last_failure {
|
||||
warn!("{failure}");
|
||||
last_failure = failure;
|
||||
}
|
||||
sleep(replication.retry_delay).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// A link to a server: what it is, what it may be sent.
|
||||
struct Link {
|
||||
frames: Framed<TlsStream<TcpStream>, LengthDelimitedCodec>,
|
||||
name: String,
|
||||
permissions: Permissions,
|
||||
/// Whether this check-in sent something it took.
|
||||
sent: bool,
|
||||
}
|
||||
|
||||
impl Link {
|
||||
async fn open(shared: &Shared, address: &str) -> Result<Link, String> {
|
||||
timeout(CONNECT_TIMEOUT, Link::connect(shared, address))
|
||||
.await
|
||||
.map_err(|_| "too slow to connect".to_owned())?
|
||||
}
|
||||
|
||||
/// TCP, TLS, the versions, its roles here, the welcome.
|
||||
async fn connect(shared: &Shared, address: &str) -> Result<Link, String> {
|
||||
let text = |error: std::io::Error| error.to_string();
|
||||
let tcp = TcpStream::connect(address).await.map_err(text)?;
|
||||
tcp.set_nodelay(true).map_err(text)?;
|
||||
let mut stream = shared
|
||||
.connector
|
||||
.connect(tls::server_name(), tcp)
|
||||
.await
|
||||
.map_err(|error| format!("TLS: {error}"))?;
|
||||
if stream.get_ref().1.alpn_protocol() != Some(ALPN) {
|
||||
return Err("not a BakaShrot server".into());
|
||||
}
|
||||
stream
|
||||
.write_all(&frame::version_bytes())
|
||||
.await
|
||||
.map_err(text)?;
|
||||
stream.flush().await.map_err(text)?;
|
||||
let mut theirs = [0; frame::VERSION_SIZE];
|
||||
stream.read_exact(&mut theirs).await.map_err(text)?;
|
||||
frame::check_version(theirs).map_err(|version| format!("speaks protocol {version}"))?;
|
||||
|
||||
let identity = tls::peer_identity(stream.get_ref().1.peer_certificates())
|
||||
.map_err(|error| error.to_string())?;
|
||||
let permissions = shared.config.permissions(&identity.roles).ok_or_else(|| {
|
||||
format!(
|
||||
"{}: none of its roles ({}) is in this server's config",
|
||||
identity.name,
|
||||
identity.roles.join(", ")
|
||||
)
|
||||
})?;
|
||||
let mut link = Link {
|
||||
frames: Framed::new(stream, frame::codec(MAX_PACKET_SIZE)),
|
||||
name: identity.name,
|
||||
permissions,
|
||||
sent: false,
|
||||
};
|
||||
match link.receive().await? {
|
||||
Packet::Welcome(_) => Ok(link),
|
||||
Packet::RequestRefused(refused) => Err(format!("refused: {}", refused.reason)),
|
||||
other => Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
|
||||
/// One check-in: what it lacks, the messages then the attachments.
|
||||
/// Whether it sent something it took.
|
||||
async fn check_in(&mut self, shared: &Arc<Shared>) -> Result<bool, String> {
|
||||
self.sent = false;
|
||||
let state = match self.ask(SyncStateRequest {}.into()).await? {
|
||||
Packet::SyncState(state) => state,
|
||||
Packet::RequestRefused(refused) => return Err(format!("refused: {}", refused.reason)),
|
||||
other => return Err(unexpected(&other)),
|
||||
};
|
||||
let heads = shared
|
||||
.read(|reader| reader.heads())
|
||||
.await
|
||||
.map_err(|refused| refused.reason)?;
|
||||
let theirs: HashMap<(String, String), u64> = state
|
||||
.heads
|
||||
.iter()
|
||||
.map(|head| (key(&head.topic, &head.node), head.last_id))
|
||||
.collect();
|
||||
for head in heads {
|
||||
let (topic, node) = (head.topic, head.node);
|
||||
if !self.sends(&state, &topic, &node) {
|
||||
continue;
|
||||
}
|
||||
let after = theirs.get(&key(&topic, &node)).copied().unwrap_or(0);
|
||||
if after < head.last_id {
|
||||
self.send_messages(shared, topic, node, after).await?;
|
||||
}
|
||||
}
|
||||
for missing in state.missing {
|
||||
if self.permissions.sends(&missing.topic, &missing.node) {
|
||||
self.send_attachment(shared, missing).await?;
|
||||
}
|
||||
}
|
||||
Ok(self.sent)
|
||||
}
|
||||
|
||||
/// Whether it takes `node`'s messages in `topic` (its `SyncState`) and
|
||||
/// may be sent them (its roles here).
|
||||
fn sends(&self, state: &SyncState, topic: &str, node: &str) -> bool {
|
||||
let listed = |list: &[String], name: &str| {
|
||||
list.iter()
|
||||
.any(|entry| names_equal(entry, name) || pattern_matches(entry, name))
|
||||
};
|
||||
listed(&state.topics, topic)
|
||||
&& listed(&state.nodes, node)
|
||||
&& self.permissions.sends(topic, node)
|
||||
}
|
||||
|
||||
/// A topic and node's messages after `after`, in batches. A refusal
|
||||
/// leaves them for the next check-in.
|
||||
async fn send_messages(
|
||||
&mut self,
|
||||
shared: &Arc<Shared>,
|
||||
topic: String,
|
||||
node: String,
|
||||
mut after: u64,
|
||||
) -> Result<(), String> {
|
||||
let limit = shared.config.replication.batch_size;
|
||||
loop {
|
||||
let (t, n) = (topic.clone(), node.clone());
|
||||
let messages = shared
|
||||
.read(move |reader| reader.to_replicate(&t, &n, after, limit))
|
||||
.await
|
||||
.map_err(|refused| refused.reason)?;
|
||||
let Some(last) = messages.last().map(|message| message.id) else {
|
||||
return Ok(());
|
||||
};
|
||||
let batch = ReplicateMessages {
|
||||
topic: topic.clone(),
|
||||
node: node.clone(),
|
||||
messages,
|
||||
};
|
||||
match self.ask(batch.into()).await? {
|
||||
Packet::MessagePushed(_) => {
|
||||
after = last;
|
||||
self.sent = true;
|
||||
}
|
||||
Packet::RequestRefused(refused) => {
|
||||
debug!("{}: {topic}:{node} refused: {}", self.name, refused.reason);
|
||||
return Ok(());
|
||||
}
|
||||
other => return Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An attachment it lacks, from the part it needs, if this server has
|
||||
/// it. One it says doesn't match its SHA-256 is checked here: a
|
||||
/// damaged copy is asked for again from this server's own peers.
|
||||
async fn send_attachment(
|
||||
&mut self,
|
||||
shared: &Arc<Shared>,
|
||||
missing: MissingAttachment,
|
||||
) -> Result<(), String> {
|
||||
let message = format!("{}:{}#{}", missing.topic, missing.node, missing.message_id);
|
||||
let (topic, node, id) = (
|
||||
missing.topic.clone(),
|
||||
missing.node.clone(),
|
||||
missing.message_id,
|
||||
);
|
||||
let stored = shared
|
||||
.read(move |reader| reader.attachment(&topic, &node, id))
|
||||
.await
|
||||
.map_err(|refused| refused.reason)?;
|
||||
let Some(stored) = stored.filter(|stored| stored.state == AttachmentState::Ready) else {
|
||||
return Ok(());
|
||||
};
|
||||
let attachment = Attachment {
|
||||
size: stored.size,
|
||||
sha256: stored.sha256,
|
||||
};
|
||||
let from_part = missing.next_part;
|
||||
if from_part >= attachment.part_count() {
|
||||
return Ok(());
|
||||
}
|
||||
let request = ReplicateAttachment {
|
||||
topic: missing.topic,
|
||||
node: missing.node,
|
||||
message_id: missing.message_id,
|
||||
from_part,
|
||||
};
|
||||
match self.ask(request.into()).await? {
|
||||
Packet::Continue(_) => {}
|
||||
Packet::RequestRefused(refused) => {
|
||||
debug!(
|
||||
"{}: {message}'s attachment refused: {}",
|
||||
self.name, refused.reason
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
other => return Err(unexpected(&other)),
|
||||
}
|
||||
for part in from_part..attachment.part_count() {
|
||||
// A part that can't be read: the link closes, it asks again.
|
||||
let data = shared
|
||||
.read(move |reader| reader.read_part(stored.id, part))
|
||||
.await
|
||||
.map_err(|refused| format!("part {part} of {message}: {}", refused.reason))?;
|
||||
self.send(AttachmentPart { data }.into()).await?;
|
||||
}
|
||||
match self.receive().await? {
|
||||
Packet::MessagePushed(_) => {
|
||||
debug!("{}: sent {message}'s attachment", self.name);
|
||||
self.sent = true;
|
||||
}
|
||||
Packet::RequestRefused(refused) if refused.code == ErrorCode::DataMismatch.code() => {
|
||||
check_own_copy(shared, stored.id, &attachment, &message).await
|
||||
}
|
||||
Packet::RequestRefused(refused) => debug!(
|
||||
"{}: {message}'s attachment refused: {}",
|
||||
self.name, refused.reason
|
||||
),
|
||||
other => return Err(unexpected(&other)),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn ask(&mut self, packet: Packet) -> Result<Packet, String> {
|
||||
self.send(packet).await?;
|
||||
self.receive().await
|
||||
}
|
||||
|
||||
async fn send(&mut self, packet: Packet) -> Result<(), String> {
|
||||
self.frames
|
||||
.send(bytes::Bytes::from(packet.encode()))
|
||||
.await
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
async fn receive(&mut self) -> Result<Packet, String> {
|
||||
match timeout(ANSWER_TIMEOUT, self.frames.next()).await {
|
||||
Err(_) => Err("no answer in time".into()),
|
||||
Ok(None) => Err("closed the link".into()),
|
||||
Ok(Some(bytes)) => {
|
||||
let bytes = bytes.map_err(|error| error.to_string())?;
|
||||
Packet::decode(&bytes).map_err(|error| error.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The other server said this server's copy doesn't match its SHA-256:
|
||||
/// read it back; damaged, it's asked for again from this server's peers
|
||||
/// (and not served meanwhile), instead of sent again and again.
|
||||
async fn check_own_copy(
|
||||
shared: &Arc<Shared>,
|
||||
attachment_id: i64,
|
||||
attachment: &Attachment,
|
||||
message: &str,
|
||||
) {
|
||||
let read = shared.hash_parts(attachment_id, 0..attachment.part_count());
|
||||
if let Ok(sha256) = read.await
|
||||
&& sha256.finish().as_ref() == attachment.sha256
|
||||
{
|
||||
return;
|
||||
}
|
||||
let damaged = Write::Damaged {
|
||||
attachment: attachment_id as u64,
|
||||
};
|
||||
match shared.pushes.send(damaged).await {
|
||||
Ok(_) => {
|
||||
warn!("{message}: this server's copy of its attachment is damaged, asked for again")
|
||||
}
|
||||
Err(refused) => warn!("{message}: a damaged attachment: {}", refused.reason),
|
||||
}
|
||||
}
|
||||
|
||||
/// A topic and node, to compare without case.
|
||||
fn key(topic: &str, node: &str) -> (String, String) {
|
||||
(topic.to_ascii_lowercase(), node.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
fn unexpected(packet: &Packet) -> String {
|
||||
format!("answered {}", packet.packet_type().name())
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
//! Retention: right away, then every `retention_interval`, each topic's
|
||||
//! messages past its age (`[retention]`) are deleted, then their
|
||||
//! attachments' parts. Every topic in the database, by its name (one no
|
||||
//! longer in `topics` too). Through the writer's queue, a batch at a time,
|
||||
//! so pushes go on in between.
|
||||
|
||||
use crate::Shared;
|
||||
use crate::writer::Write;
|
||||
use bakashrot_proto::packets::RequestRefused;
|
||||
use std::sync::Arc;
|
||||
use tracing::{info, warn};
|
||||
|
||||
/// Most messages deleted in one write.
|
||||
const MESSAGES_PER_WRITE: usize = 10_000;
|
||||
|
||||
/// Most attachment parts (1 MiB each) deleted in one write.
|
||||
const PARTS_PER_WRITE: usize = 64;
|
||||
|
||||
/// Deletes what's past its age at every interval. Never returns.
|
||||
pub(crate) async fn run(shared: &Arc<Shared>) {
|
||||
loop {
|
||||
if let Err(refused) = once(shared).await {
|
||||
warn!("retention: {}", refused.reason);
|
||||
}
|
||||
tokio::time::sleep(shared.config.server.retention_interval).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// One pass: every topic, then the attachments (also what a pass cut short
|
||||
/// left).
|
||||
async fn once(shared: &Arc<Shared>) -> Result<(), RequestRefused> {
|
||||
let now = crate::now();
|
||||
for topic in shared.read(|reader| reader.topics()).await? {
|
||||
let Some(age) = shared.config.retention.age(&topic) else {
|
||||
continue;
|
||||
};
|
||||
let cutoff = now.saturating_sub(age.as_millis() as u64);
|
||||
let deleted = repeat(shared, MESSAGES_PER_WRITE, |limit| Write::DeleteBefore {
|
||||
topic: topic.clone(),
|
||||
cutoff,
|
||||
limit,
|
||||
})
|
||||
.await?;
|
||||
if deleted > 0 {
|
||||
info!("deleted {deleted} messages of topic '{topic}'");
|
||||
}
|
||||
}
|
||||
repeat(shared, PARTS_PER_WRITE, |max_parts| {
|
||||
Write::PurgeAttachments { max_parts }
|
||||
})
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Sends `write(limit)` until one does less than `limit`: how many in all.
|
||||
async fn repeat(
|
||||
shared: &Shared,
|
||||
limit: usize,
|
||||
write: impl Fn(usize) -> Write,
|
||||
) -> Result<u64, RequestRefused> {
|
||||
let mut total = 0;
|
||||
loop {
|
||||
let count = shared.pushes.send(write(limit)).await?;
|
||||
total += count;
|
||||
if count < limit as u64 {
|
||||
return Ok(total);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
//! The writer's thread: every write goes through one queue, and the thread
|
||||
//! writes whatever is queued in one transaction (a group commit): the
|
||||
//! busier, the bigger the groups. [`Pushes::stop`] ends it once what was
|
||||
//! queued before is committed.
|
||||
|
||||
use crate::refusal;
|
||||
use bakashrot_proto::packets::{ReplicatedMessage, RequestRefused};
|
||||
use bakashrot_storage::{Batch, Writer};
|
||||
use std::sync::mpsc;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
/// Most writes in one transaction.
|
||||
const MAX_GROUP: usize = 1000;
|
||||
|
||||
/// A write's outcome: a number (a message's id, an upload's), or the
|
||||
/// refusal to answer.
|
||||
pub(crate) type Outcome = Result<u64, RequestRefused>;
|
||||
|
||||
/// What the writer does (`bakashrot_storage::Batch`'s).
|
||||
pub(crate) enum Write {
|
||||
/// A message: its id.
|
||||
Push {
|
||||
topic: String,
|
||||
node: String,
|
||||
pushed_at: u64,
|
||||
data: String,
|
||||
},
|
||||
/// An attachment's upload: its id.
|
||||
StartUpload { size: u64, sha256: [u8; 32] },
|
||||
/// An upload's next part: 1 if it was the last, 0 otherwise.
|
||||
Part {
|
||||
upload: u64,
|
||||
part: u64,
|
||||
data: Vec<u8>,
|
||||
},
|
||||
/// A message with its whole, checked upload: its id.
|
||||
PushWithUpload {
|
||||
upload: u64,
|
||||
topic: String,
|
||||
node: String,
|
||||
pushed_at: u64,
|
||||
data: String,
|
||||
},
|
||||
/// Drops an upload: 0.
|
||||
CancelUpload { upload: u64 },
|
||||
/// Retention: deletes a topic's messages pushed before `cutoff`,
|
||||
/// `limit` at most: how many.
|
||||
DeleteBefore {
|
||||
topic: String,
|
||||
cutoff: u64,
|
||||
limit: usize,
|
||||
},
|
||||
/// Deletes deleted messages' attachment parts, `max_parts` at most:
|
||||
/// how many.
|
||||
PurgeAttachments { max_parts: usize },
|
||||
/// A peer's messages: the topic and node's last id.
|
||||
Replicate {
|
||||
topic: String,
|
||||
node: String,
|
||||
messages: Vec<ReplicatedMessage>,
|
||||
max_attachment_size: u64,
|
||||
skip_before: u64,
|
||||
},
|
||||
/// A replicated attachment all of whose parts came: ready if it
|
||||
/// `matches` its SHA-256, started over otherwise. 0.
|
||||
FinishReplicated { attachment: u64, matches: bool },
|
||||
/// This server's own copy found damaged: asked for again. 0.
|
||||
Damaged { attachment: u64 },
|
||||
}
|
||||
|
||||
impl Write {
|
||||
fn run(&self, batch: &mut Batch<'_>) -> bakashrot_storage::Result<u64> {
|
||||
// Upload ids are SQLite rowids: positive.
|
||||
match self {
|
||||
Write::Push {
|
||||
topic,
|
||||
node,
|
||||
pushed_at,
|
||||
data,
|
||||
} => batch.push(topic, node, *pushed_at, data),
|
||||
Write::StartUpload { size, sha256 } => {
|
||||
batch.start_upload(*size, sha256).map(|id| id as u64)
|
||||
}
|
||||
Write::Part { upload, part, data } => {
|
||||
batch.write_part(*upload as i64, *part, data).map(u64::from)
|
||||
}
|
||||
Write::PushWithUpload {
|
||||
upload,
|
||||
topic,
|
||||
node,
|
||||
pushed_at,
|
||||
data,
|
||||
} => batch.push_with_attachment(*upload as i64, topic, node, *pushed_at, data),
|
||||
Write::CancelUpload { upload } => batch.cancel_upload(*upload as i64).map(|()| 0),
|
||||
Write::DeleteBefore {
|
||||
topic,
|
||||
cutoff,
|
||||
limit,
|
||||
} => batch
|
||||
.delete_before(topic, *cutoff, *limit)
|
||||
.map(|count| count as u64),
|
||||
Write::PurgeAttachments { max_parts } => batch
|
||||
.purge_attachments(*max_parts)
|
||||
.map(|count| count as u64),
|
||||
Write::Replicate {
|
||||
topic,
|
||||
node,
|
||||
messages,
|
||||
max_attachment_size,
|
||||
skip_before,
|
||||
} => batch.replicate(topic, node, messages, *max_attachment_size, *skip_before),
|
||||
Write::FinishReplicated {
|
||||
attachment,
|
||||
matches,
|
||||
} => batch
|
||||
.finish_replicated(*attachment as i64, *matches)
|
||||
.map(|()| 0),
|
||||
Write::Damaged { attachment } => batch.damaged(*attachment as i64).map(|()| 0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the writer's thread is sent.
|
||||
enum Job {
|
||||
Write {
|
||||
write: Write,
|
||||
done: oneshot::Sender<Outcome>,
|
||||
},
|
||||
/// Stop once the writes queued before are committed, then say so.
|
||||
Stop(oneshot::Sender<()>),
|
||||
}
|
||||
|
||||
/// The queue to the writer's thread.
|
||||
pub(crate) struct Pushes {
|
||||
queue: mpsc::Sender<Job>,
|
||||
}
|
||||
|
||||
impl Pushes {
|
||||
/// Starts the writer's thread on `writer`. It ends with the queue, or
|
||||
/// at [`Pushes::stop`].
|
||||
pub(crate) fn start(mut writer: Writer) -> std::io::Result<Pushes> {
|
||||
let (queue, pending) = mpsc::channel::<Job>();
|
||||
std::thread::Builder::new()
|
||||
.name("writer".into())
|
||||
.spawn(move || {
|
||||
while let Ok(first) = pending.recv() {
|
||||
let (mut group, mut stopped) = (Vec::new(), None);
|
||||
for job in std::iter::once(first).chain(pending.try_iter()) {
|
||||
match job {
|
||||
Job::Write { write, done } => group.push((write, done)),
|
||||
Job::Stop(done) => stopped = Some(done),
|
||||
}
|
||||
if stopped.is_some() || group.len() == MAX_GROUP {
|
||||
break;
|
||||
}
|
||||
}
|
||||
write(&mut writer, group);
|
||||
if let Some(done) = stopped {
|
||||
// Writes queued after are dropped with the queue,
|
||||
// refused as the server stopping.
|
||||
let _ = done.send(());
|
||||
return;
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(Pushes { queue })
|
||||
}
|
||||
|
||||
/// Stops the writer's thread once every write queued before is
|
||||
/// committed; the ones after are refused, the server stopping.
|
||||
pub(crate) async fn stop(&self) {
|
||||
let (done, stopped) = oneshot::channel();
|
||||
if self.queue.send(Job::Stop(done)).is_ok() {
|
||||
let _ = stopped.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Queues a write now (writes are done in the order queued), its
|
||||
/// outcome once its group is committed. Dropping the future doesn't
|
||||
/// take the write back.
|
||||
pub(crate) fn send(&self, write: Write) -> impl Future<Output = Outcome> + use<> {
|
||||
let (done, outcome) = oneshot::channel();
|
||||
let queued = self.queue.send(Job::Write { write, done });
|
||||
async move {
|
||||
queued.map_err(|_| stopped())?;
|
||||
outcome.await.unwrap_or_else(|_| Err(stopped()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes a group in one transaction, then answers each write.
|
||||
fn write(writer: &mut Writer, group: Vec<(Write, oneshot::Sender<Outcome>)>) {
|
||||
if group.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut outcomes = Vec::with_capacity(group.len());
|
||||
let committed = writer.batch(|batch| {
|
||||
for (write, _) in &group {
|
||||
outcomes.push(write.run(batch).map_err(refusal));
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
if let Err(error) = committed {
|
||||
let refused = refusal(error);
|
||||
outcomes = group.iter().map(|_| Err(refused.clone())).collect();
|
||||
}
|
||||
for ((_, done), outcome) in group.into_iter().zip(outcomes) {
|
||||
// Its connection may be gone: nothing to answer then.
|
||||
let _ = done.send(outcome);
|
||||
}
|
||||
}
|
||||
|
||||
fn stopped() -> RequestRefused {
|
||||
RequestRefused::new(
|
||||
bakashrot_proto::ErrorCode::ServerError,
|
||||
"the server is stopping",
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user