From 655c05cd62a658a0c448a64f2ccd8fed2534fab6 Mon Sep 17 00:00:00 2001 From: Jason Cameron Date: Fri, 20 Dec 2024 21:32:28 -0500 Subject: [PATCH] fix: race condition in LogRequest (https://github.com/tom-draper/api-analytics/issues/53) note: this is a theoretical fix and has not been properly tested --- analytics/go/core/core.go | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/analytics/go/core/core.go b/analytics/go/core/core.go index 80690546..006a67c6 100644 --- a/analytics/go/core/core.go +++ b/analytics/go/core/core.go @@ -57,14 +57,16 @@ func postRequest(apiKey string, requests []RequestData, framework string, privac } func LogRequest(apiKey string, request RequestData, framework string, privacyLevel int, serverURL string) { - if apiKey == "" { - return - } - now := time.Now() - requests = append(requests, request) - if time.Since(lastPosted) > time.Minute { - go postRequest(apiKey, requests, framework, privacyLevel, serverURL) - requests = nil - lastPosted = now - } + if apiKey == "" { + return + } + requests = append(requests, request) + if time.Since(lastPosted) > time.Minute { + requestsCopy := make([]RequestData, len(requests)) + copy(requestsCopy, requests) + + go postRequest(apiKey, requestsCopy, framework, privacyLevel, serverURL) + requests = nil + lastPosted = time.Now() + } }