| 1 |
package s3 |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"encoding/xml" |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
"io" |
| 10 |
"net/http" |
| 11 |
"net/url" |
| 12 |
"time" |
| 13 |
|
| 14 |
"heckel.io/ntfy/v2/log" |
| 15 |
) |
| 16 |
|
| 17 |
// AbortIncompleteUploads lists all in-progress multipart uploads and aborts those initiated |
| 18 |
// before the given cutoff time. This cleans up orphaned upload parts from interrupted uploads. |
| 19 |
// |
| 20 |
// See https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListMultipartUploads.html |
| 21 |
// and https://docs.aws.amazon.com/AmazonS3/latest/API/API_AbortMultipartUpload.html |
| 22 |
func (c *Client) AbortIncompleteUploads(ctx context.Context, cutoff time.Time) error { |
| 23 |
uploads, err := c.listMultipartUploads(ctx) |
| 24 |
if err != nil { |
| 25 |
return err |
| 26 |
} |
| 27 |
for _, u := range uploads { |
| 28 |
if !u.Initiated.IsZero() && u.Initiated.Before(cutoff) { |
| 29 |
c.abortMultipartUpload(ctx, u.Key, u.UploadID) |
| 30 |
} |
| 31 |
} |
| 32 |
return nil |
| 33 |
} |
| 34 |
|
| 35 |
// listMultipartUploads returns in-progress multipart uploads for the client's prefix. |
| 36 |
// It paginates automatically, stopping after 10,000 pages as a safety valve. |
| 37 |
func (c *Client) listMultipartUploads(ctx context.Context) ([]*multipartUpload, error) { |
| 38 |
var all []*multipartUpload |
| 39 |
var keyMarker, uploadIDMarker string |
| 40 |
for page := 0; page < maxPages; page++ { |
| 41 |
query := url.Values{"uploads": {""}} |
| 42 |
if prefix := c.config.ListPrefix(); prefix != "" { |
| 43 |
query.Set("prefix", prefix) |
| 44 |
} |
| 45 |
if keyMarker != "" { |
| 46 |
query.Set("key-marker", keyMarker) |
| 47 |
query.Set("upload-id-marker", uploadIDMarker) |
| 48 |
} |
| 49 |
respBody, err := c.do(ctx, "ListMultipartUploads", http.MethodGet, c.config.BucketURL()+"?"+query.Encode(), nil, nil) |
| 50 |
if err != nil { |
| 51 |
return nil, err |
| 52 |
} |
| 53 |
var result listMultipartUploadsResult |
| 54 |
if err := xml.Unmarshal(respBody, &result); err != nil { |
| 55 |
return nil, fmt.Errorf("error unmarshalling multipart upload result: %w", err) |
| 56 |
} |
| 57 |
for _, u := range result.Uploads { |
| 58 |
var initiated time.Time |
| 59 |
if u.Initiated != "" { |
| 60 |
initiated, _ = time.Parse(time.RFC3339, u.Initiated) |
| 61 |
} |
| 62 |
all = append(all, &multipartUpload{ |
| 63 |
Key: u.Key, |
| 64 |
UploadID: u.UploadID, |
| 65 |
Initiated: initiated, |
| 66 |
}) |
| 67 |
} |
| 68 |
if !result.IsTruncated { |
| 69 |
return all, nil |
| 70 |
} |
| 71 |
keyMarker = result.NextKeyMarker |
| 72 |
uploadIDMarker = result.NextUploadIDMarker |
| 73 |
} |
| 74 |
return nil, fmt.Errorf("error listing multipart uploads, exceeded %d pages", maxPages) |
| 75 |
} |
| 76 |
|
| 77 |
// abortMultipartUpload cancels an in-progress multipart upload. Called on error to clean up. |
| 78 |
func (c *Client) abortMultipartUpload(ctx context.Context, key, uploadID string) { |
| 79 |
log.Tag(tagS3Client).Info("Aborting multipart upload for object %s", key) |
| 80 |
reqURL := fmt.Sprintf("%s?uploadId=%s", c.config.ObjectURL(key), url.QueryEscape(uploadID)) |
| 81 |
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, reqURL, nil) |
| 82 |
if err != nil { |
| 83 |
return |
| 84 |
} |
| 85 |
c.signV4(req, emptyPayloadHash) |
| 86 |
resp, err := c.http.Do(req) |
| 87 |
if err != nil { |
| 88 |
return |
| 89 |
} |
| 90 |
resp.Body.Close() |
| 91 |
} |
| 92 |
|
| 93 |
// putObjectMultipart uploads body using S3 multipart upload. It reads the body in partSize |
| 94 |
// chunks, uploading each as a separate part. This allows uploading without knowing the total |
| 95 |
// body size in advance. |
| 96 |
func (c *Client) putObjectMultipart(ctx context.Context, key string, body io.Reader) error { |
| 97 |
log.Tag(tagS3Client).Debug("Uploading multipart object %s", key) |
| 98 |
|
| 99 |
// Step 1: Initiate multipart upload |
| 100 |
uploadID, err := c.initiateMultipartUpload(ctx, key) |
| 101 |
if err != nil { |
| 102 |
return err |
| 103 |
} |
| 104 |
|
| 105 |
// Step 2: Upload parts |
| 106 |
partNumber := 1 |
| 107 |
buf := make([]byte, partSize) |
| 108 |
var parts []*completedPart |
| 109 |
for { |
| 110 |
n, err := io.ReadFull(body, buf) |
| 111 |
if n > 0 { |
| 112 |
etag, uploadErr := c.uploadPart(ctx, key, uploadID, partNumber, buf[:n]) |
| 113 |
if uploadErr != nil { |
| 114 |
c.abortMultipartUpload(ctx, key, uploadID) |
| 115 |
return uploadErr |
| 116 |
} |
| 117 |
parts = append(parts, &completedPart{ |
| 118 |
PartNumber: partNumber, |
| 119 |
ETag: etag, |
| 120 |
}) |
| 121 |
partNumber++ |
| 122 |
} |
| 123 |
if err == io.EOF || errors.Is(err, io.ErrUnexpectedEOF) { |
| 124 |
break |
| 125 |
} else if err != nil { |
| 126 |
c.abortMultipartUpload(ctx, key, uploadID) |
| 127 |
return fmt.Errorf("error uploading object %s, reading from client failed: %w", key, err) |
| 128 |
} |
| 129 |
} |
| 130 |
|
| 131 |
// Step 3: Complete multipart upload |
| 132 |
return c.completeMultipartUpload(ctx, key, uploadID, parts) |
| 133 |
} |
| 134 |
|
| 135 |
// initiateMultipartUpload starts a new multipart upload and returns the upload ID. |
| 136 |
func (c *Client) initiateMultipartUpload(ctx context.Context, key string) (string, error) { |
| 137 |
respBody, err := c.do(ctx, "InitiateMultipartUpload", http.MethodPost, c.config.ObjectURL(key)+"?uploads", nil, nil) |
| 138 |
if err != nil { |
| 139 |
return "", err |
| 140 |
} |
| 141 |
var result initiateMultipartUploadResult |
| 142 |
if err := xml.Unmarshal(respBody, &result); err != nil { |
| 143 |
return "", fmt.Errorf("error unmarshalling initiate multipart upload response: %w", err) |
| 144 |
} |
| 145 |
return result.UploadID, nil |
| 146 |
} |
| 147 |
|
| 148 |
// uploadPart uploads a single part of a multipart upload and returns the ETag. |
| 149 |
func (c *Client) uploadPart(ctx context.Context, key, uploadID string, partNumber int, data []byte) (string, error) { |
| 150 |
log.Tag(tagS3Client).Debug("Uploading multipart part for object %s, part %d, size %d", key, partNumber, len(data)) |
| 151 |
reqURL := fmt.Sprintf("%s?partNumber=%d&uploadId=%s", c.config.ObjectURL(key), partNumber, url.QueryEscape(uploadID)) |
| 152 |
req, err := http.NewRequestWithContext(ctx, http.MethodPut, reqURL, bytes.NewReader(data)) |
| 153 |
if err != nil { |
| 154 |
return "", fmt.Errorf("error creating multipart upload part request for object %s: %w", key, err) |
| 155 |
} |
| 156 |
req.ContentLength = int64(len(data)) |
| 157 |
c.signV4(req, unsignedPayload) |
| 158 |
resp, err := c.http.Do(req) |
| 159 |
if err != nil { |
| 160 |
return "", fmt.Errorf("error uploading multipart part for object %s: %w", key, err) |
| 161 |
} |
| 162 |
defer resp.Body.Close() |
| 163 |
if !isHTTPSuccess(resp) { |
| 164 |
return "", parseError(resp) |
| 165 |
} |
| 166 |
return resp.Header.Get("ETag"), nil |
| 167 |
} |
| 168 |
|
| 169 |
// completeMultipartUpload finalizes a multipart upload with the given parts. |
| 170 |
func (c *Client) completeMultipartUpload(ctx context.Context, key, uploadID string, parts []*completedPart) error { |
| 171 |
log.Tag(tagS3Client).Debug("Completing multipart upload for object %s, %d parts", key, len(parts)) |
| 172 |
bodyBytes, err := xml.Marshal(&completeMultipartUploadRequest{Parts: parts}) |
| 173 |
if err != nil { |
| 174 |
return fmt.Errorf("error marshalling complete multipart upload request: %w", err) |
| 175 |
} |
| 176 |
reqURL := fmt.Sprintf("%s?uploadId=%s", c.config.ObjectURL(key), url.QueryEscape(uploadID)) |
| 177 |
respBody, err := c.do(ctx, "CompleteMultipartUpload", http.MethodPost, reqURL, bodyBytes, nil) |
| 178 |
if err != nil { |
| 179 |
return err |
| 180 |
} |
| 181 |
// Check if the response contains an error (S3 can return 200 with an error body) |
| 182 |
var errResp errorResponse |
| 183 |
if xml.Unmarshal(respBody, &errResp) == nil && errResp.Code != "" { |
| 184 |
return &errResp |
| 185 |
} |
| 186 |
return nil |
| 187 |
} |