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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 8b75ad05bfb533351f79dcf7c242e201a225d86cedd0a3f97358a01e91cbb830
4
- data.tar.gz: e5e89fe1645e781155862a124f37c625ad0804593959d118d5e8f2c523d629a2
3
+ metadata.gz: 8bf05b7d610367efda3b4dce6349bfbd002891563a5f16a5688bbd2660717896
4
+ data.tar.gz: 5a31b97e28d791fbda2ad4899c121fe54c2f96e944c387c716d5541d7449c8f6
5
5
  SHA512:
6
- metadata.gz: fdbc47eafe86db87598541f3c4cbf86a4b23876e321eb137bef5f2a5d9e9b04f2adfb2d38c822b1980bfd150384443717eab03980442975aa93318fb909e2473
7
- data.tar.gz: d374ca61c7fef265974aa71ed8c9bee9c98401efb6328cc240b5685997c8fbf9c1e00928fd2bf2bdd0879e7a013acb0a46200a14133307df57b66da0a44ec391
6
+ metadata.gz: 6c1a8b5cf203cb35b4697f593324b94eb1a0e0a7c4d4b171c752b669a700862679a28cbbe494b54a632294181fa6ddf7d78aa117cf5a71e1deb7e9fc036b122e
7
+ data.tar.gz: 5232cb631564969ef269b82fd1b9c38ef820ee76523640a09b2846b380348b64e5c4dc62288b0a391edde0586b4e3d28559d26614788d26e7ba26ab8a96c7bd0
@@ -8,7 +8,7 @@ module CommandTower
8
8
  Input = Data.define(:notification_type_key, :preference_state)
9
9
 
10
10
  ROUTING_KEYS = %w[controller action format notification_type_key preference].freeze
11
- ALLOWED_PREFERENCE_KEYS = %w[inboxEnabled channels].freeze
11
+ ALLOWED_PREFERENCE_KEYS = %w[inboxEnabled channels urgency sound].freeze
12
12
 
13
13
  def call(params)
14
14
  raw = normalize_hash(params)
@@ -88,6 +88,15 @@ module CommandTower
88
88
  state["inbox"] = inbox
89
89
  end
90
90
 
91
+ %w[urgency sound].each do |field|
92
+ next unless preferences.key?(field)
93
+
94
+ value = preferences[field]
95
+ return failure(errors: { message: "invalid_#{field}" }) unless value.is_a?(String) && !value.strip.empty?
96
+
97
+ state[field] = value.strip
98
+ end
99
+
91
100
  state
92
101
  end
93
102
  end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Errors
5
+ module Account
6
+ class PushTestDestinationError < CommandTower::Errors::ApplicationError
7
+ def code
8
+ "push_test_destination_unresolved"
9
+ end
10
+
11
+ def message
12
+ "Push test destination is not configured"
13
+ end
14
+
15
+ def log_level
16
+ :warn
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -21,6 +21,11 @@ module CommandTower
21
21
  class_name: "CommandTower::Messaging::ChannelDelivery",
22
22
  inverse_of: :delivery_attempts
23
23
 
24
+ # MariaDB reports JSON columns as LONGTEXT. The text caster would write
25
+ # a Ruby hash string and fail `json_valid`. Forcing the JSON caster
26
+ # writes one JSON document on MySQL and on MariaDB.
27
+ attribute :provider_metadata, :json
28
+
24
29
  validates :status, presence: true, inclusion: { in: STATUSES }
25
30
  validates :started_at, presence: true
26
31
  end
@@ -35,6 +35,12 @@ module CommandTower
35
35
  deleted_at.present?
36
36
  end
37
37
 
38
+ # NPB-5. Archived rows still open the inbox. Deleted rows do not.
39
+ # ChannelRenderer and the Expo adapter both use this predicate.
40
+ def live_for_push?
41
+ !deleted?
42
+ end
43
+
38
44
  def unread?
39
45
  !viewed? && !archived? && !deleted?
40
46
  end
@@ -73,7 +73,7 @@ module CommandTower
73
73
 
74
74
  class UnreadCountSerializer
75
75
  def self.serialize(payload)
76
- { count: payload.fetch(:count) }
76
+ { count: payload.fetch(:count), badgeCount: payload.fetch(:badge_count) }
77
77
  end
78
78
  end
79
79
 
@@ -16,6 +16,8 @@ module CommandTower
16
16
  inboxAvailable: notification.inbox_available,
17
17
  allowedChannels: notification.allowed_channels,
18
18
  availableChannels: notification.available_channels,
19
+ urgency: notification.urgency,
20
+ sound: notification.sound,
19
21
  preferences: {
20
22
  inboxEnabled: notification.inbox_enabled,
21
23
  channels: notification.channels,
@@ -8,6 +8,10 @@ module CommandTower
8
8
  MAX_ATTEMPTS = 5
9
9
  GRACE_WINDOW = 1.minute
10
10
 
11
+ PUSH_RETRY_LIMIT = 2
12
+ SUBMISSION_NOT_SUBMITTED = "not_submitted"
13
+ SUBMISSION_UNCERTAIN = "submission_uncertain"
14
+
11
15
  class << self
12
16
  def retries_exhausted?(delivery)
13
17
  delivery.status == ChannelDelivery::STATUS_FAILED_RETRYABLE &&
@@ -24,6 +28,99 @@ module CommandTower
24
28
 
25
29
  delivery.updated_at + GRACE_WINDOW
26
30
  end
31
+
32
+ def push_channel?(delivery)
33
+ delivery.channel_key == "push"
34
+ end
35
+
36
+ def max_execution_attempts_for(delivery)
37
+ push_channel?(delivery) ? PUSH_RETRY_LIMIT : MAX_ATTEMPTS
38
+ end
39
+
40
+ def confirmed_not_submitted?(attempt)
41
+ attempt.provider_metadata.is_a?(Hash) &&
42
+ attempt.provider_metadata["submission"] == SUBMISSION_NOT_SUBMITTED
43
+ end
44
+
45
+ def accepted_ticket_in_attempt?(attempt)
46
+ return true if attempt.status == Messaging::DeliveryAttempt::STATUS_SUCCEEDED
47
+
48
+ metadata = attempt.provider_metadata
49
+ return false unless metadata.is_a?(Hash)
50
+
51
+ endpoints = metadata.dig("expo", "endpoints")
52
+ return false unless endpoints.is_a?(Array)
53
+
54
+ endpoints.any? { |entry| entry["ticket_status"] == "ok" }
55
+ end
56
+
57
+ def push_has_open_started_attempt?(delivery)
58
+ delivery.delivery_attempts
59
+ .where(status: Messaging::DeliveryAttempt::STATUS_STARTED, finished_at: nil)
60
+ .exists?
61
+ end
62
+
63
+ def latest_finished_attempt(delivery)
64
+ delivery.delivery_attempts
65
+ .where.not(finished_at: nil)
66
+ .order(id: :desc)
67
+ .first
68
+ end
69
+
70
+ # Persisted proof only — not tied to channel delivery status.
71
+ def push_has_not_submitted_evidence?(delivery)
72
+ attempt = latest_finished_attempt(delivery)
73
+ attempt.present? && confirmed_not_submitted?(attempt)
74
+ end
75
+
76
+ def push_retry_budget_remaining?(delivery)
77
+ delivery.execution_attempt_count < PUSH_RETRY_LIMIT
78
+ end
79
+
80
+ # recover_failed! — delivery is failed_retryable.
81
+ def push_redrive_eligible_from_failed_retryable?(delivery)
82
+ return false unless push_channel?(delivery)
83
+ return false unless delivery.status == ChannelDelivery::STATUS_FAILED_RETRYABLE
84
+ return false if push_has_open_started_attempt?(delivery)
85
+ return false unless push_has_not_submitted_evidence?(delivery)
86
+
87
+ push_retry_budget_remaining?(delivery)
88
+ end
89
+
90
+ # recover_queued! / recover_stale_executing! — delivery may already be queued.
91
+ def push_redrive_eligible_while_queued?(delivery)
92
+ return true unless push_channel?(delivery)
93
+ return false if push_has_open_started_attempt?(delivery)
94
+ return true if delivery.delivery_attempts.none?
95
+
96
+ push_has_not_submitted_evidence?(delivery) && push_retry_budget_remaining?(delivery)
97
+ end
98
+
99
+ # DeliverWorkflow — may this execution call Expo?
100
+ def push_may_submit_to_provider?(delivery, current_attempt_id:)
101
+ return true unless push_channel?(delivery)
102
+
103
+ prior_attempts = delivery.delivery_attempts.where.not(id: current_attempt_id)
104
+ return false if prior_attempts
105
+ .where(status: Messaging::DeliveryAttempt::STATUS_STARTED, finished_at: nil)
106
+ .exists?
107
+
108
+ finished = prior_attempts.where.not(finished_at: nil)
109
+ return true if finished.none?
110
+
111
+ return false if finished.any? { |attempt| accepted_ticket_in_attempt?(attempt) }
112
+
113
+ return false if finished.any? do |attempt|
114
+ attempt.error_code == SUBMISSION_UNCERTAIN ||
115
+ (
116
+ attempt.status == Messaging::DeliveryAttempt::STATUS_FAILED_TERMINAL &&
117
+ !confirmed_not_submitted?(attempt)
118
+ )
119
+ end
120
+
121
+ latest = finished.order(:id).last
122
+ confirmed_not_submitted?(latest) && delivery.execution_attempt_count <= PUSH_RETRY_LIMIT
123
+ end
27
124
  end
28
125
  end
29
126
  end
@@ -8,6 +8,7 @@ module CommandTower
8
8
  :normalized_provider_status,
9
9
  :provider_message_id,
10
10
  :error_code,
11
+ :provider_metadata,
11
12
  ) do
12
13
  OUTCOMES = %i[success retryable_failure terminal_failure].freeze
13
14
 
@@ -15,7 +16,8 @@ module CommandTower
15
16
  outcome:,
16
17
  normalized_provider_status: nil,
17
18
  provider_message_id: nil,
18
- error_code: nil
19
+ error_code: nil,
20
+ provider_metadata: nil
19
21
  )
20
22
  raise InvalidAdapterContractError, "arbitrary hashes are not accepted as outcome" if outcome.is_a?(Hash)
21
23
  raise InvalidAdapterContractError, "raw exception objects are not accepted" if exception_like?(outcome) ||
@@ -28,12 +30,14 @@ module CommandTower
28
30
  validate_optional_string!(normalized_provider_status, "normalized_provider_status")
29
31
  validate_optional_string!(provider_message_id, "provider_message_id")
30
32
  validate_optional_string!(error_code, "error_code")
33
+ validate_optional_hash!(provider_metadata, "provider_metadata")
31
34
 
32
35
  new(
33
36
  outcome: normalized_outcome,
34
37
  normalized_provider_status:,
35
38
  provider_message_id:,
36
39
  error_code:,
40
+ provider_metadata:,
37
41
  ).freeze
38
42
  end
39
43
 
@@ -53,6 +57,12 @@ module CommandTower
53
57
  end
54
58
  private_class_method :validate_optional_string!
55
59
 
60
+ def self.validate_optional_hash!(value, field_name)
61
+ return if value.nil?
62
+ raise InvalidAdapterContractError, "#{field_name} must be a Hash" unless value.is_a?(Hash)
63
+ end
64
+ private_class_method :validate_optional_hash!
65
+
56
66
  def self.exception_like?(value)
57
67
  value.is_a?(Exception)
58
68
  end
@@ -17,6 +17,7 @@ module CommandTower
17
17
  :receipt,
18
18
  :outcome,
19
19
  :error_code,
20
+ :submitted,
20
21
  keyword_init: true,
21
22
  )
22
23
 
@@ -29,6 +30,7 @@ module CommandTower
29
30
  def call(request:)
30
31
  raise ArgumentError, "request must be an AdapterRequest" unless request.is_a?(AdapterRequest)
31
32
 
33
+ attempts = nil
32
34
  rendered = request.rendered
33
35
  unless rendered.is_a?(Rendering::RenderedPushPayload)
34
36
  return AdapterResult.build(outcome: :terminal_failure, error_code: "render_failed")
@@ -43,25 +45,40 @@ module CommandTower
43
45
  return AdapterResult.build(outcome: :terminal_failure, error_code: "recipient_missing")
44
46
  end
45
47
 
46
- delivery = Messaging::ChannelDelivery.includes(:communication).find_by(id: request.channel_delivery_id)
48
+ delivery = Messaging::ChannelDelivery.includes(communication: :inbox_item).find_by(id: request.channel_delivery_id)
47
49
  owner_user_id = delivery&.communication&.user_id
48
50
  if owner_user_id.nil?
49
51
  return AdapterResult.build(outcome: :terminal_failure, error_code: "recipient_missing")
50
52
  end
51
53
 
52
- attempts = build_endpoint_attempts(owner_user_id:, endpoint_ids:)
54
+ history = EndpointTicketHistory.call(
55
+ channel_delivery_id: delivery.id,
56
+ excluding_attempt_id: request.attempt_id,
57
+ )
58
+ unsettled_ids = endpoint_ids - history.settled_endpoint_ids
59
+ return settled_only_result(history) if unsettled_ids.empty?
60
+
61
+ attempts = build_endpoint_attempts(owner_user_id:, endpoint_ids: unsettled_ids)
53
62
  return attempts if attempts.is_a?(AdapterResult)
54
63
 
55
64
  case @configuration.adapter_name
56
65
  when "fake", "log"
57
66
  AdapterResult.build(outcome: :success, normalized_provider_status: "accepted")
58
67
  when "http"
59
- deliver_http(attempts:, rendered:, owner_user_id:)
68
+ deliver_http(
69
+ attempts:,
70
+ rendered:,
71
+ owner_user_id:,
72
+ history:,
73
+ communication: delivery.communication,
74
+ )
60
75
  else
61
76
  AdapterResult.build(outcome: :terminal_failure, error_code: "adapter_unconfigured")
62
77
  end
78
+ rescue HttpClient::RequestNotSubmitted
79
+ not_submitted_result(attempts, history:)
63
80
  rescue StandardError
64
- AdapterResult.build(outcome: :retryable_failure, error_code: "expo_transient")
81
+ uncertain_terminal_result(attempts, history:)
65
82
  end
66
83
 
67
84
  private
@@ -86,13 +103,14 @@ module CommandTower
86
103
  attempts
87
104
  end
88
105
 
89
- def deliver_http(attempts:, rendered:, owner_user_id:)
106
+ def deliver_http(attempts:, rendered:, owner_user_id:, history:, communication:)
90
107
  sendable = attempts.select { |attempt| attempt.token.present? && attempt.outcome.nil? }
91
- messages = sendable.map { |attempt| expo_message(token: attempt.token, rendered:) }
108
+ messages = sendable.map { |attempt| expo_message(token: attempt.token, rendered:, communication:) }
92
109
 
93
110
  send_result = @http_client.send_messages(messages)
111
+ sendable.each { |attempt| attempt.submitted = true }
94
112
  unless send_result[:ok]
95
- return map_http_failure(send_result[:status_code])
113
+ return map_http_failure(send_result[:status_code], attempts:, history:)
96
114
  end
97
115
 
98
116
  tickets = Array(send_result[:tickets])
@@ -104,7 +122,7 @@ module CommandTower
104
122
 
105
123
  ok_ticket_ids = sendable.filter_map { |attempt| attempt.ticket&.dig(:id) if attempt.ticket&.dig(:status) == "ok" }
106
124
  if ok_ticket_ids.any?
107
- receipts_result = @http_client.get_receipts(ok_ticket_ids)
125
+ receipts_result = fetch_receipts(ok_ticket_ids)
108
126
  if receipts_result[:ok]
109
127
  receipts = receipts_result[:receipts] || {}
110
128
  sendable.each do |attempt|
@@ -124,27 +142,63 @@ module CommandTower
124
142
  mark_invalid_if_needed!(owner_user_id:, attempt:)
125
143
  end
126
144
 
127
- aggregate_result(attempts)
145
+ aggregate_result(attempts, history:)
146
+ end
147
+
148
+ def fetch_receipts(ticket_ids)
149
+ @http_client.get_receipts(ticket_ids)
150
+ rescue StandardError
151
+ { ok: false, status_code: nil, receipts: {} }
152
+ end
153
+
154
+ # Every eligible endpoint already holds an accepted ticket or a recorded terminal
155
+ # ticket error from an earlier attempt, so there is nothing to send.
156
+ def settled_only_result(history)
157
+ if history.accepted?
158
+ return AdapterResult.build(
159
+ outcome: :success,
160
+ normalized_provider_status: "accepted",
161
+ provider_message_id: history.first_accepted_ticket_id,
162
+ )
163
+ end
164
+
165
+ AdapterResult.build(
166
+ outcome: :terminal_failure,
167
+ error_code: history.first_terminal_error_code || "expo_rejected",
168
+ )
128
169
  end
129
170
 
130
- def expo_message(token:, rendered:)
171
+ def expo_message(token:, rendered:, communication:)
131
172
  message = {
132
173
  "to" => token,
133
174
  "title" => rendered.title,
134
175
  "body" => rendered.body,
135
- "sound" => "default",
176
+ "sound" => rendered.sound || "default",
136
177
  }
137
- if rendered.deep_link.present?
138
- message["data"] = { "deepLink" => rendered.deep_link }
178
+ interruption_level = InterruptionLevel.call(
179
+ urgency: rendered.urgency,
180
+ supported: @configuration.supported_interruption_levels,
181
+ )
182
+ message["interruptionLevel"] = interruption_level if interruption_level
183
+ message["threadId"] = rendered.thread_id if rendered.thread_id
184
+ # nil omits the field. 0 is a real count and must be sent. In Ruby, 0 is truthy.
185
+ message["badge"] = rendered.badge unless rendered.badge.nil?
186
+ data = {}
187
+ data["deepLink"] = rendered.deep_link if rendered.deep_link.present?
188
+ item = communication&.inbox_item
189
+ if item&.live_for_push?
190
+ data["inboxItemId"] = item.id.to_s
191
+ data["inboxEntryId"] = communication.conversation_key.presence || item.id.to_s
139
192
  end
193
+ message["data"] = data if data.any?
140
194
  message
141
195
  end
142
196
 
143
197
  def apply_ticket_outcome!(attempt)
144
198
  ticket = attempt.ticket
145
199
  if ticket.nil?
146
- attempt.outcome = :retryable_failure
147
- attempt.error_code = "expo_transient"
200
+ attempt.outcome = :terminal_failure
201
+ attempt.error_code = submission_uncertain_code
148
202
  return
149
203
  end
150
204
 
@@ -160,8 +214,8 @@ module CommandTower
160
214
  attempt.error_code = "expo_rejected"
161
215
  end
162
216
  else
163
- attempt.outcome = :retryable_failure
164
- attempt.error_code = "expo_transient"
217
+ attempt.outcome = :terminal_failure
218
+ attempt.error_code = submission_uncertain_code
165
219
  end
166
220
  end
167
221
 
@@ -195,31 +249,146 @@ module CommandTower
195
249
  nil
196
250
  end
197
251
 
198
- def map_http_failure(status_code)
199
- if status_code.to_i >= 500 || status_code.to_i == 429
200
- AdapterResult.build(outcome: :retryable_failure, error_code: "expo_transient")
201
- else
202
- AdapterResult.build(outcome: :terminal_failure, error_code: "expo_rejected")
203
- end
252
+ # After the HTTP client returns, a non-success response is uncertain for duplicate policy
253
+ # (request may have been accepted). Terminal rejection (4xx except 429) maps to expo_rejected.
254
+ def map_http_failure(status_code, attempts:, history:)
255
+ code = status_code.to_i
256
+ error_code =
257
+ if code >= 500 || code == 429
258
+ submission_uncertain_code
259
+ else
260
+ "expo_rejected"
261
+ end
262
+ attempts.each { |attempt| attempt.error_code ||= error_code if attempt.submitted }
263
+ carried = error_code == submission_uncertain_code ? [] : carried_accepted_entries(history)
264
+
265
+ AdapterResult.build(
266
+ outcome: :terminal_failure,
267
+ error_code:,
268
+ provider_metadata: provider_metadata_for(attempts, carried:),
269
+ )
204
270
  end
205
271
 
206
- def aggregate_result(attempts)
272
+ # Delivery-wide aggregation: this attempt's endpoints plus tickets recorded earlier.
273
+ def aggregate_result(attempts, history:)
274
+ submitted = attempts.select(&:submitted)
207
275
  successes = attempts.select { |attempt| attempt.outcome == :success }
208
- if successes.any?
209
- first_ticket_id = successes.filter_map { |attempt| attempt.ticket&.dig(:id) }.first
276
+ first_ticket_id = successes.filter_map { |attempt| attempt.ticket&.dig(:id) }.first
277
+ metadata = provider_metadata_for(attempts)
278
+
279
+ if submitted.any? { |attempt| attempt.outcome == :success } &&
280
+ submitted.any? do |attempt|
281
+ attempt.outcome == :terminal_failure && attempt.error_code == submission_uncertain_code
282
+ end
283
+ return AdapterResult.build(
284
+ outcome: :terminal_failure,
285
+ error_code: submission_uncertain_code,
286
+ provider_message_id: first_ticket_id,
287
+ provider_metadata: metadata,
288
+ )
289
+ end
290
+
291
+ if attempts.any? { |attempt| attempt.outcome == :retryable_failure }
292
+ return AdapterResult.build(
293
+ outcome: :terminal_failure,
294
+ error_code: submission_uncertain_code,
295
+ provider_message_id: first_ticket_id,
296
+ provider_metadata: metadata,
297
+ )
298
+ end
299
+
300
+ if successes.any? || history.accepted?
210
301
  return AdapterResult.build(
211
302
  outcome: :success,
212
303
  normalized_provider_status: "accepted",
213
- provider_message_id: first_ticket_id,
304
+ provider_message_id: first_ticket_id || history.first_accepted_ticket_id,
305
+ provider_metadata: metadata,
214
306
  )
215
307
  end
216
308
 
217
309
  if attempts.all? { |attempt| attempt.outcome == :terminal_failure }
218
- error_code = attempts.map(&:error_code).compact.first || "expo_rejected"
219
- return AdapterResult.build(outcome: :terminal_failure, error_code:)
310
+ error_code = attempts.filter_map(&:error_code).first ||
311
+ history.first_terminal_error_code ||
312
+ "expo_rejected"
313
+ return AdapterResult.build(outcome: :terminal_failure, error_code:, provider_metadata: metadata)
220
314
  end
221
315
 
222
- AdapterResult.build(outcome: :retryable_failure, error_code: "expo_transient")
316
+ AdapterResult.build(
317
+ outcome: :terminal_failure,
318
+ error_code: submission_uncertain_code,
319
+ provider_metadata: metadata,
320
+ )
321
+ end
322
+
323
+ def not_submitted_result(_attempts, history: nil)
324
+ AdapterResult.build(
325
+ outcome: :retryable_failure,
326
+ error_code: "expo_not_submitted",
327
+ provider_metadata: {
328
+ "submission" => Messaging::DeliveryRetryPolicy::SUBMISSION_NOT_SUBMITTED,
329
+ },
330
+ )
331
+ end
332
+
333
+ def uncertain_terminal_result(attempts, history:)
334
+ metadata = provider_metadata_for(attempts)
335
+ metadata = metadata.merge("submission" => submission_uncertain_code) if metadata.is_a?(Hash)
336
+
337
+ AdapterResult.build(
338
+ outcome: :terminal_failure,
339
+ error_code: submission_uncertain_code,
340
+ provider_metadata: metadata,
341
+ )
342
+ end
343
+
344
+ def submission_uncertain_code
345
+ Messaging::DeliveryRetryPolicy::SUBMISSION_UNCERTAIN
346
+ end
347
+
348
+ def carried_accepted_entries(history)
349
+ history.accepted_ticket_ids.map do |endpoint_id, ticket_id|
350
+ entry = { "endpoint_id" => endpoint_id, "ticket_status" => "ok" }
351
+ entry["ticket_id"] = ticket_id if ticket_id.present?
352
+ entry
353
+ end
354
+ end
355
+
356
+ # Per-device facts as recorded so far. Endpoints never submitted to Expo carry
357
+ # no ticket or receipt status. No tokens, bodies, or exceptions are included.
358
+ def provider_metadata_for(attempts, carried: [])
359
+ return nil unless attempts.is_a?(Array) && attempts.any?(&:submitted)
360
+
361
+ { "expo" => { "endpoints" => attempts.map { |attempt| endpoint_metadata(attempt) } + carried } }
362
+ end
363
+
364
+ def endpoint_metadata(attempt)
365
+ entry = { "endpoint_id" => attempt.endpoint_id }
366
+ if attempt.submitted
367
+ ticket_id = attempt.ticket&.dig(:id)
368
+ entry["ticket_id"] = ticket_id if ticket_id.present?
369
+ entry["ticket_status"] = ticket_status_for(attempt)
370
+ entry["receipt_status"] = receipt_status_for(attempt)
371
+ end
372
+ entry["error_code"] = attempt.error_code if attempt.error_code.present?
373
+ entry
374
+ end
375
+
376
+ def ticket_status_for(attempt)
377
+ case attempt.ticket&.dig(:status)
378
+ when "ok" then "ok"
379
+ when "error" then "error"
380
+ else "missing"
381
+ end
382
+ end
383
+
384
+ def receipt_status_for(attempt)
385
+ return "unchecked" unless ticket_status_for(attempt) == "ok"
386
+
387
+ case attempt.receipt&.dig(:status)
388
+ when "ok" then "ok"
389
+ when "error" then "error"
390
+ else "pending"
391
+ end
223
392
  end
224
393
  end
225
394
  end
@@ -34,6 +34,11 @@ module CommandTower
34
34
  def access_token
35
35
  CommandTower.config.messaging.expo.access_token.to_s.strip
36
36
  end
37
+
38
+ # Urgency levels the host's shipped binary can honor. Normal is always supported.
39
+ def supported_interruption_levels
40
+ (Array(CommandTower.config.messaging.expo.interruption_levels).map(&:to_s) | ["normal"]).freeze
41
+ end
37
42
  end
38
43
  end
39
44
  end