lazy-cache (empty) → 0.2.0.0
raw patch · 12 files changed
+1024/−0 lines, 12 filesdep +HUnitdep +basedep +clocksetup-changed
Dependencies added: HUnit, base, clock, hashable, hspec, lazy-cache, psqueues
Files
- CHANGELOG.md +10/−0
- LICENSE +373/−0
- Readme.md +54/−0
- Setup.hs +2/−0
- lazy-cache.cabal +99/−0
- src/System/Cache.hs +150/−0
- src/System/Cache/Impl/Ghc.hs +86/−0
- src/System/Cache/Impl/MVar.hs +118/−0
- src/System/Cache/Impl/NoCache.hs +20/−0
- src/System/Cache/Internal/Interface.hs +47/−0
- test/Cheops/Cache/CacheSpec.hs +64/−0
- test/Spec.hs +1/−0
+ CHANGELOG.md view
@@ -0,0 +1,10 @@+# Revision history for lazy-cache++## 0.2.0.0 -- 2022-02-06++ * use clock for managing time periods instead of thyme;+ * remove extra dependencies;++## 0.1.0.0 -- 2020-11-15++* Initial layout
+ LICENSE view
@@ -0,0 +1,373 @@+Mozilla Public License Version 2.0+==================================++1. Definitions+--------------++1.1. "Contributor"+ means each individual or legal entity that creates, contributes to+ the creation of, or owns Covered Software.++1.2. "Contributor Version"+ means the combination of the Contributions of others (if any) used+ by a Contributor and that particular Contributor's Contribution.++1.3. "Contribution"+ means Covered Software of a particular Contributor.++1.4. "Covered Software"+ means Source Code Form to which the initial Contributor has attached+ the notice in Exhibit A, the Executable Form of such Source Code+ Form, and Modifications of such Source Code Form, in each case+ including portions thereof.++1.5. "Incompatible With Secondary Licenses"+ means++ (a) that the initial Contributor has attached the notice described+ in Exhibit B to the Covered Software; or++ (b) that the Covered Software was made available under the terms of+ version 1.1 or earlier of the License, but not also under the+ terms of a Secondary License.++1.6. "Executable Form"+ means any form of the work other than Source Code Form.++1.7. "Larger Work"+ means a work that combines Covered Software with other material, in+ a separate file or files, that is not Covered Software.++1.8. "License"+ means this document.++1.9. "Licensable"+ means having the right to grant, to the maximum extent possible,+ whether at the time of the initial grant or subsequently, any and+ all of the rights conveyed by this License.++1.10. "Modifications"+ means any of the following:++ (a) any file in Source Code Form that results from an addition to,+ deletion from, or modification of the contents of Covered+ Software; or++ (b) any new file in Source Code Form that contains any Covered+ Software.++1.11. "Patent Claims" of a Contributor+ means any patent claim(s), including without limitation, method,+ process, and apparatus claims, in any patent Licensable by such+ Contributor that would be infringed, but for the grant of the+ License, by the making, using, selling, offering for sale, having+ made, import, or transfer of either its Contributions or its+ Contributor Version.++1.12. "Secondary License"+ means either the GNU General Public License, Version 2.0, the GNU+ Lesser General Public License, Version 2.1, the GNU Affero General+ Public License, Version 3.0, or any later versions of those+ licenses.++1.13. "Source Code Form"+ means the form of the work preferred for making modifications.++1.14. "You" (or "Your")+ means an individual or a legal entity exercising rights under this+ License. For legal entities, "You" includes any entity that+ controls, is controlled by, or is under common control with You. For+ purposes of this definition, "control" means (a) the power, direct+ or indirect, to cause the direction or management of such entity,+ whether by contract or otherwise, or (b) ownership of more than+ fifty percent (50%) of the outstanding shares or beneficial+ ownership of such entity.++2. License Grants and Conditions+--------------------------------++2.1. Grants++Each Contributor hereby grants You a world-wide, royalty-free,+non-exclusive license:++(a) under intellectual property rights (other than patent or trademark)+ Licensable by such Contributor to use, reproduce, make available,+ modify, display, perform, distribute, and otherwise exploit its+ Contributions, either on an unmodified basis, with Modifications, or+ as part of a Larger Work; and++(b) under Patent Claims of such Contributor to make, use, sell, offer+ for sale, have made, import, and otherwise transfer either its+ Contributions or its Contributor Version.++2.2. Effective Date++The licenses granted in Section 2.1 with respect to any Contribution+become effective for each Contribution on the date the Contributor first+distributes such Contribution.++2.3. Limitations on Grant Scope++The licenses granted in this Section 2 are the only rights granted under+this License. No additional rights or licenses will be implied from the+distribution or licensing of Covered Software under this License.+Notwithstanding Section 2.1(b) above, no patent license is granted by a+Contributor:++(a) for any code that a Contributor has removed from Covered Software;+ or++(b) for infringements caused by: (i) Your and any other third party's+ modifications of Covered Software, or (ii) the combination of its+ Contributions with other software (except as part of its Contributor+ Version); or++(c) under Patent Claims infringed by Covered Software in the absence of+ its Contributions.++This License does not grant any rights in the trademarks, service marks,+or logos of any Contributor (except as may be necessary to comply with+the notice requirements in Section 3.4).++2.4. Subsequent Licenses++No Contributor makes additional grants as a result of Your choice to+distribute the Covered Software under a subsequent version of this+License (see Section 10.2) or under the terms of a Secondary License (if+permitted under the terms of Section 3.3).++2.5. Representation++Each Contributor represents that the Contributor believes its+Contributions are its original creation(s) or it has sufficient rights+to grant the rights to its Contributions conveyed by this License.++2.6. Fair Use++This License is not intended to limit any rights You have under+applicable copyright doctrines of fair use, fair dealing, or other+equivalents.++2.7. Conditions++Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted+in Section 2.1.++3. Responsibilities+-------------------++3.1. Distribution of Source Form++All distribution of Covered Software in Source Code Form, including any+Modifications that You create or to which You contribute, must be under+the terms of this License. You must inform recipients that the Source+Code Form of the Covered Software is governed by the terms of this+License, and how they can obtain a copy of this License. You may not+attempt to alter or restrict the recipients' rights in the Source Code+Form.++3.2. Distribution of Executable Form++If You distribute Covered Software in Executable Form then:++(a) such Covered Software must also be made available in Source Code+ Form, as described in Section 3.1, and You must inform recipients of+ the Executable Form how they can obtain a copy of such Source Code+ Form by reasonable means in a timely manner, at a charge no more+ than the cost of distribution to the recipient; and++(b) You may distribute such Executable Form under the terms of this+ License, or sublicense it under different terms, provided that the+ license for the Executable Form does not attempt to limit or alter+ the recipients' rights in the Source Code Form under this License.++3.3. Distribution of a Larger Work++You may create and distribute a Larger Work under terms of Your choice,+provided that You also comply with the requirements of this License for+the Covered Software. If the Larger Work is a combination of Covered+Software with a work governed by one or more Secondary Licenses, and the+Covered Software is not Incompatible With Secondary Licenses, this+License permits You to additionally distribute such Covered Software+under the terms of such Secondary License(s), so that the recipient of+the Larger Work may, at their option, further distribute the Covered+Software under the terms of either this License or such Secondary+License(s).++3.4. Notices++You may not remove or alter the substance of any license notices+(including copyright notices, patent notices, disclaimers of warranty,+or limitations of liability) contained within the Source Code Form of+the Covered Software, except that You may alter any license notices to+the extent required to remedy known factual inaccuracies.++3.5. Application of Additional Terms++You may choose to offer, and to charge a fee for, warranty, support,+indemnity or liability obligations to one or more recipients of Covered+Software. However, You may do so only on Your own behalf, and not on+behalf of any Contributor. You must make it absolutely clear that any+such warranty, support, indemnity, or liability obligation is offered by+You alone, and You hereby agree to indemnify every Contributor for any+liability incurred by such Contributor as a result of warranty, support,+indemnity or liability terms You offer. You may include additional+disclaimers of warranty and limitations of liability specific to any+jurisdiction.++4. Inability to Comply Due to Statute or Regulation+---------------------------------------------------++If it is impossible for You to comply with any of the terms of this+License with respect to some or all of the Covered Software due to+statute, judicial order, or regulation then You must: (a) comply with+the terms of this License to the maximum extent possible; and (b)+describe the limitations and the code they affect. Such description must+be placed in a text file included with all distributions of the Covered+Software under this License. Except to the extent prohibited by statute+or regulation, such description must be sufficiently detailed for a+recipient of ordinary skill to be able to understand it.++5. Termination+--------------++5.1. The rights granted under this License will terminate automatically+if You fail to comply with any of its terms. However, if You become+compliant, then the rights granted under this License from a particular+Contributor are reinstated (a) provisionally, unless and until such+Contributor explicitly and finally terminates Your grants, and (b) on an+ongoing basis, if such Contributor fails to notify You of the+non-compliance by some reasonable means prior to 60 days after You have+come back into compliance. Moreover, Your grants from a particular+Contributor are reinstated on an ongoing basis if such Contributor+notifies You of the non-compliance by some reasonable means, this is the+first time You have received notice of non-compliance with this License+from such Contributor, and You become compliant prior to 30 days after+Your receipt of the notice.++5.2. If You initiate litigation against any entity by asserting a patent+infringement claim (excluding declaratory judgment actions,+counter-claims, and cross-claims) alleging that a Contributor Version+directly or indirectly infringes any patent, then the rights granted to+You by any and all Contributors for the Covered Software under Section+2.1 of this License shall terminate.++5.3. In the event of termination under Sections 5.1 or 5.2 above, all+end user license agreements (excluding distributors and resellers) which+have been validly granted by You or Your distributors under this License+prior to termination shall survive termination.++************************************************************************+* *+* 6. Disclaimer of Warranty *+* ------------------------- *+* *+* Covered Software is provided under this License on an "as is" *+* basis, without warranty of any kind, either expressed, implied, or *+* statutory, including, without limitation, warranties that the *+* Covered Software is free of defects, merchantable, fit for a *+* particular purpose or non-infringing. The entire risk as to the *+* quality and performance of the Covered Software is with You. *+* Should any Covered Software prove defective in any respect, You *+* (not any Contributor) assume the cost of any necessary servicing, *+* repair, or correction. This disclaimer of warranty constitutes an *+* essential part of this License. No use of any Covered Software is *+* authorized under this License except under this disclaimer. *+* *+************************************************************************++************************************************************************+* *+* 7. Limitation of Liability *+* -------------------------- *+* *+* Under no circumstances and under no legal theory, whether tort *+* (including negligence), contract, or otherwise, shall any *+* Contributor, or anyone who distributes Covered Software as *+* permitted above, be liable to You for any direct, indirect, *+* special, incidental, or consequential damages of any character *+* including, without limitation, damages for lost profits, loss of *+* goodwill, work stoppage, computer failure or malfunction, or any *+* and all other commercial damages or losses, even if such party *+* shall have been informed of the possibility of such damages. This *+* limitation of liability shall not apply to liability for death or *+* personal injury resulting from such party's negligence to the *+* extent applicable law prohibits such limitation. Some *+* jurisdictions do not allow the exclusion or limitation of *+* incidental or consequential damages, so this exclusion and *+* limitation may not apply to You. *+* *+************************************************************************++8. Litigation+-------------++Any litigation relating to this License may be brought only in the+courts of a jurisdiction where the defendant maintains its principal+place of business and such litigation shall be governed by laws of that+jurisdiction, without reference to its conflict-of-law provisions.+Nothing in this Section shall prevent a party's ability to bring+cross-claims or counter-claims.++9. Miscellaneous+----------------++This License represents the complete agreement concerning the subject+matter hereof. If any provision of this License is held to be+unenforceable, such provision shall be reformed only to the extent+necessary to make it enforceable. Any law or regulation which provides+that the language of a contract shall be construed against the drafter+shall not be used to construe this License against a Contributor.++10. Versions of the License+---------------------------++10.1. New Versions++Mozilla Foundation is the license steward. Except as provided in Section+10.3, no one other than the license steward has the right to modify or+publish new versions of this License. Each version will be given a+distinguishing version number.++10.2. Effect of New Versions++You may distribute the Covered Software under the terms of the version+of the License under which You originally received the Covered Software,+or under the terms of any subsequent version published by the license+steward.++10.3. Modified Versions++If you create software not governed by this License, and you want to+create a new license for such software, you may create and use a+modified version of this License if you rename the license and remove+any references to the name of the license steward (except to note that+such modified license differs from this License).++10.4. Distributing Source Code Form that is Incompatible With Secondary+Licenses++If You choose to distribute Source Code Form that is Incompatible With+Secondary Licenses under the terms of this version of the License, the+notice described in Exhibit B of this License must be attached.++Exhibit A - Source Code Form License Notice+-------------------------------------------++ This Source Code Form is subject to the terms of the Mozilla Public+ License, v. 2.0. If a copy of the MPL was not distributed with this+ file, You can obtain one at http://mozilla.org/MPL/2.0/.++If it is not possible or desirable to put the notice in a particular+file, then You may include the notice in a location (such as a LICENSE+file in a relevant directory) where a recipient would be likely to look+for such a notice.++You may add additional accurate notices of copyright ownership.++Exhibit B - "Incompatible With Secondary Licenses" Notice+---------------------------------------------------------++ This Source Code Form is "Incompatible With Secondary Licenses", as+ defined by the Mozilla Public License, v. 2.0.
+ Readme.md view
@@ -0,0 +1,54 @@+# Library for caching values.++The library allows to cache result of an asynchronous computation for+no longer than a given period of time.++# How to use++In order to use the package you should add the package to the dependency+section of the cabal file of your package.++In order to use the cache you should create a 'Handle'++```haskell+{-# LANGUAGE ImportQualifiedPost #-}+{-# LANGUAGE NumericUnderscores #-}+{-# LANGUAGE BlockArguments #-}+import Control.Concurrent++import System.Cache qualified as Cache+import System.Cache.Impl.Ghc qualified as Cache.Ghc+import System.Clock.Seconds++main :: IO ()+main = do+ cache <- Cache.Ghc.new do+ Cache.mkConfig 60 Monotonic+ -- we create a cached version of computation+ -- in order to hide implementation+ let cachedTimeout input = Cache.requestOr cache input \i -> do+ threadDelay $ i * 1_000_000+ pure i+ -- We use our cached function+ print (cachedTimeout 1)+ print (cachedTimeout 1)+ print (cachedTimeout 2)+```++```+sh-3.2$ runhaskell local.hs | ts -S+00:00:03 2+00:00:03 2+00:00:06 3+```++When running the program first we wait for 2 seconds, the next call returns immediately.+The third one is long as it uses a new input value.+++# Developing the package++```+cabal configure+cabal build+```
+ Setup.hs view
@@ -0,0 +1,2 @@+import Distribution.Simple+main = defaultMain
+ lazy-cache.cabal view
@@ -0,0 +1,99 @@+cabal-version: >=1.10+name: lazy-cache+synopsis: Library for caching IO action that leverages on GHC RTS implementation+version: 0.2.0.0+author: Alexander Vershilov+maintainer: backend-dev@sirius.online+copyright: 2019-2022 (C) Фонд "Талант и Успех"+license: MPL-2.0+license-file: LICENSE+build-type: Simple+category: System+description: The library provides an interface for caching the results of IO actions.+ This library relies on a blackholing — mechanism that is used to implement lazy+ evaluation for avoiding concurrent runs of the action+ (this is where the name of the library comes from).+ .+ The library provides caching mechanismsl with the following properties:+ .+ 1. when the function is called the successful result is cached by no more than a provided time;+ 2. if the function ends with an exception, it will be rethrown, and the result will not be cached;+ 3. if the function will be called with the same input value it immediately gets cached+ result;+ 4. if functions are called concurrently with the different input values they will not+ block each other;+ 5. if functions will be called concurrently with the same argument then only one will+ act, others will wait until the first one is finished and will either return the+ result once it's received, or will rethrow an exception if the first one+ exits with an exception;+ 6. outdated values are cleared only on accesses to the cache, so if no action is called+ the data will not be cleared.+ .+ The main entry point of the library is "System.Cache" module, it explains how to+ use the library and provides the public API, that does not depend on the actual+ store implementation.+ .+ The library provides an interface for caching, and three implementations:+ .+ 1. "System.Cache.Impl.Ghc" — the main one based on GHC system;++ 2. "System.Cache.Impl.MVar" — implementation based on library functions;++ 3. "System.Cache.Impl.NoCache" — implementation that disables caching, but keeps the same interface + .+ If you want to implement your own caching mechanism, or use internal API, you+ can refer to the "System.Cache.Internal.Interface" module for an additional documentation.+extra-source-files:+ CHANGELOG.md+ Readme.md++tested-with:+ GHC == 9.2.2+ || == 8.10.7++source-repository head+ type: git+ location: https://github.com/cheopslab/lazy-cache++library+ exposed-modules:+ System.Cache+ System.Cache.Impl.Ghc+ System.Cache.Impl.MVar+ System.Cache.Impl.NoCache+ System.Cache.Internal.Interface+ other-extensions:+ RecursiveDo+ TemplateHaskell+ build-depends:+ base >=4.12 && <5,+ hashable >=1.1.2.3 && <1.5,+ psqueues >=0.2 && <0.3,+ clock >= 0.8+ hs-source-dirs: src+ ghc-options: -Wall+ default-language: Haskell2010+ default-extensions:+ LambdaCase+ NumericUnderscores+ OverloadedStrings+ RecordWildCards+ ScopedTypeVariables++test-suite spec+ type: exitcode-stdio-1.0+ main-is: Spec.hs+ other-modules:+ Cheops.Cache.CacheSpec+ hs-source-dirs:+ test+ ghc-options: -Wall -threaded -rtsopts -with-rtsopts=-N+ build-tool-depends: hspec-discover:hspec-discover+ build-depends:+ HUnit+ , base >=4.7 && <5+ , lazy-cache+ , hashable+ , hspec+ , clock+ default-language: Haskell2010
+ src/System/Cache.hs view
@@ -0,0 +1,150 @@+{-# LANGUAGE RecursiveDo #-}+{-# LANGUAGE TemplateHaskell #-}+-- |+-- General interface for the cache. This module is intended to be used+-- in th user code.+--+-- __TLDR__+-- +-- @+-- {-# LANGUAGE ImportQualifiedPost #-}+-- {-# LANGUAGE NumericUnderscores #-}+-- {-# LANGUAGE BlockArguments #-}+-- import Control.Concurrent+-- +-- import "System.Cache" qualified as Cache+-- import "System.Cache.Impl.Ghc" qualified as Cache.Ghc+-- import System.Clock.Seconds+-- +-- main :: IO ()+-- main = do+-- -- we create a new cache handle that acts as a storage for+-- -- cached values+-- cache <- Cache.Ghc.'System.Cache.Impl.Ghc.new' do+-- Cache.'System.Cache.mkConfig' 60 'System.Clock.Seconds.MonotonicCoarse'+-- -- we create a cached version of computation+-- -- in order to hide implementation+-- let cachedTimeout = Cache.'System.Cache.mkCached' @cache@ \i -> do+-- threadDelay $ i * 1_000_000+-- pure i+-- -- We use our cached function+-- print (cachedTimeout 1)+-- @+--+module System.Cache+ ( -- * API+ -- ** Create+ -- $api1+ Handle+ -- $api2+ , Config+ , mkConfig+ -- ** Use+ -- $api3+ , requestOr+ -- $api4+ , cacheIO+ -- * Helpers+ -- $helpers+ , new+ , mkCached+ ) where++import Data.Functor+import Data.Hashable+import System.Clock.Seconds++import System.Cache.Internal.Interface+import qualified System.Cache.Impl.Ghc as Ghc+import qualified System.Cache.Impl.MVar as MVar+import System.Environment+import System.IO.Unsafe++-- $api1+--+-- In order to use this library you first need to explicitly create a storage+-- for the values. This storage is implemented by the abstract type 'Handle' that+-- provides only a public function interface but hides an actual implementation.+-- You can find full description of the 'Handle' in the "System.Cache.Internal.Interface"+-- module.++-- $api2+--+-- In order to create a 'Handle' you'll need to call appropiate function from the+-- @System.Cache.Impl.\*.new@ module. This way you can chose an actual implementation.+-- Alternatively you can use 'System.Cache.new' function that will make a choise for you, or+-- create your own implementation.+--+-- Each of those functions take a 'Config' as a parameter++-- $api3+--+-- Once the storage is created you can use it for caching values via 'requestOr' method.++-- $api4+--+-- The API of the method is not safe enough because you can for example ignore input+-- value in the funciton, or pass different function in different invocations with the +-- same storage. One the one hand we do not want to prevent such usages as may be done+-- for a purpose, but in order to provide additional safety we provide more safe methods:++-- | Helper to create a config.+mkConfig+ :: Int -- ^ Max time that the value can be cached (in seconds).+ -> Clock -- ^ Type of the clock that the cache will use.+ -> Config+mkConfig n clock = Config+ { configLongestAge = fromNanoSecs (fromIntegral n * 1_000_000_000)+ , configClock = clock+ }+++-- | Perform a request.+requestOr+ :: Handle a b+ -> a -- ^ Input parameters+ -> (a -> IO b) -- ^ Function to cache.+ -> IO b -- ^ Result.+requestOr Handle {..} k f = do+ tm <- getClockTime+ requestOrInternal tm k f++-- | Wraps an IO action and returns a cached version of that method.+cacheIO+ :: Handle a b -- ^ Values storage+ -> (a -> IO b) -- ^ Action to cache+ -> (a -> IO b) -- ^ A version that caches the result+cacheIO handle f = \k -> requestOr handle k f++-- | Set default cache implementation. This method perfers to use +-- "System.Cache.Impl.Ghc" implementation unless @GHC_CACHE_IMPL@ environment value+-- has value @MVAR@ in this case "System.Cache.Impl.MVar" is used.+--+-- This method is useful as a default one because it prefers a faster and stabler+-- implementation, but in case of emergency it allows to switch to the conservative+-- implementation without program recompilation.+--+-- __N.B.__ this methos uses 'unsafePerformIO'.+new+ :: (Show a, Hashable a, Ord a)+ => Config+ -> IO (Handle a b)+{-# NOINLINE new #-}+new = unsafePerformIO $ do+ lookupEnv "GHC_CACHE_IMPL" >>= \case+ Just "MVAR" -> pure $ MVar.new+ _ -> pure $ Ghc.new++-- | Wrapper for creatio cached values. This wrapper does not expose raw 'Handle',+-- so it will not be possible to unexpectedly reuse between different methods.+--+-- @+-- cachedIO <- 'mkCached' 'System.Cache.Impl.Ghc.new' config io+-- @+mkCached+ :: (Config -> IO (Handle a b)) -- ^ Create handle function+ -> Config -- ^ Config for caching+ -> (a -> IO b) -- ^ Action to cache+ -> IO (a -> IO b) -- ^ Version that caches the result+mkCached mk config f =+ mk config <&> \handle -> cacheIO handle f
+ src/System/Cache/Impl/Ghc.hs view
@@ -0,0 +1,86 @@+{-# LANGUAGE RecursiveDo #-}+-- | Caching based on the GHC heap object properties and relies on lazyness implementation+-- in the GHC RTS. This approach does it's best effort for avoiding the duplicated work, +-- however it the pathological cases it's possible that two theads will run the computation+-- on the same input concurrently. We have not observed this case in practice, but in the+-- case if you need strict guarantees on this property you should use "System.Cache.Impl.MVar"+-- instead.+--+-- This is battle-tested implementation. That fits all the properties that are required by the+-- interface.+--+module System.Cache.Impl.Ghc+ ( new+ ) where++import Control.Exception+import Data.Hashable+import Data.HashPSQ as PSQ+import Data.IORef+import Data.Tuple+import Control.Monad+import System.Clock.Seconds++import System.Cache.Internal.Interface++-- | We need our internal values to be even more lazy, in order+-- to prevent early evaluation and deadlock.+data Lazy a = Lazy { getLazy :: a}++-- | Creates new cache Handle. Keeps priotity queue from @psqueues@ package inside.+--+-- Properties:+--+-- * if multiple threads are running an IO action with the same input+-- concurrently then only one (with the best effort) will run, all+-- the rest will wait for that action and will either return a value,+-- or throw an exception depending on the the result of the first one+-- * storage is cleared only during access, it will remove redundant work+-- but may lead to the situation when cached values are stored in memory+-- for a longer period that it was expected+-- * psqueue structure uses both 'Hashable' and 'Ord' constraints and is+-- not vulnerable to the hash collision attacks.+--+new+ :: (Show a, Hashable a, Ord a)+ => Config+ -> IO (Handle a b)+new Config {..} = do+ ref <- newIORef PSQ.empty+ pure $ Handle+ { requestOrInternal = \tm k f -> mdo+ mbox <-+ atomicModifyIORef ref+ $ swap+ . PSQ.alter+ (\case+ Just (p, ~v) | p >= diffTimeSpec tm configLongestAge ->+ (Just v, Just (p, v))+ _ -> (Nothing, Just (tm, Lazy eresult))+ )+ k+ eresult <- try $ maybe+ (f k)+ (\r -> do+ evaluate (getLazy r) >>= \case+ Left s -> throwIO s+ Right x -> pure x+ )+ mbox+ result <- case eresult of+ Left (s::SomeException) -> do+ atomicModifyIORef' ref $ \v -> (PSQ.delete k v, ())+ throwIO s+ Right x -> pure x+ atomicModifyIORef' ref $ swap . PSQ.alterMin+ (\case+ Nothing -> ((), Nothing)+ Just (kk, p, v)+ | p < diffTimeSpec tm configLongestAge -> ((), Nothing)+ | otherwise -> ((), Just (kk, p, v))+ )+ pure result+ , remove = \k -> do+ void $ atomicModifyIORef ref $ swap . PSQ.alter (const ((), Nothing)) k+ , getClockTime = getTime configClock+ }
+ src/System/Cache/Impl/MVar.hs view
@@ -0,0 +1,118 @@+-- | Safer cache version that is implemented totally+-- on the user level. Using 'MVar' as a synchronization+-- primitive.+--+-- While this implementation is slower in general case it may+-- be more resilient to changes in GHC and RTS. This implementation+-- is mostly used in order to sanity check the GHC one, and in order+-- to be able to switch to this one without program recompilation.+--+-- However if you need strict guarantees that the only one action with+-- the same input is run concurrently you should prefer this implementation.+module System.Cache.Impl.MVar+ ( new+ ) where++import Control.Concurrent+import Control.Exception+import Control.Monad+import Data.HashPSQ as PSQ+import Data.Hashable+import Data.IORef+import Data.Tuple+import System.Clock.Seconds++import System.Cache.Internal.Interface++-- | Create new cache handle. Keeps priority queue from psqueues package inside.+--+-- Properties:+--+-- * if multiple threads are running an IO action with the same input+-- concurrently then only one will run, all the rest will wait for that+-- action and will either return a value, or throw an exception depending+-- on the the result of the first one+-- * storage is cleared only during access, it will remove redundant work+-- but may lead to the situation when cached values are stored in memory+-- for a longer period that it was expected+-- * psqueue structure uses both 'Hashable' and 'Ord' constraints and is+-- not vulnerable to the hash collision attacks.+--+new+ :: (Show a, Hashable a, Ord a)+ => Config+ -> IO (Handle a b)+new cfg@Config {..} = do+ ref <- newIORef PSQ.empty+ pure $ Handle+ { requestOrInternal = \tm k f -> do+ queue <- readIORef ref+ result+ <- case PSQ.lookup k queue of+ Nothing -> insertElement cfg ref tm k f+ Just (p, (r, lock)) -> do+ readIORef r >>= \case+ Nothing+ -> updateLock cfg ref lock r tm k f+ Just v+ | p >= tm - configLongestAge -> pure v+ | otherwise -> updateLock cfg ref lock r tm k f+ atomicModifyIORef' ref $ swap . PSQ.alterMin+ (\case+ Nothing -> ((), Nothing)+ Just (kk, p, v)+ | p < tm - configLongestAge -> ((), Nothing)+ | otherwise -> ((), Just (kk, p, v))+ )+ pure result+ , remove = \k -> do+ void $ atomicModifyIORef ref $ swap . PSQ.alter (const ((), Nothing)) k+ , getClockTime = getTime configClock+ }++-- | There is no value in the queue, but someone may already trying to create a lock,+-- so we need to register a lock, verifying that it was registered concurrently.+insertElement :: (Hashable k, Ord k)+ => Config+ -> IORef (HashPSQ k Seconds (IORef (Maybe z), MVar (Maybe (Seconds, z))))+ -> Seconds+ -> k+ -> (k -> IO z)+ -> IO z+insertElement cfg ref tm k f = newEmptyMVar >>= \x -> go x `onException` (tryPutMVar x Nothing) where+ go our_lock = do+ result_box <- newIORef Nothing+ update_result+ <- atomicModifyIORef ref $ swap .+ PSQ.alter+ (\case+ Just x@(_, their_lock) -> (Just their_lock, Just x)+ Nothing -> (Nothing, Just (tm, (result_box, our_lock)))+ ) k+ case update_result of+ Just (r, their_lock)+ -> updateLock cfg ref their_lock r tm k f -- Someone else managed to insert the lock, first.+ Nothing -> do+ -- We are holding a lock, so we need to evaluate value and register it+ value <- f k+ putMVar our_lock (Just (tm, value))+ writeIORef result_box (Just value)+ pure value++updateLock :: (Hashable k, Ord k)+ => Config+ -> IORef (HashPSQ k Seconds (IORef (Maybe z), MVar (Maybe (Seconds, z))))+ -> MVar (Maybe (Seconds, z))+ -> IORef (Maybe z)+ -> Seconds + -> k+ -> (k -> IO z)+ -> IO z+updateLock Config{..} ref lock inner tm k f = modifyMVar lock $ \case+ Just x@(p, v) -- Result exists and is valid, we can just return it+ | p >= tm - configLongestAge -> pure (Just x, v)+ _ -> do -- There is no result or it's outdated, we can update it.+ value <- f k+ writeIORef inner (Just value)+ atomicModifyIORef ref (\queue -> (PSQ.insert k tm (inner,lock) queue, ()))+ pure (Just (tm, value), value)
+ src/System/Cache/Impl/NoCache.hs view
@@ -0,0 +1,20 @@+{-# LANGUAGE RecursiveDo #-}+-- | Implementation that provides no caching at all.+-- Can be useful in order to disable caching without changing+-- the code at the use sites.+module System.Cache.Impl.NoCache+ ( new+ ) where++import System.Cache.Internal.Interface+import System.Clock.Seconds++-- | Creates an implementation that does not cache anything.+-- All actions runs as-is without locking.+new :: Config -> IO (Handle a b)+new Config{..} = do+ pure $ Handle+ { requestOrInternal = \_ k f -> f k+ , remove = \_ -> pure ()+ , getClockTime = getTime configClock+ }
+ src/System/Cache/Internal/Interface.hs view
@@ -0,0 +1,47 @@+-- | +--+-- Internal interface for the Cache handle. In general you are not interested in this+-- module and should use public API from the "System.Cache" instead, unless:+--+-- 1. you need to implement your own handle,+-- 2. you need to use internal functions like 'remove',+-- 3. you need to provide your own 'getClockTime' implementation +--+--+module System.Cache.Internal.Interface+ ( Handle(..)+ , Config(..)+ ) where++import System.Clock.Seconds++-- | The public interface for the cache values storage.+--+-- A storage is expected to provide the following properties:+--+-- 1. If the function return succesfully then the result should be cached for a time period,+-- All later calls should return the cached value.+-- 2. In case of the concurrent actions an implementation should be the best effort to avoid+-- reduntant calls+data Handle a b = Handle+ { requestOrInternal :: Seconds -> a -> (a -> IO b) -> IO b+ -- ^ runs an action @f@ that takes a parameter @a@ and stores successful + -- result for time no longer than @s@.+ , remove :: a -> IO ()+ -- ^ removes the result cached for input @a@.+ , getClockTime :: IO Seconds+ -- ^ finds current time.+ }++-- | Configuration for 'Cache'+--+-- See "System.Cache.Internal.Interface" for all details on the fields.+data Config = Config+ { configLongestAge :: Seconds+ -- ^ The time that the value can be kept in cache.+ , configClock :: Clock+ -- ^ Type of the clock that is used by cache, by changing this parameter you can+ -- optimize your usage for the different use cases, see "System.Clock.Seconds"+ -- documentation for explanation of the choises.+ }+
+ test/Cheops/Cache/CacheSpec.hs view
@@ -0,0 +1,64 @@+{-# LANGUAGE RankNTypes #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE NumericUnderscores #-}+module Cheops.Cache.CacheSpec where++import Control.Exception+import Data.IORef+import System.Clock.Seconds+import Data.Hashable+import Test.Hspec+import Test.HUnit.Base ((@=?))++import qualified System.Cache as Cache+import qualified System.Cache.Impl.Ghc as Ghc+import qualified System.Cache.Impl.MVar as MVar+import System.Cache.Internal.Interface as Cache++spec :: Spec+spec = do+ describe "GHC" $ inner (Ghc.new)+ describe "MVar" $ inner (MVar.new)++inner :: (forall a b . (Show a, Hashable a, Ord a) => Cache.Config -> IO (Cache.Handle a b)) -> Spec+inner new = describe "Cache service" $ do+ let configClock = Monotonic+ let configLongestAge = fromNanoSecs (100 * 1_000_000_000)+ it "cache store values" $ do+ ch <- new Cache.Config{..}+ ir <- newIORef True+ let+ f _ = do+ firstTime <- readIORef ir+ if firstTime then writeIORef ir False >> pure 0 else pure 1+ ((0 :: Int) @=?) =<< Cache.requestOr ch () f+ ((0 :: Int) @=?) =<< Cache.requestOr ch () f+ it "honour input" $ do+ ch <- new Cache.Config{..}+ let f x = pure x+ ((3 :: Int) @=?) =<< Cache.requestOr ch 3 f+ ((4 :: Int) @=?) =<< Cache.requestOr ch 4 f+ ((3 :: Int) @=?) =<< Cache.requestOr ch 3 f+ it "drops caches" $ do+ ch <- new Cache.Config{ configLongestAge = fromNanoSecs 0, ..}+ ir <- newIORef True+ let+ f _ = do+ firstTime <- readIORef ir+ if firstTime then writeIORef ir False >> pure 0 else pure 1+ ((0 :: Int) @=?)+ =<< Cache.requestOrInternal ch (fromNanoSecs (0)) () f+ ((1 :: Int) @=?)+ =<< Cache.requestOrInternal ch (fromNanoSecs (2 * 1_000_000_000)) () f+ it "handles exceptions" $ do+ ch <- new Cache.Config{..} :: IO (Cache.Handle Int Int)+ ((Left (ErrorCall "foo")) @=?) =<<+ either (\(ErrorCallWithLocation s _) -> Left (ErrorCall s)) Right+ <$> try (Cache.requestOr ch (3::Int) (\_ -> error "foo"))+ -- second call is still ok+ ((Left (ErrorCall "bar")) @=?) =<<+ either (\(ErrorCallWithLocation s _) -> Left (ErrorCall s)) Right+ <$> try (Cache.requestOr ch (3::Int) (\_ -> error "bar"))+ (Right 4 @=?) =<<+ either (\(ErrorCallWithLocation s _) -> Left (ErrorCall s)) Right+ <$> try (Cache.requestOr ch (3::Int) (\_ -> pure 4))
+ test/Spec.hs view
@@ -0,0 +1,1 @@+{-# OPTIONS_GHC -F -pgmF hspec-discover #-}