Skip to main content

datex_core/runtime/remote_value_sync/
mod.rs

1pub mod synced_value_data;
2
3use crate::{
4    core_compiler::{
5        core_compilation_context::CompileInput,
6        update_compiler::compile_updates,
7    },
8    prelude::*,
9    runtime::{
10        RuntimeInternal,
11        execution::{
12            context::{
13                ExecutionMode, RemoteExecutionContext, RemoteExecutionTarget,
14            },
15            remote_execution_options::RemoteExecutionOptions,
16        },
17    },
18    shared_values::{
19        PointerAddress, ReferenceMutability, ReferencedSharedContainer,
20        SharedContainer, Subscribers,
21        base_shared_value_container::observers::{
22            ObserveOptions, Observer, ObserverError, TransceiverId,
23        },
24        traits::SharedContainerCommon,
25    },
26    value_updates::update_data::Update,
27    values::core_values::endpoint::Endpoint,
28};
29use alloc::rc::Rc;
30use core::{assert_matches, fmt::Display, ops::Deref};
31use log::warn;
32
33#[derive(Debug, PartialEq, Eq)]
34pub enum SubscriberError {
35    NotASelfOwnedContainer,
36    Observer(ObserverError),
37}
38
39impl From<ObserverError> for SubscriberError {
40    fn from(err: ObserverError) -> Self {
41        SubscriberError::Observer(err)
42    }
43}
44
45impl Display for SubscriberError {
46    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
47        match self {
48            SubscriberError::NotASelfOwnedContainer => {
49                write!(f, "The shared container is not self-owned.")
50            }
51            SubscriberError::Observer(err) => {
52                write!(f, "Observer error: {}", err)
53            }
54        }
55    }
56}
57
58impl RuntimeInternal {
59    /// Sends local value updates back to the owner of a (remote) shared container.
60    /// If the container is not mutable, this function does nothing.
61    pub fn sync_value_with_owner(
62        self: Rc<Self>,
63        shared_container: &SharedContainer,
64    ) -> Result<(), SubscriberError> {
65        if shared_container.can_mutate() {
66            // access as weak container so that the Rc can still be garbage collected
67            let weak_container = shared_container
68                .derive_reference_with_max_mutability()
69                .downgrade();
70            let self_clone = self.clone();
71
72            let observer_id = shared_container.observe(Observer {
73                transceiver_id: TransceiverId::Remote(
74                    shared_container.pointer_address().endpoint(),
75                ),
76                callback: Rc::new(move |update| {
77                    if let Some(container) = weak_container.upgrade() {
78                        self_clone.task_manager().register_task(
79                            self_clone.clone().send_update_to_owner(
80                                container,
81                                update.clone(),
82                            ),
83                        );
84                    }
85                }),
86                options: ObserveOptions::default(),
87            })?;
88
89            // store observer
90            let mut synced_values = self.synced_value_data_mut();
91            synced_values
92                .set_owner_observer(shared_container.clone(), observer_id);
93        }
94        Ok(())
95    }
96
97    /// Subscribes an endpoint to a self-owned shared container with the specified access rights.
98    ///
99    /// # Safety
100    /// The caller must ensure that the shared container is self-owned.
101    pub unsafe fn subscribe_endpoint_to_owned_value(
102        self: Rc<Self>,
103        shared_container: &SharedContainer,
104        endpoint: &Endpoint,
105        access_rights: ReferenceMutability,
106    ) -> Result<(), ObserverError> {
107        let mut synced_values = self.synced_value_data_mut();
108        let subscribers = if let Some(subscribers) =
109            synced_values.get_subscribers_mut(shared_container)
110        {
111            subscribers
112                .remote_execution_context_mut()
113                .add_endpoint(endpoint.clone());
114            // TODO: when new subscriber is added, send initial block for context
115            subscribers
116        } else {
117            let observer_id =
118                if shared_container.base_shared_container().is_mutable() {
119                    let container = shared_container.clone();
120                    let self_clone = self.clone();
121                    Some(shared_container.observe(Observer {
122                        transceiver_id: TransceiverId::Remote(Endpoint::ANY),
123                        callback: Rc::new(move |data| {
124                            self_clone
125                                .send_update_to_subscribers(&container, data)
126                        }),
127                        options: ObserveOptions::default(),
128                    })?)
129                } else {
130                    None
131                };
132
133            let context = RemoteExecutionContext::new(
134                vec![endpoint.clone()],
135                ExecutionMode::Static,
136                self.clone().into(),
137            );
138
139            unsafe {
140                synced_values.set_subscribers(
141                    shared_container,
142                    Subscribers::new(observer_id, context),
143                )
144            }
145        };
146        subscribers.add_subscriber(endpoint, access_rights);
147
148        Ok(())
149    }
150
151    /// Sends an update to the owner of the shared container.
152    async fn send_update_to_owner(
153        self: Rc<Self>,
154        container: ReferencedSharedContainer,
155        update: Update,
156    ) {
157        // a= [0, 43, 42]
158        // a= [0, 43, 42]
159        // @a -> a += 42 // + timestamp
160        // ...
161        // if ($a == 4) (
162        //
163        // )
164        let owner = container.pointer_address().endpoint();
165        let mark_as_debug = container.base_shared_container().is_debug();
166
167        let update_dxb = {
168            let lookup = self.pointer_availability_lookup();
169            let endpoints = [owner.clone()];
170            let input = CompileInput::new(lookup.deref(), &endpoints);
171            let mut cache = self.shared_references_cache_mut();
172            compile_updates(
173                &SharedContainer::Referenced(container),
174                &[update.data()],
175                input,
176                &mut cache,
177            )
178        };
179
180        let self_clone = self.clone();
181
182        let context = RemoteExecutionContext::new(
183            vec![owner],
184            ExecutionMode::Static,
185            self.into(),
186        );
187
188        self_clone
189            .execute_remote(
190                &context.target,
191                update_dxb,
192                RemoteExecutionOptions {
193                    is_end_of_context: true,
194                    mark_as_debug,
195                },
196            )
197            .await
198            .expect("Failed to execute remote update block");
199    }
200
201    /// Handles an update to a shared container by notifying all subscribed endpoints.
202    fn send_update_to_subscribers(
203        self: &Rc<Self>,
204        container: &SharedContainer,
205        update: &Update,
206    ) {
207        let subscriber = self.synced_value_data();
208        let subscribers = subscriber.get_subscribers(container);
209
210        if let Some(subscribers) = subscribers {
211            // TODO: don't send full update to source endpoint, but send update info with hash of the value
212            let source_endpoint = Endpoint::from(update.source_id().clone())
213                .as_local_if_endpoint(self.endpoint());
214
215            let endpoints = subscribers
216                .endpoints()
217                .filter_map(|endpoint| {
218                    let normalized_endpoint =
219                        endpoint.as_local_if_endpoint(self.endpoint());
220                    // filter out the source endpoint
221                    if normalized_endpoint == source_endpoint {
222                        None
223                    } else {
224                        Some(normalized_endpoint)
225                    }
226                })
227                .collect::<Vec<_>>();
228
229            if !endpoints.is_empty() {
230                self.task_manager().register_task(
231                    self.clone().send_update_block_to_subscribers(
232                        // TODO: no clone?
233                        container.clone(),
234                        update.clone(),
235                        endpoints,
236                    ),
237                );
238            } else {
239                warn!(
240                    "No endpoints to send update to for container: {:?}",
241                    container.pointer_address()
242                );
243            }
244        } else {
245            warn!(
246                "No subscribers found for container: {:?}",
247                container.pointer_address()
248            );
249        }
250    }
251
252    /// Compiles a DXB block for the given update and sends it to the specified subscriber endpoints.
253    /// Note: this function asserts that the shared container is still owned and that the remote execution
254    /// context still exists. It also asserts that the receiver endpoints are not empty.
255    async fn send_update_block_to_subscribers(
256        self: Rc<RuntimeInternal>,
257        container: SharedContainer,
258        update: Update,
259        receiver_endpoints: Vec<Endpoint>,
260    ) {
261        assert_matches!(
262            container.pointer_address(),
263            PointerAddress::SelfOwned(_)
264        );
265
266        let update_dxb = {
267            let lookup = self.pointer_availability_lookup();
268            let input = CompileInput::new(lookup.deref(), &receiver_endpoints);
269            let mut cache = self.shared_references_cache_mut();
270
271            compile_updates(&container, &[update.data()], input, &mut cache)
272        };
273
274        let mark_as_debug = container.base_shared_container().is_debug();
275
276        let self_clone = self.clone();
277
278        let responses = {
279            let target = RemoteExecutionTarget::new(receiver_endpoints);
280
281            self_clone
282                .execute_remote(
283                    &target,
284                    update_dxb,
285                    RemoteExecutionOptions {
286                        is_end_of_context: true,
287                        mark_as_debug,
288                    },
289                )
290                .await
291                .expect("Failed to execute remote update block")
292        };
293
294        // Remove endpoint from shared contaienr subscriber list if we get an error from the update
295        // TODO: Decide for which errors that should happen (like out of range value update no, crypto error yes)
296        let mut subscriptions = self.synced_value_data_mut();
297        for (response, endpoint) in responses {
298            if response.is_err()
299                && let Some(subscriber) =
300                    subscriptions.get_subscribers_mut(&container)
301            {
302                // remove subscriber
303                warn!(
304                    "Got error response {:?} from endpoint {:?}, removing from subscribers",
305                    response, endpoint
306                );
307                subscriber.remove_subscriber(&endpoint);
308            }
309        }
310    }
311}