farce 0.4.1-x86-linux-gnu → 0.6.0-x86-linux-gnu

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +98 -2
  3. data/README.md +3 -1
  4. data/docs/benchmarks.md +37 -21
  5. data/docs/compatibility.md +13 -0
  6. data/docs/data-structures.md +37 -0
  7. data/docs/integrations.md +1 -0
  8. data/docs/introduction.md +19 -0
  9. data/docs/modes.md +2 -0
  10. data/docs/scheduling.md +35 -3
  11. data/docs/scopes.md +3 -1
  12. data/docs/shims.md +53 -0
  13. data/docs/utilities.md +32 -0
  14. data/docs/variants.md +9 -0
  15. data/ext/farce/atom.c +23 -7
  16. data/ext/farce/containers.h +3 -0
  17. data/ext/farce/counter.c +4 -6
  18. data/ext/farce/depend +3 -1
  19. data/ext/farce/extconf.rb +19 -14
  20. data/ext/farce/farce.c +110 -3
  21. data/ext/farce/map.c +15 -7
  22. data/ext/farce/priority_queue.c +46 -1
  23. data/ext/farce/queue.c +141 -7
  24. data/ext/farce/trie.c +140 -72
  25. data/ext/farce/trie_search.h +114 -0
  26. data/ext/farce/vector.c +53 -21
  27. data/ext/farce/weak_map.c +16 -11
  28. data/ext/farce/weak_references.h +23 -0
  29. data/ext/java/org/farce/FiberScheduler.java +8 -6
  30. data/ext/java/org/farce/PriorityQueue.java +18 -2
  31. data/lib/farce/abstract/atom.rb +5 -1
  32. data/lib/farce/abstract/concurrent_map.rb +122 -0
  33. data/lib/farce/abstract/counter.rb +36 -1
  34. data/lib/farce/abstract/executor.rb +30 -7
  35. data/lib/farce/abstract/flag.rb +12 -0
  36. data/lib/farce/abstract/molecule.rb +14 -14
  37. data/lib/farce/abstract/pool.rb +158 -47
  38. data/lib/farce/abstract/priority_queue.rb +1 -1
  39. data/lib/farce/abstract/publisher.rb +189 -0
  40. data/lib/farce/abstract/queue.rb +29 -3
  41. data/lib/farce/abstract/scheduler.rb +41 -14
  42. data/lib/farce/abstract/timer_queue.rb +3 -3
  43. data/lib/farce/abstract/vector.rb +3 -1
  44. data/lib/farce/atom.rb +15 -2
  45. data/lib/farce/clock.rb +20 -7
  46. data/lib/farce/concurrent/count_down_latch.rb +37 -0
  47. data/lib/farce/concurrent/cyclic_barrier.rb +109 -0
  48. data/lib/farce/concurrent/event.rb +60 -0
  49. data/lib/farce/concurrent/fiber_local_var.rb +31 -0
  50. data/lib/farce/concurrent/local_var.rb +65 -0
  51. data/lib/farce/concurrent/thread_local_var.rb +28 -0
  52. data/lib/farce/concurrent/tuple.rb +74 -0
  53. data/lib/farce/concurrent.rb +50 -0
  54. data/lib/farce/config.rb +112 -2
  55. data/lib/farce/counter.rb +5 -15
  56. data/lib/farce/deduper.rb +12 -4
  57. data/lib/farce/engine/jruby/fiber_scheduler.jar +0 -0
  58. data/lib/farce/engine/jruby/map.rb +8 -6
  59. data/lib/farce/engine/jruby/signal.rb +2 -2
  60. data/lib/farce/engine/jvm/counter.rb +0 -2
  61. data/lib/farce/engine/jvm/farce.jar +0 -0
  62. data/lib/farce/engine/jvm/priority_queue.rb +14 -4
  63. data/lib/farce/engine/ruby/3.4/farce.so +0 -0
  64. data/lib/farce/engine/ruby/4.0/farce.so +0 -0
  65. data/lib/farce/engine/ruby/shared/parallel_scheduler.rb +9 -1
  66. data/lib/farce/engine/ruby/shared/ractor_selector.rb +1 -4
  67. data/lib/farce/engine/ruby/shared/weak_cache_mirror.rb +56 -0
  68. data/lib/farce/engine/ruby/shared/weak_map.rb +9 -12
  69. data/lib/farce/engine/ruby.rb +5 -1
  70. data/lib/farce/engine/shared/exchanger.rb +2 -2
  71. data/lib/farce/engine/shared/queue.rb +43 -5
  72. data/lib/farce/engine/shared/ractor_selector.rb +1 -1
  73. data/lib/farce/engine/shared/strict_map.rb +5 -0
  74. data/lib/farce/engine/shared/trie/ignore_case.rb +136 -0
  75. data/lib/farce/engine/shared/trie.rb +14 -1
  76. data/lib/farce/engine/shared/trie_builder.rb +19 -8
  77. data/lib/farce/engine/shared/unshared_atom.rb +1 -1
  78. data/lib/farce/engine/shared/unshared_vector.rb +11 -8
  79. data/lib/farce/engine/shared/unshared_weak_map.rb +8 -6
  80. data/lib/farce/engine/shared/vector.rb +2 -0
  81. data/lib/farce/engine/shared/weak_atom/base.rb +5 -10
  82. data/lib/farce/engine/shared/weak_map/cell.rb +1 -1
  83. data/lib/farce/engine/shared.rb +2 -0
  84. data/lib/farce/engine/truffleruby/map.rb +8 -6
  85. data/lib/farce/engine/truffleruby/native/counter.rb +0 -2
  86. data/lib/farce/engine/truffleruby/native/priority_queue.rb +18 -4
  87. data/lib/farce/engine/truffleruby/signal.rb +1 -1
  88. data/lib/farce/engine/truffleruby.rb +9 -0
  89. data/lib/farce/extension.rb +5 -3
  90. data/lib/farce/integrations/concurrent.rb +16 -3
  91. data/lib/farce/integrations/sorted_set.rb +1 -0
  92. data/lib/farce/internal/blocking_priority_queue.rb +4 -9
  93. data/lib/farce/internal/fake_ractor.rb +1 -1
  94. data/lib/farce/internal/flag_waiting.rb +1 -1
  95. data/lib/farce/internal/freeze.rb +1 -5
  96. data/lib/farce/internal/lease_initialization.rb +1 -1
  97. data/lib/farce/internal/lease_pool_state.rb +1 -1
  98. data/lib/farce/internal/lease_state.rb +2 -2
  99. data/lib/farce/internal/local_executor_methods.rb +3 -3
  100. data/lib/farce/internal/map_value_modes.rb +17 -9
  101. data/lib/farce/internal/pool_settings.rb +9 -0
  102. data/lib/farce/internal/pool_worker.rb +34 -21
  103. data/lib/farce/internal/reservation_waiting.rb +1 -1
  104. data/lib/farce/internal/scheduler_lifecycle.rb +2 -2
  105. data/lib/farce/internal/weak_map_value_modes.rb +5 -0
  106. data/lib/farce/internal.rb +19 -8
  107. data/lib/farce/lazy.rb +3 -0
  108. data/lib/farce/lazy_ref.rb +3 -0
  109. data/lib/farce/local/counter.rb +4 -10
  110. data/lib/farce/local/lease.rb +2 -9
  111. data/lib/farce/local/lease_map.rb +2 -9
  112. data/lib/farce/local/pool.rb +38 -5
  113. data/lib/farce/local/publisher.rb +30 -0
  114. data/lib/farce/local/scheduler.rb +18 -5
  115. data/lib/farce/local/vector.rb +3 -2
  116. data/lib/farce/map.rb +8 -1
  117. data/lib/farce/memoize.rb +319 -0
  118. data/lib/farce/pool.rb +5 -0
  119. data/lib/farce/priority_queue.rb +1 -1
  120. data/lib/farce/publisher.rb +57 -0
  121. data/lib/farce/shareable.rb +3 -0
  122. data/lib/farce/signal.rb +1 -1
  123. data/lib/farce/strict/publisher.rb +31 -0
  124. data/lib/farce/strict/vector.rb +3 -2
  125. data/lib/farce/strict/weak_cache.rb +199 -0
  126. data/lib/farce/subscription/definitions.rb +27 -0
  127. data/lib/farce/subscription.rb +121 -0
  128. data/lib/farce/transaction/map.rb +35 -1
  129. data/lib/farce/unshared/pool.rb +1 -1
  130. data/lib/farce/unshared/publisher.rb +25 -0
  131. data/lib/farce/unshared/scheduler.rb +3 -3
  132. data/lib/farce/unshared/vector.rb +3 -2
  133. data/lib/farce/vector.rb +20 -16
  134. data/lib/farce/version.rb +1 -1
  135. data/lib/farce/walker/definitions.rb +31 -2
  136. data/lib/farce/walker/modification.rb +28 -14
  137. data/lib/farce/walker.rb +9 -1
  138. data/lib/farce/weak_atom.rb +5 -2
  139. data/lib/farce/weak_key_map.rb +1 -1
  140. data/lib/farce/weak_map.rb +1 -1
  141. data/lib/farce/weak_value_map.rb +1 -1
  142. data/lib/farce.rb +3 -1
  143. metadata +23 -1
@@ -34,10 +34,10 @@ module Farce
34
34
  # (see Farce::Abstract::Lease#checkout)
35
35
  def checkout(timeout: nil, &block)
36
36
  deadline = timeout_deadline(timeout)
37
- lease = scoped_lease(timeout: remaining_timeout(deadline))
37
+ lease = scoped_lease(timeout: Clock.remaining(deadline))
38
38
  raise TimeoutError, "lease checkout timed out" unless lease
39
39
 
40
- timeout = remaining_timeout(deadline)
40
+ timeout = Clock.remaining(deadline)
41
41
  block ? lease.checkout(timeout:, &block) : lease.checkout(timeout:)
42
42
  end
43
43
 
@@ -65,13 +65,6 @@ module Farce
65
65
  end
66
66
  Clock.now + timeout
67
67
  end
68
-
69
- def remaining_timeout(deadline)
70
- return unless deadline
71
-
72
- remaining = deadline - Clock.now
73
- remaining.positive? ? remaining : 0
74
- end
75
68
  end
76
69
  end
77
70
  end
@@ -35,10 +35,10 @@ module Farce
35
35
 
36
36
  def checkout_canonical(key, missing_key:, timeout: nil, &)
37
37
  deadline = timeout_deadline(timeout)
38
- map = scoped_lease_map(timeout: remaining_timeout(deadline))
38
+ map = scoped_lease_map(timeout: Clock.remaining(deadline))
39
39
  raise TimeoutError, "lease checkout timed out" unless map
40
40
 
41
- map.checkout(key, timeout: remaining_timeout(deadline), receiver: self, missing_key:, &)
41
+ map.checkout(key, timeout: Clock.remaining(deadline), receiver: self, missing_key:, &)
42
42
  end
43
43
 
44
44
  def try_checkout_canonical(key, missing_key:, &)
@@ -68,13 +68,6 @@ module Farce
68
68
  end
69
69
  Clock.now + timeout
70
70
  end
71
-
72
- def remaining_timeout(deadline)
73
- return unless deadline
74
-
75
- remaining = deadline - Clock.now
76
- remaining.positive? ? remaining : 0
77
- end
78
71
  end
79
72
  end
80
73
  end
@@ -7,7 +7,8 @@ module Farce
7
7
  # A shareable handle with an independent thread pool in each scope.
8
8
  #
9
9
  # Each pool uses the scaling settings and fiber scheduler configured at
10
- # construction. Tasks always keep their block and argument references. Only
10
+ # construction. Changing settings tunes the current scope's pool. New scopes
11
+ # use the constructor settings. Tasks always keep their block and argument references. Only
11
12
  # local and smart modes are accepted when `auto_local` is false. A scheduler
12
13
  # constructor must be convertible to a shareable proc for use in each Ractor.
13
14
  # {#close} drains only the current scope's pool. {#close_all} drains every pool
@@ -31,14 +32,45 @@ module Farce
31
32
  grow_after: 0.005, shrink_after: 30, capacity: 1024, scope: :ractor,
32
33
  backend: Internal::FROZEN_CONFIG.io_backend, &constructor)
33
34
  initialize_configuration(min_size:, max_size:, max_inflight:, grow_after:, shrink_after:, backend:)
34
- @constructor = prepare_constructor(constructor || Internal::FROZEN_CONFIG.fiber_scheduler_constructor)
35
- @pools = Strict::Map.new
36
- @closed_all = Internal::Flag.new(false)
35
+ @capacity = capacity && Integer(capacity)
36
+ @constructor = prepare_constructor(constructor || Internal::FROZEN_CONFIG.fiber_scheduler_constructor)
37
+ @pools = Strict::Map.new
38
+ @closed_all = Internal::Flag.new(false)
37
39
  @initialization_key = Object.new.freeze
38
40
  super(scope:, min_size: @min_size, max_size: @max_size, max_inflight: @max_inflight,
39
41
  grow_after: @grow_after, shrink_after: @shrink_after, capacity:, backend:)
40
42
  end
41
43
 
44
+ # Settings changes affect only the current scope. New scopes use constructor defaults.
45
+ # @api private
46
+ def settings = (pool = current_pool) ? pool.settings : @settings.value
47
+
48
+ def capacity = (pool = current_pool) ? pool.capacity : @capacity
49
+
50
+ def min_size=(value)
51
+ scoped_value.min_size = value
52
+ end
53
+
54
+ def max_size=(value)
55
+ scoped_value.max_size = value
56
+ end
57
+
58
+ def max_inflight=(value)
59
+ scoped_value.max_inflight = value
60
+ end
61
+
62
+ def grow_after=(value)
63
+ scoped_value.grow_after = value
64
+ end
65
+
66
+ def shrink_after=(value)
67
+ scoped_value.shrink_after = value
68
+ end
69
+
70
+ def capacity=(value)
71
+ scoped_value.capacity = value
72
+ end
73
+
42
74
  # Stop accepting work in this scope and drain its queued tasks.
43
75
  # @return [self]
44
76
  def close
@@ -74,7 +106,8 @@ module Farce
74
106
  def closed? = @closed_all.value || super
75
107
 
76
108
  Internal.delegate(self, :scoped_value, :drained?, :admission_generation, :wait_for_admission,
77
- :admission_changed, :task_taken, :retire_worker, :worker_stopped, :scale_if_needed)
109
+ :admission_changed, :task_taken, :retire_worker, :wake_retiring_workers,
110
+ :worker_retired, :worker_stopped, :scale_if_needed)
78
111
 
79
112
  private
80
113
 
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+ # shareable_constant_value: literal
3
+ # warn_indent: true
4
+
5
+ module Farce
6
+ module Local
7
+ # Local variant of {Farce::Publisher}.
8
+ class Publisher < Abstract::Publisher
9
+ include Shareable::Unfreezable
10
+
11
+ # The scope with independent contents.
12
+ # @return [Symbol] The configured scope name.
13
+ attr_reader :scope
14
+
15
+ # @overload initialize(*subscribers)
16
+ # (see Farce::Abstract#initialize)
17
+ def initialize(*, scope: :ractor)
18
+ raise ArgumentError, "Invalid scope: #{scope.inspect}" unless Farce::SCOPES.include?(scope)
19
+ @scope = scope
20
+ super(*)
21
+ end
22
+
23
+ private
24
+
25
+ def map = Internal::Storage.store_if_absent(self, scope:) { Unshared::Map.new }
26
+
27
+ def default_mode = :local
28
+ end
29
+ end
30
+ end
@@ -56,6 +56,7 @@ module Farce
56
56
  def initialize(capacity: 1024, backend: Internal::FROZEN_CONFIG.io_backend, scope: :ractor,
57
57
  worker: nil, &constructor)
58
58
  @constructor = prepare_constructor(constructor || Internal::FROZEN_CONFIG.fiber_scheduler_constructor)
59
+ @capacity = capacity && Integer(capacity)
59
60
  @backend = backend
60
61
  @worker = worker
61
62
  @schedulers = Strict::Map.new
@@ -65,15 +66,26 @@ module Farce
65
66
  super(scope:, capacity: capacity && Integer(capacity), backend:)
66
67
  end
67
68
 
69
+ # Pending-task capacity in this scope. New scopes retain the constructor value.
70
+ def capacity = (scheduler = current_scheduler) ? scheduler.capacity : @capacity
71
+
72
+ # Resize the queue in this scope without starting a worker.
73
+ def capacity=(value)
74
+ raise SchedulerClosedError, "cannot configure a closed scheduler" if @closed_all.value
75
+ scoped_value.capacity = value
76
+ end
77
+
68
78
  # Enqueue a task in the current scope, preserving its block and arguments.
69
79
  # `mode` is ignored when `auto_local` is true. Otherwise, only local and smart modes are accepted.
70
- # @overload schedule(*args, mode: :smart, auto_local: true)
80
+ # @overload schedule(*args, mode: :smart, auto_local: true, timeout: nil)
71
81
  # @param (see Farce::Abstract::Executor#schedule)
72
- # @return [self]
82
+ # @return [self, nil] self when submitted, or nil when the scheduling timeout expires.
73
83
  def schedule(...) = enqueue_task(false, ...)
74
84
 
75
85
  # (see Abstract::Scheduler#try_schedule)
76
- def try_schedule(...) = enqueue_task(true, ...)
86
+ def try_schedule(*, mode: :smart, auto_local: true, &)
87
+ enqueue_task(true, *, mode:, auto_local:, &)
88
+ end
77
89
 
78
90
  # Starts a worker for the current scope. Other scopes retain their creation behavior.
79
91
  # @param executor [Class, nil] Thread or a custom executor that stays in this Ractor.
@@ -147,12 +159,13 @@ module Farce
147
159
 
148
160
  private
149
161
 
150
- def enqueue_task(non_block, *, mode: :smart, auto_local: true, &block)
162
+ def enqueue_task(non_block, *, mode: :smart, auto_local: true, timeout: nil, &block)
151
163
  raise SchedulerClosedError, "cannot schedule task on a closed scheduler" if @closed_all.value
152
164
  scheduler = scoped_value
153
165
  raise SchedulerClosedError, "cannot schedule task on a closed scheduler" if scheduler.closed?
154
166
  raise LocalJumpError, "Cannot schedule without a block" unless block
155
167
 
168
+ deadline = scheduling_deadline(timeout)
156
169
  validate_local_mode(mode, auto_local)
157
170
  register_scheduler(scheduler)
158
171
 
@@ -160,7 +173,7 @@ module Farce
160
173
  if non_block
161
174
  scheduler.try_schedule(*, mode:, auto_local:, &block)
162
175
  else
163
- scheduler.schedule(*, mode:, auto_local:, &block)
176
+ scheduler.schedule(*, mode:, auto_local:, timeout: Clock.remaining(deadline), &block)
164
177
  end
165
178
 
166
179
  submitted && self
@@ -8,10 +8,11 @@ module Farce
8
8
  #
9
9
  # @!method initialize(source = nil, compare_by_identity: false, scope: :ractor)
10
10
  # @!macro scopes
11
- # @param source [Array, nil] the initial values
11
+ # @param source [Array, Integer, nil] Initial values or a size filled with nil.
12
12
  # @param compare_by_identity [Boolean] whether values are compared by identity
13
13
  # @param scope [Symbol] the scope of the vector
14
14
  # @return [Vector]
15
+ # @raise [ArgumentError] If the size is negative.
15
16
  class Vector < Abstract::Vector
16
17
  include Shareable::Tracked
17
18
  include Scoped::Tracked
@@ -24,7 +25,7 @@ module Farce
24
25
  self.class.new(values, compare_by_identity: compare_by_identity?, scope:)
25
26
  end
26
27
 
27
- private def new_scoped_value(...) = Internal::UnsharedVector.new(...)
28
+ private def new_scoped_value(source = nil, **) = Internal::UnsharedVector.new(normalize_vector_source(source), **)
28
29
  end
29
30
  end
30
31
  end
data/lib/farce/map.rb CHANGED
@@ -48,7 +48,14 @@ module Farce
48
48
 
49
49
  private
50
50
 
51
- def new_map(**) = Internal::StrictMap.new(**)
51
+ def new_map(
52
+ compare_by_identity: false,
53
+ compare_keys_by_identity: compare_by_identity,
54
+ compare_values_by_identity: compare_by_identity
55
+ )
56
+ Internal::StrictMap.new(compare_by_identity:, compare_keys_by_identity:, compare_values_by_identity:)
57
+ end
58
+
52
59
  def freeze_backend = @map
53
60
 
54
61
  Internal.prepare_map_access(self, :modes)
@@ -0,0 +1,319 @@
1
+ # frozen_string_literal: true
2
+ # shareable_constant_value: literal
3
+ # warn_indent: true
4
+
5
+ module Farce
6
+ # Ractor-friendly memoization module.
7
+ #
8
+ # Replaces the following pattern:
9
+ #
10
+ # ```ruby
11
+ # class MyClass
12
+ # def time
13
+ # @time ||= Time.now
14
+ # end
15
+ # end
16
+ # ```
17
+ #
18
+ # Using `Farce::Memoize` instead gives you:
19
+ #
20
+ # * Allows memoization after freezing
21
+ # * Is Ractor-safe (with optional scoping or transfer modes) and thread-safe
22
+ # * Adds one instance variable per memoized method (avoids hash lookup and doesn't bust Ruby's data structures)
23
+ # * Is Marshal-dump/load friendly
24
+ # * Allows weak memoization, where the memoized value is kept until it is garbage collected
25
+ # * Does not need to run code on the main Ractor for memoization
26
+ #
27
+ # Methods with arguments cannot be memoized. Explicitly use a {Farce::Abstract::Map map} instead.
28
+ #
29
+ # @example Using `memoize` method
30
+ # class MyClass
31
+ # include Farce::Memoize
32
+ # memoize def time = Time.now
33
+ # end
34
+ #
35
+ # instance = MyClass.new
36
+ # first_time = instance.time
37
+ # second_time = instance.time
38
+ #
39
+ # first_time == second_time # => true
40
+ # first_time == MyClass.new.time # => false
41
+ #
42
+ # @example Scope-specific memoization
43
+ # class MyClass
44
+ # include Farce::Memoize
45
+ #
46
+ # def first = expensive_computation(0)
47
+ # def last = expensive_computation(-1)
48
+ #
49
+ # # Memoize separately per Ractor
50
+ # memoize :first, :last, scope: :ractor
51
+ # end
52
+ #
53
+ # @example Setting a mode
54
+ # class MyClass
55
+ # include Farce::Memoize
56
+ # memoize :expensive, mode: :make_shareable
57
+ # def expensive = expensive_computation
58
+ # end
59
+ #
60
+ # @example Without `memoize` extension
61
+ # class MyClass
62
+ # include Farce::Memoize[:time]
63
+ # def time = Time.now
64
+ # end
65
+ #
66
+ # @see Farce::Lazy
67
+ # @see Farce::LazyRef
68
+ #
69
+ # @!macro memoize_params
70
+ # @overload $0(*methods, scope: :global, mode: :smart, weak: false, visibility: nil)
71
+ # @param methods [Array<Symbol>]
72
+ # The methods to memoize
73
+ #
74
+ # @param scope [Symbol]
75
+ # The scope of the memoization.
76
+ # In addition to the {Farce::SCOPES normal scopes} it may also be set to `:global` or `:unshared`.
77
+ #
78
+ # @param mode [Symbol]
79
+ # The mode of the memoization. Ignored for any scope other than `:global`.
80
+ # Use `:strict` to cache shareable results directly, including with `weak: true`.
81
+ # Defaults to `:raise` with `weak: true`, which also supports `:make_shareable` and `:dedup`.
82
+ #
83
+ # @param weak [Boolean]
84
+ # Whether to use weak memoization.
85
+ # If enabled, memoized values may be garbage collected when no longer referenced.
86
+ # In this case, next access to the memoized method may recompute the value.
87
+ #
88
+ # @param visibility [Symbol, nil]
89
+ # The visibility of the memoized methods.
90
+ # May be one of `:public`, `:protected`, or `:private`.
91
+ # If set to `nil`, {Farce::Memoize#memoize} will attempt to infer the visibility based on the context.
92
+ # Other methods will default to `:public`.
93
+ module Memoize
94
+ # A named module preserves the nil marker's identity across Marshal round trips.
95
+ NIL_VALUE = Module.new.freeze
96
+ private_constant :NIL_VALUE
97
+
98
+ # Mixins used to implement memoization for different methods, scopes, and modes
99
+ # @see Farce::Memoize
100
+ class Mixin < Module
101
+ KNOWN = Strict::Map.new
102
+ private_constant :KNOWN
103
+
104
+ # @!macro memoize_params
105
+ # Creates or retrieves a memoization mixin for the given methods and options.
106
+ # @return [Mixin] the memoization mixin
107
+ def self.new(*methods, **options)
108
+ return super unless self == Mixin
109
+ methods = Farce.dedup(methods.map(&:to_sym).uniq.sort)
110
+ options = Farce.dedup(normalize_options(options))
111
+ map = KNOWN.store_if_absent(options) { Strict::Map.new }
112
+ map.store_if_absent(methods) { super(methods, **options) }
113
+ end
114
+
115
+ # @api private
116
+ def self.normalize_options(options)
117
+ options[:visibility] &&= options[:visibility].to_sym
118
+
119
+ options[:scope] ||= :global
120
+ options[:visibility] ||= :public
121
+ options[:weak] ||= false
122
+
123
+ if options[:scope] == :global
124
+ options[:mode] ||= options[:weak] ? :raise : :smart
125
+ else
126
+ options.delete(:mode)
127
+ end
128
+
129
+ options
130
+ end
131
+ private_class_method :normalize_options
132
+
133
+ # @return [Array<Symbol>] the memoized methods
134
+ attr_reader :memoized_methods
135
+
136
+ # @return [Symbol] the scope of the memoization
137
+ attr_reader :scope
138
+
139
+ # @return [Symbol, nil] the transfer mode, or nil for a scoped cache
140
+ attr_reader :mode
141
+
142
+ # @return [Symbol] the visibility of the memoized methods
143
+ attr_reader :visibility
144
+
145
+ # @api private
146
+ def initialize(methods, scope:, weak:, mode: nil, visibility: :public)
147
+ @memoized_methods = methods
148
+ @scope = scope
149
+ @mode = mode
150
+ @weak = !!weak # rubocop:disable Style/DoubleNegation
151
+ @visibility = visibility
152
+
153
+ super()
154
+
155
+ unless %i[public protected private].include?(visibility)
156
+ raise ArgumentError, "unsupported visibility: #{visibility.inspect}"
157
+ end
158
+
159
+ atom_class = weak ? "WeakAtom" : "Atom"
160
+
161
+ case scope
162
+ when :global
163
+ if mode == :strict
164
+ init = "::Farce::Strict::#{atom_class}.new"
165
+ else
166
+ modes = weak ? Internal::WeakModeManager::MODES : MODES
167
+ raise ArgumentError, "unsupported mode: #{mode.inspect}" unless modes.include?(mode)
168
+ init = "::Farce::#{atom_class}.new(mode: #{mode.inspect})"
169
+ end
170
+ args = methods.join(", ")
171
+ args += ", mode: #{mode.inspect}" unless mode == :smart
172
+ when :unshared
173
+ init = "::Farce::Unshared::#{atom_class}.new"
174
+ args = "#{methods.join(", ")}, scope: :unshared"
175
+ when *SCOPES
176
+ init = "::Farce::Local::#{atom_class}.new(scope: #{scope.inspect})"
177
+ args = "#{methods.join(", ")}, scope: #{scope.inspect}"
178
+ else
179
+ raise ArgumentError, "unsupported scope: #{scope.inspect}"
180
+ end
181
+
182
+ set_temporary_name(-"Farce::Memoize[#{args}]") if instance_of?(Mixin)
183
+ initializer = +""
184
+ # Overlapping mixins need separate slots. Stable names also survive Marshal across processes.
185
+ slot = "#{methods.join(",").unpack1("H*")}_#{scope}_#{mode}_#{@weak}_#{visibility}"
186
+
187
+ methods.each do |method|
188
+ unless method =~ /\A[a-z_]\w*[!?]?\z/i && method != :initialize
189
+ raise ArgumentError, "unsuitable method name: #{method.inspect}"
190
+ end
191
+ ivar = "@_#{method.to_s.unpack1("H*")}_memoize_#{slot}_atom"
192
+ initializer << " #{ivar} = #{init}\n"
193
+ module_eval <<~RUBY, __FILE__, __LINE__ + 1
194
+ #{visibility} def #{method}
195
+ value = #{ivar}.value || #{ivar}.store_if_absent do
196
+ result = super()
197
+ nil.equal?(result) ? NIL_VALUE : result
198
+ end
199
+ value unless NIL_VALUE.equal?(value)
200
+ end
201
+ RUBY
202
+ end
203
+
204
+ # Explicit forwarding preserves nested constructor keywords on JRuby.
205
+ module_eval <<~RUBY, __FILE__, __LINE__ + 1
206
+ def initialize(*, **, &)
207
+ #{initializer}
208
+ super
209
+ end
210
+ RUBY
211
+ end
212
+
213
+ # @return [Boolean] whether the memoization is weak
214
+ def weak? = @weak
215
+
216
+ # allow `include Farce::Memoize[...]` to work like `prepend`
217
+ private def append_features(base) = base.prepend(self)
218
+ end
219
+
220
+ # @api private
221
+ def self.append_features(base) = base.extend(self)
222
+ private_class_method :append_features
223
+
224
+ # Creates or retrieves the memoization mixin for the given methods, scope, and mode
225
+ # @!macro memoize_params
226
+ # @return [Mixin] memoization mixin for the given methods, scope, and mode
227
+ def self.[](...) = Mixin.new(...)
228
+
229
+ # @!macro memoize_params
230
+ # Creates a memoization mixin for the given arguments and adds it to the current class.
231
+ #
232
+ # Can be used as a prefix to `def`:
233
+ #
234
+ # ```ruby
235
+ # memoize def some_method = expensive_computation
236
+ # ```
237
+ #
238
+ # Or called separately with the method names, useful for passing additional options:
239
+ #
240
+ # ```ruby
241
+ # def some_method = expensive_computation
242
+ #
243
+ # # memoize some_method per thread
244
+ # memoize :some_method, scope: :thread
245
+ # ```
246
+ #
247
+ # ## Visibility of Memoized Methods
248
+ #
249
+ # If no visibility is provided, it will determine the visibility based on the existing method definitions.
250
+ # If none exist, it will default to public. This happens when `memoize` is called.
251
+ # Make sure you set the visibility before calling this method.
252
+ #
253
+ # This works:
254
+ #
255
+ # ```ruby
256
+ # memoize private def some_method = expensive_computation
257
+ # ```
258
+ #
259
+ # As does this:
260
+ #
261
+ # ```ruby
262
+ # private
263
+ # memoize def some_method = expensive_computation
264
+ # ```
265
+ #
266
+ # Or this:
267
+ #
268
+ # ```ruby
269
+ # private def some_method = expensive_computation
270
+ # memoize :some_method
271
+ # ```
272
+ #
273
+ # But this doesn't, as the mixin's method will end up public:
274
+ #
275
+ # ```ruby
276
+ # private memoize def some_method = expensive_computation
277
+ # ```
278
+ #
279
+ # Same for this one, as the mixin's method will also end up public:
280
+ #
281
+ # ```ruby
282
+ # memoize :some_method
283
+ # private def some_method = expensive_computation
284
+ # ```
285
+ #
286
+ # You can of course set visibility explicitly when calling `memoize`:
287
+ #
288
+ # ```ruby
289
+ # memoize :some_method, visibility: :private
290
+ # ```
291
+ #
292
+ # @return [Array<Symbol>] the list of memoized methods
293
+ def memoize(*methods, visibility: nil, warn: true, **)
294
+ if visibility.nil?
295
+ groups = methods.group_by do |method|
296
+ next :protected if protected_method_defined?(method)
297
+ next :private if private_method_defined?(method)
298
+ :public
299
+ end
300
+ return groups.flat_map { memoize(*_2, visibility: _1, warn:, **) }
301
+ end
302
+
303
+ if warn
304
+ methods.each do |name|
305
+ method = instance_method(name)
306
+ next if method.parameters.empty?
307
+ warn "#{method.owner}##{name} expects parameters and may be unsuitable for memoization"
308
+ rescue NameError => e
309
+ raise e unless e.name == name.to_sym
310
+ end
311
+ end
312
+
313
+ mixin = Farce::Memoize[*methods, visibility:, **]
314
+ prepend mixin
315
+
316
+ mixin.memoized_methods
317
+ end
318
+ end
319
+ end
data/lib/farce/pool.rb CHANGED
@@ -11,6 +11,11 @@ module Farce
11
11
  # `min_size` retire after `shrink_after` without queued or running work.
12
12
  # By default, the pool starts with no workers and can shrink back to zero.
13
13
  #
14
+ # Worker limits, task limits, scaling delays, and queue capacity can change while
15
+ # the pool runs. Lowering `max_size` retires extra workers as they become idle.
16
+ # Busy workers keep queued work runnable. Raising `min_size` starts workers
17
+ # immediately. Queued tasks are retained.
18
+ #
14
19
  # Most importantly, it exposes a {#schedule} method compatible with {Scheduler#schedule}.
15
20
  #
16
21
  # @example
@@ -42,7 +42,7 @@ module Farce
42
42
  result = @reverse_order ? @queue.pop_last { empty = true } : @queue.pop { empty = true }
43
43
 
44
44
  return @manager.unwrap(result) unless empty
45
- remaining = remaining_timeout(deadline)
45
+ remaining = Clock.remaining(deadline)
46
46
  return block_given? ? yield : nil unless wait_pop(timeout: remaining)
47
47
  end
48
48
  end
@@ -0,0 +1,57 @@
1
+ # frozen_string_literal: true
2
+ # shareable_constant_value: literal
3
+ # warn_indent: true
4
+
5
+ module Farce
6
+ # A message multiplexer.
7
+ # Implements the publisher-subscriber protocol.
8
+ #
9
+ # @example
10
+ # publisher = Farce::Publisher.new
11
+ #
12
+ # # Count how many messages have been received
13
+ # counter = Farce::Counter.new
14
+ # publisher.subscribe(counter)
15
+ #
16
+ # # Trigger a callback whenever a message is published
17
+ # publisher.subscribe do |message|
18
+ # puts "Received message: #{message}"
19
+ # end
20
+ #
21
+ # # Send messages to a queue
22
+ # queue = Farce::Queue.new
23
+ # publisher.subscribe(queue)
24
+ #
25
+ # # Keep track of the last published value
26
+ # atom = Farce::Atom.new
27
+ # publisher.subscribe(atom)
28
+ #
29
+ # # Send messages to a Ractor
30
+ # ractor = Ractor.new do
31
+ # while message = Ractor.receive
32
+ # puts "Received message in Ractor: #{message}"
33
+ # end
34
+ # end
35
+ # publisher.subscribe(ractor)
36
+ #
37
+ # # Publish some messages
38
+ # publisher.publish("Hello, world!")
39
+ # publisher.publish("Another message")
40
+ #
41
+ # queue.pop # => "Hello, world!"
42
+ # atom.value # => "Another message"
43
+ # counter.value # => 2
44
+ class Publisher < Farce::Abstract::Publisher
45
+ include Shareable::Unfreezable
46
+
47
+ # @overload initialize(*subscribers)
48
+ # (see Farce::Abstract#initialize)
49
+ def initialize(*subscribers)
50
+ @map = Strict::Map.new
51
+ super()
52
+ subscribers.each { subscribe(it) }
53
+ end
54
+
55
+ private attr_reader :map
56
+ end
57
+ end
@@ -13,6 +13,9 @@ module Farce
13
13
  # object = MyClass.new
14
14
  # Ractor.shareable?(object) # => true
15
15
  module Shareable
16
+ # @api private
17
+ def self.included(base) = Internal.prepare_shareable_class(base)
18
+
16
19
  # A structurally frozen wrapper whose logical frozen state is owned by its backend.
17
20
  # The including class must implement a private `freeze_backend` method.
18
21
  #
data/lib/farce/signal.rb CHANGED
@@ -80,7 +80,7 @@ module Farce
80
80
  result = yield
81
81
  return result if result
82
82
 
83
- remaining = deadline - Clock.now if deadline
83
+ remaining = Clock.remaining(deadline)
84
84
  return if remaining && !remaining.positive?
85
85
  return unless wait(observed, timeout: remaining)
86
86
  end