Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ to docs, or any other relevant information.

### Added

- `Temporalio::Worker::ThreadPool::ThreadContext` can be passed to `ThreadPool.new` as
`thread_context:` to wrap the execution of the body of each pool thread.

### Changed

- Priority is no longer marked as experimental.
Expand Down
47 changes: 47 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ Also see:
- [Activity Heartbeating and Cancellation](#activity-heartbeating-and-cancellation)
- [Activity Worker Shutdown](#activity-worker-shutdown)
- [Activity Concurrency and Executors](#activity-concurrency-and-executors)
- [Per-Thread Setup for the Thread Pool Executor](#per-thread-setup-for-the-thread-pool-executor)
- [Activity Testing](#activity-testing)
- [Telemetry](#telemetry)
- [Metrics](#metrics)
Expand Down Expand Up @@ -1084,6 +1085,52 @@ Technically the executor can be customized. The `activity_executors` worker opti
symbol and the value as a `Temporalio::Worker::ActivityExecutor` implementation. Users should usually not need to
customize this. If general code is needed to run around activities, users should use interceptors instead.

#### Per-Thread Setup for the Thread Pool Executor

To acquire a resource once per thread and reuse it across every activity that thread runs -- a database connection, say
-- pass a `Temporalio::Worker::ThreadPool::ThreadContext` when constructing a thread pool. The context's `call` method
receives a block that executes the worker's assigned tasks, and should be called exactly once. `call` should not
raise. Acquired resources should be released in an `ensure`, not directly after `yield`:

```ruby
class DatabaseConnectionContext < Temporalio::Worker::ThreadPool::ThreadContext
def call
connection = MyDatabase.connect
Thread.current[:my_connection] = connection
yield
ensure
Thread.current[:my_connection] = nil
connection&.close
end
end

pool = Temporalio::Worker::ThreadPool.new(thread_context: DatabaseConnectionContext.new)
executor = Temporalio::Worker::ActivityExecutor::ThreadPool.new(pool)

worker = Temporalio::Worker.new(
client:,
task_queue: 'my-task-queue',
activities: [MyActivity],
activity_executors: Temporalio::Worker::ActivityExecutor.defaults.merge(default: executor)
)
```

Note:

* You must explicitly construct and use a pool and executor with your custom thread context. The default pool
has no context.
* `call` must invoke the block exactly once. Invoking it again re-enters a loop the pool has stopped tracking, which
blocks that thread forever; not invoking it means the thread never runs any work.
* Clean up in an `ensure`. On a normal stop the block returns and code after the `yield` does run, but
`Temporalio::Worker::ThreadPool#kill` terminates the thread without letting the block return, so only an `ensure`
runs on every path.
* This is not an interceptor. A context wraps a thread's whole lifetime, not a single activity execution. To run code
around each activity, use an interceptor instead.
* The `call` wrapper should not raise. If it does, work already queued on the worker is dropped silently (and thus
will time out and be retried). The thread is dropped from the pool, and a new one is started when more work
arrives. Pass `restart_worker: true` to the `ThreadContext` constructor to start a replacement immediately instead;
a context that always raises will then restart without bound.

Comment on lines +1088 to +1133

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is an excessively long blurb for a very advanced feature most users won't need. All of this is better suited for YARD documentation rather than the top level readme.

#### Activity Testing

Unit testing an activity can be done via the `Temporalio::Testing::ActivityEnvironment` class. Simply instantiate the
Expand Down
116 changes: 99 additions & 17 deletions temporalio/lib/temporalio/worker/thread_pool.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,56 @@ class ThreadPool
# see MIT license at
# https://github.com/ruby-concurrency/concurrent-ruby/blob/044020f44b36930b863b930f3ee8fa1e9f750469/LICENSE.txt

# Wraps the body of each pool thread, for acquiring a resource when a thread starts and
# releasing it when the thread exits. Since the block is invoked for the entire lifetime of
# the thread, a resource acquired around it can be released from an `ensure`.
Comment on lines +14 to +15

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO this second sentence clearly follows from the first. Unsure we need to be this prescriptive around releasing resources via ensure.

Suggested change
# releasing it when the thread exits. Since the block is invoked for the entire lifetime of
# the thread, a resource acquired around it can be released from an `ensure`.
# releasing it when the thread exits.

#
# The `call` wrapper should not raise. `call` has the responsibility for calling the
# passed block exactly once, and rescuing all exceptions and errors. If the `call` wrapper
# cannot invoke the block, the block is not re-queued.
Comment on lines +18 to +19

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Block requeing is a weird thing to talk about. I think the real consequence here is that you would have a worker thread that doesn't do any work, right?

#
# If the `call` wrapper does raise, the exception is swallowed, and the worker dies.
# The `restart_worker` constructor parameter determines whether a new worker is
# immediately created to replace the one that died. It defaults to false to avoid
# a rapid fail-and-restart loop.
#
# @note The same instance is used by every thread in the pool, so implementations must be
# thread safe. Per-thread state belongs in the block, not in the ThreadContext object.
class ThreadContext
# @return [ThreadContext] Default context that just invokes the block.
def self.default
@default ||= NoOp.new
end

# @return [Boolean] Whether a thread whose context raised is replaced with a new one.
attr_reader :restart_worker

# @param restart_worker [Boolean] What to do when {call} raises. When false, the thread is
# dropped from the pool and a new one is started only when more work arrives. When true,
# a replacement thread is started immediately, which invokes {call} again -- so a context
# that always raises will restart without bound.
def initialize(restart_worker: false)
@restart_worker = restart_worker
end

# Invoke the given block for the lifetime of a pool thread. Implementations must invoke
# the block exactly once; invoking it again re-enters a loop the pool has stopped tracking,
# which blocks that thread forever and skips the rest of this method.
#
# @yield Block to invoke for the lifetime of the thread.
def call(&)
raise NotImplementedError
end

# @!visibility private
class NoOp < ThreadContext
# @see ThreadContext.call
def call(&)
yield
end
end
end

# @return [ThreadPool] Default/shared thread pool instance with unlimited max threads.
def self.default
@default ||= new
Expand All @@ -25,9 +75,12 @@ def self._monotonic_time
# @param max_threads [Integer, nil] Maximum number of thread workers to create, or nil for unlimited max.
# @param idle_timeout [Float] Number of seconds before a thread worker with no work should be stopped. Note,
# the check of whether a thread worker is idle is only done on each new {execute} call.
def initialize(max_threads: nil, idle_timeout: 20)
# @param thread_context [ThreadContext] Invoked around the body of each thread this pool starts, for
# acquiring and releasing per-thread resources. Defaults to one that adds no behavior.
def initialize(max_threads: nil, idle_timeout: 20, thread_context: ThreadContext.default)
@max_threads = max_threads
@idle_timeout = idle_timeout
@thread_context = thread_context

@mutex = Mutex.new
@pool = []
Expand Down Expand Up @@ -123,6 +176,16 @@ def _worker_task_completed
@mutex.synchronize { @completed_task_count += 1 }
end

# @!visibility private
def _thread_context
@thread_context
end

# @!visibility private
def _remove_ready_worker(worker)
@mutex.synchronize { @ready.reject! { |ready_worker, _| ready_worker.equal?(worker) } }
end

private

def locked_assign_worker(&block) # rubocop:disable Naming/PredicateMethod
Expand Down Expand Up @@ -188,12 +251,34 @@ def locked_worker_died(worker)
class Worker
def initialize(pool, id)
@queue = Queue.new
@thread = Thread.new(@queue, pool) do |my_queue, my_pool|
@thread = Thread.new(@queue, pool) { |my_queue, my_pool| worker_loop(my_queue, my_pool) }
@thread.name = "temporal-thread-#{id}"
end

# @!visibility private
def <<(block)
@queue << block
end

# @!visibility private
def stop
@queue << :stop
end

# @!visibility private
def kill
@thread.kill
end

private

def worker_loop(my_queue, my_pool)
my_pool._thread_context.call do
catch(:stop) do
loop do
case block = my_queue.pop
when :stop
pool._remove_busy_worker(self)
my_pool._remove_busy_worker(self)
throw :stop
else
begin
Expand All @@ -212,22 +297,19 @@ def initialize(pool, id)
end
end
end
@thread.name = "temporal-thread-#{id}"
rescue Exception => e # rubocop:disable Lint/RescueException
handle_thread_context_exception(my_pool, e)
end

# @!visibility private
def <<(block)
@queue << block
end

# @!visibility private
def stop
@queue << :stop
end

# @!visibility private
def kill
@thread.kill
# Removes the worker, and creates a replacement iff restart_worker is true.
def handle_thread_context_exception(my_pool, err)
warn("Unexpected thread context exception: #{err.full_message}")
my_pool._remove_ready_worker(self)
if my_pool._thread_context.restart_worker
my_pool._worker_died(self)
else
my_pool._remove_busy_worker(self)
end

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think the logic for restart_worker: false is correct.

_remove_busy_worker just removes the thread from the pool. When additional work comes to the worker and there aren't any idle threads, then the thread pool executor will spawn a new thread since we're below the max threads limit. Even if we didn't restart threads upon incoming work, this could lead to situations where we have a "live" worker with no threads to perform work on.

end
end

Expand Down
33 changes: 31 additions & 2 deletions temporalio/rbi/temporalio/worker/thread_pool.rbi
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,14 @@ class Temporalio::Worker::ThreadPool
sig { returns(Temporalio::Worker::ThreadPool) }
def self.default; end

sig { params(max_threads: T.nilable(Integer), idle_timeout: Float).void }
def initialize(max_threads: T.unsafe(nil), idle_timeout: T.unsafe(nil)); end
sig do
params(
max_threads: T.nilable(Integer),
idle_timeout: Float,
thread_context: Temporalio::Worker::ThreadPool::ThreadContext
).void
end
def initialize(max_threads: T.unsafe(nil), idle_timeout: T.unsafe(nil), thread_context: T.unsafe(nil)); end

sig { params(block: T.proc.void).void }
def execute(&block); end
Expand Down Expand Up @@ -36,3 +42,26 @@ class Temporalio::Worker::ThreadPool
sig { void }
def kill; end
end

class Temporalio::Worker::ThreadPool::ThreadContext
extend T::Sig

sig { returns(Temporalio::Worker::ThreadPool::ThreadContext) }
def self.default; end

sig { returns(T::Boolean) }
attr_reader :restart_worker

sig { params(restart_worker: T::Boolean).void }
def initialize(restart_worker: T.unsafe(nil)); end

sig { params(block: T.proc.void).void }
def call(&block); end
end

class Temporalio::Worker::ThreadPool::ThreadContext::NoOp < Temporalio::Worker::ThreadPool::ThreadContext
extend T::Sig

sig { params(block: T.proc.void).void }
def call(&block); end
end
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ module Temporalio
class ThreadPool < ActivityExecutor
def self.default: -> ThreadPool

def initialize: (?ThreadPool thread_poll) -> void
def initialize: (?::Temporalio::Worker::ThreadPool thread_pool) -> void
end
end
end
Expand Down
19 changes: 18 additions & 1 deletion temporalio/sig/temporalio/worker/thread_pool.rbs
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
module Temporalio
class Worker
class ThreadPool
class ThreadContext
def self.default: -> ThreadContext
attr_reader restart_worker: bool
def initialize: (?restart_worker: bool) -> void
def call: { -> void } -> void

class NoOp < ThreadContext
def call: { -> void } -> void
end
end

def self.default: -> ThreadPool

def self._monotonic_time: -> Float

def initialize: (
?max_threads: Integer?,
?idle_timeout: Float
?idle_timeout: Float,
?thread_context: ThreadContext
) -> void

def execute: { -> void } -> void
Expand All @@ -25,6 +37,8 @@ module Temporalio
def _ready_worker: (Worker worker, Float last_message) -> void
def _worker_died: (Worker worker) -> void
def _worker_task_completed: -> void
def _thread_context: -> ThreadContext
def _remove_ready_worker: (Worker worker) -> void
private def locked_assign_worker: { (?) -> untyped } -> void
private def locked_enqueue: { (?) -> untyped } -> void
private def locked_add_busy_worker: -> Worker?
Expand All @@ -38,6 +52,9 @@ module Temporalio
def <<: (Proc block) -> void
def stop: -> void
def kill: -> void

private def worker_loop: (Thread::Queue my_queue, ThreadPool my_pool) -> void
private def handle_thread_context_exception: (ThreadPool my_pool, Exception err) -> void
end
end
end
Expand Down
9 changes: 9 additions & 0 deletions temporalio/test/sig/worker_thread_context_test.rbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class WorkerThreadContextTest < Test
class CountingContext < Temporalio::Worker::ThreadPool::ThreadContext
def initialize: (fail_times: Numeric, ?restart_worker: bool) -> void
def count: -> Integer
def call: { -> void } -> void
end

def run_and_wait: (Temporalio::Worker::ThreadPool pool, ?timeout: Float) -> void
end
34 changes: 34 additions & 0 deletions temporalio/test/thread_context_recorder.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# frozen_string_literal: true

require 'temporalio/worker/thread_pool'

# Thread context for tests: sets a thread-local for the lifetime of each pool thread and clears it
# on the way out, so work running on that thread can observe it and a test can observe the
# teardown. `entered`, `returned` and `exited` are queues because they are pushed to from pool
# threads, which outlive the work they run.
#
# `returned` records reaching the statement after the `yield`, which only happens when the block
# returns normally -- not when the thread is killed inside it.
class ThreadContextRecorder < Temporalio::Worker::ThreadPool::ThreadContext
VALUE_KEY = :thread_context_value

attr_reader :entered, :returned, :exited

def initialize(value: 'acquired')
super()
@value = value
@entered = Queue.new
@returned = Queue.new
@exited = Queue.new
end

def call
Thread.current[VALUE_KEY] = @value
@entered.push(Thread.current.name)
yield
@returned.push(Thread.current.name)
ensure
Thread.current[VALUE_KEY] = nil
@exited.push(Thread.current.name)
end
end
Loading
Loading