thecore_backend_commons 3.12.0 → 3.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ddc427f91f30a41460afead62731a1d602b6917aca2a97fedce0b50917d5f328
4
- data.tar.gz: ece1a417d1c4ba18fa5a48f3446cddd9b6d90828caeb528b0b6352f538240518
3
+ metadata.gz: 465d99db5c28a0099476fa5f4b862390f661dae07a0a54ac3c2c6b21597cbcfa
4
+ data.tar.gz: b4282d66700aafe387cbb3382a531950c80787034b924cb56c12f97e2a222ccc
5
5
  SHA512:
6
- metadata.gz: e97593b400468ab3515ac237f50027ee8247bbad7c463b4f0fa115c5d5dd6a157a539dfea6bba0951b8d94dcb723f750d2ee06a92fef4c2eba99403d94ed719e
7
- data.tar.gz: 37d2840f2c66e15b3f2dc646c3d8eedb7109276a44c7cf2666129abb4372c16a30efcaef46c0666dad80665c86a08ec434e178d8969df55741b32a64b06fbde0
6
+ metadata.gz: e4b3948959b20e0e131e489596e6399952936ae84440b522df5fc41fc0f4f9d6fac4ef9ab01e8f7bb9c74fb8ddc8021d8587df41f29d314f375be59d9cd14358
7
+ data.tar.gz: f97bfd47f4de73499ce7f48bd9b6837d56d9b19b9ba13a3a1c68c1a66a9482d94b4496aa2f318fc42762e857b08fb54881a6e6e1a4b26cbb76959df6eb6b9730
data/README.md CHANGED
@@ -2,6 +2,20 @@ This is part of [Thecore framework](https://github.com/gabrieletassoni/thecore/t
2
2
 
3
3
  ---
4
4
 
5
+ ## Real-time messages (Action Cable): guide for frontend developers
6
+
7
+ **[docs/frontend/action-cable.md](docs/frontend/action-cable.md)** is the contract for frontends: how
8
+ to connect to `/cable` with the JWT, `PushNotificationChannel`, `ActivityLogChannel` and the shape of
9
+ each message.
10
+
11
+ Record-change messages (`ActivityLogChannel`, the `messages` room) are **off by default** since
12
+ 3.13.0: an installation turns them on with the setting `action_cable.broadcast_record_changes` =
13
+ `true` (RailsAdmin → Settings). When on, a message says which record changed (`class`, `id`,
14
+ `action`) and whether it succeeded, never the record's data: clients read the data through the REST
15
+ API.
16
+
17
+ ---
18
+
5
19
  ## Web Push notifications (VAPID)
6
20
 
7
21
  Self-contained browser push notifications — no Firebase, no APNs, no third-party account required. The gem provides the server-side half: models, dispatch service, and ActionCable channel. The client integration guide (React + service worker) lives in the [`model_driven_api` README](../model_driven_api/README.md#web-push-vapid-from-a-react-client).
@@ -1,13 +1,21 @@
1
+ # Record-change notifications (ThecoreBackendCommons::ActivityLog). The room exists only when the
2
+ # installation turns broadcasting on: otherwise the subscription is rejected. Frontend contract:
3
+ # docs/frontend/action-cable.md.
1
4
  class ActivityLogChannel < ApplicationCable::Channel
2
5
  def subscribed
3
- stream_from "messages"
6
+ return reject unless ThecoreBackendCommons::ActivityLog.enabled?
7
+
8
+ stream_from ThecoreBackendCommons::ActivityLog::ROOM
4
9
  end
5
10
 
6
11
  def unsubscribed
7
12
  # Any cleanup needed when channel is unsubscribed
8
13
  end
9
14
 
15
+ # Connection check for clients: the answer goes back to the sender only, never to the room.
10
16
  def receive(data)
11
- ActionCable.server.broadcast("messages", {message: "ActionCable is connected and received: #{data["message"]}", topic: data["topic"].presence || "general"}) if data["namespace"] == "subscriptions"
17
+ return unless data["namespace"] == "subscriptions"
18
+
19
+ transmit({ message: "ActionCable is connected and received: #{data["message"]}", topic: data["topic"].presence || "general" })
12
20
  end
13
21
  end
@@ -0,0 +1,6 @@
1
+ # Saving an action_cable setting forgets ActivityLog's cached value in this process at once
2
+ # (ThecoreBackendCommons::ActivityLog::SettingHook). to_prepare re-runs on reload: include once.
3
+ Rails.application.config.to_prepare do
4
+ hook = ThecoreBackendCommons::ActivityLog::SettingHook
5
+ ThecoreSettings::Setting.include(hook) unless ThecoreSettings::Setting.include?(hook)
6
+ end
@@ -44,25 +44,32 @@ module BaseApplicationRecordConcern
44
44
  end
45
45
  end
46
46
 
47
+ # Record-change notifications (ThecoreBackendCommons::ActivityLog): off unless the installation
48
+ # turns them on, and never carrying the record itself.
49
+ # Validation runs before any transaction callback knows the action: a new record is a create,
50
+ # anything else an update (a destroy is never validated).
47
51
  def validation_ko
48
- ActionCable.server.broadcast("messages", build_message(false, false, self.errors.full_messages.uniq)) if self.errors.any? && !is_model_forbidden
52
+ return unless errors.any?
53
+
54
+ broadcast_record_change(action: new_record? ? :create : :update, success: false, valid: false, errors: errors.full_messages.uniq)
49
55
  end
50
56
 
51
57
  def message_ok
52
- ActionCable.server.broadcast("messages", build_message(true, true, [])) unless is_model_forbidden
58
+ broadcast_record_change(action: detect_action, success: true, valid: true, errors: [])
53
59
  end
54
60
 
55
61
  def message_ko
56
- ActionCable.server.broadcast("messages", build_message(false, true, [])) unless is_model_forbidden
62
+ broadcast_record_change(action: detect_action, success: false, valid: true, errors: [])
57
63
  end
58
64
 
59
- def is_model_forbidden
60
- Rails.logger.debug("Checking if model #{self.class.name} is forbidden for ActionCable messages")
61
- ["User", "Role"].include?(self.class.name)
65
+ def broadcast_record_change(**outcome)
66
+ return if broadcast_excluded_model?
67
+
68
+ ThecoreBackendCommons::ActivityLog.broadcast(self, **outcome)
62
69
  end
63
70
 
64
- def build_message(success, valid, errors)
65
- { topic: :record, action: detect_action, class: self.class.name, success: success, valid: valid, errors: errors, record: self }
71
+ def broadcast_excluded_model?
72
+ ["User", "Role"].include?(self.class.name)
66
73
  end
67
74
 
68
75
  def detect_action
@@ -34,8 +34,7 @@ module CableConnectionConcern
34
34
 
35
35
  # JWT: the signature MUST be verified, exactly like every REST request. Decoding with the
36
36
  # verification disabled (the previous behaviour) let a forged token carrying an arbitrary
37
- # user_id authenticate as any user over the WebSocket — and ActivityLogChannel streams every
38
- # record change, so that was a full read bypass. See docs/adr and the issue tracker.
37
+ # user_id authenticate as any user over the WebSocket. See docs/adr and the issue tracker.
39
38
  body = decode_verified_jwt(m)
40
39
  jwt_user = User.find_by(id: body[:user_id]) if body && body[:user_id]
41
40
  return active_or_reject(jwt_user) if jwt_user
data/db/seeds.rb CHANGED
@@ -21,4 +21,9 @@ unless ThecoreSettings::Setting.where(ns: :vapid, key: :public_key).where.not(ra
21
21
  puts " Generated new VAPID key pair"
22
22
  end
23
23
  Thecore::Seed.save_setting :vapid, :contact_email, "" unless ThecoreSettings::Setting.where(ns: :vapid, key: :contact_email).exists?
24
- Thecore::Seed.save_setting :vapid, :max_messages_per_subscriber, "500" unless ThecoreSettings::Setting.where(ns: :vapid, key: :max_messages_per_subscriber).exists?
24
+ Thecore::Seed.save_setting :vapid, :max_messages_per_subscriber, "500" unless ThecoreSettings::Setting.where(ns: :vapid, key: :max_messages_per_subscriber).exists?
25
+ puts "Loading ThecoreBackendCommons Action Cable config"
26
+ # Record-change notifications on the "messages" room (ActivityLogChannel): off unless an admin sets
27
+ # it to "true". save_setting writes only when the value is blank, so an admin's choice survives
28
+ # every deploy. See docs/frontend/action-cable.md.
29
+ Thecore::Seed.save_setting :action_cable, :broadcast_record_changes, "false"
@@ -0,0 +1,87 @@
1
+ module ThecoreBackendCommons
2
+ # Record-change notifications on the "messages" Action Cable room (ActivityLogChannel).
3
+ #
4
+ # Off unless the installation sets the ThecoreSettings value action_cable.broadcast_record_changes
5
+ # to true (seeded "false"). When on, a message says which record changed and how it went, never
6
+ # what it contains: clients that need the data read it through the REST API, where each user's
7
+ # permissions apply. See docs/frontend/action-cable.md.
8
+ module ActivityLog
9
+ ROOM = "messages".freeze
10
+ SETTING_NS = "action_cable".freeze
11
+ SETTING_KEY = "broadcast_record_changes".freeze
12
+ TRUE_VALUES = %w[true 1 yes on].freeze
13
+ # The setting is read at most once per this many seconds per process, so a save never pays a
14
+ # query for it. The process that saves the setting forgets the cached value at once (SettingHook);
15
+ # every other process (web workers, Sidekiq) sees the change within this delay.
16
+ CACHE_SECONDS = 60
17
+
18
+ # Included into ThecoreSettings::Setting (config/initializers/activity_log.rb).
19
+ module SettingHook
20
+ extend ActiveSupport::Concern
21
+
22
+ included do
23
+ after_commit :forget_activity_log_setting, if: -> { ns.to_s == ActivityLog::SETTING_NS }
24
+ end
25
+
26
+ private
27
+
28
+ def forget_activity_log_setting
29
+ ActivityLog.reset!
30
+ end
31
+ end
32
+
33
+ class << self
34
+ def enabled?
35
+ now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
36
+ cached = @cached
37
+ return cached[:value] if cached && now < cached[:expires_at]
38
+
39
+ value = read_setting
40
+ @cached = { value: value, expires_at: now + CACHE_SECONDS }
41
+ value
42
+ end
43
+
44
+ # Forgets the cached setting: the next enabled? reads it again.
45
+ def reset!
46
+ @cached = nil
47
+ end
48
+
49
+ # The only message the room carries for a record change: identity and outcome, no attributes.
50
+ def message(record, action:, success:, valid:, errors:)
51
+ {
52
+ topic: :record,
53
+ action: action,
54
+ class: record.class.name,
55
+ id: record.id,
56
+ success: success,
57
+ valid: valid,
58
+ errors: errors,
59
+ }
60
+ end
61
+
62
+ # Sends the message when broadcasting is on. A failure to send (adapter missing, Redis down, …)
63
+ # is logged and reported to Rails.error, never raised: the change it announces is already done,
64
+ # and raising here would turn a committed save or destroy into an error (GitHub #6).
65
+ def broadcast(record, **outcome)
66
+ return unless enabled?
67
+
68
+ ActionCable.server.broadcast(ROOM, message(record, **outcome))
69
+ rescue StandardError => e
70
+ context = { model: record.class.name, id: record.id }
71
+ Rails.logger.error(
72
+ "[ActivityLog] record-change message not sent for #{context[:model]}##{context[:id].inspect}: #{e.class}: #{e.message}"
73
+ )
74
+ Rails.error.report(e, handled: true, context: context)
75
+ end
76
+
77
+ private
78
+
79
+ def read_setting
80
+ raw = ThecoreSettings::Setting.where(ns: SETTING_NS, key: SETTING_KEY).pick(:raw)
81
+ TRUE_VALUES.include?(raw.to_s.strip.downcase)
82
+ rescue ActiveRecord::ActiveRecordError
83
+ false
84
+ end
85
+ end
86
+ end
87
+ end
@@ -1,3 +1,3 @@
1
1
  module ThecoreBackendCommons
2
- VERSION = "3.12.0".freeze
2
+ VERSION = "3.13.1".freeze
3
3
  end
@@ -19,6 +19,7 @@ require "thecore_backend_commons/smtp_config"
19
19
  require "thecore_backend_commons/smtp_tester"
20
20
  require "thecore_backend_commons/push_notification_service"
21
21
  require "thecore_backend_commons/default_module_registry"
22
+ require "thecore_backend_commons/activity_log"
22
23
  require "thecore_backend_commons/discarded_job_logger"
23
24
  require "thecore_backend_commons/job_failure_policy"
24
25
 
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: thecore_backend_commons
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.12.0
4
+ version: 3.13.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Gabriele Tassoni
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-25 00:00:00.000000000 Z
11
+ date: 2026-11-30 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: thecore_auth_commons
@@ -230,6 +230,7 @@ files:
230
230
  - app/models/push_message.rb
231
231
  - app/models/push_subscriber.rb
232
232
  - config/initializers/abilities.rb
233
+ - config/initializers/activity_log.rb
233
234
  - config/initializers/add_to_db_migrations.rb
234
235
  - config/initializers/after_initialize.rb
235
236
  - config/initializers/application_config.rb
@@ -254,6 +255,7 @@ files:
254
255
  - db/seeds.rb
255
256
  - lib/tasks/thecore_backend_commons_tasks.rake
256
257
  - lib/thecore_backend_commons.rb
258
+ - lib/thecore_backend_commons/activity_log.rb
257
259
  - lib/thecore_backend_commons/default_module_registry.rb
258
260
  - lib/thecore_backend_commons/discarded_job_logger.rb
259
261
  - lib/thecore_backend_commons/engine.rb