Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 58 additions & 16 deletions ulid.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,9 +132,9 @@ func MustNewDefault(t time.Time) ULID {
return MustNew(Timestamp(t), defaultEntropy)
}

var defaultEntropy = func() io.Reader {
var defaultEntropy = func() *lockedMonotonicEntropy {
rng := rand.New(rand.NewSource(time.Now().UnixNano()))
return &LockedMonotonicReader{MonotonicReader: Monotonic(rng, 0)}
return &lockedMonotonicEntropy{MonotonicEntropy: Monotonic(rng, 0)}
}()

// DefaultEntropy returns a thread-safe per process monotonically increasing
Expand All @@ -145,11 +145,16 @@ func DefaultEntropy() io.Reader {

// Make returns a ULID with the current time in Unix milliseconds and
// monotonically increasing entropy for the same millisecond.
// It is safe for concurrent use, leveraging a sync.Pool underneath for minimal
// contention.
// It is safe for concurrent use.
func Make() (id ULID) {
// NOTE: MustNew can't panic since DefaultEntropy never returns an error.
return MustNew(Now(), defaultEntropy)
ms := Now()
if err := id.SetTime(ms); err != nil {
panic(err)
}
if err := defaultEntropy.monotonicRead(ms, id[6:]); err != nil {
panic(err)
}
return id
}

// Parse parses an encoded ULID, returning an error in case of failure.
Expand Down Expand Up @@ -611,25 +616,66 @@ func (r *LockedMonotonicReader) MonotonicRead(ms uint64, p []byte) (err error) {
// MonotonicEntropy is an opaque type that provides monotonic entropy.
type MonotonicEntropy struct {
io.Reader
ms uint64
inc uint64
entropy uint80
rand [8]byte
rng rng
ms uint64
inc uint64
entropy uint80
initialized bool // A zero entropy seed is valid state, not an uninitialized value.
seed [10]byte
rand [8]byte
rng rng
}

// MonotonicRead implements the MonotonicReader interface.
func (m *MonotonicEntropy) MonotonicRead(ms uint64, entropy []byte) (err error) {
if !m.entropy.IsZero() && m.ms == ms {
if m.initialized && m.ms == ms {
err = m.increment()
m.entropy.AppendTo(entropy)
} else if _, err = io.ReadFull(m.Reader, entropy); err == nil {
m.ms = ms
m.entropy.SetBytes(entropy)
m.initialized = true
}
return err
}

// monotonicRead is the Make fast path. It never passes the output slice to an
// entropy reader; on a new timestamp it reads into the receiver's buffer first.
func (m *MonotonicEntropy) monotonicRead(ms uint64, entropy []byte) error {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did you make the changes in a separate method, rather than just updating MonotonicRead? Please respond plainly.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually this is worth saying explicitly: Make isn't some special bespoke thing, it's just a little helper over the exported package API for a common use case, constructing a ULID (New()) with the current system time (Now()) and a reasonable monotonic entropy source (DefaultEntropy) without having to provide either of those params explicitly. Avoiding allocs is great but that optimization shouldn't just be in one specific helper function, it should be available so users can leverage it too, and so shouldn't rely on an unexported method that only this package can call...

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR head: f3a782943b10f59e3914700fd062725a3ba9d830. Response to this feedback.

The existing exported MustNewDefault(time.Time) now reaches the same value path, so callers with a timestamp can use the optimization through a public helper without new API. I left direct New and MustNew generic because they accept arbitrary readers; those direct default-entropy calls remain generic and are not claimed allocation-free.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR head: f3a782943b10f59e3914700fd062725a3ba9d830. Response to this feedback.

The value path is separate so Make's returned entropy slice is not passed through the generic reader interface, where New's MonotonicReader path makes it escape. The fast path reads new seed bytes into wrapper-owned storage and copies them to the value; the generic MonotonicRead method remains for public reader dispatch.

if m.initialized && m.ms == ms {
err := m.increment()
m.entropy.AppendTo(entropy)
return err
}

n, err := io.ReadFull(m.Reader, m.seed[:])
copy(entropy, m.seed[:n])
if err != nil {
return err
}
m.ms = ms
m.entropy.SetBytes(m.seed[:])
m.initialized = true
return nil
}

// lockedMonotonicEntropy serializes access to the process-wide entropy state.
type lockedMonotonicEntropy struct {
mu sync.Mutex
*MonotonicEntropy

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, please use a named field here instead of embedding, and explicitly define Read so that it takes the lock before using MonotonicEntropy.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment here is also wrong, it wraps any monotonic entropy source, not only the specific singleton mentioned.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR head: f3a782943b10f59e3914700fd062725a3ba9d830. Response to this feedback.

The wrapper now stores monotonic *MonotonicEntropy as a named field. Its explicit Read method locks before using the wrapped reader, and both MonotonicRead and value construction use that same mutex.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR head: f3a782943b10f59e3914700fd062725a3ba9d830. Response to this feedback.

I changed the wrapper comment to describe synchronization of the wrapped monotonic source rather than implying it only applies to the process singleton.

}

func (r *lockedMonotonicEntropy) MonotonicRead(ms uint64, p []byte) error {
r.mu.Lock()
defer r.mu.Unlock()
return r.MonotonicEntropy.MonotonicRead(ms, p)
}

func (r *lockedMonotonicEntropy) monotonicRead(ms uint64, p []byte) error {
r.mu.Lock()
defer r.mu.Unlock()
return r.MonotonicEntropy.monotonicRead(ms, p)
}

// increment the previous entropy number with a random number
// of up to m.inc (inclusive).
func (m *MonotonicEntropy) increment() error {
Expand Down Expand Up @@ -716,7 +762,3 @@ func (u *uint80) Add(n uint64) (overflow bool) {
}
return u.Hi < hi
}

func (u uint80) IsZero() bool {
return u.Hi == 0 && u.Lo == 0
}
88 changes: 88 additions & 0 deletions ulid_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Copyright 2016 The Oklog Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package ulid

import (
"bytes"
"errors"
"testing"
)

// These tests replace process-wide entropy and must not run in parallel.
func setDefaultMonotonicEntropy(t *testing.T, entropy MonotonicEntropy) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't valid, and even if it was I don't think these tests are testing anything useful. Please remove this test file.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR head: f3a782943b10f59e3914700fd062725a3ba9d830. Response to this feedback.

The earlier ulid_internal_test.go has been removed. TestDefaultConstructorsShareEntropy and TestDefaultEntropyConcurrent are in the existing external ulid_test.go and exercise public constructor ordering and concurrent default-entropy access.

t.Helper()

defaultEntropy.mu.Lock()
original := *defaultEntropy.MonotonicEntropy
*defaultEntropy.MonotonicEntropy = entropy
defaultEntropy.mu.Unlock()

t.Cleanup(func() {
defaultEntropy.mu.Lock()
*defaultEntropy.MonotonicEntropy = original
defaultEntropy.mu.Unlock()
})
}

func TestMakeSharesDefaultEntropy(t *testing.T) {
seed := make([]byte, 10)
setDefaultMonotonicEntropy(t, MonotonicEntropy{
Reader: bytes.NewReader(bytes.Repeat([]byte{0}, 20)),
inc: 1,
})

id := Make()
if !bytes.Equal(id[6:], seed) {
t.Fatalf("Make entropy: got %v, want %v", id[6:], seed)
}

next, err := New(id.Time(), DefaultEntropy())
if err != nil {
t.Fatal(err)
}

want := id
for i := len(want) - 1; i >= 6; i-- {
want[i]++
if want[i] != 0 {
break
}
}
if next != want {
t.Fatalf("New after Make: got %v, want %v", next, want)
}
}

func TestMakePanicsOnEntropyReadError(t *testing.T) {
want := errors.New("entropy read failed")
setDefaultMonotonicEntropy(t, MonotonicEntropy{
Reader: errorEntropyReader{err: want},
inc: 1,
})

defer func() {
if got := recover(); got != want {
t.Fatalf("Make panic: got %v, want %v", got, want)
}
}()
_ = Make()
}

type errorEntropyReader struct {
err error
}

func (r errorEntropyReader) Read([]byte) (int, error) {
return 0, r.err
}
30 changes: 30 additions & 0 deletions ulid_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,27 @@ func TestScan(t *testing.T) {
}
}

func TestMonotonicZeroEntropySeed(t *testing.T) {
t.Parallel()

entropy := ulid.Monotonic(bytes.NewReader(bytes.Repeat([]byte{0}, 20)), 1)
previous, err := ulid.New(123, entropy)
if err != nil {
t.Fatal(err)
}

next, err := ulid.New(123, entropy)
if err != nil {
t.Fatal(err)
}

want := previous
want[len(want)-1]++
if next != want {
t.Fatalf("zero-seed increment: got %v, want %v", next, want)
}
}

func TestMonotonic(t *testing.T) {
now := ulid.Now()
for _, e := range []struct {
Expand Down Expand Up @@ -711,6 +732,15 @@ func BenchmarkMustNew(b *testing.B) {
})
}

var benchmarkMakeSink ulid.ULID

func BenchmarkMake(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
benchmarkMakeSink = ulid.Make()
}
}

func benchmarkMakeULID(b *testing.B, f func(uint64, io.Reader)) {
b.ReportAllocs()
b.SetBytes(int64(len(ulid.ULID{})))
Expand Down
Loading