1
0
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:
2026-11-15 01:13:44 +01:00
parent 17ec69c03c
commit 5045019df4
93 changed files with 634 additions and 277 deletions
@@ -0,0 +1,108 @@
//! Attachments: one per message at most, in parts of `ATTACHMENT_PART_SIZE`
//! (the last one what's left), checked with their SHA-256 once all came.
//!
//! Parts are streamed, without a request or an answer each:
//! - **Pushing:** `PushMessage` with its `Attachment`, the server's
//! `Continue`, every part, then `MessagePushed` (or `RequestRefused`,
//! `DataMismatch` if the SHA-256 doesn't match). Once it said `Continue`,
//! the server reads every part even if storing them failed, then refuses.
//! - **Reading:** `GetAttachment`, the server's `Attachment`, then the
//! parts from the one asked to the last. A server that fails while
//! sending them closes the connection.
//! - **Replicating:** `ReplicateAttachment`, the server's `Continue`, the
//! parts from the one it lacks, then `MessagePushed`.
//!
//! A part is its data alone: its index follows from the order, its size
//! from the attachment's ([`Attachment::part_len`]), which the receiver
//! checks.
use super::rules;
use super::{Check, DecodeError};
use crate::limits::{
ATTACHMENT_PART_SIZE, MAX_ATTACHMENT_PARTS, MAX_ATTACHMENT_SIZE, attachment_part_count,
attachment_part_len,
};
use serde::{Deserialize, Serialize};
/// An attachment's size and checksum: in a `PushMessage` or a replicated
/// message, and on its own before the parts of a `GetAttachment`.
///
/// `[9, [size, sha256]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Attachment {
/// Its size, 1 to `MAX_ATTACHMENT_SIZE` (servers may take less).
pub size: u64,
/// Its SHA-256.
#[serde(with = "serde_bytes")]
pub sha256: [u8; 32],
}
impl Attachment {
/// How many parts it takes.
pub const fn part_count(&self) -> u64 {
attachment_part_count(self.size)
}
/// The size its part `index` must have, 0 if it has no such part.
pub const fn part_len(&self, index: u64) -> u64 {
attachment_part_len(self.size, index)
}
}
impl Check for Attachment {
fn check(&self) -> Result<(), DecodeError> {
rules::range(self.size, 1, MAX_ATTACHMENT_SIZE, "Attachment.size")
}
}
/// A part of an attachment, the next one.
///
/// `[10, [data]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AttachmentPart {
/// The part, 1 to `ATTACHMENT_PART_SIZE` bytes (its exact size is the
/// receiver's to check).
#[serde(with = "serde_bytes")]
pub data: Vec<u8>,
}
impl Check for AttachmentPart {
fn check(&self) -> Result<(), DecodeError> {
rules::range(
self.data.len() as u64,
1,
ATTACHMENT_PART_SIZE,
"AttachmentPart.data",
)
}
}
/// A message's attachment, from a part on (0 for all of it).
///
/// `[8, [topic, node, message_id, from_part]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GetAttachment {
/// The topic.
pub topic: String,
/// The node.
pub node: String,
/// The message.
pub message_id: u64,
/// The first part to send: a client going on from where a lost
/// connection stopped.
pub from_part: u64,
}
impl Check for GetAttachment {
fn check(&self) -> Result<(), DecodeError> {
rules::name(&self.topic, "GetAttachment.topic")?;
rules::name(&self.node, "GetAttachment.node")?;
rules::message_id(self.message_id, "GetAttachment.message_id")?;
rules::range(
self.from_part,
0,
MAX_ATTACHMENT_PARTS - 1,
"GetAttachment.from_part",
)
}
}
@@ -0,0 +1,235 @@
//! Clients' requests and their answers: pushing and reading messages,
//! names, queries.
use super::rules;
use super::{Attachment, Check, DecodeError};
use crate::limits::{
MAX_ATTACHMENT_SIZE, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, MAX_NAMES_LIST_ENTRIES,
};
use serde::{Deserialize, Serialize};
/// A message's attachment, as reads show it.
///
/// `[size, ready]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StoredAttachment {
/// Its size, 1 and up.
pub size: u64,
/// Whether all of it is on this server (it may still be on its way from
/// a peer).
pub ready: bool,
}
/// A stored message, as `Messages` carries it.
///
/// `[id, pushed_at, data, attachment]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MessageEntry {
/// Its id, in its topic/node pair (1 and up).
pub id: u64,
/// When it was pushed: milliseconds since 1970 UTC, by the server it was
/// pushed to, kept as is by replication.
pub pushed_at: u64,
/// The message, as pushed (JSON or not).
pub data: String,
/// Its attachment, if it has one.
pub attachment: Option<StoredAttachment>,
}
impl Check for MessageEntry {
fn check(&self) -> Result<(), DecodeError> {
rules::message_id(self.id, "message.id")?;
rules::timestamp(self.pushed_at, "message.pushed_at")?;
if let Some(attachment) = &self.attachment {
rules::range(
attachment.size,
1,
MAX_ATTACHMENT_SIZE,
"message.attachment.size",
)?;
}
Ok(())
}
}
/// Stores a message under the client's node. With an attachment, the
/// server answers `Continue` (or refuses), the client sends all its parts,
/// then the server stores both and answers `MessagePushed`.
///
/// `[4, [topic, data, attachment]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PushMessage {
/// The topic: a push always names it.
pub topic: String,
/// The message (JSON or not), up to `MAX_MESSAGE_SIZE` bytes (the
/// server refuses bigger ones).
pub data: String,
/// Its attachment, whose parts follow the server's `Continue`.
pub attachment: Option<Attachment>,
}
impl Check for PushMessage {
fn check(&self) -> Result<(), DecodeError> {
rules::name(&self.topic, "PushMessage.topic")?;
if let Some(attachment) = &self.attachment {
attachment.check()?;
}
Ok(())
}
}
/// The id a message was stored with (the last of a replicated batch).
///
/// `[5, [message_id]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MessagePushed {
/// The id.
pub message_id: u64,
}
impl Check for MessagePushed {
fn check(&self) -> Result<(), DecodeError> {
rules::message_id(self.message_id, "MessagePushed.message_id")
}
}
/// A topic/node's messages, in id order: those after an id, or its last
/// ones.
///
/// `[6, [topic, node, after, limit]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GetMessages {
/// The topic.
pub topic: String,
/// The node.
pub node: String,
/// Those with a higher id than this (0 for all), or nil for the last
/// `limit` ones (the latest message: nil and 1).
pub after: Option<u64>,
/// At most this many, 1 to `MAX_MESSAGES_PER_PACKET`.
pub limit: u32,
}
impl Check for GetMessages {
fn check(&self) -> Result<(), DecodeError> {
rules::name(&self.topic, "GetMessages.topic")?;
rules::name(&self.node, "GetMessages.node")?;
if let Some(after) = self.after {
rules::range(after, 0, MAX_MESSAGE_ID, "GetMessages.after")?;
}
rules::range(
self.limit.into(),
1,
MAX_MESSAGES_PER_PACKET.into(),
"GetMessages.limit",
)
}
}
/// A run of a topic/node's messages, in id order. None isn't a refusal.
///
/// `[7, [more, [message...]]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Messages {
/// Whether more follow the last one: ask again after its id.
pub more: bool,
/// The messages, ids strictly increasing, `MAX_MESSAGES_PER_PACKET` at
/// most; fewer than asked once they reach about a megabyte (the
/// server's choice), a bigger message alone.
pub messages: Vec<MessageEntry>,
}
impl Check for Messages {
fn check(&self) -> Result<(), DecodeError> {
rules::most(
self.messages.len(),
MAX_MESSAGES_PER_PACKET as usize,
"Messages.messages",
)?;
rules::increasing(self.messages.iter().map(|m| m.id), "Messages.messages")?;
self.messages.iter().try_for_each(Check::check)
}
}
/// Raw read-only SQL.
///
/// `[13, [sql]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Query {
/// The query: one statement, starting with SELECT or WITH.
pub sql: String,
}
impl Check for Query {}
/// A query's result.
///
/// `[14, [json]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct QueryResult {
/// `{"columns":[...],"rows":[[...],...]}`.
pub json: String,
}
impl Check for QueryResult {}
/// Topics or nodes: 1 or 2 on the wire.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(into = "u8", try_from = "u8")]
pub enum NameKind {
/// Topics.
Topic = 1,
/// Nodes.
Node = 2,
}
impl From<NameKind> for u8 {
fn from(kind: NameKind) -> u8 {
kind as u8
}
}
impl TryFrom<u8> for NameKind {
type Error = &'static str;
fn try_from(value: u8) -> Result<NameKind, Self::Error> {
match value {
1 => Ok(NameKind::Topic),
2 => Ok(NameKind::Node),
_ => Err("a name kind is 1 (topics) or 2 (nodes)"),
}
}
}
/// Every topic or node the client may see.
///
/// `[11, [kind]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ListNames {
/// Topics or nodes.
pub kind: NameKind,
}
impl Check for ListNames {}
/// Topics or nodes.
///
/// `[12, [kind, truncated, [name...]]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NamesList {
/// Topics or nodes.
pub kind: NameKind,
/// Whether some didn't fit.
pub truncated: bool,
/// The names, `MAX_NAMES_LIST_ENTRIES` at most.
pub names: Vec<String>,
}
impl Check for NamesList {
fn check(&self) -> Result<(), DecodeError> {
rules::most(self.names.len(), MAX_NAMES_LIST_ENTRIES, "NamesList.names")?;
self.names
.iter()
.try_for_each(|name| rules::name(name, "NamesList.names"))
}
}
+324
View File
@@ -0,0 +1,324 @@
//! Every packet of protocol 7.
//!
//! A packet is a MessagePack array of two: its type, then its fields as an
//! array, `[type, [field, field, ...]]`. Structs inside are arrays of their
//! fields too, `Option`s nil or their value, bytes binaries. All of it is
//! derived with `serde` (`rmp-serde`'s compact form): the structs below
//! are the format, `docs/protocol.md` lists them.
//!
//! [`Packet::decode`] checks everything: the types and the number of
//! fields (`serde`), then each packet's rules ([`Check`]: ranges, names,
//! ids in order), and that nothing follows. (A struct given as a map of its
//! field names is taken too, `serde`'s derive: nothing writes that form, it
//! isn't part of the format, its values are checked all the same.) Whatever isn't right is a
//! [`DecodeError`]: the connection is aborted. What's well-formed but not
//! allowed or not found (a topic this server doesn't have) is the server's
//! to refuse, with a `RequestRefused`.
//!
//! Topics and nodes are names everywhere, never ids.
//!
//! Adding a packet: a struct deriving `Serialize` and `Deserialize`, with
//! its [`Check`], in the file of its family; a line in the `packets!` table
//! below with the next id (never reuse one); a sample in `tests/packets.rs`;
//! its row in `docs/protocol.md`.
mod attachments;
mod messages;
mod replication;
mod session;
pub use attachments::{Attachment, AttachmentPart, GetAttachment};
pub use messages::{
GetMessages, ListNames, MessageEntry, MessagePushed, Messages, NameKind, NamesList,
PushMessage, Query, QueryResult, StoredAttachment,
};
pub use replication::{
Head, MissingAttachment, ReplicateAttachment, ReplicateMessages, ReplicatedMessage, SyncState,
SyncStateRequest,
};
pub use session::{Continue, RequestRefused, Welcome};
use serde::de::{self, DeserializeOwned, IgnoredAny, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::io::Cursor;
/// Why a packet couldn't be read. Any of these aborts the connection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DecodeError {
/// Not a packet: not MessagePack, a value of the wrong type, a field
/// missing or one too many, a type this version doesn't know.
Malformed(String),
/// Bytes after the packet.
TrailingBytes,
/// A field breaking a rule of its packet.
Invalid {
/// The field.
field: &'static str,
/// The rule it breaks.
rule: &'static str,
},
}
impl fmt::Display for DecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
DecodeError::Malformed(why) => write!(f, "malformed packet: {why}"),
DecodeError::TrailingBytes => f.write_str("bytes after the end of the packet"),
DecodeError::Invalid { field, rule } => write!(f, "{field}: {rule}"),
}
}
}
impl std::error::Error for DecodeError {}
/// The rules a packet's fields follow beyond their types, checked by
/// [`Packet::decode`]. None by default.
pub trait Check {
/// Fails on the first rule broken.
fn check(&self) -> Result<(), DecodeError> {
Ok(())
}
}
/// What every packet's struct is, implemented by the `packets!` table.
pub trait Body: Serialize + DeserializeOwned + Check + Into<Packet> {
/// Its type, the packet's first value.
const TYPE: PacketType;
/// The whole packet: `[type, [fields...]]`.
fn encode(&self) -> Vec<u8> {
rmp_serde::to_vec(&(Self::TYPE.id(), self)).expect("packets always serialize")
}
}
// The one table of packets: their names (the struct's and the variant's)
// and ids. Protocol 7's own: protocol 6's ids don't apply (the versions are
// checked before any packet).
macro_rules! packets {
($( $(#[$doc:meta])* $name:ident = $id:literal, )*) => {
/// The type of a packet: its first value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum PacketType {
$( $(#[$doc])* $name = $id, )*
}
impl PacketType {
/// Every type.
pub const ALL: &'static [PacketType] = &[$(PacketType::$name),*];
/// The type with this id, if there's one.
pub const fn from_id(id: u64) -> Option<PacketType> {
match id {
$( $id => Some(PacketType::$name), )*
_ => None,
}
}
/// Its id.
pub const fn id(self) -> u8 {
self as u8
}
/// Its name: "PushMessage".
pub const fn name(self) -> &'static str {
match self {
$( PacketType::$name => stringify!($name), )*
}
}
}
/// Any packet.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Packet {
$( $(#[$doc])* $name($name), )*
}
$(
impl Body for $name {
const TYPE: PacketType = PacketType::$name;
}
impl From<$name> for Packet {
fn from(body: $name) -> Packet {
Packet::$name(body)
}
}
)*
impl Packet {
/// Its type.
pub const fn packet_type(&self) -> PacketType {
match self {
$( Packet::$name(_) => PacketType::$name, )*
}
}
fn check(&self) -> Result<(), DecodeError> {
match self {
$( Packet::$name(body) => body.check(), )*
}
}
}
impl Serialize for Packet {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
$( Packet::$name(body) => (PacketType::$name.id(), body).serialize(serializer), )*
}
}
}
impl<'de> Deserialize<'de> for Packet {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Packet, D::Error> {
struct PacketVisitor;
impl<'de> Visitor<'de> for PacketVisitor {
type Value = Packet;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a packet, [type, [fields...]]")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Packet, A::Error> {
let id: u64 = seq
.next_element()?
.ok_or_else(|| de::Error::invalid_length(0, &self))?;
let packet = match PacketType::from_id(id) {
$(
Some(PacketType::$name) => Packet::$name(
seq.next_element()?
.ok_or_else(|| de::Error::invalid_length(1, &self))?,
),
)*
None => return Err(de::Error::custom(format_args!("unknown packet type {id}"))),
};
if seq.next_element::<IgnoredAny>()?.is_some() {
return Err(de::Error::invalid_length(3, &self));
}
Ok(packet)
}
}
deserializer.deserialize_seq(PacketVisitor)
}
}
};
}
packets! {
/// S→C, S→P: the server's first packet, once TLS is up.
Welcome = 1,
/// S→C, S→P: a request refused, with an error code; the connection stays.
RequestRefused = 2,
/// S→C, S→P: send the attachment's parts now.
Continue = 3,
/// C→S: stores a message, its attachment's parts after it if it has one
/// (`MessagePushed` / `RequestRefused`, `Continue` first for an attachment).
PushMessage = 4,
/// S→C, S→P: the stored message's id (the last one of a replicated batch).
MessagePushed = 5,
/// C→S: a topic/node's messages after an id, or its last ones (`Messages` / `RequestRefused`).
GetMessages = 6,
/// S→C: a run of messages.
Messages = 7,
/// C→S: a message's attachment, from a part on (`Attachment` then its parts / `RequestRefused`).
GetAttachment = 8,
/// S→C: the attachment whose parts follow.
Attachment = 9,
/// C→S, S→C, P→S: a part of an attachment, the next one.
AttachmentPart = 10,
/// C→S: every topic or node the client may see (`NamesList`).
ListNames = 11,
/// S→C: topics or nodes.
NamesList = 12,
/// C→S: read-only SQL (`QueryResult` / `RequestRefused`).
Query = 13,
/// S→C: a query's result.
QueryResult = 14,
/// P→S: what the server takes from this peer and has (`SyncState` / `RequestRefused`).
SyncStateRequest = 15,
/// S→P: what the server takes from this peer, how far it is, the attachments it lacks.
SyncState = 16,
/// P→S: messages of a topic/node the server is missing (`MessagePushed` / `RequestRefused`).
ReplicateMessages = 17,
/// P→S: an attachment the server is missing, its parts after it (`Continue`, then `MessagePushed` / `RequestRefused`).
ReplicateAttachment = 18,
}
impl Packet {
/// It, encoded: what goes in a frame.
pub fn encode(&self) -> Vec<u8> {
rmp_serde::to_vec(self).expect("packets always serialize")
}
/// Reads a packet, a frame's contents. See the [module](self) for what's
/// checked.
pub fn decode(bytes: &[u8]) -> Result<Packet, DecodeError> {
// A reader that grows its buffers as the data comes, never from a
// length the packet announces.
let mut deserializer = rmp_serde::Deserializer::new(Cursor::new(bytes));
let packet = Packet::deserialize(&mut deserializer)
.map_err(|error| DecodeError::Malformed(error.to_string()))?;
if deserializer.position() != bytes.len() as u64 {
return Err(DecodeError::TrailingBytes);
}
packet.check()?;
Ok(packet)
}
}
// The rules fields follow, for the `Check`s.
pub(crate) mod rules {
use super::DecodeError;
use crate::limits::{MAX_MESSAGE_ID, MAX_TIMESTAMP};
use crate::names;
/// Fails with `rule` unless `ok`.
pub fn require(ok: bool, field: &'static str, rule: &'static str) -> Result<(), DecodeError> {
if ok {
Ok(())
} else {
Err(DecodeError::Invalid { field, rule })
}
}
/// From `min` to `max`.
pub fn range(value: u64, min: u64, max: u64, field: &'static str) -> Result<(), DecodeError> {
require((min..=max).contains(&value), field, "out of range")
}
/// At most `max` items.
pub fn most(len: usize, max: usize, field: &'static str) -> Result<(), DecodeError> {
require(len <= max, field, "too many")
}
/// A topic or node name.
pub fn name(value: &str, field: &'static str) -> Result<(), DecodeError> {
require(names::is_valid_name(value), field, "must be a name")
}
/// A message id: 1 and up.
pub fn message_id(value: u64, field: &'static str) -> Result<(), DecodeError> {
range(value, 1, MAX_MESSAGE_ID, field)
}
/// When a message was pushed: milliseconds since 1970 UTC, 1 to 9999-12-31.
pub fn timestamp(value: u64, field: &'static str) -> Result<(), DecodeError> {
range(value, 1, MAX_TIMESTAMP, field)
}
/// Strictly increasing ids.
pub fn increasing(
ids: impl Iterator<Item = u64>,
field: &'static str,
) -> Result<(), DecodeError> {
let mut last = 0;
for id in ids {
require(id > last, field, "ids must be strictly increasing")?;
last = id;
}
Ok(())
}
}
@@ -0,0 +1,199 @@
//! Replication, between servers: at each check-in a peer (P) asks the
//! server (S) what it takes and has, then sends what it's missing,
//! messages first, then attachments (`OldSource/Design/Packets.md`,
//! "Replication"). Servers only ever send each other names: each has its
//! own ids.
use super::rules;
use super::{Attachment, Check, DecodeError};
use crate::limits::{
MAX_ATTACHMENT_PARTS, MAX_MESSAGE_ID, MAX_MESSAGES_PER_PACKET, MAX_MISSING_ATTACHMENTS,
MAX_NAMES_LIST_ENTRIES,
};
use crate::names;
use serde::{Deserialize, Serialize};
/// What the server takes from this peer, how far it is, and the
/// attachments it lacks.
///
/// `[15, []]`
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyncStateRequest {}
impl Check for SyncStateRequest {}
/// How far the server is in a topic/node pair.
///
/// `[topic, node, last_id]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Head {
/// The topic.
pub topic: String,
/// The node.
pub node: String,
/// The highest message id it has (deleted ones included).
pub last_id: u64,
}
/// An attachment the server lacks, and where to go on from.
///
/// `[topic, node, message_id, next_part]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MissingAttachment {
/// The topic.
pub topic: String,
/// The node.
pub node: String,
/// The message.
pub message_id: u64,
/// The next part it needs (it keeps what it got).
pub next_part: u64,
}
/// What the server takes from this peer, how far it is, and the
/// attachments it lacks: all a check-in needs.
///
/// `[16, [[topic...], [node...], [head...], [missing...]]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyncState {
/// The topics it takes from this peer: names, and wildcards (it takes
/// the names they match, even those it doesn't have yet).
pub topics: Vec<String>,
/// The nodes it takes from this peer, the same way.
pub nodes: Vec<String>,
/// Its highest message id in each topic/node pair of those.
pub heads: Vec<Head>,
/// The attachments it lacks among those, `MAX_MISSING_ATTACHMENTS` at
/// most.
pub missing: Vec<MissingAttachment>,
}
impl Check for SyncState {
fn check(&self) -> Result<(), DecodeError> {
for (list, field) in [
(&self.topics, "SyncState.topics"),
(&self.nodes, "SyncState.nodes"),
] {
rules::most(list.len(), MAX_NAMES_LIST_ENTRIES, field)?;
for item in list {
rules::require(
names::is_valid_name_or_pattern(item),
field,
"must be a name or a pattern",
)?;
}
}
for head in &self.heads {
rules::name(&head.topic, "SyncState.heads.topic")?;
rules::name(&head.node, "SyncState.heads.node")?;
rules::range(head.last_id, 0, MAX_MESSAGE_ID, "SyncState.heads.last_id")?;
}
rules::most(
self.missing.len(),
MAX_MISSING_ATTACHMENTS,
"SyncState.missing",
)?;
for missing in &self.missing {
rules::name(&missing.topic, "SyncState.missing.topic")?;
rules::name(&missing.node, "SyncState.missing.node")?;
rules::message_id(missing.message_id, "SyncState.missing.message_id")?;
rules::range(
missing.next_part,
0,
MAX_ATTACHMENT_PARTS - 1,
"SyncState.missing.next_part",
)?;
}
Ok(())
}
}
/// A message as replication carries it.
///
/// `[id, pushed_at, data, attachment]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReplicatedMessage {
/// Its id, as on its origin.
pub id: u64,
/// When it was pushed to its origin.
pub pushed_at: u64,
/// The message.
pub data: String,
/// Its attachment's size and SHA-256, if it has one: its parts come
/// later, by `ReplicateAttachment`.
pub attachment: Option<Attachment>,
}
/// Messages of a topic/node pair the server is missing, in id order.
///
/// `[17, [topic, node, [message...]]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReplicateMessages {
/// The topic.
pub topic: String,
/// The node.
pub node: String,
/// The messages, 1 to `MAX_MESSAGES_PER_PACKET`, ids strictly
/// increasing.
pub messages: Vec<ReplicatedMessage>,
}
impl Check for ReplicateMessages {
fn check(&self) -> Result<(), DecodeError> {
rules::name(&self.topic, "ReplicateMessages.topic")?;
rules::name(&self.node, "ReplicateMessages.node")?;
rules::require(
!self.messages.is_empty(),
"ReplicateMessages.messages",
"one at least",
)?;
rules::most(
self.messages.len(),
MAX_MESSAGES_PER_PACKET as usize,
"ReplicateMessages.messages",
)?;
rules::increasing(
self.messages.iter().map(|m| m.id),
"ReplicateMessages.messages",
)?;
for message in &self.messages {
rules::message_id(message.id, "ReplicateMessages.id")?;
rules::timestamp(message.pushed_at, "ReplicateMessages.pushed_at")?;
if let Some(attachment) = &message.attachment {
attachment.check()?;
}
}
Ok(())
}
}
/// An attachment the server is missing: the server answers `Continue` (or
/// refuses), the peer sends its parts from `from_part` to the last, the
/// server checks it all and answers `MessagePushed` with the message's id.
///
/// `[18, [topic, node, message_id, from_part]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReplicateAttachment {
/// The topic.
pub topic: String,
/// The node.
pub node: String,
/// The message.
pub message_id: u64,
/// The first part sent: the `next_part` the server listed.
pub from_part: u64,
}
impl Check for ReplicateAttachment {
fn check(&self) -> Result<(), DecodeError> {
rules::name(&self.topic, "ReplicateAttachment.topic")?;
rules::name(&self.node, "ReplicateAttachment.node")?;
rules::message_id(self.message_id, "ReplicateAttachment.message_id")?;
rules::range(
self.from_part,
0,
MAX_ATTACHMENT_PARTS - 1,
"ReplicateAttachment.from_part",
)
}
}
@@ -0,0 +1,76 @@
//! The connection itself: the server's welcome, refusals, and the go-ahead
//! for an attachment's parts.
use super::Check;
use super::DecodeError;
use super::rules;
use crate::error::{ErrorCode, MAX_REFUSAL_CODE};
use serde::{Deserialize, Serialize};
/// The server's first packet, once TLS is up and both ends' versions
/// matched (`frame::check_version()`): who this connection is, as the
/// server sees it.
///
/// `[1, [server, node]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Welcome {
/// The server's own name (its node).
pub server: String,
/// The node this connection writes as, from its certificate.
pub node: String,
}
impl Check for Welcome {
fn check(&self) -> Result<(), DecodeError> {
rules::name(&self.server, "Welcome.server")?;
rules::name(&self.node, "Welcome.node")
}
}
/// A request refused: the connection stays open.
///
/// `[2, [code, reason]]`
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RequestRefused {
/// What kind of refusal, 1-99: what clients act on. Kept as a number,
/// a newer server may send one this version doesn't know.
pub code: u32,
/// Why, for logs and people.
pub reason: String,
}
impl RequestRefused {
/// A refusal with a known code (a refusal's, 1-99).
pub fn new(code: ErrorCode, reason: impl Into<String>) -> Self {
debug_assert!(code.is_refusal(), "{code} isn't a refusal's code");
RequestRefused {
code: code.code(),
reason: reason.into(),
}
}
/// Its code, if this version knows it.
pub fn error_code(&self) -> Option<ErrorCode> {
ErrorCode::from_code(self.code)
}
}
impl Check for RequestRefused {
fn check(&self) -> Result<(), DecodeError> {
rules::range(
self.code.into(),
1,
MAX_REFUSAL_CODE.into(),
"RequestRefused.code",
)
}
}
/// Send the attachment's parts now: the answer to a `PushMessage` or a
/// `ReplicateAttachment` with an attachment, when the server takes it.
///
/// `[3, []]`
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Continue {}
impl Check for Continue {}