Skip to content

Commit

Permalink
gRPC connected!
Browse files Browse the repository at this point in the history
  • Loading branch information
0xBLCKLPTN committed Oct 24, 2024
1 parent 572843c commit 41a447d
Show file tree
Hide file tree
Showing 6 changed files with 218 additions and 4 deletions.
7 changes: 7 additions & 0 deletions Plugins/Alice-Database/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,18 @@ homepage = "https://github.com/0xBLCKLPTN/Kingdom-System"
chrono = "0.4.38"
env_logger = "0.11.5"
log = "0.4.22"
prost = "0.13.3"
serde = { version = "1.0.213", features = ["derive"] }
serde_json = "1.0.132"
simplelog = "0.12.2"
tokio = { version = "1.41.0", features = ["full"] }
tonic = "0.12.3"
uuid = { version = "1.11.0", features = ["v4"] }

[[test]]
name = "tests"
path = "src/main.rs"


[build-dependencies]
tonic-build = "0.12.3"
4 changes: 4 additions & 0 deletions Plugins/Alice-Database/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@

fn main() {
tonic_build::compile_protos("proto/instance.proto").unwrap();
}
40 changes: 40 additions & 0 deletions Plugins/Alice-Database/proto/instance.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
syntax = "proto3";

package instance;

// Message definitions
message Instance {
string name = 1;
string engine = 2;
}

message CreateInstanceRequest {
string engine_type = 1;
string root_path = 2;
}

message CreateInstanceResponse {
string instance = 1;
}

message GetInstanceRequest {
string instance_name = 1;
}

message GetInstanceResponse {
string instance = 1; // Returning the instance
}

message GetAllInstancesRequest {
string message = 1;
}

message GetAllInstancesResponse {
repeated Instance instances = 1;
}

service InstanceService {
rpc CreateInstance(CreateInstanceRequest) returns (CreateInstanceResponse);
rpc GetInstance(GetInstanceRequest) returns (GetInstanceResponse);
rpc GetAllInstances(GetAllInstancesRequest) returns (GetAllInstancesResponse);
}
71 changes: 71 additions & 0 deletions Plugins/Alice-Database/src/grpc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
use tonic::{transport::Server, Request, Response, Status};
use uuid::Uuid;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

// Import generated gRPC code
pub mod instance {
tonic::include_proto!("instance");
}

use instance::{InstanceService, CreateInstanceRequest, CreateInstanceResponse,
GetInstanceRequest, GetInstanceResponse, Instance};

// Engines enum represents the types of engines
#[derive(Debug, Clone)]
pub enum Engines {
JSONEngine(JSONEngine),
}

// Your JSONEngine structure
#[derive(Debug, Clone)]
pub struct JSONEngine {
// Add fields necessary for your JSON engine
}

impl JSONEngine {
pub fn new(_root_path: &PathBuf) -> Self {
// Initialize your JSONEngine as needed
Self {}
}
}

// Instance structure
#[derive(Debug, Clone, Default)]
pub struct Instance {
pub name: String,
pub engine: Engines,
}

// InstanceManager struct to manage instances
#[derive(Debug, Default)]
pub struct InstanceManager {
pub name: String,
pub instances: Vec<Instance>,
}

impl InstanceManager {
pub fn new() -> Self {
let name = Uuid::new_v4().to_string();
let instances: Vec<Instance> = vec![];
Self { name, instances }
}

pub fn create_instance(&mut self, engine_type: &str, root_path: &PathBuf) -> String {
let instance_name: String = Uuid::new_v4().to_string();

let engine = match engine_type {
"json_engine" => Engines::JSONEngine(JSONEngine::new(root_path)),
_ => panic!("Engine not found"),
};

let instance = Instance { engine, name: instance_name.clone() };
self.instances.push(instance);
instance_name
}

pub fn get_instance(&self, instance_name: &str) -> Option<&Instance> {
self.instances.iter().find(|i| i.name == instance_name)
}
}

9 changes: 6 additions & 3 deletions Plugins/Alice-Database/src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ pub struct Instance {
pub engine: Engines,
}

#[derive(Debug, Clone)]
pub struct InstanceManger {
#[derive(Debug, Clone, Default)]
pub struct InstanceManager {
pub name: String,
pub instances: Vec<Instance>
}


impl InstanceManger {
impl InstanceManager {
pub fn new() -> Self {
let name = Uuid::new_v4().to_string();
let mut instances: Vec<Instance> = vec![];
Expand All @@ -34,6 +34,9 @@ impl InstanceManger {
self.instances.push(instance);
instance_name
}
pub fn get_instance(&self, instance_name: &str) -> Option<&Instance> {
self.instances.iter().find(|i| i.name == instance_name)
}
// Method to mutate the engine of an existing instance

pub fn get_mutable_engine(&mut self, instance_name: &str) -> Option<&mut JSONEngine> {
Expand Down
91 changes: 90 additions & 1 deletion Plugins/Alice-Database/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,23 @@ pub mod engines;
use engines::Engines;
pub mod instance;
use instance::*;

use crate::instance::InstanceManager;


use tonic::{transport::Server, Request, Response, Status};
use uuid::Uuid;
use std::sync::{Arc, Mutex};

pub mod instance_g {
tonic::include_proto!("instance");
}
pub use instance_g::{CreateInstanceRequest, CreateInstanceResponse,
GetInstanceRequest, GetInstanceResponse, GetAllInstancesRequest, GetAllInstancesResponse};

use crate::instance_g::instance_service_server::InstanceServiceServer;
use crate::instance_g::instance_service_server::InstanceService;

// Define constants for the root path and log path
const ROOT_DIR: &str = "Alice-Database-Data";
const ADB_DATA_DIR: &str = "ADB_Data";
Expand Down Expand Up @@ -71,9 +88,81 @@ fn print_ascii() {
")
}

// Define the gRPC service
#[derive(Debug, Default)]
pub struct MyInstanceManager {
pub instances: Arc<Mutex<InstanceManager>>,
}

#[tonic::async_trait]
impl InstanceService for MyInstanceManager {

async fn create_instance(
&self,
request: Request<CreateInstanceRequest>,
) -> Result<Response<CreateInstanceResponse>, Status> {
let inner = request.into_inner();
let engine_type = inner.engine_type;
let root_path = PathBuf::from(inner.root_path); // assuming root_path is a string path
let mut manager = self.instances.lock().unwrap();
let id = manager.create_instance(&engine_type,&root_path);

let response = CreateInstanceResponse { instance: id };
Ok(Response::new(response))
}

/// Get an existing instance by name

async fn get_instance(
&self,
request: Request<GetInstanceRequest>,
) -> Result<Response<GetInstanceResponse>, Status> {
let instance_name = request.into_inner().instance_name;
// Lock the mutex to safely access the manager
let manager = self.instances.lock().unwrap();
// Retrieve the instance by name
if let Some(instance) = manager.get_instance(&instance_name) {
return Ok(Response::new(GetInstanceResponse {
instance: instance.name.clone(), // Clone the entire instance
}));
}
Err(Status::not_found("Instance not found"))
}

async fn get_all_instances(
&self,
request: Request<GetAllInstancesRequest>,
) -> Result<Response<GetAllInstancesResponse>, Status> {
let manager = self.instances.lock().unwrap();
let mut re_instances: Vec<instance_g::Instance> = vec![];
for i in &manager.instances {
re_instances.push(instance_g::Instance {name: i.name.clone(), engine: "unknown".into()} );
}
let response = GetAllInstancesResponse { instances: re_instances };
Ok(Response::new(response))

}
}


// Main function to start the gRPC server
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let instance_manager = MyInstanceManager {
instances: Arc::new(Mutex::new(InstanceManager::new())),
};

println!("Starting gRPC server...");
Server::builder()
.add_service(InstanceServiceServer::new(instance_manager))
.serve("[::1]:50051".parse()?)
.await?;

Ok(())
}


/*
fn main() {
print_ascii();
let root_path = match prepare() {
Expand All @@ -88,7 +177,7 @@ fn main() {
println!("{:#?}", im);
}
/*
/// The main entry point for the application.
fn main() -> std::io::Result<()> {
print_ascii();
Expand Down

0 comments on commit 41a447d

Please sign in to comment.