Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TS-2073] Server implementation for tooling interop #11

Draft
wants to merge 4 commits into
base: develop
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 33 additions & 79 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 8 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,11 @@ indicatif = { version = "0.17.8", features = ["improved_unicode", "tokio"] }
# async runtime and helpers
futures = "0.3"
futures-util = "0.3"
tokio = { version = "1.34", features = ["macros", "process", "rt-multi-thread"]}
tokio = { version = "1.34", features = [
"macros",
"process",
"rt-multi-thread",
] }
tokio-util = { version = "0.7", features = ["io"] }
async-compression = { version = "0.4", features = ["futures-io", "gzip"] }

Expand All @@ -45,3 +49,6 @@ log = "0.4.21"

[target.'cfg(windows)'.dependencies]
winreg = "0.50"

[dev-dependencies]
tempfile = "3.10"
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ mod error;
mod game;
mod package;
mod project;
mod server;
mod ts;
mod ui;
mod util;
Expand Down
61 changes: 61 additions & 0 deletions src/server/lock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
use std::fs::{self, File};
use std::path::{Path, PathBuf};

/// Only one server process can "own" a project at a single time.
/// We enforce this exclusive access through the creation and deletion of this lockfile.
const LOCKFILE: &'static str = ".server-lock";

Check warning

Code scanning / clippy

constants have by default a 'static lifetime Warning

constants have by default a 'static lifetime

pub struct ProjectLock {
file: File,
path: PathBuf,
}

impl ProjectLock {
/// Attempt to acquire a lock on the provided directory.
pub fn lock(project_path: &Path) -> Option<Self> {
let lock = project_path.join(LOCKFILE);
match lock.is_file() {
true => None,
false => {
let file = File::create(&lock).ok()?;
Some(Self { file, path: lock })
}
}
}
}

impl Drop for ProjectLock {
fn drop(&mut self) {
// The file handle is dropped before this, so we can safely delete it.
fs::remove_file(&self.path).unwrap();
}
}

#[cfg(test)]
mod test {
use super::*;
use tempfile::TempDir;

/// Test that project locks behave in the following way:
/// - Attempting to lock an already locked project MUST return None.
/// - Attempting to lock a project that is not locked will return a ProjectLock.
/// - Dropping a ProjectLock will remove the lockfile from the project.
#[test]
fn test_project_lock() {
let temp = TempDir::new().unwrap();
let root = temp.path();

// Acquire a lock on the directory.
{
let _lock =
ProjectLock::lock(root).expect("Failed to acquire lock on empty directory.");

// Attempting to acquire it again will return None.
let relock = ProjectLock::lock(root);
assert!(relock.is_none());
}

// Now that the previous lock is dropped we *should* be able to re-acquire it.
let _lock = ProjectLock::lock(root).expect("Failed to acquire lock on empty directory.");
}
}
43 changes: 43 additions & 0 deletions src/server/method/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
pub mod package;
pub mod project;

use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

use self::package::PackageMethod;
use self::project::ProjectMethod;
use super::Error;

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub enum Method {
Exit,
Project(ProjectMethod),
Package(PackageMethod),
}

/// Method namespace registration.
impl Method {
pub fn from_value(method: &str, value: serde_json::Value) -> Result<Self, Error> {
let mut split = method.split('/');
let (namespace, name) = (
split
.next()
.ok_or_else(|| Error::InvalidMethod(method.into()))?,
split
.next()
.ok_or_else(|| Error::InvalidMethod(method.into()))?,
);

// Route namespaces to the appropriate enum variants for construction.
Ok(match namespace {
"exit" => Self::Exit,
"project" => Self::Project(ProjectMethod::from_value(name, value)?),
"package" => Self::Package(PackageMethod::from_value(name, value)?),
x => Err(Error::InvalidMethod(x.into()))?,
})
}
}

pub fn parse_value<T: DeserializeOwned>(value: serde_json::Value) -> Result<T, serde_json::Error> {
serde_json::from_value(value)
}
21 changes: 21 additions & 0 deletions src/server/method/package.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
use serde::{Deserialize, Serialize};

use super::Error;

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub enum PackageMethod {
/// Get metadata about this package.
GetMetadata,
/// Determine if the package exists within the cache.
IsCached,
}

impl PackageMethod {
pub fn from_value(method: &str, value: serde_json::Value) -> Result<Self, Error> {

Check warning

Code scanning / clippy

unused variable: value Warning

unused variable: value
Ok(match method {
"get_metadata" => Self::GetMetadata,
"is_cached" => Self::IsCached,
x => Err(Error::InvalidMethod(x.into()))?,
})
}
}
Loading
Loading