|
1 | 1 | use serde::{Deserialize, Serialize}; |
2 | 2 | use std::collections::HashMap; |
3 | | -use uuid::Uuid; |
| 3 | +use uuid::{Builder, Uuid, Variant, Version}; |
4 | 4 |
|
5 | 5 | // Use the generated bindings from rust_wasm_component_bindgen |
6 | 6 | use user_service_bindings::exports::user_service::Guest; |
7 | 7 |
|
8 | 8 | // Re-export the generated WIT types |
9 | 9 | pub use user_service_bindings::exports::user_service::*; |
10 | 10 |
|
| 11 | +/// Global counter for UUID generation uniqueness |
| 12 | +static mut UUID_COUNTER: u64 = 0; |
| 13 | + |
| 14 | +/// Generate a deterministic UUID without depending on getrandom/wasi |
| 15 | +/// Uses timestamp + counter for uniqueness, avoiding wit-bindgen-rt version conflicts |
| 16 | +fn generate_deterministic_uuid() -> Uuid { |
| 17 | + let now = std::time::SystemTime::now() |
| 18 | + .duration_since(std::time::UNIX_EPOCH) |
| 19 | + .unwrap(); |
| 20 | + |
| 21 | + let timestamp_nanos = now.as_nanos() as u64; |
| 22 | + |
| 23 | + // Safe increment of counter |
| 24 | + let counter = unsafe { |
| 25 | + UUID_COUNTER += 1; |
| 26 | + UUID_COUNTER |
| 27 | + }; |
| 28 | + |
| 29 | + // Create 16 bytes from timestamp (8) + counter (8) |
| 30 | + let mut bytes = [0u8; 16]; |
| 31 | + bytes[0..8].copy_from_slice(×tamp_nanos.to_be_bytes()); |
| 32 | + bytes[8..16].copy_from_slice(&counter.to_be_bytes()); |
| 33 | + |
| 34 | + // Create UUID v4-style with proper version and variant bits |
| 35 | + let mut builder = Builder::from_random_bytes(bytes); |
| 36 | + builder |
| 37 | + .set_variant(Variant::RFC4122) |
| 38 | + .set_version(Version::Random) |
| 39 | + .into_uuid() |
| 40 | +} |
| 41 | + |
11 | 42 | /// Rust User Service Component |
12 | 43 | /// |
13 | 44 | /// Demonstrates Rust's memory safety and async capabilities in a WebAssembly component. |
@@ -173,7 +204,7 @@ impl UserServiceImpl { |
173 | 204 | return Err("User already exists".to_string()); |
174 | 205 | } |
175 | 206 |
|
176 | | - let user_id = Uuid::new_v4().to_string(); |
| 207 | + let user_id = generate_deterministic_uuid().to_string(); |
177 | 208 | let now = std::time::SystemTime::now() |
178 | 209 | .duration_since(std::time::UNIX_EPOCH) |
179 | 210 | .unwrap() |
@@ -309,7 +340,7 @@ impl UserServiceImpl { |
309 | 340 | return Err("Relationship already exists".to_string()); |
310 | 341 | } |
311 | 342 |
|
312 | | - let relationship_id = Uuid::new_v4().to_string(); |
| 343 | + let relationship_id = generate_deterministic_uuid().to_string(); |
313 | 344 | let now = std::time::SystemTime::now() |
314 | 345 | .duration_since(std::time::UNIX_EPOCH) |
315 | 346 | .unwrap() |
|
0 commit comments