github.com/kyma-incubator/compass/components/director@v0.0.0-20230623144113-d764f56ff805/internal/domain/tenant/fetcher_on_demand.go (about) 1 package tenant 2 3 import ( 4 "fmt" 5 "net/http" 6 7 "github.com/pkg/errors" 8 ) 9 10 // FetchOnDemandAPIConfig is the configuration needed for tenant on demand fetch API 11 type FetchOnDemandAPIConfig struct { 12 TenantOnDemandURL string `envconfig:"optional,APP_FETCH_TENANT_URL"` 13 IsDisabled bool `envconfig:"default=false,APP_DISABLE_TENANT_ON_DEMAND_MODE"` 14 } 15 16 // Fetcher calls an API which fetches details for the given tenant from an external tenancy service, stores the tenant in the Compass DB and returns 200 OK if the tenant was successfully created. 17 //go:generate mockery --name=Fetcher --output=automock --outpkg=automock --case=underscore --disable-version-string 18 type Fetcher interface { 19 FetchOnDemand(tenant, parentTenant string) error 20 } 21 22 // Client is responsible for making HTTP requests. 23 //go:generate mockery --name=Client --output=automock --outpkg=automock --case=underscore --disable-version-string 24 type Client interface { 25 Do(req *http.Request) (*http.Response, error) 26 } 27 28 type fetchOnDemandService struct { 29 client Client 30 tenantFetcherURL string 31 } 32 33 type noopOnDemandService struct{} 34 35 // NewFetchOnDemandService returns object responsible for fetching tenants 36 func NewFetchOnDemandService(client Client, config FetchOnDemandAPIConfig) Fetcher { 37 if config.IsDisabled { 38 return &noopOnDemandService{} 39 } 40 return &fetchOnDemandService{ 41 client: client, 42 tenantFetcherURL: config.TenantOnDemandURL, 43 } 44 } 45 46 // FetchOnDemand calls an API which fetches details for the given tenant from an external tenancy service, stores the tenant in the Compass DB and returns 200 OK if the tenant was successfully created. 47 func (s *fetchOnDemandService) FetchOnDemand(tenant, parentTenant string) error { 48 req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/%s/%s", s.tenantFetcherURL, parentTenant, tenant), nil) 49 if err != nil { 50 return err 51 } 52 resp, err := s.client.Do(req) 53 if err != nil { 54 return errors.Wrapf(err, "while calling tenant-on-demand API") 55 } 56 if resp.StatusCode != http.StatusOK { 57 return fmt.Errorf("received status code %d when trying to fetch tenant with ID %s", resp.StatusCode, tenant) 58 } 59 return nil 60 } 61 62 func (s *noopOnDemandService) FetchOnDemand(tenant, parentTenant string) error { 63 return nil 64 }