11//
2- // Copyright 2023 The Chainloop Authors.
2+ // Copyright 2024 The Chainloop Authors.
33//
44// Licensed under the Apache License, Version 2.0 (the "License");
55// you may not use this file except in compliance with the License.
@@ -92,7 +92,7 @@ func (s *ByteStreamService) Write(stream bytestream.ByteStream_WriteServer) erro
9292
9393 s .log .Infow ("msg" , "artifact does not exist, uploading" , "digest" , req .resource .Digest , "name" , req .resource .FileName )
9494 // Create a buffer that will be filled in the background before sending its content to the backend
95- buffer := newStreamReader ()
95+ buffer := newStreamReader (info . MaxBytes )
9696 // Add data from first request
9797 if err = buffer .Write (req .GetData ()); err != nil {
9898 return sl .LogAndMaskErr (err , s .log )
@@ -213,7 +213,7 @@ func bufferStream(ctx context.Context, stream bytestream.ByteStream_WriteServer,
213213 return
214214 }
215215
216- log .Debugw ("msg" , "upload chunk received" , "digest" , req .resource .Digest , "bufferSize " , buffer .size , "chunkSize" , len (req .GetData ()))
216+ log .Debugw ("msg" , "upload chunk received" , "digest" , req .resource .Digest , "currentSize " , buffer .size , "maxSize" , buffer . maxSize , "chunkSize" , len (req .GetData ()))
217217 }
218218 }
219219}
@@ -222,22 +222,32 @@ type streamReader struct {
222222 * bytes.Buffer
223223 // total size of the in-memory buffer in bytes
224224 size int64
225+ // Max size allowed to be uploaded
226+ maxSize int64
225227 // there was an error during stream data filling
226228 errorChan chan error
227229}
228230
229231// Wrapper around a buffer that adds
230232// the ability to record the total size of the data that went through it
231233// and a channel to be used by the clients to signal when the buffer has been filled
232- func newStreamReader () * streamReader {
234+ func newStreamReader (maxSize int64 ) * streamReader {
233235 return & streamReader {
234236 Buffer : bytes .NewBuffer (nil ),
235237 errorChan : make (chan error ),
238+ maxSize : maxSize ,
236239 }
237240}
238241
239242func (r * streamReader ) Write (data []byte ) error {
240243 r .size += int64 (len (data ))
244+
245+ // Check if the size of the buffer has exceeded the maximum allowed size
246+ // if maxSize is 0, then there is no limit
247+ if r .maxSize != 0 && r .size > r .maxSize {
248+ return fmt .Errorf ("max size of upload exceeded: want=%d, max=%d" , r .size , r .maxSize )
249+ }
250+
241251 _ , err := r .Buffer .Write (data )
242252 return err
243253}
0 commit comments