instagram_connect 0.2.1 → 0.3.0
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.
- checksums.yaml +4 -4
- data/.github/workflows/ci.yml +36 -0
- data/CHANGELOG.md +81 -0
- data/Gemfile +4 -0
- data/README.md +328 -73
- data/app/controllers/instagram_connect/comments_controller.rb +1 -1
- data/app/controllers/instagram_connect/posts_controller.rb +1 -1
- data/app/jobs/instagram_connect/account_readiness_job.rb +148 -0
- data/app/jobs/instagram_connect/fetch_media_job.rb +110 -0
- data/app/jobs/instagram_connect/profile_sync_job.rb +78 -0
- data/app/jobs/instagram_connect/replay_events_job.rb +57 -0
- data/app/jobs/instagram_connect/send_message_job.rb +44 -16
- data/app/models/instagram_connect/account.rb +27 -1
- data/app/models/instagram_connect/api_budget.rb +22 -0
- data/app/models/instagram_connect/conversation.rb +99 -11
- data/app/models/instagram_connect/inbound_message.rb +11 -3
- data/app/models/instagram_connect/insight_snapshot.rb +43 -0
- data/app/models/instagram_connect/media_item.rb +38 -0
- data/app/models/instagram_connect/mention.rb +37 -0
- data/app/models/instagram_connect/message.rb +34 -2
- data/app/models/instagram_connect/message_attachment.rb +53 -0
- data/app/models/instagram_connect/message_reaction.rb +33 -0
- data/app/models/instagram_connect/webhook_event.rb +67 -0
- data/db/migrate/20260725194732_create_instagram_connect_webhook_events.rb +52 -0
- data/db/migrate/20260725200216_add_messaging_event_fields.rb +89 -0
- data/db/migrate/20260725200250_create_instagram_connect_message_reactions.rb +30 -0
- data/db/migrate/20260725201320_create_instagram_connect_message_attachments.rb +33 -0
- data/db/migrate/20260725202616_add_outbound_send_fields.rb +27 -0
- data/db/migrate/20260725203213_create_instagram_connect_media.rb +30 -0
- data/db/migrate/20260725203214_create_instagram_connect_mentions.rb +30 -0
- data/db/migrate/20260725203215_create_instagram_connect_insight_snapshots.rb +45 -0
- data/db/migrate/20260725203306_add_comment_moderation_fields.rb +29 -0
- data/db/migrate/20260725204022_add_per_account_token_fields.rb +76 -0
- data/db/migrate/20260725204815_create_instagram_connect_api_budgets.rb +29 -0
- data/db/migrate/20260725205417_add_conversation_profile_fields.rb +21 -0
- data/docs/CONFIGURATION.md +107 -0
- data/lib/instagram_connect/client.rb +109 -3
- data/lib/instagram_connect/configuration.rb +10 -0
- data/lib/instagram_connect/engine.rb +1 -0
- data/lib/instagram_connect/ingest/dispatcher.rb +151 -0
- data/lib/instagram_connect/ingest/envelope.rb +31 -0
- data/lib/instagram_connect/ingest/handlers/base.rb +55 -0
- data/lib/instagram_connect/ingest/handlers/comments.rb +59 -0
- data/lib/instagram_connect/ingest/handlers/mentions.rb +48 -0
- data/lib/instagram_connect/ingest/handlers/message_reactions.rb +91 -0
- data/lib/instagram_connect/ingest/handlers/messages.rb +135 -0
- data/lib/instagram_connect/ingest/handlers/messaging_handover.rb +53 -0
- data/lib/instagram_connect/ingest/handlers/messaging_optins.rb +37 -0
- data/lib/instagram_connect/ingest/handlers/messaging_postbacks.rb +24 -0
- data/lib/instagram_connect/ingest/handlers/messaging_referral.rb +42 -0
- data/lib/instagram_connect/ingest/handlers/messaging_seen.rb +37 -0
- data/lib/instagram_connect/ingest/handlers/story_insights.rb +62 -0
- data/lib/instagram_connect/ingest/handlers/unknown.rb +19 -0
- data/lib/instagram_connect/ingest/registry.rb +93 -0
- data/lib/instagram_connect/ingest/summary.rb +75 -0
- data/lib/instagram_connect/ingest.rb +27 -105
- data/lib/instagram_connect/media/attaching.rb +57 -0
- data/lib/instagram_connect/media/limits.rb +46 -0
- data/lib/instagram_connect/rate_limiter.rb +88 -0
- data/lib/instagram_connect/result.rb +26 -6
- data/lib/instagram_connect/text_splitter.rb +51 -0
- data/lib/instagram_connect/usage.rb +68 -0
- data/lib/instagram_connect/version.rb +1 -1
- data/lib/instagram_connect.rb +23 -0
- metadata +60 -2
- data/MIT-LICENSE +0 -20
|
@@ -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
|
-
#
|
|
3
|
-
#
|
|
4
|
-
#
|
|
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
|
-
#
|
|
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
|
|
@@ -3,15 +3,17 @@ module InstagramConnect
|
|
|
3
3
|
# API-level failures — callers branch on +success?+ and read +error_code+ /
|
|
4
4
|
# +error_message+. Transport/programming errors still raise.
|
|
5
5
|
class Result
|
|
6
|
-
attr_reader :success, :id, :error_code, :error_message, :retry_after, :data
|
|
6
|
+
attr_reader :success, :id, :error_code, :error_message, :retry_after, :data, :usage
|
|
7
7
|
|
|
8
|
-
def initialize(success:, id: nil, error_code: nil, error_message: nil, retry_after: nil,
|
|
8
|
+
def initialize(success:, id: nil, error_code: nil, error_message: nil, retry_after: nil,
|
|
9
|
+
data: {}, usage: nil)
|
|
9
10
|
@success = success
|
|
10
11
|
@id = id
|
|
11
12
|
@error_code = error_code
|
|
12
13
|
@error_message = error_message
|
|
13
14
|
@retry_after = retry_after
|
|
14
15
|
@data = data || {}
|
|
16
|
+
@usage = usage
|
|
15
17
|
end
|
|
16
18
|
|
|
17
19
|
def success?
|
|
@@ -22,13 +24,31 @@ module InstagramConnect
|
|
|
22
24
|
!success?
|
|
23
25
|
end
|
|
24
26
|
|
|
27
|
+
# Meta's cursor for the next page, or nil when this is the last one. Reading
|
|
28
|
+
# `paging.next` rather than incrementing an offset is the only correct way
|
|
29
|
+
# through a Graph collection — results shift under you between calls.
|
|
30
|
+
def next_cursor
|
|
31
|
+
data.dig("paging", "cursors", "after").presence if more?
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
def more?
|
|
35
|
+
data.is_a?(Hash) && data.dig("paging", "next").present?
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# The rows of a collection response, or [] for a single-object one.
|
|
39
|
+
def records
|
|
40
|
+
list = data["data"]
|
|
41
|
+
list.is_a?(Array) ? list : []
|
|
42
|
+
end
|
|
43
|
+
|
|
25
44
|
# Convenience builders so call sites read cleanly.
|
|
26
|
-
def self.ok(id: nil, data: {})
|
|
27
|
-
new(success: true, id: id, data: data)
|
|
45
|
+
def self.ok(id: nil, data: {}, usage: nil)
|
|
46
|
+
new(success: true, id: id, data: data, usage: usage)
|
|
28
47
|
end
|
|
29
48
|
|
|
30
|
-
def self.error(message, error_code: nil, retry_after: nil, data: {})
|
|
31
|
-
new(success: false, error_message: message, error_code: error_code,
|
|
49
|
+
def self.error(message, error_code: nil, retry_after: nil, data: {}, usage: nil)
|
|
50
|
+
new(success: false, error_message: message, error_code: error_code,
|
|
51
|
+
retry_after: retry_after, data: data, usage: usage)
|
|
32
52
|
end
|
|
33
53
|
end
|
|
34
54
|
end
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
module InstagramConnect
|
|
2
|
+
# Splits a reply that exceeds Meta's 1000-byte message ceiling into parts that
|
|
3
|
+
# fit.
|
|
4
|
+
#
|
|
5
|
+
# Splitting rather than truncating is deliberate: a customer reading half an
|
|
6
|
+
# answer is worse than reading two bubbles, and the operator who wrote it has
|
|
7
|
+
# no way to know it was cut.
|
|
8
|
+
module TextSplitter
|
|
9
|
+
module_function
|
|
10
|
+
|
|
11
|
+
# Returns the parts to send, in order. A message already within the limit
|
|
12
|
+
# comes back as a single-element array, so callers have one code path.
|
|
13
|
+
def split(text, limit: Media::Limits::TEXT_MAX_BYTES)
|
|
14
|
+
text = text.to_s
|
|
15
|
+
return [ text ] if text.bytesize <= limit
|
|
16
|
+
|
|
17
|
+
parts = []
|
|
18
|
+
remaining = text
|
|
19
|
+
|
|
20
|
+
while remaining.bytesize > limit
|
|
21
|
+
chunk = take(remaining, limit)
|
|
22
|
+
parts << chunk.rstrip
|
|
23
|
+
remaining = remaining[chunk.length..].to_s.lstrip
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
# Text that divides exactly on a break leaves nothing over; appending an
|
|
27
|
+
# empty part would send an empty bubble.
|
|
28
|
+
parts << remaining unless remaining.empty?
|
|
29
|
+
parts
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# The longest prefix that fits, broken at whitespace where possible so words
|
|
33
|
+
# survive. Falls back to a hard character break for input with no
|
|
34
|
+
# whitespace at all — a long URL, or a script that does not use spaces.
|
|
35
|
+
def take(text, limit)
|
|
36
|
+
candidate = +""
|
|
37
|
+
last_break = nil
|
|
38
|
+
|
|
39
|
+
text.each_char do |char|
|
|
40
|
+
break if candidate.bytesize + char.bytesize > limit
|
|
41
|
+
|
|
42
|
+
candidate << char
|
|
43
|
+
last_break = candidate.length if char.match?(/\s/)
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
return candidate if last_break.nil?
|
|
47
|
+
|
|
48
|
+
candidate[0, last_break]
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
end
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
require "json"
|
|
2
|
+
|
|
3
|
+
module InstagramConnect
|
|
4
|
+
# Meta's own account of how much of the rate budget a call just consumed,
|
|
5
|
+
# parsed from the response headers.
|
|
6
|
+
#
|
|
7
|
+
# This is worth having because the documented formula — 4800 calls per 24
|
|
8
|
+
# hours multiplied by the account's impressions — depends on a number the
|
|
9
|
+
# messaging API never returns. Any budget computed locally is a guess. These
|
|
10
|
+
# headers are Meta telling you the answer directly, so they are treated as
|
|
11
|
+
# ground truth and the arithmetic only as a fallback.
|
|
12
|
+
class Usage
|
|
13
|
+
HEADERS = %w[x-business-use-case-usage x-app-usage].freeze
|
|
14
|
+
|
|
15
|
+
# Back off well before the wall: at 100% Meta stops answering, and the
|
|
16
|
+
# penalty is measured in hours.
|
|
17
|
+
WARN_AT = 80
|
|
18
|
+
CRITICAL_AT = 95
|
|
19
|
+
|
|
20
|
+
attr_reader :call_count, :total_cputime, :total_time, :estimated_time_to_regain_access
|
|
21
|
+
|
|
22
|
+
def initialize(call_count: 0, total_cputime: 0, total_time: 0, estimated_time_to_regain_access: nil)
|
|
23
|
+
@call_count = call_count.to_i
|
|
24
|
+
@total_cputime = total_cputime.to_i
|
|
25
|
+
@total_time = total_time.to_i
|
|
26
|
+
@estimated_time_to_regain_access = estimated_time_to_regain_access
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# Returns nil when Meta sent no usage headers, which is normal for some
|
|
30
|
+
# endpoints — absence is not zero usage and must not be read as headroom.
|
|
31
|
+
def self.from_headers(headers)
|
|
32
|
+
raw = HEADERS.filter_map { |name| headers&.[](name) }.first
|
|
33
|
+
return nil if raw.blank?
|
|
34
|
+
|
|
35
|
+
payload = JSON.parse(raw)
|
|
36
|
+
# The business header is keyed by object id and holds an array; the app
|
|
37
|
+
# header is a flat hash.
|
|
38
|
+
metrics = payload.is_a?(Hash) && payload.values.first.is_a?(Array) ? payload.values.first.first : payload
|
|
39
|
+
return nil unless metrics.is_a?(Hash)
|
|
40
|
+
|
|
41
|
+
new(
|
|
42
|
+
call_count: metrics["call_count"],
|
|
43
|
+
total_cputime: metrics["total_cputime"],
|
|
44
|
+
total_time: metrics["total_time"],
|
|
45
|
+
estimated_time_to_regain_access: metrics["estimated_time_to_regain_access"]
|
|
46
|
+
)
|
|
47
|
+
rescue JSON::ParserError
|
|
48
|
+
nil
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# The worst of the three, since exhausting any one of them throttles the app.
|
|
52
|
+
def percentage
|
|
53
|
+
[ call_count, total_cputime, total_time ].max
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def warning?
|
|
57
|
+
percentage >= WARN_AT
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def critical?
|
|
61
|
+
percentage >= CRITICAL_AT
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def retry_after
|
|
65
|
+
estimated_time_to_regain_access.to_i * 60 if estimated_time_to_regain_access.to_i.positive?
|
|
66
|
+
end
|
|
67
|
+
end
|
|
68
|
+
end
|