repe 3.5.2

Rust implementation of the REPE RPC protocol (JSON-focused)
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
use crate::async_client::AsyncClient;
use crate::error::RepeError;
use crate::fleet::{
    ConnectSummary, DisconnectSummary, FleetError, FleetOptions, HealthStatus, Node, NodeConfig,
    ReconnectSummary, RemoteResult, validate_fleet_options, validate_node_config,
};
use crate::message::Message;
use serde_json::Value;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::sync::Arc;
use std::time::Instant;
use tokio::sync::{Mutex, RwLock};

const DEFAULT_HEALTH_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);

struct AsyncNodeState {
    config: NodeConfig,
    tags: BTreeSet<String>,
    client: Mutex<Option<AsyncClient>>,
}

impl AsyncNodeState {
    fn new(config: NodeConfig) -> Self {
        Self {
            tags: config.tags.clone(),
            config,
            client: Mutex::new(None),
        }
    }

    fn snapshot(&self) -> Node {
        Node {
            name: self.config.name.clone(),
            host: self.config.host.clone(),
            port: self.config.port,
            tags: self.tags.clone(),
            timeout: self.config.timeout,
        }
    }
}

#[derive(Clone)]
pub struct AsyncFleet {
    nodes: Arc<RwLock<HashMap<String, Arc<AsyncNodeState>>>>,
    options: FleetOptions,
}

impl Default for AsyncFleet {
    fn default() -> Self {
        Self {
            nodes: Arc::new(RwLock::new(HashMap::new())),
            options: FleetOptions::default(),
        }
    }
}

impl AsyncFleet {
    pub fn new(configs: Vec<NodeConfig>) -> Result<Self, FleetError> {
        Self::with_options(configs, FleetOptions::default())
    }

    pub fn with_options(
        configs: Vec<NodeConfig>,
        options: FleetOptions,
    ) -> Result<Self, FleetError> {
        validate_fleet_options(&options)?;

        let mut names = HashSet::new();
        let mut nodes = HashMap::new();

        for config in configs {
            validate_node_config(&config)?;
            if !names.insert(config.name.clone()) {
                return Err(FleetError::DuplicateNodeName(config.name));
            }

            nodes.insert(config.name.clone(), Arc::new(AsyncNodeState::new(config)));
        }

        Ok(Self {
            nodes: Arc::new(RwLock::new(nodes)),
            options,
        })
    }

    pub fn options(&self) -> FleetOptions {
        self.options
    }

    pub async fn len(&self) -> usize {
        self.nodes.read().await.len()
    }

    pub async fn is_empty(&self) -> bool {
        self.len().await == 0
    }

    pub async fn keys(&self) -> Vec<String> {
        self.nodes.read().await.keys().cloned().collect()
    }

    pub async fn node(&self, name: &str) -> Result<Node, FleetError> {
        let nodes = self.nodes.read().await;
        let node = nodes
            .get(name)
            .ok_or_else(|| FleetError::NodeNotFound(name.to_string()))?;
        Ok(node.snapshot())
    }

    pub async fn nodes(&self) -> Vec<Node> {
        self.nodes
            .read()
            .await
            .values()
            .map(|node| node.snapshot())
            .collect()
    }

    pub async fn connected_nodes(&self) -> Vec<Node> {
        let states = self.snapshot_node_states().await;
        let mut out = Vec::new();
        for state in states {
            if state.client.lock().await.is_some() {
                out.push(state.snapshot());
            }
        }
        out
    }

    /// Returns nodes that contain all provided tags.
    ///
    /// Passing an empty `tags` slice matches all nodes.
    pub async fn filter_nodes<T: AsRef<str>>(&self, tags: &[T]) -> Vec<Node> {
        let tag_set: BTreeSet<String> = tags.iter().map(|tag| tag.as_ref().to_string()).collect();
        self.nodes
            .read()
            .await
            .values()
            .filter(|node| tag_set.is_subset(&node.tags))
            .map(|node| node.snapshot())
            .collect()
    }

    pub async fn add_node(&self, config: NodeConfig) -> Result<(), FleetError> {
        validate_node_config(&config)?;

        let mut nodes = self.nodes.write().await;
        if nodes.contains_key(&config.name) {
            return Err(FleetError::DuplicateNodeName(config.name));
        }

        nodes.insert(config.name.clone(), Arc::new(AsyncNodeState::new(config)));
        Ok(())
    }

    pub async fn remove_node(&self, name: &str) -> bool {
        let removed = {
            let mut nodes = self.nodes.write().await;
            nodes.remove(name)
        };

        if let Some(state) = removed {
            let mut client = state.client.lock().await;
            *client = None;
            true
        } else {
            false
        }
    }

    pub async fn connect_all(&self) -> ConnectSummary {
        let states = self.snapshot_node_states().await;
        let mut tasks = Vec::with_capacity(states.len());

        for state in states {
            tasks.push(tokio::spawn(async move {
                let name = state.config.name.clone();
                let ok = ensure_connected(&state).await.is_ok();
                (name, ok)
            }));
        }

        let mut summary = ConnectSummary::default();
        for task in tasks {
            match task.await {
                Ok((name, true)) => summary.connected.push(name),
                Ok((name, false)) => summary.failed.push(name),
                Err(_) => summary.failed.push("<unknown>".to_string()),
            }
        }

        summary
    }

    pub async fn disconnect_all(&self) -> DisconnectSummary {
        let states = self.snapshot_node_states().await;
        let mut summary = DisconnectSummary::default();

        for state in states {
            let name = state.config.name.clone();
            let mut client = state.client.lock().await;
            *client = None;
            summary.disconnected.push(name);
        }

        summary
    }

    pub async fn reconnect_disconnected(&self) -> ReconnectSummary {
        let states = self.snapshot_node_states().await;
        let mut tasks = Vec::new();

        for state in states {
            if state.client.lock().await.is_none() {
                tasks.push(tokio::spawn(async move {
                    let name = state.config.name.clone();
                    let ok = ensure_connected(&state).await.is_ok();
                    (name, ok)
                }));
            }
        }

        let mut summary = ReconnectSummary::default();
        for task in tasks {
            match task.await {
                Ok((name, true)) => summary.reconnected.push(name),
                Ok((name, false)) => summary.failed.push(name),
                Err(_) => summary.failed.push("<unknown>".to_string()),
            }
        }

        summary
    }

    pub async fn is_connected_all(&self) -> bool {
        let states = self.snapshot_node_states().await;
        for state in states {
            if state.client.lock().await.is_none() {
                return false;
            }
        }
        true
    }

    pub async fn is_connected(&self, name: &str) -> Result<bool, FleetError> {
        let state = self.node_state(name).await?;
        Ok(state.client.lock().await.is_some())
    }

    pub async fn call_json(
        &self,
        node_name: &str,
        method: &str,
        params: Option<&Value>,
    ) -> Result<RemoteResult<Value>, FleetError> {
        let state = self.node_state(node_name).await?;
        Ok(self
            .call_json_with_retry(state, method.to_string(), params.cloned())
            .await)
    }

    pub async fn call_message(
        &self,
        node_name: &str,
        method: &str,
    ) -> Result<RemoteResult<Message>, FleetError> {
        let state = self.node_state(node_name).await?;
        Ok(self
            .call_message_with_retry(state, method.to_string())
            .await)
    }

    /// Broadcasts to nodes matching all provided tags.
    ///
    /// Passing an empty `tags` slice matches all nodes.
    pub async fn broadcast_json<T: AsRef<str>>(
        &self,
        method: &str,
        params: Option<&Value>,
        tags: &[T],
    ) -> HashMap<String, RemoteResult<Value>> {
        let states = self.snapshot_target_nodes(tags).await;
        let mut tasks = Vec::with_capacity(states.len());

        for state in states {
            let fleet = self.clone();
            let method = method.to_string();
            let params = params.cloned();
            tasks.push(tokio::spawn(async move {
                let result = fleet.call_json_with_retry(state, method, params).await;
                (result.node.clone(), result)
            }));
        }

        let mut results = HashMap::new();
        for task in tasks {
            if let Ok((name, result)) = task.await {
                results.insert(name, result);
            }
        }

        results
    }

    /// Broadcasts and reduces over nodes matching all provided tags.
    ///
    /// Passing an empty `tags` slice matches all nodes.
    pub async fn map_reduce_json<T: AsRef<str>, R, F>(
        &self,
        method: &str,
        params: Option<&Value>,
        tags: &[T],
        reduce_fn: F,
    ) -> R
    where
        F: FnOnce(Vec<RemoteResult<Value>>) -> R,
    {
        let results = self.broadcast_json(method, params, tags).await;
        reduce_fn(results.into_values().collect())
    }

    pub async fn health_check(&self, health_endpoint: &str) -> HashMap<String, HealthStatus> {
        let states = self.snapshot_node_states().await;
        let mut tasks = Vec::with_capacity(states.len());

        for state in states {
            let endpoint = health_endpoint.to_string();
            tasks.push(tokio::spawn(async move {
                let start = Instant::now();
                let name = state.config.name.clone();

                let outcome = async {
                    let client = ensure_connected(&state).await?;
                    client
                        .call_message_with_timeout(&endpoint, DEFAULT_HEALTH_TIMEOUT)
                        .await
                }
                .await;

                let status = match outcome {
                    Ok(_) => HealthStatus {
                        healthy: true,
                        latency: start.elapsed(),
                        error: None,
                    },
                    Err(err) => {
                        invalidate_client(&state).await;
                        HealthStatus {
                            healthy: false,
                            latency: start.elapsed(),
                            error: Some(err),
                        }
                    }
                };

                (name, status)
            }));
        }

        let mut results = HashMap::new();
        for task in tasks {
            if let Ok((name, status)) = task.await {
                results.insert(name, status);
            }
        }

        results
    }

    async fn snapshot_node_states(&self) -> Vec<Arc<AsyncNodeState>> {
        self.nodes.read().await.values().cloned().collect()
    }

    async fn snapshot_target_nodes<T: AsRef<str>>(&self, tags: &[T]) -> Vec<Arc<AsyncNodeState>> {
        let tag_set: BTreeSet<String> = tags.iter().map(|tag| tag.as_ref().to_string()).collect();
        self.nodes
            .read()
            .await
            .values()
            .filter(|node| tag_set.is_subset(&node.tags))
            .cloned()
            .collect()
    }

    async fn node_state(&self, name: &str) -> Result<Arc<AsyncNodeState>, FleetError> {
        self.nodes
            .read()
            .await
            .get(name)
            .cloned()
            .ok_or_else(|| FleetError::NodeNotFound(name.to_string()))
    }

    async fn call_json_with_retry(
        &self,
        state: Arc<AsyncNodeState>,
        method: String,
        params: Option<Value>,
    ) -> RemoteResult<Value> {
        let started = Instant::now();
        let mut last_error = None;

        for attempt in 0..self.options.retry_policy.max_attempts {
            let timeout = state.config.timeout;
            let call = async {
                let client = ensure_connected(&state).await?;
                if let Some(ref value) = params {
                    client.call_json_with_timeout(&method, value, timeout).await
                } else {
                    let message = client.call_message_with_timeout(&method, timeout).await?;
                    message.json_body::<Value>()
                }
            }
            .await;

            match call {
                Ok(value) => {
                    return RemoteResult {
                        node: state.config.name.clone(),
                        value: Some(value),
                        error: None,
                        elapsed: started.elapsed(),
                    };
                }
                Err(err) => {
                    let should_retry = is_retryable_error(&err);
                    last_error = Some(err);

                    if should_retry {
                        invalidate_client(&state).await;
                        if attempt + 1 < self.options.retry_policy.max_attempts {
                            tokio::time::sleep(self.options.retry_policy.delay).await;
                        }
                    } else {
                        break;
                    }
                }
            }
        }

        RemoteResult {
            node: state.config.name.clone(),
            value: None,
            error: last_error,
            elapsed: started.elapsed(),
        }
    }

    async fn call_message_with_retry(
        &self,
        state: Arc<AsyncNodeState>,
        method: String,
    ) -> RemoteResult<Message> {
        let started = Instant::now();
        let mut last_error = None;

        for attempt in 0..self.options.retry_policy.max_attempts {
            let timeout = state.config.timeout;
            let call = async {
                let client = ensure_connected(&state).await?;
                client.call_message_with_timeout(&method, timeout).await
            }
            .await;

            match call {
                Ok(value) => {
                    return RemoteResult {
                        node: state.config.name.clone(),
                        value: Some(value),
                        error: None,
                        elapsed: started.elapsed(),
                    };
                }
                Err(err) => {
                    let should_retry = is_retryable_error(&err);
                    last_error = Some(err);

                    if should_retry {
                        invalidate_client(&state).await;
                        if attempt + 1 < self.options.retry_policy.max_attempts {
                            tokio::time::sleep(self.options.retry_policy.delay).await;
                        }
                    } else {
                        break;
                    }
                }
            }
        }

        RemoteResult {
            node: state.config.name.clone(),
            value: None,
            error: last_error,
            elapsed: started.elapsed(),
        }
    }
}

async fn ensure_connected(state: &Arc<AsyncNodeState>) -> Result<AsyncClient, RepeError> {
    let mut client = state.client.lock().await;
    if let Some(existing) = client.as_ref() {
        return Ok(existing.clone());
    }

    let host = state.config.host.clone();
    let created = AsyncClient::connect((host.as_str(), state.config.port)).await?;
    let cloned = created.clone();
    *client = Some(created);
    Ok(cloned)
}

async fn invalidate_client(state: &Arc<AsyncNodeState>) {
    let mut client = state.client.lock().await;
    *client = None;
}

fn is_retryable_error(err: &RepeError) -> bool {
    match err {
        RepeError::Io(io_err) => matches!(
            io_err.kind(),
            std::io::ErrorKind::TimedOut
                | std::io::ErrorKind::ConnectionRefused
                | std::io::ErrorKind::ConnectionReset
                | std::io::ErrorKind::ConnectionAborted
                | std::io::ErrorKind::NotConnected
                | std::io::ErrorKind::UnexpectedEof
                | std::io::ErrorKind::WouldBlock
                | std::io::ErrorKind::Interrupted
        ),
        RepeError::ServerError { .. } => false,
        _ => false,
    }
}