Class: Async::Service::ManagedService

Inherits:
GenericService show all
Includes:
HealthChecker
Defined in:
lib/async/service/managed_service.rb

Overview

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.

Instance Attribute Summary

Attributes inherited from GenericService

#The environment which is used to configure the service., #environment

Instance Method Summary collapse

Methods included from HealthChecker

#health_checker

Methods inherited from GenericService

#initialize, #name, #stop, #to_h, wrap

Constructor Details

This class inherits a constructor from Async::Service::GenericService

Instance Method Details

#emit_prepared(instance, start_time) ⇒ Object



57
58
# File 'lib/async/service/managed_service.rb', line 57

def emit_prepared(instance, start_time)
end

#emit_running(instance, start_time) ⇒ Object



60
61
# File 'lib/async/service/managed_service.rb', line 60

def emit_running(instance, start_time)
end

#preload!Object

Preload any resources specified by the environment.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/async/service/managed_service.rb', line 35

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

#run(instance, evaluator) ⇒ Object

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.



28
29
30
31
32
# File 'lib/async/service/managed_service.rb', line 28

def run(instance, evaluator)
  Async do
    sleep
  end
end

#setup(container) ⇒ Object

Set up the container with health checking and process title formatting.



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/async/service/managed_service.rb', line 65

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
      
      evaluator.prepare!(instance)
      
      emit_prepared(instance, start_time)

      server = run(instance, evaluator)
      
      emit_running(instance, start_time)
      
      health_checker(instance) do
        instance.name = format_title(evaluator, server)
      end
    end
  end
end

#startObject

Start the service, including preloading resources.



51
52
53
54
55
# File 'lib/async/service/managed_service.rb', line 51

def start
  preload!
  
  super
end