command_tower 0.23.0 → 0.24.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 (74) hide show
  1. checksums.yaml +4 -4
  2. data/app/controllers/command_tower/admin/home_notices_controller.rb +39 -0
  3. data/app/controllers/command_tower/me/home_notices_controller.rb +79 -0
  4. data/app/deserializers/command_tower/deserializers/admin/home_notices/control_deserializer.rb +40 -0
  5. data/app/deserializers/command_tower/deserializers/home_notices/notice_id_deserializer.rb +42 -0
  6. data/app/errors/command_tower/errors/home_notices/linked_message_unavailable_error.rb +23 -0
  7. data/app/errors/command_tower/errors/home_notices/rate_limit_error.rb +25 -0
  8. data/app/errors/command_tower/errors/home_notices/unavailable_error.rb +22 -0
  9. data/app/jobs/command_tower/home_notices/prune_ended_job.rb +14 -0
  10. data/app/models/command_tower/home_notice.rb +41 -0
  11. data/app/models/command_tower/home_notice_control.rb +12 -0
  12. data/app/serializers/command_tower/serializers/home_notices/control_serializer.rb +14 -0
  13. data/app/serializers/command_tower/serializers/home_notices/dismissal_serializer.rb +19 -0
  14. data/app/serializers/command_tower/serializers/home_notices/mutation_serializer.rb +16 -0
  15. data/app/serializers/command_tower/serializers/home_notices/notice_serializer.rb +35 -0
  16. data/app/serializers/command_tower/serializers/home_notices/selection_serializer.rb +21 -0
  17. data/app/services/command_tower/home_notices/campaign.rb +28 -0
  18. data/app/services/command_tower/home_notices/campaigns/update_app.rb +77 -0
  19. data/app/services/command_tower/home_notices/catalog/validator.rb +92 -0
  20. data/app/services/command_tower/home_notices/catalog.rb +92 -0
  21. data/app/services/command_tower/home_notices/context.rb +10 -0
  22. data/app/services/command_tower/home_notices/delivery.rb +43 -0
  23. data/app/services/command_tower/home_notices/notice.rb +88 -0
  24. data/app/services/command_tower/home_notices/notice_record.rb +28 -0
  25. data/app/services/command_tower/messaging/contract/inbox.rb +29 -0
  26. data/app/services/command_tower/messaging/contract/requests/document_for_communication.rb +24 -0
  27. data/app/services/command_tower/messaging/contract/results/inbox_document.rb +17 -0
  28. data/app/services/command_tower/services/auth/purge_user_associated_data.rb +6 -0
  29. data/app/services/command_tower/services/home_notices/acknowledge.rb +149 -0
  30. data/app/services/command_tower/services/home_notices/check_mutation_eligibility.rb +84 -0
  31. data/app/services/command_tower/services/home_notices/check_rate_limit.rb +52 -0
  32. data/app/services/command_tower/services/home_notices/compose.rb +113 -0
  33. data/app/services/command_tower/services/home_notices/deliver.rb +111 -0
  34. data/app/services/command_tower/services/home_notices/dismiss.rb +147 -0
  35. data/app/services/command_tower/services/home_notices/load_candidates.rb +85 -0
  36. data/app/services/command_tower/services/home_notices/pick_notices.rb +139 -0
  37. data/app/services/command_tower/services/home_notices/prune_ended.rb +93 -0
  38. data/app/services/command_tower/services/home_notices/read_controls.rb +31 -0
  39. data/app/services/command_tower/services/home_notices/record_impression.rb +154 -0
  40. data/app/services/command_tower/services/home_notices/resolve_notice.rb +69 -0
  41. data/app/services/command_tower/services/home_notices/select.rb +136 -0
  42. data/app/services/command_tower/services/home_notices/update_control.rb +56 -0
  43. data/app/workflows/command_tower/workflows/admin/home_notices/update_control_workflow.rb +64 -0
  44. data/app/workflows/command_tower/workflows/home_notices/acknowledge_workflow.rb +140 -0
  45. data/app/workflows/command_tower/workflows/home_notices/dismiss_workflow.rb +107 -0
  46. data/app/workflows/command_tower/workflows/home_notices/prune_ended_workflow.rb +25 -0
  47. data/app/workflows/command_tower/workflows/home_notices/record_impression_workflow.rb +92 -0
  48. data/app/workflows/command_tower/workflows/home_notices/show_workflow.rb +44 -0
  49. data/config/routes.rb +9 -0
  50. data/db/migrate/20261124200001_create_command_tower_home_notices.rb +43 -0
  51. data/db/migrate/20261124200002_create_command_tower_home_notice_controls.rb +12 -0
  52. data/docs/api_reference.md +108 -1
  53. data/docs/audit.md +12 -0
  54. data/docs/bootstrap/08-initializer.md +15 -0
  55. data/docs/bootstrap/09-rbac.md +6 -0
  56. data/docs/bootstrap/13-optional.md +12 -0
  57. data/docs/extending.md +2 -0
  58. data/docs/home_notices.md +236 -0
  59. data/docs/messaging_integration_guide.md +4 -0
  60. data/docs/models.md +4 -0
  61. data/docs/principal_capabilities.md +1 -0
  62. data/docs/ui.md +13 -0
  63. data/docs/upgrades/0.24.0.md +50 -0
  64. data/lib/command_tower/authorization/default.yml +10 -0
  65. data/lib/command_tower/configuration/config.rb +6 -0
  66. data/lib/command_tower/configuration/home_notices/config.rb +67 -0
  67. data/lib/command_tower/configuration/registry/audit/config.rb +61 -0
  68. data/lib/command_tower/configuration/registry/principal_capabilities/config.rb +1 -1
  69. data/lib/command_tower/engine.rb +1 -0
  70. data/lib/command_tower/install/baseline.rb +2 -0
  71. data/lib/command_tower/ui/document.rb +26 -5
  72. data/lib/command_tower/version.rb +1 -1
  73. data/lib/tasks/home_notices.rake +11 -0
  74. metadata +53 -2
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module HomeNotices
6
+ # Reads the kill switch for a set of notice keys (design §3.4, doc 03 §6). An absent control
7
+ # row means enabled, so only keys with a row set to `enabled: false` are returned.
8
+ #
9
+ # Success data is `{ disabled_keys: Set<String> }`. A database failure is a failed result
10
+ # (`InternalError`); callers fail closed and show no notices.
11
+ class ReadControls < CommandTower::Services::ApplicationService
12
+ validate :keys, is_a: Array, required: true
13
+
14
+ def call
15
+ context.disabled_keys = disabled_keys
16
+ rescue ActiveRecord::ActiveRecordError => e
17
+ context.fail!(application_error: CommandTower::Errors::InternalError.new(cause: e))
18
+ end
19
+
20
+ private
21
+
22
+ def disabled_keys
23
+ names = keys.map(&:to_s).uniq
24
+ return Set.new if names.empty?
25
+
26
+ CommandTower::HomeNoticeControl.where(key: names, enabled: false).pluck(:key).to_set
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,154 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module HomeNotices
6
+ # Records one impression of a resolved, eligible notice (design D3, D5, D11).
7
+ #
8
+ # Inputs: `user`, `notice_class`, `row` and `period_key` (from `ResolveNotice`; the row is nil
9
+ # for a campaign with no row in the current period yet) and `request_context` (a
10
+ # HomeNotices::Context; `now` is the clock). Eligibility is the caller's job
11
+ # (`CheckMutationEligibility` with `for_impression: true`).
12
+ #
13
+ # Every decision comes from an atomic write, never from a read before it, so concurrent
14
+ # requests record and audit exactly once. All writes and the audit share one transaction:
15
+ # - first impression of a campaign period: `insert!` creates the row. On `RecordNotUnique` a
16
+ # concurrent request created it first, and this one continues as a repeat.
17
+ # - repeat impression: `impression_count + 1` and `last_shown_at` only
18
+ # `WHERE last_shown_at IS NULL OR last_shown_at <= now - 60 s`. No row changed means a
19
+ # repeat inside the idempotency window: `recorded: false`, no audit.
20
+ # - first impression of an existing row (a delivery, or a campaign row created by another
21
+ # mutation): `first_shown_at` is set only `WHERE first_shown_at IS NULL`.
22
+ # `home_notice_impression` is audited only when the insert created the row or that
23
+ # `first_shown_at` update changed exactly one row.
24
+ #
25
+ # Rails `upsert` is not used: on mysql2 (`FOUND_ROWS`) an insert and an unchanged duplicate
26
+ # both report one affected row, and the adapter has no `RETURNING`, so the upsert cannot say
27
+ # whether it created the row. The created-signal spec records this; this is the D11 fallback.
28
+ #
29
+ # Nothing is written while impersonating or when impersonation is unknown (`impersonating` is
30
+ # not `false`).
31
+ #
32
+ # Success data is `{ recorded:, first_impression:, public_id: }`. `public_id` is nil only for an
33
+ # unrecorded campaign impression with no row.
34
+ class RecordImpression < CommandTower::Services::ApplicationService
35
+ IDEMPOTENCY_WINDOW = 60.seconds
36
+
37
+ validate :user, is_a: User, required: true
38
+ validate :notice_class, is_a: Class, required: true
39
+ validate :row, is_a: [CommandTower::HomeNotice, NilClass], required: false
40
+ validate :period_key, is_a: [String, NilClass], required: false
41
+ validate :request_context, is_a: CommandTower::HomeNotices::Context, required: true
42
+
43
+ def call
44
+ return finish(recorded: false, public_id: row&.public_id) unless writable?
45
+ return not_found if row.nil? && !campaign?
46
+
47
+ transaction { record }
48
+ end
49
+
50
+ private
51
+
52
+ def record
53
+ row ? record_repeat(row.id, row.public_id) : record_campaign
54
+ end
55
+
56
+ def now
57
+ request_context.now
58
+ end
59
+
60
+ def writable?
61
+ request_context.impersonating == false
62
+ end
63
+
64
+ def campaign?
65
+ notice_class < CommandTower::HomeNotices::Campaign
66
+ end
67
+
68
+ def stored_period_key
69
+ CommandTower::HomeNotice.stored_period_key(period_key)
70
+ end
71
+
72
+ # The first impression of the period creates the row; losing the race to a concurrent
73
+ # request falls through to the repeat path on the row it created.
74
+ def record_campaign
75
+ public_id = insert_campaign_row
76
+ return first_impression!(public_id) if public_id
77
+
78
+ id, existing_public_id = campaign_scope.lock.pick(:id, :public_id)
79
+ record_repeat(id, existing_public_id)
80
+ end
81
+
82
+ def campaign_scope
83
+ CommandTower::HomeNotice.where(
84
+ user_id: user.id, campaign_key: notice_class.key, period_key: stored_period_key
85
+ )
86
+ end
87
+
88
+ # The new row's public id, or nil when the row already exists.
89
+ def insert_campaign_row
90
+ attributes = new_campaign_attributes
91
+ CommandTower::HomeNotice.transaction(requires_new: true) do
92
+ CommandTower::HomeNotice.insert!(attributes) # rubocop:disable Rails/SkipsModelValidations
93
+ end
94
+ attributes[:public_id]
95
+ rescue ActiveRecord::RecordNotUnique
96
+ nil
97
+ end
98
+
99
+ def new_campaign_attributes
100
+ {
101
+ public_id: SecureRandom.alphanumeric(32), user_id: user.id, kind: "campaign", key: notice_class.key,
102
+ campaign_key: notice_class.key, period_key: stored_period_key,
103
+ impression_count: 1, first_shown_at: now, last_shown_at: now
104
+ }
105
+ end
106
+
107
+ def record_repeat(id, public_id)
108
+ return finish(recorded: false, public_id:) unless count_impression(id) == 1
109
+ return first_impression!(public_id) if mark_first_shown(id) == 1
110
+
111
+ finish(recorded: true, public_id:)
112
+ end
113
+
114
+ def count_impression(id)
115
+ CommandTower::HomeNotice
116
+ .where(id:)
117
+ .where("last_shown_at IS NULL OR last_shown_at <= ?", now - IDEMPOTENCY_WINDOW)
118
+ .update_all(["impression_count = impression_count + 1, last_shown_at = ?, updated_at = ?", now, now]) # rubocop:disable Rails/SkipsModelValidations
119
+ end
120
+
121
+ def mark_first_shown(id)
122
+ CommandTower::HomeNotice
123
+ .where(id:, first_shown_at: nil)
124
+ .update_all(first_shown_at: now, updated_at: now) # rubocop:disable Rails/SkipsModelValidations
125
+ end
126
+
127
+ def first_impression!(public_id)
128
+ audit(:home_notice_impression, affected_user: user, changes: {}, metadata: audit_metadata(public_id))
129
+ finish(recorded: true, first_impression: true, public_id:)
130
+ end
131
+
132
+ # Ids only (design §3.5).
133
+ def audit_metadata(public_id)
134
+ {
135
+ notice_id: public_id,
136
+ key: notice_class.key,
137
+ kind: campaign? ? "campaign" : "delivery",
138
+ severity: notice_class.severity.to_s
139
+ }
140
+ end
141
+
142
+ def finish(recorded:, public_id:, first_impression: false)
143
+ context.recorded = recorded
144
+ context.first_impression = first_impression
145
+ context.public_id = public_id
146
+ end
147
+
148
+ def not_found
149
+ context.fail!(application_error: CommandTower::Errors::NotFoundError.new)
150
+ end
151
+ end
152
+ end
153
+ end
154
+ end
@@ -0,0 +1,69 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module HomeNotices
6
+ # Finds the notice a mutation (impression, acknowledge, dismiss) names, for one user only
7
+ # (design §3.3 "Ids", §3.4).
8
+ #
9
+ # Inputs: `user`, `notice_id` (a `Deserializers::HomeNotices::NoticeIdDeserializer::Input`) and
10
+ # `request_context` (a HomeNotices::Context; `now` and the user feed a campaign `period_key`).
11
+ #
12
+ # - `public_id`: the user's own row. Another user's row is indistinguishable from a missing one.
13
+ # - `campaign:<key>`: the registered campaign and the user's row for its current period, or a nil
14
+ # row when the period has none yet. An unregistered key, or a `period_key` block that raises,
15
+ # is not found.
16
+ #
17
+ # Success data is `{ notice_class:, row:, period_key: }`. `notice_class` is nil only for a
18
+ # `public_id` row whose key is no longer registered; `CheckMutationEligibility` rejects that.
19
+ # Anything not found fails with `NotFoundError`. Eligibility is not checked here.
20
+ class ResolveNotice < CommandTower::Services::ApplicationService
21
+ validate :user, is_a: User, required: true
22
+ validate :notice_id, is_a: CommandTower::Deserializers::HomeNotices::NoticeIdDeserializer::Input, required: true
23
+ validate :request_context, is_a: CommandTower::HomeNotices::Context, required: true
24
+
25
+ def call
26
+ notice_id.public_id ? resolve_row : resolve_campaign
27
+ end
28
+
29
+ private
30
+
31
+ def resolve_row
32
+ row = CommandTower::HomeNotice.find_by(user_id: user.id, public_id: notice_id.public_id)
33
+ return not_found if row.nil?
34
+
35
+ succeed(CommandTower::HomeNotices::Catalog.find(row.key), row, row.period_key)
36
+ end
37
+
38
+ def resolve_campaign
39
+ klass = CommandTower::HomeNotices::Catalog.campaign(notice_id.campaign_key)
40
+ return not_found if klass.nil?
41
+
42
+ period_key = current_period_key(klass)
43
+ return not_found if period_key.nil?
44
+
45
+ row = CommandTower::HomeNotice.find_by(user_id: user.id, campaign_key: klass.key, period_key:)
46
+ succeed(klass, row, period_key)
47
+ end
48
+
49
+ # The stored period key, "" without a `period_key` block, or nil when the block raises.
50
+ def current_period_key(klass)
51
+ block = klass.period_key
52
+ CommandTower::HomeNotice.stored_period_key(block ? block.call(user:, context: request_context) : "")
53
+ rescue StandardError
54
+ nil
55
+ end
56
+
57
+ def succeed(notice_class, row, period_key)
58
+ context.notice_class = notice_class
59
+ context.row = row
60
+ context.period_key = period_key
61
+ end
62
+
63
+ def not_found
64
+ context.fail!(application_error: CommandTower::Errors::NotFoundError.new)
65
+ end
66
+ end
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module HomeNotices
6
+ # Chooses the home notices for one user and request (design §3.4, doc 03 §7).
7
+ #
8
+ # Inputs: `user` and `request_context` (a HomeNotices::Context). Every time rule uses
9
+ # `request_context.now`.
10
+ #
11
+ # Candidates come from `LoadCandidates` (open deliveries up to the cap, plus every registered
12
+ # campaign with its current-period row). A candidate is dropped when it is:
13
+ # - killed (an absent control row means enabled)
14
+ # - outside its window: the class `window`, and for a row its `starts_at` / `ends_at`
15
+ # (`starts_at` inclusive, `ends_at` exclusive)
16
+ # - acknowledged
17
+ # - dismissed into the future (`dismissed_until > now`)
18
+ # - a campaign at its period impression max, or inside its item cooldown
19
+ # (`last_shown_at + cooldown > now`). Deliveries have no item pacing.
20
+ # The rest are in priority order: highest `priority` first, ties to the oldest row
21
+ # (`created_at`); a campaign with no row counts as newest. `PickNotices` then picks the
22
+ # blocking and dismissible notice (daily cap, global cooldown, `show?`, compose).
23
+ #
24
+ # Success data is `{ candidates:, controls_available:, blocking:, dismissible: }`. Each
25
+ # candidate is a `Candidate(notice_class, record)`, where `record` is a NoticeRecord or nil.
26
+ # `blocking` and `dismissible` are each a `PickNotices::Pick` or nil.
27
+ # `command_tower.home_notices.selected` is published with the user id, the candidate count and
28
+ # the picked keys only. When the controls cannot be read there are no candidates and no picks,
29
+ # `controls_available` is false and `controls_unavailable` is published (user id and error
30
+ # class).
31
+ class Select < CommandTower::Services::ApplicationService
32
+ Candidate = Data.define(:notice_class, :record)
33
+
34
+ validate :user, is_a: User, required: true
35
+ validate :request_context, is_a: CommandTower::HomeNotices::Context, required: true
36
+
37
+ def call
38
+ pairs = LoadCandidates.call(user:, request_context:).data[:pairs]
39
+ disabled_keys = read_disabled_keys(pairs)
40
+ candidates = disabled_keys.nil? ? [] : eligible(pairs, disabled_keys)
41
+
42
+ context.controls_available = !disabled_keys.nil?
43
+ context.candidates = candidates
44
+ pick_notices(candidates)
45
+ end
46
+
47
+ private
48
+
49
+ def pick_notices(candidates)
50
+ picks = PickNotices.call(user:, request_context:, candidates:).data
51
+ context.blocking = picks[:blocking]
52
+ context.dismissible = picks[:dismissible]
53
+ publish_selected(candidates.size, picks)
54
+ end
55
+
56
+ def now
57
+ request_context.now
58
+ end
59
+
60
+ # Set of disabled keys, or nil when the controls cannot be read.
61
+ def read_disabled_keys(pairs)
62
+ result = ReadControls.call(keys: pairs.map { |klass, _row| klass.key })
63
+ return result.data[:disabled_keys] if result.success?
64
+
65
+ error = result.errors.first
66
+ publish("controls_unavailable", user_id: user.id, error_class: (error&.cause || error).class.name,
67
+ log_level: :error)
68
+ nil
69
+ end
70
+
71
+ def eligible(pairs, disabled_keys)
72
+ pairs.each_with_index
73
+ .reject { |(klass, row), _index| dropped?(klass, row, disabled_keys) }
74
+ .sort_by { |(klass, row), index| [-klass.priority, row&.created_at || now, index] }
75
+ .map { |(klass, row), _index| Candidate.new(notice_class: klass, record: snapshot(row)) }
76
+ end
77
+
78
+ def snapshot(row)
79
+ row && CommandTower::HomeNotices::NoticeRecord.from(row)
80
+ end
81
+
82
+ def dropped?(klass, row, disabled_keys)
83
+ return true if disabled_keys.include?(klass.key)
84
+ return true unless inside_class_window?(klass) && open_row?(row)
85
+
86
+ klass < CommandTower::HomeNotices::Campaign && paced_out?(klass, row)
87
+ end
88
+
89
+ def inside_class_window?(klass)
90
+ window = klass.window
91
+ window.nil? || inside?(window.starts_at, window.ends_at)
92
+ end
93
+
94
+ def open_row?(row)
95
+ return true if row.nil?
96
+
97
+ inside?(row.starts_at, row.ends_at) &&
98
+ row.acknowledged_at.nil? &&
99
+ (row.dismissed_until.nil? || row.dismissed_until <= now)
100
+ end
101
+
102
+ def inside?(starts_at, ends_at)
103
+ (starts_at.nil? || starts_at <= now) && (ends_at.nil? || ends_at > now)
104
+ end
105
+
106
+ def paced_out?(klass, row)
107
+ impressions = klass.impressions
108
+ return false if row.nil? || impressions.nil?
109
+
110
+ at_period_max?(impressions, row) || inside_item_cooldown?(impressions, row)
111
+ end
112
+
113
+ def at_period_max?(impressions, row)
114
+ !impressions.max.nil? && row.impression_count >= impressions.max
115
+ end
116
+
117
+ def inside_item_cooldown?(impressions, row)
118
+ return false if impressions.cooldown.nil? || row.last_shown_at.nil?
119
+
120
+ row.last_shown_at + impressions.cooldown > now
121
+ end
122
+
123
+ # Keys and counts only, never document content.
124
+ def publish_selected(candidate_count, picks)
125
+ publish("selected", user_id: user.id, candidate_count:,
126
+ blocking_key: picks[:blocking]&.notice_class&.key,
127
+ dismissible_key: picks[:dismissible]&.notice_class&.key, log_level: :info)
128
+ end
129
+
130
+ def publish(name, **payload)
131
+ CommandTower::Events.publish(category: :home_notices, name:, payload:)
132
+ end
133
+ end
134
+ end
135
+ end
136
+ end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module HomeNotices
6
+ # Sets the kill switch of one notice key (design §3.4, doc 03 §6). A key with no control row is
7
+ # enabled, so the row is created on the first change.
8
+ #
9
+ # Inputs: `key` (String), `enabled` (true or false) and `updated_by_user_id` (the admin).
10
+ # Success data is `{ key:, enabled:, previous_enabled:, changed: }`. `changed` is true only when
11
+ # this request changed the effective state: setting a key to the state it already has is an
12
+ # idempotent success with `changed: false`, and the caller audits only a change.
13
+ #
14
+ # The row is locked while it is read and written, so concurrent requests see each other's
15
+ # change. When two requests race to create the first row, the loser retries as an update.
16
+ # A database failure is a failed result (`InternalError`).
17
+ class UpdateControl < CommandTower::Services::ApplicationService
18
+ validate :key, is_a: String, required: true
19
+ validate :enabled, is_a: [TrueClass, FalseClass], required: true
20
+ validate :updated_by_user_id, is_a: [Integer, NilClass], required: false
21
+
22
+ def call
23
+ finish(transaction { apply })
24
+ rescue ActiveRecord::ActiveRecordError => e
25
+ context.fail!(application_error: CommandTower::Errors::InternalError.new(cause: e))
26
+ end
27
+
28
+ private
29
+
30
+ def finish(outcome)
31
+ context.key = key
32
+ context.enabled = enabled
33
+ context.previous_enabled = outcome[:previous_enabled]
34
+ context.changed = outcome[:previous_enabled] != enabled
35
+ end
36
+
37
+ def apply
38
+ control = CommandTower::HomeNoticeControl.lock.find_by(key:) || create_control
39
+ previous = control.enabled
40
+ control.update!(enabled:, updated_by_user_id:) if previous != enabled
41
+ { previous_enabled: previous }
42
+ end
43
+
44
+ # A new row starts enabled (the absent-row default). A concurrent request may create the
45
+ # row first; this one then locks and updates it.
46
+ def create_control
47
+ CommandTower::HomeNoticeControl.transaction(requires_new: true) do
48
+ CommandTower::HomeNoticeControl.create!(key:, enabled: true)
49
+ end
50
+ rescue ActiveRecord::RecordNotUnique
51
+ CommandTower::HomeNoticeControl.lock.find(key)
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Workflows
5
+ module Admin
6
+ module HomeNotices
7
+ # `PATCH /admin/home-notices/:key`: switches one registered notice key on or off (the kill
8
+ # switch the delivery read path honours).
9
+ #
10
+ # Authorization and the impersonation refusal belong to the controller. An unregistered key is
11
+ # a 404 and writes nothing. The write and its audit share one transaction: the audit
12
+ # `home_notice_control_changed` (admin attribution, `changes: { enabled: { from, to } }`,
13
+ # metadata `key`) is emitted only when this request changed the effective state; setting a
14
+ # key to the state it already has is an idempotent success with no audit. A database failure
15
+ # is 503 `home_notices_unavailable`.
16
+ #
17
+ # Success payload is `{ key:, enabled: }`.
18
+ class UpdateControlWorkflow < CommandTower::Workflows::ApplicationWorkflow
19
+ retry_strategy :none
20
+
21
+ def call(user:, key:, enabled:)
22
+ return not_found unless CommandTower::HomeNotices::Catalog.registered?(key)
23
+
24
+ transaction do
25
+ updated = CommandTower::Services::HomeNotices::UpdateControl.call(
26
+ key:, enabled:, updated_by_user_id: user.id
27
+ )
28
+ fail_transaction!(unavailable) if updated.failure?
29
+
30
+ audit_change(key:, data: updated.data) if updated.data[:changed]
31
+ success(payload: control_payload(key:, enabled: updated.data[:enabled]), http_status: :ok)
32
+ end
33
+ end
34
+
35
+ private
36
+
37
+ def control_payload(key:, enabled:)
38
+ CommandTower::Serializers::HomeNotices::ControlSerializer.serialize(key:, enabled:)
39
+ end
40
+
41
+ def audit_change(key:, data:)
42
+ audit(
43
+ :home_notice_control_changed,
44
+ changes: { enabled: { from: data[:previous_enabled], to: data[:enabled] } },
45
+ metadata: { key: },
46
+ attribution_mode: :admin_direct
47
+ )
48
+ end
49
+
50
+ def not_found
51
+ failure(errors: [CommandTower::Errors::NotFoundError.new], http_status: :not_found)
52
+ end
53
+
54
+ def unavailable
55
+ failure(
56
+ errors: [CommandTower::Errors::HomeNotices::UnavailableError.new],
57
+ http_status: :service_unavailable
58
+ )
59
+ end
60
+ end
61
+ end
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,140 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Workflows
5
+ module HomeNotices
6
+ # `POST /me/home-notices/:id/acknowledge`: rate limit, refuse impersonation, resolve, re-check
7
+ # eligibility, acknowledge.
8
+ #
9
+ # Authorization sequence: the controller authorizes the `me_home_notices` entity before this
10
+ # runs. While impersonating (or when that is unknown) the answer is 403 and nothing is written.
11
+ # The notice is found for `user` only, so a foreign row is a 404, as is a notice that is killed
12
+ # or outside its window. `show?` is never run: a user who saw a notice can always clear it. An
13
+ # unreadable kill switch or a database failure is 503 `home_notices_unavailable`. The shared
14
+ # mutation rate limit fails open when Redis is unavailable.
15
+ #
16
+ # `Services::HomeNotices::Acknowledge` owns the transaction (conditional update plus audit).
17
+ # `after_commit` runs once that transaction has committed; it is the seam for best-effort work
18
+ # that must not roll the acknowledgement back.
19
+ class AcknowledgeWorkflow < CommandTower::Workflows::ApplicationWorkflow
20
+ retry_strategy :none
21
+
22
+ def call(user:, notice_id:, impersonating:, app_version: nil, platform: nil)
23
+ limited = CommandTower::Services::HomeNotices::CheckRateLimit.call(user:, bucket: :mutation)
24
+ return failure(errors: limited.errors, http_status: :too_many_requests) if limited.failure?
25
+ return forbidden unless impersonating == false
26
+
27
+ request_context = build_context(impersonating:, app_version:, platform:)
28
+ resolved = CommandTower::Services::HomeNotices::ResolveNotice.call(user:, notice_id:, request_context:)
29
+ return rejected(resolved, user:) if resolved.failure?
30
+
31
+ eligible = check_eligibility(resolved:, request_context:)
32
+ return rejected(eligible, user:) if eligible.failure?
33
+
34
+ acknowledge(user:, resolved:, request_context:)
35
+ end
36
+
37
+ private
38
+
39
+ def check_eligibility(resolved:, request_context:)
40
+ CommandTower::Services::HomeNotices::CheckMutationEligibility.call(
41
+ notice_class: resolved.data[:notice_class], row: resolved.data[:row], request_context:
42
+ )
43
+ end
44
+
45
+ def build_context(impersonating:, app_version:, platform:)
46
+ CommandTower::HomeNotices::Context.new(
47
+ now: Time.current, time_zone: CommandTower::Current.client_time_zone, app_version:, platform:,
48
+ ui_catalog: CommandTower::Current.ui_catalog,
49
+ client_compatibility: CommandTower::Current.client_compatibility_recommendation, impersonating:
50
+ )
51
+ end
52
+
53
+ def acknowledge(user:, resolved:, request_context:)
54
+ acknowledged = CommandTower::Services::HomeNotices::Acknowledge.call(
55
+ user:, request_context:, **resolved.data.slice(:notice_class, :row, :period_key)
56
+ )
57
+ return rejected(acknowledged, user:) if acknowledged.failure?
58
+
59
+ after_commit(user:, notice_class: resolved.data[:notice_class], row: resolved.data[:row],
60
+ data: acknowledged.data)
61
+ respond(acknowledged.data[:recorded])
62
+ rescue ActiveRecord::ActiveRecordError => e
63
+ log_server_error(user:, error: e)
64
+ unavailable
65
+ end
66
+
67
+ # Runs after the acknowledge transaction committed, for the first acknowledgement and for an
68
+ # idempotent repeat alike. Logs ids only; further best-effort work hangs here.
69
+ def after_commit(user:, notice_class:, row:, data:)
70
+ CommandTower::Events.publish(
71
+ category: :home_notices, name: "acknowledged",
72
+ payload: { user_id: user.id, notice_key: notice_class.key, notice_id: data[:public_id],
73
+ recorded: data[:recorded] }
74
+ )
75
+ mark_linked_item_viewed(user:, notice_class:, row:)
76
+ end
77
+
78
+ # A linked delivery marks its inbox item viewed. Best effort: a failure is logged (ids and the
79
+ # error class only) and never fails the acknowledgement, which has already committed.
80
+ def mark_linked_item_viewed(user:, notice_class:, row:)
81
+ return unless notice_class < CommandTower::HomeNotices::Delivery && notice_class.composer == :message
82
+ return if row&.communication_id.nil?
83
+
84
+ CommandTower::Messaging::Contract::Inbox.mark_viewed_for_communication(
85
+ CommandTower::Messaging::Contract::Requests::MarkViewedForCommunication.build(
86
+ communication_id: row.communication_id, recipient_id: user.id
87
+ )
88
+ )
89
+ rescue StandardError => e
90
+ log_mark_failure(user:, notice_class:, row:, error: e)
91
+ end
92
+
93
+ def log_mark_failure(user:, notice_class:, row:, error:)
94
+ CommandTower::Events.publish(
95
+ category: :home_notices, name: "linked_mark_failed",
96
+ payload: { user_id: user.id, notice_key: notice_class.key, notice_id: row&.public_id,
97
+ error_class: error.class.name, log_level: :warn }
98
+ )
99
+ end
100
+
101
+ # Ids and the error class only: the message can carry SQL.
102
+ def log_server_error(user:, error:)
103
+ CommandTower::Events.publish(
104
+ category: :home_notices, name: "ack_server_error",
105
+ payload: { user_id: user.id, error_class: error.class.name }
106
+ )
107
+ end
108
+
109
+ def respond(recorded)
110
+ success(
111
+ payload: CommandTower::Serializers::HomeNotices::MutationSerializer.serialize(recorded:),
112
+ http_status: :ok
113
+ )
114
+ end
115
+
116
+ # A not-found result stays 404; any other failure (controls unreadable) is 503.
117
+ def rejected(result, user:)
118
+ return forbidden if result.errors.first.is_a?(CommandTower::Errors::ForbiddenError)
119
+
120
+ unless result.errors.first.is_a?(CommandTower::Errors::NotFoundError)
121
+ log_server_error(user:, error: result.errors.first)
122
+ return unavailable
123
+ end
124
+
125
+ failure(errors: result.errors, http_status: :not_found)
126
+ end
127
+
128
+ def forbidden
129
+ failure(errors: [CommandTower::Errors::ForbiddenError.new], http_status: :forbidden)
130
+ end
131
+
132
+ def unavailable
133
+ failure(
134
+ errors: [CommandTower::Errors::HomeNotices::UnavailableError.new], http_status: :service_unavailable
135
+ )
136
+ end
137
+ end
138
+ end
139
+ end
140
+ end