use crate::derec_message;
use crate::derec_message::DeRecMessageBuilder;
use crate::error_codes;
use crate::extensions::channel_store;
use crate::extensions::channel_store::ChannelStoreExt as _;
use crate::protocol::context::Local;
use crate::protocol::events::{
DeRecEvent, FailedRequest, PendingAction, PendingActionKind, ReplyTarget,
};
use crate::protocol::stores::{StoreSet, Stores};
use crate::protocol::types::ReplicaFilter;
use crate::protocol::{DeRecSecretStore as _, DeRecTransport, SecretKind, SecretValue};
use crate::transport::TransportPolicy;
use crate::types::{ChannelId, SharedKey};
use crate::{Error, Result};
use derec_proto::DeRecResult;
use derec_proto::ErrorResponseMessage;
use derec_proto::{MessageBody, StatusEnum, TransportProtocol};
use prost::Message as _;
use std::mem;
use std::sync::Mutex;
use std::sync::MutexGuard;
pub(crate) const GENERIC_FAILURE_MEMO: &str = "request could not be processed";
pub(crate) const UNDECODABLE_MEMO: &str = "message body could not be decoded";
pub(crate) struct Obligation {
channel_id: ChannelId,
trace_id: u64,
request: FailedRequest,
reply_to: Vec<TransportProtocol>,
state: Mutex<State>,
}
struct State {
channel_id: ChannelId,
key: Option<SharedKey>,
endpoints: Option<Vec<TransportProtocol>>,
sent: Option<(i32, String)>,
known: Option<(StatusEnum, String)>,
carried: Vec<DeRecEvent>,
}
impl Obligation {
fn new(
channel_id: ChannelId,
key: Option<SharedKey>,
trace_id: u64,
request: FailedRequest,
policy: TransportPolicy,
) -> Self {
let reply_to = channel_store::filter_reply_to(policy, &requested_reply_to(&request));
Self {
channel_id,
trace_id,
request,
reply_to,
state: Mutex::new(State {
channel_id,
key,
endpoints: None,
sent: None,
known: None,
carried: Vec::new(),
}),
}
}
pub(crate) fn for_body(
body: &MessageBody,
channel_id: ChannelId,
key: &SharedKey,
trace_id: u64,
policy: TransportPolicy,
) -> Option<Self> {
let request = match body {
MessageBody::StoreShareRequest(r) => FailedRequest::StoreShare(r.clone()),
MessageBody::VerifyShareRequest(r) => FailedRequest::VerifyShare(r.clone()),
MessageBody::GetSecretIdsVersionsRequest(r) => {
FailedRequest::GetSecretIdsVersions(r.clone())
}
MessageBody::GetShareRequest(r) => FailedRequest::GetShare(r.clone()),
MessageBody::UnpairRequest(r) if r.replica_id.is_none() => {
FailedRequest::Unpair(r.clone())
}
MessageBody::UpdateChannelInfoRequest(r) => FailedRequest::UpdateChannelInfo(r.clone()),
MessageBody::PairRequest(_) | MessageBody::PrePairRequest(_) => {
FailedRequest::Undecodable
}
_ => return None,
};
Some(Self::new(channel_id, Some(*key), trace_id, request, policy))
}
pub(crate) fn undecodable(
channel_id: ChannelId,
key: &SharedKey,
trace_id: u64,
policy: TransportPolicy,
) -> Self {
Self::new(
channel_id,
Some(*key),
trace_id,
FailedRequest::Undecodable,
policy,
)
}
pub(crate) fn for_action(action: &PendingAction, policy: TransportPolicy) -> Option<Self> {
let (channel_id, key, trace_id, request) = match action {
PendingAction::StoreShare {
channel_id,
request,
shared_key,
trace_id,
} => (
channel_id,
shared_key,
trace_id,
FailedRequest::StoreShare(request.clone()),
),
PendingAction::VerifyShare {
channel_id,
request,
shared_key,
trace_id,
} => (
channel_id,
shared_key,
trace_id,
FailedRequest::VerifyShare(request.clone()),
),
PendingAction::Discovery {
channel_id,
request,
shared_key,
trace_id,
} => (
channel_id,
shared_key,
trace_id,
FailedRequest::GetSecretIdsVersions(request.clone()),
),
PendingAction::GetShare {
channel_id,
request,
shared_key,
trace_id,
} => (
channel_id,
shared_key,
trace_id,
FailedRequest::GetShare(request.clone()),
),
PendingAction::Unpair {
channel_id,
request,
shared_key,
trace_id,
} => (
channel_id,
shared_key,
trace_id,
FailedRequest::Unpair(request.clone()),
),
PendingAction::UpdateChannelInfo {
channel_id,
request,
shared_key,
trace_id,
} => (
channel_id,
shared_key,
trace_id,
FailedRequest::UpdateChannelInfo(request.clone()),
),
PendingAction::Pairing { .. }
| PendingAction::PrePair { .. }
| PendingAction::RespondToFailure { .. } => return None,
};
Some(Self::new(
*channel_id,
Some(*key),
*trace_id,
request,
policy,
))
}
pub(crate) fn for_failure(
channel_id: ChannelId,
trace_id: u64,
reply: &ReplyTarget,
request: FailedRequest,
policy: TransportPolicy,
) -> Self {
let obligation = Self::new(channel_id, None, trace_id, request, policy);
{
let mut state = obligation.lock();
state.channel_id = reply.channel_id;
if !reply.endpoints.is_empty() {
state.endpoints = Some(reply.endpoints.clone());
}
}
obligation
}
fn lock(&self) -> MutexGuard<'_, State> {
self.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub(crate) fn kind(&self) -> PendingActionKind {
request_kind(&self.request)
}
pub(crate) fn answer_at(&self, fallback: &[TransportProtocol]) {
let endpoints = if self.reply_to.is_empty() {
fallback.to_vec()
} else {
self.reply_to.clone()
};
self.lock().endpoints = Some(endpoints);
}
pub(crate) fn encrypt_for(&self, channel_id: ChannelId, key: SharedKey) {
let mut state = self.lock();
state.channel_id = channel_id;
state.key = Some(key);
}
fn claim(&self, status: StatusEnum, memo: &str) -> bool {
let mut state = self.lock();
if state.sent.is_some() {
return false;
}
state.sent = Some((status as i32, memo.to_owned()));
true
}
pub(crate) fn fail_with(&self, status: StatusEnum, memo: &str) {
self.lock().known = Some((status, memo.to_owned()));
}
fn carry_refusal(&self, status: StatusEnum, memo: &str, event: DeRecEvent) {
let mut state = self.lock();
state.known = Some((status, memo.to_owned()));
state.carried.push(event);
}
pub(crate) fn answered(&self) -> Option<(i32, String)> {
self.lock().sent.clone()
}
fn failed_after_answer(&self, (status, memo): (i32, String), error: &Error) -> DeRecEvent {
request_failed(
self.channel_id,
self.kind(),
true,
status,
&memo,
error,
None,
)
}
async fn resolve<S: StoreSet>(
&self,
stores: &mut Stores<'_, S>,
local: &Local<'_>,
) -> Result<Option<Target>> {
let (channel_id, key, endpoints) = {
let state = self.lock();
(state.channel_id, state.key, state.endpoints.clone())
};
let endpoints = match endpoints {
Some(endpoints) if !endpoints.is_empty() => endpoints,
_ if !self.reply_to.is_empty() => self.reply_to.clone(),
_ if let Some(author) = replica_author(&self.request) => {
stores
.channels
.load_replica_member(local.secret_id, self.channel_id, author)
.await?
.transports
}
_ if self.arrived_on_group(stores, local).await? => return Ok(None),
_ => {
stores
.channels
.peer_endpoints(local.secret_id, channel_id)
.await?
}
};
let key = match key {
Some(key) => key,
None => match stores
.secrets
.load(local.secret_id, channel_id, SecretKind::SharedKey)
.await?
{
Some(SecretValue::SharedKey(key)) => key,
_ => {
return Err(Error::InvalidInput(
"channel has no shared key — not yet paired",
));
}
},
};
Ok(Some((channel_id, endpoints, key)))
}
async fn arrived_on_group<S: StoreSet>(
&self,
stores: &mut Stores<'_, S>,
local: &Local<'_>,
) -> Result<bool> {
Ok(stores
.channels
.replicas_matching(local.secret_id, ReplicaFilter::default())
.await?
.iter()
.any(|member| member.channel_id == self.channel_id))
}
fn unresolved_target(&self) -> ReplyTarget {
let state = self.lock();
ReplyTarget {
channel_id: state.channel_id,
endpoints: state.endpoints.clone().unwrap_or_default(),
}
}
}
type Target = (ChannelId, Vec<TransportProtocol>, SharedKey);
pub(crate) async fn deliver<T: DeRecTransport>(
obligation: Option<&Obligation>,
transport: &T,
endpoints: &[TransportProtocol],
envelope: Vec<u8>,
status: StatusEnum,
memo: &str,
) -> Result<()> {
if let Some(obligation) = obligation
&& !obligation.claim(status, memo)
{
return Ok(());
}
transport.send(endpoints, envelope).await
}
pub(crate) fn attempted(obligation: Option<&Obligation>) -> bool {
obligation.is_some_and(|o| o.answered().is_some())
}
pub(crate) fn reported(
obligation: Option<&Obligation>,
mut events: Vec<DeRecEvent>,
outcome: Result<()>,
) -> Result<Vec<DeRecEvent>> {
match (
outcome,
obligation.and_then(|o| o.answered().map(|sent| (o, sent))),
) {
(Ok(()), _) => Ok(events),
(Err(error), Some((obligation, sent))) => {
events.push(obligation.failed_after_answer(sent, &error));
Ok(events)
}
(Err(error), None) => Err(error),
}
}
pub(crate) fn refused(
obligation: Option<&Obligation>,
event: DeRecEvent,
status: StatusEnum,
memo: &str,
outcome: Result<()>,
) -> Result<Vec<DeRecEvent>> {
match (outcome, obligation) {
(Ok(()), _) => Ok(vec![event]),
(Err(error), Some(obligation)) if let Some(sent) = obligation.answered() => {
Ok(vec![event, obligation.failed_after_answer(sent, &error)])
}
(Err(error), Some(obligation)) => {
obligation.carry_refusal(status, memo, event);
Err(error)
}
(Err(error), None) => Err(error),
}
}
pub(crate) async fn settle<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
obligation: &Obligation,
auto_respond_on_failure: bool,
outcome: Result<Vec<DeRecEvent>>,
) -> Vec<DeRecEvent> {
let error = match outcome {
Ok(events) => return events,
Err(error) => error,
};
let (known, mut events) = {
let mut state = obligation.lock();
(state.known.take(), mem::take(&mut state.carried))
};
if let Some(sent) = obligation.answered() {
events.push(obligation.failed_after_answer(sent, &error));
return events;
}
let (status, memo) = match (&known, &obligation.request) {
(Some((status, memo)), _) => (*status, memo.as_str()),
(None, FailedRequest::Undecodable) => (StatusEnum::FormatError, UNDECODABLE_MEMO),
(None, _) => failure_status(&error),
};
let target = match obligation.resolve(stores, local).await {
Ok(None) => {
events.push(request_failed(
obligation.channel_id,
obligation.kind(),
false,
status as i32,
memo,
&error,
None,
));
return events;
}
Ok(Some(target)) => Ok(target),
Err(error) => Err(error),
};
if auto_respond_on_failure && let Ok(target) = &target {
let _sent = send_failure(stores, local, obligation, target, status, memo).await;
if obligation.answered().is_some() {
#[cfg(feature = "logging")]
if let Err(send_error) = &_sent {
tracing::warn!(
channel_id = obligation.channel_id.0,
error = %send_error,
"the failure response could not be delivered; it is not sent again"
);
}
events.push(request_failed(
obligation.channel_id,
obligation.kind(),
true,
status as i32,
memo,
&error,
None,
));
return events;
}
}
let reply = match target {
Ok((channel_id, endpoints, _)) => ReplyTarget {
channel_id,
endpoints,
},
Err(_) => obligation.unresolved_target(),
};
let token = has_stored_key(stores, local, reply.channel_id)
.await
.then(|| PendingAction::RespondToFailure {
channel_id: obligation.channel_id,
trace_id: obligation.trace_id,
reply,
request: obligation.request.clone(),
});
events.push(request_failed(
obligation.channel_id,
obligation.kind(),
false,
status as i32,
memo,
&error,
token,
));
events
}
async fn has_stored_key<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
channel_id: ChannelId,
) -> bool {
match stores
.secrets
.load(local.secret_id, channel_id, SecretKind::SharedKey)
.await
{
Ok(Some(SecretValue::SharedKey(_))) | Err(_) => true,
Ok(_) => false,
}
}
pub(crate) async fn respond_to_failure<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
obligation: &Obligation,
status: StatusEnum,
memo: &str,
) -> Result<()> {
let target = obligation
.resolve(stores, local)
.await?
.ok_or(Error::InvalidInput(
"the request names no member of the group channel it arrived on",
))?;
send_failure(stores, local, obligation, &target, status, memo).await
}
async fn send_failure<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
obligation: &Obligation,
(channel_id, endpoints, key): &Target,
status: StatusEnum,
memo: &str,
) -> Result<()> {
use crate::extensions::message_body::MessageBodyExt as _;
let mut body = failure_body(local, &obligation.request, status, memo);
let timestamp = derec_message::current_timestamp();
body.set_timestamp(timestamp);
let envelope = DeRecMessageBuilder::channel()
.channel_id(*channel_id)
.timestamp(timestamp)
.message_body(body)
.trace_id(obligation.trace_id)
.encrypt(key)?
.build()?
.encode_to_vec();
deliver(
Some(obligation),
stores.transport,
endpoints,
envelope,
status,
memo,
)
.await
}
fn failure_body(
local: &Local<'_>,
request: &FailedRequest,
status: StatusEnum,
memo: &str,
) -> MessageBody {
use crate::protocol::handlers;
match request {
FailedRequest::StoreShare(r) => handlers::sharing::failure_response(local, r, status, memo),
FailedRequest::VerifyShare(r) => handlers::verification::failure_response(r, status, memo),
FailedRequest::GetSecretIdsVersions(r) => {
handlers::discovery::failure_response(local, r, status, memo)
}
FailedRequest::GetShare(r) => handlers::recovery::failure_response(local, r, status, memo),
FailedRequest::Unpair(_) => handlers::unpairing::failure_response(status, memo),
FailedRequest::UpdateChannelInfo(_) => {
handlers::update_channel_info::failure_response(status, memo)
}
FailedRequest::Undecodable => MessageBody::ErrorResponse(ErrorResponseMessage {
result: Some(DeRecResult {
status: status as i32,
memo: memo.to_owned(),
}),
timestamp: None,
}),
}
}
pub(crate) fn failure_status(error: &Error) -> (StatusEnum, &'static str) {
match error {
Error::RoleMismatch { .. } => (
StatusEnum::Rejected,
"the sender's role does not permit this request",
),
Error::NoUsableEndpoint { .. } => (
StatusEnum::UnsupportedTransportProtocol,
"no transport endpoint in the request is supported",
),
Error::Transport(_) => (
StatusEnum::UnsupportedTransportProtocol,
"a transport endpoint in the request was refused",
),
_ => (StatusEnum::Fail, GENERIC_FAILURE_MEMO),
}
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn request_failed(
channel_id: ChannelId,
kind: PendingActionKind,
responded: bool,
status: i32,
memo: &str,
error: &Error,
action: Option<PendingAction>,
) -> DeRecEvent {
DeRecEvent::RequestFailed {
channel_id,
action_kind: kind,
responded,
status,
memo: memo.to_owned(),
error_code: error_codes::classify(error).1.name().to_owned(),
message: error.to_string(),
action,
}
}
fn request_kind(request: &FailedRequest) -> PendingActionKind {
match request {
FailedRequest::StoreShare(_) => PendingActionKind::StoreShare,
FailedRequest::VerifyShare(_) => PendingActionKind::VerifyShare,
FailedRequest::GetSecretIdsVersions(_) => PendingActionKind::Discovery,
FailedRequest::GetShare(_) => PendingActionKind::GetShare,
FailedRequest::Unpair(_) => PendingActionKind::Unpair,
FailedRequest::UpdateChannelInfo(_) => PendingActionKind::UpdateChannelInfo,
FailedRequest::Undecodable => PendingActionKind::Failed,
}
}
fn replica_author(request: &FailedRequest) -> Option<u64> {
match request {
FailedRequest::StoreShare(r) => r.replica_id,
FailedRequest::GetSecretIdsVersions(r) => r.replica_id,
FailedRequest::GetShare(r) => r.replica_id,
FailedRequest::Unpair(_)
| FailedRequest::VerifyShare(_)
| FailedRequest::UpdateChannelInfo(_)
| FailedRequest::Undecodable => None,
}
}
fn requested_reply_to(request: &FailedRequest) -> Vec<TransportProtocol> {
use crate::extensions::advertised_endpoints::reply_to_owned;
match request {
FailedRequest::StoreShare(r) => reply_to_owned(r),
FailedRequest::VerifyShare(r) => reply_to_owned(r),
FailedRequest::GetSecretIdsVersions(r) => reply_to_owned(r),
FailedRequest::GetShare(r) => reply_to_owned(r),
FailedRequest::Unpair(r) => reply_to_owned(r),
FailedRequest::UpdateChannelInfo(_) | FailedRequest::Undecodable => Vec::new(),
}
}