Files
byre/internal/store/blob.go
T

73 lines
1.7 KiB
Go
Raw Normal View History

2026-10-14 20:07:26 -07:00
package store
import (
"context"
"database/sql"
"errors"
"os"
"path/filepath"
"time"
2026-10-18 15:32:07 -07:00
"g.fc.run/ai/byre/internal/api"
2026-10-14 20:07:26 -07:00
)
const MaxBlobBytes = 5 << 20
var ImageTypes = map[string]bool{
"image/png": true,
"image/jpeg": true,
"image/gif": true,
"image/webp": true,
}
2026-10-14 20:07:26 -07:00
func (s *Store) CreateBlob(ctx context.Context, contentType string, data []byte, actor string) (api.Blob, error) {
b := api.Blob{
Id: NewID(),
ContentType: contentType,
CreatedBy: actor,
CreatedAt: time.Now().UTC(),
}
2026-10-20 21:53:37 -07:00
path := s.blobPath(b.Id)
2026-10-14 20:07:26 -07:00
2026-10-20 21:53:37 -07:00
err := os.MkdirAll(filepath.Dir(path), 0o755)
2026-10-14 20:07:26 -07:00
if err != nil {
return b, err
}
2026-10-20 21:53:37 -07:00
err = os.WriteFile(path, data, 0o644)
2026-10-14 20:07:26 -07:00
if err != nil {
return b, err
}
2026-10-20 21:53:37 -07:00
_, err = s.db.ExecContext(ctx, `INSERT INTO blobs (id, content_type, created_by, created_at) VALUES (?, ?, ?, ?)`,
b.Id, b.ContentType, b.CreatedBy, formatTime(b.CreatedAt))
2026-10-14 20:07:26 -07:00
return b, err
}
func (s *Store) GetBlob(ctx context.Context, id string) (api.Blob, string, error) {
b := api.Blob{}
createdAt := ""
2026-10-20 21:53:37 -07:00
err := s.db.QueryRowContext(ctx, `SELECT id, content_type, created_by, created_at FROM blobs WHERE id = ?`, id).
Scan(&b.Id, &b.ContentType, &b.CreatedBy, &createdAt)
2026-10-14 20:07:26 -07:00
if errors.Is(err, sql.ErrNoRows) {
return b, "", errors.Join(ErrNotFound, errors.New("no blob "+id))
}
if err != nil {
return b, "", err
}
b.CreatedAt, err = parseTime(createdAt)
2026-10-20 21:53:37 -07:00
return b, s.blobPath(b.Id), err
2026-10-14 20:07:26 -07:00
}
func (s *Store) ReadBlob(ctx context.Context, id string) (api.Blob, []byte, error) {
b, path, err := s.GetBlob(ctx, id)
if err != nil {
return b, nil, err
}
data, err := os.ReadFile(path)
return b, data, err
}
2026-10-20 21:53:37 -07:00
func (s *Store) blobPath(id string) string {
return filepath.Join(filepath.Dir(s.path), "blobs", id)
2026-10-14 20:07:26 -07:00
}