amaters-sdk-rust 0.2.1

Rust SDK for AmateRS
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
//! Transaction support for AmateRS SDK.
//!
//! A `Transaction` buffers SET and DELETE operations locally and issues a
//! single atomic `execute_batch` RPC on `commit()`.  `rollback()` discards
//! the buffer without any network call.
//!
//! ## Cache note
//!
//! `AmateRSClient::execute_batch` does not invalidate the query cache (consistent
//! with the rest of `execute_batch` usage in this crate).  If the client has a
//! cache enabled, committing a transaction may leave stale entries for the keys
//! that were written.  Callers that require strict read-your-writes guarantees
//! should either disable the cache or call `client.cache().map(|c| c.invalidate(...))`
//! manually after commit.

use crate::client::AmateRSClient;
use crate::error::{Result, SdkError};
use amaters_core::{CipherBlob, Key, Query};
use std::sync::Arc;

// ---------------------------------------------------------------------------
// Internal state / operation types
// ---------------------------------------------------------------------------

/// Lifecycle state of a [`Transaction`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TransactionState {
    Active,
    Committed,
    RolledBack,
}

/// A single buffered write operation.
#[derive(Debug, Clone)]
enum TransactionOp {
    Set { key: Key, value: CipherBlob },
    Delete { key: Key },
}

// ---------------------------------------------------------------------------
// Public Transaction type
// ---------------------------------------------------------------------------

/// A buffered, commit-or-rollback transaction over [`AmateRSClient`].
///
/// All writes are staged locally in a `Vec<TransactionOp>` until `commit()` is
/// called.  `commit()` issues a single `execute_batch` RPC so the writes are
/// applied atomically.  `rollback()` discards the local buffer with no network
/// call.
///
/// ## Reading inside a transaction
///
/// [`Transaction::get`] first inspects the local buffer using last-write-wins
/// semantics (reverse scan).  A buffered `Delete` for the queried key returns
/// `Ok(None)`.  If the key has not been written in this transaction the call
/// falls through to the server.
///
/// ## Drop behaviour
///
/// Dropping a transaction that is still `Active` and has un-committed
/// operations emits a `tracing::warn!` message.  The buffer is silently
/// discarded (no rollback RPC is issued — rollback is always local).
///
/// ## Construction
///
/// Prefer the factory method [`AmateRSClient::transaction`] over constructing
/// directly.
pub struct Transaction {
    collection: String,
    ops: Vec<TransactionOp>,
    client: Arc<AmateRSClient>,
    state: TransactionState,
}

impl Transaction {
    /// Create a new transaction bound to `collection`.
    ///
    /// Use [`AmateRSClient::transaction`] instead of calling this directly.
    pub fn new(client: Arc<AmateRSClient>, collection: impl Into<String>) -> Self {
        Self {
            collection: collection.into(),
            ops: Vec::new(),
            client,
            state: TransactionState::Active,
        }
    }

    // -----------------------------------------------------------------------
    // Write staging
    // -----------------------------------------------------------------------

    /// Stage a SET operation into the local buffer.
    ///
    /// The write is not applied to the server until [`Self::commit`] is called.
    ///
    /// # Errors
    ///
    /// Returns [`SdkError::InvalidState`] if the transaction is no longer
    /// active (already committed or rolled back).
    pub fn set(&mut self, key: Key, value: CipherBlob) -> Result<()> {
        self.ensure_active()?;
        self.ops.push(TransactionOp::Set { key, value });
        Ok(())
    }

    /// Stage a DELETE operation into the local buffer.
    ///
    /// The delete is not applied to the server until [`Self::commit`] is called.
    ///
    /// # Errors
    ///
    /// Returns [`SdkError::InvalidState`] if the transaction is no longer active.
    pub fn delete(&mut self, key: Key) -> Result<()> {
        self.ensure_active()?;
        self.ops.push(TransactionOp::Delete { key });
        Ok(())
    }

    // -----------------------------------------------------------------------
    // Read (local buffer + server fallthrough)
    // -----------------------------------------------------------------------

    /// Read a key, consulting the local buffer first (last-write-wins), then
    /// the server.
    ///
    /// * A buffered `SET` returns the in-flight value without a server round-trip.
    /// * A buffered `DELETE` returns `Ok(None)` without a server round-trip.
    /// * If the key has not been touched in this transaction, the call falls
    ///   through to `client.get()`.
    ///
    /// # Errors
    ///
    /// Returns [`SdkError::InvalidState`] if the transaction is no longer active,
    /// or any error returned by the server fall-through.
    pub async fn get(&self, key: &Key) -> Result<Option<CipherBlob>> {
        self.ensure_active()?;

        // Walk ops in reverse for the most recent write to this key.
        for op in self.ops.iter().rev() {
            match op {
                TransactionOp::Set { key: k, value: v } if k == key => {
                    return Ok(Some(v.clone()));
                }
                TransactionOp::Delete { key: k } if k == key => {
                    return Ok(None);
                }
                _ => {}
            }
        }

        // Fall through to the server.
        self.client.get(&self.collection, key).await
    }

    // -----------------------------------------------------------------------
    // Commit / rollback
    // -----------------------------------------------------------------------

    /// Commit all buffered operations atomically via `execute_batch`.
    ///
    /// On success the transaction transitions to the `Committed` state.
    /// If the batch RPC fails, the state remains `Active` so the caller can
    /// retry or roll back.
    ///
    /// An empty transaction commits instantly without a network round-trip.
    ///
    /// # Errors
    ///
    /// * [`SdkError::InvalidState`] — already committed or rolled back.
    /// * Any `SdkError` returned by the underlying `execute_batch` RPC.
    pub async fn commit(&mut self) -> Result<()> {
        self.ensure_active()?;

        if !self.ops.is_empty() {
            let queries: Vec<Query> = self
                .ops
                .drain(..)
                .map(|op| match op {
                    TransactionOp::Set { key, value } => Query::Set {
                        collection: self.collection.clone(),
                        key,
                        value,
                    },
                    TransactionOp::Delete { key } => Query::Delete {
                        collection: self.collection.clone(),
                        key,
                    },
                })
                .collect();

            self.client.execute_batch(queries).await?;
        }

        self.state = TransactionState::Committed;
        Ok(())
    }

    /// Rollback by discarding the local buffer — no network call is made.
    ///
    /// # Errors
    ///
    /// Returns [`SdkError::InvalidState`] if the transaction is already
    /// committed or rolled back.
    pub fn rollback(&mut self) -> Result<()> {
        self.ensure_active()?;
        self.ops.clear();
        self.state = TransactionState::RolledBack;
        Ok(())
    }

    // -----------------------------------------------------------------------
    // Introspection
    // -----------------------------------------------------------------------

    /// Number of operations currently staged in the local buffer.
    pub fn pending_ops(&self) -> usize {
        self.ops.len()
    }

    /// Returns `true` if the transaction is still active (not yet committed or
    /// rolled back).
    pub fn is_active(&self) -> bool {
        self.state == TransactionState::Active
    }

    /// Returns the collection name this transaction is bound to.
    pub fn collection(&self) -> &str {
        &self.collection
    }

    // -----------------------------------------------------------------------
    // Private helpers
    // -----------------------------------------------------------------------

    fn ensure_active(&self) -> Result<()> {
        if self.state != TransactionState::Active {
            Err(SdkError::InvalidState(
                "transaction already committed or rolled back".to_string(),
            ))
        } else {
            Ok(())
        }
    }
}

impl Drop for Transaction {
    fn drop(&mut self) {
        if self.state == TransactionState::Active && !self.ops.is_empty() {
            tracing::warn!(
                pending_ops = self.ops.len(),
                collection = %self.collection,
                "Transaction dropped with uncommitted operation(s) — changes discarded",
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::ClientConfig;
    use amaters_core::{CipherBlob, Key};

    /// Helper: build an offline client wrapped in Arc so Transaction::new can
    /// be called without a live server.
    fn offline_client() -> Arc<AmateRSClient> {
        let config = ClientConfig::new("http://127.0.0.1:50051");
        Arc::new(AmateRSClient::new_offline(config))
    }

    // -----------------------------------------------------------------------
    // State-machine tests (no server required)
    // -----------------------------------------------------------------------

    #[test]
    fn test_transaction_rollback_clears_buffer() {
        let client = offline_client();
        let mut tx = Transaction::new(client, "users");

        let key = Key::from_str("k1");
        let val = CipherBlob::new(vec![1, 2, 3]);
        tx.set(key, val).expect("set should succeed on active tx");
        assert_eq!(tx.pending_ops(), 1);

        tx.rollback().expect("rollback should succeed on active tx");
        assert_eq!(tx.pending_ops(), 0);
        assert!(!tx.is_active());
    }

    #[test]
    fn test_transaction_double_commit_returns_error() {
        // An empty transaction commits without a network call, so we can test
        // the state-machine offline.
        let client = offline_client();
        let mut tx = Transaction::new(client, "users");

        // First commit: no ops → fast path, no RPC.
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("failed to build runtime");

        rt.block_on(async {
            tx.commit().await.expect("first commit should succeed");

            let err = tx
                .commit()
                .await
                .expect_err("second commit should return Err");
            assert!(
                matches!(err, SdkError::InvalidState(_)),
                "expected InvalidState, got: {err}"
            );
        });
    }

    #[test]
    fn test_transaction_commit_then_rollback_is_error() {
        let client = offline_client();
        let mut tx = Transaction::new(client, "users");

        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("failed to build runtime");

        rt.block_on(async {
            tx.commit().await.expect("commit should succeed");

            let err = tx
                .rollback()
                .expect_err("rollback after commit should return Err");
            assert!(
                matches!(err, SdkError::InvalidState(_)),
                "expected InvalidState, got: {err}"
            );
        });
    }

    #[test]
    fn test_transaction_rollback_then_commit_is_error() {
        let client = offline_client();
        let mut tx = Transaction::new(client, "users");

        tx.rollback().expect("rollback should succeed on active tx");

        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .expect("failed to build runtime");

        rt.block_on(async {
            let err = tx
                .commit()
                .await
                .expect_err("commit after rollback should return Err");
            assert!(
                matches!(err, SdkError::InvalidState(_)),
                "expected InvalidState, got: {err}"
            );
        });
    }

    // -----------------------------------------------------------------------
    // Local-buffer read tests (no server required)
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_transaction_read_sees_local_set() {
        let client = offline_client();
        let mut tx = Transaction::new(client, "users");

        let key = Key::from_str("local_key");
        let val = CipherBlob::new(vec![10, 20, 30]);
        tx.set(key.clone(), val.clone())
            .expect("set should succeed");

        let result = tx.get(&key).await.expect("get should succeed (local hit)");
        assert_eq!(
            result.as_ref().map(|b| b.to_vec()),
            Some(val.to_vec()),
            "get should return the locally staged value"
        );
    }

    #[tokio::test]
    async fn test_transaction_read_sees_local_delete_as_none() {
        let client = offline_client();
        let mut tx = Transaction::new(client, "users");

        let key = Key::from_str("will_delete");
        let val = CipherBlob::new(vec![1]);
        tx.set(key.clone(), val).expect("set should succeed");
        tx.delete(key.clone()).expect("delete should succeed");

        let result = tx
            .get(&key)
            .await
            .expect("get should succeed (local delete hit)");
        assert!(
            result.is_none(),
            "locally deleted key should appear as None"
        );
    }

    #[tokio::test]
    async fn test_transaction_read_last_write_wins() {
        let client = offline_client();
        let mut tx = Transaction::new(client, "users");

        let key = Key::from_str("overwritten");
        let v1 = CipherBlob::new(vec![1]);
        let v2 = CipherBlob::new(vec![2]);
        tx.set(key.clone(), v1).expect("first set");
        tx.set(key.clone(), v2.clone()).expect("second set");

        let result = tx.get(&key).await.expect("get should succeed");
        assert_eq!(
            result.as_ref().map(|b| b.to_vec()),
            Some(v2.to_vec()),
            "last write should win"
        );
    }

    // -----------------------------------------------------------------------
    // Drop / tracing tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_transaction_empty_drop_no_warn() {
        // An empty transaction dropped while Active should NOT emit a warning.
        // We cannot assert "no log was emitted" without tracing-test, but we
        // can at least verify the Drop impl path is exercised without panic.
        let client = offline_client();
        let tx = Transaction::new(client, "noop");
        drop(tx); // should not panic or warn
    }

    #[tracing_test::traced_test]
    #[test]
    fn test_transaction_drop_warns_uncommitted() {
        let client = offline_client();
        let mut tx = Transaction::new(client, "events");

        let key = Key::from_str("pending");
        let val = CipherBlob::new(vec![0xFF]);
        tx.set(key, val).expect("set should succeed");

        // Drop without commit/rollback — should trigger the warn! in Drop.
        drop(tx);

        assert!(
            logs_contain("Transaction dropped with uncommitted operation(s)"),
            "expected a tracing warn about uncommitted ops"
        );
    }
}