Class: Phronomy::MultiAgent::FanOutSessionBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/phronomy/multi_agent/fan_out_session_builder.rb

Overview

Builds and registers a fan-out coordination FSMSession.

Constant Summary collapse

AUTO_STATE_SET =
{idle: true}.freeze
DECLARED_STATES =
%i[idle running completed failed timed_out cancelled].freeze
WAIT_STATES =
[].freeze

Class Method Summary collapse

Class Method Details

.start(invocation:, timeout: nil, cancellation_token: nil, runtime: Phronomy::Runtime.instance) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/phronomy/multi_agent/fan_out_session_builder.rb', line 13

def self.start(
  invocation:,
  timeout: nil,
  cancellation_token: nil,
  runtime: Phronomy::Runtime.instance
)
  result = Phronomy::Task.deferred(name: "fan-out:#{invocation.id}")

  if cancellation_token&.cancelled?
    result.fail(Phronomy::CancellationError.new("fan-out cancelled"))
    return result
  end

  source = Phronomy::Task.deferred(name: "fan-out-source:#{invocation.id}")
  source.on_complete do |context, error|
    if error
      result.fail(error)
    elsif context.error
      result.fail(context.error)
    else
      result.complete(context.results)
    end
  end

  session = build(invocation: invocation, runtime: runtime)
  runtime.event_loop.register(session, completion: source)

  if timeout
    runtime.timer_queue.schedule(seconds: timeout) do
      runtime.event_loop.post_to_session(
        Phronomy::Event.new(
          type: :timeout,
          target_id: invocation.id,
          payload: {message: "dispatch_parallel timed out after #{timeout}s"}
        )
      )
    end
  end

  cancellation_token&.on_cancel do
    runtime.event_loop.post_to_session(
      Phronomy::Event.new(type: :cancel, target_id: invocation.id, payload: nil)
    )
  end

  result
rescue => error
  result ||= Phronomy::Task.deferred(name: "fan-out:registration")
  result.fail(error)
  result
end