lamarge 0.9.0

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
use std::time::Duration;

use alloy_primitives::address;

use super::*;

const SIGNER: Address = address!("0x2C7536E3605D9C16a7a3D7b1898e529396a65c23");
const OTHER: Address = address!("0x00000000000000000000000000000000000000aa");

#[tokio::test]
async fn memory_store_semantics() {
    let store = MemoryStore::new();
    assert_eq!(store.load("k").await.unwrap(), None);
    store.save("k", b"one").await.unwrap();
    store.save("k", b"two").await.unwrap();
    assert_eq!(store.load("k").await.unwrap().as_deref(), Some(&b"two"[..]));
    store.delete("k").await.unwrap();
    store.delete("k").await.unwrap();
    assert_eq!(store.load("k").await.unwrap(), None);
}

#[test]
fn keys_are_namespaced_by_environment_and_signer() {
    let key = scoped_key(EscrowEnvironment::Production, SIGNER, "withdrawal:w-1");
    assert_eq!(key, "production/0x2c7536e3605d9c16a7a3d7b1898e529396a65c23/withdrawal:w-1");
    let keys = [
        key,
        scoped_key(EscrowEnvironment::Development, SIGNER, "withdrawal:w-1"),
        scoped_key(EscrowEnvironment::Production, OTHER, "withdrawal:w-1"),
    ];
    assert_ne!(keys[0], keys[1]);
    assert_ne!(keys[0], keys[2]);
}

#[tokio::test]
async fn same_record_under_two_namespaces_gives_two_records() {
    let dir = tempfile::tempdir().unwrap();
    let journal = Journal::new(FileStore::open(dir.path()).unwrap());
    let production = scoped_key(EscrowEnvironment::Production, SIGNER, "withdrawal:w");
    let development = scoped_key(EscrowEnvironment::Development, SIGNER, "withdrawal:w");
    journal.save(&production, b"p").await.unwrap();
    journal.save(&development, b"d").await.unwrap();
    assert_eq!(journal.load(&production).await.unwrap().as_deref(), Some(&b"p"[..]));
    assert_eq!(journal.load(&development).await.unwrap().as_deref(), Some(&b"d"[..]));
    journal.delete(&production).await.unwrap();
    assert_eq!(journal.load(&production).await.unwrap(), None);
    assert_eq!(journal.load(&development).await.unwrap().as_deref(), Some(&b"d"[..]));
}

#[tokio::test]
async fn journal_clones_share_key_locks() {
    let journal = Journal::new(MemoryStore::new());
    let other = journal.clone();
    let held = journal.lock("withdrawal:w").await;
    let waiting = tokio::spawn(async move {
        let _guard = other.lock("withdrawal:w").await;
    });
    tokio::time::sleep(Duration::from_millis(50)).await;
    assert!(!waiting.is_finished(), "a clone must wait for the held key");
    // Another key is independent.
    tokio::time::timeout(Duration::from_secs(1), journal.lock("withdrawal:x")).await.unwrap();
    drop(held);
    tokio::time::timeout(Duration::from_secs(1), waiting).await.unwrap().unwrap();
}

#[tokio::test]
async fn unused_locks_are_dropped() {
    let locks = KeyedLocks::default();
    drop(locks.lock("a").await);
    drop(locks.lock("b").await);
    let map = locks.locks.lock().unwrap();
    assert!(map.len() <= 1, "dead entries are pruned when a new key is locked");
    assert!(map.values().all(|lock| lock.strong_count() == 0));
}

#[tokio::test]
async fn file_store_round_trip_with_digest_names() {
    let dir = tempfile::tempdir().unwrap();
    let store = FileStore::open(dir.path()).unwrap();
    store.save("take:1", b"{\"v\":1}").await.unwrap();
    let name = hex::encode(keccak256("take:1"));
    assert!(dir.path().join(&name).is_file());
    assert!(!dir.path().join(format!("{name}.tmp")).exists(), "no temporary file left");
    assert_eq!(store.load("take:1").await.unwrap().as_deref(), Some(&b"{\"v\":1}"[..]));
    store.save("take:1", b"").await.unwrap();
    assert_eq!(store.load("take:1").await.unwrap().as_deref(), Some(&b""[..]));
    store.delete("take:1").await.unwrap();
    assert_eq!(store.load("take:1").await.unwrap(), None);
    store.delete("take:1").await.unwrap();
}

#[tokio::test]
async fn file_store_handles_maximum_length_ids_in_both_environments() {
    let dir = tempfile::tempdir().unwrap();
    let id = "a".repeat(64);
    let keys = [EscrowEnvironment::Production, EscrowEnvironment::Development]
        .map(|environment| scoped_key(environment, SIGNER, &format!("withdrawal:{id}")));
    {
        let store = FileStore::open(dir.path()).unwrap();
        for key in &keys {
            store.save(key, key.as_bytes()).await.unwrap();
        }
    }
    let store = FileStore::open(dir.path()).unwrap();
    for key in &keys {
        assert_eq!(store.load(key).await.unwrap().as_deref(), Some(key.as_bytes()));
        store.delete(key).await.unwrap();
        assert_eq!(store.load(key).await.unwrap(), None);
    }
}

#[test]
fn second_open_fails_while_the_first_lives() {
    let dir = tempfile::tempdir().unwrap();
    let first = FileStore::open(dir.path()).unwrap();
    let error = FileStore::open(dir.path()).unwrap_err();
    let Error::Store(error) = error else { panic!("expected a store error, got {error:?}") };
    assert!(!error.submitted());
    drop(first);
    FileStore::open(dir.path()).unwrap();
}

/// A save whose future is dropped while its blocking write is stalled; returns the release.
async fn stalled_save(store: &FileStore, key: &str, value: &[u8]) -> std::sync::mpsc::Sender<()> {
    let (entered_tx, entered_rx) = tokio::sync::oneshot::channel();
    let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
    *store.inner.before_write.lock().unwrap() = Some(Box::new(move || {
        entered_tx.send(()).unwrap();
        release_rx.recv().unwrap();
    }));
    let save = store.save(key, value);
    tokio::select! {
        result = save => panic!("the stalled save completed: {result:?}"),
        entered = entered_rx => entered.unwrap(),
    }
    // `save` is dropped here; its blocking write is still running.
    release_tx
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn dropped_save_cannot_overwrite_a_later_save() {
    let dir = tempfile::tempdir().unwrap();
    let store = Arc::new(FileStore::open(dir.path()).unwrap());
    let release = stalled_save(&store, "k", b"stale").await;
    let retry = tokio::spawn({
        let store = Arc::clone(&store);
        async move { store.save("k", b"retry").await }
    });
    tokio::time::sleep(Duration::from_millis(50)).await;
    assert!(!retry.is_finished(), "the retry waits for the dropped write");
    release.send(()).unwrap();
    retry.await.unwrap().unwrap();
    assert_eq!(store.load("k").await.unwrap().as_deref(), Some(&b"retry"[..]));
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn load_after_a_dropped_save_observes_it() {
    let dir = tempfile::tempdir().unwrap();
    let store = Arc::new(FileStore::open(dir.path()).unwrap());
    let release = stalled_save(&store, "k", b"first").await;
    let load = tokio::spawn({
        let store = Arc::clone(&store);
        async move { store.load("k").await }
    });
    tokio::time::sleep(Duration::from_millis(50)).await;
    release.send(()).unwrap();
    assert_eq!(load.await.unwrap().unwrap().as_deref(), Some(&b"first"[..]));
}

#[test]
fn shared_types_are_send_sync_and_futures_send() {
    fn check<T: Send + Sync + 'static>() {}
    fn send<T: Send>(_: T) {}
    let journal = Journal::new(MemoryStore::new());
    send(journal.lock("k"));
    send(journal.save("k", b"v"));
    check::<Journal>();
    check::<MemoryStore>();
    check::<FileStore>();
}