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
170 lines
5.1 KiB
Go
170 lines
5.1 KiB
Go
package database
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/glebarez/sqlite"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
type ContentType uint8
|
|
|
|
const (
|
|
ContentFile ContentType = iota
|
|
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;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 {
|
|
ID string `gorm:"column:id;primaryKey"`
|
|
UploadID string `gorm:"column:upload_id;not null;index"`
|
|
Reason string `gorm:"column:reason;not null"`
|
|
Upload Upload `gorm:"foreignKey:UploadID;references:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"`
|
|
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 {
|
|
return nil, fmt.Errorf("open database: %w", err)
|
|
}
|
|
|
|
sqlDB, err := db.DB()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("get database handle: %w", err)
|
|
}
|
|
|
|
sqlDB.SetMaxOpenConns(1)
|
|
sqlDB.SetMaxIdleConns(1)
|
|
if err := db.Exec("PRAGMA journal_mode = WAL").Error; err != nil {
|
|
walModeErr := fmt.Errorf("enable database WAL: %w", err)
|
|
return nil, errors.Join(walModeErr, sqlDB.Close())
|
|
}
|
|
if err := db.Exec("PRAGMA foreign_keys = ON").Error; err != nil {
|
|
return nil, fmt.Errorf("enable foreign keys: %w", err)
|
|
}
|
|
if err := db.Exec("PRAGMA synchronous = NORMAL").Error; err != nil {
|
|
return nil, fmt.Errorf("set synchronous normal: %w", err)
|
|
}
|
|
|
|
if err := db.AutoMigrate(&Upload{}, &Report{}, &Stat{}); err != nil {
|
|
migrationErr := fmt.Errorf("migrate database: %w", err)
|
|
return nil, errors.Join(migrationErr, sqlDB.Close())
|
|
}
|
|
|
|
return db, nil
|
|
}
|
|
|
|
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 {
|
|
return db.Omit("Upload").Create(report).Error
|
|
}
|
|
|
|
func GetUploadById(db *gorm.DB, id string) (*Upload, error) {
|
|
var upload Upload
|
|
// 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
|
|
})
|
|
}
|