| 1 | package mapa |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "log/slog" |
| 10 | "strconv" |
| 11 | "strings" |
| 12 | "time" |
| 13 | "unicode/utf8" |
| 14 | |
| 15 | "amadan.net/rastrillo/rastrillo/blobs" |
| 16 | |
| 17 | "amadan.net/oficina/mapa/internal/mapa/locale" |
| 18 | "amadan.net/oficina/mapa/internal/mapa/markup" |
| 19 | ) |
| 20 | |
| 21 | // Images (docs/superpowers/specs/2026-11-17-mapa-images.md). An image is |
| 22 | // one picture in one place: a row in images, and its bytes sealed under |
| 23 | // Mapa's DEK in the object store, keyed by the ciphertext's hash. A |
| 24 | // reader gets them only through GET /i/{id}, which checks scope first |
| 25 | // (decision 2). Copies are separate rows with separate objects. |
| 26 | |
| 27 | // The event vocabulary's image half (§6): an upload or copy, and a |
| 28 | // person's removal. The sweep logs nothing: retention is exempt by |
| 29 | // name (base §5, §3.3 here). |
| 30 | const ( |
| 31 | ObjectImage = "image" |
| 32 | VerbUploaded = "uploaded" |
| 33 | VerbRemoved = "removed" |
| 34 | ) |
| 35 | |
| 36 | // The limits (§3.4, §1.4, Paul 2026-11-17). |
| 37 | const ( |
| 38 | MaxImageBytes = 10 << 20 |
| 39 | DefaultQuotaPerson = 1 << 30 |
| 40 | DefaultQuotaTeam = 10 << 30 |
| 41 | // PendingWindow is how long the sweep keeps an image attached to |
| 42 | // nothing, unless a draft names it (§3.3). Reads apply no window. |
| 43 | PendingWindow = 7 * 24 * time.Hour |
| 44 | // BlobSlots is how many blob operations run at once (§1.4): two, |
| 45 | // until the figure is measured on the instance (build note I14). |
| 46 | BlobSlots = 2 |
| 47 | // UploadReads is how many uploads are read into memory at once |
| 48 | // (Fable N7): each holds up to its bound, before any blob slot. |
| 49 | UploadReads = 4 |
| 50 | // waitForever is the importer's wait (§7). |
| 51 | waitForever = -1 |
| 52 | ) |
| 53 | |
| 54 | // uploadWait and serveWait are how long an upload or copy, and a GET |
| 55 | // /i/{id}, wait for a blob slot before answering 503 (§1.4). |
| 56 | const ( |
| 57 | uploadWait = 10 * time.Second |
| 58 | serveWait = 30 * time.Second |
| 59 | ) |
| 60 | |
| 61 | // The typed refusals the importer writes in place of an image (§7), |
| 62 | // and the routes answer. |
| 63 | var ( |
| 64 | ErrImageType = errors.New("mapa: not a PNG, JPEG, GIF or WebP") |
| 65 | ErrImageTooLarge = errors.New("mapa: an image is at most 10 MB") |
| 66 | ErrImageDimensions = errors.New("mapa: the picture is too large") |
| 67 | ErrImageQuota = errors.New("mapa: over the image allowance") |
| 68 | ErrNoImageStore = errors.New("mapa: images aren't set up") |
| 69 | // ErrImageBusy is a wait for a blob slot that ran out (§1.4). |
| 70 | ErrImageBusy = errors.New("mapa: too many images at once") |
| 71 | // ErrStorageFull is the platform refusing PutObject (§3.4). |
| 72 | ErrStorageFull = errors.New("mapa: the storage is full") |
| 73 | ) |
| 74 | |
| 75 | // quotaError says which allowance an upload is over (§3.4). |
| 76 | type quotaError struct { |
| 77 | team bool |
| 78 | limit int64 |
| 79 | } |
| 80 | |
| 81 | func (refusal quotaError) Error() string { return refusal.say(nil) } |
| 82 | |
| 83 | // say is the refusal with its size written in dates's locale (level-up |
| 84 | // build note 85). |
| 85 | func (refusal quotaError) say(dates *locale.Locale) string { |
| 86 | if refusal.team { |
| 87 | return "Team pages hold " + byteSize(dates, refusal.limit) + |
| 88 | " of images, so Mapa takes no more uploads until some are " + |
| 89 | "removed." |
| 90 | } |
| 91 | return "Your image allowance of " + byteSize(dates, refusal.limit) + |
| 92 | " is full. Remove an image before uploading again." |
| 93 | } |
| 94 | |
| 95 | func (quotaError) Is(target error) bool { return target == ErrImageQuota } |
| 96 | |
| 97 | // byteSize is a size as the quota messages say it, its number in |
| 98 | // dates's locale. |
| 99 | func byteSize(dates *locale.Locale, size int64) string { |
| 100 | switch { |
| 101 | case size%(1<<30) == 0: |
| 102 | return dates.Number(int(size>>30)) + " GB" |
| 103 | case size%(1<<20) == 0: |
| 104 | return dates.Number(int(size>>20)) + " MB" |
| 105 | case size%(1<<10) == 0: |
| 106 | return dates.Number(int(size>>10)) + " KB" |
| 107 | } |
| 108 | return dates.Number(int(size)) + " bytes" |
| 109 | } |
| 110 | |
| 111 | // ImageSetup is the images' platform config (§1.2 decision 4, §3.4). |
| 112 | type ImageSetup struct { |
| 113 | // Objects is where sealed bytes go; nil when none is bound. |
| 114 | Objects blobs.Store |
| 115 | // Missing names the CARLOS_STORE_* a partly delivered store lacks. |
| 116 | Missing []string |
| 117 | QuotaPerson, QuotaTeam int64 |
| 118 | } |
| 119 | |
| 120 | // Image is one image as the store hands it out: its public id, and its |
| 121 | // size as shown. |
| 122 | type Image struct { |
| 123 | PublicID string |
| 124 | Width, Height int |
| 125 | } |
| 126 | |
| 127 | // Markdown is "", with alt cleaned to §2.1's form: |
| 128 | // [, ] and line breaks removed, and at most 1,000 bytes, cut at a rune. |
| 129 | func (image Image) Markdown(alt string) string { |
| 130 | return "" |
| 132 | } |
| 133 | |
| 134 | // CleanAlt is alt text as Mapa keeps it (§2.1). |
| 135 | func CleanAlt(alt string) string { |
| 136 | alt = strings.Map(func(char rune) rune { |
| 137 | if strings.ContainsRune("[]\r\n", char) { |
| 138 | return -1 |
| 139 | } |
| 140 | return char |
| 141 | }, alt) |
| 142 | if len(alt) <= markup.MaxAlt { |
| 143 | return alt |
| 144 | } |
| 145 | cut := markup.MaxAlt |
| 146 | for cut > 0 && !utf8.RuneStart(alt[cut]) { |
| 147 | cut-- |
| 148 | } |
| 149 | return alt[:cut] |
| 150 | } |
| 151 | |
| 152 | // images is the store's image state. |
| 153 | type images struct { |
| 154 | setup ImageSetup |
| 155 | slots chan struct{} |
| 156 | // reads bounds the uploads read into memory at once (UploadReads). |
| 157 | reads chan struct{} |
| 158 | // nonces draws a public id; a test may replace it. |
| 159 | nonces func() (int64, error) |
| 160 | // waits is how long a wait for a slot lasts: uploadWait and |
| 161 | // serveWait, unless a test shortens them. |
| 162 | waits map[time.Duration]time.Duration |
| 163 | } |
| 164 | |
| 165 | // SetImageWaits shortens the waits for a blob slot. Tests only: IMG6 |
| 166 | // need not wait ten seconds to see a 503. |
| 167 | func (store *Store) SetImageWaits(upload, serve time.Duration) { |
| 168 | store.images.waits = map[time.Duration]time.Duration{ |
| 169 | uploadWait: upload, serveWait: serve} |
| 170 | } |
| 171 | |
| 172 | // UseImages binds the object store and limits. Without it, uploads |
| 173 | // answer ErrNoImageStore. |
| 174 | func (store *Store) UseImages(setup ImageSetup) { |
| 175 | if setup.QuotaPerson == 0 { |
| 176 | setup.QuotaPerson = DefaultQuotaPerson |
| 177 | } |
| 178 | if setup.QuotaTeam == 0 { |
| 179 | setup.QuotaTeam = DefaultQuotaTeam |
| 180 | } |
| 181 | store.images.setup = setup |
| 182 | } |
| 183 | |
| 184 | // SetImageNonces replaces how image public ids are drawn. Tests only: |
| 185 | // IMG1 gives two runs the same team-side ids. |
| 186 | func (store *Store) SetImageNonces(next func() int64) { |
| 187 | store.images.nonces = func() (int64, error) { return next(), nil } |
| 188 | } |
| 189 | |
| 190 | // acquire takes a blob slot, waiting at most wait (forever when |
| 191 | // negative), and returns its release. |
| 192 | func (state *images) acquire(ctx context.Context, |
| 193 | wait time.Duration) (func(), error) { |
| 194 | return state.take(ctx, state.slots, wait) |
| 195 | } |
| 196 | |
| 197 | // AcquireRead takes one of the UploadReads slots, waiting as an upload |
| 198 | // waits for a blob slot, and returns its release. |
| 199 | func (store *Store) AcquireRead(ctx context.Context) (func(), error) { |
| 200 | return store.images.take(ctx, store.images.reads, uploadWait) |
| 201 | } |
| 202 | |
| 203 | // take takes a place in slots, waiting at most wait. |
| 204 | func (state *images) take(ctx context.Context, slots chan struct{}, |
| 205 | wait time.Duration) (func(), error) { |
| 206 | release := func() { <-slots } |
| 207 | if shorter, ok := state.waits[wait]; ok { |
| 208 | wait = shorter |
| 209 | } |
| 210 | if wait < 0 { |
| 211 | select { |
| 212 | case slots <- struct{}{}: |
| 213 | return release, nil |
| 214 | case <-ctx.Done(): |
| 215 | return nil, ctx.Err() |
| 216 | } |
| 217 | } |
| 218 | timer := time.NewTimer(wait) |
| 219 | defer timer.Stop() |
| 220 | select { |
| 221 | case slots <- struct{}{}: |
| 222 | return release, nil |
| 223 | case <-timer.C: |
| 224 | return nil, ErrImageBusy |
| 225 | case <-ctx.Done(): |
| 226 | return nil, ctx.Err() |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | // objects is the bound store, or ErrNoImageStore. |
| 231 | func (store *Store) objects() (blobs.Store, error) { |
| 232 | if store.images.setup.Objects == nil { |
| 233 | return nil, ErrNoImageStore |
| 234 | } |
| 235 | return store.images.setup.Objects, nil |
| 236 | } |
| 237 | |
| 238 | // LogImageSetup says, once at boot, what the images are stored in: a |
| 239 | // partial store is loud and names what it lacks (decision 4). |
| 240 | func LogImageSetup(logger *slog.Logger, setup ImageSetup) { |
| 241 | switch { |
| 242 | case len(setup.Missing) > 0: |
| 243 | logger.Error("mapa: the object store is only partly delivered; "+ |
| 244 | "uploads answer 503", "missing", |
| 245 | strings.Join(setup.Missing, ", ")) |
| 246 | case setup.Objects == nil: |
| 247 | logger.Warn("mapa: no object store is bound; uploads answer 503") |
| 248 | default: |
| 249 | logger.Info("mapa: object store bound") |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | // objectKey is the SHA-256 of the ciphertext (decision 3). |
| 254 | func objectKey(sealed []byte) string { |
| 255 | sum := sha256.Sum256(sealed) |
| 256 | return hex.EncodeToString(sum[:]) |
| 257 | } |
| 258 | |
| 259 | // publicImageID draws a public id: random base 36, never sequential. |
| 260 | func (store *Store) publicImageID() (string, error) { |
| 261 | draw := store.images.nonces |
| 262 | if draw == nil { |
| 263 | draw = randomPositive |
| 264 | } |
| 265 | nonce, err := draw() |
| 266 | if err != nil { |
| 267 | return "", fmt.Errorf("mapa: drawing an image id: %w", err) |
| 268 | } |
| 269 | return strconv.FormatInt(nonce, 36), nil |
| 270 | } |
| 271 | |