command_tower 0.18.0 → 0.20.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.
Files changed (51) hide show
  1. checksums.yaml +4 -4
  2. data/app/deserializers/command_tower/deserializers/messaging/preferences/update_deserializer.rb +10 -1
  3. data/app/errors/command_tower/errors/account/push_test_destination_error.rb +21 -0
  4. data/app/models/command_tower/messaging/delivery_attempt.rb +5 -0
  5. data/app/models/command_tower/messaging/inbox_item.rb +6 -0
  6. data/app/serializers/command_tower/serializers/messaging/inbox.rb +1 -1
  7. data/app/serializers/command_tower/serializers/messaging/preferences/notification_serializer.rb +2 -0
  8. data/app/services/command_tower/messaging/delivery_retry_policy.rb +97 -0
  9. data/app/services/command_tower/messaging/execution/adapter_result.rb +11 -1
  10. data/app/services/command_tower/messaging/execution/adapters/expo/adapter.rb +199 -30
  11. data/app/services/command_tower/messaging/execution/adapters/expo/configuration.rb +5 -0
  12. data/app/services/command_tower/messaging/execution/adapters/expo/endpoint_ticket_history.rb +86 -0
  13. data/app/services/command_tower/messaging/execution/adapters/expo/http_client.rb +4 -0
  14. data/app/services/command_tower/messaging/execution/adapters/expo/interruption_level.rb +41 -0
  15. data/app/services/command_tower/messaging/execution/attempt_ledger.rb +45 -2
  16. data/app/services/command_tower/messaging/execution/expo_receipt_collection.rb +224 -0
  17. data/app/services/command_tower/messaging/execution/operation_logger.rb +65 -5
  18. data/app/services/command_tower/messaging/execution/recovery.rb +72 -8
  19. data/app/services/command_tower/messaging/inbox/reader.rb +15 -2
  20. data/app/services/command_tower/messaging/inbox/unread_count_result.rb +3 -2
  21. data/app/services/command_tower/messaging/notification_types/declaration.rb +19 -1
  22. data/app/services/command_tower/messaging/notification_types/declaration_validator.rb +62 -0
  23. data/app/services/command_tower/messaging/notification_types/permitted_choice.rb +55 -0
  24. data/app/services/command_tower/messaging/notification_types/registry.rb +25 -0
  25. data/app/services/command_tower/messaging/notification_types.rb +3 -0
  26. data/app/services/command_tower/messaging/preferences/catalog.rb +7 -0
  27. data/app/services/command_tower/messaging/preferences/catalog_notification_result.rb +26 -1
  28. data/app/services/command_tower/messaging/preferences/effective_choice.rb +92 -0
  29. data/app/services/command_tower/messaging/preferences/preference_state.rb +24 -4
  30. data/app/services/command_tower/messaging/preferences/store.rb +10 -0
  31. data/app/services/command_tower/messaging/preferences/update.rb +36 -4
  32. data/app/services/command_tower/messaging/rendering/channel_renderer.rb +63 -3
  33. data/app/services/command_tower/messaging/rendering/inbox_document.rb +27 -0
  34. data/app/services/command_tower/messaging/rendering/push_presentation.rb +90 -0
  35. data/app/services/command_tower/messaging/rendering/rendered_push_payload.rb +54 -6
  36. data/app/services/command_tower/messaging/sound_catalog.rb +85 -0
  37. data/app/services/command_tower/services/account/push/send_self_test.rb +7 -1
  38. data/app/services/command_tower/services/messaging/communications/produce.rb +27 -0
  39. data/app/services/command_tower/services/messaging/inbox.rb +5 -1
  40. data/app/workflows/command_tower/workflows/me/error_mapping.rb +1 -0
  41. data/app/workflows/command_tower/workflows/messaging/execution/deliver_workflow.rb +24 -1
  42. data/db/migrate/20261012000001_add_provider_metadata_to_messaging_delivery_attempts.rb +7 -0
  43. data/db/migrate/20261012000002_add_finished_at_index_to_messaging_delivery_attempts.rb +8 -0
  44. data/docs/upgrades/0.19.0.md +40 -0
  45. data/docs/upgrades/0.20.0.md +29 -0
  46. data/docs/upgrades/README.md +2 -0
  47. data/lib/command_tower/configuration/messaging/config.rb +10 -0
  48. data/lib/command_tower/configuration/messaging/expo.rb +61 -0
  49. data/lib/command_tower/install/baseline.rb +2 -0
  50. data/lib/command_tower/version.rb +1 -1
  51. metadata +14 -2
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Messaging
5
+ module Execution
6
+ module Adapters
7
+ module Expo
8
+ # Read-only lookup over the provider_metadata that earlier attempts of one delivery
9
+ # recorded: which endpoints already hold an accepted Expo ticket and which hit a
10
+ # terminal ticket error. Used so a retry only sends to endpoints still unsettled.
11
+ class EndpointTicketHistory
12
+ History = Data.define(:accepted_ticket_ids, :terminal_error_codes) do
13
+ def settled_endpoint_ids
14
+ accepted_ticket_ids.keys | terminal_error_codes.keys
15
+ end
16
+
17
+ def accepted?
18
+ accepted_ticket_ids.any?
19
+ end
20
+
21
+ def first_accepted_ticket_id
22
+ accepted_ticket_ids.values.first
23
+ end
24
+
25
+ def first_terminal_error_code
26
+ terminal_error_codes.values.first
27
+ end
28
+ end
29
+
30
+ def self.call(channel_delivery_id:, excluding_attempt_id:)
31
+ new(channel_delivery_id:, excluding_attempt_id:).call
32
+ end
33
+
34
+ def initialize(channel_delivery_id:, excluding_attempt_id:)
35
+ @channel_delivery_id = channel_delivery_id
36
+ @excluding_attempt_id = excluding_attempt_id
37
+ end
38
+
39
+ def call
40
+ accepted = {}
41
+ rejected = {}
42
+
43
+ recorded_endpoints.each do |entry|
44
+ endpoint_id = entry["endpoint_id"]
45
+ next if endpoint_id.nil?
46
+
47
+ case entry["ticket_status"]
48
+ when "ok"
49
+ if entry["receipt_status"] == "error"
50
+ # Accepted ticket but the receipt reported a failure: terminal for that device.
51
+ rejected[endpoint_id] ||= entry["error_code"]
52
+ else
53
+ accepted[endpoint_id] ||= entry["ticket_id"]
54
+ end
55
+ when "error"
56
+ rejected[endpoint_id] ||= entry["error_code"]
57
+ end
58
+ end
59
+
60
+ History.new(
61
+ accepted_ticket_ids: accepted.freeze,
62
+ terminal_error_codes: rejected.except(*accepted.keys).freeze,
63
+ ).freeze
64
+ end
65
+
66
+ private
67
+
68
+ def recorded_endpoints
69
+ Messaging::DeliveryAttempt
70
+ .where(channel_delivery_id: @channel_delivery_id)
71
+ .where.not(id: @excluding_attempt_id)
72
+ .order(:started_at, :id)
73
+ .pluck(:provider_metadata)
74
+ .flat_map { |metadata| endpoints_in(metadata) }
75
+ end
76
+
77
+ def endpoints_in(metadata)
78
+ endpoints = metadata.is_a?(Hash) ? metadata.dig("expo", "endpoints") : nil
79
+ endpoints.is_a?(Array) ? endpoints.grep(Hash) : []
80
+ end
81
+ end
82
+ end
83
+ end
84
+ end
85
+ end
86
+ end
@@ -12,6 +12,8 @@ module CommandTower
12
12
  # Narrow Expo Push HTTP client for Messaging notification push.
13
13
  # Never logs tokens, Authorization headers, or raw bodies that may contain tokens.
14
14
  class HttpClient
15
+ RequestNotSubmitted = Class.new(StandardError)
16
+
15
17
  def initialize(configuration: nil)
16
18
  @configuration = configuration || Configuration.new
17
19
  end
@@ -65,6 +67,8 @@ module CommandTower
65
67
  ) do |http|
66
68
  http.request(request)
67
69
  end
70
+ rescue Net::OpenTimeout, Errno::ECONNREFUSED, Errno::EHOSTUNREACH, SocketError => error
71
+ raise RequestNotSubmitted, error.message
68
72
  end
69
73
 
70
74
  def parse_send_response(response)
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Messaging
5
+ module Execution
6
+ module Adapters
7
+ module Expo
8
+ # Maps a member's neutral urgency to Expo's `interruptionLevel`, degrading to the
9
+ # highest level the host says its shipped binary can honor:
10
+ # critical -> time_sensitive -> normal. Normal is the platform default, so it
11
+ # sends no level. Pure: no I/O.
12
+ class InterruptionLevel
13
+ EXPO_LEVELS = {
14
+ "time_sensitive" => "time-sensitive",
15
+ "critical" => "critical",
16
+ }.freeze
17
+ DEGRADE_ORDER = %w[critical time_sensitive].freeze
18
+
19
+ def self.call(urgency:, supported:)
20
+ new(urgency:, supported:).call
21
+ end
22
+
23
+ def initialize(urgency:, supported:)
24
+ @urgency = urgency.to_s
25
+ @supported = Array(supported).map(&:to_s)
26
+ end
27
+
28
+ # The Expo level string, or nil when the message should carry none.
29
+ def call
30
+ start = DEGRADE_ORDER.index(@urgency)
31
+ return nil if start.nil?
32
+
33
+ level = DEGRADE_ORDER.drop(start).find { |candidate| @supported.include?(candidate) }
34
+ EXPO_LEVELS[level]
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
41
+ end
@@ -55,6 +55,7 @@ module CommandTower
55
55
  finished_at: now,
56
56
  normalized_provider_status: result.normalized_provider_status,
57
57
  provider_message_id: result.provider_message_id,
58
+ provider_metadata: result.provider_metadata,
58
59
  error_code: nil,
59
60
  error_class: nil,
60
61
  )
@@ -65,6 +66,7 @@ module CommandTower
65
66
  finished_at: now,
66
67
  normalized_provider_status: result.normalized_provider_status,
67
68
  provider_message_id: result.provider_message_id,
69
+ provider_metadata: result.provider_metadata,
68
70
  error_code: result.error_code,
69
71
  error_class: nil,
70
72
  )
@@ -75,6 +77,7 @@ module CommandTower
75
77
  finished_at: now,
76
78
  normalized_provider_status: result.normalized_provider_status,
77
79
  provider_message_id: result.provider_message_id,
80
+ provider_metadata: result.provider_metadata,
78
81
  error_code: result.error_code,
79
82
  error_class: nil,
80
83
  )
@@ -105,6 +108,31 @@ module CommandTower
105
108
  now = Time.current
106
109
  resolved_class = error_class || error&.class&.name || "UnknownError"
107
110
 
111
+ if Messaging::DeliveryRetryPolicy.push_channel?(delivery)
112
+ uncertain = Messaging::DeliveryRetryPolicy::SUBMISSION_UNCERTAIN
113
+ ActiveRecord::Base.transaction do
114
+ attempt.update!(
115
+ status: Messaging::DeliveryAttempt::STATUS_FAILED_TERMINAL,
116
+ finished_at: now,
117
+ error_code: uncertain,
118
+ error_class: resolved_class,
119
+ normalized_provider_status: nil,
120
+ provider_message_id: nil,
121
+ )
122
+ delivery.update!(status: Messaging::ChannelDelivery::STATUS_FAILED_TERMINAL)
123
+ end
124
+
125
+ delivery.reload
126
+ attempt.reload
127
+ OperationLogger.attempt_failed(channel_delivery: delivery, delivery_attempt: attempt)
128
+ OperationLogger.failed(
129
+ channel_delivery: delivery,
130
+ error_code: uncertain,
131
+ error_class: resolved_class,
132
+ )
133
+ return delivery
134
+ end
135
+
108
136
  ActiveRecord::Base.transaction do
109
137
  attempt.update!(
110
138
  status: Messaging::DeliveryAttempt::STATUS_FAILED_RETRYABLE,
@@ -125,8 +153,17 @@ module CommandTower
125
153
  error_code: "internal_adapter_error",
126
154
  error_class: resolved_class,
127
155
  )
128
- rescue StandardError
129
- mark_failed_retryable_best_effort!(delivery)
156
+ rescue StandardError => error
157
+ OperationLogger.attempt_finalize_unpersisted(
158
+ channel_delivery: delivery,
159
+ delivery_attempt: attempt,
160
+ error_class: error.class.name,
161
+ )
162
+ if Messaging::DeliveryRetryPolicy.push_channel?(delivery)
163
+ mark_failed_terminal_best_effort!(delivery)
164
+ else
165
+ mark_failed_retryable_best_effort!(delivery)
166
+ end
130
167
  end
131
168
 
132
169
  private
@@ -140,6 +177,12 @@ module CommandTower
140
177
  rescue StandardError
141
178
  nil
142
179
  end
180
+
181
+ def mark_failed_terminal_best_effort!(delivery)
182
+ delivery.update(status: Messaging::ChannelDelivery::STATUS_FAILED_TERMINAL)
183
+ rescue StandardError
184
+ nil
185
+ end
143
186
  end
144
187
  end
145
188
  end
@@ -0,0 +1,224 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Messaging
5
+ module Execution
6
+ # Collects Expo receipts that were still pending when a push attempt finished.
7
+ # Called at the end of the recovery sweep. It only reads receipts and records them in the
8
+ # attempt's provider_metadata; it never sends, enqueues, or changes delivery or attempt status.
9
+ #
10
+ # Poll window: attempts that finished within RECEIPT_WINDOW. A bounded, best-effort cleanup
11
+ # read just behind the window marks entries that are still pending as unchecked (no HTTP).
12
+ class ExpoReceiptCollection
13
+ RECEIPT_WINDOW = 15.minutes
14
+ BATCH_SIZE = 100
15
+ RECEIPT_ID_CHUNK_SIZE = 1000
16
+ DEVICE_INVALID_ERRORS = %w[DeviceNotRegistered].freeze
17
+ COUNT_KEYS = %i[
18
+ attempt_count
19
+ receipt_ok_count
20
+ receipt_error_count
21
+ receipt_unchecked_count
22
+ invalidated_count
23
+ poll_failure_count
24
+ update_failure_count
25
+ ].freeze
26
+
27
+ def self.call(configuration: nil, http_client: nil, now: Time.current)
28
+ new(configuration:, http_client:, now:).call
29
+ end
30
+
31
+ def initialize(configuration: nil, http_client: nil, now: Time.current)
32
+ @configuration = configuration || Adapters::Expo::Configuration.new
33
+ @http_client = http_client
34
+ @now = now
35
+ @counts = COUNT_KEYS.index_with { 0 }
36
+ end
37
+
38
+ def call
39
+ return @counts unless http_adapter?
40
+
41
+ cleanup_pass
42
+ poll_pass
43
+ @counts
44
+ rescue StandardError
45
+ @counts[:update_failure_count] += 1
46
+ @counts
47
+ ensure
48
+ OperationLogger.receipts_collected(@counts) if http_adapter?
49
+ end
50
+
51
+ private
52
+
53
+ def http_adapter?
54
+ @configuration.expo_configured? && @configuration.adapter_name == "http"
55
+ end
56
+
57
+ def http_client
58
+ @http_client ||= Adapters::Expo::HttpClient.new(configuration: @configuration)
59
+ end
60
+
61
+ def window_start
62
+ @now - RECEIPT_WINDOW
63
+ end
64
+
65
+ def poll_scope
66
+ attempts_scope.where(finished_at: window_start..)
67
+ end
68
+
69
+ def cleanup_scope
70
+ attempts_scope.where(finished_at: (@now - (2 * RECEIPT_WINDOW))...window_start)
71
+ end
72
+
73
+ def attempts_scope
74
+ Messaging::DeliveryAttempt.where.not(provider_metadata: nil)
75
+ end
76
+
77
+ # Keyset batches ordered by (finished_at, id) so the finished_at index serves the range.
78
+ def each_batch(scope)
79
+ table = Messaging::DeliveryAttempt.arel_table
80
+ cursor = nil
81
+
82
+ loop do
83
+ batch_scope = scope.order(:finished_at, :id).limit(BATCH_SIZE)
84
+ if cursor
85
+ batch_scope = batch_scope.where(
86
+ table[:finished_at].gt(cursor[:finished_at]).or(
87
+ table[:finished_at].eq(cursor[:finished_at]).and(table[:id].gt(cursor[:id])),
88
+ ),
89
+ )
90
+ end
91
+
92
+ rows = batch_scope.preload(channel_delivery: :communication).to_a
93
+ break if rows.empty?
94
+
95
+ yield rows
96
+ break if rows.size < BATCH_SIZE
97
+
98
+ cursor = { finished_at: rows.last.finished_at, id: rows.last.id }
99
+ end
100
+ end
101
+
102
+ def cleanup_pass
103
+ each_batch(cleanup_scope) do |rows|
104
+ rows.each do |attempt|
105
+ next if pending_entries(attempt.provider_metadata).empty?
106
+
107
+ update_attempt(attempt, receipts: {}, expire: true)
108
+ end
109
+ end
110
+ end
111
+
112
+ def poll_pass
113
+ each_batch(poll_scope) do |rows|
114
+ pending = rows.select { |attempt| pending_entries(attempt.provider_metadata).any? }
115
+ next if pending.empty?
116
+
117
+ requested_ids = pending.flat_map { |attempt| pending_entries(attempt.provider_metadata).pluck("ticket_id") }
118
+ receipts = fetch_receipts(requested_ids.uniq)
119
+ next if receipts.empty?
120
+
121
+ pending.each do |attempt|
122
+ ticket_ids = pending_entries(attempt.provider_metadata).pluck("ticket_id")
123
+ next unless ticket_ids.any? { |ticket_id| receipts.key?(ticket_id) }
124
+
125
+ update_attempt(attempt, receipts:, expire: false)
126
+ end
127
+ end
128
+ end
129
+
130
+ def fetch_receipts(ticket_ids)
131
+ receipts = {}
132
+ ticket_ids.each_slice(RECEIPT_ID_CHUNK_SIZE) do |slice|
133
+ result = http_client.get_receipts(slice)
134
+ if result.is_a?(Hash) && result[:ok] && result[:receipts].is_a?(Hash)
135
+ receipts.merge!(result[:receipts])
136
+ else
137
+ @counts[:poll_failure_count] += 1
138
+ end
139
+ rescue StandardError
140
+ @counts[:poll_failure_count] += 1
141
+ end
142
+ receipts
143
+ end
144
+
145
+ def pending_entries(metadata)
146
+ endpoints = metadata.is_a?(Hash) ? metadata.dig("expo", "endpoints") : nil
147
+ return [] unless endpoints.is_a?(Array)
148
+
149
+ endpoints.select do |entry|
150
+ entry.is_a?(Hash) &&
151
+ entry["ticket_status"] == "ok" &&
152
+ entry["receipt_status"] == "pending" &&
153
+ entry["ticket_id"].present?
154
+ end
155
+ end
156
+
157
+ # One short transaction per attempt. A failure rolls back only this attempt and the pass
158
+ # continues with the next one; its entries stay pending for a later sweep.
159
+ def update_attempt(attempt, receipts:, expire:)
160
+ deltas = Hash.new(0)
161
+
162
+ ActiveRecord::Base.transaction do
163
+ attempt.lock!
164
+ metadata = attempt.provider_metadata.deep_dup
165
+ changed = false
166
+
167
+ pending_entries(metadata).each do |entry|
168
+ outcome = apply_outcome!(attempt:, entry:, receipt: receipts[entry["ticket_id"]], expire:, deltas:)
169
+ changed = true if outcome
170
+ end
171
+
172
+ attempt.update!(provider_metadata: metadata) if changed
173
+ deltas[:attempt_count] += 1 if changed
174
+ end
175
+
176
+ deltas.each { |key, value| @counts[key] += value }
177
+ rescue StandardError
178
+ @counts[:update_failure_count] += 1
179
+ end
180
+
181
+ # Returns :unchecked, :ok, or :error when the entry changed, nil when it stays pending.
182
+ def apply_outcome!(attempt:, entry:, receipt:, expire:, deltas:)
183
+ if expire
184
+ entry["receipt_status"] = "unchecked"
185
+ deltas[:receipt_unchecked_count] += 1
186
+ return :unchecked
187
+ end
188
+
189
+ case receipt&.dig(:status)
190
+ when "ok"
191
+ entry["receipt_status"] = "ok"
192
+ deltas[:receipt_ok_count] += 1
193
+ :ok
194
+ when "error"
195
+ record_receipt_error!(attempt:, entry:, receipt:, deltas:)
196
+ :error
197
+ end
198
+ end
199
+
200
+ def record_receipt_error!(attempt:, entry:, receipt:, deltas:)
201
+ entry["receipt_status"] = "error"
202
+ if DEVICE_INVALID_ERRORS.include?(receipt[:error].to_s)
203
+ entry["error_code"] = "expo_device_invalid"
204
+ invalidate_endpoint!(attempt:, endpoint_id: entry["endpoint_id"], deltas:)
205
+ else
206
+ entry["error_code"] = "expo_rejected"
207
+ end
208
+ deltas[:receipt_error_count] += 1
209
+ end
210
+
211
+ def invalidate_endpoint!(attempt:, endpoint_id:, deltas:)
212
+ owner_user_id = attempt.channel_delivery&.communication&.user_id
213
+ return if owner_user_id.nil? || endpoint_id.nil?
214
+
215
+ Endpoints.mark_invalid(owner_user_id:, endpoint_id:)
216
+ deltas[:invalidated_count] += 1
217
+ rescue Endpoints::NotFoundError, Endpoints::ValidationError
218
+ # The device endpoint is already gone; the receipt error is still recorded.
219
+ nil
220
+ end
221
+ end
222
+ end
223
+ end
224
+ end
@@ -45,6 +45,15 @@ module CommandTower
45
45
  info("messaging.execution.recovered", channel_delivery:)
46
46
  end
47
47
 
48
+ # One aggregate event per recovery sweep. Counts only; nothing when nothing happened.
49
+ def receipts_collected(counts)
50
+ counts = counts.to_h.slice(*ExpoReceiptCollection::COUNT_KEYS)
51
+ return if counts.values.sum.zero?
52
+
53
+ failed = counts[:poll_failure_count].to_i.positive? || counts[:update_failure_count].to_i.positive?
54
+ emit(failed ? :error : :info, "messaging.execution.receipts.collected", **counts)
55
+ end
56
+
48
57
  def attempt_started(channel_delivery:, delivery_attempt:)
49
58
  emit_attempt("messaging.execution.attempt.started", channel_delivery:, delivery_attempt:)
50
59
  end
@@ -62,6 +71,28 @@ module CommandTower
62
71
  )
63
72
  end
64
73
 
74
+ def push_destination_fallback(communication:, reason_code:, level:, channel_delivery: nil)
75
+ emit(
76
+ level,
77
+ "messaging.execution.push_destination.fallback",
78
+ channel_delivery:,
79
+ communication_id: communication.id,
80
+ notification_type_key: communication.notification_type_key.to_s,
81
+ reason_code:,
82
+ )
83
+ end
84
+
85
+ def push_presentation_fallback(communication:, reason_code:, channel_delivery: nil)
86
+ emit(
87
+ :warn,
88
+ "messaging.execution.push_presentation.fallback",
89
+ channel_delivery:,
90
+ communication_id: communication.id,
91
+ notification_type_key: communication.notification_type_key.to_s,
92
+ reason_code:,
93
+ )
94
+ end
95
+
65
96
  def attempt_create_failed(channel_delivery:, error:)
66
97
  emit(
67
98
  :error,
@@ -72,6 +103,16 @@ module CommandTower
72
103
  )
73
104
  end
74
105
 
106
+ def attempt_finalize_unpersisted(channel_delivery:, delivery_attempt:, error_class:)
107
+ emit(
108
+ :error,
109
+ "messaging.execution.attempt.finalize_unpersisted",
110
+ channel_delivery:,
111
+ delivery_attempt_id: delivery_attempt.id,
112
+ error_class:,
113
+ )
114
+ end
115
+
75
116
  def render_started(channel_delivery:, delivery_attempt:)
76
117
  emit_render(
77
118
  :info,
@@ -110,32 +151,35 @@ module CommandTower
110
151
  )
111
152
  end
112
153
 
113
- def adapter_accepted(channel_delivery:, delivery_attempt:)
154
+ def adapter_accepted(channel_delivery:, delivery_attempt:, provider_metadata: nil)
114
155
  emit_adapter(
115
156
  :info,
116
157
  "messaging.execution.adapter.accepted",
117
158
  channel_delivery:,
118
159
  delivery_attempt:,
160
+ **provider_metadata_counts(provider_metadata),
119
161
  )
120
162
  end
121
163
 
122
- def adapter_retryable(channel_delivery:, delivery_attempt:, error_code:)
164
+ def adapter_retryable(channel_delivery:, delivery_attempt:, error_code:, provider_metadata: nil)
123
165
  emit_adapter(
124
166
  :error,
125
167
  "messaging.execution.adapter.retryable",
126
168
  channel_delivery:,
127
169
  delivery_attempt:,
128
170
  error_code:,
171
+ **provider_metadata_counts(provider_metadata),
129
172
  )
130
173
  end
131
174
 
132
- def adapter_terminal(channel_delivery:, delivery_attempt:, error_code:)
175
+ def adapter_terminal(channel_delivery:, delivery_attempt:, error_code:, provider_metadata: nil)
133
176
  emit_adapter(
134
177
  :error,
135
178
  "messaging.execution.adapter.terminal",
136
179
  channel_delivery:,
137
180
  delivery_attempt:,
138
181
  error_code:,
182
+ **provider_metadata_counts(provider_metadata),
139
183
  )
140
184
  end
141
185
 
@@ -178,16 +222,32 @@ module CommandTower
178
222
  )
179
223
  end
180
224
 
181
- def emit_adapter(level, event, channel_delivery:, delivery_attempt:, error_code: nil)
225
+ # extra: optional error_code and provider_metadata counts.
226
+ def emit_adapter(level, event, channel_delivery:, delivery_attempt:, **extra)
182
227
  emit(
183
228
  level,
184
229
  event,
185
230
  channel_delivery:,
186
231
  delivery_attempt_id: delivery_attempt.id,
187
- error_code:,
232
+ error_code: nil,
233
+ **extra,
188
234
  )
189
235
  end
190
236
 
237
+ # Counts only; the per-device record stays on the attempt row.
238
+ def provider_metadata_counts(provider_metadata)
239
+ endpoints = provider_metadata.is_a?(Hash) ? provider_metadata.dig("expo", "endpoints") : nil
240
+ return {} unless endpoints.is_a?(Array)
241
+
242
+ ticket_statuses = endpoints.pluck("ticket_status")
243
+ {
244
+ endpoint_count: endpoints.size,
245
+ ticket_ok_count: ticket_statuses.count("ok"),
246
+ ticket_error_count: ticket_statuses.count { |status| %w[error missing].include?(status) },
247
+ receipt_pending_count: endpoints.count { |endpoint| endpoint["receipt_status"] == "pending" },
248
+ }
249
+ end
250
+
191
251
  def info(event, channel_delivery:)
192
252
  emit(:info, event, channel_delivery:)
193
253
  end