theam / aws-lambda-haskell-runtime

⚡Haskell runtime for AWS Lambda
https://theam.github.io/aws-lambda-haskell-runtime/
Other
269 stars 48 forks source link

Persistent execution context #72

Closed dnikolovv closed 4 years ago

dnikolovv commented 4 years ago

The Context now takes a parameter that contains your custom application context. In your custom context you can contain various things such as db connections, configuration, etc.

Your custom context will be initialized once and kept alive while the lambda is warm. You can also make changes to it during your call by mutating the IORef that contains it.

Usage:

data Config =
  Config
    { configConnectionPool :: ConnectionPool
    , configLogEnv         :: LogEnv
    , configCounter        :: Int }

handler :: Request -> Context Config -> IO (Either Error Response)
handler request context = do
  let configRef = customContext context
  config <- readIORef configRef
  -- You can use your config now
  runDbAction (configConnectionPool config) action
  -- You can change your context during your execution by modifying configRef
  -- On the next lambda call, the context counter will be incremented
  modifyIORef configRef (\c -> c { configCounter = (configCounter c + 1) })

Breaking changes:

Besides always needing to specify the additional context (of course you could always do Context ()), there is one more breaking change:

In your Main.hs file, you must have a function called initializedContext that is of type IO context. This function will be called every cold start.

initializeContext :: IO Config
initializeContext = Server.getConfig

generateLambdaDispatcher StandaloneLambda defaultDispatcherOptions

Perhaps this should be a major version bump?

Closes #60. Closes #73. Closes #74.

@NickSeagull It's definitely not perfect, but I think this is ready for review.

NickSeagull commented 4 years ago

Thank you very much for this, this is sure a great improvement!