Skip to main content

datex_core/dif/
dif_interface.rs

1use crate::{
2    dif::error::{DIFObserveError, DIFUpdateError},
3    prelude::*,
4    runtime::{
5        Runtime,
6        cache::shared_values_cache::{
7            SharedValuesCache, ValueNotFoundInCacheError,
8        },
9        execution::ExecutionError,
10        pointer_address_provider::SelfOwnedPointerAddressProvider,
11    },
12    shared_values::{
13        OwnedSharedContainer, PointerAddress, SelfOwnedPointerAddress,
14        SelfOwnedSharedContainer, SharedContainer, SharedContainerMutability,
15        SharedContainerOwnership,
16        base_shared_value_container::{
17            BaseSharedValueContainer,
18            observers::{
19                ObserveOptions, Observer, ObserverCallback, ObserverId,
20                TransceiverId,
21            },
22        },
23        traits::SharedContainerCommon,
24    },
25    traits::apply::{Apply, ApplyArgument, ApplyError},
26    types::type_definition::{
27        TypeDefinition, callable::CallableTypeDefinition,
28    },
29    value_updates::{UpdateReturn, update_data::Update},
30    values::{
31        core_values::callable::{Callable, CallableBody, NativeCallable},
32        value_container::ValueContainer,
33    },
34};
35use alloc::rc::Rc;
36use core::{cell::RefCell, result::Result};
37
38pub type DIFUpdateResult = Result<UpdateReturn, DIFUpdateError>;
39
40pub struct DIFInterface {
41    pub cache: RefCell<SharedValuesCache>,
42    address_provider: Rc<RefCell<SelfOwnedPointerAddressProvider>>,
43    transceiver_id: TransceiverId,
44}
45
46impl DIFInterface {
47    pub fn new(
48        transceiver_id: TransceiverId,
49        address_provider: Rc<RefCell<SelfOwnedPointerAddressProvider>>,
50    ) -> Self {
51        DIFInterface {
52            cache: RefCell::new(SharedValuesCache::default()),
53            address_provider,
54            transceiver_id,
55        }
56    }
57}
58impl DIFInterface {
59    /// Returns a list of all [ObserverCallback]s that are currently active for the pointer
60    pub fn get_current_observers(
61        &self,
62        address: &PointerAddress,
63        source_id: &TransceiverId,
64    ) -> Result<Vec<ObserverCallback>, ValueNotFoundInCacheError> {
65        let shared_container = self
66            .cache
67            .borrow()
68            .try_get_shared_container_immutable_reference(address)?;
69        Ok(shared_container.get_current_observers(source_id))
70    }
71
72    /// Registers a native callable function in the DIFInterface as a shared value and returns its pointer address.
73    pub fn register_callable(
74        &self,
75        callable: NativeCallable,
76        name: Option<String>,
77        signature: CallableTypeDefinition,
78    ) -> SelfOwnedPointerAddress {
79        let callable = Callable {
80            name,
81            signature: signature.clone(),
82            body: CallableBody::Native(callable),
83            creator: Default::default(),
84            docs: None,
85        };
86        let shared_base = BaseSharedValueContainer::try_new(
87            ValueContainer::from(callable),
88            TypeDefinition::Callable(signature),
89            SharedContainerMutability::Immutable,
90        )
91        .unwrap();
92        self.create_pointer(shared_base)
93    }
94
95    /// Executes an apply operation, applying the `value` to the `callee`.
96    pub fn apply_sync(
97        &self,
98        runtime: &Runtime,
99        callee: ValueContainer,
100        args: Vec<ApplyArgument>,
101    ) -> Result<(Option<ValueContainer>, Vec<ValueContainer>), ApplyError> {
102        callee.try_apply_sync_checked(runtime, args)
103    }
104
105    /// Executes an async apply operation, applying the `value` to the `callee`.
106    pub async fn apply_async(
107        self: Rc<Self>,
108        runtime: &Runtime,
109        callee: ValueContainer,
110        args: Vec<ApplyArgument>,
111    ) -> Result<(Option<ValueContainer>, Vec<ValueContainer>), ApplyError> {
112        callee.try_apply_async_checked(runtime, args).await
113    }
114
115    /// Calls async method on a value
116    pub fn call_method_sync(
117        &self,
118        runtime: &Runtime,
119        callee: ValueContainer,
120        method: String,
121        args: Vec<ApplyArgument>,
122    ) -> Result<(Option<ValueContainer>, Vec<ValueContainer>), ExecutionError>
123    {
124        let callee_arg = ApplyArgument::from(callee);
125        callee_arg.try_call_method_sync(&method, args, runtime)
126    }
127
128    /// Calls an async method on a value
129    pub async fn call_method_async(
130        self: Rc<Self>,
131        runtime: &Runtime,
132        callee: ValueContainer,
133        method: String,
134        args: Vec<ApplyArgument>,
135    ) -> Result<(Option<ValueContainer>, Vec<ValueContainer>), ExecutionError>
136    {
137        let callee_arg = ApplyArgument::from(callee);
138        callee_arg
139            .try_call_method_async(&method, args, runtime)
140            .await
141    }
142
143    /// Creates a new owned local pointer and stores it in memory.
144    /// Returns the [SelfOwnedPointerAddress] of the newly created pointer.
145    pub fn create_pointer(
146        &self,
147        value: BaseSharedValueContainer,
148    ) -> SelfOwnedPointerAddress {
149        let container = OwnedSharedContainer::new_from_self_owned_container(
150            SelfOwnedSharedContainer::new(
151                value,
152                &mut self.address_provider.borrow_mut(),
153            ),
154        );
155
156        let pointer_address = container.pointer_address().clone();
157        self.cache
158            .borrow_mut()
159            .store_shared_container(SharedContainer::Owned(container));
160        pointer_address
161    }
162
163    /// Resolves a pointer address of a pointer that is currently in memory to its [SharedContainer].
164    /// Returns an error if the pointer is not found in memory.
165    pub fn resolve_pointer_address(
166        &self,
167        address: PointerAddress,
168    ) -> Result<SharedContainer, ValueNotFoundInCacheError> {
169        self.cache
170            .borrow()
171            .try_get_shared_container(&address)
172            .cloned()
173    }
174
175    pub fn has_address_with_ownership(
176        &self,
177        pointer_address: &PointerAddress,
178        ownership: SharedContainerOwnership,
179    ) -> bool {
180        self.cache
181            .borrow()
182            .has_address_with_ownership(pointer_address, ownership)
183    }
184
185    /// Starts observing changes to the pointer at the given address.
186    /// As long as the pointer is observed, it will not be garbage collected.
187    pub fn observe_pointer(
188        &self,
189        address: PointerAddress,
190        options: ObserveOptions,
191        callback: impl Fn(&Update) + 'static,
192    ) -> Result<ObserverId, DIFObserveError> {
193        let cache = self.cache.borrow_mut();
194        let shared_container_ref = cache
195            .try_get_shared_container(&address)
196            .map_err(|_| DIFObserveError::ReferenceNotFound)?;
197        Ok(shared_container_ref.observe(Observer {
198            transceiver_id: self.transceiver_id.clone(),
199            options,
200            callback: Rc::new(callback),
201        })?)
202    }
203
204    /// Updates the options for an existing observer on the pointer at the given address.
205    /// If the observer does not exist, an error is returned.
206    pub fn update_observer_options(
207        &self,
208        address: PointerAddress,
209        observer_id: ObserverId,
210        options: ObserveOptions,
211    ) -> Result<(), DIFObserveError> {
212        let cache = self.cache.borrow_mut();
213        let shared_container_ref = cache
214            .try_get_shared_container(&address)
215            .map_err(|_| DIFObserveError::ReferenceNotFound)?;
216        shared_container_ref.update_observer_options(observer_id, options)?;
217        Ok(())
218    }
219
220    /// Stops observing changes to the pointer at the given address.
221    /// If no other references to the pointer exist, it may be garbage collected after this call.
222    pub fn unobserve_pointer(
223        &self,
224        address: PointerAddress,
225        observer_id: ObserverId,
226    ) -> Result<(), DIFObserveError> {
227        let cache = self.cache.borrow_mut();
228        let shared_container_ref = cache
229            .try_get_shared_container(&address)
230            .map_err(|_| DIFObserveError::ReferenceNotFound)?;
231        shared_container_ref.unobserve(observer_id)?;
232        Ok(())
233    }
234
235    // TODO: lock/unlock pointers
236}