wash-runtime 0.1.0

Opinionated wasmtime wrapper that provides a runtime and workload API for executing Wasm components
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
//! # WASI KeyValue Memory Plugin
//!
//! This module implements an in-memory keyvalue plugin for the wasmCloud runtime,
//! providing the `wasi:keyvalue@0.2.0-draft` interfaces for development and testing scenarios.

use std::{
    collections::{HashMap, HashSet},
    sync::Arc,
};

const WASI_KEYVALUE_ID: &str = "wasi-keyvalue";
use tokio::sync::RwLock;
use wasmtime::component::Resource;

use crate::{
    engine::{
        ctx::Ctx,
        workload::{ResolvedWorkload, WorkloadComponent},
    },
    plugin::HostPlugin,
    wit::{WitInterface, WitWorld},
};

mod bindings {
    wasmtime::component::bindgen!({
        world: "keyvalue",
        trappable_imports: true,
        async: true,
        with: {
            "wasi:keyvalue/store/bucket": crate::plugin::wasi_keyvalue::BucketHandle,
        },
    });
}

use bindings::wasi::keyvalue::store::{Error as StoreError, KeyResponse};

/// In-memory bucket representation
#[derive(Clone, Debug)]
pub struct BucketData {
    pub name: String,
    pub data: HashMap<String, Vec<u8>>,
    pub created_at: u64,
}

/// Resource representation for a bucket (key-value store)
pub type BucketHandle = String;

/// Memory-based keyvalue plugin
#[derive(Clone, Default)]
pub struct WasiKeyvalue {
    /// Storage for all buckets, keyed by workload ID, then bucket name
    storage: Arc<RwLock<HashMap<String, HashMap<String, BucketData>>>>,
}

impl WasiKeyvalue {
    pub fn new() -> Self {
        Self {
            storage: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    fn get_timestamp() -> u64 {
        std::time::SystemTime::now()
            .duration_since(std::time::SystemTime::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs()
    }
}

// Implementation for the store interface
impl bindings::wasi::keyvalue::store::Host for Ctx {
    async fn open(
        &mut self,
        identifier: String,
    ) -> anyhow::Result<Result<Resource<BucketHandle>, StoreError>> {
        let Some(plugin) = self.get_plugin::<WasiKeyvalue>(WASI_KEYVALUE_ID) else {
            return Ok(Err(StoreError::Other(
                "keyvalue plugin not available".to_string(),
            )));
        };

        let mut storage = plugin.storage.write().await;
        let workload_storage = storage.entry(self.id.clone()).or_default();

        // Create bucket if it doesn't exist
        if !workload_storage.contains_key(&identifier) {
            let bucket_data = BucketData {
                name: identifier.clone(),
                data: HashMap::new(),
                created_at: WasiKeyvalue::get_timestamp(),
            };
            workload_storage.insert(identifier.clone(), bucket_data);
        }

        let resource = self.table.push(identifier)?;
        Ok(Ok(resource))
    }
}

// Resource host trait implementations for bucket
impl bindings::wasi::keyvalue::store::HostBucket for Ctx {
    async fn get(
        &mut self,
        bucket: Resource<BucketHandle>,
        key: String,
    ) -> anyhow::Result<Result<Option<Vec<u8>>, StoreError>> {
        let bucket_name = self.table.get(&bucket)?;

        let Some(plugin) = self.get_plugin::<WasiKeyvalue>(WASI_KEYVALUE_ID) else {
            return Ok(Err(StoreError::Other(
                "keyvalue plugin not available".to_string(),
            )));
        };

        let storage = plugin.storage.read().await;
        let empty_map = HashMap::new();
        let workload_storage = storage.get(&self.id).unwrap_or(&empty_map);

        match workload_storage.get(bucket_name) {
            Some(bucket_data) => {
                let value = bucket_data.data.get(&key).cloned();
                Ok(Ok(value))
            }
            None => Ok(Err(StoreError::Other(format!(
                "bucket '{bucket_name}' does not exist"
            )))),
        }
    }

    async fn set(
        &mut self,
        bucket: Resource<BucketHandle>,
        key: String,
        value: Vec<u8>,
    ) -> anyhow::Result<Result<(), StoreError>> {
        let bucket_name = self.table.get(&bucket)?;

        let Some(plugin) = self.get_plugin::<WasiKeyvalue>(WASI_KEYVALUE_ID) else {
            return Ok(Err(StoreError::Other(
                "keyvalue plugin not available".to_string(),
            )));
        };

        let mut storage = plugin.storage.write().await;
        let workload_storage = storage.entry(self.id.clone()).or_default();

        match workload_storage.get_mut(bucket_name) {
            Some(bucket_data) => {
                bucket_data.data.insert(key, value);
                Ok(Ok(()))
            }
            None => Ok(Err(StoreError::Other(format!(
                "bucket '{bucket_name}' does not exist"
            )))),
        }
    }

    async fn delete(
        &mut self,
        bucket: Resource<BucketHandle>,
        key: String,
    ) -> anyhow::Result<Result<(), StoreError>> {
        let bucket_name = self.table.get(&bucket)?;

        let Some(plugin) = self.get_plugin::<WasiKeyvalue>(WASI_KEYVALUE_ID) else {
            return Ok(Err(StoreError::Other(
                "keyvalue plugin not available".to_string(),
            )));
        };

        let mut storage = plugin.storage.write().await;
        let workload_storage = storage.entry(self.id.clone()).or_default();

        match workload_storage.get_mut(bucket_name) {
            Some(bucket_data) => {
                bucket_data.data.remove(&key);
                Ok(Ok(()))
            }
            None => Ok(Err(StoreError::Other(format!(
                "bucket '{bucket_name}' does not exist"
            )))),
        }
    }

    async fn exists(
        &mut self,
        bucket: Resource<BucketHandle>,
        key: String,
    ) -> anyhow::Result<Result<bool, StoreError>> {
        let bucket_name = self.table.get(&bucket)?;

        let Some(plugin) = self.get_plugin::<WasiKeyvalue>(WASI_KEYVALUE_ID) else {
            return Ok(Err(StoreError::Other(
                "keyvalue plugin not available".to_string(),
            )));
        };

        let storage = plugin.storage.read().await;
        let empty_map = HashMap::new();
        let workload_storage = storage.get(&self.id).unwrap_or(&empty_map);

        match workload_storage.get(bucket_name) {
            Some(bucket_data) => Ok(Ok(bucket_data.data.contains_key(&key))),
            None => Ok(Err(StoreError::Other(format!(
                "bucket '{bucket_name}' does not exist"
            )))),
        }
    }

    async fn list_keys(
        &mut self,
        bucket: Resource<BucketHandle>,
        cursor: Option<u64>,
    ) -> anyhow::Result<Result<KeyResponse, StoreError>> {
        let bucket_name = self.table.get(&bucket)?;

        let Some(plugin) = self.get_plugin::<WasiKeyvalue>(WASI_KEYVALUE_ID) else {
            return Ok(Err(StoreError::Other(
                "keyvalue plugin not available".to_string(),
            )));
        };

        let storage = plugin.storage.read().await;
        let empty_map = HashMap::new();
        let workload_storage = storage.get(&self.id).unwrap_or(&empty_map);

        match workload_storage.get(bucket_name) {
            Some(bucket_data) => {
                let mut keys: Vec<String> = bucket_data.data.keys().cloned().collect();
                keys.sort(); // Ensure consistent ordering

                // Simple cursor-based pagination - cursor is the index from previous page
                let start_index = cursor.unwrap_or(0) as usize;

                // Return up to 100 keys per page
                const PAGE_SIZE: usize = 100;
                let end_index = std::cmp::min(start_index + PAGE_SIZE, keys.len());
                let page_keys = keys[start_index..end_index].to_vec();

                // Set next cursor if there are more keys
                let next_cursor = if end_index < keys.len() {
                    Some(end_index as u64)
                } else {
                    None
                };

                Ok(Ok(KeyResponse {
                    keys: page_keys,
                    cursor: next_cursor,
                }))
            }
            None => Ok(Err(StoreError::Other(format!(
                "bucket '{bucket_name}' does not exist"
            )))),
        }
    }

    async fn drop(&mut self, rep: Resource<BucketHandle>) -> anyhow::Result<()> {
        tracing::debug!(
            workload_id = self.id,
            resource_id = ?rep,
            "Dropping bucket resource"
        );
        self.table.delete(rep)?;
        Ok(())
    }
}

// Implementation for the atomics interface
impl bindings::wasi::keyvalue::atomics::Host for Ctx {
    async fn increment(
        &mut self,
        bucket: Resource<BucketHandle>,
        key: String,
        delta: u64,
    ) -> anyhow::Result<Result<u64, StoreError>> {
        let bucket_name = self.table.get(&bucket)?;

        let Some(plugin) = self.get_plugin::<WasiKeyvalue>(WASI_KEYVALUE_ID) else {
            return Ok(Err(StoreError::Other(
                "keyvalue plugin not available".to_string(),
            )));
        };

        let mut storage = plugin.storage.write().await;
        let workload_storage = storage.entry(self.id.clone()).or_default();

        match workload_storage.get_mut(bucket_name) {
            Some(bucket_data) => {
                // Get current value, treating missing key as 0
                let current_bytes = bucket_data.data.get(&key);
                let current_value = if let Some(bytes) = current_bytes {
                    // Try to parse as u64 from 8-byte array
                    if bytes.len() == 8 {
                        u64::from_le_bytes(bytes.clone().try_into().unwrap_or([0; 8]))
                    } else {
                        // Try to parse as string representation
                        String::from_utf8_lossy(bytes).parse::<u64>().unwrap_or(0)
                    }
                } else {
                    0
                };

                let new_value = current_value.saturating_add(delta);

                // Store as 8-byte little-endian representation
                bucket_data
                    .data
                    .insert(key, new_value.to_le_bytes().to_vec());

                Ok(Ok(new_value))
            }
            None => Ok(Err(StoreError::Other(format!(
                "bucket '{bucket_name}' does not exist"
            )))),
        }
    }
}

// Implementation for the batch interface
impl bindings::wasi::keyvalue::batch::Host for Ctx {
    async fn get_many(
        &mut self,
        bucket: Resource<BucketHandle>,
        keys: Vec<String>,
    ) -> anyhow::Result<Result<Vec<Option<(String, Vec<u8>)>>, StoreError>> {
        let bucket_name = self.table.get(&bucket)?;

        let Some(plugin) = self.get_plugin::<WasiKeyvalue>(WASI_KEYVALUE_ID) else {
            return Ok(Err(StoreError::Other(
                "keyvalue plugin not available".to_string(),
            )));
        };

        let storage = plugin.storage.read().await;
        let empty_map = HashMap::new();
        let workload_storage = storage.get(&self.id).unwrap_or(&empty_map);

        match workload_storage.get(bucket_name) {
            Some(bucket_data) => {
                let results: Vec<Option<(String, Vec<u8>)>> = keys
                    .into_iter()
                    .map(|key| {
                        bucket_data
                            .data
                            .get(&key)
                            .cloned()
                            .map(|value| (key, value))
                    })
                    .collect();
                Ok(Ok(results))
            }
            None => Ok(Err(StoreError::Other(format!(
                "bucket '{bucket_name}' does not exist"
            )))),
        }
    }

    async fn set_many(
        &mut self,
        bucket: Resource<BucketHandle>,
        key_values: Vec<(String, Vec<u8>)>,
    ) -> anyhow::Result<Result<(), StoreError>> {
        let bucket_name = self.table.get(&bucket)?;

        let Some(plugin) = self.get_plugin::<WasiKeyvalue>(WASI_KEYVALUE_ID) else {
            return Ok(Err(StoreError::Other(
                "keyvalue plugin not available".to_string(),
            )));
        };

        let mut storage = plugin.storage.write().await;
        let workload_storage = storage.entry(self.id.clone()).or_default();

        match workload_storage.get_mut(bucket_name) {
            Some(bucket_data) => {
                for (key, value) in key_values {
                    bucket_data.data.insert(key, value);
                }
                Ok(Ok(()))
            }
            None => Ok(Err(StoreError::Other(format!(
                "bucket '{bucket_name}' does not exist"
            )))),
        }
    }

    async fn delete_many(
        &mut self,
        bucket: Resource<BucketHandle>,
        keys: Vec<String>,
    ) -> anyhow::Result<Result<(), StoreError>> {
        let bucket_name = self.table.get(&bucket)?;

        let Some(plugin) = self.get_plugin::<WasiKeyvalue>(WASI_KEYVALUE_ID) else {
            return Ok(Err(StoreError::Other(
                "keyvalue plugin not available".to_string(),
            )));
        };

        let mut storage = plugin.storage.write().await;
        let workload_storage = storage.entry(self.id.clone()).or_default();

        match workload_storage.get_mut(bucket_name) {
            Some(bucket_data) => {
                for key in keys {
                    bucket_data.data.remove(&key);
                }
                Ok(Ok(()))
            }
            None => Ok(Err(StoreError::Other(format!(
                "bucket '{bucket_name}' does not exist"
            )))),
        }
    }
}

#[async_trait::async_trait]
impl HostPlugin for WasiKeyvalue {
    fn id(&self) -> &'static str {
        WASI_KEYVALUE_ID
    }

    fn world(&self) -> WitWorld {
        WitWorld {
            imports: HashSet::from([WitInterface::from(
                "wasi:keyvalue/store,atomics,batch@0.2.0-draft",
            )]),
            ..Default::default()
        }
    }

    async fn on_component_bind(
        &self,
        component: &mut WorkloadComponent,
        interfaces: std::collections::HashSet<crate::wit::WitInterface>,
    ) -> anyhow::Result<()> {
        // Check if any of the interfaces are wasi:keyvalue related
        let has_keyvalue = interfaces
            .iter()
            .any(|i| i.namespace == "wasi" && i.package == "keyvalue");

        if !has_keyvalue {
            tracing::warn!(
                "WasiKeyvalue plugin requested for non-wasi:keyvalue interface(s): {:?}",
                interfaces
            );
            return Ok(());
        }

        tracing::debug!(
            workload_id = component.id(),
            "Adding keyvalue interfaces to linker for workload"
        );
        let linker = component.linker();

        bindings::wasi::keyvalue::store::add_to_linker(linker, |ctx| ctx)?;
        bindings::wasi::keyvalue::atomics::add_to_linker(linker, |ctx| ctx)?;
        bindings::wasi::keyvalue::batch::add_to_linker(linker, |ctx| ctx)?;

        let id = component.id();
        tracing::debug!(
            workload_id = id,
            "Successfully added keyvalue interfaces to linker for workload"
        );

        // Initialize storage for this workload
        let mut storage = self.storage.write().await;
        storage.insert(id.to_string(), HashMap::new());

        tracing::debug!("WasiKeyvalue plugin bound to workload '{id}'");

        Ok(())
    }

    async fn on_workload_unbind(
        &self,
        workload_handle: &ResolvedWorkload,
        _interfaces: std::collections::HashSet<crate::wit::WitInterface>,
    ) -> anyhow::Result<()> {
        let id = workload_handle.id();
        // Clean up storage for this workload
        let mut storage = self.storage.write().await;
        storage.remove(id);

        tracing::debug!("WasiKeyvalue plugin unbound from workload '{id}'");

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_wasi_keyvalue_creation() {
        let keyvalue = WasiKeyvalue::new();
        assert!(keyvalue.storage.try_read().is_ok());
    }

    #[test]
    fn test_get_timestamp() {
        let timestamp = WasiKeyvalue::get_timestamp();
        assert!(timestamp > 0);
    }

    #[test]
    fn test_bucket_data_creation() {
        let bucket = BucketData {
            name: "test-bucket".to_string(),
            data: HashMap::new(),
            created_at: WasiKeyvalue::get_timestamp(),
        };

        assert_eq!(bucket.name, "test-bucket");
        assert!(bucket.data.is_empty());
        assert!(bucket.created_at > 0);
    }

    #[tokio::test]
    async fn test_storage_operations() {
        let keyvalue = WasiKeyvalue::new();

        // Test write access
        {
            let mut storage = keyvalue.storage.write().await;
            storage.insert("workload1".to_string(), HashMap::new());
        }

        // Test read access
        {
            let storage = keyvalue.storage.read().await;
            assert!(storage.contains_key("workload1"));
        }
    }

    #[test]
    fn test_batch_operations_data_structures() {
        // Test that we can create the data structures for batch operations
        let key_values = [
            ("key1".to_string(), b"value1".to_vec()),
            ("key2".to_string(), b"value2".to_vec()),
        ];
        assert_eq!(key_values.len(), 2);

        let keys = ["key1".to_string(), "key2".to_string()];
        assert_eq!(keys.len(), 2);

        let results: Vec<Option<(String, Vec<u8>)>> = vec![
            Some(("key1".to_string(), b"value1".to_vec())),
            None, // key not found
        ];
        assert_eq!(results.len(), 2);
        assert!(results[0].is_some());
        assert!(results[1].is_none());
    }
}