11use std:: {
2- sync:: { Arc , Once } ,
2+ sync:: { Arc , OnceLock } ,
33 time:: Duration ,
44} ;
55
@@ -18,8 +18,9 @@ const WORKER_HEARTBEAT_TTL: u64 = 30;
1818/// Worker heartbeat interval in seconds
1919const WORKER_HEARTBEAT_INTERVAL : u64 = 10 ;
2020
21- static INIT : Once = Once :: new ( ) ;
22- static mut WORKER_ID : u16 = 0 ;
21+ /// Stores the worker ID after initialization. Using OnceLock ensures thread-safe
22+ /// one-time initialization without requiring unsafe code.
23+ static WORKER_ID : OnceLock < u16 > = OnceLock :: new ( ) ;
2324
2425/// Worker ID registration manager for multi-instance coordination
2526pub struct WorkerRegistry < S : StorageBackend > {
@@ -325,16 +326,14 @@ impl IdGenerator {
325326 ) ) ) ;
326327 }
327328
328- let options = IdGeneratorOptions :: new ( )
329- . worker_id ( worker_id. into ( ) )
330- . worker_id_bit_len ( 10 )
331- . base_time ( CUSTOM_EPOCH ) ;
329+ WORKER_ID . get_or_init ( || {
330+ let options = IdGeneratorOptions :: new ( )
331+ . worker_id ( worker_id. into ( ) )
332+ . worker_id_bit_len ( 10 )
333+ . base_time ( CUSTOM_EPOCH ) ;
332334
333- INIT . call_once ( || {
334- unsafe {
335- WORKER_ID = worker_id;
336- }
337335 idgenerator:: IdInstance :: init ( options) . expect ( "Failed to initialize ID generator" ) ;
336+ worker_id
338337 } ) ;
339338
340339 Ok ( ( ) )
@@ -354,8 +353,10 @@ impl IdGenerator {
354353 }
355354
356355 /// Get the worker ID for this generator
356+ ///
357+ /// Returns 0 if the generator has not been initialized.
357358 pub fn worker_id ( ) -> u16 {
358- unsafe { WORKER_ID }
359+ WORKER_ID . get ( ) . copied ( ) . unwrap_or ( 0 )
359360 }
360361}
361362
0 commit comments