This repository has been archived by the owner on Feb 8, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathsequencer.go
59 lines (49 loc) · 1.87 KB
/
sequencer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Copyright © 2015 Clement 'cmc' Rey <cr.rey.clement@gmail.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// Package seq offers a gentle overview of the possible design solutions to the
// common problem of generating sequential / monotonically increasing IDs in a
// distributed system.
//
// Specifically, it focuses on maximizing performances and guaranteeing a fair
// distribution of the workload between the nodes as the size of the cluster
// increases.
package seq
import "sort"
// -----------------------------------------------------------------------------
// ID is a 64bits wide unsigned identifier.
type ID uint64
// IDSlice implements the `sort.Interface` for slices of `ID`s.`
//
// It is mainly used for testing purposes.
type IDSlice []ID
func (ids IDSlice) Len() int { return len(ids) }
func (ids IDSlice) Less(i, j int) bool { return ids[i] < ids[j] }
func (ids IDSlice) Swap(i, j int) { ids[i], ids[j] = ids[j], ids[i] }
func (ids IDSlice) Sort() IDSlice { sort.Sort(ids); return ids }
// IDStream is a read-only channel of `ID`s.
//
// An `IDStream` should always starts at `ID(1)`.
type IDStream <-chan ID
// Next is a simple helper to get the next `ID` from an `IDStream`.
//
// It can be helpful if you cannot simply `range` on the stream for
// some reason.
//
// `Next` blocks if no `ID` is available, and returns `ID(0)` if the stream is
// already closed.
func (ids IDStream) Next() ID {
select {
case id := <-ids:
return id
}
}
// -----------------------------------------------------------------------------
// A Sequencer exposes methods to retrieve streams of sequential `ID`s.
type Sequencer interface {
// Stream returns the `IDStream` associated with this `Sequencer`.
Stream() IDStream
// Close stops this `Sequencer` and cleans the associated resources.
Close() error
}