synapse-primitives 0.0.2

Core types and ID hashing for Synapse RPC framework
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
//! Strongly-typed identifiers with SipHash integration
//!
//! This module provides type-safe wrappers around numeric IDs that are derived
//! from string names via SipHash. This provides both efficiency (4-byte IDs on wire)
//! and type safety (can't mix up different ID types).
//!
//! # Examples
//!
//! ```
//! use synapse_primitives::id::{InterfaceId, MethodId, ServiceId, HeaderKeyId};
//!
//! // Create IDs from names
//! let interface_id = InterfaceId::from_name("mensa.user.v2.UserInterface");
//! let method_id = MethodId::from_name("GetUser");
//! let service_id = ServiceId::from_name("user-service");
//! let header_id = HeaderKeyId::from_name("trace_id");
//!
//! // Use in protobuf or network protocols
//! let wire_format: u32 = interface_id.into();
//! let restored = InterfaceId::from_raw(wire_format);
//! assert_eq!(interface_id, restored);
//! ```

use crate::siphash::hash_name_u32;
use serde::{Deserialize, Serialize};
use std::fmt;

/// Service identifier - represents a logical service unit
///
/// Services are hashed from their names (e.g., "user-service", "payment-service")
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ServiceId(u32);

impl ServiceId {
    /// Create a ServiceId from a service name
    ///
    /// # Examples
    ///
    /// ```
    /// use synapse_primitives::id::ServiceId;
    ///
    /// let id = ServiceId::from_name("user-service");
    /// ```
    pub fn from_name(name: &str) -> Self {
        Self(hash_name_u32(name))
    }

    /// Create from raw u32 (e.g., from wire protocol)
    pub const fn from_raw(id: u32) -> Self {
        Self(id)
    }

    /// Get the raw u32 value
    pub const fn as_u32(&self) -> u32 {
        self.0
    }
}

impl From<ServiceId> for u32 {
    fn from(id: ServiceId) -> u32 {
        id.0
    }
}

impl From<u32> for ServiceId {
    fn from(id: u32) -> ServiceId {
        ServiceId(id)
    }
}

impl fmt::Display for ServiceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "ServiceId(0x{:08X})", self.0)
    }
}

/// Interface identifier - represents a protobuf-defined RPC interface
///
/// Interfaces are hashed from their fully-qualified names, including version:
/// e.g., "mensa.user.v2.UserInterface"
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct InterfaceId(u32);

impl InterfaceId {
    /// Create an InterfaceId from a fully-qualified interface name
    ///
    /// # Examples
    ///
    /// ```
    /// use synapse_primitives::id::InterfaceId;
    ///
    /// let id = InterfaceId::from_name("mensa.user.v2.UserInterface");
    /// ```
    pub fn from_name(name: &str) -> Self {
        Self(hash_name_u32(name))
    }

    /// Create from raw u32 (e.g., from wire protocol)
    pub const fn from_raw(id: u32) -> Self {
        Self(id)
    }

    /// Get the raw u32 value
    pub const fn as_u32(&self) -> u32 {
        self.0
    }
}

impl From<InterfaceId> for u32 {
    fn from(id: InterfaceId) -> u32 {
        id.0
    }
}

impl From<u32> for InterfaceId {
    fn from(id: u32) -> InterfaceId {
        InterfaceId(id)
    }
}

impl fmt::Display for InterfaceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "InterfaceId(0x{:08X})", self.0)
    }
}

/// Method identifier - represents a method within an RPC interface
///
/// Methods are hashed from their names (e.g., "GetUser", "CreateUser")
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct MethodId(u32);

impl MethodId {
    /// Create a MethodId from a method name
    ///
    /// # Examples
    ///
    /// ```
    /// use synapse_primitives::id::MethodId;
    ///
    /// let id = MethodId::from_name("GetUser");
    /// ```
    pub fn from_name(name: &str) -> Self {
        Self(hash_name_u32(name))
    }

    /// Create from raw u32 (e.g., from wire protocol)
    pub const fn from_raw(id: u32) -> Self {
        Self(id)
    }

    /// Get the raw u32 value
    pub const fn as_u32(&self) -> u32 {
        self.0
    }
}

impl From<MethodId> for u32 {
    fn from(id: MethodId) -> u32 {
        id.0
    }
}

impl From<u32> for MethodId {
    fn from(id: u32) -> MethodId {
        MethodId(id)
    }
}

impl fmt::Display for MethodId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "MethodId(0x{:08X})", self.0)
    }
}

/// Header key identifier - represents a header name in RPC messages
///
/// Header keys are hashed from their names (e.g., "trace_id", "request_id")
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct HeaderKeyId(u32);

impl HeaderKeyId {
    /// Create a HeaderKeyId from a header name
    ///
    /// # Examples
    ///
    /// ```
    /// use synapse_primitives::id::HeaderKeyId;
    ///
    /// let trace_id = HeaderKeyId::from_name("trace_id");
    /// let request_id = HeaderKeyId::from_name("request_id");
    /// ```
    pub fn from_name(name: &str) -> Self {
        Self(hash_name_u32(name))
    }

    /// Create from raw u32 (e.g., from wire protocol)
    pub const fn from_raw(id: u32) -> Self {
        Self(id)
    }

    /// Get the raw u32 value
    pub const fn as_u32(&self) -> u32 {
        self.0
    }
}

impl From<HeaderKeyId> for u32 {
    fn from(id: HeaderKeyId) -> u32 {
        id.0
    }
}

impl From<u32> for HeaderKeyId {
    fn from(id: u32) -> HeaderKeyId {
        HeaderKeyId(id)
    }
}

impl fmt::Display for HeaderKeyId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "HeaderKeyId(0x{:08X})", self.0)
    }
}

/// Metric identifier - represents a metric name for monitoring
///
/// Metrics are hashed from their names (e.g., "request_count", "request_duration_ms")
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct MetricId(u32);

impl MetricId {
    /// Create a MetricId from a metric name
    ///
    /// # Examples
    ///
    /// ```
    /// use synapse_primitives::id::MetricId;
    ///
    /// let request_count = MetricId::from_name("request_count");
    /// let error_count = MetricId::from_name("error_count");
    /// ```
    pub fn from_name(name: &str) -> Self {
        Self(hash_name_u32(name))
    }

    /// Create from raw u32 (e.g., from wire protocol)
    pub const fn from_raw(id: u32) -> Self {
        Self(id)
    }

    /// Get the raw u32 value
    pub const fn as_u32(&self) -> u32 {
        self.0
    }
}

impl From<MetricId> for u32 {
    fn from(id: MetricId) -> u32 {
        id.0
    }
}

impl From<u32> for MetricId {
    fn from(id: u32) -> MetricId {
        MetricId(id)
    }
}

impl fmt::Display for MetricId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "MetricId(0x{:08X})", self.0)
    }
}

/// Instance identifier - represents a specific running instance of a service
///
/// Instances use 128-bit UUIDs for globally unique identification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct InstanceId(u128);

impl InstanceId {
    /// Create a new random instance ID using UUID v4
    pub fn new_random() -> Self {
        let uuid = uuid::Uuid::new_v4();
        Self(u128::from_be_bytes(*uuid.as_bytes()))
    }

    /// Create from raw u128
    pub const fn from_raw(id: u128) -> Self {
        Self(id)
    }

    /// Create from bytes
    pub fn from_bytes(bytes: [u8; 16]) -> Self {
        Self(u128::from_be_bytes(bytes))
    }

    /// Get the raw u128 value
    pub const fn as_u128(&self) -> u128 {
        self.0
    }

    /// Get as bytes
    pub fn as_bytes(&self) -> [u8; 16] {
        self.0.to_be_bytes()
    }
}

impl From<InstanceId> for u128 {
    fn from(id: InstanceId) -> u128 {
        id.0
    }
}

impl From<u128> for InstanceId {
    fn from(id: u128) -> InstanceId {
        InstanceId(id)
    }
}

impl fmt::Display for InstanceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "InstanceId(0x{:032X})", self.0)
    }
}

/// Common header key IDs for standard headers
///
/// Values are precomputed from `HeaderKeyId::from_name()` (SipHash) to ensure
/// these constants match runtime-computed values exactly.
pub mod well_known {
    use super::HeaderKeyId;
    use once_cell::sync::Lazy;

    /// Standard header: trace_id
    pub static TRACE_ID: Lazy<HeaderKeyId> = Lazy::new(|| HeaderKeyId::from_name("trace_id"));

    /// Standard header: span_id
    pub static SPAN_ID: Lazy<HeaderKeyId> = Lazy::new(|| HeaderKeyId::from_name("span_id"));

    /// Standard header: request_id
    pub static REQUEST_ID: Lazy<HeaderKeyId> = Lazy::new(|| HeaderKeyId::from_name("request_id"));

    /// Standard header: caller_service
    pub static CALLER_SERVICE: Lazy<HeaderKeyId> =
        Lazy::new(|| HeaderKeyId::from_name("caller_service"));

    /// Standard header: idempotency_key
    pub static IDEMPOTENCY_KEY: Lazy<HeaderKeyId> =
        Lazy::new(|| HeaderKeyId::from_name("idempotency_key"));
}

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

    #[test]
    fn test_service_id() {
        let id1 = ServiceId::from_name("user-service");
        let id2 = ServiceId::from_name("user-service");
        let id3 = ServiceId::from_name("payment-service");

        assert_eq!(id1, id2, "Same name should produce same ID");
        assert_ne!(id1, id3, "Different names should produce different IDs");

        // Round-trip through u32
        let raw: u32 = id1.into();
        let restored = ServiceId::from_raw(raw);
        assert_eq!(id1, restored);
    }

    #[test]
    fn test_interface_id() {
        let id = InterfaceId::from_name("mensa.user.v2.UserInterface");
        let raw = id.as_u32();
        let restored = InterfaceId::from_raw(raw);
        assert_eq!(id, restored);
    }

    #[test]
    fn test_method_id() {
        let get_user = MethodId::from_name("GetUser");
        let create_user = MethodId::from_name("CreateUser");
        assert_ne!(get_user, create_user);
    }

    #[test]
    fn test_header_key_id() {
        let trace_id = HeaderKeyId::from_name("trace_id");
        let request_id = HeaderKeyId::from_name("request_id");
        assert_ne!(trace_id, request_id);
    }

    #[test]
    fn test_metric_id() {
        let request_count = MetricId::from_name("request_count");
        let error_count = MetricId::from_name("error_count");
        assert_ne!(request_count, error_count);
    }

    #[test]
    fn test_instance_id() {
        let id1 = InstanceId::new_random();

        // Round-trip through bytes
        let bytes = id1.as_bytes();
        let restored = InstanceId::from_bytes(bytes);
        assert_eq!(id1, restored);

        // Verify size
        assert_eq!(bytes.len(), 16);
    }

    #[test]
    fn test_display() {
        let service_id = ServiceId::from_name("test-service");
        let display = format!("{}", service_id);
        assert!(display.starts_with("ServiceId(0x"));
    }

    #[test]
    fn test_well_known_headers() {
        // Well-known headers should match runtime-computed values
        assert_eq!(*well_known::TRACE_ID, HeaderKeyId::from_name("trace_id"));
        assert_eq!(*well_known::SPAN_ID, HeaderKeyId::from_name("span_id"));
        assert_eq!(
            *well_known::REQUEST_ID,
            HeaderKeyId::from_name("request_id")
        );
        assert_eq!(
            *well_known::CALLER_SERVICE,
            HeaderKeyId::from_name("caller_service")
        );
        assert_eq!(
            *well_known::IDEMPOTENCY_KEY,
            HeaderKeyId::from_name("idempotency_key")
        );

        // They should all be distinct
        assert_ne!(*well_known::TRACE_ID, *well_known::SPAN_ID);
    }

    #[test]
    fn test_version_sensitivity() {
        let v1 = InterfaceId::from_name("mensa.user.v1.UserInterface");
        let v2 = InterfaceId::from_name("mensa.user.v2.UserInterface");
        assert_ne!(v1, v2, "Different versions should have different IDs");
    }

    #[test]
    fn test_ordering() {
        let id1 = ServiceId::from_name("aaa");
        let id2 = ServiceId::from_name("bbb");
        let id3 = ServiceId::from_name("ccc");

        // IDs should be orderable
        let mut ids = [id3, id1, id2];
        ids.sort();

        // Ordering is based on hash, not name
        assert_eq!(ids.len(), 3);
    }
}