foundation_db 0.0.4

Unified storage backend with Turso sync API, D1, R2, and in-memory fallback
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
//! KV storage via wasm-bindgen — calls Cloudflare KV JS API directly.
//!
//! Wraps `KVNamespace` and implements `KeyValueStore` and `RateLimiterStore`
//! using Cloudflare Workers KV. Async `*_async` methods are the source of truth
//! (JS Promises); sync trait methods delegate via `schedule_future`.

use crate::core::errors::{StorageError, StorageResult};
use crate::core::storage_provider::{
    AsyncBlobStore, AsyncKeyValueStore, AsyncListStream, AsyncRateLimiterStore, BlobStore,
    DataValue, KeyValueStore, QueryStore, RateLimiterStore, SqlRow, StorageItemStream,
};
use crate::wasm::bindgen::KVNamespace;
use foundation_core::valtron::{collect_one, execute, from_future, Stream};
use js_sys::Object;
use wasm_bindgen::JsCast;
use wasm_bindgen_futures::JsFuture;
use foundation_compact::SendWrapper;


/// One-shot blocking bridge for init/migrations.
fn exec_future<T: 'static, E: Into<StorageError> + 'static, F>(future: F) -> StorageResult<T>
where
    F: std::future::Future<Output = Result<T, E>> + 'static,
{
    let task = from_future(future);
    let stream = execute(task, None)
        .map_err(|e| StorageError::Backend(format!("Valtron execution failed: {e}")))?;
    let result: Result<Option<T>, StorageError> = collect_one(stream)
        .map(|r| r.map_err(Into::into))
        .transpose();
    result?.ok_or_else(|| StorageError::Generic("No result from future execution".into()))
}

// ===========================================================================
// KVWasmStorage
// ===========================================================================

/// KV storage backend using wasm-bindgen JS bindings.
#[derive(Clone)]
pub struct KVWasmStorage {
    kv: KVNamespace,
    prefix: String,
}

impl KVWasmStorage {
    /// Create a new KV storage instance.
    #[must_use]
    pub fn new(kv: KVNamespace, prefix: &str) -> Self {
        Self {
            kv,
            prefix: prefix.to_string(),
        }
    }

    fn prefixed_key(&self, key: &str) -> String {
        format!("{}:{}", self.prefix, key)
    }

    #[allow(dead_code)]
    fn stream_once<T: Send + 'static>(val: T) -> StorageItemStream<'static, T> {
        Box::new(std::iter::once(Stream::Next(Ok(val))))
    }

    fn stream_many<T: Send + 'static>(vals: Vec<T>) -> StorageItemStream<'static, T> {
        Box::new(vals.into_iter().map(|v| Stream::Next(Ok(v))))
    }
}

// ===========================================================================
// KeyValueStore
// ===========================================================================

impl KeyValueStore for KVWasmStorage {
    fn get<'a, V: serde::de::DeserializeOwned + Send + 'static>(
        &self,
        key: &str,
    ) -> StorageResult<Option<V>> {
        let this = self.clone();
        let key = key.to_string();
        exec_future(async move {
            this.get_async::<V>(&key).await
        })
    }

    fn set<V: serde::Serialize + Send + 'static>(&self, key: &str, value: V) -> StorageResult<()> {
        let this = self.clone();
        let key = key.to_string();
        exec_future(async move {
            this.set_async(&key, value).await
        })
    }

    fn delete(&self, key: &str) -> StorageResult<()> {
        let this = self.clone();
        let key = key.to_string();
        exec_future(async move {
            this.delete_async(&key).await
        })
    }

    fn exists(&self, key: &str) -> StorageResult<bool> {
        let this = self.clone();
        let key = key.to_string();
        exec_future(async move {
            this.exists_async(&key).await
        })
    }

    fn list_keys(&self, prefix: Option<&str>) -> StorageResult<StorageItemStream<'_, String>> {
        let this = self.clone();
        let prefix = prefix.map(String::from);
        let keys = exec_future(async move {
            this.list_keys_async(prefix.as_deref()).await
        })?;
        Ok(Self::stream_many(keys))
    }
}

impl KVWasmStorage {
    /// Get a value by key.
    pub async fn get_async<V: serde::de::DeserializeOwned + Send + 'static>(
        &self,
        key: &str,
    ) -> Result<Option<V>, StorageError> {
        let prefixed = self.prefixed_key(key);
        let promise = self.kv.get(&prefixed);
        let result = SendWrapper::new(JsFuture::from(promise))
            .await
            .map_err(|e| StorageError::Backend(format!("KV get failed: {e:?}")))?;

        if result.is_null() || result.is_undefined() {
            return Ok(None);
        }

        let value = result.as_string().ok_or_else(|| {
            StorageError::Serialization("KV value is not a string".to_string())
        })?;

        let deserialized: V = serde_json::from_str(&value)
            .map_err(|e| StorageError::Serialization(e.to_string()))?;

        Ok(Some(deserialized))
    }

    /// Set a key-value pair.
    pub async fn set_async<V: serde::Serialize>(
        &self,
        key: &str,
        value: V,
    ) -> Result<(), StorageError> {
        let prefixed = self.prefixed_key(key);
        let json = serde_json::to_string(&value)
            .map_err(|e| StorageError::Serialization(e.to_string()))?;

        let value_js = wasm_bindgen::JsValue::from_str(&json);
        let promise = self.kv.put(&prefixed, &value_js);
        SendWrapper::new(JsFuture::from(promise))
            .await
            .map_err(|e| StorageError::Backend(format!("KV put failed: {e:?}")))?;

        Ok(())
    }

    /// Delete a key.
    pub async fn delete_async(&self, key: &str) -> Result<(), StorageError> {
        let prefixed = self.prefixed_key(key);
        let promise = self.kv.delete(&prefixed);
        SendWrapper::new(JsFuture::from(promise))
            .await
            .map_err(|e| StorageError::Backend(format!("KV delete failed: {e:?}")))?;

        Ok(())
    }

    /// Check if a key exists.
    pub async fn exists_async(&self, key: &str) -> Result<bool, StorageError> {
        let prefixed = self.prefixed_key(key);
        let promise = self.kv.get(&prefixed);
        let result = SendWrapper::new(JsFuture::from(promise))
            .await
            .map_err(|e| StorageError::Backend(format!("KV get failed: {e:?}")))?;

        Ok(!result.is_null() && !result.is_undefined())
    }

    /// List all keys with optional prefix filter.
    pub async fn list_keys_async(&self, prefix: Option<&str>) -> Result<Vec<String>, StorageError> {
        // KV list returns { keys: [{name: "..."}], cursor: "..." }
        let opts = Object::new();

        if let Some(p) = prefix {
            js_sys::Reflect::set(&opts, &"prefix".into(), &wasm_bindgen::JsValue::from_str(p))
                .map_err(|e| StorageError::Backend(format!("KV list opts failed: {e:?}")))?;
        }

        let promise = self.kv.list(&opts.into());
        let result = SendWrapper::new(JsFuture::from(promise))
            .await
            .map_err(|e| StorageError::Backend(format!("KV list failed: {e:?}")))?;

        let obj = result.dyn_into::<js_sys::Object>().map_err(|_| {
            StorageError::Backend("KV list returned non-object".to_string())
        })?;

        let keys_arr = js_sys::Reflect::get(&obj, &"keys".into())
            .ok()
            .and_then(|v| v.dyn_into::<js_sys::Array>().ok())
            .unwrap_or_default();

        let mut keys = Vec::new();
        for i in 0..keys_arr.length() {
            let entry = keys_arr.get(i);
            if let Ok(entry_obj) = entry.dyn_into::<js_sys::Object>() {
                if let Some(name) = js_sys::Reflect::get(&entry_obj, &"name".into())
                    .ok()
                    .and_then(|v| v.as_string())
                {
                    // Strip prefix to return clean key
                    let clean_key = name.strip_prefix(&format!("{}:", self.prefix))
                        .unwrap_or(&name)
                        .to_string();
                    keys.push(clean_key);
                }
            }
        }

        Ok(keys)
    }
}

#[async_trait::async_trait]
impl AsyncKeyValueStore for KVWasmStorage {
    async fn get_async<V: serde::de::DeserializeOwned + Send + 'static>(&self, key: &str) -> StorageResult<Option<V>> {
        foundation_compact::SendWrapper::new(async move { self.get_async(key).await }).await
    }

    async fn set_async<V: serde::Serialize + Send + 'static>(&self, key: &str, value: V) -> StorageResult<()> {
        foundation_compact::SendWrapper::new(async move { self.set_async(key, value).await }).await
    }

    async fn delete_async(&self, key: &str) -> StorageResult<()> {
        foundation_compact::SendWrapper::new(async move { self.delete_async(key).await }).await
    }

    async fn exists_async(&self, key: &str) -> StorageResult<bool> {
        foundation_compact::SendWrapper::new(async move { self.exists_async(key).await }).await
    }

    async fn list_keys_async(&self, prefix: Option<&str>) -> StorageResult<AsyncListStream> {
        let keys = foundation_compact::SendWrapper::new(async move {
            self.list_keys_async(prefix).await
        }).await?;
        Ok(AsyncListStream::new(futures_lite::stream::iter(
            keys.into_iter().map(Ok),
        )))
    }
}

// ===========================================================================
// QueryStore (not supported for KV)
// ===========================================================================

impl QueryStore for KVWasmStorage {
    fn query(
        &self,
        _sql: &str,
        _params: &[DataValue],
    ) -> StorageResult<StorageItemStream<'_, SqlRow>> {
        Err(StorageError::Generic(
            "QueryStore not supported for KVWasmStorage".to_string(),
        ))
    }

    fn execute(
        &self,
        _sql: &str,
        _params: &[DataValue],
    ) -> StorageResult<u64> {
        Err(StorageError::Generic(
            "QueryStore not supported for KVWasmStorage".to_string(),
        ))
    }

    fn execute_batch(&self, _sql: &str) -> StorageResult<()> {
        Err(StorageError::Generic(
            "QueryStore not supported for KVWasmStorage".to_string(),
        ))
    }
}

// ===========================================================================
// RateLimiterStore
// ===========================================================================

impl RateLimiterStore for KVWasmStorage {
    fn check_rate_limit(
        &self,
        key: &str,
        max_count: u32,
        window_seconds: u64,
    ) -> StorageResult<bool> {
        let this = self.clone();
        let key = key.to_string();
        exec_future(async move {
            this.check_rate_limit_async(&key, max_count, window_seconds).await
        })
    }

    fn record_rate_limit(&self, key: &str) -> StorageResult<u32> {
        let this = self.clone();
        let key = key.to_string();
        exec_future(async move {
            this.record_rate_limit_async(&key).await
        })
    }

    fn reset_rate_limit(&self, key: &str) -> StorageResult<()> {
        let this = self.clone();
        let key = key.to_string();
        exec_future(async move {
            this.reset_rate_limit_async(&key).await
        })
    }
}

impl KVWasmStorage {
    /// Check if a rate limit key is allowed.
    pub async fn check_rate_limit_async(
        &self,
        key: &str,
        max_count: u32,
        window_seconds: u64,
    ) -> Result<bool, StorageError> {
        let rate_key = format!("_rate_limit:{key}");

        let promise = self.kv.get(&self.prefixed_key(&rate_key));
        let result = SendWrapper::new(JsFuture::from(promise))
            .await
            .map_err(|e| StorageError::Backend(format!("KV get failed: {e:?}")))?;

        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        let allowed = if result.is_null() || result.is_undefined() {
            true
        } else {
            let json = result.as_string().ok_or_else(|| {
                StorageError::Serialization("KV rate limit value is not a string".to_string())
            })?;

            #[derive(serde::Deserialize)]
            struct Entry {
                count: u32,
                window_start: u64,
            }

            let entry: Entry = serde_json::from_str(&json)
                .map_err(|e| StorageError::Serialization(e.to_string()))?;

            if entry.window_start < now.saturating_sub(window_seconds) {
                true
            } else {
                entry.count < max_count
            }
        };

        Ok(allowed)
    }

    /// Record a rate-limited action.
    pub async fn record_rate_limit_async(&self, key: &str) -> Result<u32, StorageError> {
        let rate_key = format!("_rate_limit:{key}");
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Get current entry
        let promise = self.kv.get(&self.prefixed_key(&rate_key));
        let result = SendWrapper::new(JsFuture::from(promise))
            .await
            .map_err(|e| StorageError::Backend(format!("KV get failed: {e:?}")))?;

        let new_count = if result.is_null() || result.is_undefined() {
            1
        } else {
            let json = result.as_string().ok_or_else(|| {
                StorageError::Serialization("KV rate limit value is not a string".to_string())
            })?;

            #[derive(serde::Deserialize, serde::Serialize)]
            struct Entry {
                count: u32,
                window_start: u64,
            }

            let mut entry: Entry = serde_json::from_str(&json)
                .map_err(|e| StorageError::Serialization(e.to_string()))?;
            entry.count += 1;
            entry.window_start = now;

            // Save updated
            let new_json = serde_json::to_string(&entry)
                .map_err(|e| StorageError::Serialization(e.to_string()))?;
            let value_js = wasm_bindgen::JsValue::from_str(&new_json);
            let put_promise = self.kv.put(&self.prefixed_key(&rate_key), &value_js);
            SendWrapper::new(JsFuture::from(put_promise))
                .await
                .map_err(|e| StorageError::Backend(format!("KV put failed: {e:?}")))?;

            entry.count
        };

        if new_count == 1 {
            // First entry — need to save it
            let entry = serde_json::json!({ "count": 1, "window_start": now }).to_string();
            let value_js = wasm_bindgen::JsValue::from_str(&entry);
            let put_promise = self.kv.put(&self.prefixed_key(&rate_key), &value_js);
            SendWrapper::new(JsFuture::from(put_promise))
                .await
                .map_err(|e| StorageError::Backend(format!("KV put failed: {e:?}")))?;
        }

        Ok(new_count)
    }

    /// Reset a rate limit key.
    pub async fn reset_rate_limit_async(&self, key: &str) -> Result<(), StorageError> {
        let rate_key = format!("_rate_limit:{key}");
        let promise = self.kv.delete(&self.prefixed_key(&rate_key));
        SendWrapper::new(JsFuture::from(promise))
            .await
            .map_err(|e| StorageError::Backend(format!("KV delete failed: {e:?}")))?;

        Ok(())
    }
}

#[async_trait::async_trait]
impl AsyncRateLimiterStore for KVWasmStorage {
    async fn check_rate_limit_async(
        &self,
        key: &str,
        max_count: u32,
        window_seconds: u64,
    ) -> StorageResult<bool> {
        foundation_compact::SendWrapper::new(async move {
            self.check_rate_limit_async(key, max_count, window_seconds).await
        }).await
    }

    async fn record_rate_limit_async(&self, key: &str) -> StorageResult<u32> {
        foundation_compact::SendWrapper::new(async move { self.record_rate_limit_async(key).await }).await
    }

    async fn reset_rate_limit_async(&self, key: &str) -> StorageResult<()> {
        foundation_compact::SendWrapper::new(async move { self.reset_rate_limit_async(key).await }).await
    }
}

// ===========================================================================
// BlobStore (KV stores strings, so blobs are base64-encoded)
// ===========================================================================

impl BlobStore for KVWasmStorage {
    fn put_blob(&self, key: &str, data: &[u8]) -> StorageResult<()> {
        let this = self.clone();
        let key = key.to_string();
        let data = data.to_vec();
        exec_future(async move {
            this.put_blob_async(&key, &data).await
        })
    }

    fn get_blob(&self, key: &str) -> StorageResult<Option<Vec<u8>>> {
        let this = self.clone();
        let key = key.to_string();
        exec_future(async move {
            this.get_blob_async(&key).await
        })
    }

    fn delete_blob(&self, key: &str) -> StorageResult<()> {
        let this = self.clone();
        let key = key.to_string();
        exec_future(async move {
            this.delete_blob_async(&key).await
        })
    }

    fn blob_exists(&self, key: &str) -> StorageResult<bool> {
        let this = self.clone();
        let key = key.to_string();
        exec_future(async move {
            this.blob_exists_async(&key).await
        })
    }
}

impl KVWasmStorage {
    /// Put a blob into KV storage (base64-encoded).
    pub async fn put_blob_async(&self, key: &str, data: &[u8]) -> Result<(), StorageError> {
        let encoded = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, data);
        let json = serde_json::json!({ "type": "blob", "data": encoded }).to_string();
        let prefixed = self.prefixed_key(key);
        let value_js = wasm_bindgen::JsValue::from_str(&json);
        let promise = self.kv.put(&prefixed, &value_js);
        SendWrapper::new(JsFuture::from(promise))
            .await
            .map_err(|e| StorageError::Backend(format!("KV put failed: {e:?}")))?;
        Ok(())
    }

    /// Get a blob from KV storage (base64-decoded).
    pub async fn get_blob_async(&self, key: &str) -> Result<Option<Vec<u8>>, StorageError> {
        let prefixed = self.prefixed_key(key);
        let promise = self.kv.get(&prefixed);
        let result = SendWrapper::new(JsFuture::from(promise))
            .await
            .map_err(|e| StorageError::Backend(format!("KV get failed: {e:?}")))?;

        if result.is_null() || result.is_undefined() {
            return Ok(None);
        }

        let json = result.as_string().ok_or_else(|| {
            StorageError::Serialization("KV blob value is not a string".to_string())
        })?;

        let wrapper: serde_json::Value = serde_json::from_str(&json)
            .map_err(|e| StorageError::Serialization(e.to_string()))?;

        let is_blob = wrapper.get("type").and_then(|v| v.as_str()) == Some("blob");
        if !is_blob {
            return Ok(None);
        }

        let encoded = wrapper
            .get("data")
            .and_then(|v| v.as_str())
            .ok_or_else(|| StorageError::Serialization("missing data field in blob wrapper".to_string()))?;

        let decoded = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, encoded)
            .map_err(|e| StorageError::Backend(format!("Base64 decode failed: {e}")))?;

        Ok(Some(decoded))
    }

    /// Delete a blob from KV storage.
    pub async fn delete_blob_async(&self, key: &str) -> Result<(), StorageError> {
        let prefixed = self.prefixed_key(key);
        let promise = self.kv.delete(&prefixed);
        SendWrapper::new(JsFuture::from(promise))
            .await
            .map_err(|e| StorageError::Backend(format!("KV delete failed: {e:?}")))?;
        Ok(())
    }

    /// Check if a blob exists in KV storage.
    pub async fn blob_exists_async(&self, key: &str) -> Result<bool, StorageError> {
        let prefixed = self.prefixed_key(key);
        let promise = self.kv.get(&prefixed);
        let result = SendWrapper::new(JsFuture::from(promise))
            .await
            .map_err(|e| StorageError::Backend(format!("KV get failed: {e:?}")))?;
        Ok(!result.is_null() && !result.is_undefined())
    }
}

#[async_trait::async_trait]
impl AsyncBlobStore for KVWasmStorage {
    async fn put_blob_async(&self, key: &str, data: &[u8]) -> StorageResult<()> {
        foundation_compact::SendWrapper::new(async move { self.put_blob_async(key, data).await }).await
    }

    async fn get_blob_async(&self, key: &str) -> StorageResult<Option<Vec<u8>>> {
        foundation_compact::SendWrapper::new(async move { self.get_blob_async(key).await }).await
    }

    async fn delete_blob_async(&self, key: &str) -> StorageResult<()> {
        foundation_compact::SendWrapper::new(async move { self.delete_blob_async(key).await }).await
    }

    async fn blob_exists_async(&self, key: &str) -> StorageResult<bool> {
        foundation_compact::SendWrapper::new(async move { self.blob_exists_async(key).await }).await
    }
}