thecore_backend_commons 3.13.1 → 3.15.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: 465d99db5c28a0099476fa5f4b862390f661dae07a0a54ac3c2c6b21597cbcfa
4
- data.tar.gz: b4282d66700aafe387cbb3382a531950c80787034b924cb56c12f97e2a222ccc
3
+ metadata.gz: c25e75a330b000da97adb51aadde4893de944605914b1d307febcba8ba310739
4
+ data.tar.gz: 702b620b89c37ecb791bfc4644438aa0057111ddb236ef7cd8100f2947950475
5
5
  SHA512:
6
- metadata.gz: e4b3948959b20e0e131e489596e6399952936ae84440b522df5fc41fc0f4f9d6fac4ef9ab01e8f7bb9c74fb8ddc8021d8587df41f29d314f375be59d9cd14358
7
- data.tar.gz: f97bfd47f4de73499ce7f48bd9b6837d56d9b19b9ba13a3a1c68c1a66a9482d94b4496aa2f318fc42762e857b08fb54881a6e6e1a4b26cbb76959df6eb6b9730
6
+ metadata.gz: c16a2c450be82f46f8113ba82d2939c44197f07f60d0bb9dd2d4ae2d9c414b092c7c58c888acae959ec1a6d9c8c82cd18db7f388f7e075d089a64fa7e56bd4f8
7
+ data.tar.gz: 83c0155ac3b4b2f85a6258a4f3b31ab2acca3f1c76f64127e05468f12d0cdaec2f0826a9dc6ca7e60af9122b9f3a6f646647453b61a9b90814384b710a20f08d
data/README.md CHANGED
@@ -165,7 +165,9 @@ loads every model in production.
165
165
 
166
166
  Consumers today: `model_driven_api`'s `ModelDrivenApiDefaultJsonAttrs` (default `json_attrs`)
167
167
  and `thecore_ui_rails_admin`'s `ThecoreUiRailsAdminDefaultNavigationConcern` (default
168
- `navigation_label`/`navigation_icon`) — see their own READMEs for what each one does. A model
168
+ `navigation_label`/`navigation_icon`) — see their own READMEs for what each one does — and,
169
+ since 3.14.0, this gem's own `BaseApplicationRecordConcern` (every model) and
170
+ `ThecoreBackendCommonsUserConcern` (`User`), registered after the other gems' defaults. A model
169
171
  that still needs custom behavior keeps (or adds) an explicit `Api::ModelName`/
170
172
  `RailsAdmin::ModelName` concern exactly as before; it simply runs *after* the default and
171
173
  overrides it. Full mechanics (idempotency, abstract/STI exclusion, `to_prepare` vs
@@ -173,64 +175,15 @@ overrides it. Full mechanics (idempotency, abstract/STI exclusion, `to_prepare`
173
175
 
174
176
  ---
175
177
 
176
- ## Background jobs: no retries by default
178
+ ## Background jobs
177
179
 
178
- Every app using this gem runs its background jobs on Sidekiq in production, and by default:
179
-
180
- - **a failed job is never retried** (`retry: false`): it runs once, and Sidekiq keeps it in
181
- neither the retry set nor the Dead Set;
182
- - **only the latest failed job is kept in Redis**: `sidekiq-failures` (from
183
- `thecore_background_jobs`) stores each failed job's full payload, arguments included, in the
184
- Redis `failed` set; it is capped at 1, still visible in the Sidekiq web UI's Failures tab;
185
- - **every failure is written to the Rails log** by `ThecoreBackendCommons::DiscardedJobLogger`:
186
- job class (or `Mailer#action`), queue, jid and error, never the arguments.
187
-
188
- Why zero: in a Thecore app in production, mail jobs carrying a whole PDF in their arguments
189
- failed with a permanent SMTP error and were retried for weeks, then kept in the Dead Set. Redis
190
- grew to 23 GB until the host's OOM killer put it in a restart loop and no job ran for three days
191
- (`docs/adr/0002-no-job-retries-failures-logged.md`).
192
-
193
- ### Changing the defaults on an installation
194
-
195
- Set these in the environment of both the `backend` and the `worker` containers. On an
196
- installation deployed by `thecore_devcontainer` that is the target's
197
- `vendor/deploytargets/<provider>/<customer>.env`, which reaches both containers through their
198
- `env_file` (`thecore_devcontainer` ADR 0002); on a hand-written compose, its `environment:`.
199
-
200
- | Variable | Unset or blank | Accepted values | Effect |
201
- | --- | --- | --- | --- |
202
- | `THECORE_JOB_RETRIES` | `0` (no retries) | a whole number >= 0 | how many times Sidekiq retries a failed job, app-wide |
203
- | `THECORE_FAILED_JOBS_KEPT` | `1` | a whole number >= 1 | how many failed jobs stay in the Redis `failed` set |
204
-
205
- Any other value (`yes`, `-1`, `1.5`, ...) stops the app at boot with an error naming the
206
- variable: a typo never silently turns retries back on. With retries above 0, a job that uses
207
- them all ends in Sidekiq's Dead Set, which is capped by count and age but not by size.
208
-
209
- ### Changing it for one job
210
-
211
- A job class sets its own retry count with Sidekiq's option, which wins over the app-wide value
212
- in both directions (it works on ActiveJob classes and mailers' jobs alike):
213
-
214
- ```ruby
215
- class SyncInventoryJob < ApplicationJob
216
- sidekiq_options retry: 3 # or retry: false when THECORE_JOB_RETRIES is above 0
217
- end
218
- ```
219
-
220
- **Don't use ActiveJob's `retry_on` for this.** It retries independently of Sidekiq: on failure
221
- ActiveJob enqueues a new copy of the job, arguments included, whatever `THECORE_JOB_RETRIES`
222
- says, and the copies never show up as Sidekiq retries.
223
-
224
- ### Logging failures somewhere else too
225
-
226
- Add your own Sidekiq death handler next to the default one; both run:
227
-
228
- ```ruby
229
- # config/initializers/sidekiq.rb in the app
230
- Sidekiq.configure_server do |config|
231
- config.death_handlers << ->(job, exception) { MyErrorLog.record(job["jid"], exception) }
232
- end
233
- ```
180
+ Every app using this gem runs its background jobs as `thecore_background_jobs` (`~> 3.1`, a
181
+ dependency of this gem) sets them up: Solid Queue in production, no retries by default
182
+ (`THECORE_JOB_RETRIES`, `THECORE_FAILED_JOBS_KEPT`), one log line per failed job without its
183
+ arguments, and `ThecoreBackgroundJobs.on_job_failure(handler)` to record failures elsewhere too.
184
+ See that gem's README. Until 3.14 this gem configured Sidekiq for it
185
+ (`docs/adr/0001-active-job-queue-adapter-is-framework-imposed.md`,
186
+ `docs/adr/0002-no-job-retries-failures-logged.md`, both amended by thecore ADR 0017).
234
187
 
235
188
  ---
236
189
 
@@ -3,11 +3,7 @@ Rails.application.configure do
3
3
  Integer.send(:include, FixnumConcern)
4
4
  String.send(:include, StringConcern)
5
5
  ApplicationCable::Connection.send(:include, CableConnectionConcern)
6
- # ApplicationRecord.send(:include, ApplicationRecordConcern)
7
- ApplicationRecord.subclasses.each do |d|
8
- d.send(:include, BaseApplicationRecordConcern) unless d.name.start_with?("ActiveStorage::", "ActionText::")
9
- end
10
-
11
- User.send(:include, ThecoreBackendCommonsUserConcern)
6
+ # BaseApplicationRecordConcern and ThecoreBackendCommonsUserConcern are applied to each model as
7
+ # it is defined: see ThecoreBackendCommons::Engine ("thecore_backend_commons.default_modules").
12
8
  end
13
9
  end
@@ -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).
@@ -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).
@@ -83,10 +83,16 @@ module ThecoreBackendCommons
83
83
  # Called automatically by `InheritedHook` -- only call directly from
84
84
  # application/test code that needs to (re-)apply defaults to a class
85
85
  # defined before the registry/hook was set up.
86
- def apply_to(klass)
86
+ #
87
+ # +only+ restricts it to one registered module: for a class defined
88
+ # before the hook existed, a gem applies its own module after the class
89
+ # body without re-running other gems' defaults there (one that assigns
90
+ # json_attrs without merging would wipe the model's own).
91
+ def apply_to(klass, only: nil)
87
92
  return klass if klass.abstract_class?
88
93
 
89
94
  entries.each do |entry|
95
+ next if only && !entry.mod.equal?(only)
90
96
  next unless entry.applies_to.call(klass)
91
97
  next if klass.include?(entry.mod)
92
98
 
@@ -1,4 +1,34 @@
1
1
  module ThecoreBackendCommons
2
2
  class Engine < ::Rails::Engine
3
+ # BaseApplicationRecordConcern and ThecoreBackendCommonsUserConcern reach every model as it is
4
+ # defined, through DefaultModuleRegistry, so the app behaves the same with or without eager
5
+ # loading (GitHub #7; until 3.13 a post-boot scan only reached the models already loaded).
6
+ #
7
+ # Registered from a to_prepare block added after every railtie's config/initializers
8
+ # (after: :load_config_initializers matches all of them): to_prepare blocks run in the order they
9
+ # were added, so these two are registered, and therefore included, after the other gems' default
10
+ # modules. That matters because some of them set json_attrs without merging (model_driven_api's
11
+ # ModelDrivenApiDefaultJsonAttrs: `{ except: [] }`), while BaseApplicationRecordConcern merges its
12
+ # methods into whatever is there. A model's own concern, in its class body, still comes last.
13
+ #
14
+ # A model already defined when the hook arrives (one required explicitly during boot, as the
15
+ # dummy app does with User) gets these two modules at once, after its body, as before 3.14,
16
+ # through DefaultModuleRegistry.apply_to(only:), parents before children (an STI child must
17
+ # inherit the module, not include it a second time).
18
+ OWN_DEFAULT_MODULES = {
19
+ "BaseApplicationRecordConcern" => ->(klass) { klass.name.present? && !klass.name.start_with?("ActiveStorage::", "ActionText::") },
20
+ "ThecoreBackendCommonsUserConcern" => ->(klass) { klass.name == "User" },
21
+ }.freeze
22
+
23
+ initializer "thecore_backend_commons.default_modules", after: :load_config_initializers do |app|
24
+ app.config.to_prepare do
25
+ already_defined = ApplicationRecord.descendants.sort_by { |klass| klass.ancestors.size }
26
+ OWN_DEFAULT_MODULES.each do |module_name, applies_to|
27
+ mod = module_name.constantize
28
+ ThecoreBackendCommons::DefaultModuleRegistry.register(mod, applies_to: applies_to)
29
+ already_defined.each { |klass| ThecoreBackendCommons::DefaultModuleRegistry.apply_to(klass, only: mod) }
30
+ end
31
+ end
32
+ end
3
33
  end
4
34
  end
@@ -1,3 +1,3 @@
1
1
  module ThecoreBackendCommons
2
- VERSION = "3.13.1".freeze
2
+ VERSION = "3.15.0".freeze
3
3
  end
@@ -20,8 +20,6 @@ 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
22
  require "thecore_backend_commons/activity_log"
23
- require "thecore_backend_commons/discarded_job_logger"
24
- require "thecore_backend_commons/job_failure_policy"
25
23
 
26
24
  module ThecoreBackendCommons
27
25
  # 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.13.1
4
+ version: 3.15.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,14 @@ 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
41
  - !ruby/object:Gem::Dependency
42
42
  name: ostruct
43
43
  requirement: !ruby/object:Gem::Requirement
@@ -242,7 +242,6 @@ files:
242
242
  - config/initializers/default_module_registry.rb
243
243
  - config/initializers/extension_nil.rb
244
244
  - config/initializers/extension_string.rb
245
- - config/initializers/sidekiq.rb
246
245
  - config/locales/en.devise.custom.yml
247
246
  - config/locales/en.yml
248
247
  - config/locales/it.devise.custom.yml
@@ -257,9 +256,7 @@ files:
257
256
  - lib/thecore_backend_commons.rb
258
257
  - lib/thecore_backend_commons/activity_log.rb
259
258
  - lib/thecore_backend_commons/default_module_registry.rb
260
- - lib/thecore_backend_commons/discarded_job_logger.rb
261
259
  - lib/thecore_backend_commons/engine.rb
262
- - lib/thecore_backend_commons/job_failure_policy.rb
263
260
  - lib/thecore_backend_commons/push_notification_service.rb
264
261
  - lib/thecore_backend_commons/smtp_config.rb
265
262
  - 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