use crate::RedisClient;
pub use nabase::id::{Snowflake, SnowflakeError};
use serde::Deserialize;
use std::sync::Arc;
pub async fn alloc_worker_id(
_client: &RedisClient,
_key: &str,
_worker_id_bits: u32,
) -> Result<i64, SnowflakeError> {
Err(SnowflakeError::External("automatic worker allocation is disabled; an explicitly initialized non-reusing namespace is required".into()))
}
pub struct WorkerIdLease {
worker_id: i64,
}
impl WorkerIdLease {
pub fn worker_id(&self) -> i64 {
self.worker_id
}
pub async fn release(&self) -> Result<(), SnowflakeError> {
Ok(())
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct SnowflakeConfig {
pub qualifier: String,
pub key: String,
pub base_time: i64,
pub worker_id_bits: u32,
pub seq_bits: u32,
}
impl Default for SnowflakeConfig {
fn default() -> Self {
Self {
qualifier: String::new(),
key: "SNOWFLAKE-WORKERS".to_string(),
base_time: 1_704_038_400_000,
worker_id_bits: 6,
seq_bits: 6,
}
}
}
impl SnowflakeConfig {
pub fn build_local(&self) -> Result<Snowflake, SnowflakeError> {
Snowflake::new(1, self.base_time, self.worker_id_bits, self.seq_bits)
}
pub async fn build_with_redis(
&self,
client: Arc<RedisClient>,
) -> Result<(Snowflake, WorkerIdLease), SnowflakeError> {
alloc_worker_id(&client, &self.key, self.worker_id_bits).await?;
unreachable!("automatic allocation rejects all requests")
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct WorkerIdNamespace {
pub incarnation: String,
pub first_worker_id: i64,
pub last_worker_id: i64,
}
const INITIALIZE_NAMESPACE: &str = r#"
if redis.call('EXISTS', KEYS[1]) ~= 0 then
return redis.error_reply('worker namespace already exists')
end
redis.call('HSET', KEYS[1], 'incarnation', ARGV[1], 'config', ARGV[2], 'next', ARGV[3], 'last', ARGV[4])
return 1
"#;
const ALLOCATE_NAMESPACE: &str = r#"
local meta = redis.call('HMGET', KEYS[1], 'incarnation', 'config', 'next', 'last')
if meta[1] ~= ARGV[1] or meta[2] ~= ARGV[2] or not meta[3] or not meta[4] then
return redis.error_reply('worker namespace missing or configuration mismatch')
end
local next = tonumber(meta[3])
local last = tonumber(meta[4])
if not next or not last or next ~= math.floor(next) or last ~= math.floor(last)
or next < tonumber(ARGV[3]) or last ~= tonumber(ARGV[4]) or next > last then
return redis.error_reply('worker namespace exhausted or invalid')
end
redis.call('HSET', KEYS[1], 'next', next + 1)
return next
"#;
impl WorkerIdNamespace {
fn identity(&self, config: &SnowflakeConfig) -> Result<String, SnowflakeError> {
nabase::id::validate_bits(config.worker_id_bits, config.seq_bits)?;
if self.incarnation.is_empty()
|| self.incarnation.len() > 128
|| config.key.is_empty()
|| self.first_worker_id < 0
|| self.last_worker_id < self.first_worker_id
|| self.last_worker_id >= (1i64 << config.worker_id_bits)
{
return Err(SnowflakeError::External(
"invalid worker namespace identity or range".into(),
));
}
Snowflake::new(
self.first_worker_id,
config.base_time,
config.worker_id_bits,
config.seq_bits,
)?;
Ok(format!(
"snowflake:{}:{}:{}:{}:{}",
config.base_time,
config.worker_id_bits,
config.seq_bits,
self.first_worker_id,
self.last_worker_id
))
}
pub async fn initialize(
&self,
client: &RedisClient,
config: &SnowflakeConfig,
) -> Result<(), SnowflakeError> {
let identity = self.identity(config)?;
let key = format!("{}:non-reusing-workers", config.key);
let first = self.first_worker_id.to_string();
let last = self.last_worker_id.to_string();
client
.eval::<i64>(
INITIALIZE_NAMESPACE,
&[&key],
&[&self.incarnation, &identity, &first, &last],
)
.await
.map_err(|error| SnowflakeError::External(error.to_string()))?;
Ok(())
}
pub async fn allocate(
&self,
client: &RedisClient,
config: &SnowflakeConfig,
) -> Result<(Snowflake, WorkerIdLease), SnowflakeError> {
let identity = self.identity(config)?;
let key = format!("{}:non-reusing-workers", config.key);
let first = self.first_worker_id.to_string();
let last = self.last_worker_id.to_string();
let worker_id = client
.eval::<i64>(
ALLOCATE_NAMESPACE,
&[&key],
&[&self.incarnation, &identity, &first, &last],
)
.await
.map_err(|error| SnowflakeError::External(error.to_string()))?;
Ok((
Snowflake::new(
worker_id,
config.base_time,
config.worker_id_bits,
config.seq_bits,
)?,
WorkerIdLease { worker_id },
))
}
}
pub struct ManagedSnowflake {
generator: std::sync::Mutex<Option<Snowflake>>,
worker_id: i64,
}
impl ManagedSnowflake {
pub async fn allocate(
client: &RedisClient,
config: &SnowflakeConfig,
namespace: &WorkerIdNamespace,
) -> Result<Self, SnowflakeError> {
let (generator, lease) = namespace.allocate(client, config).await?;
Ok(Self {
generator: std::sync::Mutex::new(Some(generator)),
worker_id: lease.worker_id(),
})
}
pub fn generate(&self) -> Result<i64, SnowflakeError> {
let guard = self
.generator
.lock()
.map_err(|_| SnowflakeError::External("generator state unavailable".into()))?;
let generator = guard
.as_ref()
.ok_or_else(|| SnowflakeError::External("generator is closed".into()))?;
Ok(generator.generate())
}
pub fn close(&self) {
self.generator
.lock()
.unwrap_or_else(|error| error.into_inner())
.take();
}
pub fn worker_id(&self) -> i64 {
self.worker_id
}
}