github.com/esnet/gdg@v0.6.1-0.20240412190737-6b6eba9c14d8/internal/api/orgs.go (about) 1 package api 2 3 import ( 4 "context" 5 "errors" 6 "github.com/avast/retry-go" 7 "github.com/esnet/gdg/internal/config" 8 "github.com/grafana/grafana-openapi-client-go/models" 9 "log/slog" 10 "net/http" 11 "time" 12 ) 13 14 // GetConfiguredOrgId needed to call grafana API in order to configure the Grafana API correctly. Invoking 15 // this endpoint manually to avoid a circular dependency. 16 func (extended *ExtendedApi) GetConfiguredOrgId(orgName string) (int64, error) { 17 var result []*models.UserOrgDTO 18 fetch := func() error { 19 return extended.getRequestBuilder(). 20 Path("api/user/orgs"). 21 ToJSON(&result). 22 Method(http.MethodGet). 23 Fetch(context.Background()) 24 } 25 26 /* There's something goofy here. This seems to fail sporadically in grafana if we keep swapping orgs too fast. 27 This is a safety check that should ideally never be triggered, but if the URL fails, then we retry a few times 28 before finally giving up. 29 */ 30 delay := time.Second * 5 31 var count uint = 5 32 //Giving user configured value preference over defaults 33 if config.Config().GetGDGConfig().GetAppGlobals().RetryCount != 0 { 34 count = uint(config.Config().GetGDGConfig().GetAppGlobals().RetryCount) 35 } 36 if config.Config().GetGDGConfig().GetAppGlobals().GetRetryTimeout() != time.Millisecond*100 { 37 delay = config.Config().GetGDGConfig().GetAppGlobals().GetRetryTimeout() 38 } 39 err := retry.Do(fetch, 40 retry.Attempts(count), 41 retry.Delay(delay), 42 retry.OnRetry(func(n uint, err error) { 43 slog.Info("Retrying request after error", 44 slog.String("orgName", orgName), 45 slog.Any("err", err)) 46 })) 47 48 if err != nil { 49 return 0, err 50 } 51 for _, entity := range result { 52 if entity.Name == orgName { 53 return entity.OrgID, nil 54 } 55 } 56 return 0, errors.New("org not found") 57 }