nido-svc-common 0.1.0-alpha.1

Shared health, error, OpenAPI, SSE, and middleware primitives for nido-*-svc crates
Documentation
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Collision-resistant local-volume ID generation.
//!
//! Consolidates the copy-pasted `rand_xor` / `new_id` pattern that appears
//! independently in nido-photo-svc, nido-calendar-svc, nido-notifications-svc,
//! nido-voice-svc, nido-location-svc, nido-journal-svc, nido-sync-svc,
//! nido-handoff-svc (8 copies).

use std::time::{SystemTime, UNIX_EPOCH};

/// Generate a collision-resistant local-volume ID.
///
/// Uses xorshift64 seeded from the current nanosecond timestamp XOR-ed with a
/// stack-variable address.  NOT cryptographically random — replace with
/// `uuid::Uuid::new_v4()` when uuid joins `workspace.dependencies`.
///
/// Format: `nido-<16 lowercase hex digits>`
pub fn rand_id() -> String {
    let seed = nanos_seed();
    let id = xorshift64(seed);
    format!("nido-{id:016x}")
}

/// Generate a random `u32` using xorshift32 seeded from a stack address.
///
/// Suitable for short service-local IDs where cryptographic strength is not
/// required.  Used by per-service `new_id()` helpers before they migrate to
/// `rand_id()`.
pub fn rand_xor32() -> u32 {
    let v = 0u32;
    let addr_seed = (&v as *const u32 as usize) as u32;
    let mut x = addr_seed ^ 0xdeadbeef;
    x ^= x << 13;
    x ^= x >> 17;
    x ^= x << 5;
    x
}

// ── Internals ────────────────────────────────────────────────────────────────

fn nanos_seed() -> u64 {
    let nanos = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos() as u64)
        .unwrap_or(0xcafe_babe_dead_beef);
    // XOR with stack-variable address for additional per-call uniqueness
    let v = 0u64;
    let addr = &v as *const u64 as u64;
    nanos ^ addr
}

fn xorshift64(mut x: u64) -> u64 {
    // Avoid zero seed
    if x == 0 {
        x = 0xcafe_babe_1234_5678;
    }
    x ^= x << 13;
    x ^= x >> 7;
    x ^= x << 17;
    x
}