github.com/opcr-io/oras-go/v2@v2.0.0-20231122155130-eb4260d8a0ae/content/limitedstorage.go (about)

     1  /*
     2  Copyright The ORAS Authors.
     3  Licensed under the Apache License, Version 2.0 (the "License");
     4  you may not use this file except in compliance with the License.
     5  You may obtain a copy of the License at
     6  
     7  http://www.apache.org/licenses/LICENSE-2.0
     8  
     9  Unless required by applicable law or agreed to in writing, software
    10  distributed under the License is distributed on an "AS IS" BASIS,
    11  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  See the License for the specific language governing permissions and
    13  limitations under the License.
    14  */
    15  
    16  package content
    17  
    18  import (
    19  	"context"
    20  	"fmt"
    21  	"io"
    22  
    23  	"github.com/opcr-io/oras-go/v2/errdef"
    24  	ocispec "github.com/opencontainers/image-spec/specs-go/v1"
    25  )
    26  
    27  // LimitedStorage represents a CAS with a push size limit.
    28  type LimitedStorage struct {
    29  	Storage         // underlying storage
    30  	PushLimit int64 // max size for push
    31  }
    32  
    33  // Push pushes the content, matching the expected descriptor.
    34  // The size of the content cannot exceed the push size limit.
    35  func (ls *LimitedStorage) Push(ctx context.Context, expected ocispec.Descriptor, content io.Reader) error {
    36  	if expected.Size > ls.PushLimit {
    37  		return fmt.Errorf(
    38  			"content size %v exceeds push size limit %v: %w",
    39  			expected.Size,
    40  			ls.PushLimit,
    41  			errdef.ErrSizeExceedsLimit)
    42  	}
    43  
    44  	return ls.Storage.Push(ctx, expected, io.LimitReader(content, expected.Size))
    45  }
    46  
    47  // LimitStorage returns a storage with a push size limit.
    48  func LimitStorage(s Storage, n int64) *LimitedStorage {
    49  	return &LimitedStorage{s, n}
    50  }