|
| 1 | +//go:build go1.18 |
| 2 | +// +build go1.18 |
| 3 | + |
| 4 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 5 | +// Licensed under the MIT License. See License.txt in the project root for license information. |
| 6 | + |
| 7 | +package file |
| 8 | + |
| 9 | +import ( |
| 10 | + "bytes" |
| 11 | + "context" |
| 12 | + "errors" |
| 13 | + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" |
| 14 | + "io" |
| 15 | + "sync" |
| 16 | +) |
| 17 | + |
| 18 | +// chunkWriter provides methods to upload chunks that represent a file to a server. |
| 19 | +// This allows us to provide a local implementation that fakes the server for hermetic testing. |
| 20 | +type chunkWriter interface { |
| 21 | + AppendData(context.Context, int64, io.ReadSeekCloser, *AppendDataOptions) (AppendDataResponse, error) |
| 22 | + FlushData(context.Context, int64, *FlushDataOptions) (FlushDataResponse, error) |
| 23 | +} |
| 24 | + |
| 25 | +// bufferManager provides an abstraction for the management of buffers. |
| 26 | +// this is mostly for testing purposes, but does allow for different implementations without changing the algorithm. |
| 27 | +type bufferManager[T ~[]byte] interface { |
| 28 | + // Acquire returns the channel that contains the pool of buffers. |
| 29 | + Acquire() <-chan T |
| 30 | + |
| 31 | + // Release releases the buffer back to the pool for reuse/cleanup. |
| 32 | + Release(T) |
| 33 | + |
| 34 | + // Grow grows the number of buffers, up to the predefined max. |
| 35 | + // It returns the total number of buffers or an error. |
| 36 | + // No error is returned if the number of buffers has reached max. |
| 37 | + // This is called only from the reading goroutine. |
| 38 | + Grow() (int, error) |
| 39 | + |
| 40 | + // Free cleans up all buffers. |
| 41 | + Free() |
| 42 | +} |
| 43 | + |
| 44 | +// copyFromReader copies a source io.Reader to file storage using concurrent uploads. |
| 45 | +func copyFromReader[T ~[]byte](ctx context.Context, src io.Reader, dst chunkWriter, options UploadStreamOptions, getBufferManager func(maxBuffers int, bufferSize int64) bufferManager[T]) error { |
| 46 | + options.setDefaults() |
| 47 | + actualSize := int64(0) |
| 48 | + wg := sync.WaitGroup{} // Used to know when all outgoing chunks have finished processing |
| 49 | + errCh := make(chan error, 1) // contains the first error encountered during processing |
| 50 | + var err error |
| 51 | + |
| 52 | + buffers := getBufferManager(int(options.Concurrency), options.ChunkSize) |
| 53 | + defer buffers.Free() |
| 54 | + |
| 55 | + // this controls the lifetime of the uploading goroutines. |
| 56 | + // if an error is encountered, cancel() is called which will terminate all uploads. |
| 57 | + // NOTE: the ordering is important here. cancel MUST execute before |
| 58 | + // cleaning up the buffers so that any uploading goroutines exit first, |
| 59 | + // releasing their buffers back to the pool for cleanup. |
| 60 | + ctx, cancel := context.WithCancel(ctx) |
| 61 | + defer cancel() |
| 62 | + |
| 63 | + // This goroutine grabs a buffer, reads from the stream into the buffer, |
| 64 | + // then creates a goroutine to upload/stage the chunk. |
| 65 | + for chunkNum := uint32(0); true; chunkNum++ { |
| 66 | + var buffer T |
| 67 | + select { |
| 68 | + case buffer = <-buffers.Acquire(): |
| 69 | + // got a buffer |
| 70 | + default: |
| 71 | + // no buffer available; allocate a new buffer if possible |
| 72 | + if _, err := buffers.Grow(); err != nil { |
| 73 | + return err |
| 74 | + } |
| 75 | + |
| 76 | + // either grab the newly allocated buffer or wait for one to become available |
| 77 | + buffer = <-buffers.Acquire() |
| 78 | + } |
| 79 | + |
| 80 | + var n int |
| 81 | + n, err = io.ReadFull(src, buffer) |
| 82 | + |
| 83 | + if n > 0 { |
| 84 | + // some data was read, upload it |
| 85 | + wg.Add(1) // We're posting a buffer to be sent |
| 86 | + |
| 87 | + // NOTE: we must pass chunkNum as an arg to our goroutine else |
| 88 | + // it's captured by reference and can change underneath us! |
| 89 | + go func(chunkNum uint32) { |
| 90 | + // Upload the outgoing chunk, matching the number of bytes read |
| 91 | + offset := int64(chunkNum) * options.ChunkSize |
| 92 | + appendDataOpts := options.getAppendDataOptions() |
| 93 | + actualSize += int64(len(buffer[:n])) |
| 94 | + _, err := dst.AppendData(ctx, offset, streaming.NopCloser(bytes.NewReader(buffer[:n])), appendDataOpts) |
| 95 | + if err != nil { |
| 96 | + select { |
| 97 | + case errCh <- err: |
| 98 | + // error was set |
| 99 | + default: |
| 100 | + // some other error is already set |
| 101 | + } |
| 102 | + cancel() |
| 103 | + } |
| 104 | + buffers.Release(buffer) // The goroutine reading from the stream can reuse this buffer now |
| 105 | + |
| 106 | + // signal that the chunk has been staged. |
| 107 | + // we MUST do this after attempting to write to errCh |
| 108 | + // to avoid it racing with the reading goroutine. |
| 109 | + wg.Done() |
| 110 | + }(chunkNum) |
| 111 | + } else { |
| 112 | + // nothing was read so the buffer is empty, send it back for reuse/clean-up. |
| 113 | + buffers.Release(buffer) |
| 114 | + } |
| 115 | + |
| 116 | + if err != nil { // The reader is done, no more outgoing buffers |
| 117 | + if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) { |
| 118 | + // these are expected errors, we don't surface those |
| 119 | + err = nil |
| 120 | + } else { |
| 121 | + // some other error happened, terminate any outstanding uploads |
| 122 | + cancel() |
| 123 | + } |
| 124 | + break |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + wg.Wait() // Wait for all outgoing chunks to complete |
| 129 | + |
| 130 | + if err != nil { |
| 131 | + // there was an error reading from src, favor this error over any error during staging |
| 132 | + return err |
| 133 | + } |
| 134 | + |
| 135 | + select { |
| 136 | + case err = <-errCh: |
| 137 | + // there was an error during staging |
| 138 | + return err |
| 139 | + default: |
| 140 | + // no error was encountered |
| 141 | + } |
| 142 | + |
| 143 | + // All chunks uploaded, return nil error |
| 144 | + flushOpts := options.getFlushDataOptions() |
| 145 | + _, err = dst.FlushData(ctx, actualSize, flushOpts) |
| 146 | + return err |
| 147 | +} |
| 148 | + |
| 149 | +// mmbPool implements the bufferManager interface. |
| 150 | +// it uses anonymous memory mapped files for buffers. |
| 151 | +// don't use this type directly, use newMMBPool() instead. |
| 152 | +type mmbPool struct { |
| 153 | + buffers chan mmb |
| 154 | + count int |
| 155 | + max int |
| 156 | + size int64 |
| 157 | +} |
| 158 | + |
| 159 | +func newMMBPool(maxBuffers int, bufferSize int64) bufferManager[mmb] { |
| 160 | + return &mmbPool{ |
| 161 | + buffers: make(chan mmb, maxBuffers), |
| 162 | + max: maxBuffers, |
| 163 | + size: bufferSize, |
| 164 | + } |
| 165 | +} |
| 166 | + |
| 167 | +func (pool *mmbPool) Acquire() <-chan mmb { |
| 168 | + return pool.buffers |
| 169 | +} |
| 170 | + |
| 171 | +func (pool *mmbPool) Grow() (int, error) { |
| 172 | + if pool.count < pool.max { |
| 173 | + buffer, err := newMMB(pool.size) |
| 174 | + if err != nil { |
| 175 | + return 0, err |
| 176 | + } |
| 177 | + pool.buffers <- buffer |
| 178 | + pool.count++ |
| 179 | + } |
| 180 | + return pool.count, nil |
| 181 | +} |
| 182 | + |
| 183 | +func (pool *mmbPool) Release(buffer mmb) { |
| 184 | + pool.buffers <- buffer |
| 185 | +} |
| 186 | + |
| 187 | +func (pool *mmbPool) Free() { |
| 188 | + for i := 0; i < pool.count; i++ { |
| 189 | + buffer := <-pool.buffers |
| 190 | + buffer.delete() |
| 191 | + } |
| 192 | + pool.count = 0 |
| 193 | +} |
0 commit comments