max total storage usage implemented!
code may be a bit messy but.... also implemented a storage usage stat (that can be toggled in .env) that shows on the home page, you can also enable the total limit to show as well eventually i need to implement clearing old unfinished uploads both on startup, admin actions, and cleaning up on upload failure
This commit is contained in:
@@ -15,17 +15,26 @@ const (
|
||||
ContentPaste
|
||||
)
|
||||
|
||||
type UploadState uint8
|
||||
|
||||
const (
|
||||
Complete UploadState = iota
|
||||
Pending
|
||||
Deleting
|
||||
)
|
||||
|
||||
type Upload struct {
|
||||
ID string `gorm:"column:id;primaryKey" json:"id"`
|
||||
Type ContentType `gorm:"column:type;not null;default:0;type:integer" json:"type"`
|
||||
Filename string `gorm:"column:filename;not null" json:"-"`
|
||||
MIMEType string `gorm:"column:mime_type;not null" json:"mime_type"`
|
||||
Size int64 `gorm:"column:size;not null" json:"size"`
|
||||
SHA256 []byte `gorm:"column:sha256;type:blob;notnull;index" json:"-"`
|
||||
SHA256 []byte `gorm:"column:sha256;type:blob;index" json:"-"`
|
||||
CreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime" json:"created_at"`
|
||||
ExpiresAt *int64 `gorm:"column:expires_at;index" json:"expires_at"` // null means no expiration
|
||||
LastAccessedAt int64 `gorm:"column:last_accessed_at;not null;autoCreateTime;index" json:"last_accessed_at"`
|
||||
DeleteToken string `gorm:"column:delete_token;not null" json:"-"`
|
||||
State UploadState `gorm:"column:state;not null;default:0;type:integer;index" json:"-"`
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
@@ -36,6 +45,13 @@ type Report struct {
|
||||
CreatedAt int64 `gorm:"column:created_at;not null;autoCreateTime"`
|
||||
}
|
||||
|
||||
type Stat struct {
|
||||
Key string `gorm:"column:key;primaryKey"`
|
||||
Value int64 `gorm:"column:value"`
|
||||
}
|
||||
|
||||
var ErrStorageQuotaExceeded = errors.New("storage quota exceeded")
|
||||
|
||||
func InitDatabase(path string) (*gorm.DB, error) {
|
||||
db, err := gorm.Open(sqlite.Open(path), &gorm.Config{TranslateError: true})
|
||||
if err != nil {
|
||||
@@ -60,7 +76,7 @@ func InitDatabase(path string) (*gorm.DB, error) {
|
||||
return nil, fmt.Errorf("set synchronous normal: %w", err)
|
||||
}
|
||||
|
||||
if err := db.AutoMigrate(&Upload{}, &Report{}); err != nil {
|
||||
if err := db.AutoMigrate(&Upload{}, &Report{}, &Stat{}); err != nil {
|
||||
migrationErr := fmt.Errorf("migrate database: %w", err)
|
||||
return nil, errors.Join(migrationErr, sqlDB.Close())
|
||||
}
|
||||
@@ -68,8 +84,44 @@ func InitDatabase(path string) (*gorm.DB, error) {
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func InsertUpload(db *gorm.DB, upload *Upload) error {
|
||||
return db.Create(upload).Error
|
||||
func ReserveUpload(db *gorm.DB, upload *Upload, maxStorageUsage int64) (int64, error) {
|
||||
var usedBytes int64
|
||||
err := db.Transaction(func(tx *gorm.DB) error {
|
||||
query := tx.Model(&Stat{}).Where(`"Key" = ?`, "quota_usage")
|
||||
if maxStorageUsage > 0 {
|
||||
query = query.Where("value <= ?", maxStorageUsage-upload.Size)
|
||||
}
|
||||
result := query.UpdateColumn("value", gorm.Expr("value + ?", upload.Size))
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
var stat Stat
|
||||
if err := tx.Where(`"key" =?`, "quota_usage").Take(&stat).Error; err != nil {
|
||||
return fmt.Errorf("read quota usage: %w", err)
|
||||
}
|
||||
usedBytes = stat.Value
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
return fmt.Errorf("reserve upload: %w", ErrStorageQuotaExceeded)
|
||||
}
|
||||
upload.State = Pending
|
||||
return tx.Create(upload).Error
|
||||
})
|
||||
if err != nil && !errors.Is(err, ErrStorageQuotaExceeded) {
|
||||
return 0, err
|
||||
}
|
||||
return usedBytes, err
|
||||
}
|
||||
|
||||
func CompleteUpload(db *gorm.DB, upload *Upload) error {
|
||||
if upload.SHA256 == nil {
|
||||
return fmt.Errorf("sha256 hash required")
|
||||
}
|
||||
return db.Model(&Upload{}).Where("id = ? AND state = ?", upload.ID, Pending).
|
||||
Updates(map[string]any{
|
||||
"sha256": upload.SHA256,
|
||||
"state": Complete,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func InsertReport(db *gorm.DB, report *Report) error {
|
||||
@@ -78,8 +130,40 @@ func InsertReport(db *gorm.DB, report *Report) error {
|
||||
|
||||
func GetUploadById(db *gorm.DB, id string) (*Upload, error) {
|
||||
var upload Upload
|
||||
if err := db.First(&upload, "id = ?", id).Error; err != nil {
|
||||
// will only find uploads whose upload state is complete
|
||||
if err := db.First(&upload, "id = ? AND state = ?", id, Complete).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &upload, nil
|
||||
}
|
||||
|
||||
func EnsureQuotaUsage(db *gorm.DB) error {
|
||||
var stat Stat
|
||||
result := db.Where(`"key" = ?`, "quota_usage").Limit(1).Find(&stat)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
} else if result.RowsAffected == 0 {
|
||||
return rebuildQuotaUsage(db)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetQuotaUsage(db *gorm.DB) (int64, error) {
|
||||
var stat Stat
|
||||
if err := db.First(&stat, `"key" = ?`, "quota_usage").Error; err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return stat.Value, nil
|
||||
}
|
||||
|
||||
func rebuildQuotaUsage(db *gorm.DB) error {
|
||||
return db.Transaction(func(tx *gorm.DB) error {
|
||||
var total int64
|
||||
if err := tx.Model(&Upload{}).Select("COALESCE(SUM(size),0)").Scan(&total).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Exec(`
|
||||
INSERT INTO stats ("key", value) values (?,?)
|
||||
ON CONFLICT ("key") DO UPDATE SET value = excluded.value`, "quota_usage", total).Error
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user