Skip to content
This repository has been archived by the owner on Jul 2, 2024. It is now read-only.

Commit

Permalink
cli: implement preview subcommand
Browse files Browse the repository at this point in the history
  • Loading branch information
tsirysndr committed May 6, 2023
1 parent 94cc489 commit 977a76d
Show file tree
Hide file tree
Showing 26 changed files with 137 additions and 7 deletions.
1 change: 1 addition & 0 deletions examples/angular/Superfile.hcl
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ services = [
"namespace" = "demo_namespace"
"stdout" = "/tmp/angular-stdout.log"
"stderr" = "/tmp/angular-stderr.log"
"port" = 4200
flox = {
"environment" = ".#angular"
}
Expand Down
1 change: 1 addition & 0 deletions proto/objects/v1alpha1/process.proto
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,5 @@ message Process {
bool auto_restart = 13;
repeated string env = 14;
string service_id = 15;
int32 port = 16;
}
1 change: 1 addition & 0 deletions proto/objects/v1alpha1/service.proto
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ message Service {
string status = 7;
repeated string depends_on = 8;
bool auto_restart = 9;
int32 port = 10;
}
6 changes: 6 additions & 0 deletions sdk/deno/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class Service {
floxEnvironment?: string;
enableDocker?: boolean;
enableNix?: boolean;
port?: number;

constructor() {
this.name = "";
Expand Down Expand Up @@ -104,6 +105,11 @@ class Service {
this.enableNix = enableNix;
return this;
}

withPort(port: number): Service {
this.port = port;
return this;
}
}

export default Service;
6 changes: 3 additions & 3 deletions sdk/gleam/src/service.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub type Service {
auto_restart: Bool,
auto_start: Bool,
namespace: String,
port: Int,
port: Option(Int),
stdout: String,
stderr: String,
flox: Option(Flox),
Expand All @@ -33,7 +33,7 @@ pub fn new_service() -> Service {
False,
False,
"default",
0,
None,
"",
"",
None,
Expand Down Expand Up @@ -80,7 +80,7 @@ pub fn with_namespace(service: Service, namespace: String) -> Service {
}

pub fn with_port(service: Service, port: Int) -> Service {
Service(..service, port: port)
Service(..service, port: Some(port))
}

pub fn with_stdout(service: Service, stdout: String) -> Service {
Expand Down
1 change: 1 addition & 0 deletions sdk/go/examples/examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ func TestCreateProject(t *testing.T) {
deno := sdk.NewService().
WithName("deno-fresh").
WithCommand("./dev.ts").
WithPort(8000).
WithEnv(map[string]string{
"PORT": "8000",
})
Expand Down
4 changes: 4 additions & 0 deletions sdk/go/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ func BuildParams(service Service) string {
params = fmt.Sprintf(`%s command: "%s", `, params, service.Command)
}

if service.Port != nil {
params = fmt.Sprintf(`%s port: %d, `, params, *service.Port)
}

if len(service.Env) > 0 {
env := ""
for key, value := range service.Env {
Expand Down
6 changes: 6 additions & 0 deletions sdk/go/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type Service struct {
FloxEnvrionment *string
EnableDocker *bool
EnableNix *bool
Port *int
}

func NewService() *Service {
Expand Down Expand Up @@ -97,3 +98,8 @@ func (s *Service) WithEnableNix(enableNix *bool) *Service {
s.EnableNix = enableNix
return s
}

func (s *Service) WithPort(port int) *Service {
s.Port = &port
return s
}
Binary file modified sdk/node/bun.lockb
Binary file not shown.
6 changes: 6 additions & 0 deletions sdk/node/src/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ class Service {
floxEnvironment?: string;
enableDocker?: boolean;
enableNix?: boolean;
port?: number;

constructor() {
this.name = "";
Expand Down Expand Up @@ -65,6 +66,11 @@ class Service {
this.enableNix = enableNix;
return this;
}

withPort(port: number) {
this.port = port;
return this;
}
}

export default Service;
4 changes: 4 additions & 0 deletions sdk/rust/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@ fn build_params(service: Service) -> String {
params = format!(r#"{} command: "{}", "#, params, service.command);
}

if service.port.is_some() {
params = format!(r#"{} port: {}, "#, params, service.port.unwrap());
}

if !service.r#type.is_empty() {
params = format!(r#"{} type: "{}", "#, params, service.r#type);
}
Expand Down
1 change: 1 addition & 0 deletions sdk/rust/src/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub struct Service {
pub flox_enviroment: Option<String>,
pub enable_docker: Option<bool>,
pub enable_nix: Option<bool>,
pub port: Option<u32>,
}

impl Service {
Expand Down
4 changes: 4 additions & 0 deletions src/api/objects.v1alpha1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ pub struct Service {
pub depends_on: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
#[prost(bool, tag = "9")]
pub auto_restart: bool,
#[prost(int32, tag = "10")]
pub port: i32,
}
#[allow(clippy::derive_partial_eq_without_eq)]
#[derive(Clone, PartialEq, ::prost::Message)]
Expand Down Expand Up @@ -54,6 +56,8 @@ pub struct Process {
pub env: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
#[prost(string, tag = "15")]
pub service_id: ::prost::alloc::string::String,
#[prost(int32, tag = "16")]
pub port: i32,
}
#[derive(serde::Serialize)]
#[allow(clippy::derive_partial_eq_without_eq)]
Expand Down
1 change: 1 addition & 0 deletions src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub mod init;
pub mod list;
pub mod log;
pub mod new;
pub mod preview;
pub mod project;
pub mod ps;
pub mod restart;
Expand Down
59 changes: 59 additions & 0 deletions src/cmd/preview.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
use anyhow::Error;
use owo_colors::OwoColorize;
use tokio::net::UnixStream;
use tonic::transport::{ Endpoint, Uri};
use tower::service_fn;
use crate::{
api::superviseur::v1alpha1::{
control_service_client::ControlServiceClient, LoadConfigRequest, StatusRequest,
},
types::{ UNIX_SOCKET_PATH, SUPERFILE}, config::verify_if_config_file_is_present,
};

pub async fn execute_preview(name: &str) -> Result<(), Error> {
verify_if_config_file_is_present()?;
let current_dir = std::env::current_dir()?;
let config = std::fs::read_to_string(current_dir.join(SUPERFILE))?;
let channel = Endpoint::try_from("http://[::]:50051")?
.connect_with_connector(service_fn(move |_: Uri| UnixStream::connect( UNIX_SOCKET_PATH)))
.await
.map_err(|_|
Error::msg(format!("Cannot connect to the Superviseur daemon at unix:{}. Is the superviseur daemon running?", UNIX_SOCKET_PATH)))?;

// let mut client = ControlServiceClient::connect("http://127.0.0.1:5476").await?;
let mut client = ControlServiceClient::new(channel);

let request = tonic::Request::new(LoadConfigRequest {
config,
file_path: current_dir.to_str().unwrap().to_string(),
});

client.load_config(request).await?;

let request = tonic::Request::new(StatusRequest {
name: name.to_string(),
config_file_path: current_dir.to_str().unwrap().to_string(),
});

let response = client.status(request).await?;
let response = response.into_inner();

match response.process {
Some(process) => {
match process.state.as_str() {
"Running" => {
open::that(format!("http://localhost:{}", process.port))?;
println!("Previewing {} at http://localhost:{}", process.name.bright_green(), process.port);
}
_ => {
println!("{} is not running", process.name);
},
};
}
None => {
println!("{} is not running", name);
}
}

Ok(())
}
1 change: 1 addition & 0 deletions src/graphql/schema/objects/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub struct Process {
pub env: Vec<String>,
pub state: String,
pub up_time: String,
pub port: Option<u32>,
}

#[Object]
Expand Down
1 change: 1 addition & 0 deletions src/graphql/schema/objects/project_configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ impl ProjectConfiguration {
autostart: service.auto_start.unwrap_or(false),
env,
depends_on: service.depends_on.unwrap_or(vec![]),
port: service.port,
..Default::default()
};
config.services.push(service);
Expand Down
1 change: 1 addition & 0 deletions src/graphql/schema/objects/service_configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ pub struct ServiceConfiguration {
pub enable_flox: Option<bool>,
pub enable_nix: Option<bool>,
pub flox_enviroment: Option<String>,
pub port: Option<u32>,
}
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ pub mod api {
depends_on: self.depends_on,
command: self.command,
r#type: self.r#type,
port: Some(self.port as u32),
..Default::default()
}
}
Expand All @@ -45,6 +46,7 @@ pub mod api {
depends_on: service.depends_on,
command: service.command,
r#type: service.r#type,
port: service.port.unwrap_or_default() as i32,
..Default::default()
}
}
Expand Down Expand Up @@ -76,6 +78,7 @@ pub mod api {
auto_restart: self.auto_restart,
env,
service_id: self.service_id,
port: Some(self.port as u32),
..Default::default()
}
}
Expand All @@ -102,6 +105,7 @@ pub mod api {
auto_restart: process.auto_restart,
env,
service_id: process.service_id,
port: process.port.unwrap_or_default() as i32,
..Default::default()
}
}
Expand Down
10 changes: 10 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use superviseur::{
list::execute_list,
log::execute_log,
new::execute_new,
preview::execute_preview,
project::{execute_get_project, execute_list_projects},
ps::execute_ps,
restart::execute_restart,
Expand Down Expand Up @@ -117,6 +118,11 @@ A simple process supervisor"#,
)
.about("Manage projects")
)
.subcommand(
Command::new("preview")
.arg(arg!(<name> "The name of the service to preview"))
.about("Open URL of a service in the browser"),
)
}

#[tokio::main]
Expand Down Expand Up @@ -187,6 +193,10 @@ async fn main() -> Result<(), Error> {
Some(("list", _)) => execute_list_projects().await?,
_ => SubCommand::with_name("project").print_help()?,
},
Some(("preview", args)) => {
let name = args.value_of("name");
execute_preview(name.unwrap()).await?;
}
_ => cli().print_help()?,
}
Ok(())
Expand Down
1 change: 1 addition & 0 deletions src/server/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,7 @@ impl ControlService for Control {
auto_restart: service.autorestart,
stdout: service.stdout.clone(),
stderr: service.stderr.clone(),
port: service.port,
..Default::default()
});
Ok(Response::new(StatusResponse {
Expand Down
1 change: 1 addition & 0 deletions src/superviseur/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@ impl SuperviseurInternal {
process.auto_restart = service.autorestart;
process.stdout = service.stdout;
process.stderr = service.stderr;
process.port = service.port;
return Ok(());
}

Expand Down
2 changes: 1 addition & 1 deletion src/superviseur/dependencies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ struct Vertex {
autostart: bool,
autorestart: bool,
namespace: Option<String>,
port: Option<u16>,
port: Option<u32>,
stdout: String,
stderr: String,
driver: Box<dyn DriverPlugin + Send>,
Expand Down
2 changes: 1 addition & 1 deletion src/types/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub struct Service {
pub autorestart: bool,
pub namespace: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub port: Option<u16>,
pub port: Option<u32>,
pub stdout: String,
pub stderr: String,
#[serde(skip_serializing_if = "Option::is_none")]
Expand Down
11 changes: 9 additions & 2 deletions src/types/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,6 @@ pub struct Process {
#[tabled(skip)]
pub working_dir: String,
#[tabled(skip)]
pub port: Option<u16>,
#[tabled(skip)]
pub env: HashMap<String, String>,
#[tabled(skip)]
pub project: String,
Expand All @@ -117,6 +115,8 @@ pub struct Process {
pub stderr: String,
#[tabled(rename = "SERVICE_ID")]
pub service_id: String,
#[tabled(rename = "PORT", display_with = "display_port")]
pub port: Option<u32>,
}

fn display_option<T: ToString>(value: &Option<T>) -> String {
Expand Down Expand Up @@ -156,3 +156,10 @@ pub fn format_duration(duration: Duration) -> String {
let days = duration.num_days();
format!("{} {} ago", days, if days == 1 { "day" } else { "days" })
}

fn display_port(port: &Option<u32>) -> String {
match port {
Some(port) => port.clone().to_string(),
None => "-".to_string(),
}
}
9 changes: 9 additions & 0 deletions src/types/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ pub struct Service {
pub description: String,
#[tabled(skip)]
pub depends_on: Vec<String>,
#[tabled(rename = "PORT", display_with = "display_port")]
pub port: Option<u32>,
}

fn display_command(command: &str) -> String {
Expand All @@ -25,3 +27,10 @@ fn display_command(command: &str) -> String {
format!("\"{}\"", command.to_string())
}
}

fn display_port(port: &Option<u32>) -> String {
match port {
Some(port) => port.clone().to_string(),
None => "-".to_string(),
}
}

0 comments on commit 977a76d

Please sign in to comment.