pika_id/snowflake

Types

The deconstructed Snowflake ID content.

pub type DeconstructedSnowflake {
  DeconstructedSnowflake(
    id: Int,
    timestamp: Int,
    epoch: Int,
    node_id: Int,
    seq: Int,
  )
}

Constructors

  • DeconstructedSnowflake(
      id: Int,
      timestamp: Int,
      epoch: Int,
      node_id: Int,
      seq: Int,
    )

Message

opaque

The messages that the generator can receive.

pub opaque type Message(snowflake)

The Snowflake generator content. Holds the state of the gen and is used to generate IDs.

pub opaque type Snowflake

Type of the generator. It holds the actor subject that is used to handle the generator state.

Example

import pika_id/snowflake.{create_snowflake, start_snowflake}

pub fn main() {
  let assert Ok(snowflake_gen) =
    create_snowflake()
    |> start_snowflake()

  let id = snowflake_gen |> snowflake.generate
}
pub opaque type SnowflakeGen

Type alias for the Snowflake ID

pub type SnowflakeId =
  Int

Constants

pub const default_epoch: Int

The default epoch for the generator.

pub const max_seq: Int

The max number of seq that can be generated in a millisec.

Functions

pub fn create_snowflake() -> Snowflake

Creates a new Snowflake generator with default settings.

pub fn deconstruct_snowflake_id(
  snowflake_gen: SnowflakeGen,
  snowflake_id: Int,
) -> DeconstructedSnowflake

Deconstruct the Snowflake ID. Recuires a Snowflake Gen for finding epoch.

Examples

let id = snowflake_gen |> snowflake.generate
snowflake.deconstruct_snowflake_id(snowflake_gen, id)
|> io.debug 
// DeconstructedSnowflake(
//   id, 
//   timestamp, 
//   epoch, 
//   node_id, 
//   seq
// )
pub fn generate(snowflake_gen: SnowflakeGen) -> Int

Generates a new Snowflake ID.

Examples

import pika_id/snowflake.{
  create_snowflake, start_snowflake, with_epoch, with_node_id,
}

pub fn main() {
  let epoch = 1_650_153_600_000
  let node_id = 628

  let assert Ok(snowflake_gen) =
    create_snowflake()
    |> with_epoch(epoch)
    |> with_node_id(node_id)
    |> start_snowflake()

  let id = snowflake_gen |> snowflake.generate
}
pub fn start_snowflake(
  snowflake: Snowflake,
) -> Result(SnowflakeGen, String)

Starts the generator.

pub fn with_epoch(snowflake: Snowflake, epoch: Int) -> Snowflake

Sets the epoch for the generator.

pub fn with_node_id(
  snowflake: Snowflake,
  node_id: Int,
) -> Snowflake

Sets the Node ID for the generator.

Search Document