Initialize Aster VM and deploy PostgreSQL host on ces-control
Verify databases and deploy Aster VM / verify-and-deploy (push) Waiting to run

This commit is contained in:
2026-10-17 23:42:39 +08:00
commit 9648b9e8dd
34 changed files with 3717 additions and 0 deletions
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "aster-cli"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[[bin]]
name = "aster"
path = "src/main.rs"
[dependencies]
aster-core.workspace = true
aster-storage.workspace = true
tokio.workspace = true
[lints]
workspace = true
+66
View File
@@ -0,0 +1,66 @@
use std::error::Error;
use std::process::ExitCode;
use aster_core::{Value, Vm};
use aster_storage::{Storage, StorageConfig};
const USAGE: &str = "Usage: aster [bootstrap | metadata put <key> <value> | metadata get <key>]";
#[tokio::main]
async fn main() -> ExitCode {
match run().await {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("aster: {error}");
ExitCode::FAILURE
}
}
}
async fn run() -> Result<(), Box<dyn Error>> {
let args: Vec<String> = std::env::args().skip(1).collect();
match args
.iter()
.map(String::as_str)
.collect::<Vec<_>>()
.as_slice()
{
[] | ["bootstrap"] => {
let mut vm = Vm::new()?;
let root = vm.bootstrap();
let class = vm.create_class("Example", root)?;
let first = vm.create_instance(class)?;
let second = vm.create_instance(class)?;
vm.set_field(first, "message", Value::Text("Hello from Aster VM".into()))?;
println!(
"root={} parent={:?}",
vm.class(root)?.name(),
vm.class(root)?.parent()
);
println!(
"class={} instances_distinct={} heap_objects={}",
vm.class(class)?.name(),
first != second,
vm.object_count()
);
println!("bootstrap is independent of host storage");
}
["help"] | ["--help"] | ["-h"] => println!("{USAGE}"),
["metadata", "put", key, value] => {
let store = Storage::connect(&StorageConfig::from_env()?).await?;
store.put(key, value).await?;
println!("stored ({})", store.backend_name());
store.close().await;
}
["metadata", "get", key] => {
let store = Storage::connect(&StorageConfig::from_env()?).await?;
println!(
"{}",
store.get(key).await?.as_deref().unwrap_or("(missing)")
);
store.close().await;
}
_ => return Err(USAGE.into()),
}
Ok(())
}
+9
View File
@@ -0,0 +1,9 @@
[package]
name = "aster-core"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[lints]
workspace = true
+187
View File
@@ -0,0 +1,187 @@
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicU64, Ordering};
use crate::VmError;
static NEXT_HEAP_ID: AtomicU64 = AtomicU64::new(1);
/// Opaque process-local identity. Cannot be constructed or deserialized by callers.
/// Handles do not keep the VM alive; every dereference goes through its owner VM.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ObjectRef {
heap_id: u64,
index: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ClassRef(pub(crate) ObjectRef);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct InstanceRef(pub(crate) ObjectRef);
impl From<ClassRef> for ObjectRef {
fn from(value: ClassRef) -> Self {
value.0
}
}
impl From<InstanceRef> for ObjectRef {
fn from(value: InstanceRef) -> Self {
value.0
}
}
/// Primitive values are immediate; only classes and instances live on the heap.
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
Nil,
Bool(bool),
Integer(i64),
Float(f64),
Text(String),
Object(ObjectRef),
}
/// The class object and its immutable description are one heap allocation.
/// There is deliberately no metaclass or implicit class-of-class relationship.
#[derive(Debug)]
pub struct Class {
pub(crate) name: String,
pub(crate) parent: Option<ClassRef>,
}
impl Class {
pub fn name(&self) -> &str {
&self.name
}
pub fn parent(&self) -> Option<ClassRef> {
self.parent
}
}
#[derive(Debug)]
pub struct Instance {
pub(crate) class: ClassRef,
pub(crate) fields: BTreeMap<String, Value>,
}
impl Instance {
pub fn class(&self) -> ClassRef {
self.class
}
pub fn field(&self, name: &str) -> Option<&Value> {
self.fields.get(name)
}
}
#[derive(Debug)]
pub enum Object {
Class(Class),
Instance(Instance),
}
/// Allocation-only arena. No deletion or slot reuse until a GC model is chosen.
#[derive(Debug)]
pub(crate) struct Heap {
id: u64,
objects: Vec<Object>,
}
impl Heap {
pub(crate) fn new() -> Result<Self, VmError> {
let id = NEXT_HEAP_ID
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1))
.map_err(|_| VmError::IdentityExhausted)?;
Ok(Self {
id,
objects: Vec::new(),
})
}
pub(crate) fn allocate(&mut self, object: Object) -> ObjectRef {
let reference = ObjectRef {
heap_id: self.id,
index: self.objects.len(),
};
self.objects.push(object);
reference
}
pub(crate) fn get(&self, reference: ObjectRef) -> Result<&Object, VmError> {
self.validate_owner(reference)?;
self.objects
.get(reference.index)
.ok_or(VmError::InvalidHandle)
}
pub(crate) fn get_mut(&mut self, reference: ObjectRef) -> Result<&mut Object, VmError> {
self.validate_owner(reference)?;
self.objects
.get_mut(reference.index)
.ok_or(VmError::InvalidHandle)
}
fn validate_owner(&self, reference: ObjectRef) -> Result<(), VmError> {
if reference.heap_id != self.id {
return Err(VmError::ForeignHandle);
}
Ok(())
}
pub(crate) fn len(&self) -> usize {
self.objects.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn invalid_index_is_an_error_for_both_access_paths() {
let mut heap = Heap::new().unwrap();
let invalid = ObjectRef {
heap_id: heap.id,
index: usize::MAX,
};
assert!(matches!(heap.get(invalid), Err(VmError::InvalidHandle)));
assert!(matches!(heap.get_mut(invalid), Err(VmError::InvalidHandle)));
}
#[test]
fn typed_handles_are_checked_at_runtime_too() {
let mut vm = crate::Vm::new().unwrap();
let root = vm.root_class();
let instance = vm.create_instance(root).unwrap();
assert!(matches!(
vm.class(ClassRef(instance.0)),
Err(VmError::ExpectedClass)
));
assert!(matches!(
vm.instance(InstanceRef(root.0)),
Err(VmError::ExpectedInstance)
));
}
#[test]
fn invalid_value_reference_cannot_replace_a_field() {
let mut vm = crate::Vm::new().unwrap();
let root = vm.root_class();
let instance = vm.create_instance(root).unwrap();
vm.set_field(instance, "field", Value::Integer(1)).unwrap();
let invalid = ObjectRef {
heap_id: root.0.heap_id,
index: usize::MAX,
};
assert_eq!(
vm.set_field(instance, "field", Value::Object(invalid)),
Err(VmError::InvalidHandle)
);
assert_eq!(
vm.instance(instance).unwrap().field("field"),
Some(&Value::Integer(1))
);
}
}
+17
View File
@@ -0,0 +1,17 @@
//! Embeddable object runtime. No database, network, parser or executor dependencies.
//!
//! ```
//! use aster_core::{Value, Vm};
//! let mut vm = Vm::new()?;
//! let point = vm.create_class("Point", vm.root_class())?;
//! let instance = vm.create_instance(point)?;
//! vm.set_field(instance, "x", Value::Integer(42))?;
//! assert_eq!(vm.instance(instance)?.class(), point);
//! # Ok::<(), aster_core::VmError>(())
//! ```
mod heap;
mod vm;
pub use heap::{Class, ClassRef, Instance, InstanceRef, Object, ObjectRef, Value};
pub use vm::{Vm, VmError};
+146
View File
@@ -0,0 +1,146 @@
use std::collections::BTreeMap;
use std::fmt;
use crate::heap::Heap;
use crate::{Class, ClassRef, Instance, InstanceRef, Object, ObjectRef, Value};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VmError {
ForeignHandle,
InvalidHandle,
ExpectedClass,
ExpectedInstance,
EmptyClassName,
ReservedClassName,
IdentityExhausted,
}
impl fmt::Display for VmError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::ForeignHandle => "handle belongs to another VM",
Self::InvalidHandle => "handle does not identify a live object",
Self::ExpectedClass => "object is not a class",
Self::ExpectedInstance => "object is not an instance",
Self::EmptyClassName => "class name cannot be blank",
Self::ReservedClassName => "Object is reserved for the root class",
Self::IdentityExhausted => "process-local VM identities exhausted",
})
}
}
impl std::error::Error for VmError {}
/// Owns its heap and exactly one root class. Not Clone: handles have one owner.
#[derive(Debug)]
pub struct Vm {
heap: Heap,
root: ClassRef,
}
impl Vm {
/// Bootstraps Object before returning. Does not perform any host I/O.
pub fn new() -> Result<Self, VmError> {
let mut heap = Heap::new()?;
let root = ClassRef(heap.allocate(Object::Class(Class {
name: "Object".into(),
parent: None,
})));
Ok(Self { heap, root })
}
/// Idempotent: construction has already performed bootstrap exactly once.
pub fn bootstrap(&mut self) -> ClassRef {
self.root
}
pub fn root_class(&self) -> ClassRef {
self.root
}
pub fn object_count(&self) -> usize {
self.heap.len()
}
/// All user classes have an existing parent. Class names are labels rather
/// than a global registry; duplicate non-reserved names are permitted.
pub fn create_class(
&mut self,
name: impl Into<String>,
parent: ClassRef,
) -> Result<ClassRef, VmError> {
self.class(parent)?;
let name = name.into();
if name.trim().is_empty() {
return Err(VmError::EmptyClassName);
}
if name == "Object" {
return Err(VmError::ReservedClassName);
}
Ok(ClassRef(self.heap.allocate(Object::Class(Class {
name,
parent: Some(parent),
}))))
}
pub fn create_instance(&mut self, class: ClassRef) -> Result<InstanceRef, VmError> {
self.class(class)?;
Ok(InstanceRef(self.heap.allocate(Object::Instance(
Instance {
class,
fields: BTreeMap::new(),
},
))))
}
pub fn object(&self, reference: ObjectRef) -> Result<&Object, VmError> {
self.heap.get(reference)
}
pub fn class(&self, reference: ClassRef) -> Result<&Class, VmError> {
match self.heap.get(reference.0)? {
Object::Class(class) => Ok(class),
Object::Instance(_) => Err(VmError::ExpectedClass),
}
}
pub fn instance(&self, reference: InstanceRef) -> Result<&Instance, VmError> {
match self.heap.get(reference.0)? {
Object::Instance(instance) => Ok(instance),
Object::Class(_) => Err(VmError::ExpectedInstance),
}
}
/// Converts a generic reference only after validating ownership and kind.
pub fn as_class(&self, reference: ObjectRef) -> Result<ClassRef, VmError> {
let typed = ClassRef(reference);
self.class(typed)?;
Ok(typed)
}
pub fn as_instance(&self, reference: ObjectRef) -> Result<InstanceRef, VmError> {
let typed = InstanceRef(reference);
self.instance(typed)?;
Ok(typed)
}
/// Checks both destination and referenced value before changing any field.
pub fn set_field(
&mut self,
instance: InstanceRef,
name: impl Into<String>,
value: Value,
) -> Result<(), VmError> {
self.instance(instance)?;
if let Value::Object(reference) = &value {
self.heap.get(*reference)?;
}
match self.heap.get_mut(instance.0)? {
Object::Instance(instance) => {
instance.fields.insert(name.into(), value);
Ok(())
}
Object::Class(_) => Err(VmError::ExpectedInstance),
}
}
}
+120
View File
@@ -0,0 +1,120 @@
use aster_core::{Value, Vm, VmError};
#[test]
fn bootstrap_is_unique_and_root_has_no_parent() {
let mut vm = Vm::new().unwrap();
let root = vm.root_class();
assert_eq!(vm.bootstrap(), root);
assert_eq!(vm.bootstrap(), root);
assert_eq!(vm.object_count(), 1);
assert_eq!(vm.class(root).unwrap().name(), "Object");
assert_eq!(vm.class(root).unwrap().parent(), None);
}
#[test]
fn factories_preserve_class_links_and_distinct_identity() {
let mut vm = Vm::new().unwrap();
let root = vm.root_class();
let class = vm.create_class("Point", root).unwrap();
let child = vm.create_class("ColoredPoint", class).unwrap();
let first = vm.create_instance(class).unwrap();
let second = vm.create_instance(class).unwrap();
let plain = vm.create_instance(root).unwrap();
assert_ne!(first, second);
assert_eq!(vm.class(child).unwrap().parent(), Some(class));
assert_eq!(vm.instance(first).unwrap().class(), class);
assert_eq!(vm.instance(plain).unwrap().class(), root);
vm.set_field(first, "x", Value::Integer(1)).unwrap();
vm.set_field(first, "next", Value::Object(second.into()))
.unwrap();
assert_eq!(
vm.instance(first).unwrap().field("x"),
Some(&Value::Integer(1))
);
assert_eq!(vm.instance(second).unwrap().field("x"), None);
assert_eq!(vm.as_class(class.into()).unwrap(), class);
assert_eq!(vm.as_instance(first.into()).unwrap(), first);
assert_eq!(vm.as_instance(class.into()), Err(VmError::ExpectedInstance));
assert_eq!(vm.as_class(first.into()), Err(VmError::ExpectedClass));
}
#[test]
fn foreign_handles_are_rejected_without_mutation() {
let mut vm = Vm::new().unwrap();
let mut other = Vm::new().unwrap();
let local = vm.create_instance(vm.root_class()).unwrap();
let foreign = other.create_instance(other.root_class()).unwrap();
let count = vm.object_count();
assert_eq!(
vm.create_class("Alien", other.root_class()),
Err(VmError::ForeignHandle)
);
assert_eq!(
vm.create_instance(other.root_class()),
Err(VmError::ForeignHandle)
);
assert!(matches!(
vm.object(foreign.into()),
Err(VmError::ForeignHandle)
));
assert!(matches!(vm.instance(foreign), Err(VmError::ForeignHandle)));
assert_eq!(
vm.set_field(foreign, "x", Value::Nil),
Err(VmError::ForeignHandle)
);
vm.set_field(local, "x", Value::Integer(7)).unwrap();
assert_eq!(
vm.set_field(local, "x", Value::Object(foreign.into())),
Err(VmError::ForeignHandle)
);
assert_eq!(
vm.instance(local).unwrap().field("x"),
Some(&Value::Integer(7))
);
assert_eq!(vm.object_count(), count);
}
#[test]
fn handles_outliving_a_vm_cannot_alias_a_new_vm() {
let old = {
let vm = Vm::new().unwrap();
vm.root_class()
};
let vm = Vm::new().unwrap();
assert_ne!(old, vm.root_class());
assert!(matches!(vm.class(old), Err(VmError::ForeignHandle)));
}
#[test]
fn invalid_names_do_not_allocate_and_names_are_not_a_namespace() {
let mut vm = Vm::new().unwrap();
assert_eq!(
vm.create_class(" ", vm.root_class()),
Err(VmError::EmptyClassName)
);
assert_eq!(
vm.create_class("Object", vm.root_class()),
Err(VmError::ReservedClassName)
);
assert_eq!(vm.object_count(), 1);
let a = vm.create_class("Label", vm.root_class()).unwrap();
let b = vm.create_class("Label", vm.root_class()).unwrap();
assert_ne!(a, b);
}
#[test]
fn handles_remain_valid_when_the_arena_grows() {
let mut vm = Vm::new().unwrap();
let root = vm.root_class();
let first = vm.create_instance(root).unwrap();
vm.set_field(first, "stable", Value::Bool(true)).unwrap();
for _ in 0..4096 {
vm.create_instance(root).unwrap();
}
assert_eq!(vm.instance(first).unwrap().class(), root);
assert_eq!(
vm.instance(first).unwrap().field("stable"),
Some(&Value::Bool(true))
);
assert_eq!(vm.class(root).unwrap().name(), "Object");
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "aster-server"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[dependencies]
aster-core.workspace = true
aster-storage.workspace = true
axum.workspace = true
serde.workspace = true
tokio.workspace = true
[lints]
workspace = true
+126
View File
@@ -0,0 +1,126 @@
use std::error::Error;
use std::future::Future;
use std::process::ExitCode;
use std::sync::Arc;
use aster_core::Vm;
use aster_storage::{Storage, StorageConfig};
use axum::{Json, Router, extract::State, http::StatusCode, routing::get};
use serde::Serialize;
#[derive(Clone)]
struct AppState {
vm: Arc<Vm>,
storage: Storage,
}
#[derive(Serialize)]
struct Health {
status: &'static str,
storage: &'static str,
}
#[derive(Serialize)]
struct BootstrapInfo {
root_class: String,
root_has_parent: bool,
heap_objects: usize,
}
#[tokio::main]
async fn main() -> ExitCode {
match run().await {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("aster-server: {error}");
ExitCode::FAILURE
}
}
}
async fn run() -> Result<(), Box<dyn Error>> {
let vm = Arc::new(Vm::new()?);
let storage = Storage::connect(&StorageConfig::from_env()?).await?;
storage
.put("host.version", env!("CARGO_PKG_VERSION"))
.await?;
let address = std::env::var("ASTER_LISTEN").unwrap_or_else(|_| "127.0.0.1:8080".into());
let listener = tokio::net::TcpListener::bind(&address).await?;
let shutdown = shutdown_signal()?;
let app = Router::new()
.route("/health", get(health))
.route("/bootstrap", get(bootstrap))
.with_state(AppState {
vm,
storage: storage.clone(),
});
println!(
"Aster host listening on {} (storage={})",
listener.local_addr()?,
storage.backend_name()
);
axum::serve(listener, app)
.with_graceful_shutdown(shutdown)
.await?;
storage.close().await;
Ok(())
}
async fn health(State(state): State<AppState>) -> (StatusCode, Json<Health>) {
let (code, status) = match state.storage.ping().await {
Ok(()) => (StatusCode::OK, "ok"),
Err(_) => (StatusCode::SERVICE_UNAVAILABLE, "storage_unavailable"),
};
(
code,
Json(Health {
status,
storage: state.storage.backend_name(),
}),
)
}
async fn bootstrap(State(state): State<AppState>) -> Json<BootstrapInfo> {
let root = state
.vm
.class(state.vm.root_class())
.expect("VM construction guarantees a root class");
Json(BootstrapInfo {
root_class: root.name().into(),
root_has_parent: root.parent().is_some(),
heap_objects: state.vm.object_count(),
})
}
fn shutdown_signal() -> std::io::Result<impl Future<Output = ()>> {
#[cfg(unix)]
let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
Ok(async move {
#[cfg(unix)]
tokio::select! { _ = tokio::signal::ctrl_c() => {}, _ = terminate.recv() => {} }
#[cfg(not(unix))]
let _ = tokio::signal::ctrl_c().await;
})
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn health_reports_unavailable_after_storage_closes() {
let storage = Storage::connect(&StorageConfig::SqliteMemory)
.await
.unwrap();
let state = AppState {
vm: Arc::new(Vm::new().unwrap()),
storage,
};
let (status, _) = health(State(state.clone())).await;
assert_eq!(status, StatusCode::OK);
state.storage.close().await;
let (status, Json(body)) = health(State(state)).await;
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(body.status, "storage_unavailable");
}
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "aster-storage"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[dependencies]
sqlx.workspace = true
tokio.workspace = true
[dev-dependencies]
tempfile = "3"
[lints]
workspace = true
+249
View File
@@ -0,0 +1,249 @@
//! Host metadata storage; deliberately has no dependency on aster-core.
use std::fmt;
use std::path::PathBuf;
use std::str::FromStr;
use std::time::Duration;
use sqlx::postgres::{PgConnectOptions, PgPoolOptions};
use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions};
use sqlx::{PgPool, SqlitePool};
const SCHEMA: &str = include_str!("schema.sql");
/// An explicit PostgreSQL configuration never falls back to SQLite.
#[derive(Clone)]
pub enum StorageConfig {
SqliteFile(PathBuf),
SqliteMemory,
Postgres(String),
}
impl fmt::Debug for StorageConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::SqliteFile(path) => f.debug_tuple("SqliteFile").field(path).finish(),
Self::SqliteMemory => f.write_str("SqliteMemory"),
Self::Postgres(_) => f.write_str("Postgres([REDACTED])"),
}
}
}
impl StorageConfig {
/// DATABASE_URL accepts PostgreSQL only; SQLITE_PATH selects file or :memory:.
/// Empty/invalid explicit values are errors rather than default selection.
pub fn from_values(
database_url: Option<&str>,
sqlite_path: Option<&str>,
) -> Result<Self, StorageError> {
if let Some(url) = database_url {
if !(url.starts_with("postgres://") || url.starts_with("postgresql://")) {
return Err(StorageError::Config(
"DATABASE_URL must be a PostgreSQL URL",
));
}
return Ok(Self::Postgres(url.into()));
}
match sqlite_path.unwrap_or("data/aster.db") {
"" => Err(StorageError::Config("SQLITE_PATH cannot be empty")),
":memory:" => Ok(Self::SqliteMemory),
path => Ok(Self::SqliteFile(path.into())),
}
}
pub fn from_env() -> Result<Self, StorageError> {
let database_url = read_env("DATABASE_URL")?;
// Irrelevant SQLite settings must not prevent PostgreSQL configuration.
if database_url.is_some() {
return Self::from_values(database_url.as_deref(), None);
}
let sqlite_path = read_env("SQLITE_PATH")?;
Self::from_values(None, sqlite_path.as_deref())
}
}
fn read_env(name: &str) -> Result<Option<String>, StorageError> {
match std::env::var(name) {
Ok(value) => Ok(Some(value)),
Err(std::env::VarError::NotPresent) => Ok(None),
Err(std::env::VarError::NotUnicode(_)) => Err(StorageError::Config(
"storage environment must be valid Unicode",
)),
}
}
#[derive(Debug)]
pub enum StorageError {
Config(&'static str),
Directory(std::io::Error),
Database(sqlx::Error),
}
impl fmt::Display for StorageError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Config(message) => f.write_str(message),
Self::Directory(_) => f.write_str("cannot create SQLite parent directory"),
// CLI/HTTP logs must never print a connection URL or credentials.
Self::Database(_) => {
f.write_str("database operation failed; no fallback was attempted")
}
}
}
}
impl std::error::Error for StorageError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Config(_) => None,
Self::Directory(error) => Some(error),
Self::Database(error) => Some(error),
}
}
}
impl From<sqlx::Error> for StorageError {
fn from(error: sqlx::Error) -> Self {
Self::Database(error)
}
}
#[derive(Clone)]
enum Backend {
Sqlite(SqlitePool),
Postgres(PgPool),
}
/// Clones share a pool. A memory SQLite store uses exactly one connection, so
/// initialization and every operation see the same database for its lifetime.
#[derive(Clone)]
pub struct Storage {
backend: Backend,
}
impl Storage {
/// Connects eagerly and initializes the v1 metadata schema before returning.
pub async fn connect(config: &StorageConfig) -> Result<Self, StorageError> {
let backend = match config {
StorageConfig::Postgres(url) => {
let options = PgConnectOptions::from_str(url)
.map_err(|_| StorageError::Config("invalid PostgreSQL connection URL"))?;
Backend::Postgres(
PgPoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(5))
.connect_with(options)
.await?,
)
}
StorageConfig::SqliteFile(path) => {
if path.as_os_str().is_empty() || path == std::path::Path::new(":memory:") {
return Err(StorageError::Config(
"use SqliteMemory for an in-memory database",
));
}
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
tokio::fs::create_dir_all(parent)
.await
.map_err(StorageError::Directory)?;
}
let options = SqliteConnectOptions::new()
.filename(path)
.create_if_missing(true)
.journal_mode(SqliteJournalMode::Wal)
.busy_timeout(Duration::from_secs(5));
Backend::Sqlite(
SqlitePoolOptions::new()
.max_connections(5)
.acquire_timeout(Duration::from_secs(5))
.connect_with(options)
.await?,
)
}
StorageConfig::SqliteMemory => {
let options = SqliteConnectOptions::new().in_memory(true);
Backend::Sqlite(
SqlitePoolOptions::new()
.max_connections(1)
.min_connections(1)
.idle_timeout(None)
.max_lifetime(None)
.connect_with(options)
.await?,
)
}
};
let storage = Self { backend };
storage.initialize().await?;
Ok(storage)
}
async fn initialize(&self) -> Result<(), StorageError> {
match &self.backend {
Backend::Sqlite(pool) => {
sqlx::query(SCHEMA).execute(pool).await?;
}
Backend::Postgres(pool) => {
sqlx::query(SCHEMA).execute(pool).await?;
}
}
Ok(())
}
pub fn backend_name(&self) -> &'static str {
match &self.backend {
Backend::Sqlite(_) => "sqlite",
Backend::Postgres(_) => "postgresql",
}
}
pub async fn ping(&self) -> Result<(), StorageError> {
match &self.backend {
Backend::Sqlite(pool) => {
sqlx::query("SELECT 1").execute(pool).await?;
}
Backend::Postgres(pool) => {
sqlx::query("SELECT 1").execute(pool).await?;
}
}
Ok(())
}
pub async fn put(&self, key: &str, value: &str) -> Result<(), StorageError> {
match &self.backend {
Backend::Sqlite(pool) => {
sqlx::query("INSERT INTO aster_metadata (key, value) VALUES (?1, ?2) ON CONFLICT (key) DO UPDATE SET value = excluded.value")
.bind(key).bind(value).execute(pool).await?;
}
Backend::Postgres(pool) => {
sqlx::query("INSERT INTO aster_metadata (key, value) VALUES ($1, $2) ON CONFLICT (key) DO UPDATE SET value = excluded.value")
.bind(key).bind(value).execute(pool).await?;
}
}
Ok(())
}
pub async fn get(&self, key: &str) -> Result<Option<String>, StorageError> {
Ok(match &self.backend {
Backend::Sqlite(pool) => {
sqlx::query_scalar("SELECT value FROM aster_metadata WHERE key = ?1")
.bind(key)
.fetch_optional(pool)
.await?
}
Backend::Postgres(pool) => {
sqlx::query_scalar("SELECT value FROM aster_metadata WHERE key = $1")
.bind(key)
.fetch_optional(pool)
.await?
}
})
}
/// Explicitly closes the shared pool, including all Storage clones.
pub async fn close(&self) {
match &self.backend {
Backend::Sqlite(pool) => pool.close().await,
Backend::Postgres(pool) => pool.close().await,
}
}
}
+4
View File
@@ -0,0 +1,4 @@
CREATE TABLE IF NOT EXISTS aster_metadata (
key TEXT PRIMARY KEY NOT NULL,
value TEXT NOT NULL
)
+35
View File
@@ -0,0 +1,35 @@
use aster_storage::{Storage, StorageConfig};
/// Run explicitly against a disposable database; never silently skip a missing URL.
#[tokio::test]
#[ignore = "requires ASTER_TEST_POSTGRES_URL pointing to a test PostgreSQL database"]
async fn postgres_roundtrip_and_reconnect() {
let url = std::env::var("ASTER_TEST_POSTGRES_URL")
.expect("set ASTER_TEST_POSTGRES_URL to a disposable PostgreSQL database");
let config = StorageConfig::from_values(Some(&url), None).unwrap();
let store = Storage::connect(&config).await.unwrap();
assert_eq!(store.backend_name(), "postgresql");
store.ping().await.unwrap();
let key = format!(
"test.{}.{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
);
assert_eq!(store.get(&key).await.unwrap(), None);
store.put(&key, "你好 ' ; $1").await.unwrap();
assert_eq!(
store.get(&key).await.unwrap().as_deref(),
Some("你好 ' ; $1")
);
store.put(&key, "updated").await.unwrap();
store.close().await;
let reopened = Storage::connect(&config).await.unwrap();
assert_eq!(
reopened.get(&key).await.unwrap().as_deref(),
Some("updated")
);
reopened.close().await;
}
+97
View File
@@ -0,0 +1,97 @@
use aster_storage::{Storage, StorageConfig};
#[test]
fn configuration_defaults_precedence_and_errors() {
assert!(
matches!(StorageConfig::from_values(None, None).unwrap(), StorageConfig::SqliteFile(p) if p.to_str() == Some("data/aster.db"))
);
assert!(matches!(
StorageConfig::from_values(None, Some(":memory:")).unwrap(),
StorageConfig::SqliteMemory
));
assert!(matches!(
StorageConfig::from_values(Some("postgresql://localhost/aster"), Some("")).unwrap(),
StorageConfig::Postgres(_)
));
assert!(StorageConfig::from_values(Some(""), None).is_err());
assert!(StorageConfig::from_values(Some("mysql://localhost/aster"), None).is_err());
assert!(StorageConfig::from_values(None, Some("")).is_err());
let config = StorageConfig::Postgres("postgres://user:secret@localhost/db".into());
assert!(!format!("{config:?}").contains("secret"));
}
#[tokio::test]
async fn memory_store_is_shared_by_clones_but_isolated_between_stores() {
let store = Storage::connect(&StorageConfig::SqliteMemory)
.await
.unwrap();
let other = Storage::connect(&StorageConfig::SqliteMemory)
.await
.unwrap();
store.ping().await.unwrap();
assert_eq!(store.get("missing").await.unwrap(), None);
store.put("message", "你好 ' ? $1 ;").await.unwrap();
assert_eq!(
store.clone().get("message").await.unwrap().as_deref(),
Some("你好 ' ? $1 ;")
);
assert_eq!(other.get("message").await.unwrap(), None);
store.put("message", "updated").await.unwrap();
assert_eq!(
store.get("message").await.unwrap().as_deref(),
Some("updated")
);
store.close().await;
other.close().await;
}
#[tokio::test]
async fn sqlite_file_creates_parents_and_survives_reopen() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("nested/data/metadata.db");
let config = StorageConfig::SqliteFile(path.clone());
let store = Storage::connect(&config).await.unwrap();
store.put("project", "Aster VM").await.unwrap();
store.close().await;
assert!(path.is_file());
let reopened = Storage::connect(&config).await.unwrap();
assert_eq!(
reopened.get("project").await.unwrap().as_deref(),
Some("Aster VM")
);
reopened.put("project", "v2").await.unwrap();
assert_eq!(
reopened.get("project").await.unwrap().as_deref(),
Some("v2")
);
reopened.close().await;
}
#[tokio::test]
async fn invalid_sqlite_directory_reports_error() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("file");
std::fs::write(&file, "occupied").unwrap();
assert!(
Storage::connect(&StorageConfig::SqliteFile(file.join("aster.db")))
.await
.is_err()
);
}
#[tokio::test]
async fn postgres_connection_failure_is_an_error() {
// Hold a TCP port without serving PostgreSQL: deterministic local failure.
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!(
"postgres://aster:secret@{}/aster?sslmode=disable",
listener.local_addr().unwrap()
);
let result = Storage::connect(&StorageConfig::Postgres(url)).await;
let error = match result {
Ok(_) => panic!("unreachable PostgreSQL must fail"),
Err(error) => error,
};
assert!(!error.to_string().contains("secret"));
assert!(error.to_string().contains("no fallback"));
}