Method: Socrates::Core::Dispatcher#dispatch

Defined in:
lib/socrates/core/dispatcher.rb

#dispatch(message:, context: {}) ⇒ Object

rubocop:disable Metrics/AbcSize



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
# File 'lib/socrates/core/dispatcher.rb', line 21

def dispatch(message:, context: {})
  message = message.strip

  client_id = @adapter.client_id_from_context(context)

  @logger.info %(#{client_id} recv: "#{message}")

  # In many cases, a two actions will run in this loop: :listen => :ask, but it's possible that a chain of 2 or
  # more :ask actions could run, before stopping at a :listen (and waiting for the next input).
  loop do
    state_data = fetch_snapshot(client_id)
    state      = instantiate_state(state_data, context)

    args = [state.data.state_action]
    args << message if state.data.state_action == :listen

    msg = %(#{client_id} processing :#{state.data.state_id} / :#{args.first})
    msg += %( / message: "#{args.second}") if args.count > 1
    @logger.debug msg

    begin
      state.send(*args)
    rescue => e
      handle_action_error(e, client_id, state, context)
      return
    end

    # Update the persisted state data so we know what to run next time.
    state.data.state_id     = state.next_state_id
    state.data.state_action = state.next_state_action

    @logger.debug %(#{client_id} transition to :#{state.data.state_id} / :#{state.data.state_action})

    persist_snapshot(client_id, state.data)

    # Break from the loop if there's nothing left to do, i.e. no more state transitions.
    break if done_transitioning?(state)
  end
end