Initial commit
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "mm-bridge"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "mm-bridge"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
mm-core.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
@@ -0,0 +1,67 @@
|
||||
use crate::{protocol, status};
|
||||
use mm_core::{BridgeError, ErrorKind};
|
||||
|
||||
pub fn handle_request(request: protocol::Request) -> protocol::Response {
|
||||
match request.method.as_str() {
|
||||
"ping" => protocol::Response::ok(request.id, protocol::pong_result()),
|
||||
"status" => protocol::Response::ok(request.id, status::status_result()),
|
||||
_ => protocol::Response::err(
|
||||
request.id,
|
||||
BridgeError::new(
|
||||
ErrorKind::UnknownMethod,
|
||||
format!("unknown method: {}", request.method),
|
||||
),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_line(line: &str) -> protocol::Response {
|
||||
match protocol::parse_request(line) {
|
||||
Ok(request) => handle_request(request),
|
||||
Err((id, error)) => protocol::Response::err(id, error),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn response_line(line: &str) -> String {
|
||||
let response = handle_line(line);
|
||||
match protocol::encode_response(&response) {
|
||||
Ok(encoded) => encoded,
|
||||
Err(error) => fallback_error_line(&response.id, error),
|
||||
}
|
||||
}
|
||||
|
||||
fn fallback_error_line(id: &str, error: BridgeError) -> String {
|
||||
let response = protocol::Response::err(id, error);
|
||||
let value = serde_json::to_value(response).unwrap_or_else(|_| {
|
||||
serde_json::json!({
|
||||
"id": id,
|
||||
"type": "response",
|
||||
"ok": false,
|
||||
"error": {
|
||||
"code": "internal_error",
|
||||
"message": "failed to encode error response",
|
||||
"retryable": false
|
||||
}
|
||||
})
|
||||
});
|
||||
format!("{value}\n")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ping_line_returns_pong() {
|
||||
let line = response_line(r#"{"id":"1","type":"request","method":"ping","params":{}}"#);
|
||||
assert!(line.contains(r#""ok":true"#));
|
||||
assert!(line.contains(r#""pong":true"#));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_method_returns_error() {
|
||||
let line = response_line(r#"{"id":"2","type":"request","method":"nope","params":{}}"#);
|
||||
assert!(line.contains(r#""ok":false"#));
|
||||
assert!(line.contains("unknown_method"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
use std::env;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BridgeConfig {
|
||||
pub listen: String,
|
||||
}
|
||||
|
||||
impl BridgeConfig {
|
||||
pub fn from_env() -> anyhow::Result<Self> {
|
||||
let listen =
|
||||
env::var("MM_BRIDGE_LISTEN").unwrap_or_else(|_| "127.0.0.1:8765".to_string());
|
||||
|
||||
validate_listen(&listen)?;
|
||||
|
||||
Ok(Self { listen })
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_listen(listen: &str) -> anyhow::Result<()> {
|
||||
anyhow::ensure!(
|
||||
!listen.trim().is_empty(),
|
||||
"MM_BRIDGE_LISTEN must not be empty"
|
||||
);
|
||||
anyhow::ensure!(
|
||||
listen.contains(':'),
|
||||
"MM_BRIDGE_LISTEN must be host:port"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rejects_empty_listen() {
|
||||
assert!(validate_listen("").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_host_port() {
|
||||
assert!(validate_listen("127.0.0.1:8765").is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
//! Main bridge library.
|
||||
|
||||
pub mod app;
|
||||
pub mod config;
|
||||
pub mod protocol;
|
||||
pub mod server;
|
||||
pub mod status;
|
||||
pub mod transport;
|
||||
@@ -0,0 +1,24 @@
|
||||
use anyhow::Context;
|
||||
use mm_bridge::{config::BridgeConfig, server};
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
init_tracing();
|
||||
|
||||
let config = BridgeConfig::from_env().context("failed to load bridge config")?;
|
||||
tracing::info!(listen = %config.listen, "starting emacs-mattermost bridge");
|
||||
|
||||
server::run(config).await
|
||||
}
|
||||
|
||||
fn init_tracing() {
|
||||
let filter = EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| EnvFilter::new("mm_bridge=info,warn"));
|
||||
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(filter)
|
||||
.with_target(true)
|
||||
.with_writer(std::io::stderr)
|
||||
.init();
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
use mm_core::{BridgeError, ErrorKind};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
pub struct Request {
|
||||
pub id: String,
|
||||
#[serde(rename = "type")]
|
||||
pub kind: String,
|
||||
pub method: String,
|
||||
#[serde(default)]
|
||||
pub params: Value,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Response {
|
||||
pub id: String,
|
||||
#[serde(rename = "type")]
|
||||
pub kind: &'static str,
|
||||
pub ok: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub result: Option<Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub error: Option<ProtocolError>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct ProtocolError {
|
||||
pub code: String,
|
||||
pub message: String,
|
||||
pub retryable: bool,
|
||||
}
|
||||
|
||||
impl Response {
|
||||
pub fn ok(id: impl Into<String>, result: Value) -> Self {
|
||||
Self {
|
||||
id: id.into(),
|
||||
kind: "response",
|
||||
ok: true,
|
||||
result: Some(result),
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn err(id: impl Into<String>, error: BridgeError) -> Self {
|
||||
let kind = error.kind();
|
||||
Self {
|
||||
id: id.into(),
|
||||
kind: "response",
|
||||
ok: false,
|
||||
result: None,
|
||||
error: Some(ProtocolError {
|
||||
code: kind.as_str().to_string(),
|
||||
message: error.message().to_string(),
|
||||
retryable: kind.retryable(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_request(line: &str) -> Result<Request, (String, BridgeError)> {
|
||||
let value: Value = serde_json::from_str(line).map_err(|err| {
|
||||
(
|
||||
"unknown".to_string(),
|
||||
BridgeError::new(ErrorKind::InvalidJson, err.to_string()),
|
||||
)
|
||||
})?;
|
||||
|
||||
let id = value
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
|
||||
let request: Request = serde_json::from_value(value).map_err(|err| {
|
||||
(
|
||||
id.clone(),
|
||||
BridgeError::new(ErrorKind::InvalidRequest, err.to_string()),
|
||||
)
|
||||
})?;
|
||||
|
||||
validate_request(&request).map_err(|err| (id, err))?;
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
fn validate_request(request: &Request) -> Result<(), BridgeError> {
|
||||
if request.id.trim().is_empty() {
|
||||
return Err(BridgeError::new(
|
||||
ErrorKind::InvalidRequest,
|
||||
"id must not be empty",
|
||||
));
|
||||
}
|
||||
|
||||
if request.kind != "request" {
|
||||
return Err(BridgeError::new(
|
||||
ErrorKind::InvalidRequest,
|
||||
"type must be request",
|
||||
));
|
||||
}
|
||||
|
||||
if request.method.trim().is_empty() {
|
||||
return Err(BridgeError::new(
|
||||
ErrorKind::InvalidRequest,
|
||||
"method must not be empty",
|
||||
));
|
||||
}
|
||||
|
||||
if !request.params.is_object() && !request.params.is_null() {
|
||||
return Err(BridgeError::new(
|
||||
ErrorKind::InvalidRequest,
|
||||
"params must be an object",
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn encode_response(response: &Response) -> Result<String, BridgeError> {
|
||||
let mut line = serde_json::to_string(response)
|
||||
.map_err(|err| BridgeError::new(ErrorKind::InternalError, err.to_string()))?;
|
||||
line.push('\n');
|
||||
Ok(line)
|
||||
}
|
||||
|
||||
pub fn pong_result() -> Value {
|
||||
json!({ "pong": true })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_ping_request() {
|
||||
let req = parse_request(r#"{"id":"1","type":"request","method":"ping","params":{}}"#)
|
||||
.expect("valid request");
|
||||
assert_eq!(req.method, "ping");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encodes_response_with_newline() {
|
||||
let line = encode_response(&Response::ok("1", pong_result())).expect("encode");
|
||||
assert!(line.ends_with('\n'));
|
||||
assert!(line.contains(r#""pong":true"#));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use crate::{config::BridgeConfig, transport};
|
||||
use anyhow::Context;
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
pub async fn run(config: BridgeConfig) -> anyhow::Result<()> {
|
||||
let listener = TcpListener::bind(&config.listen)
|
||||
.await
|
||||
.with_context(|| format!("failed to bind {}", config.listen))?;
|
||||
|
||||
tracing::info!(listen = %config.listen, "bridge listening");
|
||||
|
||||
loop {
|
||||
let (stream, peer) = listener.accept().await.context("accept failed")?;
|
||||
tracing::debug!(%peer, "accepted connection");
|
||||
|
||||
tokio::spawn(async move {
|
||||
if let Err(error) = transport::handle_client(stream).await {
|
||||
tracing::warn!(%error, "client handler failed");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
use mm_core::{BridgeState, ServerSummary};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub const BRIDGE_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
pub fn status_result() -> Value {
|
||||
let servers: Vec<ServerSummary> = Vec::new();
|
||||
|
||||
json!({
|
||||
"bridge": {
|
||||
"version": BRIDGE_VERSION,
|
||||
"state": BridgeState::Running,
|
||||
},
|
||||
"servers": servers,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn status_has_empty_servers() {
|
||||
let value = status_result();
|
||||
assert_eq!(value["servers"].as_array().unwrap().len(), 0);
|
||||
assert_eq!(value["bridge"]["state"], "running");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use crate::app;
|
||||
|
||||
pub async fn handle_client(stream: TcpStream) -> std::io::Result<()> {
|
||||
let peer = stream.peer_addr().ok();
|
||||
tracing::info!(?peer, "client connected");
|
||||
|
||||
let (read_half, mut write_half) = stream.into_split();
|
||||
let mut lines = BufReader::new(read_half).lines();
|
||||
|
||||
while let Some(line) = lines.next_line().await? {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let response = app::response_line(&line);
|
||||
write_half.write_all(response.as_bytes()).await?;
|
||||
write_half.flush().await?;
|
||||
}
|
||||
|
||||
tracing::info!(?peer, "client disconnected");
|
||||
Ok(())
|
||||
}
|
||||
Reference in New Issue
Block a user