adds client side time based rate limiting
diff --git a/README.md b/README.md index 04a68c0..f3a0f56 100644 --- a/README.md +++ b/README.md
@@ -23,8 +23,18 @@ | LM_BEARER_TOKEN | BearerToken while using Bearer authentication.| ### Metrics Ingestion: -For metrics ingestion, user must create an object of ResourceInput, DataSourceInput, InstanceInput and DataPointInput by passing relevant metric and attribute values to the struct fields using package `github.com/logicmonitor/lm-data-sdk-go/model`. -Initialize metric ingest by calling NewLMMetricIngest. If user wants to enable batching, pass an option `WithMetricBatchingEnabled(batchinterval)` to NewLMMetricIngest() function call. +For metrics ingestion, user must create an object of `ResourceInput`, `DataSourceInput`, `InstanceInput` and `DataPointInput` by passing relevant metric and attribute values to the struct fields using package `github.com/logicmonitor/lm-data-sdk-go/model`. + +Initialize metric ingest by calling `NewLMMetricIngest`. + +#### Options: + +- If user wants to enable batching, user can pass an option `WithMetricBatchingEnabled(batchinterval)` to NewLMMetricIngest() function call. + +- Number of requests for metrics per minute can be controlled using `WithRateLimit(requestCount int)`. + +#### Example: + For exporting metrics to LM platform, call SendMetrics by passing all the attributes as input parameters. // fill the values @@ -64,8 +74,17 @@ ### Logs Ingestion -Initialize log ingest by calling NewLMLogIngest. If user wants to enable batching, pass an option `WithLogBatchingEnabled(batchinterval)` to NewLMLogIngest() function call. -For exporting logs to LM platform, call SendLogs by passing `log message`, `resource ID` and `metadatamap` as input parameters. +Initialize log ingest by calling `NewLMLogIngest`. + +#### Options: + +- If user wants to enable batching, pass an option `WithLogBatchingEnabled(batchinterval)` to NewLMLogIngest() function call. + +- Number of requests for logs per minute can be controlled using `WithRateLimit(requestCount int)` + +#### Example: + +For exporting logs to LM platform, call SendLogs by passing `log message`, `resource ID` and `metadata map` as input parameters. ``` var options []logs.Option
diff --git a/api/logs/logs.go b/api/logs/logs.go index 90537b9..2ee350a 100644 --- a/api/logs/logs.go +++ b/api/logs/logs.go
@@ -10,8 +10,10 @@ "sync" "time" - "github.com/logicmonitor/lm-data-sdk-go/internal" + "github.com/logicmonitor/lm-data-sdk-go/internal/client" "github.com/logicmonitor/lm-data-sdk-go/model" + batch "github.com/logicmonitor/lm-data-sdk-go/pkg/batch" + rateLimiter "github.com/logicmonitor/lm-data-sdk-go/pkg/ratelimiter" "github.com/logicmonitor/lm-data-sdk-go/utils" ) @@ -29,12 +31,14 @@ ) type LMLogIngest struct { - client *http.Client - url string - batch bool - interval time.Duration - auth model.AuthProvider - gzip bool + client *http.Client + url string + batch bool + interval time.Duration + auth model.AuthProvider + gzip bool + rateLimiterSetting rateLimiter.RateLimiterSetting + rateLimiter rateLimiter.RateLimiter } // NewLMLogIngest initializes LMLogIngest @@ -46,23 +50,30 @@ logsURL, err := utils.URL() if err != nil { - return nil, fmt.Errorf("Error in forming Logs URL: %v", err) + return nil, fmt.Errorf("error in forming Logs URL: %v", err) } lli := LMLogIngest{ - client: &client, - url: logsURL, - batch: true, - interval: defaultBatchingInterval, - auth: model.DefaultAuthenticator{}, - gzip: true, + client: &client, + url: logsURL, + batch: true, + interval: defaultBatchingInterval, + auth: model.DefaultAuthenticator{}, + gzip: true, + rateLimiterSetting: rateLimiter.RateLimiterSetting{}, } + for _, opt := range opts { if err := opt(&lli); err != nil { return nil, err } } + lli.rateLimiter, err = rateLimiter.NewLogRateLimiter(lli.rateLimiterSetting) + if err != nil { + return nil, err + } + go lli.rateLimiter.Run(ctx) if lli.batch { - go internal.CreateAndExportData(&lli) + go batch.CreateAndExportData(&lli) } return &lli, nil } @@ -90,7 +101,7 @@ } bodyarr := append([]model.LogPayload{}, body) - logPayloadList := internal.DataPayload{ + logPayloadList := model.DataPayload{ LogBodyList: bodyarr, } return lli.ExportData(logPayloadList, uri, http.MethodPost) @@ -116,12 +127,12 @@ } // CreateRequestBody prepares log payload from the requests present in cache after batch interval expires -func (lli *LMLogIngest) CreateRequestBody() internal.DataPayload { +func (lli *LMLogIngest) CreateRequestBody() model.DataPayload { var logPayloadList []model.LogPayload logBatchMutex.Lock() defer logBatchMutex.Unlock() if len(logBatch) == 0 { - return internal.DataPayload{} + return model.DataPayload{} } for _, logsV1 := range logBatch { var body model.LogPayload @@ -134,7 +145,7 @@ } logPayloadList = append(logPayloadList, body) } - payloadList := internal.DataPayload{ + payloadList := model.DataPayload{ LogBodyList: logPayloadList, } // flushing out log batch @@ -145,14 +156,26 @@ } // ExportData exports logs to the LM platform -func (lli *LMLogIngest) ExportData(payloadList internal.DataPayload, uri, method string) error { +func (lli *LMLogIngest) ExportData(payloadList model.DataPayload, uri, method string) error { if len(payloadList.LogBodyList) > 0 { body, err := json.Marshal(payloadList.LogBodyList) if err != nil { return fmt.Errorf("error in marshaling log payload: %v", err) } token := lli.auth.GetCredentials(method, uri, body) - _, err = internal.MakeRequest(lli.client, lli.url, body, uri, method, token, lli.gzip) + + cfg := client.RequestConfig{ + Client: lli.client, + RateLimiter: lli.rateLimiter, + Url: lli.url, + Body: body, + Uri: lli.URI(), + Method: method, + Token: token, + Gzip: lli.gzip, + } + + _, err = client.MakeRequest(context.Background(), cfg) if err != nil { return fmt.Errorf("error while exporting logs : %v", err) }
diff --git a/api/logs/logs_test.go b/api/logs/logs_test.go index 3125f3d..35c3199 100644 --- a/api/logs/logs_test.go +++ b/api/logs/logs_test.go
@@ -3,6 +3,7 @@ import ( "context" "encoding/json" + "fmt" "net/http" "net/http/httptest" "os" @@ -10,6 +11,7 @@ "time" "github.com/logicmonitor/lm-data-sdk-go/model" + rateLimiter "github.com/logicmonitor/lm-data-sdk-go/pkg/ratelimiter" "github.com/logicmonitor/lm-data-sdk-go/utils" ) @@ -49,8 +51,10 @@ for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { setEnv() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() - lli, err := NewLMLogIngest(context.Background(), tt.args.option...) + lli, err := NewLMLogIngest(ctx, tt.args.option...) if err != nil { t.Errorf("NewLMLogIngest() error = %v", err) return @@ -109,12 +113,13 @@ } t.Run(test.name, func(t *testing.T) { - setEnv() + rateLimiter, _ := rateLimiter.NewLogRateLimiter(rateLimiter.RateLimiterSetting{RequestCount: 100}) e := &LMLogIngest{ - client: test.fields.client, - url: test.fields.url, - auth: test.fields.auth, + client: test.fields.client, + url: test.fields.url, + auth: test.fields.auth, + rateLimiter: rateLimiter, } err := e.SendLogs(context.Background(), test.args.log, test.args.resourceId, test.args.metadata) if err != nil { @@ -167,12 +172,13 @@ } t.Run(test.name, func(t *testing.T) { - setEnv() + rateLimiter, _ := rateLimiter.NewLogRateLimiter(rateLimiter.RateLimiterSetting{RequestCount: 100}) e := &LMLogIngest{ - client: test.fields.client, - url: test.fields.url, - auth: test.fields.auth, + client: test.fields.client, + url: test.fields.url, + auth: test.fields.auth, + rateLimiter: rateLimiter, } err := e.SendLogs(context.Background(), test.args.log, test.args.resourceId, test.args.metadata) if err == nil { @@ -224,14 +230,15 @@ } t.Run(test.name, func(t *testing.T) { - setLMEnv() + rateLimiter, _ := rateLimiter.NewLogRateLimiter(rateLimiter.RateLimiterSetting{RequestCount: 100}) e := &LMLogIngest{ - client: test.fields.client, - url: test.fields.url, - auth: test.fields.auth, - batch: true, - interval: 1 * time.Second, + client: test.fields.client, + url: test.fields.url, + auth: test.fields.auth, + batch: true, + interval: 1 * time.Second, + rateLimiter: rateLimiter, } err := e.SendLogs(context.Background(), test.args.log, test.args.resourceId, test.args.metadata) if err != nil { @@ -321,3 +328,62 @@ os.Unsetenv("LOGICMONITOR_ACCESS_ID") os.Unsetenv("LOGICMONITOR_ACCESS_KEY") } + +func BenchmarkSendLogs(b *testing.B) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + response := utils.Response{ + Success: true, + Message: "Logs exported successfully!!", + } + body, _ := json.Marshal(response) + time.Sleep(10 * time.Millisecond) + w.Write(body) + })) + + type args struct { + log string + resourceId map[string]string + metadata map[string]string + } + + type fields struct { + client *http.Client + url string + auth model.AuthProvider + } + + test := struct { + name string + fields fields + args args + }{ + name: "Test log export without batching", + fields: fields{ + client: ts.Client(), + url: ts.URL, + auth: model.DefaultAuthenticator{}, + }, + args: args{ + log: "This is test message", + resourceId: map[string]string{"test": "resource"}, + metadata: map[string]string{"test": "metadata"}, + }, + } + setEnv() + defer cleanupEnv() + + for i := 0; i < b.N; i++ { + rateLimiter, _ := rateLimiter.NewLogRateLimiter(rateLimiter.RateLimiterSetting{RequestCount: 350}) + e := &LMLogIngest{ + client: test.fields.client, + url: test.fields.url, + auth: test.fields.auth, + rateLimiter: rateLimiter, + } + err := e.SendLogs(context.Background(), test.args.log, test.args.resourceId, test.args.metadata) + if err != nil { + fmt.Print(err) + return + } + } +}
diff --git a/api/logs/options.go b/api/logs/options.go index 75a395a..14971ac 100644 --- a/api/logs/options.go +++ b/api/logs/options.go
@@ -40,3 +40,11 @@ return nil } } + +// WithRateLimit is used to limit the log request count per minute +func WithRateLimit(requestCount int) Option { + return func(lli *LMLogIngest) error { + lli.rateLimiterSetting.RequestCount = requestCount + return nil + } +}
diff --git a/api/metrics/metrics.go b/api/metrics/metrics.go index 3a517b4..0feb9a3 100644 --- a/api/metrics/metrics.go +++ b/api/metrics/metrics.go
@@ -10,8 +10,10 @@ "sync" "time" - "github.com/logicmonitor/lm-data-sdk-go/internal" + "github.com/logicmonitor/lm-data-sdk-go/internal/client" "github.com/logicmonitor/lm-data-sdk-go/model" + "github.com/logicmonitor/lm-data-sdk-go/pkg/batch" + rateLimiter "github.com/logicmonitor/lm-data-sdk-go/pkg/ratelimiter" "github.com/logicmonitor/lm-data-sdk-go/utils" "github.com/logicmonitor/lm-data-sdk-go/validator" ) @@ -36,12 +38,14 @@ ) type LMMetricIngest struct { - client *http.Client - url string - batch bool - interval time.Duration - auth model.AuthProvider - gzip bool + client *http.Client + url string + batch bool + interval time.Duration + auth model.AuthProvider + gzip bool + rateLimiterSetting rateLimiter.RateLimiterSetting + rateLimiter rateLimiter.RateLimiter } // NewLMMetricIngest initializes LMMetricIngest @@ -53,24 +57,30 @@ metricsURL, err := utils.URL() if err != nil { - return nil, fmt.Errorf("Error in forming Metrics URL: %v", err) + return nil, fmt.Errorf("error in forming Metrics URL: %v", err) } lmi := LMMetricIngest{ - client: &client, - url: metricsURL, - batch: true, - interval: defaultBatchingInterval, - auth: model.DefaultAuthenticator{}, - gzip: true, + client: &client, + url: metricsURL, + batch: true, + interval: defaultBatchingInterval, + auth: model.DefaultAuthenticator{}, + gzip: true, + rateLimiterSetting: rateLimiter.RateLimiterSetting{}, } for _, opt := range opts { if err := opt(&lmi); err != nil { return nil, err } } + lmi.rateLimiter, err = rateLimiter.NewMetricsRateLimiter(lmi.rateLimiterSetting) + if err != nil { + return nil, err + } + go lmi.rateLimiter.Run(ctx) if lmi.batch { - go internal.CreateAndExportData(&lmi) + go batch.CreateAndExportData(&lmi) } return &lmi, nil } @@ -79,7 +89,7 @@ func (lmi *LMMetricIngest) SendMetrics(ctx context.Context, rInput model.ResourceInput, dsInput model.DatasourceInput, instInput model.InstanceInput, dpInput model.DataPointInput) error { errorMsg := validator.ValidateAttributes(rInput, dsInput, instInput, dpInput) if errorMsg != "" { - return fmt.Errorf("Validation failed : %s", errorMsg) + return fmt.Errorf("validation failed : %s", errorMsg) } dsInput, instInput, dpInput = setDefaultValues(dsInput, instInput, dpInput) @@ -95,13 +105,13 @@ } else { payload := createSingleRequestBody(input) singlePayloadBody := append([]model.MetricPayload{}, payload) - var payloadList internal.DataPayload + var payloadList model.DataPayload if input.Resource.IsCreate { - payloadList = internal.DataPayload{ + payloadList = model.DataPayload{ MetricResourceCreateList: singlePayloadBody, } } else { - payloadList = internal.DataPayload{ + payloadList = model.DataPayload{ MetricBodyList: singlePayloadBody, } } @@ -174,7 +184,7 @@ } // CreateRequestBody merges the requests present in batching cache and creates metric payload at the end of every batching interval -func (lmi *LMMetricIngest) CreateRequestBody() internal.DataPayload { +func (lmi *LMMetricIngest) CreateRequestBody() model.DataPayload { // merge the requests from map resourceMap = make(map[string]model.ResourceInput) dsMap = make(map[string][]model.DatasourceInput) @@ -184,7 +194,7 @@ metricBatchMutex.Lock() defer metricBatchMutex.Unlock() if len(metricBatch) == 0 { - return internal.DataPayload{} + return model.DataPayload{} } for _, singleRequest := range metricBatch { if _, ok := resourceMap[singleRequest.Resource.ResourceName]; !ok { @@ -246,7 +256,7 @@ } // createRestMetricsPayload prepares metrics payload -func (lmi *LMMetricIngest) createRestMetricsPayload() internal.DataPayload { +func (lmi *LMMetricIngest) createRestMetricsPayload() model.DataPayload { var payloadList []model.MetricPayload var payloadListCreateFlag []model.MetricPayload for resName, resDetails := range resourceMap { @@ -289,7 +299,7 @@ } } - metricPayload := internal.DataPayload{ + metricPayload := model.DataPayload{ MetricBodyList: payloadList, MetricResourceCreateList: payloadListCreateFlag, } @@ -301,15 +311,27 @@ } // ExportData exports metrics to the LM platform -func (lmi *LMMetricIngest) ExportData(payloadList internal.DataPayload, uri, method string) error { +func (lmi *LMMetricIngest) ExportData(payloadList model.DataPayload, uri, method string) error { + ctx := context.Background() var errStrings []string + + cfg := client.RequestConfig{ + Client: lmi.client, + Url: lmi.url, + Uri: uri, + Method: method, + Gzip: lmi.gzip, + RateLimiter: lmi.rateLimiter, + } + if method == http.MethodPatch || method == http.MethodPut { payloadBody, err := json.Marshal(payloadList.UpdatePropertiesBody) if err != nil { errStrings = append(errStrings, "error in marshaling update property metric payload: "+err.Error()) } - token := lmi.auth.GetCredentials(method, uri, payloadBody) - _, err = internal.MakeRequest(lmi.client, lmi.url, payloadBody, uri, method, token, lmi.gzip) + cfg.Token = lmi.auth.GetCredentials(method, uri, payloadBody) + cfg.Body = payloadBody + _, err = client.MakeRequest(ctx, cfg) if err != nil { errStrings = append(errStrings, "error in updating properties: "+err.Error()) } @@ -319,8 +341,9 @@ if err != nil { errStrings = append(errStrings, "error in marshaling metric payload: "+err.Error()) } - token := lmi.auth.GetCredentials(method, uri, payloadBody) - _, err = internal.MakeRequest(lmi.client, lmi.url, payloadBody, uri, method, token, lmi.gzip) + cfg.Token = lmi.auth.GetCredentials(method, uri, payloadBody) + cfg.Body = payloadBody + _, err = client.MakeRequest(ctx, cfg) if err != nil { errStrings = append(errStrings, "error while exporting metrics: "+err.Error()) } @@ -331,8 +354,10 @@ if err != nil { errStrings = append(errStrings, "error in marshaling metric payload with create flag: "+err.Error()) } - token := lmi.auth.GetCredentials(method, uri, payloadBody) - _, err = internal.MakeRequest(lmi.client, lmi.url, payloadBody, metricURI, method, token, lmi.gzip) + cfg.Token = lmi.auth.GetCredentials(method, uri, payloadBody) + cfg.Body = payloadBody + cfg.Uri = metricURI + _, err = client.MakeRequest(ctx, cfg) if err != nil { errStrings = append(errStrings, "error while exporting metrics with create flag : "+err.Error()) } @@ -365,7 +390,7 @@ method = http.MethodPatch } - updateResPropBody := internal.DataPayload{ + updateResPropBody := model.DataPayload{ UpdatePropertiesBody: updateResProp, } return lmi.ExportData(updateResPropBody, updateResPropURI, method) @@ -383,7 +408,7 @@ errorMsg += validator.CheckDSDisplayNameValidation(dsDisplayName) if errorMsg != "" { - return fmt.Errorf("Validation failed: %v", errorMsg) + return fmt.Errorf("validation failed: %v", errorMsg) } method := http.MethodPut @@ -397,9 +422,8 @@ InstanceName: insName, InstanceProperties: insProps, } - updateInsPropBody := internal.DataPayload{ + updateInsPropBody := model.DataPayload{ UpdatePropertiesBody: updateInsProp, } return lmi.ExportData(updateInsPropBody, updateInsPropURI, method) - }
diff --git a/api/metrics/metrics_test.go b/api/metrics/metrics_test.go index 5ced6c6..7fe0032 100644 --- a/api/metrics/metrics_test.go +++ b/api/metrics/metrics_test.go
@@ -11,6 +11,7 @@ "time" "github.com/logicmonitor/lm-data-sdk-go/model" + rateLimiter "github.com/logicmonitor/lm-data-sdk-go/pkg/ratelimiter" "github.com/logicmonitor/lm-data-sdk-go/utils" ) @@ -50,7 +51,9 @@ for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { setEnv() - lmi, err := NewLMMetricIngest(context.Background(), tt.args.option...) + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + lmi, err := NewLMMetricIngest(ctx, tt.args.option...) if err != nil { t.Errorf("NewLMMetricIngest() error = %v", err) return @@ -113,12 +116,13 @@ } t.Run(test.name, func(t *testing.T) { - setEnv() + rateLimiter, _ := rateLimiter.NewMetricsRateLimiter(rateLimiter.RateLimiterSetting{RequestCount: 100}) e := &LMMetricIngest{ - client: test.fields.client, - url: test.fields.url, - auth: test.fields.auth, + client: test.fields.client, + url: test.fields.url, + auth: test.fields.auth, + rateLimiter: rateLimiter, } err := e.SendMetrics(context.Background(), test.args.rInput, test.args.dsInput, test.args.instInput, test.args.dpInput) if err != nil { @@ -174,12 +178,13 @@ } t.Run(test.name, func(t *testing.T) { - setEnv() + rateLimiter, _ := rateLimiter.NewMetricsRateLimiter(rateLimiter.RateLimiterSetting{RequestCount: 100}) e := &LMMetricIngest{ - client: test.fields.client, - url: test.fields.url, - auth: test.fields.auth, + client: test.fields.client, + url: test.fields.url, + auth: test.fields.auth, + rateLimiter: rateLimiter, } err := e.SendMetrics(context.Background(), test.args.rInput, test.args.dsInput, test.args.instInput, test.args.dpInput) if err != nil { @@ -236,12 +241,13 @@ } t.Run(test.name, func(t *testing.T) { - setEnv() + rateLimiter, _ := rateLimiter.NewMetricsRateLimiter(rateLimiter.RateLimiterSetting{RequestCount: 100}) e := &LMMetricIngest{ - client: test.fields.client, - url: test.fields.url, - auth: test.fields.auth, + client: test.fields.client, + url: test.fields.url, + auth: test.fields.auth, + rateLimiter: rateLimiter, } err := e.SendMetrics(context.Background(), test.args.rInput, test.args.dsInput, test.args.instInput, test.args.dpInput) if err == nil { @@ -297,15 +303,16 @@ } t.Run(test.name, func(t *testing.T) { - setEnv() + rateLimiter, _ := rateLimiter.NewMetricsRateLimiter(rateLimiter.RateLimiterSetting{RequestCount: 100}) prepareMetricsRequestCache() e := &LMMetricIngest{ - client: test.fields.client, - url: test.fields.url, - auth: test.fields.auth, - batch: true, - interval: 2 * time.Second, + client: test.fields.client, + url: test.fields.url, + auth: test.fields.auth, + batch: true, + interval: 2 * time.Second, + rateLimiter: rateLimiter, } err := e.SendMetrics(context.Background(), test.args.rInput, test.args.dsInput, test.args.instInput, test.args.dpInput) if err != nil { @@ -513,9 +520,10 @@ } type fields struct { - client *http.Client - url string - auth model.AuthProvider + client *http.Client + url string + auth model.AuthProvider + rateLimiter *rateLimiter.MetricsRateLimiter } test := struct { @@ -538,12 +546,13 @@ } t.Run(test.name, func(t *testing.T) { - setEnv() + rateLimiter, _ := rateLimiter.NewMetricsRateLimiter(rateLimiter.RateLimiterSetting{RequestCount: 100}) e := &LMMetricIngest{ - client: test.fields.client, - url: test.fields.url, - auth: test.fields.auth, + client: test.fields.client, + url: test.fields.url, + auth: test.fields.auth, + rateLimiter: rateLimiter, } err := e.UpdateResourceProperties(test.args.resName, test.args.rId, test.args.resProp, test.args.patch) if err != nil { @@ -597,12 +606,13 @@ } t.Run(test.name, func(t *testing.T) { - setEnv() + rateLimiter, _ := rateLimiter.NewMetricsRateLimiter(rateLimiter.RateLimiterSetting{RequestCount: 100}) e := &LMMetricIngest{ - client: test.fields.client, - url: test.fields.url, - auth: test.fields.auth, + client: test.fields.client, + url: test.fields.url, + auth: test.fields.auth, + rateLimiter: rateLimiter, } err := e.UpdateResourceProperties(test.args.resName, test.args.rId, test.args.resProp, test.args.patch) if err == nil { @@ -657,12 +667,13 @@ } t.Run(test.name, func(t *testing.T) { - setEnv() + rateLimiter, _ := rateLimiter.NewMetricsRateLimiter(rateLimiter.RateLimiterSetting{RequestCount: 100}) e := &LMMetricIngest{ - client: test.fields.client, - url: test.fields.url, - auth: test.fields.auth, + client: test.fields.client, + url: test.fields.url, + auth: test.fields.auth, + rateLimiter: rateLimiter, } err := e.UpdateResourceProperties(test.args.resName, test.args.rId, test.args.resProp, test.args.patch) if err == nil { @@ -720,12 +731,13 @@ } t.Run(test.name, func(t *testing.T) { - setEnv() + rateLimiter, _ := rateLimiter.NewMetricsRateLimiter(rateLimiter.RateLimiterSetting{RequestCount: 100}) e := &LMMetricIngest{ - client: test.fields.client, - url: test.fields.url, - auth: test.fields.auth, + client: test.fields.client, + url: test.fields.url, + auth: test.fields.auth, + rateLimiter: rateLimiter, } err := e.UpdateInstanceProperties(test.args.rId, test.args.insProp, test.args.dsName, test.args.dsDisplayName, test.args.insName, test.args.patch) if err != nil { @@ -784,12 +796,14 @@ } t.Run(test.name, func(t *testing.T) { - setEnv() + rateLimiter, _ := rateLimiter.NewMetricsRateLimiter(rateLimiter.RateLimiterSetting{RequestCount: 100}) + e := &LMMetricIngest{ - client: test.fields.client, - url: test.fields.url, - auth: test.fields.auth, + client: test.fields.client, + url: test.fields.url, + auth: test.fields.auth, + rateLimiter: rateLimiter, } err := e.UpdateInstanceProperties(test.args.rId, test.args.insProp, test.args.dsName, test.args.dsDisplayName, test.args.insName, test.args.patch) if err == nil { @@ -849,12 +863,14 @@ } t.Run(test.name, func(t *testing.T) { - setEnv() + rateLimiter, _ := rateLimiter.NewMetricsRateLimiter(rateLimiter.RateLimiterSetting{RequestCount: 100}) + e := &LMMetricIngest{ - client: test.fields.client, - url: test.fields.url, - auth: test.fields.auth, + client: test.fields.client, + url: test.fields.url, + auth: test.fields.auth, + rateLimiter: rateLimiter, } err := e.UpdateInstanceProperties(test.args.rId, test.args.insProp, test.args.dsName, test.args.dsDisplayName, test.args.insName, test.args.patch) if err == nil {
diff --git a/api/metrics/options.go b/api/metrics/options.go index 96240e3..7fff42e 100644 --- a/api/metrics/options.go +++ b/api/metrics/options.go
@@ -40,3 +40,11 @@ return nil } } + +// WithRateLimit is used to limit the metric request count per minute +func WithRateLimit(requestCount int) Option { + return func(lmi *LMMetricIngest) error { + lmi.rateLimiterSetting.RequestCount = requestCount + return nil + } +}
diff --git a/example/logs/logsingestion.go b/example/logs/logsingestion.go index 517032f..9bff58f 100644 --- a/example/logs/logsingestion.go +++ b/example/logs/logsingestion.go
@@ -13,9 +13,9 @@ logstr2 := "This is 2nd log" logstr3 := "this is 3rd log" - var options []logs.Option - options = []logs.Option{ + options := []logs.Option{ logs.WithLogBatchingDisabled(), + logs.WithRateLimit(2), } lmLog, err := logs.NewLMLogIngest(context.Background(), options...) @@ -25,15 +25,26 @@ } fmt.Println("Sending log1....") - lmLog.SendLogs(context.Background(), logstr, map[string]string{"system.displayname": "example-cart-service"}, map[string]string{"testkey": "testvalue"}) + err = lmLog.SendLogs(context.Background(), logstr, map[string]string{"system.displayname": "example-cart-service"}, map[string]string{"testkey": "testvalue"}) + if err != nil { + fmt.Println("Error in sending log: ", err) + } time.Sleep(2 * time.Second) + fmt.Println("Sending log2....") - lmLog.SendLogs(context.Background(), logstr2, map[string]string{"system.displayname": "example-cart-service"}, map[string]string{"testkey": "testvalue"}) + err = lmLog.SendLogs(context.Background(), logstr2, map[string]string{"system.displayname": "example-cart-service"}, map[string]string{"testkey": "testvalue"}) + if err != nil { + fmt.Println("Error in sending log: ", err) + } time.Sleep(3 * time.Second) + fmt.Println("Sending log3....") - lmLog.SendLogs(context.Background(), logstr3, map[string]string{"system.displayname": "example-cart-service"}, map[string]string{"testkey": "testvalue"}) + err = lmLog.SendLogs(context.Background(), logstr3, map[string]string{"system.displayname": "example-cart-service"}, map[string]string{"testkey": "testvalue"}) + if err != nil { + fmt.Println("Error in sending log: ", err) + } time.Sleep(10 * time.Second) }
diff --git a/example/metrics/metricsingestion.go b/example/metrics/metricsingestion.go index 434dabd..be09a5d 100644 --- a/example/metrics/metricsingestion.go +++ b/example/metrics/metricsingestion.go
@@ -10,9 +10,9 @@ ) func main() { - var options []metrics.Option - options = []metrics.Option{ + options := []metrics.Option{ metrics.WithMetricBatchingInterval(3 * time.Second), + metrics.WithRateLimit(2), } lmMetric, err := metrics.NewLMMetricIngest(context.Background(), options...)
diff --git a/go.mod b/go.mod index 507a22d..87c8ad8b 100644 --- a/go.mod +++ b/go.mod
@@ -2,4 +2,13 @@ go 1.17 -require github.com/google/uuid v1.3.0 +require ( + github.com/google/uuid v1.3.0 + github.com/stretchr/testify v1.8.0 +) + +require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +)
diff --git a/go.sum b/go.sum index 3dfe1c9..fa222d5 100644 --- a/go.sum +++ b/go.sum
@@ -1,2 +1,17 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/internal/batching.go b/internal/batching.go deleted file mode 100644 index 965da72..0000000 --- a/internal/batching.go +++ /dev/null
@@ -1,72 +0,0 @@ -package internal - -import ( - "bytes" - "fmt" - "log" - "net/http" - "time" - - "github.com/logicmonitor/lm-data-sdk-go/model" - "github.com/logicmonitor/lm-data-sdk-go/utils" -) - -type DataPayload struct { - MetricBodyList []model.MetricPayload - MetricResourceCreateList []model.MetricPayload - LogBodyList []model.LogPayload - UpdatePropertiesBody model.UpdateProperties -} - -type LMIngest interface { - BatchInterval() time.Duration - URI() string - CreateRequestBody() DataPayload - ExportData(body DataPayload, uri, method string) error -} - -// CreateAndExportData creates and exports data (if batching is enabled) after batching interval expires -func CreateAndExportData(li LMIngest) { - ticker := time.NewTicker(li.BatchInterval()) - for range ticker.C { - body := li.CreateRequestBody() - err := li.ExportData(body, li.URI(), http.MethodPost) - if err != nil { - log.Println(err) - } - } -} - -// MakeRequest compresses the payload and exports it to LM Platform -func MakeRequest(client *http.Client, url string, body []byte, uri, method, token string, gzip bool) (*utils.Response, error) { - if token == "" { - return nil, fmt.Errorf("Missing authentication token.") - } - payloadBody := body - var err error - if gzip { - payloadBody, err = utils.Gzip(payloadBody) - if err != nil { - return nil, fmt.Errorf("error while compressing body: %v", err) - } - } - reqBody := bytes.NewBuffer(payloadBody) - fullURL := url + uri - - req, err := http.NewRequest(method, fullURL, reqBody) - if err != nil { - return nil, err - } - req.Header.Add("Content-Type", "application/json") - req.Header.Add("Authorization", token) - req.Header.Add("User-Agent", utils.BuildUserAgent()) - if gzip { - req.Header.Add("Content-Encoding", "gzip") - } - - httpResp, err := client.Do(req) - if err != nil { - return nil, err - } - return utils.ConvertHTTPToIngestResponse(httpResp) -}
diff --git a/internal/client/client.go b/internal/client/client.go new file mode 100644 index 0000000..fd1a2a1 --- /dev/null +++ b/internal/client/client.go
@@ -0,0 +1,62 @@ +package client + +import ( + "bytes" + "context" + "fmt" + "net/http" + + rateLimiter "github.com/logicmonitor/lm-data-sdk-go/pkg/ratelimiter" + "github.com/logicmonitor/lm-data-sdk-go/utils" +) + +type RequestConfig struct { + Client *http.Client + RateLimiter rateLimiter.RateLimiter + Url string + Body []byte + Uri string + Method string + Token string + Gzip bool +} + +// MakeRequest compresses the payload and exports it to LM Platform +func MakeRequest(_ context.Context, reqConfig RequestConfig) (*utils.Response, error) { + if reqConfig.Token == "" { + return nil, fmt.Errorf("missing authentication token") + } + payloadBody := reqConfig.Body + var err error + if reqConfig.Gzip { + payloadBody, err = utils.Gzip(payloadBody) + if err != nil { + return nil, fmt.Errorf("error while compressing body: %v", err) + } + } + reqBody := bytes.NewBuffer(payloadBody) + fullURL := reqConfig.Url + reqConfig.Uri + + req, err := http.NewRequest(reqConfig.Method, fullURL, reqBody) + if err != nil { + return nil, err + } + + req.Header.Add("Content-Type", "application/json") + req.Header.Add("Authorization", reqConfig.Token) + req.Header.Add("User-Agent", utils.BuildUserAgent()) + + if reqConfig.Gzip { + req.Header.Add("Content-Encoding", "gzip") + } + + if acquire, err := reqConfig.RateLimiter.Acquire(); !acquire { + return nil, err + } + + httpResp, err := reqConfig.Client.Do(req) + if err != nil { + return nil, err + } + return utils.ConvertHTTPToIngestResponse(httpResp) +}
diff --git a/model/ingest.go b/model/ingest.go new file mode 100644 index 0000000..bd63d31 --- /dev/null +++ b/model/ingest.go
@@ -0,0 +1,17 @@ +package model + +import "time" + +type DataPayload struct { + MetricBodyList []MetricPayload + MetricResourceCreateList []MetricPayload + LogBodyList []LogPayload + UpdatePropertiesBody UpdateProperties +} + +type LMIngest interface { + BatchInterval() time.Duration + URI() string + CreateRequestBody() DataPayload + ExportData(body DataPayload, uri, method string) error +}
diff --git a/pkg/batch/batch.go b/pkg/batch/batch.go new file mode 100644 index 0000000..bd3718a --- /dev/null +++ b/pkg/batch/batch.go
@@ -0,0 +1,21 @@ +package batch + +import ( + "log" + "net/http" + "time" + + "github.com/logicmonitor/lm-data-sdk-go/model" +) + +// CreateAndExportData creates and exports data (if batching is enabled) after batching interval expires +func CreateAndExportData(li model.LMIngest) { + ticker := time.NewTicker(li.BatchInterval()) + for range ticker.C { + body := li.CreateRequestBody() + err := li.ExportData(body, li.URI(), http.MethodPost) + if err != nil { + log.Println(err) + } + } +}
diff --git a/pkg/ratelimiter/logs.go b/pkg/ratelimiter/logs.go new file mode 100644 index 0000000..2a52bd8 --- /dev/null +++ b/pkg/ratelimiter/logs.go
@@ -0,0 +1,77 @@ +package ratelimiter + +import ( + "context" + "fmt" + "sync/atomic" + "time" +) + +const ( + defaultRateLimitLogs = 100 +) + +// LogRateLimiter represents the RateLimiter config for logs +type LogRateLimiter struct { + logRequestCount uint64 + maxCount uint64 + ticker *time.Ticker + shutdownCh chan struct{} +} + +// NewLogRateLimiter creates RateLimiter implementation for logs using RateLimiterSetting +func NewLogRateLimiter(setting RateLimiterSetting) (*LogRateLimiter, error) { + if setting.RequestCount == 0 { + setting.RequestCount = defaultRateLimitLogs + } + return &LogRateLimiter{ + logRequestCount: 0, + maxCount: uint64(setting.RequestCount), + ticker: time.NewTicker(time.Duration(1 * time.Minute)), + shutdownCh: make(chan struct{}, 1), + }, nil +} + +// IncRequestCount increaments the request count associated with logs by 1 +func (rateLimiter *LogRateLimiter) IncRequestCount() { + atomic.AddUint64(&rateLimiter.logRequestCount, 1) +} + +// ResetRequestCount resets the request count associated with logs to 0 +func (rateLimiter *LogRateLimiter) ResetRequestCount() { + atomic.StoreUint64(&rateLimiter.logRequestCount, 0) +} + +// Acquire checks if the requests count for logs is reached to maximum allocated quota per minute. +func (rateLimiter *LogRateLimiter) Acquire() (bool, error) { + for { + select { + case <-rateLimiter.shutdownCh: + return false, fmt.Errorf("shutdown is called") + default: + if rateLimiter.logRequestCount < rateLimiter.maxCount { + rateLimiter.IncRequestCount() + return true, nil + } + return false, fmt.Errorf("request quota of (%d) requests per min for the logs is exhausted for the interval", rateLimiter.maxCount) + } + } +} + +// Run starts the timer for reseting the logs request counter +func (rateLimiter *LogRateLimiter) Run(ctx context.Context) { + for { + select { + case <-ctx.Done(): + rateLimiter.Shutdown(ctx) + return + case <-rateLimiter.ticker.C: + rateLimiter.ResetRequestCount() + } + } +} + +// Shutdown triggers the shutdown of the LogRateLimiter +func (rateLimiter *LogRateLimiter) Shutdown(_ context.Context) { + rateLimiter.shutdownCh <- struct{}{} +}
diff --git a/pkg/ratelimiter/logs_test.go b/pkg/ratelimiter/logs_test.go new file mode 100644 index 0000000..e5def8c --- /dev/null +++ b/pkg/ratelimiter/logs_test.go
@@ -0,0 +1,95 @@ +package ratelimiter + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestNewLogRateLimiter(t *testing.T) { + setting := RateLimiterSetting{ + RequestCount: 100, + } + logRateLimiter, err := NewLogRateLimiter(setting) + assert.NoError(t, err) + assert.Equal(t, uint64(setting.RequestCount), logRateLimiter.maxCount) + assert.Equal(t, uint64(0), logRateLimiter.logRequestCount) +} + +func TestNewLogRateLimiterDefaultRequestCount(t *testing.T) { + setting := RateLimiterSetting{} + logRateLimiter, err := NewLogRateLimiter(setting) + assert.NoError(t, err) + assert.Equal(t, uint64(defaultRateLimitLogs), logRateLimiter.maxCount) + assert.Equal(t, uint64(0), logRateLimiter.logRequestCount) +} + +func TestIncRequestCount_Logs(t *testing.T) { + setting := RateLimiterSetting{ + RequestCount: 100, + } + logRateLimiter, err := NewLogRateLimiter(setting) + assert.NoError(t, err) + logRequestCountBeforeInc := logRateLimiter.logRequestCount + logRateLimiter.IncRequestCount() + logRequestCountAfterInc := logRateLimiter.logRequestCount + assert.Equal(t, logRequestCountBeforeInc+1, logRequestCountAfterInc) +} + +func TestResetRequestCount_Logs(t *testing.T) { + setting := RateLimiterSetting{ + RequestCount: 100, + } + logRateLimiter, err := NewLogRateLimiter(setting) + assert.NoError(t, err) + logRateLimiter.ResetRequestCount() + assert.Equal(t, uint64(0), logRateLimiter.logRequestCount) +} + +func TestAcquire_Logs(t *testing.T) { + setting := RateLimiterSetting{ + RequestCount: 1, + } + logRateLimiter, err := NewLogRateLimiter(setting) + assert.NoError(t, err) + + // Should allow 1 request + ok, err := logRateLimiter.Acquire() + assert.Equal(t, true, ok) + assert.NoError(t, err) + + // Should drop the second request as quota is exhausted + ok, err = logRateLimiter.Acquire() + assert.Equal(t, false, ok) + assert.Error(t, err) +} + +func TestAcquireAfterShutdown_Logs(t *testing.T) { + setting := RateLimiterSetting{ + RequestCount: 100, + } + logRateLimiter, err := NewLogRateLimiter(setting) + assert.NoError(t, err) + logRateLimiter.Shutdown(context.Background()) + ok, err := logRateLimiter.Acquire() + assert.Equal(t, false, ok) + assert.Error(t, err) +} + +func TestRun_Logs(t *testing.T) { + setting := RateLimiterSetting{ + RequestCount: 100, + } + logRateLimiter, err := NewLogRateLimiter(setting) + assert.NoError(t, err) + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) + defer cancel() + logRateLimiter.ticker.Reset(3 * time.Second) + go logRateLimiter.Run(ctx) + logRateLimiter.IncRequestCount() + time.Sleep(5 * time.Second) + assert.Equal(t, uint64(0), logRateLimiter.logRequestCount) + logRateLimiter.Shutdown(ctx) +}
diff --git a/pkg/ratelimiter/metrics.go b/pkg/ratelimiter/metrics.go new file mode 100644 index 0000000..dd303f9 --- /dev/null +++ b/pkg/ratelimiter/metrics.go
@@ -0,0 +1,77 @@ +package ratelimiter + +import ( + "context" + "fmt" + "sync/atomic" + "time" +) + +const ( + defaultRateLimitMetrics = 100 +) + +// MetricsRateLimiter represents the RateLimiter config for metrics +type MetricsRateLimiter struct { + metricRequestCount uint64 + maxCount uint64 + ticker *time.Ticker + shutdownCh chan struct{} +} + +// NewMetricsRateLimiter creates RateLimiter implementation for metrics using RateLimiterSetting +func NewMetricsRateLimiter(setting RateLimiterSetting) (*MetricsRateLimiter, error) { + if setting.RequestCount == 0 { + setting.RequestCount = defaultRateLimitMetrics + } + return &MetricsRateLimiter{ + metricRequestCount: 0, + maxCount: uint64(setting.RequestCount), + ticker: time.NewTicker(time.Duration(1 * time.Minute)), + shutdownCh: make(chan struct{}, 1), + }, nil +} + +// IncRequestCount increaments the request count associated with metrics by 1 +func (rateLimiter *MetricsRateLimiter) IncRequestCount() { + atomic.AddUint64(&rateLimiter.metricRequestCount, 1) +} + +// ResetRequestCount resets the request count associated with metrics to 0 +func (rateLimiter *MetricsRateLimiter) ResetRequestCount() { + atomic.StoreUint64(&rateLimiter.metricRequestCount, 0) +} + +// Acquire checks if the requests count for metrics is reached to maximum allocated quota per minute. +func (rateLimiter *MetricsRateLimiter) Acquire() (bool, error) { + for { + select { + case <-rateLimiter.shutdownCh: + return false, fmt.Errorf("shutdown is called") + default: + if rateLimiter.metricRequestCount < rateLimiter.maxCount { + rateLimiter.IncRequestCount() + return true, nil + } + return false, fmt.Errorf("request quota of (%d) requests per min for the metrics is exhausted for the interval", rateLimiter.maxCount) + } + } +} + +// Run starts the timer for reseting the metrics request counter +func (rateLimiter *MetricsRateLimiter) Run(ctx context.Context) { + for { + select { + case <-ctx.Done(): + rateLimiter.Shutdown(ctx) + return + case <-rateLimiter.ticker.C: + rateLimiter.ResetRequestCount() + } + } +} + +// Shutdown triggers the shutdown of the MetricsRateLimiter +func (rateLimiter *MetricsRateLimiter) Shutdown(_ context.Context) { + rateLimiter.shutdownCh <- struct{}{} +}
diff --git a/pkg/ratelimiter/metrics_test.go b/pkg/ratelimiter/metrics_test.go new file mode 100644 index 0000000..05d483d --- /dev/null +++ b/pkg/ratelimiter/metrics_test.go
@@ -0,0 +1,95 @@ +package ratelimiter + +import ( + "context" + "testing" + "time" + + "github.com/stretchr/testify/assert" +) + +func TestNewMetricsRateLimiter(t *testing.T) { + setting := RateLimiterSetting{ + RequestCount: 100, + } + metricsRateLimiter, err := NewMetricsRateLimiter(setting) + assert.NoError(t, err) + assert.Equal(t, uint64(setting.RequestCount), metricsRateLimiter.maxCount) + assert.Equal(t, uint64(0), metricsRateLimiter.metricRequestCount) +} + +func TestNewMetricsRateLimiterDefaultRequestCount(t *testing.T) { + setting := RateLimiterSetting{} + metricsRateLimiter, err := NewMetricsRateLimiter(setting) + assert.NoError(t, err) + assert.Equal(t, uint64(defaultRateLimitLogs), metricsRateLimiter.maxCount) + assert.Equal(t, uint64(0), metricsRateLimiter.metricRequestCount) +} + +func TestIncRequestCount_Metrics(t *testing.T) { + setting := RateLimiterSetting{ + RequestCount: 100, + } + metricsRateLimiter, err := NewMetricsRateLimiter(setting) + assert.NoError(t, err) + metricsRequestCountBeforeInc := metricsRateLimiter.metricRequestCount + metricsRateLimiter.IncRequestCount() + metricsRequestCountAfterInc := metricsRateLimiter.metricRequestCount + assert.Equal(t, metricsRequestCountBeforeInc+1, metricsRequestCountAfterInc) +} + +func TestResetRequestCount_Metrics(t *testing.T) { + setting := RateLimiterSetting{ + RequestCount: 100, + } + metricsRateLimiter, err := NewMetricsRateLimiter(setting) + assert.NoError(t, err) + metricsRateLimiter.ResetRequestCount() + assert.Equal(t, uint64(0), metricsRateLimiter.metricRequestCount) +} + +func TestAcquire_Metrics(t *testing.T) { + setting := RateLimiterSetting{ + RequestCount: 1, + } + metricsRateLimiter, err := NewMetricsRateLimiter(setting) + assert.NoError(t, err) + + // Should allow 1 request + ok, err := metricsRateLimiter.Acquire() + assert.Equal(t, true, ok) + assert.NoError(t, err) + + // Should drop the second request as quota is exhausted + ok, err = metricsRateLimiter.Acquire() + assert.Equal(t, false, ok) + assert.Error(t, err) +} + +func TestAcquireAfterShutdown_Metrics(t *testing.T) { + setting := RateLimiterSetting{ + RequestCount: 100, + } + metricsRateLimiter, err := NewMetricsRateLimiter(setting) + assert.NoError(t, err) + metricsRateLimiter.Shutdown(context.Background()) + ok, err := metricsRateLimiter.Acquire() + assert.Equal(t, false, ok) + assert.Error(t, err) +} + +func TestRun_Metrics(t *testing.T) { + setting := RateLimiterSetting{ + RequestCount: 100, + } + metricsRateLimiter, err := NewMetricsRateLimiter(setting) + assert.NoError(t, err) + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) + defer cancel() + metricsRateLimiter.ticker.Reset(3 * time.Second) + go metricsRateLimiter.Run(ctx) + metricsRateLimiter.IncRequestCount() + time.Sleep(5 * time.Second) + assert.Equal(t, uint64(0), metricsRateLimiter.metricRequestCount) + metricsRateLimiter.Shutdown(ctx) +}
diff --git a/pkg/ratelimiter/ratelimiter.go b/pkg/ratelimiter/ratelimiter.go new file mode 100644 index 0000000..35e2769 --- /dev/null +++ b/pkg/ratelimiter/ratelimiter.go
@@ -0,0 +1,19 @@ +package ratelimiter + +import ( + "context" +) + +// RateLimiter represents the RateLimiter operations +type RateLimiter interface { + IncRequestCount() + Acquire() (bool, error) + ResetRequestCount() + Run(context.Context) + Shutdown(context.Context) +} + +// RateLimiterSetting represents the RateLimiter config +type RateLimiterSetting struct { + RequestCount int +}