FaaS, short for Function as a Service, is a framework for building Serverless. So what do FaaS do? In simple terms, FaaS forwards HTTP requests to executable commands, and then forwards the command execution results to HTTP Response.

With this business logic we can build our own FaaS server.

Start by defining a data structure that can execute commands:

data Proc = Proc { procFuncName: :String
                 , procName: :String
                 , procArgv: :String]}Copy the code
  • procFuncNameIs the name of the HTTP request function
  • procNameIs an executable command
  • procArgvIs an executable command parameter

Execute the command using readProcessWithExitCode in System.Process

runProc: :Proc -> String -> IO (Either String String)
runProc (Proc { procName = name, procArgv = argv}) wb = do
  (code, out, err) <- readProcessWithExitCode name argv wb
  case code of 
    ExitSuccess   -> return (Right out)
    ExitFailure _ -> return (Left err)Copy the code

Use web.scotty to build the Web server

processHandler: : (String -> Maybe Proc) - >ActionM(a)processHandler getProc = do 
  func <- param "func"
  case (getProc func) of
    Nothing -> do 
        status status404
        raw LB.empty
    Just proc -> do 
        wb <- body
        result <- liftIO $ runProc proc (LB.unpack wb)
        case result of 
          Left err -> do 
            status status500
            raw (LB.pack err)
          RightThe out - > raw (LB.pack out)

catProc: :Proc 
catProc = Proc { procFuncName = "cat"
               , procName     = "cat"
               , procArgv     = []
               }

getProcByFuncName: :String -> Maybe Proc
getProcByFuncName "cat" = Just catProc
getProcByFuncName _     = Nothing

main = scotty 3000 $ do
    post "/function/:func" $ processHandler getProcByFuncNameCopy the code

Here the FaaS server is complete.

The FaaS server is as simple as that, and there are a few things we need to do in a production environment, such as functions that can be configured.

See func for the complete code