Skip to content

Commit

Permalink
Merge pull request #97 from serokell/diogo/OverloadedRecordDot
Browse files Browse the repository at this point in the history
[Chore] Avoid `RecordWildCards`
  • Loading branch information
dcastro authored Aug 31, 2023
2 parents 0f7b4f5 + 8637e2f commit a37dd4c
Show file tree
Hide file tree
Showing 15 changed files with 137 additions and 141 deletions.
20 changes: 10 additions & 10 deletions src/TzBot/BotMain.hs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ dumpConfig = \case
run :: Options -> IO ()
run opts = do
let mbConfigFilePath = oConfigFile opts
bsConfig@Config {..} <- readConfig mbConfigFilePath
bsConfig <- readConfig mbConfigFilePath
runManaged $ do

let fifteenPercentAmplitudeSettings = defaultTzCacheSettings
Expand All @@ -73,33 +73,33 @@ run opts = do
let extractShutdownFunction :: IO () -> IO ()
extractShutdownFunction = writeIORef gracefulShutdownContainer
let sCfg = defaultSlackConfig
& setApiToken (unBotToken cBotToken)
& setAppToken (unAppLevelToken cAppToken)
& setApiToken (unBotToken bsConfig.cBotToken)
& setAppToken (unAppLevelToken bsConfig.cAppToken)
& setOnException handleThreadExceptionSensibly -- auto-handle disconnects
& setGracefulShutdownHandler extractShutdownFunction

bsManager <- liftIO $ newManager tlsManagerSettings
bsFeedbackConfig <-
managed $ withFeedbackConfig bsConfig
bsUserInfoCache <-
managed $ withTzCache fifteenPercentAmplitudeSettings cCacheUsersInfo
managed $ withTzCache fifteenPercentAmplitudeSettings bsConfig.cCacheUsersInfo
bsConversationMembersCache <-
managed $ withTzCache fifteenPercentAmplitudeSettings cCacheConversationMembers
managed $ withTzCache fifteenPercentAmplitudeSettings bsConfig.cCacheConversationMembers
let defaultMessageInfoCachingTime = hour 1
bsMessageCache <-
managed $ withTzCacheDefault defaultMessageInfoCachingTime
bsMessageLinkCache <-
managed $ withTzCacheDefault defaultMessageInfoCachingTime
bsReportEntries <-
managed $ withTzCacheDefault cCacheReportDialog
managed $ withTzCacheDefault bsConfig.cCacheReportDialog
-- auto-acknowledge received messages
(bsLogNamespace, bsLogContext, bsLogEnv) <- managed $ withLogger cLogLevel
(bsLogNamespace, bsLogContext, bsLogEnv) <- managed $ withLogger bsConfig.cLogLevel
liftIO $ runSocketMode sCfg $ handler gracefulShutdownContainer BotState {..}

withFeedbackConfig :: BotConfig -> (FeedbackConfig -> IO a) -> IO a
withFeedbackConfig Config {..} action = do
let fcFeedbackChannel = cFeedbackChannel
withFeedbackFile cFeedbackFile $ \fcFeedbackFile ->
withFeedbackConfig config action = do
let fcFeedbackChannel = config.cFeedbackChannel
withFeedbackFile config.cFeedbackFile $ \fcFeedbackFile ->
action FeedbackConfig {..}
where
withFeedbackFile :: Maybe FilePath -> (Maybe Handle -> IO a) -> IO a
Expand Down
36 changes: 18 additions & 18 deletions src/TzBot/Cache.hs
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ import TzBot.Util (multTimeSpec, randomTimeSpec, timeToTimespec, (+-))
--
-- Automatic periodical cleaning is also included.
data TzCache k v = TzCache
{ rcCache :: Cache k v
, rcExpiry :: TimeSpec
, rcExpiryRandomAmplitude :: Maybe TimeSpec
{ tcCache :: Cache k v
, tcExpiry :: TimeSpec
, tcExpiryRandomAmplitude :: Maybe TimeSpec
}

data TzCacheSettings = TzCacheSettings
Expand Down Expand Up @@ -85,18 +85,18 @@ withTzCache
-> (TzCache k v -> IO a) -- ^ Action that uses the cache
-> IO a
withTzCache
TzCacheSettings {..}
(timeToTimespec -> rcExpiry)
settings
(timeToTimespec -> tcExpiry)
action
= do
let isRandAmpValid :: Double -> Bool
isRandAmpValid x = x > 0 && x < 1
when (fmap isRandAmpValid tcsExpiryRandomAmplitudeFraction == Just False) $
when (fmap isRandAmpValid settings.tcsExpiryRandomAmplitudeFraction == Just False) $
error "Expiry random amplitude should be <1 and >0"
let rcExpiryRandomAmplitude = (flip multTimeSpec rcExpiry) <$> tcsExpiryRandomAmplitudeFraction
rcCache <- Cache.newCache $ Just rcExpiry
let tcExpiryRandomAmplitude = (flip multTimeSpec tcExpiry) <$> settings.tcsExpiryRandomAmplitudeFraction
tcCache <- Cache.newCache $ Just tcExpiry
withAsync
(cleaningThread (toUnit tcsCleaningPeriod) rcCache)
(cleaningThread (toUnit settings.tcsCleaningPeriod) tcCache)
(\_ -> action TzCache {..})

cleaningThread :: (Hashable k) => Time Hour -> Cache k v -> IO ()
Expand All @@ -112,13 +112,13 @@ insert
-> v
-> TzCache k v
-> m ()
insert key val TzCache {..} = do
expiry <- case rcExpiryRandomAmplitude of
Nothing -> pure rcExpiry
insert key val cache = do
expiry <- case cache.tcExpiryRandomAmplitude of
Nothing -> pure cache.tcExpiry
Just randAmp -> do
let (minTimeSpec, maxTimeSpec) = rcExpiry +- randAmp
let (minTimeSpec, maxTimeSpec) = cache.tcExpiry +- randAmp
liftIO $ randomTimeSpec (minTimeSpec, maxTimeSpec)
liftIO $ Cache.insert' rcCache (Just expiry) key val
liftIO $ Cache.insert' cache.tcCache (Just expiry) key val

-- | Try to get a value by the key from the cache, delete if it is expired.
-- If the value is either absent or expired, perform given fetch action
Expand All @@ -133,7 +133,7 @@ fetchWithCache
fetchWithCache key fetchAction cache =
katipAddNamespace "cache" $ do
logDebug [int||Fetching key=#{key}|]
mv <- liftIO $ Cache.lookup (rcCache cache) key
mv <- liftIO $ Cache.lookup (tcCache cache) key
case mv of
Just v -> logDebug "Using cache" >> pure v
Nothing -> do
Expand All @@ -150,7 +150,7 @@ lookup
=> k
-> TzCache k v
-> m (Maybe v)
lookup key TzCache {..} = liftIO $ Cache.lookup rcCache key
lookup key cache = liftIO $ Cache.lookup cache.tcCache key

-- | Update the value by the key, expiration is not taken into account.
update
Expand All @@ -159,8 +159,8 @@ update
-> (v -> v)
-> TzCache k v
-> m ()
update key valFunc TzCache {..} = do
atomically $ modifyTVar' (CacheI.container rcCache) $ \hm ->
update key valFunc cache = do
atomically $ modifyTVar' (CacheI.container cache.tcCache) $ \hm ->
HM.adjust itemFunc key hm
where
itemFunc :: CacheI.CacheItem v -> CacheI.CacheItem v
Expand Down
22 changes: 11 additions & 11 deletions src/TzBot/Config.hs
Original file line number Diff line number Diff line change
Expand Up @@ -102,16 +102,16 @@ readConfigWithEnv env mbPath =
-- After this, we catch yaml exception in order to pretty-print it later.
handle handleFunc $ traverse evaluate $ toEither
$ do
cAppToken <- fetchRequired "appToken" appTokenEnv cAppToken
cBotToken <- fetchRequired "botToken" botTokenEnv cBotToken
cMaxRetries <- fetchOptional maxRetriesEnv cMaxRetries `bindValidation` validateMaxTries
cCacheUsersInfo <- fetchOptional cacheUsersEnv cCacheUsersInfo
cCacheConversationMembers <- fetchOptional cacheConvMembersEnv cCacheConversationMembers
cFeedbackChannel <- fetchOptional feedbackChannelEnv cFeedbackChannel
cFeedbackFile <- fetchOptional feedbackFileEnv cFeedbackFile
cCacheReportDialog <- fetchOptional cacheReportDialogEnv cCacheReportDialog
cInverseHelpUsageChance <- fetchOptional inverseHelpUsageChanceEnv cInverseHelpUsageChance
cLogLevel <- fetchOptional logLevelEnv cLogLevel
cAppToken <- fetchRequired "appToken" appTokenEnv _cfg.cAppToken
cBotToken <- fetchRequired "botToken" botTokenEnv _cfg.cBotToken
cMaxRetries <- fetchOptional maxRetriesEnv _cfg.cMaxRetries `bindValidation` validateMaxTries
cCacheUsersInfo <- fetchOptional cacheUsersEnv _cfg.cCacheUsersInfo
cCacheConversationMembers <- fetchOptional cacheConvMembersEnv _cfg.cCacheConversationMembers
cFeedbackChannel <- fetchOptional feedbackChannelEnv _cfg.cFeedbackChannel
cFeedbackFile <- fetchOptional feedbackFileEnv _cfg.cFeedbackFile
cCacheReportDialog <- fetchOptional cacheReportDialogEnv _cfg.cCacheReportDialog
cInverseHelpUsageChance <- fetchOptional inverseHelpUsageChanceEnv _cfg.cInverseHelpUsageChance
cLogLevel <- fetchOptional logLevelEnv _cfg.cLogLevel
pure Config {..}
where
handleFunc :: Y.ParseException -> IO (Either [LoadConfigError] $ Config 'CSFinal)
Expand All @@ -127,7 +127,7 @@ readConfigWithEnv env mbPath =

_cfg :: Config 'CSInterm
-- The most easy way to read file on demand, acceptable here.
_cfg@Config {..} = unsafePerformIO $
_cfg = unsafePerformIO $
loadYamlSettings (maybeToList mbPath) [toJSON defaultConfig] ignoreEnv

fetchRequired
Expand Down
14 changes: 7 additions & 7 deletions src/TzBot/Feedback/Dialog/Types.hs
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,11 @@ newtype ReportDialogId = ReportDialogId { unReportDialogId :: Text }
deriving newtype (ToJSON, FromJSON, Buildable, Hashable)

data ReportDialogEntry = ReportDialogEntry
{ rpmMessageText :: Text
, rpmTimeConversion :: Maybe ConversionPairs
, rpmSenderTimeZone :: TZLabel
, rpmMessageTimestamp :: UTCTime
, rpmUserId :: UserId
, rpmChannelId :: ChannelId
, rpmThreadId :: Maybe ThreadId
{ rpeMessageText :: Text
, rpeTimeConversion :: Maybe ConversionPairs
, rpeSenderTimeZone :: TZLabel
, rpeMessageTimestamp :: UTCTime
, rpeUserId :: UserId
, rpeChannelId :: ChannelId
, rpeThreadId :: Maybe ThreadId
} deriving stock (Eq, Show, Generic)
6 changes: 3 additions & 3 deletions src/TzBot/Feedback/Save.hs
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ logFeedbackError (displayException -> err) = do
-- and record to the file if configured.
saveFeedback :: FeedbackEntry -> BotM ()
saveFeedback entry = UnliftIO.handleAny logFeedbackError $ do
FeedbackConfig {..} <- asks bsFeedbackConfig
whenJust fcFeedbackChannel $ saveFeedbackSlack entry
whenJust fcFeedbackFile $ saveFeedbackFile entry
feedbackConfig <- asks bsFeedbackConfig
whenJust feedbackConfig.fcFeedbackChannel $ saveFeedbackSlack entry
whenJust feedbackConfig.fcFeedbackFile $ saveFeedbackFile entry

-- Send to the slack channel
saveFeedbackSlack :: FeedbackEntry -> ChannelId -> BotM ()
Expand Down
10 changes: 5 additions & 5 deletions src/TzBot/Parser.hs
Original file line number Diff line number Diff line change
Expand Up @@ -1165,9 +1165,9 @@ data TimeReferenceMatched = TimeReferenceMatched
deriving stock (Eq, Show)

matchedToPlain :: TimeReferenceMatched -> TimeReference
matchedToPlain TimeReferenceMatched {..} = TimeReference
{ trDateRef = fmap mtValue trmDateRef
, trLocationRef = fmap mtValue trmLocationRef
, trText = trmText
, trTimeOfDay = trmTimeOfDay
matchedToPlain trm = TimeReference
{ trDateRef = fmap mtValue trm.trmDateRef
, trLocationRef = fmap mtValue trm.trmLocationRef
, trText = trm.trmText
, trTimeOfDay = trm.trmTimeOfDay
}
7 changes: 3 additions & 4 deletions src/TzBot/ProcessEvents/BlockAction.hs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@ import Data.Aeson (Value)
import Text.Interpolation.Nyan (int, rmode')

import TzBot.Feedback.Dialog (lookupDialogEntry)
import TzBot.Feedback.Dialog.Types
(ReportDialogEntry(ReportDialogEntry, rpmMessageText, rpmMessageTimestamp, rpmSenderTimeZone, rpmTimeConversion))
import TzBot.Feedback.Dialog.Types (ReportDialogEntry(..))
import TzBot.Logger
import TzBot.Slack (BotM, updateModal)
import TzBot.Slack.API (UpdateViewReq(UpdateViewReq))
Expand All @@ -32,7 +31,7 @@ processReportButtonToggled val =
mbMetadata <- lookupDialogEntry metadataEntryId
case mbMetadata of
Nothing -> logWarn [int||Dialog id not found: #{metadataEntryId}|]
Just _metadata@ReportDialogEntry {..} -> updateModal $
Just reportDialogEntry -> updateModal $
UpdateViewReq
(mkReportModal rpmMessageText rpmTimeConversion metadataEntryId)
(mkReportModal reportDialogEntry.rpeMessageText reportDialogEntry.rpeTimeConversion metadataEntryId)
(vId $ vaeView val)
12 changes: 6 additions & 6 deletions src/TzBot/ProcessEvents/ChannelEvent.hs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ import TzBot.RunMonad
import TzBot.Slack.Events (MemberJoinedChannelEvent(..), MemberLeftChannelEvent(..))

processMemberJoinedChannel :: MemberJoinedChannelEvent -> BotM ()
processMemberJoinedChannel MemberJoinedChannelEvent {..} = do
logInfo [int||user #{mjceUser} joined channel #{mjceChannel}|]
processMemberJoinedChannel evt = do
logInfo [int||user #{mjceUser evt} joined channel #{mjceChannel evt}|]
channelMembersCache <- asks bsConversationMembersCache
Cache.update mjceChannel (S.insert mjceUser) channelMembersCache
Cache.update evt.mjceChannel (S.insert evt.mjceUser) channelMembersCache

processMemberLeftChannel :: MemberLeftChannelEvent -> BotM ()
processMemberLeftChannel MemberLeftChannelEvent {..} = do
logInfo [int||user #{mlceUser} left channel #{mlceChannel}|]
processMemberLeftChannel evt = do
logInfo [int||user #{mlceUser evt} left channel #{mlceChannel evt}|]
channelMembersCache <- asks bsConversationMembersCache
Cache.update mlceChannel (S.delete mlceUser) channelMembersCache
Cache.update evt.mlceChannel (S.delete evt.mlceUser) channelMembersCache
10 changes: 5 additions & 5 deletions src/TzBot/ProcessEvents/Command.hs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@ import TzBot.Slack.API (ChannelId(..), PostEphemeralReq(..), UserId(..))
import TzBot.Slack.Fixtures qualified as Fixtures

processHelpCommand :: SlashCommand -> BotM ()
processHelpCommand SlashCommand {..} = do
let postEphemeralReq@PostEphemeralReq {..} = PostEphemeralReq
{ perUser = UserId scUserId
, perChannel = ChannelId scChannelId
processHelpCommand cmd = do
let postEphemeralReq = PostEphemeralReq
{ perUser = UserId cmd.scUserId
, perChannel = ChannelId cmd.scChannelId
, perText = Fixtures.helpMessage
, perThreadTs = Nothing
, perBlocks = Nothing
}
logInfo [int||Sending help message to user #{perUser}|]
logInfo [int||Sending help message to user #{perUser postEphemeralReq}|]
sendEphemeralMessage postEphemeralReq
14 changes: 7 additions & 7 deletions src/TzBot/ProcessEvents/Common.hs
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,13 @@ openModalCommon message channelId whoTriggeredId triggerId mkModalFunc = do

guid <- ReportDialogId <$> liftIO genText
let metadata = ReportDialogEntry
{ rpmMessageText = mText message
, rpmTimeConversion = conversionPairs
, rpmSenderTimeZone = uTz sender
, rpmMessageTimestamp = mTs message
, rpmUserId = whoTriggeredId
, rpmChannelId = channelId
, rpmThreadId = mThreadId message
{ rpeMessageText = mText message
, rpeTimeConversion = conversionPairs
, rpeSenderTimeZone = uTz sender
, rpeMessageTimestamp = mTs message
, rpeUserId = whoTriggeredId
, rpeChannelId = channelId
, rpeThreadId = mThreadId message
}
insertDialogEntry guid metadata
let modal = mkModalFunc msgText conversionPairs guid
Expand Down
18 changes: 9 additions & 9 deletions src/TzBot/ProcessEvents/Interactive.hs
Original file line number Diff line number Diff line change
Expand Up @@ -57,23 +57,23 @@ processViewSubmission (ViewActionEvent view) =
mbMetadata <- lookupDialogEntry metadataEntryId
case mbMetadata of
Nothing -> logWarn [int||Dialog id not found: #{metadataEntryId}|]
Just _metadata@ReportDialogEntry {..} -> do
Just reportDialogEntry -> do
logInfo [int||
Got feedback from user #{rpmUserId}, \
Got feedback from user #{rpeUserId reportDialogEntry}, \
dialogId #{metadataEntryId}
|]
let feedbackEntry = FeedbackEntry
{ feMessageText = rpmMessageText
, feTimeConversion = rpmTimeConversion
{ feMessageText = reportDialogEntry.rpeMessageText
, feTimeConversion = reportDialogEntry.rpeTimeConversion
, feUserReport = userInput
, feMessageTimestamp = rpmMessageTimestamp
, feSenderTimezone = rpmSenderTimeZone
, feMessageTimestamp = reportDialogEntry.rpeMessageTimestamp
, feSenderTimezone = reportDialogEntry.rpeSenderTimeZone
}
saveFeedback feedbackEntry
sendEphemeralMessage $ PostEphemeralReq
{ perUser = rpmUserId
, perChannel = rpmChannelId
, perThreadTs = rpmThreadId
{ perUser = reportDialogEntry.rpeUserId
, perChannel = reportDialogEntry.rpeChannelId
, perThreadTs = reportDialogEntry.rpeThreadId
, perText = "Thanks for your feedback!"
, perBlocks = Nothing
}
Loading

0 comments on commit a37dd4c

Please sign in to comment.