github.com/criteo/command-launcher@v0.0.0-20230407142452-fb616f546e98/internal/user/user.go (about)

     1  package user
     2  
     3  import (
     4  	"github.com/criteo/command-launcher/internal/config"
     5  	"github.com/criteo/command-launcher/internal/helper"
     6  	"github.com/denisbrodbeck/machineid"
     7  	"github.com/spf13/viper"
     8  )
     9  
    10  const (
    11  	INTERNAL_START_PARTITION     = 10 // exclusive
    12  	EXPERIMENTAL_START_PARTITION = 20 // exclusive
    13  	NB_OF_USER_PARTITIONS        = 10
    14  )
    15  
    16  type User struct {
    17  	UID                    string
    18  	Partition              uint8
    19  	InternalCmdEnabled     bool
    20  	ExperimentalCmdEnabled bool
    21  }
    22  
    23  func GetUser() (User, error) {
    24  	uid, err := machineid.ID()
    25  	if err != nil {
    26  		return User{}, err
    27  	}
    28  
    29  	return User{
    30  		UID:                    uid,
    31  		Partition:              uint8(helper.Hash(uid) % NB_OF_USER_PARTITIONS),
    32  		InternalCmdEnabled:     viper.GetBool(config.INTERNAL_COMMAND_ENABLED_KEY),
    33  		ExperimentalCmdEnabled: viper.GetBool(config.EXPERIMENTAL_COMMAND_ENABLED_KEY),
    34  	}, nil
    35  
    36  }
    37  
    38  func (u User) InPartition(start uint8, end uint8) bool {
    39  	if u.InternalCmdEnabled && start > INTERNAL_START_PARTITION && start < EXPERIMENTAL_START_PARTITION {
    40  		return true
    41  	}
    42  
    43  	if u.ExperimentalCmdEnabled && start > EXPERIMENTAL_START_PARTITION {
    44  		return true
    45  	}
    46  
    47  	return u.Partition >= start && u.Partition <= end
    48  }