0.7.27 +Refactor
This commit is contained in:
225
kb_demo_app/src/demo_http.rs
Normal file
225
kb_demo_app/src/demo_http.rs
Normal file
@@ -0,0 +1,225 @@
|
||||
// file: kb_demo_app/src/demo_http.rs
|
||||
|
||||
//! Tauri commands for the HTTP demo window.
|
||||
//!
|
||||
//! This module exposes a small manual test surface over the HTTP endpoint pool.
|
||||
|
||||
use tauri::Manager;
|
||||
|
||||
/// Request payload for one demo HTTP execution.
|
||||
#[derive(Clone, Debug, serde::Deserialize, ts_rs::TS)]
|
||||
#[ts(export, export_to = "../frontend/ts/bindings/DemoHttpRequest.ts")]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct DemoHttpRequest {
|
||||
/// Logical role used to select one endpoint from the pool.
|
||||
pub role: std::string::String,
|
||||
/// JSON-RPC HTTP method name.
|
||||
pub method: std::string::String,
|
||||
/// Optional first string argument, used by methods such as
|
||||
/// `getBalance`, `getAccountInfo`, `getProgramAccounts`,
|
||||
/// `getSignaturesForAddress`, `getTransaction`, `sendTransaction`.
|
||||
pub first_arg: std::option::Option<std::string::String>,
|
||||
/// Optional JSON config payload encoded as a string.
|
||||
pub config_json: std::option::Option<std::string::String>,
|
||||
}
|
||||
|
||||
/// Response payload for one demo HTTP execution.
|
||||
#[derive(Clone, Debug, serde::Serialize, ts_rs::TS)]
|
||||
#[ts(export, export_to = "../frontend/ts/bindings/DemoHttpExecutionPayload.ts")]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct DemoHttpExecutionPayload {
|
||||
/// Selected endpoint name.
|
||||
pub endpoint_name: std::string::String,
|
||||
/// Selected endpoint provider.
|
||||
pub provider: std::string::String,
|
||||
/// Selected endpoint URL.
|
||||
pub endpoint_url: std::string::String,
|
||||
/// Requested role.
|
||||
pub role: std::string::String,
|
||||
/// Executed method name.
|
||||
pub method: std::string::String,
|
||||
/// Classified method family.
|
||||
pub method_class: std::string::String,
|
||||
/// Pretty-printed JSON response payload.
|
||||
pub response_json: std::string::String,
|
||||
}
|
||||
|
||||
/// Opens the dedicated HTTP demo window.
|
||||
#[tauri::command]
|
||||
pub(crate) fn open_demo_http_window(
|
||||
app_handle: tauri::AppHandle,
|
||||
) -> Result<(), std::string::String> {
|
||||
let existing_window_option = app_handle.get_webview_window("demo_http");
|
||||
|
||||
let demo_window = match existing_window_option {
|
||||
Some(demo_window) => demo_window,
|
||||
None => {
|
||||
let builder = tauri::WebviewWindowBuilder::new(
|
||||
&app_handle,
|
||||
"demo_http",
|
||||
tauri::WebviewUrl::App("demo_http.html".into()),
|
||||
)
|
||||
.title("Demo Http")
|
||||
.inner_size(1400.0, 768.0)
|
||||
.min_inner_size(800.0, 600.0)
|
||||
.center()
|
||||
.visible(true)
|
||||
.transparent(false)
|
||||
.decorations(true);
|
||||
let build_result = builder.build();
|
||||
match build_result {
|
||||
Ok(window) => window,
|
||||
Err(error) => {
|
||||
return Err(format!("cannot create demo_http window: {error:?}"));
|
||||
},
|
||||
}
|
||||
},
|
||||
};
|
||||
let show_result = demo_window.show();
|
||||
if let Err(error) = show_result {
|
||||
return Err(format!("cannot show demo_http window: {error:?}"));
|
||||
}
|
||||
let focus_result = demo_window.set_focus();
|
||||
if let Err(error) = focus_result {
|
||||
return Err(format!("cannot focus demo_http window: {error:?}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns a fresh snapshot of the HTTP endpoint pool.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_http_list_pool_clients(
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
) -> Result<std::vec::Vec<kb_lib::HttpPoolClientSnapshot>, std::string::String> {
|
||||
Ok(state.http_pool.snapshot().await)
|
||||
}
|
||||
|
||||
/// Executes one manual HTTP request through the endpoint pool.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_http_execute_request(
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
request: DemoHttpRequest,
|
||||
) -> Result<DemoHttpExecutionPayload, std::string::String> {
|
||||
let role = request.role.trim().to_string();
|
||||
if role.is_empty() {
|
||||
return Err("demo http role must not be empty".to_string());
|
||||
}
|
||||
let method = request.method.trim().to_string();
|
||||
if method.is_empty() {
|
||||
return Err("demo http method must not be empty".to_string());
|
||||
}
|
||||
let config_json_value_result = parse_optional_demo_http_json(request.config_json);
|
||||
let config_json_value = match config_json_value_result {
|
||||
Ok(config_json_value) => config_json_value,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let params_result =
|
||||
build_demo_http_params(&method, request.first_arg.as_deref(), config_json_value);
|
||||
let params = match params_result {
|
||||
Ok(params) => params,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let selected_client_result =
|
||||
state.http_pool.select_client_for_role_and_method(&role, &method).await;
|
||||
let selected_client = match selected_client_result {
|
||||
Ok(selected_client) => selected_client,
|
||||
Err(error) => return Err(error.to_string()),
|
||||
};
|
||||
let method_class = kb_lib::HttpClient::classify_method(&method);
|
||||
let method_class_text = demo_http_method_class_to_string(method_class);
|
||||
tracing::trace!(
|
||||
endpoint_name = %selected_client.endpoint_name(),
|
||||
endpoint_url = %selected_client.endpoint_url(),
|
||||
role = %role,
|
||||
method = %method,
|
||||
method_class = %method_class_text,
|
||||
"executing demo http request"
|
||||
);
|
||||
let response_value_result =
|
||||
selected_client.execute_json_rpc_result_raw(method.clone(), params).await;
|
||||
let response_value = match response_value_result {
|
||||
Ok(response_value) => response_value,
|
||||
Err(error) => return Err(error.to_string()),
|
||||
};
|
||||
let response_json_result = serde_json::to_string_pretty(&response_value);
|
||||
let response_json = match response_json_result {
|
||||
Ok(response_json) => response_json,
|
||||
Err(error) => {
|
||||
return Err(format!(
|
||||
"cannot pretty-print demo http response for method '{}': {}",
|
||||
method, error
|
||||
));
|
||||
},
|
||||
};
|
||||
Ok(DemoHttpExecutionPayload {
|
||||
endpoint_name: selected_client.endpoint_name().to_string(),
|
||||
provider: selected_client.endpoint_config().provider.clone(),
|
||||
endpoint_url: selected_client.endpoint_url().to_string(),
|
||||
role,
|
||||
method,
|
||||
method_class: method_class_text.to_string(),
|
||||
response_json,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_optional_demo_http_json(
|
||||
config_json: std::option::Option<std::string::String>,
|
||||
) -> Result<std::option::Option<serde_json::Value>, std::string::String> {
|
||||
let config_json = match config_json {
|
||||
Some(config_json) => config_json.trim().to_string(),
|
||||
None => {
|
||||
return Ok(None);
|
||||
},
|
||||
};
|
||||
if config_json.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let value_result = serde_json::from_str::<serde_json::Value>(&config_json);
|
||||
match value_result {
|
||||
Ok(value) => Ok(Some(value)),
|
||||
Err(error) => Err(format!("invalid configJson: {}", error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_demo_http_params(
|
||||
method: &str,
|
||||
first_arg: std::option::Option<&str>,
|
||||
config_json: std::option::Option<serde_json::Value>,
|
||||
) -> Result<std::vec::Vec<serde_json::Value>, std::string::String> {
|
||||
let needs_first_arg = matches!(
|
||||
method,
|
||||
"getBalance"
|
||||
| "getAccountInfo"
|
||||
| "getProgramAccounts"
|
||||
| "getSignaturesForAddress"
|
||||
| "getTransaction"
|
||||
| "sendTransaction"
|
||||
);
|
||||
if needs_first_arg {
|
||||
let first_arg = match first_arg {
|
||||
Some(first_arg) => first_arg.trim(),
|
||||
None => "",
|
||||
};
|
||||
if first_arg.is_empty() {
|
||||
return Err(format!("method '{}' requires firstArg", method));
|
||||
}
|
||||
let mut params = vec![serde_json::Value::String(first_arg.to_string())];
|
||||
if let Some(config_json) = config_json {
|
||||
params.push(config_json);
|
||||
}
|
||||
return Ok(params);
|
||||
}
|
||||
let mut params = std::vec::Vec::new();
|
||||
if let Some(config_json) = config_json {
|
||||
params.push(config_json);
|
||||
}
|
||||
Ok(params)
|
||||
}
|
||||
|
||||
fn demo_http_method_class_to_string(method_class: kb_lib::HttpMethodClass) -> &'static str {
|
||||
match method_class {
|
||||
kb_lib::HttpMethodClass::GeneralRpc => "GeneralRpc",
|
||||
kb_lib::HttpMethodClass::SendTransaction => "SendTransaction",
|
||||
kb_lib::HttpMethodClass::HeavyRead => "HeavyRead",
|
||||
}
|
||||
}
|
||||
1696
kb_demo_app/src/demo_pipeline.rs
Normal file
1696
kb_demo_app/src/demo_pipeline.rs
Normal file
File diff suppressed because it is too large
Load Diff
1424
kb_demo_app/src/demo_pipeline2.rs
Normal file
1424
kb_demo_app/src/demo_pipeline2.rs
Normal file
File diff suppressed because it is too large
Load Diff
974
kb_demo_app/src/demo_ws.rs
Normal file
974
kb_demo_app/src/demo_ws.rs
Normal file
@@ -0,0 +1,974 @@
|
||||
// file: kb_demo_app/src/demo_ws.rs
|
||||
|
||||
//! Demo WebSocket window commands and runtime state.
|
||||
//!
|
||||
//! This module isolates the manual WebSocket subscription test bench from the
|
||||
//! main application window.
|
||||
|
||||
use tauri::Emitter;
|
||||
use tauri::Manager;
|
||||
|
||||
/// Endpoint summary sent to the demo frontend.
|
||||
#[derive(Clone, Debug, serde::Serialize, ts_rs::TS)]
|
||||
#[ts(export, export_to = "../frontend/ts/bindings/DemoWsEndpointSummary.ts")]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct DemoWsEndpointSummary {
|
||||
name: std::string::String,
|
||||
resolved_url: std::string::String,
|
||||
provider: std::string::String,
|
||||
enabled: bool,
|
||||
roles: std::vec::Vec<std::string::String>,
|
||||
}
|
||||
|
||||
/// Current demo window runtime status.
|
||||
#[derive(Clone, Debug, serde::Serialize, ts_rs::TS)]
|
||||
#[ts(export, export_to = "../frontend/ts/bindings/DemoWsStatusPayload.ts")]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct DemoWsStatusPayload {
|
||||
connection_state: std::string::String,
|
||||
endpoint_name: std::option::Option<std::string::String>,
|
||||
endpoint_url: std::option::Option<std::string::String>,
|
||||
current_subscription_id: std::option::Option<u64>,
|
||||
current_subscribe_method: std::option::Option<std::string::String>,
|
||||
current_unsubscribe_method: std::option::Option<std::string::String>,
|
||||
current_notification_method: std::option::Option<std::string::String>,
|
||||
event_count_total: u64,
|
||||
notification_count_total: u64,
|
||||
ui_log_count: u64,
|
||||
suppressed_log_count: u64,
|
||||
last_event_kind: std::option::Option<std::string::String>,
|
||||
}
|
||||
|
||||
/// Subscribe request sent by the demo frontend.
|
||||
#[derive(Clone, Debug, serde::Deserialize, ts_rs::TS)]
|
||||
#[ts(export, export_to = "../frontend/ts/bindings/DemoWsSubscribeRequest.ts")]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct DemoWsSubscribeRequest {
|
||||
method: std::string::String,
|
||||
mode: std::string::String,
|
||||
target: std::option::Option<std::string::String>,
|
||||
filter_json: std::option::Option<std::string::String>,
|
||||
config_json: std::option::Option<std::string::String>,
|
||||
}
|
||||
|
||||
/// Runtime state for the demo websocket window.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct DemoWsRuntimeState {
|
||||
client: std::option::Option<kb_lib::WsClient>,
|
||||
relay_task: std::option::Option<tauri::async_runtime::JoinHandle<()>>,
|
||||
keepalive_task: std::option::Option<tauri::async_runtime::JoinHandle<()>>,
|
||||
endpoint_name: std::option::Option<std::string::String>,
|
||||
endpoint_url: std::option::Option<std::string::String>,
|
||||
connection_state: kb_lib::ConnectionState,
|
||||
current_subscription: std::option::Option<kb_lib::WsSubscriptionInfo>,
|
||||
event_count_total: u64,
|
||||
notification_count_total: u64,
|
||||
ui_log_count: u64,
|
||||
suppressed_log_count: u64,
|
||||
last_event_kind: std::option::Option<std::string::String>,
|
||||
last_status_emit_at: std::option::Option<std::time::Instant>,
|
||||
}
|
||||
|
||||
impl DemoWsRuntimeState {
|
||||
/// Creates a new empty runtime state.
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
client: None,
|
||||
relay_task: None,
|
||||
keepalive_task: None,
|
||||
endpoint_name: None,
|
||||
endpoint_url: None,
|
||||
connection_state: kb_lib::ConnectionState::Disconnected,
|
||||
current_subscription: None,
|
||||
event_count_total: 0,
|
||||
notification_count_total: 0,
|
||||
ui_log_count: 0,
|
||||
suppressed_log_count: 0,
|
||||
last_event_kind: None,
|
||||
last_status_emit_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn to_status_payload(&self) -> DemoWsStatusPayload {
|
||||
let current_subscription_id = self
|
||||
.current_subscription
|
||||
.as_ref()
|
||||
.map(|subscription| subscription.subscription_id);
|
||||
let current_subscribe_method = self
|
||||
.current_subscription
|
||||
.as_ref()
|
||||
.map(|subscription| subscription.subscribe_method.clone());
|
||||
let current_unsubscribe_method = self
|
||||
.current_subscription
|
||||
.as_ref()
|
||||
.map(|subscription| subscription.unsubscribe_method.clone());
|
||||
let current_notification_method = self
|
||||
.current_subscription
|
||||
.as_ref()
|
||||
.map(|subscription| subscription.notification_method.clone());
|
||||
DemoWsStatusPayload {
|
||||
connection_state: connection_state_to_string(self.connection_state),
|
||||
endpoint_name: self.endpoint_name.clone(),
|
||||
endpoint_url: self.endpoint_url.clone(),
|
||||
current_subscription_id,
|
||||
current_subscribe_method,
|
||||
current_unsubscribe_method,
|
||||
current_notification_method,
|
||||
event_count_total: self.event_count_total,
|
||||
notification_count_total: self.notification_count_total,
|
||||
ui_log_count: self.ui_log_count,
|
||||
suppressed_log_count: self.suppressed_log_count,
|
||||
last_event_kind: self.last_event_kind.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn clear(&mut self) {
|
||||
self.client = None;
|
||||
self.relay_task = None;
|
||||
self.keepalive_task = None;
|
||||
self.endpoint_name = None;
|
||||
self.endpoint_url = None;
|
||||
self.connection_state = kb_lib::ConnectionState::Disconnected;
|
||||
self.current_subscription = None;
|
||||
self.event_count_total = 0;
|
||||
self.notification_count_total = 0;
|
||||
self.ui_log_count = 0;
|
||||
self.suppressed_log_count = 0;
|
||||
self.last_event_kind = None;
|
||||
self.last_status_emit_at = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows and focuses the preconfigured `demo_ws` window.
|
||||
#[tauri::command]
|
||||
pub(crate) fn open_demo_ws_window(app_handle: tauri::AppHandle) -> Result<(), std::string::String> {
|
||||
let existing_window_option = app_handle.get_webview_window("demo_ws");
|
||||
let demo_window = match existing_window_option {
|
||||
Some(demo_window) => demo_window,
|
||||
None => {
|
||||
let builder = tauri::WebviewWindowBuilder::new(
|
||||
&app_handle,
|
||||
"demo_ws",
|
||||
tauri::WebviewUrl::App("demo_ws.html".into()),
|
||||
)
|
||||
.title("Demo Ws Subscribe")
|
||||
.inner_size(1400.0, 768.0)
|
||||
.min_inner_size(800.0, 600.0)
|
||||
.center()
|
||||
.visible(true)
|
||||
.transparent(false)
|
||||
.decorations(true);
|
||||
let build_result = builder.build();
|
||||
match build_result {
|
||||
Ok(window) => window,
|
||||
Err(error) => {
|
||||
return Err(format!("cannot create demo_ws window: {error:?}"));
|
||||
},
|
||||
}
|
||||
},
|
||||
};
|
||||
let show_result = demo_window.show();
|
||||
if let Err(error) = show_result {
|
||||
return Err(format!("cannot show demo_ws window: {error:?}"));
|
||||
}
|
||||
let focus_result = demo_window.set_focus();
|
||||
if let Err(error) = focus_result {
|
||||
return Err(format!("cannot focus demo_ws window: {error:?}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns the list of configured websocket endpoints.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_list_endpoints(
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
) -> Result<std::vec::Vec<DemoWsEndpointSummary>, std::string::String> {
|
||||
let mut endpoints = std::vec::Vec::new();
|
||||
for endpoint in &state.config.solana.ws_endpoints {
|
||||
if !endpoint.enabled {
|
||||
continue;
|
||||
}
|
||||
let resolved_url_result = endpoint.resolved_url();
|
||||
let resolved_url = match resolved_url_result {
|
||||
Ok(resolved_url) => resolved_url,
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
endpoint_name = %endpoint.name,
|
||||
"cannot resolve ws endpoint url from environment: {}",
|
||||
error
|
||||
);
|
||||
format!("UNRESOLVED_ENV [{}] {}", endpoint.name, endpoint.url)
|
||||
},
|
||||
};
|
||||
endpoints.push(DemoWsEndpointSummary {
|
||||
name: endpoint.name.clone(),
|
||||
resolved_url,
|
||||
provider: endpoint.provider.clone(),
|
||||
enabled: endpoint.enabled,
|
||||
roles: endpoint.roles.clone(),
|
||||
});
|
||||
}
|
||||
Ok(endpoints)
|
||||
}
|
||||
|
||||
/// Returns the current demo websocket runtime status.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_get_status(
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
) -> Result<DemoWsStatusPayload, std::string::String> {
|
||||
let runtime_guard = state.demo_ws_runtime.lock().await;
|
||||
Ok(runtime_guard.to_status_payload())
|
||||
}
|
||||
|
||||
/// Connects the demo websocket runtime to the selected endpoint.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_connect(
|
||||
app_handle: tauri::AppHandle,
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
endpoint_name: std::string::String,
|
||||
) -> Result<DemoWsStatusPayload, std::string::String> {
|
||||
let endpoint_option = state.config.find_ws_endpoint(&endpoint_name);
|
||||
let endpoint = match endpoint_option {
|
||||
Some(endpoint) => endpoint.clone(),
|
||||
None => {
|
||||
return Err(format!("unknown websocket endpoint '{}'", endpoint_name));
|
||||
},
|
||||
};
|
||||
let runtime_arc = state.demo_ws_runtime.clone();
|
||||
{
|
||||
let runtime_guard = runtime_arc.lock().await;
|
||||
if runtime_guard.client.is_some() {
|
||||
return Err("demo websocket client is already connected or connecting".to_string());
|
||||
}
|
||||
}
|
||||
let client_result = kb_lib::WsClient::new(endpoint.clone());
|
||||
let client = match client_result {
|
||||
Ok(client) => client,
|
||||
Err(error) => {
|
||||
return Err(format!("cannot create websocket client: {error}"));
|
||||
},
|
||||
};
|
||||
{
|
||||
let mut runtime_guard = runtime_arc.lock().await;
|
||||
runtime_guard.endpoint_name = Some(endpoint.name.clone());
|
||||
runtime_guard.endpoint_url = Some(client.endpoint_url().to_string());
|
||||
runtime_guard.connection_state = kb_lib::ConnectionState::Connecting;
|
||||
runtime_guard.current_subscription = None;
|
||||
}
|
||||
emit_demo_ws_status(&app_handle, &runtime_arc).await;
|
||||
emit_demo_ws_log(
|
||||
&app_handle,
|
||||
&format!("[demo] connecting endpoint '{}' ({})", endpoint.name, client.endpoint_url()),
|
||||
);
|
||||
let mut event_receiver = client.subscribe_events();
|
||||
let relay_runtime = runtime_arc.clone();
|
||||
let relay_app_handle = app_handle.clone();
|
||||
let relay_task = tauri::async_runtime::spawn(async move {
|
||||
loop {
|
||||
let recv_result = event_receiver.recv().await;
|
||||
match recv_result {
|
||||
Ok(event) => {
|
||||
let (emit_ui_log, emit_ui_status) =
|
||||
register_demo_ws_event_and_decide_emission(&relay_runtime, &event).await;
|
||||
if emit_ui_log {
|
||||
emit_demo_ws_log(&relay_app_handle, &format_demo_ws_event(&event));
|
||||
}
|
||||
if emit_ui_status {
|
||||
emit_demo_ws_status(&relay_app_handle, &relay_runtime).await;
|
||||
}
|
||||
},
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
|
||||
emit_demo_ws_log(
|
||||
&relay_app_handle,
|
||||
&format!("[demo] event receiver lagged and skipped {} event(s)", skipped),
|
||||
);
|
||||
},
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => {
|
||||
break;
|
||||
},
|
||||
}
|
||||
}
|
||||
});
|
||||
let keepalive_client = client.clone();
|
||||
let keepalive_app_handle = app_handle.clone();
|
||||
let keepalive_task = tauri::async_runtime::spawn(async move {
|
||||
demo_ws_keepalive_loop(&keepalive_app_handle, &keepalive_client).await;
|
||||
});
|
||||
let connect_result = client.connect().await;
|
||||
if let Err(error) = connect_result {
|
||||
relay_task.abort();
|
||||
keepalive_task.abort();
|
||||
{
|
||||
let mut runtime_guard = runtime_arc.lock().await;
|
||||
runtime_guard.clear();
|
||||
}
|
||||
emit_demo_ws_status(&app_handle, &runtime_arc).await;
|
||||
return Err(format!("cannot connect websocket client: {error}"));
|
||||
}
|
||||
{
|
||||
let mut runtime_guard = runtime_arc.lock().await;
|
||||
runtime_guard.client = Some(client);
|
||||
runtime_guard.relay_task = Some(relay_task);
|
||||
runtime_guard.keepalive_task = Some(keepalive_task);
|
||||
runtime_guard.endpoint_name = Some(endpoint.name.clone());
|
||||
runtime_guard.endpoint_url = Some(endpoint.resolved_url().unwrap_or(endpoint.url));
|
||||
runtime_guard.connection_state = kb_lib::ConnectionState::Connected;
|
||||
}
|
||||
emit_demo_ws_status(&app_handle, &runtime_arc).await;
|
||||
let runtime_guard = runtime_arc.lock().await;
|
||||
Ok(runtime_guard.to_status_payload())
|
||||
}
|
||||
|
||||
/// Disconnects the demo websocket runtime.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_disconnect(
|
||||
app_handle: tauri::AppHandle,
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
) -> Result<DemoWsStatusPayload, std::string::String> {
|
||||
let runtime_arc = state.demo_ws_runtime.clone();
|
||||
{
|
||||
let mut runtime_guard = runtime_arc.lock().await;
|
||||
runtime_guard.connection_state = kb_lib::ConnectionState::Disconnecting;
|
||||
}
|
||||
emit_demo_ws_status(&app_handle, &runtime_arc).await;
|
||||
let (client_option, relay_task_option, keepalive_task_option) = {
|
||||
let mut runtime_guard = runtime_arc.lock().await;
|
||||
(
|
||||
runtime_guard.client.take(),
|
||||
runtime_guard.relay_task.take(),
|
||||
runtime_guard.keepalive_task.take(),
|
||||
)
|
||||
};
|
||||
if let Some(keepalive_task) = keepalive_task_option {
|
||||
keepalive_task.abort();
|
||||
}
|
||||
if let Some(client) = &client_option {
|
||||
let disconnect_result = client.disconnect().await;
|
||||
if let Err(error) = disconnect_result {
|
||||
emit_demo_ws_log(&app_handle, &format!("[demo] disconnect error: {}", error));
|
||||
}
|
||||
}
|
||||
if let Some(relay_task) = relay_task_option {
|
||||
relay_task.abort();
|
||||
}
|
||||
{
|
||||
let mut runtime_guard = runtime_arc.lock().await;
|
||||
runtime_guard.clear();
|
||||
}
|
||||
emit_demo_ws_status(&app_handle, &runtime_arc).await;
|
||||
let runtime_guard = runtime_arc.lock().await;
|
||||
Ok(runtime_guard.to_status_payload())
|
||||
}
|
||||
|
||||
/// Sends one demo subscription request.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_subscribe(
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
request: DemoWsSubscribeRequest,
|
||||
) -> Result<u64, std::string::String> {
|
||||
let client_option = {
|
||||
let runtime_guard = state.demo_ws_runtime.lock().await;
|
||||
if runtime_guard.current_subscription.is_some() {
|
||||
return Err("a subscription is already active, unsubscribe it first".to_string());
|
||||
}
|
||||
runtime_guard.client.clone()
|
||||
};
|
||||
let client = match client_option {
|
||||
Some(client) => client,
|
||||
None => {
|
||||
return Err("demo websocket client is not connected".to_string());
|
||||
},
|
||||
};
|
||||
execute_demo_ws_subscribe(&client, &request).await
|
||||
}
|
||||
|
||||
/// Sends one unsubscribe request for the current active subscription.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_unsubscribe_current(
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
) -> Result<u64, std::string::String> {
|
||||
let (client_option, subscription_option) = {
|
||||
let runtime_guard = state.demo_ws_runtime.lock().await;
|
||||
(runtime_guard.client.clone(), runtime_guard.current_subscription.clone())
|
||||
};
|
||||
let client = match client_option {
|
||||
Some(client) => client,
|
||||
None => {
|
||||
return Err("demo websocket client is not connected".to_string());
|
||||
},
|
||||
};
|
||||
let subscription = match subscription_option {
|
||||
Some(subscription) => subscription,
|
||||
None => {
|
||||
return Err("no active subscription is currently registered".to_string());
|
||||
},
|
||||
};
|
||||
let params = vec![serde_json::Value::from(subscription.subscription_id)];
|
||||
let send_result = client
|
||||
.send_json_rpc_request(subscription.unsubscribe_method.clone(), params)
|
||||
.await;
|
||||
match send_result {
|
||||
Ok(request_id) => Ok(request_id),
|
||||
Err(error) => Err(format!("cannot send unsubscribe request: {error}")),
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute_demo_ws_subscribe(
|
||||
client: &kb_lib::WsClient,
|
||||
request: &DemoWsSubscribeRequest,
|
||||
) -> Result<u64, std::string::String> {
|
||||
let method = request.method.trim();
|
||||
let mode = request.mode.trim();
|
||||
if method == "account" {
|
||||
let target_result = required_target(request, "account pubkey");
|
||||
let target = match target_result {
|
||||
Ok(target) => target,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
if mode == "typed" {
|
||||
let config_result = parse_optional_json_typed::<
|
||||
solana_rpc_client_api::config::RpcAccountInfoConfig,
|
||||
>(&request.config_json, "account typed config");
|
||||
let config = match config_result {
|
||||
Ok(config) => config,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let result = client.account_subscribe_typed(target, config).await;
|
||||
return result.map_err(|error| format!("account typed subscribe failed: {error}"));
|
||||
}
|
||||
let config_result =
|
||||
parse_optional_json_value(&request.config_json, "account raw config");
|
||||
let config = match config_result {
|
||||
Ok(config) => config,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let result = client.account_subscribe_raw(target, config).await;
|
||||
return result.map_err(|error| format!("account raw subscribe failed: {error}"));
|
||||
}
|
||||
if method == "block" {
|
||||
if mode == "typed" {
|
||||
let filter_result = parse_required_json_typed::<
|
||||
solana_rpc_client_api::config::RpcBlockSubscribeFilter,
|
||||
>(&request.filter_json, "block typed filter");
|
||||
let filter = match filter_result {
|
||||
Ok(filter) => filter,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let config_result = parse_optional_json_typed::<
|
||||
solana_rpc_client_api::config::RpcBlockSubscribeConfig,
|
||||
>(&request.config_json, "block typed config");
|
||||
let config = match config_result {
|
||||
Ok(config) => config,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let result = client.block_subscribe_typed(filter, config).await;
|
||||
return result.map_err(|error| format!("block typed subscribe failed: {error}"));
|
||||
}
|
||||
let filter_result = parse_required_json_value(&request.filter_json, "block raw filter");
|
||||
let filter = match filter_result {
|
||||
Ok(filter) => filter,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let config_result = parse_optional_json_value(&request.config_json, "block raw config");
|
||||
let config = match config_result {
|
||||
Ok(config) => config,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let result = client.block_subscribe_raw(filter, config).await;
|
||||
return result.map_err(|error| format!("block raw subscribe failed: {error}"));
|
||||
}
|
||||
if method == "logs" {
|
||||
if mode == "typed" {
|
||||
let filter_result = parse_required_json_typed::<
|
||||
solana_rpc_client_api::config::RpcTransactionLogsFilter,
|
||||
>(&request.filter_json, "logs typed filter");
|
||||
let filter = match filter_result {
|
||||
Ok(filter) => filter,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let config_result = parse_optional_json_typed::<
|
||||
solana_rpc_client_api::config::RpcTransactionLogsConfig,
|
||||
>(&request.config_json, "logs typed config");
|
||||
let config = match config_result {
|
||||
Ok(config) => config,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let result = client.logs_subscribe_typed(filter, config).await;
|
||||
return result.map_err(|error| format!("logs typed subscribe failed: {error}"));
|
||||
}
|
||||
let filter_result = parse_required_json_value(&request.filter_json, "logs raw filter");
|
||||
let filter = match filter_result {
|
||||
Ok(filter) => filter,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let config_result = parse_optional_json_value(&request.config_json, "logs raw config");
|
||||
let config = match config_result {
|
||||
Ok(config) => config,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let result = client.logs_subscribe_raw(filter, config).await;
|
||||
return result.map_err(|error| format!("logs raw subscribe failed: {error}"));
|
||||
}
|
||||
if method == "program" {
|
||||
let target_result = required_target(request, "program id");
|
||||
let target = match target_result {
|
||||
Ok(target) => target,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
if mode == "typed" {
|
||||
let config_result = parse_optional_json_typed::<
|
||||
solana_rpc_client_api::config::RpcProgramAccountsConfig,
|
||||
>(&request.config_json, "program typed config");
|
||||
let config = match config_result {
|
||||
Ok(config) => config,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let result = client.program_subscribe_typed(target, config).await;
|
||||
return result.map_err(|error| format!("program typed subscribe failed: {error}"));
|
||||
}
|
||||
let config_result =
|
||||
parse_optional_json_value(&request.config_json, "program raw config");
|
||||
let config = match config_result {
|
||||
Ok(config) => config,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let result = client.program_subscribe_raw(target, config).await;
|
||||
return result.map_err(|error| format!("program raw subscribe failed: {error}"));
|
||||
}
|
||||
if method == "root" {
|
||||
let result = client.root_subscribe().await;
|
||||
return result.map_err(|error| format!("root subscribe failed: {error}"));
|
||||
}
|
||||
if method == "signature" {
|
||||
let target_result = required_target(request, "signature");
|
||||
let target = match target_result {
|
||||
Ok(target) => target,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
if mode == "typed" {
|
||||
let config_result = parse_optional_json_typed::<
|
||||
solana_rpc_client_api::config::RpcSignatureSubscribeConfig,
|
||||
>(&request.config_json, "signature typed config");
|
||||
let config = match config_result {
|
||||
Ok(config) => config,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let result = client.signature_subscribe_typed(target, config).await;
|
||||
return result.map_err(|error| format!("signature typed subscribe failed: {error}"));
|
||||
}
|
||||
let config_result =
|
||||
parse_optional_json_value(&request.config_json, "signature raw config");
|
||||
let config = match config_result {
|
||||
Ok(config) => config,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let result = client.signature_subscribe_raw(target, config).await;
|
||||
return result.map_err(|error| format!("signature raw subscribe failed: {error}"));
|
||||
}
|
||||
if method == "slot" {
|
||||
let result = client.slot_subscribe().await;
|
||||
return result.map_err(|error| format!("slot subscribe failed: {error}"));
|
||||
}
|
||||
if method == "slotsUpdates" {
|
||||
let result = client.slots_updates_subscribe().await;
|
||||
return result.map_err(|error| format!("slotsUpdates subscribe failed: {error}"));
|
||||
}
|
||||
if method == "vote" {
|
||||
let result = client.vote_subscribe().await;
|
||||
return result.map_err(|error| format!("vote subscribe failed: {error}"));
|
||||
}
|
||||
Err(format!("unsupported demo subscribe method '{}'", method))
|
||||
}
|
||||
|
||||
fn required_target(
|
||||
request: &DemoWsSubscribeRequest,
|
||||
label: &str,
|
||||
) -> Result<std::string::String, std::string::String> {
|
||||
let target_option = request.target.as_ref();
|
||||
let target = match target_option {
|
||||
Some(target) => target.trim(),
|
||||
None => {
|
||||
return Err(format!("{} is required", label));
|
||||
},
|
||||
};
|
||||
if target.is_empty() {
|
||||
return Err(format!("{} is required", label));
|
||||
}
|
||||
Ok(target.to_string())
|
||||
}
|
||||
|
||||
fn parse_optional_json_value(
|
||||
input: &std::option::Option<std::string::String>,
|
||||
label: &str,
|
||||
) -> Result<std::option::Option<serde_json::Value>, std::string::String> {
|
||||
match input {
|
||||
Some(input) => {
|
||||
if input.trim().is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let parse_result = serde_json::from_str::<serde_json::Value>(input);
|
||||
match parse_result {
|
||||
Ok(value) => Ok(Some(value)),
|
||||
Err(error) => Err(format!("cannot parse {}: {}", label, error)),
|
||||
}
|
||||
},
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_required_json_value(
|
||||
input: &std::option::Option<std::string::String>,
|
||||
label: &str,
|
||||
) -> Result<serde_json::Value, std::string::String> {
|
||||
let input_option = input.as_ref();
|
||||
let input = match input_option {
|
||||
Some(input) => input.trim(),
|
||||
None => {
|
||||
return Err(format!("{} is required", label));
|
||||
},
|
||||
};
|
||||
if input.is_empty() {
|
||||
return Err(format!("{} is required", label));
|
||||
}
|
||||
let parse_result = serde_json::from_str::<serde_json::Value>(input);
|
||||
match parse_result {
|
||||
Ok(value) => Ok(value),
|
||||
Err(error) => Err(format!("cannot parse {}: {}", label, error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_optional_json_typed<T>(
|
||||
input: &std::option::Option<std::string::String>,
|
||||
label: &str,
|
||||
) -> Result<std::option::Option<T>, std::string::String>
|
||||
where
|
||||
T: serde::de::DeserializeOwned,
|
||||
{
|
||||
match input {
|
||||
Some(input) => {
|
||||
if input.trim().is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let parse_result = serde_json::from_str::<T>(input);
|
||||
match parse_result {
|
||||
Ok(value) => Ok(Some(value)),
|
||||
Err(error) => Err(format!("cannot parse {}: {}", label, error)),
|
||||
}
|
||||
},
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_required_json_typed<T>(
|
||||
input: &std::option::Option<std::string::String>,
|
||||
label: &str,
|
||||
) -> Result<T, std::string::String>
|
||||
where
|
||||
T: serde::de::DeserializeOwned,
|
||||
{
|
||||
let input_option = input.as_ref();
|
||||
let input = match input_option {
|
||||
Some(input) => input.trim(),
|
||||
None => {
|
||||
return Err(format!("{} is required", label));
|
||||
},
|
||||
};
|
||||
if input.is_empty() {
|
||||
return Err(format!("{} is required", label));
|
||||
}
|
||||
let parse_result = serde_json::from_str::<T>(input);
|
||||
match parse_result {
|
||||
Ok(value) => Ok(value),
|
||||
Err(error) => Err(format!("cannot parse {}: {}", label, error)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn register_demo_ws_event_and_decide_emission(
|
||||
runtime_arc: &std::sync::Arc<tokio::sync::Mutex<DemoWsRuntimeState>>,
|
||||
event: &kb_lib::WsEvent,
|
||||
) -> (bool, bool) {
|
||||
let mut runtime_guard = runtime_arc.lock().await;
|
||||
runtime_guard.event_count_total = runtime_guard.event_count_total.saturating_add(1);
|
||||
runtime_guard.last_event_kind = Some(demo_ws_event_kind_name(event).to_string());
|
||||
let mut emit_ui_log = true;
|
||||
let force_status_emit = matches!(
|
||||
event,
|
||||
kb_lib::WsEvent::Connected { .. }
|
||||
| kb_lib::WsEvent::Disconnected { .. }
|
||||
| kb_lib::WsEvent::SubscriptionRegistered { .. }
|
||||
| kb_lib::WsEvent::SubscriptionUnregistered { .. }
|
||||
| kb_lib::WsEvent::Error { .. }
|
||||
);
|
||||
match event {
|
||||
kb_lib::WsEvent::Connected { endpoint_name, endpoint_url } => {
|
||||
runtime_guard.connection_state = kb_lib::ConnectionState::Connected;
|
||||
runtime_guard.endpoint_name = Some(endpoint_name.clone());
|
||||
runtime_guard.endpoint_url = Some(endpoint_url.clone());
|
||||
},
|
||||
kb_lib::WsEvent::SubscriptionRegistered { subscription, .. } => {
|
||||
runtime_guard.current_subscription = Some(subscription.clone());
|
||||
runtime_guard.notification_count_total = 0;
|
||||
},
|
||||
kb_lib::WsEvent::SubscriptionNotification { subscription, .. } => {
|
||||
runtime_guard.notification_count_total =
|
||||
runtime_guard.notification_count_total.saturating_add(1);
|
||||
let subscribe_method = subscription.subscribe_method.as_str();
|
||||
let notif_count = runtime_guard.notification_count_total;
|
||||
if subscribe_method == "logsSubscribe" || subscribe_method == "programSubscribe" {
|
||||
emit_ui_log = notif_count % 100 == 1;
|
||||
} else if subscribe_method == "slotsUpdatesSubscribe" {
|
||||
emit_ui_log = notif_count % 20 == 1;
|
||||
}
|
||||
},
|
||||
kb_lib::WsEvent::TextMessage { .. } | kb_lib::WsEvent::JsonRpcMessage { .. } => {
|
||||
let subscribe_method_option = runtime_guard
|
||||
.current_subscription
|
||||
.as_ref()
|
||||
.map(|subscription| subscription.subscribe_method.as_str());
|
||||
if let Some(subscribe_method) = subscribe_method_option {
|
||||
if subscribe_method == "logsSubscribe"
|
||||
|| subscribe_method == "programSubscribe"
|
||||
|| subscribe_method == "slotsUpdatesSubscribe"
|
||||
{
|
||||
emit_ui_log = false;
|
||||
}
|
||||
}
|
||||
},
|
||||
kb_lib::WsEvent::Pong { .. } => {
|
||||
emit_ui_log = false;
|
||||
},
|
||||
kb_lib::WsEvent::SubscriptionUnregistered { subscription_id, .. } => {
|
||||
let current_subscription_id = runtime_guard
|
||||
.current_subscription
|
||||
.as_ref()
|
||||
.map(|subscription| subscription.subscription_id);
|
||||
if current_subscription_id == Some(*subscription_id) {
|
||||
runtime_guard.current_subscription = None;
|
||||
runtime_guard.notification_count_total = 0;
|
||||
}
|
||||
},
|
||||
kb_lib::WsEvent::Disconnected { .. } => {
|
||||
runtime_guard.client = None;
|
||||
runtime_guard.relay_task = None;
|
||||
runtime_guard.keepalive_task = None;
|
||||
runtime_guard.connection_state = kb_lib::ConnectionState::Disconnected;
|
||||
runtime_guard.current_subscription = None;
|
||||
runtime_guard.notification_count_total = 0;
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
if emit_ui_log {
|
||||
runtime_guard.ui_log_count = runtime_guard.ui_log_count.saturating_add(1);
|
||||
} else {
|
||||
runtime_guard.suppressed_log_count = runtime_guard.suppressed_log_count.saturating_add(1);
|
||||
}
|
||||
let now = std::time::Instant::now();
|
||||
let emit_ui_status = if force_status_emit {
|
||||
true
|
||||
} else {
|
||||
match runtime_guard.last_status_emit_at {
|
||||
Some(last_status_emit_at) => {
|
||||
now.duration_since(last_status_emit_at) >= std::time::Duration::from_millis(250)
|
||||
},
|
||||
None => true,
|
||||
}
|
||||
};
|
||||
if emit_ui_status {
|
||||
runtime_guard.last_status_emit_at = Some(now);
|
||||
}
|
||||
(emit_ui_log, emit_ui_status)
|
||||
}
|
||||
|
||||
async fn emit_demo_ws_status(
|
||||
app_handle: &tauri::AppHandle,
|
||||
runtime_arc: &std::sync::Arc<tokio::sync::Mutex<DemoWsRuntimeState>>,
|
||||
) {
|
||||
let status_payload = {
|
||||
let runtime_guard = runtime_arc.lock().await;
|
||||
runtime_guard.to_status_payload()
|
||||
};
|
||||
let demo_window_option = app_handle.get_webview_window("demo_ws");
|
||||
let demo_window = match demo_window_option {
|
||||
Some(demo_window) => demo_window,
|
||||
None => {
|
||||
return;
|
||||
},
|
||||
};
|
||||
let emit_result = demo_window.emit("demo-ws-status", status_payload);
|
||||
if let Err(error) = emit_result {
|
||||
tracing::error!("error emitting demo-ws-status: {error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_demo_ws_log(emit_demo_ws_log: &tauri::AppHandle, line: &str) {
|
||||
tracing::trace!("{}", line);
|
||||
let demo_window_option = emit_demo_ws_log.get_webview_window("demo_ws");
|
||||
let demo_window = match demo_window_option {
|
||||
Some(demo_window) => demo_window,
|
||||
None => {
|
||||
return;
|
||||
},
|
||||
};
|
||||
let emit_result = demo_window.emit("demo-ws-log", line.to_string());
|
||||
if let Err(error) = emit_result {
|
||||
tracing::error!("error emitting demo-ws-log: {error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn connection_state_to_string(state: kb_lib::ConnectionState) -> std::string::String {
|
||||
match state {
|
||||
kb_lib::ConnectionState::Disconnected => "Disconnected".to_string(),
|
||||
kb_lib::ConnectionState::Connecting => "Connecting".to_string(),
|
||||
kb_lib::ConnectionState::Connected => "Connected".to_string(),
|
||||
kb_lib::ConnectionState::Disconnecting => "Disconnecting".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn format_demo_ws_event(event: &kb_lib::WsEvent) -> std::string::String {
|
||||
match event {
|
||||
kb_lib::WsEvent::Connected { endpoint_name, endpoint_url } => {
|
||||
format!("[demo:{endpoint_name}] connected to {endpoint_url}")
|
||||
},
|
||||
kb_lib::WsEvent::TextMessage { endpoint_name, text } => {
|
||||
format!("[demo:{endpoint_name}] text: {}", shorten_log_text(text, 1200))
|
||||
},
|
||||
kb_lib::WsEvent::JsonRpcMessage { endpoint_name, message } => {
|
||||
let rendered = format!("{message:?}");
|
||||
format!("[demo:{endpoint_name}] json-rpc: {}", shorten_log_text(&rendered, 1800))
|
||||
},
|
||||
kb_lib::WsEvent::JsonRpcParseError { endpoint_name, text, error } => {
|
||||
format!(
|
||||
"[demo:{endpoint_name}] json-rpc parse error: {} | raw={}",
|
||||
error,
|
||||
shorten_log_text(text, 1200)
|
||||
)
|
||||
},
|
||||
kb_lib::WsEvent::SubscriptionRegistered { endpoint_name, subscription } => {
|
||||
format!(
|
||||
"[demo:{endpoint_name}] subscription registered request_id={} subscription_id={} subscribe={} unsubscribe={} notification={}",
|
||||
subscription.request_id,
|
||||
subscription.subscription_id,
|
||||
subscription.subscribe_method,
|
||||
subscription.unsubscribe_method,
|
||||
subscription.notification_method
|
||||
)
|
||||
},
|
||||
kb_lib::WsEvent::SubscriptionNotification {
|
||||
endpoint_name,
|
||||
subscription,
|
||||
notification,
|
||||
method_matches_registry,
|
||||
} => {
|
||||
let result_text = notification.params.result.to_string();
|
||||
let typed_suffix = match kb_lib::parse_solana_ws_typed_notification(notification) {
|
||||
Ok(typed_notification) => {
|
||||
let rendered = format!("{typed_notification:?}");
|
||||
format!(" | typed={}", shorten_log_text(&rendered, 1200))
|
||||
},
|
||||
Err(_) => std::string::String::new(),
|
||||
};
|
||||
format!(
|
||||
"[demo:{endpoint_name}] tracked notification subscription_id={} method={} expected={} matches={} result={}{}",
|
||||
subscription.subscription_id,
|
||||
notification.method,
|
||||
subscription.notification_method,
|
||||
method_matches_registry,
|
||||
shorten_log_text(&result_text, 1600),
|
||||
typed_suffix
|
||||
)
|
||||
},
|
||||
kb_lib::WsEvent::JsonRpcNotificationWithoutSubscription { endpoint_name, notification } => {
|
||||
let result_text = notification.params.result.to_string();
|
||||
let typed_suffix = match kb_lib::parse_solana_ws_typed_notification(notification) {
|
||||
Ok(typed_notification) => {
|
||||
let rendered = format!("{typed_notification:?}");
|
||||
format!(" | typed={}", shorten_log_text(&rendered, 1200))
|
||||
},
|
||||
Err(_) => std::string::String::new(),
|
||||
};
|
||||
format!(
|
||||
"[demo:{endpoint_name}] untracked notification method={} subscription={} result={}{}",
|
||||
notification.method,
|
||||
notification.params.subscription,
|
||||
shorten_log_text(&result_text, 1600),
|
||||
typed_suffix
|
||||
)
|
||||
},
|
||||
kb_lib::WsEvent::SubscriptionUnregistered {
|
||||
endpoint_name,
|
||||
subscription_id,
|
||||
unsubscribe_method,
|
||||
was_active,
|
||||
} => {
|
||||
format!(
|
||||
"[demo:{endpoint_name}] subscription unregistered subscription_id={} unsubscribe_method={} was_active={}",
|
||||
subscription_id, unsubscribe_method, was_active
|
||||
)
|
||||
},
|
||||
kb_lib::WsEvent::BinaryMessage { endpoint_name, data } => {
|
||||
format!("[demo:{endpoint_name}] binary message ({} bytes)", data.len())
|
||||
},
|
||||
kb_lib::WsEvent::Ping { endpoint_name, data } => {
|
||||
format!("[demo:{endpoint_name}] ping ({} bytes)", data.len())
|
||||
},
|
||||
kb_lib::WsEvent::Pong { endpoint_name, data } => {
|
||||
format!("[demo:{endpoint_name}] pong ({} bytes)", data.len())
|
||||
},
|
||||
kb_lib::WsEvent::CloseReceived { endpoint_name, code, reason } => {
|
||||
format!("[demo:{endpoint_name}] close received code={:?} reason={:?}", code, reason)
|
||||
},
|
||||
kb_lib::WsEvent::Disconnected { endpoint_name } => {
|
||||
format!("[demo:{endpoint_name}] disconnected")
|
||||
},
|
||||
kb_lib::WsEvent::Error { endpoint_name, error } => {
|
||||
format!("[demo:{endpoint_name}] error: {error}")
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn shorten_log_text(input: &str, shorten_log_text: usize) -> std::string::String {
|
||||
let char_count = input.chars().count();
|
||||
if char_count <= shorten_log_text {
|
||||
return input.to_string();
|
||||
}
|
||||
|
||||
let shortened: std::string::String = input.chars().take(shorten_log_text).collect();
|
||||
format!("{shortened} …[truncated {} chars]", char_count - shorten_log_text)
|
||||
}
|
||||
|
||||
async fn demo_ws_keepalive_loop(app_handle: &tauri::AppHandle, client: &kb_lib::WsClient) {
|
||||
loop {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(30)).await;
|
||||
let state = client.connection_state().await;
|
||||
if state != kb_lib::ConnectionState::Connected {
|
||||
break;
|
||||
}
|
||||
let send_result = client.send_ping(b"demo-keepalive".to_vec()).await;
|
||||
if let Err(error) = send_result {
|
||||
emit_demo_ws_log(
|
||||
app_handle,
|
||||
&format!("[demo:{}] keepalive ping failed: {}", client.endpoint_name(), error),
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn demo_ws_event_kind_name(event: &kb_lib::WsEvent) -> &'static str {
|
||||
match event {
|
||||
kb_lib::WsEvent::Connected { .. } => "connected",
|
||||
kb_lib::WsEvent::TextMessage { .. } => "text_message",
|
||||
kb_lib::WsEvent::JsonRpcMessage { .. } => "json_rpc_message",
|
||||
kb_lib::WsEvent::JsonRpcParseError { .. } => "json_rpc_parse_error",
|
||||
kb_lib::WsEvent::SubscriptionRegistered { .. } => "subscription_registered",
|
||||
kb_lib::WsEvent::SubscriptionNotification { .. } => "subscription_notification",
|
||||
kb_lib::WsEvent::JsonRpcNotificationWithoutSubscription { .. } => "untracked_notification",
|
||||
kb_lib::WsEvent::SubscriptionUnregistered { .. } => "subscription_unregistered",
|
||||
kb_lib::WsEvent::BinaryMessage { .. } => "binary_message",
|
||||
kb_lib::WsEvent::Ping { .. } => "ping",
|
||||
kb_lib::WsEvent::Pong { .. } => "pong",
|
||||
kb_lib::WsEvent::CloseReceived { .. } => "close_received",
|
||||
kb_lib::WsEvent::Disconnected { .. } => "disconnected",
|
||||
kb_lib::WsEvent::Error { .. } => "error",
|
||||
}
|
||||
}
|
||||
485
kb_demo_app/src/demo_ws_manager.rs
Normal file
485
kb_demo_app/src/demo_ws_manager.rs
Normal file
@@ -0,0 +1,485 @@
|
||||
// file: kb_demo_app/src/demo_ws_manager.rs
|
||||
|
||||
//! Demo WebSocket manager window commands and runtime state.
|
||||
//!
|
||||
//! This module provides a lightweight test bench for `kb_lib::WsManager`.
|
||||
|
||||
use tauri::Emitter;
|
||||
use tauri::Manager;
|
||||
|
||||
/// Static endpoint summary enriched with current manager state.
|
||||
#[derive(Clone, Debug, serde::Serialize, ts_rs::TS)]
|
||||
#[ts(export, export_to = "../frontend/ts/bindings/DemoWsManagerEndpointSummary.ts")]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct DemoWsManagerEndpointSummary {
|
||||
name: std::string::String,
|
||||
resolved_url: std::string::String,
|
||||
provider: std::string::String,
|
||||
roles: std::vec::Vec<std::string::String>,
|
||||
connection_state: std::string::String,
|
||||
active_subscription_count: usize,
|
||||
}
|
||||
|
||||
/// Global demo manager snapshot payload.
|
||||
#[derive(Clone, Debug, serde::Serialize, ts_rs::TS)]
|
||||
#[ts(export, export_to = "../frontend/ts/bindings/DemoWsManagerSnapshotPayload.ts")]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub(crate) struct DemoWsManagerSnapshotPayload {
|
||||
endpoint_count: usize,
|
||||
started_count: usize,
|
||||
endpoints: std::vec::Vec<DemoWsManagerEndpointSummary>,
|
||||
}
|
||||
|
||||
/// Runtime state for the demo WebSocket manager window.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct DemoWsManagerRuntimeState {
|
||||
relay_task: std::option::Option<tauri::async_runtime::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl DemoWsManagerRuntimeState {
|
||||
/// Creates a new empty runtime state.
|
||||
pub(crate) fn new() -> DemoWsManagerRuntimeState {
|
||||
DemoWsManagerRuntimeState { relay_task: None }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct DemoWsManagerActionResult {
|
||||
action: std::string::String,
|
||||
target: std::string::String,
|
||||
matched_count: usize,
|
||||
changed_count: usize,
|
||||
unchanged_count: usize,
|
||||
}
|
||||
|
||||
/// Shows and focuses the preconfigured `demo_ws_manager` window.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn open_demo_ws_manager_window(
|
||||
app_handle: tauri::AppHandle,
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
) -> Result<(), std::string::String> {
|
||||
ensure_demo_ws_manager_relay(&app_handle, &state).await;
|
||||
let existing_window_option = app_handle.get_webview_window("demo_ws_manager");
|
||||
let demo_window = match existing_window_option {
|
||||
Some(demo_window) => demo_window,
|
||||
None => {
|
||||
let builder = tauri::WebviewWindowBuilder::new(
|
||||
&app_handle,
|
||||
"demo_ws_manager",
|
||||
tauri::WebviewUrl::App("demo_ws_manager.html".into()),
|
||||
)
|
||||
.title("Demo Ws Manager")
|
||||
.inner_size(1280.0, 800.0)
|
||||
.min_inner_size(900.0, 620.0)
|
||||
.center()
|
||||
.visible(true)
|
||||
.transparent(false)
|
||||
.decorations(true);
|
||||
let build_result = builder.build();
|
||||
match build_result {
|
||||
Ok(window) => window,
|
||||
Err(error) => {
|
||||
return Err(format!("cannot create demo_ws_manager window: {error:?}"));
|
||||
},
|
||||
}
|
||||
},
|
||||
};
|
||||
let show_result = demo_window.show();
|
||||
if let Err(error) = show_result {
|
||||
return Err(format!("cannot show demo_ws_manager window: {error:?}"));
|
||||
}
|
||||
let focus_result = demo_window.set_focus();
|
||||
if let Err(error) = focus_result {
|
||||
return Err(format!("cannot focus demo_ws_manager window: {error:?}"));
|
||||
}
|
||||
emit_demo_ws_manager_log(&app_handle, "[ui] demo_ws_manager window loaded");
|
||||
emit_demo_ws_manager_snapshot(&app_handle, &state).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns the current manager snapshot.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_manager_get_snapshot(
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
) -> Result<DemoWsManagerSnapshotPayload, std::string::String> {
|
||||
build_demo_ws_manager_snapshot(&state).await
|
||||
}
|
||||
|
||||
/// Returns the distinct configured roles for enabled websocket endpoints.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_manager_list_roles(
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
) -> Result<std::vec::Vec<std::string::String>, std::string::String> {
|
||||
let mut roles = std::collections::BTreeSet::new();
|
||||
for endpoint in &state.config.solana.ws_endpoints {
|
||||
if !endpoint.enabled {
|
||||
continue;
|
||||
}
|
||||
for role in &endpoint.roles {
|
||||
roles.insert(role.clone());
|
||||
}
|
||||
}
|
||||
Ok(roles.into_iter().collect())
|
||||
}
|
||||
|
||||
/// Starts all managed websocket endpoints.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_manager_start_all(
|
||||
app_handle: tauri::AppHandle,
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
) -> Result<DemoWsManagerSnapshotPayload, std::string::String> {
|
||||
ensure_demo_ws_manager_relay(&app_handle, &state).await;
|
||||
let matched_count = state.ws_manager.endpoint_names().await.len();
|
||||
let start_result = state.ws_manager.start_all().await;
|
||||
let changed_count = match start_result {
|
||||
Ok(changed_count) => changed_count,
|
||||
Err(error) => return Err(error.to_string()),
|
||||
};
|
||||
let action_result = build_action_result("start", "all", matched_count, changed_count);
|
||||
emit_demo_ws_manager_log(&app_handle, format_action_result_for_log(&action_result).as_str());
|
||||
emit_demo_ws_manager_snapshot(&app_handle, &state).await;
|
||||
build_demo_ws_manager_snapshot(&state).await
|
||||
}
|
||||
|
||||
/// Stops all managed websocket endpoints.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_manager_stop_all(
|
||||
app_handle: tauri::AppHandle,
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
) -> Result<DemoWsManagerSnapshotPayload, std::string::String> {
|
||||
let matched_count = state.ws_manager.endpoint_names().await.len();
|
||||
let stop_result = state.ws_manager.stop_all().await;
|
||||
let changed_count = match stop_result {
|
||||
Ok(changed_count) => changed_count,
|
||||
Err(error) => return Err(error.to_string()),
|
||||
};
|
||||
let action_result = build_action_result("stop", "all", matched_count, changed_count);
|
||||
emit_demo_ws_manager_log(&app_handle, format_action_result_for_log(&action_result).as_str());
|
||||
emit_demo_ws_manager_snapshot(&app_handle, &state).await;
|
||||
build_demo_ws_manager_snapshot(&state).await
|
||||
}
|
||||
|
||||
/// Starts all managed websocket endpoints having the selected role.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_manager_start_role(
|
||||
app_handle: tauri::AppHandle,
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
role: std::string::String,
|
||||
) -> Result<DemoWsManagerSnapshotPayload, std::string::String> {
|
||||
ensure_demo_ws_manager_relay(&app_handle, &state).await;
|
||||
let matched_count = state.ws_manager.endpoint_names_for_role(role.as_str()).await.len();
|
||||
let start_result = state.ws_manager.start_role(role.as_str()).await;
|
||||
let changed_count = match start_result {
|
||||
Ok(changed_count) => changed_count,
|
||||
Err(error) => return Err(error.to_string()),
|
||||
};
|
||||
let action_result =
|
||||
build_action_result("start", role.as_str(), matched_count, changed_count);
|
||||
emit_demo_ws_manager_log(&app_handle, format_action_result_for_log(&action_result).as_str());
|
||||
emit_demo_ws_manager_snapshot(&app_handle, &state).await;
|
||||
build_demo_ws_manager_snapshot(&state).await
|
||||
}
|
||||
|
||||
/// Stops all managed websocket endpoints having the selected role.
|
||||
#[tauri::command]
|
||||
pub(crate) async fn demo_ws_manager_stop_role(
|
||||
app_handle: tauri::AppHandle,
|
||||
state: tauri::State<'_, crate::AppState>,
|
||||
role: std::string::String,
|
||||
) -> Result<DemoWsManagerSnapshotPayload, std::string::String> {
|
||||
let matched_count = state.ws_manager.endpoint_names_for_role(role.as_str()).await.len();
|
||||
let stop_result = state.ws_manager.stop_role(role.as_str()).await;
|
||||
let changed_count = match stop_result {
|
||||
Ok(changed_count) => changed_count,
|
||||
Err(error) => return Err(error.to_string()),
|
||||
};
|
||||
let action_result = build_action_result("stop", role.as_str(), matched_count, changed_count);
|
||||
emit_demo_ws_manager_log(&app_handle, format_action_result_for_log(&action_result).as_str());
|
||||
emit_demo_ws_manager_snapshot(&app_handle, &state).await;
|
||||
build_demo_ws_manager_snapshot(&state).await
|
||||
}
|
||||
|
||||
async fn build_demo_ws_manager_snapshot(
|
||||
state: &tauri::State<'_, crate::AppState>,
|
||||
) -> Result<DemoWsManagerSnapshotPayload, std::string::String> {
|
||||
let snapshot_result = state.ws_manager.snapshot().await;
|
||||
let snapshot = match snapshot_result {
|
||||
Ok(snapshot) => snapshot,
|
||||
Err(error) => return Err(error.to_string()),
|
||||
};
|
||||
let mut endpoints = std::vec::Vec::new();
|
||||
for managed_endpoint in snapshot.endpoints {
|
||||
let config_endpoint_option = state.config.find_ws_endpoint(&managed_endpoint.endpoint_name);
|
||||
let config_endpoint = match config_endpoint_option {
|
||||
Some(config_endpoint) => config_endpoint,
|
||||
None => {
|
||||
return Err(format!(
|
||||
"managed websocket endpoint '{}' is missing from config",
|
||||
managed_endpoint.endpoint_name
|
||||
));
|
||||
},
|
||||
};
|
||||
endpoints.push(DemoWsManagerEndpointSummary {
|
||||
name: managed_endpoint.endpoint_name,
|
||||
resolved_url: managed_endpoint.resolved_url,
|
||||
provider: managed_endpoint.provider,
|
||||
roles: config_endpoint.roles.clone(),
|
||||
connection_state: connection_state_to_string(managed_endpoint.state),
|
||||
active_subscription_count: managed_endpoint.active_subscription_count,
|
||||
});
|
||||
}
|
||||
Ok(DemoWsManagerSnapshotPayload {
|
||||
endpoint_count: snapshot.endpoint_count,
|
||||
started_count: snapshot.started_count,
|
||||
endpoints,
|
||||
})
|
||||
}
|
||||
|
||||
async fn emit_demo_ws_manager_snapshot(
|
||||
app_handle: &tauri::AppHandle,
|
||||
state: &tauri::State<'_, crate::AppState>,
|
||||
) {
|
||||
let snapshot_result = build_demo_ws_manager_snapshot(state).await;
|
||||
let snapshot = match snapshot_result {
|
||||
Ok(snapshot) => snapshot,
|
||||
Err(error) => {
|
||||
emit_demo_ws_manager_log(app_handle, &format!("[ui] snapshot error: {error}"));
|
||||
return;
|
||||
},
|
||||
};
|
||||
let emit_result = app_handle.emit("kb-demo-ws-manager-snapshot", snapshot);
|
||||
if let Err(error) = emit_result {
|
||||
tracing::error!("error emitting demo_ws_manager snapshot event: {error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
async fn ensure_demo_ws_manager_relay(
|
||||
app_handle: &tauri::AppHandle,
|
||||
state: &tauri::State<'_, crate::AppState>,
|
||||
) {
|
||||
let mut runtime_guard = state.demo_ws_manager_runtime.lock().await;
|
||||
if runtime_guard.relay_task.is_some() {
|
||||
return;
|
||||
}
|
||||
let mut receiver = state.ws_manager.subscribe_events();
|
||||
let relay_app_handle = app_handle.clone();
|
||||
let relay_state = state.demo_ws_manager_runtime.clone();
|
||||
let relay_task = tauri::async_runtime::spawn(async move {
|
||||
loop {
|
||||
let recv_result = receiver.recv().await;
|
||||
match recv_result {
|
||||
Ok(event) => {
|
||||
let line = format_ws_event(&event);
|
||||
emit_demo_ws_manager_log(&relay_app_handle, line.as_str());
|
||||
},
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
|
||||
emit_demo_ws_manager_log(
|
||||
&relay_app_handle,
|
||||
&format!(
|
||||
"[manager] event receiver lagged and skipped {} message(s)",
|
||||
skipped
|
||||
),
|
||||
);
|
||||
},
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => {
|
||||
break;
|
||||
},
|
||||
}
|
||||
}
|
||||
let mut runtime_guard = relay_state.lock().await;
|
||||
runtime_guard.relay_task = None;
|
||||
});
|
||||
|
||||
runtime_guard.relay_task = Some(relay_task);
|
||||
}
|
||||
|
||||
fn emit_demo_ws_manager_log(app_handle: &tauri::AppHandle, message: &str) {
|
||||
let emit_result = app_handle.emit("kb-demo-ws-manager-log", message.to_string());
|
||||
if let Err(error) = emit_result {
|
||||
tracing::error!("error emitting demo_ws_manager log event: {error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn connection_state_to_string(state: kb_lib::ConnectionState) -> std::string::String {
|
||||
match state {
|
||||
kb_lib::ConnectionState::Disconnected => "Disconnected".to_string(),
|
||||
kb_lib::ConnectionState::Connecting => "Connecting".to_string(),
|
||||
kb_lib::ConnectionState::Connected => "Connected".to_string(),
|
||||
kb_lib::ConnectionState::Disconnecting => "Disconnecting".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn format_ws_event(event: &kb_lib::WsEvent) -> std::string::String {
|
||||
match event {
|
||||
kb_lib::WsEvent::Connected { endpoint_name, endpoint_url } => {
|
||||
format!("[ws:{endpoint_name}] connected to {endpoint_url}")
|
||||
},
|
||||
kb_lib::WsEvent::TextMessage { endpoint_name, text } => {
|
||||
format!("[ws:{endpoint_name}] text: {text}")
|
||||
},
|
||||
kb_lib::WsEvent::JsonRpcMessage { endpoint_name, message } => match message {
|
||||
kb_lib::JsonRpcWsIncomingMessage::SuccessResponse(response) => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] json-rpc success id={} result={}",
|
||||
response.id, response.result
|
||||
)
|
||||
},
|
||||
kb_lib::JsonRpcWsIncomingMessage::ErrorResponse(response) => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] json-rpc error id={} code={} message={}",
|
||||
response.id, response.error.code, response.error.message
|
||||
)
|
||||
},
|
||||
kb_lib::JsonRpcWsIncomingMessage::Notification(notification) => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] json-rpc notification method={} subscription={} result={}",
|
||||
notification.method,
|
||||
notification.params.subscription,
|
||||
notification.params.result
|
||||
)
|
||||
},
|
||||
},
|
||||
kb_lib::WsEvent::JsonRpcParseError { endpoint_name, text, error } => {
|
||||
format!("[ws:{endpoint_name}] json-rpc parse error: {} | raw={}", error, text)
|
||||
},
|
||||
kb_lib::WsEvent::SubscriptionRegistered { endpoint_name, subscription } => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] subscription registered subscribe_method={} unsubscribe_method={} notification_method={} request_id={} subscription_id={}",
|
||||
subscription.subscribe_method,
|
||||
subscription.unsubscribe_method,
|
||||
subscription.notification_method,
|
||||
subscription.request_id,
|
||||
subscription.subscription_id
|
||||
)
|
||||
},
|
||||
kb_lib::WsEvent::SubscriptionNotification {
|
||||
endpoint_name,
|
||||
subscription,
|
||||
notification,
|
||||
method_matches_registry,
|
||||
} => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] tracked notification subscription_id={} method={} expected={} matches={} result={}",
|
||||
subscription.subscription_id,
|
||||
notification.method,
|
||||
subscription.notification_method,
|
||||
method_matches_registry,
|
||||
notification.params.result
|
||||
)
|
||||
},
|
||||
kb_lib::WsEvent::JsonRpcNotificationWithoutSubscription { endpoint_name, notification } => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] untracked notification method={} subscription={} result={}",
|
||||
notification.method, notification.params.subscription, notification.params.result
|
||||
)
|
||||
},
|
||||
kb_lib::WsEvent::SubscriptionUnregistered {
|
||||
endpoint_name,
|
||||
subscription_id,
|
||||
unsubscribe_method,
|
||||
was_active,
|
||||
} => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] subscription unregistered subscription_id={} unsubscribe_method={} was_active={}",
|
||||
subscription_id, unsubscribe_method, was_active
|
||||
)
|
||||
},
|
||||
kb_lib::WsEvent::BinaryMessage { endpoint_name, data } => {
|
||||
format!("[{endpoint_name}] binary ({} bytes)", data.len())
|
||||
},
|
||||
kb_lib::WsEvent::Ping { endpoint_name, data } => {
|
||||
format!("[{endpoint_name}] ping ({} bytes)", data.len())
|
||||
},
|
||||
kb_lib::WsEvent::Pong { endpoint_name, data } => {
|
||||
format!("[{endpoint_name}] pong ({} bytes)", data.len())
|
||||
},
|
||||
kb_lib::WsEvent::CloseReceived { endpoint_name, code, reason } => {
|
||||
format!("[ws:{endpoint_name}] close received code={:?} reason={:?}", code, reason)
|
||||
},
|
||||
kb_lib::WsEvent::Disconnected { endpoint_name } => {
|
||||
format!("[ws:{endpoint_name}] disconnected")
|
||||
},
|
||||
kb_lib::WsEvent::Error { endpoint_name, error } => {
|
||||
format!("[ws:{endpoint_name}] error: {error}")
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn build_action_result(
|
||||
build_action_result: &str,
|
||||
target: &str,
|
||||
matched_count: usize,
|
||||
changed_count: usize,
|
||||
) -> DemoWsManagerActionResult {
|
||||
let unchanged_count = matched_count.saturating_sub(changed_count);
|
||||
DemoWsManagerActionResult {
|
||||
action: build_action_result.to_string(),
|
||||
target: target.to_string(),
|
||||
matched_count,
|
||||
changed_count,
|
||||
unchanged_count,
|
||||
}
|
||||
}
|
||||
|
||||
fn action_past_tense(action: &str) -> &'static str {
|
||||
match action {
|
||||
"start" => "started",
|
||||
"stop" => "stopped",
|
||||
_ => "processed",
|
||||
}
|
||||
}
|
||||
|
||||
fn format_action_result_for_log(result: &DemoWsManagerActionResult) -> std::string::String {
|
||||
let is_all = result.target == "all";
|
||||
let past = action_past_tense(result.action.as_str());
|
||||
if result.matched_count == 0 {
|
||||
if is_all {
|
||||
return "[ui] no managed websocket endpoint is configured".to_string();
|
||||
}
|
||||
return format!("[ui] no managed websocket endpoint matches role '{}'", result.target);
|
||||
}
|
||||
if result.changed_count == 0 {
|
||||
if is_all {
|
||||
return format!(
|
||||
"[ui] all managed websocket endpoints were already {}",
|
||||
if result.action == "start" { "started" } else { "stopped" }
|
||||
);
|
||||
}
|
||||
return format!(
|
||||
"[ui] role '{}' was already {} on {} endpoint(s)",
|
||||
result.target,
|
||||
if result.action == "start" { "started" } else { "stopped" },
|
||||
result.unchanged_count
|
||||
);
|
||||
}
|
||||
if result.unchanged_count == 0 {
|
||||
if is_all {
|
||||
return format!(
|
||||
"[ui] {}ed {} managed websocket endpoint(s)",
|
||||
past, result.changed_count
|
||||
);
|
||||
}
|
||||
return format!(
|
||||
"[ui] {}ed role '{}' on {} endpoint(s)",
|
||||
past, result.target, result.changed_count
|
||||
);
|
||||
}
|
||||
if is_all {
|
||||
return format!(
|
||||
"[ui] {}ed {} managed websocket endpoint(s); {} already {}",
|
||||
past,
|
||||
result.changed_count,
|
||||
result.unchanged_count,
|
||||
if result.action == "start" { "started" } else { "stopped" }
|
||||
);
|
||||
}
|
||||
format!(
|
||||
"[ui] {}ed role '{}' on {} endpoint(s); {} already {}",
|
||||
result.action,
|
||||
result.target,
|
||||
result.changed_count,
|
||||
result.unchanged_count,
|
||||
if result.action == "start" { "started" } else { "stopped" }
|
||||
)
|
||||
}
|
||||
505
kb_demo_app/src/lib.rs
Normal file
505
kb_demo_app/src/lib.rs
Normal file
@@ -0,0 +1,505 @@
|
||||
// file: kb_demo_app/src/lib.rs
|
||||
|
||||
//! Tauri application library for `khadhroony-bobobot`.
|
||||
//!
|
||||
//! This crate is intentionally thin. It loads the shared configuration,
|
||||
//! initializes shared tracing from `kb_lib`, and wires the desktop shell
|
||||
//! to the reusable backend logic.
|
||||
|
||||
#![deny(unreachable_pub)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
mod demo_http;
|
||||
mod demo_pipeline;
|
||||
mod demo_pipeline2;
|
||||
mod demo_ws;
|
||||
mod demo_ws_manager;
|
||||
mod splash;
|
||||
|
||||
pub use splash::SplashOrder;
|
||||
use tauri::Emitter;
|
||||
use tauri::Manager;
|
||||
|
||||
/// Runtime state for started WebSocket clients.
|
||||
struct WsRuntimeState {
|
||||
clients: std::vec::Vec<kb_lib::WsClient>,
|
||||
relay_tasks: std::vec::Vec<tauri::async_runtime::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl WsRuntimeState {
|
||||
fn new() -> WsRuntimeState {
|
||||
WsRuntimeState {
|
||||
clients: std::vec::Vec::new(),
|
||||
relay_tasks: std::vec::Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared application state stored inside Tauri.
|
||||
struct AppState {
|
||||
config: kb_lib::Config,
|
||||
database: std::sync::Arc<kb_lib::Database>,
|
||||
ws_runtime: tokio::sync::Mutex<WsRuntimeState>,
|
||||
demo_ws_runtime: std::sync::Arc<tokio::sync::Mutex<crate::demo_ws::DemoWsRuntimeState>>,
|
||||
demo_ws_manager_runtime:
|
||||
std::sync::Arc<tokio::sync::Mutex<crate::demo_ws_manager::DemoWsManagerRuntimeState>>,
|
||||
ws_manager: std::sync::Arc<kb_lib::WsManager>,
|
||||
http_pool: kb_lib::HttpEndpointPool,
|
||||
}
|
||||
|
||||
/// Runs the desktop application.
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub async fn run() -> Result<(), kb_lib::KhError> {
|
||||
let config_path = kb_lib::Config::default_path();
|
||||
let config_result = kb_lib::Config::load_from_path(&config_path);
|
||||
let config = match config_result {
|
||||
Ok(config) => config,
|
||||
Err(error) => {
|
||||
eprintln!(
|
||||
"kb_demo_app configuration load error from '{}': {}",
|
||||
config_path.display(),
|
||||
error
|
||||
);
|
||||
return Err(error);
|
||||
},
|
||||
};
|
||||
let prepare_result = config.prepare_filesystem();
|
||||
if let Err(error) = prepare_result {
|
||||
eprintln!("kb_demo_app filesystem preparation error: {error}");
|
||||
return Err(error);
|
||||
}
|
||||
let tracing_guard_result = kb_lib::init_tracing(&config.logging);
|
||||
let _tracing_guard = match tracing_guard_result {
|
||||
Ok(guard) => guard,
|
||||
Err(error) => {
|
||||
eprintln!("kb_demo_app tracing initialization error: {error}");
|
||||
return Err(error);
|
||||
},
|
||||
};
|
||||
tracing::info!(
|
||||
app_name = %config.app.name,
|
||||
environment = %config.app.environment,
|
||||
"starting desktop application"
|
||||
);
|
||||
let database_result = kb_lib::Database::connect_and_initialize(&config.database).await;
|
||||
let database = match database_result {
|
||||
Ok(database) => database,
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
let http_pool_result = kb_lib::HttpEndpointPool::from_config(&config);
|
||||
let http_pool = match http_pool_result {
|
||||
Ok(http_pool) => http_pool,
|
||||
Err(error) => {
|
||||
tracing::error!("cannot create http endpoint pool: {}", error);
|
||||
panic!("cannot create http endpoint pool: {}", error);
|
||||
},
|
||||
};
|
||||
let ws_manager_result = kb_lib::WsManager::from_config(&config);
|
||||
let ws_manager = match ws_manager_result {
|
||||
Ok(ws_manager) => ws_manager,
|
||||
Err(error) => {
|
||||
tracing::error!("cannot create websocket manager: {}", error);
|
||||
panic!("cannot create websocket manager: {}", error);
|
||||
},
|
||||
};
|
||||
let app_state = AppState {
|
||||
config: config.clone(),
|
||||
database: std::sync::Arc::new(database),
|
||||
ws_runtime: tokio::sync::Mutex::new(WsRuntimeState::new()),
|
||||
demo_ws_runtime: std::sync::Arc::new(tokio::sync::Mutex::new(
|
||||
crate::demo_ws::DemoWsRuntimeState::new(),
|
||||
)),
|
||||
demo_ws_manager_runtime: std::sync::Arc::new(tokio::sync::Mutex::new(
|
||||
crate::demo_ws_manager::DemoWsManagerRuntimeState::new(),
|
||||
)),
|
||||
ws_manager: std::sync::Arc::new(ws_manager),
|
||||
http_pool,
|
||||
};
|
||||
let tracing_builder = tauri_plugin_tracing::Builder::new();
|
||||
let mut tauri_builder = tauri::Builder::default();
|
||||
tauri_builder = tauri_builder.manage(app_state);
|
||||
tauri_builder = tauri_builder.invoke_handler(tauri::generate_handler![
|
||||
start_ws_clients,
|
||||
stop_ws_clients,
|
||||
crate::demo_ws::open_demo_ws_window,
|
||||
crate::demo_ws::demo_ws_list_endpoints,
|
||||
crate::demo_ws::demo_ws_get_status,
|
||||
crate::demo_ws::demo_ws_connect,
|
||||
crate::demo_ws::demo_ws_disconnect,
|
||||
crate::demo_ws::demo_ws_subscribe,
|
||||
crate::demo_ws::demo_ws_unsubscribe_current,
|
||||
crate::demo_http::open_demo_http_window,
|
||||
crate::demo_http::demo_http_list_pool_clients,
|
||||
crate::demo_http::demo_http_execute_request,
|
||||
crate::demo_ws_manager::open_demo_ws_manager_window,
|
||||
crate::demo_ws_manager::demo_ws_manager_get_snapshot,
|
||||
crate::demo_ws_manager::demo_ws_manager_list_roles,
|
||||
crate::demo_ws_manager::demo_ws_manager_start_all,
|
||||
crate::demo_ws_manager::demo_ws_manager_stop_all,
|
||||
crate::demo_ws_manager::demo_ws_manager_start_role,
|
||||
crate::demo_ws_manager::demo_ws_manager_stop_role,
|
||||
crate::demo_pipeline::open_demo_pipeline_window,
|
||||
crate::demo_pipeline::demo_pipeline_inspect_signature,
|
||||
crate::demo_pipeline::demo_pipeline_inspect_token_mint,
|
||||
crate::demo_pipeline::demo_pipeline_inspect_pair_id,
|
||||
crate::demo_pipeline::demo_pipeline_inspect_pool_address,
|
||||
crate::demo_pipeline::demo_pipeline_backfill_token_mint,
|
||||
crate::demo_pipeline::demo_pipeline_backfill_pool_address,
|
||||
crate::demo_pipeline2::open_demo_pipeline2_window,
|
||||
crate::demo_pipeline2::demo_pipeline2_get_catalog,
|
||||
crate::demo_pipeline2::demo_pipeline2_backfill_token_mint,
|
||||
crate::demo_pipeline2::demo_pipeline2_backfill_pool_address,
|
||||
crate::demo_pipeline2::demo_pipeline2_get_pair_candles,
|
||||
crate::demo_pipeline2::demo_pipeline2_replay_local_pipeline,
|
||||
crate::demo_pipeline2::demo_pipeline2_diagnose_local_pipeline,
|
||||
crate::demo_pipeline2::demo_pipeline2_validate_local_pipeline,
|
||||
]);
|
||||
tauri_builder = tauri_builder.plugin(tracing_builder.build::<tauri::Wry>());
|
||||
tauri_builder = tauri_builder.setup(|app| {
|
||||
let app_handle = app.handle().clone();
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let splash_window_option = app_handle.get_webview_window("splash");
|
||||
let splash_window = match splash_window_option {
|
||||
Some(window) => window,
|
||||
None => {
|
||||
tracing::error!("splash window not found");
|
||||
return;
|
||||
},
|
||||
};
|
||||
let main_window_option = app_handle.get_webview_window("main");
|
||||
let main_window = match main_window_option {
|
||||
Some(window) => window,
|
||||
None => {
|
||||
tracing::error!("main window not found");
|
||||
return;
|
||||
},
|
||||
};
|
||||
let is_debug = cfg!(debug_assertions);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
if is_debug {
|
||||
emit_splash_order(&splash_window, "add_log", Some("Start Fade-In"), None);
|
||||
}
|
||||
emit_splash_order(&splash_window, "fadein", None, None);
|
||||
emit_splash_order(&splash_window, "add_msg", Some("Initialisation..."), Some("info"));
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
emit_splash_order(
|
||||
&splash_window,
|
||||
"add_msg",
|
||||
Some("Loading resources..."),
|
||||
Some("info"),
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
|
||||
emit_splash_order(
|
||||
&splash_window,
|
||||
"add_msg",
|
||||
Some("Loading complete..."),
|
||||
Some("success"),
|
||||
);
|
||||
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
|
||||
tracing::trace!("start splash fadeout");
|
||||
if is_debug {
|
||||
emit_splash_order(&splash_window, "add_log", Some("Start Fade-out"), None);
|
||||
}
|
||||
emit_splash_order(&splash_window, "fadeout", None, None);
|
||||
tracing::trace!("end splash fadeout");
|
||||
tokio::time::sleep(std::time::Duration::from_millis(3100)).await;
|
||||
let close_result = splash_window.destroy();
|
||||
if let Err(error) = close_result {
|
||||
tracing::error!("error closing splash window: {error:?}");
|
||||
}
|
||||
let show_result = main_window.show();
|
||||
if let Err(error) = show_result {
|
||||
tracing::error!("error showing main window: {error:?}");
|
||||
} else {
|
||||
let emit_result = main_window.emit("setupTray", ());
|
||||
if let Err(error) = emit_result {
|
||||
tracing::error!("error emitting setupTray event: {error:?}");
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
});
|
||||
let run_result = tauri_builder.run(tauri::generate_context!());
|
||||
if let Err(error) = run_result {
|
||||
tracing::error!("error while running tauri application: {error:?}");
|
||||
return Err(kb_lib::KhError::InvalidState(format!(
|
||||
"error while running tauri application: {error:?}"
|
||||
)));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn emit_splash_order(
|
||||
splash_window: &tauri::WebviewWindow,
|
||||
order: &str,
|
||||
msg: std::option::Option<&str>,
|
||||
status: std::option::Option<&str>,
|
||||
) {
|
||||
let payload = crate::SplashOrder {
|
||||
order: order.to_string(),
|
||||
msg: msg.map(std::string::ToString::to_string),
|
||||
status: status.map(std::string::ToString::to_string),
|
||||
};
|
||||
let emit_result = splash_window.emit("splash", payload);
|
||||
if let Err(error) = emit_result {
|
||||
tracing::error!("error emitting splash event '{order}': {error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn start_ws_clients(
|
||||
app_handle: tauri::AppHandle,
|
||||
state: tauri::State<'_, AppState>,
|
||||
) -> Result<usize, std::string::String> {
|
||||
{
|
||||
let runtime_guard = state.ws_runtime.lock().await;
|
||||
if !runtime_guard.clients.is_empty() {
|
||||
return Err("websocket clients are already running".to_string());
|
||||
}
|
||||
}
|
||||
let enabled_endpoints: std::vec::Vec<kb_lib::WsEndpointConfig> = state
|
||||
.config
|
||||
.solana
|
||||
.ws_endpoints
|
||||
.iter()
|
||||
.filter(|endpoint| endpoint.enabled)
|
||||
.cloned()
|
||||
.collect();
|
||||
if enabled_endpoints.is_empty() {
|
||||
return Err("no enabled websocket endpoint found in config.json".to_string());
|
||||
}
|
||||
emit_app_log(
|
||||
&app_handle,
|
||||
&format!("[app] starting {} websocket client(s)", enabled_endpoints.len()),
|
||||
);
|
||||
let mut started_clients: std::vec::Vec<kb_lib::WsClient> = std::vec::Vec::new();
|
||||
let mut relay_tasks: std::vec::Vec<tauri::async_runtime::JoinHandle<()>> = std::vec::Vec::new();
|
||||
for endpoint in enabled_endpoints {
|
||||
emit_app_log(
|
||||
&app_handle,
|
||||
&format!("[app] preparing websocket endpoint '{}' ({})", endpoint.name, endpoint.url),
|
||||
);
|
||||
let client_result = kb_lib::WsClient::new(endpoint.clone());
|
||||
let client = match client_result {
|
||||
Ok(client) => client,
|
||||
Err(error) => {
|
||||
shutdown_started_clients(&started_clients, &mut relay_tasks).await;
|
||||
return Err(format!(
|
||||
"cannot create websocket client for endpoint '{}': {}",
|
||||
endpoint.name, error
|
||||
));
|
||||
},
|
||||
};
|
||||
let mut event_receiver = client.subscribe_events();
|
||||
let relay_app_handle = app_handle.clone();
|
||||
let relay_task = tauri::async_runtime::spawn(async move {
|
||||
loop {
|
||||
let recv_result = event_receiver.recv().await;
|
||||
match recv_result {
|
||||
Ok(event) => {
|
||||
let line = format_ws_event(&event);
|
||||
emit_app_log(&relay_app_handle, &line);
|
||||
},
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(skipped)) => {
|
||||
emit_app_log(
|
||||
&relay_app_handle,
|
||||
&format!(
|
||||
"[ws] event receiver lagged and skipped {} message(s)",
|
||||
skipped
|
||||
),
|
||||
);
|
||||
},
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => {
|
||||
break;
|
||||
},
|
||||
}
|
||||
}
|
||||
});
|
||||
let connect_result = client.connect().await;
|
||||
if let Err(error) = connect_result {
|
||||
relay_task.abort();
|
||||
shutdown_started_clients(&started_clients, &mut relay_tasks).await;
|
||||
return Err(format!(
|
||||
"cannot connect websocket client for endpoint '{}': {}",
|
||||
endpoint.name, error
|
||||
));
|
||||
}
|
||||
started_clients.push(client);
|
||||
relay_tasks.push(relay_task);
|
||||
}
|
||||
{
|
||||
let mut runtime_guard = state.ws_runtime.lock().await;
|
||||
if !runtime_guard.clients.is_empty() {
|
||||
shutdown_started_clients(&started_clients, &mut relay_tasks).await;
|
||||
return Err("websocket clients were started concurrently".to_string());
|
||||
}
|
||||
runtime_guard.clients = started_clients;
|
||||
runtime_guard.relay_tasks = relay_tasks;
|
||||
}
|
||||
let started_count = {
|
||||
let runtime_guard = state.ws_runtime.lock().await;
|
||||
runtime_guard.clients.len()
|
||||
};
|
||||
emit_app_log(&app_handle, &format!("[app] {} websocket client(s) started", started_count));
|
||||
Ok(started_count)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
async fn stop_ws_clients(
|
||||
app_handle: tauri::AppHandle,
|
||||
state: tauri::State<'_, AppState>,
|
||||
) -> Result<usize, std::string::String> {
|
||||
let (clients, mut relay_tasks) = {
|
||||
let mut runtime_guard = state.ws_runtime.lock().await;
|
||||
(
|
||||
std::mem::take(&mut runtime_guard.clients),
|
||||
std::mem::take(&mut runtime_guard.relay_tasks),
|
||||
)
|
||||
};
|
||||
if clients.is_empty() {
|
||||
emit_app_log(&app_handle, "[app] websocket clients are already stopped");
|
||||
return Ok(0);
|
||||
}
|
||||
emit_app_log(&app_handle, &format!("[app] stopping {} websocket client(s)", clients.len()));
|
||||
let stopped_count = clients.len();
|
||||
for client in &clients {
|
||||
let disconnect_result = client.disconnect().await;
|
||||
if let Err(error) = disconnect_result {
|
||||
emit_app_log(
|
||||
&app_handle,
|
||||
&format!(
|
||||
"[app] disconnect error for endpoint '{}': {}",
|
||||
client.endpoint_name(),
|
||||
error
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
for relay_task in relay_tasks.drain(..) {
|
||||
relay_task.abort();
|
||||
}
|
||||
emit_app_log(&app_handle, &format!("[app] {} websocket client(s) stopped", stopped_count));
|
||||
Ok(stopped_count)
|
||||
}
|
||||
|
||||
fn emit_app_log(app_handle: &tauri::AppHandle, message: &str) {
|
||||
let emit_result = app_handle.emit("kb-log", message.to_string());
|
||||
if let Err(error) = emit_result {
|
||||
tracing::error!("error emitting app log event: {error:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn format_ws_event(event: &kb_lib::WsEvent) -> std::string::String {
|
||||
match event {
|
||||
kb_lib::WsEvent::Connected { endpoint_name, endpoint_url } => {
|
||||
format!("[ws:{endpoint_name}] connected to {endpoint_url}")
|
||||
},
|
||||
kb_lib::WsEvent::TextMessage { endpoint_name, text } => {
|
||||
format!("[ws:{endpoint_name}] text: {text}")
|
||||
},
|
||||
kb_lib::WsEvent::JsonRpcMessage { endpoint_name, message } => match message {
|
||||
kb_lib::JsonRpcWsIncomingMessage::SuccessResponse(response) => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] json-rpc success id={} result={}",
|
||||
response.id, response.result
|
||||
)
|
||||
},
|
||||
kb_lib::JsonRpcWsIncomingMessage::ErrorResponse(response) => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] json-rpc error id={} code={} message={}",
|
||||
response.id, response.error.code, response.error.message
|
||||
)
|
||||
},
|
||||
kb_lib::JsonRpcWsIncomingMessage::Notification(notification) => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] json-rpc notification method={} subscription={} result={}",
|
||||
notification.method,
|
||||
notification.params.subscription,
|
||||
notification.params.result
|
||||
)
|
||||
},
|
||||
},
|
||||
kb_lib::WsEvent::JsonRpcParseError { endpoint_name, text, error } => {
|
||||
format!("[ws:{endpoint_name}] json-rpc parse error: {} | raw={}", error, text)
|
||||
},
|
||||
kb_lib::WsEvent::SubscriptionRegistered { endpoint_name, subscription } => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] subscription registered subscribe_method={} unsubscribe_method={} notification_method={} request_id={} subscription_id={}",
|
||||
subscription.subscribe_method,
|
||||
subscription.unsubscribe_method,
|
||||
subscription.notification_method,
|
||||
subscription.request_id,
|
||||
subscription.subscription_id
|
||||
)
|
||||
},
|
||||
kb_lib::WsEvent::SubscriptionNotification {
|
||||
endpoint_name,
|
||||
subscription,
|
||||
notification,
|
||||
method_matches_registry,
|
||||
} => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] tracked notification method={} expected_method={} matches_registry={} subscription_id={} result={}",
|
||||
notification.method,
|
||||
subscription.notification_method,
|
||||
method_matches_registry,
|
||||
subscription.subscription_id,
|
||||
notification.params.result
|
||||
)
|
||||
},
|
||||
kb_lib::WsEvent::JsonRpcNotificationWithoutSubscription { endpoint_name, notification } => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] untracked notification method={} subscription={} result={}",
|
||||
notification.method, notification.params.subscription, notification.params.result
|
||||
)
|
||||
},
|
||||
kb_lib::WsEvent::SubscriptionUnregistered {
|
||||
endpoint_name,
|
||||
subscription_id,
|
||||
unsubscribe_method,
|
||||
was_active,
|
||||
} => {
|
||||
format!(
|
||||
"[ws:{endpoint_name}] subscription unregistered subscription_id={} unsubscribe_method={} was_active={}",
|
||||
subscription_id, unsubscribe_method, was_active
|
||||
)
|
||||
},
|
||||
kb_lib::WsEvent::BinaryMessage { endpoint_name, data } => {
|
||||
format!("[ws:{endpoint_name}] binary message ({} bytes)", data.len())
|
||||
},
|
||||
kb_lib::WsEvent::Ping { endpoint_name, data } => {
|
||||
format!("[ws:{endpoint_name}] ping ({} bytes)", data.len())
|
||||
},
|
||||
kb_lib::WsEvent::Pong { endpoint_name, data } => {
|
||||
format!("[ws:{endpoint_name}] pong ({} bytes)", data.len())
|
||||
},
|
||||
kb_lib::WsEvent::CloseReceived { endpoint_name, code, reason } => {
|
||||
format!("[ws:{endpoint_name}] close received code={:?} reason={:?}", code, reason)
|
||||
},
|
||||
kb_lib::WsEvent::Disconnected { endpoint_name } => {
|
||||
format!("[ws:{endpoint_name}] disconnected")
|
||||
},
|
||||
kb_lib::WsEvent::Error { endpoint_name, error } => {
|
||||
format!("[ws:{endpoint_name}] error: {error}")
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
async fn shutdown_started_clients(
|
||||
started_clients: &[kb_lib::WsClient],
|
||||
relay_tasks: &mut std::vec::Vec<tauri::async_runtime::JoinHandle<()>>,
|
||||
) {
|
||||
for client in started_clients {
|
||||
let disconnect_result = client.disconnect().await;
|
||||
if let Err(error) = disconnect_result {
|
||||
tracing::error!(
|
||||
endpoint_name = %client.endpoint_name(),
|
||||
"cleanup disconnect error: {}",
|
||||
error
|
||||
);
|
||||
}
|
||||
}
|
||||
for relay_task in relay_tasks.drain(..) {
|
||||
relay_task.abort();
|
||||
}
|
||||
}
|
||||
48
kb_demo_app/src/main.rs
Normal file
48
kb_demo_app/src/main.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
// file: kb_demo_app/src/main.rs
|
||||
|
||||
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
//! Binary entrypoint for the kb application.
|
||||
//!
|
||||
//! This binary remains intentionally thin and delegates its logic to `kb_lib`.
|
||||
|
||||
#![deny(unreachable_pub)]
|
||||
#![warn(missing_docs)]
|
||||
|
||||
use fs2::FileExt;
|
||||
|
||||
/// Entrypoint of the kb app binary.
|
||||
#[tokio::main]
|
||||
async fn main() -> std::process::ExitCode {
|
||||
let mut lock_path = std::env::temp_dir();
|
||||
lock_path.push("com_khadhroony_solana_rust.lock");
|
||||
let lock_file = match std::fs::File::create(lock_path) {
|
||||
Ok(lock) => lock,
|
||||
Err(_err) => {
|
||||
eprintln!("Cannot create lock!");
|
||||
std::process::exit(1);
|
||||
}
|
||||
};
|
||||
// trying to aquire an exclusive lock
|
||||
if lock_file.try_lock_exclusive().is_err() {
|
||||
eprintln!("Another instance of the app is already running!");
|
||||
std::process::exit(1);
|
||||
}
|
||||
if rustls::crypto::CryptoProvider::get_default().is_none() {
|
||||
let provider_result = rustls::crypto::aws_lc_rs::default_provider().install_default();
|
||||
match provider_result {
|
||||
Ok(()) => {}
|
||||
Err(error) => {
|
||||
eprintln!("kb_demo_app rustls provider init error: {:?}", error);
|
||||
return std::process::ExitCode::FAILURE;
|
||||
}
|
||||
}
|
||||
}
|
||||
let run_result = kb_demo_app_lib::run().await;
|
||||
if let Err(error) = run_result {
|
||||
eprintln!("application error: {}", error);
|
||||
std::process::exit(1);
|
||||
}
|
||||
std::process::ExitCode::SUCCESS
|
||||
}
|
||||
18
kb_demo_app/src/splash.rs
Normal file
18
kb_demo_app/src/splash.rs
Normal file
@@ -0,0 +1,18 @@
|
||||
// file: kb_demo_app/src/splash.rs
|
||||
|
||||
//! Shared splash-screen payload types.
|
||||
//!
|
||||
//! These types are serialized by the Rust backend and exported to the
|
||||
//! TypeScript frontend through `ts-rs`.
|
||||
|
||||
/// Command payload sent from Rust to the splash frontend.
|
||||
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, ts_rs::TS)]
|
||||
#[ts(export, export_to = "../frontend/ts/bindings/SplashOrder.ts")]
|
||||
pub struct SplashOrder {
|
||||
/// Splash command name such as `fadein`, `fadeout`, `add_msg`, or `add_log`.
|
||||
pub order: std::string::String,
|
||||
/// Optional message payload attached to the command.
|
||||
pub msg: std::option::Option<std::string::String>,
|
||||
/// Optional status payload attached to the command.
|
||||
pub status: std::option::Option<std::string::String>,
|
||||
}
|
||||
Reference in New Issue
Block a user