class RatatuiRuby::Tea::Command::CancellationToken
Cooperative cancellation mechanism for long-running commands.
Long-running commands block the event loop. Commands that poll, stream, or wait indefinitely prevent clean shutdown. Killing threads mid-operation corrupts state.
This class signals cancellation requests. Commands check cancelled? periodically and stop gracefully. The runtime calls cancel! when shutdown begins.
Use it to implement WebSocket handlers, database pollers, or any command that loops.
Example
class PollerCommand include Tea::Command::Custom def call(out, token) until token.cancelled? data = fetch_batch out.put(:batch, data) sleep 5 end out.put(:poller_stopped) end end
Constants
- NONE
-
Singleton null token. Always returns
cancelled? == false.
Attributes
Number of times cancel! has been called. :nodoc:
Exposed for testing thread-safety. Not part of the public API.
Public Class Methods
Source
# File lib/ratatui_ruby/tea/command/cancellation_token.rb, line 50 def initialize @cancel_count = 0 @mutex = Mutex.new end
Creates a new cancellation token in the non-cancelled state.
Public Instance Methods
Source
# File lib/ratatui_ruby/tea/command/cancellation_token.rb, line 73 def cancel! @mutex.synchronize do current = @cancel_count sleep 0 # Force context switch (enables thread-safety testing) @cancel_count = current + 1 end end
Signals cancellation. Thread-safe.
Call this to request the command stop. The command checks cancelled? and stops at the next safe point.
Example
token = CancellationToken.new token.cancel! token.cancelled? # => true
Source
# File lib/ratatui_ruby/tea/command/cancellation_token.rb, line 100 def cancelled? @cancel_count > 0 end
Checks if cancellation was requested. Thread-safe.
Commands call this periodically in their main loop. When it returns true, the command should clean up and exit.
Example
until token.cancelled? do_work sleep 1 end