thecore_backend_commons 3.14.0 → 3.16.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3f2a8859c842b9323f8900296504b3ee72e08b77f069678833d39b1e4299fc46
4
- data.tar.gz: c68ab134016879d83e489e8725db03a4f351a6297a14c6ac3920db847e293c91
3
+ metadata.gz: 72f6c21d7349acafc03685f38433748768fa7908b1668177f5e595d62fccf754
4
+ data.tar.gz: 3053800cad2e66bd8a7559515a2aab2f521d827358f426a8ad56e919654ab0c2
5
5
  SHA512:
6
- metadata.gz: 2222a3fc4f998d7ed0b32d15e6f1cbbc1c6faea4cf8986b00db86ff34849351f7b23337dc505ec44214e4f350aa0985907903ceef8f1b52a363ffafd70b1337b
7
- data.tar.gz: 1456d9624b9bafe48b1ff9ed9008b07519f196aa6fdeb531b25b1e605100e51f7ac0fab44701c698305e53ad906154dd44f849b7e0a3e5f8e4005996cd426766
6
+ metadata.gz: 30d673fd3205f8499e4e84ab6f1e4a3827fb830a478561d958dc5bc3af50f490b1e033476c5a25d4d7f2ad270bbb3ad95177f19a73f2b8d5541f6efbea1ab854
7
+ data.tar.gz: 8a4e4342bb6081235dd4db7019d59451b79a593d4410ed9c1db6eb38cc07dbe9e42130986fc25826c10519e397d4d71c77ee4d65c559209677e5ee8ee5c525b0
data/README.md CHANGED
@@ -14,6 +14,10 @@ Record-change messages (`ActivityLogChannel`, the `messages` room) are **off by
14
14
  `action`) and whether it succeeded, never the record's data: clients read the data through the REST
15
15
  API.
16
16
 
17
+ Action Cable runs on **Solid Cable** in the app's own database (no Redis): the host's
18
+ `config/cable.yml` is written by `bin/rails generate thecore_backend_commons:install` and the table
19
+ comes with `bin/rails db:migrate`. Details: `docs/agents/action-cable.md`.
20
+
17
21
  ---
18
22
 
19
23
  ## Web Push notifications (VAPID)
@@ -175,64 +179,15 @@ overrides it. Full mechanics (idempotency, abstract/STI exclusion, `to_prepare`
175
179
 
176
180
  ---
177
181
 
178
- ## Background jobs: no retries by default
179
-
180
- Every app using this gem runs its background jobs on Sidekiq in production, and by default:
181
-
182
- - **a failed job is never retried** (`retry: false`): it runs once, and Sidekiq keeps it in
183
- neither the retry set nor the Dead Set;
184
- - **only the latest failed job is kept in Redis**: `sidekiq-failures` (from
185
- `thecore_background_jobs`) stores each failed job's full payload, arguments included, in the
186
- Redis `failed` set; it is capped at 1, still visible in the Sidekiq web UI's Failures tab;
187
- - **every failure is written to the Rails log** by `ThecoreBackendCommons::DiscardedJobLogger`:
188
- job class (or `Mailer#action`), queue, jid and error, never the arguments.
189
-
190
- Why zero: in a Thecore app in production, mail jobs carrying a whole PDF in their arguments
191
- failed with a permanent SMTP error and were retried for weeks, then kept in the Dead Set. Redis
192
- grew to 23 GB until the host's OOM killer put it in a restart loop and no job ran for three days
193
- (`docs/adr/0002-no-job-retries-failures-logged.md`).
194
-
195
- ### Changing the defaults on an installation
196
-
197
- Set these in the environment of both the `backend` and the `worker` containers. On an
198
- installation deployed by `thecore_devcontainer` that is the target's
199
- `vendor/deploytargets/<provider>/<customer>.env`, which reaches both containers through their
200
- `env_file` (`thecore_devcontainer` ADR 0002); on a hand-written compose, its `environment:`.
201
-
202
- | Variable | Unset or blank | Accepted values | Effect |
203
- | --- | --- | --- | --- |
204
- | `THECORE_JOB_RETRIES` | `0` (no retries) | a whole number >= 0 | how many times Sidekiq retries a failed job, app-wide |
205
- | `THECORE_FAILED_JOBS_KEPT` | `1` | a whole number >= 1 | how many failed jobs stay in the Redis `failed` set |
206
-
207
- Any other value (`yes`, `-1`, `1.5`, ...) stops the app at boot with an error naming the
208
- variable: a typo never silently turns retries back on. With retries above 0, a job that uses
209
- them all ends in Sidekiq's Dead Set, which is capped by count and age but not by size.
210
-
211
- ### Changing it for one job
212
-
213
- A job class sets its own retry count with Sidekiq's option, which wins over the app-wide value
214
- in both directions (it works on ActiveJob classes and mailers' jobs alike):
182
+ ## Background jobs
215
183
 
216
- ```ruby
217
- class SyncInventoryJob < ApplicationJob
218
- sidekiq_options retry: 3 # or retry: false when THECORE_JOB_RETRIES is above 0
219
- end
220
- ```
221
-
222
- **Don't use ActiveJob's `retry_on` for this.** It retries independently of Sidekiq: on failure
223
- ActiveJob enqueues a new copy of the job, arguments included, whatever `THECORE_JOB_RETRIES`
224
- says, and the copies never show up as Sidekiq retries.
225
-
226
- ### Logging failures somewhere else too
227
-
228
- Add your own Sidekiq death handler next to the default one; both run:
229
-
230
- ```ruby
231
- # config/initializers/sidekiq.rb in the app
232
- Sidekiq.configure_server do |config|
233
- config.death_handlers << ->(job, exception) { MyErrorLog.record(job["jid"], exception) }
234
- end
235
- ```
184
+ Every app using this gem runs its background jobs as `thecore_background_jobs` (`~> 3.1`, a
185
+ dependency of this gem) sets them up: Solid Queue in production, no retries by default
186
+ (`THECORE_JOB_RETRIES`, `THECORE_FAILED_JOBS_KEPT`), one log line per failed job without its
187
+ arguments, and `ThecoreBackgroundJobs.on_job_failure(handler)` to record failures elsewhere too.
188
+ See that gem's README. Until 3.14 this gem configured Sidekiq for it
189
+ (`docs/adr/0001-active-job-queue-adapter-is-framework-imposed.md`,
190
+ `docs/adr/0002-no-job-retries-failures-logged.md`, both amended by thecore ADR 0017).
236
191
 
237
192
  ---
238
193
 
@@ -1,5 +1,5 @@
1
1
  class PushDispatchJob < ApplicationJob
2
- queue_as :"#{ENV.fetch('COMPOSE_PROJECT_NAME', 'default')}_default"
2
+ queue_as { ThecoreBackgroundJobs.queue_name(:default) }
3
3
 
4
4
  def perform(push_message_id)
5
5
  message = PushMessage.find_by(id: push_message_id)
@@ -8,10 +8,5 @@ Rails.application.config.action_mailer.delivery_method = :smtp
8
8
 
9
9
  Rails.application.config.action_cable.allowed_request_origins = [/http:\/\/*/, /https:\/\/*/, /file:\/\/*/, 'file://', nil]
10
10
 
11
- # Every Thecore app ships a dedicated Sidekiq worker service alongside the web backend (see
12
- # thecore_devcontainer's docker-compose.yml) — this gem already hard-requires the sidekiq gems
13
- # and mounts Sidekiq::Web unconditionally (thecore_background_jobs), so ActiveJob should actually
14
- # route through it rather than defaulting to Rails' in-process :async, which silently drops any
15
- # job in flight when its process restarts. Production only: :async remains the default in
16
- # development/test so neither requires a reachable Redis. See docs/adr/0001, GLOSSARY.md.
17
- Rails.application.config.active_job.queue_adapter = :sidekiq if Rails.env.production?
11
+ # The production queue adapter (Solid Queue), the job failure policy and the failure logger are
12
+ # imposed by thecore_background_jobs since 3.1, not here (thecore ADR 0017, docs/adr/0001 and 0002).
@@ -13,7 +13,8 @@ module BaseApplicationRecordConcern
13
13
 
14
14
  after_commit :manage_assets
15
15
 
16
- # Broadcast messages via ActionCable for create, update, destroy actions
16
+ # Broadcast messages via ActionCable for create, update, destroy actions. The "valid: false"
17
+ # message waits for the transaction around the save to end (see validation_ko).
17
18
  after_validation :validation_ko
18
19
 
19
20
  after_commit :message_ok
@@ -48,10 +49,20 @@ module BaseApplicationRecordConcern
48
49
  # turns them on, and never carrying the record itself.
49
50
  # Validation runs before any transaction callback knows the action: a new record is a create,
50
51
  # anything else an update (a destroy is never validated).
52
+ # The message leaves after the rollback (#11): with Solid Cable a broadcast is a row in the app's
53
+ # database, and one written inside the save's transaction would be rolled back with the invalid
54
+ # save. It is registered on the transaction that is open now: the save's own one (always rolled
55
+ # back for an invalid record), or the caller's outer transaction, whichever way that one ends.
56
+ # Outside any transaction (a plain valid?) it leaves at once. The outcome is captured now, since
57
+ # the rollback restores the record's state.
51
58
  def validation_ko
52
59
  return unless errors.any?
53
60
 
54
- broadcast_record_change(action: new_record? ? :create : :update, success: false, valid: false, errors: errors.full_messages.uniq)
61
+ outcome = { action: new_record? ? :create : :update, success: false, valid: false, errors: errors.full_messages.uniq }
62
+ announce = -> { broadcast_record_change(**outcome) }
63
+ transaction = self.class.current_transaction
64
+ transaction.after_rollback(&announce)
65
+ transaction.after_commit(&announce)
55
66
  end
56
67
 
57
68
  def message_ok
@@ -0,0 +1,15 @@
1
+ # Solid Cable's table (solid_cable 4.1.0's db/cable_schema.rb), in the app's own database: no second
2
+ # database, no connects_to and no database.yml changes (thecore ADR 0017 stage 2, #11). The
3
+ # production adapter of every host's config/cable.yml (docs/agents/action-cable.md).
4
+ class CreateSolidCableTables < ActiveRecord::Migration[7.1]
5
+ def change
6
+ create_table "solid_cable_messages" do |t|
7
+ t.binary "channel", limit: 1024, null: false
8
+ t.binary "payload", limit: 536_870_912, null: false
9
+ t.datetime "created_at", null: false
10
+ t.integer "channel_hash", limit: 8, null: false
11
+ t.index ["channel_hash"], name: "index_solid_cable_messages_on_channel_hash"
12
+ t.index ["created_at"], name: "index_solid_cable_messages_on_created_at"
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,18 @@
1
+ require "rails/generators"
2
+
3
+ module ThecoreBackendCommons
4
+ module Generators
5
+ # `bin/rails generate thecore_backend_commons:install`: writes the host's config/cable.yml, Solid
6
+ # Cable in the app's own database in production (#11, thecore ADR 0017 stage 2). The host owns
7
+ # the file, and this is the only content it should have, so a Redis one is replaced.
8
+ class InstallGenerator < Rails::Generators::Base
9
+ source_root File.expand_path("templates", __dir__)
10
+ desc "Writes config/cable.yml: Solid Cable in the app's database in production, async in " \
11
+ "development, test in test."
12
+
13
+ def create_cable_yml
14
+ copy_file "cable.yml", "config/cable.yml", force: true
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,14 @@
1
+ # Action Cable adapters (thecore_backend_commons, thecore ADR 0017 stage 2). Production: Solid Cable,
2
+ # its table (solid_cable_messages, from the gem's migration) in the app's own database, no
3
+ # connects_to: the web process and the job worker broadcast to the same table, every web process
4
+ # polls it. Written by `bin/rails generate thecore_backend_commons:install`.
5
+ development:
6
+ adapter: async
7
+
8
+ test:
9
+ adapter: test
10
+
11
+ production:
12
+ adapter: solid_cable
13
+ polling_interval: 0.1.seconds
14
+ message_retention: 1.day
@@ -12,7 +12,7 @@ module ThecoreBackendCommons
12
12
  TRUE_VALUES = %w[true 1 yes on].freeze
13
13
  # The setting is read at most once per this many seconds per process, so a save never pays a
14
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.
15
+ # every other process (web workers, job workers) sees the change within this delay.
16
16
  CACHE_SECONDS = 60
17
17
 
18
18
  # Included into ThecoreSettings::Setting (config/initializers/activity_log.rb).
@@ -1,3 +1,3 @@
1
1
  module ThecoreBackendCommons
2
- VERSION = "3.14.0".freeze
2
+ VERSION = "3.16.0".freeze
3
3
  end
@@ -2,6 +2,7 @@ require "ostruct"
2
2
  require "web-push" # gem for VAPID web push (pushpad/web-push, actively maintained)
3
3
  require "thecore_auth_commons"
4
4
  require "thecore_background_jobs"
5
+ require "solid_cable" # Action Cable production adapter (#11): loads its engine and SolidCable::Message
5
6
  require "rails-i18n"
6
7
  require "devise-i18n"
7
8
  require "http_accept_language"
@@ -20,8 +21,6 @@ require "thecore_backend_commons/smtp_tester"
20
21
  require "thecore_backend_commons/push_notification_service"
21
22
  require "thecore_backend_commons/default_module_registry"
22
23
  require "thecore_backend_commons/activity_log"
23
- require "thecore_backend_commons/discarded_job_logger"
24
- require "thecore_backend_commons/job_failure_policy"
25
24
 
26
25
  module ThecoreBackendCommons
27
26
  # Deep-merges +dest+ into +src+ (mutating and returning +src+), extending existing arrays
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.14.0
4
+ version: 3.16.0
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-30 00:00:00.000000000 Z
11
+ date: 2026-12-05 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: thecore_auth_commons
@@ -30,14 +30,28 @@ dependencies:
30
30
  requirements:
31
31
  - - "~>"
32
32
  - !ruby/object:Gem::Version
33
- version: '3.0'
33
+ version: '3.1'
34
34
  type: :runtime
35
35
  prerelease: false
36
36
  version_requirements: !ruby/object:Gem::Requirement
37
37
  requirements:
38
38
  - - "~>"
39
39
  - !ruby/object:Gem::Version
40
- version: '3.0'
40
+ version: '3.1'
41
+ - !ruby/object:Gem::Dependency
42
+ name: solid_cable
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '4.1'
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '4.1'
41
55
  - !ruby/object:Gem::Dependency
42
56
  name: ostruct
43
57
  requirement: !ruby/object:Gem::Requirement
@@ -242,7 +256,6 @@ files:
242
256
  - config/initializers/default_module_registry.rb
243
257
  - config/initializers/extension_nil.rb
244
258
  - config/initializers/extension_string.rb
245
- - config/initializers/sidekiq.rb
246
259
  - config/locales/en.devise.custom.yml
247
260
  - config/locales/en.yml
248
261
  - config/locales/it.devise.custom.yml
@@ -252,14 +265,15 @@ files:
252
265
  - db/migrate/20260625000001_add_sender_user_id_to_push_messages.rb
253
266
  - db/migrate/20260629000001_add_message_type_to_push_messages.rb
254
267
  - db/migrate/20260908000010_add_time_zone_columns_to_push_messages.rb
268
+ - db/migrate/20261205000001_create_solid_cable_tables.rb
255
269
  - db/seeds.rb
270
+ - lib/generators/thecore_backend_commons/install/install_generator.rb
271
+ - lib/generators/thecore_backend_commons/install/templates/cable.yml
256
272
  - lib/tasks/thecore_backend_commons_tasks.rake
257
273
  - lib/thecore_backend_commons.rb
258
274
  - lib/thecore_backend_commons/activity_log.rb
259
275
  - lib/thecore_backend_commons/default_module_registry.rb
260
- - lib/thecore_backend_commons/discarded_job_logger.rb
261
276
  - lib/thecore_backend_commons/engine.rb
262
- - lib/thecore_backend_commons/job_failure_policy.rb
263
277
  - lib/thecore_backend_commons/push_notification_service.rb
264
278
  - lib/thecore_backend_commons/smtp_config.rb
265
279
  - lib/thecore_backend_commons/smtp_tester.rb
@@ -1,11 +0,0 @@
1
- # What a failed background job leaves behind, app-wide, from the container's environment:
2
- # THECORE_JOB_RETRIES (default 0, no retries) and THECORE_FAILED_JOBS_KEPT (default 1, the latest
3
- # failure in the sidekiq-failures set); an invalid value refuses to boot (JobFailurePolicy).
4
- # Why: docs/adr/0002-no-job-retries-failures-logged.md.
5
- ThecoreBackendCommons::JobFailurePolicy.apply!
6
-
7
- # Every failed job leaves one line in the Rails log (DiscardedJobLogger); apps append their own
8
- # handlers next to it. Required, not autoloaded: see docs/adr/0002-no-job-retries-failures-logged.md.
9
- Sidekiq.configure_server do |config|
10
- config.death_handlers << ThecoreBackendCommons::DiscardedJobLogger unless config.death_handlers.include?(ThecoreBackendCommons::DiscardedJobLogger)
11
- end
@@ -1,31 +0,0 @@
1
- module ThecoreBackendCommons
2
- # Generic Sidekiq death handler, registered by config/initializers/sidekiq.rb: with retries off
3
- # Sidekiq drops a failed job without keeping it anywhere, so this writes one line to the Rails log
4
- # per failure. Only the job's identity goes in: class (or Mailer#action for a mail job), queue, jid
5
- # and the error, never the arguments, which can be huge or sensitive (docs/adr/0002). Apps add their own handlers next to this one (`config.death_handlers << MyHandler`
6
- # inside `Sidekiq.configure_server`), e.g. to record failures in their own integration log.
7
- module DiscardedJobLogger
8
- MAX_MESSAGE_LENGTH = 500
9
-
10
- def self.call(job, exception)
11
- error = "#{exception.class}: #{exception.message}".truncate(MAX_MESSAGE_LENGTH)
12
- Rails.logger.error(
13
- "Background job #{name_of(job)} failed and was discarded (no retry left): " \
14
- "queue=#{job["queue"]} jid=#{job["jid"]} error=#{error}"
15
- )
16
- rescue StandardError => e
17
- Rails.logger.error("DiscardedJobLogger could not record a failed job: #{e.class}: #{e.message}")
18
- end
19
-
20
- def self.name_of(job)
21
- wrapped = (job["wrapped"] || job["class"]).to_s
22
- first = Array(job["args"]).first
23
- arguments = first.is_a?(Hash) ? Array(first["arguments"]) : []
24
- return wrapped unless wrapped == "ActionMailer::MailDeliveryJob" && arguments.size >= 2
25
-
26
- "#{arguments[0]}##{arguments[1]}"
27
- end
28
-
29
- private_class_method :name_of
30
- end
31
- end
@@ -1,54 +0,0 @@
1
- module ThecoreBackendCommons
2
- # What happens to a failed background job, app-wide, read from the container's environment by
3
- # config/initializers/sidekiq.rb (docs/adr/0002-no-job-retries-failures-logged.md):
4
- #
5
- # - THECORE_JOB_RETRIES: how many times Sidekiq retries a failed job. Unset or blank = 0, i.e.
6
- # `retry: false` (not `retry: 0`, which would still send the job to the Dead Set).
7
- # - THECORE_FAILED_JOBS_KEPT: how many failed jobs sidekiq-failures keeps in the Redis `failed`
8
- # set, payload and arguments included (Sidekiq.failures_max_count). Unset or blank = 1, the
9
- # latest, still shown in the Failures tab.
10
- #
11
- # Any other value refuses to boot: a typo must never silently re-enable retries or keep every
12
- # failed payload. A job class still overrides the retry count with `sidekiq_options retry: N`.
13
- # Required, not autoloaded: see the ADR.
14
- module JobFailurePolicy
15
- RETRIES_VARIABLE = "THECORE_JOB_RETRIES".freeze
16
- KEPT_VARIABLE = "THECORE_FAILED_JOBS_KEPT".freeze
17
- DEFAULT_RETRIES = 0
18
- DEFAULT_KEPT = 1
19
-
20
- class InvalidValue < StandardError; end
21
-
22
- # Sets Sidekiq's app-wide default retry option and the sidekiq-failures cap.
23
- def self.apply!
24
- Sidekiq.default_job_options = Sidekiq.default_job_options.merge("retry" => sidekiq_retry_option)
25
- Sidekiq.failures_max_count = failed_jobs_kept
26
- end
27
-
28
- # The value for Sidekiq's `retry` option: false for no retries, else the count.
29
- def self.sidekiq_retry_option
30
- retries.zero? ? false : retries
31
- end
32
-
33
- def self.retries
34
- whole_number_from_env(RETRIES_VARIABLE, default: DEFAULT_RETRIES, minimum: 0, expected: "a whole number >= 0")
35
- end
36
-
37
- def self.failed_jobs_kept
38
- whole_number_from_env(KEPT_VARIABLE, default: DEFAULT_KEPT, minimum: 1, expected: "a whole number >= 1")
39
- end
40
-
41
- # The whole number in the environment variable, default when unset or blank; raises InvalidValue
42
- # on anything else or below minimum.
43
- def self.whole_number_from_env(variable, default:, minimum:, expected:)
44
- raw = ENV.fetch(variable, nil)
45
- return default if raw.nil? || raw.strip.empty?
46
-
47
- value = raw.strip
48
- return value.to_i if value.match?(/\A\d+\z/) && value.to_i >= minimum
49
-
50
- raise InvalidValue, "#{variable}=#{raw.inspect} is not valid: use #{expected}, or leave it unset (default #{default})"
51
- end
52
- private_class_method :whole_number_from_env
53
- end
54
- end