snowglake
A module for generating unique IDs using the Twitter Snowflake algorithm.
Types
Type of the generator. It is the actual public interface for the generator and should be used to interact with it. It holds the actor subject that is used to handle the generator state.
Examples
import gleam/snowglake
pub type Context {
Context(generator: snowglake.Generator)
}
let assert Ok(generator) = snowglake.new_generator() |> snowglake.start()
let context = Context(generator: generator)
let id = context.generator |> snowglake.generate()
pub opaque type Generator
Values
pub const default_epoch: Int
The default epoch for the generator. Corresponds to the Twitter epoch.
pub fn generate(generator: Generator) -> Int
Generates a new Snowflake ID.
Examples
import gleam/snowglake
let epoch = 1_420_070_400_000
let worker_id = 12
let process_id = 1
let assert Ok(generator) =
snowglake.new_generator()
|> snowglake.with_epoch(epoch)
|> snowglake.with_worker_id(worker_id)
|> snowglake.with_process_id(process_id)
|> snowglake.start()
let id = snowglake.generate(generator)
pub fn generate_lazy(generator: Generator) -> Int
Generates a new Snowflake ID lazily.
It works like the generate function but it does not uses the current
timestamp, instead it consumes all the 4096 IDs of every millisecond.
It may be faster and useful in some cases than the generate function.
For example, to generate a batch of IDs or to generate IDs for a particular
time.
pub fn generate_many(
generator: Generator,
count: Int,
) -> List(Int)
Generates many Snowflake IDs.
Examples
import gleam/snowglake
let assert Ok(generator) = snowglake.new_generator() |> snowglake.start()
let ids = snowglake.generate_many(generator, 5000)
pub fn generate_many_lazy(
generator: Generator,
count: Int,
) -> List(Int)
Generates many Snowflake IDs lazily.
Examples
import gleam/snowglake
let assert Ok(generator) = snowglake.new_generator() |> snowglake.start()
let ids = snowglake.generate_many_lazy(generator, 5000)
pub fn get_now_milliseconds() -> Int
pub fn new_generator() -> Node
Creates a new Snowflake ID generator with default settings.
pub fn timestamp(id: Int, epoch: Int) -> Int
Extracts the timestamp from a Snowflake ID using the provided epoch.
pub fn with_timestamp(node: Node, last_ts: Int) -> Node
Sets timestamp for the generator. Useful for lazy generation. It should not be used along with normal generation.