Line data Source code
1 4 : (ns matchscore.db.postgres.telegram-publications
2 : "Persistence and idempotency state for administrator-authored Telegram posts."
3 : (:require
4 : [cheshire.core :as json]
5 : [clojure.string :as str]
6 : [next.jdbc :as jdbc]
7 : [next.jdbc.result-set :as rs])
8 : (:import
9 : (java.security MessageDigest)))
10 :
11 :
12 16 : (def ^:private query-options {:builder-fn rs/as-unqualified-kebab-maps})
13 :
14 :
15 4 : (defn- sha256
16 : [value]
17 10 : (let [digest (.digest (MessageDigest/getInstance "SHA-256") (.getBytes (str value) "UTF-8"))]
18 12 : (str/join (map #(format "%02x" (bit-and % 0xff)) digest))))
19 :
20 :
21 4 : (defn content-hash
22 : "Hashes the normalized, ordered publication value used for preview and delivery."
23 : [content]
24 5 : (sha256 (pr-str content)))
25 :
26 :
27 4 : (defn upsert-changelog-candidate!
28 : "Imports a code-generated draft idempotently. A changed bundled draft may
29 : update an awaiting-review candidate while saved publication revisions remain
30 : immutable; published and rejected candidates are never changed."
31 : [ds {:keys [source-id title source content]}]
32 3 : (let [fingerprint (content-hash
33 4 : {:source source
34 1 : :content content})]
35 2 : (jdbc/execute-one!
36 1 : ds
37 2 : ["INSERT INTO telegram_changelog_candidates
38 : (source_id, source_fingerprint, title, source_metadata, content)
39 : VALUES (?, ?, ?, ?::jsonb, ?::jsonb)
40 : ON CONFLICT (source_id) DO UPDATE
41 : SET source_fingerprint = EXCLUDED.source_fingerprint,
42 : title = EXCLUDED.title,
43 : source_metadata = EXCLUDED.source_metadata,
44 : content = EXCLUDED.content
45 : WHERE telegram_changelog_candidates.status = 'awaiting_review'
46 : RETURNING *"
47 1 : source-id
48 1 : fingerprint
49 1 : title
50 3 : (json/generate-string source)
51 3 : (json/generate-string content)]
52 1 : query-options)))
53 :
54 :
55 4 : (defn delete-unbundled-changelog-candidates!
56 : "Removes awaiting-review candidates whose bundled file is gone, so the review
57 : queue mirrors the bundle. A candidate with a saved preview keeps its row
58 : because a reviewer already worked on it; published and rejected candidates
59 : are history and are never removed."
60 : [ds bundled-source-ids]
61 2 : (jdbc/execute!
62 1 : ds
63 2 : ["DELETE FROM telegram_changelog_candidates
64 : WHERE status = 'awaiting_review'
65 : AND publication_id IS NULL
66 : AND source_id <> ALL (?)
67 : RETURNING source_id"
68 4 : (into-array String bundled-source-ids)]
69 1 : query-options))
70 :
71 :
72 4 : (defn changelog-candidates
73 : [ds]
74 2 : (jdbc/execute!
75 1 : ds
76 2 : ["SELECT * FROM telegram_changelog_candidates
77 : ORDER BY
78 : CASE status WHEN 'awaiting_review' THEN 0 WHEN 'published' THEN 1 ELSE 2 END,
79 : created_datetime DESC"]
80 1 : query-options))
81 :
82 :
83 4 : (defn published-updates
84 : "Returns the latest successfully published Telegram revisions for the in-app
85 : updates feed. The bounded result intentionally excludes partial deliveries."
86 : [ds]
87 2 : (jdbc/execute!
88 1 : ds
89 2 : ["SELECT p.uuid AS publication_id,
90 : r.uuid AS revision_id,
91 : p.published_datetime,
92 : r.content,
93 : c.source_id,
94 : c.title
95 : FROM telegram_publications p
96 : JOIN telegram_publication_revisions r
97 : ON r.publication_id = p.uuid
98 : AND r.revision = p.current_revision
99 : LEFT JOIN telegram_changelog_candidates c
100 : ON c.publication_id = p.uuid
101 : WHERE p.status = 'published'
102 : ORDER BY p.published_datetime DESC, p.uuid DESC
103 : LIMIT 50"]
104 1 : query-options))
105 :
106 :
107 4 : (defn- changelog-candidate-row
108 : [tx candidate-id]
109 2 : (jdbc/execute-one!
110 1 : tx
111 2 : ["SELECT * FROM telegram_changelog_candidates
112 1 : WHERE uuid = ?::uuid FOR UPDATE" candidate-id]
113 1 : query-options))
114 :
115 :
116 4 : (defn reject-changelog-candidate!
117 : "Archives an awaiting-review candidate without publishing it. Repeating the
118 : action is idempotent; a candidate with any delivery attempt cannot be
119 : represented as an unposted archive."
120 : [ds candidate-id reviewer-id]
121 4 : (jdbc/with-transaction
122 1 : [tx ds]
123 1 : (let
124 4 : [candidate (or
125 4 : (changelog-candidate-row tx candidate-id)
126 0 : (throw (ex-info "Generated changelog candidate not found." {:type :api-not-found})))
127 : attempted?
128 6 : (and
129 3 : (:publication-id candidate)
130 : (:exists
131 2 : (jdbc/execute-one!
132 1 : tx
133 2 : ["SELECT EXISTS (
134 : SELECT 1
135 : FROM telegram_publication_revisions r
136 : JOIN telegram_publication_deliveries d ON d.revision_id = r.uuid
137 : WHERE r.publication_id = ?::uuid
138 : ) AS exists"
139 3 : (:publication-id candidate)]
140 1 : query-options)))]
141 5 : (case (:status candidate)
142 1 : "rejected" candidate
143 0 : "published" (throw
144 0 : (ex-info
145 : "Published changelogs cannot be archived."
146 0 : {:type :admin-telegram-validation
147 : :message "Published changelogs cannot be archived."}))
148 : "awaiting_review"
149 1 : (do
150 2 : (when attempted?
151 0 : (throw
152 0 : (ex-info
153 : "A changelog with a Telegram delivery attempt cannot be archived as unposted."
154 0 : {:type :admin-telegram-validation
155 : :message
156 : "This changelog already has a Telegram delivery attempt and cannot be archived as unposted."})))
157 2 : (jdbc/execute-one!
158 1 : tx
159 2 : ["UPDATE telegram_changelog_candidates
160 : SET status = 'rejected', reviewed_by = ?::uuid, reviewed_datetime = now()
161 : WHERE uuid = ?::uuid
162 : RETURNING *"
163 1 : reviewer-id
164 1 : candidate-id]
165 1 : query-options))))))
166 :
167 :
168 4 : (defn- publication-row
169 : [tx publication-id]
170 2 : (jdbc/execute-one!
171 1 : tx
172 3 : ["SELECT * FROM telegram_publications WHERE uuid = ?::uuid FOR UPDATE" publication-id]
173 1 : query-options))
174 :
175 :
176 4 : (defn- create-publication!
177 : [tx destination-chat-id creator-id]
178 2 : (jdbc/execute-one!
179 1 : tx
180 2 : ["INSERT INTO telegram_publications (destination_chat_id, created_by)
181 : VALUES (?, ?::uuid) RETURNING *"
182 1 : destination-chat-id
183 1 : creator-id]
184 1 : query-options))
185 :
186 :
187 4 : (defn- find-revision-by-hash
188 : [tx publication-id hash]
189 2 : (jdbc/execute-one!
190 1 : tx
191 2 : ["SELECT * FROM telegram_publication_revisions
192 : WHERE publication_id = ?::uuid AND content_hash = ?"
193 1 : publication-id
194 1 : hash]
195 1 : query-options))
196 :
197 :
198 4 : (defn- save-media!
199 : [tx revision-id creator-id posts]
200 53 : (doseq [[post-index post] (map-indexed vector posts)
201 2 : [media-index image-url] (map-indexed
202 1 : vector
203 8 : (cond-> (:inline-image-urls post)
204 7 : (:image-url post) (conj (:image-url post))))]
205 2 : (jdbc/execute-one!
206 1 : tx
207 2 : ["INSERT INTO telegram_publication_media_assets
208 : (revision_id, post_sequence, media_sequence, media_type, source_url, created_by)
209 : VALUES (?::uuid, ?, ?, 'photo', ?, ?::uuid)"
210 1 : revision-id
211 1 : post-index
212 1 : media-index
213 1 : image-url
214 1 : creator-id])))
215 :
216 :
217 4 : (defn save-preview!
218 : "Creates or advances a publication and stores the exact immutable revision
219 : that was previewed. Re-previewing identical content reuses the same revision."
220 : [ds creator-id publication-id candidate-id prepared]
221 4 : (jdbc/with-transaction
222 1 : [tx ds]
223 1 : (let
224 3 : [candidate (when candidate-id
225 4 : (or
226 4 : (changelog-candidate-row tx candidate-id)
227 : (throw
228 0 : (ex-info "Generated changelog candidate not found." {:type :api-not-found}))))
229 13 : _ (when (and candidate (not= "awaiting_review" (:status candidate)))
230 1 : (throw
231 3 : (ex-info
232 : "That generated changelog has already been reviewed."
233 5 : {:type :admin-telegram-validation
234 : :message "That generated changelog has already been reviewed."})))
235 3 : candidate-publication-id (:publication-id candidate)
236 1 : _ (when
237 8 : (and
238 1 : publication-id
239 1 : candidate-publication-id
240 0 : (not= (str publication-id) (str candidate-publication-id)))
241 0 : (throw
242 0 : (ex-info
243 : "The draft belongs to another generated changelog."
244 0 : {:type :admin-telegram-validation
245 : :message "The draft belongs to another generated changelog."})))
246 5 : effective-publication-id (or candidate-publication-id publication-id)
247 2 : publication (if effective-publication-id
248 4 : (or
249 4 : (publication-row tx effective-publication-id)
250 0 : (throw (ex-info "Telegram publication not found." {:type :api-not-found})))
251 7 : (create-publication! tx (:chat-id prepared) creator-id))
252 7 : content (select-keys prepared [:chat-id :disable-notification :posts])
253 3 : hash (content-hash content)
254 7 : existing (find-revision-by-hash tx (:uuid publication) hash)
255 : revision
256 5 : (or
257 1 : existing
258 : (let
259 4 : [next-revision (inc (:current-revision publication))
260 : saved
261 2 : (jdbc/execute-one!
262 1 : tx
263 2 : ["INSERT INTO telegram_publication_revisions
264 : (publication_id, revision, source_format, content,
265 : content_hash, created_by)
266 : VALUES (?::uuid, ?, 'rich_markdown', ?::jsonb, ?, ?::uuid)
267 : RETURNING *"
268 3 : (:uuid publication)
269 1 : next-revision
270 3 : (json/generate-string content)
271 1 : hash
272 1 : creator-id]
273 1 : query-options)]
274 10 : (save-media! tx (:uuid saved) creator-id (:posts prepared))
275 1 : saved))]
276 2 : (jdbc/execute-one!
277 1 : tx
278 2 : ["UPDATE telegram_publications
279 : SET destination_chat_id = ?, current_revision = ?,
280 : status = CASE WHEN ? AND status = 'published' THEN status ELSE 'draft' END,
281 : published_by = CASE WHEN ? AND status = 'published' THEN published_by ELSE NULL END,
282 : published_datetime = CASE
283 : WHEN ? AND status = 'published' THEN published_datetime ELSE NULL END
284 : WHERE uuid = ?::uuid"
285 3 : (:chat-id prepared)
286 3 : (:revision revision)
287 2 : (boolean existing)
288 2 : (boolean existing)
289 2 : (boolean existing)
290 3 : (:uuid publication)])
291 3 : (when candidate
292 2 : (jdbc/execute-one!
293 1 : tx
294 2 : ["UPDATE telegram_changelog_candidates
295 : SET publication_id = ?::uuid
296 : WHERE uuid = ?::uuid"
297 3 : (:uuid publication)
298 1 : candidate-id]))
299 9 : {:publication-id (:uuid publication)
300 3 : :revision-id (:uuid revision)
301 3 : :revision (:revision revision)
302 5 : :content-hash (str/trim (:content-hash revision))
303 1 : :candidate-id candidate-id})))
304 :
305 :
306 4 : (defn revision
307 : [ds revision-id]
308 2 : (jdbc/execute-one!
309 1 : ds
310 2 : ["SELECT r.*, p.uuid AS publication_id
311 : FROM telegram_publication_revisions r
312 : JOIN telegram_publications p ON p.uuid = r.publication_id
313 : WHERE r.uuid = ?::uuid"
314 1 : revision-id]
315 1 : query-options))
316 :
317 :
318 4 : (defn- delivery-by-revision
319 : [tx revision-id destination-chat-id]
320 2 : (jdbc/execute-one!
321 1 : tx
322 2 : ["SELECT * FROM telegram_publication_deliveries
323 : WHERE revision_id = ?::uuid AND destination_chat_id = ?"
324 1 : revision-id
325 1 : destination-chat-id]
326 1 : query-options))
327 :
328 :
329 4 : (defn delivery-items
330 : [ds delivery-id]
331 2 : (jdbc/execute!
332 1 : ds
333 2 : ["SELECT * FROM telegram_publication_delivery_items
334 : WHERE delivery_id = ?::uuid ORDER BY sequence"
335 1 : delivery-id]
336 1 : query-options))
337 :
338 :
339 4 : (defn- candidate-status-for-revision
340 : [tx revision-id]
341 2 : (jdbc/execute-one!
342 1 : tx
343 2 : ["SELECT c.status
344 : FROM telegram_changelog_candidates c
345 : JOIN telegram_publication_revisions r ON r.publication_id = c.publication_id
346 : WHERE r.uuid = ?::uuid
347 : FOR UPDATE OF c"
348 1 : revision-id]
349 1 : query-options))
350 :
351 :
352 4 : (defn begin-delivery!
353 : "Atomically claims one delivery for a revision and destination. The database
354 : uniqueness constraint is the final guard against double publication."
355 : [ds requester-id revision-id idempotency-key content]
356 4 : (jdbc/with-transaction
357 1 : [tx ds]
358 1 : (let
359 6 : [candidate-status (:status (candidate-status-for-revision tx revision-id))
360 5 : _ (when (= "rejected" candidate-status)
361 1 : (throw
362 3 : (ex-info
363 : "Archived changelogs cannot be published."
364 5 : {:type :admin-telegram-validation
365 : :message "This changelog was archived and cannot be published."})))
366 3 : destination (:chat-id content)
367 : inserted
368 2 : (jdbc/execute-one!
369 1 : tx
370 2 : ["INSERT INTO telegram_publication_deliveries
371 : (revision_id, destination_chat_id, idempotency_key, requested_by)
372 : VALUES (?::uuid, ?, ?::uuid, ?::uuid)
373 : ON CONFLICT DO NOTHING
374 : RETURNING *"
375 1 : revision-id
376 1 : destination
377 1 : idempotency-key
378 1 : requester-id]
379 1 : query-options)
380 10 : delivery (or inserted (delivery-by-revision tx revision-id destination))]
381 3 : (when-not delivery
382 0 : (throw
383 0 : (ex-info
384 : "That publish request key is already used by another publication."
385 0 : {:type :admin-telegram-validation
386 : :message "That publish request is no longer valid. Preview the draft again."})))
387 3 : (when inserted
388 31 : (doseq [[sequence post] (map-indexed vector (:posts content))]
389 6 : (let [payload {:chat_id destination
390 5 : :disable_notification (true? (:disable-notification content))
391 3 : :rich_message (:rich-message post)}]
392 2 : (jdbc/execute-one!
393 1 : tx
394 2 : ["INSERT INTO telegram_publication_delivery_items
395 : (delivery_id, sequence, payload)
396 : VALUES (?::uuid, ?, ?::jsonb)"
397 3 : (:uuid delivery)
398 1 : sequence
399 3 : (json/generate-string payload)])))
400 2 : (jdbc/execute-one!
401 1 : tx
402 2 : ["UPDATE telegram_publications p
403 : SET status = 'publishing'
404 : FROM telegram_publication_revisions r
405 : WHERE r.uuid = ?::uuid AND p.uuid = r.publication_id"
406 1 : revision-id]))
407 5 : {:created? (boolean inserted)
408 1 : :delivery delivery})))
409 :
410 :
411 4 : (defn mark-item-sending!
412 : [ds item-id]
413 2 : (jdbc/execute-one!
414 1 : ds
415 2 : ["UPDATE telegram_publication_delivery_items
416 : SET status = 'sending', attempts = attempts + 1, started_datetime = now(), error = NULL
417 : WHERE uuid = ?::uuid"
418 1 : item-id]))
419 :
420 :
421 4 : (defn mark-item-sent!
422 : [ds item-id message-id]
423 2 : (jdbc/execute-one!
424 1 : ds
425 2 : ["UPDATE telegram_publication_delivery_items
426 : SET status = 'sent', telegram_message_id = ?, finished_datetime = now(), error = NULL
427 : WHERE uuid = ?::uuid"
428 1 : message-id
429 1 : item-id]))
430 :
431 :
432 4 : (defn mark-item-error!
433 : [ds item-id status error]
434 2 : (jdbc/execute-one!
435 1 : ds
436 2 : ["UPDATE telegram_publication_delivery_items
437 : SET status = ?, error = ?::jsonb, finished_datetime = now()
438 : WHERE uuid = ?::uuid"
439 1 : status
440 3 : (json/generate-string error)
441 1 : item-id]))
442 :
443 :
444 4 : (defn finish-delivery!
445 : [ds delivery-id publication-id publisher-id status error]
446 4 : (jdbc/with-transaction
447 1 : [tx ds]
448 2 : (jdbc/execute-one!
449 1 : tx
450 2 : ["UPDATE telegram_publication_deliveries
451 : SET status = ?, error = ?::jsonb, finished_datetime = now()
452 : WHERE uuid = ?::uuid"
453 1 : status
454 3 : (json/generate-string error)
455 1 : delivery-id])
456 2 : (jdbc/execute-one!
457 1 : tx
458 2 : ["UPDATE telegram_publications
459 : SET status = ?,
460 : published_by = CASE WHEN ? = 'published' THEN ?::uuid ELSE published_by END,
461 : published_datetime = CASE WHEN ? = 'published' THEN now() ELSE published_datetime END
462 : WHERE uuid = ?::uuid"
463 1 : status
464 1 : status
465 1 : publisher-id
466 1 : status
467 1 : publication-id])
468 5 : (when (= "published" status)
469 2 : (jdbc/execute-one!
470 1 : tx
471 2 : ["UPDATE telegram_changelog_candidates
472 : SET status = 'published', reviewed_by = ?::uuid, reviewed_datetime = now()
473 : WHERE publication_id = ?::uuid AND status = 'awaiting_review'"
474 1 : publisher-id
475 1 : publication-id]))))
|