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,113 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+
5
+ module CommandTower
6
+ module Services
7
+ module HomeNotices
8
+ # Builds, validates and redacts the document for one notice (design D6, D13).
9
+ #
10
+ # Inputs: `notice_class` (a Campaign or Delivery subclass), `user`, `request_context` (a
11
+ # HomeNotices::Context) and `record` (a NoticeRecord, or nil for an unmaterialized campaign).
12
+ #
13
+ # Success data is `{ document:, content_hash: }`. `document` is nil, with no hash, when the
14
+ # notice cannot be shown: the client catalog is below 2, or compose or validation failed
15
+ # (the notice is skipped, never raised). A blocking notice is validated with the
16
+ # `:blocking_notice` profile, a dismissible one with the default profile. A blocking failure
17
+ # publishes `command_tower.home_notices.blocking_invalid` (key and error class only).
18
+ #
19
+ # A linked delivery (`composer :message`) takes its document from
20
+ # `Messaging::Contract::Inbox.document_for_communication` instead of `compose`.
21
+ #
22
+ # The hash is an HMAC-SHA256 of the composed, redacted document JSON (D13). Rotating
23
+ # `secret_key_base` makes stored hashes unverifiable.
24
+ class Compose < CommandTower::Services::ApplicationService
25
+ MIN_CATALOG = 2
26
+ HASH_KEY_SALT = "command_tower/home_notices/content_hash"
27
+ HASH_KEY_BYTES = 32
28
+
29
+ validate :notice_class, is_a: Class, required: true
30
+ validate :user, is_a: User, required: true
31
+ validate :request_context, is_a: CommandTower::HomeNotices::Context, required: true
32
+ validate :record, is_a: CommandTower::HomeNotices::NoticeRecord, required: false
33
+
34
+ def call
35
+ document = build_document
36
+ context.document = document
37
+ context.content_hash = document && content_hash(document)
38
+ end
39
+
40
+ private
41
+
42
+ def build_document
43
+ return nil if request_context.ui_catalog.to_i < MIN_CATALOG
44
+
45
+ composed = linked? ? linked_document : compose_valid_document
46
+ return nil if composed.nil?
47
+
48
+ CommandTower::UI::Redaction.call(composed, impersonating: request_context.impersonating)
49
+ rescue StandardError => e
50
+ log_failure(e)
51
+ nil
52
+ end
53
+
54
+ def linked?
55
+ notice_class < CommandTower::HomeNotices::Delivery && notice_class.composer == :message
56
+ end
57
+
58
+ # A linked delivery shows the inbox item's own document, fetched through the Messaging
59
+ # contract (never the host `compose`). Nil when the item is missing, deleted, archived,
60
+ # foreign or undefined: the notice is then not shown.
61
+ def linked_document
62
+ return nil if record&.communication_id.nil?
63
+
64
+ request = CommandTower::Messaging::Contract::Requests::DocumentForCommunication.build(
65
+ communication_id: record.communication_id, recipient_id: user.id,
66
+ impersonating: request_context.impersonating
67
+ )
68
+ result = CommandTower::Messaging::Contract::Inbox.document_for_communication(request)
69
+ result&.document&.validate!(profile:)
70
+ end
71
+
72
+ def compose_valid_document
73
+ root = built_document.validate!(profile:).root
74
+ fallback = CommandTower::UI::TextDerivation.call(root, **derivation_options)
75
+ CommandTower::UI::Document.new(root:, text_fallback: fallback).validate!(profile:)
76
+ end
77
+
78
+ def built_document
79
+ CommandTower::UI.document(text_fallback: "-") do |builder|
80
+ notice_class.new.compose(builder, user:, context: request_context, notice: record)
81
+ end
82
+ end
83
+
84
+ def profile
85
+ notice_class.blocking? ? :blocking_notice : :default
86
+ end
87
+
88
+ def derivation_options
89
+ zone = request_context.time_zone
90
+ zone.present? ? { user_zone: zone } : {}
91
+ end
92
+
93
+ def content_hash(document)
94
+ OpenSSL::HMAC.hexdigest("SHA256", hash_key, document.as_json.to_json)
95
+ end
96
+
97
+ def hash_key
98
+ Rails.application.key_generator.generate_key(HASH_KEY_SALT, HASH_KEY_BYTES)
99
+ end
100
+
101
+ # Keys and error classes only: never document content, spans or hrefs.
102
+ def log_failure(error)
103
+ name = notice_class.blocking? ? "blocking_invalid" : "compose_failed"
104
+ CommandTower::Events.publish(
105
+ category: :home_notices,
106
+ name:,
107
+ payload: { notice_key: notice_class.key.to_s, error_class: error.class.name, log_level: :warn }
108
+ )
109
+ end
110
+ end
111
+ end
112
+ end
113
+ end
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module HomeNotices
6
+ # Pushes one Delivery notice to one user (design D9). Host workflows call it directly after
7
+ # `Produce`.
8
+ #
9
+ # Inputs: `user`, `notice` (a Delivery subclass), `identity` (the caller's stable key for this
10
+ # occurrence), `communication_id` (required for a linked delivery), `starts_at`, `ends_at` and
11
+ # `metadata` (a Hash, ids and small values only).
12
+ #
13
+ # - Idempotent on `(user, identity)`: a repeat returns the existing row and writes nothing.
14
+ # - A linked delivery (`composer :message`) is refused with `LinkedMessageUnavailableError`
15
+ # (`linked_message_unavailable`) when the inbox item is missing, deleted, foreign or
16
+ # undefined. No row is written.
17
+ # - Over `max_open_deliveries` open rows the delivery is ignored and
18
+ # `command_tower.home_notices.delivery_over_cap` is published (key only).
19
+ #
20
+ # Success data is `{ delivered:, public_id: }`. `delivered` is true only when this call wrote
21
+ # the row; `public_id` is nil when the delivery was ignored over the cap.
22
+ class Deliver < CommandTower::Services::ApplicationService
23
+ validate :user, is_a: User, required: true
24
+ validate :notice, is_a: Class, required: true
25
+ validate :identity, is_a: String, required: true
26
+ validate :communication_id, is_a: [Integer, NilClass], required: false
27
+ validate :starts_at, is_a: [Time, ActiveSupport::TimeWithZone, NilClass], required: false
28
+ validate :ends_at, is_a: [Time, ActiveSupport::TimeWithZone, NilClass], required: false
29
+ validate :metadata, is_a: [Hash, NilClass], required: false
30
+
31
+ def call
32
+ return invalid unless delivery_class?
33
+
34
+ existing = existing_row
35
+ return finish(delivered: false, public_id: existing.public_id) if existing
36
+ return unavailable if linked? && !linked_message_available?
37
+ return over_cap if open_count >= CommandTower.config.home_notices.max_open_deliveries
38
+
39
+ create_row
40
+ end
41
+
42
+ private
43
+
44
+ def delivery_class?
45
+ notice < CommandTower::HomeNotices::Delivery
46
+ end
47
+
48
+ def linked?
49
+ notice.composer == :message
50
+ end
51
+
52
+ def scope
53
+ CommandTower::HomeNotice.where(user_id: user.id)
54
+ end
55
+
56
+ def existing_row
57
+ scope.find_by(identity:)
58
+ end
59
+
60
+ def open_count
61
+ scope.where(kind: "delivery", acknowledged_at: nil)
62
+ .where("ends_at IS NULL OR ends_at > ?", Time.current)
63
+ .count
64
+ end
65
+
66
+ def linked_message_available?
67
+ return false if communication_id.nil?
68
+
69
+ request = CommandTower::Messaging::Contract::Requests::DocumentForCommunication.build(
70
+ communication_id:, recipient_id: user.id, impersonating: false
71
+ )
72
+ !CommandTower::Messaging::Contract::Inbox.document_for_communication(request).nil?
73
+ end
74
+
75
+ def create_row
76
+ row = CommandTower::HomeNotice.create!(
77
+ user:, kind: "delivery", key: notice.key, identity:, communication_id:,
78
+ starts_at:, ends_at:, metadata: metadata || {}
79
+ )
80
+ finish(delivered: true, public_id: row.public_id)
81
+ rescue ActiveRecord::RecordNotUnique
82
+ finish(delivered: false, public_id: existing_row&.public_id)
83
+ end
84
+
85
+ def over_cap
86
+ CommandTower::Events.publish(
87
+ category: :home_notices,
88
+ name: "delivery_over_cap",
89
+ payload: { notice_key: notice.key.to_s, log_level: :warn }
90
+ )
91
+ finish(delivered: false, public_id: nil)
92
+ end
93
+
94
+ def finish(delivered:, public_id:)
95
+ context.delivered = delivered
96
+ context.public_id = public_id
97
+ end
98
+
99
+ def invalid
100
+ context.fail!(application_error: CommandTower::Errors::ValidationError.new(
101
+ details: { notice: ["must be a Delivery subclass"] }
102
+ ))
103
+ end
104
+
105
+ def unavailable
106
+ context.fail!(application_error: CommandTower::Errors::HomeNotices::LinkedMessageUnavailableError.new)
107
+ end
108
+ end
109
+ end
110
+ end
111
+ end
@@ -0,0 +1,147 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module HomeNotices
6
+ # Dismisses one resolved dismissible notice for its user (design D3, §3.4).
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`). It never runs `show?`: a user who saw a notice can always clear
12
+ # it.
13
+ #
14
+ # Only a dismissible notice can be dismissed. A blocking notice fails with `ValidationError`
15
+ # and nothing is written. Nothing is written while impersonating or when impersonation is
16
+ # unknown (`impersonating` is not `false`): the result fails with `ForbiddenError`.
17
+ #
18
+ # `dismissed_until` is `now + DISMISSAL_DURATION`. The decision to audit comes from an atomic
19
+ # write, never from a read before it, so concurrent requests dismiss and audit exactly once.
20
+ # The write and the audit share one transaction:
21
+ # - existing row: `dismissed_until` is set only
22
+ # `WHERE dismissed_until IS NULL OR dismissed_until <= now`. Exactly one row changed means
23
+ # this request dismissed it and `home_notice_dismissed` is audited. No row changed means it is
24
+ # already dismissed into the future: an idempotent success with no audit.
25
+ # - campaign with no row: `insert!` creates the row already dismissed. On `RecordNotUnique` a
26
+ # concurrent request created it first, and this one continues as the existing-row case.
27
+ #
28
+ # Success data is `{ dismissed: true, recorded:, public_id:, dismissed_until: }`. `recorded` is
29
+ # true only when this request made the change (and audited it).
30
+ class Dismiss < CommandTower::Services::ApplicationService
31
+ # How long a dismissed notice stays hidden. The notice's window, kill switch and pacing
32
+ # still apply after it lapses.
33
+ DISMISSAL_DURATION = 7.days
34
+
35
+ validate :user, is_a: User, required: true
36
+ validate :notice_class, is_a: Class, required: true
37
+ validate :row, is_a: [CommandTower::HomeNotice, NilClass], required: false
38
+ validate :period_key, is_a: [String, NilClass], required: false
39
+ validate :request_context, is_a: CommandTower::HomeNotices::Context, required: true
40
+
41
+ def call
42
+ return forbidden unless request_context.impersonating == false
43
+ return not_found if row.nil? && !campaign?
44
+ return not_dismissible unless notice_class.dismissible?
45
+
46
+ transaction { dismiss }
47
+ end
48
+
49
+ private
50
+
51
+ def now
52
+ request_context.now
53
+ end
54
+
55
+ def dismissed_until
56
+ now + DISMISSAL_DURATION
57
+ end
58
+
59
+ def campaign?
60
+ notice_class < CommandTower::HomeNotices::Campaign
61
+ end
62
+
63
+ def stored_period_key
64
+ CommandTower::HomeNotice.stored_period_key(period_key)
65
+ end
66
+
67
+ def dismiss
68
+ return dismiss_existing(row.id, row.public_id) if row
69
+
70
+ public_id = insert_campaign_row
71
+ return dismissed!(public_id) if public_id
72
+
73
+ id, existing_public_id = campaign_scope.lock.pick(:id, :public_id)
74
+ dismiss_existing(id, existing_public_id)
75
+ end
76
+
77
+ def campaign_scope
78
+ CommandTower::HomeNotice.where(
79
+ user_id: user.id, campaign_key: notice_class.key, period_key: stored_period_key
80
+ )
81
+ end
82
+
83
+ # The new row's public id, or nil when the row already exists.
84
+ def insert_campaign_row
85
+ attributes = new_campaign_attributes
86
+ CommandTower::HomeNotice.transaction(requires_new: true) do
87
+ CommandTower::HomeNotice.insert!(attributes) # rubocop:disable Rails/SkipsModelValidations
88
+ end
89
+ attributes[:public_id]
90
+ rescue ActiveRecord::RecordNotUnique
91
+ nil
92
+ end
93
+
94
+ def new_campaign_attributes
95
+ {
96
+ public_id: SecureRandom.alphanumeric(32), user_id: user.id, kind: "campaign", key: notice_class.key,
97
+ campaign_key: notice_class.key, period_key: stored_period_key, dismissed_until:
98
+ }
99
+ end
100
+
101
+ def dismiss_existing(id, public_id)
102
+ changed = CommandTower::HomeNotice
103
+ .where(id:)
104
+ .where("dismissed_until IS NULL OR dismissed_until <= ?", now)
105
+ .update_all(dismissed_until:, updated_at: now) # rubocop:disable Rails/SkipsModelValidations
106
+ return dismissed!(public_id) if changed == 1
107
+
108
+ finish(recorded: false, public_id:, until_time: CommandTower::HomeNotice.where(id:).pick(:dismissed_until))
109
+ end
110
+
111
+ def dismissed!(public_id)
112
+ audit(:home_notice_dismissed, affected_user: user, changes: {}, metadata: audit_metadata(public_id))
113
+ finish(recorded: true, public_id:, until_time: dismissed_until)
114
+ end
115
+
116
+ # Ids only (design §3.5).
117
+ def audit_metadata(public_id)
118
+ {
119
+ notice_id: public_id,
120
+ key: notice_class.key,
121
+ kind: campaign? ? "campaign" : "delivery",
122
+ severity: notice_class.severity.to_s
123
+ }
124
+ end
125
+
126
+ def finish(recorded:, public_id:, until_time:)
127
+ context.dismissed = true
128
+ context.recorded = recorded
129
+ context.public_id = public_id
130
+ context.dismissed_until = until_time
131
+ end
132
+
133
+ def forbidden
134
+ context.fail!(application_error: CommandTower::Errors::ForbiddenError.new)
135
+ end
136
+
137
+ def not_found
138
+ context.fail!(application_error: CommandTower::Errors::NotFoundError.new)
139
+ end
140
+
141
+ def not_dismissible
142
+ context.fail!(application_error: CommandTower::Errors::ValidationError.new(details: { notice: "blocking" }))
143
+ end
144
+ end
145
+ end
146
+ end
147
+ end
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module HomeNotices
6
+ # Gathers the unfiltered selection candidates for one user (design §3.4 step 1, doc 03 §7).
7
+ # `Select` applies the drop rules.
8
+ #
9
+ # Inputs: `user` and `request_context` (a HomeNotices::Context; `now` is the clock).
10
+ #
11
+ # Success data is `{ pairs: [[notice_class, row], ...] }`:
12
+ # - the user's open deliveries (unacknowledged, not ended at `now`), oldest first, at most
13
+ # `config.home_notices.max_open_deliveries`, kept only when their key is a registered Delivery
14
+ # - every registered campaign, with its row for the current period, or nil when it has none.
15
+ # A campaign whose `period_key` block raises is skipped and
16
+ # `command_tower.home_notices.period_key_failed` is published (key and error class only).
17
+ class LoadCandidates < CommandTower::Services::ApplicationService
18
+ validate :user, is_a: User, required: true
19
+ validate :request_context, is_a: CommandTower::HomeNotices::Context, required: true
20
+
21
+ def call
22
+ context.pairs = delivery_pairs + campaign_pairs
23
+ end
24
+
25
+ private
26
+
27
+ def now
28
+ request_context.now
29
+ end
30
+
31
+ def delivery_pairs
32
+ open_delivery_rows.filter_map do |row|
33
+ klass = CommandTower::HomeNotices::Catalog.find(row.key)
34
+ [klass, row] if klass && klass < CommandTower::HomeNotices::Delivery
35
+ end
36
+ end
37
+
38
+ def open_delivery_rows
39
+ CommandTower::HomeNotice
40
+ .where(user_id: user.id, kind: "delivery", acknowledged_at: nil)
41
+ .where("ends_at IS NULL OR ends_at > ?", now)
42
+ .order(:created_at, :id)
43
+ .limit(CommandTower.config.home_notices.max_open_deliveries)
44
+ .to_a
45
+ end
46
+
47
+ def campaign_pairs
48
+ period_keys = campaign_classes.each_with_object({}) do |klass, memo|
49
+ period_key = period_key_for(klass)
50
+ memo[klass] = period_key unless period_key.nil?
51
+ end
52
+ rows = campaign_rows(period_keys)
53
+
54
+ period_keys.map { |klass, period_key| [klass, rows[[klass.key, period_key]]] }
55
+ end
56
+
57
+ def campaign_classes
58
+ CommandTower::HomeNotices::Catalog.notices.select { |klass| klass < CommandTower::HomeNotices::Campaign }
59
+ end
60
+
61
+ # The stored period key, "" without a `period_key` block, or nil when the block raises.
62
+ def period_key_for(klass)
63
+ block = klass.period_key
64
+ raw = block ? block.call(user:, context: request_context) : ""
65
+ CommandTower::HomeNotice.stored_period_key(raw)
66
+ rescue StandardError => e
67
+ CommandTower::Events.publish(
68
+ category: :home_notices,
69
+ name: "period_key_failed",
70
+ payload: { notice_key: klass.key.to_s, error_class: e.class.name, log_level: :warn }
71
+ )
72
+ nil
73
+ end
74
+
75
+ def campaign_rows(period_keys)
76
+ return {} if period_keys.empty?
77
+
78
+ CommandTower::HomeNotice
79
+ .where(user_id: user.id, campaign_key: period_keys.keys.map(&:key), period_key: period_keys.values.uniq)
80
+ .index_by { |row| [row.campaign_key, row.period_key] }
81
+ end
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module HomeNotices
6
+ # Picks at most one blocking and one dismissible notice from `Select`'s candidates (design §3.4
7
+ # steps 3 and 4, doc 03 §7 and §8).
8
+ #
9
+ # Inputs: `user`, `request_context` (a HomeNotices::Context; `now` is the clock) and
10
+ # `candidates` (`Select::Candidate`s, already in priority order).
11
+ #
12
+ # Nothing is picked when the client catalog is below 2. Otherwise each severity takes the
13
+ # first candidate that passes its gate, then `show?`, then `Compose` (which applies the
14
+ # `:blocking_notice` or default profile and skips a notice that fails):
15
+ # - blocking gate, the UTC daily cap: a notice already started (`first_shown_at` set) is always
16
+ # re-served until acknowledged; otherwise the user's rows of registered blocking notices
17
+ # first shown in the current UTC day must number below `blocking_daily_cap`. Concurrent
18
+ # requests can each start a different notice before either impression lands, so the cap can
19
+ # be exceeded by one per concurrent request (design D5, accepted).
20
+ # - dismissible gate, the global cooldown: clear when `max(last_shown_at)` over the user's rows
21
+ # of registered dismissible notices, plus `global_cooldown`, is at or before `now`; or, for a
22
+ # delivery, when its `ends_at` is at or before the moment the cooldown clears. Blocking
23
+ # impressions do not start the cooldown.
24
+ #
25
+ # `show?` has a 50 ms budget: an overrun publishes `command_tower.home_notices.show_if_slow`
26
+ # (key and ms) and the answer is still used. An exception means "not shown" and publishes
27
+ # `show_if_failed` (key and error class; error level for blocking keys, warn otherwise).
28
+ #
29
+ # Success data is `{ blocking:, dismissible: }`, each a `Pick(notice_class, record, document,
30
+ # content_hash)` or nil.
31
+ class PickNotices < CommandTower::Services::ApplicationService
32
+ Pick = Data.define(:notice_class, :record, :document, :content_hash)
33
+
34
+ SHOW_BUDGET_MS = 50
35
+
36
+ validate :user, is_a: User, required: true
37
+ validate :request_context, is_a: CommandTower::HomeNotices::Context, required: true
38
+ validate :candidates, is_a: Array, required: true
39
+
40
+ def call
41
+ context.blocking = pick(:blocking?) { |candidate| under_daily_cap?(candidate) }
42
+ context.dismissible = pick(:dismissible?) { |candidate| cooldown_clear?(candidate) }
43
+ end
44
+
45
+ private
46
+
47
+ def now
48
+ request_context.now
49
+ end
50
+
51
+ def config
52
+ CommandTower.config.home_notices
53
+ end
54
+
55
+ # First candidate of the severity that passes the gate (the block), `show?` and compose.
56
+ def pick(severity_predicate)
57
+ return nil if request_context.ui_catalog.to_i < Compose::MIN_CATALOG
58
+
59
+ candidates.each do |candidate|
60
+ next unless candidate.notice_class.public_send(severity_predicate)
61
+ next unless yield(candidate) && shown?(candidate)
62
+
63
+ composed = compose(candidate)
64
+ return composed unless composed.nil?
65
+ end
66
+ nil
67
+ end
68
+
69
+ def under_daily_cap?(candidate)
70
+ !candidate.record&.first_shown_at.nil? || blocking_started_today < config.blocking_daily_cap
71
+ end
72
+
73
+ def blocking_started_today
74
+ @blocking_started_today ||= begin
75
+ day = now.utc.beginning_of_day
76
+ user_rows(:blocking?).where(first_shown_at: day...(day + 1.day)).count
77
+ end
78
+ end
79
+
80
+ def cooldown_clear?(candidate)
81
+ clears_at = global_cooldown_clears_at
82
+ return true if clears_at.nil? || clears_at <= now
83
+
84
+ ends_at = candidate.record&.ends_at
85
+ candidate.notice_class < CommandTower::HomeNotices::Delivery && !ends_at.nil? && ends_at <= clears_at
86
+ end
87
+
88
+ def global_cooldown_clears_at
89
+ return @global_cooldown_clears_at if defined?(@global_cooldown_clears_at)
90
+
91
+ last_shown_at = user_rows(:dismissible?).maximum(:last_shown_at)
92
+ @global_cooldown_clears_at = last_shown_at && (last_shown_at + config.global_cooldown)
93
+ end
94
+
95
+ # The user's rows whose key is a registered notice of the given severity.
96
+ def user_rows(severity_predicate)
97
+ keys = CommandTower::HomeNotices::Catalog.notices.select(&severity_predicate).map(&:key)
98
+ CommandTower::HomeNotice.where(user_id: user.id, key: keys)
99
+ end
100
+
101
+ def shown?(candidate)
102
+ klass = candidate.notice_class
103
+ started_at = monotonic_seconds
104
+ shown = klass.new.show?(user:, context: request_context, notice: candidate.record)
105
+ report_slow(klass, started_at)
106
+ shown ? true : false
107
+ rescue StandardError => e
108
+ publish("show_if_failed", notice_key: klass.key, error_class: e.class.name,
109
+ log_level: klass.blocking? ? :error : :warn)
110
+ false
111
+ end
112
+
113
+ def report_slow(klass, started_at)
114
+ elapsed_ms = ((monotonic_seconds - started_at) * 1000).round
115
+ return if elapsed_ms <= SHOW_BUDGET_MS
116
+
117
+ publish("show_if_slow", notice_key: klass.key, ms: elapsed_ms, log_level: :warn)
118
+ end
119
+
120
+ def monotonic_seconds
121
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
122
+ end
123
+
124
+ def compose(candidate)
125
+ data = Compose.call(notice_class: candidate.notice_class, user:, request_context:,
126
+ record: candidate.record).data
127
+ return nil if data[:document].nil?
128
+
129
+ Pick.new(notice_class: candidate.notice_class, record: candidate.record,
130
+ document: data[:document], content_hash: data[:content_hash])
131
+ end
132
+
133
+ def publish(name, **payload)
134
+ CommandTower::Events.publish(category: :home_notices, name:, payload:)
135
+ end
136
+ end
137
+ end
138
+ end
139
+ end
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CommandTower
4
+ module Services
5
+ module HomeNotices
6
+ # Deletes home notice rows that are finished and idle (design D12).
7
+ #
8
+ # A row is pruned only when its last activity is older than `RETENTION` (180 days):
9
+ # `GREATEST(created_at, last_shown_at, acknowledged_at, dismissed_until)`, each nullable column
10
+ # wrapped in `COALESCE(..., created_at)` because MariaDB `GREATEST` returns NULL when any
11
+ # argument is NULL (a never-shown row would otherwise never be pruned).
12
+ #
13
+ # And it has ended:
14
+ # - delivery: acknowledged, dismissed, or past its `ends_at`
15
+ # - campaign: unacknowledged, or its key is unregistered, or its window has ended (the class
16
+ # window or the row `ends_at`). An acknowledged row of a live campaign is kept, because
17
+ # pruning it would show the campaign again.
18
+ #
19
+ # Unregistered keys are never selected, so their rows wait out the retention and are pruned. A
20
+ # key re-registered inside the retention window gets its old state back.
21
+ #
22
+ # Deletes in batches of `BATCH_SIZE`. Success data is `{ deleted: Integer }`. Writes no audit
23
+ # rows. CommandTower ships no scheduler: the host runs the job daily.
24
+ class PruneEnded < CommandTower::Services::ApplicationService
25
+ RETENTION = 180.days
26
+ BATCH_SIZE = 1_000
27
+
28
+ LAST_ACTIVITY_SQL = <<~SQL.squish
29
+ GREATEST(
30
+ created_at,
31
+ COALESCE(last_shown_at, created_at),
32
+ COALESCE(acknowledged_at, created_at),
33
+ COALESCE(dismissed_until, created_at)
34
+ )
35
+ SQL
36
+
37
+ validate :now, is_a: [Time, ActiveSupport::TimeWithZone], required: false
38
+
39
+ def call
40
+ context.deleted = prune
41
+ end
42
+
43
+ private
44
+
45
+ def current_time
46
+ now || Time.current
47
+ end
48
+
49
+ def prune
50
+ scope = idle.merge(ended_deliveries.or(ended_campaigns))
51
+ scope.in_batches(of: BATCH_SIZE).sum(&:delete_all)
52
+ end
53
+
54
+ def idle
55
+ CommandTower::HomeNotice.where("#{LAST_ACTIVITY_SQL} < ?", current_time - RETENTION)
56
+ end
57
+
58
+ def table
59
+ CommandTower::HomeNotice
60
+ end
61
+
62
+ def ended_deliveries
63
+ table.where(kind: "delivery").and(
64
+ table.where.not(acknowledged_at: nil)
65
+ .or(table.where.not(dismissed_until: nil))
66
+ .or(table.where(ends_at: ...current_time))
67
+ )
68
+ end
69
+
70
+ def ended_campaigns
71
+ table.where(kind: "campaign").and(
72
+ table.where(acknowledged_at: nil)
73
+ .or(table.where(ends_at: ...current_time))
74
+ .or(table.where.not(key: live_campaign_keys))
75
+ )
76
+ end
77
+
78
+ # Registered campaigns whose class window has not ended.
79
+ def live_campaign_keys
80
+ CommandTower::HomeNotices::Catalog.notices
81
+ .select { |klass| klass < CommandTower::HomeNotices::Campaign }
82
+ .reject { |klass| window_ended?(klass) }
83
+ .map(&:key)
84
+ end
85
+
86
+ def window_ended?(klass)
87
+ ends_at = klass.window&.ends_at
88
+ !ends_at.nil? && ends_at <= current_time
89
+ end
90
+ end
91
+ end
92
+ end
93
+ end