class ManagedService
A managed service with built-in health checking, restart policies, and process title formatting.
This is the recommended base class for most services that need robust lifecycle management.
Definitions
def run(instance, evaluator)
Run the service logic.
Override this method to implement your service. Return an object that represents the running service (e.g., a server, task, or worker pool) for health checking.
Signature
-
parameter
instanceObject The container instance.
-
parameter
evaluatorEnvironment::Evaluator The environment evaluator.
-
returns
Object The service object (server, task, etc.)
Implementation
def run(instance, evaluator)
Async do
sleep
end
end
def preload!
Preload any resources specified by the environment.
Implementation
def preload!
if scripts = @evaluator.preload
root = @evaluator.root
scripts = Array(scripts)
scripts.each do |path|
Console.info(self){"Preloading #{path}..."}
full_path = File.expand_path(path, root)
require(full_path)
end
end
rescue StandardError, LoadError => error
Console.warn(self, "Service preload failed!", error)
end
def start
Start the service, including preloading resources.
Implementation
def start
preload!
super
end
def emit_prepared(instance, start_time)
Called after the service has been prepared but before it starts running.
Override this method to emit metrics, logs, or perform other actions when the service preparation is complete.
Signature
-
parameter
instanceAsync::Container::Instance The container instance.
-
parameter
start_timeAsync::Clock The monotonic start time from
Async::Clock.start.
Implementation
def emit_prepared(instance, start_time)
# Override in subclasses as needed.
end
def emit_running(instance, start_time)
Called after the service has started running.
Override this method to emit metrics, logs, or perform other actions when the service begins running.
Signature
-
parameter
instanceAsync::Container::Instance The container instance.
-
parameter
start_timeAsync::Clock The monotonic start time from
Async::Clock.start.
Implementation
def emit_running(instance, start_time)
# Override in subclasses as needed.
end
def setup(container)
Set up the container with health checking and process title formatting.
Signature
-
parameter
containerAsync::Container The container to configure.
Implementation
def setup(container)
super
container_options = @evaluator.container_options
health_check_timeout = container_options[:health_check_timeout]
container.run(**container_options) do |instance|
start_time = Async::Clock.start
Async do
evaluator = self.environment.evaluator
instance.status!("Preparing...")
evaluator.prepare!(instance)
emit_prepared(instance, start_time)
instance.status!("Running...")
server = run(instance, evaluator)
emit_running(instance, start_time)
health_checker(instance) do
instance.name = format_title(evaluator, server)
end
end
end
end