tembra_runtime/host/
resources.rs1use super::*;
4
5#[derive(Clone)]
7pub struct Cancellation(pub(super) Rc<CancellationState>);
8
9pub(super) struct CancellationState {
10 cancelled: Cell<bool>,
11 reason: Cell<&'static str>,
13 send: RefCell<Option<oneshot::Sender<()>>>,
14 wait: Shared<LocalBoxFuture<'static, ()>>,
15}
16
17pub type ResourceSignal = Cancellation;
19
20impl Cancellation {
21 pub(super) fn new(reason: &'static str) -> Self {
22 let (send, receive) = oneshot::channel();
23 Self(Rc::new(CancellationState {
24 cancelled: Cell::new(false),
25 reason: Cell::new(reason),
26 send: RefCell::new(Some(send)),
27 wait: async move {
28 let _ = receive.await;
29 }
30 .boxed_local()
31 .shared(),
32 }))
33 }
34
35 pub(super) fn cancel(&self) {
36 self.0.cancelled.set(true);
37 if let Some(send) = self.0.send.borrow_mut().take() {
38 let _ = send.send(());
39 }
40 }
41
42 pub(super) fn cancel_because(&self, reason: &'static str) {
44 if !self.0.cancelled.get() {
45 self.0.reason.set(reason);
46 }
47 self.0.cancelled.set(true);
48 if let Some(send) = self.0.send.borrow_mut().take() {
49 let _ = send.send(());
50 }
51 }
52
53 pub fn is_cancelled(&self) -> bool {
55 self.0.cancelled.get()
56 }
57
58 pub fn check(&self) -> Result<()> {
60 if self.is_cancelled() {
61 Err(Error::new(
62 core::Code::Cancelled,
63 self.0.reason.get(),
64 "operation was cancelled",
65 ))
66 } else {
67 Ok(())
68 }
69 }
70
71 pub async fn cancelled(&self) {
73 self.0.wait.clone().await;
74 }
75}
76
77#[derive(Clone)]
78pub struct ResourceKey {
79 pub(super) host: Host,
80 pub(super) id: core::Id,
81 pub(super) name: Rc<str>,
83 pub(super) version: u32,
84}
85
86pub struct Resource<T> {
87 pub(super) key: ResourceKey,
88 pub(super) marker: std::marker::PhantomData<T>,
89}
90impl<T: 'static> Resource<T> {
91 pub fn key(&self) -> ResourceKey {
93 self.key.clone()
94 }
95
96 pub fn value(&self) -> Result<Rc<T>> {
99 let host = &self.key.host;
100 let id = host.kernel().resource_value(self.key.id)?;
101 let value = host
102 .0
103 .values
104 .borrow()
105 .get(&id)
106 .map(|record| record.value.clone())
107 .ok_or_else(|| {
108 Error::new(
109 core::Code::Gone,
110 Reason::Resource,
111 format!("the value of the resource `{}` was released", self.key.name),
112 )
113 })?;
114 value.downcast().map_err(|_| {
115 Error::invalid(
116 Reason::RustType,
117 format!(
118 "the resource `{}` holds a value of another Rust type than the one it is \
119 read as",
120 self.key.name
121 ),
122 )
123 })
124 }
125}
126
127impl<T> Clone for Resource<T> {
128 fn clone(&self) -> Self {
129 Self {
130 key: self.key.clone(),
131 marker: std::marker::PhantomData,
132 }
133 }
134}
135impl<T> Resource<T> {
136 pub fn version(&self) -> u32 {
138 self.key.version
139 }
140}