runtime

package
v1.16.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2024 License: MIT Imports: 45 Imported by: 1,635

Documentation

Overview

Package runtime contains various facilities for creating requests and handling responses. The content is intended for SDK authors.

Index

Constants

View Source
const (
	// APIVersionLocationQueryParam indicates a query parameter
	APIVersionLocationQueryParam = 0
	// APIVersionLocationHeader indicates a header
	APIVersionLocationHeader = 1
)
View Source
const (
	// FinalStateViaAzureAsyncOp indicates the final payload comes from the Azure-AsyncOperation URL.
	FinalStateViaAzureAsyncOp = pollers.FinalStateViaAzureAsyncOp

	// FinalStateViaLocation indicates the final payload comes from the Location URL.
	FinalStateViaLocation = pollers.FinalStateViaLocation

	// FinalStateViaOriginalURI indicates the final payload comes from the original URL.
	FinalStateViaOriginalURI = pollers.FinalStateViaOriginalURI

	// FinalStateViaOpLocation indicates the final payload comes from the Operation-Location URL.
	FinalStateViaOpLocation = pollers.FinalStateViaOpLocation
)

Variables

This section is empty.

Functions

func DecodeByteArray

func DecodeByteArray(s string, v *[]byte, format Base64Encoding) error

DecodeByteArray will base-64 decode the provided string into v.

func Drain

func Drain(resp *http.Response)

Drain reads the response body to completion then closes it. The bytes read are discarded.

func EncodeByteArray

func EncodeByteArray(v []byte, format Base64Encoding) string

EncodeByteArray will base-64 encode the byte slice v.

func EncodeQueryParams added in v1.8.0

func EncodeQueryParams(u string) (string, error)

EncodeQueryParams will parse and encode any query parameters in the specified URL. Any semicolons will automatically be escaped.

func FetcherForNextLink(ctx context.Context, pl Pipeline, nextLink string, firstReq func(context.Context) (*policy.Request, error), options *FetcherForNextLinkOptions) (*http.Response, error)

FetcherForNextLink is a helper containing boilerplate code to simplify creating a PagingHandler[T].Fetcher from a next link URL.

  • ctx is the context.Context controlling the lifetime of the HTTP operation
  • pl is the Pipeline used to dispatch the HTTP request
  • nextLink is the URL used to fetch the next page. the empty string indicates the first page is to be requested
  • firstReq is the func to be called when creating the request for the first page
  • options contains any optional parameters, pass nil to accept the default values

func HasStatusCode

func HasStatusCode(resp *http.Response, statusCodes ...int) bool

HasStatusCode returns true if the Response's status code is one of the specified values.

func JoinPaths

func JoinPaths(root string, paths ...string) string

JoinPaths concatenates multiple URL path segments into one path, inserting path separation characters as required. JoinPaths will preserve query parameters in the root path

func MarshalAsByteArray

func MarshalAsByteArray(req *policy.Request, v []byte, format Base64Encoding) error

MarshalAsByteArray will base-64 encode the byte slice v, then calls SetBody. The encoded value is treated as a JSON string.

func MarshalAsJSON

func MarshalAsJSON(req *policy.Request, v any) error

MarshalAsJSON calls json.Marshal() to get the JSON encoding of v then calls SetBody.

func MarshalAsXML

func MarshalAsXML(req *policy.Request, v any) error

MarshalAsXML calls xml.Marshal() to get the XML encoding of v then calls SetBody.

func NewLogPolicy

func NewLogPolicy(o *policy.LogOptions) policy.Policy

NewLogPolicy creates a request/response logging policy object configured using the specified options. Pass nil to accept the default values; this is the same as passing a zero-value options.

func NewRequest

func NewRequest(ctx context.Context, httpMethod string, endpoint string) (*policy.Request, error)

NewRequest creates a new policy.Request with the specified input. The endpoint MUST be properly encoded before calling this function.

func NewRequestFromRequest added in v1.13.0

func NewRequestFromRequest(req *http.Request) (*policy.Request, error)

NewRequestFromRequest creates a new policy.Request with an existing *http.Request

func NewRequestIDPolicy added in v1.0.0

func NewRequestIDPolicy() policy.Policy

NewRequestIDPolicy returns a policy that add the x-ms-client-request-id header

func NewResponseError

func NewResponseError(resp *http.Response) error

NewResponseError creates an *azcore.ResponseError from the provided HTTP response. Call this when a service request returns a non-successful status code. The error code will be extracted from the *http.Response, either from the x-ms-error-code header (preferred) or attempted to be parsed from the response body.

func NewResponseErrorWithErrorCode added in v1.10.0

func NewResponseErrorWithErrorCode(resp *http.Response, errorCode string) error

NewResponseErrorWithErrorCode creates an *azcore.ResponseError from the provided HTTP response and errorCode. Use this variant when the error code is in a non-standard location.

func NewRetryPolicy

func NewRetryPolicy(o *policy.RetryOptions) policy.Policy

NewRetryPolicy creates a policy object configured using the specified options. Pass nil to accept the default values; this is the same as passing a zero-value options.

func NewTelemetryPolicy

func NewTelemetryPolicy(mod, ver string, o *policy.TelemetryOptions) policy.Policy

NewTelemetryPolicy creates a telemetry policy object that adds telemetry information to outgoing HTTP requests. The format is [<application_id> ]azsdk-go-<mod>/<ver> <platform_info>. Pass nil to accept the default values; this is the same as passing a zero-value options.

func NewUUID added in v1.12.0

func NewUUID() (string, error)

NewUUID returns a new UUID using the RFC4122 algorithm.

func Payload

func Payload(resp *http.Response) ([]byte, error)

Payload reads and returns the response body or an error. On a successful read, the response body is cached. Subsequent reads will access the cached value.

func SetMultipartFormData

func SetMultipartFormData(req *policy.Request, formData map[string]any) error

SetMultipartFormData writes the specified keys/values as multi-part form fields with the specified value. File content must be specified as an io.ReadSeekCloser or streaming.MultipartContent. Byte slices will be treated as JSON. All other values are treated as string values.

func SkipBodyDownload added in v0.21.0

func SkipBodyDownload(req *policy.Request)

SkipBodyDownload will disable automatic downloading of the response body.

func StartSpan added in v1.9.0

func StartSpan(ctx context.Context, name string, tracer tracing.Tracer, options *StartSpanOptions) (context.Context, func(error))

StartSpan starts a new tracing span. You must call the returned func to terminate the span. Pass the applicable error if the span will exit with an error condition.

  • ctx is the parent context of the newly created context
  • name is the name of the span. this is typically the fully qualified name of an API ("Client.Method")
  • tracer is the client's Tracer for creating spans
  • options contains optional values. pass nil to accept any default values

func UnmarshalAsByteArray

func UnmarshalAsByteArray(resp *http.Response, v *[]byte, format Base64Encoding) error

UnmarshalAsByteArray will base-64 decode the received payload and place the result into the value pointed to by v.

func UnmarshalAsJSON

func UnmarshalAsJSON(resp *http.Response, v any) error

UnmarshalAsJSON calls json.Unmarshal() to unmarshal the received payload into the value pointed to by v.

func UnmarshalAsXML

func UnmarshalAsXML(resp *http.Response, v any) error

UnmarshalAsXML calls xml.Unmarshal() to unmarshal the received payload into the value pointed to by v.

func WithCaptureResponse added in v0.22.0

func WithCaptureResponse(parent context.Context, resp **http.Response) context.Context

WithCaptureResponse applies the HTTP response retrieval annotation to the parent context. The resp parameter will contain the HTTP response after the request has completed. Deprecated: use policy.WithCaptureResponse instead.

func WithHTTPHeader added in v0.22.0

func WithHTTPHeader(parent context.Context, header http.Header) context.Context

WithHTTPHeader adds the specified http.Header to the parent context. Use this to specify custom HTTP headers at the API-call level. Any overlapping headers will have their values replaced with the values specified here. Deprecated: use policy.WithHTTPHeader instead.

func WithRetryOptions added in v0.22.0

func WithRetryOptions(parent context.Context, options policy.RetryOptions) context.Context

WithRetryOptions adds the specified RetryOptions to the parent context. Use this to specify custom RetryOptions at the API-call level. Deprecated: use policy.WithRetryOptions instead.

Types

type APIVersionLocation added in v1.2.0

type APIVersionLocation int

APIVersionLocation indicates which part of a request identifies the service version

type APIVersionOptions added in v1.2.0

type APIVersionOptions struct {
	// Location indicates where to set the version on a request, for example in a header or query param
	Location APIVersionLocation
	// Name is the name of the header or query parameter, for example "api-version"
	Name string
}

APIVersionOptions contains options for API versions

type Base64Encoding

type Base64Encoding = exported.Base64Encoding

Base64Encoding is usesd to specify which base-64 encoder/decoder to use when encoding/decoding a slice of bytes to/from a string.

const (
	// Base64StdFormat uses base64.StdEncoding for encoding and decoding payloads.
	Base64StdFormat Base64Encoding = exported.Base64StdFormat

	// Base64URLFormat uses base64.RawURLEncoding for encoding and decoding payloads.
	Base64URLFormat Base64Encoding = exported.Base64URLFormat
)

type BearerTokenPolicy added in v0.20.0

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

BearerTokenPolicy authorizes requests with bearer tokens acquired from a TokenCredential. It handles Continuous Access Evaluation (CAE) challenges. Clients needing to handle additional authentication challenges, or needing more control over authorization, should provide a policy.AuthorizationHandler in policy.BearerTokenOptions.

func NewBearerTokenPolicy added in v0.20.0

func NewBearerTokenPolicy(cred exported.TokenCredential, scopes []string, opts *policy.BearerTokenOptions) *BearerTokenPolicy

NewBearerTokenPolicy creates a policy object that authorizes requests with bearer tokens. cred: an azcore.TokenCredential implementation such as a credential object from azidentity scopes: the list of permission scopes required for the token. opts: optional settings. Pass nil to accept default values; this is the same as passing a zero-value options.

func (*BearerTokenPolicy) Do added in v0.20.0

Do authorizes a request with a bearer token

type CtxAPINameKey added in v1.9.0

type CtxAPINameKey = shared.CtxAPINameKey

CtxAPINameKey is used as a context key for adding/retrieving the API name.

type FetcherForNextLinkOptions added in v1.8.0

type FetcherForNextLinkOptions struct {
	// NextReq is the func to be called when requesting subsequent pages.
	// Used for paged operations that have a custom next link operation.
	NextReq func(context.Context, string) (*policy.Request, error)

	// StatusCodes contains additional HTTP status codes indicating success.
	// The default value is http.StatusOK.
	StatusCodes []int
}

FetcherForNextLinkOptions contains the optional values for FetcherForNextLink.

type FinalStateVia added in v0.23.0

type FinalStateVia = pollers.FinalStateVia

FinalStateVia is the enumerated type for the possible final-state-via values.

type KeyCredentialPolicy added in v1.8.0

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

KeyCredentialPolicy authorizes requests with a [azcore.KeyCredential].

func NewKeyCredentialPolicy added in v1.8.0

func NewKeyCredentialPolicy(cred *exported.KeyCredential, header string, options *KeyCredentialPolicyOptions) *KeyCredentialPolicy

NewKeyCredentialPolicy creates a new instance of KeyCredentialPolicy.

  • cred is the [azcore.KeyCredential] used to authenticate with the service
  • header is the name of the HTTP request header in which the key is placed
  • options contains optional configuration, pass nil to accept the default values

func (*KeyCredentialPolicy) Do added in v1.8.0

Do implementes the Do method on the policy.Polilcy interface.

type KeyCredentialPolicyOptions added in v1.8.0

type KeyCredentialPolicyOptions struct {
	// InsecureAllowCredentialWithHTTP enables authenticated requests over HTTP.
	// By default, authenticated requests to an HTTP endpoint are rejected by the client.
	// WARNING: setting this to true will allow sending the authentication key in clear text. Use with caution.
	InsecureAllowCredentialWithHTTP bool

	// Prefix is used if the key requires a prefix before it's inserted into the HTTP request.
	Prefix string
}

KeyCredentialPolicyOptions contains the optional values configuring KeyCredentialPolicy.

type NewPollerFromResumeTokenOptions added in v0.23.0

type NewPollerFromResumeTokenOptions[T any] struct {
	// Response contains a preconstructed response type.
	// The final payload will be unmarshaled into it and returned.
	Response *T

	// Handler[T] contains a custom polling implementation.
	Handler PollingHandler[T]

	// Tracer contains the Tracer from the client that's creating the Poller.
	Tracer tracing.Tracer
}

NewPollerFromResumeTokenOptions contains the optional parameters for NewPollerFromResumeToken.

type NewPollerOptions added in v0.23.0

type NewPollerOptions[T any] struct {
	// FinalStateVia contains the final-state-via value for the LRO.
	FinalStateVia FinalStateVia

	// Response contains a preconstructed response type.
	// The final payload will be unmarshaled into it and returned.
	Response *T

	// Handler[T] contains a custom polling implementation.
	Handler PollingHandler[T]

	// Tracer contains the Tracer from the client that's creating the Poller.
	Tracer tracing.Tracer
}

NewPollerOptions contains the optional parameters for NewPoller.

type Pager added in v0.23.0

type Pager[T any] struct {
	// contains filtered or unexported fields
}

Pager provides operations for iterating over paged responses.

func NewPager added in v0.23.0

func NewPager[T any](handler PagingHandler[T]) *Pager[T]

NewPager creates an instance of Pager using the specified PagingHandler. Pass a non-nil T for firstPage if the first page has already been retrieved.

func (*Pager[T]) More added in v0.23.0

func (p *Pager[T]) More() bool

More returns true if there are more pages to retrieve.

func (*Pager[T]) NextPage added in v0.23.0

func (p *Pager[T]) NextPage(ctx context.Context) (T, error)

NextPage advances the pager to the next page.

func (*Pager[T]) UnmarshalJSON added in v0.23.0

func (p *Pager[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Pager[T].

type PagingHandler added in v1.0.0

type PagingHandler[T any] struct {
	// More returns a boolean indicating if there are more pages to fetch.
	// It uses the provided page to make the determination.
	More func(T) bool

	// Fetcher fetches the first and subsequent pages.
	Fetcher func(context.Context, *T) (T, error)

	// Tracer contains the Tracer from the client that's creating the Pager.
	Tracer tracing.Tracer
}

PagingHandler contains the required data for constructing a Pager.

type Pipeline

type Pipeline = exported.Pipeline

Pipeline represents a primitive for sending HTTP requests and receiving responses. Its behavior can be extended by specifying policies during construction.

func NewPipeline

func NewPipeline(module, version string, plOpts PipelineOptions, options *policy.ClientOptions) Pipeline

NewPipeline creates a pipeline from connection options, with any additional policies as specified. Policies from ClientOptions are placed after policies from PipelineOptions. The module and version parameters are used by the telemetry policy, when enabled.

type PipelineOptions added in v0.21.0

type PipelineOptions struct {
	// AllowedHeaders is the slice of headers to log with their values intact.
	// All headers not in the slice will have their values REDACTED.
	// Applies to request and response headers.
	AllowedHeaders []string

	// AllowedQueryParameters is the slice of query parameters to log with their values intact.
	// All query parameters not in the slice will have their values REDACTED.
	AllowedQueryParameters []string

	// APIVersion overrides the default version requested of the service.
	// Set with caution as this package version has not been tested with arbitrary service versions.
	APIVersion APIVersionOptions

	// PerCall contains custom policies to inject into the pipeline.
	// Each policy is executed once per request.
	PerCall []policy.Policy

	// PerRetry contains custom policies to inject into the pipeline.
	// Each policy is executed once per request, and for each retry of that request.
	PerRetry []policy.Policy

	// Tracing contains options used to configure distributed tracing.
	Tracing TracingOptions
}

PipelineOptions contains Pipeline options for SDK developers

type PollUntilDoneOptions added in v1.0.0

type PollUntilDoneOptions struct {
	// Frequency is the time to wait between polling intervals in absence of a Retry-After header. Allowed minimum is one second.
	// Pass zero to accept the default value (30s).
	Frequency time.Duration
}

PollUntilDoneOptions contains the optional values for the Poller[T].PollUntilDone() method.

type Poller added in v0.23.0

type Poller[T any] struct {
	// contains filtered or unexported fields
}

Poller encapsulates a long-running operation, providing polling facilities until the operation reaches a terminal state.

func NewPoller

func NewPoller[T any](resp *http.Response, pl exported.Pipeline, options *NewPollerOptions[T]) (*Poller[T], error)

NewPoller creates a Poller based on the provided initial response.

func NewPollerFromResumeToken

func NewPollerFromResumeToken[T any](token string, pl exported.Pipeline, options *NewPollerFromResumeTokenOptions[T]) (*Poller[T], error)

NewPollerFromResumeToken creates a Poller from a resume token string.

func (*Poller[T]) Done added in v0.23.0

func (p *Poller[T]) Done() bool

Done returns true if the LRO has reached a terminal state. Once a terminal state is reached, call Result().

func (*Poller[T]) Poll added in v0.23.0

func (p *Poller[T]) Poll(ctx context.Context) (resp *http.Response, err error)

Poll fetches the latest state of the LRO. It returns an HTTP response or error. If Poll succeeds, the poller's state is updated and the HTTP response is returned. If Poll fails, the poller's state is unmodified and the error is returned. Calling Poll on an LRO that has reached a terminal state will return the last HTTP response.

func (*Poller[T]) PollUntilDone added in v0.23.0

func (p *Poller[T]) PollUntilDone(ctx context.Context, options *PollUntilDoneOptions) (res T, err error)

PollUntilDone will poll the service endpoint until a terminal state is reached, an error is received, or the context expires. It internally uses Poll(), Done(), and Result() in its polling loop, sleeping for the specified duration between intervals. options: pass nil to accept the default values. NOTE: the default polling frequency is 30 seconds which works well for most operations. However, some operations might benefit from a shorter or longer duration.

func (*Poller[T]) Result added in v0.23.0

func (p *Poller[T]) Result(ctx context.Context) (res T, err error)

Result returns the result of the LRO and is meant to be used in conjunction with Poll and Done. If the LRO completed successfully, a populated instance of T is returned. If the LRO failed or was canceled, an *azcore.ResponseError error is returned. Calling this on an LRO in a non-terminal state will return an error.

func (*Poller[T]) ResumeToken added in v0.23.0

func (p *Poller[T]) ResumeToken() (string, error)

ResumeToken returns a value representing the poller that can be used to resume the LRO at a later time. ResumeTokens are unique per service operation. The token's format should be considered opaque and is subject to change. Calling this on an LRO in a terminal state will return an error.

type PollingHandler added in v1.0.0

type PollingHandler[T any] interface {
	// Done returns true if the LRO has reached a terminal state.
	Done() bool

	// Poll fetches the latest state of the LRO.
	Poll(context.Context) (*http.Response, error)

	// Result is called once the LRO has reached a terminal state. It populates the out parameter
	// with the result of the operation.
	Result(ctx context.Context, out *T) error
}

PollingHandler[T] abstracts the differences among poller implementations.

type SASCredentialPolicy added in v1.8.0

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

SASCredentialPolicy authorizes requests with a [azcore.SASCredential].

func NewSASCredentialPolicy added in v1.8.0

func NewSASCredentialPolicy(cred *exported.SASCredential, header string, options *SASCredentialPolicyOptions) *SASCredentialPolicy

NewSASCredentialPolicy creates a new instance of SASCredentialPolicy.

  • cred is the [azcore.SASCredential] used to authenticate with the service
  • header is the name of the HTTP request header in which the shared access signature is placed
  • options contains optional configuration, pass nil to accept the default values

func (*SASCredentialPolicy) Do added in v1.8.0

Do implementes the Do method on the policy.Polilcy interface.

type SASCredentialPolicyOptions added in v1.8.0

type SASCredentialPolicyOptions struct {
	// InsecureAllowCredentialWithHTTP enables authenticated requests over HTTP.
	// By default, authenticated requests to an HTTP endpoint are rejected by the client.
	// WARNING: setting this to true will allow sending the authentication key in clear text. Use with caution.
	InsecureAllowCredentialWithHTTP bool
}

SASCredentialPolicyOptions contains the optional values configuring SASCredentialPolicy.

type StartSpanOptions added in v1.9.0

type StartSpanOptions struct {
	// Kind indicates the kind of Span.
	Kind tracing.SpanKind
	// Attributes contains key-value pairs of attributes for the span.
	Attributes []tracing.Attribute
}

StartSpanOptions contains the optional values for StartSpan.

type TracingOptions added in v1.9.0

type TracingOptions struct {
	// Namespace contains the value to use for the az.namespace span attribute.
	Namespace string
}

TracingOptions contains tracing options for SDK developers.

Jump to

Keyboard shortcuts

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