Migrating hosting from Codeberg to git.kmalloc.org. Renames the module path in go.mod, every internal import, and the OCI image source label in the Dockerfile. Build and full test suite verified green after the rename.
68 lines
2.3 KiB
Go
68 lines
2.3 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"errors"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/uptrace/bun"
|
|
|
|
"git.kmalloc.org/squid/sonda/internal/waveform"
|
|
)
|
|
|
|
type peaksRow struct {
|
|
bun.BaseModel `bun:"table:track_peaks"`
|
|
|
|
TrackID int64 `bun:"track_id,pk"`
|
|
SizeBytes int64 `bun:"size_bytes,notnull"`
|
|
MTimeUnix int64 `bun:"mtime_unix,notnull"`
|
|
Peaks []byte `bun:"peaks,notnull"`
|
|
UpdatedAt int64 `bun:"updated_at,notnull"`
|
|
}
|
|
|
|
// WaveformRepo keeps the shape of tracks. It implements waveform.Store.
|
|
type WaveformRepo struct{ db *bun.DB }
|
|
|
|
// NewWaveformRepo builds a WaveformRepo.
|
|
func NewWaveformRepo(db *bun.DB) *WaveformRepo { return &WaveformRepo{db: db} }
|
|
|
|
// Get returns what is kept for a track, with found=false when nothing is.
|
|
func (r *WaveformRepo) Get(ctx context.Context, trackID int64) (waveform.Record, bool, error) {
|
|
var row peaksRow
|
|
err := r.db.NewSelect().Model(&row).Where("track_id = ?", trackID).Limit(1).Scan(ctx)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return waveform.Record{}, false, nil
|
|
}
|
|
if err != nil {
|
|
return waveform.Record{}, false, fmt.Errorf("select track peaks: %w", err)
|
|
}
|
|
return waveform.Record{SizeBytes: row.SizeBytes, MTimeUnix: row.MTimeUnix, Peaks: row.Peaks}, true, nil
|
|
}
|
|
|
|
// Save keeps the shape of a track, replacing an older one. A track that no longer exists is not an error: its shape is
|
|
// simply not kept (it was deleted while its file was being decoded).
|
|
func (r *WaveformRepo) Save(ctx context.Context, trackID int64, rec waveform.Record) error {
|
|
peaks := rec.Peaks
|
|
if peaks == nil {
|
|
peaks = []byte{} // the column cannot be NULL: empty means "could not be decoded"
|
|
}
|
|
row := &peaksRow{TrackID: trackID, SizeBytes: rec.SizeBytes, MTimeUnix: rec.MTimeUnix, Peaks: peaks, UpdatedAt: time.Now().Unix()}
|
|
_, err := r.db.NewInsert().Model(row).
|
|
On("CONFLICT (track_id) DO UPDATE").
|
|
Set("size_bytes = EXCLUDED.size_bytes").
|
|
Set("mtime_unix = EXCLUDED.mtime_unix").
|
|
Set("peaks = EXCLUDED.peaks").
|
|
Set("updated_at = EXCLUDED.updated_at").
|
|
Exec(ctx)
|
|
if err != nil {
|
|
// The track was deleted while its file was being decoded: there is nothing to keep the shape for.
|
|
if strings.Contains(strings.ToLower(err.Error()), "foreign key") {
|
|
return nil
|
|
}
|
|
return fmt.Errorf("save track peaks: %w", err)
|
|
}
|
|
return nil
|
|
}
|