LCOV - code coverage report
Current view: top level - matchscore/media - db.clj Coverage Total Hit
Test: lcov.info Lines: 85.9 % 284 244
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.media.db
       2              :   "PostgreSQL persistence and locking for media assets and ordered galleries."
       3              :   (:require
       4              :    [clojure.string :as str]
       5              :    [next.jdbc :as jdbc]
       6              :    [next.jdbc.result-set :as rs]))
       7              : 
       8              : 
       9            8 : (def max-images 10)
      10              : 
      11              : 
      12            8 : (def max-uploads-per-hour 60)
      13              : 
      14              : 
      15           24 : (def max-pending-bytes (* 200 1024 1024))
      16              : 
      17              : 
      18            4 : (defn validate-image-ids!
      19              :  "Validates the client gallery value without touching persistence. Nil is not
      20              :   a valid supplied value; callers distinguish omission with `contains?`."
      21              :  [image-ids]
      22           11 :  (when-not (vector? image-ids)
      23            7 :    (throw (ex-info "image_ids must be an ordered array" {:type :media/invalid-gallery})))
      24           11 :  (when (> (count image-ids) max-images)
      25            7 :    (throw (ex-info "A gallery may contain at most 10 images" {:type :media/invalid-gallery})))
      26           19 :  (when-not (= (count image-ids) (count (distinct image-ids)))
      27            7 :    (throw (ex-info "A gallery cannot contain duplicate images" {:type :media/invalid-gallery})))
      28            2 :  image-ids)
      29              : 
      30              : 
      31            4 : (defn- one
      32              :   [ds sql-params]
      33           21 :   (jdbc/execute-one! ds sql-params {:builder-fn rs/as-unqualified-kebab-maps}))
      34              : 
      35              : 
      36            4 : (defn- many
      37              :   [ds sql-params]
      38           21 :   (jdbc/execute! ds sql-params {:builder-fn rs/as-unqualified-kebab-maps}))
      39              : 
      40              : 
      41            4 : (defn reserve-upload!
      42              :  "Atomically serializes a user's quota check and inserts a reservation."
      43              :  [tx {:keys [uuid uploader-uuid resource-type resource-uuid image-key thumbnail-key byte-size]}]
      44            8 :  (one tx ["SELECT pg_advisory_xact_lock(hashtext(?))" (str uploader-uuid)])
      45            1 :  (let
      46              :    [quota
      47            2 :     (one
      48            1 :      tx
      49            2 :      ["SELECT count(*) FILTER (WHERE created_datetime >= now() - interval '1 hour') AS upload_count,
      50              :                         coalesce(sum(byte_size) FILTER (WHERE state IN ('reserved','ready')
      51              :                           AND unreferenced_datetime IS NOT NULL), 0) AS pending_bytes
      52              :                   FROM media_assets WHERE uploader_uuid = ?::uuid"
      53            1 :       uploader-uuid])]
      54            8 :    (when (>= (long (:upload-count quota)) max-uploads-per-hour)
      55            7 :      (throw (ex-info "Upload rate limit exceeded" {:type :media/quota-exceeded})))
      56           10 :    (when (> (+ (long (:pending-bytes quota)) byte-size) max-pending-bytes)
      57            7 :      (throw (ex-info "Pending upload quota exceeded" {:type :media/quota-exceeded}))))
      58            2 :  (one
      59            1 :   tx
      60            2 :   ["INSERT INTO media_assets
      61              :        (uuid,uploader_uuid,resource_type,resource_uuid,image_key,thumbnail_key,byte_size,state,
      62              :         reserved_datetime,unreferenced_datetime)
      63              :      VALUES (?::uuid,?::uuid,?,?::uuid,?,?,?,'reserved',now(),now()) RETURNING *"
      64            1 :    uuid
      65            1 :    uploader-uuid
      66            1 :    resource-type
      67            1 :    resource-uuid
      68            1 :    image-key
      69            1 :    thumbnail-key
      70            1 :    byte-size]))
      71              : 
      72              : 
      73            4 : (defn mark-ready!
      74              :  [ds asset-id {:keys [mime width height]}]
      75            0 :  (one
      76            0 :   ds
      77            0 :   ["UPDATE media_assets SET state='ready', mime_type=?, width=?, height=?, ready_datetime=now(),
      78              :         updated_datetime=now() WHERE uuid=?::uuid AND state='reserved' RETURNING *"
      79            0 :    mime
      80            0 :    width
      81            0 :    height
      82            0 :    asset-id]))
      83              : 
      84              : 
      85            4 : (defn mark-storage-failure!
      86              :  [ds asset-id message]
      87            0 :  (one
      88            0 :   ds
      89            0 :   ["UPDATE media_assets SET state='deleting', deletion_last_error=?,
      90              :         deletion_next_attempt_datetime=now(), updated_datetime=now()
      91              :       WHERE uuid=?::uuid AND state <> 'deleted' RETURNING *"
      92            0 :    (subs (str message) 0 (min 2000 (count (str message))))
      93            0 :    asset-id]))
      94              : 
      95              : 
      96            4 : (defn asset-by-id
      97              :  [ds asset-id]
      98           18 :  (one ds ["SELECT * FROM media_assets WHERE uuid=?::uuid" asset-id]))
      99              : 
     100              : 
     101            4 : (defn asset-gallery-owners
     102              :  "Entities whose gallery currently contains the asset:
     103              :   `{:event [event-id ...] :template [template-id ...]}`."
     104              :  [ds asset-id]
     105            5 :  {:event    (mapv
     106            4 :              (comp str :event-id)
     107            6 :              (many ds ["SELECT event_id FROM event_images WHERE asset_id=?::uuid" asset-id]))
     108            2 :   :template (mapv
     109            4 :              (comp str :template-id)
     110            2 :              (many
     111            1 :               ds
     112            3 :               ["SELECT template_id FROM template_images WHERE asset_id=?::uuid" asset-id]))})
     113              : 
     114              : 
     115            4 : (defn set-focus!
     116              :  "Stores the focus point (fractions 0..1) of a ready asset; nil x/y clears it."
     117              :  [ds asset-id x y]
     118            2 :  (one
     119            1 :   ds
     120            2 :   ["UPDATE media_assets SET focus_x=?, focus_y=?, updated_datetime=now()
     121              :       WHERE uuid=?::uuid AND state='ready' RETURNING *"
     122            9 :    (some->
     123            1 :      x
     124              :      float)
     125            9 :    (some->
     126            1 :      y
     127              :      float)
     128            1 :    asset-id]))
     129              : 
     130              : 
     131            4 : (defn- entity-spec
     132              :   [entity-type]
     133            9 :   (case entity-type
     134           21 :     :event    {:parent-table "events"
     135              :                :assoc-table  "event_images"
     136              :                :parent-col   "event_id"}
     137           21 :     :template {:parent-table "templates"
     138              :                :assoc-table  "template_images"
     139              :                :parent-col   "template_id"}
     140            0 :     (throw (ex-info "Unknown gallery entity type" {:entity-type entity-type}))))
     141              : 
     142              : 
     143            4 : (defn- existing-asset-ids
     144              :   [tx {:keys [assoc-table parent-col]} entity-id]
     145            4 :   (mapv
     146            8 :    (comp str :asset-id)
     147            4 :    (many
     148            2 :     tx
     149           16 :     [(str "SELECT asset_id FROM " assoc-table " WHERE " parent-col "=?::uuid ORDER BY position")
     150            2 :      entity-id])))
     151              : 
     152              : 
     153            4 : (defn- lock-asset!
     154              :   [tx asset-id]
     155           12 :   (one tx ["SELECT * FROM media_assets WHERE uuid=?::uuid FOR UPDATE" asset-id]))
     156              : 
     157              : 
     158            4 : (defn- referenced?
     159              :   [tx asset-id]
     160            2 :   (:referenced
     161            2 :    (one
     162            1 :     tx
     163            2 :     ["SELECT EXISTS(SELECT 1 FROM event_images WHERE asset_id=?::uuid)
     164              :           OR EXISTS(SELECT 1 FROM template_images WHERE asset_id=?::uuid) AS referenced"
     165            1 :      asset-id
     166            1 :      asset-id])))
     167              : 
     168              : 
     169            4 : (defn- mark-unreferenced!
     170              :   [tx asset-id]
     171            6 :   (when-not (referenced? tx asset-id)
     172            0 :     (one
     173            0 :      tx
     174            0 :      ["UPDATE media_assets SET unreferenced_datetime=coalesce(unreferenced_datetime,now()),
     175              :           updated_datetime=now() WHERE uuid=?::uuid RETURNING uuid"
     176            0 :       asset-id])))
     177              : 
     178              : 
     179            4 : (defn replace-gallery!
     180              :  "Locks parent then assets, validates scope/ownership, replaces order without
     181              :   transient unique-position conflicts, and increments images_version. Must run
     182              :   on the same transaction connection as the parent form save."
     183              :  [tx entity-type entity-id uploader-uuid image-ids expected-version]
     184            3 :  (validate-image-ids! image-ids)
     185            5 :  (when (nil? expected-version)
     186            0 :    (throw
     187            0 :     (ex-info
     188              :      "images_version is required when image_ids is supplied"
     189            0 :      {:type :media/version-conflict})))
     190            1 :  (let [{:keys [parent-table assoc-table parent-col]
     191              :         :as   spec}
     192            3 :        (entity-spec entity-type)
     193              :        parent
     194            2 :        (one
     195            1 :         tx
     196            6 :         [(str "SELECT uuid,images_version FROM " parent-table " WHERE uuid=?::uuid FOR UPDATE")
     197            1 :          entity-id])]
     198            3 :    (when-not parent (throw (ex-info "Gallery parent not found" {:type :api-not-found})))
     199           10 :    (when-not (= (long expected-version) (long (:images-version parent)))
     200            1 :      (throw
     201            3 :       (ex-info
     202              :        "Gallery has changed"
     203            4 :        {:type :media/version-conflict
     204            3 :         :current-version (:images-version parent)})))
     205            6 :    (let [existing-ordered (existing-asset-ids tx spec entity-id)
     206            3 :          existing         (set existing-ordered)]
     207            7 :      (if (= (mapv str image-ids) existing-ordered)
     208            3 :        (:images-version parent)
     209           10 :        (let [assets (mapv lock-asset! (repeat tx) (sort image-ids))
     210           13 :              by-id  (into {} (map (juxt (comp str :uuid) identity)) assets)]
     211           26 :          (doseq [asset-id image-ids]
     212            6 :            (let [asset     (get by-id (str asset-id))
     213            6 :                  retained? (contains? existing (str asset-id))
     214            9 :                  scope-ok? (and
     215            7 :                             (= (name entity-type) (:resource-type asset))
     216              :                             (or
     217            6 :                              (nil? (:resource-uuid asset))
     218            8 :                              (= (str entity-id) (str (:resource-uuid asset)))))]
     219            3 :              (when-not
     220           15 :                (and
     221            1 :                 asset
     222            5 :                 (= "ready" (:state asset))
     223           10 :                 (or retained? (and (= (str uploader-uuid) (str (:uploader-uuid asset))) scope-ok?)))
     224            1 :                (throw
     225            3 :                 (ex-info
     226              :                  "Image is not attachable to this resource"
     227            4 :                  {:type     :media/invalid-asset
     228            1 :                   :asset-id asset-id})))))
     229            2 :          (jdbc/execute!
     230            1 :           tx
     231            9 :           [(str "DELETE FROM " assoc-table " WHERE " parent-col "=?::uuid") entity-id])
     232           29 :          (doseq [[position asset-id] (map-indexed vector image-ids)]
     233            2 :            (jdbc/execute!
     234            1 :             tx
     235            7 :             [(str
     236            1 :               "INSERT INTO " assoc-table
     237            1 :               " (" parent-col
     238              :               ",asset_id,position)" " VALUES (?::uuid,?::uuid,?)")
     239            1 :              entity-id
     240            1 :              asset-id
     241            1 :              position])
     242            2 :            (one
     243            1 :             tx
     244            2 :             ["UPDATE media_assets SET unreferenced_datetime=NULL,updated_datetime=now()
     245              :                   WHERE uuid=?::uuid RETURNING uuid"
     246            1 :              asset-id]))
     247           26 :          (doseq [asset-id image-ids]
     248            2 :            (one
     249            1 :             tx
     250            2 :             ["UPDATE media_assets SET resource_uuid=coalesce(resource_uuid,?::uuid)
     251              :                   WHERE uuid=?::uuid AND resource_type=? RETURNING uuid"
     252            1 :              entity-id
     253            1 :              asset-id
     254            3 :              (name entity-type)]))
     255           34 :          (doseq [removed (remove (set (map str image-ids)) existing)]
     256            4 :            (mark-unreferenced! tx removed))
     257            2 :          (one
     258            1 :           tx
     259            5 :           [(str
     260              :             "UPDATE "
     261            1 :             parent-table
     262              :             " SET images_version=images_version+1 WHERE uuid=?::uuid RETURNING images_version")
     263            1 :            entity-id]))))))
     264              : 
     265              : 
     266            4 : (defn attach-created-gallery!
     267              :  "Attaches an explicit create gallery, or snapshots the full template gallery
     268              :   for an event whose image_ids field was omitted. The new parent's version stays
     269              :   zero because this is part of its initial atomic state."
     270              :  [tx entity-type entity-id uploader-uuid data]
     271           12 :  (let [{:keys [assoc-table parent-col]} (entity-spec entity-type)
     272           12 :        supplied? (contains? data :image-ids)
     273           18 :        image-ids (when supplied? (validate-image-ids! (:image-ids data)))
     274              :        image-ids
     275           52 :        (if (and (= entity-type :event) (not supplied?) (:template-id data))
     276            6 :          (mapv
     277           12 :           (comp str :asset-id)
     278            6 :           (many
     279            3 :            tx
     280            6 :            ["SELECT asset_id FROM template_images WHERE template_id=?::uuid ORDER BY position"
     281            9 :             (:template-id data)]))
     282           17 :          (or image-ids []))]
     283           52 :    (if (and (= entity-type :event) (not supplied?) (:template-id data))
     284            3 :      (do
     285              :        ;; Match replace-gallery!'s global asset lock order. Display order can
     286              :        ;; be arbitrary and must never determine row-lock order.
     287           83 :        (doseq [asset-id (sort image-ids)] (lock-asset! tx asset-id))
     288           78 :        (doseq [[position asset-id] (map-indexed vector image-ids)]
     289            4 :          (jdbc/execute!
     290            2 :           tx
     291           14 :           [(str
     292            2 :             "INSERT INTO " assoc-table
     293            2 :             " (" parent-col
     294              :             ",asset_id,position)" " VALUES (?::uuid,?::uuid,?)")
     295            2 :            entity-id
     296            2 :            asset-id
     297            2 :            position])
     298            4 :          (one
     299            2 :           tx
     300            4 :           ["UPDATE media_assets SET unreferenced_datetime=NULL WHERE uuid=?::uuid RETURNING uuid"
     301            2 :            asset-id])))
     302            3 :      (do
     303           83 :        (doseq [asset-id (sort image-ids)] (lock-asset! tx asset-id))
     304           78 :        (doseq [[position asset-id] (map-indexed vector image-ids)]
     305           10 :          (let [asset (asset-by-id tx asset-id)]
     306            4 :            (when-not
     307           30 :              (and
     308            2 :               asset
     309           10 :               (= "ready" (:state asset))
     310           18 :               (= (str uploader-uuid) (str (:uploader-uuid asset)))
     311           14 :               (= (name entity-type) (:resource-type asset))
     312            6 :               (nil? (:resource-uuid asset)))
     313            0 :              (throw
     314            0 :               (ex-info
     315              :                "Image is not attachable to this new resource"
     316            0 :                {:type     :media/invalid-asset
     317            0 :                 :asset-id asset-id}))))
     318            4 :          (jdbc/execute!
     319            2 :           tx
     320           14 :           [(str
     321            2 :             "INSERT INTO " assoc-table
     322            2 :             " (" parent-col
     323              :             ",asset_id,position)" " VALUES (?::uuid,?::uuid,?)")
     324            2 :            entity-id
     325            2 :            asset-id
     326            2 :            position])
     327            4 :          (one
     328            2 :           tx
     329            4 :           ["UPDATE media_assets SET unreferenced_datetime=NULL,resource_uuid=?::uuid
     330              :                     WHERE uuid=?::uuid RETURNING uuid"
     331            2 :            entity-id
     332            2 :            asset-id]))))
     333            3 :    image-ids))
     334              : 
     335              : 
     336            4 : (defn galleries-by-entity-ids
     337              :  "One batched metadata query for any number of entities."
     338              :  [ds entity-type entity-ids]
     339           12 :  (if (empty? entity-ids)
     340            0 :    {}
     341           12 :    (let [{:keys [assoc-table parent-col]} (entity-spec entity-type)
     342           24 :          placeholders (str/join "," (repeat (count entity-ids) "?::uuid"))
     343            6 :          rows         (many
     344            3 :                        ds
     345            6 :                        (into
     346           30 :                         [(str
     347              :                           "SELECT i."
     348            3 :                           parent-col
     349              :                           " AS entity_id,i.position,a.* FROM "
     350            3 :                           assoc-table
     351              :                           " i"
     352              :                           " JOIN media_assets a ON a.uuid=i.asset_id WHERE i."
     353            3 :                           parent-col
     354              :                           " IN ("
     355            3 :                           placeholders
     356              :                           ") AND a.state='ready' ORDER BY i."
     357            3 :                           parent-col
     358              :                           ",i.position")]
     359            3 :                         entity-ids))]
     360            6 :      (into
     361            3 :       {}
     362            6 :       (map
     363            3 :        (fn [[id xs]]
     364           21 :         [(str id) (vec xs)]))
     365           12 :       (group-by :entity-id rows)))))
     366              : 
     367              : 
     368            4 : (defn gallery-asset-ids
     369              :  [tx entity-type entity-id]
     370            7 :  (existing-asset-ids tx (entity-spec entity-type) entity-id))
     371              : 
     372              : 
     373            4 : (defn mark-orphans!
     374              :  "Called after a parent deletion in the same transaction. Inherited/shared
     375              :   assets remain referenced and are never synchronously deleted."
     376              :  [tx asset-ids]
     377           19 :  (doseq [asset-id (sort asset-ids)]
     378            0 :    (lock-asset! tx asset-id)
     379            0 :    (mark-unreferenced! tx asset-id)))
     380              : 
     381              : 
     382            4 : (defn claim-cleanup-batch!
     383              :  "Claims only still-unreferenced rows under an asset lock. Attachment takes the
     384              :   same lock, making attach/cleanup races deterministic."
     385              :  [tx limit]
     386            1 :  (let
     387              :    [candidates
     388            2 :     (many
     389            1 :      tx
     390            2 :      ["SELECT * FROM media_assets a
     391              :                        WHERE ((state='reserved' AND reserved_datetime < now()-interval '24 hours')
     392              :                           OR (state='ready' AND unreferenced_datetime < now()-interval '24 hours')
     393              :                           OR (state='deleting' AND coalesce(deletion_next_attempt_datetime,now()) <= now()))
     394              :                        ORDER BY a.uuid LIMIT ?
     395              :                        FOR UPDATE SKIP LOCKED"
     396            1 :       limit])]
     397            1 :    (->>
     398            1 :      candidates
     399            2 :      (keep
     400            1 :       (fn [asset]
     401            7 :        (if (referenced? tx (:uuid asset))
     402            2 :          (do
     403            2 :            (one
     404            1 :             tx
     405            2 :             ["UPDATE media_assets SET unreferenced_datetime=NULL,updated_datetime=now()
     406              :                           WHERE uuid=?::uuid RETURNING uuid"
     407            3 :              (:uuid asset)])
     408              :            nil)
     409            0 :          (one
     410            0 :           tx
     411            0 :           ["UPDATE media_assets SET state='deleting',updated_datetime=now()
     412              :                         WHERE uuid=?::uuid RETURNING *"
     413            0 :            (:uuid asset)]))))
     414            1 :      vec)))
     415              : 
     416              : 
     417            4 : (defn finish-delete!
     418              :  [ds asset-id]
     419            0 :  (one
     420            0 :   ds
     421            0 :   ["UPDATE media_assets SET state='deleted',unreferenced_datetime=NULL,
     422              :             deletion_last_error=NULL,deletion_next_attempt_datetime=NULL,updated_datetime=now()
     423              :             WHERE uuid=?::uuid AND state='deleting' RETURNING *"
     424            0 :    asset-id]))
     425              : 
     426              : 
     427            4 : (defn fail-delete!
     428              :  [ds asset-id message]
     429            0 :  (one
     430            0 :   ds
     431            0 :   ["UPDATE media_assets SET deletion_attempts=deletion_attempts+1,
     432              :             deletion_last_error=?, deletion_next_attempt_datetime=now()+interval '1 hour',
     433              :             updated_datetime=now() WHERE uuid=?::uuid AND state='deleting' RETURNING *"
     434            0 :    (subs (str message) 0 (min 2000 (count (str message))))
     435            0 :    asset-id]))
        

Generated by: LCOV version 2.0-1