src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

api_client.go (30015B)


      1 // Code generated by smithy-go-codegen DO NOT EDIT.
      2 
      3 package signin
      4 
      5 import (
      6 	"context"
      7 	cryptorand "crypto/rand"
      8 	"errors"
      9 	"fmt"
     10 	"net"
     11 	"net/http"
     12 	"sync/atomic"
     13 	"time"
     14 
     15 	"github.com/aws/aws-sdk-go-v2/aws"
     16 	"github.com/aws/aws-sdk-go-v2/aws/defaults"
     17 	awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
     18 	"github.com/aws/aws-sdk-go-v2/aws/retry"
     19 	v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
     20 	awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
     21 	internalauth "github.com/aws/aws-sdk-go-v2/internal/auth"
     22 	internalauthsmithy "github.com/aws/aws-sdk-go-v2/internal/auth/smithy"
     23 	internalConfig "github.com/aws/aws-sdk-go-v2/internal/configsources"
     24 	smithy "github.com/aws/smithy-go"
     25 	smithydocument "github.com/aws/smithy-go/document"
     26 	"github.com/aws/smithy-go/logging"
     27 	"github.com/aws/smithy-go/metrics"
     28 	"github.com/aws/smithy-go/middleware"
     29 	smithyrand "github.com/aws/smithy-go/rand"
     30 	"github.com/aws/smithy-go/tracing"
     31 	smithyhttp "github.com/aws/smithy-go/transport/http"
     32 )
     33 
     34 const ServiceID = "Signin"
     35 const ServiceAPIVersion = "2023-01-01"
     36 
     37 type operationMetrics struct {
     38 	Duration                metrics.Float64Histogram
     39 	SerializeDuration       metrics.Float64Histogram
     40 	ResolveIdentityDuration metrics.Float64Histogram
     41 	ResolveEndpointDuration metrics.Float64Histogram
     42 	SignRequestDuration     metrics.Float64Histogram
     43 	DeserializeDuration     metrics.Float64Histogram
     44 }
     45 
     46 func (m *operationMetrics) histogramFor(name string) metrics.Float64Histogram {
     47 	switch name {
     48 	case "client.call.duration":
     49 		return m.Duration
     50 	case "client.call.serialization_duration":
     51 		return m.SerializeDuration
     52 	case "client.call.resolve_identity_duration":
     53 		return m.ResolveIdentityDuration
     54 	case "client.call.resolve_endpoint_duration":
     55 		return m.ResolveEndpointDuration
     56 	case "client.call.signing_duration":
     57 		return m.SignRequestDuration
     58 	case "client.call.deserialization_duration":
     59 		return m.DeserializeDuration
     60 	default:
     61 		panic("unrecognized operation metric")
     62 	}
     63 }
     64 
     65 func timeOperationMetric[T any](
     66 	ctx context.Context, metric string, fn func() (T, error),
     67 	opts ...metrics.RecordMetricOption,
     68 ) (T, error) {
     69 	mm := getOperationMetrics(ctx)
     70 	if mm == nil { // not using the metrics system
     71 		return fn()
     72 	}
     73 
     74 	instr := mm.histogramFor(metric)
     75 	opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...)
     76 
     77 	start := time.Now()
     78 	v, err := fn()
     79 	end := time.Now()
     80 
     81 	elapsed := end.Sub(start)
     82 	instr.Record(ctx, float64(elapsed)/1e9, opts...)
     83 	return v, err
     84 }
     85 
     86 func startMetricTimer(ctx context.Context, metric string, opts ...metrics.RecordMetricOption) func() {
     87 	mm := getOperationMetrics(ctx)
     88 	if mm == nil { // not using the metrics system
     89 		return func() {}
     90 	}
     91 
     92 	instr := mm.histogramFor(metric)
     93 	opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...)
     94 
     95 	var ended bool
     96 	start := time.Now()
     97 	return func() {
     98 		if ended {
     99 			return
    100 		}
    101 		ended = true
    102 
    103 		end := time.Now()
    104 
    105 		elapsed := end.Sub(start)
    106 		instr.Record(ctx, float64(elapsed)/1e9, opts...)
    107 	}
    108 }
    109 
    110 func withOperationMetadata(ctx context.Context) metrics.RecordMetricOption {
    111 	return func(o *metrics.RecordMetricOptions) {
    112 		o.Properties.Set("rpc.service", middleware.GetServiceID(ctx))
    113 		o.Properties.Set("rpc.method", middleware.GetOperationName(ctx))
    114 	}
    115 }
    116 
    117 type operationMetricsKey struct{}
    118 
    119 func withOperationMetrics(parent context.Context, mp metrics.MeterProvider) (context.Context, error) {
    120 	if _, ok := mp.(metrics.NopMeterProvider); ok {
    121 		// not using the metrics system - setting up the metrics context is a memory-intensive operation
    122 		// so we should skip it in this case
    123 		return parent, nil
    124 	}
    125 
    126 	meter := mp.Meter("github.com/aws/aws-sdk-go-v2/service/signin")
    127 	om := &operationMetrics{}
    128 
    129 	var err error
    130 
    131 	om.Duration, err = operationMetricTimer(meter, "client.call.duration",
    132 		"Overall call duration (including retries and time to send or receive request and response body)")
    133 	if err != nil {
    134 		return nil, err
    135 	}
    136 	om.SerializeDuration, err = operationMetricTimer(meter, "client.call.serialization_duration",
    137 		"The time it takes to serialize a message body")
    138 	if err != nil {
    139 		return nil, err
    140 	}
    141 	om.ResolveIdentityDuration, err = operationMetricTimer(meter, "client.call.auth.resolve_identity_duration",
    142 		"The time taken to acquire an identity (AWS credentials, bearer token, etc) from an Identity Provider")
    143 	if err != nil {
    144 		return nil, err
    145 	}
    146 	om.ResolveEndpointDuration, err = operationMetricTimer(meter, "client.call.resolve_endpoint_duration",
    147 		"The time it takes to resolve an endpoint (endpoint resolver, not DNS) for the request")
    148 	if err != nil {
    149 		return nil, err
    150 	}
    151 	om.SignRequestDuration, err = operationMetricTimer(meter, "client.call.auth.signing_duration",
    152 		"The time it takes to sign a request")
    153 	if err != nil {
    154 		return nil, err
    155 	}
    156 	om.DeserializeDuration, err = operationMetricTimer(meter, "client.call.deserialization_duration",
    157 		"The time it takes to deserialize a message body")
    158 	if err != nil {
    159 		return nil, err
    160 	}
    161 
    162 	return context.WithValue(parent, operationMetricsKey{}, om), nil
    163 }
    164 
    165 func operationMetricTimer(m metrics.Meter, name, desc string) (metrics.Float64Histogram, error) {
    166 	return m.Float64Histogram(name, func(o *metrics.InstrumentOptions) {
    167 		o.UnitLabel = "s"
    168 		o.Description = desc
    169 	})
    170 }
    171 
    172 func getOperationMetrics(ctx context.Context) *operationMetrics {
    173 	if v := ctx.Value(operationMetricsKey{}); v != nil {
    174 		return v.(*operationMetrics)
    175 	}
    176 	return nil
    177 }
    178 
    179 func operationTracer(p tracing.TracerProvider) tracing.Tracer {
    180 	return p.Tracer("github.com/aws/aws-sdk-go-v2/service/signin")
    181 }
    182 
    183 // Client provides the API client to make operations call for AWS Sign-In Service.
    184 type Client struct {
    185 	options Options
    186 
    187 	// Difference between the time reported by the server and the client
    188 	timeOffset *atomic.Int64
    189 }
    190 
    191 // New returns an initialized Client based on the functional options. Provide
    192 // additional functional options to further configure the behavior of the client,
    193 // such as changing the client's endpoint or adding custom middleware behavior.
    194 func New(options Options, optFns ...func(*Options)) *Client {
    195 	options = options.Copy()
    196 
    197 	resolveDefaultLogger(&options)
    198 
    199 	setResolvedDefaultsMode(&options)
    200 
    201 	resolveRetryer(&options)
    202 
    203 	resolveHTTPClient(&options)
    204 
    205 	resolveHTTPSignerV4(&options)
    206 
    207 	resolveIdempotencyTokenProvider(&options)
    208 
    209 	resolveEndpointResolverV2(&options)
    210 
    211 	resolveTracerProvider(&options)
    212 
    213 	resolveMeterProvider(&options)
    214 
    215 	resolveAuthSchemeResolver(&options)
    216 
    217 	for _, fn := range optFns {
    218 		fn(&options)
    219 	}
    220 
    221 	finalizeRetryMaxAttempts(&options)
    222 
    223 	ignoreAnonymousAuth(&options)
    224 
    225 	wrapWithAnonymousAuth(&options)
    226 
    227 	resolveAuthSchemes(&options)
    228 
    229 	client := &Client{
    230 		options: options,
    231 	}
    232 
    233 	initializeTimeOffsetResolver(client)
    234 
    235 	return client
    236 }
    237 
    238 // Options returns a copy of the client configuration.
    239 //
    240 // Callers SHOULD NOT perform mutations on any inner structures within client
    241 // config. Config overrides should instead be made on a per-operation basis through
    242 // functional options.
    243 func (c *Client) Options() Options {
    244 	return c.options.Copy()
    245 }
    246 
    247 func (c *Client) invokeOperation(
    248 	ctx context.Context, opID string, params interface{}, optFns []func(*Options), stackFns ...func(*middleware.Stack, Options) error,
    249 ) (
    250 	result interface{}, metadata middleware.Metadata, err error,
    251 ) {
    252 	ctx = middleware.ClearStackValues(ctx)
    253 	ctx = middleware.WithServiceID(ctx, ServiceID)
    254 	ctx = middleware.WithOperationName(ctx, opID)
    255 
    256 	stack := middleware.NewStack(opID, smithyhttp.NewStackRequest)
    257 	options := c.options.Copy()
    258 
    259 	for _, fn := range optFns {
    260 		fn(&options)
    261 	}
    262 
    263 	finalizeOperationRetryMaxAttempts(&options, *c)
    264 
    265 	finalizeClientEndpointResolverOptions(&options)
    266 
    267 	ctx = setLoggerContext(ctx, options, opID)
    268 
    269 	ctx = resolveServiceMetadata(ctx, options, opID)
    270 
    271 	if err := c.addCommonMiddlewares(stack, options, opID); err != nil {
    272 		return nil, metadata, err
    273 	}
    274 
    275 	for _, fn := range stackFns {
    276 		if err := fn(stack, options); err != nil {
    277 			return nil, metadata, err
    278 		}
    279 	}
    280 
    281 	for _, fn := range options.APIOptions {
    282 		if err := fn(stack); err != nil {
    283 			return nil, metadata, err
    284 		}
    285 	}
    286 
    287 	ctx, err = withOperationMetrics(ctx, options.MeterProvider)
    288 	if err != nil {
    289 		return nil, metadata, err
    290 	}
    291 
    292 	tracer := operationTracer(options.TracerProvider)
    293 	spanName := fmt.Sprintf("%s.%s", ServiceID, opID)
    294 
    295 	ctx = tracing.WithOperationTracer(ctx, tracer)
    296 
    297 	ctx, span := tracer.StartSpan(ctx, spanName, func(o *tracing.SpanOptions) {
    298 		o.Kind = tracing.SpanKindClient
    299 		o.Properties.Set("rpc.system", "aws-api")
    300 		o.Properties.Set("rpc.method", opID)
    301 		o.Properties.Set("rpc.service", ServiceID)
    302 	})
    303 	endTimer := startMetricTimer(ctx, "client.call.duration")
    304 	defer endTimer()
    305 	defer span.End()
    306 
    307 	handler := smithyhttp.NewClientHandlerWithOptions(options.HTTPClient, func(o *smithyhttp.ClientHandler) {
    308 		o.Meter = options.MeterProvider.Meter("github.com/aws/aws-sdk-go-v2/service/signin")
    309 	})
    310 	decorated := middleware.DecorateHandler(handler, stack)
    311 	result, metadata, err = decorated.Handle(ctx, params)
    312 	if err != nil {
    313 		span.SetProperty("exception.type", fmt.Sprintf("%T", err))
    314 		span.SetProperty("exception.message", err.Error())
    315 
    316 		var aerr smithy.APIError
    317 		if errors.As(err, &aerr) {
    318 			span.SetProperty("api.error_code", aerr.ErrorCode())
    319 			span.SetProperty("api.error_message", aerr.ErrorMessage())
    320 			span.SetProperty("api.error_fault", aerr.ErrorFault().String())
    321 		}
    322 
    323 		err = &smithy.OperationError{
    324 			ServiceID:     ServiceID,
    325 			OperationName: opID,
    326 			Err:           err,
    327 		}
    328 	}
    329 
    330 	span.SetProperty("error", err != nil)
    331 	if err == nil {
    332 		span.SetStatus(tracing.SpanStatusOK)
    333 	} else {
    334 		span.SetStatus(tracing.SpanStatusError)
    335 	}
    336 
    337 	return result, metadata, err
    338 }
    339 
    340 type operationInputKey struct{}
    341 
    342 func setOperationInput(ctx context.Context, input interface{}) context.Context {
    343 	return middleware.WithStackValue(ctx, operationInputKey{}, input)
    344 }
    345 
    346 func getOperationInput(ctx context.Context) interface{} {
    347 	return middleware.GetStackValue(ctx, operationInputKey{})
    348 }
    349 
    350 type setOperationInputMiddleware struct {
    351 }
    352 
    353 func (*setOperationInputMiddleware) ID() string {
    354 	return "setOperationInput"
    355 }
    356 
    357 func (m *setOperationInputMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) (
    358 	out middleware.SerializeOutput, metadata middleware.Metadata, err error,
    359 ) {
    360 	ctx = setOperationInput(ctx, in.Parameters)
    361 	return next.HandleSerialize(ctx, in)
    362 }
    363 
    364 func addProtocolFinalizerMiddlewares(stack *middleware.Stack, options Options, operation string) error {
    365 	if err := stack.Finalize.Add(&resolveAuthSchemeMiddleware{operation: operation, options: options}, middleware.Before); err != nil {
    366 		return fmt.Errorf("add ResolveAuthScheme: %w", err)
    367 	}
    368 	if err := stack.Finalize.Insert(&getIdentityMiddleware{options: options}, "ResolveAuthScheme", middleware.After); err != nil {
    369 		return fmt.Errorf("add GetIdentity: %v", err)
    370 	}
    371 	if err := stack.Finalize.Insert(&resolveEndpointV2Middleware{options: options}, "GetIdentity", middleware.After); err != nil {
    372 		return fmt.Errorf("add ResolveEndpointV2: %v", err)
    373 	}
    374 	if err := stack.Finalize.Insert(&signRequestMiddleware{options: options}, "ResolveEndpointV2", middleware.After); err != nil {
    375 		return fmt.Errorf("add Signing: %w", err)
    376 	}
    377 	return nil
    378 }
    379 
    380 func (c *Client) addCommonMiddlewares(stack *middleware.Stack, options Options, operation string) error {
    381 	if err := stack.Serialize.Add(&setOperationInputMiddleware{}, middleware.After); err != nil {
    382 		return err
    383 	}
    384 	if err := addProtocolFinalizerMiddlewares(stack, options, operation); err != nil {
    385 		return fmt.Errorf("add protocol finalizers: %v", err)
    386 	}
    387 	if err := addClientRequestID(stack); err != nil {
    388 		return err
    389 	}
    390 	if err := addRetry(stack, options, c); err != nil {
    391 		return err
    392 	}
    393 	if err := addRawResponseToMetadata(stack); err != nil {
    394 		return err
    395 	}
    396 	if err := addSpanRetryLoop(stack, options); err != nil {
    397 		return err
    398 	}
    399 	if err := addClientUserAgent(stack, options); err != nil {
    400 		return err
    401 	}
    402 	if err := addSetLegacyContextSigningOptionsMiddleware(stack); err != nil {
    403 		return err
    404 	}
    405 	if err := addUserAgentRetryMode(stack, options); err != nil {
    406 		return err
    407 	}
    408 	if err := addRecursionDetection(stack); err != nil {
    409 		return err
    410 	}
    411 	if err := addInterceptBeforeRetryLoop(stack, options); err != nil {
    412 		return err
    413 	}
    414 	if err := addInterceptAttempt(stack, options); err != nil {
    415 		return err
    416 	}
    417 	return nil
    418 }
    419 func resolveAuthSchemeResolver(options *Options) {
    420 	if options.AuthSchemeResolver == nil {
    421 		options.AuthSchemeResolver = &defaultAuthSchemeResolver{}
    422 	}
    423 }
    424 
    425 func resolveAuthSchemes(options *Options) {
    426 	if options.AuthSchemes == nil {
    427 		options.AuthSchemes = []smithyhttp.AuthScheme{
    428 			internalauth.NewHTTPAuthScheme("aws.auth#sigv4", &internalauthsmithy.V4SignerAdapter{
    429 				Signer:     options.HTTPSignerV4,
    430 				Logger:     options.Logger,
    431 				LogSigning: options.ClientLogMode.IsSigning(),
    432 			}),
    433 		}
    434 	}
    435 }
    436 
    437 type noSmithyDocumentSerde = smithydocument.NoSerde
    438 
    439 func resolveDefaultLogger(o *Options) {
    440 	if o.Logger != nil {
    441 		return
    442 	}
    443 	o.Logger = logging.Nop{}
    444 }
    445 
    446 func setLoggerContext(ctx context.Context, options Options, operation string) context.Context {
    447 	_ = operation
    448 	return middleware.SetLogger(ctx, options.Logger)
    449 }
    450 
    451 func setResolvedDefaultsMode(o *Options) {
    452 	if len(o.resolvedDefaultsMode) > 0 {
    453 		return
    454 	}
    455 
    456 	var mode aws.DefaultsMode
    457 	mode.SetFromString(string(o.DefaultsMode))
    458 
    459 	if mode == aws.DefaultsModeAuto {
    460 		mode = defaults.ResolveDefaultsModeAuto(o.Region, o.RuntimeEnvironment)
    461 	}
    462 
    463 	o.resolvedDefaultsMode = mode
    464 }
    465 
    466 // NewFromConfig returns a new client from the provided config.
    467 func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client {
    468 	opts := Options{
    469 		Region:                     cfg.Region,
    470 		DefaultsMode:               cfg.DefaultsMode,
    471 		RuntimeEnvironment:         cfg.RuntimeEnvironment,
    472 		HTTPClient:                 cfg.HTTPClient,
    473 		Credentials:                cfg.Credentials,
    474 		APIOptions:                 cfg.APIOptions,
    475 		Logger:                     cfg.Logger,
    476 		ClientLogMode:              cfg.ClientLogMode,
    477 		AppID:                      cfg.AppID,
    478 		DisableClockSkewCorrection: cfg.DisableClockSkewCorrection,
    479 		AuthSchemePreference:       cfg.AuthSchemePreference,
    480 	}
    481 	resolveAWSRetryerProvider(cfg, &opts)
    482 	resolveAWSRetryMaxAttempts(cfg, &opts)
    483 	resolveAWSRetryMode(cfg, &opts)
    484 	resolveAWSEndpointResolver(cfg, &opts)
    485 	resolveInterceptors(cfg, &opts)
    486 	resolveUseDualStackEndpoint(cfg, &opts)
    487 	resolveUseFIPSEndpoint(cfg, &opts)
    488 	resolveBaseEndpoint(cfg, &opts)
    489 	return New(opts, func(o *Options) {
    490 		for _, opt := range cfg.ServiceOptions {
    491 			opt(ServiceID, o)
    492 		}
    493 		for _, opt := range optFns {
    494 			opt(o)
    495 		}
    496 	})
    497 }
    498 
    499 func resolveHTTPClient(o *Options) {
    500 	var buildable *awshttp.BuildableClient
    501 
    502 	if o.HTTPClient != nil {
    503 		var ok bool
    504 		buildable, ok = o.HTTPClient.(*awshttp.BuildableClient)
    505 		if !ok {
    506 			return
    507 		}
    508 	} else {
    509 		buildable = awshttp.NewBuildableClient()
    510 	}
    511 
    512 	modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode)
    513 	if err == nil {
    514 		buildable = buildable.WithDialerOptions(func(dialer *net.Dialer) {
    515 			if dialerTimeout, ok := modeConfig.GetConnectTimeout(); ok {
    516 				dialer.Timeout = dialerTimeout
    517 			}
    518 		})
    519 
    520 		buildable = buildable.WithTransportOptions(func(transport *http.Transport) {
    521 			if tlsHandshakeTimeout, ok := modeConfig.GetTLSNegotiationTimeout(); ok {
    522 				transport.TLSHandshakeTimeout = tlsHandshakeTimeout
    523 			}
    524 		})
    525 	}
    526 
    527 	o.HTTPClient = buildable
    528 }
    529 
    530 func resolveRetryer(o *Options) {
    531 	if o.Retryer != nil {
    532 		return
    533 	}
    534 
    535 	if len(o.RetryMode) == 0 {
    536 		modeConfig, err := defaults.GetModeConfiguration(o.resolvedDefaultsMode)
    537 		if err == nil {
    538 			o.RetryMode = modeConfig.RetryMode
    539 		}
    540 	}
    541 	if len(o.RetryMode) == 0 {
    542 		o.RetryMode = aws.RetryModeStandard
    543 	}
    544 
    545 	var standardOptions []func(*retry.StandardOptions)
    546 	if v := o.RetryMaxAttempts; v != 0 {
    547 		standardOptions = append(standardOptions, func(so *retry.StandardOptions) {
    548 			so.MaxAttempts = v
    549 		})
    550 	}
    551 
    552 	switch o.RetryMode {
    553 	case aws.RetryModeAdaptive:
    554 		var adaptiveOptions []func(*retry.AdaptiveModeOptions)
    555 		if len(standardOptions) != 0 {
    556 			adaptiveOptions = append(adaptiveOptions, func(ao *retry.AdaptiveModeOptions) {
    557 				ao.StandardOptions = append(ao.StandardOptions, standardOptions...)
    558 			})
    559 		}
    560 		o.Retryer = retry.NewAdaptiveMode(adaptiveOptions...)
    561 
    562 	default:
    563 		o.Retryer = retry.NewStandard(standardOptions...)
    564 	}
    565 }
    566 
    567 func resolveAWSRetryerProvider(cfg aws.Config, o *Options) {
    568 	if cfg.Retryer == nil {
    569 		return
    570 	}
    571 	o.Retryer = cfg.Retryer()
    572 }
    573 
    574 func resolveAWSRetryMode(cfg aws.Config, o *Options) {
    575 	if len(cfg.RetryMode) == 0 {
    576 		return
    577 	}
    578 	o.RetryMode = cfg.RetryMode
    579 }
    580 func resolveAWSRetryMaxAttempts(cfg aws.Config, o *Options) {
    581 	if cfg.RetryMaxAttempts == 0 {
    582 		return
    583 	}
    584 	o.RetryMaxAttempts = cfg.RetryMaxAttempts
    585 }
    586 
    587 func finalizeRetryMaxAttempts(o *Options) {
    588 	if o.RetryMaxAttempts == 0 {
    589 		return
    590 	}
    591 
    592 	o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts)
    593 }
    594 
    595 func finalizeOperationRetryMaxAttempts(o *Options, client Client) {
    596 	if v := o.RetryMaxAttempts; v == 0 || v == client.options.RetryMaxAttempts {
    597 		return
    598 	}
    599 
    600 	o.Retryer = retry.AddWithMaxAttempts(o.Retryer, o.RetryMaxAttempts)
    601 }
    602 
    603 func resolveAWSEndpointResolver(cfg aws.Config, o *Options) {
    604 	if cfg.EndpointResolver == nil && cfg.EndpointResolverWithOptions == nil {
    605 		return
    606 	}
    607 	o.EndpointResolver = withEndpointResolver(cfg.EndpointResolver, cfg.EndpointResolverWithOptions)
    608 }
    609 
    610 func resolveInterceptors(cfg aws.Config, o *Options) {
    611 	o.Interceptors = cfg.Interceptors.Copy()
    612 }
    613 
    614 func addClientUserAgent(stack *middleware.Stack, options Options) error {
    615 	ua, err := getOrAddRequestUserAgent(stack)
    616 	if err != nil {
    617 		return err
    618 	}
    619 
    620 	ua.AddSDKAgentKeyValue(awsmiddleware.APIMetadata, "signin", goModuleVersion)
    621 	if len(options.AppID) > 0 {
    622 		ua.AddSDKAgentKey(awsmiddleware.ApplicationIdentifier, options.AppID)
    623 	}
    624 
    625 	return nil
    626 }
    627 
    628 func getOrAddRequestUserAgent(stack *middleware.Stack) (*awsmiddleware.RequestUserAgent, error) {
    629 	id := (*awsmiddleware.RequestUserAgent)(nil).ID()
    630 	mw, ok := stack.Build.Get(id)
    631 	if !ok {
    632 		mw = awsmiddleware.NewRequestUserAgent()
    633 		if err := stack.Build.Add(mw, middleware.After); err != nil {
    634 			return nil, err
    635 		}
    636 	}
    637 
    638 	ua, ok := mw.(*awsmiddleware.RequestUserAgent)
    639 	if !ok {
    640 		return nil, fmt.Errorf("%T for %s middleware did not match expected type", mw, id)
    641 	}
    642 
    643 	return ua, nil
    644 }
    645 
    646 type HTTPSignerV4 interface {
    647 	SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time, optFns ...func(*v4.SignerOptions)) error
    648 }
    649 
    650 func resolveHTTPSignerV4(o *Options) {
    651 	if o.HTTPSignerV4 != nil {
    652 		return
    653 	}
    654 	o.HTTPSignerV4 = newDefaultV4Signer(*o)
    655 }
    656 
    657 func newDefaultV4Signer(o Options) *v4.Signer {
    658 	return v4.NewSigner(func(so *v4.SignerOptions) {
    659 		so.Logger = o.Logger
    660 		so.LogSigning = o.ClientLogMode.IsSigning()
    661 	})
    662 }
    663 
    664 func addClientRequestID(stack *middleware.Stack) error {
    665 	return stack.Build.Add(&awsmiddleware.ClientRequestID{}, middleware.After)
    666 }
    667 
    668 func addComputeContentLength(stack *middleware.Stack) error {
    669 	return stack.Build.Insert(&smithyhttp.ComputeContentLength{}, "ClientRequestID", middleware.After)
    670 }
    671 
    672 func addRawResponseToMetadata(stack *middleware.Stack) error {
    673 	return stack.Deserialize.Add(&awsmiddleware.AddRawResponse{}, middleware.Before)
    674 }
    675 
    676 func addRecordResponseTiming(stack *middleware.Stack, options Options) error {
    677 	return stack.Deserialize.Add(&awsmiddleware.RecordResponseTiming{
    678 		DisableClockSkewCorrection: options.DisableClockSkewCorrection,
    679 	}, middleware.After)
    680 }
    681 
    682 func addSpanRetryLoop(stack *middleware.Stack, options Options) error {
    683 	return stack.Finalize.Insert(&spanRetryLoop{options: options}, "Retry", middleware.Before)
    684 }
    685 
    686 type spanRetryLoop struct {
    687 	options Options
    688 }
    689 
    690 func (*spanRetryLoop) ID() string {
    691 	return "spanRetryLoop"
    692 }
    693 
    694 func (m *spanRetryLoop) HandleFinalize(
    695 	ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler,
    696 ) (
    697 	middleware.FinalizeOutput, middleware.Metadata, error,
    698 ) {
    699 	tracer := operationTracer(m.options.TracerProvider)
    700 	ctx, span := tracer.StartSpan(ctx, "RetryLoop")
    701 	defer span.End()
    702 
    703 	return next.HandleFinalize(ctx, in)
    704 }
    705 func addStreamingEventsPayload(stack *middleware.Stack) error {
    706 	return stack.Finalize.Add(&v4.StreamingEventsPayload{}, middleware.Before)
    707 }
    708 
    709 func addUnsignedPayload(stack *middleware.Stack) error {
    710 	return stack.Finalize.Insert(&v4.UnsignedPayload{}, "ResolveEndpointV2", middleware.After)
    711 }
    712 
    713 func addComputePayloadSHA256(stack *middleware.Stack) error {
    714 	return stack.Finalize.Insert(&v4.ComputePayloadSHA256{}, "ResolveEndpointV2", middleware.After)
    715 }
    716 
    717 func addContentSHA256Header(stack *middleware.Stack) error {
    718 	return stack.Finalize.Insert(&v4.ContentSHA256Header{}, (*v4.ComputePayloadSHA256)(nil).ID(), middleware.After)
    719 }
    720 
    721 func addIsWaiterUserAgent(o *Options) {
    722 	o.APIOptions = append(o.APIOptions, func(stack *middleware.Stack) error {
    723 		ua, err := getOrAddRequestUserAgent(stack)
    724 		if err != nil {
    725 			return err
    726 		}
    727 
    728 		ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureWaiter)
    729 		return nil
    730 	})
    731 }
    732 
    733 func addIsPaginatorUserAgent(o *Options) {
    734 	o.APIOptions = append(o.APIOptions, func(stack *middleware.Stack) error {
    735 		ua, err := getOrAddRequestUserAgent(stack)
    736 		if err != nil {
    737 			return err
    738 		}
    739 
    740 		ua.AddUserAgentFeature(awsmiddleware.UserAgentFeaturePaginator)
    741 		return nil
    742 	})
    743 }
    744 
    745 func resolveIdempotencyTokenProvider(o *Options) {
    746 	if o.IdempotencyTokenProvider != nil {
    747 		return
    748 	}
    749 	o.IdempotencyTokenProvider = smithyrand.NewUUIDIdempotencyToken(cryptorand.Reader)
    750 }
    751 
    752 func addRetry(stack *middleware.Stack, o Options, c *Client) error {
    753 	attempt := retry.NewAttemptMiddleware(o.Retryer, smithyhttp.RequestCloner, func(m *retry.Attempt) {
    754 		m.LogAttempts = o.ClientLogMode.IsRetries()
    755 		m.OperationMeter = o.MeterProvider.Meter("github.com/aws/aws-sdk-go-v2/service/signin")
    756 		m.ClientSkew = c.timeOffset
    757 		m.DisableClockSkewCorrection = o.DisableClockSkewCorrection
    758 	})
    759 	if err := stack.Finalize.Insert(attempt, "ResolveAuthScheme", middleware.Before); err != nil {
    760 		return err
    761 	}
    762 	if err := stack.Finalize.Insert(&retry.MetricsHeader{}, attempt.ID(), middleware.After); err != nil {
    763 		return err
    764 	}
    765 	return nil
    766 }
    767 
    768 // resolves dual-stack endpoint configuration
    769 func resolveUseDualStackEndpoint(cfg aws.Config, o *Options) error {
    770 	if len(cfg.ConfigSources) == 0 {
    771 		return nil
    772 	}
    773 	value, found, err := internalConfig.ResolveUseDualStackEndpoint(context.Background(), cfg.ConfigSources)
    774 	if err != nil {
    775 		return err
    776 	}
    777 	if found {
    778 		o.EndpointOptions.UseDualStackEndpoint = value
    779 	}
    780 	return nil
    781 }
    782 
    783 // resolves FIPS endpoint configuration
    784 func resolveUseFIPSEndpoint(cfg aws.Config, o *Options) error {
    785 	if len(cfg.ConfigSources) == 0 {
    786 		return nil
    787 	}
    788 	value, found, err := internalConfig.ResolveUseFIPSEndpoint(context.Background(), cfg.ConfigSources)
    789 	if err != nil {
    790 		return err
    791 	}
    792 	if found {
    793 		o.EndpointOptions.UseFIPSEndpoint = value
    794 	}
    795 	return nil
    796 }
    797 
    798 func initializeTimeOffsetResolver(c *Client) {
    799 	c.timeOffset = new(atomic.Int64)
    800 }
    801 
    802 func addUserAgentRetryMode(stack *middleware.Stack, options Options) error {
    803 	ua, err := getOrAddRequestUserAgent(stack)
    804 	if err != nil {
    805 		return err
    806 	}
    807 
    808 	switch options.Retryer.(type) {
    809 	case *retry.Standard:
    810 		ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureRetryModeStandard)
    811 	case *retry.AdaptiveMode:
    812 		ua.AddUserAgentFeature(awsmiddleware.UserAgentFeatureRetryModeAdaptive)
    813 	}
    814 	return nil
    815 }
    816 
    817 type setCredentialSourceMiddleware struct {
    818 	ua      *awsmiddleware.RequestUserAgent
    819 	options Options
    820 }
    821 
    822 func (m setCredentialSourceMiddleware) ID() string { return "SetCredentialSourceMiddleware" }
    823 
    824 func (m setCredentialSourceMiddleware) HandleBuild(ctx context.Context, in middleware.BuildInput, next middleware.BuildHandler) (
    825 	out middleware.BuildOutput, metadata middleware.Metadata, err error,
    826 ) {
    827 	asProviderSource, ok := m.options.Credentials.(aws.CredentialProviderSource)
    828 	if !ok {
    829 		return next.HandleBuild(ctx, in)
    830 	}
    831 	providerSources := asProviderSource.ProviderSources()
    832 	for _, source := range providerSources {
    833 		m.ua.AddCredentialsSource(source)
    834 	}
    835 	return next.HandleBuild(ctx, in)
    836 }
    837 
    838 func addCredentialSource(stack *middleware.Stack, options Options) error {
    839 	ua, err := getOrAddRequestUserAgent(stack)
    840 	if err != nil {
    841 		return err
    842 	}
    843 
    844 	mw := setCredentialSourceMiddleware{ua: ua, options: options}
    845 	return stack.Build.Insert(&mw, "UserAgent", middleware.Before)
    846 }
    847 
    848 func resolveTracerProvider(options *Options) {
    849 	if options.TracerProvider == nil {
    850 		options.TracerProvider = &tracing.NopTracerProvider{}
    851 	}
    852 }
    853 
    854 func resolveMeterProvider(options *Options) {
    855 	if options.MeterProvider == nil {
    856 		options.MeterProvider = metrics.NopMeterProvider{}
    857 	}
    858 }
    859 
    860 // IdempotencyTokenProvider interface for providing idempotency token
    861 type IdempotencyTokenProvider interface {
    862 	GetIdempotencyToken() (string, error)
    863 }
    864 
    865 func resolveServiceMetadata(ctx context.Context, options Options, operation string) context.Context {
    866 	ctx = awsmiddleware.SetServiceID(ctx, ServiceID)
    867 	if options.Region != "" {
    868 		ctx = awsmiddleware.SetRegion(ctx, options.Region)
    869 	}
    870 	ctx = awsmiddleware.SetOperationName(ctx, operation)
    871 	if options.EndpointResolver != nil {
    872 		ctx = awsmiddleware.SetRequiresLegacyEndpoints(ctx, true)
    873 	}
    874 	return ctx
    875 }
    876 
    877 func addRecursionDetection(stack *middleware.Stack) error {
    878 	return stack.Build.Add(&awsmiddleware.RecursionDetection{}, middleware.After)
    879 }
    880 
    881 func addRequestIDRetrieverMiddleware(stack *middleware.Stack) error {
    882 	return stack.Deserialize.Insert(&awsmiddleware.RequestIDRetriever{}, "OperationDeserializer", middleware.Before)
    883 
    884 }
    885 
    886 func addResponseErrorMiddleware(stack *middleware.Stack) error {
    887 	return stack.Deserialize.Insert(&awshttp.ResponseErrorWrapper{}, "RequestIDRetriever", middleware.Before)
    888 
    889 }
    890 
    891 func addRequestResponseLogging(stack *middleware.Stack, o Options) error {
    892 	return stack.Deserialize.Add(&smithyhttp.RequestResponseLogger{
    893 		LogRequest:          o.ClientLogMode.IsRequest(),
    894 		LogRequestWithBody:  o.ClientLogMode.IsRequestWithBody(),
    895 		LogResponse:         o.ClientLogMode.IsResponse(),
    896 		LogResponseWithBody: o.ClientLogMode.IsResponseWithBody(),
    897 	}, middleware.After)
    898 }
    899 
    900 type disableHTTPSMiddleware struct {
    901 	DisableHTTPS bool
    902 }
    903 
    904 func (*disableHTTPSMiddleware) ID() string {
    905 	return "disableHTTPS"
    906 }
    907 
    908 func (m *disableHTTPSMiddleware) HandleFinalize(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) (
    909 	out middleware.FinalizeOutput, metadata middleware.Metadata, err error,
    910 ) {
    911 	req, ok := in.Request.(*smithyhttp.Request)
    912 	if !ok {
    913 		return out, metadata, fmt.Errorf("unknown transport type %T", in.Request)
    914 	}
    915 
    916 	if m.DisableHTTPS && !smithyhttp.GetHostnameImmutable(ctx) {
    917 		req.URL.Scheme = "http"
    918 	}
    919 
    920 	return next.HandleFinalize(ctx, in)
    921 }
    922 
    923 func addDisableHTTPSMiddleware(stack *middleware.Stack, o Options) error {
    924 	return stack.Finalize.Insert(&disableHTTPSMiddleware{
    925 		DisableHTTPS: o.EndpointOptions.DisableHTTPS,
    926 	}, "ResolveEndpointV2", middleware.After)
    927 }
    928 
    929 func addInterceptBeforeRetryLoop(stack *middleware.Stack, opts Options) error {
    930 	return stack.Finalize.Insert(&smithyhttp.InterceptBeforeRetryLoop{
    931 		Interceptors: opts.Interceptors.BeforeRetryLoop,
    932 	}, "Retry", middleware.Before)
    933 }
    934 
    935 func addInterceptAttempt(stack *middleware.Stack, opts Options) error {
    936 	return stack.Finalize.Insert(&smithyhttp.InterceptAttempt{
    937 		BeforeAttempt: opts.Interceptors.BeforeAttempt,
    938 		AfterAttempt:  opts.Interceptors.AfterAttempt,
    939 	}, "Retry", middleware.After)
    940 }
    941 
    942 func addInterceptors(stack *middleware.Stack, opts Options) error {
    943 	// middlewares are expensive, don't add all of these interceptor ones unless the caller
    944 	// actually has at least one interceptor configured
    945 	//
    946 	// at the moment it's all-or-nothing because some of the middlewares here are responsible for
    947 	// setting fields in the interceptor context for future ones
    948 	if len(opts.Interceptors.BeforeExecution) == 0 &&
    949 		len(opts.Interceptors.BeforeSerialization) == 0 && len(opts.Interceptors.AfterSerialization) == 0 &&
    950 		len(opts.Interceptors.BeforeRetryLoop) == 0 &&
    951 		len(opts.Interceptors.BeforeAttempt) == 0 &&
    952 		len(opts.Interceptors.BeforeSigning) == 0 && len(opts.Interceptors.AfterSigning) == 0 &&
    953 		len(opts.Interceptors.BeforeTransmit) == 0 && len(opts.Interceptors.AfterTransmit) == 0 &&
    954 		len(opts.Interceptors.BeforeDeserialization) == 0 && len(opts.Interceptors.AfterDeserialization) == 0 &&
    955 		len(opts.Interceptors.AfterAttempt) == 0 && len(opts.Interceptors.AfterExecution) == 0 {
    956 		return nil
    957 	}
    958 
    959 	return errors.Join(
    960 		stack.Initialize.Add(&smithyhttp.InterceptExecution{
    961 			BeforeExecution: opts.Interceptors.BeforeExecution,
    962 			AfterExecution:  opts.Interceptors.AfterExecution,
    963 		}, middleware.Before),
    964 		stack.Serialize.Insert(&smithyhttp.InterceptBeforeSerialization{
    965 			Interceptors: opts.Interceptors.BeforeSerialization,
    966 		}, "OperationSerializer", middleware.Before),
    967 		stack.Serialize.Insert(&smithyhttp.InterceptAfterSerialization{
    968 			Interceptors: opts.Interceptors.AfterSerialization,
    969 		}, "OperationSerializer", middleware.After),
    970 		stack.Finalize.Insert(&smithyhttp.InterceptBeforeSigning{
    971 			Interceptors: opts.Interceptors.BeforeSigning,
    972 		}, "Signing", middleware.Before),
    973 		stack.Finalize.Insert(&smithyhttp.InterceptAfterSigning{
    974 			Interceptors: opts.Interceptors.AfterSigning,
    975 		}, "Signing", middleware.After),
    976 		stack.Deserialize.Add(&smithyhttp.InterceptTransmit{
    977 			BeforeTransmit: opts.Interceptors.BeforeTransmit,
    978 			AfterTransmit:  opts.Interceptors.AfterTransmit,
    979 		}, middleware.After),
    980 		stack.Deserialize.Insert(&smithyhttp.InterceptBeforeDeserialization{
    981 			Interceptors: opts.Interceptors.BeforeDeserialization,
    982 		}, "OperationDeserializer", middleware.After), // (deserialize stack is called in reverse)
    983 		stack.Deserialize.Insert(&smithyhttp.InterceptAfterDeserialization{
    984 			Interceptors: opts.Interceptors.AfterDeserialization,
    985 		}, "OperationDeserializer", middleware.Before),
    986 	)
    987 }