1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
//! WebSocket-based RemoteExecutor — sends plans to workers and collects results.
use somatize_core::error::{Result, SomaError};
use somatize_core::filter::RemoteTarget;
use somatize_core::value::Value;
use somatize_runtime::executor::RemoteExecutor;
use crate::protocol::*;
use std::sync::RwLock;
/// A remote executor that dispatches work to workers via WebSocket.
///
/// Workers are registered by address + optional token.
/// When `execute_remote` is called, it finds a matching worker,
/// connects via WS, sends the plan, and waits for the result.
pub struct WsRemoteExecutor {
/// Registered workers: (address, token, tags)
workers: RwLock<Vec<WorkerEntry>>,
}
#[derive(Clone)]
struct WorkerEntry {
address: String,
token: Option<String>,
tags: Vec<String>,
}
impl WsRemoteExecutor {
pub fn new() -> Self {
Self {
workers: RwLock::new(Vec::new()),
}
}
/// Register a worker endpoint.
pub fn add_worker(&self, address: impl Into<String>, token: Option<String>, tags: Vec<String>) {
let mut workers = self.workers.write().unwrap();
workers.push(WorkerEntry {
address: address.into(),
token,
tags,
});
}
/// Find a worker matching the given target.
fn find_worker(&self, target: &RemoteTarget) -> Option<WorkerEntry> {
let workers = self.workers.read().unwrap();
match target {
RemoteTarget::WorkerId(id) => workers.iter().find(|w| w.address.contains(id)).cloned(),
RemoteTarget::Tag(tag) => workers.iter().find(|w| w.tags.contains(tag)).cloned(),
}
}
/// Send a plan to a worker via WebSocket and wait for the result.
fn execute_on_worker(
&self,
worker: &WorkerEntry,
node_id: &str,
input: Option<&Value>,
) -> Result<Value> {
let rt = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.map_err(|e| SomaError::Other(format!("tokio runtime: {e}")))?;
rt.block_on(async {
let url = if let Some(token) = &worker.token {
format!("{}/ws?token={}", worker.address, token)
} else {
format!("{}/ws", worker.address)
};
// No size limits — workers handle arbitrary payloads (datasets, model weights, etc.)
let mut ws_config =
tokio_tungstenite::tungstenite::protocol::WebSocketConfig::default();
ws_config.max_message_size = None;
ws_config.max_frame_size = None;
let (mut ws, _) =
tokio_tungstenite::connect_async_with_config(&url, Some(ws_config), false)
.await
.map_err(|e| {
SomaError::Other(format!("WS connect to {}: {e}", worker.address))
})?;
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::tungstenite::Message;
// Build a simple plan: execute this one node
let plan = SerializedPlan {
plan_id: format!("remote_{node_id}"),
plan: somatize_compiler::ExecutionPlan::Execute {
node_id: node_id.to_string(),
},
input: input.map(|v| InputSource::Inline { value: v.clone() }),
filters: vec![],
mode: ExecutionMode::default(),
metadata: serde_json::json!({}),
};
let msg = CoordinatorToWorker::AssignPlan { plan };
let json = serde_json::to_string(&msg)
.map_err(|e| SomaError::Other(format!("serialize: {e}")))?;
ws.send(Message::Text(json.into()))
.await
.map_err(|e| SomaError::Other(format!("WS send: {e}")))?;
// Wait for result
while let Some(Ok(Message::Text(response))) = ws.next().await {
if let Ok(result) = serde_json::from_str::<WorkerToCoordinator>(&response) {
match result {
WorkerToCoordinator::PlanResult { result, .. } => match result {
PlanResult::Success { output, .. } => {
let _ = ws.close(None).await;
let value = match output {
OutputDelivery::Inline { value } => value,
OutputDelivery::Reference { data_ref } => {
// Download from worker via HTTP
let http_addr = worker
.address
.replace("ws://", "http://")
.replace("wss://", "https://");
let url = format!("{http_addr}/download");
let ref_json =
serde_json::to_string(&data_ref).map_err(|e| {
SomaError::Other(format!("serialize data_ref: {e}"))
})?;
let client = reqwest::blocking::Client::new();
let mut req = client.get(&url).query(&[("ref", &ref_json)]);
if let Some(token) = &worker.token {
req = req.query(&[("token", token)]);
}
let resp = req.send().map_err(|e| {
SomaError::Other(format!("HTTP download: {e}"))
})?;
if !resp.status().is_success() {
return Err(SomaError::Other(format!(
"download failed: {}",
resp.status()
)));
}
let bytes = resp.bytes().map_err(|e| {
SomaError::Other(format!("read response: {e}"))
})?;
rmp_serde::from_slice(&bytes).or_else(|_| {
serde_json::from_slice(&bytes).map_err(|e| {
SomaError::Other(format!(
"deserialize download: {e}"
))
})
})?
}
};
return Ok(value);
}
PlanResult::Failed { error, .. } => {
let _ = ws.close(None).await;
return Err(SomaError::Execution {
node_id: node_id.to_string(),
message: error,
});
}
},
// Skip progress/event messages
_ => continue,
}
}
}
let _ = ws.close(None).await;
Err(SomaError::Other(format!(
"worker {} closed without result",
worker.address
)))
})
}
pub fn has_workers(&self) -> bool {
!self.workers.read().unwrap().is_empty()
}
}
impl Default for WsRemoteExecutor {
fn default() -> Self {
Self::new()
}
}
impl RemoteExecutor for WsRemoteExecutor {
fn execute_remote(
&self,
node_id: &str,
target: &RemoteTarget,
input: Option<&Value>,
) -> Result<Value> {
let worker = self
.find_worker(target)
.ok_or_else(|| SomaError::Other(format!("no worker found for target {target:?}")))?;
tracing::info!(
"Dispatching node '{node_id}' to worker at {}",
worker.address
);
self.execute_on_worker(&worker, node_id, input)
}
}