instagram_connect 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. checksums.yaml +4 -4
  2. data/.github/workflows/ci.yml +36 -0
  3. data/CHANGELOG.md +102 -0
  4. data/Gemfile +4 -0
  5. data/README.md +328 -73
  6. data/app/controllers/instagram_connect/comments_controller.rb +1 -1
  7. data/app/controllers/instagram_connect/posts_controller.rb +1 -1
  8. data/app/jobs/instagram_connect/account_readiness_job.rb +150 -0
  9. data/app/jobs/instagram_connect/fetch_media_job.rb +110 -0
  10. data/app/jobs/instagram_connect/profile_sync_job.rb +78 -0
  11. data/app/jobs/instagram_connect/replay_events_job.rb +57 -0
  12. data/app/jobs/instagram_connect/send_message_job.rb +44 -16
  13. data/app/models/instagram_connect/account.rb +27 -1
  14. data/app/models/instagram_connect/api_budget.rb +22 -0
  15. data/app/models/instagram_connect/conversation.rb +99 -11
  16. data/app/models/instagram_connect/inbound_message.rb +11 -3
  17. data/app/models/instagram_connect/insight_snapshot.rb +43 -0
  18. data/app/models/instagram_connect/media_item.rb +38 -0
  19. data/app/models/instagram_connect/mention.rb +37 -0
  20. data/app/models/instagram_connect/message.rb +34 -2
  21. data/app/models/instagram_connect/message_attachment.rb +53 -0
  22. data/app/models/instagram_connect/message_reaction.rb +33 -0
  23. data/app/models/instagram_connect/webhook_event.rb +67 -0
  24. data/db/migrate/20260725194732_create_instagram_connect_webhook_events.rb +52 -0
  25. data/db/migrate/20260725200216_add_messaging_event_fields.rb +89 -0
  26. data/db/migrate/20260725200250_create_instagram_connect_message_reactions.rb +30 -0
  27. data/db/migrate/20260725201320_create_instagram_connect_message_attachments.rb +33 -0
  28. data/db/migrate/20260725202616_add_outbound_send_fields.rb +27 -0
  29. data/db/migrate/20260725203213_create_instagram_connect_media.rb +30 -0
  30. data/db/migrate/20260725203214_create_instagram_connect_mentions.rb +30 -0
  31. data/db/migrate/20260725203215_create_instagram_connect_insight_snapshots.rb +45 -0
  32. data/db/migrate/20260725203306_add_comment_moderation_fields.rb +29 -0
  33. data/db/migrate/20260725204022_add_per_account_token_fields.rb +76 -0
  34. data/db/migrate/20260725204815_create_instagram_connect_api_budgets.rb +29 -0
  35. data/db/migrate/20260725205417_add_conversation_profile_fields.rb +21 -0
  36. data/docs/CONFIGURATION.md +107 -0
  37. data/lib/instagram_connect/client.rb +129 -3
  38. data/lib/instagram_connect/configuration.rb +10 -0
  39. data/lib/instagram_connect/connect.rb +27 -4
  40. data/lib/instagram_connect/engine.rb +1 -0
  41. data/lib/instagram_connect/ingest/dispatcher.rb +151 -0
  42. data/lib/instagram_connect/ingest/envelope.rb +31 -0
  43. data/lib/instagram_connect/ingest/handlers/base.rb +55 -0
  44. data/lib/instagram_connect/ingest/handlers/comments.rb +59 -0
  45. data/lib/instagram_connect/ingest/handlers/mentions.rb +48 -0
  46. data/lib/instagram_connect/ingest/handlers/message_reactions.rb +91 -0
  47. data/lib/instagram_connect/ingest/handlers/messages.rb +135 -0
  48. data/lib/instagram_connect/ingest/handlers/messaging_handover.rb +53 -0
  49. data/lib/instagram_connect/ingest/handlers/messaging_optins.rb +37 -0
  50. data/lib/instagram_connect/ingest/handlers/messaging_postbacks.rb +24 -0
  51. data/lib/instagram_connect/ingest/handlers/messaging_referral.rb +42 -0
  52. data/lib/instagram_connect/ingest/handlers/messaging_seen.rb +37 -0
  53. data/lib/instagram_connect/ingest/handlers/story_insights.rb +62 -0
  54. data/lib/instagram_connect/ingest/handlers/unknown.rb +19 -0
  55. data/lib/instagram_connect/ingest/registry.rb +93 -0
  56. data/lib/instagram_connect/ingest/summary.rb +75 -0
  57. data/lib/instagram_connect/ingest.rb +27 -105
  58. data/lib/instagram_connect/media/attaching.rb +57 -0
  59. data/lib/instagram_connect/media/limits.rb +46 -0
  60. data/lib/instagram_connect/rate_limiter.rb +88 -0
  61. data/lib/instagram_connect/result.rb +26 -6
  62. data/lib/instagram_connect/text_splitter.rb +51 -0
  63. data/lib/instagram_connect/usage.rb +68 -0
  64. data/lib/instagram_connect/version.rb +1 -1
  65. data/lib/instagram_connect.rb +23 -0
  66. metadata +60 -2
  67. data/MIT-LICENSE +0 -20
@@ -0,0 +1,24 @@
1
+ module InstagramConnect
2
+ class Ingest
3
+ module Handlers
4
+ # A tap on an ice breaker, a persistent-menu item, or a template button.
5
+ # Postbacks carry no message of their own, so there is nothing to persist
6
+ # yet — the host callback is the whole point.
7
+ class MessagingPostbacks < Base
8
+ def self.dedupe_key(event)
9
+ event.dig("postback", "mid").presence
10
+ end
11
+
12
+ def call
13
+ notify(config.on_postback, {
14
+ account_id: account.id,
15
+ sender_id: event.dig("sender", "id"),
16
+ payload: event.dig("postback", "payload"),
17
+ title: event.dig("postback", "title")
18
+ })
19
+ nil
20
+ end
21
+ end
22
+ end
23
+ end
24
+ end
@@ -0,0 +1,42 @@
1
+ module InstagramConnect
2
+ class Ingest
3
+ module Handlers
4
+ # The customer arrived through an ig.me link, an ad, or a product tag.
5
+ # A referral opens the 24-hour messaging window even before they type
6
+ # anything, so it has to bump the thread's activity.
7
+ #
8
+ # Only a standalone referral reaches here — one nested inside a message
9
+ # or postback stays with its parent event (see Registry).
10
+ class MessagingReferral < Base
11
+ def self.dedupe_key(event)
12
+ ref = event.dig("referral", "ref").presence or return nil
13
+
14
+ "#{event.dig('sender', 'id')}:#{ref}:#{event['timestamp']}"
15
+ end
16
+
17
+ def call
18
+ conversation.register_referral(ref: payload["ref"], at: referred_at)
19
+ conversation
20
+ end
21
+
22
+ private
23
+
24
+ def payload
25
+ event["referral"] || {}
26
+ end
27
+
28
+ def igsid
29
+ event.dig("sender", "id").to_s
30
+ end
31
+
32
+ def referred_at
33
+ envelope.occurred_at || Time.current
34
+ end
35
+
36
+ def conversation
37
+ @conversation ||= InstagramConnect::Conversation.locate(account: account, igsid: igsid)
38
+ end
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,37 @@
1
+ module InstagramConnect
2
+ class Ingest
3
+ module Handlers
4
+ # A read receipt: the customer has seen everything up to this message.
5
+ class MessagingSeen < Base
6
+ def self.dedupe_key(event)
7
+ mid = event.dig("read", "mid").presence or return nil
8
+
9
+ "#{event.dig('sender', 'id')}:#{mid}"
10
+ end
11
+
12
+ def call
13
+ conversation.mark_read_by_customer(at: seen_at, mid: mid)
14
+ conversation
15
+ end
16
+
17
+ private
18
+
19
+ def mid
20
+ event.dig("read", "mid").to_s
21
+ end
22
+
23
+ def igsid
24
+ event.dig("sender", "id").to_s
25
+ end
26
+
27
+ def seen_at
28
+ envelope.occurred_at || Time.current
29
+ end
30
+
31
+ def conversation
32
+ @conversation ||= InstagramConnect::Conversation.locate(account: account, igsid: igsid)
33
+ end
34
+ end
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,62 @@
1
+ module InstagramConnect
2
+ class Ingest
3
+ module Handlers
4
+ # A story expired, and Meta sent its final metrics with the notification.
5
+ #
6
+ # This is the only durable capture path there is. Story insights are
7
+ # retrievable from the API for 24 hours; after that the numbers do not
8
+ # exist anywhere. So the snapshot is written here, inside ingest, rather
9
+ # than handed to a job that might be delayed past the point of no return.
10
+ class StoryInsights < Base
11
+ def self.dedupe_key(event)
12
+ event.dig("value", "media_id").presence
13
+ end
14
+
15
+ def self.requires_dedupe_key?
16
+ true
17
+ end
18
+
19
+ def call
20
+ # The story may well have been posted from a phone rather than through
21
+ # this app, so its media row might not exist yet.
22
+ InstagramConnect::MediaItem.record(
23
+ account: account, ig_media_id: media_id, media_product_type: "STORY"
24
+ )
25
+
26
+ InstagramConnect::InsightSnapshot.record(
27
+ account: account,
28
+ subject_type: "story",
29
+ subject_ref: media_id,
30
+ period: "lifetime",
31
+ period_start: captured_at.to_date,
32
+ source: "webhook",
33
+ metrics: metrics,
34
+ empty: metrics.empty?,
35
+ captured_at: captured_at
36
+ )
37
+ end
38
+
39
+ private
40
+
41
+ def value
42
+ event["value"] || {}
43
+ end
44
+
45
+ def media_id
46
+ value["media_id"].to_s
47
+ end
48
+
49
+ # Everything except the identifier is a metric. Meta omits a metric it
50
+ # will not report rather than sending a zero, and that distinction is
51
+ # preserved by copying the payload as-is instead of filling defaults.
52
+ def metrics
53
+ @metrics ||= value.except("media_id")
54
+ end
55
+
56
+ def captured_at
57
+ envelope.occurred_at || Time.current
58
+ end
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,19 @@
1
+ module InstagramConnect
2
+ class Ingest
3
+ module Handlers
4
+ # Anything the gem does not parse yet, or an entry belonging to no
5
+ # connected account. The event is banked verbatim rather than dropped:
6
+ # Meta never re-delivers, so replaying the row later is the only way to
7
+ # recover it once a handler exists.
8
+ #
9
+ # The dispatcher marks these `unhandled` without calling `#call` — this
10
+ # class exists so the registry always resolves to something, and so the
11
+ # ledger records which handler was chosen.
12
+ class Unknown < Base
13
+ def call
14
+ nil
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,93 @@
1
+ module InstagramConnect
2
+ class Ingest
3
+ # Maps a webhook field to the handler that parses it, and infers the field
4
+ # for messaging events (Meta delivers all of them under `entry.messaging`
5
+ # regardless of which subscription triggered them, so the field has to be
6
+ # recovered from the event's shape).
7
+ module Registry
8
+ HANDLERS = {
9
+ "messages" => Handlers::Messages,
10
+ "message_echoes" => Handlers::Messages,
11
+ "messaging_postbacks" => Handlers::MessagingPostbacks,
12
+ "message_reactions" => Handlers::MessageReactions,
13
+ "messaging_seen" => Handlers::MessagingSeen,
14
+ "messaging_referral" => Handlers::MessagingReferral,
15
+ "messaging_optins" => Handlers::MessagingOptins,
16
+ "messaging_handover" => Handlers::MessagingHandover,
17
+ "comments" => Handlers::Comments,
18
+ "live_comments" => Handlers::Comments,
19
+ "mentions" => Handlers::Mentions,
20
+ "story_insights" => Handlers::StoryInsights
21
+ }.freeze
22
+
23
+ # Every field the gem knows Meta can send on the `instagram` object.
24
+ # Fields without a handler are still worth subscribing to: they bank as
25
+ # `unhandled` rows and replay once a handler ships, whereas an
26
+ # unsubscribed field is gone for good — Meta does not store `mentions` or
27
+ # `story_insights` notifications, and re-delivers nothing.
28
+ KNOWN_FIELDS = %w[
29
+ messages
30
+ message_echoes
31
+ message_reactions
32
+ messaging_postbacks
33
+ messaging_seen
34
+ messaging_referral
35
+ messaging_optins
36
+ messaging_handover
37
+ messaging_policy_enforcement
38
+ response_feedback
39
+ standby
40
+ comments
41
+ live_comments
42
+ mentions
43
+ story_insights
44
+ ].freeze
45
+
46
+ # Shape tests in priority order. `is_echo` must be checked before the
47
+ # plain `message` case, since an echo carries a message too.
48
+ MESSAGING_SHAPES = [
49
+ [ "message_echoes", ->(e) { e["message"] && e.dig("message", "is_echo") } ],
50
+ [ "messages", ->(e) { e["message"] } ],
51
+ [ "message_reactions", ->(e) { e["reaction"] } ],
52
+ [ "messaging_postbacks", ->(e) { e["postback"] } ],
53
+ [ "messaging_seen", ->(e) { e["read"] } ],
54
+ [ "messaging_referral", ->(e) { e["referral"] } ],
55
+ [ "messaging_optins", ->(e) { e["optin"] } ],
56
+ [ "messaging_handover", lambda { |e|
57
+ e["pass_thread_control"] || e["take_thread_control"] || e["request_thread_control"]
58
+ } ]
59
+ ].freeze
60
+
61
+ UNKNOWN_FIELD = "unknown".freeze
62
+
63
+ module_function
64
+
65
+ def handler_for(field)
66
+ HANDLERS.fetch(field, Handlers::Unknown)
67
+ end
68
+
69
+ def handled?(field)
70
+ HANDLERS.key?(field)
71
+ end
72
+
73
+ # The fields a host should subscribe its Page to. Everything the gem
74
+ # knows about, handled or not — see KNOWN_FIELDS.
75
+ def subscribable_fields
76
+ KNOWN_FIELDS
77
+ end
78
+
79
+ def handled_fields
80
+ HANDLERS.keys
81
+ end
82
+
83
+ # `message.referral` and `postback.referral` are nested inside their
84
+ # parent event and stay with it; only a standalone `referral` is a
85
+ # referral event in its own right, which is why the shape tests run in
86
+ # order rather than checking every key independently.
87
+ def messaging_field_for(event)
88
+ found = MESSAGING_SHAPES.find { |(_field, test)| test.call(event) }
89
+ found ? found.first : UNKNOWN_FIELD
90
+ end
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,75 @@
1
+ module InstagramConnect
2
+ class Ingest
3
+ # What one webhook delivery produced. Behaves as a Hash so the return value
4
+ # of Ingest.call stays compatible with hosts written against 0.2.x, which
5
+ # read summary[:messages] and friends.
6
+ class Summary
7
+ COUNTERS = {
8
+ "messages" => :messages,
9
+ "message_echoes" => :messages,
10
+ "messaging_postbacks" => :postbacks,
11
+ "comments" => :comments,
12
+ "live_comments" => :comments
13
+ }.freeze
14
+
15
+ attr_accessor :messages, :comments, :postbacks, :duplicates, :unhandled,
16
+ :failed, :callback_errors
17
+
18
+ def initialize
19
+ @messages = 0
20
+ @comments = 0
21
+ @postbacks = 0
22
+ @duplicates = 0
23
+ @unhandled = 0
24
+ @failed = 0
25
+ @callback_errors = 0
26
+ end
27
+
28
+ def count(field)
29
+ counter = COUNTERS[field]
30
+ return if counter.nil?
31
+
32
+ public_send(:"#{counter}=", public_send(counter) + 1)
33
+ end
34
+
35
+ # 0.2.x reported one `skipped` number covering both "we have seen this
36
+ # already" and "we do not parse this". They are different problems now —
37
+ # duplicates are healthy, unhandled events are a backlog to replay — but
38
+ # the combined figure is kept so existing hosts keep working.
39
+ def skipped
40
+ duplicates + unhandled
41
+ end
42
+
43
+ def to_h
44
+ {
45
+ messages: messages,
46
+ comments: comments,
47
+ postbacks: postbacks,
48
+ skipped: skipped,
49
+ duplicates: duplicates,
50
+ unhandled: unhandled,
51
+ failed: failed,
52
+ callback_errors: callback_errors
53
+ }
54
+ end
55
+
56
+ # Implicit conversion, not just the explicit #to_h: it is what makes a
57
+ # Summary behave as a Hash for callers (and matchers) written against the
58
+ # plain hash 0.2.x returned.
59
+ alias_method :to_hash, :to_h
60
+
61
+ def [](key)
62
+ to_h[key.to_sym]
63
+ end
64
+
65
+ def ==(other)
66
+ other.respond_to?(:to_h) ? to_h == other.to_h : super
67
+ end
68
+
69
+ def each(&block)
70
+ to_h.each(&block)
71
+ end
72
+ include Enumerable
73
+ end
74
+ end
75
+ end
@@ -1,112 +1,34 @@
1
1
  module InstagramConnect
2
- # Parses a verified Meta webhook payload and persists it into the engine's
3
- # chat models, deduping on Meta's message id. After persistence it fires the
4
- # configured host handlers (on_message / on_comment / on_postback) so the host
5
- # can layer extras (notifications, AI replies) on top.
2
+ # Turns a verified Meta webhook payload into persisted rows, and fires the
3
+ # configured host callbacks (on_message / on_comment / on_postback) so the
4
+ # host can layer notifications, AI drafting or CRM linking on top.
6
5
  #
7
- # Returns a summary hash of what was processed.
6
+ # Every event is banked on InstagramConnect::WebhookEvent before anything
7
+ # parses it. That is what makes an unparsed or mis-parsed event recoverable:
8
+ # Meta neither stores nor re-delivers webhooks, so anything dropped here is
9
+ # gone permanently. See Ingest::Dispatcher for the walk.
10
+ #
11
+ # Returns a Summary, which reads like the plain hash 0.2.x returned.
8
12
  class Ingest
9
13
  def self.call(payload:, config: InstagramConnect.configuration)
10
- new(config).call(payload)
11
- end
12
-
13
- def initialize(config)
14
- @config = config
15
- end
16
-
17
- def call(payload)
18
- summary = { messages: 0, comments: 0, postbacks: 0, skipped: 0 }
19
- Array(payload && payload["entry"]).each do |entry|
20
- account = account_for(entry)
21
- if account.nil?
22
- summary[:skipped] += 1
23
- next
24
- end
25
- Array(entry["messaging"]).each { |event| ingest_messaging(account, event, summary) }
26
- Array(entry["changes"]).each { |change| ingest_change(account, change, summary) }
27
- end
28
- summary
29
- end
30
-
31
- private
32
-
33
- attr_reader :config
34
-
35
- def account_for(entry)
36
- id = entry["id"].to_s
37
- Account.find_by(ig_user_id: id) || Account.find_by(page_id: id)
38
- end
39
-
40
- def ingest_messaging(account, event, summary)
41
- if event["message"]
42
- ingest_message(account, event, summary)
43
- elsif event["postback"]
44
- invoke(config.on_postback, build_postback(account, event))
45
- summary[:postbacks] += 1
46
- else
47
- summary[:skipped] += 1
48
- end
49
- end
50
-
51
- def ingest_message(account, event, summary)
52
- msg = event["message"]
53
- mid = msg["mid"].to_s
54
- if mid.empty? || !InboundMessage.claim(ig_message_id: mid, account_id: account.id)
55
- summary[:skipped] += 1
56
- return
57
- end
58
-
59
- echo = msg["is_echo"] ? true : false
60
- igsid = (echo ? event.dig("recipient", "id") : event.dig("sender", "id")).to_s
61
- conversation = Conversation.locate(account: account, igsid: igsid)
62
- message = Message.create!(
63
- conversation: conversation,
64
- direction: echo ? "outbound" : "inbound",
65
- status: echo ? "sent" : "received",
66
- source: echo ? "operator_app" : "inbound",
67
- kind: "dm",
68
- body: msg["text"],
69
- ig_message_id: mid,
70
- media_status: media?(msg) ? "pending" : "none"
71
- )
72
- conversation.register_message(message)
73
- invoke(config.on_message, message) unless echo
74
- summary[:messages] += 1
75
- end
76
-
77
- def ingest_change(account, change, summary)
78
- unless change["field"] == "comments"
79
- summary[:skipped] += 1
80
- return
81
- end
82
- value = change["value"] || {}
83
- comment = Comment.record(
84
- account: account,
85
- comment_id: value["id"].to_s,
86
- media_id: value.dig("media", "id"),
87
- text: value["text"],
88
- from_username: value.dig("from", "username"),
89
- parent_id: value["parent_id"]
90
- )
91
- invoke(config.on_comment, comment)
92
- summary[:comments] += 1
93
- end
94
-
95
- def media?(msg)
96
- Array(msg["attachments"]).any?
97
- end
98
-
99
- def build_postback(account, event)
100
- {
101
- account_id: account.id,
102
- sender_id: event.dig("sender", "id"),
103
- payload: event.dig("postback", "payload"),
104
- title: event.dig("postback", "title")
105
- }
106
- end
107
-
108
- def invoke(handler, arg)
109
- handler.call(arg) if handler.respond_to?(:call)
14
+ Dispatcher.new(config).call(payload)
110
15
  end
111
16
  end
112
17
  end
18
+
19
+ require_relative "ingest/envelope"
20
+ require_relative "ingest/summary"
21
+ require_relative "ingest/handlers/base"
22
+ require_relative "ingest/handlers/messages"
23
+ require_relative "ingest/handlers/messaging_postbacks"
24
+ require_relative "ingest/handlers/message_reactions"
25
+ require_relative "ingest/handlers/messaging_seen"
26
+ require_relative "ingest/handlers/messaging_referral"
27
+ require_relative "ingest/handlers/messaging_optins"
28
+ require_relative "ingest/handlers/messaging_handover"
29
+ require_relative "ingest/handlers/comments"
30
+ require_relative "ingest/handlers/mentions"
31
+ require_relative "ingest/handlers/story_insights"
32
+ require_relative "ingest/handlers/unknown"
33
+ require_relative "ingest/registry"
34
+ require_relative "ingest/dispatcher"
@@ -0,0 +1,57 @@
1
+ require "marcel"
2
+ require "stringio"
3
+
4
+ module InstagramConnect
5
+ module Media
6
+ # Turns fetched bytes into a stored file, or into an honest reason why not.
7
+ #
8
+ # The rule that matters here: when the declared Content-Type and the actual
9
+ # magic bytes disagree, the magic bytes win. A Content-Type header is
10
+ # metadata anyone can set; the first few bytes of the file are what the file
11
+ # actually is. Trusting the header is how a host ends up serving an HTML
12
+ # document from an <img> tag.
13
+ module Attaching
14
+ Result = Struct.new(:ok, :mime, :size, :error, keyword_init: true) do
15
+ def ok? = ok
16
+ end
17
+
18
+ module_function
19
+
20
+ def evaluate(body:, declared_mime:, filename: nil, config: InstagramConnect.configuration)
21
+ bytes = body.to_s
22
+ return failure("empty") if bytes.empty?
23
+
24
+ mime = sniff(bytes, filename: filename, declared: declared_mime)
25
+ return failure("type_not_allowed:#{mime}") unless allowed?(mime, config)
26
+ return failure("too_large:#{bytes.bytesize}") unless within_size?(mime, bytes.bytesize, config)
27
+
28
+ Result.new(ok: true, mime: mime, size: bytes.bytesize)
29
+ end
30
+
31
+ def sniff(bytes, filename: nil, declared: nil)
32
+ sniffed = ::Marcel::MimeType.for(StringIO.new(bytes), name: filename)
33
+ # Marcel falls back to this when it recognises nothing, in which case the
34
+ # declared type is the only information available and is better than
35
+ # nothing.
36
+ return declared.to_s.split(";").first.to_s.strip if sniffed == "application/octet-stream" && declared.present?
37
+
38
+ sniffed
39
+ end
40
+
41
+ def allowed?(mime, config)
42
+ allowed = config.allowed_media_types
43
+ allowed.blank? || allowed.include?(mime)
44
+ end
45
+
46
+ # Both Meta's per-type ceiling and the host's own cap have to hold. The
47
+ # host's exists so an adopter can be stricter than Meta, never looser.
48
+ def within_size?(mime, bytes, config)
49
+ Limits.within_size?(mime, bytes) && bytes <= config.media_max_bytes.to_i
50
+ end
51
+
52
+ def failure(reason)
53
+ Result.new(ok: false, error: reason)
54
+ end
55
+ end
56
+ end
57
+ end
@@ -0,0 +1,46 @@
1
+ module InstagramConnect
2
+ module Media
3
+ # Meta's ceilings, in one place, read by the composer, the send path and the
4
+ # client so the numbers cannot drift apart.
5
+ module Limits
6
+ IMAGE_MAX_BYTES = 8 * 1024 * 1024
7
+ AUDIO_VIDEO_MAX_BYTES = 25 * 1024 * 1024
8
+ ATTACHMENTS_MAX = 10
9
+
10
+ # BYTES, not characters. An emoji-heavy 400-character reply is over the
11
+ # limit and Meta rejects the whole send, so anything measuring this with
12
+ # String#length is measuring the wrong thing.
13
+ TEXT_MAX_BYTES = 1000
14
+
15
+ IMAGE_TYPES = %w[image/jpeg image/png image/gif].freeze
16
+ AUDIO_TYPES = %w[audio/aac audio/mp4 audio/mpeg audio/ogg audio/wav].freeze
17
+ VIDEO_TYPES = %w[video/mp4 video/ogg video/avi video/quicktime video/webm].freeze
18
+
19
+ module_function
20
+
21
+ # The ceiling that applies to a given MIME type. Images get a tighter one
22
+ # than audio and video, and an unknown type is held to the tighter of the
23
+ # two rather than waved through.
24
+ def max_bytes_for(mime)
25
+ image?(mime) ? IMAGE_MAX_BYTES : AUDIO_VIDEO_MAX_BYTES
26
+ end
27
+
28
+ def image?(mime)
29
+ IMAGE_TYPES.include?(mime.to_s)
30
+ end
31
+
32
+ def within_size?(mime, bytes)
33
+ bytes.to_i.positive? && bytes.to_i <= max_bytes_for(mime)
34
+ end
35
+
36
+ # Only images can be batched; Meta accepts one audio or video per message.
37
+ def attachments_within_limit?(count)
38
+ count.to_i <= ATTACHMENTS_MAX
39
+ end
40
+
41
+ def text_within_limit?(text)
42
+ text.to_s.bytesize <= TEXT_MAX_BYTES
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,88 @@
1
+ module InstagramConnect
2
+ # Keeps calls inside Meta's per-account ceilings.
3
+ #
4
+ # Meta publishes several limits at once and exhausting any of them throttles
5
+ # the whole app for hours, so the cost of being slightly conservative is far
6
+ # lower than the cost of being slightly wrong.
7
+ module RateLimiter
8
+ # Meta's documented per-account limits. The graph default is the floor of
9
+ # the 4800 × impressions formula: impressions are not knowable from the
10
+ # messaging API, so the floor is what is safe to assume until the usage
11
+ # headers say otherwise.
12
+ BUCKETS = {
13
+ graph: { limit: 4800, window: 86_400 },
14
+ conversations: { limit: 2, window: 1 },
15
+ send_text: { limit: 100, window: 1 },
16
+ send_media: { limit: 10, window: 1 },
17
+ private_reply: { limit: 750, window: 3600 },
18
+ publish: { limit: 50, window: 86_400 }
19
+ }.freeze
20
+
21
+ Outcome = Struct.new(:allowed, :retry_after, keyword_init: true) do
22
+ def allowed? = allowed
23
+ end
24
+
25
+ module_function
26
+
27
+ # Claims one call from a bucket. Returns an Outcome saying whether to
28
+ # proceed and, if not, how long to wait — callers re-enqueue rather than
29
+ # sleep, since a worker asleep on a rate limit is a worker not delivering
30
+ # anything else.
31
+ def acquire(account:, bucket:, now: Time.current)
32
+ spec = BUCKETS.fetch(bucket.to_sym)
33
+ row = budget_for(account, bucket, spec, now)
34
+
35
+ return Outcome.new(allowed: false, retry_after: (row.blocked_until - now).ceil) if row.blocked?
36
+
37
+ claimed = ApiBudget.where(id: row.id).where("used < limit_value")
38
+ .update_all("used = used + 1, updated_at = #{ApiBudget.connection.quote(now)}")
39
+
40
+ if claimed == 1
41
+ Outcome.new(allowed: true, retry_after: nil)
42
+ else
43
+ Outcome.new(allowed: false, retry_after: (row.window_end - now).ceil.clamp(1, spec[:window]))
44
+ end
45
+ end
46
+
47
+ # Records what Meta reported after a call. Its own numbers beat any local
48
+ # arithmetic, so a warning halves the remaining allowance and a critical
49
+ # reading blocks the account outright until the stated recovery time.
50
+ def observe(account:, bucket:, usage:, now: Time.current)
51
+ return if usage.nil?
52
+
53
+ spec = BUCKETS.fetch(bucket.to_sym)
54
+ row = budget_for(account, bucket, spec, now)
55
+
56
+ if usage.critical?
57
+ row.update!(blocked_until: now + (usage.retry_after || spec[:window]))
58
+ elsif usage.warning?
59
+ row.update!(limit_value: [ row.limit_value / 2, row.used + 1 ].max)
60
+ end
61
+ end
62
+
63
+ # Called when Meta returns an explicit retry_after: one 429 pauses every
64
+ # job for that account, rather than each one having to discover it.
65
+ def block!(account:, bucket:, seconds:, now: Time.current)
66
+ spec = BUCKETS.fetch(bucket.to_sym)
67
+ budget_for(account, bucket, spec, now).update!(blocked_until: now + seconds.to_i)
68
+ end
69
+
70
+ def budget_for(account, bucket, spec, now)
71
+ start = window_start(now, spec[:window])
72
+ ApiBudget.find_or_create_by!(
73
+ account_id: account.id, bucket: bucket.to_s, window_start: start
74
+ ) do |row|
75
+ row.window_seconds = spec[:window]
76
+ row.limit_value = spec[:limit]
77
+ end
78
+ rescue ActiveRecord::RecordNotUnique
79
+ ApiBudget.find_by!(account_id: account.id, bucket: bucket.to_s, window_start: start)
80
+ end
81
+
82
+ # Fixed windows aligned to the epoch, so every process agrees on where a
83
+ # window starts without having to coordinate.
84
+ def window_start(now, seconds)
85
+ Time.at((now.to_i / seconds) * seconds).utc
86
+ end
87
+ end
88
+ end