How to maintain stateful in yaws

666 views Asked by At

I have some process (spawned) with state.

How to maintain simple stateful service in yaws? How to implement communication to process in "appmods" erl source file?

update: let's we have simple process

start() -> loop(0).

loop(C) ->
  receive 
    {inc} -> loop(C + 1);
    {get, FromPid} -> FromPid ! C, loop(C)
  end.

What is the simplest (trivial: without gen_server, yapp) way to access process from web?

Maybe, I need a minimal example with gen_server+yapp+yaws / appmods+yaws.

2

There are 2 answers

0
Muzaaya Joshua On

There only 2 ways to access a process in Erlang: Either you know its Pid (and the node where you expect the process to be) or You know its registered Name (and the erlang node its expected to be).

Lets say you have your appmod:

-module(myappmod).
-export([out/1]).
-include("PATH/TO/YAWS_SERVER/include/yaws_api.hrl").
-include("PATH/TO/YAWS_SERVER/include/yaws.hrl").
out(Arg) -> case check_initial_state(Arg) of unknown -> create_initial_state(); {ok,Value}-> UserPid = list_to_pid(Value), UserPid ! extract_request(Arg), receive Response -> {html,format_response(Response)} after ?TIMEOUT -> {html,"request_timedout"} end end.
check_initial_state(A)-> CookieObject = (A#arg.headers)#headers.cookie, case yaws_api:find_cookie_val("InitialState", CookieObject) of [] -> unkown; Cookie -> {ok,Cookie} end.
extract_request(Arg)->
%% get request from POST Data or Get Data Post__data_proplist = yaws_api:parse_post(Arg), Get_data_proplist = yaws_api:parse_query(Arg), %% do many other things.... Request = remove_request(Post__data_proplist,Get_data_proplist), Request.
That simple set up shows you how you would use processes to keep things about a user. However, the use of processes is not good. Processes do fail, so you need a way of recovering what data they were holding.

A better approach is to have a Data storage about your users and have one gen_server to do the look ups. You could use Mnesia. I do not advise you to use processes on the web to keep user state, no matter what kind of app you are doing, even if its a messaging app. Mnesia or ETS tables can keep state and all you need to do is look up.

Use a better storage mechanism to keep state other than processes. Processes are a point of failure. Others use Cookies (and/or Session cookies), whose value is used in some way to look up something from a database. However, if you insist that you need processes, then, have a way of remembering their Pids or registered names. You could store a user Pid into their session cookie e.t.c.

0
PokerFace On

The #arg structure is a very important datastructure for the yaws programmer. In the ARG of Yaws out/1 there is a variable that can save user state.

"state, %% State for use by users of the out/1 callback"

You can get detail info here .