go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/bq/insertid.go (about)

     1  // Copyright 2018 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package bq
    16  
    17  import (
    18  	"fmt"
    19  	"math/rand"
    20  	"os"
    21  	"sync/atomic"
    22  	"time"
    23  )
    24  
    25  var (
    26  	// defaultPrefix is a global value is used to populate a zero-value
    27  	// InsertIDGenerator.
    28  	defaultPrefix string
    29  )
    30  
    31  func init() {
    32  	t := time.Now().UnixNano()
    33  	defaultPrefix = fmt.Sprintf("%d:%d:%d", rand.Int(), os.Getpid(), t)
    34  }
    35  
    36  // InsertIDGenerator generates unique Insert IDs.
    37  //
    38  // BigQuery uses Insert IDs to deduplicate rows in the streaming insert buffer.
    39  // The association between Insert ID and row persists only for the time the row
    40  // is in the buffer.
    41  //
    42  // InsertIDGenerator is safe for concurrent use.
    43  type InsertIDGenerator struct {
    44  	// Counter is an atomically-managed counter used to differentiate Insert
    45  	// IDs produced by the same process.
    46  	Counter int64
    47  	// Prefix should be able to uniquely identify this specific process,
    48  	// to differentiate Insert IDs produced by different processes.
    49  	//
    50  	// If empty, prefix will be derived from system and process specific
    51  	// properties.
    52  	Prefix string
    53  }
    54  
    55  // Generate returns a unique Insert ID.
    56  func (id *InsertIDGenerator) Generate() string {
    57  	prefix := id.Prefix
    58  	if prefix == "" {
    59  		prefix = defaultPrefix
    60  	}
    61  	c := atomic.AddInt64(&id.Counter, 1)
    62  	return fmt.Sprintf("%s:%d", prefix, c)
    63  }