common

package
v0.0.0-...-61eae9e Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 27, 2024 License: Apache-2.0, Apache-2.0, UPL-1.0 Imports: 39 Imported by: 0

Documentation

Overview

Package common provides supporting functions and structs used by service packages

Index

Constants

View Source
const (
	// CircuitBreakerDefaultFailureRateThreshold is the requests failure rate which calculates in at most 120 seconds, once reaches to this rate, the circuit breaker state changes from closed to open
	CircuitBreakerDefaultFailureRateThreshold float64 = 0.80
	// CircuitBreakerDefaultClosedWindow is the default value of closeStateWindow, which is the cyclic period of the closed state
	CircuitBreakerDefaultClosedWindow time.Duration = 120 * time.Second
	// CircuitBreakerDefaultResetTimeout is the default value of openStateWindow, which is the wait time before setting the breaker to halfOpen state from open state
	CircuitBreakerDefaultResetTimeout time.Duration = 30 * time.Second
	// CircuitBreakerDefaultVolumeThreshold is the default value of minimumRequests in closed status
	CircuitBreakerDefaultVolumeThreshold uint32 = 10
	// DefaultCircuitBreakerName is the name of the circuit breaker
	DefaultCircuitBreakerName string = "DefaultCircuitBreaker"
	// DefaultCircuitBreakerServiceName is the servicename of the circuit breaker
	DefaultCircuitBreakerServiceName string = ""
	// DefaultCircuitBreakerHistoryCount is the default count of failed response history in circuit breaker
	DefaultCircuitBreakerHistoryCount int = 5
)
View Source
const (

	//EndpointTemplateForRegionWithDot Environment Variable
	EndpointTemplateForRegionWithDot = "https://{endpoint_service_name}.{region}"

	// OciRealmSpecificServiceEndpointTemplateEnabledEnvVar is the environment variable name to enable the realm specific service endpoint template.
	OciRealmSpecificServiceEndpointTemplateEnabledEnvVar = "OCI_REALM_SPECIFIC_SERVICE_ENDPOINT_TEMPLATE_ENABLED"
)
View Source
const (
	// DefaultHostURLTemplate The default url template for service hosts
	DefaultHostURLTemplate = "%s.%s.oraclecloud.com"
)
View Source
const InvalidResponseErrorMessage = "invalid response struct given to NewSSEReader"
View Source
const OciAllowOnlyDeveloperToolConfigurationRegionsEnvVar = "OCI_ALLOW_ONLY_DEVELOPER_TOOL_CONFIGURATION_REGIONS"

OciAllowOnlyDeveloperToolConfigurationRegionsEnvVar is the environment variable name for the OCI Allow only Dev Tool Config Regions

View Source
const OciDeveloperToolConfigurationFilePathEnvVar = "OCI_DEVELOPER_TOOL_CONFIGURATION_FILE_PATH"

OciDeveloperToolConfigurationFilePathEnvVar is the environment variable name for the OCI Developer Tool Config File Path

View Source
const (
	// OciGoSdkEcConfigEnvVarName contains the name of the environment variable that can be used to configure the eventual consistency (EC) communication mode.
	// Allowed values for environment variable:
	// 1. OCI_GO_SDK_EC_CONFIG = "file,/path/to/shared/timestamp/file"
	// 2. OCI_GO_SDK_EC_CONFIG = "inprocess"
	// 3. absent -- same as OCI_GO_SDK_EC_CONFIG = "inprocess"
	OciGoSdkEcConfigEnvVarName string = "OCI_GO_SDK_EC_CONFIG"
)
View Source
const (
	// UnlimitedNumAttemptsValue is the value for indicating unlimited attempts for reaching success
	UnlimitedNumAttemptsValue = uint(0)
)
View Source
const (
	//UsingExpectHeaderEnvVar is the key to determine whether expect 100-continue is enabled or not
	UsingExpectHeaderEnvVar = "OCI_GOSDK_USING_EXPECT_HEADER"
)

Variables

View Source
var DeadlineExceededByBackoff error = deadlineExceededByBackoffError{}

DeadlineExceededByBackoff is the error returned by Call() when GetNextDuration() returns a time.Duration that would force the user to wait past the request deadline before re-issuing a request. This enables us to exit early, since we cannot succeed based on the configured retry policy.

View Source
var EcContext = newEcContext()

EcContext contains the information about the end of the eventually consistent window for this process.

View Source
var OciDeveloperToolConfigurationProvider string

OciDeveloperToolConfigurationProvider is the provider name for the OCI Developer Tool Configuration file

View Source
var OciGlobalRefreshIntervalForCustomCerts int = -1

OciGlobalRefreshIntervalForCustomCerts is the global policy for overriding the refresh interval in minutes. This variable has a higher precedence than the env variable OCI_DEFAULT_REFRESH_INTERVAL_FOR_CUSTOM_CERTS and the defaultRefreshIntervalForCustomCerts values. If the value is negative, then it is assumed that this property is not configured if the value is Zero, then the refresh of custom certs will be disabled

View Source
var OciRealmSpecificServiceEndpointTemplateEnabled *bool = nil

OciRealmSpecificServiceEndpointTemplateEnabled is the flag to enable the realm specific service endpoint template. This one has higher priority than the environment variable.

View Source
var OciSdkEnabledServicesMap map[string]bool

OciSdkEnabledServicesMap is a list of services that are enabled, default is an empty list which means all services are enabled

Functions

func AddRegionSchemaForPlc

func AddRegionSchemaForPlc(regionSchema map[string]string)

AddRegionSchemaForPlc add region schema to region map

func AddServiceToEnabledServicesMap

func AddServiceToEnabledServicesMap(serviceName string)

AddServiceToEnabledServicesMap adds the service to the enabledServiceMap The service name will auto transit to lower case and remove all the non-word characters.

func Bool

func Bool(value bool) *bool

Bool returns a pointer to the provided bool

func CertPoolFrom

func CertPoolFrom(caBundleFile string) (*x509.CertPool, error)

CertPoolFrom creates a new x509.CertPool from a given file.

func CheckForEnabledServices

func CheckForEnabledServices(serviceName string) bool

CheckForEnabledServices checks if the service is enabled in the enabledServiceMap. It will first check if the map is initialized, if not, it will initialize the map. If the map is empty, it means all the services are enabled. If the map is not empty, it means only the services in the map and value is true are enabled.

func CloneHTTPDefaultTransport

func CloneHTTPDefaultTransport() *http.Transport

CloneHTTPDefaultTransport returns a clone of http.DefaultTransport.

func CloseBodyIfValid

func CloseBodyIfValid(httpResponse *http.Response)

CloseBodyIfValid closes the body of an http response if the response and the body are valid

func CloseLogFile

func CloseLogFile() error

CloseLogFile close the logging file and return error

func ConfigCircuitBreakerFromEnvVar

func ConfigCircuitBreakerFromEnvVar(baseClient *BaseClient)

ConfigCircuitBreakerFromEnvVar is used for checking the circuit breaker environment variable setting, default value is nil

func ConfigCircuitBreakerFromGlobalVar

func ConfigCircuitBreakerFromGlobalVar(baseClient *BaseClient)

ConfigCircuitBreakerFromGlobalVar is used for checking if global circuitBreakerSetting is configured, the priority is higher than cb env var

func Debug

func Debug(v ...interface{})

Debug logs v if debug mode is set

func Debugf

func Debugf(format string, v ...interface{})

Debugf logs v with the provided format if debug mode is set

func Debugln

func Debugln(v ...interface{})

Debugln logs v appending a new line if debug mode is set

func DefaultBodyHeaders

func DefaultBodyHeaders() []string

DefaultBodyHeaders list of default body headers that is used in signing

func DefaultGenericHeaders

func DefaultGenericHeaders() []string

DefaultGenericHeaders list of default generic headers that is used in signing

func DefaultShouldRetryOperation

func DefaultShouldRetryOperation(r OCIOperationResponse) bool

DefaultShouldRetryOperation is the function that should be used for RetryPolicy.ShouldRetryOperation when not taking eventual consistency into account.

func DefaultTransport

func DefaultTransport(tlsClientConfig *tls.Config) (*http.Transport, error)

DefaultTransport creates a clone of http.DefaultTransport and applies the tlsClientConfig on top of it. The result is never nil, to prevent panics in client code. Never returns any errors, but needs to return an error to adhere to TransportTemplate interface.

func EnableInstanceMetadataServiceLookup

func EnableInstanceMetadataServiceLookup()

EnableInstanceMetadataServiceLookup provides the interface to lookup IMDS region info

func EventuallyConsistentShouldRetryOperation

func EventuallyConsistentShouldRetryOperation(r OCIOperationResponse) bool

EventuallyConsistentShouldRetryOperation is the function that should be used for RetryPolicy.ShouldRetryOperation when taking eventual consistency into account

func Float32

func Float32(value float32) *float32

Float32 returns a pointer to the provided float32

func Float64

func Float64(value float64) *float64

Float64 returns a pointer to the provided float64

func GetBackoffWithoutJitter

func GetBackoffWithoutJitter(policy RetryPolicy, attempt uint) time.Duration

GetBackoffWithoutJitter calculates the backoff without jitter for the attempt, given the retry policy.

func GetBodyHash

func GetBodyHash(request *http.Request) (hashString string, err error)

GetBodyHash creates a base64 string from the hash of body the request

func GetEventuallyConsistentBackoffWithoutJitter

func GetEventuallyConsistentBackoffWithoutJitter(policy RetryPolicy, attempt uint, backoffScalingFactor float64) time.Duration

GetEventuallyConsistentBackoffWithoutJitter calculates the backoff without jitter for the attempt, given the retry policy and dealing with eventually consistent effects. The result is then multiplied by backoffScalingFactor.

func GetMaximumCumulativeBackoffWithoutJitter

func GetMaximumCumulativeBackoffWithoutJitter(policy RetryPolicy) time.Duration

GetMaximumCumulativeBackoffWithoutJitter calculates the maximum backoff without jitter, according to the retry policy, if every retry attempt is made.

func GetMaximumCumulativeEventuallyConsistentBackoffWithoutJitter

func GetMaximumCumulativeEventuallyConsistentBackoffWithoutJitter(policy RetryPolicy) time.Duration

GetMaximumCumulativeEventuallyConsistentBackoffWithoutJitter calculates the maximum backoff without jitter, according to the retry policy and taking eventually consistent effects into account, if every retry attempt is made.

func HTTPRequestMarshaller

func HTTPRequestMarshaller(requestStruct interface{}, httpRequest *http.Request) (err error)

HTTPRequestMarshaller marshals a structure to an http request using tag values in the struct The marshaller tag should like the following

type A struct {
		 ANumber string `contributesTo="query" name="number"`
		 TheBody `contributesTo="body"`
}

where the contributesTo tag can be: header, path, query, body and the 'name' tag is the name of the value used in the http request(not applicable for path) If path is specified as part of the tag, the values are appened to the url path in the order they appear in the structure The current implementation only supports primitive types, except for the body tag, which needs a struct type. The body of a request will be marshaled using the tags of the structure

func IfDebug

func IfDebug(fn func())

IfDebug executes closure if debug is enabled

func IfInfo

func IfInfo(fn func())

IfInfo executes closure if info is enabled

func InitializeEcContextFile

func InitializeEcContextFile(timestampFileName string)

InitializeEcContextFile initializes the EcContext variable to be kept in a timestamp file, protected by a lock file. timestampFileName should be set to a file accessible by all processes that need to share information about eventual consistency. A sensible choice are files inside the temp directory, as returned by os.TempDir() The lock file will use the same name, with the suffix ".lock" added.

func InitializeEcContextFromEnvVar

func InitializeEcContextFromEnvVar()

InitializeEcContextFromEnvVar initializes the EcContext variable as configured in the OCI_GO_SDK_EC_CONFIG environment variable.

func InitializeEcContextInProcess

func InitializeEcContextInProcess()

InitializeEcContextInProcess initializes the EcContext variable to be in-process only.

func Int

func Int(value int) *int

Int returns a pointer to the provided int

func Int64

func Int64(value int64) *int64

Int64 returns a pointer to the provided int64

func IsCircuitBreakerError

func IsCircuitBreakerError(err error) bool

IsCircuitBreakerError validates if an error's text is Open state ErrOpenState or HalfOpen state ErrTooManyRequests

func IsConfigurationProviderValid

func IsConfigurationProviderValid(conf ConfigurationProvider) (ok bool, err error)

IsConfigurationProviderValid Tests all parts of the configuration provider do not return an error, this method will not check AuthType(), since authType() is not required to be there.

func IsEnvVarFalse

func IsEnvVarFalse(envVarKey string) bool

IsEnvVarFalse is used for checking if an environment variable is explicitly set to false, otherwise would set it true by default

func IsEnvVarTrue

func IsEnvVarTrue(envVarKey string) bool

IsEnvVarTrue is used for checking if an environment variable is explicitly set to true, otherwise would set it true by default

func IsErrorAffectedByEventualConsistency

func IsErrorAffectedByEventualConsistency(Error error) bool

IsErrorAffectedByEventualConsistency returns true if the error is affected by eventual consistency.

func IsErrorRetryableByDefault

func IsErrorRetryableByDefault(err error) bool

IsErrorRetryableByDefault returns true if the error is retryable by OCI default retry policy

func IsNetworkError

func IsNetworkError(err error) bool

IsNetworkError validates if an error is a net.Error and check if it's temporary or timeout

func Logf

func Logf(format string, v ...interface{})

Logf logs v with the provided format

func Logln

func Logln(v ...interface{})

Logln logs v appending a new line at the end Deprecated

func MakeDefaultHTTPRequest

func MakeDefaultHTTPRequest(method, path string) (httpRequest http.Request)

MakeDefaultHTTPRequest creates the basic http request with the necessary headers set

func MakeDefaultHTTPRequestWithTaggedStruct

func MakeDefaultHTTPRequestWithTaggedStruct(method, path string, requestStruct interface{}) (httpRequest http.Request, err error)

MakeDefaultHTTPRequestWithTaggedStruct creates an http request from an struct with tagged fields, see HTTPRequestMarshaller for more information

func MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders

func MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders(method, path string, requestStruct interface{}, extraHeaders map[string]string) (httpRequest http.Request, err error)

MakeDefaultHTTPRequestWithTaggedStructAndExtraHeaders creates an http request from an struct with tagged fields, see HTTPRequestMarshaller for more information

func NewGoCircuitBreaker

func NewGoCircuitBreaker(st gobreaker.Settings) *gobreaker.CircuitBreaker

NewGoCircuitBreaker is a function to initialize a CircuitBreaker object with the specified configuration Add the interface, to allow the user directly use the 3P gobreaker.Setting's params.

func PointerString

func PointerString(datastruct interface{}) (representation string)

PointerString prints the values of pointers in a struct Producing a human friendly string for an struct with pointers. useful when debugging the values of a struct

func PostProcessServiceError

func PostProcessServiceError(err error, service string, method string, apiReferenceLink string) error

PostProcessServiceError process the service error after an error is raised and complete it with extra information

func PrivateKeyFromBytes

func PrivateKeyFromBytes(pemData []byte, password *string) (key *rsa.PrivateKey, e error)

PrivateKeyFromBytes is a helper function that will produce a RSA private key from bytes. This function is deprecated in favour of PrivateKeyFromBytesWithPassword Deprecated

func PrivateKeyFromBytesWithPassword

func PrivateKeyFromBytesWithPassword(pemData, password []byte) (key *rsa.PrivateKey, e error)

PrivateKeyFromBytesWithPassword is a helper function that will produce a RSA private key from bytes and a password.

func RetryToken

func RetryToken() string

RetryToken generates a retry token that must be included on any request passed to the Retry method.

func SetMissingTemplateParams

func SetMissingTemplateParams(client *BaseClient)

SetMissingTemplateParams function will parse the {} template in client host and replace with empty string.

func SetSDKLogger

func SetSDKLogger(logger sdkLogger)

SetSDKLogger sets the logger used by the sdk

func String

func String(value string) *string

String returns a pointer to the provided string

func Uint

func Uint(value uint) *uint

Uint returns a pointer to the provided uint

func UnmarshalResponse

func UnmarshalResponse(httpResponse *http.Response, responseStruct interface{}) (err error)

UnmarshalResponse hydrates the fields of a struct with the values of a http response, guided by the field tags. The directive tag is "presentIn" and it can be either

  • "header": Will look for the header tagged as "name" in the headers of the struct and set it value to that
  • "body": It will try to marshal the body from a json string to a struct tagged with 'presentIn: "body"'.

Further this method will consume the body it should be safe to close it after this function Notice the current implementation only supports native types:int, strings, floats, bool as the field types

func UnmarshalResponseWithPolymorphicBody

func UnmarshalResponseWithPolymorphicBody(httpResponse *http.Response, responseStruct interface{}, unmarshaler PolymorphicJSONUnmarshaler) (err error)

UnmarshalResponseWithPolymorphicBody similar to UnmarshalResponse but assumes the body of the response contains polymorphic json. This function will use the unmarshaler argument to unmarshal json content

func UpdateRequestBinaryBody

func UpdateRequestBinaryBody(httpRequest *http.Request, rsc *OCIReadSeekCloser)

UpdateRequestBinaryBody updates the http request's body once it is binary request and the request body is seekable if the content length is zero, no need to update request body(since it's already been set to http.Nody)

func Version

func Version() string

Version returns semantic version of the sdk

Types

type AuthConfig

type AuthConfig struct {
	AuthType AuthenticationType
	// IsFromConfigFile is used to point out if the authConfig is from configuration file
	IsFromConfigFile bool
	OboToken         *string
}

AuthConfig is used for getting auth related paras in config file

type AuthenticationType

type AuthenticationType string

AuthenticationType for auth

const (
	// UserPrincipal is default auth type
	UserPrincipal AuthenticationType = "user_principal"
	// InstancePrincipal is used for instance principal auth type
	InstancePrincipal AuthenticationType = "instance_principal"
	// InstancePrincipalDelegationToken is used for instance principal delegation token auth type
	InstancePrincipalDelegationToken AuthenticationType = "instance_principle_delegation_token"
	// ResourcePrincipalDelegationToken is used for resource principal delegation token auth type
	ResourcePrincipalDelegationToken AuthenticationType = "resource_principle_delegation_token"
	// UnknownAuthenticationType is used for none meaningful auth type
	UnknownAuthenticationType AuthenticationType = "unknown_auth_type"
)

type BaseClient

type BaseClient struct {
	//HTTPClient performs the http network operations
	HTTPClient HTTPRequestDispatcher

	//Signer performs auth operation
	Signer HTTPRequestSigner

	//A request interceptor can be used to customize the request before signing and dispatching
	Interceptor RequestInterceptor

	//The host of the service
	Host string

	//The user agent
	UserAgent string

	//Base path for all operations of this client
	BasePath string

	Configuration CustomClientConfiguration
}

BaseClient struct implements all basic operations to call oci web services.

func DefaultBaseClientWithSigner

func DefaultBaseClientWithSigner(signer HTTPRequestSigner) BaseClient

DefaultBaseClientWithSigner creates a default base client with a given signer

func NewClientWithConfig

func NewClientWithConfig(configProvider ConfigurationProvider) (client BaseClient, err error)

NewClientWithConfig Create a new client with a configuration provider, the configuration provider will be used for the default signer as well as reading the region This function does not check for valid regions to implement forward compatibility

func NewClientWithOboToken

func NewClientWithOboToken(configProvider ConfigurationProvider, oboToken string) (client BaseClient, err error)

NewClientWithOboToken Create a new client that will use oboToken for auth

func (BaseClient) Call

func (client BaseClient) Call(ctx context.Context, request *http.Request) (response *http.Response, err error)

Call executes the http request with the given context

func (BaseClient) CallWithDetails

func (client BaseClient) CallWithDetails(ctx context.Context, request *http.Request, details ClientCallDetails) (response *http.Response, err error)

CallWithDetails executes the http request, the given context using details specified in the parameters, this function provides a way to override some settings present in the client

func (*BaseClient) Endpoint

func (client *BaseClient) Endpoint() string

Endpoint returns the endpoint configured for client

func (BaseClient) IsOciRealmSpecificServiceEndpointTemplateEnabled

func (client BaseClient) IsOciRealmSpecificServiceEndpointTemplateEnabled() bool

IsOciRealmSpecificServiceEndpointTemplateEnabled returns true if the client is configured to use realm specific service endpoint template it will first check the client configuration, if not set, it will check the environment variable

func (BaseClient) IsRefreshableAuthType

func (client BaseClient) IsRefreshableAuthType() bool

IsRefreshableAuthType validates if a signer is from a refreshable config provider

func (BaseClient) RefreshableTokenWrappedCallWithDetails

func (client BaseClient) RefreshableTokenWrappedCallWithDetails(ctx context.Context, request *http.Request, details ClientCallDetails) (response *http.Response, err error)

RefreshableTokenWrappedCallWithDetails wraps the CallWithDetails with retry on 401 for Refreshable Toekn (Instance Principal, Resource Principal etc.) This is to intimitate the race condition on refresh

func (*BaseClient) RetryPolicy

func (client *BaseClient) RetryPolicy() *RetryPolicy

RetryPolicy returns the retryPolicy configured for client

func (*BaseClient) SetCustomClientConfiguration

func (client *BaseClient) SetCustomClientConfiguration(config CustomClientConfiguration)

SetCustomClientConfiguration sets client with retry and other custom configurations

type CircuitBreakerOption

type CircuitBreakerOption func(cbst *CircuitBreakerSetting)

CircuitBreakerOption is the type of the options for NewCircuitBreakerWithOptions.

func WithCloseStateWindow

func WithCloseStateWindow(window time.Duration) CircuitBreakerOption

WithCloseStateWindow is the option for NewCircuitBreaker that sets the closeStateWindow.

func WithFailureRateThreshold

func WithFailureRateThreshold(threshold float64) CircuitBreakerOption

WithFailureRateThreshold is the option for NewCircuitBreaker that sets the failureRateThreshold.

func WithHistoryCount

func WithHistoryCount(count int) CircuitBreakerOption

WithHistoryCount to set the number of failed responses

func WithIsEnabled

func WithIsEnabled(isEnabled bool) CircuitBreakerOption

WithIsEnabled is the option for NewCircuitBreaker that sets the isEnabled.

func WithMinimumRequests

func WithMinimumRequests(num uint32) CircuitBreakerOption

WithMinimumRequests is the option for NewCircuitBreaker that sets the minimumRequests.

func WithName

func WithName(name string) CircuitBreakerOption

WithName is the option for NewCircuitBreaker that sets the Name.

func WithOpenStateWindow

func WithOpenStateWindow(window time.Duration) CircuitBreakerOption

WithOpenStateWindow is the option for NewCircuitBreaker that sets the openStateWindow.

func WithServiceName

func WithServiceName(serviceName string) CircuitBreakerOption

WithServiceName is the option for NewCircuitBreaker that sets the ServiceName.

func WithSuccessStatCodeMap

func WithSuccessStatCodeMap(successStatCodeMap map[int]bool) CircuitBreakerOption

WithSuccessStatCodeMap is the option for NewCircuitBreaker that sets the successStatCodeMap.

func WithSuccessStatErrCodeMap

func WithSuccessStatErrCodeMap(successStatErrCodeMap map[StatErrCode]bool) CircuitBreakerOption

WithSuccessStatErrCodeMap is the option for NewCircuitBreaker that sets the successStatErrCodeMap.

type CircuitBreakerSetting

type CircuitBreakerSetting struct {
	// contains filtered or unexported fields
}

CircuitBreakerSetting wraps all exposed configurable params of circuit breaker

var GlobalCircuitBreakerSetting *CircuitBreakerSetting = nil

GlobalCircuitBreakerSetting is global level circuit breaker setting, it would impact all services, the precedence is lower than client level circuit breaker

func DefaultCircuitBreakerSetting

func DefaultCircuitBreakerSetting() *CircuitBreakerSetting

DefaultCircuitBreakerSetting is used for set circuit breaker with default config

func DefaultCircuitBreakerSettingWithServiceName

func DefaultCircuitBreakerSettingWithServiceName(servicename string) *CircuitBreakerSetting

DefaultCircuitBreakerSettingWithServiceName is used for set circuit breaker with default config

func NewCircuitBreakerSettingWithOptions

func NewCircuitBreakerSettingWithOptions(opts ...CircuitBreakerOption) *CircuitBreakerSetting

NewCircuitBreakerSettingWithOptions is a helper method to assemble a CircuitBreakerSetting object. It starts out with the values returned by defaultCircuitBreakerSetting().

func NoCircuitBreakerSetting

func NoCircuitBreakerSetting() *CircuitBreakerSetting

NoCircuitBreakerSetting is used for disable Circuit Breaker

func (CircuitBreakerSetting) String

func (cbst CircuitBreakerSetting) String() string

String Converts CircuitBreakerSetting to human-readable string representation

type ClientCallDetails

type ClientCallDetails struct {
	Signer HTTPRequestSigner
}

ClientCallDetails a set of settings used by the a single Call operation of the http Client

type ConfigurationProvider

type ConfigurationProvider interface {
	KeyProvider
	TenancyOCID() (string, error)
	UserOCID() (string, error)
	KeyFingerprint() (string, error)
	Region() (string, error)
	// AuthType() is used for specify the needed auth type, like UserPrincipal, InstancePrincipal, etc.
	AuthType() (AuthConfig, error)
}

ConfigurationProvider wraps information about the account owner

func ComposingConfigurationProvider

func ComposingConfigurationProvider(providers []ConfigurationProvider) (ConfigurationProvider, error)

ComposingConfigurationProvider creates a composing configuration provider with the given slice of configuration providers A composing provider will return the configuration of the first provider that has the required property if no provider has the property it will return an error.

func ConfigurationProviderEnvironmentVariables

func ConfigurationProviderEnvironmentVariables(environmentVariablePrefix, privateKeyPassword string) ConfigurationProvider

ConfigurationProviderEnvironmentVariables creates a ConfigurationProvider from a uniform set of environment variables starting with a prefix The env variables should look like: [prefix]_private_key_path, [prefix]_tenancy_ocid, [prefix]_user_ocid, [prefix]_fingerprint [prefix]_region

func ConfigurationProviderForSessionToken

func ConfigurationProviderForSessionToken(configFilePath, privateKeyPassword string) (ConfigurationProvider, error)

ConfigurationProviderForSessionToken creates a session token configuration provider from a configuration file by reading the "DEFAULT" profile

func ConfigurationProviderForSessionTokenWithProfile

func ConfigurationProviderForSessionTokenWithProfile(configFilePath, profile, privateKeyPassword string) (ConfigurationProvider, error)

ConfigurationProviderForSessionTokenWithProfile creates a session token configuration provider from a configuration file by reading the given profile

func ConfigurationProviderFromFile

func ConfigurationProviderFromFile(configFilePath, privateKeyPassword string) (ConfigurationProvider, error)

ConfigurationProviderFromFile creates a configuration provider from a configuration file by reading the "DEFAULT" profile

func ConfigurationProviderFromFileWithProfile

func ConfigurationProviderFromFileWithProfile(configFilePath, profile, privateKeyPassword string) (ConfigurationProvider, error)

ConfigurationProviderFromFileWithProfile creates a configuration provider from a configuration file and the given profile

func CustomProfileConfigProvider

func CustomProfileConfigProvider(customConfigPath string, profile string) ConfigurationProvider

CustomProfileConfigProvider returns the config provider of given profile. The custom profile config provider will look for configurations in 2 places: file in $HOME/.oci/config, and variables names starting with the string TF_VAR. If the same configuration is found in multiple places the provider will prefer the first one.

func CustomProfileSessionTokenConfigProvider

func CustomProfileSessionTokenConfigProvider(customConfigPath string, profile string) ConfigurationProvider

CustomProfileSessionTokenConfigProvider returns the session token config provider of the given profile. This will look for the configuration in the given config file path.

func DefaultConfigProvider

func DefaultConfigProvider() ConfigurationProvider

DefaultConfigProvider returns the default config provider. The default config provider will look for configurations in 3 places: file in $HOME/.oci/config, HOME/.obmcs/config and variables names starting with the string TF_VAR. If the same configuration is found in multiple places the provider will prefer the first one. If the config file is not placed in the default location, the environment variable OCI_CONFIG_FILE can provide the config file location.

func NewRawConfigurationProvider

func NewRawConfigurationProvider(tenancy, user, region, fingerprint, privateKey string, privateKeyPassphrase *string) ConfigurationProvider

NewRawConfigurationProvider will create a ConfigurationProvider with the arguments of the function

type CustomClientConfiguration

type CustomClientConfiguration struct {
	RetryPolicy                                 *RetryPolicy
	CircuitBreaker                              *OciCircuitBreaker
	RealmSpecificServiceEndpointTemplateEnabled *bool
}

CustomClientConfiguration contains configurations set at client level, currently it only includes RetryPolicy

type DefaultMTLSConfigProvider

type DefaultMTLSConfigProvider struct {
	// contains filtered or unexported fields
}

DefaultMTLSConfigProvider is a provider that provides a MTLS tls.config for the HTTPTransport

func (*DefaultMTLSConfigProvider) NewOrDefault

func (t *DefaultMTLSConfigProvider) NewOrDefault() (*tls.Config, error)

NewOrDefault returns a default tls.Config which sets its RootCAs to be a *x509.CertPool from caBundlePath and calls tls.LoadX509KeyPair(clientCertPath, clientKeyPath) to set mtls client certs.

func (*DefaultMTLSConfigProvider) WatchedFilesModified

func (t *DefaultMTLSConfigProvider) WatchedFilesModified() bool

WatchedFilesModified returns true if any files in the watchedFilesStatsMap has been modified else returns false

type DefaultSDKLogger

type DefaultSDKLogger struct {
	// contains filtered or unexported fields
}

DefaultSDKLogger the default implementation of the sdkLogger

func NewSDKLogger

func NewSDKLogger() (DefaultSDKLogger, error)

NewSDKLogger creates a defaultSDKLogger Debug logging is turned on/off by the presence of the environment variable "OCI_GO_SDK_DEBUG" The value of the "OCI_GO_SDK_DEBUG" environment variable controls the logging level. "null" outputs no log messages "i" or "info" outputs minimal log messages "d" or "debug" outputs some logs messages "v" or "verbose" outputs all logs messages, including body of requests

func (DefaultSDKLogger) Log

func (l DefaultSDKLogger) Log(logLevel int, format string, v ...interface{}) error

Log logs v with the provided format if the current log level is loglevel

func (DefaultSDKLogger) LogLevel

func (l DefaultSDKLogger) LogLevel() int

LogLevel returns the current debug level

type DefaultTLSConfigProvider

type DefaultTLSConfigProvider struct {
	// contains filtered or unexported fields
}

DefaultTLSConfigProvider is a provider that provides a TLS tls.config for the HTTPTransport

func (*DefaultTLSConfigProvider) NewOrDefault

func (t *DefaultTLSConfigProvider) NewOrDefault() (*tls.Config, error)

NewOrDefault returns a default tls.Config which sets its RootCAs to be a *x509.CertPool from caBundlePath.

func (*DefaultTLSConfigProvider) WatchedFilesModified

func (t *DefaultTLSConfigProvider) WatchedFilesModified() bool

WatchedFilesModified returns true if any files in the watchedFilesStatsMap has been modified else returns false

type EcMode

type EcMode int64

EcMode is the eventual consistency (EC) communication mode used.

const (
	// Uninitialized means the EC communication mode has not been set yet.
	Uninitialized EcMode = iota // 0

	// InProcess is the default EC communication mode which only communicates the end-of-window timestamp inside the same process.
	InProcess

	// File is the EC communication mode that uses a file to communicate the end-of-window timestamp using a file visible across processes.
	// Locking is performed using a lock file.
	File
)

type EventuallyConsistentContext

type EventuallyConsistentContext struct {
	// contains filtered or unexported fields
}

EventuallyConsistentContext contains the information about the end of the eventually consistent window.

func (*EventuallyConsistentContext) GetEndOfWindow

func (e *EventuallyConsistentContext) GetEndOfWindow() *time.Time

GetEndOfWindow returns the end time an eventually consistent window, or nil if no eventually consistent requests were made

func (*EventuallyConsistentContext) UpdateEndOfWindow

func (e *EventuallyConsistentContext) UpdateEndOfWindow(windowSize time.Duration) *time.Time

UpdateEndOfWindow sets the end time of the eventually consistent window the specified duration into the future

type HTTPRequestDispatcher

type HTTPRequestDispatcher interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPRequestDispatcher wraps the execution of a http request, it is generally implemented by http.Client.Do, but can be customized for testing

type HTTPRequestSigner

type HTTPRequestSigner interface {
	Sign(r *http.Request) error
}

HTTPRequestSigner the interface to sign a request

func DefaultRequestSigner

func DefaultRequestSigner(provider KeyProvider) HTTPRequestSigner

DefaultRequestSigner creates a signer with default parameters.

func NewSignerFromOCIRequestSigner

func NewSignerFromOCIRequestSigner(oldSigner HTTPRequestSigner, predicate SignerBodyHashPredicate) (HTTPRequestSigner, error)

NewSignerFromOCIRequestSigner creates a copy of the request signer and attaches the new SignerBodyHashPredicate returns an error if the passed signer is not of type ociRequestSigner

func RequestSigner

func RequestSigner(provider KeyProvider, genericHeaders, bodyHeaders []string) HTTPRequestSigner

RequestSigner creates a signer that utilizes the specified headers for signing and the default predicate for using the body of the request as part of the signature

func RequestSignerExcludeBody

func RequestSignerExcludeBody(provider KeyProvider) HTTPRequestSigner

RequestSignerExcludeBody creates a signer without hash the body.

func RequestSignerWithBodyHashingPredicate

func RequestSignerWithBodyHashingPredicate(provider KeyProvider, genericHeaders, bodyHeaders []string, shouldHashBody SignerBodyHashPredicate) HTTPRequestSigner

RequestSignerWithBodyHashingPredicate creates a signer that utilizes the specified headers for signing, as well as a predicate for using the body of the request and bodyHeaders parameter as part of the signature

type InvalidSSEResponseError

type InvalidSSEResponseError struct {
}

InvalidSSEResponseError returned in the case that a nil response body was given to NewSSEReader()

func (InvalidSSEResponseError) Error

func (e InvalidSSEResponseError) Error() string

type KeyProvider

type KeyProvider interface {
	PrivateRSAKey() (*rsa.PrivateKey, error)
	KeyID() (string, error)
}

KeyProvider interface that wraps information about the key's account owner

type NonSeekableRequestRetryFailure

type NonSeekableRequestRetryFailure struct {
	// contains filtered or unexported fields
}

NonSeekableRequestRetryFailure is the error returned when the request is with binary request body, and is configured retry, but the request body is not retryable

func (NonSeekableRequestRetryFailure) Error

type OCIOperation

OCIOperation is the generalization of a request-response cycle undergone by an OCI service.

type OCIOperationResponse

type OCIOperationResponse struct {
	// Response from OCI Operation
	Response OCIResponse

	// Error from OCI Operation
	Error error

	// Operation Attempt Number (one-based)
	AttemptNumber uint

	// End of eventually consistent effects, or nil if no such effects
	EndOfWindowTime *time.Time

	// Backoff scaling factor (only used for dealing with eventual consistency)
	BackoffScalingFactor float64

	// Time of the initial attempt
	InitialAttemptTime time.Time
}

OCIOperationResponse represents the output of an OCIOperation, with additional context of error message and operation attempt number.

func NewOCIOperationResponse

func NewOCIOperationResponse(response OCIResponse, err error, attempt uint) OCIOperationResponse

NewOCIOperationResponse assembles an OCI Operation Response object. Note that InitialAttemptTime is not set, nor is EndOfWindowTime, and BackoffScalingFactor is set to 1.0. EndOfWindowTime and BackoffScalingFactor are only important for eventual consistency. InitialAttemptTime can be useful for time-based (as opposed to count-based) retry policies.

func NewOCIOperationResponseExtended

func NewOCIOperationResponseExtended(response OCIResponse, err error, attempt uint, endOfWindowTime *time.Time, backoffScalingFactor float64,
	initialAttemptTime time.Time) OCIOperationResponse

NewOCIOperationResponseExtended assembles an OCI Operation Response object, with the value for the EndOfWindowTime, BackoffScalingFactor, and InitialAttemptTime set. EndOfWindowTime and BackoffScalingFactor are only important for eventual consistency. InitialAttemptTime can be useful for time-based (as opposed to count-based) retry policies.

type OCIReadSeekCloser

type OCIReadSeekCloser struct {
	// contains filtered or unexported fields
}

OCIReadSeekCloser is a thread-safe io.ReadSeekCloser to prevent racing with retrying binary requests

func NewOCIReadSeekCloser

func NewOCIReadSeekCloser(rc io.ReadCloser) *OCIReadSeekCloser

NewOCIReadSeekCloser constructs OCIReadSeekCloser, the only input is binary request body

func (*OCIReadSeekCloser) Close

func (rsc *OCIReadSeekCloser) Close() error

Close is a thread-safe operation, it closes the instance of the OCIReadSeekCloser's access to the underlying io.ReadCloser.

func (*OCIReadSeekCloser) Read

func (rsc *OCIReadSeekCloser) Read(p []byte) (n int, err error)

Read is a thread-safe operation, it implements io.Read() interface

func (*OCIReadSeekCloser) Seek

func (rsc *OCIReadSeekCloser) Seek(offset int64, whence int) (int64, error)

Seek is a thread-safe operation, it implements io.seek() interface, if the original request body implements io.seek() interface, or implements "well-known" data type like os.File, io.SectionReader, or wrapped by ioutil.NopCloser can be supported

func (*OCIReadSeekCloser) Seekable

func (rsc *OCIReadSeekCloser) Seekable() bool

Seekable is used for check if the binary request body can be seek or no

type OCIRequest

type OCIRequest interface {
	// HTTPRequest assembles an HTTP request.
	HTTPRequest(method, path string, binaryRequestBody *OCIReadSeekCloser, extraHeaders map[string]string) (http.Request, error)
}

OCIRequest is any request made to an OCI service.

type OCIResponse

type OCIResponse interface {
	// HTTPResponse returns the raw HTTP response.
	HTTPResponse() *http.Response
}

OCIResponse is the response from issuing a request to an OCI service.

func Retry

func Retry(ctx context.Context, request OCIRetryableRequest, operation OCIOperation, policy RetryPolicy) (OCIResponse, error)

Retry is a package-level operation that executes the retryable request using the specified operation and retry policy.

type OCIRetryableRequest

type OCIRetryableRequest interface {
	// Any retryable request must implement the OCIRequest interface
	OCIRequest

	// Each operation should implement this method, if has binary body, return OCIReadSeekCloser and true, otherwise return nil, false
	BinaryRequestBody() (*OCIReadSeekCloser, bool)

	// Each operation specifies default retry behavior. By passing no arguments to this method, the default retry
	// behavior, as determined on a per-operation-basis, will be honored. Variadic retry policy option arguments
	// passed to this method will override the default behavior.
	RetryPolicy() *RetryPolicy
}

OCIRetryableRequest represents a request that can be reissued according to the specified policy.

type OciCircuitBreaker

type OciCircuitBreaker struct {
	Cbst *CircuitBreakerSetting
	Cb   *gobreaker.CircuitBreaker
	// contains filtered or unexported fields
}

OciCircuitBreaker wraps all exposed configurable params of circuit breaker and 3P gobreaker CircuirBreaker

func NewCircuitBreaker

func NewCircuitBreaker(cbst *CircuitBreakerSetting) *OciCircuitBreaker

NewCircuitBreaker is used for initialing specified circuit breaker configuration with base client

func NewOciCircuitBreaker

func NewOciCircuitBreaker(cbst *CircuitBreakerSetting, gbcb *gobreaker.CircuitBreaker) *OciCircuitBreaker

NewOciCircuitBreaker is used for initializing specified oci circuit breaker configuration with circuit breaker settings

func (*OciCircuitBreaker) AddToHistory

func (ocb *OciCircuitBreaker) AddToHistory(resp *http.Response, err ServiceError)

AddToHistory processed the response and adds to response history queue

func (*OciCircuitBreaker) GetHistory

func (ocb *OciCircuitBreaker) GetHistory() string

GetHistory processes the rsponse in queue to construct a String

type OciHTTPTransportWrapper

type OciHTTPTransportWrapper struct {
	// RefreshRate specifies the duration at which http.Transport
	// (with its tls.Config) must be refreshed.
	// Defaults to 5 minutes.
	RefreshRate time.Duration

	// TLSConfigProvider creates a new tls.Config.
	// If not set, nil tls.Config is returned.
	TLSConfigProvider TLSConfigProvider

	// ClientTemplate is responsible for creating a new http.Client with
	// a given tls.Config.
	//
	// If not set, a new http.Client with a cloned http.DefaultTransport is returned.
	TransportTemplate TransportTemplateProvider
	// contains filtered or unexported fields
}

OciHTTPTransportWrapper is a http.RoundTripper that periodically refreshes the underlying http.Transport according to its templates. Upon the first use (or once the RefreshRate duration is elapsed), a new transport will be created from the TransportTemplate (if set).

func (*OciHTTPTransportWrapper) Delegate

Delegate returns the currently active http.RoundTripper. Might be nil.

func (*OciHTTPTransportWrapper) Refresh

func (t *OciHTTPTransportWrapper) Refresh(force bool) error

Refresh forces refresh of the underlying delegate.

func (*OciHTTPTransportWrapper) RoundTrip

func (t *OciHTTPTransportWrapper) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type PolymorphicJSONUnmarshaler

type PolymorphicJSONUnmarshaler interface {
	UnmarshalPolymorphicJSON(data []byte) (interface{}, error)
}

PolymorphicJSONUnmarshaler is the interface to unmarshal polymorphic json payloads

type RefreshableConfigurationProvider

type RefreshableConfigurationProvider interface {
	Refreshable() bool
}

RefreshableConfigurationProvider the interface to identity if the config provider is refreshable

type Region

type Region string

Region type for regions

const (
	//RegionAPChuncheon1 region Chuncheon
	RegionAPChuncheon1 Region = "ap-chuncheon-1"
	//RegionAPHyderabad1 region Hyderabad
	RegionAPHyderabad1 Region = "ap-hyderabad-1"
	//RegionAPMelbourne1 region Melbourne
	RegionAPMelbourne1 Region = "ap-melbourne-1"
	//RegionAPMumbai1 region Mumbai
	RegionAPMumbai1 Region = "ap-mumbai-1"
	//RegionAPOsaka1 region Osaka
	RegionAPOsaka1 Region = "ap-osaka-1"
	//RegionAPSeoul1 region Seoul
	RegionAPSeoul1 Region = "ap-seoul-1"
	//RegionAPSydney1 region Sydney
	RegionAPSydney1 Region = "ap-sydney-1"
	//RegionAPTokyo1 region Tokyo
	RegionAPTokyo1 Region = "ap-tokyo-1"
	//RegionCAMontreal1 region Montreal
	RegionCAMontreal1 Region = "ca-montreal-1"
	//RegionCAToronto1 region Toronto
	RegionCAToronto1 Region = "ca-toronto-1"
	//RegionEUAmsterdam1 region Amsterdam
	RegionEUAmsterdam1 Region = "eu-amsterdam-1"
	//RegionFRA region Frankfurt
	RegionFRA Region = "eu-frankfurt-1"
	//RegionEUZurich1 region Zurich
	RegionEUZurich1 Region = "eu-zurich-1"
	//RegionMEJeddah1 region Jeddah
	RegionMEJeddah1 Region = "me-jeddah-1"
	//RegionMEDubai1 region Dubai
	RegionMEDubai1 Region = "me-dubai-1"
	//RegionSASaopaulo1 region Saopaulo
	RegionSASaopaulo1 Region = "sa-saopaulo-1"
	//RegionUKCardiff1 region Cardiff
	RegionUKCardiff1 Region = "uk-cardiff-1"
	//RegionLHR region London
	RegionLHR Region = "uk-london-1"
	//RegionIAD region Ashburn
	RegionIAD Region = "us-ashburn-1"
	//RegionPHX region Phoenix
	RegionPHX Region = "us-phoenix-1"
	//RegionSJC1 region Sanjose
	RegionSJC1 Region = "us-sanjose-1"
	//RegionSAVinhedo1 region Vinhedo
	RegionSAVinhedo1 Region = "sa-vinhedo-1"
	//RegionSASantiago1 region Santiago
	RegionSASantiago1 Region = "sa-santiago-1"
	//RegionILJerusalem1 region Jerusalem
	RegionILJerusalem1 Region = "il-jerusalem-1"
	//RegionEUMarseille1 region Marseille
	RegionEUMarseille1 Region = "eu-marseille-1"
	//RegionAPSingapore1 region Singapore
	RegionAPSingapore1 Region = "ap-singapore-1"
	//RegionMEAbudhabi1 region Abudhabi
	RegionMEAbudhabi1 Region = "me-abudhabi-1"
	//RegionEUMilan1 region Milan
	RegionEUMilan1 Region = "eu-milan-1"
	//RegionEUStockholm1 region Stockholm
	RegionEUStockholm1 Region = "eu-stockholm-1"
	//RegionAFJohannesburg1 region Johannesburg
	RegionAFJohannesburg1 Region = "af-johannesburg-1"
	//RegionEUParis1 region Paris
	RegionEUParis1 Region = "eu-paris-1"
	//RegionMXQueretaro1 region Queretaro
	RegionMXQueretaro1 Region = "mx-queretaro-1"
	//RegionEUMadrid1 region Madrid
	RegionEUMadrid1 Region = "eu-madrid-1"
	//RegionUSChicago1 region Chicago
	RegionUSChicago1 Region = "us-chicago-1"
	//RegionMXMonterrey1 region Monterrey
	RegionMXMonterrey1 Region = "mx-monterrey-1"
	//RegionUSSaltlake2 region Saltlake
	RegionUSSaltlake2 Region = "us-saltlake-2"
	//RegionSABogota1 region Bogota
	RegionSABogota1 Region = "sa-bogota-1"
	//RegionSAValparaiso1 region Valparaiso
	RegionSAValparaiso1 Region = "sa-valparaiso-1"
	//RegionAPSingapore2 region Singapore
	RegionAPSingapore2 Region = "ap-singapore-2"
	//RegionMERiyadh1 region Riyadh
	RegionMERiyadh1 Region = "me-riyadh-1"
	//RegionUSLangley1 region Langley
	RegionUSLangley1 Region = "us-langley-1"
	//RegionUSLuke1 region Luke
	RegionUSLuke1 Region = "us-luke-1"
	//RegionUSGovAshburn1 gov region Ashburn
	RegionUSGovAshburn1 Region = "us-gov-ashburn-1"
	//RegionUSGovChicago1 gov region Chicago
	RegionUSGovChicago1 Region = "us-gov-chicago-1"
	//RegionUSGovPhoenix1 gov region Phoenix
	RegionUSGovPhoenix1 Region = "us-gov-phoenix-1"
	//RegionUKGovLondon1 gov region London
	RegionUKGovLondon1 Region = "uk-gov-london-1"
	//RegionUKGovCardiff1 gov region Cardiff
	RegionUKGovCardiff1 Region = "uk-gov-cardiff-1"
	//RegionAPChiyoda1 region Chiyoda
	RegionAPChiyoda1 Region = "ap-chiyoda-1"
	//RegionAPIbaraki1 region Ibaraki
	RegionAPIbaraki1 Region = "ap-ibaraki-1"
	//RegionMEDccMuscat1 region Muscat
	RegionMEDccMuscat1 Region = "me-dcc-muscat-1"
	//RegionAPDccCanberra1 region Canberra
	RegionAPDccCanberra1 Region = "ap-dcc-canberra-1"
	//RegionEUDccMilan1 region Milan
	RegionEUDccMilan1 Region = "eu-dcc-milan-1"
	//RegionEUDccMilan2 region Milan
	RegionEUDccMilan2 Region = "eu-dcc-milan-2"
	//RegionEUDccDublin2 region Dublin
	RegionEUDccDublin2 Region = "eu-dcc-dublin-2"
	//RegionEUDccRating2 region Rating
	RegionEUDccRating2 Region = "eu-dcc-rating-2"
	//RegionEUDccRating1 region Rating
	RegionEUDccRating1 Region = "eu-dcc-rating-1"
	//RegionEUDccDublin1 region Dublin
	RegionEUDccDublin1 Region = "eu-dcc-dublin-1"
	//RegionAPDccGazipur1 region Gazipur
	RegionAPDccGazipur1 Region = "ap-dcc-gazipur-1"
	//RegionEUMadrid2 region Madrid
	RegionEUMadrid2 Region = "eu-madrid-2"
	//RegionEUFrankfurt2 region Frankfurt
	RegionEUFrankfurt2 Region = "eu-frankfurt-2"
	//RegionEUJovanovac1 region Jovanovac
	RegionEUJovanovac1 Region = "eu-jovanovac-1"
	//RegionMEDccDoha1 region Doha
	RegionMEDccDoha1 Region = "me-dcc-doha-1"
	//RegionUSSomerset1 region Somerset
	RegionUSSomerset1 Region = "us-somerset-1"
	//RegionUSThames1 region Thames
	RegionUSThames1 Region = "us-thames-1"
	//RegionEUDccZurich1 region Zurich
	RegionEUDccZurich1 Region = "eu-dcc-zurich-1"
	//RegionEUCrissier1 region Crissier
	RegionEUCrissier1 Region = "eu-crissier-1"
	//RegionMEAbudhabi3 region Abudhabi
	RegionMEAbudhabi3 Region = "me-abudhabi-3"
	//RegionMEAbudhabi2 region Abudhabi
	RegionMEAbudhabi2 Region = "me-abudhabi-2"
	//RegionMEAbudhabi4 region Abudhabi
	RegionMEAbudhabi4 Region = "me-abudhabi-4"
)

func StringToRegion

func StringToRegion(stringRegion string) (r Region)

StringToRegion convert a string to Region type

func (Region) Endpoint

func (region Region) Endpoint(service string) string

Endpoint returns a endpoint for a service

func (Region) EndpointForTemplate

func (region Region) EndpointForTemplate(service string, serviceEndpointTemplate string) string

EndpointForTemplate returns a endpoint for a service based on template, only unknown region name can fall back to "oc1", but not short code region name.

func (Region) EndpointForTemplateDottedRegion

func (region Region) EndpointForTemplateDottedRegion(service string, serviceEndpointTemplate string, endpointServiceName string) (string, error)

EndpointForTemplateDottedRegion returns a endpoint for a service based on the service name and EndpointTemplateForRegionWithDot template. If a service name is missing it is obtained from serviceEndpointTemplate and endpoint is constructed usingEndpointTemplateForRegionWithDot template.

func (Region) RealmID

func (region Region) RealmID() (string, error)

RealmID is used for getting realmID from region, if no region found, directly throw error

type RequestInterceptor

type RequestInterceptor func(*http.Request) error

RequestInterceptor function used to customize the request before calling the underlying service

type RequestMetadata

type RequestMetadata struct {
	// RetryPolicy is the policy for reissuing the request. If no retry policy is set on the request,
	// then the request will be issued exactly once.
	RetryPolicy *RetryPolicy
}

RequestMetadata is metadata about an OCIRequest. This structure represents the behavior exhibited by the SDK when issuing (or reissuing) a request.

type ResponseHistory

type ResponseHistory struct {
	// contains filtered or unexported fields
}

ResponseHistory wraps the response params

func (ResponseHistory) String

func (rh ResponseHistory) String() string

String Converts ResponseHistory to human-readable string representation

type RetryPolicy

type RetryPolicy struct {
	// MaximumNumberAttempts is the maximum number of times to retry a request. Zero indicates an unlimited
	// number of attempts.
	MaximumNumberAttempts uint

	// ShouldRetryOperation inspects the http response, error, and operation attempt number, and
	// - returns true if we should retry the operation
	// - returns false otherwise
	ShouldRetryOperation func(OCIOperationResponse) bool

	// GetNextDuration computes the duration to pause between operation retries.
	NextDuration func(OCIOperationResponse) time.Duration

	// minimum sleep between attempts in seconds
	MinSleepBetween float64

	// maximum sleep between attempts in seconds
	MaxSleepBetween float64

	// the base for the exponential backoff
	ExponentialBackoffBase float64

	// DeterminePolicyToUse may modify the policy to handle eventual consistency; the return values are
	// the retry policy to use, the end of the eventually consistent time window, and the backoff scaling factor
	// If eventual consistency is not considered, this function should return the unmodified policy that was
	// provided as input, along with (*time.Time)(nil) (no time window), and 1.0 (unscaled backoff).
	DeterminePolicyToUse func(policy RetryPolicy) (RetryPolicy, *time.Time, float64)

	// if the retry policy considers eventual consistency, but there is no eventual consistency present
	// the retries will fall back to the policy specified here; recommendation is to set this to DefaultRetryPolicyWithoutEventualConsistency()
	NonEventuallyConsistentPolicy *RetryPolicy

	// Stores the maximum cumulative backoff in seconds. This can usually be calculated using
	// MaximumNumberAttempts, MinSleepBetween, MaxSleepBetween, and ExponentialBackoffBase,
	// but if MaximumNumberAttempts is 0 (unlimited attempts), then this needs to be set explicitly
	// for Eventual Consistency retries to work.
	MaximumCumulativeBackoffWithoutJitter float64
}

RetryPolicy is the class that holds all relevant information for retrying operations.

var GlobalRetry *RetryPolicy = nil

GlobalRetry is user defined global level retry policy, it would impact all services, the precedence is lower than user defined client/request level retry policy

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy is a helper method that assembles and returns a return policy that is defined to be a default one The default retry policy will retry on (409, IncorrectState), (429, TooManyRequests) and any 5XX errors except (501, MethodNotImplemented) The default retry behavior is using exponential backoff with jitter, the maximum wait time is 30s plus 1s jitter The maximum cumulative backoff after all 8 attempts have been made is about 1.5 minutes. It will also retry on errors affected by eventual consistency. The eventual consistency retry behavior is using exponential backoff with jitter, the maximum wait time is 45s plus 1s jitter Under eventual consistency, the maximum cumulative backoff after all 9 attempts have been made is about 4 minutes.

func DefaultRetryPolicyWithoutEventualConsistency

func DefaultRetryPolicyWithoutEventualConsistency() RetryPolicy

DefaultRetryPolicyWithoutEventualConsistency is a helper method that assembles and returns a return policy that is defined to be a default one The default retry policy will retry on (409, IncorrectState), (429, TooManyRequests) and any 5XX errors except (501, MethodNotImplemented) It will not retry on errors affected by eventual consistency. The default retry behavior is using exponential backoff with jitter, the maximum wait time is 30s plus 1s jitter

func EventuallyConsistentRetryPolicy

func EventuallyConsistentRetryPolicy(nonEventuallyConsistentPolicy RetryPolicy) RetryPolicy

EventuallyConsistentRetryPolicy is a helper method that assembles and returns a return policy that is defined to be a default one plus dealing with errors affected by eventual consistency. The default retry behavior is using exponential backoff with jitter, the maximum wait time is 45s plus 1s jitter

func NewRetryPolicy

func NewRetryPolicy(attempts uint, retryOperation func(OCIOperationResponse) bool, nextDuration func(OCIOperationResponse) time.Duration) RetryPolicy

NewRetryPolicy is a helper method for assembling a Retry Policy object. It does not handle eventual consistency, so as to not break existing code. If you want to handle eventual consistency, the simplest way to do that is to replace the code

NewRetryPolicy(a, r, n)

with the code

  NewRetryPolicyWithOptions(
		WithMaximumNumberAttempts(a),
		WithFixedBackoff(fb) // fb is the fixed backoff duration
		WithShouldRetryOperation(r))

or

  NewRetryPolicyWithOptions(
		WithMaximumNumberAttempts(a),
		WithExponentialBackoff(mb, e) // mb is the maximum backoff duration, and e is the base for exponential backoff, e.g. 2.0
		WithShouldRetryOperation(r))

or, if a == 0 (the maximum number of attempts is unlimited)

NewRetryPolicyWithEventualConsistencyUnlimitedAttempts(a, r, n, mcb) // mcb is the maximum cumulative backoff duration without jitter

func NewRetryPolicyWithEventualConsistencyUnlimitedAttempts

func NewRetryPolicyWithEventualConsistencyUnlimitedAttempts(attempts uint, retryOperation func(OCIOperationResponse) bool, nextDuration func(OCIOperationResponse) time.Duration,
	maximumCumulativeBackoffWithoutJitter time.Duration) (*RetryPolicy, error)

NewRetryPolicyWithEventualConsistencyUnlimitedAttempts is a helper method for assembling a Retry Policy object. It does handle eventual consistency, but other than that, it is very similar to NewRetryPolicy. NewRetryPolicyWithEventualConsistency does not support limited attempts, use NewRetryPolicyWithEventualConsistency instead.

func NewRetryPolicyWithOptions

func NewRetryPolicyWithOptions(opts ...RetryPolicyOption) RetryPolicy

NewRetryPolicyWithOptions is a helper method for assembling a Retry Policy object. It starts out with the values returned by DefaultRetryPolicy() and does handle eventual consistency, unless you replace all options set using ReplaceWithValuesFromRetryPolicy(DefaultRetryPolicyWithoutEventualConsistency()).

func NoRetryPolicy

func NoRetryPolicy() RetryPolicy

NoRetryPolicy is a helper method that assembles and returns a return policy that indicates an operation should never be retried (the operation is performed exactly once).

func (RetryPolicy) GetMaximumCumulativeBackoffWithoutJitter

func (rp RetryPolicy) GetMaximumCumulativeBackoffWithoutJitter() time.Duration

GetMaximumCumulativeBackoffWithoutJitter returns the maximum cumulative backoff the retry policy would do, taking into account whether eventually consistency is considered or not. This function uses either GetMaximumCumulativeBackoffWithoutJitter or GetMaximumCumulativeEventuallyConsistentBackoffWithoutJitter, whichever is appropriate

func (RetryPolicy) String

func (rp RetryPolicy) String() string

String Converts retry policy to human-readable string representation

type RetryPolicyOption

type RetryPolicyOption func(rp *RetryPolicy)

RetryPolicyOption is the type of the options for NewRetryPolicy.

func ReplaceWithValuesFromRetryPolicy

func ReplaceWithValuesFromRetryPolicy(other RetryPolicy) RetryPolicyOption

ReplaceWithValuesFromRetryPolicy is an option for NewRetryPolicyWithOptions that copies over all settings from another RetryPolicy

func WithConditionalOption

func WithConditionalOption(enabled bool, otherOption RetryPolicyOption) RetryPolicyOption

WithConditionalOption is an option for NewRetryPolicyWithOptions that enables or disables another option.

func WithEventualConsistency

func WithEventualConsistency() RetryPolicyOption

WithEventualConsistency is the option for NewRetryPolicyWithOptions that enables considering eventual backoff for the policy.

func WithExponentialBackoff

func WithExponentialBackoff(newMaxSleepBetween time.Duration, newExponentialBackoffBase float64) RetryPolicyOption

WithExponentialBackoff is an option for NewRetryPolicyWithOptions that sets the exponential backoff base, minimum and maximum sleep between attempts, and next duration function. Therefore, WithExponentialBackoff is a combination of WithNextDuration, withMinSleepBetween, withMaxSleepBetween, and withExponentialBackoffBase.

func WithFixedBackoff

func WithFixedBackoff(newSleepBetween time.Duration) RetryPolicyOption

WithFixedBackoff is an option for NewRetryPolicyWithOptions that sets the backoff to always be exactly the same value. There is no jitter either. Therefore, WithFixedBackoff is a combination of WithNextDuration, withMinSleepBetween, withMaxSleepBetween, and withExponentialBackoffBase.

func WithMaximumNumberAttempts

func WithMaximumNumberAttempts(attempts uint) RetryPolicyOption

WithMaximumNumberAttempts is the option for NewRetryPolicyWithOptions that sets the maximum number of attempts.

func WithNextDuration

func WithNextDuration(nextDuration func(OCIOperationResponse) time.Duration) RetryPolicyOption

WithNextDuration is the option for NewRetryPolicyWithOptions that sets the function for computing the next backoff duration. It is preferred to use WithFixedBackoff or WithExponentialBackoff instead.

func WithShouldRetryOperation

func WithShouldRetryOperation(retryOperation func(OCIOperationResponse) bool) RetryPolicyOption

WithShouldRetryOperation is the option for NewRetryPolicyWithOptions that sets the function that checks whether retries should be performed.

func WithUnlimitedAttempts

func WithUnlimitedAttempts(maximumCumulativeBackoffWithoutJitter time.Duration) RetryPolicyOption

WithUnlimitedAttempts is the option for NewRetryPolicyWithOptions that sets unlimited number of attempts, but it needs to set a MaximumCumulativeBackoffWithoutJitter duration. If you use WithUnlimitedAttempts, you should set your own NextDuration function using WithNextDuration.

type SDKDate

type SDKDate struct {
	//Date date information
	Date time.Time
}

SDKDate a struct that parses/renders to/from json using only date information

func NewSDKDateFromString

func NewSDKDateFromString(dateString string) (*SDKDate, error)

NewSDKDateFromString parses the dateString into SDKDate

func (*SDKDate) MarshalJSON

func (t *SDKDate) MarshalJSON() (buff []byte, e error)

MarshalJSON marshals to JSON

func (*SDKDate) String

func (t *SDKDate) String() string

String returns string representation of SDKDate

func (*SDKDate) UnmarshalJSON

func (t *SDKDate) UnmarshalJSON(data []byte) (e error)

UnmarshalJSON unmarshals from json

type SDKTime

type SDKTime struct {
	time.Time
}

SDKTime a struct that parses/renders to/from json using RFC339 date-time information

func (*SDKTime) MarshalJSON

func (t *SDKTime) MarshalJSON() (buff []byte, e error)

MarshalJSON marshals to JSON

func (*SDKTime) UnmarshalJSON

func (t *SDKTime) UnmarshalJSON(data []byte) (e error)

UnmarshalJSON unmarshals from json

type ServiceError

type ServiceError interface {
	// The http status code of the error
	GetHTTPStatusCode() int

	// The human-readable error string as sent by the service
	GetMessage() string

	// A short error code that defines the error, meant for programmatic parsing.
	// See https://docs.cloud.oracle.com/Content/API/References/apierrors.htm
	GetCode() string

	// Unique Oracle-assigned identifier for the request.
	// If you need to contact Oracle about a particular request, please provide the request ID.
	GetOpcRequestID() string
}

ServiceError models all potential errors generated the service call

func IsServiceError

func IsServiceError(err error) (failure ServiceError, ok bool)

IsServiceError returns false if the error is not service side, otherwise true additionally it returns an interface representing the ServiceError

type ServiceErrorLocalizationMessage

type ServiceErrorLocalizationMessage interface {
	ServiceErrorRichInfo
	// The original error message string as sent by the service
	GetOriginalMessage() string

	// The values to be substituted into the originalMessageTemplate, expressed as a string-to-string map.
	GetMessageArgument() map[string]string

	// Template in ICU MessageFormat for the human-readable error string in English, but without the values replaced
	GetOriginalMessageTemplate() string
}

ServiceErrorLocalizationMessage models all potential errors generated the service call and has localized error message info

func IsServiceErrorLocalizationMessage

func IsServiceErrorLocalizationMessage(err error) (failure ServiceErrorLocalizationMessage, ok bool)

IsServiceErrorLocalizationMessage returns false if the error is not service side, otherwise true additionally it returns an interface representing the ServiceErrorOriginalMessage

type ServiceErrorRichInfo

type ServiceErrorRichInfo interface {
	ServiceError
	// The service this service call is sending to
	GetTargetService() string

	// The API name this service call is sending to
	GetOperationName() string

	// The timestamp when this request is made
	GetTimestamp() SDKTime

	// The endpoint and the Http method of this service call
	GetRequestTarget() string

	// The client version, in this case the oci go sdk version
	GetClientVersion() string

	// The API reference doc link for this API, optional and maybe empty
	GetOperationReferenceLink() string

	// Troubleshooting doc link
	GetErrorTroubleshootingLink() string
}

ServiceErrorRichInfo models all potential errors generated the service call and contains rich info for debugging purpose

func IsServiceErrorRichInfo

func IsServiceErrorRichInfo(err error) (failure ServiceErrorRichInfo, ok bool)

IsServiceErrorRichInfo returns false if the error is not service side or is not containing rich info, otherwise true additionally it returns an interface representing the ServiceErrorRichInfo

type SignerBodyHashPredicate

type SignerBodyHashPredicate func(r *http.Request) bool

SignerBodyHashPredicate a function that allows to disable/enable body hashing of requests and headers associated with body content

type SseReader

type SseReader struct {
	HttpBody io.ReadCloser

	OnClose func(r *SseReader)
	// contains filtered or unexported fields
}

func NewSSEReader

func NewSSEReader(response *http.Response) (*SseReader, error)

NewSSEReader returns an SSE Reader given an sse response

func (*SseReader) ReadAllEvents

func (r *SseReader) ReadAllEvents(eventHandler func(e []byte)) error

ReadAllEvents reads all events from the response stream, and processes each with given event handler

func (*SseReader) ReadNextEvent

func (r *SseReader) ReadNextEvent() (event []byte, err error)

ReadNextEvent reads the next event in the stream, return it unmarshalled

type StatErrCode

type StatErrCode struct {
	// contains filtered or unexported fields
}

StatErrCode is a type which wraps error's statusCode and errorCode from service end

type TLSConfigProvider

type TLSConfigProvider interface {
	NewOrDefault() (*tls.Config, error)
	WatchedFilesModified() bool
}

TLSConfigProvider is an interface the defines a function that creates a new *tls.Config.

func GetTLSConfigTemplateForTransport

func GetTLSConfigTemplateForTransport() TLSConfigProvider

GetTLSConfigTemplateForTransport returns the TLSConfigTemplate to used depending on whether any additional CA Bundle or client side certs have been configured

type TemplateParamForPerRealmEndpoint

type TemplateParamForPerRealmEndpoint struct {
	Template    string
	EndsWithDot bool
}

TemplateParamForPerRealmEndpoint is a template parameter for per-realm endpoint.

type TransportTemplateProvider

type TransportTemplateProvider func(tlsClientConfig *tls.Config) (http.RoundTripper, error)

TransportTemplateProvider defines a function that creates a new http transport from a given TLS client config.

func (TransportTemplateProvider) NewOrDefault

func (t TransportTemplateProvider) NewOrDefault(tlsClientConfig *tls.Config) (http.RoundTripper, error)

NewOrDefault creates a new TransportTemplate If t is nil, then DefaultTransport is returned

Directories

Path Synopsis
Package auth provides supporting functions and structs for authentication
Package auth provides supporting functions and structs for authentication

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL