vifu-server 0.1.2

HTTP, WebSocket, and persistent server implementation for Vifu.
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;

use serde_json::Value;
use tokio::sync::{mpsc, oneshot, Mutex};
use uuid::Uuid;
use vifu_gateway::protocol::AgentGatewayCommand;
use vifu_runtime::{
    AgentProvider, CancellationToken, InvocationData, ProviderFuture, ProviderRequest,
    ProviderResponse, RuntimeError,
};

use crate::models::EndpointRoute;

#[derive(Clone)]
pub struct RelayHub {
    inner: Arc<Mutex<RelayState>>,
    queue_capacity: usize,
}

struct RelayState {
    connections: HashMap<String, AgentGatewayConnection>,
    pending: HashMap<Uuid, PendingCall>,
    next_channel_id: u64,
}

#[derive(Clone)]
struct AgentGatewayConnection {
    connection_id: Uuid,
    session_id: Uuid,
    sender: mpsc::Sender<AgentGatewayCommand>,
}

struct PendingCall {
    connection_id: Uuid,
    channel_id: u64,
    sender: oneshot::Sender<Result<Value, RelayCallError>>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RelayCallError {
    AgentGatewayUnavailable,
    Backpressure,
    Timeout,
    Cancelled,
    AgentGateway(String),
}

struct PendingInvocation {
    hub: RelayHub,
    request_id: Uuid,
    channel_id: u64,
    sender: mpsc::Sender<AgentGatewayCommand>,
    armed: bool,
}

impl PendingInvocation {
    async fn abort(&mut self) {
        if !self.armed {
            return;
        }
        self.armed = false;
        self.hub.remove_pending(self.request_id).await;
        let _ = self.sender.try_send(AgentGatewayCommand::Cancel {
            request_id: self.request_id,
            channel_id: self.channel_id,
        });
    }

    fn disarm(&mut self) {
        self.armed = false;
    }
}

impl Drop for PendingInvocation {
    fn drop(&mut self) {
        if !self.armed {
            return;
        }
        let hub = self.hub.clone();
        let request_id = self.request_id;
        let channel_id = self.channel_id;
        let sender = self.sender.clone();
        tokio::spawn(async move {
            hub.remove_pending(request_id).await;
            let _ = sender.try_send(AgentGatewayCommand::Cancel {
                request_id,
                channel_id,
            });
        });
    }
}

pub(crate) struct RelayAgentProvider {
    name: String,
    capability: String,
    hub: RelayHub,
    route: EndpointRoute,
    request_id: Uuid,
    timeout: Duration,
}

impl RelayAgentProvider {
    pub(crate) fn new(
        name: impl Into<String>,
        capability: impl Into<String>,
        hub: RelayHub,
        route: EndpointRoute,
        request_id: Uuid,
        timeout: Duration,
    ) -> Self {
        Self {
            name: name.into(),
            capability: capability.into(),
            hub,
            route,
            request_id,
            timeout,
        }
    }
}

impl AgentProvider for RelayAgentProvider {
    fn supports(&self, capability: &str) -> bool {
        capability == self.capability
    }

    fn invoke<'a>(
        &'a self,
        request: ProviderRequest,
        cancellation: CancellationToken,
    ) -> ProviderFuture<'a> {
        Box::pin(async move {
            let InvocationData::Json(input) = request.data else {
                return Err(RuntimeError::InvalidDefinition(
                    "agent gateway capabilities require JSON input".to_string(),
                ));
            };
            let output = self
                .hub
                .invoke_with_cancellation(
                    &self.route,
                    self.request_id,
                    input,
                    self.timeout,
                    cancellation,
                )
                .await
                .map_err(|error| match error {
                    RelayCallError::AgentGatewayUnavailable => {
                        RuntimeError::Unavailable(self.name.clone())
                    }
                    RelayCallError::Backpressure => RuntimeError::Backpressure(self.name.clone()),
                    RelayCallError::Timeout => RuntimeError::Timeout(duration_millis(self.timeout)),
                    RelayCallError::Cancelled => RuntimeError::Cancelled,
                    RelayCallError::AgentGateway(message) => {
                        RuntimeError::provider(&self.name, message)
                    }
                })?;
            Ok(ProviderResponse::json(output))
        })
    }
}

impl RelayHub {
    pub fn new(queue_capacity: usize) -> Self {
        Self {
            inner: Arc::new(Mutex::new(RelayState {
                connections: HashMap::new(),
                pending: HashMap::new(),
                next_channel_id: 1,
            })),
            queue_capacity,
        }
    }

    pub fn channel(
        &self,
    ) -> (
        mpsc::Sender<AgentGatewayCommand>,
        mpsc::Receiver<AgentGatewayCommand>,
    ) {
        mpsc::channel(self.queue_capacity)
    }

    pub async fn register(
        &self,
        gateway_id: String,
        connection_id: Uuid,
        session_id: Uuid,
        sender: mpsc::Sender<AgentGatewayCommand>,
    ) {
        let replaced = {
            let mut state = self.inner.lock().await;
            state.connections.insert(
                gateway_id,
                AgentGatewayConnection {
                    connection_id,
                    session_id,
                    sender,
                },
            )
        };
        if let Some(replaced) = replaced {
            let _ = replaced.sender.try_send(AgentGatewayCommand::Error {
                request_id: None,
                channel_id: None,
                code: "SESSION_REPLACED".to_string(),
                message: "A newer connection replaced this agent gateway session.".to_string(),
            });
        }
    }

    pub async fn unregister(&self, gateway_id: &str, connection_id: Uuid) -> bool {
        let (removed_current, pending) = {
            let mut state = self.inner.lock().await;
            let removed_current = if state
                .connections
                .get(gateway_id)
                .is_some_and(|connection| connection.connection_id == connection_id)
            {
                state.connections.remove(gateway_id);
                true
            } else {
                false
            };

            let request_ids = state
                .pending
                .iter()
                .filter_map(|(request_id, pending)| {
                    (pending.connection_id == connection_id).then_some(*request_id)
                })
                .collect::<Vec<_>>();
            let pending = request_ids
                .into_iter()
                .filter_map(|request_id| state.pending.remove(&request_id))
                .collect::<Vec<_>>();
            (removed_current, pending)
        };
        for pending in pending {
            let _ = pending
                .sender
                .send(Err(RelayCallError::AgentGatewayUnavailable));
        }
        removed_current
    }

    pub async fn session_for(&self, gateway_id: &str) -> Option<Uuid> {
        self.inner
            .lock()
            .await
            .connections
            .get(gateway_id)
            .map(|connection| connection.session_id)
    }

    pub async fn connection_count(&self) -> usize {
        self.inner.lock().await.connections.len()
    }

    pub async fn disconnect(&self, gateway_id: &str, code: &str) -> bool {
        let connection = self.inner.lock().await.connections.get(gateway_id).cloned();
        let Some(connection) = connection else {
            return false;
        };
        connection
            .sender
            .try_send(AgentGatewayCommand::Error {
                request_id: None,
                channel_id: None,
                code: code.to_string(),
                message: "The agent gateway credential is no longer active.".to_string(),
            })
            .is_ok()
    }

    pub async fn notify_runtime_config(&self, gateway_id: &str, deployment_ids: Vec<Uuid>) -> bool {
        let connection = self.inner.lock().await.connections.get(gateway_id).cloned();
        let Some(connection) = connection else {
            return false;
        };
        connection
            .sender
            .try_send(AgentGatewayCommand::RuntimeConfigChanged { deployment_ids })
            .is_ok()
    }

    pub async fn invoke(
        &self,
        route: &EndpointRoute,
        request_id: Uuid,
        input: Value,
        timeout: Duration,
    ) -> Result<Value, RelayCallError> {
        self.invoke_with_cancellation(
            route,
            request_id,
            input,
            timeout,
            CancellationToken::default(),
        )
        .await
    }

    pub async fn invoke_with_cancellation(
        &self,
        route: &EndpointRoute,
        request_id: Uuid,
        input: Value,
        timeout: Duration,
        cancellation: CancellationToken,
    ) -> Result<Value, RelayCallError> {
        let (response_sender, response_receiver) = oneshot::channel();
        let (connection, channel_id) = {
            let mut state = self.inner.lock().await;
            let connection = state
                .connections
                .get(&route.gateway_id)
                .cloned()
                .ok_or(RelayCallError::AgentGatewayUnavailable)?;
            let channel_id = next_channel_id(&mut state);
            state.pending.insert(
                request_id,
                PendingCall {
                    connection_id: connection.connection_id,
                    channel_id,
                    sender: response_sender,
                },
            );
            (connection, channel_id)
        };

        let message = AgentGatewayCommand::Invoke {
            request_id,
            channel_id,
            endpoint_id: route.endpoint_id,
            profile_id: route.profile_id,
            binding_id: route.binding_id,
            agent_id: route.agent_id.clone(),
            binding: route.binding_config.clone(),
            input,
            timeout_ms: timeout.as_millis().try_into().unwrap_or(u64::MAX),
        };

        if let Err(error) = connection.sender.try_send(message) {
            self.remove_pending(request_id).await;
            return match error {
                mpsc::error::TrySendError::Full(_) => Err(RelayCallError::Backpressure),
                mpsc::error::TrySendError::Closed(_) => {
                    Err(RelayCallError::AgentGatewayUnavailable)
                }
            };
        }

        let mut pending = PendingInvocation {
            hub: self.clone(),
            request_id,
            channel_id,
            sender: connection.sender,
            armed: true,
        };
        tokio::select! {
            response = tokio::time::timeout(timeout, response_receiver) => {
                match response {
                    Ok(Ok(result)) => {
                        pending.disarm();
                        result
                    }
                    Ok(Err(_)) => {
                        pending.disarm();
                        Err(RelayCallError::AgentGatewayUnavailable)
                    }
                    Err(_) => {
                        pending.abort().await;
                        Err(RelayCallError::Timeout)
                    }
                }
            }
            _ = cancellation.cancelled() => {
                pending.abort().await;
                Err(RelayCallError::Cancelled)
            }
        }
    }

    pub async fn complete_result(
        &self,
        connection_id: Uuid,
        request_id: Uuid,
        channel_id: u64,
        output: Value,
    ) -> bool {
        self.complete(connection_id, request_id, channel_id, Ok(output))
            .await
    }

    pub async fn complete_error(
        &self,
        connection_id: Uuid,
        request_id: Uuid,
        channel_id: u64,
        message: String,
    ) -> bool {
        self.complete(
            connection_id,
            request_id,
            channel_id,
            Err(RelayCallError::AgentGateway(message)),
        )
        .await
    }

    async fn complete(
        &self,
        connection_id: Uuid,
        request_id: Uuid,
        channel_id: u64,
        result: Result<Value, RelayCallError>,
    ) -> bool {
        let pending = {
            let mut state = self.inner.lock().await;
            let matches = state.pending.get(&request_id).is_some_and(|pending| {
                pending.connection_id == connection_id && pending.channel_id == channel_id
            });
            matches.then(|| state.pending.remove(&request_id)).flatten()
        };
        pending.is_some_and(|pending| pending.sender.send(result).is_ok())
    }

    async fn remove_pending(&self, request_id: Uuid) {
        self.inner.lock().await.pending.remove(&request_id);
    }
}

fn next_channel_id(state: &mut RelayState) -> u64 {
    let channel_id = state.next_channel_id.max(1);
    state.next_channel_id = channel_id.wrapping_add(1).max(1);
    channel_id
}

fn duration_millis(duration: Duration) -> u64 {
    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use serde_json::json;
    use uuid::Uuid;
    use vifu_gateway::protocol::AgentGatewayCommand;

    use super::{RelayCallError, RelayHub};
    use crate::models::EndpointRoute;
    use vifu_runtime::CancellationToken;

    #[tokio::test]
    async fn multiplexes_ten_concurrent_calls_on_one_connection() {
        let hub = RelayHub::new(16);
        let (sender, mut receiver) = hub.channel();
        let connection_id = Uuid::new_v4();
        hub.register(
            "openclaw-local".to_string(),
            connection_id,
            Uuid::new_v4(),
            sender,
        )
        .await;
        let route = route();

        let calls = (0..10)
            .map(|index| {
                let hub = hub.clone();
                let route = route.clone();
                tokio::spawn(async move {
                    hub.invoke(
                        &route,
                        Uuid::new_v4(),
                        json!({ "index": index }),
                        Duration::from_secs(1),
                    )
                    .await
                })
            })
            .collect::<Vec<_>>();

        for _ in 0..10 {
            let message = receiver.recv().await.unwrap();
            let AgentGatewayCommand::Invoke {
                request_id,
                channel_id,
                input,
                ..
            } = message
            else {
                panic!("expected invoke");
            };
            assert!(channel_id > 0);
            hub.complete_result(connection_id, request_id, channel_id, input)
                .await;
        }

        for call in calls {
            assert!(call.await.unwrap().is_ok());
        }
        assert_eq!(hub.connection_count().await, 1);
    }

    #[tokio::test]
    async fn applies_backpressure_to_a_full_agent_gateway_queue() {
        let hub = RelayHub::new(1);
        let (sender, _receiver) = hub.channel();
        hub.register(
            "openclaw-local".to_string(),
            Uuid::new_v4(),
            Uuid::new_v4(),
            sender,
        )
        .await;

        let first = {
            let hub = hub.clone();
            tokio::spawn(async move {
                hub.invoke(
                    &route(),
                    Uuid::new_v4(),
                    json!({}),
                    Duration::from_millis(500),
                )
                .await
            })
        };
        tokio::task::yield_now().await;
        let second = hub
            .invoke(
                &route(),
                Uuid::new_v4(),
                json!({}),
                Duration::from_millis(500),
            )
            .await;
        assert_eq!(second, Err(RelayCallError::Backpressure));
        first.abort();
    }

    #[tokio::test]
    async fn cancelling_a_call_removes_it_and_notifies_the_agent_gateway() {
        let hub = RelayHub::new(4);
        let (sender, mut receiver) = hub.channel();
        let connection_id = Uuid::new_v4();
        hub.register(
            "openclaw-local".to_string(),
            connection_id,
            Uuid::new_v4(),
            sender,
        )
        .await;
        let request_id = Uuid::new_v4();
        let cancellation = CancellationToken::default();
        let call = {
            let hub = hub.clone();
            let cancellation = cancellation.clone();
            tokio::spawn(async move {
                hub.invoke_with_cancellation(
                    &route(),
                    request_id,
                    json!({}),
                    Duration::from_secs(5),
                    cancellation,
                )
                .await
            })
        };
        let invoke = receiver.recv().await.expect("invoke should be queued");
        let AgentGatewayCommand::Invoke { channel_id, .. } = invoke else {
            panic!("expected invoke");
        };

        cancellation.cancel();
        assert_eq!(call.await.unwrap(), Err(RelayCallError::Cancelled));
        assert_eq!(
            receiver.recv().await,
            Some(AgentGatewayCommand::Cancel {
                request_id,
                channel_id,
            })
        );
        assert!(
            !hub.complete_result(connection_id, request_id, channel_id, json!({}))
                .await
        );
    }

    fn route() -> EndpointRoute {
        EndpointRoute {
            endpoint_id: Uuid::new_v4(),
            endpoint_slug: "guide".to_string(),
            endpoint_name: "Guide".to_string(),
            request_timeout_ms: 30_000,
            profile_id: Uuid::new_v4(),
            binding_id: Uuid::new_v4(),
            gateway_id: "openclaw-local".to_string(),
            agent_id: "guide-agent".to_string(),
            binding_config: json!({}),
        }
    }
}