mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Paged SyncState, Added Ping, Required ALPN on the server, Capped retention ages, Closed idle database connections
- Protocol 8: SyncStateRequest takes `after` (a Pair), SyncState has `more` and 32768 heads at most (MAX_HEADS_PER_PACKET), the lists and missing attachments in the first page only; heads_after in storage, both ends of replication read in pages (step 17) - Protocol 8: Ping / Pong (19, 20) keep an idle connection open (IDLE_TIMEOUT_SECS 300, KEEPALIVE_SECS 60). Client::ping, BakaShrot_Ping, Python ping(), C# Ping(), the PureBasic prototype; the tool's --follow, Python's follow(), C#'s Follow() and the replication links ping every minute while waiting longer, so sync_interval over 5 min works now (dropped from known-issues.md) - The server closes a client offering no ALPN right after TLS: rustls only refused one offering other protocols - Retention ages are 100 years at most (MAX_RETENTION_AGE); the cutoff is computed once, saturating (Retention::cutoff): a huge age wrapped around to almost nothing in milliseconds - [server] idle_database_connections (8 by default, 0-512): the idle read and query connections each pool keeps, those unused for a minute closed by a sweeping thread - Tests for each, docs, the C header, revamp.md (step 18) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -5,9 +5,12 @@
|
||||
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::limits::{
|
||||
ATTACHMENT_PART_SIZE, MAX_HEADS_PER_PACKET, MAX_MESSAGE_SIZE, MAX_MISSING_ATTACHMENTS,
|
||||
};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, Continue, MessagePushed, ReplicateAttachment, ReplicateMessages, SyncState,
|
||||
Attachment, Continue, Head, MessagePushed, ReplicateAttachment, ReplicateMessages, SyncState,
|
||||
SyncStateRequest,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
@@ -111,27 +114,61 @@ async fn check(shared: &Shared, peer: &mut Peer, topic: &str, node: &str) -> Res
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// attachments it lacks among them: a page of it, the lists in the first.
|
||||
pub(crate) async fn sync_state(
|
||||
shared: &Arc<Shared>,
|
||||
peer: &mut Peer,
|
||||
request: SyncStateRequest,
|
||||
) -> 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));
|
||||
let first = request.after.is_none();
|
||||
let mut after = request.after.map(|pair| (pair.topic, pair.node));
|
||||
let (mut heads, mut more) = (Vec::new(), false);
|
||||
// Read in pages too, those it doesn't take from this peer skipped:
|
||||
// until the page is full and one more is found, or none is left.
|
||||
'pages: loop {
|
||||
let from = after.clone();
|
||||
let read = shared
|
||||
.read(move |reader| {
|
||||
let from = from.as_ref().map(|(t, n)| (t.as_str(), n.as_str()));
|
||||
reader.heads_after(from, MAX_HEADS_PER_PACKET)
|
||||
})
|
||||
.await;
|
||||
let read: Vec<Head> = match read {
|
||||
Ok(read) => read,
|
||||
Err(refusal) => return refusal.into(),
|
||||
};
|
||||
let last_page = read.len() < MAX_HEADS_PER_PACKET;
|
||||
after = read.last().map(|h| (h.topic.clone(), h.node.clone()));
|
||||
for head in read {
|
||||
if peer.permissions.accepts(&head.topic, &head.node) {
|
||||
if heads.len() == MAX_HEADS_PER_PACKET {
|
||||
more = true;
|
||||
break 'pages;
|
||||
}
|
||||
heads.push(head);
|
||||
}
|
||||
}
|
||||
if last_page {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let (mut topics, mut nodes, mut missing) = (Vec::new(), Vec::new(), Vec::new());
|
||||
if first {
|
||||
(topics, nodes) = peer.permissions.accepted();
|
||||
missing = match shared
|
||||
.read(|reader| reader.missing_attachments(MAX_MISSING_ATTACHMENTS))
|
||||
.await
|
||||
{
|
||||
Ok(missing) => missing,
|
||||
Err(refusal) => return refusal.into(),
|
||||
};
|
||||
missing.retain(|missing| peer.permissions.accepts(&missing.topic, &missing.node));
|
||||
}
|
||||
SyncState {
|
||||
more,
|
||||
topics,
|
||||
nodes,
|
||||
heads,
|
||||
@@ -163,8 +200,8 @@ pub(crate) async fn replicate_messages(
|
||||
let skip_before = shared
|
||||
.config
|
||||
.retention
|
||||
.age(&batch.topic)
|
||||
.map_or(0, |age| now().saturating_sub(age.as_millis() as u64));
|
||||
.cutoff(&batch.topic, now())
|
||||
.unwrap_or(0);
|
||||
let write = Write::Replicate {
|
||||
topic: batch.topic,
|
||||
node: batch.node,
|
||||
|
||||
@@ -6,11 +6,13 @@ 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::limits::{
|
||||
ALPN, IDLE_TIMEOUT_SECS, MAX_MESSAGE_SIZE, MAX_NAMES_LIST_ENTRIES, MAX_PACKET_SIZE,
|
||||
};
|
||||
use bakashrot_proto::names::{name_matches, names_equal};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, Continue, GetAttachment, GetMessages, ListNames, MessagePushed,
|
||||
Messages, NameKind, NamesList, PushMessage, Query, QueryResult, RequestRefused, Welcome,
|
||||
Messages, NameKind, NamesList, Pong, PushMessage, Query, QueryResult, RequestRefused, Welcome,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
@@ -29,8 +31,9 @@ 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 a connection may stay silent between requests (a `Ping`
|
||||
/// counts).
|
||||
const IDLE_TIMEOUT: Duration = Duration::from_secs(IDLE_TIMEOUT_SECS);
|
||||
|
||||
/// How long an attachment's next part may take to come.
|
||||
const PART_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
@@ -107,7 +110,10 @@ async fn serve(shared: &Arc<Shared>, tcp: TcpStream, address: IpAddr) -> Result<
|
||||
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::Ping(_) => Pong {}.into(),
|
||||
Packet::SyncStateRequest(request) => {
|
||||
accept_from::sync_state(shared, &mut peer, request).await
|
||||
}
|
||||
Packet::ReplicateMessages(batch) => {
|
||||
accept_from::replicate_messages(shared, &mut peer, batch).await
|
||||
}
|
||||
@@ -158,6 +164,12 @@ async fn open(
|
||||
return Err(format!("TLS: {error}"));
|
||||
}
|
||||
};
|
||||
// rustls refuses a client offering other protocols, not one offering
|
||||
// none: that one is refused here, before the versions.
|
||||
if stream.get_ref().1.alpn_protocol() != Some(ALPN) {
|
||||
let _ = stream.shutdown().await;
|
||||
return Err("TLS: no ALPN \"bakashrot\" offered, not a BakaShrot client".into());
|
||||
}
|
||||
|
||||
stream
|
||||
.write_all(&frame::version_bytes())
|
||||
|
||||
@@ -31,8 +31,8 @@ use bakashrot_storage::{Database, QueryRunner, Reader};
|
||||
use std::collections::HashSet;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::Path;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_rustls::{TlsAcceptor, TlsConnector};
|
||||
use tracing::{info, warn};
|
||||
@@ -44,6 +44,12 @@ const CRL_POLL: Duration = Duration::from_secs(5);
|
||||
/// How often the WAL is checkpointed.
|
||||
const CHECKPOINT_INTERVAL: Duration = Duration::from_secs(1);
|
||||
|
||||
/// How long an idle database connection is kept before it's closed.
|
||||
const POOL_IDLE: Duration = Duration::from_secs(60);
|
||||
|
||||
/// How often the idle database connections are looked at.
|
||||
const POOL_SWEEP: Duration = Duration::from_secs(10);
|
||||
|
||||
/// A server, ready to take connections.
|
||||
#[derive(Clone)]
|
||||
pub struct Server {
|
||||
@@ -64,9 +70,9 @@ struct Shared {
|
||||
database: Database,
|
||||
pushes: Pushes,
|
||||
/// Read connections not in use.
|
||||
readers: Mutex<Vec<Reader>>,
|
||||
readers: Pool<Reader>,
|
||||
/// Query connections not in use.
|
||||
queries: Mutex<Vec<QueryRunner>>,
|
||||
queries: Pool<QueryRunner>,
|
||||
/// The replicated attachments being received (topic, node, message
|
||||
/// id): one peer at a time each (`accept_from.rs`).
|
||||
receiving: Mutex<HashSet<(String, String, u64)>>,
|
||||
@@ -101,21 +107,21 @@ impl Server {
|
||||
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()),
|
||||
receiving: Mutex::new(HashSet::new()),
|
||||
config,
|
||||
}),
|
||||
})
|
||||
let shared = Arc::new(Shared {
|
||||
name,
|
||||
acceptor: TlsAcceptor::from(tls),
|
||||
connector: TlsConnector::from(dialing),
|
||||
revocations,
|
||||
ca,
|
||||
database,
|
||||
pushes,
|
||||
readers: Pool::new(),
|
||||
queries: Pool::new(),
|
||||
receiving: Mutex::new(HashSet::new()),
|
||||
config,
|
||||
});
|
||||
start_pool_sweeps(&shared)?;
|
||||
Ok(Server { shared })
|
||||
}
|
||||
|
||||
/// The server's name: its certificate's.
|
||||
@@ -231,24 +237,22 @@ impl Shared {
|
||||
}
|
||||
|
||||
/// Runs `work` on an idle connection of `pool`, or a new one, then
|
||||
/// puts it back.
|
||||
/// puts it back (closed if the pool has enough idle ones already).
|
||||
async fn pooled<C: Send + 'static, T: Send + 'static>(
|
||||
self: &Arc<Self>,
|
||||
pool: fn(&Shared) -> &Mutex<Vec<C>>,
|
||||
pool: fn(&Shared) -> &Pool<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 {
|
||||
let connection = match pool(&shared).take() {
|
||||
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);
|
||||
}
|
||||
let max = shared.config.server.idle_database_connections;
|
||||
pool(&shared).put_back(connection, max, Instant::now());
|
||||
value
|
||||
})
|
||||
.await
|
||||
@@ -256,6 +260,80 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
|
||||
/// Database connections not in use, each with when it was put back: the
|
||||
/// last one put back is taken first, so the others age out.
|
||||
struct Pool<C> {
|
||||
idle: Mutex<Vec<(C, Instant)>>,
|
||||
}
|
||||
|
||||
impl<C> Pool<C> {
|
||||
fn new() -> Self {
|
||||
Pool {
|
||||
idle: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
fn lock(&self) -> std::sync::MutexGuard<'_, Vec<(C, Instant)>> {
|
||||
self.idle.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// The idle connection used last, if any.
|
||||
fn take(&self) -> Option<C> {
|
||||
self.lock().pop().map(|(connection, _)| connection)
|
||||
}
|
||||
|
||||
/// Keeps `connection` for later, unused since `now`, unless `max` are
|
||||
/// kept already: then it's closed (outside the lock).
|
||||
fn put_back(&self, connection: C, max: usize, now: Instant) {
|
||||
let mut idle = self.lock();
|
||||
if idle.len() < max {
|
||||
idle.push((connection, now));
|
||||
} else {
|
||||
drop(idle);
|
||||
drop(connection);
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes the connections unused for `idle_for` or more at `now`.
|
||||
fn sweep(&self, now: Instant, idle_for: Duration) {
|
||||
let stale: Vec<(C, Instant)> = {
|
||||
let mut idle = self.lock();
|
||||
let (stale, fresh) = idle
|
||||
.drain(..)
|
||||
.partition(|(_, since)| now.saturating_duration_since(*since) >= idle_for);
|
||||
*idle = fresh;
|
||||
stale
|
||||
};
|
||||
drop(stale);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn len(&self) -> usize {
|
||||
self.lock().len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes the pools' connections unused for [`POOL_IDLE`], looked at every
|
||||
/// [`POOL_SWEEP`] on a thread of its own, until the server is dropped.
|
||||
fn start_pool_sweeps(shared: &Arc<Shared>) -> Result<(), String> {
|
||||
let shared = Arc::downgrade(shared);
|
||||
std::thread::Builder::new()
|
||||
.name("pool sweeps".into())
|
||||
.spawn(move || {
|
||||
loop {
|
||||
std::thread::sleep(POOL_SWEEP);
|
||||
let Some(shared) = shared.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let now = Instant::now();
|
||||
shared.readers.sweep(now, POOL_IDLE);
|
||||
shared.queries.sweep(now, POOL_IDLE);
|
||||
}
|
||||
})
|
||||
.map(|_| ())
|
||||
.map_err(|error| format!("the pool sweeps' thread: {error}"))
|
||||
}
|
||||
|
||||
/// 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`, "The benchmark").
|
||||
@@ -339,6 +417,27 @@ fn stamp(path: &Path) -> Option<(SystemTime, u64)> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn pools_keep_few_and_close_the_idle() {
|
||||
let pool = Pool::new();
|
||||
let start = Instant::now();
|
||||
// Three back at once, two kept at most: the third closed.
|
||||
for connection in [1, 2, 3] {
|
||||
pool.put_back(connection, 2, start);
|
||||
}
|
||||
assert_eq!(pool.len(), 2);
|
||||
// The last one put back is taken first.
|
||||
assert_eq!(pool.take(), Some(2));
|
||||
pool.put_back(2, 2, start + Duration::from_secs(30));
|
||||
// At 60 s, the one idle since the start goes, not the other.
|
||||
pool.sweep(start + POOL_IDLE, POOL_IDLE);
|
||||
assert_eq!(pool.take(), Some(2));
|
||||
assert_eq!(pool.take(), None);
|
||||
// None kept at all.
|
||||
pool.put_back(4, 0, start);
|
||||
assert_eq!(pool.len(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clock_before_1970_is_refused() {
|
||||
assert!(check_clock(UNIX_EPOCH).is_ok());
|
||||
|
||||
@@ -11,11 +11,11 @@ use crate::connection::SEND_TIMEOUT;
|
||||
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::limits::{ALPN, KEEPALIVE_SECS, MAX_PACKET_SIZE};
|
||||
use bakashrot_proto::names::name_matches;
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment, AttachmentPart, MissingAttachment, ReplicateAttachment, ReplicateMessages,
|
||||
SyncState, SyncStateRequest,
|
||||
Attachment, AttachmentPart, MissingAttachment, Pair, Ping, ReplicateAttachment,
|
||||
ReplicateMessages, SyncState, SyncStateRequest,
|
||||
};
|
||||
use bakashrot_proto::{ErrorCode, Packet, frame};
|
||||
use bakashrot_storage::AttachmentState;
|
||||
@@ -58,10 +58,13 @@ async fn keep_linked(shared: Arc<Shared>, address: String) {
|
||||
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),
|
||||
let checked = match link.check_in(&shared).await {
|
||||
Ok(true) => Ok(()),
|
||||
Ok(false) => link.wait(replication.sync_interval).await,
|
||||
Err(why) => Err(why),
|
||||
};
|
||||
if let Err(why) = checked {
|
||||
break format!("{} ({address}): {why}", link.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -139,20 +142,11 @@ impl Link {
|
||||
/// 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 (state, theirs) = self.sync_state().await?;
|
||||
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) {
|
||||
@@ -171,13 +165,44 @@ impl Link {
|
||||
Ok(self.sent)
|
||||
}
|
||||
|
||||
/// Its `SyncState`, every page: the first (the lists), and the last
|
||||
/// id of each topic and node.
|
||||
async fn sync_state(&mut self) -> Result<(SyncState, HashMap<(String, String), u64>), String> {
|
||||
let mut theirs = HashMap::new();
|
||||
let mut first = None;
|
||||
let mut after = None;
|
||||
loop {
|
||||
let mut page = match self.ask(SyncStateRequest { after }.into()).await? {
|
||||
Packet::SyncState(page) => page,
|
||||
Packet::RequestRefused(refused) => {
|
||||
return Err(format!("refused: {}", refused.reason));
|
||||
}
|
||||
other => return Err(unexpected(&other)),
|
||||
};
|
||||
after = match page.more {
|
||||
true => page.heads.last().map(|head| Pair {
|
||||
topic: head.topic.clone(),
|
||||
node: head.node.clone(),
|
||||
}),
|
||||
false => None,
|
||||
};
|
||||
theirs.extend(
|
||||
page.heads
|
||||
.drain(..)
|
||||
.map(|head| (key(&head.topic, &head.node), head.last_id)),
|
||||
);
|
||||
first.get_or_insert(page);
|
||||
if after.is_none() {
|
||||
return Ok((first.expect("a page came"), theirs));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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))
|
||||
};
|
||||
let listed =
|
||||
|list: &[String], name: &str| list.iter().any(|entry| name_matches(entry, name));
|
||||
listed(&state.topics, topic)
|
||||
&& listed(&state.nodes, node)
|
||||
&& self.permissions.sends(topic, node)
|
||||
@@ -292,6 +317,26 @@ impl Link {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Waits `duration` before the next check-in, with a `Ping` every
|
||||
/// `KEEPALIVE_SECS` meanwhile: the other server closes a link silent
|
||||
/// for `IDLE_TIMEOUT_SECS`.
|
||||
async fn wait(&mut self, duration: Duration) -> Result<(), String> {
|
||||
let keepalive = Duration::from_secs(KEEPALIVE_SECS);
|
||||
let mut left = duration;
|
||||
loop {
|
||||
let step = left.min(keepalive);
|
||||
sleep(step).await;
|
||||
left -= step;
|
||||
if left.is_zero() {
|
||||
return Ok(());
|
||||
}
|
||||
match self.ask(Ping {}.into()).await? {
|
||||
Packet::Pong(_) => {}
|
||||
other => return Err(unexpected(&other)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn ask(&mut self, packet: Packet) -> Result<Packet, String> {
|
||||
self.send(packet).await?;
|
||||
self.receive().await
|
||||
|
||||
@@ -31,10 +31,9 @@ pub(crate) async fn run(shared: &Arc<Shared>) {
|
||||
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 {
|
||||
let Some(cutoff) = shared.config.retention.cutoff(&topic, now) 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,
|
||||
|
||||
Reference in New Issue
Block a user