varpulis-cluster 0.10.0

Distributed execution cluster for Varpulis streaming analytics
Documentation
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! Worker node types and registration protocol.

use std::time::Instant;

use serde::{Deserialize, Serialize};
use varpulis_core::security::SecretString;

/// Unique identifier for a worker node.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct WorkerId(pub String);

impl std::fmt::Display for WorkerId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Status of a worker node in the cluster.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WorkerStatus {
    Registering,
    Ready,
    Unhealthy,
    Draining,
}

impl std::fmt::Display for WorkerStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Registering => write!(f, "registering"),
            Self::Ready => write!(f, "ready"),
            Self::Unhealthy => write!(f, "unhealthy"),
            Self::Draining => write!(f, "draining"),
        }
    }
}

/// Capacity information for a worker node.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkerCapacity {
    pub cpu_cores: usize,
    pub pipelines_running: usize,
    pub max_pipelines: usize,
}

impl Default for WorkerCapacity {
    fn default() -> Self {
        Self {
            cpu_cores: num_cpus(),
            pipelines_running: 0,
            max_pipelines: 100,
        }
    }
}

fn num_cpus() -> usize {
    std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1)
}

/// A worker node in the cluster.
#[derive(Debug)]
pub struct WorkerNode {
    pub id: WorkerId,
    pub address: String,
    /// Worker API key — stored as `SecretString` so it is zeroized on drop.
    pub api_key: SecretString,
    pub status: WorkerStatus,
    pub capacity: WorkerCapacity,
    pub last_heartbeat: Instant,
    pub assigned_pipelines: Vec<String>,
    /// Total events processed by this worker (from heartbeats).
    pub events_processed: u64,
}

impl WorkerNode {
    pub fn new(id: WorkerId, address: String, api_key: String) -> Self {
        Self {
            id,
            address,
            api_key: SecretString::new(api_key),
            status: WorkerStatus::Registering,
            capacity: WorkerCapacity::default(),
            last_heartbeat: Instant::now(),
            assigned_pipelines: Vec::new(),
            events_processed: 0,
        }
    }

    pub fn is_available(&self) -> bool {
        self.status == WorkerStatus::Ready
            && self.capacity.pipelines_running < self.capacity.max_pipelines
    }
}

/// Request body for worker registration.
#[derive(Debug, Serialize, Deserialize)]
pub struct RegisterWorkerRequest {
    pub worker_id: String,
    pub address: String,
    pub api_key: String,
    pub capacity: WorkerCapacity,
}

/// Response body for worker registration.
#[derive(Debug, Serialize, Deserialize)]
pub struct RegisterWorkerResponse {
    pub worker_id: String,
    pub status: String,
    /// Optional heartbeat interval override from coordinator (seconds).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub heartbeat_interval_secs: Option<u64>,
}

/// Health status of a single connector within a pipeline.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectorHealth {
    pub connector_name: String,
    pub connector_type: String,
    pub connected: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_error: Option<String>,
    pub messages_received: u64,
    pub seconds_since_last_message: u64,
}

/// Per-pipeline metrics reported in heartbeats.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PipelineMetrics {
    pub pipeline_name: String,
    pub events_in: u64,
    pub events_out: u64,
    #[serde(default)]
    pub connector_health: Vec<ConnectorHealth>,
}

/// Request body for worker heartbeat.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HeartbeatRequest {
    pub events_processed: u64,
    pub pipelines_running: usize,
    #[serde(default)]
    pub pipeline_metrics: Vec<PipelineMetrics>,
}

/// Response body for worker heartbeat.
#[derive(Debug, Serialize, Deserialize)]
pub struct HeartbeatResponse {
    pub acknowledged: bool,
}

/// Serializable worker info for API responses.
#[derive(Debug, Serialize, Deserialize)]
pub struct WorkerInfo {
    pub id: String,
    pub address: String,
    pub status: String,
    pub pipelines_running: usize,
    pub max_pipelines: usize,
    pub cpu_cores: usize,
    pub assigned_pipelines: Vec<String>,
    pub events_processed: u64,
}

impl From<&WorkerNode> for WorkerInfo {
    fn from(node: &WorkerNode) -> Self {
        Self {
            id: node.id.0.clone(),
            address: node.address.clone(),
            status: node.status.to_string(),
            pipelines_running: node.capacity.pipelines_running,
            max_pipelines: node.capacity.max_pipelines,
            cpu_cores: node.capacity.cpu_cores,
            assigned_pipelines: node.assigned_pipelines.clone(),
            events_processed: node.events_processed,
        }
    }
}

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

    #[test]
    fn test_worker_node_creation() {
        let node = WorkerNode::new(
            WorkerId("w1".into()),
            "http://localhost:9000".into(),
            "key".into(),
        );
        assert_eq!(node.id, WorkerId("w1".into()));
        assert_eq!(node.status, WorkerStatus::Registering);
        assert!(!node.is_available()); // not Ready yet
    }

    #[test]
    fn test_worker_is_available() {
        let mut node = WorkerNode::new(
            WorkerId("w1".into()),
            "http://localhost:9000".into(),
            "key".into(),
        );
        node.status = WorkerStatus::Ready;
        assert!(node.is_available());

        node.status = WorkerStatus::Unhealthy;
        assert!(!node.is_available());
    }

    #[test]
    fn test_worker_status_display() {
        assert_eq!(WorkerStatus::Ready.to_string(), "ready");
        assert_eq!(WorkerStatus::Unhealthy.to_string(), "unhealthy");
        assert_eq!(WorkerStatus::Draining.to_string(), "draining");
        assert_eq!(WorkerStatus::Registering.to_string(), "registering");
    }

    #[test]
    fn test_worker_id_display() {
        let id = WorkerId("my-worker-42".into());
        assert_eq!(id.to_string(), "my-worker-42");
        assert_eq!(format!("Worker: {}", id), "Worker: my-worker-42");
    }

    #[test]
    fn test_worker_not_available_when_draining() {
        let mut node = WorkerNode::new(
            WorkerId("w1".into()),
            "http://localhost:9000".into(),
            "key".into(),
        );
        node.status = WorkerStatus::Draining;
        assert!(!node.is_available());
    }

    #[test]
    fn test_worker_not_available_at_max_capacity() {
        let mut node = WorkerNode::new(
            WorkerId("w1".into()),
            "http://localhost:9000".into(),
            "key".into(),
        );
        node.status = WorkerStatus::Ready;
        node.capacity.max_pipelines = 5;
        node.capacity.pipelines_running = 5;
        assert!(!node.is_available());
    }

    #[test]
    fn test_worker_available_just_below_capacity() {
        let mut node = WorkerNode::new(
            WorkerId("w1".into()),
            "http://localhost:9000".into(),
            "key".into(),
        );
        node.status = WorkerStatus::Ready;
        node.capacity.max_pipelines = 5;
        node.capacity.pipelines_running = 4;
        assert!(node.is_available());
    }

    #[test]
    fn test_worker_info_from_node() {
        let mut node = WorkerNode::new(
            WorkerId("w1".into()),
            "http://localhost:9000".into(),
            "secret-key".into(),
        );
        node.status = WorkerStatus::Ready;
        node.capacity.pipelines_running = 3;
        node.capacity.max_pipelines = 10;
        node.capacity.cpu_cores = 8;
        node.assigned_pipelines = vec!["p1".into(), "p2".into(), "p3".into()];
        node.events_processed = 42000;

        let info = WorkerInfo::from(&node);
        assert_eq!(info.id, "w1");
        assert_eq!(info.address, "http://localhost:9000");
        assert_eq!(info.status, "ready");
        assert_eq!(info.pipelines_running, 3);
        assert_eq!(info.max_pipelines, 10);
        assert_eq!(info.cpu_cores, 8);
        assert_eq!(info.assigned_pipelines, vec!["p1", "p2", "p3"]);
        assert_eq!(info.events_processed, 42000);
    }

    #[test]
    fn test_worker_capacity_default() {
        let cap = WorkerCapacity::default();
        assert!(cap.cpu_cores >= 1);
        assert_eq!(cap.pipelines_running, 0);
        assert_eq!(cap.max_pipelines, 100);
    }

    #[test]
    fn test_worker_id_equality() {
        let a = WorkerId("w1".into());
        let b = WorkerId("w1".into());
        let c = WorkerId("w2".into());
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn test_worker_id_hash() {
        use std::collections::HashSet;
        let mut set = HashSet::new();
        set.insert(WorkerId("w1".into()));
        set.insert(WorkerId("w1".into())); // duplicate
        set.insert(WorkerId("w2".into()));
        assert_eq!(set.len(), 2);
    }

    #[test]
    fn test_register_worker_request_serde() {
        let req = RegisterWorkerRequest {
            worker_id: "w1".into(),
            address: "http://localhost:9000".into(),
            api_key: "key".into(),
            capacity: WorkerCapacity::default(),
        };
        let json = serde_json::to_string(&req).unwrap();
        let parsed: RegisterWorkerRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.worker_id, "w1");
        assert_eq!(parsed.address, "http://localhost:9000");
    }

    #[test]
    fn test_heartbeat_request_serde() {
        let hb = HeartbeatRequest {
            events_processed: 42,
            pipelines_running: 3,
            pipeline_metrics: vec![],
        };
        let json = serde_json::to_string(&hb).unwrap();
        let parsed: HeartbeatRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.events_processed, 42);
        assert_eq!(parsed.pipelines_running, 3);
    }

    #[test]
    fn test_connector_health_serde() {
        let ch = ConnectorHealth {
            connector_name: "mqtt_in".into(),
            connector_type: "mqtt".into(),
            connected: true,
            last_error: None,
            messages_received: 42,
            seconds_since_last_message: 5,
        };
        let json = serde_json::to_string(&ch).unwrap();
        let parsed: ConnectorHealth = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.connector_name, "mqtt_in");
        assert!(parsed.connected);
        assert!(parsed.last_error.is_none());
        assert_eq!(parsed.messages_received, 42);
        // last_error should be skipped when None
        assert!(!json.contains("last_error"));
    }

    #[test]
    fn test_pipeline_metrics_backward_compat() {
        // Old heartbeats without connector_health should deserialize with empty vec
        let json = r#"{"pipeline_name":"p1","events_in":100,"events_out":50}"#;
        let parsed: PipelineMetrics = serde_json::from_str(json).unwrap();
        assert_eq!(parsed.pipeline_name, "p1");
        assert_eq!(parsed.events_in, 100);
        assert_eq!(parsed.events_out, 50);
        assert!(parsed.connector_health.is_empty());
    }

    #[test]
    fn test_pipeline_metrics_with_connector_health() {
        let pm = PipelineMetrics {
            pipeline_name: "p1".into(),
            events_in: 100,
            events_out: 50,
            connector_health: vec![ConnectorHealth {
                connector_name: "mqtt_in".into(),
                connector_type: "mqtt".into(),
                connected: false,
                last_error: Some("connection refused".into()),
                messages_received: 0,
                seconds_since_last_message: 120,
            }],
        };
        let json = serde_json::to_string(&pm).unwrap();
        let parsed: PipelineMetrics = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.connector_health.len(), 1);
        assert!(!parsed.connector_health[0].connected);
        assert_eq!(
            parsed.connector_health[0].last_error.as_deref(),
            Some("connection refused")
        );
    }

    #[test]
    fn test_worker_status_serde() {
        let status = WorkerStatus::Ready;
        let json = serde_json::to_string(&status).unwrap();
        assert_eq!(json, "\"ready\"");
        let parsed: WorkerStatus = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed, WorkerStatus::Ready);

        // All variants round-trip
        for s in [
            WorkerStatus::Registering,
            WorkerStatus::Ready,
            WorkerStatus::Unhealthy,
            WorkerStatus::Draining,
        ] {
            let json = serde_json::to_string(&s).unwrap();
            let parsed: WorkerStatus = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, s);
        }
    }
}