packages feed

dep-t-value (empty) → 0.1.0.0

raw patch · 11 files changed

+530/−0 lines, 11 filesdep +aesondep +basedep +bytestring

Dependencies added: aeson, base, bytestring, containers, dep-t, dep-t-value, directory, filepath, mtl, split, tasty, tasty-hunit, text, transformers, unliftio-core

Files

+ CHANGELOG.md view
@@ -0,0 +1,5 @@+# Revision history for dep-t-value-sqlite
+
+## 0.1.0.0 -- YYYY-mm-dd
+
+* First version. Released on an unsuspecting world.
+ LICENSE view
@@ -0,0 +1,30 @@+Copyright (c) 2021, Daniel Diaz
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+    * Redistributions of source code must retain the above copyright
+      notice, this list of conditions and the following disclaimer.
+
+    * Redistributions in binary form must reproduce the above
+      copyright notice, this list of conditions and the following
+      disclaimer in the documentation and/or other materials provided
+      with the distribution.
+
+    * Neither the name of Daniel Diaz nor the names of other
+      contributors may be used to endorse or promote products derived
+      from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ README.md view
@@ -0,0 +1,56 @@+# dep-t-value
+
+Pair resources files with types within your program.
+
+Part of the [dep-t-framework](https://github.com/danidiaz/dep-t-framework). 
+
+## How to use
+
+- Take a datatype that you want to associate to a resource file, and derive a `Dep.Resource.FromResource` instance for it.
+
+- Make your program logic take a `Value yourdatatype` record.
+
+- When assembling the global application environment,
+
+    - Use `dataDirLoader` to define a `Loader` that searches for resource files by following the datatype's module path, and uses the dataype's name as file name.
+
+    - Build the `Value yourdatatype` by using functions form `Dep.Value.JSON` or `Dep.Value.Text`.
+
+## Links
+
+- the built-in [`Paths_pkgname` mechanism for accessing data files from package code](https://cabal.readthedocs.io/en/latest/cabal-package.html#accessing-data-files-from-package-code).
+
+- the [data-files](https://cabal.readthedocs.io/en/latest/cabal-package.html#pkg-field-data-files) cabal field.
+
+    > If you decide to import the Paths_pkgname module then it must be listed
+    > in the other-modules field just like any other module in your package and
+    > on autogen-modules as the file is autogenerated.
+
+- the [data-dir](https://cabal.readthedocs.io/en/latest/cabal-package.html#pkg-field-data-dir) cabal field.
+
+- [prefix-independence](https://cabal.readthedocs.io/en/latest/setup-commands.html#prefix-independence)
+
+- [Paths in the simple build system](https://cabal.readthedocs.io/en/latest/setup-commands.html?#paths-in-the-simple-build-system)
+
+- GitHub issue: [Rework data-file handling to be file-embed-like?](https://github.com/haskell/cabal/issues/6096) 
+
+- Another issue, opened by me: [Questions about prefix-independence for data files](https://github.com/haskell/cabal/issues/7888).
+
+- The "prefix-independence" feature seems to be in bad shape:
+
+    when ("${pkgroot}" `isPrefixOf` prefix dirs) $
+      warn verbosity $ "Using ${pkgroot} in prefix " ++ prefix dirs
+                    ++ " will not work if you rely on the Path_* module "
+                    ++ " or other hard coded paths.  Cabal does not yet "
+                    ++ " support fully  relocatable builds! "
+                    ++ " See #462 #2302 #2994 #3305 #3473 #3586 #3909"
+                    ++ " #4097 #4291 #4872"
+
+- However, overriding the data dir using an environment variable is different from "prefix-independence" and it [*does* work](https://cabal.readthedocs.io/en/3.6/cabal-package.html?highlight=data-files#accessing-data-files-from-package-code): 
+
+> The actual location of all these directories can be individually overridden at runtime using environment variables of the form pkg_name_var, where pkg_name is the name of the package with all hyphens converted into underscores, and var is either bindir, libdir, dynlibdir, datadir, libexedir or sysconfdir. For example, the configured data directory for pretty-show is controlled with the pretty_show_datadir environment variable.
+
+- [file-embed: Use Template Haskell to embed file contents directly.](https://hackage.haskell.org/package/file-embed)
+
+- [data-embed: Embed files and other binary blobs inside executables without Template Haskell.](https://hackage.haskell.org/package/data-embed)
+
+ dep-t-value.cabal view
@@ -0,0 +1,51 @@+cabal-version:       3.0
+
+name:                dep-t-value
+version:             0.1.0.0
+synopsis:            Pair resources files with types within your program.
+description:         Pair resources files with types within your program.
+license:             BSD-3-Clause
+license-file:        LICENSE
+author:              Daniel Diaz
+maintainer:          diaz_carrete@yahoo.com
+category:            Control
+extra-source-files:  CHANGELOG.md, README.md
+
+source-repository    head
+  type:     git
+  location: https://github.com/danidiaz/dep-t-value.git
+
+common common
+  build-depends:       base >=4.10.0.0 && < 5,
+                       transformers >= 0.5.0.0,
+                       mtl >= 2.2,
+                       unliftio-core >= 0.2.0.0,
+                       dep-t ^>= 0.6.1.0,
+                       text >= 1.2.5.0,
+                       bytestring >= 0.10.12.0,
+                       aeson >= 2.0.2.0,
+                       split >= 0.2.3,
+                       filepath >= 1.4.0.0,
+                       directory >= 1.3.6.0,
+                       containers >= 0.6.5.1,
+  default-language:    Haskell2010
+
+library
+  import: common
+  exposed-modules:     Dep.Value
+                       Dep.Value.Cached
+                       Dep.Value.JSON
+                       Dep.Value.Text
+                       Dep.Resource
+                       Dep.Loader
+  hs-source-dirs:      lib 
+
+test-suite dep-t-value-test
+  import: common
+  type:                exitcode-stdio-1.0
+  hs-source-dirs:      test
+  main-is:             tests.hs
+  build-depends:       
+    dep-t-value,
+    tasty              >= 1.3.1,
+    tasty-hunit        >= 0.10.0.2,
+ lib/Dep/Loader.hs view
@@ -0,0 +1,166 @@+{-# LANGUAGE AllowAmbiguousTypes #-}
+{-# LANGUAGE BlockArguments #-}
+{-# LANGUAGE DataKinds #-}
+{-# LANGUAGE DefaultSignatures #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE NamedFieldPuns #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TypeApplications #-}
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE UndecidableInstances #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE DerivingStrategies #-}
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+{-# LANGUAGE StandaloneDeriving #-}
+{-# LANGUAGE ViewPatterns #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE DeriveFunctor #-}
+
+-- | Define resource 'Loader's and wire them into 'Value's.
+--
+-- Typically, this module only needs to be imported when creating the global
+-- application environment.
+module Dep.Loader
+  ( 
+    -- * Resource loader.
+    Loader (..),
+    ResourceKey (..),
+    DatatypeName,
+    ModuleName,
+    load,
+    ResourceNotFound (..),
+    -- * Datatypes tied to resources.
+    FromResource (..),
+    -- * Loaders for resources in a directory.
+    dataDirLoader,
+    FileExtension,
+    DataDir,
+    dataDir,
+    extendDataDir,
+  )
+where
+
+import Control.Exception (Exception, throw, throwIO)
+import Control.Monad.IO.Class
+import Control.Monad.Trans.Maybe
+import Data.ByteString
+import Data.Functor
+import Data.List.Split
+import Data.Map.Strict qualified as Map
+import Data.Monoid
+import Data.Proxy
+import GHC.Generics qualified as G
+import GHC.TypeLits (KnownSymbol, symbolVal)
+import System.Directory (doesFileExist)
+import System.FilePath
+import Data.Coerce
+import GHC.Generics qualified
+import System.Console.GetOpt (getOpt)
+import Data.Foldable qualified
+import Data.Typeable
+import Data.Proxy
+import System.Environment (lookupEnv)
+import Dep.Has
+import Dep.Value
+import Data.Aeson qualified 
+import Data.Text
+import Data.Text.Encoding (decodeUtf8')
+import Data.Text.Encoding.Error
+import Data.List.Split
+
+newtype Loader v m =
+   Loader { loadMaybe :: ResourceKey -> m (Maybe v) }
+   deriving G.Generic
+
+-- | Throws 'ResourceNotFound'.
+load :: forall r v m . (FromResource r, Typeable r, Typeable v, Monad m) => Loader v m -> m v
+load loader = do
+  let key = resourceKey @r
+  mb <- loadMaybe loader key
+  case mb of
+    Nothing -> throw $ ResourceNotFound (typeRep (Proxy @r)) key (typeRep (Proxy @v)) 
+    Just b -> pure b
+
+-- | The left 'Loader' is consulted first.
+instance Monad m => Semigroup (Loader v m) where
+  -- KnownKeysLoader l1 <> KnownKeysLoader l2 = KnownKeysLoader (l1 <> l2)
+   Loader f <> Loader g = Loader \key -> do
+     let Alt (MaybeT m) = (coerce f <> coerce g) key
+     m
+
+instance Monad m => Monoid (Loader v m) where
+  mempty = Loader \_ -> pure Nothing
+
+data ResourceKey = ResourceKey
+  { modulePath :: [ModuleName],
+    datatypeName :: DatatypeName
+  }
+  deriving (Show, Eq, Ord)
+
+type DatatypeName = String
+
+type ModuleName = String
+
+type FileExtension = String
+
+-- | Class for datatypes tied to resources.
+--
+-- Derive it with @DeriveAnyClass@. The datatype must have a "GHC.Generics.Generic" instance.
+class FromResource a where
+  resourceKey :: ResourceKey
+  default resourceKey ::
+    forall name mod p n nt x.
+    ( G.Generic a,
+      G.Rep a ~ G.D1 ('G.MetaData name mod p nt) x,
+      KnownSymbol name,
+      KnownSymbol mod
+    ) =>
+    ResourceKey
+  resourceKey = ResourceKey (Data.List.Split.splitOn "." (symbolVal (Proxy @mod))) (symbolVal (Proxy @name))
+
+data ResourceNotFound = ResourceNotFound TypeRep ResourceKey TypeRep deriving (Show)
+
+instance Exception ResourceNotFound
+
+-- | Function that completes a relative `FilePath` pointing to a data file,
+-- and returns its absolute path.
+--
+-- The [@getDataFileName@ function from @Paths_pkgname@](https://cabal.readthedocs.io/en/latest/cabal-package.html#accessing-data-files-from-package-code) is a valid 'DataDir'.
+-- You can also create a 'DataDir' by using 'dataDir'.
+type DataDir = FilePath -> IO FilePath
+
+-- | Build a 'DataDir' out of a base directory path.
+dataDir :: FilePath -> DataDir
+dataDir dirPath filePath = pure (dirPath </> filePath)
+
+-- | Given a relative path to a subdirectory of a 'DataDir', return a 'DataDir'
+-- that completes paths within that subdirectory.
+extendDataDir :: DataDir -> FilePath -> DataDir
+extendDataDir dataDir relDir filePath = dataDir (relDir </> filePath)
+
+-- | A @dataDirLoader ["js", "json"] (dataDir "conf")@ 'Loader' will, for a datatype @Baz@ defined
+-- in module @Foo.Bar@, look for the files @conf\/Foo\/Bar\/Baz.js@ and @conf\/Foo\/Bar\/Baz.json@,
+-- in that order.
+dataDirLoader :: MonadIO m => [FileExtension] -> DataDir -> Loader ByteString m
+dataDirLoader extensions base = Loader \ResourceKey {modulePath, datatypeName} -> do
+  let go [] = do 
+        pure Nothing
+      go (ext : exts) = do
+        let relative = joinPath modulePath </> addExtension datatypeName ext
+        absolute <- liftIO $ base relative
+        mbytes <- readFileMaybe absolute
+        case mbytes of
+          Just bs -> pure $ Just bs
+          Nothing -> go exts
+  go extensions
+  where
+  readFileMaybe :: MonadIO m => FilePath -> m (Maybe ByteString)
+  readFileMaybe absolute = do
+    exists <- liftIO (doesFileExist absolute)
+    if not exists
+      then do
+        pure Nothing
+      else do
+        bytes <- liftIO $ Data.ByteString.readFile absolute
+        pure (Just bytes)
+ lib/Dep/Resource.hs view
@@ -0,0 +1,6 @@+module Dep.Resource (
+    -- * Class for datatypes tied to resources.
+    FromResource
+) where
+
+import Dep.Loader
+ lib/Dep/Value.hs view
@@ -0,0 +1,13 @@+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE FlexibleContexts #-}
+module Dep.Value (
+       -- * A provider of values.
+        Value (..)
+    ) where
+import GHC.Generics qualified as G
+
+-- | Typically injected into program logic using "Dep.Has.Has".
+newtype Value v m = Value { 
+        value :: m v 
+    } deriving G.Generic
+ lib/Dep/Value/Cached.hs view
@@ -0,0 +1,46 @@+{-# LANGUAGE BlockArguments #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE LambdaCase #-}
+{-# LANGUAGE NamedFieldPuns #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TypeApplications #-}
+{-# LANGUAGE ViewPatterns #-}
+-- | Cache 'Value's to avoid repeated calls to the underlying value-obtaining action, which migh be expensive.
+--
+-- Typically, this module only needs to be imported when creating the global application environment.
+module Dep.Value.Cached
+  ( 
+    -- * caching 'Value's
+    Ref,
+    allocateRef,
+    cache,
+  )
+where
+
+import Control.Concurrent.MVar
+import Control.Exception
+import Control.Monad.IO.Class
+import Control.Monad.IO.Unlift
+import Control.Monad.Trans.Cont
+import Dep.Has
+import Dep.Value
+import Data.ByteString
+import Data.Typeable
+import Data.Proxy
+
+type Ref v = MVar (Maybe v)
+
+allocateRef :: MonadIO m => ContT () m (Ref v)
+allocateRef = ContT \f -> do
+  ref <- liftIO $ newMVar Nothing
+  f ref
+
+cache :: MonadUnliftIO m => Ref v -> Value v m -> Value v m
+cache ref Value {value} = Value do
+  run <- askRunInIO
+  liftIO $ modifyMVar ref \case
+    Just v -> do
+      pure (Just v, v)
+    Nothing -> do
+      v <- run value
+      pure (Just v, v)
+ lib/Dep/Value/JSON.hs view
@@ -0,0 +1,39 @@+{-# LANGUAGE BlockArguments #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE UndecidableInstances #-}
+{-# LANGUAGE DerivingStrategies #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE TypeApplications #-}
+
+module Dep.Value.JSON (
+    -- * Constuct 'Value's parsed from JSON.
+    fromBytes,
+    JSONValueDecodeError (..)
+) where
+
+import Data.Aeson qualified 
+import Data.ByteString
+import Data.Typeable
+import Dep.Value
+import Control.Exception
+
+fromBytes ::
+  forall v m e.
+  ( 
+    Typeable v,
+    Data.Aeson.FromJSON v,
+    Monad m
+  ) =>
+  m ByteString ->
+  Value v m
+fromBytes action = Value do
+  bytes <- action
+  case Data.Aeson.eitherDecodeStrict' bytes of
+    Left errMsg -> throw (JSONValueDecodeError (typeRep (Proxy @v)) errMsg)
+    Right r -> pure r
+
+data JSONValueDecodeError = JSONValueDecodeError TypeRep String deriving (Show)
+
+instance Exception JSONValueDecodeError
+ lib/Dep/Value/Text.hs view
@@ -0,0 +1,41 @@+{-# LANGUAGE BlockArguments #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE UndecidableInstances #-}
+{-# LANGUAGE DerivingStrategies #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE TypeApplications #-}
+
+module Dep.Value.Text (
+    -- * Construct 'Text' 'Value's.
+    fromUtf8,
+    TextValueDecodeError (..)
+) where
+
+import Data.Typeable
+import Data.ByteString
+import Dep.Value
+import Control.Exception
+import Data.Text
+import Data.Text.Encoding (decodeUtf8')
+import Data.Text.Encoding.Error
+
+fromUtf8 ::
+  forall v m.
+  ( 
+    Typeable v,
+    Monad m
+  ) =>
+  (Text -> v) ->
+  m ByteString ->
+  Value v m
+fromUtf8 ctor action = Value do
+  bytes <- action
+  case decodeUtf8' bytes of
+    Left uex -> throw (TextValueDecodeError (typeRep (Proxy @v)) uex)
+    Right v -> pure (ctor v)
+
+data TextValueDecodeError = TextValueDecodeError TypeRep UnicodeException deriving (Show)
+
+instance Exception TextValueDecodeError
+ test/tests.hs view
@@ -0,0 +1,77 @@+{-# LANGUAGE ImportQualifiedPost #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE DeriveGeneric #-}
+{-# LANGUAGE StandaloneDeriving #-}
+{-# LANGUAGE DeriveAnyClass #-}
+{-# LANGUAGE DerivingStrategies #-}
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE AllowAmbiguousTypes #-}
+{-# LANGUAGE TypeApplications #-}
+{-# LANGUAGE BlockArguments #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+module Main where
+
+import Test.Tasty
+import Test.Tasty.HUnit
+
+import Dep.Env
+import Dep.Value
+import Dep.Value.Cached
+import Dep.Value.JSON
+import Dep.Value.Text
+import Dep.Loader
+import Data.Functor.Identity
+import Data.Text
+import Data.ByteString
+import GHC.Generics qualified as G
+import Data.IORef
+import Control.Exception
+import Control.Monad.Trans.Cont
+
+-- Orphan instance, just for tests.
+deriving anyclass instance FromResource (Identity Text)
+
+tests :: TestTree
+tests =
+  testGroup
+    "All"
+    [    
+        testCase "loadUtf8" textResourceLoads,
+        testCase "loadUtf8Precedence" textResourcePrecedence,
+        testCase "valueIsCached" valueIsCached
+    ]
+
+textResourceLoads :: Assertion
+textResourceLoads = do
+    let loader :: Loader ByteString IO 
+        loader = dataDirLoader ["zzz","txt"] $ dataDir "test" `extendDataDir` "conf"
+        v = Dep.Value.Text.fromUtf8 Identity (load @(Identity Text) loader)
+    Identity txt <- value v
+    assertEqual "text loaded correctly" (Data.Text.pack "Lorem Ipsum") txt
+
+textResourcePrecedence :: Assertion
+textResourcePrecedence = do
+    let loader :: Loader ByteString IO 
+        loader = dataDirLoader ["zzz","txt"] (dataDir "test" `extendDataDir` "conf2")
+                 <> dataDirLoader ["zzz","txt"] (dataDir "test" `extendDataDir` "conf")
+        v = Dep.Value.Text.fromUtf8 Identity (load @(Identity Text) loader)
+    Identity txt <- value v
+    assertEqual "text loaded correctly" (Data.Text.pack "alternative text") txt
+
+valueIsCached :: Assertion
+valueIsCached = do
+  let bombs = pure () : repeat (throwIO $ userError "boom!")
+  bombsRef <- newIORef @[IO ()] bombs
+  let attempt = do
+        action <- atomicModifyIORef bombsRef \(b : bs) -> (bs, b)
+        action
+  runContT allocateRef \valueRef -> do
+    let v :: Value () IO = Dep.Value.Cached.cache valueRef $ Value attempt
+    () <- value v
+    () <- value v
+    pure ()
+
+main :: IO ()
+main = defaultMain tests