What is Megaphone?

What is Megaphone?
The Megaphone project is about enhancing open source chat software. Specifically, the goal is to allow ejabberd to support 1,000,000 simultaneous users. See The Plan page for more details on how I plan to solve this problem. See the About this Blog page for more details on why I created this blog.

Thursday, December 22, 2011

OTP Behavior: gen_fsm

gen_fsm is a generate state machine pattern.  With gen_fsm, each state is represented with a function that has the form:

<state name>(Event, LoopData) -> { next_state, NewState, NewLoopData }


The FSM can also tell the framework to terminate via the following:


<state name>(Event, LoopData) -> { stop, Reason, NewLoopData }


Client API

  • start(Module, Args, Options)
  • start(Name, Module, Args, Options)
  • start_link(Module, Args, Options)
  • start_link(Name, Module, Args, Options)
    Start up the FSM.  These functions will call init/1 in the specified Module.  start_link links the new FSM to the caller, start does not.  The name will register the newly created process locally or globally, as appropriate.
  • send_event (Reference, Event)
    This will cause the corresponding <state name> function to be called.  The call returns immediately.
  • send_all_state_event (Reference, Event)
    Will cause handle_event to be called on the server instead of the function for the current state.
  • sync_send_event (Reference, Event)
    This will cause the corresponding <state name> function to be called.  The call waits for the FSM to complete before continuing
  • sync_send_all_state_event (Reference, Event)
    This will cause the handle_event function to be called on the server.  The caller will wait for the event to be processed before continuing.
  • reply(Caller, Reply)
    This is actually an internal call that is used to set the reply that will be returned in the case of sync_send_event and sync_send_all_state_event.
Server API
  • init(Args) -> { ok, StateName, StateData }
    Start up the state machine.
  • <State Name>(Event, Data) -> {next_state, NextState, NewData}
    Handle an event sent to the state machine via send_event or sync_send_event  Can also return:
    • { stop, Reason, NewData} in order to terminate the FSM.
  • handle_event(Event, State, Data) ->
        {next_state, NextState, NewData}

    Handle an event sent to the FSM via send_all_state_event.
  • handle_sync_event(Event, State, Data) ->
        {next_state, NextState, NewData}

    Handle an event sent to the FSM via sync_send_all_state_event.
  • terminate(Reason, StateName, Data)
    Clean up hook.
A slight change of plan: I am not going to cover the application behavior.

No comments:

Post a Comment