Skip to content

Commit 881b453

Browse files
author
John Hann
committed
Add Expiry type.
1 parent 4cea018 commit 881b453

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

Network/Memcache/Protocol.hs

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ import System.IO
1414
import qualified Data.ByteString as B
1515
import Data.ByteString (ByteString)
1616
import Data.Word
17+
import Data.Time
18+
import Data.Time.Clock.POSIX
1719

1820
-- | Gather results from action until condition is true.
1921
ioUntil :: (a -> Bool) -> IO a -> IO [a]
@@ -41,8 +43,14 @@ hPutCommand h strs = hPutNetLn h (unwords strs) >> hFlush h
4143

4244
type Flags = Word32
4345

46+
data Expiry = Seconds Word32 | Date UTCTime
47+
deriving (Show)
48+
-- figure out how to limit seconds to the memcached limit of 30 days.
49+
4450
newtype Connection = Connection { sHandle :: Handle }
4551

52+
never = Seconds 0
53+
4654
-- connect :: String -> Network.Socket.PortNumber -> IO Connection
4755
connect :: Network.HostName -> Network.PortNumber -> IO Connection
4856
connect host port = do
@@ -63,11 +71,11 @@ stats (Connection handle) = do
6371
(key:rest) -> (key, unwords rest)
6472
[] -> (line, "")
6573

66-
store :: (Key k, Serializable s) => String -> Connection -> Word32 -> Flags -> k -> s -> IO Bool
74+
store :: (Key k, Serializable s) => String -> Connection -> Expiry -> Flags -> k -> s -> IO Bool
6775
store action (Connection handle) exptime flags key val = do
6876
let valstr = serialize val
6977
let bytes = B.length valstr
70-
let cmd = unwords [action, toKey key, show flags, show exptime, show bytes]
78+
let cmd = unwords [action, toKey key, show flags, show (expiryToWord exptime), show bytes]
7179
hPutNetLn handle cmd
7280
hBSPutNetLn handle valstr
7381
hFlush handle
@@ -84,8 +92,8 @@ getOneValue handle = do
8492
return $ Just val
8593
_ -> return Nothing
8694

87-
incDec :: (Key k) => String -> Connection -> Word32 -> k -> Word32 -> IO (Maybe Int)
88-
incDec cmd (Connection handle) exptime key delta = do
95+
incDec :: (Key k) => String -> Connection -> k -> Word32 -> IO (Maybe Int)
96+
incDec cmd (Connection handle) key delta = do
8997
hPutCommand handle [cmd, toKey key, show delta]
9098
response <- hGetNetLn handle
9199
case response of
@@ -107,5 +115,8 @@ delete (Connection handle) key = do
107115
response <- hGetNetLn handle
108116
return (response == "DELETED")
109117

118+
expiryToWord :: Expiry -> Word32
119+
expiryToWord (Seconds s) = max (30 * 24 * 60 * 60) s
120+
expiryToWord (Date d) = floor (utcTimeToPOSIXSeconds d)
110121

111122
-- vim: set ts=2 sw=2 et :

0 commit comments

Comments
 (0)