misc
diff --git a/api.go b/api.go index f72ec1b..cebd66b 100644 --- a/api.go +++ b/api.go
@@ -2,6 +2,7 @@ import ( "encoding/json" + "fmt" "github.com/30x/apid-core" "github.com/30x/apidQuota/constants" "github.com/30x/apidQuota/globalVariables" @@ -9,26 +10,16 @@ "github.com/30x/apidQuota/util" "io/ioutil" "net/http" - "strconv" ) func InitAPI(services apid.Services) { - globalVariables.Log.Debug("initialized API's exposed by apidQuota plugin") + globalVariables.Log.Debug("initializing apidQuota plugin APIs") quotaBasePath := globalVariables.Config.GetString(constants.ConfigQuotaBasePath) - services.API().HandleFunc(quotaBasePath, getAllQuotaValues).Methods("GET") //yet to implement. - services.API().HandleFunc(quotaBasePath+"/{quotaItentifier}", incrementAndCheckQuotaLimit).Methods("POST") + services.API().HandleFunc(quotaBasePath, checkQuotaLimitExceeded).Methods("POST") } -func getAllQuotaValues(res http.ResponseWriter, req *http.Request) { - stringbytes := []byte("yet to implement") - res.Header().Set("Content-Type", "application/json") - res.WriteHeader(http.StatusOK) - res.Write(stringbytes) - -} - -func incrementAndCheckQuotaLimit(res http.ResponseWriter, req *http.Request) { +func checkQuotaLimitExceeded(res http.ResponseWriter, req *http.Request) { bodyBytes, err := ioutil.ReadAll(req.Body) defer req.Body.Close() @@ -42,24 +33,26 @@ util.WriteErrorResponse(http.StatusBadRequest, constants.UnMarshalJSONError, "unable to convert request body to an object: "+err.Error(), res, req) return } - globalVariables.Log.Println("quotaBucketMap from request: ", quotaBucketMap) - // parse the request body into the Event struct + // parse the request body into the QuotaBucket struct qBucket := new(quotaBucket.QuotaBucket) if err = qBucket.FromAPIRequest(quotaBucketMap); err != nil { util.WriteErrorResponse(http.StatusBadRequest, constants.ErrorConvertReqBodyToEntity, err.Error(), res, req) return } - quotaCount, err := qBucket.GetQuotaCount() + results, err := qBucket.IncrementQuotaLimit() if err != nil { util.WriteErrorResponse(http.StatusBadRequest, constants.UnMarshalJSONError, "error retrieving count for the give identifier "+err.Error(), res, req) return } - stringbytes := []byte(strconv.Itoa(quotaCount)) + respMap := results.ToAPIResponse() + fmt.Println("results from inc quota: ", results) + respbytes, err := json.Marshal(respMap) + res.Header().Set("Content-Type", "application/json") res.WriteHeader(http.StatusOK) - res.Write(stringbytes) + res.Write(respbytes) }
diff --git a/init.go b/init.go index 66e0a40..8938f9a 100644 --- a/init.go +++ b/init.go
@@ -1,32 +1,20 @@ package apidQuota import ( + "fmt" "github.com/30x/apid-core" "github.com/30x/apidQuota/constants" "github.com/30x/apidQuota/globalVariables" + "reflect" ) func init() { apid.RegisterPlugin(initPlugin) - initCounterService() -} - -// set config for counter service. -func initCounterService() { - //counterBasePath := globalVariables.Config.Get(constants.ConfigCounterServiceBasePath) - //fmt.Println("counterBasePath: ", counterBasePath , "//") - /*if counterBasePath != nil { - if reflect.TypeOf(counterBasePath).Kind() != reflect.String{ - globalVariables.Log.Fatal("value of: " + constants.ConfigCounterServiceBasePath + " in the config should be string") - } - globalVariables.CounterServiceURL = counterBasePath.(string) - }*/ - globalVariables.CounterServiceURL = "http://54.86.114.219:8989/increment" } func initPlugin(services apid.Services) (apid.PluginData, error) { globalVariables.Log = services.Log().ForModule("apidQuota") - globalVariables.Log.Debug("start init") + globalVariables.Log.Debug("start init for apidQuota") setConfig(services) InitAPI(services) @@ -40,4 +28,14 @@ // set plugin config defaults globalVariables.Config.SetDefault(constants.ConfigQuotaBasePath, constants.QuotaBasePathDefault) + counterServiceBasePath := globalVariables.Config.Get(constants.ConfigCounterServiceBasePath) + fmt.Println("counterBasePath: ", counterServiceBasePath, "//") + if counterServiceBasePath != nil { + if reflect.TypeOf(counterServiceBasePath).Kind() != reflect.String { + globalVariables.Log.Fatal("value of: " + constants.ConfigCounterServiceBasePath + " in the config should be string") + } + globalVariables.CounterServiceURL = counterServiceBasePath.(string) + } + globalVariables.CounterServiceURL = "http://54.86.114.219:8989/increment" //todo: comment it once the above code works. + }
diff --git a/quotaBucket/apiUtil.go b/quotaBucket/apiUtil.go index c29e427..5515271 100644 --- a/quotaBucket/apiUtil.go +++ b/quotaBucket/apiUtil.go
@@ -2,18 +2,25 @@ import ( "errors" - "fmt" "reflect" ) +type QuotaBucketResults struct { + EdgeOrgID string + ID string + exceededTokens bool + allowedTokens int64 + MaxCount int64 + startedAt int64 + expiresAt int64 +} + func (qBucket *QuotaBucket) FromAPIRequest(quotaBucketMap map[string]interface{}) error { var edgeOrgID, id, timeUnit, quotaType, bucketType string - var interval, maxCount int - var startTime int64 + var interval int + var startTime, maxCount, weight int64 var preciseAtSecondsLevel bool - fmt.Println("quotaBucketMap: ", quotaBucketMap) - value, ok := quotaBucketMap["edgeOrgID"] if !ok { return errors.New(`missing field: 'edgeOrgID' is required`) @@ -22,7 +29,6 @@ return errors.New(`invalid type : 'edgeOrgID' should be a string`) } edgeOrgID = value.(string) - //fmt.Println("edgeOrgID: ", edgeOrgID) value, ok = quotaBucketMap["id"] if !ok { @@ -32,7 +38,6 @@ return errors.New(`invalid type : 'id' should be a string`) } id = value.(string) - //fmt.Println("id: ", id) value, ok = quotaBucketMap["interval"] if !ok { @@ -44,7 +49,6 @@ } intervalFloat := value.(float64) interval = int(intervalFloat) - //fmt.Println("interval: ", interval) //TimeUnit {SECOND, MINUTE, HOUR, DAY, WEEK, MONTH} value, ok = quotaBucketMap["timeUnit"] @@ -55,7 +59,6 @@ return errors.New(`invalid type : 'timeUnit' should be a string`) } timeUnit = value.(string) - //fmt.Println("timeUnit: ", timeUnit) //Type {CALENDAR, FLEXI, ROLLING_WINDOW} value, ok = quotaBucketMap["quotaType"] @@ -66,7 +69,6 @@ return errors.New(`invalid type : 'quotaType' should be a string`) } quotaType = value.(string) - //fmt.Println("quotaType: ", quotaType) value, ok = quotaBucketMap["preciseAtSecondsLevel"] if !ok { @@ -76,7 +78,6 @@ return errors.New(`invalid type : 'preciseAtSecondsLevel' should be boolean`) } preciseAtSecondsLevel = value.(bool) - //fmt.Println("preciseAtSecondsLevel: ", preciseAtSecondsLevel) value, ok = quotaBucketMap["startTime"] if !ok { @@ -88,7 +89,6 @@ } startTimeFloat := value.(float64) startTime = int64(startTimeFloat) - //fmt.Println("startTime: ", startTime) value, ok = quotaBucketMap["maxCount"] if !ok { @@ -99,8 +99,7 @@ return errors.New(`invalid type : 'maxCount' should be a number`) } maxCountFloat := value.(float64) - maxCount = int(maxCountFloat) - //fmt.Println("maxCount: ", maxCount) + maxCount = int64(maxCountFloat) value, ok = quotaBucketMap["bucketType"] if !ok { @@ -110,9 +109,20 @@ return errors.New(`invalid type : 'bucketType' should be a string`) } bucketType = value.(string) - //fmt.Println("bucketType: ", bucketType) - newQBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + value, ok = quotaBucketMap["weight"] + if !ok { + return errors.New(`missing field: 'weight' is required`) + } + //from input when its read its float, need to then convert to int. + if weightType := reflect.TypeOf(value); weightType.Kind() != reflect.Float64 { + return errors.New(`invalid type : 'maxCount' should be a number`) + } + weightFloat := value.(float64) + weight = int64(weightFloat) + + + newQBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) if err != nil { return errors.New("error creating newquotaBucket: " + err.Error()) @@ -127,3 +137,17 @@ return nil } + +func (qBucketResults *QuotaBucketResults) ToAPIResponse() (map[string]interface{}) { + resultsMap := make(map[string]interface{}) + resultsMap["edgeOrgID"] = qBucketResults.ID + resultsMap["id"] = qBucketResults.ID + resultsMap["exceededTokens"] = qBucketResults.exceededTokens + resultsMap["allowedTokens"] = qBucketResults.allowedTokens + resultsMap["MaxCount"] = qBucketResults.MaxCount + resultsMap["startedAt"] = qBucketResults.startedAt + resultsMap["expiresAt"] = qBucketResults.expiresAt + + + return resultsMap +} \ No newline at end of file
diff --git a/quotaBucket/quotaBucket.go b/quotaBucket/quotaBucket.go index 119482b..871baa5 100644 --- a/quotaBucket/quotaBucket.go +++ b/quotaBucket/quotaBucket.go
@@ -92,8 +92,9 @@ PreciseAtSecondsLevel bool Period QuotaPeriod StartTime time.Time - MaxCount int + MaxCount int64 BucketType string // SyncDistributed, AsyncDistributed, NonDistributed + Weight int64 } type QuotaBucket struct { @@ -102,7 +103,7 @@ func NewQuotaBucket(edgeOrgID string, id string, interval int, timeUnit string, quotaType string, preciseAtSecondsLevel bool, - startTime int64, maxCount int, bucketType string) (*QuotaBucket, error) { + startTime int64, maxCount int64, bucketType string, weight int64) (*QuotaBucket, error) { fromUNIXTime := time.Unix(startTime, 0) @@ -116,6 +117,7 @@ StartTime: fromUNIXTime, MaxCount: maxCount, BucketType: bucketType, + Weight: weight, } quotaBucket := &QuotaBucket{ @@ -196,8 +198,9 @@ if err != nil { return nil, err } + //setCurrentPeriod if endTime > time.now() - if period.endTime.Before(time.Now().UTC()) || period.endTime.Equal(time.Now().UTC()) { + if period == nil || period.endTime.Before(time.Now().UTC()) || period.endTime.Equal(time.Now().UTC()) { if err := q.setCurrentPeriod(); err != nil { return nil, err } @@ -218,7 +221,7 @@ return &q.quotaBucketData.Period, nil } -func (q *QuotaBucket) GetMaxCount() int { +func (q *QuotaBucket) GetMaxCount() int64 { return q.quotaBucketData.MaxCount } @@ -226,6 +229,10 @@ return q.quotaBucketData.BucketType } +func (q *QuotaBucket) GetBucketWeight() int64 { + return q.quotaBucketData.Weight +} + func (q *QuotaBucket) SetPeriod(startTime time.Time, endTime time.Time) { period := QuotaPeriod{inputStartTime: q.GetStartTime(), startTime: startTime, @@ -260,28 +267,69 @@ return false } -func (q *QuotaBucket) GetQuotaCount() (int, error) { - err := q.setCurrentPeriod() - if err != nil { - return 0, errors.New("error setCurrentPeriod(): " + err.Error()) - } +func (q *QuotaBucket) IncrementQuotaLimit() (*QuotaBucketResults, error) { + maxCount := q.GetMaxCount() + exceededCount := false + allowedCount := int64(0) + weight := q.GetBucketWeight() period, err := q.GetPeriod() if err != nil { - return 0, errors.New("error getting period: " + err.Error()) + return nil, errors.New("error getting period: " + err.Error()) } - fmt.Println("period set: ", period) + fmt.Println("period set, start time: ", period.GetPeriodStartTime().String(), " end time: ", period.GetPeriodEndTime().String()) - resp, err := services.IncrementAndGetCount(q.GetEdgeOrgID(), q.GetID(), 0) + //first retrieve the count from counter service. + currentCount, err := services.IncrementAndGetCount(q.GetEdgeOrgID(), q.GetID(), 0, period.GetPeriodStartTime().Unix(), period.GetPeriodEndTime().Unix()) if err != nil { - return 0, err + return nil, err } - return resp, nil -} + fmt.Println("startTime get period : ", period.GetPeriodStartTime().String()) + fmt.Println("endTime get period : ", period.GetPeriodEndTime().String()) -func (q *QuotaBucket) IncrementQuota() (int, error) { - //todo - return 0, nil + if period.IsCurrentPeriod(q) { + + if currentCount < maxCount { + allowed := maxCount - currentCount + + if allowed > weight { + + if weight != 0 { + + currentCount, err = services.IncrementAndGetCount(q.GetEdgeOrgID(), q.GetID(), weight, period.GetPeriodStartTime().Unix(), period.GetPeriodEndTime().Unix()) + if err != nil { + return nil, err + } + } + + allowedCount = currentCount + weight + } else { + + if weight != 0 { + + exceededCount = true + } + allowedCount = currentCount + weight + } + } else { + + exceededCount = true + allowedCount = currentCount + } + } + + results := &QuotaBucketResults{ + EdgeOrgID : q.GetEdgeOrgID(), + ID : q.GetID(), + exceededTokens : exceededCount, + allowedTokens : allowedCount, + MaxCount : maxCount, + startedAt : period.GetPeriodStartTime().Unix(), + expiresAt : period.GetPeriodEndTime().Unix(), + + } + + return results, nil } func IsValidTimeUnit(timeUnit string) bool {
diff --git a/quotaBucket/quotaBucket_test.go b/quotaBucket/quotaBucket_test.go index 4d1e166..3adfce6 100644 --- a/quotaBucket/quotaBucket_test.go +++ b/quotaBucket/quotaBucket_test.go
@@ -95,11 +95,12 @@ quotaType := "calendar" bucketType := "synchronous" interval := 1 - maxCount := 10 + maxCount := int64(10) + weight := int64(1) preciseAtSecondsLevel := true startTime := time.Now().UTC().AddDate(0, -1, 0).Unix() - quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -132,11 +133,12 @@ quotaType := "calendar" bucketType := "synchronous" interval := 1 - maxCount := 10 + maxCount := int64(10) + weight := int64(1) preciseAtSecondsLevel := true startTime := time.Now().UTC().AddDate(0, -1, 0).Unix() - quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) quotaBucket.SetPeriod(time.Now().UTC().UTC().AddDate(0, 1, 0), time.Now().AddDate(0, 0, -1)) @@ -157,10 +159,11 @@ quotaType := "calendar" bucketType := "synchronous" interval := 1 - maxCount := 10 + maxCount := int64(10) + weight := int64(1) preciseAtSecondsLevel := true startTime := time.Now().UTC().AddDate(0, -1, 0).Unix() - quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).To(HaveOccurred()) if !strings.Contains(err.Error(), InvalidQuotaTimeUnitType) { @@ -179,11 +182,12 @@ quotaType := "calendar" bucketType := "invalidQuotaBucket" interval := 1 - maxCount := 10 + maxCount := int64(10) + weight := int64(1) preciseAtSecondsLevel := true startTime := time.Now().UTC().AddDate(0, -1, 0).Unix() - quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -206,12 +210,13 @@ quotaType := "rollingwindow" bucketType := "synchronous" interval := 1 - maxCount := 10 + maxCount := int64(10) + weight := int64(1) preciseAtSecondsLevel := true //InputStart time is before now startTime := time.Now().UTC().AddDate(0, -1, 0).Unix() - quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() Expect(err).NotTo(HaveOccurred()) @@ -226,7 +231,7 @@ //InputStart time is now startTime = time.Now().UTC().Unix() - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() Expect(err).NotTo(HaveOccurred()) @@ -249,12 +254,13 @@ quotaType := "rollingwindow" bucketType := "synchronous" interval := 1 - maxCount := 10 + maxCount := int64(10) + weight := int64(1) preciseAtSecondsLevel := true //InputStart time is after now. startTime := time.Now().UTC().AddDate(0, 1, 0).Unix() - quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -269,7 +275,7 @@ //endTime before startTime in period startTime = time.Now().UTC().AddDate(0, -1, 0).Unix() - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) quotaBucket.SetPeriod(time.Now().UTC(), time.Now().UTC().AddDate(0, -1, 0)) @@ -286,13 +292,14 @@ quotaType := "calendar" bucketType := "synchronous" interval := 1 - maxCount := 10 + maxCount := int64(10) + weight := int64(1) preciseAtSecondsLevel := true //InputStart time is before now startTime := time.Now().UTC().UTC().AddDate(-1, -1, 0).Unix() - quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -308,7 +315,7 @@ //InputStart time is now startTime = time.Now().UTC().Unix() - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -325,7 +332,7 @@ //start Time in period is before now startTime = time.Now().UTC().Unix() - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -344,7 +351,7 @@ //start Time in period is now startTime = time.Now().UTC().Unix() - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -379,7 +386,7 @@ //end Time in period is after now startTime = time.Now().UTC().Unix() - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -399,7 +406,7 @@ //start time in period is before end time startTime = time.Now().UTC().Unix() - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -425,7 +432,8 @@ quotaType := "calendar" bucketType := "synchronous" interval := 1 - maxCount := 10 + maxCount := int64(10) + weight := int64(1) preciseAtSecondsLevel := true //InputStart time is after now. @@ -433,7 +441,7 @@ time.Now().UTC().AddDate(0, 1, 0).Unix(), time.Now().AddDate(1, 0, 1).Unix()) startTime := time.Now().UTC().AddDate(0, 1, 0).Unix() - quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -445,7 +453,7 @@ //endTime is before start time startTime = time.Now().UTC().AddDate(0, -1, 0).Unix() - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -482,11 +490,12 @@ quotaType := "rollingwindow" bucketType := "synchronous" interval := 1 - maxCount := 10 + maxCount := int64(10) + weight := int64(1) preciseAtSecondsLevel := true //InputStart time is before now startTime := time.Now().UTC().AddDate(0, -1, 0).Unix() - quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) quotaBucket.SetPeriod(time.Now().UTC().AddDate(0, 0, -1), time.Now().UTC().AddDate(0, 1, 0)) @@ -508,7 +517,7 @@ quotaType = "calendar" pstartTime := time.Now().UTC().AddDate(0, -1, 0) pendTime := time.Now().UTC().AddDate(0, 1, 0) - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) quotaBucket.SetPeriod(pstartTime, pendTime) @@ -524,7 +533,7 @@ quotaType = "calendar" pstartTime = time.Now().UTC().AddDate(0, -1, 0) pendTime = time.Now().UTC().AddDate(0, -1, 0) - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) quotaBucket.SetPeriod(pstartTime, pendTime)
diff --git a/quotaBucket/quotaDescriptorType.go b/quotaBucket/quotaDescriptorType.go index 87e8f0c..8dec92c 100644 --- a/quotaBucket/quotaDescriptorType.go +++ b/quotaBucket/quotaDescriptorType.go
@@ -144,7 +144,7 @@ return currentEnd.Sub(currentStart), nil case QuotaTypeRollingWindow: currentEnd = now - currentStart = currentEnd.AddDate(0, -qb.Interval, 0) + currentStart = currentEnd.AddDate(0, (-1)*qb.Interval, 0) return currentEnd.Sub(currentStart), nil default: return time.Duration(0), errors.New(InvalidQuotaDescriptorType + " : ignoring unrecognized quotaType : " + quotaType)
diff --git a/quotaBucket/quotaDescriptorType_test.go b/quotaBucket/quotaDescriptorType_test.go index 5c83148..30c7c68 100644 --- a/quotaBucket/quotaDescriptorType_test.go +++ b/quotaBucket/quotaDescriptorType_test.go
@@ -4,17 +4,16 @@ . "github.com/30x/apidQuota/quotaBucket" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "time" - "strings" "reflect" + "strings" + "time" ) - var _ = Describe("Check Descriptor Type ", func() { It("test Calendar Type descriptor", func() { descriptorType, err := GetQuotaDescriptorTypeHandler("calendar") Expect(err).NotTo(HaveOccurred()) - if reflect.TypeOf(descriptorType)!= reflect.TypeOf(&CalendarQuotaDescriptorType{}){ + if reflect.TypeOf(descriptorType) != reflect.TypeOf(&CalendarQuotaDescriptorType{}) { Fail("Excepted CalendarQuotaDescriptorType, but got: " + reflect.TypeOf(descriptorType).String()) } }) @@ -22,7 +21,7 @@ It("test RollingWindow Type descriptor", func() { descriptorType, err := GetQuotaDescriptorTypeHandler("rollingwindow") Expect(err).NotTo(HaveOccurred()) - if reflect.TypeOf(descriptorType)!= reflect.TypeOf(&RollingWindowQuotaDescriptorType{}){ + if reflect.TypeOf(descriptorType) != reflect.TypeOf(&RollingWindowQuotaDescriptorType{}) { Fail("Excepted RollingWindowQuotaDescriptorType, but got: " + reflect.TypeOf(descriptorType).String()) } }) @@ -46,11 +45,13 @@ quotaType := "calendar" bucketType := "synchronous" interval := 1 - maxCount := 10 + maxCount := int64(10) + weight := int64(1) + preciseAtSecondsLevel := true startTime := time.Now().UTC().UTC().AddDate(0, -1, 0).Unix() - quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -68,11 +69,10 @@ intervalDuration := period.GetPeriodEndTime().Sub(period.GetPeriodStartTime()) Expect(intervalDuration).Should(Equal(time.Second)) - // test set period for timeUnit=minute timeUnit = "minute" - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -93,7 +93,7 @@ // test set period for timeUnit=hour timeUnit = "hour" - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -111,11 +111,10 @@ intervalDuration = period.GetPeriodEndTime().Sub(period.GetPeriodStartTime()) Expect(intervalDuration).Should(Equal(time.Hour)) - // test set period for timeUnit=day timeUnit = "day" - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -136,7 +135,7 @@ // test set period for timeUnit=week timeUnit = "week" - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -154,11 +153,10 @@ intervalDuration = period.GetPeriodEndTime().Sub(period.GetPeriodStartTime()) Expect(intervalDuration).Should(Equal(7 * 24 * time.Hour)) - // test set period for timeUnit=month timeUnit = "month" - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -174,7 +172,7 @@ Expect(period.GetPeriodStartTime().String()).ShouldNot(BeEmpty()) Expect(period.GetPeriodEndTime().String()).ShouldNot(BeEmpty()) intervalDuration = period.GetPeriodEndTime().Sub(period.GetPeriodStartTime()) - addMonthToStartDate := period.GetPeriodStartTime().AddDate(0,interval*1,0) + addMonthToStartDate := period.GetPeriodStartTime().AddDate(0, interval*1, 0) actualDuration := addMonthToStartDate.Sub(period.GetPeriodStartTime()) Expect(intervalDuration).Should(Equal(actualDuration)) @@ -189,11 +187,12 @@ quotaType := "calendar" bucketType := "synchronous" interval := 1 - maxCount := 10 + maxCount := int64(10) + weight := int64(1) preciseAtSecondsLevel := true startTime := time.Now().UTC().UTC().AddDate(0, -1, 0).Unix() - quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -211,13 +210,12 @@ intervalDuration := period.GetPeriodEndTime().Sub(period.GetPeriodStartTime()) Expect(intervalDuration).Should(Equal(time.Second)) - // test set period for timeUnit=month timeUnit = "invalidTimeUnit" - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).To(HaveOccurred()) - if ok := strings.Contains(err.Error(),InvalidQuotaTimeUnitType); !ok { + if ok := strings.Contains(err.Error(), InvalidQuotaTimeUnitType); !ok { Fail("expected error to contain " + InvalidQuotaTimeUnitType + " but got different error message: " + err.Error()) } @@ -232,11 +230,12 @@ quotaType := "rollingWindow" bucketType := "synchronous" interval := 1 - maxCount := 10 + maxCount := int64(10) + weight := int64(1) preciseAtSecondsLevel := true startTime := time.Now().UTC().UTC().AddDate(0, -1, 0).Unix() - quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -254,11 +253,10 @@ intervalDuration := period.GetPeriodEndTime().Sub(period.GetPeriodStartTime()) Expect(intervalDuration).Should(Equal(time.Second)) - // test set period for timeUnit=minute timeUnit = "minute" - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -279,7 +277,7 @@ // test set period for timeUnit=hour timeUnit = "hour" - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -297,11 +295,10 @@ intervalDuration = period.GetPeriodEndTime().Sub(period.GetPeriodStartTime()) Expect(intervalDuration).Should(Equal(time.Hour)) - // test set period for timeUnit=day timeUnit = "day" - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -322,7 +319,7 @@ // test set period for timeUnit=week timeUnit = "week" - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -340,11 +337,10 @@ intervalDuration = period.GetPeriodEndTime().Sub(period.GetPeriodStartTime()) Expect(intervalDuration).Should(Equal(7 * 24 * time.Hour)) - // test set period for timeUnit=month timeUnit = "month" - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -360,8 +356,8 @@ Expect(period.GetPeriodStartTime().String()).ShouldNot(BeEmpty()) Expect(period.GetPeriodEndTime().String()).ShouldNot(BeEmpty()) intervalDuration = period.GetPeriodEndTime().Sub(period.GetPeriodStartTime()) - addMonthToStartDate := period.GetPeriodStartTime().AddDate(0,interval*1,0) - actualDuration := addMonthToStartDate.Sub(period.GetPeriodStartTime()) + subMonthToEndtDate := period.GetPeriodEndTime().AddDate(0, -interval*1, 0) + actualDuration := period.GetPeriodEndTime().Sub(subMonthToEndtDate) Expect(intervalDuration).Should(Equal(actualDuration)) }) @@ -375,11 +371,12 @@ quotaType := "rollingwindow" bucketType := "synchronous" interval := 1 - maxCount := 10 + maxCount := int64(10) + weight := int64(1) preciseAtSecondsLevel := true startTime := time.Now().UTC().UTC().AddDate(0, -1, 0).Unix() - quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err := NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).NotTo(HaveOccurred()) err = quotaBucket.Validate() @@ -397,15 +394,14 @@ intervalDuration := period.GetPeriodEndTime().Sub(period.GetPeriodStartTime()) Expect(intervalDuration).Should(Equal(time.Second)) - // test set period for timeUnit=month timeUnit = "invalidTimeUnit" - quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType) + quotaBucket, err = NewQuotaBucket(edgeOrgID, id, interval, timeUnit, quotaType, preciseAtSecondsLevel, startTime, maxCount, bucketType, weight) Expect(err).To(HaveOccurred()) - if ok := strings.Contains(err.Error(),InvalidQuotaTimeUnitType); !ok { + if ok := strings.Contains(err.Error(), InvalidQuotaTimeUnitType); !ok { Fail("expected error to contain " + InvalidQuotaTimeUnitType + " but got different error message: " + err.Error()) } }) -}) \ No newline at end of file +})
diff --git a/services/counterServiceHelper.go b/services/counterServiceHelper.go index 8568d8d..1f08a6b 100644 --- a/services/counterServiceHelper.go +++ b/services/counterServiceHelper.go
@@ -4,6 +4,7 @@ "bytes" "encoding/json" "errors" + "fmt" "github.com/30x/apidQuota/constants" "github.com/30x/apidQuota/globalVariables" "io/ioutil" @@ -23,7 +24,7 @@ Timeout: time.Duration(60 * time.Second), } -func IncrementAndGetCount(orgID string, quotaKey string, count int) (int, error) { +func IncrementAndGetCount(orgID string, quotaKey string, count int64, startTimeInt int64, endTimeInt int64) (int64, error) { headers := http.Header{} headers.Set("Accept", "application/json") headers.Set("Content-Type", "application/json") @@ -44,6 +45,11 @@ reqBody[edgeOrgID] = orgID reqBody[key] = quotaKey reqBody[delta] = count + reqBody["startTime"] = startTimeInt + reqBody["endTime"] = endTimeInt + + fmt.Println("startTime: ", startTimeInt) + fmt.Println("endTime: ", endTimeInt) reqBodyBytes, err := json.Marshal(reqBody) if err != nil { @@ -89,13 +95,15 @@ if !ok { return 0, errors.New(`invalid response from counter service. field 'count' not sent in the response`) } + fmt.Println("respcount: ", respCount) globalVariables.Log.Debug("responseCount: ", respCount) - respCountInt, ok := respCount.(int) + + respCountInt, ok := respCount.(float64) if !ok { - return 0, errors.New(`invalid response from counter service. field 'count' sent in the response is not int`) + return 0, errors.New(`invalid response from counter service. field 'count' sent in the response is not float`) } - return respCountInt, nil + return int64(respCountInt), nil }