use std::{sync::{atomic::Ordering, Arc, Mutex}, task::Waker};
use super::{core::ObjectCore, state_sink::{ObjectStateSink, ObjectStateSinkSharedMutable}};
use crate::{contract::Contract, exchange::core::ExchangeCore, expose_contract::ExposeContract, object::state_sink::ExposeContractMutable, LocalExchange, ObjectDescriptor};
#[derive(Clone)]
pub struct ObjectExposeContract {
drop_guard: Arc<ObjectExposeContractDropGuard>,
}
struct ObjectExposeContractDropGuard {
shared: Arc<ObjectExposeContractShared>,
}
pub(crate) struct ObjectExposeContractShared {
local_exchange: LocalExchange,
object_core: Arc<ObjectCore>,
composition_cost: u32,
mutable: Mutex<ObjectExposeContractSharedMutable>,
}
struct ObjectExposeContractSharedMutable {
terminated: bool,
object_state_sink_ready_for_check_out: bool,
object_state_sink: Option<Arc<Mutex<ObjectStateSinkSharedMutable>>>,
assigned: bool,
waker: Vec<Waker>,
}
impl ObjectExposeContract {
pub(super) fn new(exchange: LocalExchange, object_core: Arc<ObjectCore>, composition_cost: u32) -> ObjectExposeContract {
let shared = Arc::new(ObjectExposeContractShared {
object_core,
local_exchange: exchange,
composition_cost,
mutable: Mutex::new(ObjectExposeContractSharedMutable {
waker: Vec::new(),
object_state_sink: None,
object_state_sink_ready_for_check_out: false,
assigned: false,
terminated: false,
}),
});
shared.object_core.link_expose_contract(shared.clone());
ObjectExposeContract { drop_guard: Arc::new(ObjectExposeContractDropGuard { shared }) }
}
pub fn descriptor(&self) -> &ObjectDescriptor {
&self.drop_guard.shared.object_core.descriptor
}
pub fn ready(&mut self) -> Option<ObjectStateSink> {
let mut shared_mutable = self.drop_guard.shared.mutable.lock().unwrap();
shared_mutable.check_out_object_state_sink(&self.drop_guard.shared).flatten()
}
pub fn terminate(&mut self) {
self.drop_guard.shared.terminate();
}
}
impl Drop for ObjectExposeContractDropGuard {
fn drop(&mut self) {
self.shared.contract_dropped();
}
}
impl ObjectExposeContractShared {
fn contract_dropped(self: &Arc<Self>) {
self.terminate();
assert_eq!(Arc::strong_count(self), 1);
}
pub(crate) fn object_state_sink_dropped(self: &Arc<Self>) {
let mut mutable = self.mutable.lock().unwrap();
mutable.object_state_sink.take().unwrap();
if mutable.assigned {
mutable.object_state_sink_ready_for_check_out = true;
};
mutable.wake();
}
fn terminate(self: &Arc<Self>) {
let mut mutable = self.mutable.lock().unwrap();
if !mutable.terminated {
mutable.terminate();
drop(mutable);
let dyn_self: Arc<dyn ExposeContract> = self.clone();
self.object_core.unlink_expose_contract(&dyn_self);
self.local_exchange.shared.object_changed(self.object_core.descriptor.clone());
drop(dyn_self);
}
}
}
impl Contract for ObjectExposeContractShared {
fn id(&self) -> usize {
(self as *const Self) as usize
}
fn exchange_core(&self) -> &Arc<ExchangeCore> {
self.local_exchange.shared.exchange_core.as_ref().unwrap()
}
}
impl ObjectExposeContractSharedMutable {
fn wake(&mut self) {
for waker in self.waker.drain(..) {
waker.wake();
}
}
fn check_out_object_state_sink(&mut self, shared: &Arc<ObjectExposeContractShared>) -> Option<Option<ObjectStateSink>> {
if self.terminated {
Some(None)
} else if self.object_state_sink_ready_for_check_out {
if self.object_state_sink.is_some() {
panic!("Double accept")
};
self.object_state_sink_ready_for_check_out = false;
let object_state_sink = ObjectStateSink::new(shared.object_core.clone(), ExposeContractMutable::Object(shared.clone()));
self.object_state_sink = Some(object_state_sink.drop_guard.shared.clone());
Some(Some(object_state_sink))
} else {
None
}
}
fn terminate(&mut self) {
if !self.terminated {
self.terminated = true;
self.wake();
if let Some(object_state_sink) = self.object_state_sink.take() {
object_state_sink.lock().unwrap().contract_terminated();
};
}
}
}
impl ExposeContract for ObjectExposeContractShared {
fn composition_cost(&self) -> u32 {
self.composition_cost
}
fn assign(&self, _object_core: &Arc<ObjectCore>) -> bool {
let mut mutable = self.mutable.lock().unwrap();
if mutable.assigned {
panic!("Double assign");
};
mutable.assigned = true;
if let Some(object_state_sink) = &mutable.object_state_sink {
object_state_sink.lock().unwrap().assign();
} else {
mutable.object_state_sink_ready_for_check_out = true;
};
self.exchange_core().load.fetch_add(self.composition_cost(), Ordering::Relaxed);
mutable.wake();
true
}
fn unassign(&self, _object_core: &Arc<ObjectCore>) -> bool {
let mut mutable = self.mutable.lock().unwrap();
if !mutable.assigned {
panic!("Double unassign (#1)");
};
mutable.assigned = false;
if let Some(object_state_sink) = &mutable.object_state_sink {
object_state_sink.lock().unwrap().unassign();
} else {
mutable.object_state_sink_ready_for_check_out = false;
}
self.exchange_core().load.fetch_sub(self.composition_cost(), Ordering::Relaxed);
mutable.wake();
true
}
fn object(&self) -> bool {
true
}
}
impl futures::Stream for ObjectExposeContract {
type Item = ObjectStateSink;
fn poll_next(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Option<Self::Item>> {
let mut shared_mutable = self.drop_guard.shared.mutable.lock().unwrap();
match shared_mutable.check_out_object_state_sink(&self.drop_guard.shared) {
Some(object_state_sink) => std::task::Poll::Ready(object_state_sink),
None => {
shared_mutable.waker.push(cx.waker().clone());
std::task::Poll::Pending
}
}
}
}
impl std::fmt::Debug for ObjectExposeContractShared {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(&format!("ObjectExposeContract:{}", self.object_core.descriptor))
}
}