ockam_api 0.93.0

Ockam's request-response API
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
use rand::random;
use std::path::{Path, PathBuf};
use tokio::sync::broadcast::{channel, Receiver, Sender};

use ockam::SqlxDatabase;
use ockam_core::env::get_env_with_default;
use ockam_node::database::{DatabaseConfiguration, DatabaseType};

use crate::cli_state::error::Result;
use crate::cli_state::CliStateError;
use crate::logs::ExportingEnabled;
use crate::terminal::notification::Notification;

pub const OCKAM_HOME: &str = "OCKAM_HOME";

/// Maximum number of notifications present in the channel
const NOTIFICATIONS_CHANNEL_CAPACITY: usize = 16;

/// The CliState struct manages all the data persisted locally.
///
/// The data is saved to several files:
///
/// - The "nodes" database file. That file contains most of the configuration for the nodes running locally: project, node,
///   inlets, outlets, etc... That file is deleted when the `ockam reset` command is executed
///
/// - The "application" database file. That file stores the tracing data which needs to persist across all commands
///   including reset
///
/// - One file per additional vault created with the `ockam vault create` command
///
/// The database files are accessed with the SqlxDatabase struct, and use different migration files to define their
/// schema.
///
/// On top of each SqlxDatabase, there are different repositories. A Repository encapsulates SQL queries for
/// creating / updating / deleting entities. Some examples of entities that are persisted: Project, Space, Vault, Identity, etc...
///
/// The repositories themselves are not accessible from the `CliState` directly since it is often
/// necessary to use more than one repository to implement a given behaviour. For example deleting
/// an identity requires to query the nodes that are using that identity and only delete it if no
/// node is using that identity
///
#[derive(Debug, Clone)]
pub struct CliState {
    pub mode: CliStateMode,
    database: SqlxDatabase,
    application_database: SqlxDatabase,
    exporting_enabled: ExportingEnabled,
    /// Broadcast channel to be notified of major events during a process supported by the CliState API
    notifications: Sender<Notification>,
}

impl CliState {
    pub fn dir(&self) -> Result<PathBuf> {
        match &self.mode {
            CliStateMode::Persistent(dir) => Ok(dir.to_path_buf()),
            CliStateMode::InMemory => Self::default_dir(),
        }
    }

    pub fn database(&self) -> SqlxDatabase {
        self.database.clone()
    }

    pub fn database_ref(&self) -> &SqlxDatabase {
        &self.database
    }

    pub fn database_configuration(&self) -> Result<DatabaseConfiguration> {
        Self::make_database_configuration(&self.mode)
    }

    pub fn is_using_in_memory_database(&self) -> Result<bool> {
        match self.database_configuration()? {
            DatabaseConfiguration::SqliteInMemory { .. } => Ok(true),
            _ => Ok(false),
        }
    }

    pub fn is_database_path(&self, path: &Path) -> bool {
        let database_configuration = self.database_configuration().ok();
        match database_configuration {
            Some(c) => c.path() == Some(path.to_path_buf()),
            None => false,
        }
    }

    pub fn application_database(&self) -> SqlxDatabase {
        self.application_database.clone()
    }

    pub fn application_database_configuration(&self) -> Result<DatabaseConfiguration> {
        Self::make_application_database_configuration(&self.mode)
    }

    pub fn subscribe_to_notifications(&self) -> Receiver<Notification> {
        self.notifications.subscribe()
    }

    pub fn notify_message(&self, message: impl Into<String>) {
        self.notify(Notification::message(message));
    }

    pub fn notify_progress(&self, message: impl Into<String>) {
        self.notify(Notification::progress(message));
    }

    pub fn notify_progress_finish(&self, message: impl Into<String>) {
        self.notify(Notification::progress_finish(Some(message.into())));
    }

    pub fn notify_progress_finish_and_clear(&self) {
        self.notify(Notification::progress_finish(None));
    }

    fn notify(&self, notification: Notification) {
        let _ = self.notifications.send(notification);
    }
}

/// These functions allow to create and reset the local state
impl CliState {
    /// Return a new CliState using a default directory to store its data or
    /// using an in-memory storage if the OCKAM_SQLITE_IN_MEMORY environment variable is set to true
    pub async fn new(in_memory: bool) -> Result<Self> {
        let mode = if in_memory {
            CliStateMode::InMemory
        } else {
            CliStateMode::with_default_dir()?
        };

        Self::create(mode).await
    }

    /// Stop nodes and remove all the directories storing state
    /// Don't touch the database data if Postgres is used and reset was called accidentally.
    pub async fn reset(&self) -> Result<()> {
        if Self::make_database_configuration(&self.mode)?.database_type() == DatabaseType::Postgres
        {
            Err(CliStateError::InvalidOperation(
                "Cannot reset the database when using Postgres".to_string(),
            ))
        } else {
            self.delete_all_named_identities().await?;
            self.delete_all_nodes().await?;
            self.delete_all_named_vaults().await?;
            self.delete().await
        }
    }

    /// Removes all the directories storing state without loading the current state
    /// The database data is only removed if the database is a SQLite one
    pub fn hard_reset() -> Result<()> {
        let dir = Self::default_dir()?;
        Self::delete_at(&dir)
    }

    /// Delete the local database and log files
    pub async fn delete(&self) -> Result<()> {
        self.delete_local_data()
    }

    /// Delete the local data on disk: sqlite database file and log files
    pub fn delete_local_data(&self) -> Result<()> {
        if let CliStateMode::Persistent(dir) = &self.mode {
            Self::delete_at(dir)?;
        }
        Ok(())
    }

    /// Reset all directories and return a new CliState
    pub async fn recreate(&self) -> Result<CliState> {
        self.reset().await?;
        Self::create(self.mode.clone()).await
    }

    /// Backup and reset is used to save aside
    /// some corrupted local state for later inspection and then reset the state.
    /// The database is backed-up only if it is a SQLite database.
    pub async fn backup_and_reset() -> Result<()> {
        let dir = Self::default_dir()?;

        // Reset backup directory
        let backup_dir = Self::backup_default_dir()?;
        if backup_dir.exists() {
            let _ = std::fs::remove_dir_all(&backup_dir);
        }
        std::fs::create_dir_all(&backup_dir)?;

        // Move state to backup directory
        for entry in std::fs::read_dir(&dir)? {
            let entry = entry?;
            let from = entry.path();
            let to = backup_dir.join(entry.file_name());
            std::fs::rename(from, to)?;
        }

        // Reset state
        Self::delete_at(&dir)?;
        Self::create(CliStateMode::Persistent(dir.clone())).await?;

        let backup_dir = CliState::backup_default_dir()?;
        eprintln!("The {dir:?} directory has been reset and has been backed up to {backup_dir:?}");
        Ok(())
    }

    /// Returns the default backup directory for the CLI state.
    pub fn backup_default_dir() -> Result<PathBuf> {
        let dir = Self::default_dir()?;
        let dir_name = dir.file_name().and_then(|n| n.to_str()).ok_or_else(|| {
            CliStateError::InvalidOperation(
                "The $OCKAM_HOME directory does not have a valid name".to_string(),
            )
        })?;
        let parent = dir.parent().ok_or_else(|| {
            CliStateError::InvalidOperation(
                "The $OCKAM_HOME directory does not a valid parent directory".to_string(),
            )
        })?;
        Ok(parent.join(format!("{dir_name}.bak")))
    }
}

/// Low-level functions for creating / deleting CliState files
impl CliState {
    /// Create a new CliState where the data is stored at a given path
    pub async fn create(mode: CliStateMode) -> Result<Self> {
        if let CliStateMode::Persistent(ref dir) = mode {
            std::fs::create_dir_all(dir.as_path())?;
        }
        let database = SqlxDatabase::create(&Self::make_database_configuration(&mode)?).await?;
        debug!("Opened the main database with options {:?}", database);

        // TODO: This should not be called unless we're running the App
        let application_database = SqlxDatabase::create_application_database(
            &Self::make_application_database_configuration(&mode)?,
        )
        .await?;
        debug!(
            "Opened the application database with options {:?}",
            application_database
        );

        let (notifications, _) = channel::<Notification>(NOTIFICATIONS_CHANNEL_CAPACITY);

        let state = Self {
            mode,
            database,
            application_database,
            // We initialize the CliState with no tracing.
            // Once the logging/tracing options have been determined, then
            // the function set_tracing_enabled can be used to enable tracing, which
            // is eventually used to trace user journeys.
            exporting_enabled: ExportingEnabled::Off,
            notifications,
        };

        Ok(state)
    }

    pub fn is_tracing_enabled(&self) -> bool {
        self.exporting_enabled == ExportingEnabled::On
    }

    pub fn set_tracing_enabled(self, enabled: bool) -> CliState {
        CliState {
            exporting_enabled: if enabled {
                ExportingEnabled::On
            } else {
                ExportingEnabled::Off
            },
            ..self
        }
    }

    /// If the postgres database is configured, return the postgres configuration
    ///
    pub(super) fn make_database_configuration(
        mode: &CliStateMode,
    ) -> Result<DatabaseConfiguration> {
        match mode {
            CliStateMode::Persistent(root_path) => {
                let sqlite_path = root_path.join("database.sqlite3");
                match DatabaseConfiguration::postgres_with_legacy_sqlite_path(Some(
                    sqlite_path.clone(),
                ))? {
                    Some(configuration) => Ok(configuration),
                    None => Ok(DatabaseConfiguration::sqlite(sqlite_path)),
                }
            }
            CliStateMode::InMemory => Ok(DatabaseConfiguration::sqlite_in_memory()),
        }
    }

    /// If the postgres database is configured, return the postgres configuration
    pub(super) fn make_application_database_configuration(
        mode: &CliStateMode,
    ) -> Result<DatabaseConfiguration> {
        match DatabaseConfiguration::postgres()? {
            Some(configuration) => Ok(configuration),
            None => match mode {
                CliStateMode::Persistent(root_path) => Ok(DatabaseConfiguration::sqlite(
                    root_path.join("application_database.sqlite3"),
                )),
                CliStateMode::InMemory => Ok(DatabaseConfiguration::sqlite_in_memory()),
            },
        }
    }

    pub(super) fn make_node_dir_path(root_path: impl AsRef<Path>, node_name: &str) -> PathBuf {
        Self::make_nodes_dir_path(root_path).join(node_name)
    }

    pub(super) fn make_command_log_path(
        root_path: impl AsRef<Path>,
        command_name: &str,
    ) -> PathBuf {
        Self::make_commands_log_dir_path(root_path).join(command_name)
    }

    pub(super) fn make_nodes_dir_path(root_path: impl AsRef<Path>) -> PathBuf {
        root_path.as_ref().join("nodes")
    }

    pub(super) fn make_commands_log_dir_path(root_path: impl AsRef<Path>) -> PathBuf {
        root_path.as_ref().join("commands")
    }

    /// Delete the state files
    fn delete_at(root_path: &PathBuf) -> Result<()> {
        // Delete nodes logs
        let _ = std::fs::remove_dir_all(Self::make_nodes_dir_path(root_path));
        // Delete command logs
        let _ = std::fs::remove_dir_all(Self::make_commands_log_dir_path(root_path));
        // Delete the nodes database, keep the application database
        if let Some(path) =
            Self::make_database_configuration(&CliStateMode::Persistent(root_path.clone()))?.path()
        {
            std::fs::remove_file(path)?;
        };
        Ok(())
    }

    /// Returns the default directory for the CLI state.
    /// That directory is determined by `OCKAM_HOME` environment variable and is
    /// $OCKAM_HOME/.ockam.
    ///
    /// If $OCKAM_HOME is not defined, then $HOME is used instead
    pub(super) fn default_dir() -> Result<PathBuf> {
        Ok(get_env_with_default::<PathBuf>(
            "OCKAM_HOME",
            home::home_dir()
                .ok_or_else(|| CliStateError::InvalidPath("$HOME".to_string()))?
                .join(".ockam"),
        )?)
    }
}

/// Return a random, but memorable, name which can be used to name identities, nodes, vaults, etc...
pub fn random_name() -> String {
    petname::petname(2, "-").unwrap_or(hex::encode(random::<[u8; 4]>()))
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CliStateMode {
    Persistent(PathBuf),
    InMemory,
}

impl CliStateMode {
    pub fn with_default_dir() -> Result<Self> {
        Ok(Self::Persistent(CliState::default_dir()?))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use itertools::Itertools;
    use ockam_node::database::{skip_if_postgres, DatabaseType};
    use std::fs;
    use tempfile::NamedTempFile;

    #[tokio::test]
    async fn test_reset() -> Result<()> {
        // We don't need to test reset with Postgres since we don't want reset be used accidentally
        // with a Postgres database (resetting in that case throws an error).
        skip_if_postgres(|| async {
            let db_file = NamedTempFile::new().unwrap();
            let cli_state_directory = db_file.path().parent().unwrap().join(random_name());
            let mode = CliStateMode::Persistent(cli_state_directory.clone());
            let cli = CliState::create(mode).await?;

            // create 2 vaults
            // the second vault is using a separate file
            let _vault1 = cli.get_or_create_named_vault("vault1").await?;
            let _vault2 = cli.get_or_create_named_vault("vault2").await?;

            // create 2 identities
            let identity1 = cli
                .create_identity_with_name_and_vault("identity1", "vault1")
                .await?;
            let identity2 = cli
                .create_identity_with_name_and_vault("identity2", "vault2")
                .await?;

            // create 2 nodes
            let _node1 = cli
                .create_node_with_identifier("node1", &identity1.identifier())
                .await?;
            let _node2 = cli
                .create_node_with_identifier("node2", &identity2.identifier())
                .await?;

            let file_names = list_file_names(&cli_state_directory);

            // this test is not executed with Postgres
            let expected = match cli.database_configuration()?.database_type() {
                DatabaseType::Sqlite => vec![
                    "vault-vault2".to_string(),
                    "application_database.sqlite3".to_string(),
                    "database.sqlite3".to_string(),
                ],
                DatabaseType::Postgres => vec![],
            };

            assert_eq!(
                file_names.iter().sorted().as_slice(),
                expected.iter().sorted().as_slice()
            );

            // reset the local state
            cli.reset().await?;
            let result = fs::read_dir(&cli_state_directory);
            assert!(result.is_ok(), "the cli state directory is not deleted");

            // this test is not executed with Postgres
            match cli.database_configuration()?.database_type() {
                DatabaseType::Sqlite => {
                    // When the database is SQLite, only the application database must remain
                    let file_names = list_file_names(&cli_state_directory);
                    let expected = vec!["application_database.sqlite3".to_string()];
                    assert_eq!(file_names, expected);
                }
                DatabaseType::Postgres => (),
            };
            Ok(())
        })
        .await
    }

    // HELPERS
    fn list_file_names(dir: &Path) -> Vec<String> {
        fs::read_dir(dir)
            .unwrap()
            .map(|f| f.unwrap().file_name().to_string_lossy().to_string())
            .collect()
    }
}