# Airone
Airone is a library inspired from Aral Balkan's [JSDB](https://github.com/small-tech/jsdb) principles applied to a Rust library.
The name has nothing to do with "air" or "one", it simply comes from the Italian word "Airone", which means "Heron".
Hence, it has to be read `[aiˈrone]`.
This library persists a list of structs from memory to disk. Every change in the data in memory is saved to disk automatically in a fast way, avoiding the full dump of the whole list.
As saving a long list of objects to a file each time a change happens may be cumbersome, `airone` writes each incremental change to an append-only file. This incremental transaction log is applied at the next restart to compact the base dump file; in this way, the heavy operation of writing the full dump of data from memory is executed only once at startup. After that, each change is written in a fast way to the append-only log.
# Architecture
## Usage scenario
Airone is developed to be used in situations where all of these prerequisites apply:
- No big-data: the whole dataset should fit in memory
- the dataset has to be persisted to disk
- after some data is modified, the change needs to be written to disk in a _fast_ way
- we can slow down the program start time without any relevant consequence
- no nested objects
These limits can be a problem for some usage scenarios. Existing databases add all sort of optimizations, caching mechanisms and are very complex, in order to be able to deal with such big amount of data.
However, when the above-mentioned prerequisites apply, we can leverage these limits to simplify the source code, making it more maintanable and getting rid of all the bloatware.
Moreover, limiting object nesting makes it compatible with CSV style files, ensuring you can manipulate data with standard UNIX tools such as `grep` and `awk`.
Here are two examples of good usage scenarios:
- small web server: data may change fast and can entirely fit into memory. The length of the timespan neeeded to start the server is not important, a long as the server is performant _while_ it's running. I provide an [external template](https://gitlab.com/MassiminoilTrace/rocket_plus_airone_template) using airone and a Rocket server
- an offline GUI/TUI program: you can store modifications of some data in a very fast way thanks to airone's append-only file architecture, so the interface freeze during the saving process is barely noticeable.
## Context
Airone is aimed at helping _small-tech_ to be produced, which is a way of building technology antithetical to the Silicon Valley model. Small-tech features close-to-zero data collection, a free and open source structure to achieve good transparency, no lust to scale exponentially, no desire in tracking people's behaviour while crunching tons of data and, overall, it has a goal to keep things simple and human.
## Implementation limitations
This project is still a Work in Progress. It has been started only out of curiosity attempting to replicate JSDB behaviour with the bare minimum number of dependencies I could achieve (only one). It has unit tests, but it has not **NOT** been used in production so far.
OS: Windows and Mac are not supported nor endorsed and `airone` has not been tested on them. Beware that WSL is a compatibility layer and may unexpectedly break too. I encourage you to switch to an actually freedom-and-privacy respecting operating system such as GNU/Linux, where this library has been tested on more. Head to [https://www.youtube.com/watch?v=Ag1AKIl_2GM](https://www.youtube.com/watch?v=Ag1AKIl_2GM) for more information
Licensing: This project is licensed under an AGPL style license. Head to the COPYING file and Copyright section for detailed information.
Make sure to respect the license terms to use this library.
## Internal Data Format
Data is written into two files, depending of the phase of execution.
The base dump file contains the full dump of data in memory. This is recreated whenever the program starts by using the old dump data file as a base point and applying each incremental change to it. Afterwards, the data is saved to the a new dump file and the old transaction log is deleted.
From this point, the program continues its execution saving changes to a new transaction log.
Both files follow this character convention:
- the `\n` character is used as a newline (no carriage return)
- the `\t` character is used as a field separator.
### Base Dump File
The base dump file is saved using a standard UNIX-style CSV text file.
Let's use this struct as an example:
```rust
struct ExampleStruct
{
field1: String,
field2: f64,
field3: i32
}
```
Given a list of two `ExampleStruct` elements, the base dump file could look like this:
```plain
abc 3.15 57
text2 47.89 -227
```
### Append-only transaction log
When the program is running, changes are written to the append-only transaction log.
Each line of this file is formatted as it follows, depending on the applied operation.
#### Adding an element
The first letter `A` sets the operation to `Add`. The new object fields are serialized as in the base dump file, by writing each field's value in the proper order.
The index sets the position in the list where the element will be added.
Structure:
```plain
A index field1 field2 field3
```
Example:
```plain
A 3 abc 3.15 57
```
#### Deleting an element
The first letter `D` sets the operation to `Delete`. After that, it expects the index of the element to remove.
Structure:
```plain
D index_of_element_to_remove
```
Example:
```plain
D 2
```
#### Setting a field value
The first letter `E` sets the operation to `Edit`. After that field, adhere to the following structure.
Structure:
```plain
E variable_type index_of_element field_to_change new_value
```
Example
```plain
E f64 0 field2 -57.5
```
## Extending and supporting custom types
You can serialize and deserialize your custom types by implementing [LoadableValue] and [PersistableValue] traits on each field type.
The serialized string must be on a single line and must escape any `\t`, `\r` and `\n` character to ensure CSV style compatibility.
For most types, you can simply use Rust's `format!()` and `parse()` features.
# Usage
## Installation
Add this line to your dependencies section of the `Cargo.toml` file.
```toml
airone = "0.2.0"
```
If you're planning to use it in a [Rocket](rocket.rs/) webserver, you can enable airone optional "rocket" feature.
```toml
airone = {version="0.2.0", features=["rocket"]}
```
## Basic operations
The core lies in the [airone_db!] macro. Pass a struct named as you wish to it (let's take `Foo` as an example) and the macro
will define a new struct named `$structname+AironeListProxy` (which expands to `FooAironeListProxy` in this example).
The newly creates struct acts as a proxy between you and the underlying list of data, automatically persisting
changes when they happen and providing methods to interact with them.
Given the example structure:
```
#[macro_use] extern crate airone;
use airone::prelude::*;
// This generates a FooAironeListProxy struct
// to interact with the data while saving any change to disk.
airone_db!(
struct Foo
{
pub field1: f64,
pub field2: String,
field3: Option<i32>
}
);
{
// Open the database
let mut db = FooAironeListProxy::new();
// Add one element using
// a method from the Database trait
db.push(
Foo{
field1: 0.5,
field2: "Hello world".to_string(),
field3: Some(-45)
}
);
// Change a field using the generated setter method
db.set_field3(0, None);
// The database is closed automatically here
}
{
// Open again, check the modified data
// has been correctly persisted.
let mut db = FooAironeListProxy::new();
assert_eq!(
*db.get_field3(0).unwrap(),
None
);
}
# use std::fs::{remove_file};
# remove_file("Foo.csv").unwrap();
# remove_file("Foo.changes.csv").unwrap();
```
The generated struct implements all methods from the [Database] trait,
plus getter and setters for each variable to change the element
at the specified index in the form of:
```rust,ignore
fn set_$field_name(&mut self, index: usize, new_value: $field_type) -> Result<(), AironeError>
fn get_$field_name(&self, index: usize) -> Result<$field_type, AironeError>
fn set_bulk_$field_name(&mut self, indices: Vec<usize>, value: $field_type) -> Result<(), AironeError>
```
## Query chaining
You can use the [Query] struct to make queries using dot notation, chaining them one after another.
```rust
# #[macro_use] extern crate airone;
# use airone::prelude::*;
# airone_db!(
# struct QueryExample
# {
# internal_id: i32,
# my_text: String
# }
# );
#
use airone::Query;
let mut db = QueryExampleAironeListProxy::new();
// Fill in data how you want here
// …
//
# db.push(
# QueryExample{
# internal_id: 56,
# my_text: "Hello world".to_string()
# }
# );
# db.push(
# QueryExample{
# internal_id: 57,
# my_text: "Test string".to_string()
# }
# );
# db.push(
# QueryExample{
# internal_id: 57,
# my_text: "Test string".to_string()
# }
# );
// Use brackets to create an inner scope
// so that the &mut db reference we pass to
// the query object will be given back
// when the query object is released.
{
let mut q = Query::new(&mut db);
// Can now use dot notation chaining operations
q.filter(
|e|
{
e.get_my_text() == "Test string"
}
)
.delete().unwrap();
// Query goes out of scope
// and mutable borrow is released
// to the outer scope
}
// Do something else with `db` object
# use std::fs::{remove_file};
# remove_file("QueryExample.csv").unwrap();
# remove_file("QueryExample.changes.csv").unwrap();
```
## Transactions
Transactions ensure that a series of changes is applied without errors, or it is reverted to bring the database to the previous valid state.
Auto-commit is enabled by default, which means that any change will be persisted to disk instantly by internally calling [commit()](Database::commit()).
You can enable or disable it through [set_auto_commit()](Database::set_auto_commit()) method.
When autocommit is disabled, you must manually call [commit()](Database::commit()) and [rollback()](Database::rollback()) methods.
```rust
# #[macro_use] extern crate airone;
# use airone::prelude::*;
# use std::fs::remove_file;
# airone_db!(
# pub struct Animal
# {
# a: i32,
# n: f64,
# testo: String
# }
# );
let mut db = AnimalAironeListProxy::new_with_filename("rollback_example");
# db.push(Animal {
# a: 0,
# n: 5.0,
# testo: "Abc".to_string()
# }).unwrap();
# db.push(Animal {
# a: 1,
# n: 1.4142135,
# testo: "Se\nco\nndo".to_string()
# }).unwrap();
# db.push(Animal {
# a: 2,
# n: 1.4142135,
# testo: "Se\nco\nndo".to_string()
# }).unwrap();
// This database has 3 elements inside it
// Disabling auto-commit, so
// we can now use commit() and rollback()
db.set_auto_commit(false);
// Add and rollback
db.push(Animal {
a: 156,
n: 1.4142135,
testo: "test".to_string()
}).unwrap();
assert_eq!(db.len(), 4);
// We rollback and we have again 3 elements only
db.rollback().unwrap();
assert_eq!(db.len(), 3);
// Edit a value
db.set_a(2, 10).unwrap();
// The value has been changed in memory only
assert_eq!(*db.get_a(2).unwrap(), 10);
// Roll back
db.rollback().unwrap();
// Check the object has its original value
assert_eq!(*db.get_a(2).unwrap(), 2);
// Deleting some objects
db.remove(1).unwrap();
db.remove(0).unwrap();
// Check data in memory has changed
assert_eq!(db.len(), 1);
// Rollback and make sure
// the elements are back
db.rollback().unwrap();
assert_eq!(db.len(), 3);
# remove_file("rollback_example.csv").unwrap();
# remove_file("rollback_example.changes.csv").unwrap();
```
# Copyright
This is **NOT** public domain, make sure to respect the license terms.
You can find the license text in the [COPYING](https://gitlab.com/MassiminoilTrace/airone/-/blob/master/COPYING) file.
Copyright © 2022 Massimo Gismondi
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see https://www.gnu.org/licenses/.
## Other external libraries used in this project
- [paste](https://github.com/dtolnay/paste) crate, made by David Tolnay. Licensed under either of Apache License, Version 2.0 or MIT license at your option.
- optional [rocket](https://github.com/SergioBenitez/Rocket) crate, made by Sergio Benitez. Licensed under either of Apache License, Version 2.0 or MIT license at your option.