Line data Source code
1 4 : (ns matchscore.media.storage
2 : "Private object storage for media images.
3 :
4 : A storage instance knows how to persist object bytes under immutable random
5 : keys, delete objects (best effort, retried by cleanup), and produce
6 : short-lived signed read URLs. The database stores metadata and keys only —
7 : never signed URLs.
8 :
9 : Two implementations exist:
10 : - `make-memory-storage`: in-memory fake for tests and local development.
11 : - `matchscore.media.storage.s3/make-s3-storage`: official AWS SDK v2 adapter
12 : using the SDK standard credential chain."
13 : (:import
14 : (java.nio.charset StandardCharsets)
15 : (java.time Instant)
16 : (java.util Base64)))
17 :
18 :
19 4 : (defprotocol
20 : MediaStorage
21 : (put-object!
22 : [this key content-type bytes]
23 : "Stores bytes under key. Throws on failure.")
24 : (get-object
25 : [this key]
26 : "Returns stored bytes or nil. Used by tests/diagnostics.")
27 : (delete-object!
28 : [this key]
29 : "Deletes the object; idempotent (missing object is success). Throws only
30 : on transport failure, so cleanup can retry.")
31 : (sign-get-url
32 : [this key expires-at]
33 : "Returns a signed read URL valid until expires-at (an Instant)."))
34 :
35 :
36 4 : (defn random-key
37 : "Immutable, unguessable object key prefix for an asset derivative."
38 : [label]
39 5 : (let [uuid-str (str (java.util.UUID/randomUUID))
40 3 : encoder (.withoutPadding (Base64/getUrlEncoder))
41 7 : b64 (.encodeToString encoder (.getBytes (str label uuid-str) StandardCharsets/UTF_8))]
42 6 : (str "media/" label "/" b64)))
43 :
44 :
45 4 : (defrecord
46 : MemoryStorage
47 : [objects]
48 : MediaStorage
49 : (put-object!
50 : [_ key _content-type bytes]
51 10 : (swap! objects assoc key (if (bytes? bytes) bytes (byte-array 0))))
52 0 : (get-object [_ key] (get @objects key))
53 0 : (delete-object! [_ key] (swap! objects dissoc key) nil)
54 : (sign-get-url
55 : [_ key expires-at]
56 4 : (let [exp (.getEpochSecond ^Instant expires-at)
57 8 : sig (subs
58 4 : (str
59 16 : (java.util.UUID/nameUUIDFromBytes (.getBytes (str key exp) StandardCharsets/UTF_8)))
60 : 0
61 : 8)]
62 16 : (str "memory://" key "?expires=" exp "&sig=" sig))))
63 :
64 :
65 4 : (defn make-memory-storage
66 : "In-memory storage fake. Optional seed maps key -> bytes."
67 6 : ([] (make-memory-storage {}))
68 10 : ([seed] (->MemoryStorage (atom seed))))
|