1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
use std::{path::PathBuf, sync::Arc, time::Duration};

use anyhow::anyhow;
use exocore_core::{
    cell::Cell,
    futures::{block_on, owned_spawn, sleep, spawn_blocking, spawn_future, BatchingStream},
    time::Clock,
    utils::backoff::BackoffCalculator,
};
use exocore_protos::{
    apps::{in_message::InMessageType, out_message::OutMessageType, InMessage, OutMessage},
    prost::Message,
    store::{EntityQuery, MutationRequest},
};
use exocore_store::store::Store;
use futures::{
    channel::mpsc,
    future::{pending, select_all, FutureExt},
    lock::Mutex,
    Future, SinkExt, StreamExt,
};

use super::wasmtime::WasmTimeRuntime;
use crate::{Config, Error};

const MSG_BUFFER_SIZE: usize = 5000;
const RUNTIME_MSG_BATCH_SIZE: usize = 1000;
const APP_MIN_TICK_TIME: Duration = Duration::from_millis(100);

/// Exocore applications host.
///
/// Executes applications that have a WASM module in a background thread per
/// applications and handles incoming and outgoing messages to the module for
/// store and communication.
pub struct Applications<S: Store> {
    config: Config,
    cell: Cell,
    clock: Clock,
    store: S,
    apps: Vec<Application>,
}

impl<S: Store> Applications<S> {
    pub async fn new(
        config: Config,
        clock: Clock,
        cell: Cell,
        store: S,
    ) -> Result<Applications<S>, Error> {
        let mut apps = Vec::new();
        for app in cell.applications().applications() {
            let cell_app = app.application();

            let app_manifest = cell_app.manifest();
            if app_manifest.module.is_none() {
                continue;
            };

            let module_path = cell_app
                .module_path()
                .ok_or_else(|| anyhow!("Couldn't find module path"))?;

            let app = Application {
                cell: cell.clone(),
                cell_app: cell_app.clone(),
                module_path,
            };
            app.cell_app
                .validate()
                .map_err(|err| anyhow!("Couldn't validate module: {}", err))?;

            apps.push(app);
        }

        Ok(Applications {
            config,
            cell,
            clock,
            store,
            apps,
        })
    }

    /// Starts and runs applications.
    pub async fn run(self) -> Result<(), Error> {
        if self.apps.is_empty() {
            info!("{}: No apps to start. Blocking forever.", self.cell);
            pending::<()>().await;
            return Ok(());
        }

        let mut spawned_apps = Vec::new();
        for app in self.apps {
            spawned_apps.push(owned_spawn(Self::start_app_loop(
                self.clock.clone(),
                self.config,
                app,
                self.store.clone(),
            )));
        }

        // wait for any applications to terminate
        let _ = select_all(spawned_apps).await;

        Ok(())
    }

    async fn start_app_loop(clock: Clock, config: Config, app: Application, store: S) {
        let mut backoff = BackoffCalculator::new(clock, config.restart_backoff);
        loop {
            info!(
                "{}: Starting application (version {})",
                app,
                app.cell_app.version()
            );

            let store = store.clone();
            Self::start_app(&app, store).await;

            backoff.increment_failure();

            let restart_delay = backoff.backoff_duration();
            error!(
                "{}: Application has quit. Restarting in {:?}...",
                app, restart_delay
            );
            sleep(restart_delay).await;
        }
    }

    async fn start_app(app: &Application, store: S) {
        let (in_sender, in_receiver) = mpsc::channel(MSG_BUFFER_SIZE);
        let (out_sender, mut out_receiver) = mpsc::channel(MSG_BUFFER_SIZE);

        // Spawn the application module runtime on a separate thread.
        let runtime_spawn = {
            let env = Arc::new(WiredEnvironment {
                log_prefix: app.to_string(),
                sender: std::sync::Mutex::new(out_sender),
            });

            let app_module_path = app.module_path.clone();
            let app_prefix = app.to_string();
            spawn_blocking(move || -> Result<(), Error> {
                let mut app_runtime = WasmTimeRuntime::from_file(app_module_path, env)?;
                let mut batch_receiver = BatchingStream::new(in_receiver, RUNTIME_MSG_BATCH_SIZE);

                let mut started = false;
                let mut next_tick = sleep(APP_MIN_TICK_TIME);
                loop {
                    let in_messages: Option<Vec<InMessage>> = block_on(async {
                        futures::select! {
                            _ = next_tick.fuse() => Some(vec![]),
                            msgs = batch_receiver.next().fuse() => msgs,
                        }
                    });

                    let in_messages = if let Some(in_messages) = in_messages {
                        in_messages
                    } else {
                        info!(
                            "{}: In message receiver returned none. Stopping app runtime",
                            app_prefix
                        );
                        return Ok(());
                    };
                    let in_messages_count = in_messages.len();

                    for in_message in in_messages {
                        app_runtime.send_message(in_message)?;
                    }

                    let next_tick_duration = app_runtime.tick()?.unwrap_or(APP_MIN_TICK_TIME);
                    next_tick = sleep(next_tick_duration);

                    debug!(
                        "{}: App ticked. {} incoming message, next tick in {:?}",
                        app_prefix, in_messages_count, next_tick_duration
                    );

                    if !started {
                        info!("{}: Application started", app_prefix);
                        started = true;
                    }
                }
            })
        };

        // Spawn a task to handle store requests coming from the application
        let store_worker = {
            let store = store.clone();
            let app_prefix = app.to_string();
            async move {
                let in_sender = Arc::new(Mutex::new(in_sender));
                while let Some(message) = out_receiver.next().await {
                    match OutMessageType::from_i32(message.r#type) {
                        Some(OutMessageType::StoreEntityQuery) => {
                            let store = store.clone();
                            handle_store_message(
                                message.rendez_vous_id,
                                InMessageType::StoreEntityResults,
                                in_sender.clone(),
                                move || handle_entity_query(message, store),
                            )
                        }
                        Some(OutMessageType::StoreMutationRequest) => {
                            let store = store.clone();
                            handle_store_message(
                                message.rendez_vous_id,
                                InMessageType::StoreMutationResult,
                                in_sender.clone(),
                                move || handle_entity_mutation(message, store),
                            )
                        }
                        other => {
                            error!(
                                "{}: Got an unknown message type {:?} with id {}",
                                app_prefix, other, message.r#type
                            );
                        }
                    }
                }

                Ok::<(), Error>(())
            }
        };

        futures::select! {
            res = runtime_spawn.fuse() => {
                info!("{}: App runtime spawn has stopped: {:?}", app, res);
            }
            _ = store_worker.fuse() => {
                info!("{}: Store worker task has stopped", app);
            }
        };
    }
}

fn handle_store_message<F, O>(
    rendez_vous_id: u32,
    reply_type: InMessageType,
    in_sender: Arc<Mutex<mpsc::Sender<InMessage>>>,
    func: F,
) where
    F: (FnOnce() -> O) + Send + 'static,
    O: Future<Output = Result<Vec<u8>, Error>> + Send + 'static,
{
    spawn_future(async move {
        let mut msg = InMessage {
            r#type: reply_type.into(),
            rendez_vous_id,
            ..Default::default()
        };

        let res = func();
        match res.await {
            Ok(res) => msg.data = res,
            Err(err) => msg.error = err.to_string(),
        }

        let mut in_sender = in_sender.lock().await;
        let _ = in_sender.send(msg).await;
    });
}

async fn handle_entity_query<S: Store>(
    out_message: OutMessage,
    store: S,
) -> Result<Vec<u8>, Error> {
    let query = EntityQuery::decode(out_message.data.as_ref())?;
    let res = store.query(query);
    let res = res.await?;

    Ok(res.encode_to_vec())
}

async fn handle_entity_mutation<S: Store>(
    out_message: OutMessage,
    store: S,
) -> Result<Vec<u8>, Error> {
    let mutation = MutationRequest::decode(out_message.data.as_ref())?;
    let res = store.mutate(mutation);
    let res = res.await?;

    Ok(res.encode_to_vec())
}

struct WiredEnvironment {
    log_prefix: String,
    sender: std::sync::Mutex<mpsc::Sender<exocore_protos::apps::OutMessage>>,
}

impl super::wasmtime::HostEnvironment for WiredEnvironment {
    fn handle_message(&self, msg: exocore_protos::apps::OutMessage) {
        let mut sender = self.sender.lock().unwrap();
        if let Err(err) = sender.try_send(msg) {
            error!("Couldn't send message via channel: {}", err)
        }
    }

    fn handle_log(&self, level: log::Level, msg: &str) {
        log!(level, "{}: WASM: {}", self.log_prefix, msg);
    }
}

struct Application {
    cell: Cell,
    cell_app: exocore_core::cell::Application,
    module_path: PathBuf,
}

impl std::fmt::Display for Application {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} App{{{}}}", self.cell, self.cell_app.name())
    }
}