snowgleam
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/snowgleam
pub type Context {
Context(generator: snowgleam.Generator)
}
let assert Ok(generator) = snowgleam.new_generator() |> snowgleam.start()
let context = Context(generator: generator)
let id = context.generator |> snowgleam.generate()
pub opaque type Generator
Constants
pub const default_epoch: Int
The default epoch for the generator. Corresponds to the Twitter epoch.
Functions
pub fn generate(generator: Generator) -> Int
Generates a new Snowflake ID.
Examples
import gleam/snowgleam
let epoch = 1_420_070_400_000
let worker_id = 12
let process_id = 1
let assert Ok(generator) =
snowgleam.new_generator()
|> snowgleam.with_epoch(epoch)
|> snowgleam.with_worker_id(worker_id)
|> snowgleam.with_process_id(process_id)
|> snowgleam.start()
let id = snowgleam.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/snowgleam
let assert Ok(generator) = snowgleam.new_generator() |> snowgleam.start()
let ids = snowgleam.generate_many(generator, 5000)
pub fn generate_many_lazy(
generator: Generator,
count: Int,
) -> List(Int)
Generates many Snowflake IDs lazily.
Examples
import gleam/snowgleam
let assert Ok(generator) = snowgleam.new_generator() |> snowgleam.start()
let ids = snowgleam.generate_many_lazy(generator, 5000)
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_process_id(node: Node, process_id: Int) -> Node
Sets the process ID for the generator.
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.
pub fn with_worker_id(node: Node, worker_id: Int) -> Node
Sets the worker ID for the generator.