|
| 1 | +# Одна джоба на все типы постов и все сети. Каждый ранний выход логируем с |
| 2 | +# причиной: без этого отладка токенов превращается в гадание. |
| 3 | +class PostSocialJob < ApplicationJob |
| 4 | + queue_as :default |
| 5 | + |
| 6 | + CLAIM_TIMEOUT = 30.minutes |
| 7 | + |
| 8 | + def perform(kind, dedup_key, network) |
| 9 | + adapter = Social.adapter_for(network) |
| 10 | + return log(kind, dedup_key, network, "unknown network") unless adapter |
| 11 | + return log(kind, dedup_key, network, "adapter not configured") unless adapter.configured? |
| 12 | + |
| 13 | + content = Social::Content.build(kind, dedup_key) |
| 14 | + return log(kind, dedup_key, network, "no content") unless content |
| 15 | + return log(kind, dedup_key, network, "material is gone") unless content.available? |
| 16 | + |
| 17 | + claim = claim(kind, dedup_key, network) |
| 18 | + return log(kind, dedup_key, network, "already posted or claimed") unless claim |
| 19 | + |
| 20 | + begin |
| 21 | + post_id = adapter.new(content: content, locale: Social.locale_for(network)).call |
| 22 | + rescue StandardError |
| 23 | + release(claim) |
| 24 | + raise |
| 25 | + end |
| 26 | + |
| 27 | + unless post_id |
| 28 | + release(claim) |
| 29 | + return log(kind, dedup_key, network, "adapter returned nothing") |
| 30 | + end |
| 31 | + |
| 32 | + complete(claim, post_id) |
| 33 | + end |
| 34 | + |
| 35 | + private |
| 36 | + |
| 37 | + def claim(kind, dedup_key, network) |
| 38 | + token = "claim:#{SecureRandom.uuid}" |
| 39 | + post = SocialPost.create!(network: network, kind: kind, dedup_key: dedup_key, |
| 40 | + external_post_id: token, posted_at: nil) |
| 41 | + [ post.id, token ] |
| 42 | + rescue ActiveRecord::RecordNotUnique |
| 43 | + post = SocialPost.find_by!(network: network, kind: kind, dedup_key: dedup_key) |
| 44 | + return if post.posted_at? || post.updated_at >= CLAIM_TIMEOUT.ago |
| 45 | + |
| 46 | + claimed_at = Time.current |
| 47 | + taken = SocialPost.where(id: post.id, posted_at: nil) |
| 48 | + .where("updated_at < ?", CLAIM_TIMEOUT.ago) |
| 49 | + .update_all(external_post_id: token, updated_at: claimed_at) |
| 50 | + [ post.id, token ] if taken == 1 |
| 51 | + end |
| 52 | + |
| 53 | + def release(claim) |
| 54 | + id, token = claim |
| 55 | + SocialPost.where(id: id, external_post_id: token, posted_at: nil).delete_all |
| 56 | + end |
| 57 | + |
| 58 | + def complete(claim, post_id) |
| 59 | + id, token = claim |
| 60 | + now = Time.current |
| 61 | + updated = SocialPost.where(id: id, external_post_id: token, posted_at: nil) |
| 62 | + .update_all(external_post_id: post_id, posted_at: now, updated_at: now) |
| 63 | + raise "Social post claim was lost" unless updated == 1 |
| 64 | + end |
| 65 | + |
| 66 | + def log(kind, dedup_key, network, reason) |
| 67 | + Rails.logger.info("[Social] skip #{network} #{kind}/#{dedup_key}: #{reason}") |
| 68 | + nil |
| 69 | + end |
| 70 | +end |
0 commit comments