Haskell Webserver: Saving Application State

I am trying to get a better understanding of Haskell by creating web-app-ish services.

Let's say I'm developing a web server, and I want to maintain a constant state between requests; counter, for example. What is the Haskell way of doing things?

I found this discussion in my google search. The proposed solution looks like a good example of what not to do.

One of my ideas was that the request handler accepted MVar:

requestHandler :: MVar State -> IO (Maybe Response) 

When registering a handler, it can be drawn with MVar, which was created mainly.

There must be a better way. I cannot help but think that I am approaching this problem in a non-functional way.

Thanks!

+7
source share
2 answers

You probably want an acid state , which gives you exactly what: a constant state for Haskell data types. The documentation I linked even starts with a request counter, as you requested.

Note that MVars are not persistent; the counter will get reset when the server restarts. If this is actually the behavior you want, I suggest you instead of TVar ; this way you can update the counter atomically without blocking or the risk of deadlocks that come with them.

+4
source

If you like persistence and TVAR, you can use DBRefs that have the same semantics and the same usage patterns as TVars. You must define a unique key for the state, and you have automatic file saving. To save the database, you must define an instance of IResource.

The state will have a unique counter for each session:

 import Data.Map as M import Data.TCache import Data.TCache.DefaultPersistence type Counter= Int type SessionId :: String data State= State SessionId Counter deriving (Read, Show, Typeable) instance Indexable State where key (State k _)= k requestHandler :: Request -> DBRef State -> IO (Maybe Response) 
+1
source