tsid

package module
v1.0.0-alpha Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 17, 2023 License: MIT Imports: 10 Imported by: 0

README

TSID

English | 中文

A unique ID generator based on a timestamp or time series, inspired by Twitter's Snowflake.

Woohoo! ❗️ Timestamp segment and sequence segment is REQUIRED!

FEATURES ✨

  1. The maximum 126 bits
  2. Customize the width of each bits segment
  3. Customize the sequence of bits segments
  4. Support customize encoders
  5. BASE36 is default, using the go package strconv.FormatInt
  6. An improved BASE64 encoder to encode/decode identifiers
  7. Customize the options or use the provided default settings
  8. Supports random or auto-increment identifiers. Note: auto-increment identifiers are still random and not strictly increment
  9. Provides a classic snowflake algorithm (fixed width and position), with better performance
  10. Data source types
    • Timestamps of various precision: nanosecond, millisecond, microsecond, and second
    • Various date and time values: year, month, day, week, hour, minute, second, millisecond, and the number of days and weeks in a year
    • 1 to 63 bits secure random number
    • Option value
    • Environment variables
    • Fixed value
    • Simple sequence/serial number
    • Data sources
    • Parameter by caller

USAGE 🚀

Example 1
package main

import (
  "fmt"

  . "github.com/StarryLab/tsid.go"
)

func main() {
  // $> ./tsid -host=8 -node=6
  host := flag.Int("host", "data center(host) id")
  node := flag.Int("node", "server node id")
  b, e := Snowflake(host, node)
  if e != nil {
    fmt.Println("Error: ", e)
    return
  }
  fmt.Println("TSID: ", b.NextString()) // strconv.FormatInt
}
Example 2
package main

import (
  "flag"
  "fmt"

  . "github.com/StarryLab/tsid.go"
)

func main() {
  // $> ./tsid -host=8
  host := flag.Int("host", "data center(host) id")
  c, e := Simple(host)
  if e != nil {
    fmt.Println("Error: ", e)
    return
  }
  for i := 0; i < 100; i++ {
    fmt.Printf("%3d. %d", i+1, c())
  }
}

Example 3
package main

import (
  "fmt"

  . "github.com/StarryLab/tsid.go"
)

func main() {
  // Environment variable: SERVER_HOST, SERVER_NODE
  opt := O(
    Sequence(SequenceWidth), // 12 bits, REQUIRED!
    Env(6, "SERVER_HOST", 0) // data center id, 6 bits [0, 31]
    Env(4, "SERVER_NODE", 0) // data center id, 4 bits [0, 15]
    Timestamp(TimestampWidth, TimestampMilliseconds), // 41 bits, REQUIRED!
  )
  b, e := Make(opt)
  if e != nil {
    fmt.Println("Error: ", e)
    return
  }
  fmt.Println("TSID: ", b.NextString()) // strconv.FormatInt
}

Documentation

Index

Constants

View Source
const (
	// Min indicates the minimum days approaching the end that the system limits
	Min int64 = 7 * msPerDay
	// EpochMS is the default start timestamp,
	// measured in milliseconds starting
	// at midnight on December 12, 2022
	EpochMS = 1_670_774_400_000
)
View Source
const (
	// HostWidth is the default width of the bits segment,
	// value range [0, 63]
	HostWidth = 6
	// NodeWidth is the default width of the bits segment,
	// value range [0, 15]
	NodeWidth = 4
	// TimestampWidth is the default width of the bits segment.
	// It measures time by the number of seconds that have
	// elapsed since EpochMS, value range [0, 68 years after]
	TimestampWidth = 41
	// SequenceWidth is the default width of the bits segment,
	// value range [0, 4095]
	SequenceWidth = 12
)

Variables

This section is empty.

Functions

func Rand

func Rand(w byte) int64

rand generates a secure random number with a width specified by w, which is the expected bit width, value range is [1, 63].

func SeqID

func SeqID(host, node int64) (func(args ...int64) int64, error)

SeqID implements sequential identifiers. The value range of host is [0, 63]. The value range of node is [0, 15].

if c, e := SeqID(10, 10); e == nil {
   fmt.Println("ID: ", c())
}

func Simple

func Simple(server int64) (func() int64, error)

Simple implements a simple snowflake algorithm. The value range of server is [0, 1023].

if b, e := SimpleSnowflake(16); e == nil {
  fmt.Println("ID:")
  for i := 0; i < 100; i++ {
    fmt.Println(i+1, ". ", b())
  }
} else {
  fmt.Println("Error: ", e)
}

Types

type Base64

type Base64 struct {
	Aligned bool
}

func (*Base64) Decode

func (e *Base64) Decode(no string) (id *ID, err error)

func (*Base64) Encode

func (e *Base64) Encode(id *ID) string

type Bits

type Bits struct {
	// Source indicates that bits segment data source
	Source DataSource
	Width  byte
	Value  int64
	// Key indicates the data source key
	Key string
	// Index indicates the data source index
	Index int
	// contains filtered or unexported fields
}

func Arg

func Arg(width byte, index int, fallback int64) Bits

Arg to make a bits segment, which value from caller arguments

func Data

func Data(width byte, key string, index int, fallback int64) Bits

Data to make a bits segment, which value from data provider

func Env

func Env(width byte, name string, fallback int64) Bits

Env to make a bits segment, which value from OS environment variable

func Fixed

func Fixed(width byte, value int64) Bits

Fixed to make a bits segment, which value is fixed

func Host

func Host(width byte, fallback int64) Bits

Host to make the bits segment of data center id, which value from settings

func Node

func Node(width byte, fallback int64) Bits

Node to make the bits segments of server node, which value from settings

func Option

func Option(width byte, key string, fallback int64) Bits

Option to make a bits segment, which value from settings in options

func Random

func Random(width byte) Bits

Random to make a bits segment, which value from random number

func Sequence

func Sequence(width byte) Bits

Sequence to make a bits segment, which value from runtime sequence

func Timestamp

func Timestamp(width byte, t DateTimeType) Bits

Timestamp to make a bits segment, which value from system unix timestamp

type Builder

type Builder struct {
	sync.Mutex

	Encoder Encoder
	Debug   bool
	// contains filtered or unexported fields
}

func Make

func Make(opt Options) (m *Builder, err error)

func Snowflake

func Snowflake(host, node int64) (*Builder, error)

Snowflake implements the common snowflake algorithm. The value range of host is [0, 63]. The value range of node is [0, 15].

func (*Builder) Next

func (b *Builder) Next(argv ...int64) (id *ID, info *DebugInfo)

func (*Builder) NextString

func (b *Builder) NextString(argv ...int64) string

func (*Builder) ResetEpoch

func (b *Builder) ResetEpoch(epoch int64) error

type DataProvider

type DataProvider interface {
	Read(name string, index int) int64
}

type DataSource

type DataSource int
const (
	// Static indicates that the value is from default
	Static DataSource = iota
	// Args indicates that the value is from arguments of caller
	Args
	// OS indicates that the value is from OS environment
	OS
	// Settings indicates that the value is from options
	Settings
	// SequenceID indicates that the value is from sequence value
	SequenceID
	// DateTime indicates that the value is from system unix timestamp in nanoseconds
	DateTime
	// Random indicates that the value is from a random number
	RandomID
	// Provider indicates that the value is from data provider
	Provider
)

func (DataSource) String

func (d DataSource) String() string

type DataWrapper

type DataWrapper struct {
	// contains filtered or unexported fields
}

func DataWrap

func DataWrap(hook ...func(string, int) int64) (dw *DataWrapper)

func (*DataWrapper) Read

func (w *DataWrapper) Read(name string, index int) int64

func (*DataWrapper) Write

func (w *DataWrapper) Write(name string, data ...int64) *DataWrapper

type DateTimeType

type DateTimeType int
const (
	TimestampMilliseconds DateTimeType = iota
	TimestampNanoseconds
	TimestampMicroseconds
	TimestampSeconds
	TimeMillisecond
	TimeSecond
	TimeMinute
	TimeHour
	TimeDay
	TimeMonth
	TimeYear
	TimeYearDay
	TimeWeekday
	TimeWeekNumber
)

func (DateTimeType) String

func (d DateTimeType) String() string

type DebugInfo

type DebugInfo struct {
	Now,
	Sequence int64
	Bits []int64
}

type DecodeError

type DecodeError struct {
	No  string
	Err error
}

func (*DecodeError) Error

func (e *DecodeError) Error() string

func (*DecodeError) Unwrap

func (e *DecodeError) Unwrap() error

type Encoder

type Encoder interface {
	Encode(id *ID) string
	Decode(no string) (id *ID, err error)
}

type ID

type ID struct {
	Main,
	Ext int64
	Signed bool
}

type Options

type Options struct {
	// Min indicates the minimum days approaching the end
	Min,

	EpochMS int64
	// Signed is used to on/off the sign bit
	Signed bool
	// contains filtered or unexported fields
}

Options MUST include DateTime segment AND SequenceID segment

func Config

func Config(host, node int64, segments ...Bits) *Options

Config is a shortcut for make Options, segments MUST include DateTime segment AND SequenceID segment.

func Default

func Default(host, node int64) *Options

Default is a shortcut for make Options, segments MUST include DateTime segment AND SequenceID segment.

func Define

func Define(settings map[string]int64, segments ...Bits) (o *Options)

Define is a shortcut for make Options, segments MUST include DateTime segment AND SequenceID segment.

func O

func O(segments ...Bits) (o *Options)

O is a shortcut for make Options

func Shuffle

func Shuffle(host, node int64) *Options

Shuffle is a shortcut for make Options.

func (*Options) Add

func (o *Options) Add(b Bits) *Options

Add to add a bits segment

func (*Options) Bind

func (o *Options) Bind(p DataProvider) *Options

Bind to bind the data provider

func (*Options) NewEpoch

func (o *Options) NewEpoch(v int64) *Options

NewEpoch to set the start timestamp

func (*Options) Set

func (o *Options) Set(k string, v int64) *Options

Set to set the settings

type OptionsError

type OptionsError struct {
	Name  string
	Extra []string
	Err   error
}

func (*OptionsError) Error

func (e *OptionsError) Error() string

func (*OptionsError) SameAs

func (e *OptionsError) SameAs(err error) bool

func (*OptionsError) Unwrap

func (e *OptionsError) Unwrap() error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL