use std::{
collections::{BTreeMap, HashMap},
fmt,
future::Future,
sync::Arc,
};
use chrono::{DateTime, TimeDelta, Utc};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use crate::{
Error, Quoter, Result,
error::ErrorCode,
flows::records,
model::{Fill, FillRole, FillState, MakerLeg, PaymentLeg},
store::Journal,
types::{FillId, VenueId},
};
const STUCK: TimeDelta = TimeDelta::seconds(15);
pub trait FillSource: Send + Sync {
fn fills(&self) -> impl Future<Output = Result<Vec<Fill>>> + Send;
fn accept(&self, id: FillId) -> impl Future<Output = Result<()>> + Send;
fn deliver(&self, id: FillId, hash: &str) -> impl Future<Output = Result<Fill>> + Send;
}
impl FillSource for Quoter {
async fn fills(&self) -> Result<Vec<Fill>> {
Quoter::fills(self).list().await
}
async fn accept(&self, id: FillId) -> Result<()> {
Quoter::fills(self).accept(id).await
}
async fn deliver(&self, id: FillId, hash: &str) -> Result<Fill> {
Quoter::fills(self).deliver(id, hash).await
}
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{0}")]
pub struct Refused(pub String);
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DeliveryError {
#[error(transparent)]
Refused(#[from] Refused),
#[error("{0}")]
Venue(String),
#[error(transparent)]
Lamarge(#[from] Error),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DeliveryOutcome {
Reported,
Failed,
Dropped,
Refused,
Unknown,
}
pub trait DeliveryRecord: Clone + Serialize + DeserializeOwned + Send + Sync + 'static {
fn fill_id(&self) -> FillId;
fn outcome(&self) -> Option<DeliveryOutcome>;
}
pub type Deliveries<D> = BTreeMap<String, D>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Retry {
at: DateTime<Utc>,
wait: TimeDelta,
}
#[derive(Debug, Default, Clone)]
pub struct Backoff(HashMap<String, Retry>);
impl Backoff {
pub fn clear(&mut self, id: &str) {
self.0.remove(id);
}
}
#[derive(Serialize, Deserialize)]
#[serde(bound = "D: DeliveryRecord")]
struct Record<D> {
deliveries: Deliveries<D>,
}
pub struct DeliveryCore {
venue: VenueId,
send_margin: TimeDelta,
journal: Journal,
key: String,
clock: Arc<dyn Fn() -> DateTime<Utc> + Send + Sync>,
accepting: bool,
stuck_since: Option<DateTime<Utc>>,
report_at: HashMap<String, Retry>,
}
impl fmt::Debug for DeliveryCore {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DeliveryCore")
.field("venue", &self.venue)
.field("key", &self.key)
.field("accepting", &self.accepting)
.field("stuck_since", &self.stuck_since)
.finish_non_exhaustive()
}
}
impl DeliveryCore {
pub fn now(&self) -> DateTime<Utc> {
(self.clock)()
}
pub async fn load<D: DeliveryRecord>(&self) -> Result<Deliveries<D>> {
let record = records::load::<Record<D>>(&self.journal, &self.key).await?;
Ok(record.map_or_else(Deliveries::new, |record| record.deliveries))
}
pub async fn save<D: DeliveryRecord>(&self, deliveries: &Deliveries<D>) -> Result<()> {
let record = Record { deliveries: deliveries.clone() };
records::save(&self.journal, &self.key, &record, false).await
}
pub async fn record<D: DeliveryRecord>(
&self,
deliveries: &mut Deliveries<D>,
delivery: D,
) -> Result<()> {
deliveries.insert(delivery.fill_id().to_string(), delivery);
self.save(deliveries).await
}
pub fn awaits(&self, fill: Option<&Fill>) -> bool {
fill.is_some_and(|fill| {
fill.payment_leg == PaymentLeg::Locked
&& matches!(fill.maker_leg, MakerLeg::None | MakerLeg::Abandoned)
&& fill.report_by.is_none_or(|by| by > self.now())
})
}
pub fn turn(&self, backoff: &mut Backoff, id: &str) -> bool {
let now = self.now();
let last = backoff.0.get(id).copied();
if last.is_some_and(|last| last.at > now) {
return false;
}
let wait = (last.map_or(TimeDelta::milliseconds(250), |last| last.wait) * 2)
.min(TimeDelta::seconds(5));
backoff.0.insert(id.to_owned(), Retry { at: now + wait, wait });
true
}
pub fn report_due(&self, id: &str) -> bool {
self.report_at.get(id).is_none_or(|retry| retry.at <= self.now())
}
pub async fn report<S: FillSource>(
&mut self,
source: &S,
id: FillId,
hash: &str,
) -> Option<DeliveryOutcome> {
let key = id.to_string();
let error = match source.deliver(id, hash).await {
Ok(fill) if fill.delivery_hash.as_deref() == Some(hash) => {
self.report_at.remove(&key);
tracing::info!(fill = %id, state = %fill.state, "delivered");
return Some(DeliveryOutcome::Reported);
}
Ok(_) => Error::InvalidRequest("the server recorded another delivery".into()),
Err(error) => error,
};
let code = error.code().cloned();
if matches!(
code,
Some(ErrorCode::ValidationError | ErrorCode::StateConflict | ErrorCode::NotFound)
) {
tracing::warn!(fill = %id, %error, "delivery refused");
return Some(DeliveryOutcome::Failed);
}
let last = self.report_at.get(&key).map(|retry| retry.wait);
let wait = if code == Some(ErrorCode::DeliveryPending) {
(last.unwrap_or(TimeDelta::milliseconds(500)) * 2).min(TimeDelta::seconds(30))
} else {
TimeDelta::seconds(1)
};
self.report_at.insert(key, Retry { at: self.now() + wait, wait });
tracing::info!(fill = %id, %error, "report pending");
None
}
}
pub trait DeliveryVenue: Send {
type Record: DeliveryRecord;
fn venue(&self) -> VenueId;
fn send_margin(&self) -> TimeDelta;
fn settle<S: FillSource>(
&mut self,
core: &mut DeliveryCore,
source: &S,
id: &str,
fill: Option<&Fill>,
deliveries: &mut Deliveries<Self::Record>,
) -> impl Future<Output = std::result::Result<bool, DeliveryError>> + Send;
fn deliver<S: FillSource>(
&mut self,
core: &mut DeliveryCore,
source: &S,
due: Vec<Fill>,
deliveries: &mut Deliveries<Self::Record>,
) -> impl Future<Output = std::result::Result<bool, DeliveryError>> + Send;
}
pub struct VenueDeliverer<V: DeliveryVenue> {
venue: V,
core: DeliveryCore,
}
impl<V: DeliveryVenue + fmt::Debug> fmt::Debug for VenueDeliverer<V> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("VenueDeliverer")
.field("venue", &self.venue)
.field("core", &self.core)
.finish()
}
}
impl<V: DeliveryVenue> VenueDeliverer<V> {
pub fn new(venue: V, journal: Journal) -> Self {
let id = venue.venue();
let core = DeliveryCore {
key: format!("deliveries:{id}"),
venue: id,
send_margin: venue.send_margin(),
journal,
clock: Arc::new(Utc::now),
accepting: true,
stuck_since: None,
report_at: HashMap::new(),
};
Self { venue, core }
}
#[must_use]
pub fn clock(mut self, clock: impl Fn() -> DateTime<Utc> + Send + Sync + 'static) -> Self {
self.core.clock = Arc::new(clock);
self
}
pub fn venue(&self) -> &V {
&self.venue
}
pub async fn deliveries(&self) -> Result<Deliveries<V::Record>> {
self.core.load().await
}
pub fn stop_accepting(&mut self) {
self.core.accepting = false;
}
pub fn blocked(&self) -> bool {
self.core.stuck_since.is_some_and(|since| self.core.now() - since >= STUCK)
}
pub async fn run<S: FillSource>(
&mut self,
source: &S,
) -> std::result::Result<(), DeliveryError> {
let pass = self.pass(source).await;
let now = self.core.now();
match pass {
Ok(true) => self.core.stuck_since = None,
Ok(false) | Err(_) => {
self.core.stuck_since.get_or_insert(now);
}
}
pass.map(|_| ())
}
pub async fn outstanding<S: FillSource>(&self, source: &S) -> Result<usize> {
let deliveries = self.core.load::<V::Record>().await?;
let open = deliveries.values().filter(|delivery| delivery.outcome().is_none()).count();
let now = self.core.now();
let fills = source.fills().await?;
let sendable = fills
.iter()
.filter(|fill| {
fill.role == FillRole::Maker
&& fill.to_venue == self.core.venue
&& fill.maker_leg == MakerLeg::None
&& (matches!(fill.state, FillState::Reserved | FillState::Paid)
|| (fill.state == FillState::Prepared && fill.maker_accepted_at.is_some()))
&& fill.deliver_by.is_some_and(|by| by - self.core.send_margin > now)
})
.count();
Ok(open + sendable)
}
async fn pass<S: FillSource>(
&mut self,
source: &S,
) -> std::result::Result<bool, DeliveryError> {
let mut deliveries = self.core.load::<V::Record>().await?;
let fills: Vec<Fill> = source
.fills()
.await?
.into_iter()
.filter(|fill| {
fill.role == FillRole::Maker
&& fill.to_venue == self.core.venue
&& fill.delivery_to.is_some()
})
.collect();
let open: Vec<String> = deliveries
.iter()
.filter(|(_, delivery)| delivery.outcome().is_none())
.map(|(id, _)| id.clone())
.collect();
let mut unknown = false;
for id in open {
let fill = fills.iter().find(|fill| fill.id.to_string() == id);
match self.venue.settle(&mut self.core, source, &id, fill, &mut deliveries).await {
Ok(settled) => unknown |= !settled,
Err(error) => {
unknown = true;
tracing::warn!(fill = %id, %error, "delivery unsettled");
}
}
}
if unknown {
return Ok(false);
}
let now = self.core.now();
let margin = self.core.send_margin;
let mut due: Vec<Fill> = fills
.iter()
.filter(|fill| {
!deliveries.contains_key(&fill.id.to_string())
&& fill.state == FillState::Paid
&& fill.maker_leg == MakerLeg::None
&& fill.delivery_hash.is_none()
&& fill.payment_verified_at.is_some()
&& fill.deliver_by.is_some_and(|by| by - now > margin)
})
.cloned()
.collect();
due.sort_by_key(|fill| fill.deliver_by);
let progressed = self.venue.deliver(&mut self.core, source, due, &mut deliveries).await?;
if !progressed || !self.core.accepting {
return Ok(progressed);
}
let requests: Vec<FillId> = fills
.iter()
.filter(|fill| {
fill.maker_accept_by.is_some_and(|by| by > now)
&& fill.maker_accepted_at.is_none()
&& matches!(fill.state, FillState::Prepared | FillState::Reserved)
&& fill.maker_leg == MakerLeg::None
&& fill.payment_leg == PaymentLeg::None
})
.map(|fill| fill.id)
.collect();
if !requests.is_empty() {
self.core.save(&deliveries).await?;
let accepted =
futures_util::future::join_all(requests.iter().map(|id| source.accept(*id))).await;
for (id, outcome) in requests.iter().zip(accepted) {
match outcome {
Ok(()) => tracing::info!(fill = %id, "accepted for delivery"),
Err(error) => tracing::warn!(fill = %id, %error, "acceptance pending"),
}
}
}
Ok(true)
}
}
#[cfg(test)]
pub(crate) mod testing;