db

package
v0.2.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 17, 2026 License: AGPL-3.0 Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const CleanupInterval = 1 * time.Hour

CleanupInterval is how often the orphan cleanup job runs.

Variables

This section is empty.

Functions

func AddBytesDownloaded added in v0.2.1

func AddBytesDownloaded(n int64)

AddBytesDownloaded adds n bytes to the total bytes downloaded counter

func AddBytesUploaded added in v0.2.1

func AddBytesUploaded(n int64)

AddBytesUploaded adds n bytes to the total bytes uploaded counter

func AutoMigrate

func AutoMigrate()
func CleanupExpiredLinks() error

CleanupExpiredLinks removes all expired shareable links

func CleanupExpiredPresignedURLs added in v0.2.0

func CleanupExpiredPresignedURLs() error

func Close

func Close() error

Close closes the underlying database connection.

func CreateStatsTable

func CreateStatsTable()

func DecryptSecretKey added in v0.2.0

func DecryptSecretKey(apiKey *APIKey) (string, error)

DecryptSecretKey decrypts the stored encrypted secret key.

func DeleteAPIKey

func DeleteAPIKey(accessKeyID string) error

DeleteAPIKey deletes an API key by access key ID

func DeletePresignedURL added in v0.2.0

func DeletePresignedURL(token string) error
func DeleteShareableLink(token string) error

DeleteShareableLink deletes a shareable link by token

func DisableAPIKey

func DisableAPIKey(accessKeyID string) error

DisableAPIKey disables an API key without deleting it

func GenerateKeyPair

func GenerateKeyPair() (accessKeyID, secretKey string, err error)

GenerateKeyPair creates a new access key ID and secret key

func GenerateToken

func GenerateToken() (string, error)

GenerateToken creates a unique random token for shareable links

func GetDB

func GetDB() *gorm.DB

func Increment

func Increment(field string)

Increment increments the specified field by 1

func IncrementAccessCount

func IncrementAccessCount(token string) error

IncrementAccessCount increments the access count for a shareable link

func IncrementDownloads

func IncrementDownloads()

IncrementDownloads increments the download count by 1

func IncrementPresignedURLDownloads added in v0.2.0

func IncrementPresignedURLDownloads(token string) error

func IncrementRequests

func IncrementRequests()

IncrementRequests increments the request count by 1

func IncrementUploads

func IncrementUploads()

IncrementUploads increments the upload count by 1

func Init

func Init()

Init explicitly initializes the database. Must be called after config flags (like --db-path) have been applied. Safe to call multiple times; only the first call takes effect.

func InitializeStats

func InitializeStats()

InitializeStats creates an initial stats record if one doesn't exist

func IsStarred

func IsStarred(filePath string) bool

IsStarred checks if a file is starred

func ResetStats

func ResetStats()

ResetStats resets the server stats to zero and updates the start time to now

func StarFile

func StarFile(filePath string) error

StarFile adds a file to the starred files list

func UnstarFile

func UnstarFile(filePath string) error

UnstarFile removes a file from the starred files list

func UpdateLastUsed

func UpdateLastUsed(accessKeyID string) error

UpdateLastUsed updates the last used timestamp for an API key

func ValidateLinkPassword

func ValidateLinkPassword(link *ShareableLink, password string) bool

ValidateLinkPassword verifies a password for a password-protected link

func WithTransaction

func WithTransaction(fn func(tx *gorm.DB) error) error

WithTransaction executes fn inside a database transaction. If fn returns an error the transaction is rolled back; otherwise it is committed. This is the canonical helper for wrapping multi-step DB operations.

Types

type APIKey

type APIKey struct {
	ID          uint       `gorm:"primaryKey" json:"id"`
	Name        string     `gorm:"size:255;not null" json:"name"`
	AccessKeyID string     `gorm:"column:access_key_id;uniqueIndex;size:24;not null" json:"accessKeyId"`
	SecretKey   string     `gorm:"column:secret_key;size:256;not null" json:"-"` // Encrypted at rest with AES-256-GCM
	Permissions string     `gorm:"type:text" json:"permissions"`                 // JSON permissions
	BucketScope string     `gorm:"column:bucket_scope;size:255" json:"bucketScope,omitempty"`
	ExpiresAt   *time.Time `gorm:"column:expires_at" json:"expiresAt,omitempty"`
	LastUsedAt  *time.Time `gorm:"column:last_used_at" json:"lastUsedAt,omitempty"`
	CreatedAt   time.Time  `gorm:"column:created_at;default:CURRENT_TIMESTAMP" json:"createdAt"`
	Disabled    bool       `gorm:"default:false" json:"disabled"`
}

APIKey represents an API key for S3-like API access

func CreateAPIKey

func CreateAPIKey(name string, permissions string, bucketScope string, expiresIn *time.Duration) (*APIKey, string, error)

CreateAPIKey creates a new API key and returns the secret (only shown once)

func GetAPIKeyByAccessID

func GetAPIKeyByAccessID(accessKeyID string) (*APIKey, error)

GetAPIKeyByAccessID retrieves an API key by its access key ID

func ListAPIKeys

func ListAPIKeys() ([]APIKey, error)

ListAPIKeys returns all API keys (without secrets)

func (APIKey) TableName

func (APIKey) TableName() string

type Config

type Config struct {
	Password string
}

func (Config) TableName

func (Config) TableName() string

type OrphanCleaner

type OrphanCleaner struct {
	// contains filtered or unexported fields
}

OrphanCleaner periodically removes DB records that reference filesystem paths that no longer exist.

func NewOrphanCleaner

func NewOrphanCleaner(sharedDir string) *OrphanCleaner

NewOrphanCleaner creates a new cleaner. Call Start() to begin.

func (*OrphanCleaner) RunOnce

func (oc *OrphanCleaner) RunOnce()

RunOnce performs a single cleanup pass. Can be called directly for testing.

func (*OrphanCleaner) Start

func (oc *OrphanCleaner) Start()

Start launches the background cleanup goroutine.

func (*OrphanCleaner) Stop

func (oc *OrphanCleaner) Stop()

Stop signals the background goroutine to exit.

type PresignedURL added in v0.2.0

type PresignedURL struct {
	ID            uint       `gorm:"primaryKey" json:"id"`
	Token         string     `gorm:"column:token;uniqueIndex;size:32;not null" json:"token"`
	Bucket        string     `gorm:"column:bucket;size:255;not null" json:"bucket"`
	Key           string     `gorm:"column:key;size:1024;not null" json:"key"`
	Method        string     `gorm:"column:method;size:10;not null;default:GET" json:"method"` // GET or PUT
	ExpiresAt     *time.Time `gorm:"column:expires_at" json:"expiresAt,omitempty"`
	MaxDownloads  *int       `gorm:"column:max_downloads" json:"maxDownloads,omitempty"`
	DownloadCount int        `gorm:"column:download_count;default:0" json:"downloadCount"`
	CreatedBy     string     `gorm:"column:created_by;size:255" json:"createdBy,omitempty"` // access_key_id
	CreatedAt     time.Time  `gorm:"column:created_at;default:CURRENT_TIMESTAMP" json:"createdAt"`
}

func CreatePresignedURL added in v0.2.0

func CreatePresignedURL(bucket, key, method, createdBy string, expiresIn *time.Duration, maxDownloads *int) (*PresignedURL, error)

func GetPresignedURLByToken added in v0.2.0

func GetPresignedURLByToken(token string) (*PresignedURL, error)

func ListPresignedURLs added in v0.2.0

func ListPresignedURLs() ([]PresignedURL, error)

func (PresignedURL) TableName added in v0.2.0

func (PresignedURL) TableName() string

type Saga

type Saga struct {
	// contains filtered or unexported fields
}

Saga orchestrates a sequence of steps where each step has a compensating action. If any step fails, all previously completed steps are rolled back in reverse order (the "saga pattern").

Use this when you need to coordinate changes across different systems that don't share a single transaction boundary for example, writing a DB record AND a file to disk.

func NewSaga

func NewSaga(name string) *Saga

NewSaga creates a new saga with the given name (used in log messages).

func (*Saga) AddStep

func (s *Saga) AddStep(step SagaStep)

AddStep appends a step to the saga.

func (*Saga) Execute

func (s *Saga) Execute() error

Execute runs all steps in order. If a step fails, it compensates all previously completed steps in reverse order and returns the original error. Compensation errors are logged but do not replace the original error.

type SagaStep

type SagaStep struct {
	Name       string       // human-readable label for logging
	Action     func() error // forward action (e.g. DB insert, FS write)
	Compensate func() error // rollback action (e.g. DB delete, FS remove)
}

SagaStep represents a single forward action with a compensating rollback.

type ServerStats

type ServerStats struct {
	ID              uint      `gorm:"primaryKey" json:"id"`
	Downloads       int       `gorm:"column:downloads;default:0" json:"downloads"`
	Requests        int       `gorm:"column:requests;default:0" json:"requests"`
	Uploads         int       `gorm:"column:uploads;default:0" json:"uploads"`
	BytesUploaded   int64     `gorm:"column:bytes_uploaded;default:0" json:"bytesUploaded"`
	BytesDownloaded int64     `gorm:"column:bytes_downloaded;default:0" json:"bytesDownloaded"`
	StartTime       time.Time `gorm:"column:start_time;default:CURRENT_TIMESTAMP" json:"startTime"`
}

func GetStats

func GetStats() (ServerStats, error)

GetStats retrieves the current server stats

func (ServerStats) TableName

func (ServerStats) TableName() string
type ShareableLink struct {
	ID           uint       `gorm:"primaryKey" json:"id"`
	Path         string     `gorm:"column:path;size:1024;not null" json:"path"`             // File or folder path
	Token        string     `gorm:"column:token;uniqueIndex;size:32;not null" json:"token"` // Unique token for the link
	PasswordHash string     `gorm:"column:password_hash;size:128" json:"-"`                 // Bcrypt hash (supports legacy SHA-256)
	ExpiresAt    *time.Time `gorm:"column:expires_at" json:"expiresAt,omitempty"`           // Optional expiry time
	AccessCount  int        `gorm:"column:access_count;default:0" json:"accessCount"`       // Number of times accessed
	CreatedAt    time.Time  `gorm:"column:created_at;default:CURRENT_TIMESTAMP" json:"createdAt"`
	CreatedBy    string     `gorm:"column:created_by;size:255" json:"createdBy,omitempty"` // Optional user identifier
}

ShareableLink represents a shareable link for a file or folder

func CreateShareableLink(path string, password string, expiresIn *time.Duration) (*ShareableLink, error)

CreateShareableLink creates a new shareable link for a file or folder

func GetShareableLinkByToken

func GetShareableLinkByToken(token string) (*ShareableLink, error)

GetShareableLinkByToken retrieves a shareable link by its token

func ListShareableLinks() ([]ShareableLink, error)

ListShareableLinks returns all shareable links

func (ShareableLink) TableName

func (ShareableLink) TableName() string

type StarredFile

type StarredFile struct {
	ID        uint      `gorm:"primaryKey" json:"id"`
	FilePath  string    `gorm:"column:file_path;uniqueIndex;not null" json:"filePath"`
	CreatedAt time.Time `gorm:"column:created_at;default:CURRENT_TIMESTAMP" json:"createdAt"`
}

StarredFile represents a starred file in the database

func GetStarredFiles

func GetStarredFiles() ([]StarredFile, error)

GetStarredFiles retrieves all starred files

func (StarredFile) TableName

func (StarredFile) TableName() string

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL