Documentation
¶
Overview ¶
Package gcosid is part of the gcosid project.
Status: experimental scaffold (v0.0.0-dev). The API is not stable yet.
Index ¶
- Constants
- Variables
- func JoinNodes(nodes []string) string
- type AtomicGenerator
- type CachedSharding
- type ChainGenerator
- type ChainOption
- type ClockSync
- type ClockSyncGenerator
- type CosIDState
- type DateGroup
- type DatePrefix
- type DefaultClockSync
- type Generator
- type GroupBy
- type GroupedAllocator
- type GroupedGenerator
- func (g *GroupedGenerator) Close(ctx context.Context) error
- func (g *GroupedGenerator) Namespace() string
- func (g *GroupedGenerator) Next(ctx context.Context) (int64, GroupedKey, error)
- func (g *GroupedGenerator) NextString(ctx context.Context, delimiter string, actual StringConverter) (string, error)
- type GroupedKey
- type GroupedPrefix
- type Guarder
- type GuarderOption
- type GuardianState
- type HostAddressSupplier
- type Injector
- type InstanceID
- type IntegerGenerator
- type IntervalNode
- type IntervalStep
- type IntervalTimeline
- type Layout
- type LazyGenerator
- type LeaseDistributor
- type LeaseOption
- type LocalDateTimeConverter
- type LocalHostAddress
- type LocalStateStorage
- type MachineIdDistributor
- type MachineState
- type MachineStateStorage
- type ManualDistributor
- type MemoryAllocator
- type MemoryMachineStorage
- type ModCycle
- type NamedGenerator
- type NamespacedInstanceID
- type NoopGuarder
- type Period
- type Prefix
- type Provider
- func (p *Provider) All() []Generator
- func (p *Provider) Clear()
- func (p *Provider) Get(name string) (Generator, bool)
- func (p *Provider) Names() []string
- func (p *Provider) Remove(name string) Generator
- func (p *Provider) RemoveShare() Generator
- func (p *Provider) Required(name string) (Generator, error)
- func (p *Provider) Set(name string, gen Generator)
- func (p *Provider) SetShare(gen Generator)
- func (p *Provider) Share() Generator
- func (p *Provider) ShareRequired() (Generator, error)
- type Radix
- type RadixStateParser
- type Segment
- type SegmentAllocator
- type SegmentGenerator
- type SegmentOption
- type Sharding
- type SnowflakeConverter
- type SnowflakeFriendly
- type SnowflakeGenerator
- type SnowflakeOption
- type StandardConverter
- type Stat
- type State
- type StatefulSetDistributor
- type Statistical
- type StepUnit
- type StringClockSyncGenerator
- type StringConverter
- type StringCosIDGenerator
- func (g *StringCosIDGenerator) GenerateAsString(ctx context.Context) (string, error)
- func (g *StringCosIDGenerator) Next(context.Context) (int64, error)
- func (g *StringCosIDGenerator) NextState() (CosIDState, error)
- func (g *StringCosIDGenerator) Parser() RadixStateParser
- func (g *StringCosIDGenerator) Stat() Stat
- func (g *StringCosIDGenerator) StateOfString(id string) (CosIDState, error)
- type StringCosIDOption
- type StringGenerator
- type StringSegmentID
- type StringSnowflakeID
- type Suffix
- type ToString
- type UUIDGenerator
- type UncertaintyGenerator
Constants ¶
const ( TTLForever = core.TTLForever CosIdEpoch = core.CosIdEpoch CosIdEpochSecond = core.CosIdEpochSecond TotalBit = core.TotalBit JSMaxSafeNumberBit = core.JSMaxSafeNumberBit JSMaxSafeNumber = core.JSMaxSafeNumber DefaultHostnameEnv = machine.DefaultHostnameEnv )
const ( CosIDStringTimestampBits = 44 CosIDStringMachineBits = 20 CosIDStringSequenceBits = 16 )
CosID's string generator family (RadixCosIdGenerator) uses a different layout from the int64 snowflake: 44 timestamp bits + 20 machine bits + 16 sequence bits. The sum exceeds 63 on purpose — the output is a fixed-width string, not a packed int64, and the timestamp is the *raw* epoch millisecond (no epoch offset).
const DefaultSafeDistance = 2
DefaultSafeDistance is CosID's SegmentChainId.DEFAULT_SAFE_DISTANCE: the chain keeps two segments ready ahead of the cursor.
ShareName is CosID's IdGeneratorProvider.SHARE: the generator used when a caller does not name one. `@CosId` without a value resolves to it, and every registry operation treats it like any other name.
const TagKey = "cosid"
TagKey marks a struct field as an id field — the Go equivalent of CosID's `@CosId` annotation:
type Order struct {
ID int64 `cosid:"order"`
Name string
}
The tag value is the generator name in the Injector's registry. `cosid:"-"` opts a field out, and an empty value (`cosid:""`) means the shared generator, which is what CosID's `@CosId` without a value does. String fields accept a StringGenerator; numeric fields accept a Generator.
const Version = "0.0.0-dev"
Version is the semantic version of this library.
Variables ¶
var ( MillisecondLayout = core.MillisecondLayout SecondLayout = core.SecondLayout SafeJSMillisecondLayout = core.SafeJSMillisecondLayout SafeJSSecondLayout = core.SafeJSSecondLayout ErrClosed = core.ErrClosed ErrInvalidConfig = core.ErrInvalidConfig ErrExhausted = core.ErrExhausted ErrClockMovedBackwards = core.ErrClockMovedBackwards ErrInvalidMachineID = core.ErrInvalidMachineID ErrNamespaceConflict = core.ErrNamespaceConflict )
var ( NewStat = core.NewStat NewRadix = core.NewRadix NewInstanceID = machine.NewInstanceID WithGuardTiming = machine.WithGuardTiming WithGuardClock = machine.WithGuardClock NewGuarder = machine.NewGuarder InstanceIDFrom = machine.InstanceIDFrom DefaultStatePath = machine.DefaultStatePath NewLocalStateStorage = machine.NewLocalStateStorage NewMemoryMachineStorage = machine.NewMemoryMachineStorage WithLeaseStable = machine.WithLeaseStable WithLeaseSafeGuard = machine.WithLeaseSafeGuard NewLeaseDistributor = machine.NewLeaseDistributor NewStatefulSetDistributor = machine.NewStatefulSetDistributor )
Constructors and options keep their names by forwarding to the package that owns them.
var NeverGrouped = GroupedKey{Key: "", TTLAt: TTLForever}
NeverGrouped is GroupedKey.NEVER: an ungrouped allocation.
Functions ¶
Types ¶
type AtomicGenerator ¶
type AtomicGenerator struct {
// contains filtered or unexported fields
}
AtomicGenerator is CosID's jvm.AtomicLongGenerator: a per-process counter. It is only unique inside one process, so it is for caches and tests, never for a persisted primary key.
func NewAtomicGenerator ¶
func NewAtomicGenerator() *AtomicGenerator
NewAtomicGenerator creates a counter starting at zero.
type CachedSharding ¶
CachedSharding memoises range lookups — CosID's CachedSharding. Precise lookups are cheap enough to pass through.
func NewCachedSharding ¶
func NewCachedSharding[T any](actual Sharding[T]) *CachedSharding[T]
NewCachedSharding wraps a sharding with a range cache.
func (*CachedSharding[T]) EffectiveNodes ¶
func (c *CachedSharding[T]) EffectiveNodes() []string
EffectiveNodes implements Sharding.
func (*CachedSharding[T]) Sharding ¶
func (c *CachedSharding[T]) Sharding(value T) (string, error)
Sharding implements Sharding.
func (*CachedSharding[T]) ShardingRange ¶
func (c *CachedSharding[T]) ShardingRange(lower, upper T, hasLower, hasUpper bool) []string
ShardingRange implements Sharding with memoisation. The key renders the range bounds as strings, which is stable because bounds are compared, never mutated.
type ChainGenerator ¶
type ChainGenerator struct {
// contains filtered or unexported fields
}
ChainGenerator is CosID's SegmentChainId: a chain of reserved ranges, walked forward as they expire or overflow, with a background prefetcher that keeps `safeDistance` ranges ready.
func NewChainGenerator ¶
func NewChainGenerator(namespace string, step int64, alloc SegmentAllocator, opts ...ChainOption) (*ChainGenerator, error)
NewChainGenerator creates a chain generator and starts the prefetcher.
func (*ChainGenerator) Close ¶
func (g *ChainGenerator) Close(ctx context.Context) error
Close stops the prefetcher. Buffered ranges are dropped: a closed generator never hands out another id.
func (*ChainGenerator) Namespace ¶
func (g *ChainGenerator) Namespace() string
Namespace implements NamedGenerator.
func (*ChainGenerator) Next ¶
func (g *ChainGenerator) Next(ctx context.Context) (int64, error)
Next implements Generator, mirroring SegmentChainId.generate: walk the chain for an available range, and extend it when nothing is left.
func (*ChainGenerator) Stat ¶
func (g *ChainGenerator) Stat() Stat
Stat implements Statistical for a chain generator.
type ChainOption ¶
type ChainOption func(*ChainGenerator)
ChainOption configures a ChainGenerator.
func WithChainClock ¶
func WithChainClock(now func() int64) ChainOption
WithChainClock overrides the clock (tests).
func WithChainTTL ¶
func WithChainTTL(ttl time.Duration) ChainOption
WithChainTTL gives every reserved range a lifetime. Durations shorter than a second round up: a zero TTL would expire each range the moment it is created.
func WithSafeDistance ¶
func WithSafeDistance(n int) ChainOption
WithSafeDistance keeps `n` ranges ready ahead of the cursor.
type ClockSync ¶
type ClockSync interface {
// Synchronize waits until the clock catches up with lastTimestamp.
Synchronize(lastTimestamp int64) error
}
CosID 2.15.1 constants (the CosId class, SnowflakeId implementations).
type ClockSyncGenerator ¶
ClockSyncGenerator wraps any generator with a clock-backwards handler — CosID's ClockSyncSnowflakeId / ClockSyncCosIdGenerator. The wrapped generator still owns the layout; this decorator only intervenes when the clock moved backwards.
SnowflakeGenerator already accepts WithClockSync directly, but the string family and user-supplied generators do not, which is what this decorator is for.
func NewClockSyncGenerator ¶
func NewClockSyncGenerator(actual Generator, sync ClockSync) (*ClockSyncGenerator, error)
NewClockSyncGenerator wraps a generator. A nil sync means CosID's default thresholds.
func (*ClockSyncGenerator) Next ¶
func (g *ClockSyncGenerator) Next(ctx context.Context) (int64, error)
Next implements Generator.
func (*ClockSyncGenerator) Stat ¶
func (g *ClockSyncGenerator) Stat() Stat
Stat implements Statistical.
type CosIDState ¶
CosIDState is one generated value split into its three parts (CosID's CosIdState).
func (CosIDState) Compare ¶
func (s CosIDState) Compare(other CosIDState) int
Compare orders states by timestamp, then machine, then sequence.
type DateGroup ¶
type DateGroup struct {
Period Period
Layout string // Go layout; defaults follow the period
Location *time.Location
}
DateGroup groups allocations by calendar period, like CosID's AbstractDateGroupBySupplier: the key is the formatted period and the TTL ends with it, so the next period starts a fresh counter.
func NewDateGroup ¶
NewDateGroup builds a date-based grouping.
type DatePrefix ¶
type DatePrefix = core.DatePrefix
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type DefaultClockSync ¶
type DefaultClockSync struct {
SpinThreshold int64 // milliseconds
BrokenThreshold int64 // milliseconds
Now func() int64
Sleep func(time.Duration)
}
DefaultClockSync mirrors DefaultClockBackwardsSynchronizer.
func NewDefaultClockSync ¶
func NewDefaultClockSync() *DefaultClockSync
NewDefaultClockSync returns CosID's default thresholds (1ms / 500ms).
func (*DefaultClockSync) Synchronize ¶
func (d *DefaultClockSync) Synchronize(lastTimestamp int64) error
Synchronize implements ClockSync.
type GroupBy ¶
type GroupBy interface {
Group(now time.Time) GroupedKey
}
GroupBy resolves the group of a moment in time — CosID's GroupBySupplier.
type GroupedAllocator ¶
type GroupedAllocator struct {
Source SegmentAllocator
By GroupBy
Now func() time.Time
}
GroupedAllocator turns a SegmentAllocator into per-period counters: each period gets its own storage key `name@<group>`, so ids restart when the period rolls over — CosID's DefaultGroupedIdSegmentDistributor.
func (*GroupedAllocator) Key ¶
func (g *GroupedAllocator) Key() GroupedKey
Key returns the current group.
func (*GroupedAllocator) NameFor ¶
func (g *GroupedAllocator) NameFor(name string) string
NameFor renders the storage key of the current period.
type GroupedGenerator ¶
type GroupedGenerator struct {
Allocator *GroupedAllocator
Generator *ChainGenerator
}
GroupedGenerator pairs a generator with its group key, which is what a GroupedPrefix converter needs to render `<group>-<id>`. CosID carries the key in a ThreadLocal; passing it explicitly keeps this library free of ambient state.
func NewGroupedGenerator ¶
func NewGroupedGenerator(allocator *GroupedAllocator, step int64, opts ...ChainOption) (*GroupedGenerator, error)
NewGroupedGenerator builds a chain generator backed by per-period counters.
func (*GroupedGenerator) Close ¶
func (g *GroupedGenerator) Close(ctx context.Context) error
Close releases the underlying generator.
func (*GroupedGenerator) Namespace ¶
func (g *GroupedGenerator) Namespace() string
Namespace implements NamedGenerator.
func (*GroupedGenerator) Next ¶
func (g *GroupedGenerator) Next(ctx context.Context) (int64, GroupedKey, error)
Next returns one id together with the group it belongs to.
func (*GroupedGenerator) NextString ¶
func (g *GroupedGenerator) NextString(ctx context.Context, delimiter string, actual StringConverter) (string, error)
NextString renders the id with a grouped prefix, e.g. `2026-000042`.
type GroupedKey ¶
GroupedKey labels an allocation period — CosID's GroupedKey. TTLAt is the unix second at which the group ends, so a caller can tell when a counter restarts.
type GroupedPrefix ¶
type GroupedPrefix = core.GroupedPrefix
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type Guarder ¶
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type GuarderOption ¶
type GuarderOption = machine.GuarderOption
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type GuardianState ¶
type GuardianState = machine.GuardianState
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type HostAddressSupplier ¶
type HostAddressSupplier = machine.HostAddressSupplier
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type Injector ¶
type Injector struct {
// contains filtered or unexported fields
}
Injector fills id fields of structs from registered generators. CosID reaches the fields through reflection on annotated classes; Go does the same through struct tags, so an entity does not have to know about the generator at all.
func NewInjectorFromProvider ¶
NewInjectorFromProvider creates an injector backed by a Provider's named generators. The registry is read on every fill, so generators may be replaced at runtime.
func (*Injector) Ensure ¶
Ensure fills every empty id field of the entity. It reports whether anything was filled, mirroring CosID's EnsureId: an entity that already carries an id is left untouched.
func (*Injector) RegisterString ¶
func (i *Injector) RegisterString(name string, gen StringGenerator)
RegisterString binds a generator name to a string id field.
type IntegerGenerator ¶
type IntegerGenerator struct {
Actual Generator
}
IntegerGenerator exposes a Generator as a 32-bit id source, refusing values that do not fit — CosID's IntegerIdGenerator.
func (IntegerGenerator) GenerateAsString ¶
func (g IntegerGenerator) GenerateAsString(ctx context.Context) (string, error)
GenerateAsString implements StringGenerator: the decimal rendering of the id.
type IntervalNode ¶
IntervalNode is one node of a timeline with the instant it starts at.
type IntervalStep ¶
type IntervalStep struct {
// Kind is the calendar unit; months and years are not fixed durations, so
// arithmetic goes through the calendar rather than a time.Duration.
Kind StepUnit
Amount int
}
IntervalStep is one step of an interval timeline: `Amount` units of `Unit`, floored to the unit — CosID's IntervalStep.
func NewIntervalStep ¶
func NewIntervalStep(unit StepUnit, amount int) (IntervalStep, error)
NewIntervalStep validates a step.
func (IntervalStep) FloorUnit ¶
func (s IntervalStep) FloorUnit(t time.Time) time.Time
FloorUnit truncates to the start of the unit, like IntervalStep.floorUnit.
type IntervalTimeline ¶
type IntervalTimeline struct {
Prefix string
Layout string
Step IntervalStep
Lower time.Time
Upper time.Time
Location *time.Location
// contains filtered or unexported fields
}
IntervalTimeline shards by time window: node names are `prefix + formatted window start`, so each window can live in its own storage — CosID's IntervalTimeline.
func NewIntervalTimeline ¶
func NewIntervalTimeline(prefix, layout string, step IntervalStep, lower, upper time.Time) (*IntervalTimeline, error)
NewIntervalTimeline builds a timeline covering [lower, upper] in steps.
func (*IntervalTimeline) EffectiveNodes ¶
func (tl *IntervalTimeline) EffectiveNodes() []string
EffectiveNodes implements Sharding.
func (*IntervalTimeline) Sharding ¶
func (tl *IntervalTimeline) Sharding(value time.Time) (string, error)
Sharding implements Sharding for instants. Values outside the timeline are an error rather than silently landing on the first or last node.
func (*IntervalTimeline) ShardingRange ¶
func (tl *IntervalTimeline) ShardingRange(lower, upper time.Time, hasLower, hasUpper bool) []string
ShardingRange implements Sharding.
type Layout ¶
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type LazyGenerator ¶
type LazyGenerator struct {
// contains filtered or unexported fields
}
LazyGenerator defers construction until the first Next call — CosID's LazyIdGenerator. It lets a distribution wire a generator whose backing store (or machine id) is only available after start-up.
func NewLazyGenerator ¶
func NewLazyGenerator(init func(context.Context) (Generator, error)) *LazyGenerator
NewLazyGenerator creates a generator that builds itself on first use.
type LeaseDistributor ¶
type LeaseDistributor = machine.LeaseDistributor
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type LeaseOption ¶
type LeaseOption = machine.LeaseOption
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type LocalDateTimeConverter ¶
LocalDateTimeConverter turns a sharding value of any supported shape into an instant — CosID's LocalDateTimeConvertor. Sharding then works uniformly for timestamps, formatted strings and snowflake ids.
type LocalHostAddress ¶
type LocalHostAddress = machine.LocalHostAddress
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type LocalStateStorage ¶
type LocalStateStorage = machine.LocalStateStorage
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type MachineIdDistributor ¶
type MachineIdDistributor = machine.MachineIdDistributor
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type MachineState ¶
type MachineState = machine.MachineState
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type MachineStateStorage ¶
type MachineStateStorage = machine.MachineStateStorage
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type ManualDistributor ¶
type ManualDistributor = machine.ManualDistributor
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type MemoryAllocator ¶
type MemoryAllocator struct {
// contains filtered or unexported fields
}
MemoryAllocator is an in-process allocator for tests and single-process deployments without a database.
func NewMemoryAllocator ¶
func NewMemoryAllocator(step int64) *MemoryAllocator
NewMemoryAllocator creates an allocator using `step` when the caller does not request one.
type MemoryMachineStorage ¶
type MemoryMachineStorage = machine.MemoryMachineStorage
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type ModCycle ¶
ModCycle spreads values over `divisor` nodes by modulo — CosID's ModCycle. The node name is `prefix + (value mod divisor)`.
func NewModCycle ¶
NewModCycle creates a modulo cycle sharding.
func (*ModCycle) EffectiveNodes ¶
EffectiveNodes implements Sharding.
type NamedGenerator ¶
type NamedGenerator = core.NamedGenerator
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type NamespacedInstanceID ¶
type NamespacedInstanceID = machine.NamespacedInstanceID
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type NoopGuarder ¶
type NoopGuarder = machine.NoopGuarder
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type Prefix ¶
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type Provider ¶
type Provider struct {
// contains filtered or unexported fields
}
Provider is CosID's IdGeneratorProvider: a registry of named generators.
func (*Provider) Clear ¶
func (p *Provider) Clear()
Clear drops every generator, including the shared one.
func (*Provider) RemoveShare ¶
RemoveShare clears the shared generator and returns it.
func (*Provider) Required ¶
Required returns a named generator or an error naming it, mirroring IdGeneratorProvider.getRequired.
func (*Provider) Set ¶
Set registers a generator. The share name routes to SetShare so the two views never disagree.
func (*Provider) SetShare ¶
SetShare installs the shared generator. As in CosID, the shared generator is also reachable by name, so Get(ShareName) works.
func (*Provider) ShareRequired ¶
ShareRequired returns the shared generator or an error naming it. It is what an unnamed id field resolves to.
type Radix ¶
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type RadixStateParser ¶
RadixStateParser renders a state as fixed-width padded radix fields — CosID's RadixCosIdStateParser. Each field is padded to the digit count its bit width needs, so the total length is constant.
func NewRadixStateParser ¶
func NewRadixStateParser(base, timestampBits, machineBits, sequenceBits int) (*RadixStateParser, error)
NewRadixStateParser builds a parser for the given bits and radix.
func (RadixStateParser) Format ¶
func (p RadixStateParser) Format(state CosIDState) string
Format implements the string rendering.
func (RadixStateParser) Parse ¶
func (p RadixStateParser) Parse(id string) (CosIDState, error)
Parse is the inverse of Format.
type Segment ¶
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type SegmentAllocator ¶
type SegmentAllocator = core.SegmentAllocator
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type SegmentGenerator ¶
type SegmentGenerator struct {
// contains filtered or unexported fields
}
SegmentGenerator issues the values of ranges reserved from a SegmentAllocator. It keeps one range in reserve so a refill does not stall every caller.
Concurrency: Next is safe for concurrent use. The synchronous refill path holds the generator lock across the allocator call; that path is rare because the fetcher keeps a range ready.
func NewSegmentGenerator ¶
func NewSegmentGenerator(namespace string, step int64, alloc SegmentAllocator, opts ...SegmentOption) (*SegmentGenerator, error)
NewSegmentGenerator creates a generator for one namespace. Ranges are prefetched once half of the current one is consumed.
func (*SegmentGenerator) Close ¶
func (g *SegmentGenerator) Close(ctx context.Context) error
Close stops prefetching and waits for the in-flight reservation to finish. Ranges already buffered are dropped: a closed generator never hands out another id.
func (*SegmentGenerator) Namespace ¶
func (g *SegmentGenerator) Namespace() string
Namespace implements NamedGenerator.
func (*SegmentGenerator) Next ¶
func (g *SegmentGenerator) Next(ctx context.Context) (int64, error)
Next implements Generator. The first id of a reserved range (offset+1) is handed out first, exactly like CosID's DefaultIdSegment.
func (*SegmentGenerator) Stat ¶
func (g *SegmentGenerator) Stat() Stat
Stat implements Statistical for a segment generator: the same fields CosID's SegmentIdStat exposes, so an operator sees how much of the range is left.
type SegmentOption ¶
type SegmentOption func(*SegmentGenerator)
SegmentOption configures a SegmentGenerator.
func WithPrefetchRatio ¶
func WithPrefetchRatio(ratio float64) SegmentOption
WithPrefetchRatio sets the fraction of a range that must remain for a prefetch to start. 0 disables prefetching.
func WithSegmentClock ¶
func WithSegmentClock(now func() int64) SegmentOption
WithSegmentClock overrides the clock used for TTL checks (tests).
func WithSegmentTTL ¶
func WithSegmentTTL(ttl time.Duration) SegmentOption
WithSegmentTTL gives reserved ranges a lifetime. An expired range is abandoned and a new one is reserved, matching CosID's IdSegment.isExpired. Durations shorter than a second round up, so a range never starts expired.
type Sharding ¶
type Sharding[T any] interface { // Sharding returns the node for a single value. Sharding(value T) (string, error) // ShardingRange returns the nodes a range touches, deduplicated. ShardingRange(lower, upper T, hasLower, hasUpper bool) []string // EffectiveNodes lists every node the sharding can produce. EffectiveNodes() []string }
Sharding maps a value (or a value range) to logical node names — CosID's sharding package. It is how a deployment spreads snowflake ids of different time windows over different storage shards.
type SnowflakeConverter ¶
type SnowflakeConverter struct {
Layout Layout
// Radix parses string values; nil means decimal.
Radix *Radix
}
SnowflakeConverter goes the other way: from an id (or its rendered string) to the instant it was generated — CosID's SnowflakeLocalDateTimeConvertor. That is what lets a sharding question start from an id instead of a timestamp.
type SnowflakeFriendly ¶
type SnowflakeFriendly = core.SnowflakeFriendly
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type SnowflakeGenerator ¶
type SnowflakeGenerator struct {
// contains filtered or unexported fields
}
SnowflakeGenerator implements Generator on a fixed layout.
func NewSnowflake ¶
func NewSnowflake(layout Layout, machineID int64, opts ...SnowflakeOption) (*SnowflakeGenerator, error)
NewSnowflake creates a generator for one machine id.
func (*SnowflakeGenerator) Layout ¶
func (g *SnowflakeGenerator) Layout() Layout
Layout returns the configured layout.
func (*SnowflakeGenerator) Next ¶
func (g *SnowflakeGenerator) Next(context.Context) (int64, error)
Next implements Generator, following AbstractSnowflakeId.generate.
func (*SnowflakeGenerator) Stat ¶
func (g *SnowflakeGenerator) Stat() Stat
Stat implements Statistical for a snowflake generator.
type SnowflakeOption ¶
type SnowflakeOption func(*SnowflakeGenerator)
SnowflakeOption configures a SnowflakeGenerator.
func WithClockSync ¶
func WithClockSync(sync ClockSync) SnowflakeOption
WithClockSync installs a clock-backwards handler. Without one the generator fails on any backwards movement.
func WithSequenceResetThreshold ¶
func WithSequenceResetThreshold(threshold int64) SnowflakeOption
WithSequenceResetThreshold overrides CosID's default (half the sequence space), which evens out id distribution across shards.
func WithSnowflakeClock ¶
func WithSnowflakeClock(now func() int64) SnowflakeOption
WithSnowflakeClock overrides the time source (tests). It must return the same unit as the layout: milliseconds for millisecond layouts, seconds for second layouts.
type StandardConverter ¶
type StandardConverter struct {
// SecondEpoch treats numeric values as seconds instead of milliseconds.
SecondEpoch bool
Location *time.Location
// Layout parses string values; RFC3339 when empty.
Layout string
}
StandardConverter accepts time.Time, epoch millis or seconds, and RFC3339 strings — CosID's StandardLocalDateTimeConvertor.
type Stat ¶
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type State ¶
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type StatefulSetDistributor ¶
type StatefulSetDistributor = machine.StatefulSetDistributor
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type Statistical ¶
type Statistical = core.Statistical
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type StringClockSyncGenerator ¶
type StringClockSyncGenerator struct {
Actual StringGenerator
Sync ClockSync
}
StringClockSyncGenerator is ClockSyncGenerator for string generators.
func NewStringClockSyncGenerator ¶
func NewStringClockSyncGenerator(actual StringGenerator, sync ClockSync) (*StringClockSyncGenerator, error)
NewStringClockSyncGenerator wraps a string generator.
func (*StringClockSyncGenerator) GenerateAsString ¶
func (g *StringClockSyncGenerator) GenerateAsString(ctx context.Context) (string, error)
GenerateAsString implements StringGenerator.
type StringConverter ¶
type StringConverter = core.StringConverter
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type StringCosIDGenerator ¶
type StringCosIDGenerator struct {
// contains filtered or unexported fields
}
StringCosIDGenerator is CosID's Radix36/Radix62 generator: a string id made of timestamp, machine and sequence, rendered in a radix.
func NewStringCosIDGenerator ¶
func NewStringCosIDGenerator(base int, machineID int32, opts ...StringCosIDOption) (*StringCosIDGenerator, error)
NewStringCosIDGenerator creates a base36 or base62 string generator.
func (*StringCosIDGenerator) GenerateAsString ¶
func (g *StringCosIDGenerator) GenerateAsString(ctx context.Context) (string, error)
GenerateAsString implements StringGenerator.
func (*StringCosIDGenerator) Next ¶
func (g *StringCosIDGenerator) Next(context.Context) (int64, error)
Next is not supported: this generator produces strings, not int64 ids.
func (*StringCosIDGenerator) NextState ¶
func (g *StringCosIDGenerator) NextState() (CosIDState, error)
NextState implements CosID's RadixCosIdGenerator.generateAsState: the same sequence reset / overflow handling as the snowflake, but without an epoch offset and without bit packing.
func (*StringCosIDGenerator) Parser ¶
func (g *StringCosIDGenerator) Parser() RadixStateParser
Parser exposes the state parser (useful for tests and tooling).
func (*StringCosIDGenerator) Stat ¶
func (g *StringCosIDGenerator) Stat() Stat
Stat implements Statistical for the CosID string family.
func (*StringCosIDGenerator) StateOfString ¶
func (g *StringCosIDGenerator) StateOfString(id string) (CosIDState, error)
StateOfString parses an id produced by a generator with the same layout.
type StringCosIDOption ¶
type StringCosIDOption func(*StringCosIDGenerator)
StringCosIDOption configures a StringCosIDGenerator.
func WithStringCosIDClock ¶
func WithStringCosIDClock(now func() int64) StringCosIDOption
WithStringCosIDClock overrides the millisecond clock (tests).
func WithStringCosIDLayout ¶
func WithStringCosIDLayout(timestampBits, machineBits, sequenceBits int) StringCosIDOption
WithStringCosIDLayout overrides the bit layout (defaults 44/20/16).
type StringGenerator ¶
StringGenerator renders ids as strings. Some generators (UUID, CosID's base36/base62 family) only make sense as strings, so they implement this instead of Generator.
func StringOf ¶
func StringOf(gen Generator, conv StringConverter) StringGenerator
StringOf adapts a Generator to StringGenerator using a converter — the Go equivalent of CosID's StringIdGenerator decorators (Radix36/62, friendly).
type StringSegmentID ¶
type StringSegmentID struct {
Actual *SegmentGenerator
Converter StringConverter
}
StringSegmentID is a segment generator rendered as a string — CosID's StringSegmentId. The numeric generator stays the source of truth; the wrapper only changes the surface, and it exposes the current segment and the stat of both halves.
func NewStringSegmentID ¶
func NewStringSegmentID(actual *SegmentGenerator, converter StringConverter) (*StringSegmentID, error)
NewStringSegmentID wraps a segment generator with a converter.
func (*StringSegmentID) Current ¶
func (s *StringSegmentID) Current() Segment
Current exposes the segment in use, like SegmentId.current().
func (*StringSegmentID) GenerateAsString ¶
func (s *StringSegmentID) GenerateAsString(ctx context.Context) (string, error)
GenerateAsString implements StringGenerator.
func (*StringSegmentID) Next ¶
func (s *StringSegmentID) Next(ctx context.Context) (int64, error)
Next keeps the numeric view available.
func (*StringSegmentID) Stat ¶
func (s *StringSegmentID) Stat() Stat
Stat implements Statistical, keeping the converter visible in the tree.
type StringSnowflakeID ¶
type StringSnowflakeID struct {
Actual *SnowflakeGenerator
Converter StringConverter
}
StringSnowflakeID is a snowflake generator rendered as a string — CosID's StringSnowflakeId.
func NewStringSnowflakeID ¶
func NewStringSnowflakeID(actual *SnowflakeGenerator, converter StringConverter) (*StringSnowflakeID, error)
NewStringSnowflakeID wraps a snowflake generator with a converter.
func (*StringSnowflakeID) GenerateAsString ¶
func (s *StringSnowflakeID) GenerateAsString(ctx context.Context) (string, error)
GenerateAsString implements StringGenerator.
func (*StringSnowflakeID) Layout ¶
func (s *StringSnowflakeID) Layout() Layout
Layout exposes the wrapped layout, like SnowflakeId.getEpoch()/getTimestampBit().
func (*StringSnowflakeID) Next ¶
func (s *StringSnowflakeID) Next(ctx context.Context) (int64, error)
Next keeps the numeric view available.
func (*StringSnowflakeID) Stat ¶
func (s *StringSnowflakeID) Stat() Stat
Stat implements Statistical.
type Suffix ¶
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type ToString ¶
The vocabulary every generator, converter and allocator shares lives in ./core: the generator contracts, the segment model, the radix/prefix vocabulary, the snowflake layout and the Stat tree. Every name below is an alias, so a consumer keeps importing gcosid and still gets the core type — one definition, two import paths.
type UUIDGenerator ¶
type UUIDGenerator struct{}
UUIDGenerator is CosID's jvm.UuidGenerator: random UUIDv4 as a string.
func (UUIDGenerator) GenerateAsString ¶
func (UUIDGenerator) GenerateAsString(context.Context) (string, error)
GenerateAsString implements StringGenerator.
type UncertaintyGenerator ¶
type UncertaintyGenerator struct {
Actual Generator
UncertaintyBits int
// contains filtered or unexported fields
}
UncertaintyGenerator appends random low bits to every id — CosID's UncertaintyIdGenerator. The ordering is preserved at the granularity of the original id, while the trailing digits no longer expose the sequence, which keeps ids from advertising how many were issued or which one comes next.
func NewUncertaintyGenerator ¶
func NewUncertaintyGenerator(actual Generator, bits int) (*UncertaintyGenerator, error)
NewUncertaintyGenerator wraps a generator, reserving `bits` low bits for randomness. `bits` must leave room for the original id inside 63 bits.
func (*UncertaintyGenerator) Bound ¶
func (g *UncertaintyGenerator) Bound() int64
Bound is the exclusive upper bound of the random suffix.
func (*UncertaintyGenerator) Next ¶
func (g *UncertaintyGenerator) Next(ctx context.Context) (int64, error)
Next implements Generator.
func (*UncertaintyGenerator) OriginalMaxID ¶
func (g *UncertaintyGenerator) OriginalMaxID() int64
OriginalMaxID is the largest id the wrapped generator may produce.
func (*UncertaintyGenerator) Stat ¶
func (g *UncertaintyGenerator) Stat() Stat
Stat implements Statistical.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package database implements gcosid's segment allocator on top of database/sql.
|
Package database implements gcosid's segment allocator on top of database/sql. |
|
examples
|
|
|
inject
command
Command inject shows how gcosid fills entity ids.
|
Command inject shows how gcosid fills entity ids. |
|
repository
command
Command repository shows where id injection belongs in a real service.
|
Command repository shows where id injection belongs in a real service. |
|
Package redis implements CosID's Redis storage protocol.
|
Package redis implements CosID's Redis storage protocol. |