| 1 |
package attachment |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"fmt" |
| 6 |
"io" |
| 7 |
"sync" |
| 8 |
"time" |
| 9 |
|
| 10 |
"heckel.io/ntfy/v2/log" |
| 11 |
"heckel.io/ntfy/v2/model" |
| 12 |
"heckel.io/ntfy/v2/s3" |
| 13 |
"heckel.io/ntfy/v2/util" |
| 14 |
) |
| 15 |
|
| 16 |
const ( |
| 17 |
tagStore = "attachment_store" |
| 18 |
syncInterval = 15 * time.Minute // How often to run the background sync loop |
| 19 |
) |
| 20 |
|
| 21 |
var errInvalidFileID = errors.New("invalid file ID") |
| 22 |
|
| 23 |
// Store manages attachment storage with shared logic for size tracking, limiting, |
| 24 |
// ID validation, and background sync to reconcile storage with the database. |
| 25 |
type Store struct { |
| 26 |
backend backend |
| 27 |
limit int64 // Defined limit of the store in bytes |
| 28 |
size int64 // Current size of the store in bytes |
| 29 |
sizes map[string]int64 // File ID -> size, for subtracting on Remove |
| 30 |
attachmentsWithSizes func() (map[string]int64, error) // Returns file ID -> size for active attachments |
| 31 |
orphanGracePeriod time.Duration // Don't delete orphaned objects younger than this |
| 32 |
closeChan chan struct{} |
| 33 |
doneChan chan struct{} |
| 34 |
mu sync.RWMutex // Protects size and sizes |
| 35 |
} |
| 36 |
|
| 37 |
// NewFileStore creates a new file-system backed attachment cache |
| 38 |
func NewFileStore(dir string, totalSizeLimit int64, orphanGracePeriod time.Duration, attachmentsWithSizes func() (map[string]int64, error)) (*Store, error) { |
| 39 |
b, err := newFileBackend(dir) |
| 40 |
if err != nil { |
| 41 |
return nil, err |
| 42 |
} |
| 43 |
return newStore(b, totalSizeLimit, orphanGracePeriod, attachmentsWithSizes) |
| 44 |
} |
| 45 |
|
| 46 |
// NewS3Store creates a new S3-backed attachment cache. The s3URL must be in the format: |
| 47 |
// |
| 48 |
// s3://ACCESS_KEY:SECRET_KEY@BUCKET[/PREFIX]?region=REGION[&endpoint=ENDPOINT][&disable_http2=true] |
| 49 |
func NewS3Store(s3URL string, totalSizeLimit int64, orphanGracePeriod time.Duration, attachmentsWithSizes func() (map[string]int64, error)) (*Store, error) { |
| 50 |
config, err := s3.ParseURL(s3URL) |
| 51 |
if err != nil { |
| 52 |
return nil, err |
| 53 |
} |
| 54 |
return newStore(newS3Backend(s3.New(config)), totalSizeLimit, orphanGracePeriod, attachmentsWithSizes) |
| 55 |
} |
| 56 |
|
| 57 |
func newStore(backend backend, totalSizeLimit int64, orphanGracePeriod time.Duration, attachmentsWithSizes func() (map[string]int64, error)) (*Store, error) { |
| 58 |
c := &Store{ |
| 59 |
backend: backend, |
| 60 |
limit: totalSizeLimit, |
| 61 |
sizes: make(map[string]int64), |
| 62 |
attachmentsWithSizes: attachmentsWithSizes, |
| 63 |
orphanGracePeriod: orphanGracePeriod, |
| 64 |
closeChan: make(chan struct{}), |
| 65 |
doneChan: make(chan struct{}), |
| 66 |
} |
| 67 |
// Hydrate sizes from the database immediately so that Size()/Remaining()/Remove() |
| 68 |
// are accurate from the start, without waiting for the first sync() call. |
| 69 |
if attachmentsWithSizes != nil { |
| 70 |
attachments, err := attachmentsWithSizes() |
| 71 |
if err != nil { |
| 72 |
return nil, fmt.Errorf("attachment store: failed to load existing attachments: %w", err) |
| 73 |
} |
| 74 |
for id, size := range attachments { |
| 75 |
c.sizes[id] = size |
| 76 |
c.size += size |
| 77 |
} |
| 78 |
go c.syncLoop() |
| 79 |
} else { |
| 80 |
close(c.doneChan) |
| 81 |
} |
| 82 |
return c, nil |
| 83 |
} |
| 84 |
|
| 85 |
// Write stores an attachment file. The id is validated, and the write is subject to |
| 86 |
// the total size limit and any additional limiters. The untrustedLength is a hint |
| 87 |
// from the client's Content-Length header; backends may use it to optimize uploads (e.g. |
| 88 |
// streaming directly to S3 without buffering). |
| 89 |
func (c *Store) Write(id string, reader io.Reader, untrustedLength int64, limiters ...util.Limiter) (int64, error) { |
| 90 |
if !model.ValidMessageID(id) { |
| 91 |
return 0, errInvalidFileID |
| 92 |
} |
| 93 |
log.Tag(tagStore).Field("message_id", id).Debug("Writing attachment") |
| 94 |
limiters = append(limiters, util.NewFixedLimiter(c.Remaining())) |
| 95 |
countingReader := util.NewCountingReader(reader) |
| 96 |
limitReader := util.NewLimitReader(countingReader, limiters...) |
| 97 |
if err := c.backend.Put(id, limitReader, untrustedLength); err != nil { |
| 98 |
c.backend.Delete(id) //nolint:errcheck |
| 99 |
return 0, err |
| 100 |
} |
| 101 |
size := countingReader.Total() |
| 102 |
c.mu.Lock() |
| 103 |
c.size += size |
| 104 |
c.sizes[id] = size |
| 105 |
c.mu.Unlock() |
| 106 |
return size, nil |
| 107 |
} |
| 108 |
|
| 109 |
// Read retrieves an attachment file by ID |
| 110 |
func (c *Store) Read(id string) (io.ReadCloser, int64, error) { |
| 111 |
if !model.ValidMessageID(id) { |
| 112 |
return nil, 0, errInvalidFileID |
| 113 |
} |
| 114 |
return c.backend.Get(id) |
| 115 |
} |
| 116 |
|
| 117 |
// Remove deletes attachment files by ID and subtracts their known sizes from |
| 118 |
// the total. Sizes for objects not tracked (e.g. written before this process |
| 119 |
// started and before the first sync) are corrected by the next sync() call. |
| 120 |
func (c *Store) Remove(ids ...string) error { |
| 121 |
for _, id := range ids { |
| 122 |
if !model.ValidMessageID(id) { |
| 123 |
return errInvalidFileID |
| 124 |
} |
| 125 |
} |
| 126 |
// Remove from backend |
| 127 |
for _, id := range ids { |
| 128 |
log.Tag(tagStore).Field("message_id", id).Debug("Removing attachment") |
| 129 |
} |
| 130 |
if err := c.backend.Delete(ids...); err != nil { |
| 131 |
return err |
| 132 |
} |
| 133 |
// Update total cache size |
| 134 |
c.mu.Lock() |
| 135 |
for _, id := range ids { |
| 136 |
if size, ok := c.sizes[id]; ok { |
| 137 |
c.size -= size |
| 138 |
delete(c.sizes, id) |
| 139 |
} |
| 140 |
} |
| 141 |
if c.size < 0 { |
| 142 |
c.size = 0 |
| 143 |
} |
| 144 |
c.mu.Unlock() |
| 145 |
return nil |
| 146 |
} |
| 147 |
|
| 148 |
// Sync triggers an immediate reconciliation of storage with the database. |
| 149 |
func (c *Store) Sync() error { |
| 150 |
return c.sync() |
| 151 |
} |
| 152 |
|
| 153 |
// sync reconciles the backend storage with the database. It lists all objects, |
| 154 |
// deletes orphans (not in the valid ID set and older than the grace period), and |
| 155 |
// recomputes the total size from the existing attachments in the database. |
| 156 |
func (c *Store) sync() error { |
| 157 |
if c.attachmentsWithSizes == nil { |
| 158 |
return nil |
| 159 |
} |
| 160 |
attachmentsWithSizes, err := c.attachmentsWithSizes() |
| 161 |
if err != nil { |
| 162 |
return fmt.Errorf("attachment sync: failed to get existing attachments: %w", err) |
| 163 |
} |
| 164 |
remoteObjects, err := c.backend.List() |
| 165 |
if err != nil { |
| 166 |
return fmt.Errorf("attachment sync: failed to list objects: %w", err) |
| 167 |
} |
| 168 |
// Calculate total cache size and collect orphaned attachments, excluding objects younger |
| 169 |
// than the grace period to account for races, and skipping objects with invalid IDs. |
| 170 |
cutoff := time.Now().Add(-c.orphanGracePeriod) |
| 171 |
var orphanIDs []string |
| 172 |
var count, totalSize int64 |
| 173 |
sizes := make(map[string]int64, len(remoteObjects)) |
| 174 |
for _, obj := range remoteObjects { |
| 175 |
if !model.ValidMessageID(obj.ID) { |
| 176 |
continue |
| 177 |
} |
| 178 |
if _, ok := attachmentsWithSizes[obj.ID]; !ok && obj.LastModified.Before(cutoff) { |
| 179 |
orphanIDs = append(orphanIDs, obj.ID) |
| 180 |
} else { |
| 181 |
count++ |
| 182 |
totalSize += attachmentsWithSizes[obj.ID] |
| 183 |
sizes[obj.ID] = attachmentsWithSizes[obj.ID] |
| 184 |
} |
| 185 |
} |
| 186 |
log.Tag(tagStore).Debug("Attachment store updated: %d attachment(s), %s", count, util.FormatSizeHuman(totalSize)) |
| 187 |
c.mu.Lock() |
| 188 |
c.size = totalSize |
| 189 |
c.sizes = sizes |
| 190 |
c.mu.Unlock() |
| 191 |
// Delete orphaned attachments |
| 192 |
if len(orphanIDs) > 0 { |
| 193 |
log.Tag(tagStore).Debug("Deleting %d orphaned attachment(s)", len(orphanIDs)) |
| 194 |
if err := c.backend.Delete(orphanIDs...); err != nil { |
| 195 |
return fmt.Errorf("attachment sync: failed to delete orphaned objects: %w", err) |
| 196 |
} |
| 197 |
} |
| 198 |
// Clean up incomplete uploads (S3 only) |
| 199 |
if err := c.backend.DeleteIncomplete(cutoff); err != nil { |
| 200 |
log.Tag(tagStore).Err(err).Warn("Failed to abort incomplete uploads from attachment cache") |
| 201 |
} |
| 202 |
return nil |
| 203 |
} |
| 204 |
|
| 205 |
// Size returns the current total size of all attachments |
| 206 |
func (c *Store) Size() int64 { |
| 207 |
c.mu.RLock() |
| 208 |
defer c.mu.RUnlock() |
| 209 |
return c.size |
| 210 |
} |
| 211 |
|
| 212 |
// Remaining returns the remaining capacity for attachments |
| 213 |
func (c *Store) Remaining() int64 { |
| 214 |
c.mu.RLock() |
| 215 |
defer c.mu.RUnlock() |
| 216 |
remaining := c.limit - c.size |
| 217 |
if remaining < 0 { |
| 218 |
return 0 |
| 219 |
} |
| 220 |
return remaining |
| 221 |
} |
| 222 |
|
| 223 |
// Close stops the background sync goroutine and waits for it to finish |
| 224 |
func (c *Store) Close() { |
| 225 |
close(c.closeChan) |
| 226 |
<-c.doneChan |
| 227 |
} |
| 228 |
|
| 229 |
func (c *Store) syncLoop() { |
| 230 |
defer close(c.doneChan) |
| 231 |
if err := c.sync(); err != nil { |
| 232 |
log.Tag(tagStore).Err(err).Warn("Attachment sync failed") |
| 233 |
} |
| 234 |
ticker := time.NewTicker(syncInterval) |
| 235 |
defer ticker.Stop() |
| 236 |
for { |
| 237 |
select { |
| 238 |
case <-ticker.C: |
| 239 |
if err := c.sync(); err != nil { |
| 240 |
log.Tag(tagStore).Err(err).Warn("Attachment sync failed") |
| 241 |
} |
| 242 |
case <-c.closeChan: |
| 243 |
return |
| 244 |
} |
| 245 |
} |
| 246 |
} |