use crate::protocol::{DeRecChannelStore, DeRecTransport};
use crate::{
Error, Result,
derec_message::{DeRecMessageBuilder, current_timestamp},
protocol::types::{
ChannelQuery, ChannelStatus, HelperChannel, HelperFilter, ReplicaFilter, ReplicaMember,
Target,
},
types::{ChannelId, SharedKey},
};
use derec_proto::{MessageBody, SenderKind, TransportProtocol};
use prost::Message;
pub(crate) trait ChannelStoreExt: DeRecChannelStore {
async fn helpers_matching(
&self,
secret_id: u64,
filter: HelperFilter,
) -> Result<Vec<HelperChannel>> {
let rows = self.helpers(secret_id, filter.clone()).await?;
Ok(retain_matching(rows, "helpers", |c| {
filter.matches(&c.channel_id, c.status, &c.peer_role)
}))
}
async fn replicas_matching(
&self,
secret_id: u64,
filter: ReplicaFilter,
) -> Result<Vec<ReplicaMember>> {
let rows = self.replicas(secret_id, filter.clone()).await?;
Ok(retain_matching(rows, "replicas", |m| {
filter.matches(&m.replica_id, m.status, &m.role)
}))
}
async fn require_role(
&self,
secret_id: u64,
channel_ids: &[ChannelId],
expected: SenderKind,
) -> Result<()> {
for channel_id in channel_ids {
let channel = self
.load(
secret_id,
ChannelQuery::Helper {
channel_id: *channel_id,
},
)
.await?
.and_then(|r| r.as_helper().cloned())
.ok_or(Error::InvalidInput(
"channel id not present in channel store",
))?;
if channel.peer_role != expected {
return Err(Error::RoleMismatch {
channel_id: *channel_id,
expected,
actual: channel.peer_role,
});
}
}
Ok(())
}
async fn resolve_target(&self, secret_id: u64, target: Target) -> Result<Vec<ChannelId>> {
let known: Vec<ChannelId> = self
.helpers_matching(
secret_id,
HelperFilter {
ids: target.ids(),
status: vec![ChannelStatus::Paired],
..Default::default()
},
)
.await?
.iter()
.map(|c| c.channel_id)
.collect();
Ok(target.filter(&known))
}
async fn peer_endpoints(
&self,
secret_id: u64,
channel_id: ChannelId,
) -> Result<Vec<TransportProtocol>> {
let channel = self
.load(secret_id, ChannelQuery::Helper { channel_id })
.await?;
channel
.map(|ch| ch.transports().to_vec())
.filter(|endpoints| !endpoints.is_empty())
.ok_or(Error::InvalidInput("no transport endpoint for channel"))
}
async fn resolve_response_endpoints(
&self,
secret_id: u64,
channel_id: ChannelId,
reply_to: &[TransportProtocol],
) -> Result<Vec<TransportProtocol>> {
if !reply_to.is_empty() {
return Ok(reply_to.to_vec());
}
self.peer_endpoints(secret_id, channel_id).await
}
async fn load_replica_member(
&self,
secret_id: u64,
channel_id: ChannelId,
author: u64,
) -> Result<ReplicaMember> {
let replica_id = crate::types::ReplicaId::try_from(author)?;
self.load(
secret_id,
ChannelQuery::Replica {
channel_id,
replica_id,
},
)
.await?
.and_then(|r| r.as_replica().cloned())
.ok_or(Error::InvalidInput(
"replica sync names a member that is not in the group",
))
}
}
impl<T: DeRecChannelStore> ChannelStoreExt for T {}
#[allow(clippy::too_many_arguments)]
pub(crate) async fn send_channel_message<Ch: DeRecChannelStore, T: DeRecTransport>(
channel_store: &Ch,
transport: &T,
secret_id: u64,
channel_id: ChannelId,
body: MessageBody,
shared_key: &SharedKey,
inbound_trace_id: u64,
reply_to: &[TransportProtocol],
) -> Result<()> {
let envelope = DeRecMessageBuilder::channel()
.channel_id(channel_id)
.timestamp(current_timestamp())
.message_body(body)
.trace_id(inbound_trace_id)
.encrypt(shared_key)?
.build()?;
let wire_bytes = envelope.encode_to_vec();
let endpoint = channel_store
.resolve_response_endpoints(secret_id, channel_id, reply_to)
.await?;
transport.send(&endpoint, wire_bytes).await?;
Ok(())
}
fn retain_matching<T>(rows: Vec<T>, listing: &str, keep: impl Fn(&T) -> bool) -> Vec<T> {
let before = rows.len();
let kept: Vec<T> = rows.into_iter().filter(keep).collect();
#[cfg(feature = "logging")]
if kept.len() != before {
tracing::warn!(
listing,
returned = before,
kept = kept.len(),
"channel store did not apply the filter it was given; the excluded \
rows were dropped here, but the store is transferring rows the \
protocol discards and must apply the filter in its query"
);
}
#[cfg(not(feature = "logging"))]
let _ = (before, listing);
kept
}
#[cfg(test)]
mod defiant_store_tests {
use super::*;
use crate::protocol::test::{InMemChannelStore, run_async};
use crate::protocol::traits::{ChannelStoreFuture, DeRecChannelStore};
use crate::protocol::types::{
ChannelQuery, ChannelRecord, ChannelStatus, HelperChannel, ReplicaMember, ReplicaRole,
};
use crate::types::ReplicaId;
const SECRET_ID: u64 = 0xDEF1;
const GROUP: ChannelId = ChannelId(500);
#[derive(Default)]
struct DefiantStore(InMemChannelStore);
impl DeRecChannelStore for DefiantStore {
fn load(
&self,
secret_id: u64,
query: ChannelQuery,
) -> ChannelStoreFuture<'_, Option<ChannelRecord>> {
self.0.load(secret_id, query)
}
fn save(&mut self, secret_id: u64, record: ChannelRecord) -> ChannelStoreFuture<'_, ()> {
self.0.save(secret_id, record)
}
fn remove(&mut self, secret_id: u64, query: ChannelQuery) -> ChannelStoreFuture<'_, bool> {
self.0.remove(secret_id, query)
}
fn helpers(
&self,
secret_id: u64,
_filter: HelperFilter,
) -> ChannelStoreFuture<'_, Vec<HelperChannel>> {
self.0.helpers(secret_id, HelperFilter::default())
}
fn replicas(
&self,
secret_id: u64,
_filter: ReplicaFilter,
) -> ChannelStoreFuture<'_, Vec<ReplicaMember>> {
self.0.replicas(secret_id, ReplicaFilter::default())
}
fn link_channel(
&mut self,
secret_id: u64,
a: ChannelId,
b: ChannelId,
) -> ChannelStoreFuture<'_, ()> {
self.0.link_channel(secret_id, a, b)
}
fn linked_channels(
&self,
secret_id: u64,
channel_id: ChannelId,
) -> ChannelStoreFuture<'_, Vec<ChannelId>> {
self.0.linked_channels(secret_id, channel_id)
}
}
async fn seed(store: &mut DefiantStore, replica_id: u64, status: ChannelStatus) {
store
.save(
SECRET_ID,
ChannelRecord::Replica(ReplicaMember {
channel_id: GROUP,
replica_id: ReplicaId(replica_id),
transports: vec![TransportProtocol {
uri: "https://peer.example".to_owned(),
protocol: derec_proto::Protocol::Https as i32,
}],
communication_info: std::collections::HashMap::new(),
role: ReplicaRole::Destination,
status,
created_at: 0,
}),
)
.await
.expect("seed");
}
#[test]
fn a_by_id_filter_yields_only_that_member_even_when_the_store_ignores_it() {
run_async(async {
let mut store = DefiantStore::default();
for id in [7001u64, 7002, 7003] {
seed(&mut store, id, ChannelStatus::Paired).await;
}
let rows = store
.replicas_matching(
SECRET_ID,
ReplicaFilter {
ids: vec![ReplicaId(7002)],
..Default::default()
},
)
.await
.expect("listing");
assert_eq!(
rows.iter().map(|m| m.replica_id.0).collect::<Vec<_>>(),
vec![7002],
"the defiant store returned the whole roster; only the named member may survive"
);
});
}
#[test]
fn a_status_filter_holds_even_when_the_store_ignores_it() {
run_async(async {
let mut store = DefiantStore::default();
seed(&mut store, 8001, ChannelStatus::Pending).await;
seed(&mut store, 8002, ChannelStatus::Paired).await;
seed(&mut store, 8003, ChannelStatus::Paired).await;
let rows = store
.replicas_matching(
SECRET_ID,
ReplicaFilter {
status: vec![ChannelStatus::Pending],
..Default::default()
},
)
.await
.expect("listing");
assert_eq!(
rows.iter().map(|m| m.replica_id.0).collect::<Vec<_>>(),
vec![8001],
"a paired member must never reach a sweep that asked for pending ones"
);
});
}
#[test]
fn exclude_holds_even_when_the_store_ignores_it() {
run_async(async {
let mut store = DefiantStore::default();
for id in [9001u64, 9002] {
seed(&mut store, id, ChannelStatus::Paired).await;
}
let rows = store
.replicas_matching(
SECRET_ID,
ReplicaFilter {
exclude: vec![ReplicaId(9001)],
..Default::default()
},
)
.await
.expect("listing");
assert_eq!(
rows.iter().map(|m| m.replica_id.0).collect::<Vec<_>>(),
vec![9002]
);
});
}
#[test]
fn a_conforming_store_is_unaffected() {
run_async(async {
let mut store = InMemChannelStore::default();
for (id, status) in [(1u64, ChannelStatus::Pending), (2, ChannelStatus::Paired)] {
store
.save(
SECRET_ID,
ChannelRecord::Replica(ReplicaMember {
channel_id: GROUP,
replica_id: ReplicaId(id),
transports: Vec::new(),
communication_info: std::collections::HashMap::new(),
role: ReplicaRole::Destination,
status,
created_at: 0,
}),
)
.await
.expect("seed");
}
let rows = store
.replicas_matching(
SECRET_ID,
ReplicaFilter {
status: vec![ChannelStatus::Paired],
..Default::default()
},
)
.await
.expect("listing");
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].replica_id.0, 2);
});
}
}