misc

package
v0.0.0-...-0ade494 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 26, 2022 License: AGPL-3.0 Imports: 43 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// RFC3339Milli with milli sec precision
	RFC3339Milli            = "2006-01-02T15:04:05.000Z07:00"
	POSTGRESTIMEFORMATPARSE = "2006-01-02T15:04:05"
)
View Source
const (
	RudderAsyncDestinationLogs    = "rudder-async-destination-logs"
	RudderArchives                = "rudder-archives"
	RudderWarehouseStagingUploads = "rudder-warehouse-staging-uploads"
	RudderRawDataDestinationLogs  = "rudder-raw-data-destination-logs"
	RudderWarehouseLoadUploadsTmp = "rudder-warehouse-load-uploads-tmp"
	RudderIdentityMergeRulesTmp   = "rudder-identity-merge-rules-tmp"
	RudderIdentityMappingsTmp     = "rudder-identity-mappings-tmp"
	RudderRedshiftManifests       = "rudder-redshift-manifests"
	RudderWarehouseJsonUploadsTmp = "rudder-warehouse-json-uploads-tmp"
	RudderTestPayload             = "rudder-test-payload"
)

Variables

View Source
var (
	AppStartTime int64
)

Functions

func AddFileToZip

func AddFileToZip(zipWriter *zip.Writer, filename string) error

AddFileToZip adds file to zip including size header stats

func AppendError

func AppendError(callingMethodName string, firstError, secondError *error)

AppendError creates or appends second error to first error

func BugsnagNotify

func BugsnagNotify(ctx context.Context, team string) func()

func ConcatErrors

func ConcatErrors(givenErrors []error) error

func ContainsInt

func ContainsInt(slice []int, val int) bool

func ContainsInt64

func ContainsInt64(slice []int64, val int64) bool

func ContainsString

func ContainsString(slice []string, str string) bool

func ConvertInterfaceToStringArray

func ConvertInterfaceToStringArray(input []interface{}) []string

func ConvertStringInterfaceToIntArray

func ConvertStringInterfaceToIntArray(interfaceT interface{}) ([]int64, error)

func Copy

func Copy(dst, src interface{})

Copy copies the exported fields from src to dest Used for copying the default transport

func CopyStringMap

func CopyStringMap(originalMap map[string]string) map[string]string

func CreateTMPDIR

func CreateTMPDIR() (string, error)

CreateTMPDIR creates tmp dir at path configured via RUDDER_TMPDIR env var

func FastUUID

func FastUUID() uuid.UUID

func GetChronologicalTimeStamp

func GetChronologicalTimeStamp(receivedAt, sentAt, originalTimestamp time.Time) time.Time

 Returns chronological timestamp of the event using the formula  timestamp = receivedAt - (sentAt - originalTimestamp)

func GetDatabricksVersion

func GetDatabricksVersion() (version string)

func GetHash

func GetHash(s string) int

func GetIPFromReq

func GetIPFromReq(req *http.Request) string

GetIPFromReq gets ip address from request

func GetJsonSchemaDTFromGoDT

func GetJsonSchemaDTFromGoDT(goType string) string

GetJsonSchemaDTFromGoDT returns the json schema supported data types from go lang supported data types. References: 1. Go supported types: https://golangbyexample.com/all-data-types-in-golang-with-examples/ 2. Json schema supported types: https://json-schema.org/understanding-json-schema/reference/type.html

func GetMD5Hash

func GetMD5Hash(input string) string

GetMD5Hash returns EncodeToString(md5 hash of the input string)

func GetMD5UUID

func GetMD5UUID(str string) (uuid.UUID, error)

GetMD5UUID hashes the given string into md5 and returns it as auuid

func GetMacAddress

func GetMacAddress() string

func GetMandatoryJSONFieldNames

func GetMandatoryJSONFieldNames(st interface{}) []string

GetMandatoryJSONFieldNames returns all the json field names defined against the json tag for each field.

func GetNodeID

func GetNodeID() string

GetNodeID returns the nodeId of the current node

func GetObjectStorageConfig

func GetObjectStorageConfig(opts ObjectStorageOptsT) map[string]interface{}

func GetOutboundIP

func GetOutboundIP() (net.IP, error)

GetOutboundIP returns preferred outbound ip of this machine https://stackoverflow.com/a/37382208

func GetParsedTimestamp

func GetParsedTimestamp(input interface{}) (time.Time, bool)

GetParsedTimestamp returns the parsed timestamp

func GetRudderEventVal

func GetRudderEventVal(key string, rudderEvent types.SingularEventT) (interface{}, bool)

GetRudderEventVal returns the value corresponding to the key in the message structure

func GetRudderID

func GetRudderID(event types.SingularEventT) (string, bool)

GetRudderID return the UserID from the object

func GetRudderObjectStorageAccessKeys

func GetRudderObjectStorageAccessKeys() (accessKeyID, accessKey string)

func GetRudderObjectStorageConfig

func GetRudderObjectStorageConfig(prefixOverride string) (storageConfig map[string]interface{})

func GetRudderObjectStoragePrefix

func GetRudderObjectStoragePrefix() (prefix string)

func GetSpacesLocation

func GetSpacesLocation(location string) (region string)

func GetStringifiedData

func GetStringifiedData(data interface{}) string

func GetTagName

func GetTagName(id string, names ...string) string

GetTagName gets the tag name using a uuid and name

func GetWarehouseURL

func GetWarehouseURL() (url string)

func HTTPCallWithRetry

func HTTPCallWithRetry(url string, payload []byte) ([]byte, int)

func HTTPCallWithRetryWithTimeout

func HTTPCallWithRetryWithTimeout(url string, payload []byte, timeout time.Duration) ([]byte, int)

func HasAWSKeysInConfig

func HasAWSKeysInConfig(config interface{}) bool

func HasAWSRegionInConfig

func HasAWSRegionInConfig(config interface{}) bool

func IncrementMapByKey

func IncrementMapByKey(m map[string]int, key string, increment int)

IncrementMapByKey starts with 1 and increments the counter of a key

func Init

func Init()

func IntArrayToString

func IntArrayToString(a []int64, delim string) string

func IsConfiguredToUseRudderObjectStorage

func IsConfiguredToUseRudderObjectStorage(storageConfig map[string]interface{}) bool

func IsValidUUID

func IsValidUUID(uuid string) bool

IsValidUUID will check if provided string is a valid UUID

func KeepProcessAlive

func KeepProcessAlive()

func LoadDestinations

func LoadDestinations() ([]string, []string)

func MakeHTTPRequestWithTimeout

func MakeHTTPRequestWithTimeout(url string, payload io.Reader, timeout time.Duration) ([]byte, int, error)

func MakeJSONArray

func MakeJSONArray(bytesArray [][]byte) []byte

func MakeRetryablePostRequest

func MakeRetryablePostRequest(url, endpoint string, data interface{}) (response []byte, statusCode int, err error)

MakeRetryablePostRequest is Util function to make a post request.

func MapLookup

func MapLookup(mapToLookup map[string]interface{}, keys ...string) interface{}

lookup map recursively and return value

func MapStringKeys

func MapStringKeys(input map[string]interface{}) []string

func MaxInt

func MaxInt(a, b int) int

func MergeMaps

func MergeMaps(maps ...map[string]interface{}) map[string]interface{}

MergeMaps merging with one level of nesting.

func MinInt

func MinInt(a, b int) int

func NestedMapLookup

func NestedMapLookup(m map[string]interface{}, ks ...string) (rval interface{}, err error)

NestedMapLookup m: a map from strings to other maps or values, of arbitrary depth ks: successive keys to reach an internal or leaf node (variadic) If an internal node is reached, will return the internal map

Returns: (Exactly one of these will be nil) rval: the target node (if found) err: an error created by fmt.Errorf

func ParseRudderEventBatch

func ParseRudderEventBatch(eventPayload json.RawMessage) ([]types.SingularEventT, bool)

ParseRudderEventBatch looks for the batch structure inside event

func QuoteLiteral

func QuoteLiteral(literal string) string

func ReadLines

func ReadLines(path string) ([]string, error)

ReadLines reads a whole file into memory and returns a slice of its lines.

func RecordAppError

func RecordAppError(err error)

RecordAppError appends the error occurred to error_store.json

func RemoveEmptyFolderStructureForFilePath

func RemoveEmptyFolderStructureForFilePath(fp string)

RemoveEmptyFolderStructureForFilePath recursively cleans up everything till it reaches the stage where the folders are not empty or parent.

func RemoveFilePaths

func RemoveFilePaths(filePaths ...string)

RemoveFilePaths removes filePaths as well as cleans up the empty folder structure.

func ReplaceDB

func ReplaceDB(dbName, targetName string)

ReplaceDB : Rename the OLD DB and create a new one. Since we are not journaling, this should be idemponent

func ReplaceMultiRegex

func ReplaceMultiRegex(str string, expList map[string]string) (string, error)

func RetryWith

func RetryWith(parentContext context.Context, timeout time.Duration, maxAttempts int, f func(ctx context.Context) error) error

func ReverseInt

func ReverseInt(s []int) []int

ReverseInt reverses an array of int

func RunWithConcurrency

func RunWithConcurrency(config *RWCConfig)

RunWithConcurrency runs provided function f with concurrency provided by the factor factor.

func RunWithTimeout

func RunWithTimeout(f, onTimeout func(), d time.Duration)

RunWithTimeout runs provided function f until provided timeout d. If the timeout is reached, onTimeout callback will be called.

func SingleQuoteLiteralJoin

func SingleQuoteLiteralJoin(slice []string) string

func SleepCtx

func SleepCtx(ctx context.Context, delay time.Duration) bool

func SortMap

func SortMap(inputMap map[string]metric.MovingAverage) []string

func SortedMapKeys

func SortedMapKeys(input interface{}) []string

func SortedStructSliceValues

func SortedStructSliceValues(input interface{}, filedName string) []string

func StringKeys

func StringKeys(input interface{}) []string

func TailTruncateStr

func TailTruncateStr(str string, count int) string

TailTruncateStr returns the last `count` digits of a string

func TruncateStr

func TruncateStr(str string, limit int) string

func Unique

func Unique(stringSlice []string) []string

func UpdateJSONWithNewKeyVal

func UpdateJSONWithNewKeyVal(params []byte, key string, val interface{}) []byte

UpdateJSONWithNewKeyVal enhances the json passed with key, val

func UseFairPickup

func UseFairPickup() bool

func WithBugsnag

func WithBugsnag(fn func() error) func() error

func WithBugsnagForWarehouse

func WithBugsnagForWarehouse(fn func() error) func() error

func ZipFiles

func ZipFiles(filename string, files []string) error

ZipFiles compresses files[] into zip at filename

Types

type BufferedWriter

type BufferedWriter struct {
	File   *os.File
	Writer *bufio.Writer
}

func CreateBufferedWriter

func CreateBufferedWriter(s string) (w BufferedWriter, err error)

func (BufferedWriter) Close

func (b BufferedWriter) Close() error

func (BufferedWriter) GetFile

func (b BufferedWriter) GetFile() *os.File

func (BufferedWriter) Write

func (b BufferedWriter) Write(p []byte) (int, error)

type DefaultString

type DefaultString string

DefaultString is a utility type for providing default values using one-liners in otherwise multi-line scenarios.

E.g. this

v := misc.DefaultString("unknown").OnError(os.Hostname())

is the equivalent of

v, err := os.Hostname()
if err != nil {
  v = 	"unknown"
}

func (DefaultString) OnError

func (r DefaultString) OnError(value string, err error) string

OnError returns the default value if the err argument is not nil, otherwise the value

type ErrorStoreT

type ErrorStoreT struct {
	Errors []RudderError
}

ErrorStoreT : DS to store the app errors

type GZipWriter

type GZipWriter struct {
	File      *os.File
	GzWriter  *gzip.Writer
	BufWriter *bufio.Writer
}

func CreateGZ

func CreateGZ(s string) (w GZipWriter, err error)

func (GZipWriter) Close

func (w GZipWriter) Close() error

func (GZipWriter) CloseGZ

func (w GZipWriter) CloseGZ() error

func (GZipWriter) GetLoadFile

func (w GZipWriter) GetLoadFile() *os.File

func (GZipWriter) Write

func (w GZipWriter) Write(b []byte) (count int, err error)

func (GZipWriter) WriteGZ

func (w GZipWriter) WriteGZ(s string) error

func (GZipWriter) WriteRow

func (w GZipWriter) WriteRow(row []interface{}) error

type ObjectStorageOptsT

type ObjectStorageOptsT struct {
	Provider                    string
	Config                      interface{}
	UseRudderStorage            bool
	RudderStoragePrefixOverride string
}

type PerfStats

type PerfStats struct {
	// contains filtered or unexported fields
}

PerfStats is the class for managing performance stats. Not multi-threaded safe now

func (*PerfStats) End

func (stats *PerfStats) End(events int)

End marks the end of one round of stat collection. events is number of events processed since start

func (*PerfStats) Rate

func (stats *PerfStats) Rate(events int, elapsed time.Duration)

func (*PerfStats) Setup

func (stats *PerfStats) Setup(comp string)

Setup initializes the stat collector

func (*PerfStats) Start

func (stats *PerfStats) Start()

Start marks the start of event collection

func (*PerfStats) Status

func (stats *PerfStats) Status() map[string]interface{}

type RFP

type RFP struct {
	// contains filtered or unexported fields
}

func GetReservedFolderPaths

func GetReservedFolderPaths() []*RFP

GetReservedFolderPaths returns all temporary folder paths.

type RWCConfig

type RWCConfig struct {
	Factor int
	Jobs   *[]RWCJob
	Run    func(RWCJob interface{})
}

type RWCJob

type RWCJob interface{}

RWCConfig config for RunWithConcurrency factor: number of concurrent job jobs: range of jobs you need to provide runJob: caller function for the concurrent job

type RudderError

type RudderError struct {
	StartTime         int64
	CrashTime         int64
	ReadableStartTime string
	ReadableCrashTime string
	Message           string
	StackTrace        string
	Code              int
}

RudderError : to store rudder error

type WaitGroup

type WaitGroup struct {
	// contains filtered or unexported fields
}

func NewWaitGroup

func NewWaitGroup() *WaitGroup

func (*WaitGroup) Add

func (wg *WaitGroup) Add(delta int)

func (*WaitGroup) Done

func (wg *WaitGroup) Done()

func (*WaitGroup) Err

func (wg *WaitGroup) Err(err error)

func (*WaitGroup) Wait

func (wg *WaitGroup) Wait() error

func (*WaitGroup) WaitForAll

func (wg *WaitGroup) WaitForAll() []error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL