Random
The random module provides cryptographically secure random value generation using platform-native sources.
Required Imports
Section titled “Required Imports”#[allow(warnings)]mod bindings;
use bindings::exports::mik::core::handler::{self, Guest, Response};use mik_sdk::prelude::*;The random module is included in mik_sdk::prelude::*.
Platform Support
Section titled “Platform Support”| Platform | Implementation |
|---|---|
| WASM (wasm32-wasip2) | Native wasi:random/random |
| Native (testing) | getrandom crate (OS entropy) |
All functions use cryptographically secure randomness suitable for tokens, secrets, and UUIDs.
UUID Generation
Section titled “UUID Generation”Generate RFC 4122 compliant UUID v4:
use mik_sdk::random;
let id = random::uuid();// Example: "550e8400-e29b-41d4-a716-446655440000"
assert_eq!(id.len(), 36);assert_eq!(id.chars().nth(14), Some('4')); // Version 4Common Patterns
Section titled “Common Patterns”// Resource creationfn create_user(body: CreateInput, _req: &Request) -> Response { let id = random::uuid();
created!(format!("/users/{}", id), { "id": id, "name": body.name })}
// Session tokenslet session_id = random::uuid();
// Correlation IDslet request_id = random::uuid();log!(info, "request received", request_id: &request_id);Hex Strings
Section titled “Hex Strings”Generate random hexadecimal strings:
let token = random::hex(16); // 16 bytes = 32 hex chars// Example: "a3f7c2e91b4d6f8a0c5e7d3b9a1f4e2c"
let short_token = random::hex(8); // 8 bytes = 16 hex chars// Example: "f7c2e91b4d6f8a0c"Common Uses
Section titled “Common Uses”// API tokenslet api_key = random::hex(32); // 64 character token
// Verification codeslet code = random::hex(4); // 8 character code
// Password reset tokenslet reset_token = random::hex(24); // 48 character token
// Short codes (e.g., invite codes)let invite_code = random::hex(6).to_uppercase(); // "A3F7C2E91B4D"Raw Bytes
Section titled “Raw Bytes”Generate random bytes:
let bytes = random::bytes(32); // Vec<u8> of 32 random bytes
assert_eq!(bytes.len(), 32);Common Uses
Section titled “Common Uses”// Encryption keyslet key = random::bytes(32); // 256-bit key
// Initialization vectorslet iv = random::bytes(16); // 128-bit IV
// Salt for hashinglet salt = random::bytes(16);Random Integers
Section titled “Random Integers”Generate random 64-bit integers:
let num = random::u64(); // u64
// Example: 12345678901234567890Common Uses
Section titled “Common Uses”// Random selectionlet items = vec!["a", "b", "c", "d"];let index = (random::u64() as usize) % items.len();let selected = items[index];
// Random delays (for jitter)let jitter_ms = random::u64() % 1000; // 0-999msComplete Examples
Section titled “Complete Examples”Token-Based Authentication
Section titled “Token-Based Authentication”fn create_api_key(body: CreateKeyInput, _req: &Request) -> Response { let key_id = random::uuid(); let secret = random::hex(32);
// Store hash of secret in database let (sql, params) = sql_create!(api_keys { id: &key_id, name: &body.name, secret_hash: hash(&secret), // Hash before storing created_at: time::now_iso(), });
// Return secret to user (only time it's visible) created!(format!("/api-keys/{}", key_id), { "id": key_id, "secret": secret, // User must save this "message": "Save this secret - it won't be shown again" })}Session Management
Section titled “Session Management”fn login(body: LoginInput, _req: &Request) -> Response { // Validate credentials...
let session_id = random::uuid(); let session_token = random::hex(32);
// Store session let (sql, params) = sql_create!(sessions { id: &session_id, user_id: &body.user_id, token_hash: hash(&session_token), created_at: time::now_iso(), expires_at: time::to_iso(time::now() + 86400, 0), // 24h });
ok!({ "session_id": session_id, "token": session_token })}Request Tracing
Section titled “Request Tracing”fn handler(req: &Request) -> Response { // Use existing trace ID or generate new one let incoming_trace = req.trace_id_or(""); let trace_id = if incoming_trace.is_empty() { random::uuid() } else { incoming_trace.to_string() };
log!(info, "handling request", trace_id: &trace_id, path: req.path_without_query() );
// Forward to downstream services let response = fetch!(GET "http://api:8080/data") .with_trace_id(Some(&trace_id)) .send()?;
ok!({ "trace_id": trace_id })}Security Notes
Section titled “Security Notes”API Summary
Section titled “API Summary”| Function | Returns | Description |
|---|---|---|
random::uuid() | String | UUID v4 (36 chars) |
random::hex(n) | String | n bytes as hex (2n chars) |
random::bytes(n) | Vec<u8> | n random bytes |
random::u64() | u64 | Random 64-bit integer |
Examples
Section titled “Examples”use mik_sdk::random;
// UUIDslet user_id = random::uuid(); // "550e8400-e29b-..."let order_id = random::uuid(); // "7c9e6679-..."
// Tokenslet api_key = random::hex(32); // 64 hex charslet short_code = random::hex(4); // 8 hex chars
// Raw byteslet key = random::bytes(32); // 32 bytes for encryption
// Random numberlet n = random::u64(); // Random u64