Commit Graph

9068 Commits

Author SHA1 Message Date
Jean Boussier 151ba1ab0c DescendantsTracker: fix the TruffleRuby implementation
Ref: https://github.com/rails/rails/pull/43723

This was pretty much a typo...
2021-12-09 09:38:49 +01:00
Jonathan Hefner 1a4e27e216 Fix assert_called_with with empty args array
`[].all?(Array)` returns `true`.  Thus when an empty `args` array was
passed to `assert_called_with`, `expect` would not be called on the mock
object, eventually leading to an "unmocked method" error.

This commit allows an empty array to be passed as `args`, which behaves
the same as passing `[[]]`.
2021-12-08 12:15:36 -06:00
sampatbadhe 0055b72a3b replace duplicate entries of to_formatted_s with to_fs 2021-12-08 12:31:05 +05:30
Rafael Mendonça França de065c9f7e
Merge pull request #42919 from jcmfernandes/avoid-double-string-split-message-verifier
Avoid unnecessary double string split in ActiveSupport::MessageVerifier#verified
2021-12-07 11:23:19 -05:00
Rafael Mendonça França 83d85b2207
Start Rails 7.1 development 2021-12-07 15:52:30 +00:00
Joao Fernandes 02eda1b950 Extract components from signed messages by calculating their indexes
ActiveSupport::MessageVerifier#verified is causing signed_message to be
split twice: first inside #valid_message? and then inside #verified.
This is ultimately unnecessary.

We can avoid String#split all together by calculating the indexes of the
data and the digest in the payload. This increases the resistance of the
solution against ill-formed payloads that don't include the separator.
2021-12-07 09:44:53 +00:00
Ryuta Kamizono 30ff804ca7 Fix typo in the rdoc for `Pathname#existence` [ci-skip] 2021-12-07 16:01:41 +09:00
Richard Macklin 4954317aac Fix test name in PathnameExistenceTest
This was likely a copy-paste typo from
00fb4e6bbd/activesupport/test/core_ext/object/blank_test.rb (L32)
introduced in 1a14bcb8cd
2021-12-06 21:45:00 -08:00
Rafael Mendonça França 83a3df0136
Add config to disable the `to_s` override in Ruby core classes
This will allow users to take advantage early of Ruby 3.1 optimization
in string interpolation.
2021-12-06 19:22:07 +00:00
Rafael Mendonça França 9aae3ae183
Alias to_formatted_s as to_fs 2021-12-06 19:22:06 +00:00
Rafael Mendonça França 58ecdd0cf2
Deprecate `to_s(format)` in favor of `to_formatted_s(format)`
Ruby 3.1 is going to introduce an [optimization][] that makes interpolation
of some types of objects faster, unless there is a custom implementation
of to_s. Since Rails is overriding `to_s` for a bunch of core classes it
means that this optimization in Rails applications will be disabled.

In order to allow Rails applications to use this optimization in
the future we are deprecating all the reasons we override `to_s` in
those core classes in favor of using `to_formatted_s`.

[optimization]: b08dacfea3
2021-12-06 19:22:05 +00:00
Rafael Mendonça França c2e12e0191
Use `to_formatted_s(:db)` instead of `to_s(:db)` internally
Ruby 3.1 introduced an optimization to string interpolation for some
core classes in b08dacfea3.

But since we override `to_s` in some of those core classes to add behavior
like `to_s(:db)`, all Rails applications will not be able to take advantage
of that improvement.

Since we can use the `to_formatted_s` alias for the Rails specific behavior
it is best for us to deprecate the `to_s` core extension and allow Rails
applications to get the proformace improvement.

This commit starts removing all the `to_s(:db)` calls inside the framework
so we can deprecate the core extension in the next commit.
2021-12-06 19:22:04 +00:00
Sam Bostock 7007d1b2b5
Document ActiveSupport::Testing::Deprecation
Co-authored-by: Sam Jordan <sam.jordan@shopify.com>
Co-authored-by: Sam Bostock <sam.bostock@shopify.com>
2021-12-03 15:04:25 -05:00
Jonathan Hefner 763c219539 Fix flakey test in notifications_test.rb
Example failure: https://buildkite.com/rails/rails/builds/82905#80d6c6ec-943d-4ba3-b360-1ef6c4aa5d89/1012-1022

The test designates the event end time as 0.01 seconds (i.e. 10
milliseconds) after the start time.  It then asserts that the event
duration is 10 ± 0.0001 milliseconds.  This sometimes fails due to
floating point precision errors.

This commit changes the assertion to instead check that the duration is
within 1% of the expected value.
2021-11-30 14:03:32 -06:00
Timo Schilling 115c562927
Fix type in Pathname#existence documentation 2021-11-30 08:37:28 +01:00
Rafael Mendonça França be3ed75ec7
Merge pull request #43718 from esparta/fix_race_conditions_test_cache_v
ActiveSupport::Cache, fix race conditions on test/cache - part V
2021-11-29 16:51:21 -05:00
Rafael Mendonça França 223ba6f81d
Fix documentation of Pathname#existence 2021-11-29 21:49:31 +00:00
Alex Ghiculescu 5046d1cce9 Wrap ActionController::TestCase with Rails executor
Update actionpack/lib/action_controller/test_case.rb

Co-authored-by: Jean Boussier <jean.boussier@gmail.com>
2021-11-26 17:54:47 -06:00
Rafael Mendonça França c14cb9150e
Revert "Add missing `require "active_support` in XmlMini"
This reverts commit 0181f0edd5.

Users of Active Support should always require the top level file of
the framework before requiring anything else inside it, so we don't
need to require that top level file here.
2021-11-26 19:21:10 +00:00
Vipul A M bd04720c7f
Merge pull request #43731 from shunyama/fix/tiny-typo-fix
[skip ci] Fixed tiny typo
2021-11-26 11:23:07 -05:00
shunyama 4b89f16ad4 [skip ci] fix tiny typo 2021-11-27 00:57:08 +09:00
Jean Boussier 0181f0edd5 Add missing `require "active_support` in XmlMini 2021-11-26 11:51:57 +01:00
Espartaco Palma c677229b2c
ActiveSupport::Cache, Part V - change clear override for MemCached 2021-11-26 01:17:31 -08:00
Rafael Mendonça França 33157e2173
Merge pull request #43726 from timoschilling/add-pathname-existence
add Pathname#existence
2021-11-25 15:48:32 -05:00
Rafael Mendonça França df35d93adf
Merge pull request #43719 from kmcphillips/error-reporter-fallback-callable
Require the ErrorReporter#handle fallback to be a callable
2021-11-25 14:32:15 -05:00
Rafael Mendonça França 100ad4341d
Merge pull request #43324 from ghiculescu/patch-5
Be more explicit about lack of inheritance on `thread_mattr_accessor`
2021-11-25 13:46:36 -05:00
Kevin McPhillips d0eeee03be Require the ErrorReporter#handle fallback to be a callable 2021-11-25 13:33:51 -05:00
Jean Boussier ff5e909b63 DescendantsTracker: fix the TruffleRuby branch 2021-11-25 18:09:44 +01:00
Timo Schilling 1a14bcb8cd add Pathname#existence 2021-11-25 16:51:58 +00:00
Jean Boussier 617c8357f6
Merge pull request #43723 from Shopify/descendant-tracker-3.1
Fix DescendantTracker.clear on Ruby 3.1
2021-11-25 17:50:46 +01:00
Jean Boussier cb82f5f0a4 Fix DescendantTracker.clear on Ruby 3.1
Previously I assumed it was useless, however I was wrong.

The method is called by the reloader to give the illusion that
the GC is precise. Meaning a class that will be unloaded is
immediately made invisible without waiting for it to be garbage collected.

This is easy to do up to Ruby 3.0 because `DescendantTracker` keeps
a map of all tracked classes.

However on 3.1 we need to use the inverse strategy, we keep a WeakMap
of all the classes we cleared, and we filter the return value of `descendants`
and `subclasses`.

Since `clear` is private API and is only used when reloading is enabled,
to reduce the performance impact in production mode, we entirely remove
this behavior when `config.cache_classes` is enabled.
2021-11-25 17:32:52 +01:00
Jean Boussier eea74ec211 AS::Callbacks specialize call templates for better performance
By doing so we avoid a lot of extra work.

```
            baseline:  4092604.4 i/s
          opt-method:   693204.7 i/s - 5.90x  (± 0.00) slower
              method:   614761.0 i/s - 6.66x  (± 0.00) slower
```

Baseline is calling `run_callbacks` with no callbacks registered.

Full benchmark: https://gist.github.com/casperisfine/837a7a665c6b232dadcf980d73694748
2021-11-25 14:03:46 +01:00
Espartaco Palma 2bf5e6618e
ActiveSupport::Cache, fix race conditions on test/cache - part V 2021-11-24 16:51:29 -08:00
Rafael Mendonça França 4799156cc3
Merge pull request #43704 from esparta/fix_race_conditions_test_cache_iv
ActiveSupport::Cache, fix race conditions on test/cache - part IV
2021-11-24 17:02:38 -05:00
Jean Boussier 2fbe5d7f29
Merge pull request #43711 from Shopify/thread-accessor-isolated-state
Use IsolatedExecutionState in `thread_mattr_accessor`
2021-11-24 23:01:10 +01:00
Jean Boussier b9098f6ec4
Merge pull request #43712 from Shopify/as-cache-error-handling
Report Memcached and Redis cache errors to Rails.error
2021-11-24 23:00:57 +01:00
Kevin McPhillips ac751edab3
Allow a fallback value to be returned from Rails.error.handle 2021-11-24 11:19:00 -05:00
Jean Boussier c63da2005e Report Memcached and Redis cache errors to Rails.error
Ref: https://github.com/rails/rails/issues/43472

We swallow these exceptions because it makes sense for a cache to
fallback to a cache miss in case of transcient failures.

However there's value in reporting these to the application
owners so that they can be alerted that something undesirable happened.
2021-11-24 12:25:03 +01:00
Jean Boussier 2bf5974287 Use IsolatedExecutionState in `thread_mattr_accessor`
Ref: https://github.com/rails/rails/pull/43596

This allow users to declare wether their unit of work is isolated
by fibers or by threads.
2021-11-24 11:41:16 +01:00
Espartaco Palma 36c5e7f7ab
ActiveSupport::Cache, fix race conditions on test/cache - part IV 2021-11-23 15:23:41 -08:00
Rafael Mendonça França c496ae8441
Merge pull request #43693 from esparta/fix_race_conditions_test_cache_iii
ActiveSupport::Cache - fix more race conditions on test/cache - part III
2021-11-23 15:33:34 -05:00
Jean Boussier 359240dff6 Use native Class#subclasses if available
Followup: https://github.com/rails/rails/pull/43548
Ref: https://github.com/ruby/ruby/pull/5045

That feature was accepted by Matz and should make it to Ruby 3.1.

We use feature testing just in case it wouldn't and also to better
support alternative implementations.
2021-11-23 09:32:28 +01:00
Espartaco Palma f57d1111de
ActiveSupport, fix more race conditions on test/cache - part III 2021-11-22 15:32:59 -08:00
Benoit Daloze 302b966375 Improve check for GC.stat(:total_allocated_objects)
* This works whether the Ruby implementation raises or uses a Hash with
  a default of 0 to represent unknown keys (like TruffleRuby) and so
  this is more portable.
* Also avoids an extra exception on JRuby.
2021-11-22 14:51:43 +01:00
Jean Boussier b4eae47bbe Eliminate internal uses of `PerThreadRegistry` and deprecate it
This module has been soft deprecated for a long time, but since
it was used internally it wasn't throwing deprecation warnings.

Now we can throw a deprecation warning.
2021-11-22 09:53:16 +01:00
Jean Boussier ce3a73abe7
Merge pull request #43671 from Shopify/as-use-isolated-state
Use `IsolatedExecutionState` across Active Support
2021-11-22 09:50:46 +01:00
willnet 11601dafaa
[ci skip]Add a missing double quote on code comments 2021-11-22 10:39:20 +09:00
Rafael Mendonça França f47204802a
Merge pull request #43675 from esparta/fix_race_conditions_test_cache_ii
ActiveSupport, fix more race conditions on test/cache - part II
2021-11-19 16:21:41 -07:00
Rafael Mendonça França fd0ec3f4f6
Remove deprecate `ActiveSupport::Multibyte::Unicode.default_normalization_form` 2021-11-19 23:15:57 +00:00
Espartaco Palma efed47e8b6
ActiveSupport, fix more race conditions on test/cache - part II 2021-11-19 14:59:16 -08:00
Rafael Mendonça França 59eb7edb68
Remove deprecated support to use `Range#include?` to check the inclusion of a value in a date time range is deprecated 2021-11-19 21:43:24 +00:00
Rafael Mendonça França 93c35945cf
Remove deprecated `URI.parser` 2021-11-19 21:43:23 +00:00
Rafael Mendonça França 82313145df
Remove deprecated `config.active_support.use_sha1_digests` 2021-11-19 21:43:22 +00:00
Jean Boussier 5a985451f9
Merge pull request #43625 from Shopify/error-reporting-api
Rails standardized error reporting interface
2021-11-19 16:29:29 +01:00
Jean Boussier 0ea374c81f Use `IsolatedExecutionState` across Active Support
Ref: https://github.com/rails/rails/pull/43596

This allow users to declare wether their unit of work is isolated by
fibers or by threads.

`PerThreadRegistry` and `thread_mattr_accessor` were intentionally left
out as they require documentation change. I'll submit them in separate
pull requests.
2021-11-19 09:58:15 +01:00
Espartaco Palma 71d8483826
Fix some race conditions on ActiveSupport cache test 2021-11-18 12:59:04 -08:00
Jean Boussier 192a652cb6
Merge pull request #43596 from Shopify/active-support-local-store
Introduce `ActiveSupport::IsolatedExecutionState` for internal use
2021-11-18 15:55:36 +01:00
Jean Boussier 540d2f41f6 Introduce ActiveSupport::IsolatedExecutionState for internal use
Many places in Active Support and Rails in general use `Thread.current#[]`
to store "request (or job) local data". This often cause problems with
`Enumerator` because it runs in a different fiber.

On the other hand, some places migrated to `Thread#thread_variable_get`
which cause issues with fiber based servers (`falcon`).

Based on this, I believe the isolation level should be an application
configuration.

For backward compatibility it could ship with `:fiber` isolation as a default
but longer term :thread would make more sense as it would work fine for
all deployment targets except falcon.

Ref: https://github.com/rails/rails/pull/38905
Ref: https://github.com/rails/rails/pull/39428
Ref: https://github.com/rails/rails/pull/34495
(and possibly many others)
2021-11-18 15:55:15 +01:00
Rafael Mendonça França d4ad739454
Remove deprecated `Rails.config.action_view.raise_on_missing_translations` 2021-11-17 21:51:16 +00:00
Jean Boussier 8cbc19d86b Rails standardized error reporting interface
Fix: https://github.com/rails/rails/issues/43472

The reporter is held by the executor, but the `Rails` module provides a
nicer `Rails.error` shortcut.

For ease of use, two block based specialized methods are exposed.

`handle`, which swallow errors and forward them to the subscribers:

```ruby
Rails.error.handle do
  1 + '1' # raises TypeError
end
1 + 1 # This will be executed
```

`record`, which forward the errors to the subscribes but let it
continue rewinding the call stack:

```ruby
Rails.error.record do
  1 + '1' # raises TypeError
end
1 + 1 # This won't be executed.
```

For cases where the blocked based API isn't suitable, the lower level
`report` method can be used:

```ruby
Rails.error.report(error, handled: true / false)
```
2021-11-16 13:34:53 +01:00
Rafael Mendonça França 4e06e83736
Merge pull request #43652 from esparta/remove_warnings_test_cache_stores
ActiveSupport: Remove warnings on test/cache/stores
2021-11-15 15:38:50 -07:00
Espartaco Palma 5606c35697
Remove warnings on AS/test/cache/stores
Since the test are skipped when Redis | Memcache are not reacheable two
instance variables are not initialized properly but used on teardown
blocks, having warnings about undeclared variables:

- instance variable @cache not initialized (redis cache store)
- instance variable @_stores not initialized (memcache store)
2021-11-15 14:27:03 -08:00
Rafael Mendonça França a134eebea5
Invert conditional
This avoid a method call and also is easier to read.
2021-11-15 22:19:38 +00:00
Sean Doyle 8dc27b59c5 Support `Object#with_options` without a block
When the block argument is omitted, the decorated Object instance is returned:

```ruby
 # app/helpers/my_styled_helpers.rb
 module MyStyledHelpers
   def styled
     with_options style: "color: red;"
   end
 end

 # styled.link_to "I'm red", "/"
 # #=> <a href="/" style="color: red;">I'm red</a>

 # styled.button_tag "I'm red too!"
 # #=> <button style="color: red;">I'm red too!</button>
```
2021-11-15 17:00:36 -05:00
Rafael Mendonça França 1fde031e89 Fix gemspec 2021-11-15 21:06:21 +00:00
Rafael Mendonça França 9195b7fd0a
Require MFA to release rails 2021-11-15 20:37:42 +00:00
Nikita Vasilevsky 2a00c89a7d
Enable Lint/DuplicateMethods rubocop rule 2021-11-15 13:51:28 -05:00
Jean Boussier 1b0dca131b Improve compatibility with `date` versions `3.2.1`, `3.1.2`, `3.0.2` and `2.0.1`
Historically `Date._iso8601(nil)` returns `{}`.

But in these versions it raises a `TypeError` changing the exception type
of `ActiveSupport::TimeZone#iso8601(nil)`, which may break some applications.
2021-11-15 12:04:55 +01:00
Jean Boussier 6bad959565 Extract ActiveSupport::ExecutionContext out of ActiveRecord::QueryLogs
I'm working on a standardized error reporting interface
(https://github.com/rails/rails/issues/43472) and it has the same need
for a `context` than Active Record's query logs.

Just like query logs, when reporting an error you want to know what the
current controller or job is, etc.

So by extracting it we can allow both API to use the same store.
2021-11-10 09:36:02 +01:00
Jean Boussier acd462fc23 Only wrap subscriber exceptions if there is more than one
Ref: https://github.com/rails/rails/pull/43282
Ref: https://github.com/rails/rails/pull/43561

It can be legitimate for subscriber to want to bubble up some exception
to the caller, so wrapping it change the exception class which might break
the calling code expecting a specific error.

We can minimize this by only using InstrumentationSubscriberError
when more than one subscriber raised.
2021-11-02 16:47:37 +01:00
Jean Boussier bf33510d86 Optimize CurrentAttributes method generation
The bulk of the optimization is to generate code rather than use
`define_method` with a closure.

```
Warming up --------------------------------------
            original   207.468k i/100ms
      code-generator   340.849k i/100ms
Calculating -------------------------------------
            original      2.127M (± 1.1%) i/s -     10.788M in   5.073860s
      code-generator      3.426M (± 0.9%) i/s -     17.383M in   5.073965s

Comparison:
      code-generator:  3426241.0 i/s
            original:  2126539.2 i/s - 1.61x  (± 0.00) slower
```

```ruby

require 'benchmark/ips'
require 'active_support/all'

class Original < ActiveSupport::CurrentAttributes
  attribute :foo
end

class CodeGen < ActiveSupport::CurrentAttributes
  class << self
    def attribute(*names)
      ActiveSupport::CodeGenerator.batch(generated_attribute_methods, __FILE__, __LINE__) do |owner|
        names.each do |name|
          owner.define_cached_method(name, namespace: :current_attributes) do |batch|
            batch <<
              "def #{name}" <<
              "attributes[:#{name}]" <<
              "end"
          end
          owner.define_cached_method("#{name}=", namespace: :current_attributes) do |batch|
            batch <<
              "def #{name}=(value)" <<
              "attributes[:#{name}] = value" <<
              "end"
          end
        end
      end

      ActiveSupport::CodeGenerator.batch(singleton_class, __FILE__, __LINE__) do |owner|
        names.each do |name|
          owner.define_cached_method(name, namespace: :current_attributes_delegation) do |batch|
            batch <<
              "def #{name}" <<
              "instance.#{name}" <<
              "end"
          end
          owner.define_cached_method("#{name}=", namespace: :current_attributes_delegation) do |batch|
            batch <<
              "def #{name}=(value)" <<
              "instance.#{name} = value" <<
              "end"
          end
        end
      end
    end
  end
  attribute :foo
end

Benchmark.ips do |x|
  x.report('original') { Original.foo }
  x.report('code-generator') { CodeGen.foo }
  x.compare!
end
```
2021-11-02 15:52:25 +01:00
Rafael Mendonça França 33ca392317
Avoid adding new method to `ActiveSupport`.
We don't need this delegation and can be setting directly to the right
object.

Also document the new configuration.
2021-11-02 01:12:32 +00:00
Ryuta Kamizono 96df650d9e
Merge pull request #43552 from Thornolf/inflector_underscore_regression_after_optimization
Fix (Inflector::Methods#underscore): small regression
2021-10-29 17:59:42 +09:00
Ryuta Kamizono 479e4c19a2 Fix markup in activesupport/CHANGELOG.md
[ci-skip]
2021-10-29 17:20:38 +09:00
Jean Boussier 7b5096947e Call Executor#wrap around each test
It's `Rails.application.executor.wrap` that is responsible for
clearing request/job local state such as `CurrentAttributes`.

Instead of including an ad hoc helper to clear `CurrentAttributes` it's
better to run the executor so we properly clear other states as well.

However it means all executor hooks now need to be re-entrant.
2021-10-28 15:18:29 +02:00
Jean Boussier ffae3bd8d6 Refactor DescendantsTracker to leverage native Class#descendants on Ruby 3.1 2021-10-28 10:46:42 +02:00
Jean Boussier d2734111dd
Revert "Call Executor#wrap around each test" 2021-10-28 00:35:07 +02:00
Quentin "Thornolf" Baudet 86faeb8386
Fix (Inflector::Methods#underscore): small regression 2021-10-28 00:25:09 +02:00
Jean Boussier d8936b755d Use the native `Class#descendants` if available
Ruby 3.1 is very likely to ship with a native implementation
of `Class#descendants` that doesn't need to iterate over
ObjectSpace. So we should use it if available.

Ref: https://bugs.ruby-lang.org/issues/14394
Ref: https://github.com/ruby/ruby/pull/4974
2021-10-27 14:53:45 +02:00
Jean Boussier 265c1e9f2d Call Executor#wrap around each test
It's `Rails.application.executor.wrap` that is responsible for
clearing request/job local state such as `CurrentAttributes`.

Instead of including an ad hoc helper to clear `CurrentAttributes` it's
better to run the executor so we properly clear other states as well.
2021-10-27 12:46:22 +02:00
Jean Boussier b3df08355a Skip RedisCacheStore test if no Redis server is running
MemCacheStore tests have been doing the same for a while.

As an extra safety, if `ENV["CI"]` is set, we always run
the tests.
2021-10-27 10:10:30 +02:00
Jean Boussier fe4ead7fc6 Ruby 3.1: decorate Process._fork if available
Ref: https://bugs.ruby-lang.org/issues/17795

This new API makes it much easier to correctly
intercept forks.
2021-10-25 15:29:12 +02:00
Erich Soares Machado cdf537ad0a
Addresses `Digest::UUID` RFC 4122 compatibility.
Updates the `Digest::UUID.uuid_from_hash` to return the correct UUID values
for namespace IDs that are different from the ones provided on `Digest::UUID`.

- The new behavior will be enabled by setting the
  `config.active_support.use_rfc4122_namespaced_uuids` option to `true`
  and is the default for new apps.

- The old behavior is the default for upgraded apps and will output a
  deprecation warning every time a value that is different than one of
  the constants defined on the `Digest::UUID` extension is used as the
  namespace ID.

Fixes #37681.
2021-10-23 10:16:16 -04:00
Jean Boussier 9636b4da36 Feature test GC.stat(:total_allocated_objects) rather than check for JRuby 2021-10-21 10:07:00 +02:00
Jean Boussier 81d0dc90be Use Process.clock_gettime unit argument to save some floating point multiplications 2021-10-21 10:05:32 +02:00
Jean Boussier 7ddfa93ba5 Stop using `Concurrent.monotonic_time`
Unless you are on a Ruby older than 2.3 (or some very old JRuby)
`Concurrent.monotonic_time` is just `Process.clock_gettime(Process::CLOCK_MONOTONIC)`.
So might as well skip the extra method call, and more importantly
it allows in many cases to pass the scale as second argument and save some
floating point multiplication.
2021-10-21 09:31:25 +02:00
Rafael Mendonça França 6a1ee787a0
Disable Dalli compression on the protocal level
We were disabling in the write level but since Dalli 3 the protocol
is compressing by default and ignoring the option at write level.
2021-10-14 17:49:49 +00:00
Yasuo Honda 370ef3d5b6 Use `Dalli::Protocol::Binary` instead of deprecated `Dalli::Server`
This commit addresses these failures with Dalli 3.0.1, which loses Dalli 2.x support.

```ruby
$ bin/test test/cache/stores/mem_cache_store_test.rb -n test_fetch_read_failure_returns_nil
Run options: -n test_fetch_read_failure_returns_nil --seed 2554

F

Failure:
OptimizedMemCacheStoreTest#test_fetch_read_failure_returns_nil [/home/yahonda/src/github.com/rails/rails/activesupport/test/cache/behaviors/failure_safety_behavior.rb:8]:
Expected "bar" to be nil.

bin/test test/cache/behaviors/failure_safety_behavior.rb:4

F

Failure:
MemCacheStoreTest#test_fetch_read_failure_returns_nil [/home/yahonda/src/github.com/rails/rails/activesupport/test/cache/behaviors/failure_safety_behavior.rb:8]:
Expected "bar" to be nil.

bin/test test/cache/behaviors/failure_safety_behavior.rb:4

Finished in 0.010229s, 195.5206 runs/s, 195.5206 assertions/s.
2 runs, 2 assertions, 2 failures, 0 errors, 0 skips
$
```
2021-10-14 17:49:44 +00:00
Yasuo Honda 2f8db2db0e Use `Dalli::Protocol::Binary` to address deprecataion warning
```ruby
Dalli::Server is deprecated, use Dalli::Protocol::Binary instead
```

Refer https://github.com/petergoldstein/dalli/pull/760
2021-10-14 17:49:37 +00:00
Rafael Mendonça França 28bc4f87fd
Extract common behavior of html safe translation to a module
This module will be a private module in Active Support, this way
if we need to change the behavior of translate in controllers or
views don't forget to change in the other one.
2021-10-12 18:03:46 +00:00
Alex Ghiculescu 616f302d66 Be more explicit about lack of inheritance on `thread_mattr_accessor`
Co-authored-by: Petrik de Heus <petrik@deheus.net>
2021-10-12 15:49:30 +02:00
Rafael Mendonça França 5e1a039a1d
Merge pull request #43282 from theojulienne/guard-against-instrumentation-exceptions
Guard against subscriber exceptions in ActiveSupport::Notifications
2021-10-08 13:23:37 -04:00
John Hawthorn 3c9a76dd4f
Merge pull request #43382 from jhawthorn/notification_match_cleanup
Simplify ActiveSupport::Notification matching
2021-10-06 10:10:05 -07:00
Daniel Colson ccb3cb573b
Replace ableist language
The word "Crazy" has long been associated with mental illness. While
there may be other dictionary definitions, it's difficult for some of us
to separate the word from the stigmatization, gaslighting, and bullying
that often comes along with it.

This commit replaces instances of the word with various alternatives. I
find most of these more focused and descriptive than what we had before.
2021-10-05 22:27:09 -04:00
John Hawthorn 3c1bec407c Move AllMessages behaviour into Matcher
This avoids needing to delegate all methods to the actual subscriber
class and we can deal just with the message name matching behaviour.
2021-10-05 14:43:28 -07:00
John Hawthorn daa78a6d9e Remove "matches?" from AS::N subscriber classes
This was not being used anymore
2021-10-05 14:43:11 -07:00
Theo Julienne 8f76cca3d9 Ensure we guard against all exceptions, not just StandardError 2021-10-04 23:07:50 +00:00
Jonathan Hefner 414e8dea59
Merge pull request #43334 from federicoaldunate/add-that-raises-exception-message-encryptor
Update MessageEncryptor guide to show that an exception is raised [ci-skip]
2021-09-29 12:15:59 -05:00
Federico Aldunate 4860d8534b Update MessageEncryptor guide to show that an exception is raised
swap order
2021-09-29 14:06:58 -03:00
Étienne Barrié 5bf6073614 Revert "Fix ForkTracker on ruby <= 2.5.3"
This reverts commit 332a2909d4.
2021-09-24 13:02:05 +02:00
Étienne Barrié d63add1039 Don't override Object#fork in Ruby 3.0
It's no longer necessary with https://bugs.ruby-lang.org/issues/9573
2021-09-24 13:01:55 +02:00
Theo Julienne 8afcbb6f21 Guard against subscriber exceptions in ActiveSupport::Notifications 2021-09-22 02:07:45 +00:00
Rafael Mendonça França a76344ffc5
Merge PR #42475 2021-09-20 18:03:57 -04:00
Rafael Mendonça França d177551c30
Preparing for 7.0.0.alpha2 release 2021-09-15 18:22:51 -04:00
Rafael Mendonça França 9b7be48212
Preparing for 7.0.0.alpha1 release 2021-09-15 17:55:08 -04:00
Jean Boussier c91c266872 Enable `Style/ExplicitBlockArgument` cop
This reduce the stack size which is beneficial for
exceptions performance.

See: https://gist.github.com/byroot/cb3bcadcc3701c2518d002fb8d3a4e7a

However the cop is unsafe because it might change the block arity,
so it can run into some false positives.
2021-09-05 17:06:19 +02:00
Jean Boussier 5fbc750840 Get rid of `mattr_accessor` in `ActiveSupport::Dependencies`
Since the module isn't included anywhere and is purely static
there iss no point using `mattr_accessor`, which define instance
accessors and other extra overhead.

Regular `attr_accessor` does the job just fine.
2021-09-05 12:42:23 +02:00
Xavier Noria 1d6355f6e1 Move Zeitwerk to railties
Active Support should not know about Rails. Once classic has been removed,
AS should get anything it needs from the application as usual.
2021-09-05 03:37:46 +02:00
Xavier Noria 5346dfdf74 Move the default autoloaders inflector to railties 2021-09-04 20:44:39 +02:00
Xavier Noria e0d77f124d Formatting 2021-09-04 09:32:04 +02:00
Xavier Noria d9fc52cc7b Update the AS CHANGELOG 2021-09-04 09:30:08 +02:00
Xavier Noria 556572ac19 Fixes typo 2021-09-04 07:56:57 +02:00
Xavier Noria 7ce6f45ae3 Revise private docs of AS::Dependencies 2021-09-02 19:41:21 +02:00
Xavier Noria 174ee7bb60 Depends on Zeitwerk 2.5.0.beta3 2021-09-01 15:31:04 +02:00
Jean Boussier a3cfa4a20d
Merge pull request #43098 from flavorjones/flavorjones-number-to-currency-detect-parse-failures
Fix number_to_currency regression in handling "-0.0"
2021-08-26 15:45:13 +02:00
Mike Dalessio 81175fb98a
Fix number_to_currency regression in handling "-0.0"
simplifying the method along the way.

This regressed in #42581 and is related to prior work in #39350 and #37865.
2021-08-25 22:30:12 -04:00
Mike Dalessio 900ce92c9d
Avoid use of exceptions to detect invalid floats
Use Kernel::Float(..., exceptions:false) instead of a rescue block in
ActionView::Helpers::NumberHelper and
ActiveSupport::NumberHelper::NumberConverter to slightly improve
performance.

Also remove documentation that incorrectly states
ActiveSupport::NumberHelper supports the `raise:` option.
2021-08-25 21:44:45 -04:00
Nicholas Stuart aabc27fe15
Move `assert_raise` into behavior classes 2021-08-24 12:06:53 -07:00
Nicholas Stuart 2c15e00a2c
Address PR comments. 2021-08-24 10:09:07 -07:00
Nicholas Stuart 2e097e86d2
Add test case 2021-08-24 09:36:55 -07:00
Nicholas Stuart c83e690311
Revert the `raise_errors` param and Removed rescue block from `ActiveSupport::Cache::RedisCacheStore#handle_exception` 2021-08-24 09:33:08 -07:00
Nicholas Stuart 22b000bde8
Update CHANGELOG.md 2021-08-23 20:29:18 -07:00
Nicholas Stuart 7f1129277b
init commit 2021-08-23 17:35:00 -07:00
Xavier Noria fddfaa08af Move AS::Dependencies.clear to the main file 2021-08-23 17:49:48 +02:00
Xavier Noria a8fa8b0ef8 Delete AS::Dependencies.verbose=
As documented, the public way to trace autoloading activity
is Rails.autoloaders.log!
2021-08-23 10:05:13 +02:00
Xavier Noria 61d7f33f67 Delete AS::Dependencies.autoloaded_constants 2021-08-23 10:05:13 +02:00
Xavier Noria 86a55dbe0f Delete private constant AS::Dependencies::UNBOUND_METHOD_MODULE_NAME 2021-08-23 10:05:13 +02:00
Xavier Noria 651737f059 AS::Dependencies no longer extends self
AS::Dependencies is not meant to be used as a mixin. I guess extend self
made sense time ago.
2021-08-23 10:05:13 +02:00
Xavier Noria 7bbe1f4bce Delete the classic version of AS::Dependencies.clear 2021-08-23 10:05:08 +02:00
Xavier Noria 08481be86e Delete the classic version of AS::Dependencies.autoloaded_constants 2021-08-23 09:20:52 +02:00
Xavier Noria b99b14a1cf Delete AS::Dependencies.autoloaded? 2021-08-23 09:04:35 +02:00
Xavier Noria 39a7658b61 Deletes spurious spaces 2021-08-23 00:49:18 +02:00
Xavier Noria 340b39ea31 Remove autoloading logic from AS::DescendantsTracker
The descendants tracker is a generic tracker that you can use anywhere.
In particular, outside Rails applications.

Should provide API to clear only a subset of classes, but in my view
should know nothing about autoloading. That is a concern of client code.
2021-08-23 00:24:26 +02:00
Xavier Noria 6a2a824e85 Namespace fixture classes in this test
This test was defining classes with common names like `Parent` or `Child` in the
top-level namespace. Better to have them below a custom one.
2021-08-22 22:08:28 +02:00
Xavier Noria fc9a179033 Depends on Zeitwerk 2.5.0.beta2 2021-08-21 01:23:21 +02:00
Xavier Noria 38e82daee8 Delete AS::Dependencies.safe_constantize 2021-08-20 17:51:05 +02:00
Xavier Noria 3e3504bdaa Delete AS::Dependencies.constantize 2021-08-20 09:47:22 +02:00
Xavier Noria d4ab55e901 Delete orphan requires in AS::Dependencies 2021-08-19 00:14:06 +02:00
Xavier Noria c640deef99 Delete AS::Dependencies.explicitly_unloadable_constants 2021-08-18 23:26:29 +02:00
Xavier Noria fb9a33d602 Delete AS::Dependencies.mechanism 2021-08-18 23:26:25 +02:00
Xavier Noria 0f2d2ba87d Delete AS::Dependencies.load? 2021-08-18 23:26:20 +02:00
Xavier Noria ed1571ddc0 Delete AS::Dependencies.autoloadable_module? 2021-08-18 23:26:16 +02:00
Xavier Noria c1a89b57df Delete AS::Dependencies.load_once_path? 2021-08-18 23:26:12 +02:00
Xavier Noria bde4b04323 Delete AS::Dependencies.uninitialized_constant 2021-08-18 23:26:07 +02:00
Xavier Noria bc2cd69c22 Delete AS::Dependencies::WatchStack 2021-08-18 23:26:03 +02:00
Xavier Noria dd5d632a6b Delete AS::Dependencies.constant_watch_stack 2021-08-18 23:25:59 +02:00
Xavier Noria e5cdd54525 Delete AS::Dependencies.will_autoload? 2021-08-18 23:25:54 +02:00
Xavier Noria 2105d1ed3e Delete AS::Dependencies.mark_for_unload 2021-08-18 23:25:49 +02:00
Xavier Noria 7788697797 Delete AS::Dependencies.loading 2021-08-18 23:25:49 +02:00
Xavier Noria 4ba449aafb Delete AS::Dependencies.loaded 2021-08-18 23:25:49 +02:00
Xavier Noria 46576a4555 Delete AS::Dependencies.history 2021-08-18 23:25:49 +02:00
Xavier Noria 5102fdeacf Delete AS::Dependencies.remove_constant 2021-08-18 23:25:49 +02:00
Xavier Noria 2b31655493 Delete AS::Dependencies.new_constants_in 2021-08-18 23:25:49 +02:00
Xavier Noria e24ae73021 Delete AS::Dependencies.qualified_name_for 2021-08-18 23:25:49 +02:00
Xavier Noria 1b92154ff4 Delete AS::Dependencies.autoload_module! 2021-08-18 23:25:49 +02:00
Xavier Noria 7b2223be8b Delete AS::Dependencies.remove_unloadable_constants! 2021-08-18 23:25:49 +02:00
Xavier Noria d3ffcafb14 Delete AS::Dependencies.load_file 2021-08-18 23:25:44 +02:00
Xavier Noria 805067e6d2 Delete AS::Dependencies.loadable_constants_for_path 2021-08-18 23:25:35 +02:00
Xavier Noria 98381b7ba2 Delete AS::Dependencies.require_or_load 2021-08-18 22:44:59 +02:00
Xavier Noria 1343a3a67d Delete AS::Dependencies.load_missing_constant 2021-08-18 22:43:52 +02:00
Xavier Noria 27262897c7 Delete AS::Dependencies::Loadable 2021-08-18 22:31:07 +02:00
Xavier Noria a7a217212b Delete AS::Dependencies::ModuleConstMissing 2021-08-18 22:27:55 +02:00
Xavier Noria 627037fa8b Delete AS::Dependencies.depend_on 2021-08-18 22:24:08 +02:00
Xavier Noria 2306a8e645 Setup the once autoloader on bootstrap 2021-08-17 05:23:51 +02:00
Xavier Noria bbe74a8c97 Delete AS::Dependencies.unhook! 2021-08-17 05:18:22 +02:00
Xavier Noria 2a22b4c53b Delete AS::Dependencies.hook! 2021-08-17 05:18:22 +02:00
Kasper Timm Hansen 0965b67bf7
Merge pull request #42967 from p8/main
Clean up missing dots in changelogs
2021-08-13 02:24:40 +02:00
Ryuta Kamizono ee98178ea5 Fix rubocop offences
https://github.com/rails/rails/runs/3294975031
2021-08-11 13:53:39 +09:00
Xavier Noria 3401139842 Move require_dependencies suite to the one for dependencies
require_dependency has now one single definition, and its implementation
does not depend on Zeitwerk or even applications. It only depends on
having some autoload paths in place.

We can test that in the AS test suite.
2021-08-11 00:12:53 +02:00
Xavier Noria 6983a89c72 Deletes the classic implementation of require_dependency 2021-08-09 17:26:51 +02:00
Xavier Noria 36e716cdc1 Implement support for before_remove_const in zeitwek mode
This needs Zeitwerk 2.5 for the on_unload hook.
2021-08-09 13:15:10 +02:00
Petrik de Heus 6828334555
Add missing dots to changelogs 2021-08-07 18:53:10 +02:00
Ryuta Kamizono 685caef33b Fix "warning: instance variable @parallelized not initialized" 2021-08-07 13:04:31 +09:00
Ryuta Kamizono e0ce6bbd6a Fix kwargs delegation in `PerThreadRegistry#method_missing`
Without this fix, the delegation will raise the ArgumentError:

```
% bin/test -w test/per_thread_registry_test.rb
Running 1 tests in a single process (parallelization threshold is 50)
Run options: --seed 23992

# Running:

E

Error:
PerThreadRegistryTest#test_method_missing_with_kwargs:
ArgumentError: wrong number of arguments (given 1, expected 0; required keyword: x)
    /Users/kamipo/src/github.com/rails/rails/activesupport/test/per_thread_registry_test.rb:9:in `foo'
    /Users/kamipo/src/github.com/rails/rails/activesupport/lib/active_support/per_thread_registry.rb:55:in `foo'
    /Users/kamipo/src/github.com/rails/rails/activesupport/lib/active_support/per_thread_registry.rb:57:in `method_missing'
    /Users/kamipo/src/github.com/rails/rails/activesupport/test/per_thread_registry_test.rb:13:in `test_method_missing_with_kwargs'
```
2021-08-06 18:24:02 +09:00
Ryuta Kamizono 6e7e8128d2 Fix markup in RDoc [ci skip] 2021-08-06 16:24:03 +09:00
Rafael França 207da352dd
Merge pull request #42913 from ghiculescu/deprecation-opt-out
Allow entirely opting out of deprecation warnings
2021-08-05 23:52:41 -04:00
Xavier Noria 6068639775 Upgrades Zeitwerk to 2.5.0.beta 2021-08-04 09:43:06 +02:00
Rafael Mendonça França 18707ab17f
Standardize nodoc comments 2021-07-29 21:18:07 +00:00
Alex Ghiculescu ea3185ebdd Allow entirely opting out of deprecation warnings
Previously if you did `app.config.active_support.deprecation = :silence`, some work would still be done on each call to `ActiveSupport::Deprecation.warn`. Specifically [checking the backtrace](12372c5482/activesupport/lib/active_support/deprecation/reporting.rb (L21)), generating the [deprecation warning](12372c5482/activesupport/lib/active_support/deprecation/reporting.rb (L22)), and [checking if the warning is disallowed](12372c5482/activesupport/lib/active_support/deprecation/reporting.rb (L23)).

In very hot paths, this could cause performance issues. This PR lets you turn off deprecation reporting entirely for a specific environment.

```ruby
config.active_support.report_deprecations = false
```

^ so has the same outcome as:

```ruby
config.active_support.deprecation = :silence
config.active_support.disallowed_deprecation = :silence
```

But it will short circuit [here](12372c5482/activesupport/lib/active_support/deprecation/reporting.rb (L19)).
2021-07-29 16:00:02 -05:00
Rafael França 12372c5482
Merge pull request #42905 from dgorelik/patch-1
s/octopus/cactus
2021-07-29 14:26:10 -04:00
Daniel Gorelik b802b54092
s/octopus/cactus 2021-07-29 08:17:06 -04:00
Jean Boussier 5d1e8884bd Fix MemCacheStore local cache duplication
Followup: https://github.com/rails/rails/pull/42833

The previous fix wasn't working in practice because the LocalCache
middleware doesn't use `with_local_cache` but directly set a
regular `LocalStore` instance in the registry.

So instead we redecorate it on every access. It may cause some extra
allocations, but since it only happens in 6.1 mode, it's not as
much of a concern.
2021-07-29 11:57:59 +02:00
Rafael França 80585daf2d
Merge pull request #42358 from ghiculescu/credentials-backwards-compat
Credentials: support hash style access in more cases
2021-07-28 21:09:43 -04:00
Rafael França 646e9d3d62
Merge pull request #42030 from diegotoral/configurable-default-option
Add support for defining default values as option for ActiveSupport::Configurable accessors
2021-07-28 20:30:21 -04:00
Jean Boussier f7cedc6b43
Merge pull request #42626 from Shopify/as-file-store-remove-local-cache
Remove LocalCache in FileStore
2021-07-28 17:06:56 +02:00
Jean Boussier 8a22369071
Merge pull request #42870 from pedrosnk/pm/import_of_active_support_test_assertions
assert_changes works on including ActiveSupport::Assertions class
2021-07-28 15:59:21 +02:00
Santiago Bartesaghi 92f12d77c4 Fix :nodoc: [ci skip] 2021-07-27 16:52:58 -03:00
Jorge Manrubia a29884d733 Remove mechanism to disable test parallelization when runnin gonly 1 test
#42761 made the old system of disable paralleling testing when
only one test file was included obsolete.
2021-07-27 10:33:09 -07:00
Étienne Barrié 39b382cf78 Remove leak when using CurrentAttributes in thread variables
The test for CurrentAttributes using thread-local variables leaks
an instance in Thread.current.

Usually instances are reset in the test helper but the objects remain:
activesupport/lib/active_support/current_attributes/test_helper.rb:11

In this situation we use clear_all to make sure we don't leave instances
behind when the configuration is changed.
2021-07-27 11:50:37 +02:00
Pedro Medeiros f6ffdcfcff assert_changes works on including Assertions class
assert_not_equal is an alias for refute_equal that is defined only on
the class ActiveSupport::TestCase. This commit ensures
ActiveSupport::Testing::Assertions#assert_changes doesn't depends on
ActiveSupport::TestCase to work.
2021-07-25 14:27:18 -04:00
Dino Maric a6c0e84f02 FIX: Setting remove_deprecated_time_with_zone_name in new framework defaults
Setting `remove_deprecated_time_with_zone_name` didn't work because
the value is checked in a framework initialiser, which runs before application initialiser.

This PR moves the setting inside the `config.after_initialize` block.
I've also added 2 tests for this behaviour.

Fixes #42820
2021-07-24 16:47:49 +02:00
Jean Boussier 5db5de5341
Merge pull request #42845 from jonathanhefner/fix-descendants-garbage-collection-test
Isolate descendants garbage collection test
2021-07-23 18:11:33 +02:00
Ryuta Kamizono 93b16e71f9
Merge pull request #42842 from jonathanhefner/fix-file-update-checker-test-double-waits
Avoid double wait in EventedFileUpdateCheckerTest
2021-07-23 12:34:01 +09:00
Jonathan Hefner 60fc40ea58 Isolate descendants garbage collection test
This prevents the test from being affected by Ruby-internal thread
locals set by other tests.

Example failure: https://buildkite.com/rails/rails/builds/79505#cb261462-8e40-4adc-99fc-81708a473cc6/1076-1085

Co-authored-by: Jean Boussier <jean.boussier@gmail.com>
2021-07-22 14:32:22 -05:00
Jonathan Hefner 86c732a606 Avoid double wait in EventedFileUpdateCheckerTest
Waiting after touching the file system is a concern of
`EventedFileUpdateCheckerTest`.  Therefore, only call `wait` inside
`EventedFileUpdateCheckerTest`.  This avoids calling `wait` an extra
time when calling `touch`.

Before:

    $ bin/test test/evented_file_update_checker_test.rb test/file_update_checker_test.rb

    Finished in 43.357019s, 0.9918 runs/s, 2.5371 assertions/s.
    43 runs, 110 assertions, 0 failures, 0 errors, 0 skips

After:

    $ bin/test test/evented_file_update_checker_test.rb test/file_update_checker_test.rb

    Finished in 34.351007s, 1.2518 runs/s, 3.2022 assertions/s.
    43 runs, 110 assertions, 0 failures, 0 errors, 0 skips
2021-07-22 12:29:27 -05:00
Jean Boussier fcacb93295
Merge pull request #39428 from etiennebarrie/thread-local-current-attributes
Allow using thread variables for CurrentAttributes instances
2021-07-22 16:40:10 +02:00
Jean Boussier 733774f35e MemCacheStore: Properly duplicate local cache values in 6.1 mode
Followup: https://github.com/rails/rails/pull/42649

I found a way to preserve the `deep_dup` behavior in 6.1 mode.
So we no longer need to skip these tests.
2021-07-21 17:55:09 +02:00
Étienne Barrié 8195cd5f99 Allow using thread variables for CurrentAttributes instances 2021-07-21 16:53:32 +02:00
Eugene Kenny 8dab534ca8
Merge pull request #42827 from jdufresne/author-id
Correct Inflector.humanize keep_id_suffix argument docs
2021-07-21 08:56:35 +01:00
Jean Boussier 17db990ed0
Merge pull request #42649 from Shopify/local-cache-refactor
Refactor local cache to avoid serializing entries twice
2021-07-21 08:56:09 +02:00
Jon Dufresne a4a8478801 Correct Inflector.humanize keep_id_suffix argument docs
The "id" word is not capitalized. Observe:

    irb(main):001:0> ActiveSupport::Inflector.humanize('author_id', keep_id_suffix: true)
    => "Author id"
2021-07-20 20:42:27 -07:00
Ryuta Kamizono e50b0e3ab3 Fixup CHANGELOGs [ci skip] 2021-07-21 10:08:08 +09:00
Ryuta Kamizono a206aecedf chore: Use `e.g.` which is the more used spelling
```
% git grep -i '\be\.g\.' | wc -l
290
```
2021-07-21 09:17:54 +09:00
Diego Toral 99525cb6ff ActiveSupport::Configurable default value option
Sometimes it can be very strange or long have to define default values
for config accessors as blocks, specially when config is a simple value
like 1, true, :symbol. This commit adds the ability to specify those
values by just passing a ` default` option when defining the accessor.

It also makes config accessor's interface similar to other Rails
methods like `class_attribute`, which also has the instance_reader,
instance_writer and instance_accessor options.
2021-07-20 10:36:58 -03:00
Jean Boussier 81b70f13ca Refactor local cache to avoid serializing entries repeatedly
Since `LocalCache` store needs to call `dup_value!` on write (to avoid
mutating the original value), we end up serializing each cache entry twice.
Once for the local cache, and a second time for the actual backend. So the
write performance is quite bad.

So the idea here is than rather than to store `Entry` instances, the local
cache now instead store whatever payload was sent to the real backend.

This means that we now only serialize the `Entry` once, and if the cache
store was configured with an optimized coder, it will be used for the local
cache too.

Current Rails `main`:
```
fetch in rails 7.0.0.alpha
                         52.423  (± 1.9%) i/s -    265.000  in   5.058089s
write in rails 7.0.0.alpha
                         12.412  (± 0.0%) i/s -     62.000  in   5.005204s
```

Current Rails `main` with local cache disabled:
```
fetch in rails 7.0.0.alpha
                         52.047  (± 3.8%) i/s -    260.000  in   5.000138s
write in rails 7.0.0.alpha
                         25.513  (± 0.0%) i/s -    128.000  in   5.018942s
```

This branch:
```
fetch in rails 7.0.0.alpha
                         50.259  (± 4.0%) i/s -    255.000  in   5.085783s
write in rails 7.0.0.alpha
                         25.805  (± 0.0%) i/s -    130.000  in   5.039486s
```

So essentially, the local cache overhead on write has been eliminated.

Benchmark:
```
require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"
  gem "rails", github: "rails/rails", branch: "main"
  gem 'benchmark-ips'
  gem "mysql2"
  gem "pry"
end

require "active_record"
require "logger"
require 'benchmark/ips'

ActiveRecord::Base.establish_connection(adapter: "mysql2", database: 'test', host: 'localhost', user: 'root', password: '')
ActiveRecord::Base.logger = Logger.new(nil)

ActiveRecord::Schema.define do
  create_table :users, force: true do |t|
    t.string :name
    t.integer :phone
  end
end

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end

class User < ApplicationRecord
end

1_000.times { |i| User.create(name: "test #{i}") }

cache = ActiveSupport::Cache::FileStore.new(ARGV[0] || '/tmp/rails-cache')
cache.clear
unless ENV['DISABLE_LOCAL_CACHE']
  ActiveSupport::Cache::Strategy::LocalCache::LocalCacheRegistry.set_cache_for(
    cache.middleware.local_cache_key,
    ActiveSupport::Cache::Strategy::LocalCache::LocalStore.new
  )
end

h = {}
h = User.last(Integer(ENV.fetch('SIZE', 1000))).each { |u| h[u.id] = u }

puts "== Benchmarking read_entry code and write_entry code in rails #{Rails.version}"

Benchmark.ips do |x|
  x.report("fetch in rails #{Rails.version}") {
    cache.fetch('key', compress: false) { h }
  }

  x.report("write in rails #{Rails.version}") {
    cache.write("key+#{Time.now}", h, compress: false) { h }
  }
end
```
2021-07-20 12:59:08 +02:00
Eileen M. Uchitelle 4a906cbbbc
Merge pull request #42796 from schneems/schneems/faster-try-yet-again
Fix NilClass#try and NilClass#try! performance slowdown in Ruby 2.7+
2021-07-16 14:51:15 -04:00
Jorge Manrubia 675d9ffb6e
Add an option threshold: to .parallel() setup method (#42789)
This adds an additional method to configure the parallelization
threshold. Before this, the only way of configuring the threshold was
via an option:

```
config.active_support.test_parallelization_minimum_number_of_tests
```
2021-07-16 11:32:23 -07:00
Richard Schneeman bb513b8541 Fix performance slowdown in Ruby 2.7+
In #34068 I introduced code that improved performance in Ruby 2.5. But recently @Jeremyevans pointed out that it made code slower in 2.7+ which Rails targets https://gist.github.com/jeremyevans/40675ac1f69b4ac405d3c6ba060cdd35. Here's the twitter thread https://twitter.com/jeremyevans0/status/1414731600693108737.

This change essentially reverts #34068

```
$ cat scratch.rb
class FooCurrent
  def try(_method_name = nil, *)
    nil
  end
end

class FooUpdated
  def try(*)
    nil
  end
end

require 'benchmark/ips'

foo_updated = FooUpdated.new
foo_current = FooCurrent.new

Benchmark.ips do |x|
  x.report("updated") { foo_updated.try(:anything) }
  x.report("current") { foo_current.try(:anything) }
  x.compare!
end

$ ruby -v
ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-darwin19]
$ ruby scratch.rb
Warming up --------------------------------------
             updated   854.461k i/100ms
             current   687.183k i/100ms
Calculating -------------------------------------
             updated      8.418M (± 2.1%) i/s -     42.723M in   5.077403s
             current      6.619M (± 9.6%) i/s -     32.985M in   5.048477s

Comparison:
             updated:  8418315.3 i/s
             current:  6619074.1 i/s - 1.27x  (± 0.00) slower
```
2021-07-16 11:08:32 -05:00
Akshay Mohite b3aacdc512 Used already defined method parallelized? and fixed semantics of the test name.
- Related to https://github.com/rails/rails/pull/42761
- Used `parallelized?` method instead of calling a method `should_parallelize?` to figure out if parallezation is enabled.
- Fixed semantics of the test name corresponding to the change
- Updated test name as per the code review suggestion.
2021-07-14 22:35:21 +05:30
Eileen M. Uchitelle c18339791f
Merge pull request #42761 from basecamp/smart-parallel-tests
Parallelize tests only when there are enough to justify the parallelization overhead
2021-07-14 10:18:24 -04:00
Jorge Manrubia ecc5afed30 Parallelize tests only when overhead is justified
Parallelizing tests has a cost in terms of database setup and fixture
loading. This change makes Rails disable parallelization when the number
of tests is below a configurable threshold.

When running tests in parallel each process gets its own database
instance. On each execution, each process will update each database
schema (if needed) and load all the fixtures. This can be very expensive
for non trivial datasets.

As an example, for HEY, when running a single file with 18 tests,
running tests in parallel in my box adds an overhead of 13 seconds
versus not parallelizing them. Of course parallelizing is totally worthy
when there are many tests to run, but not when running just a few tests.

The threshold is configurable via
config.active_support.test_parallelization_minimum_number_of_tests,
which is 30 50 by default.

This also adds some tracing to know how tests are being executed:

When in parallel:

```
Running 2829 tests in parallel in 8 processes
```

When not in parallel:

```
Running 15 tests in a single process (parallelization threshold is 30)
```
2021-07-14 13:36:28 +02:00
John Hawthorn 2379bc5d2a Avoid using class var in LoggerThreadSafeLevel
Class variables are confusing and can be slow. In this case we were just
using the class variable as a global to implement Fiber-local variables
on top of. Instead we can use Thread#[] directly to store our Fiber-locals.
2021-07-12 10:18:02 -07:00
Alex Ghiculescu 4b42beb3b8 Log a warning when assertions are incorrectly nested and errors are raised
Follow up to https://github.com/rails/rails/pull/37313

- Adds regression tests
- Logs a warning in cases where assertions are nested in a way that's likely to be confusing
2021-07-12 10:37:43 -05:00
Ryuta Kamizono db767c332a Fix CI failure caused by error_highlight gem
Since https://github.com/ruby/ruby/pull/4586, error.message includes the
line of code that raised.

https://bugs.ruby-lang.org/issues/17930
2021-07-02 17:44:10 +09:00
Yasuo Honda 08299d1ba4 Address `NameError: uninitialized constant Digest::UUID::OpenSSL`
Follow up #41722

This commit addresses these Active Support test errors.

```ruby
% ruby -v
ruby 3.0.1p64 (2021-04-05 revision 0fb782ee38) [x86_64-darwin21]
% cd activesupport
% bundle exec ruby -w test/core_ext/digest/uuid_test.rb
Run options: --seed 50574

E

Error:
DigestUUIDExt#test_v3_uuids:
NameError: uninitialized constant Digest::UUID::OpenSSL
    /Users/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/core_ext/digest/uuid.rb:40:in `uuid_v3'
    test/core_ext/digest/uuid_test.rb:8:in `test_v3_uuids'

rails test test/core_ext/digest/uuid_test.rb:7

F

Failure:
DigestUUIDExt#test_invalid_hash_class [test/core_ext/digest/uuid_test.rb:22]:
[ArgumentError] exception expected, not
Class: <NameError>
Message: <"uninitialized constant DigestUUIDExt::OpenSSL">
---Backtrace---
test/core_ext/digest/uuid_test.rb:23:in `block in test_invalid_hash_class'
---------------

rails test test/core_ext/digest/uuid_test.rb:21

E

Error:
DigestUUIDExt#test_v5_uuids:
NameError: uninitialized constant Digest::UUID::OpenSSL
    /Users/yahonda/src/github.com/rails/rails/activesupport/lib/active_support/core_ext/digest/uuid.rb:45:in `uuid_v5'
    test/core_ext/digest/uuid_test.rb:15:in `test_v5_uuids'

rails test test/core_ext/digest/uuid_test.rb:14

Finished in 0.006611s, 453.7891 runs/s, 151.2630 assertions/s.
3 runs, 1 assertions, 1 failures, 2 errors, 0 skips
%
```
2021-07-02 10:06:42 +09:00
Dirkjan Bussink 0523532a3c
Always use OpenSSL constants for Digest operations
As also previously discussed in
https://github.com/rails/rails/pull/40770#issuecomment-748347066, this
moves the usage of Digest constants to always use the OpenSSL version of
those Digest implementations.
2021-06-30 13:57:54 +02:00
Steve Laing 21ca4a49ac Add support for ordinal date values in AS::TimeZone.iso8601
Date._iso8601 will attempt to parse certain args as ordinal dates eg. '21087' => 2021-03-28. Add ActiveSupport::TimeZone.iso8601 support for these
ordinal values to be consistent with Date._iso8601 and raise ArgumentError where the day of year is invalid.
2021-06-28 18:00:51 +01:00
Jean Boussier a2148b9d0a Remove LocalCache in FileStore 2021-06-28 15:22:07 +02:00
Alex Ghiculescu d132095ce7 `Time#change` should pass the `zone` property through if it's set 2021-06-25 11:49:54 -05:00
Jean Boussier 99913f6a5e Report async queries lock wait duration
This duration is very important to figure wether the `load_async`
actually improved something.
2021-06-25 13:59:47 +02:00
Guillermo Iguaran acee501edd
Merge pull request #42532 from zzak/zzak/35035
Allow any module or class to be converted to JSON in a simple way
2021-06-23 22:47:04 -07:00
Mike Dalessio 8489a5e114
Fix number_to_currency to use negative format when rounding 0.5
Previously this function would fail to apply the negative format
correctly if the value being rounded was 0.5 exactly (modulo
precision).

This fixes the logic to use `>= 0.5` instead of `> 0.5`
2021-06-23 12:55:16 -04:00
Mike Dalessio 9a05443d1e
Fix number_to_currency to avoid negative format when displaying zero.
This is a more-complete version of the fix in #37865 which originally
addressed #37846.

Also see context at #39350 with respect to alternate input formats.

Closes #42577
2021-06-23 12:54:44 -04:00
Alex Ghiculescu 25b47c25ba Optimized Cache::Entry should support old dalli_store values
Same bug as https://github.com/rails/rails/pull/42559, but a very different fix due to https://github.com/rails/rails/pull/42025. To recap, the issue:

- While using the `dalli_store`, you set any value in the Rails cache with no expiry.
- You change to the `mem_cache_store`.
- You upgrade to Rails 7.
- You try to read the same cache key you set in step 1, and it crashes on read.

https://github.com/rails/rails/pull/42025 was backward compatible with entries written using the `mem_cache_store`, but *not* the `dalli_store` which did not use `ActiveSupport::Cache::Entry`. This PR attempts to fix that.
2021-06-22 15:17:33 -05:00
Alex Ghiculescu 9a87546bd3 Test cleanup for cache store tests 2021-06-22 13:48:06 -05:00
Zachary Scott f186a00aac Add CHANGELOG for #42532 2021-06-18 20:54:43 +09:00
Tyler Rick cb40ae38c1 Allow any module or class to be converted to JSON in a simple way 2021-06-18 14:06:50 +09:00
Oli Peate a8ae85a331 Support clearing acronyms in ActiveSupport::Inflector::Inflections
Previously calling ActiveSupport::Inflector::Inflections.clear(:acronyms)
reset the instance variable to an empty Array, which is not the correct
default. The next time an acronym is added a TypeError is thrown.
2021-06-15 10:22:19 +01:00
sho shimohata 443169784d add space 2021-06-15 12:55:20 +09:00
Rafael França 0bd2bd3d71
Merge pull request #42405 from c960657/time-travel
Allow travel/travel_to blocks after standalone travel/travel_to
2021-06-08 18:49:41 -04:00
Christian Schmidt 7e6dd6b21f Travel back after block 2021-06-08 16:54:42 +02:00
Jean Boussier 517a2803f4 Improve `AS::TimeWithZone` error message on `NoMethodError`
Because we re-use the message generated by the `Time` instance
it causes `TimeWithZone` to still pretend being a `Time` instance
even with `remove_deprecated_time_with_zone_name = true` which is
confusing.
2021-06-08 10:03:34 +02:00
Rafael França 5c09cfd96f
Merge pull request #42370 from sunny/better-error-message-when-encrypted-file-key-is-blank
Raise missing key error when master key env variable is blank
2021-06-07 16:59:35 -04:00
Christian Schmidt a829bb7639 Allow travel blocks after standalone travelt 2021-06-05 15:58:41 +02:00
Sunny Ripert afdc2af9e2 Raise missing key error when master key env var is blank 2021-06-03 16:21:53 +02:00
Alex Ghiculescu c87e16bf0e Credentials: support hash style access in more cases
Fixes https://github.com/rails/rails/issues/42351

https://github.com/rails/rails/pull/42106 broke if you wanted to treat a set of nested credentials as a hash. This PR fixes it.
2021-06-02 10:34:22 -05:00
Adam Hess 6489ee522a Always use %f formatter for ISO8601 durations since they can't be in scientific notation
Manually formats the seconds. This avoids using the %g formatter which can convert large numbers or very small fractions into scientific notation which is not supported by iso8601
2021-06-02 07:09:16 -07:00
Zachary Scott bfdb634034 NumberToRoundedConverter should handle -Float::INFINITY
cc https://github.com/rails/rails/pull/42316#issuecomment-851606043
2021-06-01 16:08:21 +09:00
Petrik 99fd13d967 Fix typo in ActionableError [skip ci]
"let's" is short for "let us".
2021-05-31 20:44:00 +02:00
Andrew White 2af84159e8
Merge pull request #42316 from federicoaldunate/fix_decimal_to_float_converter 2021-05-31 12:07:29 +01:00
Federico Aldunate bd6277d568 Use BigDecimal compatible operation in NumberToRoundedConverter 2021-05-30 10:29:09 -03:00
Santiago Bartesaghi d49724c496 Minor docs style fix [ci skip] 2021-05-26 17:16:26 -03:00
Eugene Kenny 42a71d1428
Merge pull request #42277 from georgeclaghorn/assert-no-changes-from
Add from: option to ActiveSupport::TestCase#assert_no_changes
2021-05-24 21:25:57 +01:00
Maxime Garcia a69e725124
Minor: Typo in ActiveSupport::SecureCompareRotator doc 2021-05-24 15:02:27 +02:00
George Claghorn 21aea0db55 Add from: option to ActiveSupport::TestCase#assert_no_changes
Permit asserting on the initial value that is expected not to change.
2021-05-23 16:26:52 -04:00
Jean Boussier 1e56b1d115 Fix ruby-master test suite (Psych 4.0.0)
Ruby master ships with Psych 4.0.0 which makes `YAML.load`
defaults to safe mode (https://github.com/ruby/psych/pull/487).

However since these YAML files are trustworthy sources
we can parse them with `unsafe_load`.
2021-05-19 14:21:21 +02:00
Jean Boussier 22737122a2 Fix compatibility with Psych 4
Psych 4 load in safe mode by default:
https://github.com/ruby/psych/pull/487

So aliases need to be explicitly allowed.
2021-05-18 10:03:42 +02:00
Michael Lutaaya eb43eb689c
[ci skip] Fix typo in MessageVerifier docs 2021-05-14 07:10:29 -04:00
jithindasad 153f4fe284 update tests for SecureRandom.base58 method 2021-05-12 01:05:22 +05:30
Ryuta Kamizono 908ccc194e
Merge pull request #42173 from okuramasafumi/improve-docs-of-activesupport-callbacks
[ci-skip] Improve doc for `ActiveSupport::Callbacks.skip_callback`
2021-05-08 18:39:29 +09:00