Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 95d32d4592 | |||
| c00d28c34a | |||
| ad3ff57260 | |||
| c9f1a5dddc |
@@ -1,5 +1,20 @@
|
||||
# Changelog
|
||||
|
||||
## 2026-05-02 - 2.10.0 - feat(rustdb)
|
||||
extract service API logic into a dedicated Rust module and expose shared service types
|
||||
|
||||
- adds a new rustdb service_api module to handle health, tenant, and database import/export operations
|
||||
- moves SmartDB service interfaces into a dedicated TypeScript service-types module and re-exports them through the public API
|
||||
- updates management request handling to delegate service operations through shared service API helpers
|
||||
|
||||
## 2026-05-02 - 2.9.0 - feat(server)
|
||||
add tenant management, health checks, and database export/import APIs
|
||||
|
||||
- adds TypeScript and Rust management commands for creating, listing, deleting, and rotating isolated database tenants
|
||||
- introduces health reporting with storage, auth, database, collection, and uptime information
|
||||
- supports exporting and importing single-database snapshots and increases IPC payload size for larger transfers
|
||||
- adds integration coverage for tenant isolation, password rotation, persistence across restart, and database restore flows
|
||||
|
||||
## 2026-04-29 - 2.8.0 - feat(transactions)
|
||||
add single-node transaction support with session-aware reads, commits, aborts, and transaction metrics
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@push.rocks/smartdb",
|
||||
"version": "2.8.0",
|
||||
"version": "2.10.0",
|
||||
"private": false,
|
||||
"description": "A MongoDB-compatible embedded database server with wire protocol support, backed by a high-performance Rust engine.",
|
||||
"exports": {
|
||||
|
||||
@@ -282,6 +282,27 @@ impl AuthEngine {
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn list_users(&self) -> Vec<AuthenticatedUser> {
|
||||
let users = self.users.read().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let mut result: Vec<AuthenticatedUser> = users
|
||||
.values()
|
||||
.map(AuthUser::to_authenticated_user)
|
||||
.collect();
|
||||
result.sort_by(|a, b| a.database.cmp(&b.database).then(a.username.cmp(&b.username)));
|
||||
result
|
||||
}
|
||||
|
||||
pub fn drop_users_for_database(&self, database: &str) -> Result<usize, AuthError> {
|
||||
let mut users = self.users.write().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let before = users.len();
|
||||
users.retain(|_, user| user.database != database);
|
||||
let dropped = before.saturating_sub(users.len());
|
||||
if dropped > 0 {
|
||||
self.persist_locked(&users)?;
|
||||
}
|
||||
Ok(dropped)
|
||||
}
|
||||
|
||||
pub fn start_scram_sha256(
|
||||
&self,
|
||||
database: &str,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
pub mod management;
|
||||
pub mod service_api;
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::BufReader;
|
||||
@@ -299,6 +300,11 @@ impl RustDb {
|
||||
pub fn ctx(&self) -> &Arc<CommandContext> {
|
||||
&self.ctx
|
||||
}
|
||||
|
||||
/// Get the server options used for this instance.
|
||||
pub fn options(&self) -> &RustDbOptions {
|
||||
&self.options
|
||||
}
|
||||
}
|
||||
|
||||
fn build_tls_acceptor(options: &TlsOptions) -> Result<TlsAcceptor> {
|
||||
|
||||
@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use tracing::{info, error};
|
||||
|
||||
use crate::service_api;
|
||||
use crate::RustDb;
|
||||
use rustdb_config::RustDbOptions;
|
||||
|
||||
@@ -139,7 +140,36 @@ async fn handle_request(
|
||||
"start" => handle_start(&id, &request.params, db).await,
|
||||
"stop" => handle_stop(&id, db).await,
|
||||
"getStatus" => handle_get_status(&id, db),
|
||||
"getHealth" => ManagementResponse::ok(id, service_api::get_health(db.as_ref()).await),
|
||||
"getMetrics" => handle_get_metrics(&id, db).await,
|
||||
"createDatabaseTenant" => match db.as_ref() {
|
||||
Some(d) => service_response(&id, service_api::create_database_tenant(d, &request.params).await),
|
||||
None => server_not_running_response(&id),
|
||||
},
|
||||
"deleteDatabaseTenant" => match db.as_ref() {
|
||||
Some(d) => service_response(&id, service_api::delete_database_tenant(d, &request.params).await),
|
||||
None => server_not_running_response(&id),
|
||||
},
|
||||
"rotateDatabaseTenantPassword" => match db.as_ref() {
|
||||
Some(d) => service_response(&id, service_api::rotate_database_tenant_password(d, &request.params).await),
|
||||
None => server_not_running_response(&id),
|
||||
},
|
||||
"listDatabaseTenants" => match db.as_ref() {
|
||||
Some(d) => service_response(&id, service_api::list_database_tenants(d)),
|
||||
None => server_not_running_response(&id),
|
||||
},
|
||||
"getDatabaseTenantDescriptor" => match db.as_ref() {
|
||||
Some(d) => service_response(&id, service_api::get_database_tenant_descriptor(d, &request.params)),
|
||||
None => server_not_running_response(&id),
|
||||
},
|
||||
"exportDatabase" => match db.as_ref() {
|
||||
Some(d) => service_response(&id, service_api::export_database(d, &request.params).await),
|
||||
None => server_not_running_response(&id),
|
||||
},
|
||||
"importDatabase" => match db.as_ref() {
|
||||
Some(d) => service_response(&id, service_api::import_database(d, &request.params).await),
|
||||
None => server_not_running_response(&id),
|
||||
},
|
||||
"getOpLog" => handle_get_oplog(&id, &request.params, db),
|
||||
"getOpLogStats" => handle_get_oplog_stats(&id, db),
|
||||
"revertToSeq" => handle_revert_to_seq(&id, &request.params, db).await,
|
||||
@@ -149,6 +179,17 @@ async fn handle_request(
|
||||
}
|
||||
}
|
||||
|
||||
fn service_response(id: &str, result: service_api::ServiceResult) -> ManagementResponse {
|
||||
match result {
|
||||
Ok(value) => ManagementResponse::ok(id.to_string(), value),
|
||||
Err(message) => ManagementResponse::err(id.to_string(), message),
|
||||
}
|
||||
}
|
||||
|
||||
fn server_not_running_response(id: &str) -> ManagementResponse {
|
||||
ManagementResponse::err(id.to_string(), "Server is not running".to_string())
|
||||
}
|
||||
|
||||
async fn handle_start(
|
||||
id: &str,
|
||||
params: &serde_json::Value,
|
||||
@@ -274,7 +315,9 @@ fn handle_get_oplog(
|
||||
) -> ManagementResponse {
|
||||
let d = match db.as_ref() {
|
||||
Some(d) => d,
|
||||
None => return ManagementResponse::err(id.to_string(), "Server is not running".to_string()),
|
||||
None => {
|
||||
return ManagementResponse::err(id.to_string(), "Server is not running".to_string())
|
||||
}
|
||||
};
|
||||
|
||||
let ctx = d.ctx();
|
||||
|
||||
@@ -0,0 +1,446 @@
|
||||
use bson::{Bson, Document};
|
||||
use rustdb_config::StorageType;
|
||||
|
||||
use crate::RustDb;
|
||||
|
||||
pub type ServiceResult = Result<serde_json::Value, String>;
|
||||
|
||||
pub async fn get_health(db: Option<&RustDb>) -> serde_json::Value {
|
||||
match db {
|
||||
Some(d) => {
|
||||
let ctx = d.ctx();
|
||||
let (database_count, collection_count) = database_and_collection_counts(ctx).await;
|
||||
let options = d.options();
|
||||
let storage = match &options.storage {
|
||||
StorageType::Memory => "memory",
|
||||
StorageType::File => "file",
|
||||
};
|
||||
serde_json::json!({
|
||||
"running": true,
|
||||
"storage": storage,
|
||||
"storagePath": options.storage_path.clone().or_else(|| options.persist_path.clone()),
|
||||
"authEnabled": ctx.auth.enabled(),
|
||||
"authUsers": ctx.auth.user_count(),
|
||||
"usersPathConfigured": options.auth.users_path.is_some(),
|
||||
"databaseCount": database_count,
|
||||
"collectionCount": collection_count,
|
||||
"uptimeSeconds": ctx.start_time.elapsed().as_secs(),
|
||||
})
|
||||
}
|
||||
None => serde_json::json!({
|
||||
"running": false,
|
||||
"databaseCount": 0,
|
||||
"collectionCount": 0,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create_database_tenant(db: &RustDb, params: &serde_json::Value) -> ServiceResult {
|
||||
let ctx = db.ctx();
|
||||
if !ctx.auth.enabled() {
|
||||
return Err("Authentication must be enabled to create database tenants".to_string());
|
||||
}
|
||||
|
||||
let database_name = string_param(params, "databaseName")?;
|
||||
validate_database_name(database_name)?;
|
||||
let username = string_param(params, "username")?;
|
||||
validate_username(username)?;
|
||||
let password = string_param(params, "password")?;
|
||||
if password.is_empty() {
|
||||
return Err("password must not be empty".to_string());
|
||||
}
|
||||
let roles = roles_param(params)?;
|
||||
|
||||
if let Err(e) = ctx.storage.create_database(database_name).await {
|
||||
if !is_already_exists(&e.to_string()) {
|
||||
return Err(format!("Failed to create database: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
match ctx
|
||||
.auth
|
||||
.create_user(database_name, username, password, roles)
|
||||
{
|
||||
Ok(()) => {
|
||||
let users = ctx.auth.users_info(database_name, Some(username));
|
||||
users
|
||||
.first()
|
||||
.map(tenant_descriptor_json)
|
||||
.ok_or_else(|| "Tenant user was created but could not be read back".to_string())
|
||||
}
|
||||
Err(e) => Err(format!("Failed to create tenant user: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_database_tenant(db: &RustDb, params: &serde_json::Value) -> ServiceResult {
|
||||
let ctx = db.ctx();
|
||||
let database_name = string_param(params, "databaseName")?;
|
||||
validate_database_name(database_name)?;
|
||||
let username = params.get("username").and_then(|v| v.as_str());
|
||||
if let Some(username) = username {
|
||||
validate_username(username)?;
|
||||
}
|
||||
|
||||
if let Err(e) = ctx.storage.drop_database(database_name).await {
|
||||
return Err(format!("Failed to drop database: {e}"));
|
||||
}
|
||||
remove_database_indexes(ctx, database_name);
|
||||
|
||||
let mut deleted_users = 0usize;
|
||||
if ctx.auth.enabled() {
|
||||
if let Some(username) = username {
|
||||
match ctx.auth.drop_user(database_name, username) {
|
||||
Ok(()) => deleted_users = 1,
|
||||
Err(rustdb_auth::AuthError::UserNotFound(_)) => deleted_users = 0,
|
||||
Err(e) => return Err(format!("Failed to drop tenant user: {e}")),
|
||||
}
|
||||
} else {
|
||||
deleted_users = ctx
|
||||
.auth
|
||||
.drop_users_for_database(database_name)
|
||||
.map_err(|e| format!("Failed to drop tenant users: {e}"))?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"databaseName": database_name,
|
||||
"deletedUsers": deleted_users,
|
||||
"databaseDropped": true,
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn rotate_database_tenant_password(
|
||||
db: &RustDb,
|
||||
params: &serde_json::Value,
|
||||
) -> ServiceResult {
|
||||
let ctx = db.ctx();
|
||||
if !ctx.auth.enabled() {
|
||||
return Err(
|
||||
"Authentication must be enabled to rotate database tenant passwords".to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
let username = string_param(params, "username")?;
|
||||
validate_username(username)?;
|
||||
let password = string_param(params, "password")?;
|
||||
if password.is_empty() {
|
||||
return Err("password must not be empty".to_string());
|
||||
}
|
||||
|
||||
let matches: Vec<_> = ctx
|
||||
.auth
|
||||
.list_users()
|
||||
.into_iter()
|
||||
.filter(|user| user.username == username)
|
||||
.collect();
|
||||
if matches.is_empty() {
|
||||
return Err(format!("tenant user not found: {username}"));
|
||||
}
|
||||
if matches.len() > 1 {
|
||||
return Err(format!(
|
||||
"tenant username is ambiguous across databases: {username}"
|
||||
));
|
||||
}
|
||||
|
||||
let user = &matches[0];
|
||||
ctx.auth
|
||||
.update_user(&user.database, username, Some(password), None)
|
||||
.map_err(|e| format!("Failed to rotate tenant password: {e}"))?;
|
||||
let users = ctx.auth.users_info(&user.database, Some(username));
|
||||
users
|
||||
.first()
|
||||
.map(tenant_descriptor_json)
|
||||
.ok_or_else(|| "Tenant user was updated but could not be read back".to_string())
|
||||
}
|
||||
|
||||
pub fn list_database_tenants(db: &RustDb) -> ServiceResult {
|
||||
let tenants: Vec<serde_json::Value> = db
|
||||
.ctx()
|
||||
.auth
|
||||
.list_users()
|
||||
.into_iter()
|
||||
.filter(|user| user.database != "admin")
|
||||
.map(|user| tenant_descriptor_json(&user))
|
||||
.collect();
|
||||
Ok(serde_json::json!({ "tenants": tenants }))
|
||||
}
|
||||
|
||||
pub fn get_database_tenant_descriptor(db: &RustDb, params: &serde_json::Value) -> ServiceResult {
|
||||
let database_name = string_param(params, "databaseName")?;
|
||||
let username = string_param(params, "username")?;
|
||||
let users = db.ctx().auth.users_info(database_name, Some(username));
|
||||
users
|
||||
.first()
|
||||
.map(tenant_descriptor_json)
|
||||
.ok_or_else(|| format!("tenant user not found: {database_name}.{username}"))
|
||||
}
|
||||
|
||||
pub async fn export_database(db: &RustDb, params: &serde_json::Value) -> ServiceResult {
|
||||
let ctx = db.ctx();
|
||||
let database_name = string_param(params, "databaseName")?;
|
||||
validate_database_name(database_name)?;
|
||||
match ctx.storage.database_exists(database_name).await {
|
||||
Ok(true) => {}
|
||||
Ok(false) => return Err(format!("database not found: {database_name}")),
|
||||
Err(e) => return Err(format!("Failed to check database: {e}")),
|
||||
}
|
||||
|
||||
let collection_names = ctx
|
||||
.storage
|
||||
.list_collections(database_name)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to list collections: {e}"))?;
|
||||
let mut collections = Vec::with_capacity(collection_names.len());
|
||||
for collection_name in collection_names {
|
||||
let documents = ctx
|
||||
.storage
|
||||
.find_all(database_name, &collection_name)
|
||||
.await
|
||||
.map_err(|e| format!("Failed to export collection '{collection_name}': {e}"))?
|
||||
.into_iter()
|
||||
.map(|doc| bson_doc_to_json(&doc))
|
||||
.collect::<Vec<_>>();
|
||||
let indexes = match ctx
|
||||
.storage
|
||||
.get_indexes(database_name, &collection_name)
|
||||
.await
|
||||
{
|
||||
Ok(specs) => specs
|
||||
.into_iter()
|
||||
.map(|doc| bson_doc_to_json(&doc))
|
||||
.collect::<Vec<_>>(),
|
||||
Err(_) => Vec::new(),
|
||||
};
|
||||
collections.push(serde_json::json!({
|
||||
"name": collection_name,
|
||||
"documents": documents,
|
||||
"indexes": indexes,
|
||||
}));
|
||||
}
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"format": "smartdb.database.export.v1",
|
||||
"databaseName": database_name,
|
||||
"exportedAtMs": now_ms(),
|
||||
"collections": collections,
|
||||
}))
|
||||
}
|
||||
|
||||
pub async fn import_database(db: &RustDb, params: &serde_json::Value) -> ServiceResult {
|
||||
let ctx = db.ctx();
|
||||
let database_name = string_param(params, "databaseName")?;
|
||||
validate_database_name(database_name)?;
|
||||
let source = params
|
||||
.get("source")
|
||||
.ok_or_else(|| "Missing 'source' parameter".to_string())?;
|
||||
let source_collections = source
|
||||
.get("collections")
|
||||
.and_then(|value| value.as_array())
|
||||
.ok_or_else(|| "source.collections must be an array".to_string())?;
|
||||
|
||||
if let Err(e) = ctx.storage.drop_database(database_name).await {
|
||||
return Err(format!("Failed to clear database before import: {e}"));
|
||||
}
|
||||
remove_database_indexes(ctx, database_name);
|
||||
if let Err(e) = ctx.storage.create_database(database_name).await {
|
||||
if !is_already_exists(&e.to_string()) {
|
||||
return Err(format!("Failed to create database: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
let mut imported_collections = 0usize;
|
||||
let mut imported_documents = 0usize;
|
||||
for collection in source_collections {
|
||||
let collection_name = collection
|
||||
.get("name")
|
||||
.and_then(|value| value.as_str())
|
||||
.ok_or_else(|| "source collection is missing a string 'name'".to_string())?;
|
||||
validate_collection_name(collection_name)?;
|
||||
if let Err(e) = ctx
|
||||
.storage
|
||||
.create_collection(database_name, collection_name)
|
||||
.await
|
||||
{
|
||||
if !is_already_exists(&e.to_string()) {
|
||||
return Err(format!(
|
||||
"Failed to create collection '{collection_name}': {e}"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(documents) = collection
|
||||
.get("documents")
|
||||
.and_then(|value| value.as_array())
|
||||
{
|
||||
for document_value in documents {
|
||||
let document = json_to_bson_doc(document_value).map_err(|message| {
|
||||
format!("Invalid document in '{collection_name}': {message}")
|
||||
})?;
|
||||
if let Err(e) = ctx
|
||||
.storage
|
||||
.insert_one(database_name, collection_name, document)
|
||||
.await
|
||||
{
|
||||
return Err(format!(
|
||||
"Failed to import document into '{collection_name}': {e}"
|
||||
));
|
||||
}
|
||||
imported_documents += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(indexes) = collection.get("indexes").and_then(|value| value.as_array()) {
|
||||
for index_value in indexes {
|
||||
let index_doc = json_to_bson_doc(index_value).map_err(|message| {
|
||||
format!("Invalid index in '{collection_name}': {message}")
|
||||
})?;
|
||||
let name = index_doc.get_str("name").unwrap_or("_id_").to_string();
|
||||
if let Err(e) = ctx
|
||||
.storage
|
||||
.save_index(database_name, collection_name, &name, index_doc)
|
||||
.await
|
||||
{
|
||||
return Err(format!(
|
||||
"Failed to import index '{name}' into '{collection_name}': {e}"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
imported_collections += 1;
|
||||
}
|
||||
|
||||
Ok(serde_json::json!({
|
||||
"databaseName": database_name,
|
||||
"collections": imported_collections,
|
||||
"documents": imported_documents,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn database_and_collection_counts(ctx: &rustdb_commands::CommandContext) -> (usize, u64) {
|
||||
let databases = ctx.storage.list_databases().await.unwrap_or_default();
|
||||
let mut collections = 0u64;
|
||||
for database in &databases {
|
||||
if let Ok(database_collections) = ctx.storage.list_collections(database).await {
|
||||
collections += database_collections.len() as u64;
|
||||
}
|
||||
}
|
||||
(databases.len(), collections)
|
||||
}
|
||||
|
||||
fn remove_database_indexes(ctx: &rustdb_commands::CommandContext, database_name: &str) {
|
||||
let prefix = format!("{}.", database_name);
|
||||
let keys_to_remove: Vec<String> = ctx
|
||||
.indexes
|
||||
.iter()
|
||||
.filter(|entry| entry.key().starts_with(&prefix))
|
||||
.map(|entry| entry.key().clone())
|
||||
.collect();
|
||||
for key in keys_to_remove {
|
||||
ctx.indexes.remove(&key);
|
||||
}
|
||||
}
|
||||
|
||||
fn tenant_descriptor_json(user: &rustdb_auth::AuthenticatedUser) -> serde_json::Value {
|
||||
serde_json::json!({
|
||||
"databaseName": user.database.clone(),
|
||||
"username": user.username.clone(),
|
||||
"roles": user.roles.clone(),
|
||||
"authSource": user.database.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn string_param<'a>(params: &'a serde_json::Value, key: &str) -> Result<&'a str, String> {
|
||||
params
|
||||
.get(key)
|
||||
.and_then(|value| value.as_str())
|
||||
.ok_or_else(|| format!("Missing '{key}' parameter"))
|
||||
}
|
||||
|
||||
fn roles_param(params: &serde_json::Value) -> Result<Vec<String>, String> {
|
||||
let Some(value) = params.get("roles") else {
|
||||
return Ok(vec!["readWrite".to_string(), "dbAdmin".to_string()]);
|
||||
};
|
||||
let roles = value
|
||||
.as_array()
|
||||
.ok_or_else(|| "roles must be an array of strings".to_string())?;
|
||||
let mut result = Vec::with_capacity(roles.len());
|
||||
for role in roles {
|
||||
let Some(role_name) = role.as_str() else {
|
||||
return Err("roles must be an array of strings".to_string());
|
||||
};
|
||||
if role_name.is_empty() {
|
||||
return Err("roles must not contain empty role names".to_string());
|
||||
}
|
||||
result.push(role_name.to_string());
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
fn validate_database_name(name: &str) -> Result<(), String> {
|
||||
if name.is_empty() {
|
||||
return Err("databaseName must not be empty".to_string());
|
||||
}
|
||||
if name == "."
|
||||
|| name == ".."
|
||||
|| name.contains('/')
|
||||
|| name.contains('\\')
|
||||
|| name.contains('\0')
|
||||
{
|
||||
return Err(format!(
|
||||
"databaseName contains invalid path characters: {name}"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_collection_name(name: &str) -> Result<(), String> {
|
||||
if name.is_empty() {
|
||||
return Err("collection name must not be empty".to_string());
|
||||
}
|
||||
if name == "."
|
||||
|| name == ".."
|
||||
|| name.contains('/')
|
||||
|| name.contains('\\')
|
||||
|| name.contains('\0')
|
||||
{
|
||||
return Err(format!(
|
||||
"collection name contains invalid path characters: {name}"
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_username(username: &str) -> Result<(), String> {
|
||||
if username.is_empty() {
|
||||
return Err("username must not be empty".to_string());
|
||||
}
|
||||
if username.contains('\0') {
|
||||
return Err("username must not contain NUL bytes".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_already_exists(message: &str) -> bool {
|
||||
message.contains("AlreadyExists") || message.contains("already exists")
|
||||
}
|
||||
|
||||
fn json_to_bson_doc(value: &serde_json::Value) -> Result<Document, String> {
|
||||
let bson_value: Bson = serde_json::from_value(value.clone()).map_err(|e| e.to_string())?;
|
||||
match bson_value {
|
||||
Bson::Document(document) => Ok(document),
|
||||
_ => Err("expected BSON document".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn now_ms() -> u64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis() as u64
|
||||
}
|
||||
|
||||
fn bson_doc_to_json(doc: &bson::Document) -> serde_json::Value {
|
||||
let bson_val = bson::Bson::Document(doc.clone());
|
||||
bson_val.into_relaxed_extjson()
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
||||
import * as smartdb from '../ts/index.js';
|
||||
import { MongoClient } from 'mongodb';
|
||||
import * as fs from 'fs';
|
||||
import * as os from 'os';
|
||||
import * as path from 'path';
|
||||
|
||||
let server: smartdb.SmartdbServer;
|
||||
let tmpDir: string;
|
||||
let storagePath: string;
|
||||
let usersPath: string;
|
||||
const port = 27129;
|
||||
const openedClients: MongoClient[] = [];
|
||||
|
||||
let tenantA: smartdb.ISmartDbDatabaseTenantDescriptor;
|
||||
let tenantB: smartdb.ISmartDbDatabaseTenantDescriptor;
|
||||
let exportedTenantA: smartdb.ISmartDbDatabaseExport;
|
||||
|
||||
function makeTmpDir(): string {
|
||||
return fs.mkdtempSync(path.join(os.tmpdir(), 'smartdb-tenants-test-'));
|
||||
}
|
||||
|
||||
function cleanTmpDir(dir: string): void {
|
||||
if (fs.existsSync(dir)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
async function connect(uri: string): Promise<MongoClient> {
|
||||
const client = new MongoClient(uri, {
|
||||
directConnection: true,
|
||||
serverSelectionTimeoutMS: 5000,
|
||||
});
|
||||
await client.connect();
|
||||
openedClients.push(client);
|
||||
return client;
|
||||
}
|
||||
|
||||
async function expectConnectionToFail(uri: string): Promise<void> {
|
||||
const client = new MongoClient(uri, {
|
||||
directConnection: true,
|
||||
serverSelectionTimeoutMS: 5000,
|
||||
});
|
||||
let threw = false;
|
||||
try {
|
||||
await client.connect();
|
||||
await client.db('tenant_a').command({ ping: 1 });
|
||||
} catch {
|
||||
threw = true;
|
||||
} finally {
|
||||
await client.close().catch(() => undefined);
|
||||
}
|
||||
expect(threw).toBeTrue();
|
||||
}
|
||||
|
||||
async function closeOpenedClients(): Promise<void> {
|
||||
while (openedClients.length > 0) {
|
||||
const client = openedClients.pop();
|
||||
await client?.close().catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
function createServer(): smartdb.SmartdbServer {
|
||||
return new smartdb.SmartdbServer({
|
||||
port,
|
||||
storage: 'file',
|
||||
storagePath,
|
||||
auth: {
|
||||
enabled: true,
|
||||
usersPath,
|
||||
scramIterations: 4096,
|
||||
users: [
|
||||
{
|
||||
username: 'root',
|
||||
password: 'secret',
|
||||
database: 'admin',
|
||||
roles: ['root'],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
tap.test('tenants: should start durable authenticated service', async () => {
|
||||
tmpDir = makeTmpDir();
|
||||
storagePath = path.join(tmpDir, 'data');
|
||||
usersPath = path.join(tmpDir, 'users.json');
|
||||
server = createServer();
|
||||
await server.start();
|
||||
expect(server.running).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('tenants: should create isolated database tenants', async () => {
|
||||
tenantA = await server.createDatabaseTenant({
|
||||
databaseName: 'tenant_a',
|
||||
username: 'tenant_a_user',
|
||||
password: 'tenant-a-pass-1',
|
||||
});
|
||||
tenantB = await server.createDatabaseTenant({
|
||||
databaseName: 'tenant_b',
|
||||
username: 'tenant_b_user',
|
||||
password: 'tenant-b-pass-1',
|
||||
});
|
||||
|
||||
expect(tenantA.databaseName).toEqual('tenant_a');
|
||||
expect(tenantA.authSource).toEqual('tenant_a');
|
||||
expect(tenantA.roles.includes('readWrite')).toBeTrue();
|
||||
expect(tenantA.roles.includes('dbAdmin')).toBeTrue();
|
||||
expect(typeof tenantA.mongodbUri).toEqual('string');
|
||||
|
||||
const tenants = await server.listDatabaseTenants();
|
||||
expect(tenants.some((tenant) => tenant.databaseName === 'tenant_a')).toBeTrue();
|
||||
expect(tenants.some((tenant) => tenant.databaseName === 'tenant_b')).toBeTrue();
|
||||
|
||||
const descriptor = await server.getDatabaseTenantDescriptor({
|
||||
databaseName: 'tenant_a',
|
||||
username: 'tenant_a_user',
|
||||
});
|
||||
expect(descriptor.username).toEqual('tenant_a_user');
|
||||
});
|
||||
|
||||
tap.test('tenants: should work with official MongoDB driver and enforce auth isolation', async () => {
|
||||
const clientA = await connect(tenantA.mongodbUri!);
|
||||
const clientB = await connect(tenantB.mongodbUri!);
|
||||
|
||||
const ping = await clientA.db('tenant_a').command({ ping: 1 });
|
||||
expect(ping.ok).toEqual(1);
|
||||
|
||||
await clientA.db('tenant_a').collection('notes').insertOne({ title: 'tenant a note' });
|
||||
await clientA.db('tenant_a').collection('notes').createIndex({ title: 1 });
|
||||
await clientB.db('tenant_b').collection('notes').insertOne({ title: 'tenant b note' });
|
||||
|
||||
let threw = false;
|
||||
try {
|
||||
await clientA.db('tenant_b').collection('notes').findOne({ title: 'tenant b note' });
|
||||
} catch (err: any) {
|
||||
threw = true;
|
||||
expect(err.code).toEqual(13);
|
||||
}
|
||||
expect(threw).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('tenants: should expose health and metrics for readiness checks', async () => {
|
||||
const health = await server.getHealth();
|
||||
expect(health.running).toBeTrue();
|
||||
expect(health.storagePath).toEqual(storagePath);
|
||||
expect(health.authEnabled).toBeTrue();
|
||||
expect(health.databaseCount >= 2).toBeTrue();
|
||||
expect(health.collectionCount >= 2).toBeTrue();
|
||||
|
||||
const metrics = await server.getMetrics();
|
||||
expect(metrics.authEnabled).toBeTrue();
|
||||
expect(metrics.databases >= 2).toBeTrue();
|
||||
expect(metrics.collections >= 2).toBeTrue();
|
||||
});
|
||||
|
||||
tap.test('tenants: should rotate password without restart', async () => {
|
||||
const oldUri = tenantA.mongodbUri!;
|
||||
await closeOpenedClients();
|
||||
|
||||
tenantA = await server.rotateDatabaseTenantPassword({
|
||||
username: 'tenant_a_user',
|
||||
password: 'tenant-a-pass-2',
|
||||
});
|
||||
expect(typeof tenantA.mongodbUri).toEqual('string');
|
||||
|
||||
await expectConnectionToFail(oldUri);
|
||||
const rotatedClient = await connect(tenantA.mongodbUri!);
|
||||
const doc = await rotatedClient.db('tenant_a').collection('notes').findOne({ title: 'tenant a note' });
|
||||
expect(doc).toBeTruthy();
|
||||
});
|
||||
|
||||
tap.test('tenants: should persist runtime users and file-backed data across restart', async () => {
|
||||
await closeOpenedClients();
|
||||
await server.stop();
|
||||
|
||||
server = createServer();
|
||||
await server.start();
|
||||
|
||||
const clientA = await connect(tenantA.mongodbUri!);
|
||||
const clientB = await connect(tenantB.mongodbUri!);
|
||||
const docA = await clientA.db('tenant_a').collection('notes').findOne({ title: 'tenant a note' });
|
||||
const docB = await clientB.db('tenant_b').collection('notes').findOne({ title: 'tenant b note' });
|
||||
expect(docA).toBeTruthy();
|
||||
expect(docB).toBeTruthy();
|
||||
});
|
||||
|
||||
tap.test('tenants: should export and restore one database without unrelated tenants', async () => {
|
||||
exportedTenantA = await server.exportDatabase({ databaseName: 'tenant_a' });
|
||||
expect(exportedTenantA.databaseName).toEqual('tenant_a');
|
||||
expect(exportedTenantA.collections.length).toEqual(1);
|
||||
expect(JSON.stringify(exportedTenantA).includes('tenant b note')).toBeFalse();
|
||||
|
||||
await closeOpenedClients();
|
||||
const deleteResult = await server.deleteDatabaseTenant({
|
||||
databaseName: 'tenant_a',
|
||||
username: 'tenant_a_user',
|
||||
});
|
||||
expect(deleteResult.databaseDropped).toBeTrue();
|
||||
expect(deleteResult.deletedUsers).toEqual(1);
|
||||
|
||||
await expectConnectionToFail(tenantA.mongodbUri!);
|
||||
|
||||
const importResult = await server.importDatabase({
|
||||
databaseName: 'tenant_a',
|
||||
source: exportedTenantA,
|
||||
});
|
||||
expect(importResult.databaseName).toEqual('tenant_a');
|
||||
expect(importResult.documents).toEqual(1);
|
||||
|
||||
tenantA = await server.createDatabaseTenant({
|
||||
databaseName: 'tenant_a',
|
||||
username: 'tenant_a_user',
|
||||
password: 'tenant-a-pass-3',
|
||||
});
|
||||
const restoredClient = await connect(tenantA.mongodbUri!);
|
||||
const restoredDoc = await restoredClient.db('tenant_a').collection('notes').findOne({ title: 'tenant a note' });
|
||||
expect(restoredDoc).toBeTruthy();
|
||||
|
||||
const clientB = await connect(tenantB.mongodbUri!);
|
||||
const unrelatedDoc = await clientB.db('tenant_b').collection('notes').findOne({ title: 'tenant b note' });
|
||||
expect(unrelatedDoc).toBeTruthy();
|
||||
});
|
||||
|
||||
tap.test('tenants: cleanup', async () => {
|
||||
await closeOpenedClients();
|
||||
await server.stop();
|
||||
expect(server.running).toBeFalse();
|
||||
cleanTmpDir(tmpDir);
|
||||
});
|
||||
|
||||
export default tap.start();
|
||||
@@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartdb',
|
||||
version: '2.8.0',
|
||||
version: '2.10.0',
|
||||
description: 'A MongoDB-compatible embedded database server with wire protocol support, backed by a high-performance Rust engine.'
|
||||
}
|
||||
|
||||
+10
@@ -22,4 +22,14 @@ export type {
|
||||
ICollectionInfo,
|
||||
IDocumentsResult,
|
||||
ISmartDbMetrics,
|
||||
ISmartDbHealth,
|
||||
ISmartDbDatabaseTenantInput,
|
||||
ISmartDbDeleteDatabaseTenantInput,
|
||||
ISmartDbRotateDatabaseTenantPasswordInput,
|
||||
ISmartDbDatabaseTenantDescriptor,
|
||||
ISmartDbDeleteDatabaseTenantResult,
|
||||
ISmartDbDatabaseExportCollection,
|
||||
ISmartDbDatabaseExport,
|
||||
ISmartDbImportDatabaseInput,
|
||||
ISmartDbImportDatabaseResult,
|
||||
} from './ts_smartdb/index.js';
|
||||
|
||||
@@ -22,3 +22,17 @@ export type {
|
||||
IDocumentsResult,
|
||||
ISmartDbMetrics,
|
||||
} from './rust-db-bridge.js';
|
||||
|
||||
// Export service API types
|
||||
export type {
|
||||
ISmartDbHealth,
|
||||
ISmartDbDatabaseTenantInput,
|
||||
ISmartDbDeleteDatabaseTenantInput,
|
||||
ISmartDbRotateDatabaseTenantPasswordInput,
|
||||
ISmartDbDatabaseTenantDescriptor,
|
||||
ISmartDbDeleteDatabaseTenantResult,
|
||||
ISmartDbDatabaseExportCollection,
|
||||
ISmartDbDatabaseExport,
|
||||
ISmartDbImportDatabaseInput,
|
||||
ISmartDbImportDatabaseResult,
|
||||
} from './service-types.js';
|
||||
|
||||
@@ -2,6 +2,30 @@ import * as plugins from './plugins.js';
|
||||
import * as path from 'path';
|
||||
import * as url from 'url';
|
||||
import { EventEmitter } from 'events';
|
||||
import type {
|
||||
ISmartDbHealth,
|
||||
ISmartDbDatabaseTenantInput,
|
||||
ISmartDbDeleteDatabaseTenantInput,
|
||||
ISmartDbRotateDatabaseTenantPasswordInput,
|
||||
ISmartDbDatabaseTenantDescriptor,
|
||||
ISmartDbDeleteDatabaseTenantResult,
|
||||
ISmartDbDatabaseExport,
|
||||
ISmartDbImportDatabaseInput,
|
||||
ISmartDbImportDatabaseResult,
|
||||
} from './service-types.js';
|
||||
|
||||
export type {
|
||||
ISmartDbHealth,
|
||||
ISmartDbDatabaseTenantInput,
|
||||
ISmartDbDeleteDatabaseTenantInput,
|
||||
ISmartDbRotateDatabaseTenantPasswordInput,
|
||||
ISmartDbDatabaseTenantDescriptor,
|
||||
ISmartDbDeleteDatabaseTenantResult,
|
||||
ISmartDbDatabaseExportCollection,
|
||||
ISmartDbDatabaseExport,
|
||||
ISmartDbImportDatabaseInput,
|
||||
ISmartDbImportDatabaseResult,
|
||||
} from './service-types.js';
|
||||
|
||||
/**
|
||||
* A single oplog entry returned from the Rust engine.
|
||||
@@ -90,7 +114,36 @@ type TSmartDbCommands = {
|
||||
start: { params: { config: ISmartDbRustConfig }; result: { connectionUri: string } };
|
||||
stop: { params: Record<string, never>; result: void };
|
||||
getStatus: { params: Record<string, never>; result: { running: boolean } };
|
||||
getHealth: { params: Record<string, never>; result: ISmartDbHealth };
|
||||
getMetrics: { params: Record<string, never>; result: ISmartDbMetrics };
|
||||
createDatabaseTenant: {
|
||||
params: ISmartDbDatabaseTenantInput;
|
||||
result: ISmartDbDatabaseTenantDescriptor;
|
||||
};
|
||||
deleteDatabaseTenant: {
|
||||
params: ISmartDbDeleteDatabaseTenantInput;
|
||||
result: ISmartDbDeleteDatabaseTenantResult;
|
||||
};
|
||||
rotateDatabaseTenantPassword: {
|
||||
params: ISmartDbRotateDatabaseTenantPasswordInput;
|
||||
result: ISmartDbDatabaseTenantDescriptor;
|
||||
};
|
||||
listDatabaseTenants: {
|
||||
params: Record<string, never>;
|
||||
result: { tenants: ISmartDbDatabaseTenantDescriptor[] };
|
||||
};
|
||||
getDatabaseTenantDescriptor: {
|
||||
params: { databaseName: string; username: string };
|
||||
result: ISmartDbDatabaseTenantDescriptor;
|
||||
};
|
||||
exportDatabase: {
|
||||
params: { databaseName: string };
|
||||
result: ISmartDbDatabaseExport;
|
||||
};
|
||||
importDatabase: {
|
||||
params: ISmartDbImportDatabaseInput;
|
||||
result: ISmartDbImportDatabaseResult;
|
||||
};
|
||||
getOpLog: {
|
||||
params: { sinceSeq?: number; limit?: number; db?: string; collection?: string };
|
||||
result: IOpLogResult;
|
||||
@@ -202,7 +255,7 @@ export class RustDbBridge extends EventEmitter {
|
||||
envVarName: 'SMARTDB_RUST_BINARY',
|
||||
platformPackagePrefix: '@push.rocks/smartdb',
|
||||
localPaths: buildLocalPaths(),
|
||||
maxPayloadSize: 10 * 1024 * 1024, // 10 MB
|
||||
maxPayloadSize: 100 * 1024 * 1024, // database exports/imports can be larger than command replies
|
||||
});
|
||||
|
||||
// Forward events from the inner bridge
|
||||
@@ -251,6 +304,48 @@ export class RustDbBridge extends EventEmitter {
|
||||
return this.bridge.sendCommand('getMetrics', {} as Record<string, never>) as Promise<ISmartDbMetrics>;
|
||||
}
|
||||
|
||||
public async getHealth(): Promise<ISmartDbHealth> {
|
||||
return this.bridge.sendCommand('getHealth', {} as Record<string, never>) as Promise<ISmartDbHealth>;
|
||||
}
|
||||
|
||||
public async createDatabaseTenant(
|
||||
params: ISmartDbDatabaseTenantInput,
|
||||
): Promise<ISmartDbDatabaseTenantDescriptor> {
|
||||
return this.bridge.sendCommand('createDatabaseTenant', params) as Promise<ISmartDbDatabaseTenantDescriptor>;
|
||||
}
|
||||
|
||||
public async deleteDatabaseTenant(
|
||||
params: ISmartDbDeleteDatabaseTenantInput,
|
||||
): Promise<ISmartDbDeleteDatabaseTenantResult> {
|
||||
return this.bridge.sendCommand('deleteDatabaseTenant', params) as Promise<ISmartDbDeleteDatabaseTenantResult>;
|
||||
}
|
||||
|
||||
public async rotateDatabaseTenantPassword(
|
||||
params: ISmartDbRotateDatabaseTenantPasswordInput,
|
||||
): Promise<ISmartDbDatabaseTenantDescriptor> {
|
||||
return this.bridge.sendCommand('rotateDatabaseTenantPassword', params) as Promise<ISmartDbDatabaseTenantDescriptor>;
|
||||
}
|
||||
|
||||
public async listDatabaseTenants(): Promise<ISmartDbDatabaseTenantDescriptor[]> {
|
||||
const result = await this.bridge.sendCommand('listDatabaseTenants', {} as Record<string, never>) as { tenants: ISmartDbDatabaseTenantDescriptor[] };
|
||||
return result.tenants;
|
||||
}
|
||||
|
||||
public async getDatabaseTenantDescriptor(params: {
|
||||
databaseName: string;
|
||||
username: string;
|
||||
}): Promise<ISmartDbDatabaseTenantDescriptor> {
|
||||
return this.bridge.sendCommand('getDatabaseTenantDescriptor', params) as Promise<ISmartDbDatabaseTenantDescriptor>;
|
||||
}
|
||||
|
||||
public async exportDatabase(params: { databaseName: string }): Promise<ISmartDbDatabaseExport> {
|
||||
return this.bridge.sendCommand('exportDatabase', params) as Promise<ISmartDbDatabaseExport>;
|
||||
}
|
||||
|
||||
public async importDatabase(params: ISmartDbImportDatabaseInput): Promise<ISmartDbImportDatabaseResult> {
|
||||
return this.bridge.sendCommand('importDatabase', params) as Promise<ISmartDbImportDatabaseResult>;
|
||||
}
|
||||
|
||||
public async getOpLog(params: {
|
||||
sinceSeq?: number;
|
||||
limit?: number;
|
||||
|
||||
@@ -9,6 +9,17 @@ import type {
|
||||
IDocumentsResult,
|
||||
ISmartDbMetrics,
|
||||
} from '../rust-db-bridge.js';
|
||||
import type {
|
||||
ISmartDbHealth,
|
||||
ISmartDbDatabaseTenantInput,
|
||||
ISmartDbDeleteDatabaseTenantInput,
|
||||
ISmartDbRotateDatabaseTenantPasswordInput,
|
||||
ISmartDbDatabaseTenantDescriptor,
|
||||
ISmartDbDeleteDatabaseTenantResult,
|
||||
ISmartDbDatabaseExport,
|
||||
ISmartDbImportDatabaseInput,
|
||||
ISmartDbImportDatabaseResult,
|
||||
} from '../service-types.js';
|
||||
|
||||
/**
|
||||
* Server configuration options
|
||||
@@ -204,6 +215,85 @@ export class SmartdbServer {
|
||||
return this.options.host ?? '127.0.0.1';
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an isolated database/user pair for an application tenant.
|
||||
*/
|
||||
async createDatabaseTenant(
|
||||
params: ISmartDbDatabaseTenantInput,
|
||||
): Promise<ISmartDbDatabaseTenantDescriptor> {
|
||||
const descriptor = await this.bridge.createDatabaseTenant(params);
|
||||
return this.withTenantMongoUri(descriptor, params.password);
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a tenant database and its tenant user(s).
|
||||
*/
|
||||
async deleteDatabaseTenant(
|
||||
params: ISmartDbDeleteDatabaseTenantInput,
|
||||
): Promise<ISmartDbDeleteDatabaseTenantResult> {
|
||||
return this.bridge.deleteDatabaseTenant(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rotate a tenant user's password without restarting the server.
|
||||
*/
|
||||
async rotateDatabaseTenantPassword(
|
||||
params: ISmartDbRotateDatabaseTenantPasswordInput,
|
||||
): Promise<ISmartDbDatabaseTenantDescriptor> {
|
||||
const descriptor = await this.bridge.rotateDatabaseTenantPassword(params);
|
||||
return this.withTenantMongoUri(descriptor, params.password);
|
||||
}
|
||||
|
||||
/**
|
||||
* List known database tenants.
|
||||
*/
|
||||
async listDatabaseTenants(): Promise<ISmartDbDatabaseTenantDescriptor[]> {
|
||||
return this.bridge.listDatabaseTenants();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a tenant descriptor without exposing a password.
|
||||
*/
|
||||
async getDatabaseTenantDescriptor(params: {
|
||||
databaseName: string;
|
||||
username: string;
|
||||
}): Promise<ISmartDbDatabaseTenantDescriptor> {
|
||||
return this.bridge.getDatabaseTenantDescriptor(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Export one database as an Extended JSON snapshot.
|
||||
*/
|
||||
async exportDatabase(params: { databaseName: string }): Promise<ISmartDbDatabaseExport> {
|
||||
return this.bridge.exportDatabase(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace one database with a previously exported snapshot.
|
||||
*/
|
||||
async importDatabase(params: ISmartDbImportDatabaseInput): Promise<ISmartDbImportDatabaseResult> {
|
||||
return this.bridge.importDatabase(params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get readiness/health details for long-running service use.
|
||||
*/
|
||||
async getHealth(): Promise<ISmartDbHealth> {
|
||||
if (!this.isRunning) {
|
||||
return {
|
||||
running: false,
|
||||
storage: this.options.storage,
|
||||
storagePath: this.options.storage === 'file' ? this.options.storagePath : this.options.persistPath,
|
||||
authEnabled: Boolean(this.options.auth?.enabled),
|
||||
authUsers: this.options.auth?.users?.length ?? 0,
|
||||
usersPathConfigured: Boolean(this.options.auth?.usersPath),
|
||||
databaseCount: 0,
|
||||
collectionCount: 0,
|
||||
};
|
||||
}
|
||||
return this.bridge.getHealth();
|
||||
}
|
||||
|
||||
// --- OpLog / Debug API ---
|
||||
|
||||
/**
|
||||
@@ -258,4 +348,26 @@ export class SmartdbServer {
|
||||
async getMetrics(): Promise<ISmartDbMetrics> {
|
||||
return this.bridge.getMetrics();
|
||||
}
|
||||
|
||||
private withTenantMongoUri(
|
||||
descriptor: ISmartDbDatabaseTenantDescriptor,
|
||||
password: string,
|
||||
): ISmartDbDatabaseTenantDescriptor {
|
||||
return {
|
||||
...descriptor,
|
||||
mongodbUri: this.buildTenantMongoUri(descriptor.databaseName, descriptor.username, password),
|
||||
};
|
||||
}
|
||||
|
||||
private buildTenantMongoUri(databaseName: string, username: string, password: string): string {
|
||||
const host = this.options.socketPath
|
||||
? encodeURIComponent(this.options.socketPath)
|
||||
: `${this.options.host ?? '127.0.0.1'}:${this.options.port ?? 27017}`;
|
||||
const auth = `${encodeURIComponent(username)}:${encodeURIComponent(password)}@`;
|
||||
const query = new URLSearchParams({ authSource: databaseName });
|
||||
if (this.options.tls?.enabled) {
|
||||
query.set('tls', 'true');
|
||||
}
|
||||
return `mongodb://${auth}${host}/${encodeURIComponent(databaseName)}?${query.toString()}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
export interface ISmartDbHealth {
|
||||
running: boolean;
|
||||
storage?: 'memory' | 'file';
|
||||
storagePath?: string;
|
||||
authEnabled?: boolean;
|
||||
authUsers?: number;
|
||||
usersPathConfigured?: boolean;
|
||||
databaseCount: number;
|
||||
collectionCount: number;
|
||||
uptimeSeconds?: number;
|
||||
}
|
||||
|
||||
export interface ISmartDbDatabaseTenantInput {
|
||||
databaseName: string;
|
||||
username: string;
|
||||
password: string;
|
||||
roles?: string[];
|
||||
}
|
||||
|
||||
export interface ISmartDbDeleteDatabaseTenantInput {
|
||||
databaseName: string;
|
||||
username?: string;
|
||||
}
|
||||
|
||||
export interface ISmartDbRotateDatabaseTenantPasswordInput {
|
||||
username: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface ISmartDbDatabaseTenantDescriptor {
|
||||
databaseName: string;
|
||||
username: string;
|
||||
roles: string[];
|
||||
authSource: string;
|
||||
mongodbUri?: string;
|
||||
}
|
||||
|
||||
export interface ISmartDbDeleteDatabaseTenantResult {
|
||||
databaseName: string;
|
||||
deletedUsers: number;
|
||||
databaseDropped: boolean;
|
||||
}
|
||||
|
||||
export interface ISmartDbDatabaseExportCollection {
|
||||
name: string;
|
||||
documents: Record<string, any>[];
|
||||
indexes: Record<string, any>[];
|
||||
}
|
||||
|
||||
export interface ISmartDbDatabaseExport {
|
||||
format: 'smartdb.database.export.v1';
|
||||
databaseName: string;
|
||||
exportedAtMs: number;
|
||||
collections: ISmartDbDatabaseExportCollection[];
|
||||
}
|
||||
|
||||
export interface ISmartDbImportDatabaseInput {
|
||||
databaseName: string;
|
||||
source: ISmartDbDatabaseExport;
|
||||
}
|
||||
|
||||
export interface ISmartDbImportDatabaseResult {
|
||||
databaseName: string;
|
||||
collections: number;
|
||||
documents: number;
|
||||
}
|
||||
Reference in New Issue
Block a user