-
Notifications
You must be signed in to change notification settings - Fork 700
/
FileMonitor.hs
1141 lines (1056 loc) · 41.8 KB
/
FileMonitor.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | An abstraction to help with re-running actions when files or other
-- input values they depend on have changed.
module Distribution.Client.FileMonitor
( -- * Declaring files to monitor
module Distribution.Simple.FileMonitor.Types
-- * Creating and checking sets of monitored files
, FileMonitor (..)
, newFileMonitor
, MonitorChanged (..)
, MonitorChangedReason (..)
, checkFileMonitorChanged
, updateFileMonitor
, MonitorTimestamp
, beginUpdateFileMonitor
-- * Internal
, MonitorStateFileSet
, MonitorStateFile
, MonitorStateGlob
) where
import Distribution.Client.Compat.Prelude
import qualified Distribution.Compat.Binary as Binary
import Prelude ()
import Data.Binary.Get (runGetOrFail)
import qualified Data.ByteString.Lazy as BS
import qualified Data.Map.Strict as Map
import Control.Exception
import Control.Monad
import Control.Monad.Except
( ExceptT
, runExceptT
, throwError
, withExceptT
)
import Control.Monad.State (StateT, mapStateT)
import qualified Control.Monad.State as State
import Control.Monad.Trans (MonadIO, liftIO)
import Distribution.Client.Glob
import Distribution.Client.HashValue
import Distribution.Client.Utils (MergeResult (..), mergeBy)
import Distribution.Compat.Time
import Distribution.Simple.FileMonitor.Types
import Distribution.Simple.Utils (handleDoesNotExist, writeFileAtomic)
import Distribution.Utils.Structured (Tag (..), structuredEncode)
import System.Directory
import System.FilePath
import System.IO
------------------------------------------------------------------------------
-- Implementation types, files status
--
-- | The state necessary to determine whether a set of monitored
-- files has changed. It consists of two parts: a set of specific
-- files to be monitored (index by their path), and a list of
-- globs, which monitor may files at once.
data MonitorStateFileSet
= MonitorStateFileSet
![MonitorStateFile]
![MonitorStateGlob]
-- Morally this is not actually a set but a bag (represented by lists).
-- There is no principled reason to use a bag here rather than a set, but
-- there is also no particular gain either. That said, we do preserve the
-- order of the lists just to reduce confusion (and have predictable I/O
-- patterns).
deriving (Show, Generic)
instance Binary MonitorStateFileSet
instance Structured MonitorStateFileSet
-- | The state necessary to determine whether a monitored file has changed.
--
-- This covers all the cases of 'MonitorFilePath' except for globs which is
-- covered separately by 'MonitorStateGlob'.
--
-- The @Maybe ModTime@ is to cover the case where we already consider the
-- file to have changed, either because it had already changed by the time we
-- did the snapshot (i.e. too new, changed since start of update process) or it
-- no longer exists at all.
data MonitorStateFile
= MonitorStateFile
!MonitorKindFile
!MonitorKindDir
!FilePath
!MonitorStateFileStatus
deriving (Show, Generic)
data MonitorStateFileStatus
= MonitorStateFileExists
| -- | cached file mtime
MonitorStateFileModTime !ModTime
| -- | cached mtime and content hash
MonitorStateFileHashed !ModTime !HashValue
| MonitorStateDirExists
| -- | cached dir mtime
MonitorStateDirModTime !ModTime
| MonitorStateNonExistent
| MonitorStateAlreadyChanged
deriving (Show, Generic)
instance Binary MonitorStateFile
instance Binary MonitorStateFileStatus
instance Structured MonitorStateFile
instance Structured MonitorStateFileStatus
-- | The state necessary to determine whether the files matched by a globbing
-- match have changed.
data MonitorStateGlob
= MonitorStateGlob
!MonitorKindFile
!MonitorKindDir
!FilePathRoot
!MonitorStateGlobRel
deriving (Show, Generic)
data MonitorStateGlobRel
= MonitorStateGlobDirs
!GlobPieces
!Glob
!ModTime
![(FilePath, MonitorStateGlobRel)] -- invariant: sorted
| MonitorStateGlobFiles
!GlobPieces
!ModTime
![(FilePath, MonitorStateFileStatus)] -- invariant: sorted
| MonitorStateGlobDirTrailing
deriving (Show, Generic)
instance Binary MonitorStateGlob
instance Binary MonitorStateGlobRel
instance Structured MonitorStateGlob
instance Structured MonitorStateGlobRel
-- | We can build a 'MonitorStateFileSet' from a set of 'MonitorFilePath' by
-- inspecting the state of the file system, and we can go in the reverse
-- direction by just forgetting the extra info.
reconstructMonitorFilePaths :: MonitorStateFileSet -> [MonitorFilePath]
reconstructMonitorFilePaths (MonitorStateFileSet singlePaths globPaths) =
map getSinglePath singlePaths ++ map getGlobPath globPaths
where
getSinglePath :: MonitorStateFile -> MonitorFilePath
getSinglePath (MonitorStateFile kindfile kinddir filepath _) =
MonitorFile kindfile kinddir filepath
getGlobPath :: MonitorStateGlob -> MonitorFilePath
getGlobPath (MonitorStateGlob kindfile kinddir root gstate) =
MonitorFileGlob kindfile kinddir $
RootedGlob root $
case gstate of
MonitorStateGlobDirs glob globs _ _ -> GlobDir glob globs
MonitorStateGlobFiles glob _ _ -> GlobFile glob
MonitorStateGlobDirTrailing -> GlobDirTrailing
------------------------------------------------------------------------------
-- Checking the status of monitored files
--
-- | A monitor for detecting changes to a set of files. It can be used to
-- efficiently test if any of a set of files (specified individually or by
-- glob patterns) has changed since some snapshot. In addition, it also checks
-- for changes in a value (of type @a@), and when there are no changes in
-- either it returns a saved value (of type @b@).
--
-- The main use case looks like this: suppose we have some expensive action
-- that depends on certain pure inputs and reads some set of files, and
-- produces some pure result. We want to avoid re-running this action when it
-- would produce the same result. So we need to monitor the files the action
-- looked at, the other pure input values, and we need to cache the result.
-- Then at some later point, if the input value didn't change, and none of the
-- files changed, then we can re-use the cached result rather than re-running
-- the action.
--
-- This can be achieved using a 'FileMonitor'. Each 'FileMonitor' instance
-- saves state in a disk file, so the file for that has to be specified,
-- making sure it is unique. The pattern is to use 'checkFileMonitorChanged'
-- to see if there's been any change. If there is, re-run the action, keeping
-- track of the files, then use 'updateFileMonitor' to record the current
-- set of files to monitor, the current input value for the action, and the
-- result of the action.
--
-- The typical occurrence of this pattern is captured by 'rerunIfChanged'
-- and the 'Rebuild' monad. More complicated cases may need to use
-- 'checkFileMonitorChanged' and 'updateFileMonitor' directly.
data FileMonitor a b = FileMonitor
{ fileMonitorCacheFile :: FilePath
-- ^ The file where this 'FileMonitor' should store its state.
, fileMonitorKeyValid :: a -> a -> Bool
-- ^ Compares a new cache key with old one to determine if a
-- corresponding cached value is still valid.
--
-- Typically this is just an equality test, but in some
-- circumstances it can make sense to do things like subset
-- comparisons.
--
-- The first arg is the new value, the second is the old cached value.
, fileMonitorCheckIfOnlyValueChanged :: Bool
-- ^ When this mode is enabled, if 'checkFileMonitorChanged' returns
-- 'MonitoredValueChanged' then we have the guarantee that no files
-- changed, that the value change was the only change. In the default
-- mode no such guarantee is provided which is slightly faster.
}
-- | Define a new file monitor.
--
-- It's best practice to define file monitor values once, and then use the
-- same value for 'checkFileMonitorChanged' and 'updateFileMonitor' as this
-- ensures you get the same types @a@ and @b@ for reading and writing.
--
-- The path of the file monitor itself must be unique because it keeps state
-- on disk and these would clash.
newFileMonitor
:: Eq a
=> FilePath
-- ^ The file to cache the state of the
-- file monitor. Must be unique.
-> FileMonitor a b
newFileMonitor path = FileMonitor path (==) False
-- | The result of 'checkFileMonitorChanged': either the monitored files or
-- value changed (and it tells us which it was) or nothing changed and we get
-- the cached result.
data MonitorChanged a b
= -- | The monitored files and value did not change. The cached result is
-- @b@.
--
-- The set of monitored files is also returned. This is useful
-- for composing or nesting 'FileMonitor's.
MonitorUnchanged b [MonitorFilePath]
| -- | The monitor found that something changed. The reason is given.
MonitorChanged (MonitorChangedReason a)
deriving (Show)
-- | What kind of change 'checkFileMonitorChanged' detected.
data MonitorChangedReason a
= -- | One of the files changed (existence, file type, mtime or file
-- content, depending on the 'MonitorFilePath' in question)
MonitoredFileChanged FilePath
| -- | The pure input value changed.
--
-- The previous cached key value is also returned. This is sometimes
-- useful when using a 'fileMonitorKeyValid' function that is not simply
-- '(==)', when invalidation can be partial. In such cases it can make
-- sense to 'updateFileMonitor' with a key value that's a combination of
-- the new and old (e.g. set union).
MonitoredValueChanged a
| -- | There was no saved monitor state, cached value etc. Ie the file
-- for the 'FileMonitor' does not exist.
MonitorFirstRun
| -- | There was existing state, but we could not read it. This typically
-- happens when the code has changed compared to an existing 'FileMonitor'
-- cache file and type of the input value or cached value has changed such
-- that we cannot decode the values. This is completely benign as we can
-- treat is just as if there were no cache file and re-run.
MonitorCorruptCache
deriving (Eq, Show, Functor)
-- | Test if the input value or files monitored by the 'FileMonitor' have
-- changed. If not, return the cached value.
--
-- See 'FileMonitor' for a full explanation.
checkFileMonitorChanged
:: forall a b
. (Binary a, Structured a, Binary b, Structured b)
=> FileMonitor a b
-- ^ cache file path
-> FilePath
-- ^ root directory
-> a
-- ^ guard or key value
-> IO (MonitorChanged a b)
-- ^ did the key or any paths change?
checkFileMonitorChanged
monitor@FileMonitor
{ fileMonitorKeyValid
, fileMonitorCheckIfOnlyValueChanged
}
root
currentKey =
-- Consider it a change if the cache file does not exist,
-- or we cannot decode it. Sadly ErrorCall can still happen, despite
-- using decodeFileOrFail, e.g. Data.Char.chr errors
handleDoesNotExist (MonitorChanged MonitorFirstRun) $
handleErrorCall (MonitorChanged MonitorCorruptCache) $
withCacheFile monitor $
either
(\_ -> return (MonitorChanged MonitorCorruptCache))
checkStatusCache
where
checkStatusCache :: (MonitorStateFileSet, a, Either String b) -> IO (MonitorChanged a b)
checkStatusCache (cachedFileStatus, cachedKey, cachedResult) = do
change <- checkForChanges
case change of
Just reason -> return (MonitorChanged reason)
Nothing -> case cachedResult of
Left _ -> pure (MonitorChanged MonitorCorruptCache)
Right cr -> return (MonitorUnchanged cr monitorFiles)
where
monitorFiles = reconstructMonitorFilePaths cachedFileStatus
where
-- In fileMonitorCheckIfOnlyValueChanged mode we want to guarantee that
-- if we return MonitoredValueChanged that only the value changed.
-- We do that by checking for file changes first. Otherwise it makes
-- more sense to do the cheaper test first.
checkForChanges :: IO (Maybe (MonitorChangedReason a))
checkForChanges
| fileMonitorCheckIfOnlyValueChanged =
checkFileChange cachedFileStatus cachedKey cachedResult
`mplusMaybeT` checkValueChange cachedKey
| otherwise =
checkValueChange cachedKey
`mplusMaybeT` checkFileChange cachedFileStatus cachedKey cachedResult
mplusMaybeT :: Monad m => m (Maybe a1) -> m (Maybe a1) -> m (Maybe a1)
mplusMaybeT ma mb = do
mx <- ma
case mx of
Nothing -> mb
Just x -> return (Just x)
-- Check if the guard value has changed
checkValueChange :: a -> IO (Maybe (MonitorChangedReason a))
checkValueChange cachedKey
| not (fileMonitorKeyValid currentKey cachedKey) =
return (Just (MonitoredValueChanged cachedKey))
| otherwise =
return Nothing
-- Check if any file has changed
checkFileChange :: MonitorStateFileSet -> a -> Either String b -> IO (Maybe (MonitorChangedReason a))
checkFileChange cachedFileStatus cachedKey cachedResult = do
res <- probeFileSystem root cachedFileStatus
case res of
-- Some monitored file has changed
Left changedPath ->
return (Just (MonitoredFileChanged (normalise changedPath)))
-- No monitored file has changed
Right (cachedFileStatus', cacheStatus) -> do
-- But we might still want to update the cache
whenCacheChanged cacheStatus $
case cachedResult of
Left _ -> pure ()
Right cr -> rewriteCacheFile monitor cachedFileStatus' cachedKey cr
return Nothing
-- | Lazily decode a triple, parsing the first two fields strictly and
-- returning a lazy value containing either the last one or an error.
-- This is helpful for cabal cache files where the first two components
-- contain header data that lets one test if the cache is still valid,
-- and the last (potentially large) component is the cached value itself.
-- This way we can test for cache validity without needing to pay the
-- cost of the decode of stale cache data. This lives here rather than
-- Distribution.Utils.Structured because it depends on a newer version of
-- binary than supported in the Cabal library proper.
structuredDecodeTriple
:: forall a b c
. (Structured a, Structured b, Structured c, Binary.Binary a, Binary.Binary b, Binary.Binary c)
=> BS.ByteString
-> Either String (a, b, Either String c)
structuredDecodeTriple lbs =
let partialDecode =
(`runGetOrFail` lbs) $ do
(_ :: Tag (a, b, c)) <- Binary.get
(a :: a) <- Binary.get
(b :: b) <- Binary.get
pure (a, b)
cleanEither (Left (_, pos, msg)) = Left ("Data.Binary.Get.runGet at position " ++ show pos ++ ": " ++ msg)
cleanEither (Right (_, _, v)) = Right v
in case partialDecode of
Left (_, pos, msg) -> Left ("Data.Binary.Get.runGet at position " ++ show pos ++ ": " ++ msg)
Right (lbs', _, (x, y)) -> Right (x, y, cleanEither $ runGetOrFail (Binary.get :: Binary.Get c) lbs')
-- | Helper for reading the cache file.
--
-- This determines the type and format of the binary cache file.
withCacheFile
:: (Binary a, Structured a, Binary b, Structured b)
=> FileMonitor a b
-> (Either String (MonitorStateFileSet, a, Either String b) -> IO r)
-> IO r
withCacheFile (FileMonitor{fileMonitorCacheFile}) k =
withBinaryFile fileMonitorCacheFile ReadMode $ \hnd -> do
contents <- structuredDecodeTriple <$> BS.hGetContents hnd
k contents
-- | Helper for writing the cache file.
--
-- This determines the type and format of the binary cache file.
rewriteCacheFile
:: (Binary a, Structured a, Binary b, Structured b)
=> FileMonitor a b
-> MonitorStateFileSet
-> a
-> b
-> IO ()
rewriteCacheFile FileMonitor{fileMonitorCacheFile} fileset key result =
writeFileAtomic fileMonitorCacheFile $
structuredEncode (fileset, key, result)
-- | Probe the file system to see if any of the monitored files have changed.
--
-- It returns Nothing if any file changed, or returns a possibly updated
-- file 'MonitorStateFileSet' plus an indicator of whether it actually changed.
--
-- We may need to update the cache since there may be changes in the filesystem
-- state which don't change any of our affected files.
--
-- Consider the glob @{proj1,proj2}\/\*.cabal@. Say we first run and find a
-- @proj1@ directory containing @proj1.cabal@ yet no @proj2@. If we later run
-- and find @proj2@ was created, yet contains no files matching @*.cabal@ then
-- we want to update the cache despite no changes in our relevant file set.
-- Specifically, we should add an mtime for this directory so we can avoid
-- re-traversing the directory in future runs.
probeFileSystem
:: FilePath
-> MonitorStateFileSet
-> IO (Either FilePath (MonitorStateFileSet, CacheChanged))
probeFileSystem root (MonitorStateFileSet singlePaths globPaths) =
runChangedM $ do
sequence_
[ probeMonitorStateFileStatus root file status
| MonitorStateFile _ _ file status <- singlePaths
]
-- The glob monitors can require state changes
globPaths' <-
sequence
[ probeMonitorStateGlob root globPath
| globPath <- globPaths
]
return (MonitorStateFileSet singlePaths globPaths')
-----------------------------------------------
-- Monad for checking for file system changes
--
-- We need to be able to bail out if we detect a change (using ExceptT),
-- but if there's no change we need to be able to rebuild the monitor
-- state. And we want to optimise that rebuilding by keeping track if
-- anything actually changed (using StateT), so that in the typical case
-- we can avoid rewriting the state file.
newtype ChangedM a = ChangedM (StateT CacheChanged (ExceptT FilePath IO) a)
deriving (Functor, Applicative, Monad, MonadIO)
runChangedM :: ChangedM a -> IO (Either FilePath (a, CacheChanged))
runChangedM (ChangedM action) =
runExceptT $ State.runStateT action CacheUnchanged
somethingChanged :: FilePath -> ChangedM a
somethingChanged path = ChangedM $ throwError path
cacheChanged :: ChangedM ()
cacheChanged = ChangedM $ State.put CacheChanged
mapChangedFile :: (FilePath -> FilePath) -> ChangedM a -> ChangedM a
mapChangedFile adjust (ChangedM a) =
ChangedM (mapStateT (withExceptT adjust) a)
data CacheChanged = CacheChanged | CacheUnchanged
whenCacheChanged :: Monad m => CacheChanged -> m () -> m ()
whenCacheChanged CacheChanged action = action
whenCacheChanged CacheUnchanged _ = return ()
----------------------
-- | Probe the file system to see if a single monitored file has changed.
probeMonitorStateFileStatus
:: FilePath
-> FilePath
-> MonitorStateFileStatus
-> ChangedM ()
probeMonitorStateFileStatus root file status =
case status of
MonitorStateFileExists ->
probeFileExistence root file
MonitorStateFileModTime mtime ->
probeFileModificationTime root file mtime
MonitorStateFileHashed mtime hash ->
probeFileModificationTimeAndHash root file mtime hash
MonitorStateDirExists ->
probeDirExistence root file
MonitorStateDirModTime mtime ->
probeFileModificationTime root file mtime
MonitorStateNonExistent ->
probeFileNonExistence root file
MonitorStateAlreadyChanged ->
somethingChanged file
-- | Probe the file system to see if a monitored file glob has changed.
probeMonitorStateGlob
:: FilePath
-- ^ root path
-> MonitorStateGlob
-> ChangedM MonitorStateGlob
probeMonitorStateGlob
relroot
(MonitorStateGlob kindfile kinddir globroot glob) = do
root <- liftIO $ getFilePathRootDirectory globroot relroot
case globroot of
FilePathRelative ->
MonitorStateGlob kindfile kinddir globroot
<$> probeMonitorStateGlobRel kindfile kinddir root "." glob
-- for absolute cases, make the changed file we report absolute too
_ ->
mapChangedFile (root </>) $
MonitorStateGlob kindfile kinddir globroot
<$> probeMonitorStateGlobRel kindfile kinddir root "" glob
probeMonitorStateGlobRel
:: MonitorKindFile
-> MonitorKindDir
-> FilePath
-- ^ root path
-> FilePath
-- ^ path of the directory we are
-- looking in relative to @root@
-> MonitorStateGlobRel
-> ChangedM MonitorStateGlobRel
probeMonitorStateGlobRel
kindfile
kinddir
root
dirName
(MonitorStateGlobDirs glob globPath mtime children) = do
change <- liftIO $ checkDirectoryModificationTime (root </> dirName) mtime
case change of
Nothing -> do
children' <-
sequence
[ do
fstate' <-
probeMonitorStateGlobRel
kindfile
kinddir
root
(dirName </> fname)
fstate
return (fname, fstate')
| (fname, fstate) <- children
]
return $! MonitorStateGlobDirs glob globPath mtime children'
Just mtime' -> do
-- directory modification time changed:
-- a matching subdir may have been added or deleted
matches <-
filterM
( \entry ->
let subdir = root </> dirName </> entry
in liftIO $ doesDirectoryExist subdir
)
. filter (matchGlobPieces glob)
=<< liftIO (getDirectoryContents (root </> dirName))
children' <-
traverse probeMergeResult $
mergeBy
(\(path1, _) path2 -> compare path1 path2)
children
(sort matches)
return $! MonitorStateGlobDirs glob globPath mtime' children'
where
-- Note that just because the directory has changed, we don't force
-- a cache rewrite with 'cacheChanged' since that has some cost, and
-- all we're saving is scanning the directory. But we do rebuild the
-- cache with the new mtime', so that if the cache is rewritten for
-- some other reason, we'll take advantage of that.
probeMergeResult
:: MergeResult (FilePath, MonitorStateGlobRel) FilePath
-> ChangedM (FilePath, MonitorStateGlobRel)
-- Only in cached (directory deleted)
probeMergeResult (OnlyInLeft (path, fstate)) = do
case allMatchingFiles (dirName </> path) fstate of
[] -> return (path, fstate)
-- Strictly speaking we should be returning 'CacheChanged' above
-- as we should prune the now-missing 'MonitorStateGlobRel'. However
-- we currently just leave these now-redundant entries in the
-- cache as they cost no IO and keeping them allows us to avoid
-- rewriting the cache.
(file : _) -> somethingChanged file
-- Only in current filesystem state (directory added)
probeMergeResult (OnlyInRight path) = do
fstate <-
liftIO $
buildMonitorStateGlobRel
Nothing
Map.empty
kindfile
kinddir
root
(dirName </> path)
globPath
case allMatchingFiles (dirName </> path) fstate of
(file : _) -> somethingChanged file
-- This is the only case where we use 'cacheChanged' because we can
-- have a whole new dir subtree (of unbounded size and cost), so we
-- need to save the state of that new subtree in the cache.
[] -> cacheChanged >> return (path, fstate)
-- Found in path
probeMergeResult (InBoth (path, fstate) _) = do
fstate' <-
probeMonitorStateGlobRel
kindfile
kinddir
root
(dirName </> path)
fstate
return (path, fstate')
-- \| Does a 'MonitorStateGlob' have any relevant files within it?
allMatchingFiles :: FilePath -> MonitorStateGlobRel -> [FilePath]
allMatchingFiles dir (MonitorStateGlobFiles _ _ entries) =
[dir </> fname | (fname, _) <- entries]
allMatchingFiles dir (MonitorStateGlobDirs _ _ _ entries) =
[ res
| (subdir, fstate) <- entries
, res <- allMatchingFiles (dir </> subdir) fstate
]
allMatchingFiles dir MonitorStateGlobDirTrailing =
[dir]
probeMonitorStateGlobRel
_
_
root
dirName
(MonitorStateGlobFiles glob mtime children) = do
change <- liftIO $ checkDirectoryModificationTime (root </> dirName) mtime
mtime' <- case change of
Nothing -> return mtime
Just mtime' -> do
-- directory modification time changed:
-- a matching file may have been added or deleted
matches <-
return . filter (matchGlobPieces glob)
=<< liftIO (getDirectoryContents (root </> dirName))
traverse_ probeMergeResult $
mergeBy
(\(path1, _) path2 -> compare path1 path2)
children
(sort matches)
return mtime'
-- Check that none of the children have changed
for_ children $ \(file, status) ->
probeMonitorStateFileStatus root (dirName </> file) status
return (MonitorStateGlobFiles glob mtime' children)
where
-- Again, we don't force a cache rewrite with 'cacheChanged', but we do use
-- the new mtime' if any.
probeMergeResult
:: MergeResult (FilePath, MonitorStateFileStatus) FilePath
-> ChangedM ()
probeMergeResult mr = case mr of
InBoth _ _ -> return ()
-- this is just to be able to accurately report which file changed:
OnlyInLeft (path, _) -> somethingChanged (dirName </> path)
OnlyInRight path -> somethingChanged (dirName </> path)
probeMonitorStateGlobRel _ _ _ _ MonitorStateGlobDirTrailing =
return MonitorStateGlobDirTrailing
------------------------------------------------------------------------------
-- | Update the input value and the set of files monitored by the
-- 'FileMonitor', plus the cached value that may be returned in future.
--
-- This takes a snapshot of the state of the monitored files right now, so
-- 'checkFileMonitorChanged' will look for file system changes relative to
-- this snapshot.
--
-- This is typically done once the action has been completed successfully and
-- we have the action's result and we know what files it looked at. See
-- 'FileMonitor' for a full explanation.
--
-- If we do take the snapshot after the action has completed then we have a
-- problem. The problem is that files might have changed /while/ the action was
-- running but /after/ the action read them. If we take the snapshot after the
-- action completes then we will miss these changes. The solution is to record
-- a timestamp before beginning execution of the action and then we make the
-- conservative assumption that any file that has changed since then has
-- already changed, ie the file monitor state for these files will be such that
-- 'checkFileMonitorChanged' will report that they have changed.
--
-- So if you do use 'updateFileMonitor' after the action (so you can discover
-- the files used rather than predicting them in advance) then use
-- 'beginUpdateFileMonitor' to get a timestamp and pass that. Alternatively,
-- if you take the snapshot in advance of the action, or you're not monitoring
-- any files then you can use @Nothing@ for the timestamp parameter.
updateFileMonitor
:: (Binary a, Structured a, Binary b, Structured b)
=> FileMonitor a b
-- ^ cache file path
-> FilePath
-- ^ root directory
-> Maybe MonitorTimestamp
-- ^ timestamp when the update action started
-> [MonitorFilePath]
-- ^ files of interest relative to root
-> a
-- ^ the current key value
-> b
-- ^ the current result value
-> IO ()
updateFileMonitor
monitor
root
startTime
monitorFiles
cachedKey
cachedResult = do
hashcache <- readCacheFileHashes monitor
msfs <- buildMonitorStateFileSet startTime hashcache root monitorFiles
rewriteCacheFile monitor msfs cachedKey cachedResult
-- | A timestamp to help with the problem of file changes during actions.
-- See 'updateFileMonitor' for details.
newtype MonitorTimestamp = MonitorTimestamp ModTime
-- | Record a timestamp at the beginning of an action, and when the action
-- completes call 'updateFileMonitor' passing it the timestamp.
-- See 'updateFileMonitor' for details.
beginUpdateFileMonitor :: IO MonitorTimestamp
beginUpdateFileMonitor = MonitorTimestamp <$> getCurTime
-- | Take the snapshot of the monitored files. That is, given the
-- specification of the set of files we need to monitor, inspect the state
-- of the file system now and collect the information we'll need later to
-- determine if anything has changed.
buildMonitorStateFileSet
:: Maybe MonitorTimestamp
-- ^ optional: timestamp
-- of the start of the action
-> FileHashCache
-- ^ existing file hashes
-> FilePath
-- ^ root directory
-> [MonitorFilePath]
-- ^ patterns of interest
-- relative to root
-> IO MonitorStateFileSet
buildMonitorStateFileSet mstartTime hashcache root =
go [] []
where
go
:: [MonitorStateFile]
-> [MonitorStateGlob]
-> [MonitorFilePath]
-> IO MonitorStateFileSet
go !singlePaths !globPaths [] =
return (MonitorStateFileSet (reverse singlePaths) (reverse globPaths))
go
!singlePaths
!globPaths
(MonitorFile kindfile kinddir path : monitors) = do
monitorState <-
MonitorStateFile kindfile kinddir path
<$> buildMonitorStateFile
mstartTime
hashcache
kindfile
kinddir
root
path
go (monitorState : singlePaths) globPaths monitors
go
!singlePaths
!globPaths
(MonitorFileGlob kindfile kinddir globPath : monitors) = do
monitorState <-
buildMonitorStateGlob
mstartTime
hashcache
kindfile
kinddir
root
globPath
go singlePaths (monitorState : globPaths) monitors
buildMonitorStateFile
:: Maybe MonitorTimestamp
-- ^ start time of update
-> FileHashCache
-- ^ existing file hashes
-> MonitorKindFile
-> MonitorKindDir
-> FilePath
-- ^ the root directory
-> FilePath
-> IO MonitorStateFileStatus
buildMonitorStateFile mstartTime hashcache kindfile kinddir root path = do
let abspath = root </> path
isFile <- doesFileExist abspath
isDir <- doesDirectoryExist abspath
case (isFile, kindfile, isDir, kinddir) of
(_, FileNotExists, _, DirNotExists) ->
-- we don't need to care if it exists now, since we check at probe time
return MonitorStateNonExistent
(False, _, False, _) ->
return MonitorStateAlreadyChanged
(True, FileExists, _, _) ->
return MonitorStateFileExists
(True, FileModTime, _, _) ->
handleIOException MonitorStateAlreadyChanged $ do
mtime <- getModTime abspath
if changedDuringUpdate mstartTime mtime
then return MonitorStateAlreadyChanged
else return (MonitorStateFileModTime mtime)
(True, FileHashed, _, _) ->
handleIOException MonitorStateAlreadyChanged $ do
mtime <- getModTime abspath
if changedDuringUpdate mstartTime mtime
then return MonitorStateAlreadyChanged
else do
hash <- getFileHash hashcache abspath abspath mtime
return (MonitorStateFileHashed mtime hash)
(_, _, True, DirExists) ->
return MonitorStateDirExists
(_, _, True, DirModTime) ->
handleIOException MonitorStateAlreadyChanged $ do
mtime <- getModTime abspath
if changedDuringUpdate mstartTime mtime
then return MonitorStateAlreadyChanged
else return (MonitorStateDirModTime mtime)
(False, _, True, DirNotExists) -> return MonitorStateAlreadyChanged
(True, FileNotExists, False, _) -> return MonitorStateAlreadyChanged
-- | If we have a timestamp for the beginning of the update, then any file
-- mtime later than this means that it changed during the update and we ought
-- to consider the file as already changed.
changedDuringUpdate :: Maybe MonitorTimestamp -> ModTime -> Bool
changedDuringUpdate (Just (MonitorTimestamp startTime)) mtime =
mtime > startTime
changedDuringUpdate _ _ = False
-- | Much like 'buildMonitorStateFileSet' but for the somewhat complicated case
-- of a file glob.
--
-- This gets used both by 'buildMonitorStateFileSet' when we're taking the
-- file system snapshot, but also by 'probeGlobStatus' as part of checking
-- the monitored (globed) files for changes when we find a whole new subtree.
buildMonitorStateGlob
:: Maybe MonitorTimestamp
-- ^ start time of update
-> FileHashCache
-- ^ existing file hashes
-> MonitorKindFile
-> MonitorKindDir
-> FilePath
-- ^ the root directory
-> RootedGlob
-- ^ the matching glob
-> IO MonitorStateGlob
buildMonitorStateGlob
mstartTime
hashcache
kindfile
kinddir
relroot
(RootedGlob globroot globPath) = do
root <- liftIO $ getFilePathRootDirectory globroot relroot
MonitorStateGlob kindfile kinddir globroot
<$> buildMonitorStateGlobRel
mstartTime
hashcache
kindfile
kinddir
root
"."
globPath
buildMonitorStateGlobRel
:: Maybe MonitorTimestamp
-- ^ start time of update
-> FileHashCache
-- ^ existing file hashes
-> MonitorKindFile
-> MonitorKindDir
-> FilePath
-- ^ the root directory
-> FilePath
-- ^ directory we are examining
-- relative to the root
-> Glob
-- ^ the matching glob
-> IO MonitorStateGlobRel
buildMonitorStateGlobRel
mstartTime
hashcache
kindfile
kinddir
root
dir
globPath = do
let absdir = root </> dir
dirEntries <- getDirectoryContents absdir
dirMTime <- getModTime absdir
case globPath of
GlobDirRecursive{} -> error "Monitoring directory-recursive globs (i.e. ../**/...) is currently unsupported"
GlobDir glob globPath' -> do
subdirs <-
filterM (\subdir -> doesDirectoryExist (absdir </> subdir)) $
filter (matchGlobPieces glob) dirEntries
subdirStates <-
for (sort subdirs) $ \subdir -> do
fstate <-
buildMonitorStateGlobRel
mstartTime
hashcache
kindfile
kinddir
root
(dir </> subdir)
globPath'
return (subdir, fstate)
return $! MonitorStateGlobDirs glob globPath' dirMTime subdirStates
GlobFile glob -> do
let files = filter (matchGlobPieces glob) dirEntries
filesStates <-
for (sort files) $ \file -> do
fstate <-
buildMonitorStateFile
mstartTime
hashcache
kindfile
kinddir
root
(dir </> file)
return (file, fstate)
return $! MonitorStateGlobFiles glob dirMTime filesStates
GlobDirTrailing ->
return MonitorStateGlobDirTrailing
-- | We really want to avoid re-hashing files all the time. We already make
-- the assumption that if a file mtime has not changed then we don't need to
-- bother checking if the content hash has changed. We can apply the same
-- assumption when updating the file monitor state. In the typical case of
-- updating a file monitor the set of files is the same or largely the same so
-- we can grab the previously known content hashes with their corresponding
-- mtimes.
type FileHashCache = Map FilePath (ModTime, HashValue)
-- | We declare it a cache hit if the mtime of a file is the same as before.
lookupFileHashCache :: FileHashCache -> FilePath -> ModTime -> Maybe HashValue
lookupFileHashCache hashcache file mtime = do
(mtime', hash) <- Map.lookup file hashcache
guard (mtime' == mtime)
return hash
-- | Either get it from the cache or go read the file
getFileHash :: FileHashCache -> FilePath -> FilePath -> ModTime -> IO HashValue
getFileHash hashcache relfile absfile mtime =
case lookupFileHashCache hashcache relfile mtime of
Just hash -> return hash
Nothing -> readFileHashValue absfile
-- | Build a 'FileHashCache' from the previous 'MonitorStateFileSet'. While
-- in principle we could preserve the structure of the previous state, given
-- that the set of files to monitor can change then it's simpler just to throw
-- away the structure and use a finite map.
readCacheFileHashes
:: (Binary a, Structured a, Binary b, Structured b)
=> FileMonitor a b
-> IO FileHashCache
readCacheFileHashes monitor =
handleDoesNotExist Map.empty $
handleErrorCall Map.empty $
withCacheFile monitor $ \res ->
case res of
Left _ -> return Map.empty
Right (msfs, _, _) -> return (mkFileHashCache msfs)
where
mkFileHashCache :: MonitorStateFileSet -> FileHashCache
mkFileHashCache (MonitorStateFileSet singlePaths globPaths) =
collectAllFileHashes singlePaths
`Map.union` collectAllGlobHashes globPaths
collectAllFileHashes :: [MonitorStateFile] -> Map FilePath (ModTime, HashValue)
collectAllFileHashes singlePaths =