github.com/cockroachdb/cockroach@v20.2.0-alpha.1+incompatible/pkg/sql/cluster_wide_id.go (about) 1 // Copyright 2018 The Cockroach Authors. 2 // 3 // Use of this software is governed by the Business Source License 4 // included in the file licenses/BSL.txt. 5 // 6 // As of the Change Date specified in that file, in accordance with 7 // the Business Source License, use of this software will be governed 8 // by the Apache License, Version 2.0, included in the file 9 // licenses/APL.txt. 10 11 package sql 12 13 import ( 14 "github.com/cockroachdb/cockroach/pkg/base" 15 "github.com/cockroachdb/cockroach/pkg/util/hlc" 16 "github.com/cockroachdb/cockroach/pkg/util/uint128" 17 ) 18 19 // ClusterWideID represents an identifier that is guaranteed to be unique across 20 // a cluster. It is a wrapper around a uint128. It logically consists of 96 bits 21 // of HLC timestamp, and 32 bits of node ID. 22 type ClusterWideID struct { 23 uint128.Uint128 24 } 25 26 // GenerateClusterWideID takes a timestamp and SQLInstanceID, and generates a 27 // ClusterWideID. 28 func GenerateClusterWideID(timestamp hlc.Timestamp, instID base.SQLInstanceID) ClusterWideID { 29 loInt := (uint64)(instID) 30 loInt = loInt | ((uint64)(timestamp.Logical) << 32) 31 32 return ClusterWideID{Uint128: uint128.FromInts((uint64)(timestamp.WallTime), loInt)} 33 } 34 35 // StringToClusterWideID converts a string to a ClusterWideID. If the string is 36 // not a valid uint128, an error is returned. 37 func StringToClusterWideID(s string) (ClusterWideID, error) { 38 id, err := uint128.FromString(s) 39 if err != nil { 40 return ClusterWideID{}, err 41 } 42 return ClusterWideID{Uint128: id}, nil 43 } 44 45 // BytesToClusterWideID converts raw bytes into a ClusterWideID. 46 // The caller is responsible for ensuring the byte slice contains 16 bytes. 47 func BytesToClusterWideID(b []byte) ClusterWideID { 48 id := uint128.FromBytes(b) 49 return ClusterWideID{Uint128: id} 50 } 51 52 // GetNodeID extracts the node ID from a ClusterWideID. 53 func (id ClusterWideID) GetNodeID() int32 { 54 return int32(0xFFFFFFFF & id.Lo) 55 }