| 1 | package mapa |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/mapa/internal/mapa/imagefile" |
| 13 | "amadan.net/oficina/mapa/internal/mapa/seal" |
| 14 | ) |
| 15 | |
| 16 | // Getting an image in (§3.2 items 1 and 3): an upload or a copy makes a |
| 17 | // pending image owned by the person, attached to nothing, and logs |
| 18 | // "uploaded". The object work happens before any transaction: the bytes |
| 19 | // are checked, stripped, padded, sealed and Put, and only then is the |
| 20 | // row written. A transaction that fails after a Put deletes the object. |
| 21 | |
| 22 | // imageRecord is what an image's sealed record holds (§1.3). |
| 23 | type imageRecord struct { |
| 24 | Type string `json:"type"` |
| 25 | Width int `json:"width"` |
| 26 | Height int `json:"height"` |
| 27 | // Size is the true length, before padding. |
| 28 | Size int `json:"size"` |
| 29 | } |
| 30 | |
| 31 | // stored is one sealed object, Put, waiting for its row. |
| 32 | type stored struct { |
| 33 | key string |
| 34 | size int64 |
| 35 | record []byte |
| 36 | image Image |
| 37 | } |
| 38 | |
| 39 | // AddImage reads one image, checks and strips it (§5), seals it, stores |
| 40 | // it, and records it as a pending image owned by actor, logging |
| 41 | // "uploaded" by actor (never Mapa). It waits for the blob semaphore |
| 42 | // (§1.4) rather than failing. |
| 43 | func (store *Store) AddImage(ctx context.Context, actor int64, |
| 44 | data io.Reader) (Image, error) { |
| 45 | return store.addImage(ctx, byMember(actor), data, waitForever) |
| 46 | } |
| 47 | |
| 48 | // UploadImage is AddImage for a person named by address, as the route |
| 49 | // has them: their first write creates their member row. It waits |
| 50 | // uploadWait for a slot. |
| 51 | func (store *Store) UploadImage(ctx context.Context, who string, |
| 52 | data io.Reader) (Image, error) { |
| 53 | return store.addImage(ctx, byAddress(who), data, uploadWait) |
| 54 | } |
| 55 | |
| 56 | // person is who an image write is by: a member id, or an address |
| 57 | // whose member row the write creates if need be. |
| 58 | type person struct { |
| 59 | id int64 |
| 60 | address string |
| 61 | } |
| 62 | |
| 63 | func byMember(id int64) person { return person{id: id} } |
| 64 | func byAddress(address string) person { return person{address: address} } |
| 65 | |
| 66 | // in is the person's member id inside tx. |
| 67 | func (who person) in(tx *Tx) (int64, error) { |
| 68 | if who.address == "" { |
| 69 | return who.id, nil |
| 70 | } |
| 71 | return tx.member(who.address) |
| 72 | } |
| 73 | |
| 74 | // known is the person's member id outside a write, 0 for nobody yet. |
| 75 | func (store *Store) known(ctx context.Context, who person) (int64, error) { |
| 76 | if who.address == "" { |
| 77 | return who.id, nil |
| 78 | } |
| 79 | viewer, err := store.Viewer(ctx, who.address, nil) |
| 80 | return viewer.MemberID, err |
| 81 | } |
| 82 | |
| 83 | // UploadBytes is UploadImage for bytes already read (the route's, in |
| 84 | // bounded memory): no second copy (Fable N7). |
| 85 | func (store *Store) UploadBytes(ctx context.Context, who string, |
| 86 | raw []byte) (Image, error) { |
| 87 | return store.addRaw(ctx, byAddress(who), raw, uploadWait) |
| 88 | } |
| 89 | |
| 90 | func (store *Store) addImage(ctx context.Context, who person, |
| 91 | data io.Reader, wait time.Duration) (Image, error) { |
| 92 | if _, err := store.objects(); err != nil { |
| 93 | return Image{}, err |
| 94 | } |
| 95 | raw, err := io.ReadAll(io.LimitReader(data, MaxImageBytes+1)) |
| 96 | if err != nil { |
| 97 | return Image{}, err |
| 98 | } |
| 99 | return store.addRaw(ctx, who, raw, wait) |
| 100 | } |
| 101 | |
| 102 | // addRaw checks, strips, seals and stores raw, holding a blob slot. |
| 103 | func (store *Store) addRaw(ctx context.Context, who person, raw []byte, |
| 104 | wait time.Duration) (Image, error) { |
| 105 | if _, err := store.objects(); err != nil { |
| 106 | return Image{}, err |
| 107 | } |
| 108 | if len(raw) > MaxImageBytes { |
| 109 | return Image{}, ErrImageTooLarge |
| 110 | } |
| 111 | release, err := store.images.acquire(ctx, wait) |
| 112 | if err != nil { |
| 113 | return Image{}, err |
| 114 | } |
| 115 | defer release() |
| 116 | cleaned, info, err := imagefile.Clean(raw) |
| 117 | if err != nil { |
| 118 | return Image{}, refusalOf(err) |
| 119 | } |
| 120 | return store.keep(ctx, who, cleaned, info) |
| 121 | } |
| 122 | |
| 123 | // refusalOf is a walker's refusal as the store's typed one. |
| 124 | func refusalOf(err error) error { |
| 125 | switch { |
| 126 | case errors.Is(err, imagefile.ErrDimensions): |
| 127 | return ErrImageDimensions |
| 128 | case errors.Is(err, imagefile.ErrType), |
| 129 | errors.Is(err, imagefile.ErrMalformed): |
| 130 | return ErrImageType |
| 131 | } |
| 132 | return err |
| 133 | } |
| 134 | |
| 135 | // keep checks the allowances, seals and Puts plain, and writes its row. |
| 136 | // The caller holds a blob slot. |
| 137 | func (store *Store) keep(ctx context.Context, who person, plain []byte, |
| 138 | info imagefile.Info) (Image, error) { |
| 139 | sealed, err := store.sealImage(plain, info) |
| 140 | if err != nil { |
| 141 | return Image{}, err |
| 142 | } |
| 143 | member, err := store.known(ctx, who) |
| 144 | if err != nil { |
| 145 | return Image{}, err |
| 146 | } |
| 147 | if err := store.checkQuota(ctx, member, sealed.size); err != nil { |
| 148 | return Image{}, err |
| 149 | } |
| 150 | if err := store.putObject(ctx, sealed.key, sealed.blob); err != nil { |
| 151 | return Image{}, err |
| 152 | } |
| 153 | image, err := store.recordImage(ctx, who, sealed) |
| 154 | if err != nil { |
| 155 | store.dropObject(ctx, sealed.key) |
| 156 | } |
| 157 | return image, err |
| 158 | } |
| 159 | |
| 160 | // sealedImage is one image sealed for the bucket. |
| 161 | type sealedImage struct { |
| 162 | stored |
| 163 | blob []byte |
| 164 | } |
| 165 | |
| 166 | // sealImage pads and seals plain under the image purpose, and seals its |
| 167 | // record (decision 1). |
| 168 | func (store *Store) sealImage(plain []byte, |
| 169 | info imagefile.Info) (sealedImage, error) { |
| 170 | blob, err := store.sealer.SealPadded(seal.PurposeImage, plain) |
| 171 | if err != nil { |
| 172 | return sealedImage{}, err |
| 173 | } |
| 174 | record, err := json.Marshal(imageRecord{Type: info.Type, |
| 175 | Width: info.Width, Height: info.Height, Size: len(plain)}) |
| 176 | if err != nil { |
| 177 | return sealedImage{}, err |
| 178 | } |
| 179 | sealedRecord, err := store.sealer.Seal(seal.PurposeImageRecord, record) |
| 180 | if err != nil { |
| 181 | return sealedImage{}, err |
| 182 | } |
| 183 | return sealedImage{blob: blob, stored: stored{key: objectKey(blob), |
| 184 | size: int64(len(blob)), record: sealedRecord, |
| 185 | image: Image{Width: info.Width, Height: info.Height}}}, nil |
| 186 | } |
| 187 | |
| 188 | // putObject stores sealed bytes as application/octet-stream. A refusal |
| 189 | // from the platform (403 past the plan's grace) is ErrStorageFull. |
| 190 | func (store *Store) putObject(ctx context.Context, key string, |
| 191 | blob []byte) error { |
| 192 | objects, err := store.objects() |
| 193 | if err != nil { |
| 194 | return err |
| 195 | } |
| 196 | // A Buffer, so a store that can take its bytes as they are does |
| 197 | // (bucket.Put). |
| 198 | ref, err := objects.Put(ctx, bytes.NewBuffer(blob), |
| 199 | "application/octet-stream") |
| 200 | if err != nil { |
| 201 | if errors.Is(err, errPutDenied) { |
| 202 | return fmt.Errorf("%w: %v", ErrStorageFull, err) |
| 203 | } |
| 204 | return fmt.Errorf("mapa: storing an image: %w", err) |
| 205 | } |
| 206 | if ref.Hash != key { |
| 207 | store.dropObject(ctx, ref.Hash) |
| 208 | return errors.New("mapa: the object store keyed an image " + |
| 209 | "by another hash") |
| 210 | } |
| 211 | return nil |
| 212 | } |
| 213 | |
| 214 | // dropObject deletes an object no row names, now; if that fails it is |
| 215 | // logged, never returned: the row's absence is what matters. |
| 216 | func (store *Store) dropObject(ctx context.Context, key string) { |
| 217 | objects, err := store.objects() |
| 218 | if err == nil { |
| 219 | err = objects.Delete(context.WithoutCancel(ctx), key) |
| 220 | } |
| 221 | if err != nil { |
| 222 | store.logger().Error("mapa: deleting an image object", "err", err) |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | // recordImage writes a pending image's row and its event. |
| 227 | func (store *Store) recordImage(ctx context.Context, who person, |
| 228 | sealed sealedImage) (Image, error) { |
| 229 | image := sealed.image |
| 230 | err := store.write(ctx, func(tx *Tx) error { |
| 231 | actor, err := who.in(tx) |
| 232 | if err != nil { |
| 233 | return err |
| 234 | } |
| 235 | if image.PublicID, err = store.publicImageID(); err != nil { |
| 236 | return err |
| 237 | } |
| 238 | row := ImageRow{PublicID: image.PublicID, OwnerID: actor, |
| 239 | CreatedAt: tx.at, StoredBytes: sealed.size, |
| 240 | ObjectKey: sealed.key, SealedRecord: sealed.record} |
| 241 | if err := tx.db.Create(&row).Error; err != nil { |
| 242 | return fmt.Errorf("mapa: recording an image: %w", err) |
| 243 | } |
| 244 | return tx.log(actor, ObjectImage, row.ID, VerbUploaded, 0) |
| 245 | }) |
| 246 | return image, err |
| 247 | } |
| 248 | |