-
Notifications
You must be signed in to change notification settings - Fork 641
/
api_client.go
356 lines (292 loc) · 10.9 KB
/
api_client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
// Code generated by smithy-go-codegen DO NOT EDIT.
package s3
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/retry"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
acceptencodingcust "github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding"
"github.com/aws/aws-sdk-go-v2/service/internal/s3shared"
s3cust "github.com/aws/aws-sdk-go-v2/service/s3/internal/customizations"
smithy "github.com/awslabs/smithy-go"
"github.com/awslabs/smithy-go/logging"
"github.com/awslabs/smithy-go/middleware"
smithyhttp "github.com/awslabs/smithy-go/transport/http"
"net/http"
"time"
)
const ServiceID = "S3"
const ServiceAPIVersion = "2006-03-01"
// Client provides the API client to make operations call for Amazon Simple Storage
// Service.
type Client struct {
options Options
}
// New returns an initialized Client based on the functional options. Provide
// additional functional options to further configure the behavior of the client,
// such as changing the client's endpoint or adding custom middleware behavior.
func New(options Options, optFns ...func(*Options)) *Client {
options = options.Copy()
resolveDefaultLogger(&options)
resolveRetryer(&options)
resolveHTTPClient(&options)
resolveHTTPSignerV4(&options)
resolveDefaultEndpointConfiguration(&options)
for _, fn := range optFns {
fn(&options)
}
client := &Client{
options: options,
}
return client
}
type Options struct {
// Set of options to modify how an operation is invoked. These apply to all
// operations invoked for this client. Use functional options on operation call to
// modify this list for per operation behavior.
APIOptions []func(*middleware.Stack) error
// Configures the events that will be sent to the configured logger.
ClientLogMode aws.ClientLogMode
// The credentials object to use when signing requests.
Credentials aws.CredentialsProvider
// The endpoint options to be used when attempting to resolve an endpoint.
EndpointOptions EndpointResolverOptions
// The service endpoint resolver.
EndpointResolver EndpointResolver
// Signature Version 4 (SigV4) Signer
HTTPSignerV4 HTTPSignerV4
// The logger writer interface to write logging messages to.
Logger logging.Logger
// The region to send requests to. (Required)
Region string
// Retryer guides how HTTP requests should be retried in case of recoverable
// failures. When nil the API client will use a default retryer.
Retryer retry.Retryer
// Allows you to enable arn region support for the service.
UseARNRegion bool
// Allows you to enable S3 Accelerate feature. All operations compatible with S3
// Accelerate will use the accelerate endpoint for requests. Requests not
// compatible will fall back to normal S3 requests. The bucket must be enabled for
// accelerate to be used with S3 client with accelerate enabled. If the bucket is
// not enabled for accelerate an error will be returned. The bucket name must be
// DNS compatible to work with accelerate.
UseAccelerate bool
// Allows you to enable Dualstack endpoint support for the service.
UseDualstack bool
// Allows you to enable the client to use path-style addressing, i.e.,
// https://s3.amazonaws.com/BUCKET/KEY. By default, the S3 client will use virtual
// hosted bucket addressing when possible(https://BUCKET.s3.amazonaws.com/KEY).
UsePathStyle bool
// The HTTP client to invoke API calls with. Defaults to client's default HTTP
// implementation if nil.
HTTPClient HTTPClient
}
type HTTPClient interface {
Do(*http.Request) (*http.Response, error)
}
// Copy creates a clone where the APIOptions list is deep copied.
func (o Options) Copy() Options {
to := o
to.APIOptions = make([]func(*middleware.Stack) error, len(o.APIOptions))
copy(to.APIOptions, o.APIOptions)
return to
}
func (c *Client) invokeOperation(ctx context.Context, opID string, params interface{}, optFns []func(*Options), stackFns ...func(*middleware.Stack, Options) error) (result interface{}, metadata middleware.Metadata, err error) {
stack := middleware.NewStack(opID, smithyhttp.NewStackRequest)
options := c.options.Copy()
for _, fn := range optFns {
fn(&options)
}
for _, fn := range stackFns {
if err := fn(stack, options); err != nil {
return nil, metadata, err
}
}
for _, fn := range options.APIOptions {
if err := fn(stack); err != nil {
return nil, metadata, err
}
}
handler := middleware.DecorateHandler(smithyhttp.NewClientHandler(options.HTTPClient), stack)
result, metadata, err = handler.Handle(ctx, params)
if err != nil {
err = &smithy.OperationError{
ServiceID: ServiceID,
OperationName: opID,
Err: err,
}
}
return result, metadata, err
}
func resolveDefaultLogger(o *Options) {
if o.Logger != nil {
return
}
o.Logger = logging.Nop{}
}
func addSetLoggerMiddleware(stack *middleware.Stack, o Options) error {
return middleware.AddSetLoggerMiddleware(stack, o.Logger)
}
// NewFromConfig returns a new client from the provided config.
func NewFromConfig(cfg aws.Config, optFns ...func(*Options)) *Client {
opts := Options{
Region: cfg.Region,
Retryer: cfg.Retryer,
HTTPClient: cfg.HTTPClient,
Credentials: cfg.Credentials,
APIOptions: cfg.APIOptions,
Logger: cfg.Logger,
ClientLogMode: cfg.ClientLogMode,
}
resolveAWSEndpointResolver(cfg, &opts)
return New(opts, optFns...)
}
func resolveHTTPClient(o *Options) {
if o.HTTPClient != nil {
return
}
o.HTTPClient = awshttp.NewBuildableClient()
}
func resolveRetryer(o *Options) {
if o.Retryer != nil {
return
}
o.Retryer = retry.NewStandard()
}
func resolveAWSEndpointResolver(cfg aws.Config, o *Options) {
if cfg.EndpointResolver == nil {
return
}
o.EndpointResolver = WithEndpointResolver(cfg.EndpointResolver, NewDefaultEndpointResolver())
}
func addClientUserAgent(stack *middleware.Stack) error {
return awsmiddleware.AddUserAgentKey("s3")(stack)
}
func addHTTPSignerV4Middleware(stack *middleware.Stack, o Options) error {
return stack.Finalize.Add(v4.NewSignHTTPRequestMiddleware(o.Credentials, o.HTTPSignerV4), middleware.After)
}
type HTTPSignerV4 interface {
SignHTTP(ctx context.Context, credentials aws.Credentials, r *http.Request, payloadHash string, service string, region string, signingTime time.Time) error
}
func resolveHTTPSignerV4(o *Options) {
if o.HTTPSignerV4 != nil {
return
}
o.HTTPSignerV4 = v4.NewSigner(
func(s *v4.Signer) {
s.Logger = o.Logger
s.LogSigning = o.ClientLogMode.IsSigning()
s.DisableURIPathEscaping = true
},
)
}
func addRetryMiddlewares(stack *middleware.Stack, o Options) error {
mo := retry.AddRetryMiddlewaresOptions{
Retryer: o.Retryer,
LogRetryAttempts: o.ClientLogMode.IsRetries(),
}
return retry.AddRetryMiddlewares(stack, mo)
}
func addMetadataRetrieverMiddleware(stack *middleware.Stack) error {
return s3shared.AddMetadataRetrieverMiddleware(stack)
}
// nopGetBucketAccessor is no-op accessor for operation that don't support bucket
// member as input
func nopGetBucketAccessor(input interface{}) (*string, bool) {
return nil, false
}
func addResponseErrorMiddleware(stack *middleware.Stack) error {
return s3shared.AddResponseErrorMiddleware(stack)
}
func disableAcceptEncodingGzip(stack *middleware.Stack) error {
return acceptencodingcust.AddAcceptEncodingGzip(stack, acceptencodingcust.AddAcceptEncodingGzipOptions{})
}
func addRequestResponseLogging(stack *middleware.Stack, o Options) error {
return stack.Deserialize.Add(&smithyhttp.RequestResponseLogger{
LogRequest: o.ClientLogMode.IsRequest(),
LogRequestWithBody: o.ClientLogMode.IsRequestWithBody(),
LogResponse: o.ClientLogMode.IsResponse(),
LogResponseWithBody: o.ClientLogMode.IsResponseWithBody(),
}, middleware.After)
}
// HTTPPresignerV4 represents presigner interface used by presign url client
type HTTPPresignerV4 interface {
PresignHTTP(
ctx context.Context, credentials aws.Credentials, r *http.Request,
payloadHash string, service string, region string, signingTime time.Time,
) (url string, signedHeader http.Header, err error)
}
// PresignOptions represents the presign client options
type PresignOptions struct {
// ClientOptions are list of functional options to mutate client options used by
// presign client
ClientOptions []func(*Options)
// Presigner is the presigner used by the presign url client
Presigner HTTPPresignerV4
// Expires sets the expiration duration for the generated presign url. This should
// be the duration in seconds the presigned URL should be considered valid for. If
// not set or set to zero, presign url would default to expire after 900 seconds.
Expires time.Duration
}
// WithPresignClientFromClientOptions is a helper utility to retrieve a function
// that takes PresignOption as input
func WithPresignClientFromClientOptions(optFns ...func(*Options)) func(*PresignOptions) {
return withPresignClientFromClientOptions(optFns).options
}
type withPresignClientFromClientOptions []func(*Options)
func (w withPresignClientFromClientOptions) options(o *PresignOptions) {
o.ClientOptions = append(o.ClientOptions, w...)
}
// WithPresignExpires is a helper utility to append Expires value on presign
// options optional function
func WithPresignExpires(dur time.Duration) func(*PresignOptions) {
return withPresignExpires(dur).options
}
type withPresignExpires time.Duration
func (w withPresignExpires) options(o *PresignOptions) {
o.Expires = time.Duration(w)
}
// PresignClient represents the presign url client
type PresignClient struct {
client *Client
presigner HTTPPresignerV4
expires time.Duration
}
// NewPresignClient generates a presign client using provided API Client and
// presign options
func NewPresignClient(c *Client, optFns ...func(*PresignOptions)) *PresignClient {
var presignOptions PresignOptions
for _, fn := range optFns {
fn(&presignOptions)
}
client := copyAPIClient(c, presignOptions.ClientOptions...)
if presignOptions.Presigner == nil {
presignOptions.Presigner = v4.NewSigner()
}
return &PresignClient{
client: client,
presigner: presignOptions.Presigner,
expires: presignOptions.Expires,
}
}
func copyAPIClient(c *Client, optFns ...func(*Options)) *Client {
return New(c.options, optFns...)
}
func (c *PresignClient) convertToPresignMiddleware(stack *middleware.Stack, options Options) (err error) {
stack.Finalize.Clear()
stack.Deserialize.Clear()
stack.Build.Remove((*awsmiddleware.ClientRequestID)(nil).ID())
err = stack.Finalize.Add(v4.NewPresignHTTPRequestMiddleware(options.Credentials, c.presigner), middleware.After)
if err != nil {
return err
}
// add middleware to set expiration for s3 presigned url, if expiration is set to
// 0, this middleware sets a default expiration of 900 seconds
err = stack.Build.Add(&s3cust.AddExpiresOnPresignedURL{Expires: c.expires}, middleware.After)
if err != nil {
return err
}
return nil
}