slop-ai 0.2.0

Rust SDK for the SLOP protocol — let AI observe and interact with your app's state
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
//! Async SLOP consumer — connects to a provider, mirrors state, and dispatches
//! actions via a channel-based transport abstraction.
//!
//! Gated behind the `native` feature (requires tokio).

use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use serde_json::{json, Value};
use tokio::sync::{mpsc, oneshot, Mutex};

use crate::error::{Result, SlopError};
use crate::state_mirror::StateMirror;
use crate::types::{PatchOp, SlopNode};

type TransportChannels = (
    mpsc::UnboundedSender<Value>,
    mpsc::UnboundedReceiver<Value>,
);

type ConnectFuture = Pin<Box<dyn Future<Output = Result<TransportChannels>> + Send>>;

type PatchCallback = Arc<dyn Fn(&str, &[PatchOp], u64) + Send + Sync>;
type DisconnectCallback = Arc<dyn Fn() + Send + Sync>;
type ErrorCallback = Arc<dyn Fn(&str, &str, &str) + Send + Sync>;
type EventCallback = Arc<dyn Fn(&str, Option<&Value>) + Send + Sync>;
type GapCallback = Arc<dyn Fn(&str, u64, u64) + Send + Sync>;

#[derive(Clone)]
struct SubscriptionRecord {
    path: String,
    depth: i32,
}

// ---------------------------------------------------------------------------
// Transport trait
// ---------------------------------------------------------------------------

/// Client transport — implementors provide a pair of unbounded channels upon
/// connection.  The consumer sends JSON messages to the provider via the
/// sender and receives messages via the receiver.
pub trait ClientTransport: Send + Sync {
    /// Establish a connection, returning `(sender, receiver)`.
    fn connect(&self) -> ConnectFuture;
}

// ---------------------------------------------------------------------------
// Consumer
// ---------------------------------------------------------------------------

/// A SLOP consumer that connects to a provider, maintains local state mirrors,
/// and exposes subscribe / query / invoke operations.
///
/// All public methods are `&self` — interior mutability via `Arc<Mutex<..>>`.
pub struct SlopConsumer {
    inner: Arc<Mutex<ConsumerInner>>,
}

struct ConsumerInner {
    sender: Option<mpsc::UnboundedSender<Value>>,
    mirrors: HashMap<String, StateMirror>,
    subscriptions: HashMap<String, SubscriptionRecord>,
    pending: HashMap<String, oneshot::Sender<Value>>,
    sub_counter: u32,
    req_counter: u32,
    patch_callbacks: Vec<PatchCallback>,
    disconnect_callbacks: Vec<DisconnectCallback>,
    error_callbacks: Vec<ErrorCallback>,
    event_callbacks: Vec<EventCallback>,
    gap_callbacks: Vec<GapCallback>,
}

impl SlopConsumer {
    /// Create a new, disconnected consumer.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(ConsumerInner {
                sender: None,
                mirrors: HashMap::new(),
                subscriptions: HashMap::new(),
                pending: HashMap::new(),
                sub_counter: 0,
                req_counter: 0,
                patch_callbacks: Vec::new(),
                disconnect_callbacks: Vec::new(),
                error_callbacks: Vec::new(),
                event_callbacks: Vec::new(),
                gap_callbacks: Vec::new(),
            })),
        }
    }

    /// Connect to a provider using the given transport.
    ///
    /// Returns the `hello` message from the provider.
    pub async fn connect(&self, transport: &dyn ClientTransport) -> Result<Value> {
        let (tx, mut rx) = transport.connect().await?;

        {
            let mut inner = self.inner.lock().await;
            inner.sender = Some(tx);
        }

        // Wait for the hello message.
        let hello = rx
            .recv()
            .await
            .ok_or(SlopError::ConnectionClosed)?;

        // Spawn the read loop.
        let inner_ref = Arc::clone(&self.inner);
        tokio::spawn(async move {
            while let Some(msg) = rx.recv().await {
                Self::dispatch(Arc::clone(&inner_ref), msg).await;
            }
            // Connection closed — fire disconnect callbacks.
            let inner = inner_ref.lock().await;
            for cb in &inner.disconnect_callbacks {
                cb();
            }
        });

        Ok(hello)
    }

    /// Subscribe to a path and receive the initial snapshot.
    ///
    /// Returns `(subscription_id, tree)`.
    pub async fn subscribe(&self, path: &str, depth: i32) -> Result<(String, SlopNode)> {
        let (sub_id, rx) = {
            let mut inner = self.inner.lock().await;
            inner.sub_counter += 1;
            let sub_id = format!("sub-{}", inner.sub_counter);
            let (tx, rx) = oneshot::channel();
            inner.pending.insert(sub_id.clone(), tx);
            inner.subscriptions.insert(
                sub_id.clone(),
                SubscriptionRecord {
                    path: path.to_string(),
                    depth,
                },
            );
            self.send_inner(
                &inner,
                json!({
                    "type": "subscribe",
                    "id": sub_id,
                    "path": path,
                    "depth": depth,
                }),
            )?;
            (sub_id, rx)
        };

        let snapshot = rx.await.map_err(|_| SlopError::ConnectionClosed)?;
        let version = snapshot["version"].as_u64().unwrap_or(0);
        let seq = snapshot["seq"].as_u64().unwrap_or(0);
        let tree: SlopNode =
            serde_json::from_value(snapshot["tree"].clone()).map_err(SlopError::Serialization)?;

        {
            let mut inner = self.inner.lock().await;
            inner.mirrors.insert(
                sub_id.clone(),
                StateMirror::new_with_seq(tree.clone(), version, seq),
            );
        }

        Ok((sub_id, tree))
    }

    /// Unsubscribe from a subscription.
    pub async fn unsubscribe(&self, id: &str) {
        let mut inner = self.inner.lock().await;
        inner.mirrors.remove(id);
        inner.subscriptions.remove(id);
        let _ = self.send_inner(
            &inner,
            json!({"type": "unsubscribe", "id": id}),
        );
    }

    /// One-shot query of the tree at a path.
    pub async fn query(&self, path: &str, depth: i32) -> Result<SlopNode> {
        let rx = {
            let mut inner = self.inner.lock().await;
            inner.req_counter += 1;
            let req_id = format!("q-{}", inner.req_counter);
            let (tx, rx) = oneshot::channel();
            inner.pending.insert(req_id.clone(), tx);
            self.send_inner(
                &inner,
                json!({
                    "type": "query",
                    "id": req_id,
                    "path": path,
                    "depth": depth,
                }),
            )?;
            rx
        };

        let snapshot = rx.await.map_err(|_| SlopError::ConnectionClosed)?;
        let tree: SlopNode =
            serde_json::from_value(snapshot["tree"].clone()).map_err(SlopError::Serialization)?;
        Ok(tree)
    }

    /// Invoke an action on the provider.
    pub async fn invoke(
        &self,
        path: &str,
        action: &str,
        params: Option<Value>,
    ) -> Result<Value> {
        let rx = {
            let mut inner = self.inner.lock().await;
            inner.req_counter += 1;
            let req_id = format!("inv-{}", inner.req_counter);
            let (tx, rx) = oneshot::channel();
            inner.pending.insert(req_id.clone(), tx);
            let mut msg = json!({
                "type": "invoke",
                "id": req_id,
                "path": path,
                "action": action,
            });
            if let Some(p) = params {
                msg["params"] = p;
            }
            self.send_inner(&inner, msg)?;
            rx
        };

        let result = rx.await.map_err(|_| SlopError::ConnectionClosed)?;
        if result["status"] == "error" {
            return Err(SlopError::ActionFailed {
                code: result["error"]["code"]
                    .as_str()
                    .unwrap_or("unknown")
                    .to_string(),
                message: result["error"]["message"]
                    .as_str()
                    .unwrap_or("unknown error")
                    .to_string(),
            });
        }
        Ok(result)
    }

    /// Get a clone of the current tree for a subscription.
    pub async fn tree(&self, subscription_id: &str) -> Option<SlopNode> {
        let inner = self.inner.lock().await;
        inner
            .mirrors
            .get(subscription_id)
            .map(|m| m.tree().clone())
    }

    /// Disconnect from the provider.
    pub async fn disconnect(&self) {
        let mut inner = self.inner.lock().await;
        inner.sender = None;
        inner.mirrors.clear();
        inner.subscriptions.clear();
        inner.pending.clear();
    }

    /// Register a callback for patch events.
    pub async fn on_patch<F>(&self, callback: F)
    where
        F: Fn(&str, &[PatchOp], u64) + Send + Sync + 'static,
    {
        let mut inner = self.inner.lock().await;
        inner.patch_callbacks.push(Arc::new(callback));
    }

    /// Register a callback for disconnect events.
    pub async fn on_disconnect<F>(&self, callback: F)
    where
        F: Fn() + Send + Sync + 'static,
    {
        let mut inner = self.inner.lock().await;
        inner.disconnect_callbacks.push(Arc::new(callback));
    }

    /// Register a callback for error messages.
    ///
    /// The callback receives `(id, error_code, error_message)`.
    pub async fn on_error<F>(&self, callback: F)
    where
        F: Fn(&str, &str, &str) + Send + Sync + 'static,
    {
        let mut inner = self.inner.lock().await;
        inner.error_callbacks.push(Arc::new(callback));
    }

    /// Register a callback for event messages.
    ///
    /// The callback receives `(event_name, optional_data)`.
    pub async fn on_event<F>(&self, callback: F)
    where
        F: Fn(&str, Option<&Value>) + Send + Sync + 'static,
    {
        let mut inner = self.inner.lock().await;
        inner.event_callbacks.push(Arc::new(callback));
    }

    /// Register a callback invoked when a per-subscription seq gap is
    /// detected and the consumer has initiated unsubscribe+resubscribe
    /// recovery. The callback receives `(subscription_id, expected, received)`.
    pub async fn on_gap<F>(&self, callback: F)
    where
        F: Fn(&str, u64, u64) + Send + Sync + 'static,
    {
        let mut inner = self.inner.lock().await;
        inner.gap_callbacks.push(Arc::new(callback));
    }

    // -- internals --

    fn send_inner(
        &self,
        inner: &ConsumerInner,
        msg: Value,
    ) -> Result<()> {
        inner
            .sender
            .as_ref()
            .ok_or(SlopError::ConnectionClosed)?
            .send(msg)
            .map_err(|e| SlopError::Transport(e.to_string()))
    }

    async fn dispatch(inner: Arc<Mutex<ConsumerInner>>, msg: Value) {
        let msg_type = msg["type"].as_str().unwrap_or("");
        let msg_id = msg["id"].as_str().unwrap_or("").to_string();

        match msg_type {
            "snapshot" => {
                // Resolve the pending request if any.
                let mut locked = inner.lock().await;
                if let Some(tx) = locked.pending.remove(&msg_id) {
                    let _ = tx.send(msg.clone());
                }
                // If we have a mirror for this subscription, update it.
                if let Some(mirror) = locked.mirrors.get_mut(&msg_id) {
                    let version = msg["version"].as_u64().unwrap_or(0);
                    let seq = msg["seq"].as_u64().unwrap_or(0);
                    if let Ok(tree) = serde_json::from_value::<SlopNode>(msg["tree"].clone()) {
                        *mirror = StateMirror::new_with_seq(tree, version, seq);
                    }
                }
            }
            "patch" => {
                let sub_id = msg["subscription"].as_str().unwrap_or(&msg_id).to_string();
                let version = msg["version"].as_u64().unwrap_or(0);
                let seq_opt = msg["seq"].as_u64();
                let ops: Vec<PatchOp> = msg["ops"]
                    .as_array()
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| serde_json::from_value(v.clone()).ok())
                            .collect()
                    })
                    .unwrap_or_default();

                let mut locked = inner.lock().await;
                let mut gap: Option<(u64, u64)> = None;
                if let Some(mirror) = locked.mirrors.get_mut(&sub_id) {
                    match seq_opt {
                        Some(seq) => match mirror.apply_patch_with_seq(&ops, version, seq) {
                            Ok(()) => {}
                            Err(err) => {
                                gap = Some((err.expected, err.received));
                            }
                        },
                        None => {
                            mirror.apply_patch(&ops, version);
                        }
                    }
                }

                if let Some((expected, received)) = gap {
                    // Spec: consumer MUST unsubscribe + fresh-subscribe to recover.
                    locked.mirrors.remove(&sub_id);
                    let sub = locked.subscriptions.get(&sub_id).cloned();
                    let _ = locked
                        .sender
                        .as_ref()
                        .map(|tx| tx.send(json!({"type": "unsubscribe", "id": &sub_id})));
                    if let Some(sub) = sub {
                        let _ = locked.sender.as_ref().map(|tx| {
                            tx.send(json!({
                                "type": "subscribe",
                                "id": &sub_id,
                                "path": sub.path,
                                "depth": sub.depth,
                            }))
                        });
                    }
                    let callbacks: Vec<_> = locked.gap_callbacks.clone();
                    drop(locked);
                    for cb in &callbacks {
                        cb(&sub_id, expected, received);
                    }
                    return;
                }

                // Fire patch callbacks.
                let callbacks: Vec<_> = locked.patch_callbacks.clone();
                drop(locked);
                for cb in &callbacks {
                    cb(&sub_id, &ops, version);
                }
            }
            "result" => {
                let mut locked = inner.lock().await;
                if let Some(tx) = locked.pending.remove(&msg_id) {
                    let _ = tx.send(msg);
                }
            }
            "error" => {
                let mut locked = inner.lock().await;
                let code = msg["error"]["code"].as_str().unwrap_or("unknown");
                let message = msg["error"]["message"].as_str().unwrap_or("");

                // If this error correlates with a pending request, resolve it
                if !msg_id.is_empty() {
                    if let Some(tx) = locked.pending.remove(&msg_id) {
                        let _ = tx.send(msg.clone());
                    }
                }

                let callbacks: Vec<_> = locked.error_callbacks.clone();
                drop(locked);
                for cb in &callbacks {
                    cb(&msg_id, code, message);
                }
            }
            "event" => {
                let locked = inner.lock().await;
                let name = msg["name"].as_str().unwrap_or("");
                let data = msg.get("data");
                let callbacks: Vec<_> = locked.event_callbacks.clone();
                drop(locked);
                for cb in &callbacks {
                    cb(name, data);
                }
            }
            "batch" => {
                if let Some(messages) = msg["messages"].as_array() {
                    for sub_msg in messages {
                        Box::pin(Self::dispatch(Arc::clone(&inner), sub_msg.clone())).await;
                    }
                }
            }
            _ => {}
        }
    }
}

impl Default for SlopConsumer {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::sync::atomic::{AtomicBool, Ordering};

    /// A mock transport that uses in-memory channels.
    struct MockTransport {
        /// Messages the "provider" will send to the consumer.
        provider_messages: Vec<Value>,
    }

    impl ClientTransport for MockTransport {
        fn connect(
            &self,
        ) -> Pin<
            Box<
                dyn Future<
                        Output = Result<(
                            mpsc::UnboundedSender<Value>,
                            mpsc::UnboundedReceiver<Value>,
                        )>,
                    > + Send,
            >,
        > {
            let messages = self.provider_messages.clone();
            Box::pin(async move {
                let (consumer_tx, _consumer_rx) = mpsc::unbounded_channel();
                let (provider_tx, provider_rx) = mpsc::unbounded_channel();

                // Send all provider messages.
                for msg in messages {
                    provider_tx.send(msg).unwrap();
                }

                Ok((consumer_tx, provider_rx))
            })
        }
    }

    #[tokio::test]
    async fn test_connect_hello() {
        let transport = MockTransport {
            provider_messages: vec![json!({
                "type": "hello",
                "provider": {"id": "app", "name": "App", "slop_version": "0.1"}
            })],
        };

        let consumer = SlopConsumer::new();
        let hello = consumer.connect(&transport).await.unwrap();
        assert_eq!(hello["type"], "hello");
        assert_eq!(hello["provider"]["id"], "app");
    }

    #[tokio::test]
    async fn test_disconnect_callback() {
        let called = Arc::new(AtomicBool::new(false));
        let called_clone = called.clone();

        let consumer = SlopConsumer::new();
        consumer
            .on_disconnect(move || {
                called_clone.store(true, Ordering::SeqCst);
            })
            .await;

        // The callback is registered.
        let inner = consumer.inner.lock().await;
        assert_eq!(inner.disconnect_callbacks.len(), 1);
    }

    #[tokio::test]
    async fn test_patch_callback() {
        let consumer = SlopConsumer::new();
        let patch_count = Arc::new(std::sync::atomic::AtomicU32::new(0));
        let pc = patch_count.clone();
        consumer
            .on_patch(move |_sub, _ops, _v| {
                pc.fetch_add(1, Ordering::SeqCst);
            })
            .await;

        let inner = consumer.inner.lock().await;
        assert_eq!(inner.patch_callbacks.len(), 1);
    }

    #[tokio::test]
    async fn test_new_default() {
        let c1 = SlopConsumer::new();
        let c2 = SlopConsumer::default();
        let inner1 = c1.inner.lock().await;
        let inner2 = c2.inner.lock().await;
        assert!(inner1.sender.is_none());
        assert!(inner2.sender.is_none());
    }
}