Separate mycelium client more from supervisor client
Signed-off-by: Lee Smet <lee.smet@hotmail.com>
This commit is contained in:
@@ -1,28 +1,20 @@
|
||||
use std::net::IpAddr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
|
||||
use reqwest::Client as HttpClient;
|
||||
use serde_json::{Value, json};
|
||||
use thiserror::Error;
|
||||
|
||||
/// Destination for Mycelium messages
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Destination {
|
||||
Ip(IpAddr),
|
||||
Pk(String), // 64-hex public key
|
||||
}
|
||||
use crate::clients::{Destination, MyceliumClient, MyceliumClientError};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SupervisorClient {
|
||||
base_url: String, // e.g. "http://127.0.0.1:8990"
|
||||
destination: Destination, // ip or pk
|
||||
topic: String, // e.g. "supervisor.rpc"
|
||||
secret: Option<String>, // optional, required by several supervisor methods
|
||||
http: HttpClient,
|
||||
id_counter: Arc<AtomicU64>, // JSON-RPC id generator (for inner + outer requests)
|
||||
mycelium: Arc<MyceliumClient>, // Delegated Mycelium transport
|
||||
destination: Destination, // ip or pk
|
||||
topic: String, // e.g. "supervisor.rpc"
|
||||
secret: Option<String>, // optional, required by several supervisor methods
|
||||
id_counter: Arc<AtomicU64>, // JSON-RPC id generator (for inner supervisor requests)
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
@@ -41,8 +33,37 @@ pub enum SupervisorClientError {
|
||||
MissingSecret,
|
||||
}
|
||||
|
||||
impl From<MyceliumClientError> for SupervisorClientError {
|
||||
fn from(e: MyceliumClientError) -> Self {
|
||||
match e {
|
||||
MyceliumClientError::TransportTimeout => SupervisorClientError::TransportTimeout,
|
||||
MyceliumClientError::RpcError(m) => SupervisorClientError::RpcError(m),
|
||||
MyceliumClientError::InvalidResponse(m) => SupervisorClientError::InvalidResponse(m),
|
||||
MyceliumClientError::Http(err) => SupervisorClientError::Http(err),
|
||||
MyceliumClientError::Json(err) => SupervisorClientError::Json(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SupervisorClient {
|
||||
/// Create a new client. base_url defaults to Mycelium spec "http://127.0.0.1:8990" if empty.
|
||||
/// Preferred constructor: provide a shared Mycelium client.
|
||||
pub fn new_with_client(
|
||||
mycelium: Arc<MyceliumClient>,
|
||||
destination: Destination,
|
||||
topic: impl Into<String>,
|
||||
secret: Option<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
mycelium,
|
||||
destination,
|
||||
topic: topic.into(),
|
||||
secret,
|
||||
id_counter: Arc::new(AtomicU64::new(1)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Backward-compatible constructor that builds a Mycelium client from base_url.
|
||||
/// base_url defaults to Mycelium spec "http://127.0.0.1:8990" if empty.
|
||||
pub fn new(
|
||||
base_url: impl Into<String>,
|
||||
destination: Destination,
|
||||
@@ -53,21 +74,15 @@ impl SupervisorClient {
|
||||
if url.is_empty() {
|
||||
url = "http://127.0.0.1:8990".to_string();
|
||||
}
|
||||
let http = HttpClient::builder().build()?;
|
||||
Ok(Self {
|
||||
base_url: url,
|
||||
destination,
|
||||
topic: topic.into(),
|
||||
secret,
|
||||
http,
|
||||
id_counter: Arc::new(AtomicU64::new(1)),
|
||||
})
|
||||
let mycelium = Arc::new(MyceliumClient::new(url)?);
|
||||
Ok(Self::new_with_client(mycelium, destination, topic, secret))
|
||||
}
|
||||
|
||||
fn next_id(&self) -> u64 {
|
||||
self.id_counter.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Internal helper used by tests to inspect dst JSON shape.
|
||||
fn build_dst(&self) -> Value {
|
||||
match &self.destination {
|
||||
Destination::Ip(ip) => json!({ "ip": ip.to_string() }),
|
||||
@@ -89,49 +104,6 @@ impl SupervisorClient {
|
||||
Ok(BASE64_STANDARD.encode(s.as_bytes()))
|
||||
}
|
||||
|
||||
fn build_push_request(&self, payload_b64: String) -> Value {
|
||||
let dst = self.build_dst();
|
||||
let msg = json!({
|
||||
"dst": dst,
|
||||
"topic": self.topic,
|
||||
"payload": payload_b64
|
||||
});
|
||||
|
||||
// Async path: no reply_timeout attached
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": self.next_id(),
|
||||
"method": "pushMessage",
|
||||
"params": [ { "message": msg } ]
|
||||
})
|
||||
}
|
||||
|
||||
async fn send_push(&self, req: &Value) -> Result<Value, SupervisorClientError> {
|
||||
let resp = self.http.post(&self.base_url).json(req).send().await?;
|
||||
let status = resp.status();
|
||||
let body: Value = resp.json().await?;
|
||||
// JSON-RPC error object handling
|
||||
if let Some(err) = body.get("error") {
|
||||
let code = err.get("code").and_then(|v| v.as_i64()).unwrap_or(0);
|
||||
let msg = err
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("unknown error");
|
||||
if code == 408 {
|
||||
return Err(SupervisorClientError::TransportTimeout);
|
||||
}
|
||||
return Err(SupervisorClientError::RpcError(format!(
|
||||
"code={code} msg={msg}"
|
||||
)));
|
||||
}
|
||||
if !status.is_success() {
|
||||
return Err(SupervisorClientError::RpcError(format!(
|
||||
"HTTP status {status}, body {body}"
|
||||
)));
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
fn extract_message_id_from_result(result: &Value) -> Option<String> {
|
||||
// Two possibilities per Mycelium spec oneOf:
|
||||
// - PushMessageResponseId: { "id": "0123456789abcdef" }
|
||||
@@ -142,34 +114,28 @@ impl SupervisorClient {
|
||||
.map(|s| s.to_string())
|
||||
}
|
||||
|
||||
/// Generic call: build supervisor JSON-RPC message, wrap in Mycelium pushMessage, return outbound message id (hex).
|
||||
/// Generic call: build supervisor JSON-RPC message, send via Mycelium pushMessage, return outbound message id (hex).
|
||||
pub async fn call(&self, method: &str, params: Value) -> Result<String, SupervisorClientError> {
|
||||
let inner = self.build_supervisor_payload(method, params);
|
||||
let payload_b64 = Self::encode_payload(&inner)?;
|
||||
let push_req = self.build_push_request(payload_b64);
|
||||
let resp = self.send_push(&push_req).await?;
|
||||
let result = self
|
||||
.mycelium
|
||||
.push_message(&self.destination, &self.topic, &payload_b64, None)
|
||||
.await?;
|
||||
|
||||
// Expect "result" to be either inbound message or response id
|
||||
match resp.get("result") {
|
||||
Some(res_obj) => {
|
||||
if let Some(id) = Self::extract_message_id_from_result(res_obj) {
|
||||
return Ok(id);
|
||||
}
|
||||
// Some servers might return the oneOf wrapped, handle len==1 array defensively (not in spec but resilient)
|
||||
if let Some(arr) = res_obj.as_array()
|
||||
&& arr.len() == 1
|
||||
&& let Some(id) = Self::extract_message_id_from_result(&arr[0])
|
||||
{
|
||||
return Ok(id);
|
||||
}
|
||||
Err(SupervisorClientError::InvalidResponse(format!(
|
||||
"result did not contain message id: {res_obj}"
|
||||
)))
|
||||
}
|
||||
None => Err(SupervisorClientError::InvalidResponse(format!(
|
||||
"missing result in response: {resp}"
|
||||
))),
|
||||
if let Some(id) = MyceliumClient::extract_message_id_from_result(&result) {
|
||||
return Ok(id);
|
||||
}
|
||||
// Some servers might return the oneOf wrapped, handle len==1 array defensively (not in spec but resilient)
|
||||
if let Some(arr) = result.as_array()
|
||||
&& arr.len() == 1
|
||||
&& let Some(id) = MyceliumClient::extract_message_id_from_result(&arr[0])
|
||||
{
|
||||
return Ok(id);
|
||||
}
|
||||
Err(SupervisorClientError::InvalidResponse(format!(
|
||||
"result did not contain message id: {result}"
|
||||
)))
|
||||
}
|
||||
|
||||
fn need_secret(&self) -> Result<&str, SupervisorClientError> {
|
||||
@@ -334,8 +300,10 @@ impl SupervisorClient {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::net::IpAddr;
|
||||
|
||||
fn mk_client() -> SupervisorClient {
|
||||
// Uses the legacy constructor but will not issue real network calls in these tests.
|
||||
SupervisorClient::new(
|
||||
"http://127.0.0.1:8990",
|
||||
Destination::Pk(
|
||||
@@ -368,20 +336,21 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wraps_supervisor_payload_in_push_message() {
|
||||
fn encodes_supervisor_payload_b64() {
|
||||
let c = mk_client();
|
||||
let payload = c.build_supervisor_payload("list_runners", json!([]));
|
||||
let b64 = SupervisorClient::encode_payload(&payload).unwrap();
|
||||
let req = c.build_push_request(b64);
|
||||
assert_eq!(req.get("method").unwrap().as_str().unwrap(), "pushMessage");
|
||||
let params = req.get("params").unwrap().as_array().unwrap();
|
||||
let msg = params[0].get("message").unwrap();
|
||||
assert!(msg.get("payload").is_some());
|
||||
|
||||
// decode and compare round-trip JSON
|
||||
let raw = base64::engine::general_purpose::STANDARD
|
||||
.decode(b64.as_bytes())
|
||||
.unwrap();
|
||||
let decoded: Value = serde_json::from_slice(&raw).unwrap();
|
||||
assert_eq!(
|
||||
msg.get("topic").unwrap().as_str().unwrap(),
|
||||
"supervisor.rpc"
|
||||
decoded.get("method").unwrap().as_str().unwrap(),
|
||||
"list_runners"
|
||||
);
|
||||
assert!(msg.get("dst").unwrap().get("pk").is_some());
|
||||
assert_eq!(decoded.get("jsonrpc").unwrap().as_str().unwrap(), "2.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
Reference in New Issue
Block a user