mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Added replication, Added clean stops, logs and releases (0.2.0)
Step 11: the servers replicate by name (push_to and accept_from), their messages and attachments, damaged copies asked for again. Step 12: the server stops cleanly on SIGTERM/SIGINT (Ctrl+C, Ctrl+Break and the console closing on Windows), committing what was queued; logs go to the console, BAKASHROT_LOG sets the level. release.py builds a release per platform (the programs, the DLL, a Python wheel with the library, THIRD-PARTY.txt) and smoke-tests it; CI runs it on v* tags. Built for size (opt-level "s"): 25-31% smaller. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -156,14 +156,16 @@ impl Batch<'_> {
|
||||
/// Stores messages a peer sent for `topic` and `node`, with their own
|
||||
/// ids, in order; ones already here are kept as they are. Their
|
||||
/// attachments are noted, to be asked for (`replicating`), or never if
|
||||
/// bigger than `max_attachment_size` (`too_big`). Returns the topic and
|
||||
/// node's last id.
|
||||
/// bigger than `max_attachment_size` (`too_big`). Ones pushed before
|
||||
/// `skip_before` (ms, past their age here) aren't stored, but count as
|
||||
/// received. Returns the topic and node's last id.
|
||||
pub fn replicate(
|
||||
&mut self,
|
||||
topic: &str,
|
||||
node: &str,
|
||||
messages: &[ReplicatedMessage],
|
||||
max_attachment_size: u64,
|
||||
skip_before: u64,
|
||||
) -> Result<u64> {
|
||||
self.atomic(|db| {
|
||||
let (stream, mut last_id) = stream(db, topic, node)?;
|
||||
@@ -177,6 +179,11 @@ impl Batch<'_> {
|
||||
if !(1..=MAX_MESSAGE_ID).contains(&message.id) {
|
||||
return Err(Error::Invalid(format!("message id {}", message.id)));
|
||||
}
|
||||
// What the trigger keeps: one ignored was here, below it.
|
||||
last_id = last_id.max(message.id);
|
||||
if message.pushed_at < skip_before {
|
||||
continue;
|
||||
}
|
||||
let key = message_key(stream, message.id);
|
||||
let stored = insert.execute((key, message.pushed_at, &message.data))? == 1;
|
||||
if let (true, Some(attachment)) = (stored, &message.attachment) {
|
||||
@@ -187,9 +194,10 @@ impl Batch<'_> {
|
||||
};
|
||||
attach.execute((key, attachment.size, &attachment.sha256, state))?;
|
||||
}
|
||||
// What the trigger keeps: one ignored was here, below it.
|
||||
last_id = last_id.max(message.id);
|
||||
}
|
||||
// The skipped ones move it too.
|
||||
db.prepare_cached("UPDATE streams SET last_id = ?2 WHERE stream_id = ?1")?
|
||||
.execute((stream, last_id))?;
|
||||
Ok(last_id)
|
||||
})
|
||||
}
|
||||
@@ -214,6 +222,26 @@ impl Batch<'_> {
|
||||
})
|
||||
}
|
||||
|
||||
/// A ready attachment found not to match its SHA-256 (a damaged
|
||||
/// disk, a bug): its parts go, it's asked for again from its peers
|
||||
/// (`replicating`), and not served meanwhile.
|
||||
pub fn damaged(&mut self, attachment_id: i64) -> Result<()> {
|
||||
self.atomic(|db| {
|
||||
if attachment(db, attachment_id)?.0 != AttachmentState::Ready {
|
||||
return Err(Error::Invalid(format!(
|
||||
"attachment {attachment_id} isn't a ready one"
|
||||
)));
|
||||
}
|
||||
delete_parts(db, attachment_id, None)?;
|
||||
db.prepare_cached(
|
||||
"UPDATE attachments SET state = 'replicating', received = 0 \
|
||||
WHERE attachment_id = ?1",
|
||||
)?
|
||||
.execute([attachment_id])?;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Retention: deletes `topic`'s messages pushed before `cutoff` (ms),
|
||||
/// `limit` at most (call again while it returns `limit`). Each stream
|
||||
/// is read from its oldest message and stops at the first one it keeps:
|
||||
@@ -381,8 +409,21 @@ fn delete_attachment(db: &Connection, attachment_id: i64) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Deletes every upload: at start, none of them can be pushed any more.
|
||||
pub(crate) fn delete_uploads(db: &Connection) -> Result<()> {
|
||||
/// At start: deletes every upload (none of them can be pushed any more),
|
||||
/// and starts over the replicated attachments all of whose parts came but
|
||||
/// weren't checked (stopped in between).
|
||||
pub(crate) fn clean_up(db: &Connection) -> Result<()> {
|
||||
let unchecked: Vec<i64> = db
|
||||
.prepare(
|
||||
"SELECT attachment_id FROM attachments \
|
||||
WHERE state = 'replicating' AND received = size",
|
||||
)?
|
||||
.query_map([], |row| row.get(0))?
|
||||
.collect::<rusqlite::Result<_>>()?;
|
||||
for attachment_id in unchecked {
|
||||
delete_parts(db, attachment_id, None)?;
|
||||
set_attachment(db, attachment_id, "received = ?2", 0)?;
|
||||
}
|
||||
let uploads: Vec<i64> = db
|
||||
.prepare("SELECT attachment_id FROM attachments WHERE state = 'uploading'")?
|
||||
.query_map([], |row| row.get(0))?
|
||||
|
||||
@@ -98,7 +98,7 @@ impl Database {
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
crate::batch::delete_uploads(&transaction)?;
|
||||
crate::batch::clean_up(&transaction)?;
|
||||
transaction.commit()?;
|
||||
Ok(database)
|
||||
}
|
||||
|
||||
@@ -5,7 +5,10 @@ use crate::{
|
||||
AttachmentState, Error, Result, find_stream, message_id, message_key, part_key, stream_keys,
|
||||
};
|
||||
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_MESSAGE_ID};
|
||||
use bakashrot_proto::packets::{Head, MessageEntry, Messages, MissingAttachment, StoredAttachment};
|
||||
use bakashrot_proto::packets::{
|
||||
Attachment as Sent, Head, MessageEntry, Messages, MissingAttachment, ReplicatedMessage,
|
||||
StoredAttachment,
|
||||
};
|
||||
use rusqlite::{Connection, OptionalExtension, Row};
|
||||
|
||||
/// About how many bytes of messages one answer carries: past it, the rest
|
||||
@@ -23,6 +26,11 @@ const LATEST: &str = "SELECT d.key, d.pushed_at, d.message_data, a.size, a.state
|
||||
FROM data d LEFT JOIN attachments a ON a.message_key = d.key \
|
||||
WHERE d.key >= ?1 AND d.key <= ?2 ORDER BY d.key DESC LIMIT ?3";
|
||||
|
||||
/// A stream's messages after a key, as replication sends them.
|
||||
const TO_REPLICATE: &str = "SELECT d.key, d.pushed_at, d.message_data, a.size, a.sha256 \
|
||||
FROM data d LEFT JOIN attachments a ON a.message_key = d.key \
|
||||
WHERE d.key > ?1 AND d.key <= ?2 ORDER BY d.key LIMIT ?3";
|
||||
|
||||
/// A connection that reads.
|
||||
#[derive(Debug)]
|
||||
pub struct Reader {
|
||||
@@ -97,6 +105,48 @@ impl Reader {
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// A topic and node's messages after an id, as replication sends them:
|
||||
/// `limit` at most, about [`MESSAGES_BYTES`] at most (a bigger one
|
||||
/// alone). None once there are no more.
|
||||
pub fn to_replicate(
|
||||
&self,
|
||||
topic: &str,
|
||||
node: &str,
|
||||
after: u64,
|
||||
limit: u32,
|
||||
) -> Result<Vec<ReplicatedMessage>> {
|
||||
let mut messages = Vec::new();
|
||||
let Some((stream, _)) = find_stream(&self.connection, topic, node)? else {
|
||||
return Ok(messages);
|
||||
};
|
||||
let (_, last) = stream_keys(stream);
|
||||
let mut statement = self.connection.prepare_cached(TO_REPLICATE)?;
|
||||
let from = message_key(stream, after.min(MAX_MESSAGE_ID));
|
||||
let mut rows = statement.query((from, last, i64::from(limit)))?;
|
||||
let mut bytes = 0;
|
||||
while let Some(row) = rows.next()? {
|
||||
let data: String = row.get(2)?;
|
||||
if !messages.is_empty() && bytes + data.len() > MESSAGES_BYTES {
|
||||
break;
|
||||
}
|
||||
bytes += data.len();
|
||||
let attachment = match row.get::<_, Option<u64>>(3)? {
|
||||
Some(size) => Some(Sent {
|
||||
size,
|
||||
sha256: row.get(4)?,
|
||||
}),
|
||||
None => None,
|
||||
};
|
||||
messages.push(ReplicatedMessage {
|
||||
id: message_id(row.get(0)?),
|
||||
pushed_at: row.get(1)?,
|
||||
data,
|
||||
attachment,
|
||||
});
|
||||
}
|
||||
Ok(messages)
|
||||
}
|
||||
|
||||
/// Every topic with messages (or that had some), in order.
|
||||
pub fn topics(&self) -> Result<Vec<String>> {
|
||||
self.strings("SELECT DISTINCT topic FROM streams ORDER BY topic")
|
||||
|
||||
@@ -316,6 +316,7 @@ fn replication() {
|
||||
replicated(12, 300, Some((50, sha))),
|
||||
],
|
||||
1000,
|
||||
0,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
@@ -331,6 +332,7 @@ fn replication() {
|
||||
..replicated(5, 1, None)
|
||||
}],
|
||||
1000,
|
||||
0,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
@@ -407,6 +409,7 @@ fn replication() {
|
||||
"garage",
|
||||
&[replicated(1, 1, Some((2 * PART as u64, sha)))],
|
||||
u64::MAX,
|
||||
0,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
@@ -420,9 +423,78 @@ fn replication() {
|
||||
("garage", 1)
|
||||
);
|
||||
|
||||
// What's sent on: after an id, with its attachments' SHA-256s.
|
||||
let sent = reader.to_replicate("logs", "kitchen", 5, 10).unwrap();
|
||||
let sent_ids: Vec<u64> = sent.iter().map(|m| m.id).collect();
|
||||
assert_eq!(sent_ids, [9, 12, 13]);
|
||||
assert_eq!(
|
||||
sent[0].attachment,
|
||||
Some(Sent {
|
||||
size: PART as u64 + 1,
|
||||
sha256: sha
|
||||
})
|
||||
);
|
||||
assert_eq!(sent[2].attachment, None);
|
||||
assert_eq!(
|
||||
reader.to_replicate("logs", "kitchen", 9, 1).unwrap()[0].id,
|
||||
12
|
||||
);
|
||||
assert!(
|
||||
reader
|
||||
.to_replicate("logs", "kitchen", 13, 10)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
assert!(
|
||||
reader
|
||||
.to_replicate("logs", "nobody", 0, 10)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
// A damaged ready copy: its parts go, asked for again.
|
||||
writer.batch(|b| b.damaged(small.id)).unwrap();
|
||||
let again = reader.attachment("logs", "kitchen", 12).unwrap().unwrap();
|
||||
assert_eq!(
|
||||
(again.state, again.received),
|
||||
(AttachmentState::Replicating, 0)
|
||||
);
|
||||
assert!(reader.read_part(small.id, 0).is_err());
|
||||
assert!(matches!(
|
||||
writer.batch(|b| b.damaged(small.id)),
|
||||
Err(Error::Invalid(_))
|
||||
));
|
||||
|
||||
// Past their age here: not stored, but counted.
|
||||
let last = writer
|
||||
.batch(|b| {
|
||||
b.replicate(
|
||||
"logs",
|
||||
"attic",
|
||||
&[
|
||||
replicated(1, 100, Some((50, sha))),
|
||||
replicated(2, 200, None),
|
||||
replicated(3, 300, None),
|
||||
],
|
||||
1000,
|
||||
201,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(last, 3);
|
||||
assert_eq!(
|
||||
ids(&reader.messages("logs", "attic", Some(0), 10).unwrap()),
|
||||
[3]
|
||||
);
|
||||
assert_eq!(reader.last_id("logs", "attic").unwrap(), 3);
|
||||
let skipped = writer
|
||||
.batch(|b| b.replicate("logs", "cellar", &[replicated(7, 100, None)], 1000, 201))
|
||||
.unwrap();
|
||||
assert_eq!((skipped, reader.last_id("logs", "cellar").unwrap()), (7, 7));
|
||||
|
||||
// Ids out of range.
|
||||
assert!(matches!(
|
||||
writer.batch(|b| b.replicate("logs", "kitchen", &[replicated(0, 1, None)], 0)),
|
||||
writer.batch(|b| b.replicate("logs", "kitchen", &[replicated(0, 1, None)], 0, 0)),
|
||||
Err(Error::Invalid(_))
|
||||
));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user