-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathlarge_file_upload_task.go
196 lines (166 loc) · 5.4 KB
/
large_file_upload_task.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
package fileuploader
import (
"context"
"errors"
abstractions "github.com/microsoft/kiota-abstractions-go"
"github.com/microsoft/kiota-abstractions-go/serialization"
"io"
"os"
"strconv"
"strings"
"sync"
"time"
)
type LargeFileUploadTask[T serialization.Parsable] interface {
Upload(progress ProgressCallBack) UploadResult[T]
Resume(progress ProgressCallBack) (UploadResult[T], error)
RefreshUploadStatus() error
Cancel() error
}
// ByteStream is an interface that represents a stream of bytes
type ByteStream interface {
io.ReaderAt
Stat() (os.FileInfo, error)
}
type largeFileUploadTask[T serialization.Parsable] struct {
uploadSession UploadSession
adapter abstractions.RequestAdapter
byteStream ByteStream // *os.File by default implements ByteStream
maxSlice int64
parsableFactory serialization.ParsableFactory
errorMappings abstractions.ErrorMappings
}
func NewLargeFileUploadTask[T serialization.Parsable](adapter abstractions.RequestAdapter, uploadSession UploadSession, byteStream ByteStream, maxSlice int64, parsableFactory serialization.ParsableFactory, errorMappings abstractions.ErrorMappings) LargeFileUploadTask[T] {
return &largeFileUploadTask[T]{
adapter: adapter,
uploadSession: uploadSession,
byteStream: byteStream,
maxSlice: maxSlice,
parsableFactory: parsableFactory,
errorMappings: errorMappings,
}
}
// Upload uploads the byteStream in slices and returns the result of the upload
func (l *largeFileUploadTask[T]) Upload(progress ProgressCallBack) UploadResult[T] {
result := NewUploadResult[T]()
slices := l.createUploadSlices()
maxRetriesPerRequest := 3
// slices of errors
var responseErrors []error
var itemResponse T
var location *string
var wg sync.WaitGroup
wg.Add(len(slices))
for _, slice := range slices {
uploadSlice := slice
go func() {
defer wg.Done()
response, uploadLocation, err := l.uploadWithRetry(uploadSlice, maxRetriesPerRequest)
if err != nil {
responseErrors = append(responseErrors, err)
} else {
progress(uploadSlice.RangeEnd, uploadSlice.TotalSessionLength)
}
if response != nil {
itemResponse = response.(T)
}
location = uploadLocation
}()
}
wg.Wait()
if len(responseErrors) > 0 {
result.SetUploadSucceeded(false)
result.SetResponseErrors(responseErrors)
} else {
result.SetUploadSucceeded(true)
result.SetUploadSession(l.uploadSession)
result.SetItemResponse(itemResponse)
result.SetURI(location)
}
return result
}
// Resume uploads the byteStream in slices and returns the result of the upload
func (l *largeFileUploadTask[T]) Resume(progress ProgressCallBack) (UploadResult[T], error) {
err := l.RefreshUploadStatus()
if err != nil {
return nil, err
}
if len(l.uploadSession.GetNextExpectedRanges()) == 0 {
return nil, errors.New("UploadSession does not have next expected ranges")
}
if l.uploadSession.GetExpirationDateTime().Before(time.Now()) {
return nil, errors.New("UploadSession has expired")
}
return l.Upload(progress), nil
}
func (l *largeFileUploadTask[T]) RefreshUploadStatus() error {
requestInfo := abstractions.NewRequestInformation()
requestInfo.UrlTemplate = *l.uploadSession.GetUploadUrl()
requestInfo.Method = abstractions.GET
requestInfo.Headers.TryAdd("Accept", "application/json")
result, err := l.adapter.Send(context.Background(), requestInfo, CreateUploadSessionDiscriminator, l.errorMappings)
if err != nil {
return err
}
sessionResponse := result.(UploadSessionResponse)
l.uploadSession.SetExpirationDateTime(sessionResponse.GetExpirationDateTime())
l.uploadSession.SetNextExpectedRanges(sessionResponse.GetNextExpectedRanges())
return nil
}
// Cancel cancels the upload
func (l *largeFileUploadTask[T]) Cancel() error {
requestInfo := abstractions.NewRequestInformationWithMethodAndUrlTemplateAndPathParameters(abstractions.DELETE, *l.uploadSession.GetUploadUrl(), make(map[string]string))
err := l.adapter.SendNoContent(context.Background(), requestInfo, l.errorMappings)
return err
}
func (l *largeFileUploadTask[T]) uploadWithRetry(slice uploadSlice[T], maxRetry int) (interface{}, *string, error) {
retry := 1
var parseable interface{}
var location *string
var err error
for retry < maxRetry {
// store the result of the upload
parseable, location, err = slice.Upload(l.parsableFactory) // check if successful
if err != nil {
if retry >= maxRetry {
return nil, nil, err
}
// backoff before retrying
time.Sleep(time.Duration(retry) * time.Second)
}
retry++
}
return parseable, location, err
}
func (l *largeFileUploadTask[T]) getRangesRemaining() []rangePair {
rangePairs := make([]rangePair, len(l.uploadSession.GetNextExpectedRanges()))
for i, ranges := range l.uploadSession.GetNextExpectedRanges() {
rangeValues := strings.Split(ranges, "-")
var startRange int64
if s, err := strconv.ParseInt(rangeValues[0], 10, 64); err == nil {
startRange = s
}
var endRange int64
if !stringIsNullOrEmpty(rangeValues[1]) {
if s, err := strconv.ParseInt(rangeValues[1], 10, 64); err == nil {
if endRange > l.fileSize() {
endRange = l.fileSize() - 1
} else {
endRange = s
}
}
} else {
endRange = l.fileSize() - 1
}
rangePairs[i] = rangePair{
Start: startRange,
End: endRange,
}
}
return rangePairs
}
// returns the size of a byteStream
func (l *largeFileUploadTask[T]) fileSize() int64 {
fileInfo, _ := l.byteStream.Stat()
return fileInfo.Size()
}