refid

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2023 License: MIT Imports: 12 Imported by: 1

README

RefID

Build Status GoDoc Go Report Card License

About

A RefID (short for Reference Identifier) is a sortable unique identifier, similar to UUIDv7, with a few difference.

There are two types of RefIDs: TimePrefixed and RandomPrefixed.

TimePrefixed (type:0x00)
 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                           unix_ts_ms                          |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|           unix_ts_ms          |    rand_a   |t|      tag      |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                             rand_b                            |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                             rand_b                            |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
unix_ts_ms:
    48 bits big-endian unsigned number of Unix epoch timestamp milliseconds.
    (2284 years worth... until about year 4200 or so)
rand_a:
    7 bits random pad. fill with crypto/rand random.
t:
    1 bit for type. either RefId (type:0) or RefIdRand (type:1)
tag:
    8 bits tag. 255 separate tags (0 being untagged).
rand_b:
    64 bits random pad. fill with crypto/rand random.
RandomPrefixed (type:0x01)
 0                   1                   2                   3
 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                             rand_a                            |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                    rand_a                   |t|      tag      |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                             rand_b                            |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|                             rand_b                            |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
rand_a:
    55 bits random pad. fill with crypto/rand random.
t:
    1 bit for type. either RefId (type:0) or RefIdRand (type:1)
tag:
    8 bits tag. 255 separate tags (0 being untagged).
rand_b:
    64 bits random pad. fill with crypto/rand random.

Features

General:

  • tagging (support for 255 distinct tags)
  • supports go/sql scanner/valuer
  • multiple encodings supported: native (base32), base64, base16 (hex)
  • similar to UUIDv7, with different tradeoffs

TimePrefix:

  • unix timestamp with millisecond precision
  • Compared to UUIDv7
    • tagging support
    • 48 bits of Unix timestamp milliseconds from epoch (similar to UUIDv7)
    • slightly smaller random section (71 vs 74 bits), though still good collision resistance
    • not a standard

RandomPrefix:

  • Compared to UUIDv7
    • tagging support
    • slightly smaller random section (119 vs 122 bits), though still good collision resistance
    • not a standard

Non-Features

  • refids, like UUIDs, do not internally perform any signature verification. If the validity of the encoded timestamp and tag are required for any secure operations, the refid SHOULD be externally verified before parsing/decoding.
    An example of this could be a wrapping encoder/decoder doing hmac signing and verification.

Inspirations

Installation

go get -u github.com/dropwhile/refid

Usage

Simple
// generate a TimePrefixed RefID
rID, err := refid.New()
// generate a TimePrefixed RefID (or panic)
rID = refid.Must(refid.New())
// generate a RandomPrefixed RefID (or panic)
rID = refid.Must(refid.NewRandom())

// encoding...
// encode to native encoding (base32 with Crockford alphabet)
s := rID.String() // "0r326xw2xbpga5tya7px89m7hw"
// encode to base64 encoding
s = rID.ToBase64String() // "BgYjd4Lq7QUXXlHt1CaHjw"
// encode to hex encoding
s = rID.ToHexString() // "0606237782eaed05175e51edd426878f"
// raw bytes
b := rID.Bytes()

// decoding...
// decode from native
rID, err := refid.Parse(s)
// decode from base64
rID, err = refid.FromBase64String(s)
// decode from hex
rID, err = refid.FromHexString(s)

// get the time out of a TimePrefixed RefID (as a time.Time)
var ts time.Time = rID.Time()
Tagging

Simple tagging usage:

myTag := 2

// generate a RefID with tag set to 1
rID = refid.Must(refid.NewTagged(1))
// you can also set it manually after generation
rID.SetTag(myTag)
// check if it is tagged
rID.Tagged() // true
// check if it has a specific tag
rID.HasTag(1) // false
rID.HasTag(2) // true


s := rID.String()
// require desired tag or fail parsing
r, err := refid.ParseTagged(1, s) // err != nil here, as refid was tagged 2
r, err = refid.ParseTagged(2, s) // err == nil here, as refid was tagged 2
What use is tagging?

Tag support ensures that a refid of a certain tag type can be made distinct from other refids -- those of a different tag type, or those with no tag type.

A hypothetical example is a refid url paramater for a type named "author", can be enforced as invalid when someone attempts to supply it as input for a different refid url parameter for a type named "book".

Making tagging usage easier with RefIDTagger:

// AuthorRefID ensures it will only succesfully generate and parse tag=2 refids
AuthorRefIDT := refid.RefIDTagger(2)
// BookRefID ensures it will only succesfully generate and parse tag=3 refids
BookRefIDT := refid.RefIDTagger(3)

authorRefID := refid.Must(AuthorRefIDT.New()) // generated with a tag of 2
authorRefID.HasTag(2) // true
bookRefID := refid.Must(BookRefIDT.New()) // generated with a tag of 3
bookRefID.HasTag(3) // true

r, err := AuthorRefIDT.Parse(authorRefID.String()) // succeeds; err == nil
r, err = bookRefID.Parse(authorRefID.String()) // fails; err != nil

reftool command like utility

Installation:

go install github.com/dropwhile/refid/cmd/reftool@latest
# generate a refid with a tag of 5
% reftool generate -t 5
native enc:   0r326xw2xbpga5tya7px89m7hw
hex enc:      0606237782eaed05175e51edd426878f
base64 enc:   BgYjd4Lq7QUXXlHt1CaHjw
tag value:    5
type:         TimePrefixed
time(string): 2023-09-24T23:47:38.954477Z
time(millis): 1695599258954477

# generate a refid with a tag of 5, and only output the native(base32) encoding
% reftool generate -t 5 -o
0r34ky6h51r012an8skhbsvxt0

# generate a refid with a tag of 5, and only output the hex encoding
% reftool generate -t 5 -o=hex
060649f82794f10039169e91d0696763

# generate a refid with a tag of 5, and only output the base64 encoding
% reftool generate -o=base64
BgZJ-i1F2wALdZFJrWvNzA

# genrate a refid with a tag of 2, at a specific timestamp
% reftool generate -t 2 -w "2023-01-01T00:00:11.123456Z"
native enc:   0qrjh15pzc004nzrkbpcp2v0wm
hex enc:      05f12884b6fb000257f89aeccb0b60e5
base64 enc:   BfEohLb7AAJX-Jrsywtg5Q
tag value:    2
type:         TimePrefixed
time(string): 2023-01-01T00:00:11.123456Z
time(millis): 1672531211123456

# decode a refid and display
% reftool decode 0qrjh15pzc004nzrkbpcp2v0wm
native enc:   0qrjh15pzc004nzrkbpcp2v0wm
hex enc:      05f12884b6fb000257f89aeccb0b60e5
base64 enc:   BfEohLb7AAJX-Jrsywtg5Q
tag value:    2
type:         TimePrefixed
time(string): 2023-01-01T00:00:11.123456Z
time(millis): 1672531211123456

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (

	// Nil is the nil RefID, that has all 128 bits set to zero.
	Nil = RefID{}
)

Functions

func Must

func Must[T any](r T, err error) T

Must is a helper that wraps a call to a function returning (any, error) and panics if the error is non-nil. It is intended for use in variable initializations such as

var (
	refA = refid.Must(refid.New())
	refB = refid.Must(refid.NewTagged(2))
	refC = refid.Must(refid.Parse("0r2nbq0wqhjg186167t0gcd1gw"))
	refD = refid.Must(refid.ParseTagged("0r2nbq0wqhjg186167t0gcd1gw", 2))
)

Types

type AnyMatcher

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

A matcher that supports the following interfaces:

func MatchAny

func MatchAny(tag byte) AnyMatcher

Create a AnyMatcher matcher that matches that matches against a specific Tag. Any valid RefIDs that do not match the tag specified, will be considered not matching.

If tag is 0, will support matching any RefID (tag is then ignored)

Example usage:

mock.ExpectQuery("^INSERT INTO some_table (.+)").
 WithArgs(refid.MatchAny(1), 1).
 WillReturnRows(rows)

func (AnyMatcher) Match

func (a AnyMatcher) Match(v interface{}) bool

type NullRefID added in v1.0.1

type NullRefID struct {
	RefID RefID
	Valid bool
}

NullRefID can be used with the standard sql package to represent a RefID value that can be NULL in the database.

func (NullRefID) MarshalJSON added in v1.0.1

func (u NullRefID) MarshalJSON() ([]byte, error)

MarshalJSON marshals the NullRefID as null or the nested RefID

func (*NullRefID) Scan added in v1.0.1

func (u *NullRefID) Scan(src interface{}) error

Scan implements the sql.Scanner interface.

func (*NullRefID) UnmarshalJSON added in v1.0.1

func (u *NullRefID) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a NullRefID

func (NullRefID) Value added in v1.0.1

func (u NullRefID) Value() (driver.Value, error)

Value implements the sql/driver.Valuer interface.

type RefID added in v1.0.1

type RefID [size]byte

A RefID is a 16 byte identifier that has:

  • tagging support (support for 255 distinct tag types)
  • go/sql scanner/valuer support
  • multiple encodings supported: native (base32), base64, base16 (hex)

func FromBytes

func FromBytes(input []byte) (RefID, error)

FromBytes creates a new RefID from a byte slice. Returns an error if the slice does not have a length of 16. The bytes are copied from the slice.

func FromString

func FromString(s string) (RefID, error)

FromString is an alias of Parse.

func New

func New() (RefID, error)

New returns a new TimePrefixed type RefID.

If random bytes cannot be generated, it will return an error.

func NewRandom added in v1.0.2

func NewRandom() (RefID, error)

NewRandom returns a new RandomPrefixed type RefID.

If random bytes cannot be generated, it will return an error.

func NewRandomTagged added in v1.0.2

func NewRandomTagged(tag byte) (RefID, error)

NewRandomTagged returns a new RandomPrefixed type RefID tagged with tag.

If random bytes cannot be generated, it will return an error.

func NewTagged

func NewTagged(tag byte) (RefID, error)

NewTagged returns a new TimePrefixed type RefID tagged with tag.

If random bytes cannot be generated, it will return an error.

func Parse

func Parse(s string) (RefID, error)

Parse parses a textual RefID representation, and returns a RefID. Supports parsing the following text formats:

  • native/base32 (Crockford's alphabet)
  • base64
  • base16/hex

Will return an error on parse failure.

func ParseWithRequire added in v1.0.2

func ParseWithRequire(s string, reqs ...Requirement) (RefID, error)

ParseWithRequire parses a textual RefID representation (same formats as Parse), while additionally requiring each reqs Requirement to pass, and returns a RefID.

Returns an error if RefID fails to parse or if any of the reqs Requirements fail.

Example:

ParseWithRequire("afd661f4f2tg2vr3dca92qp6k8", HasType(RandomPrefix))

func (RefID) Bytes added in v1.0.1

func (r RefID) Bytes() []byte

Bytes returns a slice of a copy of the current RefID underlying data.

func (*RefID) ClearTag added in v1.0.1

func (r *RefID) ClearTag() *RefID

ClearTag clears the RefID tag.

func (RefID) Equal added in v1.0.1

func (r RefID) Equal(other RefID) bool

Equal compares a RefID to another RefID to see if they have the same underlying bytes.

func (RefID) Format added in v1.0.1

func (r RefID) Format(f fmt.State, c rune)

Format implements the fmt.Formatter interface.

func (RefID) HasTag added in v1.0.1

func (r RefID) HasTag(tag byte) bool

IsTagged reports whether the RefID is tagged and if so, if it is tagged with tag.

func (RefID) HasType added in v1.0.2

func (r RefID) HasType(t Type) bool

HasType reports whether the [RefId] is of type t.

func (RefID) IsNil added in v1.0.1

func (r RefID) IsNil() bool

IsNil reports if the RefID is the nil value RefID.

func (RefID) IsTagged added in v1.0.1

func (r RefID) IsTagged() bool

IsTagged reports whether the RefID is tagged.

func (RefID) MarshalBinary added in v1.0.1

func (r RefID) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

func (RefID) MarshalJSON added in v1.0.1

func (r RefID) MarshalJSON() ([]byte, error)

MarshalJson implements the json.Marshaler interface.

func (RefID) MarshalText added in v1.0.1

func (r RefID) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*RefID) Scan added in v1.0.1

func (r *RefID) Scan(src interface{}) error

Scan implements the sql.Scanner interface. A 16-byte slice will be handled by RefID.UnmarshalBinary, while a longer byte slice or a string will be handled by RefID.UnmarshalText.

func (*RefID) SetTag added in v1.0.1

func (r *RefID) SetTag(tag byte) *RefID

SetTag sets the RefID tag to the specified value.

func (*RefID) SetTime added in v1.0.1

func (r *RefID) SetTime(ts time.Time) error

SetTime sets the time component of a RefID to the time specified by ts.

func (RefID) String added in v1.0.1

func (r RefID) String() string

String returns the native (base32 w/Crockford alphabet) textual represenation of a RefID

func (RefID) Tag added in v1.0.1

func (r RefID) Tag() byte

Tag returns the current tag of the RefID. If the RefID is untagged, it will retrun 0.

func (RefID) Time added in v1.0.1

func (r RefID) Time() time.Time

Time returns the timestamp portion of a RefID as a time.Time

func (RefID) ToBase32String added in v1.0.2

func (r RefID) ToBase32String() string

ToBase32String is an alias of [String]

func (RefID) ToBase64String added in v1.0.1

func (r RefID) ToBase64String() string

String returns the base64 textual represenation of a RefID

func (RefID) ToHexString added in v1.0.1

func (r RefID) ToHexString() string

String returns the base16/hex textual represenation of a RefID

func (RefID) ToString added in v1.0.1

func (r RefID) ToString() string

ToString is an alias of [String]

func (RefID) Type added in v1.0.2

func (r RefID) Type() Type

Type returns the type of the RefID.

func (*RefID) UnmarshalBinary added in v1.0.1

func (r *RefID) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface. It will return an error if the slice isn't of appropriate size.

func (*RefID) UnmarshalJSON added in v1.0.1

func (r *RefID) UnmarshalJSON(b []byte) error

UnmarshalJson implements the json.Unmarshaler interface.

func (*RefID) UnmarshalText added in v1.0.1

func (r *RefID) UnmarshalText(b []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. It will return an error if the slice isn't of appropriate size.

func (RefID) Value added in v1.0.1

func (r RefID) Value() (driver.Value, error)

Value implements the sql/driver.Valuer interface.

type Requirement added in v1.0.2

type Requirement func(RefID) error

func HasTag added in v1.0.2

func HasTag(tag byte) Requirement

func HasType added in v1.0.2

func HasType(t Type) Requirement

type Tagger

type Tagger byte

A Tagger is a conveniece container for encoding and parsing RefID's of a specific tag.

func NewTagger

func NewTagger(tag byte) Tagger

NewTagger returns a new Tagger with tag

func (Tagger) AnyMatcher

func (t Tagger) AnyMatcher() AnyMatcher

AnyMather returns an AnyMatcher, which will match only against a RefID tagged with the same tag as the Tagger

func (Tagger) HasCorrectTag

func (t Tagger) HasCorrectTag(r RefID) bool

HasTag reports whether a RefID is tagged with the same tag as the Tagger

func (Tagger) HasTag

func (t Tagger) HasTag(r RefID, tag byte) bool

HasTag reports whether a RefID is tagged with a given tag

func (Tagger) IsTagged

func (t Tagger) IsTagged(r RefID) bool

IsTagged reports wheater a RefID is tagged at all. Note: This only checks that the RefID is tagged, not that it is tagged with the same tag as Tagger. For that functionality use Tagger.HasCorrectTag.

func (Tagger) New

func (t Tagger) New() (RefID, error)

New generates a new [TimePrefix] type RefID with tag set to the tag of the Tagger

func (Tagger) NewRandom added in v1.0.2

func (t Tagger) NewRandom() (RefID, error)

NewRandom generates a new [RandomPrefix] type RefID with tag set to the tag of the Tagger

func (Tagger) Parse

func (t Tagger) Parse(s string) (RefID, error)

Parse parses a RefID, additionally enforcing that it is tagged with the same tag as the Tagger

func (Tagger) ParseWithRequire added in v1.0.2

func (t Tagger) ParseWithRequire(s string, reqs ...Requirement) (RefID, error)

ParseWithRequire parses a textual RefID representation (same formats as Parse), enforcing that it is tagged with the same tag as the Tagger, while additionally requiring each reqs Requirement to pass, and returns a RefID.

Returns an error if RefID fails to parse, is not tagged with the same tag as Tagger, or if any of the reqs Requirements fail.

Example:

ParseWithRequire("afd661f4f2tg2vr3dca92qp6k8", HasType(RandomPrefix))

func (Tagger) Tag

func (t Tagger) Tag() byte

Tag returns the tag of the Tagger

type Type added in v1.0.2

type Type byte
const (
	TimePrefixed   Type = 0x00
	RandomPrefixed Type = 0x01
)

func (Type) String added in v1.0.2

func (i Type) String() string

Directories

Path Synopsis
cmd
reftool command

Jump to

Keyboard shortcuts

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