code.gitea.io/gitea@v1.21.7/models/packages/package_blob_upload.go (about)

     1  // Copyright 2022 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package packages
     5  
     6  import (
     7  	"context"
     8  	"strings"
     9  	"time"
    10  
    11  	"code.gitea.io/gitea/models/db"
    12  	"code.gitea.io/gitea/modules/timeutil"
    13  	"code.gitea.io/gitea/modules/util"
    14  )
    15  
    16  // ErrPackageBlobUploadNotExist indicates a package blob upload not exist error
    17  var ErrPackageBlobUploadNotExist = util.NewNotExistErrorf("package blob upload does not exist")
    18  
    19  func init() {
    20  	db.RegisterModel(new(PackageBlobUpload))
    21  }
    22  
    23  // PackageBlobUpload represents a package blob upload
    24  type PackageBlobUpload struct {
    25  	ID             string             `xorm:"pk"`
    26  	BytesReceived  int64              `xorm:"NOT NULL DEFAULT 0"`
    27  	HashStateBytes []byte             `xorm:"BLOB"`
    28  	CreatedUnix    timeutil.TimeStamp `xorm:"created NOT NULL"`
    29  	UpdatedUnix    timeutil.TimeStamp `xorm:"updated INDEX NOT NULL"`
    30  }
    31  
    32  // CreateBlobUpload inserts a blob upload
    33  func CreateBlobUpload(ctx context.Context) (*PackageBlobUpload, error) {
    34  	id, err := util.CryptoRandomString(25)
    35  	if err != nil {
    36  		return nil, err
    37  	}
    38  
    39  	pbu := &PackageBlobUpload{
    40  		ID: strings.ToLower(id),
    41  	}
    42  
    43  	_, err = db.GetEngine(ctx).Insert(pbu)
    44  	return pbu, err
    45  }
    46  
    47  // GetBlobUploadByID gets a blob upload by id
    48  func GetBlobUploadByID(ctx context.Context, id string) (*PackageBlobUpload, error) {
    49  	pbu := &PackageBlobUpload{}
    50  
    51  	has, err := db.GetEngine(ctx).ID(id).Get(pbu)
    52  	if err != nil {
    53  		return nil, err
    54  	}
    55  	if !has {
    56  		return nil, ErrPackageBlobUploadNotExist
    57  	}
    58  	return pbu, nil
    59  }
    60  
    61  // UpdateBlobUpload updates the blob upload
    62  func UpdateBlobUpload(ctx context.Context, pbu *PackageBlobUpload) error {
    63  	_, err := db.GetEngine(ctx).ID(pbu.ID).Update(pbu)
    64  	return err
    65  }
    66  
    67  // DeleteBlobUploadByID deletes the blob upload
    68  func DeleteBlobUploadByID(ctx context.Context, id string) error {
    69  	_, err := db.GetEngine(ctx).ID(id).Delete(&PackageBlobUpload{})
    70  	return err
    71  }
    72  
    73  // FindExpiredBlobUploads gets all expired blob uploads
    74  func FindExpiredBlobUploads(ctx context.Context, olderThan time.Duration) ([]*PackageBlobUpload, error) {
    75  	pbus := make([]*PackageBlobUpload, 0, 10)
    76  	return pbus, db.GetEngine(ctx).
    77  		Where("updated_unix < ?", time.Now().Add(-olderThan).Unix()).
    78  		Find(&pbus)
    79  }