Skip to content

Commit 96059c4

Browse files
committed
ref(daemon): move state to daemon module
1 parent 4aacd34 commit 96059c4

File tree

14 files changed

+120
-103
lines changed

14 files changed

+120
-103
lines changed

src/daemon.rs

Lines changed: 9 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,76 +1,32 @@
11
use anyhow::{bail, Context, Result};
22
mod command;
3+
pub mod state;
4+
35
pub use command::*;
46

7+
#[cfg(feature = "daemon")]
8+
pub use state::DaemonState;
9+
510
pub const DAEMON_SOCKET_PATH: &str = "/tmp/xcodebase-daemon.socket";
611
pub const DAEMON_BINARY: &str =
712
"/Users/tami5/repos/neovim/xcodebase.nvim/target/debug/xcodebase-daemon";
813

914
pub struct Daemon {
1015
#[cfg(feature = "daemon")]
11-
state: std::sync::Arc<tokio::sync::Mutex<crate::state::State>>,
16+
pub state: std::sync::Arc<tokio::sync::Mutex<state::DaemonStateData>>,
1217
#[cfg(feature = "daemon")]
13-
listener: tokio::net::UnixListener,
18+
pub listener: tokio::net::UnixListener,
1419
}
1520

16-
#[cfg(feature = "daemon")]
1721
impl Daemon {
18-
pub fn default() -> Self {
19-
if std::fs::metadata(DAEMON_SOCKET_PATH).is_ok() {
20-
std::fs::remove_file(DAEMON_SOCKET_PATH).ok();
21-
}
22-
23-
tracing::info!("Started");
24-
22+
#[cfg(feature = "daemon")]
23+
pub fn new() -> Self {
2524
Self {
2625
state: Default::default(),
2726
listener: tokio::net::UnixListener::bind(DAEMON_SOCKET_PATH).unwrap(),
2827
}
2928
}
3029

31-
/// Run Main daemon server loop
32-
pub async fn run(&mut self) -> ! {
33-
use tokio::io::AsyncReadExt;
34-
35-
loop {
36-
let state = self.state.clone();
37-
let (mut s, _) = self.listener.accept().await.unwrap();
38-
tokio::spawn(async move {
39-
// let mut current_state = state.lock().await;
40-
// current_state.update_clients();
41-
42-
// trace!("Current State: {:?}", state.lock().await)
43-
let mut string = String::default();
44-
45-
if let Err(e) = s.read_to_string(&mut string).await {
46-
tracing::error!("[Read Error]: {:?}", e);
47-
return;
48-
};
49-
50-
if string.len() == 0 {
51-
return;
52-
}
53-
54-
let msg = DaemonCommand::parse(string.as_str().trim());
55-
56-
if let Err(e) = msg {
57-
tracing::error!("[Parse Error]: {:?}", e);
58-
return;
59-
};
60-
61-
let msg = msg.unwrap();
62-
if let Err(e) = msg.handle(state.clone()).await {
63-
tracing::error!("[Failure]: Cause: ({:?}), Message: {:?}", e, msg);
64-
return;
65-
};
66-
67-
crate::watch::update(state, msg).await;
68-
});
69-
}
70-
}
71-
}
72-
73-
impl Daemon {
7430
/// Spawn new instance of the server via running binaray is a child process
7531
pub fn spawn() -> Result<()> {
7632
std::process::Command::new(DAEMON_BINARY)

src/daemon/bin.rs

Lines changed: 74 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,77 @@
1+
use tokio::io::AsyncReadExt;
2+
use xcodebase::util::tracing::install_tracing;
3+
use xcodebase::{daemon::*, util::watch};
4+
15
#[tokio::main]
26
async fn main() -> anyhow::Result<()> {
3-
xcodebase::install_tracing("/tmp", "xcodebase-daemon.log", tracing::Level::TRACE, true)?;
4-
xcodebase::Daemon::default().run().await
7+
install_tracing("/tmp", "xcodebase-daemon.log", tracing::Level::TRACE, true)?;
8+
9+
if std::fs::metadata(DAEMON_SOCKET_PATH).is_ok() {
10+
std::fs::remove_file(DAEMON_SOCKET_PATH).ok();
11+
}
12+
13+
tracing::info!("Started");
14+
15+
let daemon = Daemon::new();
16+
17+
loop {
18+
let state = daemon.state.clone();
19+
let (mut s, _) = daemon.listener.accept().await.unwrap();
20+
tokio::spawn(async move {
21+
let mut string = String::default();
22+
23+
if let Err(e) = s.read_to_string(&mut string).await {
24+
tracing::error!("[Read Error]: {:?}", e);
25+
return;
26+
};
27+
28+
if string.len() == 0 {
29+
return;
30+
}
31+
32+
let msg = DaemonCommand::parse(string.as_str().trim());
33+
34+
if let Err(e) = msg {
35+
tracing::error!("[Parse Error]: {:?}", e);
36+
return;
37+
};
38+
39+
let msg = msg.unwrap();
40+
if let Err(e) = msg.handle(state.clone()).await {
41+
tracing::error!("[Failure]: Cause: ({:?}), Message: {:?}", e, msg);
42+
return;
43+
};
44+
45+
// watch::update(state, msg).await;
46+
47+
let copy = state.clone();
48+
let mut current_state = copy.lock().await;
49+
// let mut watched_roots: Vec<String> = vec![];
50+
let mut start_watching: Vec<String> = vec![];
51+
52+
// TODO: Remove wathcers for workspaces that are no longer exist
53+
54+
let watched_roots = current_state
55+
.watchers
56+
.keys()
57+
.map(Clone::clone)
58+
.collect::<Vec<String>>();
59+
// for key in current_state.watchers.keys() {
60+
// watched_roots.push(key.clone());
61+
// }
62+
63+
for key in current_state.workspaces.keys() {
64+
if !watched_roots.contains(key) {
65+
start_watching.push(key.clone());
66+
}
67+
}
68+
69+
for root in start_watching {
70+
let handle = watch::handler(state.clone(), root.clone());
71+
#[cfg(feature = "logging")]
72+
tracing::info!("Watching {root}");
73+
current_state.watchers.insert(root, handle);
74+
}
75+
});
76+
}
577
}

src/daemon/command.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ pub use run::Run;
1515
#[async_trait::async_trait]
1616
#[cfg(feature = "daemon")]
1717
pub trait DaemonCommandExt {
18-
async fn handle(&self, state: crate::SharedState) -> Result<()>;
18+
async fn handle(&self, state: crate::daemon::DaemonState) -> Result<()>;
1919
}
2020

2121
#[derive(Debug)]
@@ -29,7 +29,7 @@ pub enum DaemonCommand {
2929

3030
impl DaemonCommand {
3131
#[cfg(feature = "daemon")]
32-
pub async fn handle(&self, state: crate::SharedState) -> Result<()> {
32+
pub async fn handle(&self, state: crate::daemon::DaemonState) -> Result<()> {
3333
use DaemonCommand::*;
3434

3535
match self {

src/daemon/command/build.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use anyhow::Result;
22

3-
use crate::Daemon;
3+
use crate::daemon::Daemon;
44

55
#[derive(Debug)]
66
pub struct Build {
@@ -16,8 +16,8 @@ pub struct Build {
1616
// with the options needed to build
1717
#[cfg(feature = "daemon")]
1818
#[async_trait::async_trait]
19-
impl crate::DaemonCommandExt for Build {
20-
async fn handle(&self, _state: crate::state::SharedState) -> Result<()> {
19+
impl crate::daemon::DaemonCommandExt for Build {
20+
async fn handle(&self, _state: crate::daemon::DaemonState) -> Result<()> {
2121
tracing::info!("build command");
2222
Ok(())
2323
}
@@ -46,7 +46,7 @@ impl Build {
4646
impl Build {
4747
#[cfg(feature = "lua")]
4848
pub fn lua(lua: &mlua::Lua, (t, c, s): (String, String, String)) -> mlua::Result<()> {
49-
use crate::LuaExtension;
49+
use crate::util::mlua::LuaExtension;
5050
lua.trace(format!("Build (target: {t} configuration: {c}, scheme: {s})").as_ref())?;
5151
Self::request(&t, &c, &s).map_err(mlua::Error::external)
5252
}

src/daemon/command/drop.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ pub struct Drop {
99

1010
#[cfg(feature = "daemon")]
1111
#[async_trait::async_trait]
12-
impl crate::DaemonCommandExt for Drop {
13-
async fn handle(&self, state: crate::state::SharedState) -> Result<()> {
12+
impl crate::daemon::DaemonCommandExt for Drop {
13+
async fn handle(&self, state: crate::daemon::DaemonState) -> Result<()> {
1414
tracing::trace!("{:?}", self);
1515
state
1616
.lock()
@@ -38,7 +38,7 @@ impl TryFrom<Vec<&str>> for Drop {
3838
impl Drop {
3939
pub const KEY: &'static str = "drop";
4040
pub fn request(pid: i32, root: String) -> Result<()> {
41-
crate::Daemon::execute(&[Self::KEY, pid.to_string().as_str(), root.as_str()])
41+
crate::daemon::Daemon::execute(&[Self::KEY, pid.to_string().as_str(), root.as_str()])
4242
}
4343

4444
#[cfg(feature = "lua")]

src/daemon/command/register.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ pub struct Register {
99

1010
#[cfg(feature = "daemon")]
1111
#[async_trait::async_trait]
12-
impl crate::DaemonCommandExt for Register {
13-
async fn handle(&self, state: crate::SharedState) -> Result<()> {
12+
impl crate::daemon::DaemonCommandExt for Register {
13+
async fn handle(&self, state: crate::daemon::DaemonState) -> Result<()> {
1414
tracing::trace!("{:?}", self);
1515
state.lock().await.add_workspace(&self.root, self.pid).await
1616
}
@@ -34,14 +34,14 @@ impl TryFrom<Vec<&str>> for Register {
3434
impl Register {
3535
pub const KEY: &'static str = "register";
3636
pub fn request(pid: i32, root: String) -> Result<()> {
37-
crate::Daemon::execute(&[Self::KEY, pid.to_string().as_str(), root.as_str()])
37+
crate::daemon::Daemon::execute(&[Self::KEY, pid.to_string().as_str(), root.as_str()])
3838
}
3939
}
4040

4141
#[cfg(feature = "lua")]
4242
impl Register {
4343
pub fn lua(lua: &mlua::Lua, (pid, root): (i32, String)) -> mlua::Result<()> {
44-
use crate::LuaExtension;
44+
use crate::util::mlua::LuaExtension;
4545
lua.trace(&format!("Add (pid: {pid} cwd: {root})"))?;
4646
Self::request(pid, root).map_err(mlua::Error::external)
4747
}

src/daemon/command/rename_file.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ pub struct RenameFile {
1212
// TODO: Implement file rename along with it's main class if any.
1313
#[cfg(feature = "daemon")]
1414
#[async_trait::async_trait]
15-
impl crate::DaemonCommandExt for RenameFile {
16-
async fn handle(&self, _state: crate::SharedState) -> Result<()> {
15+
impl crate::daemon::DaemonCommandExt for RenameFile {
16+
async fn handle(&self, _state: crate::daemon::DaemonState) -> Result<()> {
1717
tracing::info!("Reanmed command");
1818
Ok(())
1919
}
@@ -44,7 +44,7 @@ impl TryFrom<Vec<&str>> for RenameFile {
4444
impl RenameFile {
4545
pub const KEY: &'static str = "rename_file";
4646
pub fn request(path: &str, name: &str, new_name: &str) -> Result<()> {
47-
crate::Daemon::execute(&[Self::KEY, path, name, new_name])
47+
crate::daemon::Daemon::execute(&[Self::KEY, path, name, new_name])
4848
}
4949
}
5050

@@ -54,7 +54,7 @@ impl RenameFile {
5454
lua: &mlua::Lua,
5555
(path, name, new_name): (String, String, String),
5656
) -> mlua::Result<()> {
57-
use crate::LuaExtension;
57+
use crate::util::mlua::LuaExtension;
5858
lua.trace(&format!("Rename command called"))?;
5959
Self::request(&path, &name, &new_name).map_err(mlua::Error::external)
6060
}

src/daemon/command/run.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ pub struct Run {
1313
// macos apps, which is wrong
1414
#[cfg(feature = "daemon")]
1515
#[async_trait::async_trait]
16-
impl crate::DaemonCommandExt for Run {
17-
async fn handle(&self, _state: crate::state::SharedState) -> Result<()> {
16+
impl crate::daemon::DaemonCommandExt for Run {
17+
async fn handle(&self, _state: crate::daemon::DaemonState) -> Result<()> {
1818
tracing::info!("Run command");
1919
Ok(())
2020
}
@@ -33,14 +33,14 @@ impl Run {
3333
pub const KEY: &'static str = "run";
3434

3535
pub fn request(with_simulator: bool) -> Result<()> {
36-
crate::Daemon::execute(&[Self::KEY, &with_simulator.to_string()])
36+
crate::daemon::Daemon::execute(&[Self::KEY, &with_simulator.to_string()])
3737
}
3838
}
3939

4040
#[cfg(feature = "lua")]
4141
impl Run {
4242
pub fn lua(lua: &mlua::Lua, with_simulator: bool) -> mlua::Result<()> {
43-
use crate::LuaExtension;
43+
use crate::util::mlua::LuaExtension;
4444
lua.trace(&format!("Run command called"))?;
4545
Self::request(with_simulator).map_err(mlua::Error::external)
4646
}
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use std::collections::HashMap;
1111

1212
/// Main state
1313
#[derive(Default, Debug)]
14-
pub struct State {
14+
pub struct DaemonStateData {
1515
/// Manged workspaces
1616
pub workspaces: HashMap<String, Workspace>,
1717
/// Connected clients
@@ -22,10 +22,10 @@ pub struct State {
2222
}
2323

2424
#[cfg(feature = "async")]
25-
pub type SharedState = std::sync::Arc<tokio::sync::Mutex<State>>;
25+
pub type DaemonState = std::sync::Arc<tokio::sync::Mutex<DaemonStateData>>;
2626

2727
#[cfg(feature = "daemon")]
28-
impl State {
28+
impl DaemonStateData {
2929
pub fn update_clients(&mut self) {
3030
self.clients
3131
.retain(|pid| crate::util::proc::exists(pid, || tracing::info!("Removing {pid}")));

0 commit comments

Comments
 (0)